1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3 * CDDL HEADER START
4 *
5 * The contents of this file are subject to the terms of the
6 * Common Development and Distribution License (the "License").
7 * You may not use this file except in compliance with the License.
8 *
9 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 * or https://opensource.org/licenses/CDDL-1.0.
11 * See the License for the specific language governing permissions
12 * and limitations under the License.
13 *
14 * When distributing Covered Code, include this CDDL HEADER in each
15 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 * If applicable, add the following below this CDDL HEADER, with the
17 * fields enclosed by brackets "[]" replaced with your own identifying
18 * information: Portions Copyright [yyyy] [name of copyright owner]
19 *
20 * CDDL HEADER END
21 */
22 /*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
25 * Copyright (c) 2013 by Saso Kiselkov. All rights reserved.
26 * Copyright (c) 2015, Nexenta Systems, Inc. All rights reserved.
27 * Copyright (c) 2017, Intel Corporation.
28 */
29
30 #include <sys/zfs_context.h>
31 #include <sys/brt.h>
32 #include <sys/dmu.h>
33 #include <sys/dmu_tx.h>
34 #include <sys/space_map.h>
35 #include <sys/metaslab_impl.h>
36 #include <sys/vdev_impl.h>
37 #include <sys/vdev_draid.h>
38 #include <sys/zio.h>
39 #include <sys/spa_impl.h>
40 #include <sys/zfeature.h>
41 #include <sys/vdev_indirect_mapping.h>
42 #include <sys/zap.h>
43 #include <sys/btree.h>
44
45 #define GANG_ALLOCATION(flags) \
46 ((flags) & (METASLAB_GANG_CHILD | METASLAB_GANG_HEADER))
47
48 /*
49 * Metaslab group's per child vdev granularity, in bytes. This is roughly
50 * similar to what would be referred to as the "stripe size" in traditional
51 * RAID arrays. In normal operation, we will try to write this amount of
52 * data to each disk before moving on to the next top-level vdev.
53 */
54 static uint64_t metaslab_aliquot = 2 * 1024 * 1024;
55
56 /*
57 * For testing, make some blocks above a certain size be gang blocks.
58 */
59 uint64_t metaslab_force_ganging = SPA_MAXBLOCKSIZE + 1;
60
61 /*
62 * Of blocks of size >= metaslab_force_ganging, actually gang them this often.
63 */
64 uint_t metaslab_force_ganging_pct = 3;
65
66 /*
67 * In pools where the log space map feature is not enabled we touch
68 * multiple metaslabs (and their respective space maps) with each
69 * transaction group. Thus, we benefit from having a small space map
70 * block size since it allows us to issue more I/O operations scattered
71 * around the disk. So a sane default for the space map block size
72 * is 8~16K.
73 */
74 int zfs_metaslab_sm_blksz_no_log = (1 << 14);
75
76 /*
77 * When the log space map feature is enabled, we accumulate a lot of
78 * changes per metaslab that are flushed once in a while so we benefit
79 * from a bigger block size like 128K for the metaslab space maps.
80 */
81 int zfs_metaslab_sm_blksz_with_log = (1 << 17);
82
83 /*
84 * The in-core space map representation is more compact than its on-disk form.
85 * The zfs_metaslab_condense_pct determines how much more compact the in-core
86 * space map representation must be before we compact it on-disk.
87 * Values should be greater than or equal to 100.
88 */
89 uint_t zfs_metaslab_condense_pct = 200;
90
91 /*
92 * Condensing a metaslab is not guaranteed to actually reduce the amount of
93 * space used on disk. In particular, a space map uses data in increments of
94 * MAX(1 << ashift, space_map_blksz), so a metaslab might use the
95 * same number of blocks after condensing. Since the goal of condensing is to
96 * reduce the number of IOPs required to read the space map, we only want to
97 * condense when we can be sure we will reduce the number of blocks used by the
98 * space map. Unfortunately, we cannot precisely compute whether or not this is
99 * the case in metaslab_should_condense since we are holding ms_lock. Instead,
100 * we apply the following heuristic: do not condense a spacemap unless the
101 * uncondensed size consumes greater than zfs_metaslab_condense_block_threshold
102 * blocks.
103 */
104 static const int zfs_metaslab_condense_block_threshold = 4;
105
106 /*
107 * The zfs_mg_noalloc_threshold defines which metaslab groups should
108 * be eligible for allocation. The value is defined as a percentage of
109 * free space. Metaslab groups that have more free space than
110 * zfs_mg_noalloc_threshold are always eligible for allocations. Once
111 * a metaslab group's free space is less than or equal to the
112 * zfs_mg_noalloc_threshold the allocator will avoid allocating to that
113 * group unless all groups in the pool have reached zfs_mg_noalloc_threshold.
114 * Once all groups in the pool reach zfs_mg_noalloc_threshold then all
115 * groups are allowed to accept allocations. Gang blocks are always
116 * eligible to allocate on any metaslab group. The default value of 0 means
117 * no metaslab group will be excluded based on this criterion.
118 */
119 static uint_t zfs_mg_noalloc_threshold = 0;
120
121 /*
122 * Metaslab groups are considered eligible for allocations if their
123 * fragmentation metric (measured as a percentage) is less than or
124 * equal to zfs_mg_fragmentation_threshold. If a metaslab group
125 * exceeds this threshold then it will be skipped unless all metaslab
126 * groups within the metaslab class have also crossed this threshold.
127 *
128 * This tunable was introduced to avoid edge cases where we continue
129 * allocating from very fragmented disks in our pool while other, less
130 * fragmented disks, exists. On the other hand, if all disks in the
131 * pool are uniformly approaching the threshold, the threshold can
132 * be a speed bump in performance, where we keep switching the disks
133 * that we allocate from (e.g. we allocate some segments from disk A
134 * making it bypassing the threshold while freeing segments from disk
135 * B getting its fragmentation below the threshold).
136 *
137 * Empirically, we've seen that our vdev selection for allocations is
138 * good enough that fragmentation increases uniformly across all vdevs
139 * the majority of the time. Thus we set the threshold percentage high
140 * enough to avoid hitting the speed bump on pools that are being pushed
141 * to the edge.
142 */
143 static uint_t zfs_mg_fragmentation_threshold = 95;
144
145 /*
146 * Allow metaslabs to keep their active state as long as their fragmentation
147 * percentage is less than or equal to zfs_metaslab_fragmentation_threshold. An
148 * active metaslab that exceeds this threshold will no longer keep its active
149 * status allowing better metaslabs to be selected.
150 */
151 static uint_t zfs_metaslab_fragmentation_threshold = 77;
152
153 /*
154 * When set will load all metaslabs when pool is first opened.
155 */
156 int metaslab_debug_load = B_FALSE;
157
158 /*
159 * When set will prevent metaslabs from being unloaded.
160 */
161 static int metaslab_debug_unload = B_FALSE;
162
163 /*
164 * Minimum size which forces the dynamic allocator to change
165 * it's allocation strategy. Once the space map cannot satisfy
166 * an allocation of this size then it switches to using more
167 * aggressive strategy (i.e search by size rather than offset).
168 */
169 uint64_t metaslab_df_alloc_threshold = SPA_OLD_MAXBLOCKSIZE;
170
171 /*
172 * The minimum free space, in percent, which must be available
173 * in a space map to continue allocations in a first-fit fashion.
174 * Once the space map's free space drops below this level we dynamically
175 * switch to using best-fit allocations.
176 */
177 uint_t metaslab_df_free_pct = 4;
178
179 /*
180 * Maximum distance to search forward from the last offset. Without this
181 * limit, fragmented pools can see >100,000 iterations and
182 * metaslab_block_picker() becomes the performance limiting factor on
183 * high-performance storage.
184 *
185 * With the default setting of 16MB, we typically see less than 500
186 * iterations, even with very fragmented, ashift=9 pools. The maximum number
187 * of iterations possible is:
188 * metaslab_df_max_search / (2 * (1<<ashift))
189 * With the default setting of 16MB this is 16*1024 (with ashift=9) or
190 * 2048 (with ashift=12).
191 */
192 static uint_t metaslab_df_max_search = 16 * 1024 * 1024;
193
194 /*
195 * Forces the metaslab_block_picker function to search for at least this many
196 * segments forwards until giving up on finding a segment that the allocation
197 * will fit into.
198 */
199 static const uint32_t metaslab_min_search_count = 100;
200
201 /*
202 * If we are not searching forward (due to metaslab_df_max_search,
203 * metaslab_df_free_pct, or metaslab_df_alloc_threshold), this tunable
204 * controls what segment is used. If it is set, we will use the largest free
205 * segment. If it is not set, we will use a segment of exactly the requested
206 * size (or larger).
207 */
208 static int metaslab_df_use_largest_segment = B_FALSE;
209
210 /*
211 * These tunables control how long a metaslab will remain loaded after the
212 * last allocation from it. A metaslab can't be unloaded until at least
213 * metaslab_unload_delay TXG's and metaslab_unload_delay_ms milliseconds
214 * have elapsed. However, zfs_metaslab_mem_limit may cause it to be
215 * unloaded sooner. These settings are intended to be generous -- to keep
216 * metaslabs loaded for a long time, reducing the rate of metaslab loading.
217 */
218 static uint_t metaslab_unload_delay = 32;
219 static uint_t metaslab_unload_delay_ms = 10 * 60 * 1000; /* ten minutes */
220
221 /*
222 * Max number of metaslabs per group to preload.
223 */
224 uint_t metaslab_preload_limit = 10;
225
226 /*
227 * Enable/disable preloading of metaslab.
228 */
229 static int metaslab_preload_enabled = B_TRUE;
230
231 /*
232 * Enable/disable fragmentation weighting on metaslabs.
233 */
234 static int metaslab_fragmentation_factor_enabled = B_TRUE;
235
236 /*
237 * Enable/disable lba weighting (i.e. outer tracks are given preference).
238 */
239 static int metaslab_lba_weighting_enabled = B_TRUE;
240
241 /*
242 * Enable/disable space-based metaslab group biasing.
243 */
244 static int metaslab_bias_enabled = B_TRUE;
245
246 /*
247 * Control performance-based metaslab group biasing.
248 */
249 static int metaslab_perf_bias = 1;
250
251 /*
252 * Enable/disable remapping of indirect DVAs to their concrete vdevs.
253 */
254 static const boolean_t zfs_remap_blkptr_enable = B_TRUE;
255
256 /*
257 * Enable/disable segment-based metaslab selection.
258 */
259 static int zfs_metaslab_segment_weight_enabled = B_TRUE;
260
261 /*
262 * When using segment-based metaslab selection, we will continue
263 * allocating from the active metaslab until we have exhausted
264 * zfs_metaslab_switch_threshold of its buckets.
265 */
266 static int zfs_metaslab_switch_threshold = 2;
267
268 /*
269 * Internal switch to enable/disable the metaslab allocation tracing
270 * facility.
271 */
272 static const boolean_t metaslab_trace_enabled = B_FALSE;
273
274 /*
275 * Maximum entries that the metaslab allocation tracing facility will keep
276 * in a given list when running in non-debug mode. We limit the number
277 * of entries in non-debug mode to prevent us from using up too much memory.
278 * The limit should be sufficiently large that we don't expect any allocation
279 * to every exceed this value. In debug mode, the system will panic if this
280 * limit is ever reached allowing for further investigation.
281 */
282 static const uint64_t metaslab_trace_max_entries = 5000;
283
284 /*
285 * Maximum number of metaslabs per group that can be disabled
286 * simultaneously.
287 */
288 static const int max_disabled_ms = 3;
289
290 /*
291 * Time (in seconds) to respect ms_max_size when the metaslab is not loaded.
292 * To avoid 64-bit overflow, don't set above UINT32_MAX.
293 */
294 static uint64_t zfs_metaslab_max_size_cache_sec = 1 * 60 * 60; /* 1 hour */
295
296 /*
297 * Maximum percentage of memory to use on storing loaded metaslabs. If loading
298 * a metaslab would take it over this percentage, the oldest selected metaslab
299 * is automatically unloaded.
300 */
301 static uint_t zfs_metaslab_mem_limit = 25;
302
303 /*
304 * Force the per-metaslab range trees to use 64-bit integers to store
305 * segments. Used for debugging purposes.
306 */
307 static const boolean_t zfs_metaslab_force_large_segs = B_FALSE;
308
309 /*
310 * By default we only store segments over a certain size in the size-sorted
311 * metaslab trees (ms_allocatable_by_size and
312 * ms_unflushed_frees_by_size). This dramatically reduces memory usage and
313 * improves load and unload times at the cost of causing us to use slightly
314 * larger segments than we would otherwise in some cases.
315 */
316 static const uint32_t metaslab_by_size_min_shift = 14;
317
318 /*
319 * If not set, we will first try normal allocation. If that fails then
320 * we will do a gang allocation. If that fails then we will do a "try hard"
321 * gang allocation. If that fails then we will have a multi-layer gang
322 * block.
323 *
324 * If set, we will first try normal allocation. If that fails then
325 * we will do a "try hard" allocation. If that fails we will do a gang
326 * allocation. If that fails we will do a "try hard" gang allocation. If
327 * that fails then we will have a multi-layer gang block.
328 */
329 static int zfs_metaslab_try_hard_before_gang = B_FALSE;
330
331 /*
332 * When not trying hard, we only consider the best zfs_metaslab_find_max_tries
333 * metaslabs. This improves performance, especially when there are many
334 * metaslabs per vdev and the allocation can't actually be satisfied (so we
335 * would otherwise iterate all the metaslabs). If there is a metaslab with a
336 * worse weight but it can actually satisfy the allocation, we won't find it
337 * until trying hard. This may happen if the worse metaslab is not loaded
338 * (and the true weight is better than we have calculated), or due to weight
339 * bucketization. E.g. we are looking for a 60K segment, and the best
340 * metaslabs all have free segments in the 32-63K bucket, but the best
341 * zfs_metaslab_find_max_tries metaslabs have ms_max_size <60KB, and a
342 * subsequent metaslab has ms_max_size >60KB (but fewer segments in this
343 * bucket, and therefore a lower weight).
344 */
345 static uint_t zfs_metaslab_find_max_tries = 100;
346
347 static uint64_t metaslab_weight(metaslab_t *, boolean_t);
348 static void metaslab_set_fragmentation(metaslab_t *, boolean_t);
349 static void metaslab_free_impl(vdev_t *, uint64_t, uint64_t, boolean_t);
350 static void metaslab_check_free_impl(vdev_t *, uint64_t, uint64_t);
351
352 static void metaslab_passivate(metaslab_t *msp, uint64_t weight);
353 static uint64_t metaslab_weight_from_range_tree(metaslab_t *msp);
354 static void metaslab_flush_update(metaslab_t *, dmu_tx_t *);
355 static unsigned int metaslab_idx_func(multilist_t *, void *);
356 static void metaslab_evict(metaslab_t *, uint64_t);
357 static void metaslab_rt_add(zfs_range_tree_t *rt, zfs_range_seg_t *rs,
358 void *arg);
359 kmem_cache_t *metaslab_alloc_trace_cache;
360
361 typedef struct metaslab_stats {
362 kstat_named_t metaslabstat_trace_over_limit;
363 kstat_named_t metaslabstat_reload_tree;
364 kstat_named_t metaslabstat_too_many_tries;
365 kstat_named_t metaslabstat_try_hard;
366 } metaslab_stats_t;
367
368 static metaslab_stats_t metaslab_stats = {
369 { "trace_over_limit", KSTAT_DATA_UINT64 },
370 { "reload_tree", KSTAT_DATA_UINT64 },
371 { "too_many_tries", KSTAT_DATA_UINT64 },
372 { "try_hard", KSTAT_DATA_UINT64 },
373 };
374
375 #define METASLABSTAT_BUMP(stat) \
376 atomic_inc_64(&metaslab_stats.stat.value.ui64);
377
378 char *
metaslab_rt_name(metaslab_group_t * mg,metaslab_t * ms,const char * name)379 metaslab_rt_name(metaslab_group_t *mg, metaslab_t *ms, const char *name)
380 {
381 return (kmem_asprintf("{spa=%s vdev_guid=%llu ms_id=%llu %s}",
382 spa_name(mg->mg_vd->vdev_spa),
383 (u_longlong_t)mg->mg_vd->vdev_guid,
384 (u_longlong_t)ms->ms_id,
385 name));
386 }
387
388
389 static kstat_t *metaslab_ksp;
390
391 void
metaslab_stat_init(void)392 metaslab_stat_init(void)
393 {
394 ASSERT0P(metaslab_alloc_trace_cache);
395 metaslab_alloc_trace_cache = kmem_cache_create(
396 "metaslab_alloc_trace_cache", sizeof (metaslab_alloc_trace_t),
397 0, NULL, NULL, NULL, NULL, NULL, 0);
398 metaslab_ksp = kstat_create("zfs", 0, "metaslab_stats",
399 "misc", KSTAT_TYPE_NAMED, sizeof (metaslab_stats) /
400 sizeof (kstat_named_t), KSTAT_FLAG_VIRTUAL);
401 if (metaslab_ksp != NULL) {
402 metaslab_ksp->ks_data = &metaslab_stats;
403 kstat_install(metaslab_ksp);
404 }
405 }
406
407 void
metaslab_stat_fini(void)408 metaslab_stat_fini(void)
409 {
410 if (metaslab_ksp != NULL) {
411 kstat_delete(metaslab_ksp);
412 metaslab_ksp = NULL;
413 }
414
415 kmem_cache_destroy(metaslab_alloc_trace_cache);
416 metaslab_alloc_trace_cache = NULL;
417 }
418
419 /*
420 * ==========================================================================
421 * Metaslab classes
422 * ==========================================================================
423 */
424 metaslab_class_t *
metaslab_class_create(spa_t * spa,const char * name,const metaslab_ops_t * ops,boolean_t is_log)425 metaslab_class_create(spa_t *spa, const char *name,
426 const metaslab_ops_t *ops, boolean_t is_log)
427 {
428 metaslab_class_t *mc;
429
430 mc = kmem_zalloc(offsetof(metaslab_class_t,
431 mc_allocator[spa->spa_alloc_count]), KM_SLEEP);
432
433 mc->mc_spa = spa;
434 mc->mc_name = name;
435 mc->mc_ops = ops;
436 mc->mc_is_log = is_log;
437 mc->mc_alloc_io_size = SPA_OLD_MAXBLOCKSIZE;
438 mc->mc_alloc_max = UINT64_MAX;
439 mutex_init(&mc->mc_lock, NULL, MUTEX_DEFAULT, NULL);
440 multilist_create(&mc->mc_metaslab_txg_list, sizeof (metaslab_t),
441 offsetof(metaslab_t, ms_class_txg_node), metaslab_idx_func);
442 for (int i = 0; i < spa->spa_alloc_count; i++) {
443 metaslab_class_allocator_t *mca = &mc->mc_allocator[i];
444 mutex_init(&mca->mca_lock, NULL, MUTEX_DEFAULT, NULL);
445 avl_create(&mca->mca_tree, zio_bookmark_compare,
446 sizeof (zio_t), offsetof(zio_t, io_queue_node.a));
447 mca->mca_rotor = NULL;
448 mca->mca_reserved = 0;
449 }
450
451 return (mc);
452 }
453
454 void
metaslab_class_destroy(metaslab_class_t * mc)455 metaslab_class_destroy(metaslab_class_t *mc)
456 {
457 spa_t *spa = mc->mc_spa;
458
459 ASSERT0(mc->mc_alloc);
460 ASSERT0(mc->mc_dalloc);
461 ASSERT0(mc->mc_deferred);
462 ASSERT0(mc->mc_ddeferred);
463 ASSERT0(mc->mc_space);
464 ASSERT0(mc->mc_dspace);
465
466 for (int i = 0; i < spa->spa_alloc_count; i++) {
467 metaslab_class_allocator_t *mca = &mc->mc_allocator[i];
468 avl_destroy(&mca->mca_tree);
469 mutex_destroy(&mca->mca_lock);
470 ASSERT0P(mca->mca_rotor);
471 ASSERT0(mca->mca_reserved);
472 }
473 mutex_destroy(&mc->mc_lock);
474 multilist_destroy(&mc->mc_metaslab_txg_list);
475 kmem_free(mc, offsetof(metaslab_class_t,
476 mc_allocator[spa->spa_alloc_count]));
477 }
478
479 void
metaslab_class_validate(metaslab_class_t * mc)480 metaslab_class_validate(metaslab_class_t *mc)
481 {
482 #ifdef ZFS_DEBUG
483 spa_t *spa = mc->mc_spa;
484
485 /*
486 * Must hold one of the spa_config locks.
487 */
488 ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) ||
489 spa_config_held(spa, SCL_ALL, RW_WRITER));
490
491 for (int i = 0; i < spa->spa_alloc_count; i++) {
492 metaslab_class_allocator_t *mca = &mc->mc_allocator[i];
493 metaslab_group_t *mg, *rotor;
494
495 ASSERT0(avl_numnodes(&mca->mca_tree));
496 ASSERT0(mca->mca_reserved);
497
498 if ((mg = rotor = mca->mca_rotor) == NULL)
499 continue;
500 do {
501 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
502 vdev_t *vd = mg->mg_vd;
503
504 ASSERT3P(vd->vdev_top, ==, vd);
505 ASSERT(vd->vdev_mg == mg || vd->vdev_log_mg == mg);
506 ASSERT3P(mg->mg_class, ==, mc);
507 ASSERT3P(vd->vdev_ops, !=, &vdev_hole_ops);
508 ASSERT0(zfs_refcount_count(&mga->mga_queue_depth));
509 } while ((mg = mg->mg_next) != rotor);
510 }
511 #endif
512 }
513
514 /*
515 * For each metaslab group in a class pre-calculate allocation quota and
516 * target queue depth to balance their space usage and write performance.
517 * Based on those pre-calculate class allocation throttle threshold for
518 * optimal saturation. onsync is true once per TXG to enable/disable
519 * allocation throttling and update moving average of maximum I/O size.
520 */
521 void
metaslab_class_balance(metaslab_class_t * mc,boolean_t onsync)522 metaslab_class_balance(metaslab_class_t *mc, boolean_t onsync)
523 {
524 metaslab_group_t *mg, *first;
525
526 /*
527 * Must hold one of the spa_config locks.
528 */
529 ASSERT(spa_config_held(mc->mc_spa, SCL_ALL, RW_READER) ||
530 spa_config_held(mc->mc_spa, SCL_ALL, RW_WRITER));
531
532 if (onsync)
533 metaslab_class_validate(mc);
534
535 if (mc->mc_groups == 0) {
536 if (onsync)
537 mc->mc_alloc_throttle_enabled = B_FALSE;
538 mc->mc_alloc_max = UINT64_MAX;
539 return;
540 }
541
542 if (onsync) {
543 /*
544 * Moving average of maximum allocation size, in absence of
545 * large allocations shrinking to 1/8 of metaslab_aliquot.
546 */
547 mc->mc_alloc_io_size = (3 * mc->mc_alloc_io_size +
548 metaslab_aliquot / 8) / 4;
549 mc->mc_alloc_throttle_enabled = mc->mc_is_log ? 0 :
550 zio_dva_throttle_enabled;
551 }
552
553 mg = first = mc->mc_allocator[0].mca_rotor;
554 uint64_t children = 0;
555 do {
556 children += vdev_get_ndisks(mg->mg_vd) -
557 vdev_get_nparity(mg->mg_vd);
558 } while ((mg = mg->mg_next) != first);
559
560 uint64_t sum_aliquot = 0;
561 do {
562 vdev_stat_t *vs = &mg->mg_vd->vdev_stat;
563 uint_t ratio;
564
565 /*
566 * Scale allocations per iteration with average number of
567 * children. Wider vdevs need more sequential allocations
568 * to keep decent per-child I/O size.
569 */
570 uint64_t mg_aliquot = MAX(metaslab_aliquot * children /
571 mc->mc_groups, mc->mc_alloc_io_size * 4);
572
573 /*
574 * Scale allocations per iteration with the vdev capacity,
575 * relative to average. Bigger vdevs should get more to
576 * fill up at the same time as smaller ones.
577 */
578 uint64_t mc_space = atomic_load_64(&mc->mc_space);
579 uint64_t vs_space = atomic_load_64(&vs->vs_space);
580 if (mc_space > 0 && vs_space > 0) {
581 ratio = vs_space / (mc_space / (mc->mc_groups *
582 256) + 1);
583 mg_aliquot = mg_aliquot * ratio / 256;
584 }
585
586 /*
587 * Scale allocations per iteration with the vdev's free space
588 * fraction, relative to average. Despite the above, vdevs free
589 * space fractions may get imbalanced, for example due to new
590 * vdev addition or different performance. We want free space
591 * fractions to be similar to postpone fragmentation.
592 *
593 * But same time we don't want to throttle vdevs still having
594 * plenty of free space, that appear faster than others, even
595 * if that cause temporary imbalance. Allow them to allocate
596 * more by keeping their allocation queue depth equivalent to
597 * 2.5 full iteration, even if they repeatedly drain it. Later
598 * with the free space reduction gradually reduce the target
599 * queue depth, stronger enforcing the free space balance.
600 */
601 if (metaslab_bias_enabled &&
602 mc_space > 0 && vs_space > 0) {
603 uint64_t mc_alloc = atomic_load_64(&mc->mc_alloc);
604 uint64_t vs_alloc = atomic_load_64(&vs->vs_alloc);
605 uint64_t vs_free = vs_space > vs_alloc ?
606 vs_space - vs_alloc : 0;
607 uint64_t mc_free = mc_space > mc_alloc ?
608 mc_space - mc_alloc : 0;
609 /*
610 * vs_fr is 16 bit fixed-point free space fraction.
611 * mc_fr is 8 bit fixed-point free space fraction.
612 * ratio as their quotient is 8 bit fixed-point.
613 */
614 uint_t vs_fr = vs_free / (vs_space / 65536 + 1);
615 uint_t mc_fr = mc_free / (mc_space / 256 + 1);
616 ratio = vs_fr / (mc_fr + 1);
617 mg->mg_aliquot = mg_aliquot * ratio / 256;
618 /* From 2.5x at 25% full to 1x at 75%. */
619 ratio = MIN(163840, vs_fr * 3 + 16384);
620 mg->mg_queue_target = MAX(mg->mg_aliquot,
621 mg->mg_aliquot * ratio / 65536);
622 } else {
623 mg->mg_aliquot = mg_aliquot;
624 mg->mg_queue_target = mg->mg_aliquot * 2;
625 }
626 sum_aliquot += mg->mg_aliquot;
627 } while ((mg = mg->mg_next) != first);
628
629 /*
630 * Set per-class allocation throttle threshold to 4 iterations through
631 * all the vdevs. This should keep all vdevs busy even if some are
632 * allocating more than we planned for them due to bigger blocks or
633 * better performance.
634 */
635 mc->mc_alloc_max = sum_aliquot * 4;
636 }
637
638 static void
metaslab_class_rotate(metaslab_group_t * mg,int allocator,uint64_t psize,boolean_t success)639 metaslab_class_rotate(metaslab_group_t *mg, int allocator, uint64_t psize,
640 boolean_t success)
641 {
642 metaslab_class_t *mc = mg->mg_class;
643 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
644 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
645
646 /*
647 * Exit fast if there is nothing to rotate, we are not following
648 * the rotor (copies, gangs, etc) or somebody already rotated it.
649 */
650 if (mc->mc_groups < 2 || mca->mca_rotor != mg)
651 return;
652
653 /*
654 * Always rotate in case of allocation error or a log class.
655 */
656 if (!success || mc->mc_is_log)
657 goto rotate;
658
659 /*
660 * Allocate from this group if we expect next I/O of the same size to
661 * mostly fit within the allocation quota. Rotate if we expect it to
662 * mostly go over the target queue depth. Meanwhile, to stripe between
663 * groups in configured amounts per child even if we can't reach the
664 * target queue depth, i.e. can't saturate the group write performance,
665 * always rotate after allocating the queue target bytes.
666 */
667 uint64_t naq = atomic_add_64_nv(&mca->mca_aliquot, psize) + psize / 2;
668 if (naq < mg->mg_aliquot)
669 return;
670 if (naq >= mg->mg_queue_target)
671 goto rotate;
672 if (zfs_refcount_count(&mga->mga_queue_depth) + psize + psize / 2 >=
673 mg->mg_queue_target)
674 goto rotate;
675
676 /*
677 * When the pool is not too busy, prefer restoring the vdev free space
678 * balance instead of getting maximum speed we might not need, so that
679 * we could have more flexibility during more busy times later.
680 */
681 if (metaslab_perf_bias <= 0)
682 goto rotate;
683 if (metaslab_perf_bias >= 2)
684 return;
685 spa_t *spa = mc->mc_spa;
686 dsl_pool_t *dp = spa_get_dsl(spa);
687 if (dp == NULL)
688 return;
689 uint64_t busy_thresh = zfs_dirty_data_max *
690 (zfs_vdev_async_write_active_min_dirty_percent +
691 zfs_vdev_async_write_active_max_dirty_percent) / 200;
692 if (dp->dp_dirty_total > busy_thresh || spa_has_pending_synctask(spa))
693 return;
694
695 rotate:
696 mca->mca_rotor = mg->mg_next;
697 mca->mca_aliquot = 0;
698 }
699
700 static void
metaslab_class_space_update(metaslab_class_t * mc,int64_t alloc_delta,int64_t dalloc_delta,int64_t deferred_delta,int64_t ddeferred_delta,int64_t space_delta,int64_t dspace_delta)701 metaslab_class_space_update(metaslab_class_t *mc, int64_t alloc_delta,
702 int64_t dalloc_delta, int64_t deferred_delta, int64_t ddeferred_delta,
703 int64_t space_delta, int64_t dspace_delta)
704 {
705 atomic_add_64(&mc->mc_alloc, alloc_delta);
706 atomic_add_64(&mc->mc_dalloc, dalloc_delta);
707 atomic_add_64(&mc->mc_deferred, deferred_delta);
708 atomic_add_64(&mc->mc_ddeferred, ddeferred_delta);
709 atomic_add_64(&mc->mc_space, space_delta);
710 atomic_add_64(&mc->mc_dspace, dspace_delta);
711 }
712
713 const char *
metaslab_class_get_name(metaslab_class_t * mc)714 metaslab_class_get_name(metaslab_class_t *mc)
715 {
716 return (mc->mc_name);
717 }
718
719 uint64_t
metaslab_class_get_alloc(metaslab_class_t * mc)720 metaslab_class_get_alloc(metaslab_class_t *mc)
721 {
722 return (atomic_load_64(&mc->mc_alloc));
723 }
724
725 uint64_t
metaslab_class_get_dalloc(metaslab_class_t * mc)726 metaslab_class_get_dalloc(metaslab_class_t *mc)
727 {
728 return (spa_deflate(mc->mc_spa) ? atomic_load_64(&mc->mc_dalloc) :
729 atomic_load_64(&mc->mc_alloc));
730 }
731
732 uint64_t
metaslab_class_get_deferred(metaslab_class_t * mc)733 metaslab_class_get_deferred(metaslab_class_t *mc)
734 {
735 return (spa_deflate(mc->mc_spa) ? atomic_load_64(&mc->mc_ddeferred) :
736 atomic_load_64(&mc->mc_deferred));
737 }
738
739 uint64_t
metaslab_class_get_space(metaslab_class_t * mc)740 metaslab_class_get_space(metaslab_class_t *mc)
741 {
742 return (atomic_load_64(&mc->mc_space));
743 }
744
745 uint64_t
metaslab_class_get_dspace(metaslab_class_t * mc)746 metaslab_class_get_dspace(metaslab_class_t *mc)
747 {
748 return (spa_deflate(mc->mc_spa) ? atomic_load_64(&mc->mc_dspace) :
749 atomic_load_64(&mc->mc_space));
750 }
751
752 void
metaslab_class_histogram_verify(metaslab_class_t * mc)753 metaslab_class_histogram_verify(metaslab_class_t *mc)
754 {
755 spa_t *spa = mc->mc_spa;
756 vdev_t *rvd = spa->spa_root_vdev;
757 uint64_t *mc_hist;
758 int i;
759
760 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
761 return;
762
763 mc_hist = kmem_zalloc(sizeof (uint64_t) * ZFS_RANGE_TREE_HISTOGRAM_SIZE,
764 KM_SLEEP);
765
766 mutex_enter(&mc->mc_lock);
767 for (int c = 0; c < rvd->vdev_children; c++) {
768 vdev_t *tvd = rvd->vdev_child[c];
769 metaslab_group_t *mg = vdev_get_mg(tvd, mc);
770
771 /*
772 * Skip any holes, uninitialized top-levels, or
773 * vdevs that are not in this metalab class.
774 */
775 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
776 mg->mg_class != mc) {
777 continue;
778 }
779
780 IMPLY(mg == mg->mg_vd->vdev_log_mg,
781 mc == spa_embedded_log_class(mg->mg_vd->vdev_spa) ||
782 mc == spa_special_embedded_log_class(mg->mg_vd->vdev_spa));
783
784 for (i = 0; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE; i++)
785 mc_hist[i] += mg->mg_histogram[i];
786 }
787
788 for (i = 0; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE; i++) {
789 VERIFY3U(mc_hist[i], ==, mc->mc_histogram[i]);
790 }
791
792 mutex_exit(&mc->mc_lock);
793 kmem_free(mc_hist, sizeof (uint64_t) * ZFS_RANGE_TREE_HISTOGRAM_SIZE);
794 }
795
796 /*
797 * Calculate the metaslab class's fragmentation metric. The metric
798 * is weighted based on the space contribution of each metaslab group.
799 * The return value will be a number between 0 and 100 (inclusive), or
800 * ZFS_FRAG_INVALID if the metric has not been set. See comment above the
801 * zfs_frag_table for more information about the metric.
802 */
803 uint64_t
metaslab_class_fragmentation(metaslab_class_t * mc)804 metaslab_class_fragmentation(metaslab_class_t *mc)
805 {
806 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
807 uint64_t fragmentation = 0;
808
809 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
810
811 uint64_t space = metaslab_class_get_space(mc);
812 if (space == 0) {
813 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
814 return (ZFS_FRAG_INVALID);
815 }
816
817 for (int c = 0; c < rvd->vdev_children; c++) {
818 vdev_t *tvd = rvd->vdev_child[c];
819 metaslab_group_t *mg = tvd->vdev_mg;
820
821 /*
822 * Skip any holes, uninitialized top-levels,
823 * or vdevs that are not in this metalab class.
824 */
825 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
826 mg->mg_class != mc) {
827 continue;
828 }
829
830 /*
831 * If a metaslab group does not contain a fragmentation
832 * metric then just bail out.
833 */
834 if (mg->mg_fragmentation == ZFS_FRAG_INVALID) {
835 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
836 return (ZFS_FRAG_INVALID);
837 }
838
839 /*
840 * Determine how much this metaslab_group is contributing
841 * to the overall pool fragmentation metric.
842 */
843 fragmentation += mg->mg_fragmentation *
844 metaslab_group_get_space(mg);
845 }
846 fragmentation /= space;
847
848 ASSERT3U(fragmentation, <=, 100);
849 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
850 return (fragmentation);
851 }
852
853 /*
854 * Calculate the amount of expandable space that is available in
855 * this metaslab class. If a device is expanded then its expandable
856 * space will be the amount of allocatable space that is currently not
857 * part of this metaslab class.
858 */
859 uint64_t
metaslab_class_expandable_space(metaslab_class_t * mc)860 metaslab_class_expandable_space(metaslab_class_t *mc)
861 {
862 vdev_t *rvd = mc->mc_spa->spa_root_vdev;
863 uint64_t space = 0;
864
865 spa_config_enter(mc->mc_spa, SCL_VDEV, FTAG, RW_READER);
866 for (int c = 0; c < rvd->vdev_children; c++) {
867 vdev_t *tvd = rvd->vdev_child[c];
868 metaslab_group_t *mg = tvd->vdev_mg;
869
870 if (!vdev_is_concrete(tvd) || tvd->vdev_ms_shift == 0 ||
871 mg->mg_class != mc) {
872 continue;
873 }
874
875 /*
876 * Calculate if we have enough space to add additional
877 * metaslabs. We report the expandable space in terms
878 * of the metaslab size since that's the unit of expansion.
879 */
880 space += P2ALIGN_TYPED(tvd->vdev_max_asize - tvd->vdev_asize,
881 1ULL << tvd->vdev_ms_shift, uint64_t);
882 }
883 spa_config_exit(mc->mc_spa, SCL_VDEV, FTAG);
884 return (space);
885 }
886
887 void
metaslab_class_evict_old(metaslab_class_t * mc,uint64_t txg)888 metaslab_class_evict_old(metaslab_class_t *mc, uint64_t txg)
889 {
890 multilist_t *ml = &mc->mc_metaslab_txg_list;
891 uint64_t now = gethrestime_sec();
892 /* Round delay up to next second. */
893 uint_t delay = (metaslab_unload_delay_ms + 999) / 1000;
894 for (int i = 0; i < multilist_get_num_sublists(ml); i++) {
895 multilist_sublist_t *mls = multilist_sublist_lock_idx(ml, i);
896 metaslab_t *msp = multilist_sublist_head(mls);
897 multilist_sublist_unlock(mls);
898 while (msp != NULL) {
899 mutex_enter(&msp->ms_lock);
900
901 /*
902 * If the metaslab has been removed from the list
903 * (which could happen if we were at the memory limit
904 * and it was evicted during this loop), then we can't
905 * proceed and we should restart the sublist.
906 */
907 if (!multilist_link_active(&msp->ms_class_txg_node)) {
908 mutex_exit(&msp->ms_lock);
909 i--;
910 break;
911 }
912 mls = multilist_sublist_lock_idx(ml, i);
913 metaslab_t *next_msp = multilist_sublist_next(mls, msp);
914 multilist_sublist_unlock(mls);
915 if (txg >
916 msp->ms_selected_txg + metaslab_unload_delay &&
917 now > msp->ms_selected_time + delay &&
918 (msp->ms_allocator == -1 ||
919 !metaslab_preload_enabled)) {
920 metaslab_evict(msp, txg);
921 } else {
922 /*
923 * Once we've hit a metaslab selected too
924 * recently to evict, we're done evicting for
925 * now.
926 */
927 mutex_exit(&msp->ms_lock);
928 break;
929 }
930 mutex_exit(&msp->ms_lock);
931 msp = next_msp;
932 }
933 }
934 }
935
936 static int
metaslab_compare(const void * x1,const void * x2)937 metaslab_compare(const void *x1, const void *x2)
938 {
939 const metaslab_t *m1 = (const metaslab_t *)x1;
940 const metaslab_t *m2 = (const metaslab_t *)x2;
941
942 int sort1 = 0;
943 int sort2 = 0;
944 if (m1->ms_allocator != -1 && m1->ms_primary)
945 sort1 = 1;
946 else if (m1->ms_allocator != -1 && !m1->ms_primary)
947 sort1 = 2;
948 if (m2->ms_allocator != -1 && m2->ms_primary)
949 sort2 = 1;
950 else if (m2->ms_allocator != -1 && !m2->ms_primary)
951 sort2 = 2;
952
953 /*
954 * Sort inactive metaslabs first, then primaries, then secondaries. When
955 * selecting a metaslab to allocate from, an allocator first tries its
956 * primary, then secondary active metaslab. If it doesn't have active
957 * metaslabs, or can't allocate from them, it searches for an inactive
958 * metaslab to activate. If it can't find a suitable one, it will steal
959 * a primary or secondary metaslab from another allocator.
960 */
961 if (sort1 < sort2)
962 return (-1);
963 if (sort1 > sort2)
964 return (1);
965
966 int cmp = TREE_CMP(m2->ms_weight, m1->ms_weight);
967 if (likely(cmp))
968 return (cmp);
969
970 IMPLY(TREE_CMP(m1->ms_start, m2->ms_start) == 0, m1 == m2);
971
972 return (TREE_CMP(m1->ms_start, m2->ms_start));
973 }
974
975 /*
976 * ==========================================================================
977 * Metaslab groups
978 * ==========================================================================
979 */
980 /*
981 * Update the allocatable flag and the metaslab group's capacity.
982 * The allocatable flag is set to true if the capacity is below
983 * the zfs_mg_noalloc_threshold or has a fragmentation value that is
984 * greater than zfs_mg_fragmentation_threshold. If a metaslab group
985 * transitions from allocatable to non-allocatable or vice versa then the
986 * metaslab group's class is updated to reflect the transition.
987 */
988 static void
metaslab_group_alloc_update(metaslab_group_t * mg)989 metaslab_group_alloc_update(metaslab_group_t *mg)
990 {
991 vdev_t *vd = mg->mg_vd;
992 metaslab_class_t *mc = mg->mg_class;
993 vdev_stat_t *vs = &vd->vdev_stat;
994 boolean_t was_allocatable;
995 boolean_t was_initialized;
996
997 ASSERT(vd == vd->vdev_top);
998 ASSERT3U(spa_config_held(mc->mc_spa, SCL_ALLOC, RW_READER), ==,
999 SCL_ALLOC);
1000
1001 mutex_enter(&mg->mg_lock);
1002 was_allocatable = mg->mg_allocatable;
1003 was_initialized = mg->mg_initialized;
1004
1005 uint64_t free_capacity = ((vs->vs_space - vs->vs_alloc) * 100) /
1006 (vs->vs_space + 1);
1007
1008 mutex_enter(&mc->mc_lock);
1009
1010 /*
1011 * If the metaslab group was just added then it won't
1012 * have any space until we finish syncing out this txg.
1013 * At that point we will consider it initialized and available
1014 * for allocations. We also don't consider non-activated
1015 * metaslab groups (e.g. vdevs that are in the middle of being removed)
1016 * to be initialized, because they can't be used for allocation.
1017 */
1018 mg->mg_initialized = metaslab_group_initialized(mg);
1019 if (!was_initialized && mg->mg_initialized) {
1020 mc->mc_groups++;
1021 } else if (was_initialized && !mg->mg_initialized) {
1022 ASSERT3U(mc->mc_groups, >, 0);
1023 mc->mc_groups--;
1024 }
1025 if (mg->mg_initialized)
1026 mg->mg_no_free_space = B_FALSE;
1027
1028 /*
1029 * A metaslab group is considered allocatable if it has plenty
1030 * of free space or is not heavily fragmented. We only take
1031 * fragmentation into account if the metaslab group has a valid
1032 * fragmentation metric (i.e. a value between 0 and 100).
1033 */
1034 mg->mg_allocatable = (mg->mg_activation_count > 0 &&
1035 free_capacity > zfs_mg_noalloc_threshold &&
1036 (mg->mg_fragmentation == ZFS_FRAG_INVALID ||
1037 mg->mg_fragmentation <= zfs_mg_fragmentation_threshold));
1038
1039 /*
1040 * The mc_alloc_groups maintains a count of the number of
1041 * groups in this metaslab class that are still above the
1042 * zfs_mg_noalloc_threshold. This is used by the allocating
1043 * threads to determine if they should avoid allocations to
1044 * a given group. The allocator will avoid allocations to a group
1045 * if that group has reached or is below the zfs_mg_noalloc_threshold
1046 * and there are still other groups that are above the threshold.
1047 * When a group transitions from allocatable to non-allocatable or
1048 * vice versa we update the metaslab class to reflect that change.
1049 * When the mc_alloc_groups value drops to 0 that means that all
1050 * groups have reached the zfs_mg_noalloc_threshold making all groups
1051 * eligible for allocations. This effectively means that all devices
1052 * are balanced again.
1053 */
1054 if (was_allocatable && !mg->mg_allocatable)
1055 mc->mc_alloc_groups--;
1056 else if (!was_allocatable && mg->mg_allocatable)
1057 mc->mc_alloc_groups++;
1058 mutex_exit(&mc->mc_lock);
1059
1060 mutex_exit(&mg->mg_lock);
1061 }
1062
1063 int
metaslab_sort_by_flushed(const void * va,const void * vb)1064 metaslab_sort_by_flushed(const void *va, const void *vb)
1065 {
1066 const metaslab_t *a = va;
1067 const metaslab_t *b = vb;
1068
1069 int cmp = TREE_CMP(a->ms_unflushed_txg, b->ms_unflushed_txg);
1070 if (likely(cmp))
1071 return (cmp);
1072
1073 uint64_t a_vdev_id = a->ms_group->mg_vd->vdev_id;
1074 uint64_t b_vdev_id = b->ms_group->mg_vd->vdev_id;
1075 cmp = TREE_CMP(a_vdev_id, b_vdev_id);
1076 if (cmp)
1077 return (cmp);
1078
1079 return (TREE_CMP(a->ms_id, b->ms_id));
1080 }
1081
1082 metaslab_group_t *
metaslab_group_create(metaslab_class_t * mc,vdev_t * vd)1083 metaslab_group_create(metaslab_class_t *mc, vdev_t *vd)
1084 {
1085 spa_t *spa = mc->mc_spa;
1086 metaslab_group_t *mg;
1087
1088 mg = kmem_zalloc(offsetof(metaslab_group_t,
1089 mg_allocator[spa->spa_alloc_count]), KM_SLEEP);
1090 mutex_init(&mg->mg_lock, NULL, MUTEX_DEFAULT, NULL);
1091 mutex_init(&mg->mg_ms_disabled_lock, NULL, MUTEX_DEFAULT, NULL);
1092 cv_init(&mg->mg_ms_disabled_cv, NULL, CV_DEFAULT, NULL);
1093 avl_create(&mg->mg_metaslab_tree, metaslab_compare,
1094 sizeof (metaslab_t), offsetof(metaslab_t, ms_group_node));
1095 mg->mg_vd = vd;
1096 mg->mg_class = mc;
1097 mg->mg_activation_count = 0;
1098 mg->mg_initialized = B_FALSE;
1099 mg->mg_no_free_space = B_TRUE;
1100
1101 for (int i = 0; i < spa->spa_alloc_count; i++) {
1102 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
1103 zfs_refcount_create_tracked(&mga->mga_queue_depth);
1104 }
1105
1106 return (mg);
1107 }
1108
1109 void
metaslab_group_destroy(metaslab_group_t * mg)1110 metaslab_group_destroy(metaslab_group_t *mg)
1111 {
1112 spa_t *spa = mg->mg_class->mc_spa;
1113
1114 ASSERT0P(mg->mg_prev);
1115 ASSERT0P(mg->mg_next);
1116 /*
1117 * We may have gone below zero with the activation count
1118 * either because we never activated in the first place or
1119 * because we're done, and possibly removing the vdev.
1120 */
1121 ASSERT(mg->mg_activation_count <= 0);
1122
1123 avl_destroy(&mg->mg_metaslab_tree);
1124 mutex_destroy(&mg->mg_lock);
1125 mutex_destroy(&mg->mg_ms_disabled_lock);
1126 cv_destroy(&mg->mg_ms_disabled_cv);
1127
1128 for (int i = 0; i < spa->spa_alloc_count; i++) {
1129 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
1130 zfs_refcount_destroy(&mga->mga_queue_depth);
1131 }
1132 kmem_free(mg, offsetof(metaslab_group_t,
1133 mg_allocator[spa->spa_alloc_count]));
1134 }
1135
1136 void
metaslab_group_activate(metaslab_group_t * mg)1137 metaslab_group_activate(metaslab_group_t *mg)
1138 {
1139 metaslab_class_t *mc = mg->mg_class;
1140 spa_t *spa = mc->mc_spa;
1141 metaslab_group_t *mgprev, *mgnext;
1142
1143 ASSERT3U(spa_config_held(spa, SCL_ALLOC, RW_WRITER), !=, 0);
1144
1145 ASSERT0P(mg->mg_prev);
1146 ASSERT0P(mg->mg_next);
1147 ASSERT(mg->mg_activation_count <= 0);
1148
1149 if (++mg->mg_activation_count <= 0)
1150 return;
1151
1152 metaslab_group_alloc_update(mg);
1153
1154 if ((mgprev = mc->mc_allocator[0].mca_rotor) == NULL) {
1155 mg->mg_prev = mg;
1156 mg->mg_next = mg;
1157 } else {
1158 mgnext = mgprev->mg_next;
1159 mg->mg_prev = mgprev;
1160 mg->mg_next = mgnext;
1161 mgprev->mg_next = mg;
1162 mgnext->mg_prev = mg;
1163 }
1164 for (int i = 0; i < spa->spa_alloc_count; i++) {
1165 mc->mc_allocator[i].mca_rotor = mg;
1166 mg = mg->mg_next;
1167 }
1168 metaslab_class_balance(mc, B_FALSE);
1169 }
1170
1171 /*
1172 * Passivate a metaslab group and remove it from the allocation rotor.
1173 * Callers must hold both the SCL_ALLOC and SCL_ZIO lock prior to passivating
1174 * a metaslab group. This function will momentarily drop spa_config_locks
1175 * that are lower than the SCL_ALLOC lock (see comment below).
1176 */
1177 void
metaslab_group_passivate(metaslab_group_t * mg)1178 metaslab_group_passivate(metaslab_group_t *mg)
1179 {
1180 metaslab_class_t *mc = mg->mg_class;
1181 spa_t *spa = mc->mc_spa;
1182 metaslab_group_t *mgprev, *mgnext;
1183 int locks = spa_config_held(spa, SCL_ALL, RW_WRITER);
1184
1185 ASSERT3U(spa_config_held(spa, SCL_ALLOC | SCL_ZIO, RW_WRITER), ==,
1186 (SCL_ALLOC | SCL_ZIO));
1187
1188 if (--mg->mg_activation_count != 0) {
1189 for (int i = 0; i < spa->spa_alloc_count; i++)
1190 ASSERT(mc->mc_allocator[i].mca_rotor != mg);
1191 ASSERT0P(mg->mg_prev);
1192 ASSERT0P(mg->mg_next);
1193 ASSERT(mg->mg_activation_count < 0);
1194 return;
1195 }
1196
1197 /*
1198 * The spa_config_lock is an array of rwlocks, ordered as
1199 * follows (from highest to lowest):
1200 * SCL_CONFIG > SCL_STATE > SCL_L2ARC > SCL_ALLOC >
1201 * SCL_ZIO > SCL_FREE > SCL_VDEV
1202 * (For more information about the spa_config_lock see spa_misc.c)
1203 * The higher the lock, the broader its coverage. When we passivate
1204 * a metaslab group, we must hold both the SCL_ALLOC and the SCL_ZIO
1205 * config locks. However, the metaslab group's taskq might be trying
1206 * to preload metaslabs so we must drop the SCL_ZIO lock and any
1207 * lower locks to allow the I/O to complete. At a minimum,
1208 * we continue to hold the SCL_ALLOC lock, which prevents any future
1209 * allocations from taking place and any changes to the vdev tree.
1210 */
1211 spa_config_exit(spa, locks & ~(SCL_ZIO - 1), spa);
1212 taskq_wait_outstanding(spa->spa_metaslab_taskq, 0);
1213 spa_config_enter(spa, locks & ~(SCL_ZIO - 1), spa, RW_WRITER);
1214 metaslab_group_alloc_update(mg);
1215 for (int i = 0; i < spa->spa_alloc_count; i++) {
1216 metaslab_group_allocator_t *mga = &mg->mg_allocator[i];
1217 metaslab_t *msp = mga->mga_primary;
1218 if (msp != NULL) {
1219 mutex_enter(&msp->ms_lock);
1220 metaslab_passivate(msp,
1221 metaslab_weight(msp, B_TRUE) &
1222 ~METASLAB_ACTIVE_MASK);
1223 mutex_exit(&msp->ms_lock);
1224 }
1225 msp = mga->mga_secondary;
1226 if (msp != NULL) {
1227 mutex_enter(&msp->ms_lock);
1228 metaslab_passivate(msp,
1229 metaslab_weight(msp, B_TRUE) &
1230 ~METASLAB_ACTIVE_MASK);
1231 mutex_exit(&msp->ms_lock);
1232 }
1233 }
1234
1235 mgprev = mg->mg_prev;
1236 mgnext = mg->mg_next;
1237
1238 if (mg == mgnext) {
1239 mgnext = NULL;
1240 } else {
1241 mgprev->mg_next = mgnext;
1242 mgnext->mg_prev = mgprev;
1243 }
1244 for (int i = 0; i < spa->spa_alloc_count; i++) {
1245 if (mc->mc_allocator[i].mca_rotor == mg)
1246 mc->mc_allocator[i].mca_rotor = mgnext;
1247 }
1248
1249 mg->mg_prev = NULL;
1250 mg->mg_next = NULL;
1251 metaslab_class_balance(mc, B_FALSE);
1252 }
1253
1254 boolean_t
metaslab_group_initialized(metaslab_group_t * mg)1255 metaslab_group_initialized(metaslab_group_t *mg)
1256 {
1257 vdev_t *vd = mg->mg_vd;
1258 vdev_stat_t *vs = &vd->vdev_stat;
1259
1260 return (vs->vs_space != 0 && mg->mg_activation_count > 0);
1261 }
1262
1263 uint64_t
metaslab_group_get_space(metaslab_group_t * mg)1264 metaslab_group_get_space(metaslab_group_t *mg)
1265 {
1266 /*
1267 * Note that the number of nodes in mg_metaslab_tree may be one less
1268 * than vdev_ms_count, due to the embedded log metaslab.
1269 */
1270 mutex_enter(&mg->mg_lock);
1271 uint64_t ms_count = avl_numnodes(&mg->mg_metaslab_tree);
1272 mutex_exit(&mg->mg_lock);
1273 return ((1ULL << mg->mg_vd->vdev_ms_shift) * ms_count);
1274 }
1275
1276 void
metaslab_group_histogram_verify(metaslab_group_t * mg)1277 metaslab_group_histogram_verify(metaslab_group_t *mg)
1278 {
1279 uint64_t *mg_hist;
1280 avl_tree_t *t = &mg->mg_metaslab_tree;
1281 uint64_t ashift = mg->mg_vd->vdev_ashift;
1282
1283 if ((zfs_flags & ZFS_DEBUG_HISTOGRAM_VERIFY) == 0)
1284 return;
1285
1286 mg_hist = kmem_zalloc(sizeof (uint64_t) * ZFS_RANGE_TREE_HISTOGRAM_SIZE,
1287 KM_SLEEP);
1288
1289 ASSERT3U(ZFS_RANGE_TREE_HISTOGRAM_SIZE, >=,
1290 SPACE_MAP_HISTOGRAM_SIZE + ashift);
1291
1292 mutex_enter(&mg->mg_lock);
1293 for (metaslab_t *msp = avl_first(t);
1294 msp != NULL; msp = AVL_NEXT(t, msp)) {
1295 VERIFY3P(msp->ms_group, ==, mg);
1296 /* skip if not active */
1297 if (msp->ms_sm == NULL)
1298 continue;
1299
1300 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1301 mg_hist[i + ashift] +=
1302 msp->ms_sm->sm_phys->smp_histogram[i];
1303 }
1304 }
1305
1306 for (int i = 0; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE; i ++)
1307 VERIFY3U(mg_hist[i], ==, mg->mg_histogram[i]);
1308
1309 mutex_exit(&mg->mg_lock);
1310
1311 kmem_free(mg_hist, sizeof (uint64_t) * ZFS_RANGE_TREE_HISTOGRAM_SIZE);
1312 }
1313
1314 static void
metaslab_group_histogram_add(metaslab_group_t * mg,metaslab_t * msp)1315 metaslab_group_histogram_add(metaslab_group_t *mg, metaslab_t *msp)
1316 {
1317 metaslab_class_t *mc = mg->mg_class;
1318 uint64_t ashift = mg->mg_vd->vdev_ashift;
1319
1320 ASSERT(MUTEX_HELD(&msp->ms_lock));
1321 if (msp->ms_sm == NULL)
1322 return;
1323
1324 mutex_enter(&mg->mg_lock);
1325 mutex_enter(&mc->mc_lock);
1326 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1327 IMPLY(mg == mg->mg_vd->vdev_log_mg,
1328 mc == spa_embedded_log_class(mg->mg_vd->vdev_spa) ||
1329 mc == spa_special_embedded_log_class(mg->mg_vd->vdev_spa));
1330 mg->mg_histogram[i + ashift] +=
1331 msp->ms_sm->sm_phys->smp_histogram[i];
1332 mc->mc_histogram[i + ashift] +=
1333 msp->ms_sm->sm_phys->smp_histogram[i];
1334 }
1335 mutex_exit(&mc->mc_lock);
1336 mutex_exit(&mg->mg_lock);
1337 }
1338
1339 void
metaslab_group_histogram_remove(metaslab_group_t * mg,metaslab_t * msp)1340 metaslab_group_histogram_remove(metaslab_group_t *mg, metaslab_t *msp)
1341 {
1342 metaslab_class_t *mc = mg->mg_class;
1343 uint64_t ashift = mg->mg_vd->vdev_ashift;
1344
1345 ASSERT(MUTEX_HELD(&msp->ms_lock));
1346 if (msp->ms_sm == NULL)
1347 return;
1348
1349 mutex_enter(&mg->mg_lock);
1350 mutex_enter(&mc->mc_lock);
1351 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
1352 ASSERT3U(mg->mg_histogram[i + ashift], >=,
1353 msp->ms_sm->sm_phys->smp_histogram[i]);
1354 ASSERT3U(mc->mc_histogram[i + ashift], >=,
1355 msp->ms_sm->sm_phys->smp_histogram[i]);
1356 IMPLY(mg == mg->mg_vd->vdev_log_mg,
1357 mc == spa_embedded_log_class(mg->mg_vd->vdev_spa) ||
1358 mc == spa_special_embedded_log_class(mg->mg_vd->vdev_spa));
1359
1360 mg->mg_histogram[i + ashift] -=
1361 msp->ms_sm->sm_phys->smp_histogram[i];
1362 mc->mc_histogram[i + ashift] -=
1363 msp->ms_sm->sm_phys->smp_histogram[i];
1364 }
1365 mutex_exit(&mc->mc_lock);
1366 mutex_exit(&mg->mg_lock);
1367 }
1368
1369 static void
metaslab_group_add(metaslab_group_t * mg,metaslab_t * msp)1370 metaslab_group_add(metaslab_group_t *mg, metaslab_t *msp)
1371 {
1372 ASSERT0P(msp->ms_group);
1373 mutex_enter(&mg->mg_lock);
1374 msp->ms_group = mg;
1375 msp->ms_weight = 0;
1376 avl_add(&mg->mg_metaslab_tree, msp);
1377 mutex_exit(&mg->mg_lock);
1378
1379 mutex_enter(&msp->ms_lock);
1380 metaslab_group_histogram_add(mg, msp);
1381 mutex_exit(&msp->ms_lock);
1382 }
1383
1384 static void
metaslab_group_remove(metaslab_group_t * mg,metaslab_t * msp)1385 metaslab_group_remove(metaslab_group_t *mg, metaslab_t *msp)
1386 {
1387 mutex_enter(&msp->ms_lock);
1388 metaslab_group_histogram_remove(mg, msp);
1389 mutex_exit(&msp->ms_lock);
1390
1391 mutex_enter(&mg->mg_lock);
1392 ASSERT(msp->ms_group == mg);
1393 avl_remove(&mg->mg_metaslab_tree, msp);
1394
1395 metaslab_class_t *mc = msp->ms_group->mg_class;
1396 multilist_sublist_t *mls =
1397 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
1398 if (multilist_link_active(&msp->ms_class_txg_node))
1399 multilist_sublist_remove(mls, msp);
1400 multilist_sublist_unlock(mls);
1401
1402 msp->ms_group = NULL;
1403 mutex_exit(&mg->mg_lock);
1404 }
1405
1406 static void
metaslab_group_sort_impl(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)1407 metaslab_group_sort_impl(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1408 {
1409 ASSERT(MUTEX_HELD(&msp->ms_lock));
1410 ASSERT(MUTEX_HELD(&mg->mg_lock));
1411 ASSERT(msp->ms_group == mg);
1412
1413 avl_remove(&mg->mg_metaslab_tree, msp);
1414 msp->ms_weight = weight;
1415 avl_add(&mg->mg_metaslab_tree, msp);
1416
1417 }
1418
1419 static void
metaslab_group_sort(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)1420 metaslab_group_sort(metaslab_group_t *mg, metaslab_t *msp, uint64_t weight)
1421 {
1422 /*
1423 * Although in principle the weight can be any value, in
1424 * practice we do not use values in the range [1, 511].
1425 */
1426 ASSERT(weight >= SPA_MINBLOCKSIZE || weight == 0);
1427 ASSERT(MUTEX_HELD(&msp->ms_lock));
1428
1429 mutex_enter(&mg->mg_lock);
1430 metaslab_group_sort_impl(mg, msp, weight);
1431 mutex_exit(&mg->mg_lock);
1432 }
1433
1434 /*
1435 * Calculate the fragmentation for a given metaslab group. Weight metaslabs
1436 * on the amount of free space. The return value will be between 0 and 100
1437 * (inclusive), or ZFS_FRAG_INVALID if less than half of the metaslab in this
1438 * group have a fragmentation metric.
1439 */
1440 uint64_t
metaslab_group_fragmentation(metaslab_group_t * mg)1441 metaslab_group_fragmentation(metaslab_group_t *mg)
1442 {
1443 vdev_t *vd = mg->mg_vd;
1444 uint64_t fragmentation = 0;
1445 uint64_t valid_ms = 0, total_ms = 0;
1446 uint64_t free, total_free = 0;
1447
1448 for (int m = 0; m < vd->vdev_ms_count; m++) {
1449 metaslab_t *msp = vd->vdev_ms[m];
1450
1451 if (msp->ms_group != mg)
1452 continue;
1453 total_ms++;
1454 if (msp->ms_fragmentation == ZFS_FRAG_INVALID)
1455 continue;
1456
1457 valid_ms++;
1458 free = (msp->ms_size - metaslab_allocated_space(msp)) /
1459 SPA_MINBLOCKSIZE; /* To prevent overflows. */
1460 total_free += free;
1461 fragmentation += msp->ms_fragmentation * free;
1462 }
1463
1464 if (valid_ms < (total_ms + 1) / 2 || total_free == 0)
1465 return (ZFS_FRAG_INVALID);
1466
1467 fragmentation /= total_free;
1468 ASSERT3U(fragmentation, <=, 100);
1469 return (fragmentation);
1470 }
1471
1472 /*
1473 * ==========================================================================
1474 * Range tree callbacks
1475 * ==========================================================================
1476 */
1477
1478 /*
1479 * Comparison function for the private size-ordered tree using 32-bit
1480 * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1481 */
1482 __attribute__((always_inline)) inline
1483 static int
metaslab_rangesize32_compare(const void * x1,const void * x2)1484 metaslab_rangesize32_compare(const void *x1, const void *x2)
1485 {
1486 const zfs_range_seg32_t *r1 = x1;
1487 const zfs_range_seg32_t *r2 = x2;
1488
1489 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1490 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1491
1492 int cmp = TREE_CMP(rs_size1, rs_size2);
1493
1494 return (cmp + !cmp * TREE_CMP(r1->rs_start, r2->rs_start));
1495 }
1496
1497 /*
1498 * Comparison function for the private size-ordered tree using 64-bit
1499 * ranges. Tree is sorted by size, larger sizes at the end of the tree.
1500 */
1501 __attribute__((always_inline)) inline
1502 static int
metaslab_rangesize64_compare(const void * x1,const void * x2)1503 metaslab_rangesize64_compare(const void *x1, const void *x2)
1504 {
1505 const zfs_range_seg64_t *r1 = x1;
1506 const zfs_range_seg64_t *r2 = x2;
1507
1508 uint64_t rs_size1 = r1->rs_end - r1->rs_start;
1509 uint64_t rs_size2 = r2->rs_end - r2->rs_start;
1510
1511 int cmp = TREE_CMP(rs_size1, rs_size2);
1512
1513 return (cmp + !cmp * TREE_CMP(r1->rs_start, r2->rs_start));
1514 }
1515
1516 typedef struct metaslab_rt_arg {
1517 zfs_btree_t *mra_bt;
1518 uint32_t mra_floor_shift;
1519 } metaslab_rt_arg_t;
1520
1521 struct mssa_arg {
1522 zfs_range_tree_t *rt;
1523 metaslab_rt_arg_t *mra;
1524 };
1525
1526 static void
metaslab_size_sorted_add(void * arg,uint64_t start,uint64_t size)1527 metaslab_size_sorted_add(void *arg, uint64_t start, uint64_t size)
1528 {
1529 struct mssa_arg *mssap = arg;
1530 zfs_range_tree_t *rt = mssap->rt;
1531 metaslab_rt_arg_t *mrap = mssap->mra;
1532 zfs_range_seg_max_t seg = {0};
1533 zfs_rs_set_start(&seg, rt, start);
1534 zfs_rs_set_end(&seg, rt, start + size);
1535 metaslab_rt_add(rt, &seg, mrap);
1536 }
1537
1538 static void
metaslab_size_tree_full_load(zfs_range_tree_t * rt)1539 metaslab_size_tree_full_load(zfs_range_tree_t *rt)
1540 {
1541 metaslab_rt_arg_t *mrap = rt->rt_arg;
1542 METASLABSTAT_BUMP(metaslabstat_reload_tree);
1543 ASSERT0(zfs_btree_numnodes(mrap->mra_bt));
1544 mrap->mra_floor_shift = 0;
1545 struct mssa_arg arg = {0};
1546 arg.rt = rt;
1547 arg.mra = mrap;
1548 zfs_range_tree_walk(rt, metaslab_size_sorted_add, &arg);
1549 }
1550
1551
ZFS_BTREE_FIND_IN_BUF_FUNC(metaslab_rt_find_rangesize32_in_buf,zfs_range_seg32_t,metaslab_rangesize32_compare)1552 ZFS_BTREE_FIND_IN_BUF_FUNC(metaslab_rt_find_rangesize32_in_buf,
1553 zfs_range_seg32_t, metaslab_rangesize32_compare)
1554
1555 ZFS_BTREE_FIND_IN_BUF_FUNC(metaslab_rt_find_rangesize64_in_buf,
1556 zfs_range_seg64_t, metaslab_rangesize64_compare)
1557
1558 /*
1559 * Create any block allocator specific components. The current allocators
1560 * rely on using both a size-ordered zfs_range_tree_t and an array of
1561 * uint64_t's.
1562 */
1563 static void
1564 metaslab_rt_create(zfs_range_tree_t *rt, void *arg)
1565 {
1566 metaslab_rt_arg_t *mrap = arg;
1567 zfs_btree_t *size_tree = mrap->mra_bt;
1568
1569 size_t size;
1570 int (*compare) (const void *, const void *);
1571 bt_find_in_buf_f bt_find;
1572 switch (rt->rt_type) {
1573 case ZFS_RANGE_SEG32:
1574 size = sizeof (zfs_range_seg32_t);
1575 compare = metaslab_rangesize32_compare;
1576 bt_find = metaslab_rt_find_rangesize32_in_buf;
1577 break;
1578 case ZFS_RANGE_SEG64:
1579 size = sizeof (zfs_range_seg64_t);
1580 compare = metaslab_rangesize64_compare;
1581 bt_find = metaslab_rt_find_rangesize64_in_buf;
1582 break;
1583 default:
1584 panic("Invalid range seg type %d", rt->rt_type);
1585 }
1586 zfs_btree_create(size_tree, compare, bt_find, size);
1587 mrap->mra_floor_shift = metaslab_by_size_min_shift;
1588 }
1589
1590 static void
metaslab_rt_destroy(zfs_range_tree_t * rt,void * arg)1591 metaslab_rt_destroy(zfs_range_tree_t *rt, void *arg)
1592 {
1593 (void) rt;
1594 metaslab_rt_arg_t *mrap = arg;
1595 zfs_btree_t *size_tree = mrap->mra_bt;
1596
1597 zfs_btree_destroy(size_tree);
1598 kmem_free(mrap, sizeof (*mrap));
1599 }
1600
1601 static void
metaslab_rt_add(zfs_range_tree_t * rt,zfs_range_seg_t * rs,void * arg)1602 metaslab_rt_add(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)
1603 {
1604 metaslab_rt_arg_t *mrap = arg;
1605 zfs_btree_t *size_tree = mrap->mra_bt;
1606
1607 if (zfs_rs_get_end(rs, rt) - zfs_rs_get_start(rs, rt) <
1608 (1ULL << mrap->mra_floor_shift))
1609 return;
1610
1611 zfs_btree_add(size_tree, rs);
1612 }
1613
1614 static void
metaslab_rt_remove(zfs_range_tree_t * rt,zfs_range_seg_t * rs,void * arg)1615 metaslab_rt_remove(zfs_range_tree_t *rt, zfs_range_seg_t *rs, void *arg)
1616 {
1617 metaslab_rt_arg_t *mrap = arg;
1618 zfs_btree_t *size_tree = mrap->mra_bt;
1619
1620 if (zfs_rs_get_end(rs, rt) - zfs_rs_get_start(rs, rt) < (1ULL <<
1621 mrap->mra_floor_shift))
1622 return;
1623
1624 zfs_btree_remove(size_tree, rs);
1625 }
1626
1627 static void
metaslab_rt_vacate(zfs_range_tree_t * rt,void * arg)1628 metaslab_rt_vacate(zfs_range_tree_t *rt, void *arg)
1629 {
1630 metaslab_rt_arg_t *mrap = arg;
1631 zfs_btree_t *size_tree = mrap->mra_bt;
1632 zfs_btree_clear(size_tree);
1633 zfs_btree_destroy(size_tree);
1634
1635 metaslab_rt_create(rt, arg);
1636 }
1637
1638 static const zfs_range_tree_ops_t metaslab_rt_ops = {
1639 .rtop_create = metaslab_rt_create,
1640 .rtop_destroy = metaslab_rt_destroy,
1641 .rtop_add = metaslab_rt_add,
1642 .rtop_remove = metaslab_rt_remove,
1643 .rtop_vacate = metaslab_rt_vacate
1644 };
1645
1646 /*
1647 * ==========================================================================
1648 * Common allocator routines
1649 * ==========================================================================
1650 */
1651
1652 /*
1653 * Return the maximum contiguous segment within the metaslab.
1654 */
1655 uint64_t
metaslab_largest_allocatable(metaslab_t * msp)1656 metaslab_largest_allocatable(metaslab_t *msp)
1657 {
1658 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1659 zfs_range_seg_t *rs;
1660
1661 if (t == NULL)
1662 return (0);
1663 if (zfs_btree_numnodes(t) == 0)
1664 metaslab_size_tree_full_load(msp->ms_allocatable);
1665
1666 rs = zfs_btree_last(t, NULL);
1667 if (rs == NULL)
1668 return (0);
1669
1670 return (zfs_rs_get_end(rs, msp->ms_allocatable) - zfs_rs_get_start(rs,
1671 msp->ms_allocatable));
1672 }
1673
1674 /*
1675 * Return the maximum contiguous segment within the unflushed frees of this
1676 * metaslab.
1677 */
1678 static uint64_t
metaslab_largest_unflushed_free(metaslab_t * msp)1679 metaslab_largest_unflushed_free(metaslab_t *msp)
1680 {
1681 ASSERT(MUTEX_HELD(&msp->ms_lock));
1682
1683 if (msp->ms_unflushed_frees == NULL)
1684 return (0);
1685
1686 if (zfs_btree_numnodes(&msp->ms_unflushed_frees_by_size) == 0)
1687 metaslab_size_tree_full_load(msp->ms_unflushed_frees);
1688 zfs_range_seg_t *rs = zfs_btree_last(&msp->ms_unflushed_frees_by_size,
1689 NULL);
1690 if (rs == NULL)
1691 return (0);
1692
1693 /*
1694 * When a range is freed from the metaslab, that range is added to
1695 * both the unflushed frees and the deferred frees. While the block
1696 * will eventually be usable, if the metaslab were loaded the range
1697 * would not be added to the ms_allocatable tree until TXG_DEFER_SIZE
1698 * txgs had passed. As a result, when attempting to estimate an upper
1699 * bound for the largest currently-usable free segment in the
1700 * metaslab, we need to not consider any ranges currently in the defer
1701 * trees. This algorithm approximates the largest available chunk in
1702 * the largest range in the unflushed_frees tree by taking the first
1703 * chunk. While this may be a poor estimate, it should only remain so
1704 * briefly and should eventually self-correct as frees are no longer
1705 * deferred. Similar logic applies to the ms_freed tree. See
1706 * metaslab_load() for more details.
1707 *
1708 * There are two primary sources of inaccuracy in this estimate. Both
1709 * are tolerated for performance reasons. The first source is that we
1710 * only check the largest segment for overlaps. Smaller segments may
1711 * have more favorable overlaps with the other trees, resulting in
1712 * larger usable chunks. Second, we only look at the first chunk in
1713 * the largest segment; there may be other usable chunks in the
1714 * largest segment, but we ignore them.
1715 */
1716 uint64_t rstart = zfs_rs_get_start(rs, msp->ms_unflushed_frees);
1717 uint64_t rsize = zfs_rs_get_end(rs, msp->ms_unflushed_frees) - rstart;
1718 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
1719 uint64_t start = 0;
1720 uint64_t size = 0;
1721 boolean_t found = zfs_range_tree_find_in(msp->ms_defer[t],
1722 rstart, rsize, &start, &size);
1723 if (found) {
1724 if (rstart == start)
1725 return (0);
1726 rsize = start - rstart;
1727 }
1728 }
1729
1730 uint64_t start = 0;
1731 uint64_t size = 0;
1732 boolean_t found = zfs_range_tree_find_in(msp->ms_freed, rstart,
1733 rsize, &start, &size);
1734 if (found)
1735 rsize = start - rstart;
1736
1737 return (rsize);
1738 }
1739
1740 static zfs_range_seg_t *
metaslab_block_find(zfs_btree_t * t,zfs_range_tree_t * rt,uint64_t start,uint64_t size,uint64_t max_size,zfs_btree_index_t * where)1741 metaslab_block_find(zfs_btree_t *t, zfs_range_tree_t *rt, uint64_t start,
1742 uint64_t size, uint64_t max_size, zfs_btree_index_t *where)
1743 {
1744 zfs_range_seg_t *rs;
1745 zfs_range_seg_max_t rsearch;
1746
1747 zfs_rs_set_start(&rsearch, rt, start);
1748 zfs_rs_set_end(&rsearch, rt, start + max_size);
1749
1750 rs = zfs_btree_find(t, &rsearch, where);
1751 if (rs == NULL) {
1752 if (size == max_size) {
1753 rs = zfs_btree_next(t, where, where);
1754 } else {
1755 /*
1756 * If we're searching for a range, get the largest
1757 * segment in that range, or the smallest one bigger
1758 * than it.
1759 */
1760 rs = zfs_btree_prev(t, where, where);
1761 if (rs == NULL || zfs_rs_get_end(rs, rt) -
1762 zfs_rs_get_start(rs, rt) < size) {
1763 rs = zfs_btree_next(t, where, where);
1764 }
1765 }
1766 }
1767
1768 return (rs);
1769 }
1770
1771 /*
1772 * This is a helper function that can be used by the allocator to find a
1773 * suitable block to allocate. This will search the specified B-tree looking
1774 * for a block that matches the specified criteria.
1775 */
1776 static uint64_t
metaslab_block_picker(zfs_range_tree_t * rt,uint64_t * cursor,uint64_t size,uint64_t max_size,uint64_t max_search,uint64_t * found_size)1777 metaslab_block_picker(zfs_range_tree_t *rt, uint64_t *cursor, uint64_t size,
1778 uint64_t max_size, uint64_t max_search, uint64_t *found_size)
1779 {
1780 if (*cursor == 0)
1781 *cursor = rt->rt_start;
1782 zfs_btree_t *bt = &rt->rt_root;
1783 zfs_btree_index_t where;
1784 zfs_range_seg_t *rs = metaslab_block_find(bt, rt, *cursor, size,
1785 max_size, &where);
1786 uint64_t first_found;
1787 int count_searched = 0;
1788
1789 if (rs != NULL)
1790 first_found = zfs_rs_get_start(rs, rt);
1791
1792 while (rs != NULL && (zfs_rs_get_start(rs, rt) - first_found <=
1793 max_search || count_searched < metaslab_min_search_count)) {
1794 uint64_t offset = zfs_rs_get_start(rs, rt);
1795 if (offset + size <= zfs_rs_get_end(rs, rt)) {
1796 *found_size = MIN(zfs_rs_get_end(rs, rt) - offset,
1797 max_size);
1798 *cursor = offset + *found_size;
1799 return (offset);
1800 }
1801 rs = zfs_btree_next(bt, &where, &where);
1802 count_searched++;
1803 }
1804
1805 *cursor = 0;
1806 *found_size = 0;
1807 return (-1ULL);
1808 }
1809
1810 static uint64_t metaslab_df_alloc(metaslab_t *msp, uint64_t size,
1811 uint64_t max_size, uint64_t *found_size);
1812 static uint64_t metaslab_cf_alloc(metaslab_t *msp, uint64_t size,
1813 uint64_t max_size, uint64_t *found_size);
1814 static uint64_t metaslab_ndf_alloc(metaslab_t *msp, uint64_t size,
1815 uint64_t max_size, uint64_t *found_size);
1816 metaslab_ops_t *metaslab_allocator(spa_t *spa);
1817
1818 static metaslab_ops_t metaslab_allocators[] = {
1819 { "dynamic", metaslab_df_alloc },
1820 { "cursor", metaslab_cf_alloc },
1821 { "new-dynamic", metaslab_ndf_alloc },
1822 };
1823
1824 static int
spa_find_allocator_byname(const char * val)1825 spa_find_allocator_byname(const char *val)
1826 {
1827 int a = ARRAY_SIZE(metaslab_allocators) - 1;
1828 if (strcmp("new-dynamic", val) == 0)
1829 return (-1); /* remove when ndf is working */
1830 for (; a >= 0; a--) {
1831 if (strcmp(val, metaslab_allocators[a].msop_name) == 0)
1832 return (a);
1833 }
1834 return (-1);
1835 }
1836
1837 void
spa_set_allocator(spa_t * spa,const char * allocator)1838 spa_set_allocator(spa_t *spa, const char *allocator)
1839 {
1840 int a = spa_find_allocator_byname(allocator);
1841 if (a < 0) a = 0;
1842 spa->spa_active_allocator = a;
1843 zfs_dbgmsg("spa allocator: %s", metaslab_allocators[a].msop_name);
1844 }
1845
1846 int
spa_get_allocator(spa_t * spa)1847 spa_get_allocator(spa_t *spa)
1848 {
1849 return (spa->spa_active_allocator);
1850 }
1851
1852 #if defined(_KERNEL)
1853 int
param_set_active_allocator_common(const char * val)1854 param_set_active_allocator_common(const char *val)
1855 {
1856 char *p;
1857
1858 if (val == NULL)
1859 return (SET_ERROR(EINVAL));
1860
1861 if ((p = strchr(val, '\n')) != NULL)
1862 *p = '\0';
1863
1864 int a = spa_find_allocator_byname(val);
1865 if (a < 0)
1866 return (SET_ERROR(EINVAL));
1867
1868 zfs_active_allocator = metaslab_allocators[a].msop_name;
1869 return (0);
1870 }
1871 #endif
1872
1873 metaslab_ops_t *
metaslab_allocator(spa_t * spa)1874 metaslab_allocator(spa_t *spa)
1875 {
1876 int allocator = spa_get_allocator(spa);
1877 return (&metaslab_allocators[allocator]);
1878 }
1879
1880 /*
1881 * ==========================================================================
1882 * Dynamic Fit (df) block allocator
1883 *
1884 * Search for a free chunk of at least this size, starting from the last
1885 * offset (for this alignment of block) looking for up to
1886 * metaslab_df_max_search bytes (16MB). If a large enough free chunk is not
1887 * found within 16MB, then return a free chunk of exactly the requested size (or
1888 * larger).
1889 *
1890 * If it seems like searching from the last offset will be unproductive, skip
1891 * that and just return a free chunk of exactly the requested size (or larger).
1892 * This is based on metaslab_df_alloc_threshold and metaslab_df_free_pct. This
1893 * mechanism is probably not very useful and may be removed in the future.
1894 *
1895 * The behavior when not searching can be changed to return the largest free
1896 * chunk, instead of a free chunk of exactly the requested size, by setting
1897 * metaslab_df_use_largest_segment.
1898 * ==========================================================================
1899 */
1900 static uint64_t
metaslab_df_alloc(metaslab_t * msp,uint64_t size,uint64_t max_size,uint64_t * found_size)1901 metaslab_df_alloc(metaslab_t *msp, uint64_t size, uint64_t max_size,
1902 uint64_t *found_size)
1903 {
1904 /*
1905 * Find the largest power of 2 block size that evenly divides the
1906 * requested size. This is used to try to allocate blocks with similar
1907 * alignment from the same area of the metaslab (i.e. same cursor
1908 * bucket) but it does not guarantee that other allocations sizes
1909 * may exist in the same region.
1910 */
1911 uint64_t align = max_size & -max_size;
1912 uint64_t *cursor = &msp->ms_lbas[highbit64(align) - 1];
1913 zfs_range_tree_t *rt = msp->ms_allocatable;
1914 uint_t free_pct = zfs_range_tree_space(rt) * 100 / msp->ms_size;
1915 uint64_t offset;
1916
1917 ASSERT(MUTEX_HELD(&msp->ms_lock));
1918
1919 /*
1920 * If we're running low on space, find a segment based on size,
1921 * rather than iterating based on offset.
1922 */
1923 if (metaslab_largest_allocatable(msp) < metaslab_df_alloc_threshold ||
1924 free_pct < metaslab_df_free_pct) {
1925 align = size & -size;
1926 cursor = &msp->ms_lbas[highbit64(align) - 1];
1927 offset = -1;
1928 } else {
1929 offset = metaslab_block_picker(rt, cursor, size, max_size,
1930 metaslab_df_max_search, found_size);
1931 if (max_size != size && offset == -1) {
1932 align = size & -size;
1933 cursor = &msp->ms_lbas[highbit64(align) - 1];
1934 offset = metaslab_block_picker(rt, cursor, size,
1935 max_size, metaslab_df_max_search, found_size);
1936 }
1937 }
1938
1939 if (offset == -1) {
1940 zfs_range_seg_t *rs;
1941 if (zfs_btree_numnodes(&msp->ms_allocatable_by_size) == 0)
1942 metaslab_size_tree_full_load(msp->ms_allocatable);
1943
1944 if (metaslab_df_use_largest_segment) {
1945 /* use largest free segment */
1946 rs = zfs_btree_last(&msp->ms_allocatable_by_size, NULL);
1947 } else {
1948 zfs_btree_index_t where;
1949 /* use segment of this size, or next largest */
1950 rs = metaslab_block_find(&msp->ms_allocatable_by_size,
1951 rt, msp->ms_start, size, max_size, &where);
1952 }
1953 if (rs != NULL && zfs_rs_get_start(rs, rt) + size <=
1954 zfs_rs_get_end(rs, rt)) {
1955 offset = zfs_rs_get_start(rs, rt);
1956 *found_size = MIN(zfs_rs_get_end(rs, rt) - offset,
1957 max_size);
1958 *cursor = offset + *found_size;
1959 }
1960 }
1961
1962 return (offset);
1963 }
1964
1965 /*
1966 * ==========================================================================
1967 * Cursor fit block allocator -
1968 * Select the largest region in the metaslab, set the cursor to the beginning
1969 * of the range and the cursor_end to the end of the range. As allocations
1970 * are made advance the cursor. Continue allocating from the cursor until
1971 * the range is exhausted and then find a new range.
1972 * ==========================================================================
1973 */
1974 static uint64_t
metaslab_cf_alloc(metaslab_t * msp,uint64_t size,uint64_t max_size,uint64_t * found_size)1975 metaslab_cf_alloc(metaslab_t *msp, uint64_t size, uint64_t max_size,
1976 uint64_t *found_size)
1977 {
1978 zfs_range_tree_t *rt = msp->ms_allocatable;
1979 zfs_btree_t *t = &msp->ms_allocatable_by_size;
1980 uint64_t *cursor = &msp->ms_lbas[0];
1981 uint64_t *cursor_end = &msp->ms_lbas[1];
1982 uint64_t offset = 0;
1983
1984 ASSERT(MUTEX_HELD(&msp->ms_lock));
1985
1986 ASSERT3U(*cursor_end, >=, *cursor);
1987
1988 if ((*cursor + size) > *cursor_end) {
1989 zfs_range_seg_t *rs;
1990
1991 if (zfs_btree_numnodes(t) == 0)
1992 metaslab_size_tree_full_load(msp->ms_allocatable);
1993 rs = zfs_btree_last(t, NULL);
1994 if (rs == NULL || (zfs_rs_get_end(rs, rt) -
1995 zfs_rs_get_start(rs, rt)) < size)
1996 return (-1ULL);
1997
1998 *cursor = zfs_rs_get_start(rs, rt);
1999 *cursor_end = zfs_rs_get_end(rs, rt);
2000 }
2001
2002 offset = *cursor;
2003 *found_size = MIN(*cursor_end - offset, max_size);
2004 *cursor = offset + *found_size;
2005
2006 return (offset);
2007 }
2008
2009 /*
2010 * ==========================================================================
2011 * New dynamic fit allocator -
2012 * Select a region that is large enough to allocate 2^metaslab_ndf_clump_shift
2013 * contiguous blocks. If no region is found then just use the largest segment
2014 * that remains.
2015 * ==========================================================================
2016 */
2017
2018 /*
2019 * Determines desired number of contiguous blocks (2^metaslab_ndf_clump_shift)
2020 * to request from the allocator.
2021 */
2022 uint64_t metaslab_ndf_clump_shift = 4;
2023
2024 static uint64_t
metaslab_ndf_alloc(metaslab_t * msp,uint64_t size,uint64_t max_size,uint64_t * found_size)2025 metaslab_ndf_alloc(metaslab_t *msp, uint64_t size, uint64_t max_size,
2026 uint64_t *found_size)
2027 {
2028 zfs_btree_t *t = &msp->ms_allocatable->rt_root;
2029 zfs_range_tree_t *rt = msp->ms_allocatable;
2030 zfs_btree_index_t where;
2031 zfs_range_seg_t *rs;
2032 zfs_range_seg_max_t rsearch;
2033 uint64_t hbit = highbit64(max_size);
2034 uint64_t *cursor = &msp->ms_lbas[hbit - 1];
2035 uint64_t max_possible_size = metaslab_largest_allocatable(msp);
2036
2037 ASSERT(MUTEX_HELD(&msp->ms_lock));
2038
2039 if (max_possible_size < size)
2040 return (-1ULL);
2041
2042 zfs_rs_set_start(&rsearch, rt, *cursor);
2043 zfs_rs_set_end(&rsearch, rt, *cursor + max_size);
2044
2045 rs = zfs_btree_find(t, &rsearch, &where);
2046 if (rs == NULL || (zfs_rs_get_end(rs, rt) - zfs_rs_get_start(rs, rt)) <
2047 max_size) {
2048 hbit = highbit64(size);
2049 cursor = &msp->ms_lbas[hbit - 1];
2050 zfs_rs_set_start(&rsearch, rt, *cursor);
2051 zfs_rs_set_end(&rsearch, rt, *cursor + size);
2052
2053 rs = zfs_btree_find(t, &rsearch, &where);
2054 }
2055 if (rs == NULL || (zfs_rs_get_end(rs, rt) - zfs_rs_get_start(rs, rt)) <
2056 size) {
2057 t = &msp->ms_allocatable_by_size;
2058
2059 zfs_rs_set_start(&rsearch, rt, 0);
2060 zfs_rs_set_end(&rsearch, rt, MIN(max_possible_size,
2061 1ULL << (hbit + metaslab_ndf_clump_shift)));
2062
2063 rs = zfs_btree_find(t, &rsearch, &where);
2064 if (rs == NULL)
2065 rs = zfs_btree_next(t, &where, &where);
2066 ASSERT(rs != NULL);
2067 }
2068
2069 if ((zfs_rs_get_end(rs, rt) - zfs_rs_get_start(rs, rt)) >= size) {
2070 *found_size = MIN(zfs_rs_get_end(rs, rt) -
2071 zfs_rs_get_start(rs, rt), max_size);
2072 *cursor = zfs_rs_get_start(rs, rt) + *found_size;
2073 return (zfs_rs_get_start(rs, rt));
2074 }
2075 return (-1ULL);
2076 }
2077
2078 /*
2079 * ==========================================================================
2080 * Metaslabs
2081 * ==========================================================================
2082 */
2083
2084 /*
2085 * Wait for any in-progress metaslab loads to complete.
2086 */
2087 static void
metaslab_load_wait(metaslab_t * msp)2088 metaslab_load_wait(metaslab_t *msp)
2089 {
2090 ASSERT(MUTEX_HELD(&msp->ms_lock));
2091
2092 while (msp->ms_loading) {
2093 ASSERT(!msp->ms_loaded);
2094 cv_wait(&msp->ms_load_cv, &msp->ms_lock);
2095 }
2096 }
2097
2098 /*
2099 * Wait for any in-progress flushing to complete.
2100 */
2101 static void
metaslab_flush_wait(metaslab_t * msp)2102 metaslab_flush_wait(metaslab_t *msp)
2103 {
2104 ASSERT(MUTEX_HELD(&msp->ms_lock));
2105
2106 while (msp->ms_flushing)
2107 cv_wait(&msp->ms_flush_cv, &msp->ms_lock);
2108 }
2109
2110 static unsigned int
metaslab_idx_func(multilist_t * ml,void * arg)2111 metaslab_idx_func(multilist_t *ml, void *arg)
2112 {
2113 metaslab_t *msp = arg;
2114
2115 /*
2116 * ms_id values are allocated sequentially, so full 64bit
2117 * division would be a waste of time, so limit it to 32 bits.
2118 */
2119 return ((unsigned int)msp->ms_id % multilist_get_num_sublists(ml));
2120 }
2121
2122 uint64_t
metaslab_allocated_space(metaslab_t * msp)2123 metaslab_allocated_space(metaslab_t *msp)
2124 {
2125 return (msp->ms_allocated_space);
2126 }
2127
2128 /*
2129 * Verify that the space accounting on disk matches the in-core range_trees.
2130 */
2131 static void
metaslab_verify_space(metaslab_t * msp,uint64_t txg)2132 metaslab_verify_space(metaslab_t *msp, uint64_t txg)
2133 {
2134 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2135 uint64_t allocating = 0;
2136 uint64_t sm_free_space, msp_free_space;
2137
2138 ASSERT(MUTEX_HELD(&msp->ms_lock));
2139 ASSERT(!msp->ms_condensing);
2140
2141 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
2142 return;
2143
2144 /*
2145 * We can only verify the metaslab space when we're called
2146 * from syncing context with a loaded metaslab that has an
2147 * allocated space map. Calling this in non-syncing context
2148 * does not provide a consistent view of the metaslab since
2149 * we're performing allocations in the future.
2150 */
2151 if (txg != spa_syncing_txg(spa) || msp->ms_sm == NULL ||
2152 !msp->ms_loaded)
2153 return;
2154
2155 /*
2156 * Even though the smp_alloc field can get negative,
2157 * when it comes to a metaslab's space map, that should
2158 * never be the case.
2159 */
2160 ASSERT3S(space_map_allocated(msp->ms_sm), >=, 0);
2161
2162 ASSERT3U(space_map_allocated(msp->ms_sm), >=,
2163 zfs_range_tree_space(msp->ms_unflushed_frees));
2164
2165 ASSERT3U(metaslab_allocated_space(msp), ==,
2166 space_map_allocated(msp->ms_sm) +
2167 zfs_range_tree_space(msp->ms_unflushed_allocs) -
2168 zfs_range_tree_space(msp->ms_unflushed_frees));
2169
2170 sm_free_space = msp->ms_size - metaslab_allocated_space(msp);
2171
2172 /*
2173 * Account for future allocations since we would have
2174 * already deducted that space from the ms_allocatable.
2175 */
2176 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
2177 allocating +=
2178 zfs_range_tree_space(msp->ms_allocating[(txg + t) &
2179 TXG_MASK]);
2180 }
2181 ASSERT3U(allocating + msp->ms_allocated_this_txg, ==,
2182 msp->ms_allocating_total);
2183
2184 ASSERT3U(msp->ms_deferspace, ==,
2185 zfs_range_tree_space(msp->ms_defer[0]) +
2186 zfs_range_tree_space(msp->ms_defer[1]));
2187
2188 msp_free_space = zfs_range_tree_space(msp->ms_allocatable) +
2189 allocating + msp->ms_deferspace +
2190 zfs_range_tree_space(msp->ms_freed);
2191
2192 VERIFY3U(sm_free_space, ==, msp_free_space);
2193 }
2194
2195 static void
metaslab_aux_histograms_clear(metaslab_t * msp)2196 metaslab_aux_histograms_clear(metaslab_t *msp)
2197 {
2198 /*
2199 * Auxiliary histograms are only cleared when resetting them,
2200 * which can only happen while the metaslab is loaded.
2201 */
2202 ASSERT(msp->ms_loaded);
2203
2204 memset(msp->ms_synchist, 0, sizeof (msp->ms_synchist));
2205 for (int t = 0; t < TXG_DEFER_SIZE; t++)
2206 memset(msp->ms_deferhist[t], 0, sizeof (msp->ms_deferhist[t]));
2207 }
2208
2209 static void
metaslab_aux_histogram_add(uint64_t * histogram,uint64_t shift,zfs_range_tree_t * rt)2210 metaslab_aux_histogram_add(uint64_t *histogram, uint64_t shift,
2211 zfs_range_tree_t *rt)
2212 {
2213 /*
2214 * This is modeled after space_map_histogram_add(), so refer to that
2215 * function for implementation details. We want this to work like
2216 * the space map histogram, and not the range tree histogram, as we
2217 * are essentially constructing a delta that will be later subtracted
2218 * from the space map histogram.
2219 */
2220 int idx = 0;
2221 for (int i = shift; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE; i++) {
2222 ASSERT3U(i, >=, idx + shift);
2223 histogram[idx] += rt->rt_histogram[i] << (i - idx - shift);
2224
2225 if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
2226 ASSERT3U(idx + shift, ==, i);
2227 idx++;
2228 ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
2229 }
2230 }
2231 }
2232
2233 /*
2234 * Called at every sync pass that the metaslab gets synced.
2235 *
2236 * The reason is that we want our auxiliary histograms to be updated
2237 * wherever the metaslab's space map histogram is updated. This way
2238 * we stay consistent on which parts of the metaslab space map's
2239 * histogram are currently not available for allocations (e.g because
2240 * they are in the defer, freed, and freeing trees).
2241 */
2242 static void
metaslab_aux_histograms_update(metaslab_t * msp)2243 metaslab_aux_histograms_update(metaslab_t *msp)
2244 {
2245 space_map_t *sm = msp->ms_sm;
2246 ASSERT(sm != NULL);
2247
2248 /*
2249 * This is similar to the metaslab's space map histogram updates
2250 * that take place in metaslab_sync(). The only difference is that
2251 * we only care about segments that haven't made it into the
2252 * ms_allocatable tree yet.
2253 */
2254 if (msp->ms_loaded) {
2255 metaslab_aux_histograms_clear(msp);
2256
2257 metaslab_aux_histogram_add(msp->ms_synchist,
2258 sm->sm_shift, msp->ms_freed);
2259
2260 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2261 metaslab_aux_histogram_add(msp->ms_deferhist[t],
2262 sm->sm_shift, msp->ms_defer[t]);
2263 }
2264 }
2265
2266 metaslab_aux_histogram_add(msp->ms_synchist,
2267 sm->sm_shift, msp->ms_freeing);
2268 }
2269
2270 /*
2271 * Called every time we are done syncing (writing to) the metaslab,
2272 * i.e. at the end of each sync pass.
2273 * [see the comment in metaslab_impl.h for ms_synchist, ms_deferhist]
2274 */
2275 static void
metaslab_aux_histograms_update_done(metaslab_t * msp,boolean_t defer_allowed)2276 metaslab_aux_histograms_update_done(metaslab_t *msp, boolean_t defer_allowed)
2277 {
2278 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2279 space_map_t *sm = msp->ms_sm;
2280
2281 if (sm == NULL) {
2282 /*
2283 * We came here from metaslab_init() when creating/opening a
2284 * pool, looking at a metaslab that hasn't had any allocations
2285 * yet.
2286 */
2287 return;
2288 }
2289
2290 /*
2291 * This is similar to the actions that we take for the ms_freed
2292 * and ms_defer trees in metaslab_sync_done().
2293 */
2294 uint64_t hist_index = spa_syncing_txg(spa) % TXG_DEFER_SIZE;
2295 if (defer_allowed) {
2296 memcpy(msp->ms_deferhist[hist_index], msp->ms_synchist,
2297 sizeof (msp->ms_synchist));
2298 } else {
2299 memset(msp->ms_deferhist[hist_index], 0,
2300 sizeof (msp->ms_deferhist[hist_index]));
2301 }
2302 memset(msp->ms_synchist, 0, sizeof (msp->ms_synchist));
2303 }
2304
2305 /*
2306 * Ensure that the metaslab's weight and fragmentation are consistent
2307 * with the contents of the histogram (either the range tree's histogram
2308 * or the space map's depending whether the metaslab is loaded).
2309 */
2310 static void
metaslab_verify_weight_and_frag(metaslab_t * msp)2311 metaslab_verify_weight_and_frag(metaslab_t *msp)
2312 {
2313 ASSERT(MUTEX_HELD(&msp->ms_lock));
2314
2315 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
2316 return;
2317
2318 /*
2319 * We can end up here from vdev_remove_complete(), in which case we
2320 * cannot do these assertions because we hold spa config locks and
2321 * thus we are not allowed to read from the DMU.
2322 *
2323 * We check if the metaslab group has been removed and if that's
2324 * the case we return immediately as that would mean that we are
2325 * here from the aforementioned code path.
2326 */
2327 if (msp->ms_group == NULL)
2328 return;
2329
2330 /*
2331 * Devices being removed always return a weight of 0 and leave
2332 * fragmentation and ms_max_size as is - there is nothing for
2333 * us to verify here.
2334 */
2335 vdev_t *vd = msp->ms_group->mg_vd;
2336 if (vd->vdev_removing)
2337 return;
2338
2339 /*
2340 * If the metaslab is dirty it probably means that we've done
2341 * some allocations or frees that have changed our histograms
2342 * and thus the weight.
2343 */
2344 for (int t = 0; t < TXG_SIZE; t++) {
2345 if (txg_list_member(&vd->vdev_ms_list, msp, t))
2346 return;
2347 }
2348
2349 /*
2350 * This verification checks that our in-memory state is consistent
2351 * with what's on disk. If the pool is read-only then there aren't
2352 * any changes and we just have the initially-loaded state.
2353 */
2354 if (!spa_writeable(msp->ms_group->mg_vd->vdev_spa))
2355 return;
2356
2357 /* some extra verification for in-core tree if you can */
2358 if (msp->ms_loaded) {
2359 zfs_range_tree_stat_verify(msp->ms_allocatable);
2360 VERIFY(space_map_histogram_verify(msp->ms_sm,
2361 msp->ms_allocatable));
2362 }
2363
2364 uint64_t weight = msp->ms_weight;
2365 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
2366 boolean_t space_based = WEIGHT_IS_SPACEBASED(msp->ms_weight);
2367 uint64_t frag = msp->ms_fragmentation;
2368 uint64_t max_segsize = msp->ms_max_size;
2369
2370 msp->ms_weight = 0;
2371 msp->ms_fragmentation = 0;
2372
2373 /*
2374 * This function is used for verification purposes and thus should
2375 * not introduce any side-effects/mutations on the system's state.
2376 *
2377 * Regardless of whether metaslab_weight() thinks this metaslab
2378 * should be active or not, we want to ensure that the actual weight
2379 * (and therefore the value of ms_weight) would be the same if it
2380 * was to be recalculated at this point.
2381 *
2382 * In addition we set the nodirty flag so metaslab_weight() does
2383 * not dirty the metaslab for future TXGs (e.g. when trying to
2384 * force condensing to upgrade the metaslab spacemaps).
2385 */
2386 msp->ms_weight = metaslab_weight(msp, B_TRUE) | was_active;
2387
2388 VERIFY3U(max_segsize, ==, msp->ms_max_size);
2389
2390 /*
2391 * If the weight type changed then there is no point in doing
2392 * verification. Revert fields to their original values.
2393 */
2394 if ((space_based && !WEIGHT_IS_SPACEBASED(msp->ms_weight)) ||
2395 (!space_based && WEIGHT_IS_SPACEBASED(msp->ms_weight))) {
2396 msp->ms_fragmentation = frag;
2397 msp->ms_weight = weight;
2398 return;
2399 }
2400
2401 VERIFY3U(msp->ms_fragmentation, ==, frag);
2402 VERIFY3U(msp->ms_weight, ==, weight);
2403 }
2404
2405 /*
2406 * If we're over the zfs_metaslab_mem_limit, select the loaded metaslab from
2407 * this class that was used longest ago, and attempt to unload it. We don't
2408 * want to spend too much time in this loop to prevent performance
2409 * degradation, and we expect that most of the time this operation will
2410 * succeed. Between that and the normal unloading processing during txg sync,
2411 * we expect this to keep the metaslab memory usage under control.
2412 */
2413 static void
metaslab_potentially_evict(metaslab_class_t * mc)2414 metaslab_potentially_evict(metaslab_class_t *mc)
2415 {
2416 #ifdef _KERNEL
2417 uint64_t allmem = arc_all_memory();
2418 uint64_t inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2419 uint64_t size = spl_kmem_cache_entry_size(zfs_btree_leaf_cache);
2420 uint_t tries = 0;
2421 for (; allmem * zfs_metaslab_mem_limit / 100 < inuse * size &&
2422 tries < multilist_get_num_sublists(&mc->mc_metaslab_txg_list) * 2;
2423 tries++) {
2424 unsigned int idx = multilist_get_random_index(
2425 &mc->mc_metaslab_txg_list);
2426 multilist_sublist_t *mls =
2427 multilist_sublist_lock_idx(&mc->mc_metaslab_txg_list, idx);
2428 metaslab_t *msp = multilist_sublist_head(mls);
2429 multilist_sublist_unlock(mls);
2430 while (msp != NULL && allmem * zfs_metaslab_mem_limit / 100 <
2431 inuse * size) {
2432 VERIFY3P(mls, ==, multilist_sublist_lock_idx(
2433 &mc->mc_metaslab_txg_list, idx));
2434 ASSERT3U(idx, ==,
2435 metaslab_idx_func(&mc->mc_metaslab_txg_list, msp));
2436
2437 if (!multilist_link_active(&msp->ms_class_txg_node)) {
2438 multilist_sublist_unlock(mls);
2439 break;
2440 }
2441 metaslab_t *next_msp = multilist_sublist_next(mls, msp);
2442 multilist_sublist_unlock(mls);
2443 /*
2444 * If the metaslab is currently loading there are two
2445 * cases. If it's the metaslab we're evicting, we
2446 * can't continue on or we'll panic when we attempt to
2447 * recursively lock the mutex. If it's another
2448 * metaslab that's loading, it can be safely skipped,
2449 * since we know it's very new and therefore not a
2450 * good eviction candidate. We check later once the
2451 * lock is held that the metaslab is fully loaded
2452 * before actually unloading it.
2453 */
2454 if (msp->ms_loading) {
2455 msp = next_msp;
2456 inuse =
2457 spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2458 continue;
2459 }
2460 /*
2461 * We can't unload metaslabs with no spacemap because
2462 * they're not ready to be unloaded yet. We can't
2463 * unload metaslabs with outstanding allocations
2464 * because doing so could cause the metaslab's weight
2465 * to decrease while it's unloaded, which violates an
2466 * invariant that we use to prevent unnecessary
2467 * loading. We also don't unload metaslabs that are
2468 * currently active because they are high-weight
2469 * metaslabs that are likely to be used in the near
2470 * future.
2471 */
2472 mutex_enter(&msp->ms_lock);
2473 if (msp->ms_allocator == -1 && msp->ms_sm != NULL &&
2474 msp->ms_allocating_total == 0) {
2475 metaslab_unload(msp);
2476 }
2477 mutex_exit(&msp->ms_lock);
2478 msp = next_msp;
2479 inuse = spl_kmem_cache_inuse(zfs_btree_leaf_cache);
2480 }
2481 }
2482 #else
2483 (void) mc, (void) zfs_metaslab_mem_limit;
2484 #endif
2485 }
2486
2487 static int
metaslab_load_impl(metaslab_t * msp)2488 metaslab_load_impl(metaslab_t *msp)
2489 {
2490 int error = 0;
2491
2492 ASSERT(MUTEX_HELD(&msp->ms_lock));
2493 ASSERT(msp->ms_loading);
2494 ASSERT(!msp->ms_condensing);
2495
2496 /*
2497 * We temporarily drop the lock to unblock other operations while we
2498 * are reading the space map. Therefore, metaslab_sync() and
2499 * metaslab_sync_done() can run at the same time as we do.
2500 *
2501 * If we are using the log space maps, metaslab_sync() can't write to
2502 * the metaslab's space map while we are loading as we only write to
2503 * it when we are flushing the metaslab, and that can't happen while
2504 * we are loading it.
2505 *
2506 * If we are not using log space maps though, metaslab_sync() can
2507 * append to the space map while we are loading. Therefore we load
2508 * only entries that existed when we started the load. Additionally,
2509 * metaslab_sync_done() has to wait for the load to complete because
2510 * there are potential races like metaslab_load() loading parts of the
2511 * space map that are currently being appended by metaslab_sync(). If
2512 * we didn't, the ms_allocatable would have entries that
2513 * metaslab_sync_done() would try to re-add later.
2514 *
2515 * That's why before dropping the lock we remember the synced length
2516 * of the metaslab and read up to that point of the space map,
2517 * ignoring entries appended by metaslab_sync() that happen after we
2518 * drop the lock.
2519 */
2520 uint64_t length = msp->ms_synced_length;
2521 mutex_exit(&msp->ms_lock);
2522
2523 hrtime_t load_start = gethrtime();
2524 metaslab_rt_arg_t *mrap;
2525 if (msp->ms_allocatable->rt_arg == NULL) {
2526 mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
2527 } else {
2528 mrap = msp->ms_allocatable->rt_arg;
2529 msp->ms_allocatable->rt_ops = NULL;
2530 msp->ms_allocatable->rt_arg = NULL;
2531 }
2532 mrap->mra_bt = &msp->ms_allocatable_by_size;
2533 mrap->mra_floor_shift = metaslab_by_size_min_shift;
2534
2535 if (msp->ms_sm != NULL) {
2536 error = space_map_load_length(msp->ms_sm, msp->ms_allocatable,
2537 SM_FREE, length);
2538
2539 /* Now, populate the size-sorted tree. */
2540 metaslab_rt_create(msp->ms_allocatable, mrap);
2541 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2542 msp->ms_allocatable->rt_arg = mrap;
2543
2544 struct mssa_arg arg = {0};
2545 arg.rt = msp->ms_allocatable;
2546 arg.mra = mrap;
2547 zfs_range_tree_walk(msp->ms_allocatable,
2548 metaslab_size_sorted_add, &arg);
2549 } else {
2550 /*
2551 * Add the size-sorted tree first, since we don't need to load
2552 * the metaslab from the spacemap.
2553 */
2554 metaslab_rt_create(msp->ms_allocatable, mrap);
2555 msp->ms_allocatable->rt_ops = &metaslab_rt_ops;
2556 msp->ms_allocatable->rt_arg = mrap;
2557 /*
2558 * The space map has not been allocated yet, so treat
2559 * all the space in the metaslab as free and add it to the
2560 * ms_allocatable tree.
2561 */
2562 zfs_range_tree_add(msp->ms_allocatable,
2563 msp->ms_start, msp->ms_size);
2564
2565 if (msp->ms_new) {
2566 /*
2567 * If the ms_sm doesn't exist, this means that this
2568 * metaslab hasn't gone through metaslab_sync() and
2569 * thus has never been dirtied. So we shouldn't
2570 * expect any unflushed allocs or frees from previous
2571 * TXGs.
2572 */
2573 ASSERT(zfs_range_tree_is_empty(
2574 msp->ms_unflushed_allocs));
2575 ASSERT(zfs_range_tree_is_empty(
2576 msp->ms_unflushed_frees));
2577 }
2578 }
2579
2580 /*
2581 * We need to grab the ms_sync_lock to prevent metaslab_sync() from
2582 * changing the ms_sm (or log_sm) and the metaslab's range trees
2583 * while we are about to use them and populate the ms_allocatable.
2584 * The ms_lock is insufficient for this because metaslab_sync() doesn't
2585 * hold the ms_lock while writing the ms_checkpointing tree to disk.
2586 */
2587 mutex_enter(&msp->ms_sync_lock);
2588 mutex_enter(&msp->ms_lock);
2589
2590 ASSERT(!msp->ms_condensing);
2591 ASSERT(!msp->ms_flushing);
2592
2593 if (error != 0) {
2594 mutex_exit(&msp->ms_sync_lock);
2595 return (error);
2596 }
2597
2598 ASSERT3P(msp->ms_group, !=, NULL);
2599 msp->ms_loaded = B_TRUE;
2600
2601 /*
2602 * Apply all the unflushed changes to ms_allocatable right
2603 * away so any manipulations we do below have a clear view
2604 * of what is allocated and what is free.
2605 */
2606 zfs_range_tree_walk(msp->ms_unflushed_allocs,
2607 zfs_range_tree_remove, msp->ms_allocatable);
2608 zfs_range_tree_walk(msp->ms_unflushed_frees,
2609 zfs_range_tree_add, msp->ms_allocatable);
2610
2611 ASSERT3P(msp->ms_group, !=, NULL);
2612 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2613 if (spa_syncing_log_sm(spa) != NULL) {
2614 ASSERT(spa_feature_is_enabled(spa,
2615 SPA_FEATURE_LOG_SPACEMAP));
2616
2617 /*
2618 * If we use a log space map we add all the segments
2619 * that are in ms_unflushed_frees so they are available
2620 * for allocation.
2621 *
2622 * ms_allocatable needs to contain all free segments
2623 * that are ready for allocations (thus not segments
2624 * from ms_freeing, ms_freed, and the ms_defer trees).
2625 * But if we grab the lock in this code path at a sync
2626 * pass later that 1, then it also contains the
2627 * segments of ms_freed (they were added to it earlier
2628 * in this path through ms_unflushed_frees). So we
2629 * need to remove all the segments that exist in
2630 * ms_freed from ms_allocatable as they will be added
2631 * later in metaslab_sync_done().
2632 *
2633 * When there's no log space map, the ms_allocatable
2634 * correctly doesn't contain any segments that exist
2635 * in ms_freed [see ms_synced_length].
2636 */
2637 zfs_range_tree_walk(msp->ms_freed,
2638 zfs_range_tree_remove, msp->ms_allocatable);
2639 }
2640
2641 /*
2642 * If we are not using the log space map, ms_allocatable
2643 * contains the segments that exist in the ms_defer trees
2644 * [see ms_synced_length]. Thus we need to remove them
2645 * from ms_allocatable as they will be added again in
2646 * metaslab_sync_done().
2647 *
2648 * If we are using the log space map, ms_allocatable still
2649 * contains the segments that exist in the ms_defer trees.
2650 * Not because it read them through the ms_sm though. But
2651 * because these segments are part of ms_unflushed_frees
2652 * whose segments we add to ms_allocatable earlier in this
2653 * code path.
2654 */
2655 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2656 zfs_range_tree_walk(msp->ms_defer[t],
2657 zfs_range_tree_remove, msp->ms_allocatable);
2658 }
2659
2660 /*
2661 * Call metaslab_recalculate_weight_and_sort() now that the
2662 * metaslab is loaded so we get the metaslab's real weight.
2663 *
2664 * Unless this metaslab was created with older software and
2665 * has not yet been converted to use segment-based weight, we
2666 * expect the new weight to be better or equal to the weight
2667 * that the metaslab had while it was not loaded. This is
2668 * because the old weight does not take into account the
2669 * consolidation of adjacent segments between TXGs. [see
2670 * comment for ms_synchist and ms_deferhist[] for more info]
2671 */
2672 uint64_t weight = msp->ms_weight;
2673 uint64_t max_size = msp->ms_max_size;
2674 metaslab_recalculate_weight_and_sort(msp);
2675 if (!WEIGHT_IS_SPACEBASED(weight))
2676 ASSERT3U(weight, <=, msp->ms_weight);
2677 msp->ms_max_size = metaslab_largest_allocatable(msp);
2678 ASSERT3U(max_size, <=, msp->ms_max_size);
2679 hrtime_t load_end = gethrtime();
2680 msp->ms_load_time = load_end;
2681 zfs_dbgmsg("metaslab_load: txg %llu, spa %s, class %s, vdev_id %llu, "
2682 "ms_id %llu, smp_length %llu, "
2683 "unflushed_allocs %llu, unflushed_frees %llu, "
2684 "freed %llu, defer %llu + %llu, unloaded time %llu ms, "
2685 "loading_time %lld ms, ms_max_size %llu, "
2686 "max size error %lld, "
2687 "old_weight %llx, new_weight %llx",
2688 (u_longlong_t)spa_syncing_txg(spa), spa_name(spa),
2689 msp->ms_group->mg_class->mc_name,
2690 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
2691 (u_longlong_t)msp->ms_id,
2692 (u_longlong_t)space_map_length(msp->ms_sm),
2693 (u_longlong_t)zfs_range_tree_space(msp->ms_unflushed_allocs),
2694 (u_longlong_t)zfs_range_tree_space(msp->ms_unflushed_frees),
2695 (u_longlong_t)zfs_range_tree_space(msp->ms_freed),
2696 (u_longlong_t)zfs_range_tree_space(msp->ms_defer[0]),
2697 (u_longlong_t)zfs_range_tree_space(msp->ms_defer[1]),
2698 (longlong_t)((load_start - msp->ms_unload_time) / 1000000),
2699 (longlong_t)((load_end - load_start) / 1000000),
2700 (u_longlong_t)msp->ms_max_size,
2701 (u_longlong_t)msp->ms_max_size - max_size,
2702 (u_longlong_t)weight, (u_longlong_t)msp->ms_weight);
2703
2704 metaslab_verify_space(msp, spa_syncing_txg(spa));
2705 mutex_exit(&msp->ms_sync_lock);
2706 return (0);
2707 }
2708
2709 int
metaslab_load(metaslab_t * msp)2710 metaslab_load(metaslab_t *msp)
2711 {
2712 ASSERT(MUTEX_HELD(&msp->ms_lock));
2713
2714 /*
2715 * There may be another thread loading the same metaslab, if that's
2716 * the case just wait until the other thread is done and return.
2717 */
2718 metaslab_load_wait(msp);
2719 if (msp->ms_loaded)
2720 return (0);
2721 VERIFY(!msp->ms_loading);
2722 ASSERT(!msp->ms_condensing);
2723
2724 /*
2725 * We set the loading flag BEFORE potentially dropping the lock to
2726 * wait for an ongoing flush (see ms_flushing below). This way other
2727 * threads know that there is already a thread that is loading this
2728 * metaslab.
2729 */
2730 msp->ms_loading = B_TRUE;
2731
2732 /*
2733 * Wait for any in-progress flushing to finish as we drop the ms_lock
2734 * both here (during space_map_load()) and in metaslab_flush() (when
2735 * we flush our changes to the ms_sm).
2736 */
2737 if (msp->ms_flushing)
2738 metaslab_flush_wait(msp);
2739
2740 /*
2741 * In the possibility that we were waiting for the metaslab to be
2742 * flushed (where we temporarily dropped the ms_lock), ensure that
2743 * no one else loaded the metaslab somehow.
2744 */
2745 ASSERT(!msp->ms_loaded);
2746
2747 /*
2748 * If we're loading a metaslab in the normal class, consider evicting
2749 * another one to keep our memory usage under the limit defined by the
2750 * zfs_metaslab_mem_limit tunable.
2751 */
2752 if (spa_normal_class(msp->ms_group->mg_class->mc_spa) ==
2753 msp->ms_group->mg_class) {
2754 metaslab_potentially_evict(msp->ms_group->mg_class);
2755 }
2756
2757 int error = metaslab_load_impl(msp);
2758
2759 ASSERT(MUTEX_HELD(&msp->ms_lock));
2760 msp->ms_loading = B_FALSE;
2761 cv_broadcast(&msp->ms_load_cv);
2762
2763 return (error);
2764 }
2765
2766 void
metaslab_unload(metaslab_t * msp)2767 metaslab_unload(metaslab_t *msp)
2768 {
2769 ASSERT(MUTEX_HELD(&msp->ms_lock));
2770
2771 /*
2772 * This can happen if a metaslab is selected for eviction (in
2773 * metaslab_potentially_evict) and then unloaded during spa_sync (via
2774 * metaslab_class_evict_old).
2775 */
2776 if (!msp->ms_loaded)
2777 return;
2778
2779 zfs_range_tree_vacate(msp->ms_allocatable, NULL, NULL);
2780 msp->ms_loaded = B_FALSE;
2781 msp->ms_unload_time = gethrtime();
2782
2783 msp->ms_activation_weight = 0;
2784 msp->ms_weight &= ~METASLAB_ACTIVE_MASK;
2785
2786 if (msp->ms_group != NULL) {
2787 metaslab_class_t *mc = msp->ms_group->mg_class;
2788 multilist_sublist_t *mls =
2789 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
2790 if (multilist_link_active(&msp->ms_class_txg_node))
2791 multilist_sublist_remove(mls, msp);
2792 multilist_sublist_unlock(mls);
2793
2794 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
2795 zfs_dbgmsg("metaslab_unload: txg %llu, spa %s, class %s, "
2796 "vdev_id %llu, ms_id %llu, weight %llx, "
2797 "selected txg %llu (%llu s ago), alloc_txg %llu, "
2798 "loaded %llu ms ago, max_size %llu",
2799 (u_longlong_t)spa_syncing_txg(spa), spa_name(spa),
2800 msp->ms_group->mg_class->mc_name,
2801 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
2802 (u_longlong_t)msp->ms_id,
2803 (u_longlong_t)msp->ms_weight,
2804 (u_longlong_t)msp->ms_selected_txg,
2805 (u_longlong_t)(NSEC2SEC(msp->ms_unload_time) -
2806 msp->ms_selected_time),
2807 (u_longlong_t)msp->ms_alloc_txg,
2808 (u_longlong_t)(msp->ms_unload_time -
2809 msp->ms_load_time) / 1000 / 1000,
2810 (u_longlong_t)msp->ms_max_size);
2811 }
2812
2813 /*
2814 * We explicitly recalculate the metaslab's weight based on its space
2815 * map (as it is now not loaded). We want unload metaslabs to always
2816 * have their weights calculated from the space map histograms, while
2817 * loaded ones have it calculated from their in-core range tree
2818 * [see metaslab_load()]. This way, the weight reflects the information
2819 * available in-core, whether it is loaded or not.
2820 *
2821 * If ms_group == NULL means that we came here from metaslab_fini(),
2822 * at which point it doesn't make sense for us to do the recalculation
2823 * and the sorting.
2824 */
2825 if (msp->ms_group != NULL)
2826 metaslab_recalculate_weight_and_sort(msp);
2827 }
2828
2829 /*
2830 * We want to optimize the memory use of the per-metaslab range
2831 * trees. To do this, we store the segments in the range trees in
2832 * units of sectors, zero-indexing from the start of the metaslab. If
2833 * the vdev_ms_shift - the vdev_ashift is less than 32, we can store
2834 * the ranges using two uint32_ts, rather than two uint64_ts.
2835 */
2836 zfs_range_seg_type_t
metaslab_calculate_range_tree_type(vdev_t * vdev,metaslab_t * msp,uint64_t * start,uint64_t * shift)2837 metaslab_calculate_range_tree_type(vdev_t *vdev, metaslab_t *msp,
2838 uint64_t *start, uint64_t *shift)
2839 {
2840 if (vdev->vdev_ms_shift - vdev->vdev_ashift < 32 &&
2841 !zfs_metaslab_force_large_segs) {
2842 *shift = vdev->vdev_ashift;
2843 *start = msp->ms_start;
2844 return (ZFS_RANGE_SEG32);
2845 } else {
2846 *shift = 0;
2847 *start = 0;
2848 return (ZFS_RANGE_SEG64);
2849 }
2850 }
2851
2852 void
metaslab_set_selected_txg(metaslab_t * msp,uint64_t txg)2853 metaslab_set_selected_txg(metaslab_t *msp, uint64_t txg)
2854 {
2855 ASSERT(MUTEX_HELD(&msp->ms_lock));
2856 metaslab_class_t *mc = msp->ms_group->mg_class;
2857 multilist_sublist_t *mls =
2858 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
2859 if (multilist_link_active(&msp->ms_class_txg_node))
2860 multilist_sublist_remove(mls, msp);
2861 msp->ms_selected_txg = txg;
2862 msp->ms_selected_time = gethrestime_sec();
2863 multilist_sublist_insert_tail(mls, msp);
2864 multilist_sublist_unlock(mls);
2865 }
2866
2867 void
metaslab_space_update(metaslab_group_t * mg,int64_t alloc_delta,int64_t defer_delta,int64_t space_delta)2868 metaslab_space_update(metaslab_group_t *mg, int64_t alloc_delta,
2869 int64_t defer_delta, int64_t space_delta)
2870 {
2871 vdev_t *vd = mg->mg_vd;
2872 int64_t dalloc_delta = vdev_deflated_space(vd, alloc_delta);
2873 int64_t ddefer_delta = vdev_deflated_space(vd, defer_delta);
2874 int64_t dspace_delta = vdev_deflated_space(vd, space_delta);
2875
2876 vdev_space_update(vd, alloc_delta, defer_delta, space_delta);
2877
2878 ASSERT3P(vd->vdev_spa->spa_root_vdev, ==, vd->vdev_parent);
2879 ASSERT(vd->vdev_ms_count != 0);
2880
2881 metaslab_class_space_update(mg->mg_class, alloc_delta, dalloc_delta,
2882 defer_delta, ddefer_delta, space_delta, dspace_delta);
2883 }
2884
2885 int
metaslab_init(metaslab_group_t * mg,uint64_t id,uint64_t object,uint64_t txg,metaslab_t ** msp)2886 metaslab_init(metaslab_group_t *mg, uint64_t id, uint64_t object,
2887 uint64_t txg, metaslab_t **msp)
2888 {
2889 vdev_t *vd = mg->mg_vd;
2890 spa_t *spa = vd->vdev_spa;
2891 objset_t *mos = spa->spa_meta_objset;
2892 metaslab_t *ms;
2893 int error;
2894
2895 ms = kmem_zalloc(sizeof (metaslab_t), KM_SLEEP);
2896 mutex_init(&ms->ms_lock, NULL, MUTEX_DEFAULT, NULL);
2897 mutex_init(&ms->ms_sync_lock, NULL, MUTEX_DEFAULT, NULL);
2898 cv_init(&ms->ms_load_cv, NULL, CV_DEFAULT, NULL);
2899 cv_init(&ms->ms_flush_cv, NULL, CV_DEFAULT, NULL);
2900 multilist_link_init(&ms->ms_class_txg_node);
2901
2902 ms->ms_id = id;
2903 ms->ms_start = id << vd->vdev_ms_shift;
2904 ms->ms_size = 1ULL << vd->vdev_ms_shift;
2905 ms->ms_allocator = -1;
2906 ms->ms_new = B_TRUE;
2907
2908 vdev_ops_t *ops = vd->vdev_ops;
2909 if (ops->vdev_op_metaslab_init != NULL)
2910 ops->vdev_op_metaslab_init(vd, &ms->ms_start, &ms->ms_size);
2911
2912 /*
2913 * We only open space map objects that already exist. All others
2914 * will be opened when we finally allocate an object for it. For
2915 * readonly pools there is no need to open the space map object.
2916 *
2917 * Note:
2918 * When called from vdev_expand(), we can't call into the DMU as
2919 * we are holding the spa_config_lock as a writer and we would
2920 * deadlock [see relevant comment in vdev_metaslab_init()]. in
2921 * that case, the object parameter is zero though, so we won't
2922 * call into the DMU.
2923 */
2924 if (object != 0 && !(spa->spa_mode == SPA_MODE_READ &&
2925 !spa->spa_read_spacemaps)) {
2926 error = space_map_open(&ms->ms_sm, mos, object, ms->ms_start,
2927 ms->ms_size, vd->vdev_ashift);
2928
2929 if (error != 0) {
2930 kmem_free(ms, sizeof (metaslab_t));
2931 return (error);
2932 }
2933
2934 ASSERT(ms->ms_sm != NULL);
2935 ms->ms_allocated_space = space_map_allocated(ms->ms_sm);
2936 }
2937
2938 uint64_t shift, start;
2939 zfs_range_seg_type_t type =
2940 metaslab_calculate_range_tree_type(vd, ms, &start, &shift);
2941
2942 ms->ms_allocatable = zfs_range_tree_create_flags(
2943 NULL, type, NULL, start, shift,
2944 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_allocatable"));
2945 for (int t = 0; t < TXG_SIZE; t++) {
2946 ms->ms_allocating[t] = zfs_range_tree_create_flags(
2947 NULL, type, NULL, start, shift,
2948 ZFS_RT_F_DYN_NAME,
2949 metaslab_rt_name(mg, ms, "ms_allocating"));
2950 }
2951 ms->ms_freeing = zfs_range_tree_create_flags(
2952 NULL, type, NULL, start, shift,
2953 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_freeing"));
2954 ms->ms_freed = zfs_range_tree_create_flags(
2955 NULL, type, NULL, start, shift,
2956 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_freed"));
2957 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
2958 ms->ms_defer[t] = zfs_range_tree_create_flags(
2959 NULL, type, NULL, start, shift,
2960 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_defer"));
2961 }
2962 ms->ms_checkpointing = zfs_range_tree_create_flags(
2963 NULL, type, NULL, start, shift,
2964 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_checkpointing"));
2965 ms->ms_unflushed_allocs = zfs_range_tree_create_flags(
2966 NULL, type, NULL, start, shift,
2967 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_unflushed_allocs"));
2968
2969 metaslab_rt_arg_t *mrap = kmem_zalloc(sizeof (*mrap), KM_SLEEP);
2970 mrap->mra_bt = &ms->ms_unflushed_frees_by_size;
2971 mrap->mra_floor_shift = metaslab_by_size_min_shift;
2972 ms->ms_unflushed_frees = zfs_range_tree_create_flags(
2973 &metaslab_rt_ops, type, mrap, start, shift,
2974 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_unflushed_frees"));
2975
2976 ms->ms_trim = zfs_range_tree_create_flags(
2977 NULL, type, NULL, start, shift,
2978 ZFS_RT_F_DYN_NAME, metaslab_rt_name(mg, ms, "ms_trim"));
2979
2980 metaslab_group_add(mg, ms);
2981 metaslab_set_fragmentation(ms, B_FALSE);
2982
2983 /*
2984 * If we're opening an existing pool (txg == 0) or creating
2985 * a new one (txg == TXG_INITIAL), all space is available now.
2986 * If we're adding space to an existing pool, the new space
2987 * does not become available until after this txg has synced.
2988 * The metaslab's weight will also be initialized when we sync
2989 * out this txg. This ensures that we don't attempt to allocate
2990 * from it before we have initialized it completely.
2991 */
2992 if (txg <= TXG_INITIAL) {
2993 metaslab_sync_done(ms, 0);
2994 metaslab_space_update(mg, metaslab_allocated_space(ms), 0, 0);
2995 }
2996
2997 if (txg != 0) {
2998 vdev_dirty(vd, 0, NULL, txg);
2999 vdev_dirty(vd, VDD_METASLAB, ms, txg);
3000 }
3001
3002 *msp = ms;
3003
3004 return (0);
3005 }
3006
3007 static void
metaslab_fini_flush_data(metaslab_t * msp)3008 metaslab_fini_flush_data(metaslab_t *msp)
3009 {
3010 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3011
3012 if (metaslab_unflushed_txg(msp) == 0) {
3013 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL),
3014 ==, NULL);
3015 return;
3016 }
3017 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
3018
3019 mutex_enter(&spa->spa_flushed_ms_lock);
3020 avl_remove(&spa->spa_metaslabs_by_flushed, msp);
3021 mutex_exit(&spa->spa_flushed_ms_lock);
3022
3023 spa_log_sm_decrement_mscount(spa, metaslab_unflushed_txg(msp));
3024 spa_log_summary_decrement_mscount(spa, metaslab_unflushed_txg(msp),
3025 metaslab_unflushed_dirty(msp));
3026 }
3027
3028 uint64_t
metaslab_unflushed_changes_memused(metaslab_t * ms)3029 metaslab_unflushed_changes_memused(metaslab_t *ms)
3030 {
3031 return ((zfs_range_tree_numsegs(ms->ms_unflushed_allocs) +
3032 zfs_range_tree_numsegs(ms->ms_unflushed_frees)) *
3033 ms->ms_unflushed_allocs->rt_root.bt_elem_size);
3034 }
3035
3036 void
metaslab_fini(metaslab_t * msp)3037 metaslab_fini(metaslab_t *msp)
3038 {
3039 metaslab_group_t *mg = msp->ms_group;
3040 vdev_t *vd = mg->mg_vd;
3041 spa_t *spa = vd->vdev_spa;
3042
3043 metaslab_fini_flush_data(msp);
3044
3045 metaslab_group_remove(mg, msp);
3046
3047 mutex_enter(&msp->ms_lock);
3048 VERIFY0P(msp->ms_group);
3049
3050 /*
3051 * If this metaslab hasn't been through metaslab_sync_done() yet its
3052 * space hasn't been accounted for in its vdev and doesn't need to be
3053 * subtracted.
3054 */
3055 if (!msp->ms_new) {
3056 metaslab_space_update(mg, -metaslab_allocated_space(msp), 0,
3057 -msp->ms_size);
3058 }
3059 space_map_close(msp->ms_sm);
3060 msp->ms_sm = NULL;
3061
3062 metaslab_unload(msp);
3063
3064 zfs_range_tree_destroy(msp->ms_allocatable);
3065 zfs_range_tree_destroy(msp->ms_freeing);
3066 zfs_range_tree_destroy(msp->ms_freed);
3067
3068 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3069 metaslab_unflushed_changes_memused(msp));
3070 spa->spa_unflushed_stats.sus_memused -=
3071 metaslab_unflushed_changes_memused(msp);
3072 zfs_range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3073 zfs_range_tree_destroy(msp->ms_unflushed_allocs);
3074 zfs_range_tree_destroy(msp->ms_checkpointing);
3075 zfs_range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3076 zfs_range_tree_destroy(msp->ms_unflushed_frees);
3077
3078 for (int t = 0; t < TXG_SIZE; t++) {
3079 zfs_range_tree_destroy(msp->ms_allocating[t]);
3080 }
3081 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3082 zfs_range_tree_destroy(msp->ms_defer[t]);
3083 }
3084 ASSERT0(msp->ms_deferspace);
3085
3086 for (int t = 0; t < TXG_SIZE; t++)
3087 ASSERT(!txg_list_member(&vd->vdev_ms_list, msp, t));
3088
3089 zfs_range_tree_vacate(msp->ms_trim, NULL, NULL);
3090 zfs_range_tree_destroy(msp->ms_trim);
3091
3092 mutex_exit(&msp->ms_lock);
3093 cv_destroy(&msp->ms_load_cv);
3094 cv_destroy(&msp->ms_flush_cv);
3095 mutex_destroy(&msp->ms_lock);
3096 mutex_destroy(&msp->ms_sync_lock);
3097 ASSERT3U(msp->ms_allocator, ==, -1);
3098
3099 kmem_free(msp, sizeof (metaslab_t));
3100 }
3101
3102 /*
3103 * This table defines a segment size based fragmentation metric that will
3104 * allow each metaslab to derive its own fragmentation value. This is done
3105 * by calculating the space in each bucket of the spacemap histogram and
3106 * multiplying that by the fragmentation metric in this table. Doing
3107 * this for all buckets and dividing it by the total amount of free
3108 * space in this metaslab (i.e. the total free space in all buckets) gives
3109 * us the fragmentation metric. This means that a high fragmentation metric
3110 * equates to most of the free space being comprised of small segments.
3111 * Conversely, if the metric is low, then most of the free space is in
3112 * large segments.
3113 *
3114 * This table defines 0% fragmented space using 512M segments. Using this value,
3115 * we derive the rest of the table. This table originally went up to 16MB, but
3116 * with larger recordsizes, larger ashifts, and use of raidz3, it is possible
3117 * to have significantly larger allocations than were previously possible.
3118 * Since the fragmentation value is never stored on disk, it is possible to
3119 * change these calculations in the future.
3120 */
3121 static const int zfs_frag_table[] = {
3122 100, /* 512B */
3123 99, /* 1K */
3124 97, /* 2K */
3125 93, /* 4K */
3126 88, /* 8K */
3127 83, /* 16K */
3128 77, /* 32K */
3129 71, /* 64K */
3130 64, /* 128K */
3131 57, /* 256K */
3132 50, /* 512K */
3133 43, /* 1M */
3134 36, /* 2M */
3135 29, /* 4M */
3136 23, /* 8M */
3137 17, /* 16M */
3138 12, /* 32M */
3139 7, /* 64M */
3140 3, /* 128M */
3141 1, /* 256M */
3142 0, /* 512M */
3143 };
3144 #define FRAGMENTATION_TABLE_SIZE \
3145 (sizeof (zfs_frag_table)/(sizeof (zfs_frag_table[0])))
3146
3147 /*
3148 * Calculate the metaslab's fragmentation metric and set ms_fragmentation.
3149 * Setting this value to ZFS_FRAG_INVALID means that the metaslab has not
3150 * been upgraded and does not support this metric. Otherwise, the return
3151 * value should be in the range [0, 100].
3152 */
3153 static void
metaslab_set_fragmentation(metaslab_t * msp,boolean_t nodirty)3154 metaslab_set_fragmentation(metaslab_t *msp, boolean_t nodirty)
3155 {
3156 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3157 uint64_t fragmentation = 0;
3158 uint64_t total = 0;
3159 boolean_t feature_enabled = spa_feature_is_enabled(spa,
3160 SPA_FEATURE_SPACEMAP_HISTOGRAM);
3161
3162 if (!feature_enabled) {
3163 msp->ms_fragmentation = ZFS_FRAG_INVALID;
3164 return;
3165 }
3166
3167 /*
3168 * A null space map means that the entire metaslab is free
3169 * and thus is not fragmented.
3170 */
3171 if (msp->ms_sm == NULL) {
3172 msp->ms_fragmentation = 0;
3173 return;
3174 }
3175
3176 /*
3177 * If this metaslab's space map has not been upgraded, flag it
3178 * so that we upgrade next time we encounter it.
3179 */
3180 if (msp->ms_sm->sm_dbuf->db_size != sizeof (space_map_phys_t)) {
3181 uint64_t txg = spa_syncing_txg(spa);
3182 vdev_t *vd = msp->ms_group->mg_vd;
3183
3184 /*
3185 * If we've reached the final dirty txg, then we must
3186 * be shutting down the pool. We don't want to dirty
3187 * any data past this point so skip setting the condense
3188 * flag. We can retry this action the next time the pool
3189 * is imported. We also skip marking this metaslab for
3190 * condensing if the caller has explicitly set nodirty.
3191 */
3192 if (!nodirty &&
3193 spa_writeable(spa) && txg < spa_final_dirty_txg(spa)) {
3194 msp->ms_condense_wanted = B_TRUE;
3195 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
3196 zfs_dbgmsg("txg %llu, requesting force condense: "
3197 "ms_id %llu, vdev_id %llu", (u_longlong_t)txg,
3198 (u_longlong_t)msp->ms_id,
3199 (u_longlong_t)vd->vdev_id);
3200 }
3201 msp->ms_fragmentation = ZFS_FRAG_INVALID;
3202 return;
3203 }
3204
3205 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
3206 uint64_t space = 0;
3207 uint8_t shift = msp->ms_sm->sm_shift;
3208
3209 int idx = MIN(shift - SPA_MINBLOCKSHIFT + i,
3210 FRAGMENTATION_TABLE_SIZE - 1);
3211
3212 if (msp->ms_sm->sm_phys->smp_histogram[i] == 0)
3213 continue;
3214
3215 space = msp->ms_sm->sm_phys->smp_histogram[i] << (i + shift);
3216 total += space;
3217
3218 ASSERT3U(idx, <, FRAGMENTATION_TABLE_SIZE);
3219 fragmentation += space * zfs_frag_table[idx];
3220 }
3221
3222 if (total > 0)
3223 fragmentation /= total;
3224 ASSERT3U(fragmentation, <=, 100);
3225
3226 msp->ms_fragmentation = fragmentation;
3227 }
3228
3229 /*
3230 * Compute a weight -- a selection preference value -- for the given metaslab.
3231 * This is based on the amount of free space, the level of fragmentation,
3232 * the LBA range, and whether the metaslab is loaded.
3233 */
3234 static uint64_t
metaslab_space_weight(metaslab_t * msp)3235 metaslab_space_weight(metaslab_t *msp)
3236 {
3237 metaslab_group_t *mg = msp->ms_group;
3238 vdev_t *vd = mg->mg_vd;
3239 uint64_t weight, space;
3240
3241 ASSERT(MUTEX_HELD(&msp->ms_lock));
3242
3243 /*
3244 * The baseline weight is the metaslab's free space.
3245 */
3246 space = msp->ms_size - metaslab_allocated_space(msp);
3247
3248 if (metaslab_fragmentation_factor_enabled &&
3249 msp->ms_fragmentation != ZFS_FRAG_INVALID) {
3250 /*
3251 * Use the fragmentation information to inversely scale
3252 * down the baseline weight. We need to ensure that we
3253 * don't exclude this metaslab completely when it's 100%
3254 * fragmented. To avoid this we reduce the fragmented value
3255 * by 1.
3256 */
3257 space = (space * (100 - (msp->ms_fragmentation - 1))) / 100;
3258
3259 /*
3260 * If space < SPA_MINBLOCKSIZE, then we will not allocate from
3261 * this metaslab again. The fragmentation metric may have
3262 * decreased the space to something smaller than
3263 * SPA_MINBLOCKSIZE, so reset the space to SPA_MINBLOCKSIZE
3264 * so that we can consume any remaining space.
3265 */
3266 if (space > 0 && space < SPA_MINBLOCKSIZE)
3267 space = SPA_MINBLOCKSIZE;
3268 }
3269 weight = space;
3270
3271 /*
3272 * Modern disks have uniform bit density and constant angular velocity.
3273 * Therefore, the outer recording zones are faster (higher bandwidth)
3274 * than the inner zones by the ratio of outer to inner track diameter,
3275 * which is typically around 2:1. We account for this by assigning
3276 * higher weight to lower metaslabs (multiplier ranging from 2x to 1x).
3277 * In effect, this means that we'll select the metaslab with the most
3278 * free bandwidth rather than simply the one with the most free space.
3279 */
3280 if (!vd->vdev_nonrot && metaslab_lba_weighting_enabled) {
3281 weight = 2 * weight - (msp->ms_id * weight) / vd->vdev_ms_count;
3282 ASSERT(weight >= space && weight <= 2 * space);
3283 }
3284
3285 /*
3286 * If this metaslab is one we're actively using, adjust its
3287 * weight to make it preferable to any inactive metaslab so
3288 * we'll polish it off. If the fragmentation on this metaslab
3289 * has exceed our threshold, then don't mark it active.
3290 */
3291 if (msp->ms_loaded && msp->ms_fragmentation != ZFS_FRAG_INVALID &&
3292 msp->ms_fragmentation <= zfs_metaslab_fragmentation_threshold) {
3293 weight |= (msp->ms_weight & METASLAB_ACTIVE_MASK);
3294 }
3295
3296 WEIGHT_SET_SPACEBASED(weight);
3297 return (weight);
3298 }
3299
3300 /*
3301 * Return the weight of the specified metaslab, according to the segment-based
3302 * weighting algorithm. The metaslab must be loaded. This function can
3303 * be called within a sync pass since it relies only on the metaslab's
3304 * range tree which is always accurate when the metaslab is loaded.
3305 */
3306 static uint64_t
metaslab_weight_from_range_tree(metaslab_t * msp)3307 metaslab_weight_from_range_tree(metaslab_t *msp)
3308 {
3309 uint64_t weight = 0;
3310 uint32_t segments = 0;
3311
3312 ASSERT(msp->ms_loaded);
3313
3314 for (int i = ZFS_RANGE_TREE_HISTOGRAM_SIZE - 1; i >= SPA_MINBLOCKSHIFT;
3315 i--) {
3316 uint8_t shift = msp->ms_group->mg_vd->vdev_ashift;
3317 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
3318
3319 segments <<= 1;
3320 segments += msp->ms_allocatable->rt_histogram[i];
3321
3322 /*
3323 * The range tree provides more precision than the space map
3324 * and must be downgraded so that all values fit within the
3325 * space map's histogram. This allows us to compare loaded
3326 * vs. unloaded metaslabs to determine which metaslab is
3327 * considered "best".
3328 */
3329 if (i > max_idx)
3330 continue;
3331
3332 if (segments != 0) {
3333 WEIGHT_SET_COUNT(weight, segments);
3334 WEIGHT_SET_INDEX(weight, i);
3335 WEIGHT_SET_ACTIVE(weight, 0);
3336 break;
3337 }
3338 }
3339 return (weight);
3340 }
3341
3342 /*
3343 * Calculate the weight based on the on-disk histogram. Should be applied
3344 * only to unloaded metaslabs (i.e no incoming allocations) in-order to
3345 * give results consistent with the on-disk state
3346 */
3347 static uint64_t
metaslab_weight_from_spacemap(metaslab_t * msp)3348 metaslab_weight_from_spacemap(metaslab_t *msp)
3349 {
3350 space_map_t *sm = msp->ms_sm;
3351 ASSERT(!msp->ms_loaded);
3352 ASSERT(sm != NULL);
3353 ASSERT3U(space_map_object(sm), !=, 0);
3354 ASSERT3U(sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3355
3356 /*
3357 * Create a joint histogram from all the segments that have made
3358 * it to the metaslab's space map histogram, that are not yet
3359 * available for allocation because they are still in the freeing
3360 * pipeline (e.g. freeing, freed, and defer trees). Then subtract
3361 * these segments from the space map's histogram to get a more
3362 * accurate weight.
3363 */
3364 uint64_t deferspace_histogram[SPACE_MAP_HISTOGRAM_SIZE] = {0};
3365 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++)
3366 deferspace_histogram[i] += msp->ms_synchist[i];
3367 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3368 for (int i = 0; i < SPACE_MAP_HISTOGRAM_SIZE; i++) {
3369 deferspace_histogram[i] += msp->ms_deferhist[t][i];
3370 }
3371 }
3372
3373 uint64_t weight = 0;
3374 for (int i = SPACE_MAP_HISTOGRAM_SIZE - 1; i >= 0; i--) {
3375 ASSERT3U(sm->sm_phys->smp_histogram[i], >=,
3376 deferspace_histogram[i]);
3377 uint64_t count =
3378 sm->sm_phys->smp_histogram[i] - deferspace_histogram[i];
3379 if (count != 0) {
3380 WEIGHT_SET_COUNT(weight, count);
3381 WEIGHT_SET_INDEX(weight, i + sm->sm_shift);
3382 WEIGHT_SET_ACTIVE(weight, 0);
3383 break;
3384 }
3385 }
3386 return (weight);
3387 }
3388
3389 /*
3390 * Compute a segment-based weight for the specified metaslab. The weight
3391 * is determined by highest bucket in the histogram. The information
3392 * for the highest bucket is encoded into the weight value.
3393 */
3394 static uint64_t
metaslab_segment_weight(metaslab_t * msp)3395 metaslab_segment_weight(metaslab_t *msp)
3396 {
3397 metaslab_group_t *mg = msp->ms_group;
3398 uint64_t weight = 0;
3399 uint8_t shift = mg->mg_vd->vdev_ashift;
3400
3401 ASSERT(MUTEX_HELD(&msp->ms_lock));
3402
3403 /*
3404 * The metaslab is completely free.
3405 */
3406 if (metaslab_allocated_space(msp) == 0) {
3407 int idx = highbit64(msp->ms_size) - 1;
3408 int max_idx = SPACE_MAP_HISTOGRAM_SIZE + shift - 1;
3409
3410 if (idx < max_idx) {
3411 WEIGHT_SET_COUNT(weight, 1ULL);
3412 WEIGHT_SET_INDEX(weight, idx);
3413 } else {
3414 WEIGHT_SET_COUNT(weight, 1ULL << (idx - max_idx));
3415 WEIGHT_SET_INDEX(weight, max_idx);
3416 }
3417 WEIGHT_SET_ACTIVE(weight, 0);
3418 ASSERT(!WEIGHT_IS_SPACEBASED(weight));
3419 return (weight);
3420 }
3421
3422 ASSERT3U(msp->ms_sm->sm_dbuf->db_size, ==, sizeof (space_map_phys_t));
3423
3424 /*
3425 * If the metaslab is fully allocated then just make the weight 0.
3426 */
3427 if (metaslab_allocated_space(msp) == msp->ms_size)
3428 return (0);
3429 /*
3430 * If the metaslab is already loaded, then use the range tree to
3431 * determine the weight. Otherwise, we rely on the space map information
3432 * to generate the weight.
3433 */
3434 if (msp->ms_loaded) {
3435 weight = metaslab_weight_from_range_tree(msp);
3436 } else {
3437 weight = metaslab_weight_from_spacemap(msp);
3438 }
3439
3440 /*
3441 * If the metaslab was active the last time we calculated its weight
3442 * then keep it active. We want to consume the entire region that
3443 * is associated with this weight.
3444 */
3445 if (msp->ms_activation_weight != 0 && weight != 0)
3446 WEIGHT_SET_ACTIVE(weight, WEIGHT_GET_ACTIVE(msp->ms_weight));
3447 return (weight);
3448 }
3449
3450 /*
3451 * Determine if we should attempt to allocate from this metaslab. If the
3452 * metaslab is loaded, then we can determine if the desired allocation
3453 * can be satisfied by looking at the size of the maximum free segment
3454 * on that metaslab. Otherwise, we make our decision based on the metaslab's
3455 * weight. For segment-based weighting we can determine the maximum
3456 * allocation based on the index encoded in its value. For space-based
3457 * weights we rely on the entire weight (excluding the weight-type bit).
3458 */
3459 static boolean_t
metaslab_should_allocate(metaslab_t * msp,uint64_t asize,boolean_t try_hard)3460 metaslab_should_allocate(metaslab_t *msp, uint64_t asize, boolean_t try_hard)
3461 {
3462 /*
3463 * This case will usually but not always get caught by the checks below;
3464 * metaslabs can be loaded by various means, including the trim and
3465 * initialize code. Once that happens, without this check they are
3466 * allocatable even before they finish their first txg sync.
3467 */
3468 if (unlikely(msp->ms_new))
3469 return (B_FALSE);
3470
3471 /*
3472 * If the metaslab is loaded, ms_max_size is definitive and we can use
3473 * the fast check. If it's not, the ms_max_size is a lower bound (once
3474 * set), and we should use the fast check as long as we're not in
3475 * try_hard and it's been less than zfs_metaslab_max_size_cache_sec
3476 * seconds since the metaslab was unloaded.
3477 */
3478 if (msp->ms_loaded ||
3479 (msp->ms_max_size != 0 && !try_hard && gethrtime() <
3480 msp->ms_unload_time + SEC2NSEC(zfs_metaslab_max_size_cache_sec)))
3481 return (msp->ms_max_size >= asize);
3482
3483 boolean_t should_allocate;
3484 if (!WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
3485 /*
3486 * The metaslab segment weight indicates segments in the
3487 * range [2^i, 2^(i+1)), where i is the index in the weight.
3488 * Since the asize might be in the middle of the range, we
3489 * should attempt the allocation if asize < 2^(i+1).
3490 */
3491 should_allocate = (asize <
3492 1ULL << (WEIGHT_GET_INDEX(msp->ms_weight) + 1));
3493 } else {
3494 should_allocate = (asize <=
3495 (msp->ms_weight & ~METASLAB_WEIGHT_TYPE));
3496 }
3497
3498 return (should_allocate);
3499 }
3500
3501 static uint64_t
metaslab_weight(metaslab_t * msp,boolean_t nodirty)3502 metaslab_weight(metaslab_t *msp, boolean_t nodirty)
3503 {
3504 vdev_t *vd = msp->ms_group->mg_vd;
3505 spa_t *spa = vd->vdev_spa;
3506 uint64_t weight;
3507
3508 ASSERT(MUTEX_HELD(&msp->ms_lock));
3509
3510 metaslab_set_fragmentation(msp, nodirty);
3511
3512 /*
3513 * Update the maximum size. If the metaslab is loaded, this will
3514 * ensure that we get an accurate maximum size if newly freed space
3515 * has been added back into the free tree. If the metaslab is
3516 * unloaded, we check if there's a larger free segment in the
3517 * unflushed frees. This is a lower bound on the largest allocatable
3518 * segment size. Coalescing of adjacent entries may reveal larger
3519 * allocatable segments, but we aren't aware of those until loading
3520 * the space map into a range tree.
3521 */
3522 if (msp->ms_loaded) {
3523 msp->ms_max_size = metaslab_largest_allocatable(msp);
3524 } else {
3525 msp->ms_max_size = MAX(msp->ms_max_size,
3526 metaslab_largest_unflushed_free(msp));
3527 }
3528
3529 /*
3530 * Segment-based weighting requires space map histogram support.
3531 */
3532 if (zfs_metaslab_segment_weight_enabled &&
3533 spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
3534 (msp->ms_sm == NULL || msp->ms_sm->sm_dbuf->db_size ==
3535 sizeof (space_map_phys_t))) {
3536 weight = metaslab_segment_weight(msp);
3537 } else {
3538 weight = metaslab_space_weight(msp);
3539 }
3540 return (weight);
3541 }
3542
3543 void
metaslab_recalculate_weight_and_sort(metaslab_t * msp)3544 metaslab_recalculate_weight_and_sort(metaslab_t *msp)
3545 {
3546 ASSERT(MUTEX_HELD(&msp->ms_lock));
3547
3548 /* note: we preserve the mask (e.g. indication of primary, etc..) */
3549 uint64_t was_active = msp->ms_weight & METASLAB_ACTIVE_MASK;
3550 metaslab_group_sort(msp->ms_group, msp,
3551 metaslab_weight(msp, B_FALSE) | was_active);
3552 }
3553
3554 static int
metaslab_activate_allocator(metaslab_group_t * mg,metaslab_t * msp,int allocator,uint64_t activation_weight)3555 metaslab_activate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3556 int allocator, uint64_t activation_weight)
3557 {
3558 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
3559 ASSERT(MUTEX_HELD(&msp->ms_lock));
3560
3561 /*
3562 * If we're activating for the claim code, we don't want to actually
3563 * set the metaslab up for a specific allocator.
3564 */
3565 if (activation_weight == METASLAB_WEIGHT_CLAIM) {
3566 ASSERT0(msp->ms_activation_weight);
3567 msp->ms_activation_weight = msp->ms_weight;
3568 metaslab_group_sort(mg, msp, msp->ms_weight |
3569 activation_weight);
3570 return (0);
3571 }
3572
3573 metaslab_t **mspp = (activation_weight == METASLAB_WEIGHT_PRIMARY ?
3574 &mga->mga_primary : &mga->mga_secondary);
3575
3576 mutex_enter(&mg->mg_lock);
3577 if (*mspp != NULL) {
3578 mutex_exit(&mg->mg_lock);
3579 return (EEXIST);
3580 }
3581
3582 *mspp = msp;
3583 ASSERT3S(msp->ms_allocator, ==, -1);
3584 msp->ms_allocator = allocator;
3585 msp->ms_primary = (activation_weight == METASLAB_WEIGHT_PRIMARY);
3586
3587 ASSERT0(msp->ms_activation_weight);
3588 msp->ms_activation_weight = msp->ms_weight;
3589 metaslab_group_sort_impl(mg, msp,
3590 msp->ms_weight | activation_weight);
3591 mutex_exit(&mg->mg_lock);
3592
3593 return (0);
3594 }
3595
3596 static int
metaslab_activate(metaslab_t * msp,int allocator,uint64_t activation_weight)3597 metaslab_activate(metaslab_t *msp, int allocator, uint64_t activation_weight)
3598 {
3599 ASSERT(MUTEX_HELD(&msp->ms_lock));
3600
3601 /*
3602 * The current metaslab is already activated for us so there
3603 * is nothing to do. Already activated though, doesn't mean
3604 * that this metaslab is activated for our allocator nor our
3605 * requested activation weight. The metaslab could have started
3606 * as an active one for our allocator but changed allocators
3607 * while we were waiting to grab its ms_lock or we stole it
3608 * [see find_valid_metaslab()]. This means that there is a
3609 * possibility of passivating a metaslab of another allocator
3610 * or from a different activation mask, from this thread.
3611 */
3612 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3613 ASSERT(msp->ms_loaded);
3614 return (0);
3615 }
3616
3617 int error = metaslab_load(msp);
3618 if (error != 0) {
3619 metaslab_group_sort(msp->ms_group, msp, 0);
3620 return (error);
3621 }
3622
3623 /*
3624 * When entering metaslab_load() we may have dropped the
3625 * ms_lock because we were loading this metaslab, or we
3626 * were waiting for another thread to load it for us. In
3627 * that scenario, we recheck the weight of the metaslab
3628 * to see if it was activated by another thread.
3629 *
3630 * If the metaslab was activated for another allocator or
3631 * it was activated with a different activation weight (e.g.
3632 * we wanted to make it a primary but it was activated as
3633 * secondary) we return error (EBUSY).
3634 *
3635 * If the metaslab was activated for the same allocator
3636 * and requested activation mask, skip activating it.
3637 */
3638 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) != 0) {
3639 if (msp->ms_allocator != allocator)
3640 return (EBUSY);
3641
3642 if ((msp->ms_weight & activation_weight) == 0)
3643 return (SET_ERROR(EBUSY));
3644
3645 EQUIV((activation_weight == METASLAB_WEIGHT_PRIMARY),
3646 msp->ms_primary);
3647 return (0);
3648 }
3649
3650 /*
3651 * If the metaslab has literally 0 space, it will have weight 0. In
3652 * that case, don't bother activating it. This can happen if the
3653 * metaslab had space during find_valid_metaslab, but another thread
3654 * loaded it and used all that space while we were waiting to grab the
3655 * lock.
3656 */
3657 if (msp->ms_weight == 0) {
3658 ASSERT0(zfs_range_tree_space(msp->ms_allocatable));
3659 return (SET_ERROR(ENOSPC));
3660 }
3661
3662 if ((error = metaslab_activate_allocator(msp->ms_group, msp,
3663 allocator, activation_weight)) != 0) {
3664 return (error);
3665 }
3666
3667 ASSERT(msp->ms_loaded);
3668 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
3669
3670 return (0);
3671 }
3672
3673 static void
metaslab_passivate_allocator(metaslab_group_t * mg,metaslab_t * msp,uint64_t weight)3674 metaslab_passivate_allocator(metaslab_group_t *mg, metaslab_t *msp,
3675 uint64_t weight)
3676 {
3677 ASSERT(MUTEX_HELD(&msp->ms_lock));
3678 ASSERT(msp->ms_loaded);
3679
3680 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
3681 metaslab_group_sort(mg, msp, weight);
3682 return;
3683 }
3684
3685 mutex_enter(&mg->mg_lock);
3686 ASSERT3P(msp->ms_group, ==, mg);
3687 ASSERT3S(0, <=, msp->ms_allocator);
3688 ASSERT3U(msp->ms_allocator, <, mg->mg_class->mc_spa->spa_alloc_count);
3689
3690 metaslab_group_allocator_t *mga = &mg->mg_allocator[msp->ms_allocator];
3691 if (msp->ms_primary) {
3692 ASSERT3P(mga->mga_primary, ==, msp);
3693 ASSERT(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
3694 mga->mga_primary = NULL;
3695 } else {
3696 ASSERT3P(mga->mga_secondary, ==, msp);
3697 ASSERT(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
3698 mga->mga_secondary = NULL;
3699 }
3700 msp->ms_allocator = -1;
3701 metaslab_group_sort_impl(mg, msp, weight);
3702 mutex_exit(&mg->mg_lock);
3703 }
3704
3705 static void
metaslab_passivate(metaslab_t * msp,uint64_t weight)3706 metaslab_passivate(metaslab_t *msp, uint64_t weight)
3707 {
3708 uint64_t size __maybe_unused = weight & ~METASLAB_WEIGHT_TYPE;
3709
3710 /*
3711 * If size < SPA_MINBLOCKSIZE, then we will not allocate from
3712 * this metaslab again. In that case, it had better be empty,
3713 * or we would be leaving space on the table.
3714 */
3715 ASSERT(!WEIGHT_IS_SPACEBASED(msp->ms_weight) ||
3716 size >= SPA_MINBLOCKSIZE ||
3717 zfs_range_tree_space(msp->ms_allocatable) == 0);
3718 ASSERT0(weight & METASLAB_ACTIVE_MASK);
3719
3720 ASSERT(msp->ms_activation_weight != 0);
3721 msp->ms_activation_weight = 0;
3722 metaslab_passivate_allocator(msp->ms_group, msp, weight);
3723 ASSERT0(msp->ms_weight & METASLAB_ACTIVE_MASK);
3724 }
3725
3726 /*
3727 * Segment-based metaslabs are activated once and remain active until
3728 * we either fail an allocation attempt (similar to space-based metaslabs)
3729 * or have exhausted the free space in zfs_metaslab_switch_threshold
3730 * buckets since the metaslab was activated. This function checks to see
3731 * if we've exhausted the zfs_metaslab_switch_threshold buckets in the
3732 * metaslab and passivates it proactively. This will allow us to select a
3733 * metaslab with a larger contiguous region, if any, remaining within this
3734 * metaslab group. If we're in sync pass > 1, then we continue using this
3735 * metaslab so that we don't dirty more block and cause more sync passes.
3736 */
3737 static void
metaslab_segment_may_passivate(metaslab_t * msp)3738 metaslab_segment_may_passivate(metaslab_t *msp)
3739 {
3740 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3741
3742 if (WEIGHT_IS_SPACEBASED(msp->ms_weight) || spa_sync_pass(spa) > 1)
3743 return;
3744
3745 /*
3746 * As long as a single largest free segment covers majorioty of free
3747 * space, don't consider the metaslab fragmented. It should allow
3748 * us to fill new unfragmented metaslabs full before switching.
3749 */
3750 if (metaslab_largest_allocatable(msp) >
3751 zfs_range_tree_space(msp->ms_allocatable) * 15 / 16)
3752 return;
3753
3754 /*
3755 * Since we are in the middle of a sync pass, the most accurate
3756 * information that is accessible to us is the in-core range tree
3757 * histogram; calculate the new weight based on that information.
3758 */
3759 uint64_t weight = metaslab_weight_from_range_tree(msp);
3760 int activation_idx = WEIGHT_GET_INDEX(msp->ms_activation_weight);
3761 int current_idx = WEIGHT_GET_INDEX(weight);
3762
3763 if (current_idx <= activation_idx - zfs_metaslab_switch_threshold)
3764 metaslab_passivate(msp, weight);
3765 }
3766
3767 static void
metaslab_preload(void * arg)3768 metaslab_preload(void *arg)
3769 {
3770 metaslab_t *msp = arg;
3771 metaslab_class_t *mc = msp->ms_group->mg_class;
3772 spa_t *spa = mc->mc_spa;
3773 fstrans_cookie_t cookie = spl_fstrans_mark();
3774
3775 ASSERT(!MUTEX_HELD(&msp->ms_group->mg_lock));
3776
3777 mutex_enter(&msp->ms_lock);
3778 (void) metaslab_load(msp);
3779 metaslab_set_selected_txg(msp, spa_syncing_txg(spa));
3780 mutex_exit(&msp->ms_lock);
3781 spl_fstrans_unmark(cookie);
3782 }
3783
3784 static void
metaslab_group_preload(metaslab_group_t * mg)3785 metaslab_group_preload(metaslab_group_t *mg)
3786 {
3787 spa_t *spa = mg->mg_vd->vdev_spa;
3788 metaslab_t *msp;
3789 avl_tree_t *t = &mg->mg_metaslab_tree;
3790 int m = 0;
3791
3792 if (spa_shutting_down(spa) || !metaslab_preload_enabled)
3793 return;
3794
3795 mutex_enter(&mg->mg_lock);
3796
3797 /*
3798 * Load the next potential metaslabs
3799 */
3800 for (msp = avl_first(t); msp != NULL; msp = AVL_NEXT(t, msp)) {
3801 ASSERT3P(msp->ms_group, ==, mg);
3802
3803 /*
3804 * We preload only the maximum number of metaslabs specified
3805 * by metaslab_preload_limit. If a metaslab is being forced
3806 * to condense then we preload it too. This will ensure
3807 * that force condensing happens in the next txg.
3808 */
3809 if (++m > metaslab_preload_limit && !msp->ms_condense_wanted) {
3810 continue;
3811 }
3812
3813 VERIFY(taskq_dispatch(spa->spa_metaslab_taskq, metaslab_preload,
3814 msp, TQ_SLEEP | (m <= spa->spa_alloc_count ? TQ_FRONT : 0))
3815 != TASKQID_INVALID);
3816 }
3817 mutex_exit(&mg->mg_lock);
3818 }
3819
3820 /*
3821 * Determine if the space map's on-disk footprint is past our tolerance for
3822 * inefficiency. We would like to use the following criteria to make our
3823 * decision:
3824 *
3825 * 1. Do not condense if the size of the space map object would dramatically
3826 * increase as a result of writing out the free space range tree.
3827 *
3828 * 2. Condense if the on on-disk space map representation is at least
3829 * zfs_metaslab_condense_pct/100 times the size of the optimal representation
3830 * (i.e. zfs_metaslab_condense_pct = 110 and in-core = 1MB, optimal = 1.1MB).
3831 *
3832 * 3. Do not condense if the on-disk size of the space map does not actually
3833 * decrease.
3834 *
3835 * Unfortunately, we cannot compute the on-disk size of the space map in this
3836 * context because we cannot accurately compute the effects of compression, etc.
3837 * Instead, we apply the heuristic described in the block comment for
3838 * zfs_metaslab_condense_block_threshold - we only condense if the space used
3839 * is greater than a threshold number of blocks.
3840 */
3841 static boolean_t
metaslab_should_condense(metaslab_t * msp)3842 metaslab_should_condense(metaslab_t *msp)
3843 {
3844 space_map_t *sm = msp->ms_sm;
3845 vdev_t *vd = msp->ms_group->mg_vd;
3846 uint64_t vdev_blocksize = 1ULL << vd->vdev_ashift;
3847
3848 ASSERT(MUTEX_HELD(&msp->ms_lock));
3849 ASSERT(msp->ms_loaded);
3850 ASSERT(sm != NULL);
3851 ASSERT3U(spa_sync_pass(vd->vdev_spa), ==, 1);
3852
3853 /*
3854 * We always condense metaslabs that are empty and metaslabs for
3855 * which a condense request has been made.
3856 */
3857 if (zfs_range_tree_numsegs(msp->ms_allocatable) == 0 ||
3858 msp->ms_condense_wanted)
3859 return (B_TRUE);
3860
3861 uint64_t record_size = MAX(sm->sm_blksz, vdev_blocksize);
3862 uint64_t object_size = space_map_length(sm);
3863 uint64_t optimal_size = space_map_estimate_optimal_size(sm,
3864 msp->ms_allocatable, SM_NO_VDEVID);
3865
3866 return (object_size >=
3867 (optimal_size * zfs_metaslab_condense_pct / 100) &&
3868 object_size > zfs_metaslab_condense_block_threshold * record_size);
3869 }
3870
3871 /*
3872 * Condense the on-disk space map representation to its minimized form.
3873 * The minimized form consists of a small number of allocations followed
3874 * by the entries of the free range tree (ms_allocatable). The condensed
3875 * spacemap contains all the entries of previous TXGs (including those in
3876 * the pool-wide log spacemaps; thus this is effectively a superset of
3877 * metaslab_flush()), but this TXG's entries still need to be written.
3878 */
3879 static void
metaslab_condense(metaslab_t * msp,dmu_tx_t * tx)3880 metaslab_condense(metaslab_t *msp, dmu_tx_t *tx)
3881 {
3882 zfs_range_tree_t *condense_tree;
3883 space_map_t *sm = msp->ms_sm;
3884 uint64_t txg = dmu_tx_get_txg(tx);
3885 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
3886
3887 ASSERT(MUTEX_HELD(&msp->ms_lock));
3888 ASSERT(msp->ms_loaded);
3889 ASSERT(msp->ms_sm != NULL);
3890
3891 /*
3892 * In order to condense the space map, we need to change it so it
3893 * only describes which segments are currently allocated and free.
3894 *
3895 * All the current free space resides in the ms_allocatable, all
3896 * the ms_defer trees, and all the ms_allocating trees. We ignore
3897 * ms_freed because it is empty because we're in sync pass 1. We
3898 * ignore ms_freeing because these changes are not yet reflected
3899 * in the spacemap (they will be written later this txg).
3900 *
3901 * So to truncate the space map to represent all the entries of
3902 * previous TXGs we do the following:
3903 *
3904 * 1] We create a range tree (condense tree) that is 100% empty.
3905 * 2] We add to it all segments found in the ms_defer trees
3906 * as those segments are marked as free in the original space
3907 * map. We do the same with the ms_allocating trees for the same
3908 * reason. Adding these segments should be a relatively
3909 * inexpensive operation since we expect these trees to have a
3910 * small number of nodes.
3911 * 3] We vacate any unflushed allocs, since they are not frees we
3912 * need to add to the condense tree. Then we vacate any
3913 * unflushed frees as they should already be part of ms_allocatable.
3914 * 4] At this point, we would ideally like to add all segments
3915 * in the ms_allocatable tree from the condense tree. This way
3916 * we would write all the entries of the condense tree as the
3917 * condensed space map, which would only contain freed
3918 * segments with everything else assumed to be allocated.
3919 *
3920 * Doing so can be prohibitively expensive as ms_allocatable can
3921 * be large, and therefore computationally expensive to add to
3922 * the condense_tree. Instead we first sync out an entry marking
3923 * everything as allocated, then the condense_tree and then the
3924 * ms_allocatable, in the condensed space map. While this is not
3925 * optimal, it is typically close to optimal and more importantly
3926 * much cheaper to compute.
3927 *
3928 * 5] Finally, as both of the unflushed trees were written to our
3929 * new and condensed metaslab space map, we basically flushed
3930 * all the unflushed changes to disk, thus we call
3931 * metaslab_flush_update().
3932 */
3933 ASSERT3U(spa_sync_pass(spa), ==, 1);
3934 ASSERT(zfs_range_tree_is_empty(msp->ms_freed)); /* since it is pass 1 */
3935
3936 zfs_dbgmsg("condensing: txg %llu, msp[%llu] %px, vdev id %llu, "
3937 "spa %s, smp size %llu, segments %llu, forcing condense=%s",
3938 (u_longlong_t)txg, (u_longlong_t)msp->ms_id, msp,
3939 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
3940 spa->spa_name, (u_longlong_t)space_map_length(msp->ms_sm),
3941 (u_longlong_t)zfs_range_tree_numsegs(msp->ms_allocatable),
3942 msp->ms_condense_wanted ? "TRUE" : "FALSE");
3943
3944 msp->ms_condense_wanted = B_FALSE;
3945
3946 zfs_range_seg_type_t type;
3947 uint64_t shift, start;
3948 type = metaslab_calculate_range_tree_type(msp->ms_group->mg_vd, msp,
3949 &start, &shift);
3950
3951 condense_tree = zfs_range_tree_create_flags(
3952 NULL, type, NULL, start, shift,
3953 ZFS_RT_F_DYN_NAME,
3954 metaslab_rt_name(msp->ms_group, msp, "condense_tree"));
3955
3956 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
3957 zfs_range_tree_walk(msp->ms_defer[t],
3958 zfs_range_tree_add, condense_tree);
3959 }
3960
3961 for (int t = 0; t < TXG_CONCURRENT_STATES; t++) {
3962 zfs_range_tree_walk(msp->ms_allocating[(txg + t) & TXG_MASK],
3963 zfs_range_tree_add, condense_tree);
3964 }
3965
3966 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
3967 metaslab_unflushed_changes_memused(msp));
3968 spa->spa_unflushed_stats.sus_memused -=
3969 metaslab_unflushed_changes_memused(msp);
3970 zfs_range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
3971 zfs_range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
3972
3973 /*
3974 * We're about to drop the metaslab's lock thus allowing other
3975 * consumers to change it's content. Set the metaslab's ms_condensing
3976 * flag to ensure that allocations on this metaslab do not occur
3977 * while we're in the middle of committing it to disk. This is only
3978 * critical for ms_allocatable as all other range trees use per TXG
3979 * views of their content.
3980 */
3981 msp->ms_condensing = B_TRUE;
3982
3983 mutex_exit(&msp->ms_lock);
3984 uint64_t object = space_map_object(msp->ms_sm);
3985 space_map_truncate(sm,
3986 spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
3987 zfs_metaslab_sm_blksz_with_log : zfs_metaslab_sm_blksz_no_log, tx);
3988
3989 /*
3990 * space_map_truncate() may have reallocated the spacemap object.
3991 * If so, update the vdev_ms_array.
3992 */
3993 if (space_map_object(msp->ms_sm) != object) {
3994 object = space_map_object(msp->ms_sm);
3995 dmu_write(spa->spa_meta_objset,
3996 msp->ms_group->mg_vd->vdev_ms_array, sizeof (uint64_t) *
3997 msp->ms_id, sizeof (uint64_t), &object, tx,
3998 DMU_READ_NO_PREFETCH);
3999 }
4000
4001 /*
4002 * Note:
4003 * When the log space map feature is enabled, each space map will
4004 * always have ALLOCS followed by FREES for each sync pass. This is
4005 * typically true even when the log space map feature is disabled,
4006 * except from the case where a metaslab goes through metaslab_sync()
4007 * and gets condensed. In that case the metaslab's space map will have
4008 * ALLOCS followed by FREES (due to condensing) followed by ALLOCS
4009 * followed by FREES (due to space_map_write() in metaslab_sync()) for
4010 * sync pass 1.
4011 */
4012 zfs_range_tree_t *tmp_tree = zfs_range_tree_create_flags(
4013 NULL, type, NULL, start, shift,
4014 ZFS_RT_F_DYN_NAME,
4015 metaslab_rt_name(msp->ms_group, msp, "tmp_tree"));
4016 zfs_range_tree_add(tmp_tree, msp->ms_start, msp->ms_size);
4017 space_map_write(sm, tmp_tree, SM_ALLOC, SM_NO_VDEVID, tx);
4018 space_map_write(sm, msp->ms_allocatable, SM_FREE, SM_NO_VDEVID, tx);
4019 space_map_write(sm, condense_tree, SM_FREE, SM_NO_VDEVID, tx);
4020
4021 zfs_range_tree_vacate(condense_tree, NULL, NULL);
4022 zfs_range_tree_destroy(condense_tree);
4023 zfs_range_tree_vacate(tmp_tree, NULL, NULL);
4024 zfs_range_tree_destroy(tmp_tree);
4025 mutex_enter(&msp->ms_lock);
4026
4027 msp->ms_condensing = B_FALSE;
4028 metaslab_flush_update(msp, tx);
4029 }
4030
4031 static void
metaslab_unflushed_add(metaslab_t * msp,dmu_tx_t * tx)4032 metaslab_unflushed_add(metaslab_t *msp, dmu_tx_t *tx)
4033 {
4034 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
4035 ASSERT(spa_syncing_log_sm(spa) != NULL);
4036 ASSERT(msp->ms_sm != NULL);
4037 ASSERT(zfs_range_tree_is_empty(msp->ms_unflushed_allocs));
4038 ASSERT(zfs_range_tree_is_empty(msp->ms_unflushed_frees));
4039
4040 mutex_enter(&spa->spa_flushed_ms_lock);
4041 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
4042 metaslab_set_unflushed_dirty(msp, B_TRUE);
4043 avl_add(&spa->spa_metaslabs_by_flushed, msp);
4044 mutex_exit(&spa->spa_flushed_ms_lock);
4045
4046 spa_log_sm_increment_current_mscount(spa);
4047 spa_log_summary_add_flushed_metaslab(spa, B_TRUE);
4048 }
4049
4050 void
metaslab_unflushed_bump(metaslab_t * msp,dmu_tx_t * tx,boolean_t dirty)4051 metaslab_unflushed_bump(metaslab_t *msp, dmu_tx_t *tx, boolean_t dirty)
4052 {
4053 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
4054 ASSERT(spa_syncing_log_sm(spa) != NULL);
4055 ASSERT(msp->ms_sm != NULL);
4056 ASSERT(metaslab_unflushed_txg(msp) != 0);
4057 ASSERT3P(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL), ==, msp);
4058 ASSERT(zfs_range_tree_is_empty(msp->ms_unflushed_allocs));
4059 ASSERT(zfs_range_tree_is_empty(msp->ms_unflushed_frees));
4060
4061 VERIFY3U(tx->tx_txg, <=, spa_final_dirty_txg(spa));
4062
4063 /* update metaslab's position in our flushing tree */
4064 uint64_t ms_prev_flushed_txg = metaslab_unflushed_txg(msp);
4065 boolean_t ms_prev_flushed_dirty = metaslab_unflushed_dirty(msp);
4066 mutex_enter(&spa->spa_flushed_ms_lock);
4067 avl_remove(&spa->spa_metaslabs_by_flushed, msp);
4068 metaslab_set_unflushed_txg(msp, spa_syncing_txg(spa), tx);
4069 metaslab_set_unflushed_dirty(msp, dirty);
4070 avl_add(&spa->spa_metaslabs_by_flushed, msp);
4071 mutex_exit(&spa->spa_flushed_ms_lock);
4072
4073 /* update metaslab counts of spa_log_sm_t nodes */
4074 spa_log_sm_decrement_mscount(spa, ms_prev_flushed_txg);
4075 spa_log_sm_increment_current_mscount(spa);
4076
4077 /* update log space map summary */
4078 spa_log_summary_decrement_mscount(spa, ms_prev_flushed_txg,
4079 ms_prev_flushed_dirty);
4080 spa_log_summary_add_flushed_metaslab(spa, dirty);
4081
4082 /* cleanup obsolete logs if any */
4083 spa_cleanup_old_sm_logs(spa, tx);
4084 }
4085
4086 /*
4087 * Called when the metaslab has been flushed (its own spacemap now reflects
4088 * all the contents of the pool-wide spacemap log). Updates the metaslab's
4089 * metadata and any pool-wide related log space map data (e.g. summary,
4090 * obsolete logs, etc..) to reflect that.
4091 */
4092 static void
metaslab_flush_update(metaslab_t * msp,dmu_tx_t * tx)4093 metaslab_flush_update(metaslab_t *msp, dmu_tx_t *tx)
4094 {
4095 metaslab_group_t *mg = msp->ms_group;
4096 spa_t *spa = mg->mg_vd->vdev_spa;
4097
4098 ASSERT(MUTEX_HELD(&msp->ms_lock));
4099
4100 ASSERT3U(spa_sync_pass(spa), ==, 1);
4101
4102 /*
4103 * Just because a metaslab got flushed, that doesn't mean that
4104 * it will pass through metaslab_sync_done(). Thus, make sure to
4105 * update ms_synced_length here in case it doesn't.
4106 */
4107 msp->ms_synced_length = space_map_length(msp->ms_sm);
4108
4109 /*
4110 * We may end up here from metaslab_condense() without the
4111 * feature being active. In that case this is a no-op.
4112 */
4113 if (!spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP) ||
4114 metaslab_unflushed_txg(msp) == 0)
4115 return;
4116
4117 metaslab_unflushed_bump(msp, tx, B_FALSE);
4118 }
4119
4120 boolean_t
metaslab_flush(metaslab_t * msp,dmu_tx_t * tx)4121 metaslab_flush(metaslab_t *msp, dmu_tx_t *tx)
4122 {
4123 spa_t *spa = msp->ms_group->mg_vd->vdev_spa;
4124
4125 ASSERT(MUTEX_HELD(&msp->ms_lock));
4126 ASSERT3U(spa_sync_pass(spa), ==, 1);
4127 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
4128
4129 ASSERT(msp->ms_sm != NULL);
4130 ASSERT(metaslab_unflushed_txg(msp) != 0);
4131 ASSERT(avl_find(&spa->spa_metaslabs_by_flushed, msp, NULL) != NULL);
4132
4133 /*
4134 * There is nothing wrong with flushing the same metaslab twice, as
4135 * this codepath should work on that case. However, the current
4136 * flushing scheme makes sure to avoid this situation as we would be
4137 * making all these calls without having anything meaningful to write
4138 * to disk. We assert this behavior here.
4139 */
4140 ASSERT3U(metaslab_unflushed_txg(msp), <, dmu_tx_get_txg(tx));
4141
4142 /*
4143 * We can not flush while loading, because then we would
4144 * not load the ms_unflushed_{allocs,frees}.
4145 */
4146 if (msp->ms_loading)
4147 return (B_FALSE);
4148
4149 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
4150 metaslab_verify_weight_and_frag(msp);
4151
4152 /*
4153 * Metaslab condensing is effectively flushing. Therefore if the
4154 * metaslab can be condensed we can just condense it instead of
4155 * flushing it.
4156 *
4157 * Note that metaslab_condense() does call metaslab_flush_update()
4158 * so we can just return immediately after condensing. We also
4159 * don't need to care about setting ms_flushing or broadcasting
4160 * ms_flush_cv, even if we temporarily drop the ms_lock in
4161 * metaslab_condense(), as the metaslab is already loaded.
4162 */
4163 if (msp->ms_loaded && metaslab_should_condense(msp)) {
4164 metaslab_group_t *mg = msp->ms_group;
4165
4166 /*
4167 * For all histogram operations below refer to the
4168 * comments of metaslab_sync() where we follow a
4169 * similar procedure.
4170 */
4171 metaslab_group_histogram_verify(mg);
4172 metaslab_class_histogram_verify(mg->mg_class);
4173 metaslab_group_histogram_remove(mg, msp);
4174
4175 metaslab_condense(msp, tx);
4176
4177 space_map_histogram_clear(msp->ms_sm);
4178 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
4179 ASSERT(zfs_range_tree_is_empty(msp->ms_freed));
4180 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4181 space_map_histogram_add(msp->ms_sm,
4182 msp->ms_defer[t], tx);
4183 }
4184 metaslab_aux_histograms_update(msp);
4185
4186 metaslab_group_histogram_add(mg, msp);
4187 metaslab_group_histogram_verify(mg);
4188 metaslab_class_histogram_verify(mg->mg_class);
4189
4190 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
4191
4192 /*
4193 * Since we recreated the histogram (and potentially
4194 * the ms_sm too while condensing) ensure that the
4195 * weight is updated too because we are not guaranteed
4196 * that this metaslab is dirty and will go through
4197 * metaslab_sync_done().
4198 */
4199 metaslab_recalculate_weight_and_sort(msp);
4200 return (B_TRUE);
4201 }
4202
4203 msp->ms_flushing = B_TRUE;
4204 uint64_t sm_len_before = space_map_length(msp->ms_sm);
4205
4206 mutex_exit(&msp->ms_lock);
4207 space_map_write(msp->ms_sm, msp->ms_unflushed_allocs, SM_ALLOC,
4208 SM_NO_VDEVID, tx);
4209 space_map_write(msp->ms_sm, msp->ms_unflushed_frees, SM_FREE,
4210 SM_NO_VDEVID, tx);
4211 mutex_enter(&msp->ms_lock);
4212
4213 uint64_t sm_len_after = space_map_length(msp->ms_sm);
4214 if (zfs_flags & ZFS_DEBUG_LOG_SPACEMAP) {
4215 zfs_dbgmsg("flushing: txg %llu, spa %s, vdev_id %llu, "
4216 "ms_id %llu, unflushed_allocs %llu, unflushed_frees %llu, "
4217 "appended %llu bytes", (u_longlong_t)dmu_tx_get_txg(tx),
4218 spa_name(spa),
4219 (u_longlong_t)msp->ms_group->mg_vd->vdev_id,
4220 (u_longlong_t)msp->ms_id,
4221 (u_longlong_t)zfs_range_tree_space(
4222 msp->ms_unflushed_allocs),
4223 (u_longlong_t)zfs_range_tree_space(
4224 msp->ms_unflushed_frees),
4225 (u_longlong_t)(sm_len_after - sm_len_before));
4226 }
4227
4228 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
4229 metaslab_unflushed_changes_memused(msp));
4230 spa->spa_unflushed_stats.sus_memused -=
4231 metaslab_unflushed_changes_memused(msp);
4232 zfs_range_tree_vacate(msp->ms_unflushed_allocs, NULL, NULL);
4233 zfs_range_tree_vacate(msp->ms_unflushed_frees, NULL, NULL);
4234
4235 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
4236 metaslab_verify_weight_and_frag(msp);
4237
4238 metaslab_flush_update(msp, tx);
4239
4240 metaslab_verify_space(msp, dmu_tx_get_txg(tx));
4241 metaslab_verify_weight_and_frag(msp);
4242
4243 msp->ms_flushing = B_FALSE;
4244 cv_broadcast(&msp->ms_flush_cv);
4245 return (B_TRUE);
4246 }
4247
4248 /*
4249 * Write a metaslab to disk in the context of the specified transaction group.
4250 */
4251 void
metaslab_sync(metaslab_t * msp,uint64_t txg)4252 metaslab_sync(metaslab_t *msp, uint64_t txg)
4253 {
4254 metaslab_group_t *mg = msp->ms_group;
4255 vdev_t *vd = mg->mg_vd;
4256 spa_t *spa = vd->vdev_spa;
4257 objset_t *mos = spa_meta_objset(spa);
4258 zfs_range_tree_t *alloctree = msp->ms_allocating[txg & TXG_MASK];
4259 dmu_tx_t *tx;
4260
4261 ASSERT(!vd->vdev_ishole);
4262
4263 /*
4264 * This metaslab has just been added so there's no work to do now.
4265 */
4266 if (msp->ms_new) {
4267 ASSERT0(zfs_range_tree_space(alloctree));
4268 ASSERT0(zfs_range_tree_space(msp->ms_freeing));
4269 ASSERT0(zfs_range_tree_space(msp->ms_freed));
4270 ASSERT0(zfs_range_tree_space(msp->ms_checkpointing));
4271 ASSERT0(zfs_range_tree_space(msp->ms_trim));
4272 return;
4273 }
4274
4275 /*
4276 * Normally, we don't want to process a metaslab if there are no
4277 * allocations or frees to perform. However, if the metaslab is being
4278 * forced to condense, it's loaded and we're not beyond the final
4279 * dirty txg, we need to let it through. Not condensing beyond the
4280 * final dirty txg prevents an issue where metaslabs that need to be
4281 * condensed but were loaded for other reasons could cause a panic
4282 * here. By only checking the txg in that branch of the conditional,
4283 * we preserve the utility of the VERIFY statements in all other
4284 * cases.
4285 */
4286 if (zfs_range_tree_is_empty(alloctree) &&
4287 zfs_range_tree_is_empty(msp->ms_freeing) &&
4288 zfs_range_tree_is_empty(msp->ms_checkpointing) &&
4289 !(msp->ms_loaded && msp->ms_condense_wanted &&
4290 txg <= spa_final_dirty_txg(spa)))
4291 return;
4292
4293
4294 VERIFY3U(txg, <=, spa_final_dirty_txg(spa));
4295
4296 /*
4297 * The only state that can actually be changing concurrently
4298 * with metaslab_sync() is the metaslab's ms_allocatable. No
4299 * other thread can be modifying this txg's alloc, freeing,
4300 * freed, or space_map_phys_t. We drop ms_lock whenever we
4301 * could call into the DMU, because the DMU can call down to
4302 * us (e.g. via zio_free()) at any time.
4303 *
4304 * The spa_vdev_remove_thread() can be reading metaslab state
4305 * concurrently, and it is locked out by the ms_sync_lock.
4306 * Note that the ms_lock is insufficient for this, because it
4307 * is dropped by space_map_write().
4308 */
4309 tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
4310
4311 /*
4312 * Generate a log space map if one doesn't exist already.
4313 */
4314 spa_generate_syncing_log_sm(spa, tx);
4315
4316 if (msp->ms_sm == NULL) {
4317 uint64_t new_object = space_map_alloc(mos,
4318 spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP) ?
4319 zfs_metaslab_sm_blksz_with_log :
4320 zfs_metaslab_sm_blksz_no_log, tx);
4321 VERIFY3U(new_object, !=, 0);
4322
4323 dmu_write(mos, vd->vdev_ms_array, sizeof (uint64_t) *
4324 msp->ms_id, sizeof (uint64_t), &new_object, tx,
4325 DMU_READ_NO_PREFETCH);
4326
4327 VERIFY0(space_map_open(&msp->ms_sm, mos, new_object,
4328 msp->ms_start, msp->ms_size, vd->vdev_ashift));
4329 ASSERT(msp->ms_sm != NULL);
4330
4331 ASSERT(zfs_range_tree_is_empty(msp->ms_unflushed_allocs));
4332 ASSERT(zfs_range_tree_is_empty(msp->ms_unflushed_frees));
4333 ASSERT0(metaslab_allocated_space(msp));
4334 }
4335
4336 if (!zfs_range_tree_is_empty(msp->ms_checkpointing) &&
4337 vd->vdev_checkpoint_sm == NULL) {
4338 ASSERT(spa_has_checkpoint(spa));
4339
4340 uint64_t new_object = space_map_alloc(mos,
4341 zfs_vdev_standard_sm_blksz, tx);
4342 VERIFY3U(new_object, !=, 0);
4343
4344 VERIFY0(space_map_open(&vd->vdev_checkpoint_sm,
4345 mos, new_object, 0, vd->vdev_asize, vd->vdev_ashift));
4346 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4347
4348 /*
4349 * We save the space map object as an entry in vdev_top_zap
4350 * so it can be retrieved when the pool is reopened after an
4351 * export or through zdb.
4352 */
4353 VERIFY0(zap_add(vd->vdev_spa->spa_meta_objset,
4354 vd->vdev_top_zap, VDEV_TOP_ZAP_POOL_CHECKPOINT_SM,
4355 sizeof (new_object), 1, &new_object, tx));
4356 }
4357
4358 mutex_enter(&msp->ms_sync_lock);
4359 mutex_enter(&msp->ms_lock);
4360
4361 /*
4362 * Note: metaslab_condense() clears the space map's histogram.
4363 * Therefore we must verify and remove this histogram before
4364 * condensing.
4365 */
4366 metaslab_group_histogram_verify(mg);
4367 metaslab_class_histogram_verify(mg->mg_class);
4368 metaslab_group_histogram_remove(mg, msp);
4369
4370 if (spa->spa_sync_pass == 1 && msp->ms_loaded &&
4371 metaslab_should_condense(msp))
4372 metaslab_condense(msp, tx);
4373
4374 /*
4375 * We'll be going to disk to sync our space accounting, thus we
4376 * drop the ms_lock during that time so allocations coming from
4377 * open-context (ZIL) for future TXGs do not block.
4378 */
4379 mutex_exit(&msp->ms_lock);
4380 space_map_t *log_sm = spa_syncing_log_sm(spa);
4381 if (log_sm != NULL) {
4382 ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4383 if (metaslab_unflushed_txg(msp) == 0)
4384 metaslab_unflushed_add(msp, tx);
4385 else if (!metaslab_unflushed_dirty(msp))
4386 metaslab_unflushed_bump(msp, tx, B_TRUE);
4387
4388 space_map_write(log_sm, alloctree, SM_ALLOC,
4389 vd->vdev_id, tx);
4390 space_map_write(log_sm, msp->ms_freeing, SM_FREE,
4391 vd->vdev_id, tx);
4392 mutex_enter(&msp->ms_lock);
4393
4394 ASSERT3U(spa->spa_unflushed_stats.sus_memused, >=,
4395 metaslab_unflushed_changes_memused(msp));
4396 spa->spa_unflushed_stats.sus_memused -=
4397 metaslab_unflushed_changes_memused(msp);
4398 zfs_range_tree_remove_xor_add(alloctree,
4399 msp->ms_unflushed_frees, msp->ms_unflushed_allocs);
4400 zfs_range_tree_remove_xor_add(msp->ms_freeing,
4401 msp->ms_unflushed_allocs, msp->ms_unflushed_frees);
4402 spa->spa_unflushed_stats.sus_memused +=
4403 metaslab_unflushed_changes_memused(msp);
4404 } else {
4405 ASSERT(!spa_feature_is_enabled(spa, SPA_FEATURE_LOG_SPACEMAP));
4406
4407 space_map_write(msp->ms_sm, alloctree, SM_ALLOC,
4408 SM_NO_VDEVID, tx);
4409 space_map_write(msp->ms_sm, msp->ms_freeing, SM_FREE,
4410 SM_NO_VDEVID, tx);
4411 mutex_enter(&msp->ms_lock);
4412 }
4413
4414 msp->ms_allocated_space += zfs_range_tree_space(alloctree);
4415 ASSERT3U(msp->ms_allocated_space, >=,
4416 zfs_range_tree_space(msp->ms_freeing));
4417 msp->ms_allocated_space -= zfs_range_tree_space(msp->ms_freeing);
4418
4419 if (!zfs_range_tree_is_empty(msp->ms_checkpointing)) {
4420 ASSERT(spa_has_checkpoint(spa));
4421 ASSERT3P(vd->vdev_checkpoint_sm, !=, NULL);
4422
4423 /*
4424 * Since we are doing writes to disk and the ms_checkpointing
4425 * tree won't be changing during that time, we drop the
4426 * ms_lock while writing to the checkpoint space map, for the
4427 * same reason mentioned above.
4428 */
4429 mutex_exit(&msp->ms_lock);
4430 space_map_write(vd->vdev_checkpoint_sm,
4431 msp->ms_checkpointing, SM_FREE, SM_NO_VDEVID, tx);
4432 mutex_enter(&msp->ms_lock);
4433
4434 spa->spa_checkpoint_info.sci_dspace +=
4435 zfs_range_tree_space(msp->ms_checkpointing);
4436 vd->vdev_stat.vs_checkpoint_space +=
4437 zfs_range_tree_space(msp->ms_checkpointing);
4438 ASSERT3U(vd->vdev_stat.vs_checkpoint_space, ==,
4439 -space_map_allocated(vd->vdev_checkpoint_sm));
4440
4441 zfs_range_tree_vacate(msp->ms_checkpointing, NULL, NULL);
4442 }
4443
4444 if (msp->ms_loaded) {
4445 /*
4446 * When the space map is loaded, we have an accurate
4447 * histogram in the range tree. This gives us an opportunity
4448 * to bring the space map's histogram up-to-date so we clear
4449 * it first before updating it.
4450 */
4451 space_map_histogram_clear(msp->ms_sm);
4452 space_map_histogram_add(msp->ms_sm, msp->ms_allocatable, tx);
4453
4454 /*
4455 * Since we've cleared the histogram we need to add back
4456 * any free space that has already been processed, plus
4457 * any deferred space. This allows the on-disk histogram
4458 * to accurately reflect all free space even if some space
4459 * is not yet available for allocation (i.e. deferred).
4460 */
4461 space_map_histogram_add(msp->ms_sm, msp->ms_freed, tx);
4462
4463 /*
4464 * Add back any deferred free space that has not been
4465 * added back into the in-core free tree yet. This will
4466 * ensure that we don't end up with a space map histogram
4467 * that is completely empty unless the metaslab is fully
4468 * allocated.
4469 */
4470 for (int t = 0; t < TXG_DEFER_SIZE; t++) {
4471 space_map_histogram_add(msp->ms_sm,
4472 msp->ms_defer[t], tx);
4473 }
4474 }
4475
4476 /*
4477 * Always add the free space from this sync pass to the space
4478 * map histogram. We want to make sure that the on-disk histogram
4479 * accounts for all free space. If the space map is not loaded,
4480 * then we will lose some accuracy but will correct it the next
4481 * time we load the space map.
4482 */
4483 space_map_histogram_add(msp->ms_sm, msp->ms_freeing, tx);
4484 metaslab_aux_histograms_update(msp);
4485
4486 metaslab_group_histogram_add(mg, msp);
4487 metaslab_group_histogram_verify(mg);
4488 metaslab_class_histogram_verify(mg->mg_class);
4489
4490 /*
4491 * For sync pass 1, we avoid traversing this txg's free range tree
4492 * and instead will just swap the pointers for freeing and freed.
4493 * We can safely do this since the freed_tree is guaranteed to be
4494 * empty on the initial pass.
4495 *
4496 * Keep in mind that even if we are currently using a log spacemap
4497 * we want current frees to end up in the ms_allocatable (but not
4498 * get appended to the ms_sm) so their ranges can be reused as usual.
4499 */
4500 if (spa_sync_pass(spa) == 1) {
4501 zfs_range_tree_swap(&msp->ms_freeing, &msp->ms_freed);
4502 ASSERT0(msp->ms_allocated_this_txg);
4503 } else {
4504 zfs_range_tree_vacate(msp->ms_freeing,
4505 zfs_range_tree_add, msp->ms_freed);
4506 }
4507 msp->ms_allocated_this_txg += zfs_range_tree_space(alloctree);
4508 zfs_range_tree_vacate(alloctree, NULL, NULL);
4509
4510 ASSERT0(zfs_range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4511 ASSERT0(zfs_range_tree_space(msp->ms_allocating[TXG_CLEAN(txg)
4512 & TXG_MASK]));
4513 ASSERT0(zfs_range_tree_space(msp->ms_freeing));
4514 ASSERT0(zfs_range_tree_space(msp->ms_checkpointing));
4515
4516 mutex_exit(&msp->ms_lock);
4517
4518 /*
4519 * Verify that the space map object ID has been recorded in the
4520 * vdev_ms_array.
4521 */
4522 uint64_t object;
4523 VERIFY0(dmu_read(mos, vd->vdev_ms_array,
4524 msp->ms_id * sizeof (uint64_t), sizeof (uint64_t), &object, 0));
4525 VERIFY3U(object, ==, space_map_object(msp->ms_sm));
4526
4527 mutex_exit(&msp->ms_sync_lock);
4528 dmu_tx_commit(tx);
4529 }
4530
4531 static void
metaslab_evict(metaslab_t * msp,uint64_t txg)4532 metaslab_evict(metaslab_t *msp, uint64_t txg)
4533 {
4534 if (!msp->ms_loaded || msp->ms_disabled != 0)
4535 return;
4536
4537 for (int t = 1; t < TXG_CONCURRENT_STATES; t++) {
4538 VERIFY0(zfs_range_tree_space(
4539 msp->ms_allocating[(txg + t) & TXG_MASK]));
4540 }
4541 if (msp->ms_allocator != -1)
4542 metaslab_passivate(msp, msp->ms_weight & ~METASLAB_ACTIVE_MASK);
4543
4544 if (!metaslab_debug_unload)
4545 metaslab_unload(msp);
4546 }
4547
4548 /*
4549 * Called after a transaction group has completely synced to mark
4550 * all of the metaslab's free space as usable.
4551 */
4552 void
metaslab_sync_done(metaslab_t * msp,uint64_t txg)4553 metaslab_sync_done(metaslab_t *msp, uint64_t txg)
4554 {
4555 metaslab_group_t *mg = msp->ms_group;
4556 vdev_t *vd = mg->mg_vd;
4557 spa_t *spa = vd->vdev_spa;
4558 zfs_range_tree_t **defer_tree;
4559 int64_t alloc_delta, defer_delta;
4560 boolean_t defer_allowed = B_TRUE;
4561
4562 ASSERT(!vd->vdev_ishole);
4563
4564 mutex_enter(&msp->ms_lock);
4565
4566 if (msp->ms_new) {
4567 /* this is a new metaslab, add its capacity to the vdev */
4568 metaslab_space_update(mg, 0, 0, msp->ms_size);
4569
4570 /* there should be no allocations nor frees at this point */
4571 VERIFY0(msp->ms_allocated_this_txg);
4572 VERIFY0(zfs_range_tree_space(msp->ms_freed));
4573 }
4574
4575 ASSERT0(zfs_range_tree_space(msp->ms_freeing));
4576 ASSERT0(zfs_range_tree_space(msp->ms_checkpointing));
4577
4578 defer_tree = &msp->ms_defer[txg % TXG_DEFER_SIZE];
4579
4580 uint64_t free_space = metaslab_class_get_space(spa_normal_class(spa)) -
4581 metaslab_class_get_alloc(spa_normal_class(spa));
4582 if (free_space <= spa_get_slop_space(spa) || vd->vdev_removing ||
4583 vd->vdev_rz_expanding) {
4584 defer_allowed = B_FALSE;
4585 }
4586
4587 defer_delta = 0;
4588 alloc_delta = msp->ms_allocated_this_txg -
4589 zfs_range_tree_space(msp->ms_freed);
4590
4591 if (defer_allowed) {
4592 defer_delta = zfs_range_tree_space(msp->ms_freed) -
4593 zfs_range_tree_space(*defer_tree);
4594 } else {
4595 defer_delta -= zfs_range_tree_space(*defer_tree);
4596 }
4597 metaslab_space_update(mg, alloc_delta + defer_delta, defer_delta, 0);
4598
4599 if (spa_syncing_log_sm(spa) == NULL) {
4600 /*
4601 * If there's a metaslab_load() in progress and we don't have
4602 * a log space map, it means that we probably wrote to the
4603 * metaslab's space map. If this is the case, we need to
4604 * make sure that we wait for the load to complete so that we
4605 * have a consistent view at the in-core side of the metaslab.
4606 */
4607 metaslab_load_wait(msp);
4608 } else {
4609 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
4610 }
4611
4612 /*
4613 * When auto-trimming is enabled, free ranges which are added to
4614 * ms_allocatable are also be added to ms_trim. The ms_trim tree is
4615 * periodically consumed by the vdev_autotrim_thread() which issues
4616 * trims for all ranges and then vacates the tree. The ms_trim tree
4617 * can be discarded at any time with the sole consequence of recent
4618 * frees not being trimmed.
4619 */
4620 if (spa_get_autotrim(spa) == SPA_AUTOTRIM_ON) {
4621 zfs_range_tree_walk(*defer_tree, zfs_range_tree_add,
4622 msp->ms_trim);
4623 if (!defer_allowed) {
4624 zfs_range_tree_walk(msp->ms_freed, zfs_range_tree_add,
4625 msp->ms_trim);
4626 }
4627 } else {
4628 zfs_range_tree_vacate(msp->ms_trim, NULL, NULL);
4629 }
4630
4631 /*
4632 * Move the frees from the defer_tree back to the free
4633 * range tree (if it's loaded). Swap the freed_tree and
4634 * the defer_tree -- this is safe to do because we've
4635 * just emptied out the defer_tree.
4636 */
4637 zfs_range_tree_vacate(*defer_tree,
4638 msp->ms_loaded ? zfs_range_tree_add : NULL, msp->ms_allocatable);
4639 if (defer_allowed) {
4640 zfs_range_tree_swap(&msp->ms_freed, defer_tree);
4641 } else {
4642 zfs_range_tree_vacate(msp->ms_freed,
4643 msp->ms_loaded ? zfs_range_tree_add : NULL,
4644 msp->ms_allocatable);
4645 }
4646
4647 msp->ms_synced_length = space_map_length(msp->ms_sm);
4648
4649 msp->ms_deferspace += defer_delta;
4650 ASSERT3S(msp->ms_deferspace, >=, 0);
4651 ASSERT3S(msp->ms_deferspace, <=, msp->ms_size);
4652 if (msp->ms_deferspace != 0) {
4653 /*
4654 * Keep syncing this metaslab until all deferred frees
4655 * are back in circulation.
4656 */
4657 vdev_dirty(vd, VDD_METASLAB, msp, txg + 1);
4658 }
4659 metaslab_aux_histograms_update_done(msp, defer_allowed);
4660
4661 if (msp->ms_new) {
4662 msp->ms_new = B_FALSE;
4663 mutex_enter(&mg->mg_lock);
4664 mg->mg_ms_ready++;
4665 mutex_exit(&mg->mg_lock);
4666 }
4667
4668 /*
4669 * Re-sort metaslab within its group now that we've adjusted
4670 * its allocatable space.
4671 */
4672 metaslab_recalculate_weight_and_sort(msp);
4673
4674 ASSERT0(zfs_range_tree_space(msp->ms_allocating[txg & TXG_MASK]));
4675 ASSERT0(zfs_range_tree_space(msp->ms_freeing));
4676 ASSERT0(zfs_range_tree_space(msp->ms_freed));
4677 ASSERT0(zfs_range_tree_space(msp->ms_checkpointing));
4678 msp->ms_allocating_total -= msp->ms_allocated_this_txg;
4679 msp->ms_allocated_this_txg = 0;
4680 mutex_exit(&msp->ms_lock);
4681 }
4682
4683 void
metaslab_sync_reassess(metaslab_group_t * mg)4684 metaslab_sync_reassess(metaslab_group_t *mg)
4685 {
4686 spa_t *spa = mg->mg_class->mc_spa;
4687
4688 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
4689 mg->mg_fragmentation = metaslab_group_fragmentation(mg);
4690 metaslab_group_alloc_update(mg);
4691
4692 /*
4693 * Preload the next potential metaslabs but only on active
4694 * metaslab groups. We can get into a state where the metaslab
4695 * is no longer active since we dirty metaslabs as we remove a
4696 * a device, thus potentially making the metaslab group eligible
4697 * for preloading.
4698 */
4699 if (mg->mg_activation_count > 0) {
4700 metaslab_group_preload(mg);
4701 }
4702 spa_config_exit(spa, SCL_ALLOC, FTAG);
4703 }
4704
4705 /*
4706 * When writing a ditto block (i.e. more than one DVA for a given BP) on
4707 * the same vdev as an existing DVA of this BP, then try to allocate it
4708 * on a different metaslab than existing DVAs (i.e. a unique metaslab).
4709 */
4710 static boolean_t
metaslab_is_unique(metaslab_t * msp,dva_t * dva)4711 metaslab_is_unique(metaslab_t *msp, dva_t *dva)
4712 {
4713 uint64_t dva_ms_id;
4714
4715 if (DVA_GET_ASIZE(dva) == 0)
4716 return (B_TRUE);
4717
4718 if (msp->ms_group->mg_vd->vdev_id != DVA_GET_VDEV(dva))
4719 return (B_TRUE);
4720
4721 dva_ms_id = DVA_GET_OFFSET(dva) >> msp->ms_group->mg_vd->vdev_ms_shift;
4722
4723 return (msp->ms_id != dva_ms_id);
4724 }
4725
4726 /*
4727 * ==========================================================================
4728 * Metaslab allocation tracing facility
4729 * ==========================================================================
4730 */
4731
4732 /*
4733 * Add an allocation trace element to the allocation tracing list.
4734 */
4735 static void
metaslab_trace_add(zio_alloc_list_t * zal,metaslab_group_t * mg,metaslab_t * msp,uint64_t psize,uint32_t dva_id,uint64_t offset,int allocator)4736 metaslab_trace_add(zio_alloc_list_t *zal, metaslab_group_t *mg,
4737 metaslab_t *msp, uint64_t psize, uint32_t dva_id, uint64_t offset,
4738 int allocator)
4739 {
4740 metaslab_alloc_trace_t *mat;
4741
4742 if (!metaslab_trace_enabled)
4743 return;
4744
4745 /*
4746 * When the tracing list reaches its maximum we remove
4747 * the second element in the list before adding a new one.
4748 * By removing the second element we preserve the original
4749 * entry as a clue to what allocations steps have already been
4750 * performed.
4751 */
4752 if (zal->zal_size == metaslab_trace_max_entries) {
4753 metaslab_alloc_trace_t *mat_next;
4754 #ifdef ZFS_DEBUG
4755 panic("too many entries in allocation list");
4756 #endif
4757 METASLABSTAT_BUMP(metaslabstat_trace_over_limit);
4758 zal->zal_size--;
4759 mat_next = list_next(&zal->zal_list, list_head(&zal->zal_list));
4760 list_remove(&zal->zal_list, mat_next);
4761 kmem_cache_free(metaslab_alloc_trace_cache, mat_next);
4762 }
4763
4764 mat = kmem_cache_alloc(metaslab_alloc_trace_cache, KM_SLEEP);
4765 list_link_init(&mat->mat_list_node);
4766 mat->mat_mg = mg;
4767 mat->mat_msp = msp;
4768 mat->mat_size = psize;
4769 mat->mat_dva_id = dva_id;
4770 mat->mat_offset = offset;
4771 mat->mat_weight = 0;
4772 mat->mat_allocator = allocator;
4773
4774 if (msp != NULL)
4775 mat->mat_weight = msp->ms_weight;
4776
4777 /*
4778 * The list is part of the zio so locking is not required. Only
4779 * a single thread will perform allocations for a given zio.
4780 */
4781 list_insert_tail(&zal->zal_list, mat);
4782 zal->zal_size++;
4783
4784 ASSERT3U(zal->zal_size, <=, metaslab_trace_max_entries);
4785 }
4786
4787 void
metaslab_trace_move(zio_alloc_list_t * old,zio_alloc_list_t * new)4788 metaslab_trace_move(zio_alloc_list_t *old, zio_alloc_list_t *new)
4789 {
4790 ASSERT0(new->zal_size);
4791 list_move_tail(&new->zal_list, &old->zal_list);
4792 new->zal_size = old->zal_size;
4793 list_destroy(&old->zal_list);
4794 }
4795
4796 void
metaslab_trace_init(zio_alloc_list_t * zal)4797 metaslab_trace_init(zio_alloc_list_t *zal)
4798 {
4799 list_create(&zal->zal_list, sizeof (metaslab_alloc_trace_t),
4800 offsetof(metaslab_alloc_trace_t, mat_list_node));
4801 zal->zal_size = 0;
4802 }
4803
4804 void
metaslab_trace_fini(zio_alloc_list_t * zal)4805 metaslab_trace_fini(zio_alloc_list_t *zal)
4806 {
4807 metaslab_alloc_trace_t *mat;
4808
4809 while ((mat = list_remove_head(&zal->zal_list)) != NULL)
4810 kmem_cache_free(metaslab_alloc_trace_cache, mat);
4811 list_destroy(&zal->zal_list);
4812 zal->zal_size = 0;
4813 }
4814
4815 /*
4816 * ==========================================================================
4817 * Metaslab block operations
4818 * ==========================================================================
4819 */
4820
4821 static void
metaslab_group_alloc_increment(spa_t * spa,uint64_t vdev,int allocator,int flags,uint64_t psize,const void * tag)4822 metaslab_group_alloc_increment(spa_t *spa, uint64_t vdev, int allocator,
4823 int flags, uint64_t psize, const void *tag)
4824 {
4825 if (!(flags & METASLAB_ASYNC_ALLOC) || tag == NULL)
4826 return;
4827
4828 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4829 if (!mg->mg_class->mc_alloc_throttle_enabled)
4830 return;
4831
4832 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4833 (void) zfs_refcount_add_many(&mga->mga_queue_depth, psize, tag);
4834 }
4835
4836 void
metaslab_group_alloc_increment_all(spa_t * spa,blkptr_t * bp,int allocator,int flags,uint64_t psize,const void * tag)4837 metaslab_group_alloc_increment_all(spa_t *spa, blkptr_t *bp, int allocator,
4838 int flags, uint64_t psize, const void *tag)
4839 {
4840 for (int d = 0; d < BP_GET_NDVAS(bp); d++) {
4841 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[d]);
4842 metaslab_group_alloc_increment(spa, vdev, allocator, flags,
4843 psize, tag);
4844 }
4845 }
4846
4847 void
metaslab_group_alloc_decrement(spa_t * spa,uint64_t vdev,int allocator,int flags,uint64_t psize,const void * tag)4848 metaslab_group_alloc_decrement(spa_t *spa, uint64_t vdev, int allocator,
4849 int flags, uint64_t psize, const void *tag)
4850 {
4851 if (!(flags & METASLAB_ASYNC_ALLOC) || tag == NULL)
4852 return;
4853
4854 metaslab_group_t *mg = vdev_lookup_top(spa, vdev)->vdev_mg;
4855 if (!mg->mg_class->mc_alloc_throttle_enabled)
4856 return;
4857
4858 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
4859 (void) zfs_refcount_remove_many(&mga->mga_queue_depth, psize, tag);
4860 }
4861
4862 static uint64_t
metaslab_block_alloc(metaslab_t * msp,uint64_t size,uint64_t max_size,uint64_t txg,uint64_t * actual_size)4863 metaslab_block_alloc(metaslab_t *msp, uint64_t size, uint64_t max_size,
4864 uint64_t txg, uint64_t *actual_size)
4865 {
4866 uint64_t start;
4867 zfs_range_tree_t *rt = msp->ms_allocatable;
4868 metaslab_class_t *mc = msp->ms_group->mg_class;
4869
4870 ASSERT(MUTEX_HELD(&msp->ms_lock));
4871 VERIFY(!msp->ms_condensing);
4872 VERIFY0(msp->ms_disabled);
4873 VERIFY0(msp->ms_new);
4874
4875 start = mc->mc_ops->msop_alloc(msp, size, max_size, actual_size);
4876 if (start != -1ULL) {
4877 size = *actual_size;
4878 metaslab_group_t *mg = msp->ms_group;
4879 vdev_t *vd = mg->mg_vd;
4880
4881 VERIFY0(P2PHASE(start, 1ULL << vd->vdev_ashift));
4882 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
4883 VERIFY3U(zfs_range_tree_space(rt) - size, <=, msp->ms_size);
4884 zfs_range_tree_remove(rt, start, size);
4885 zfs_range_tree_clear(msp->ms_trim, start, size);
4886
4887 if (zfs_range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
4888 vdev_dirty(mg->mg_vd, VDD_METASLAB, msp, txg);
4889
4890 zfs_range_tree_add(msp->ms_allocating[txg & TXG_MASK], start,
4891 size);
4892 msp->ms_allocating_total += size;
4893
4894 /* Track the last successful allocation */
4895 msp->ms_alloc_txg = txg;
4896 metaslab_verify_space(msp, txg);
4897 }
4898
4899 /*
4900 * Now that we've attempted the allocation we need to update the
4901 * metaslab's maximum block size since it may have changed.
4902 */
4903 msp->ms_max_size = metaslab_largest_allocatable(msp);
4904 return (start);
4905 }
4906
4907 /*
4908 * Find the metaslab with the highest weight that is less than what we've
4909 * already tried. In the common case, this means that we will examine each
4910 * metaslab at most once. Note that concurrent callers could reorder metaslabs
4911 * by activation/passivation once we have dropped the mg_lock. If a metaslab is
4912 * activated by another thread, and we fail to allocate from the metaslab we
4913 * have selected, we may not try the newly-activated metaslab, and instead
4914 * activate another metaslab. This is not optimal, but generally does not cause
4915 * any problems (a possible exception being if every metaslab is completely full
4916 * except for the newly-activated metaslab which we fail to examine).
4917 */
4918 static metaslab_t *
find_valid_metaslab(metaslab_group_t * mg,uint64_t activation_weight,dva_t * dva,int d,uint64_t asize,int allocator,boolean_t try_hard,zio_alloc_list_t * zal,metaslab_t * search,boolean_t * was_active)4919 find_valid_metaslab(metaslab_group_t *mg, uint64_t activation_weight,
4920 dva_t *dva, int d, uint64_t asize, int allocator,
4921 boolean_t try_hard, zio_alloc_list_t *zal, metaslab_t *search,
4922 boolean_t *was_active)
4923 {
4924 avl_index_t idx;
4925 avl_tree_t *t = &mg->mg_metaslab_tree;
4926 metaslab_t *msp = avl_find(t, search, &idx);
4927 if (msp == NULL)
4928 msp = avl_nearest(t, idx, AVL_AFTER);
4929
4930 uint_t tries = 0;
4931 for (; msp != NULL; msp = AVL_NEXT(t, msp)) {
4932 int i;
4933
4934 if (!try_hard && tries > zfs_metaslab_find_max_tries) {
4935 METASLABSTAT_BUMP(metaslabstat_too_many_tries);
4936 return (NULL);
4937 }
4938 tries++;
4939
4940 if (!metaslab_should_allocate(msp, asize, try_hard)) {
4941 metaslab_trace_add(zal, mg, msp, asize, d,
4942 TRACE_TOO_SMALL, allocator);
4943 continue;
4944 }
4945
4946 /*
4947 * If the selected metaslab is condensing or disabled, or
4948 * hasn't gone through a metaslab_sync_done(), then skip it.
4949 */
4950 if (msp->ms_condensing || msp->ms_disabled > 0 || msp->ms_new)
4951 continue;
4952
4953 *was_active = msp->ms_allocator != -1;
4954 /*
4955 * If we're activating as primary, this is our first allocation
4956 * from this disk, so we don't need to check how close we are.
4957 * If the metaslab under consideration was already active,
4958 * we're getting desperate enough to steal another allocator's
4959 * metaslab, so we still don't care about distances.
4960 */
4961 if (activation_weight == METASLAB_WEIGHT_PRIMARY || *was_active)
4962 break;
4963
4964 if (!try_hard) {
4965 for (i = 0; i < d; i++) {
4966 if (!metaslab_is_unique(msp, &dva[i]))
4967 break; /* try another metaslab */
4968 }
4969 if (i == d)
4970 break;
4971 }
4972 }
4973
4974 if (msp != NULL) {
4975 search->ms_weight = msp->ms_weight;
4976 search->ms_start = msp->ms_start + 1;
4977 search->ms_allocator = msp->ms_allocator;
4978 search->ms_primary = msp->ms_primary;
4979 }
4980 return (msp);
4981 }
4982
4983 static void
metaslab_active_mask_verify(metaslab_t * msp)4984 metaslab_active_mask_verify(metaslab_t *msp)
4985 {
4986 ASSERT(MUTEX_HELD(&msp->ms_lock));
4987
4988 if ((zfs_flags & ZFS_DEBUG_METASLAB_VERIFY) == 0)
4989 return;
4990
4991 if ((msp->ms_weight & METASLAB_ACTIVE_MASK) == 0)
4992 return;
4993
4994 if (msp->ms_weight & METASLAB_WEIGHT_PRIMARY) {
4995 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
4996 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
4997 VERIFY3S(msp->ms_allocator, !=, -1);
4998 VERIFY(msp->ms_primary);
4999 return;
5000 }
5001
5002 if (msp->ms_weight & METASLAB_WEIGHT_SECONDARY) {
5003 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
5004 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_CLAIM);
5005 VERIFY3S(msp->ms_allocator, !=, -1);
5006 VERIFY(!msp->ms_primary);
5007 return;
5008 }
5009
5010 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM) {
5011 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_PRIMARY);
5012 VERIFY0(msp->ms_weight & METASLAB_WEIGHT_SECONDARY);
5013 VERIFY3S(msp->ms_allocator, ==, -1);
5014 return;
5015 }
5016 }
5017
5018 static uint64_t
metaslab_group_alloc(metaslab_group_t * mg,zio_alloc_list_t * zal,uint64_t asize,uint64_t max_asize,uint64_t txg,dva_t * dva,int d,int allocator,boolean_t try_hard,uint64_t * actual_asize)5019 metaslab_group_alloc(metaslab_group_t *mg, zio_alloc_list_t *zal,
5020 uint64_t asize, uint64_t max_asize, uint64_t txg,
5021 dva_t *dva, int d, int allocator, boolean_t try_hard,
5022 uint64_t *actual_asize)
5023 {
5024 metaslab_t *msp = NULL;
5025 uint64_t offset = -1ULL;
5026
5027 uint64_t activation_weight = METASLAB_WEIGHT_PRIMARY;
5028 for (int i = 0; i < d; i++) {
5029 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
5030 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
5031 activation_weight = METASLAB_WEIGHT_SECONDARY;
5032 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
5033 DVA_GET_VDEV(&dva[i]) == mg->mg_vd->vdev_id) {
5034 activation_weight = METASLAB_WEIGHT_CLAIM;
5035 break;
5036 }
5037 }
5038
5039 /*
5040 * If we don't have enough metaslabs active, we just use the 0th slot.
5041 */
5042 if (allocator >= mg->mg_ms_ready / 3)
5043 allocator = 0;
5044 metaslab_group_allocator_t *mga = &mg->mg_allocator[allocator];
5045
5046 ASSERT3U(mg->mg_vd->vdev_ms_count, >=, 2);
5047
5048 metaslab_t *search = kmem_alloc(sizeof (*search), KM_SLEEP);
5049 search->ms_weight = UINT64_MAX;
5050 search->ms_start = 0;
5051 /*
5052 * At the end of the metaslab tree are the already-active metaslabs,
5053 * first the primaries, then the secondaries. When we resume searching
5054 * through the tree, we need to consider ms_allocator and ms_primary so
5055 * we start in the location right after where we left off, and don't
5056 * accidentally loop forever considering the same metaslabs.
5057 */
5058 search->ms_allocator = -1;
5059 search->ms_primary = B_TRUE;
5060 for (;;) {
5061 boolean_t was_active = B_FALSE;
5062
5063 mutex_enter(&mg->mg_lock);
5064
5065 if (activation_weight == METASLAB_WEIGHT_PRIMARY &&
5066 mga->mga_primary != NULL) {
5067 msp = mga->mga_primary;
5068
5069 /*
5070 * Even though we don't hold the ms_lock for the
5071 * primary metaslab, those fields should not
5072 * change while we hold the mg_lock. Thus it is
5073 * safe to make assertions on them.
5074 */
5075 ASSERT(msp->ms_primary);
5076 ASSERT3S(msp->ms_allocator, ==, allocator);
5077 ASSERT(msp->ms_loaded);
5078
5079 was_active = B_TRUE;
5080 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
5081 } else if (activation_weight == METASLAB_WEIGHT_SECONDARY &&
5082 mga->mga_secondary != NULL) {
5083 msp = mga->mga_secondary;
5084
5085 /*
5086 * See comment above about the similar assertions
5087 * for the primary metaslab.
5088 */
5089 ASSERT(!msp->ms_primary);
5090 ASSERT3S(msp->ms_allocator, ==, allocator);
5091 ASSERT(msp->ms_loaded);
5092
5093 was_active = B_TRUE;
5094 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
5095 } else {
5096 msp = find_valid_metaslab(mg, activation_weight, dva, d,
5097 asize, allocator, try_hard, zal, search,
5098 &was_active);
5099 }
5100
5101 mutex_exit(&mg->mg_lock);
5102 if (msp == NULL)
5103 break;
5104 mutex_enter(&msp->ms_lock);
5105
5106 metaslab_active_mask_verify(msp);
5107
5108 /*
5109 * This code is disabled out because of issues with
5110 * tracepoints in non-gpl kernel modules.
5111 */
5112 #if 0
5113 DTRACE_PROBE3(ms__activation__attempt,
5114 metaslab_t *, msp, uint64_t, activation_weight,
5115 boolean_t, was_active);
5116 #endif
5117
5118 /*
5119 * Ensure that the metaslab we have selected is still
5120 * capable of handling our request. It's possible that
5121 * another thread may have changed the weight while we
5122 * were blocked on the metaslab lock. We check the
5123 * active status first to see if we need to set_selected_txg
5124 * a new metaslab.
5125 */
5126 if (was_active && !(msp->ms_weight & METASLAB_ACTIVE_MASK)) {
5127 ASSERT3S(msp->ms_allocator, ==, -1);
5128 mutex_exit(&msp->ms_lock);
5129 continue;
5130 }
5131
5132 /*
5133 * If the metaslab was activated for another allocator
5134 * while we were waiting in the ms_lock above, or it's
5135 * a primary and we're seeking a secondary (or vice versa),
5136 * we go back and select a new metaslab.
5137 */
5138 if (!was_active && (msp->ms_weight & METASLAB_ACTIVE_MASK) &&
5139 (msp->ms_allocator != -1) &&
5140 (msp->ms_allocator != allocator || ((activation_weight ==
5141 METASLAB_WEIGHT_PRIMARY) != msp->ms_primary))) {
5142 ASSERT(msp->ms_loaded);
5143 ASSERT((msp->ms_weight & METASLAB_WEIGHT_CLAIM) ||
5144 msp->ms_allocator != -1);
5145 mutex_exit(&msp->ms_lock);
5146 continue;
5147 }
5148
5149 /*
5150 * This metaslab was used for claiming regions allocated
5151 * by the ZIL during pool import. Once these regions are
5152 * claimed we don't need to keep the CLAIM bit set
5153 * anymore. Passivate this metaslab to zero its activation
5154 * mask.
5155 */
5156 if (msp->ms_weight & METASLAB_WEIGHT_CLAIM &&
5157 activation_weight != METASLAB_WEIGHT_CLAIM) {
5158 ASSERT(msp->ms_loaded);
5159 ASSERT3S(msp->ms_allocator, ==, -1);
5160 metaslab_passivate(msp, msp->ms_weight &
5161 ~METASLAB_WEIGHT_CLAIM);
5162 mutex_exit(&msp->ms_lock);
5163 continue;
5164 }
5165
5166 metaslab_set_selected_txg(msp, txg);
5167
5168 int activation_error =
5169 metaslab_activate(msp, allocator, activation_weight);
5170 metaslab_active_mask_verify(msp);
5171
5172 /*
5173 * If the metaslab was activated by another thread for
5174 * another allocator or activation_weight (EBUSY), or it
5175 * failed because another metaslab was assigned as primary
5176 * for this allocator (EEXIST) we continue using this
5177 * metaslab for our allocation, rather than going on to a
5178 * worse metaslab (we waited for that metaslab to be loaded
5179 * after all).
5180 *
5181 * If the activation failed due to an I/O error or ENOSPC we
5182 * skip to the next metaslab.
5183 */
5184 boolean_t activated;
5185 if (activation_error == 0) {
5186 activated = B_TRUE;
5187 } else if (activation_error == EBUSY ||
5188 activation_error == EEXIST) {
5189 activated = B_FALSE;
5190 } else {
5191 mutex_exit(&msp->ms_lock);
5192 continue;
5193 }
5194 ASSERT(msp->ms_loaded);
5195
5196 /*
5197 * Now that we have the lock, recheck to see if we should
5198 * continue to use this metaslab for this allocation. The
5199 * the metaslab is now loaded so metaslab_should_allocate()
5200 * can accurately determine if the allocation attempt should
5201 * proceed.
5202 */
5203 if (!metaslab_should_allocate(msp, asize, try_hard)) {
5204 /* Passivate this metaslab and select a new one. */
5205 metaslab_trace_add(zal, mg, msp, asize, d,
5206 TRACE_TOO_SMALL, allocator);
5207 goto next;
5208 }
5209
5210 /*
5211 * If this metaslab is currently condensing then pick again
5212 * as we can't manipulate this metaslab until it's committed
5213 * to disk. If this metaslab is being initialized, we shouldn't
5214 * allocate from it since the allocated region might be
5215 * overwritten after allocation.
5216 */
5217 if (msp->ms_condensing) {
5218 metaslab_trace_add(zal, mg, msp, asize, d,
5219 TRACE_CONDENSING, allocator);
5220 if (activated) {
5221 metaslab_passivate(msp, msp->ms_weight &
5222 ~METASLAB_ACTIVE_MASK);
5223 }
5224 mutex_exit(&msp->ms_lock);
5225 continue;
5226 } else if (msp->ms_disabled > 0) {
5227 metaslab_trace_add(zal, mg, msp, asize, d,
5228 TRACE_DISABLED, allocator);
5229 if (activated) {
5230 metaslab_passivate(msp, msp->ms_weight &
5231 ~METASLAB_ACTIVE_MASK);
5232 }
5233 mutex_exit(&msp->ms_lock);
5234 continue;
5235 }
5236
5237 offset = metaslab_block_alloc(msp, asize, max_asize, txg,
5238 actual_asize);
5239
5240 if (offset != -1ULL) {
5241 metaslab_trace_add(zal, mg, msp, *actual_asize, d,
5242 offset, allocator);
5243 /* Proactively passivate the metaslab, if needed */
5244 if (activated)
5245 metaslab_segment_may_passivate(msp);
5246 mutex_exit(&msp->ms_lock);
5247 break;
5248 }
5249 metaslab_trace_add(zal, mg, msp, asize, d, offset, allocator);
5250 next:
5251 ASSERT(msp->ms_loaded);
5252
5253 /*
5254 * This code is disabled out because of issues with
5255 * tracepoints in non-gpl kernel modules.
5256 */
5257 #if 0
5258 DTRACE_PROBE2(ms__alloc__failure, metaslab_t *, msp,
5259 uint64_t, asize);
5260 #endif
5261
5262 /*
5263 * We were unable to allocate from this metaslab so determine
5264 * a new weight for this metaslab. The weight was last
5265 * recalculated either when we loaded it (if this is the first
5266 * TXG it's been loaded in), or the last time a txg was synced
5267 * out.
5268 */
5269 uint64_t weight;
5270 if (WEIGHT_IS_SPACEBASED(msp->ms_weight)) {
5271 metaslab_set_fragmentation(msp, B_TRUE);
5272 weight = metaslab_space_weight(msp) &
5273 ~METASLAB_ACTIVE_MASK;
5274 } else {
5275 weight = metaslab_weight_from_range_tree(msp);
5276 }
5277
5278 if (activated) {
5279 metaslab_passivate(msp, weight);
5280 } else {
5281 /*
5282 * For the case where we use the metaslab that is
5283 * active for another allocator we want to make
5284 * sure that we retain the activation mask.
5285 */
5286 weight |= msp->ms_weight & METASLAB_ACTIVE_MASK;
5287 metaslab_group_sort(mg, msp, weight);
5288 }
5289 metaslab_active_mask_verify(msp);
5290
5291 /*
5292 * We have just failed an allocation attempt, check
5293 * that metaslab_should_allocate() agrees. Otherwise,
5294 * we may end up in an infinite loop retrying the same
5295 * metaslab.
5296 */
5297 ASSERT(!metaslab_should_allocate(msp, asize, try_hard));
5298
5299 mutex_exit(&msp->ms_lock);
5300 }
5301 kmem_free(search, sizeof (*search));
5302
5303 if (offset == -1ULL) {
5304 metaslab_trace_add(zal, mg, NULL, asize, d,
5305 TRACE_GROUP_FAILURE, allocator);
5306 if (asize <= vdev_get_min_alloc(mg->mg_vd)) {
5307 /*
5308 * This metaslab group was unable to allocate
5309 * the minimum block size so it must be out of
5310 * space. Notify the allocation throttle to
5311 * skip allocation attempts to this group until
5312 * more space becomes available.
5313 */
5314 mg->mg_no_free_space = B_TRUE;
5315 }
5316 }
5317 return (offset);
5318 }
5319
5320 static boolean_t
metaslab_group_allocatable(spa_t * spa,metaslab_group_t * mg,uint64_t psize,int d,int flags,boolean_t try_hard,zio_alloc_list_t * zal,int allocator)5321 metaslab_group_allocatable(spa_t *spa, metaslab_group_t *mg, uint64_t psize,
5322 int d, int flags, boolean_t try_hard, zio_alloc_list_t *zal, int allocator)
5323 {
5324 metaslab_class_t *mc = mg->mg_class;
5325 vdev_t *vd = mg->mg_vd;
5326 boolean_t allocatable;
5327
5328 /*
5329 * Don't allocate from faulted devices.
5330 */
5331 if (try_hard)
5332 spa_config_enter(spa, SCL_ZIO, FTAG, RW_READER);
5333 allocatable = vdev_allocatable(vd);
5334 if (try_hard)
5335 spa_config_exit(spa, SCL_ZIO, FTAG);
5336 if (!allocatable) {
5337 metaslab_trace_add(zal, mg, NULL, psize, d,
5338 TRACE_NOT_ALLOCATABLE, allocator);
5339 return (B_FALSE);
5340 }
5341
5342 if (!try_hard) {
5343 /*
5344 * Avoid vdevs with too little space or too fragmented.
5345 */
5346 if (!GANG_ALLOCATION(flags) && (mg->mg_no_free_space ||
5347 (!mg->mg_allocatable && mc->mc_alloc_groups > 0))) {
5348 metaslab_trace_add(zal, mg, NULL, psize, d,
5349 TRACE_NOT_ALLOCATABLE, allocator);
5350 return (B_FALSE);
5351 }
5352
5353 /*
5354 * Avoid writing single-copy data to an unhealthy,
5355 * non-redundant vdev.
5356 */
5357 if (d == 0 && vd->vdev_state < VDEV_STATE_HEALTHY &&
5358 vd->vdev_children == 0) {
5359 metaslab_trace_add(zal, mg, NULL, psize, d,
5360 TRACE_VDEV_ERROR, allocator);
5361 return (B_FALSE);
5362 }
5363 }
5364
5365 return (B_TRUE);
5366 }
5367
5368 static int
metaslab_alloc_dva_range(spa_t * spa,metaslab_class_t * mc,uint64_t psize,uint64_t max_psize,dva_t * dva,int d,const dva_t * hintdva,uint64_t txg,int flags,zio_alloc_list_t * zal,int allocator,uint64_t * actual_psize)5369 metaslab_alloc_dva_range(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
5370 uint64_t max_psize, dva_t *dva, int d, const dva_t *hintdva, uint64_t txg,
5371 int flags, zio_alloc_list_t *zal, int allocator, uint64_t *actual_psize)
5372 {
5373 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
5374 metaslab_group_t *mg = NULL, *rotor;
5375 vdev_t *vd;
5376 boolean_t try_hard = B_FALSE;
5377
5378 ASSERT(!DVA_IS_VALID(&dva[d]));
5379
5380 /*
5381 * For testing, make some blocks above a certain size be gang blocks.
5382 * This will result in more split blocks when using device removal,
5383 * and a large number of split blocks coupled with ztest-induced
5384 * damage can result in extremely long reconstruction times. This
5385 * will also test spilling from special to normal.
5386 */
5387 if (psize >= metaslab_force_ganging &&
5388 metaslab_force_ganging_pct > 0 &&
5389 (random_in_range(100) < MIN(metaslab_force_ganging_pct, 100))) {
5390 metaslab_trace_add(zal, NULL, NULL, psize, d, TRACE_FORCE_GANG,
5391 allocator);
5392 return (SET_ERROR(ENOSPC));
5393 }
5394 if (max_psize > psize && max_psize >= metaslab_force_ganging &&
5395 metaslab_force_ganging_pct > 0 &&
5396 (random_in_range(100) < MIN(metaslab_force_ganging_pct, 100))) {
5397 max_psize = MAX((psize + max_psize) / 2,
5398 metaslab_force_ganging);
5399 }
5400 ASSERT3U(psize, <=, max_psize);
5401
5402 /*
5403 * Start at the rotor and loop through all mgs until we find something.
5404 * Note that there's no locking on mca_rotor or mca_aliquot because
5405 * nothing actually breaks if we miss a few updates -- we just won't
5406 * allocate quite as evenly. It all balances out over time.
5407 *
5408 * If we are doing ditto or log blocks, try to spread them across
5409 * consecutive vdevs. If we're forced to reuse a vdev before we've
5410 * allocated all of our ditto blocks, then try and spread them out on
5411 * that vdev as much as possible. If it turns out to not be possible,
5412 * gradually lower our standards until anything becomes acceptable.
5413 * Also, allocating on consecutive vdevs (as opposed to random vdevs)
5414 * gives us hope of containing our fault domains to something we're
5415 * able to reason about. Otherwise, any two top-level vdev failures
5416 * will guarantee the loss of data. With consecutive allocation,
5417 * only two adjacent top-level vdev failures will result in data loss.
5418 *
5419 * If we are doing gang blocks (hintdva is non-NULL), try to keep
5420 * ourselves on the same vdev as our gang block header. It makes our
5421 * fault domains something tractable.
5422 */
5423 if (hintdva && DVA_IS_VALID(&hintdva[d])) {
5424 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&hintdva[d]));
5425 mg = vdev_get_mg(vd, mc);
5426 }
5427 if (mg == NULL && d != 0) {
5428 vd = vdev_lookup_top(spa, DVA_GET_VDEV(&dva[d - 1]));
5429 mg = vdev_get_mg(vd, mc)->mg_next;
5430 }
5431 if (mg == NULL || mg->mg_class != mc || mg->mg_activation_count <= 0) {
5432 ASSERT(mca->mca_rotor != NULL);
5433 mg = mca->mca_rotor;
5434 }
5435
5436 rotor = mg;
5437 top:
5438 do {
5439 ASSERT(mg->mg_activation_count == 1);
5440 ASSERT(mg->mg_class == mc);
5441
5442 if (!metaslab_group_allocatable(spa, mg, psize, d, flags,
5443 try_hard, zal, allocator))
5444 goto next;
5445
5446 vd = mg->mg_vd;
5447 uint64_t asize = vdev_psize_to_asize_txg(vd, psize, txg);
5448 ASSERT0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
5449 uint64_t max_asize = vdev_psize_to_asize_txg(vd, max_psize,
5450 txg);
5451 ASSERT0(P2PHASE(max_asize, 1ULL << vd->vdev_ashift));
5452 uint64_t offset = metaslab_group_alloc(mg, zal, asize,
5453 max_asize, txg, dva, d, allocator, try_hard,
5454 &asize);
5455
5456 if (offset != -1ULL) {
5457 if (actual_psize)
5458 *actual_psize = vdev_asize_to_psize_txg(vd,
5459 asize, txg);
5460 metaslab_class_rotate(mg, allocator, psize, B_TRUE);
5461
5462 DVA_SET_VDEV(&dva[d], vd->vdev_id);
5463 DVA_SET_OFFSET(&dva[d], offset);
5464 DVA_SET_GANG(&dva[d],
5465 ((flags & METASLAB_GANG_HEADER) ? 1 : 0));
5466 DVA_SET_ASIZE(&dva[d], asize);
5467 return (0);
5468 }
5469 next:
5470 metaslab_class_rotate(mg, allocator, psize, B_FALSE);
5471 } while ((mg = mg->mg_next) != rotor);
5472
5473 /*
5474 * If we haven't tried hard, perhaps do so now.
5475 */
5476 if (!try_hard && (zfs_metaslab_try_hard_before_gang ||
5477 GANG_ALLOCATION(flags) || (flags & METASLAB_ZIL) != 0 ||
5478 psize <= spa->spa_min_alloc)) {
5479 METASLABSTAT_BUMP(metaslabstat_try_hard);
5480 try_hard = B_TRUE;
5481 goto top;
5482 }
5483
5484 memset(&dva[d], 0, sizeof (dva_t));
5485
5486 metaslab_trace_add(zal, rotor, NULL, psize, d, TRACE_ENOSPC, allocator);
5487 return (SET_ERROR(ENOSPC));
5488 }
5489
5490 /*
5491 * Allocate a block for the specified i/o.
5492 */
5493 int
metaslab_alloc_dva(spa_t * spa,metaslab_class_t * mc,uint64_t psize,dva_t * dva,int d,const dva_t * hintdva,uint64_t txg,int flags,zio_alloc_list_t * zal,int allocator)5494 metaslab_alloc_dva(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
5495 dva_t *dva, int d, const dva_t *hintdva, uint64_t txg, int flags,
5496 zio_alloc_list_t *zal, int allocator)
5497 {
5498 return (metaslab_alloc_dva_range(spa, mc, psize, psize, dva, d, hintdva,
5499 txg, flags, zal, allocator, NULL));
5500 }
5501
5502 void
metaslab_free_concrete(vdev_t * vd,uint64_t offset,uint64_t asize,boolean_t checkpoint)5503 metaslab_free_concrete(vdev_t *vd, uint64_t offset, uint64_t asize,
5504 boolean_t checkpoint)
5505 {
5506 metaslab_t *msp;
5507 spa_t *spa = vd->vdev_spa;
5508 int m = offset >> vd->vdev_ms_shift;
5509
5510 ASSERT(vdev_is_concrete(vd));
5511 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5512 VERIFY3U(m, <, vd->vdev_ms_count);
5513
5514 msp = vd->vdev_ms[m];
5515
5516 VERIFY(!msp->ms_condensing);
5517 VERIFY3U(offset, >=, msp->ms_start);
5518 VERIFY3U(offset + asize, <=, msp->ms_start + msp->ms_size);
5519 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5520 VERIFY0(P2PHASE(asize, 1ULL << vd->vdev_ashift));
5521
5522 metaslab_check_free_impl(vd, offset, asize);
5523
5524 mutex_enter(&msp->ms_lock);
5525 if (zfs_range_tree_is_empty(msp->ms_freeing) &&
5526 zfs_range_tree_is_empty(msp->ms_checkpointing)) {
5527 vdev_dirty(vd, VDD_METASLAB, msp, spa_syncing_txg(spa));
5528 }
5529
5530 if (checkpoint) {
5531 ASSERT(spa_has_checkpoint(spa));
5532 zfs_range_tree_add(msp->ms_checkpointing, offset, asize);
5533 } else {
5534 zfs_range_tree_add(msp->ms_freeing, offset, asize);
5535 }
5536 mutex_exit(&msp->ms_lock);
5537 }
5538
5539 void
metaslab_free_impl_cb(uint64_t inner_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)5540 metaslab_free_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5541 uint64_t size, void *arg)
5542 {
5543 (void) inner_offset;
5544 boolean_t *checkpoint = arg;
5545
5546 ASSERT3P(checkpoint, !=, NULL);
5547
5548 if (vd->vdev_ops->vdev_op_remap != NULL)
5549 vdev_indirect_mark_obsolete(vd, offset, size);
5550 else
5551 metaslab_free_impl(vd, offset, size, *checkpoint);
5552 }
5553
5554 static void
metaslab_free_impl(vdev_t * vd,uint64_t offset,uint64_t size,boolean_t checkpoint)5555 metaslab_free_impl(vdev_t *vd, uint64_t offset, uint64_t size,
5556 boolean_t checkpoint)
5557 {
5558 spa_t *spa = vd->vdev_spa;
5559
5560 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5561
5562 if (spa_syncing_txg(spa) > spa_freeze_txg(spa))
5563 return;
5564
5565 if (spa->spa_vdev_removal != NULL &&
5566 spa->spa_vdev_removal->svr_vdev_id == vd->vdev_id &&
5567 vdev_is_concrete(vd)) {
5568 /*
5569 * Note: we check if the vdev is concrete because when
5570 * we complete the removal, we first change the vdev to be
5571 * an indirect vdev (in open context), and then (in syncing
5572 * context) clear spa_vdev_removal.
5573 */
5574 free_from_removing_vdev(vd, offset, size);
5575 } else if (vd->vdev_ops->vdev_op_remap != NULL) {
5576 vdev_indirect_mark_obsolete(vd, offset, size);
5577 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5578 metaslab_free_impl_cb, &checkpoint);
5579 } else {
5580 metaslab_free_concrete(vd, offset, size, checkpoint);
5581 }
5582 }
5583
5584 typedef struct remap_blkptr_cb_arg {
5585 blkptr_t *rbca_bp;
5586 spa_remap_cb_t rbca_cb;
5587 vdev_t *rbca_remap_vd;
5588 uint64_t rbca_remap_offset;
5589 void *rbca_cb_arg;
5590 } remap_blkptr_cb_arg_t;
5591
5592 static void
remap_blkptr_cb(uint64_t inner_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)5593 remap_blkptr_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5594 uint64_t size, void *arg)
5595 {
5596 remap_blkptr_cb_arg_t *rbca = arg;
5597 blkptr_t *bp = rbca->rbca_bp;
5598
5599 /* We can not remap split blocks. */
5600 if (size != DVA_GET_ASIZE(&bp->blk_dva[0]))
5601 return;
5602 ASSERT0(inner_offset);
5603
5604 if (rbca->rbca_cb != NULL) {
5605 /*
5606 * At this point we know that we are not handling split
5607 * blocks and we invoke the callback on the previous
5608 * vdev which must be indirect.
5609 */
5610 ASSERT3P(rbca->rbca_remap_vd->vdev_ops, ==, &vdev_indirect_ops);
5611
5612 rbca->rbca_cb(rbca->rbca_remap_vd->vdev_id,
5613 rbca->rbca_remap_offset, size, rbca->rbca_cb_arg);
5614
5615 /* set up remap_blkptr_cb_arg for the next call */
5616 rbca->rbca_remap_vd = vd;
5617 rbca->rbca_remap_offset = offset;
5618 }
5619
5620 /*
5621 * The phys birth time is that of dva[0]. This ensures that we know
5622 * when each dva was written, so that resilver can determine which
5623 * blocks need to be scrubbed (i.e. those written during the time
5624 * the vdev was offline). It also ensures that the key used in
5625 * the ARC hash table is unique (i.e. dva[0] + phys_birth). If
5626 * we didn't change the phys_birth, a lookup in the ARC for a
5627 * remapped BP could find the data that was previously stored at
5628 * this vdev + offset.
5629 */
5630 vdev_t *oldvd = vdev_lookup_top(vd->vdev_spa,
5631 DVA_GET_VDEV(&bp->blk_dva[0]));
5632 vdev_indirect_births_t *vib = oldvd->vdev_indirect_births;
5633 uint64_t physical_birth = vdev_indirect_births_physbirth(vib,
5634 DVA_GET_OFFSET(&bp->blk_dva[0]), DVA_GET_ASIZE(&bp->blk_dva[0]));
5635
5636 /*
5637 * For rewritten blocks, use the old physical birth as the new logical
5638 * birth (representing when the space was allocated) and the removal
5639 * time as the new physical birth (representing when it was actually
5640 * written).
5641 */
5642 if (BP_GET_REWRITE(bp)) {
5643 uint64_t old_physical_birth = BP_GET_PHYSICAL_BIRTH(bp);
5644 ASSERT3U(old_physical_birth, <, physical_birth);
5645 BP_SET_BIRTH(bp, old_physical_birth, physical_birth);
5646 BP_SET_REWRITE(bp, 0);
5647 } else {
5648 BP_SET_PHYSICAL_BIRTH(bp, physical_birth);
5649 }
5650
5651 DVA_SET_VDEV(&bp->blk_dva[0], vd->vdev_id);
5652 DVA_SET_OFFSET(&bp->blk_dva[0], offset);
5653 }
5654
5655 /*
5656 * If the block pointer contains any indirect DVAs, modify them to refer to
5657 * concrete DVAs. Note that this will sometimes not be possible, leaving
5658 * the indirect DVA in place. This happens if the indirect DVA spans multiple
5659 * segments in the mapping (i.e. it is a "split block").
5660 *
5661 * If the BP was remapped, calls the callback on the original dva (note the
5662 * callback can be called multiple times if the original indirect DVA refers
5663 * to another indirect DVA, etc).
5664 *
5665 * Returns TRUE if the BP was remapped.
5666 */
5667 boolean_t
spa_remap_blkptr(spa_t * spa,blkptr_t * bp,spa_remap_cb_t callback,void * arg)5668 spa_remap_blkptr(spa_t *spa, blkptr_t *bp, spa_remap_cb_t callback, void *arg)
5669 {
5670 remap_blkptr_cb_arg_t rbca;
5671
5672 if (!zfs_remap_blkptr_enable)
5673 return (B_FALSE);
5674
5675 if (!spa_feature_is_enabled(spa, SPA_FEATURE_OBSOLETE_COUNTS))
5676 return (B_FALSE);
5677
5678 /*
5679 * Dedup BP's can not be remapped, because ddt_phys_select() depends
5680 * on DVA[0] being the same in the BP as in the DDT (dedup table).
5681 */
5682 if (BP_GET_DEDUP(bp))
5683 return (B_FALSE);
5684
5685 /*
5686 * Gang blocks can not be remapped, because
5687 * zio_checksum_gang_verifier() depends on the DVA[0] that's in
5688 * the BP used to read the gang block header (GBH) being the same
5689 * as the DVA[0] that we allocated for the GBH.
5690 */
5691 if (BP_IS_GANG(bp))
5692 return (B_FALSE);
5693
5694 /*
5695 * Embedded BP's have no DVA to remap.
5696 */
5697 if (BP_GET_NDVAS(bp) < 1)
5698 return (B_FALSE);
5699
5700 /*
5701 * Cloned blocks can not be remapped since BRT depends on specific
5702 * vdev id and offset in the DVA[0] for its reference counting.
5703 */
5704 if (!BP_IS_METADATA(bp) && brt_maybe_exists(spa, bp))
5705 return (B_FALSE);
5706
5707 /*
5708 * Note: we only remap dva[0]. If we remapped other dvas, we
5709 * would no longer know what their phys birth txg is.
5710 */
5711 dva_t *dva = &bp->blk_dva[0];
5712
5713 uint64_t offset = DVA_GET_OFFSET(dva);
5714 uint64_t size = DVA_GET_ASIZE(dva);
5715 vdev_t *vd = vdev_lookup_top(spa, DVA_GET_VDEV(dva));
5716
5717 if (vd->vdev_ops->vdev_op_remap == NULL)
5718 return (B_FALSE);
5719
5720 rbca.rbca_bp = bp;
5721 rbca.rbca_cb = callback;
5722 rbca.rbca_remap_vd = vd;
5723 rbca.rbca_remap_offset = offset;
5724 rbca.rbca_cb_arg = arg;
5725
5726 /*
5727 * remap_blkptr_cb() will be called in order for each level of
5728 * indirection, until a concrete vdev is reached or a split block is
5729 * encountered. old_vd and old_offset are updated within the callback
5730 * as we go from the one indirect vdev to the next one (either concrete
5731 * or indirect again) in that order.
5732 */
5733 vd->vdev_ops->vdev_op_remap(vd, offset, size, remap_blkptr_cb, &rbca);
5734
5735 /* Check if the DVA wasn't remapped because it is a split block */
5736 if (DVA_GET_VDEV(&rbca.rbca_bp->blk_dva[0]) == vd->vdev_id)
5737 return (B_FALSE);
5738
5739 return (B_TRUE);
5740 }
5741
5742 /*
5743 * Undo the allocation of a DVA which happened in the given transaction group.
5744 */
5745 void
metaslab_unalloc_dva(spa_t * spa,const dva_t * dva,uint64_t txg)5746 metaslab_unalloc_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5747 {
5748 metaslab_t *msp;
5749 vdev_t *vd;
5750 uint64_t vdev = DVA_GET_VDEV(dva);
5751 uint64_t offset = DVA_GET_OFFSET(dva);
5752 uint64_t size = DVA_GET_ASIZE(dva);
5753
5754 ASSERT(DVA_IS_VALID(dva));
5755 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5756
5757 if (txg > spa_freeze_txg(spa))
5758 return;
5759
5760 if ((vd = vdev_lookup_top(spa, vdev)) == NULL || !DVA_IS_VALID(dva) ||
5761 (offset >> vd->vdev_ms_shift) >= vd->vdev_ms_count) {
5762 zfs_panic_recover("metaslab_free_dva(): bad DVA %llu:%llu:%llu",
5763 (u_longlong_t)vdev, (u_longlong_t)offset,
5764 (u_longlong_t)size);
5765 return;
5766 }
5767
5768 ASSERT(!vd->vdev_removing);
5769 ASSERT(vdev_is_concrete(vd));
5770 ASSERT0(vd->vdev_indirect_config.vic_mapping_object);
5771 ASSERT0P(vd->vdev_indirect_mapping);
5772
5773 if (DVA_GET_GANG(dva))
5774 size = vdev_gang_header_asize(vd);
5775
5776 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5777
5778 mutex_enter(&msp->ms_lock);
5779 zfs_range_tree_remove(msp->ms_allocating[txg & TXG_MASK],
5780 offset, size);
5781 msp->ms_allocating_total -= size;
5782
5783 VERIFY(!msp->ms_condensing);
5784 VERIFY3U(offset, >=, msp->ms_start);
5785 VERIFY3U(offset + size, <=, msp->ms_start + msp->ms_size);
5786 VERIFY3U(zfs_range_tree_space(msp->ms_allocatable) + size, <=,
5787 msp->ms_size);
5788 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5789 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
5790 zfs_range_tree_add(msp->ms_allocatable, offset, size);
5791 mutex_exit(&msp->ms_lock);
5792 }
5793
5794 /*
5795 * Free the block represented by the given DVA.
5796 */
5797 void
metaslab_free_dva(spa_t * spa,const dva_t * dva,boolean_t checkpoint)5798 metaslab_free_dva(spa_t *spa, const dva_t *dva, boolean_t checkpoint)
5799 {
5800 uint64_t vdev = DVA_GET_VDEV(dva);
5801 uint64_t offset = DVA_GET_OFFSET(dva);
5802 uint64_t size = DVA_GET_ASIZE(dva);
5803 vdev_t *vd = vdev_lookup_top(spa, vdev);
5804
5805 ASSERT(DVA_IS_VALID(dva));
5806 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
5807
5808 if (DVA_GET_GANG(dva)) {
5809 size = vdev_gang_header_asize(vd);
5810 }
5811
5812 metaslab_free_impl(vd, offset, size, checkpoint);
5813 }
5814
5815 /*
5816 * Reserve some space for a future allocation. The reservation system must be
5817 * called before we call into the allocator. If there aren't enough space
5818 * available, the calling I/O will be throttled until another I/O completes and
5819 * its reservation is released. The function returns true if it was successful
5820 * in placing the reservation.
5821 */
5822 boolean_t
metaslab_class_throttle_reserve(metaslab_class_t * mc,int allocator,int copies,uint64_t io_size,boolean_t must,boolean_t * more)5823 metaslab_class_throttle_reserve(metaslab_class_t *mc, int allocator,
5824 int copies, uint64_t io_size, boolean_t must, boolean_t *more)
5825 {
5826 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
5827
5828 ASSERT(mc->mc_alloc_throttle_enabled);
5829 if (mc->mc_alloc_io_size < io_size) {
5830 mc->mc_alloc_io_size = io_size;
5831 metaslab_class_balance(mc, B_FALSE);
5832 }
5833 if (must || mca->mca_reserved <= mc->mc_alloc_max) {
5834 /*
5835 * The potential race between compare and add is covered by the
5836 * allocator lock in most cases, or irrelevant due to must set.
5837 * But even if we assume some other non-existing scenario, the
5838 * worst that can happen is few more I/Os get to allocation
5839 * earlier, that is not a problem.
5840 */
5841 int64_t delta = copies * io_size;
5842 *more = (atomic_add_64_nv(&mca->mca_reserved, delta) <=
5843 mc->mc_alloc_max);
5844 return (B_TRUE);
5845 }
5846 *more = B_FALSE;
5847 return (B_FALSE);
5848 }
5849
5850 boolean_t
metaslab_class_throttle_unreserve(metaslab_class_t * mc,int allocator,int copies,uint64_t io_size)5851 metaslab_class_throttle_unreserve(metaslab_class_t *mc, int allocator,
5852 int copies, uint64_t io_size)
5853 {
5854 metaslab_class_allocator_t *mca = &mc->mc_allocator[allocator];
5855
5856 ASSERT(mc->mc_alloc_throttle_enabled);
5857 int64_t delta = copies * io_size;
5858 return (atomic_add_64_nv(&mca->mca_reserved, -delta) <=
5859 mc->mc_alloc_max);
5860 }
5861
5862 static int
metaslab_claim_concrete(vdev_t * vd,uint64_t offset,uint64_t size,uint64_t txg)5863 metaslab_claim_concrete(vdev_t *vd, uint64_t offset, uint64_t size,
5864 uint64_t txg)
5865 {
5866 metaslab_t *msp;
5867 spa_t *spa = vd->vdev_spa;
5868 int error = 0;
5869
5870 if (offset >> vd->vdev_ms_shift >= vd->vdev_ms_count)
5871 return (SET_ERROR(ENXIO));
5872
5873 ASSERT3P(vd->vdev_ms, !=, NULL);
5874 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
5875
5876 mutex_enter(&msp->ms_lock);
5877
5878 if ((txg != 0 && spa_writeable(spa)) || !msp->ms_loaded) {
5879 error = metaslab_activate(msp, 0, METASLAB_WEIGHT_CLAIM);
5880 if (error == EBUSY) {
5881 ASSERT(msp->ms_loaded);
5882 ASSERT(msp->ms_weight & METASLAB_ACTIVE_MASK);
5883 error = 0;
5884 }
5885 }
5886
5887 if (error == 0 &&
5888 !zfs_range_tree_contains(msp->ms_allocatable, offset, size))
5889 error = SET_ERROR(ENOENT);
5890
5891 if (error || txg == 0) { /* txg == 0 indicates dry run */
5892 mutex_exit(&msp->ms_lock);
5893 return (error);
5894 }
5895
5896 VERIFY(!msp->ms_condensing);
5897 VERIFY0(P2PHASE(offset, 1ULL << vd->vdev_ashift));
5898 VERIFY0(P2PHASE(size, 1ULL << vd->vdev_ashift));
5899 VERIFY3U(zfs_range_tree_space(msp->ms_allocatable) - size, <=,
5900 msp->ms_size);
5901 zfs_range_tree_remove(msp->ms_allocatable, offset, size);
5902 zfs_range_tree_clear(msp->ms_trim, offset, size);
5903
5904 if (spa_writeable(spa)) { /* don't dirty if we're zdb(8) */
5905 metaslab_class_t *mc = msp->ms_group->mg_class;
5906 multilist_sublist_t *mls =
5907 multilist_sublist_lock_obj(&mc->mc_metaslab_txg_list, msp);
5908 if (!multilist_link_active(&msp->ms_class_txg_node)) {
5909 msp->ms_selected_txg = txg;
5910 multilist_sublist_insert_head(mls, msp);
5911 }
5912 multilist_sublist_unlock(mls);
5913
5914 if (zfs_range_tree_is_empty(msp->ms_allocating[txg & TXG_MASK]))
5915 vdev_dirty(vd, VDD_METASLAB, msp, txg);
5916 zfs_range_tree_add(msp->ms_allocating[txg & TXG_MASK],
5917 offset, size);
5918 msp->ms_allocating_total += size;
5919 }
5920
5921 mutex_exit(&msp->ms_lock);
5922
5923 return (0);
5924 }
5925
5926 typedef struct metaslab_claim_cb_arg_t {
5927 uint64_t mcca_txg;
5928 int mcca_error;
5929 } metaslab_claim_cb_arg_t;
5930
5931 static void
metaslab_claim_impl_cb(uint64_t inner_offset,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)5932 metaslab_claim_impl_cb(uint64_t inner_offset, vdev_t *vd, uint64_t offset,
5933 uint64_t size, void *arg)
5934 {
5935 (void) inner_offset;
5936 metaslab_claim_cb_arg_t *mcca_arg = arg;
5937
5938 if (mcca_arg->mcca_error == 0) {
5939 mcca_arg->mcca_error = metaslab_claim_concrete(vd, offset,
5940 size, mcca_arg->mcca_txg);
5941 }
5942 }
5943
5944 int
metaslab_claim_impl(vdev_t * vd,uint64_t offset,uint64_t size,uint64_t txg)5945 metaslab_claim_impl(vdev_t *vd, uint64_t offset, uint64_t size, uint64_t txg)
5946 {
5947 if (vd->vdev_ops->vdev_op_remap != NULL) {
5948 metaslab_claim_cb_arg_t arg;
5949
5950 /*
5951 * Only zdb(8) can claim on indirect vdevs. This is used
5952 * to detect leaks of mapped space (that are not accounted
5953 * for in the obsolete counts, spacemap, or bpobj).
5954 */
5955 ASSERT(!spa_writeable(vd->vdev_spa));
5956 arg.mcca_error = 0;
5957 arg.mcca_txg = txg;
5958
5959 vd->vdev_ops->vdev_op_remap(vd, offset, size,
5960 metaslab_claim_impl_cb, &arg);
5961
5962 if (arg.mcca_error == 0) {
5963 arg.mcca_error = metaslab_claim_concrete(vd,
5964 offset, size, txg);
5965 }
5966 return (arg.mcca_error);
5967 } else {
5968 return (metaslab_claim_concrete(vd, offset, size, txg));
5969 }
5970 }
5971
5972 /*
5973 * Intent log support: upon opening the pool after a crash, notify the SPA
5974 * of blocks that the intent log has allocated for immediate write, but
5975 * which are still considered free by the SPA because the last transaction
5976 * group didn't commit yet.
5977 */
5978 static int
metaslab_claim_dva(spa_t * spa,const dva_t * dva,uint64_t txg)5979 metaslab_claim_dva(spa_t *spa, const dva_t *dva, uint64_t txg)
5980 {
5981 uint64_t vdev = DVA_GET_VDEV(dva);
5982 uint64_t offset = DVA_GET_OFFSET(dva);
5983 uint64_t size = DVA_GET_ASIZE(dva);
5984 vdev_t *vd;
5985
5986 if ((vd = vdev_lookup_top(spa, vdev)) == NULL) {
5987 return (SET_ERROR(ENXIO));
5988 }
5989
5990 ASSERT(DVA_IS_VALID(dva));
5991
5992 if (DVA_GET_GANG(dva))
5993 size = vdev_gang_header_asize(vd);
5994
5995 return (metaslab_claim_impl(vd, offset, size, txg));
5996 }
5997
5998 int
metaslab_alloc(spa_t * spa,metaslab_class_t * mc,uint64_t psize,blkptr_t * bp,int ndvas,uint64_t txg,const blkptr_t * hintbp,int flags,zio_alloc_list_t * zal,int allocator,const void * tag)5999 metaslab_alloc(spa_t *spa, metaslab_class_t *mc, uint64_t psize, blkptr_t *bp,
6000 int ndvas, uint64_t txg, const blkptr_t *hintbp, int flags,
6001 zio_alloc_list_t *zal, int allocator, const void *tag)
6002 {
6003 return (metaslab_alloc_range(spa, mc, psize, psize, bp, ndvas, txg,
6004 hintbp, flags, zal, allocator, tag, NULL));
6005 }
6006
6007 int
metaslab_alloc_range(spa_t * spa,metaslab_class_t * mc,uint64_t psize,uint64_t max_psize,blkptr_t * bp,int ndvas,uint64_t txg,const blkptr_t * hintbp,int flags,zio_alloc_list_t * zal,int allocator,const void * tag,uint64_t * actual_psize)6008 metaslab_alloc_range(spa_t *spa, metaslab_class_t *mc, uint64_t psize,
6009 uint64_t max_psize, blkptr_t *bp, int ndvas, uint64_t txg,
6010 const blkptr_t *hintbp, int flags, zio_alloc_list_t *zal, int allocator,
6011 const void *tag, uint64_t *actual_psize)
6012 {
6013 dva_t *dva = bp->blk_dva;
6014 const dva_t *hintdva = (hintbp != NULL) ? hintbp->blk_dva : NULL;
6015 int error = 0;
6016
6017 ASSERT0(BP_GET_LOGICAL_BIRTH(bp));
6018 ASSERT0(BP_GET_RAW_PHYSICAL_BIRTH(bp));
6019
6020 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
6021
6022 if (mc->mc_allocator[allocator].mca_rotor == NULL) {
6023 /* no vdevs in this class */
6024 spa_config_exit(spa, SCL_ALLOC, FTAG);
6025 return (SET_ERROR(ENOSPC));
6026 }
6027
6028 ASSERT(ndvas > 0 && ndvas <= spa_max_replication(spa));
6029 ASSERT0(BP_GET_NDVAS(bp));
6030 ASSERT(hintbp == NULL || ndvas <= BP_GET_NDVAS(hintbp));
6031 ASSERT3P(zal, !=, NULL);
6032
6033 uint64_t smallest_psize = UINT64_MAX;
6034 for (int d = 0; d < ndvas; d++) {
6035 uint64_t cur_psize = 0;
6036 error = metaslab_alloc_dva_range(spa, mc, psize,
6037 MIN(smallest_psize, max_psize), dva, d, hintdva, txg,
6038 flags, zal, allocator, actual_psize ? &cur_psize : NULL);
6039 if (error != 0) {
6040 for (d--; d >= 0; d--) {
6041 metaslab_unalloc_dva(spa, &dva[d], txg);
6042 metaslab_group_alloc_decrement(spa,
6043 DVA_GET_VDEV(&dva[d]), allocator, flags,
6044 psize, tag);
6045 memset(&dva[d], 0, sizeof (dva_t));
6046 }
6047 spa_config_exit(spa, SCL_ALLOC, FTAG);
6048 return (error);
6049 } else {
6050 /*
6051 * Update the metaslab group's queue depth
6052 * based on the newly allocated dva.
6053 */
6054 metaslab_group_alloc_increment(spa,
6055 DVA_GET_VDEV(&dva[d]), allocator, flags, psize,
6056 tag);
6057 if (actual_psize)
6058 smallest_psize = MIN(cur_psize, smallest_psize);
6059 }
6060 }
6061 ASSERT0(error);
6062 ASSERT(BP_GET_NDVAS(bp) == ndvas);
6063 if (actual_psize)
6064 *actual_psize = smallest_psize;
6065
6066 spa_config_exit(spa, SCL_ALLOC, FTAG);
6067
6068 BP_SET_BIRTH(bp, txg, 0);
6069
6070 return (0);
6071 }
6072
6073 void
metaslab_free(spa_t * spa,const blkptr_t * bp,uint64_t txg,boolean_t now)6074 metaslab_free(spa_t *spa, const blkptr_t *bp, uint64_t txg, boolean_t now)
6075 {
6076 const dva_t *dva = bp->blk_dva;
6077 int ndvas = BP_GET_NDVAS(bp);
6078
6079 ASSERT(!BP_IS_HOLE(bp));
6080 ASSERT(!now || BP_GET_BIRTH(bp) >= spa_syncing_txg(spa));
6081
6082 /*
6083 * If we have a checkpoint for the pool we need to make sure that
6084 * the blocks that we free that are part of the checkpoint won't be
6085 * reused until the checkpoint is discarded or we revert to it.
6086 *
6087 * The checkpoint flag is passed down the metaslab_free code path
6088 * and is set whenever we want to add a block to the checkpoint's
6089 * accounting. That is, we "checkpoint" blocks that existed at the
6090 * time the checkpoint was created and are therefore referenced by
6091 * the checkpointed uberblock.
6092 *
6093 * Note that, we don't checkpoint any blocks if the current
6094 * syncing txg <= spa_checkpoint_txg. We want these frees to sync
6095 * normally as they will be referenced by the checkpointed uberblock.
6096 */
6097 boolean_t checkpoint = B_FALSE;
6098 if (BP_GET_BIRTH(bp) <= spa->spa_checkpoint_txg &&
6099 spa_syncing_txg(spa) > spa->spa_checkpoint_txg) {
6100 /*
6101 * At this point, if the block is part of the checkpoint
6102 * there is no way it was created in the current txg.
6103 */
6104 ASSERT(!now);
6105 ASSERT3U(spa_syncing_txg(spa), ==, txg);
6106 checkpoint = B_TRUE;
6107 }
6108
6109 spa_config_enter(spa, SCL_FREE, FTAG, RW_READER);
6110
6111 for (int d = 0; d < ndvas; d++) {
6112 if (now) {
6113 metaslab_unalloc_dva(spa, &dva[d], txg);
6114 } else {
6115 ASSERT3U(txg, ==, spa_syncing_txg(spa));
6116 metaslab_free_dva(spa, &dva[d], checkpoint);
6117 }
6118 }
6119
6120 spa_config_exit(spa, SCL_FREE, FTAG);
6121 }
6122
6123 int
metaslab_claim(spa_t * spa,const blkptr_t * bp,uint64_t txg)6124 metaslab_claim(spa_t *spa, const blkptr_t *bp, uint64_t txg)
6125 {
6126 const dva_t *dva = bp->blk_dva;
6127 int ndvas = BP_GET_NDVAS(bp);
6128 int error = 0;
6129
6130 ASSERT(!BP_IS_HOLE(bp));
6131
6132 if (txg != 0) {
6133 /*
6134 * First do a dry run to make sure all DVAs are claimable,
6135 * so we don't have to unwind from partial failures below.
6136 */
6137 if ((error = metaslab_claim(spa, bp, 0)) != 0)
6138 return (error);
6139 }
6140
6141 spa_config_enter(spa, SCL_ALLOC, FTAG, RW_READER);
6142
6143 for (int d = 0; d < ndvas; d++) {
6144 error = metaslab_claim_dva(spa, &dva[d], txg);
6145 if (error != 0)
6146 break;
6147 }
6148
6149 spa_config_exit(spa, SCL_ALLOC, FTAG);
6150
6151 ASSERT(error == 0 || txg == 0);
6152
6153 return (error);
6154 }
6155
6156 static void
metaslab_check_free_impl_cb(uint64_t inner,vdev_t * vd,uint64_t offset,uint64_t size,void * arg)6157 metaslab_check_free_impl_cb(uint64_t inner, vdev_t *vd, uint64_t offset,
6158 uint64_t size, void *arg)
6159 {
6160 (void) inner, (void) arg;
6161
6162 if (vd->vdev_ops == &vdev_indirect_ops)
6163 return;
6164
6165 metaslab_check_free_impl(vd, offset, size);
6166 }
6167
6168 static void
metaslab_check_free_impl(vdev_t * vd,uint64_t offset,uint64_t size)6169 metaslab_check_free_impl(vdev_t *vd, uint64_t offset, uint64_t size)
6170 {
6171 metaslab_t *msp;
6172 spa_t *spa __maybe_unused = vd->vdev_spa;
6173
6174 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
6175 return;
6176
6177 if (vd->vdev_ops->vdev_op_remap != NULL) {
6178 vd->vdev_ops->vdev_op_remap(vd, offset, size,
6179 metaslab_check_free_impl_cb, NULL);
6180 return;
6181 }
6182
6183 ASSERT(vdev_is_concrete(vd));
6184 ASSERT3U(offset >> vd->vdev_ms_shift, <, vd->vdev_ms_count);
6185 ASSERT3U(spa_config_held(spa, SCL_ALL, RW_READER), !=, 0);
6186
6187 msp = vd->vdev_ms[offset >> vd->vdev_ms_shift];
6188
6189 mutex_enter(&msp->ms_lock);
6190 if (msp->ms_loaded) {
6191 zfs_range_tree_verify_not_present(msp->ms_allocatable,
6192 offset, size);
6193 }
6194
6195 /*
6196 * Check all segments that currently exist in the freeing pipeline.
6197 *
6198 * It would intuitively make sense to also check the current allocating
6199 * tree since metaslab_unalloc_dva() exists for extents that are
6200 * allocated and freed in the same sync pass within the same txg.
6201 * Unfortunately there are places (e.g. the ZIL) where we allocate a
6202 * segment but then we free part of it within the same txg
6203 * [see zil_sync()]. Thus, we don't call zfs_range_tree_verify() in the
6204 * current allocating tree.
6205 */
6206 zfs_range_tree_verify_not_present(msp->ms_freeing, offset, size);
6207 zfs_range_tree_verify_not_present(msp->ms_checkpointing, offset, size);
6208 zfs_range_tree_verify_not_present(msp->ms_freed, offset, size);
6209 for (int j = 0; j < TXG_DEFER_SIZE; j++)
6210 zfs_range_tree_verify_not_present(msp->ms_defer[j], offset,
6211 size);
6212 zfs_range_tree_verify_not_present(msp->ms_trim, offset, size);
6213 mutex_exit(&msp->ms_lock);
6214 }
6215
6216 void
metaslab_check_free(spa_t * spa,const blkptr_t * bp)6217 metaslab_check_free(spa_t *spa, const blkptr_t *bp)
6218 {
6219 if ((zfs_flags & ZFS_DEBUG_ZIO_FREE) == 0)
6220 return;
6221
6222 spa_config_enter(spa, SCL_VDEV, FTAG, RW_READER);
6223 for (int i = 0; i < BP_GET_NDVAS(bp); i++) {
6224 uint64_t vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
6225 vdev_t *vd = vdev_lookup_top(spa, vdev);
6226 uint64_t offset = DVA_GET_OFFSET(&bp->blk_dva[i]);
6227 uint64_t size = DVA_GET_ASIZE(&bp->blk_dva[i]);
6228
6229 if (DVA_GET_GANG(&bp->blk_dva[i]))
6230 size = vdev_gang_header_asize(vd);
6231
6232 ASSERT3P(vd, !=, NULL);
6233
6234 metaslab_check_free_impl(vd, offset, size);
6235 }
6236 spa_config_exit(spa, SCL_VDEV, FTAG);
6237 }
6238
6239 static void
metaslab_group_disable_wait(metaslab_group_t * mg)6240 metaslab_group_disable_wait(metaslab_group_t *mg)
6241 {
6242 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6243 while (mg->mg_disabled_updating) {
6244 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6245 }
6246 }
6247
6248 static void
metaslab_group_disabled_increment(metaslab_group_t * mg)6249 metaslab_group_disabled_increment(metaslab_group_t *mg)
6250 {
6251 ASSERT(MUTEX_HELD(&mg->mg_ms_disabled_lock));
6252 ASSERT(mg->mg_disabled_updating);
6253
6254 while (mg->mg_ms_disabled >= max_disabled_ms) {
6255 cv_wait(&mg->mg_ms_disabled_cv, &mg->mg_ms_disabled_lock);
6256 }
6257 mg->mg_ms_disabled++;
6258 ASSERT3U(mg->mg_ms_disabled, <=, max_disabled_ms);
6259 }
6260
6261 /*
6262 * Mark the metaslab as disabled to prevent any allocations on this metaslab.
6263 * We must also track how many metaslabs are currently disabled within a
6264 * metaslab group and limit them to prevent allocation failures from
6265 * occurring because all metaslabs are disabled.
6266 */
6267 void
metaslab_disable(metaslab_t * msp)6268 metaslab_disable(metaslab_t *msp)
6269 {
6270 ASSERT(!MUTEX_HELD(&msp->ms_lock));
6271 metaslab_group_t *mg = msp->ms_group;
6272
6273 mutex_enter(&mg->mg_ms_disabled_lock);
6274
6275 /*
6276 * To keep an accurate count of how many threads have disabled
6277 * a specific metaslab group, we only allow one thread to mark
6278 * the metaslab group at a time. This ensures that the value of
6279 * ms_disabled will be accurate when we decide to mark a metaslab
6280 * group as disabled. To do this we force all other threads
6281 * to wait till the metaslab's mg_disabled_updating flag is no
6282 * longer set.
6283 */
6284 metaslab_group_disable_wait(mg);
6285 mg->mg_disabled_updating = B_TRUE;
6286 if (msp->ms_disabled == 0) {
6287 metaslab_group_disabled_increment(mg);
6288 }
6289 mutex_enter(&msp->ms_lock);
6290 msp->ms_disabled++;
6291 mutex_exit(&msp->ms_lock);
6292
6293 mg->mg_disabled_updating = B_FALSE;
6294 cv_broadcast(&mg->mg_ms_disabled_cv);
6295 mutex_exit(&mg->mg_ms_disabled_lock);
6296 }
6297
6298 void
metaslab_enable(metaslab_t * msp,boolean_t sync,boolean_t unload)6299 metaslab_enable(metaslab_t *msp, boolean_t sync, boolean_t unload)
6300 {
6301 metaslab_group_t *mg = msp->ms_group;
6302 spa_t *spa = mg->mg_vd->vdev_spa;
6303
6304 /*
6305 * Wait for the outstanding IO to be synced to prevent newly
6306 * allocated blocks from being overwritten. This used by
6307 * initialize and TRIM which are modifying unallocated space.
6308 */
6309 if (sync)
6310 txg_wait_synced(spa_get_dsl(spa), 0);
6311
6312 mutex_enter(&mg->mg_ms_disabled_lock);
6313 mutex_enter(&msp->ms_lock);
6314 if (--msp->ms_disabled == 0) {
6315 mg->mg_ms_disabled--;
6316 cv_broadcast(&mg->mg_ms_disabled_cv);
6317 if (unload)
6318 metaslab_unload(msp);
6319 }
6320 mutex_exit(&msp->ms_lock);
6321 mutex_exit(&mg->mg_ms_disabled_lock);
6322 }
6323
6324 void
metaslab_set_unflushed_dirty(metaslab_t * ms,boolean_t dirty)6325 metaslab_set_unflushed_dirty(metaslab_t *ms, boolean_t dirty)
6326 {
6327 ms->ms_unflushed_dirty = dirty;
6328 }
6329
6330 static void
metaslab_update_ondisk_flush_data(metaslab_t * ms,dmu_tx_t * tx)6331 metaslab_update_ondisk_flush_data(metaslab_t *ms, dmu_tx_t *tx)
6332 {
6333 vdev_t *vd = ms->ms_group->mg_vd;
6334 spa_t *spa = vd->vdev_spa;
6335 objset_t *mos = spa_meta_objset(spa);
6336
6337 ASSERT(spa_feature_is_active(spa, SPA_FEATURE_LOG_SPACEMAP));
6338
6339 metaslab_unflushed_phys_t entry = {
6340 .msp_unflushed_txg = metaslab_unflushed_txg(ms),
6341 };
6342 uint64_t entry_size = sizeof (entry);
6343 uint64_t entry_offset = ms->ms_id * entry_size;
6344
6345 uint64_t object = 0;
6346 int err = zap_lookup(mos, vd->vdev_top_zap,
6347 VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6348 &object);
6349 if (err == ENOENT) {
6350 object = dmu_object_alloc(mos, DMU_OTN_UINT64_METADATA,
6351 SPA_OLD_MAXBLOCKSIZE, DMU_OT_NONE, 0, tx);
6352 VERIFY0(zap_add(mos, vd->vdev_top_zap,
6353 VDEV_TOP_ZAP_MS_UNFLUSHED_PHYS_TXGS, sizeof (uint64_t), 1,
6354 &object, tx));
6355 } else {
6356 VERIFY0(err);
6357 }
6358
6359 dmu_write(spa_meta_objset(spa), object, entry_offset, entry_size,
6360 &entry, tx, DMU_READ_NO_PREFETCH);
6361 }
6362
6363 void
metaslab_set_unflushed_txg(metaslab_t * ms,uint64_t txg,dmu_tx_t * tx)6364 metaslab_set_unflushed_txg(metaslab_t *ms, uint64_t txg, dmu_tx_t *tx)
6365 {
6366 ms->ms_unflushed_txg = txg;
6367 metaslab_update_ondisk_flush_data(ms, tx);
6368 }
6369
6370 boolean_t
metaslab_unflushed_dirty(metaslab_t * ms)6371 metaslab_unflushed_dirty(metaslab_t *ms)
6372 {
6373 return (ms->ms_unflushed_dirty);
6374 }
6375
6376 uint64_t
metaslab_unflushed_txg(metaslab_t * ms)6377 metaslab_unflushed_txg(metaslab_t *ms)
6378 {
6379 return (ms->ms_unflushed_txg);
6380 }
6381
6382 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, aliquot, U64, ZMOD_RW,
6383 "Allocation granularity (a.k.a. stripe size)");
6384
6385 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_load, INT, ZMOD_RW,
6386 "Load all metaslabs when pool is first opened");
6387
6388 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, debug_unload, INT, ZMOD_RW,
6389 "Prevent metaslabs from being unloaded");
6390
6391 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, preload_enabled, INT, ZMOD_RW,
6392 "Preload potential metaslabs during reassessment");
6393
6394 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, preload_limit, UINT, ZMOD_RW,
6395 "Max number of metaslabs per group to preload");
6396
6397 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay, UINT, ZMOD_RW,
6398 "Delay in txgs after metaslab was last used before unloading");
6399
6400 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, unload_delay_ms, UINT, ZMOD_RW,
6401 "Delay in milliseconds after metaslab was last used before unloading");
6402
6403 ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, noalloc_threshold, UINT, ZMOD_RW,
6404 "Percentage of metaslab group size that should be free to make it "
6405 "eligible for allocation");
6406
6407 ZFS_MODULE_PARAM(zfs_mg, zfs_mg_, fragmentation_threshold, UINT, ZMOD_RW,
6408 "Percentage of metaslab group size that should be considered eligible "
6409 "for allocations unless all metaslab groups within the metaslab class "
6410 "have also crossed this threshold");
6411
6412 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, fragmentation_factor_enabled, INT,
6413 ZMOD_RW,
6414 "Use the fragmentation metric to prefer less fragmented metaslabs");
6415
6416 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, fragmentation_threshold, UINT,
6417 ZMOD_RW, "Fragmentation for metaslab to allow allocation");
6418
6419 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, lba_weighting_enabled, INT, ZMOD_RW,
6420 "Prefer metaslabs with lower LBAs");
6421
6422 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, bias_enabled, INT, ZMOD_RW,
6423 "Enable space-based metaslab group biasing");
6424
6425 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, perf_bias, INT, ZMOD_RW,
6426 "Enable performance-based metaslab group biasing");
6427
6428 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, segment_weight_enabled, INT,
6429 ZMOD_RW, "Enable segment-based metaslab selection");
6430
6431 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, switch_threshold, INT, ZMOD_RW,
6432 "Segment-based metaslab selection maximum buckets before switching");
6433
6434 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, force_ganging, U64, ZMOD_RW,
6435 "Blocks larger than this size are sometimes forced to be gang blocks");
6436
6437 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, force_ganging_pct, UINT, ZMOD_RW,
6438 "Percentage of large blocks that will be forced to be gang blocks");
6439
6440 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_max_search, UINT, ZMOD_RW,
6441 "Max distance (bytes) to search forward before using size tree");
6442
6443 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_use_largest_segment, INT, ZMOD_RW,
6444 "When looking in size tree, use largest segment instead of exact fit");
6445
6446 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_alloc_threshold, U64, ZMOD_RW,
6447 "Minimum size which forces the dynamic allocator to change its "
6448 "allocation strategy");
6449
6450 ZFS_MODULE_PARAM(zfs_metaslab, metaslab_, df_free_pct, UINT, ZMOD_RW,
6451 "The minimum free space, in percent, to continue allocations in a "
6452 "first-fit fashion");
6453
6454 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, max_size_cache_sec, U64,
6455 ZMOD_RW, "How long to trust the cached max chunk size of a metaslab");
6456
6457 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, mem_limit, UINT, ZMOD_RW,
6458 "Percentage of memory that can be used to store metaslab range trees");
6459
6460 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, try_hard_before_gang, INT,
6461 ZMOD_RW, "Try hard to allocate before ganging");
6462
6463 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, find_max_tries, UINT, ZMOD_RW,
6464 "Normally only consider this many of the best metaslabs in each vdev");
6465
6466 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, sm_blksz_no_log, INT, ZMOD_RW,
6467 "Block size for space map in pools with log space map disabled. "
6468 "Power of 2 greater than 4096.");
6469
6470 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, sm_blksz_with_log, INT, ZMOD_RW,
6471 "Block size for space map in pools with log space map enabled. "
6472 "Power of 2 greater than 4096.");
6473
6474 ZFS_MODULE_PARAM_CALL(zfs, zfs_, active_allocator,
6475 param_set_active_allocator, param_get_charp, ZMOD_RW,
6476 "SPA active allocator");
6477
6478 ZFS_MODULE_PARAM(zfs_metaslab, zfs_metaslab_, condense_pct, UINT, ZMOD_RW,
6479 "Condense on-disk spacemap when it is more than this many percents "
6480 "of in-memory counterpart");
6481