xref: /freebsd/sys/contrib/openzfs/include/sys/metaslab_impl.h (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
14  * Use is subject to license terms.
15  */
16 
17 /*
18  * Copyright (c) 2011, 2019 by Delphix. All rights reserved.
19  */
20 
21 #ifndef _SYS_METASLAB_IMPL_H
22 #define	_SYS_METASLAB_IMPL_H
23 
24 #include <sys/metaslab.h>
25 #include <sys/space_map.h>
26 #include <sys/range_tree.h>
27 #include <sys/vdev.h>
28 #include <sys/txg.h>
29 #include <sys/avl.h>
30 #include <sys/multilist.h>
31 
32 #ifdef	__cplusplus
33 extern "C" {
34 #endif
35 
36 #ifdef METASLAB_TRACE
37 /*
38  * Metaslab allocation tracing record.
39  */
40 typedef struct metaslab_alloc_trace {
41 	list_node_t			mat_list_node;
42 	metaslab_group_t		*mat_mg;
43 	metaslab_t			*mat_msp;
44 	uint64_t			mat_size;
45 	uint64_t			mat_weight;
46 	uint32_t			mat_dva_id;
47 	uint64_t			mat_offset;
48 	int					mat_allocator;
49 } metaslab_alloc_trace_t;
50 #endif
51 
52 /*
53  * Used by the metaslab allocation tracing facility to indicate
54  * error conditions. These errors are stored to the offset member
55  * of the metaslab_alloc_trace_t record and displayed by mdb.
56  */
57 typedef enum trace_alloc_type {
58 	TRACE_ALLOC_FAILURE	= -1ULL,
59 	TRACE_TOO_SMALL		= -2ULL,
60 	TRACE_FORCE_GANG	= -3ULL,
61 	TRACE_NOT_ALLOCATABLE	= -4ULL,
62 	TRACE_GROUP_FAILURE	= -5ULL,
63 	TRACE_ENOSPC		= -6ULL,
64 	TRACE_CONDENSING	= -7ULL,
65 	TRACE_VDEV_ERROR	= -8ULL,
66 	TRACE_DISABLED		= -9ULL,
67 } trace_alloc_type_t;
68 
69 #define	METASLAB_WEIGHT_PRIMARY		(1ULL << 63)
70 #define	METASLAB_WEIGHT_SECONDARY	(1ULL << 62)
71 #define	METASLAB_WEIGHT_CLAIM		(1ULL << 61)
72 #define	METASLAB_WEIGHT_TYPE		(1ULL << 60)
73 #define	METASLAB_ACTIVE_MASK		\
74 	(METASLAB_WEIGHT_PRIMARY | METASLAB_WEIGHT_SECONDARY | \
75 	METASLAB_WEIGHT_CLAIM)
76 
77 /*
78  * The metaslab weight is used to encode the amount of free space in a
79  * metaslab, such that the "best" metaslab appears first when sorting the
80  * metaslabs by weight. The weight (and therefore the "best" metaslab) can
81  * be determined in two different ways: by computing a weighted sum of all
82  * the free space in the metaslab (a space based weight) or by counting only
83  * the free segments of the largest size (a segment based weight). We prefer
84  * the segment based weight because it reflects how the free space is
85  * comprised, but we cannot always use it -- legacy pools do not have the
86  * space map histogram information necessary to determine the largest
87  * contiguous regions. Pools that have the space map histogram determine
88  * the segment weight by looking at each bucket in the histogram and
89  * determining the free space whose size in bytes is in the range:
90  *	[2^i, 2^(i+1))
91  * We then encode the largest index, i, that contains regions into the
92  * segment-weighted value.
93  *
94  * Space-based weight:
95  *
96  *      64      56      48      40      32      24      16      8       0
97  *      +-------+-------+-------+-------+-------+-------+-------+-------+
98  *      |PSC1|                  weighted-free space                     |
99  *      +-------+-------+-------+-------+-------+-------+-------+-------+
100  *
101  *	PS - indicates primary and secondary activation
102  *	C - indicates activation for claimed block zio
103  *	space - the fragmentation-weighted space
104  *
105  * Segment-based weight:
106  *
107  *      64      56      48      40      32      24      16      8       0
108  *      +-------+-------+-------+-------+-------+-------+-------+-------+
109  *      |PSC0| idx|            count of segments in region              |
110  *      +-------+-------+-------+-------+-------+-------+-------+-------+
111  *
112  *	PS - indicates primary and secondary activation
113  *	C - indicates activation for claimed block zio
114  *	idx - index for the highest bucket in the histogram
115  *	count - number of segments in the specified bucket
116  */
117 #define	WEIGHT_GET_ACTIVE(weight)		BF64_GET((weight), 61, 3)
118 #define	WEIGHT_SET_ACTIVE(weight, x)		BF64_SET((weight), 61, 3, x)
119 
120 #define	WEIGHT_IS_SPACEBASED(weight)		\
121 	((weight) == 0 || BF64_GET((weight), 60, 1))
122 #define	WEIGHT_SET_SPACEBASED(weight)		BF64_SET((weight), 60, 1, 1)
123 
124 /*
125  * These macros are only applicable to segment-based weighting.
126  */
127 #define	WEIGHT_GET_INDEX(weight)		BF64_GET((weight), 54, 6)
128 #define	WEIGHT_SET_INDEX(weight, x)		BF64_SET((weight), 54, 6, x)
129 #define	WEIGHT_GET_COUNT(weight)		BF64_GET((weight), 0, 54)
130 #define	WEIGHT_SET_COUNT(weight, x)		BF64_SET((weight), 0, 54, x)
131 
132 /*
133  * Per-allocator data structure.
134  */
135 typedef struct metaslab_class_allocator {
136 	kmutex_t		mca_lock;
137 	avl_tree_t		mca_tree;
138 
139 	metaslab_group_t	*mca_rotor;
140 	uint64_t		mca_aliquot;
141 
142 	/*
143 	 * The allocation throttle works on a reservation system. Whenever
144 	 * an asynchronous zio wants to perform an allocation it must
145 	 * first reserve the number of bytes that it wants to allocate.
146 	 * If there aren't sufficient slots available for the pending zio
147 	 * then that I/O is throttled until more slots free up. The current
148 	 * size of reserved allocations is maintained by mca_reserved.
149 	 * The maximum total size of reserved allocations is determined by
150 	 * mc_alloc_max in the metaslab_class_t.  Gang blocks are allowed
151 	 * to reserve for their headers even if we've reached the maximum.
152 	 */
153 	uint64_t		mca_reserved;
154 } ____cacheline_aligned metaslab_class_allocator_t;
155 
156 /*
157  * A metaslab class encompasses a category of allocatable top-level vdevs.
158  * Each top-level vdev is associated with a metaslab group which defines
159  * the allocatable region for that vdev. Examples of these categories include
160  * "normal" for data block allocations (i.e. main pool allocations) or "log"
161  * for allocations designated for intent log devices (i.e. slog devices).
162  * When a block allocation is requested from the SPA it is associated with a
163  * metaslab_class_t, and only top-level vdevs (i.e. metaslab groups) belonging
164  * to the class can be used to satisfy that request. Allocations are done
165  * by traversing the metaslab groups that are linked off of the mca_rotor field.
166  * This rotor points to the next metaslab group where allocations will be
167  * attempted. Allocating a block is a 3 step process -- select the metaslab
168  * group, select the metaslab, and then allocate the block. The metaslab
169  * class defines the low-level block allocator that will be used as the
170  * final step in allocation. These allocators are pluggable allowing each class
171  * to use a block allocator that best suits that class.
172  */
173 struct metaslab_class {
174 	kmutex_t		mc_lock;
175 	spa_t			*mc_spa;
176 	const char		*mc_name;
177 	const metaslab_ops_t	*mc_ops;
178 
179 	/*
180 	 * Track the number of metaslab groups that have been initialized
181 	 * and can accept allocations. An initialized metaslab group is
182 	 * one has been completely added to the config (i.e. we have
183 	 * updated the MOS config and the space has been added to the pool).
184 	 */
185 	uint64_t		mc_groups;
186 
187 	boolean_t		mc_is_log;
188 	boolean_t		mc_alloc_throttle_enabled;
189 	uint64_t		mc_alloc_io_size;
190 	uint64_t		mc_alloc_max;
191 
192 	uint64_t		mc_alloc_groups; /* # of allocatable groups */
193 
194 	uint64_t		mc_alloc;	/* allocated space */
195 	uint64_t		mc_dalloc;	/* deflated allocated space */
196 	uint64_t		mc_deferred;	/* deferred frees */
197 	uint64_t		mc_ddeferred;	/* deflated deferred frees */
198 	uint64_t		mc_space;	/* total space (alloc + free) */
199 	uint64_t		mc_dspace;	/* deflated total space */
200 	uint64_t		mc_histogram[ZFS_RANGE_TREE_HISTOGRAM_SIZE];
201 
202 	/*
203 	 * List of all loaded metaslabs in the class, sorted in order of most
204 	 * recent use.
205 	 */
206 	multilist_t		mc_metaslab_txg_list;
207 
208 	metaslab_class_allocator_t	mc_allocator[];
209 };
210 
211 /*
212  * Per-allocator data structure.
213  */
214 typedef struct metaslab_group_allocator {
215 	zfs_refcount_t	mga_queue_depth;
216 	metaslab_t	*mga_primary;
217 	metaslab_t	*mga_secondary;
218 } ____cacheline_aligned metaslab_group_allocator_t;
219 
220 /*
221  * Metaslab groups encapsulate all the allocatable regions (i.e. metaslabs)
222  * of a top-level vdev. They are linked together to form a circular linked
223  * list and can belong to only one metaslab class. Metaslab groups may become
224  * ineligible for allocations for a number of reasons such as limited free
225  * space, fragmentation, or going offline. When this happens the allocator will
226  * simply find the next metaslab group in the linked list and attempt
227  * to allocate from that group instead.
228  */
229 struct metaslab_group {
230 	kmutex_t		mg_lock;
231 	avl_tree_t		mg_metaslab_tree;
232 	uint64_t		mg_aliquot;
233 	uint64_t		mg_queue_target;
234 	boolean_t		mg_allocatable;		/* can we allocate? */
235 	uint64_t		mg_ms_ready;
236 
237 	/*
238 	 * A metaslab group is considered to be initialized only after
239 	 * we have updated the MOS config and added the space to the pool.
240 	 * We only allow allocation attempts to a metaslab group if it
241 	 * has been initialized.
242 	 */
243 	boolean_t		mg_initialized;
244 
245 	int64_t			mg_activation_count;
246 	metaslab_class_t	*mg_class;
247 	vdev_t			*mg_vd;
248 	metaslab_group_t	*mg_prev;
249 	metaslab_group_t	*mg_next;
250 
251 	/*
252 	 * A metalab group that can no longer allocate the minimum block
253 	 * size will set mg_no_free_space. Once a metaslab group is out
254 	 * of space then its share of work must be distributed to other
255 	 * groups.
256 	 */
257 	boolean_t		mg_no_free_space;
258 
259 	uint64_t		mg_fragmentation;
260 	uint64_t		mg_histogram[ZFS_RANGE_TREE_HISTOGRAM_SIZE];
261 
262 	int			mg_ms_disabled;
263 	boolean_t		mg_disabled_updating;
264 	kmutex_t		mg_ms_disabled_lock;
265 	kcondvar_t		mg_ms_disabled_cv;
266 
267 	metaslab_group_allocator_t	mg_allocator[];
268 };
269 
270 /*
271  * This value defines the number of elements in the ms_lbas array. The value
272  * of 64 was chosen as it covers all power of 2 buckets up to UINT64_MAX.
273  * This is the equivalent of highbit(UINT64_MAX).
274  */
275 #define	MAX_LBAS	64
276 
277 /*
278  * Each metaslab maintains a set of in-core trees to track metaslab
279  * operations.  The in-core free tree (ms_allocatable) contains the list of
280  * free segments which are eligible for allocation.  As blocks are
281  * allocated, the allocated segments are removed from the ms_allocatable and
282  * added to a per txg allocation tree (ms_allocating).  As blocks are
283  * freed, they are added to the free tree (ms_freeing).  These trees
284  * allow us to process all allocations and frees in syncing context
285  * where it is safe to update the on-disk space maps.  An additional set
286  * of in-core trees is maintained to track deferred frees
287  * (ms_defer).  Once a block is freed it will move from the
288  * ms_freed to the ms_defer tree.  A deferred free means that a block
289  * has been freed but cannot be used by the pool until TXG_DEFER_SIZE
290  * transactions groups later.  For example, a block that is freed in txg
291  * 50 will not be available for reallocation until txg 52 (50 +
292  * TXG_DEFER_SIZE).  This provides a safety net for uberblock rollback.
293  * A pool could be safely rolled back TXG_DEFERS_SIZE transactions
294  * groups and ensure that no block has been reallocated.
295  *
296  * The simplified transition diagram looks like this:
297  *
298  *
299  *      ALLOCATE
300  *         |
301  *         V
302  *    free segment (ms_allocatable) -> ms_allocating[4] -> (write to space map)
303  *         ^
304  *         |                        ms_freeing <--- FREE
305  *         |                             |
306  *         |                             v
307  *         |                         ms_freed
308  *         |                             |
309  *         +-------- ms_defer[2] <-------+-------> (write to space map)
310  *
311  *
312  * Each metaslab's space is tracked in a single space map in the MOS,
313  * which is only updated in syncing context.  Each time we sync a txg,
314  * we append the allocs and frees from that txg to the space map.  The
315  * pool space is only updated once all metaslabs have finished syncing.
316  *
317  * To load the in-core free tree we read the space map from disk.  This
318  * object contains a series of alloc and free records that are combined
319  * to make up the list of all free segments in this metaslab.  These
320  * segments are represented in-core by the ms_allocatable and are stored
321  * in an AVL tree.
322  *
323  * As the space map grows (as a result of the appends) it will
324  * eventually become space-inefficient.  When the metaslab's in-core
325  * free tree is zfs_metaslab_condense_pct/100 times the size of the minimal
326  * on-disk representation, we rewrite it in its minimized form.  If a
327  * metaslab needs to condense then we must set the ms_condensing flag to
328  * ensure that allocations are not performed on the metaslab that is
329  * being written.
330  */
331 struct metaslab {
332 	/*
333 	 * This is the main lock of the metaslab and its purpose is to
334 	 * coordinate our allocations and frees [e.g., metaslab_block_alloc(),
335 	 * metaslab_free_concrete(), ..etc] with our various syncing
336 	 * procedures [e.g., metaslab_sync(), metaslab_sync_done(), ..etc].
337 	 *
338 	 * The lock is also used during some miscellaneous operations like
339 	 * using the metaslab's histogram for the metaslab group's histogram
340 	 * aggregation, or marking the metaslab for initialization.
341 	 */
342 	kmutex_t	ms_lock;
343 
344 	/*
345 	 * Acquired together with the ms_lock whenever we expect to
346 	 * write to metaslab data on-disk (i.e flushing entries to
347 	 * the metaslab's space map). It helps coordinate readers of
348 	 * the metaslab's space map [see spa_vdev_remove_thread()]
349 	 * with writers [see metaslab_sync() or metaslab_flush()].
350 	 *
351 	 * Note that metaslab_load(), even though a reader, uses
352 	 * a completely different mechanism to deal with the reading
353 	 * of the metaslab's space map based on ms_synced_length. That
354 	 * said, the function still uses the ms_sync_lock after it
355 	 * has read the ms_sm [see relevant comment in metaslab_load()
356 	 * as to why].
357 	 */
358 	kmutex_t	ms_sync_lock;
359 
360 	kcondvar_t	ms_load_cv;
361 	space_map_t	*ms_sm;
362 	uint64_t	ms_id;
363 	uint64_t	ms_start;
364 	uint64_t	ms_size;
365 	uint64_t	ms_fragmentation;
366 
367 	zfs_range_tree_t	*ms_allocating[TXG_SIZE];
368 	zfs_range_tree_t	*ms_allocatable;
369 	uint64_t	ms_allocated_this_txg;
370 	uint64_t	ms_allocating_total;
371 
372 	/*
373 	 * The following range trees are accessed only from syncing context.
374 	 * ms_free*tree only have entries while syncing, and are empty
375 	 * between syncs.
376 	 */
377 	zfs_range_tree_t	*ms_freeing;	/* to free this syncing txg */
378 	/* already freed this syncing txg */
379 	zfs_range_tree_t	*ms_freed;
380 	zfs_range_tree_t	*ms_defer[TXG_DEFER_SIZE];
381 	/* to add to the checkpoint */
382 	zfs_range_tree_t	*ms_checkpointing;
383 
384 	/*
385 	 * The ms_trim tree is the set of allocatable segments which are
386 	 * eligible for trimming. (When the metaslab is loaded, it's a
387 	 * subset of ms_allocatable.)  It's kept in-core as long as the
388 	 * autotrim property is set and is not vacated when the metaslab
389 	 * is unloaded.  Its purpose is to aggregate freed ranges to
390 	 * facilitate efficient trimming.
391 	 */
392 	zfs_range_tree_t	*ms_trim;
393 
394 	boolean_t	ms_condensing;	/* condensing? */
395 	boolean_t	ms_condense_wanted;
396 
397 	/*
398 	 * The number of consumers which have disabled the metaslab.
399 	 */
400 	uint64_t	ms_disabled;
401 
402 	/*
403 	 * We must always hold the ms_lock when modifying ms_loaded
404 	 * and ms_loading.
405 	 */
406 	boolean_t	ms_loaded;
407 	boolean_t	ms_loading;
408 	kcondvar_t	ms_flush_cv;
409 	boolean_t	ms_flushing;
410 
411 	/*
412 	 * The following histograms count entries that are in the
413 	 * metaslab's space map (and its histogram) but are not in
414 	 * ms_allocatable yet, because they are in ms_freed, ms_freeing,
415 	 * or ms_defer[].
416 	 *
417 	 * When the metaslab is not loaded, its ms_weight needs to
418 	 * reflect what is allocatable (i.e. what will be part of
419 	 * ms_allocatable if it is loaded).  The weight is computed from
420 	 * the spacemap histogram, but that includes ranges that are
421 	 * not yet allocatable (because they are in ms_freed,
422 	 * ms_freeing, or ms_defer[]).  Therefore, when calculating the
423 	 * weight, we need to remove those ranges.
424 	 *
425 	 * The ranges in the ms_freed and ms_defer[] range trees are all
426 	 * present in the spacemap.  However, the spacemap may have
427 	 * multiple entries to represent a contiguous range, because it
428 	 * is written across multiple sync passes, but the changes of
429 	 * all sync passes are consolidated into the range trees.
430 	 * Adjacent ranges that are freed in different sync passes of
431 	 * one txg will be represented separately (as 2 or more entries)
432 	 * in the space map (and its histogram), but these adjacent
433 	 * ranges will be consolidated (represented as one entry) in the
434 	 * ms_freed/ms_defer[] range trees (and their histograms).
435 	 *
436 	 * When calculating the weight, we can not simply subtract the
437 	 * range trees' histograms from the spacemap's histogram,
438 	 * because the range trees' histograms may have entries in
439 	 * higher buckets than the spacemap, due to consolidation.
440 	 * Instead we must subtract the exact entries that were added to
441 	 * the spacemap's histogram.  ms_synchist and ms_deferhist[]
442 	 * represent these exact entries, so we can subtract them from
443 	 * the spacemap's histogram when calculating ms_weight.
444 	 *
445 	 * ms_synchist represents the same ranges as ms_freeing +
446 	 * ms_freed, but without consolidation across sync passes.
447 	 *
448 	 * ms_deferhist[i] represents the same ranges as ms_defer[i],
449 	 * but without consolidation across sync passes.
450 	 */
451 	uint64_t	ms_synchist[SPACE_MAP_HISTOGRAM_SIZE];
452 	uint64_t	ms_deferhist[TXG_DEFER_SIZE][SPACE_MAP_HISTOGRAM_SIZE];
453 
454 	/*
455 	 * Tracks the exact amount of allocated space of this metaslab
456 	 * (and specifically the metaslab's space map) up to the most
457 	 * recently completed sync pass [see usage in metaslab_sync()].
458 	 */
459 	uint64_t	ms_allocated_space;
460 	int64_t		ms_deferspace;	/* sum of ms_defermap[] space	*/
461 	uint64_t	ms_weight;	/* weight vs. others in group	*/
462 	uint64_t	ms_activation_weight;	/* activation weight	*/
463 
464 	/*
465 	 * Track of whenever a metaslab is selected for loading or allocation.
466 	 * We use this value to determine how long the metaslab should
467 	 * stay cached.
468 	 */
469 	uint64_t	ms_selected_txg;
470 	/*
471 	 * ms_load/unload_time can be used for performance monitoring
472 	 * (e.g. by dtrace or mdb).
473 	 */
474 	hrtime_t	ms_load_time;	/* time last loaded */
475 	hrtime_t	ms_unload_time;	/* time last unloaded */
476 	uint64_t	ms_selected_time; /* time last allocated from (secs) */
477 
478 	uint64_t	ms_alloc_txg;	/* last successful alloc (debug only) */
479 	uint64_t	ms_max_size;	/* maximum allocatable size	*/
480 
481 	/*
482 	 * -1 if it's not active in an allocator, otherwise set to the allocator
483 	 * this metaslab is active for.
484 	 */
485 	int		ms_allocator;
486 	boolean_t	ms_primary; /* Only valid if ms_allocator is not -1 */
487 
488 	/*
489 	 * The metaslab block allocators can optionally use a size-ordered
490 	 * range tree and/or an array of LBAs. Not all allocators use
491 	 * this functionality. The ms_allocatable_by_size should always
492 	 * contain the same number of segments as the ms_allocatable. The
493 	 * only difference is that the ms_allocatable_by_size is ordered by
494 	 * segment sizes.
495 	 */
496 	zfs_btree_t		ms_allocatable_by_size;
497 	zfs_btree_t		ms_unflushed_frees_by_size;
498 	uint64_t	ms_lbas[MAX_LBAS];
499 
500 	metaslab_group_t *ms_group;	/* metaslab group		*/
501 	avl_node_t	ms_group_node;	/* node in metaslab group tree	*/
502 	txg_node_t	ms_txg_node;	/* per-txg dirty metaslab links	*/
503 	avl_node_t	ms_spa_txg_node; /* node in spa_metaslabs_by_txg */
504 	/*
505 	 * Node in metaslab class's selected txg list
506 	 */
507 	multilist_node_t	ms_class_txg_node;
508 
509 	/*
510 	 * Allocs and frees that are committed to the vdev log spacemap but
511 	 * not yet to this metaslab's spacemap.
512 	 */
513 	zfs_range_tree_t	*ms_unflushed_allocs;
514 	zfs_range_tree_t	*ms_unflushed_frees;
515 
516 	/*
517 	 * We have flushed entries up to but not including this TXG. In
518 	 * other words, all changes from this TXG and onward should not
519 	 * be in this metaslab's space map and must be read from the
520 	 * log space maps.
521 	 */
522 	uint64_t	ms_unflushed_txg;
523 	boolean_t	ms_unflushed_dirty;
524 
525 	/* updated every time we are done syncing the metaslab's space map */
526 	uint64_t	ms_synced_length;
527 
528 	boolean_t	ms_new;
529 };
530 
531 typedef struct metaslab_unflushed_phys {
532 	/* on-disk counterpart of ms_unflushed_txg */
533 	uint64_t	msp_unflushed_txg;
534 } metaslab_unflushed_phys_t;
535 
536 char *metaslab_rt_name(metaslab_group_t *, metaslab_t *, const char *);
537 
538 #ifdef	__cplusplus
539 }
540 #endif
541 
542 #endif	/* _SYS_METASLAB_IMPL_H */
543