xref: /freebsd/sys/contrib/openzfs/module/zfs/space_map.c (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  * Copyright (c) 2012, 2019 by Delphix. All rights reserved.
18  */
19 
20 #include <sys/zfs_context.h>
21 #include <sys/spa.h>
22 #include <sys/dmu.h>
23 #include <sys/dmu_tx.h>
24 #include <sys/dnode.h>
25 #include <sys/dsl_pool.h>
26 #include <sys/zio.h>
27 #include <sys/space_map.h>
28 #include <sys/zfeature.h>
29 
30 /*
31  * Note on space map block size:
32  *
33  * The data for a given space map can be kept on blocks of any size.
34  * Larger blocks entail fewer I/O operations, but they also cause the
35  * DMU to keep more data in-core, and also to waste more I/O bandwidth
36  * when only a few blocks have changed since the last transaction group.
37  */
38 
39 /*
40  * Enabled whenever we want to stress test the use of double-word
41  * space map entries.
42  */
43 boolean_t zfs_force_some_double_word_sm_entries = B_FALSE;
44 
45 /*
46  * Override the default indirect block size of 128K, instead use 16K for
47  * spacemaps (2^14 bytes).  This dramatically reduces write inflation since
48  * appending to a spacemap typically has to write one data block (4KB) and one
49  * or two indirect blocks (16K-32K, rather than 128K).
50  */
51 int space_map_ibs = 14;
52 
53 boolean_t
sm_entry_is_debug(uint64_t e)54 sm_entry_is_debug(uint64_t e)
55 {
56 	return (SM_PREFIX_DECODE(e) == SM_DEBUG_PREFIX);
57 }
58 
59 boolean_t
sm_entry_is_single_word(uint64_t e)60 sm_entry_is_single_word(uint64_t e)
61 {
62 	uint8_t prefix = SM_PREFIX_DECODE(e);
63 	return (prefix != SM_DEBUG_PREFIX && prefix != SM2_PREFIX);
64 }
65 
66 boolean_t
sm_entry_is_double_word(uint64_t e)67 sm_entry_is_double_word(uint64_t e)
68 {
69 	return (SM_PREFIX_DECODE(e) == SM2_PREFIX);
70 }
71 
72 /*
73  * Iterate through the space map, invoking the callback on each (non-debug)
74  * space map entry. Stop after reading 'end' bytes of the space map.
75  */
76 int
space_map_iterate(space_map_t * sm,uint64_t end,sm_cb_t callback,void * arg)77 space_map_iterate(space_map_t *sm, uint64_t end, sm_cb_t callback, void *arg)
78 {
79 	uint64_t blksz = sm->sm_blksz;
80 
81 	ASSERT3U(blksz, !=, 0);
82 	ASSERT3U(end, <=, space_map_length(sm));
83 	ASSERT0(P2PHASE(end, sizeof (uint64_t)));
84 
85 	dmu_prefetch_stream(sm->sm_os, space_map_object(sm), 0, end, B_FALSE);
86 
87 	int error = 0;
88 	uint64_t txg = 0, sync_pass = 0;
89 	for (uint64_t block_base = 0; block_base < end && error == 0;
90 	    block_base += blksz) {
91 		dmu_buf_t *db;
92 		error = dmu_buf_hold(sm->sm_os, space_map_object(sm),
93 		    block_base, FTAG, &db, DMU_READ_PREFETCH);
94 		if (error != 0)
95 			return (error);
96 
97 		uint64_t *block_start = db->db_data;
98 		uint64_t block_length = MIN(end - block_base, blksz);
99 		uint64_t *block_end = block_start +
100 		    (block_length / sizeof (uint64_t));
101 
102 		VERIFY0(P2PHASE(block_length, sizeof (uint64_t)));
103 		VERIFY3U(block_length, !=, 0);
104 		ASSERT3U(blksz, ==, db->db_size);
105 
106 		for (uint64_t *block_cursor = block_start;
107 		    block_cursor < block_end && error == 0; block_cursor++) {
108 			uint64_t e = *block_cursor;
109 
110 			if (sm_entry_is_debug(e)) {
111 				/*
112 				 * Debug entries are only needed to record the
113 				 * current TXG and sync pass if available.
114 				 *
115 				 * Note though that sometimes there can be
116 				 * debug entries that are used as padding
117 				 * at the end of space map blocks in-order
118 				 * to not split a double-word entry in the
119 				 * middle between two blocks. These entries
120 				 * have their TXG field set to 0 and we
121 				 * skip them without recording the TXG.
122 				 * [see comment in space_map_write_seg()]
123 				 */
124 				uint64_t e_txg = SM_DEBUG_TXG_DECODE(e);
125 				if (e_txg != 0) {
126 					txg = e_txg;
127 					sync_pass = SM_DEBUG_SYNCPASS_DECODE(e);
128 				} else {
129 					ASSERT0(SM_DEBUG_SYNCPASS_DECODE(e));
130 				}
131 				continue;
132 			}
133 
134 			uint64_t raw_offset, raw_run, vdev_id;
135 			maptype_t type;
136 			if (sm_entry_is_single_word(e)) {
137 				type = SM_TYPE_DECODE(e);
138 				vdev_id = SM_NO_VDEVID;
139 				raw_offset = SM_OFFSET_DECODE(e);
140 				raw_run = SM_RUN_DECODE(e);
141 			} else {
142 				/* it is a two-word entry */
143 				ASSERT(sm_entry_is_double_word(e));
144 				raw_run = SM2_RUN_DECODE(e);
145 				vdev_id = SM2_VDEV_DECODE(e);
146 
147 				/* move on to the second word */
148 				block_cursor++;
149 				e = *block_cursor;
150 				VERIFY3P(block_cursor, <=, block_end);
151 
152 				type = SM2_TYPE_DECODE(e);
153 				raw_offset = SM2_OFFSET_DECODE(e);
154 			}
155 
156 			uint64_t entry_offset = (raw_offset << sm->sm_shift) +
157 			    sm->sm_start;
158 			uint64_t entry_run = raw_run << sm->sm_shift;
159 
160 			VERIFY0(P2PHASE(entry_offset, 1ULL << sm->sm_shift));
161 			VERIFY0(P2PHASE(entry_run, 1ULL << sm->sm_shift));
162 			ASSERT3U(entry_offset, >=, sm->sm_start);
163 			ASSERT3U(entry_offset, <, sm->sm_start + sm->sm_size);
164 			ASSERT3U(entry_run, <=, sm->sm_size);
165 			ASSERT3U(entry_offset + entry_run, <=,
166 			    sm->sm_start + sm->sm_size);
167 
168 			space_map_entry_t sme = {
169 			    .sme_type = type,
170 			    .sme_vdev = vdev_id,
171 			    .sme_offset = entry_offset,
172 			    .sme_run = entry_run,
173 			    .sme_txg = txg,
174 			    .sme_sync_pass = sync_pass
175 			};
176 			error = callback(&sme, arg);
177 		}
178 		dmu_buf_rele(db, FTAG);
179 	}
180 	return (error);
181 }
182 
183 /*
184  * Reads the entries from the last block of the space map into
185  * buf in reverse order. Populates nwords with number of words
186  * in the last block.
187  *
188  * Refer to block comment within space_map_incremental_destroy()
189  * to understand why this function is needed.
190  */
191 static int
space_map_reversed_last_block_entries(space_map_t * sm,uint64_t * buf,uint64_t bufsz,uint64_t * nwords)192 space_map_reversed_last_block_entries(space_map_t *sm, uint64_t *buf,
193     uint64_t bufsz, uint64_t *nwords)
194 {
195 	int error = 0;
196 	dmu_buf_t *db;
197 
198 	/*
199 	 * Find the offset of the last word in the space map and use
200 	 * that to read the last block of the space map with
201 	 * dmu_buf_hold().
202 	 */
203 	uint64_t last_word_offset =
204 	    sm->sm_phys->smp_length - sizeof (uint64_t);
205 	error = dmu_buf_hold(sm->sm_os, space_map_object(sm), last_word_offset,
206 	    FTAG, &db, DMU_READ_NO_PREFETCH);
207 	if (error != 0)
208 		return (error);
209 
210 	ASSERT3U(sm->sm_object, ==, db->db_object);
211 	ASSERT3U(sm->sm_blksz, ==, db->db_size);
212 	ASSERT3U(bufsz, >=, db->db_size);
213 	ASSERT(nwords != NULL);
214 
215 	uint64_t *words = db->db_data;
216 	*nwords =
217 	    (sm->sm_phys->smp_length - db->db_offset) / sizeof (uint64_t);
218 
219 	ASSERT3U(*nwords, <=, bufsz / sizeof (uint64_t));
220 
221 	uint64_t n = *nwords;
222 	uint64_t j = n - 1;
223 	for (uint64_t i = 0; i < n; i++) {
224 		uint64_t entry = words[i];
225 		if (sm_entry_is_double_word(entry)) {
226 			/*
227 			 * Since we are populating the buffer backwards
228 			 * we have to be extra careful and add the two
229 			 * words of the double-word entry in the right
230 			 * order.
231 			 */
232 			ASSERT3U(j, >, 0);
233 			buf[j - 1] = entry;
234 
235 			i++;
236 			ASSERT3U(i, <, n);
237 			entry = words[i];
238 			buf[j] = entry;
239 			j -= 2;
240 		} else {
241 			ASSERT(sm_entry_is_debug(entry) ||
242 			    sm_entry_is_single_word(entry));
243 			buf[j] = entry;
244 			j--;
245 		}
246 	}
247 
248 	/*
249 	 * Assert that we wrote backwards all the
250 	 * way to the beginning of the buffer.
251 	 */
252 	ASSERT3S(j, ==, -1);
253 
254 	dmu_buf_rele(db, FTAG);
255 	return (error);
256 }
257 
258 /*
259  * Note: This function performs destructive actions - specifically
260  * it deletes entries from the end of the space map. Thus, callers
261  * should ensure that they are holding the appropriate locks for
262  * the space map that they provide.
263  */
264 int
space_map_incremental_destroy(space_map_t * sm,sm_cb_t callback,void * arg,dmu_tx_t * tx)265 space_map_incremental_destroy(space_map_t *sm, sm_cb_t callback, void *arg,
266     dmu_tx_t *tx)
267 {
268 	uint64_t bufsz = MAX(sm->sm_blksz, SPA_MINBLOCKSIZE);
269 	uint64_t *buf = zio_buf_alloc(bufsz);
270 
271 	dmu_buf_will_dirty(sm->sm_dbuf, tx);
272 
273 	/*
274 	 * Ideally we would want to iterate from the beginning of the
275 	 * space map to the end in incremental steps. The issue with this
276 	 * approach is that we don't have any field on-disk that points
277 	 * us where to start between each step. We could try zeroing out
278 	 * entries that we've destroyed, but this doesn't work either as
279 	 * an entry that is 0 is a valid one (ALLOC for range [0x0:0x200]).
280 	 *
281 	 * As a result, we destroy its entries incrementally starting from
282 	 * the end after applying the callback to each of them.
283 	 *
284 	 * The problem with this approach is that we cannot literally
285 	 * iterate through the words in the space map backwards as we
286 	 * can't distinguish two-word space map entries from their second
287 	 * word. Thus we do the following:
288 	 *
289 	 * 1] We get all the entries from the last block of the space map
290 	 *    and put them into a buffer in reverse order. This way the
291 	 *    last entry comes first in the buffer, the second to last is
292 	 *    second, etc.
293 	 * 2] We iterate through the entries in the buffer and we apply
294 	 *    the callback to each one. As we move from entry to entry we
295 	 *    we decrease the size of the space map, deleting effectively
296 	 *    each entry.
297 	 * 3] If there are no more entries in the space map or the callback
298 	 *    returns a value other than 0, we stop iterating over the
299 	 *    space map. If there are entries remaining and the callback
300 	 *    returned 0, we go back to step [1].
301 	 */
302 	int error = 0;
303 	while (space_map_length(sm) > 0 && error == 0) {
304 		uint64_t nwords = 0;
305 		error = space_map_reversed_last_block_entries(sm, buf, bufsz,
306 		    &nwords);
307 		if (error != 0)
308 			break;
309 
310 		ASSERT3U(nwords, <=, bufsz / sizeof (uint64_t));
311 
312 		for (uint64_t i = 0; i < nwords; i++) {
313 			uint64_t e = buf[i];
314 
315 			if (sm_entry_is_debug(e)) {
316 				sm->sm_phys->smp_length -= sizeof (uint64_t);
317 				continue;
318 			}
319 
320 			int words = 1;
321 			uint64_t raw_offset, raw_run, vdev_id;
322 			maptype_t type;
323 			if (sm_entry_is_single_word(e)) {
324 				type = SM_TYPE_DECODE(e);
325 				vdev_id = SM_NO_VDEVID;
326 				raw_offset = SM_OFFSET_DECODE(e);
327 				raw_run = SM_RUN_DECODE(e);
328 			} else {
329 				ASSERT(sm_entry_is_double_word(e));
330 				words = 2;
331 
332 				raw_run = SM2_RUN_DECODE(e);
333 				vdev_id = SM2_VDEV_DECODE(e);
334 
335 				/* move to the second word */
336 				i++;
337 				e = buf[i];
338 
339 				ASSERT3P(i, <=, nwords);
340 
341 				type = SM2_TYPE_DECODE(e);
342 				raw_offset = SM2_OFFSET_DECODE(e);
343 			}
344 
345 			uint64_t entry_offset =
346 			    (raw_offset << sm->sm_shift) + sm->sm_start;
347 			uint64_t entry_run = raw_run << sm->sm_shift;
348 
349 			VERIFY0(P2PHASE(entry_offset, 1ULL << sm->sm_shift));
350 			VERIFY0(P2PHASE(entry_run, 1ULL << sm->sm_shift));
351 			VERIFY3U(entry_offset, >=, sm->sm_start);
352 			VERIFY3U(entry_offset, <, sm->sm_start + sm->sm_size);
353 			VERIFY3U(entry_run, <=, sm->sm_size);
354 			VERIFY3U(entry_offset + entry_run, <=,
355 			    sm->sm_start + sm->sm_size);
356 
357 			space_map_entry_t sme = {
358 			    .sme_type = type,
359 			    .sme_vdev = vdev_id,
360 			    .sme_offset = entry_offset,
361 			    .sme_run = entry_run
362 			};
363 			error = callback(&sme, arg);
364 			if (error != 0)
365 				break;
366 
367 			if (type == SM_ALLOC)
368 				sm->sm_phys->smp_alloc -= entry_run;
369 			else
370 				sm->sm_phys->smp_alloc += entry_run;
371 			sm->sm_phys->smp_length -= words * sizeof (uint64_t);
372 		}
373 	}
374 
375 	if (space_map_length(sm) == 0) {
376 		ASSERT0(error);
377 		ASSERT0(space_map_allocated(sm));
378 	}
379 
380 	zio_buf_free(buf, bufsz);
381 	return (error);
382 }
383 
384 typedef struct space_map_load_arg {
385 	space_map_t	*smla_sm;
386 	zfs_range_tree_t	*smla_rt;
387 	maptype_t	smla_type;
388 } space_map_load_arg_t;
389 
390 static int
space_map_load_callback(space_map_entry_t * sme,void * arg)391 space_map_load_callback(space_map_entry_t *sme, void *arg)
392 {
393 	space_map_load_arg_t *smla = arg;
394 	if (sme->sme_type == smla->smla_type) {
395 		VERIFY3U(zfs_range_tree_space(smla->smla_rt) + sme->sme_run, <=,
396 		    smla->smla_sm->sm_size);
397 		zfs_range_tree_add(smla->smla_rt, sme->sme_offset,
398 		    sme->sme_run);
399 	} else {
400 		zfs_range_tree_remove(smla->smla_rt, sme->sme_offset,
401 		    sme->sme_run);
402 	}
403 
404 	return (0);
405 }
406 
407 /*
408  * Load the spacemap into the rangetree, like space_map_load. But only
409  * read the first 'length' bytes of the spacemap.
410  */
411 int
space_map_load_length(space_map_t * sm,zfs_range_tree_t * rt,maptype_t maptype,uint64_t length)412 space_map_load_length(space_map_t *sm, zfs_range_tree_t *rt, maptype_t maptype,
413     uint64_t length)
414 {
415 	space_map_load_arg_t smla;
416 
417 	VERIFY0(zfs_range_tree_space(rt));
418 
419 	if (maptype == SM_FREE)
420 		zfs_range_tree_add(rt, sm->sm_start, sm->sm_size);
421 
422 	smla.smla_rt = rt;
423 	smla.smla_sm = sm;
424 	smla.smla_type = maptype;
425 	int err = space_map_iterate(sm, length,
426 	    space_map_load_callback, &smla);
427 
428 	if (err != 0)
429 		zfs_range_tree_vacate(rt, NULL, NULL);
430 
431 	return (err);
432 }
433 
434 /*
435  * Load the space map disk into the specified range tree. Segments of maptype
436  * are added to the range tree, other segment types are removed.
437  */
438 int
space_map_load(space_map_t * sm,zfs_range_tree_t * rt,maptype_t maptype)439 space_map_load(space_map_t *sm, zfs_range_tree_t *rt, maptype_t maptype)
440 {
441 	return (space_map_load_length(sm, rt, maptype, space_map_length(sm)));
442 }
443 
444 void
space_map_histogram_clear(space_map_t * sm)445 space_map_histogram_clear(space_map_t *sm)
446 {
447 	if (sm->sm_dbuf->db_size != sizeof (space_map_phys_t))
448 		return;
449 
450 	memset(sm->sm_phys->smp_histogram, 0,
451 	    sizeof (sm->sm_phys->smp_histogram));
452 }
453 
454 boolean_t
space_map_histogram_verify(space_map_t * sm,zfs_range_tree_t * rt)455 space_map_histogram_verify(space_map_t *sm, zfs_range_tree_t *rt)
456 {
457 	/*
458 	 * Verify that the in-core range tree does not have any
459 	 * ranges smaller than our sm_shift size.
460 	 */
461 	for (int i = 0; i < sm->sm_shift; i++) {
462 		if (rt->rt_histogram[i] != 0)
463 			return (B_FALSE);
464 	}
465 	return (B_TRUE);
466 }
467 
468 void
space_map_histogram_add(space_map_t * sm,zfs_range_tree_t * rt,dmu_tx_t * tx)469 space_map_histogram_add(space_map_t *sm, zfs_range_tree_t *rt, dmu_tx_t *tx)
470 {
471 	int idx = 0;
472 
473 	ASSERT(dmu_tx_is_syncing(tx));
474 	VERIFY3U(space_map_object(sm), !=, 0);
475 
476 	if (sm->sm_dbuf->db_size != sizeof (space_map_phys_t))
477 		return;
478 
479 	dmu_buf_will_dirty(sm->sm_dbuf, tx);
480 
481 	ASSERT(space_map_histogram_verify(sm, rt));
482 	/*
483 	 * Transfer the content of the range tree histogram to the space
484 	 * map histogram. The space map histogram contains 32 buckets ranging
485 	 * between 2^sm_shift to 2^(32+sm_shift-1). The range tree,
486 	 * however, can represent ranges from 2^0 to 2^63. Since the space
487 	 * map only cares about allocatable blocks (minimum of sm_shift) we
488 	 * can safely ignore all ranges in the range tree smaller than sm_shift.
489 	 */
490 	for (int i = sm->sm_shift; i < ZFS_RANGE_TREE_HISTOGRAM_SIZE; i++) {
491 
492 		/*
493 		 * Since the largest histogram bucket in the space map is
494 		 * 2^(32+sm_shift-1), we need to normalize the values in
495 		 * the range tree for any bucket larger than that size. For
496 		 * example given an sm_shift of 9, ranges larger than 2^40
497 		 * would get normalized as if they were 1TB ranges. Assume
498 		 * the range tree had a count of 5 in the 2^44 (16TB) bucket,
499 		 * the calculation below would normalize this to 5 * 2^4 (16).
500 		 */
501 		ASSERT3U(i, >=, idx + sm->sm_shift);
502 		sm->sm_phys->smp_histogram[idx] +=
503 		    rt->rt_histogram[i] << (i - idx - sm->sm_shift);
504 
505 		/*
506 		 * Increment the space map's index as long as we haven't
507 		 * reached the maximum bucket size. Accumulate all ranges
508 		 * larger than the max bucket size into the last bucket.
509 		 */
510 		if (idx < SPACE_MAP_HISTOGRAM_SIZE - 1) {
511 			ASSERT3U(idx + sm->sm_shift, ==, i);
512 			idx++;
513 			ASSERT3U(idx, <, SPACE_MAP_HISTOGRAM_SIZE);
514 		}
515 	}
516 }
517 
518 static void
space_map_write_intro_debug(space_map_t * sm,maptype_t maptype,dmu_tx_t * tx)519 space_map_write_intro_debug(space_map_t *sm, maptype_t maptype, dmu_tx_t *tx)
520 {
521 	dmu_buf_will_dirty(sm->sm_dbuf, tx);
522 
523 	uint64_t dentry = SM_PREFIX_ENCODE(SM_DEBUG_PREFIX) |
524 	    SM_DEBUG_ACTION_ENCODE(maptype) |
525 	    SM_DEBUG_SYNCPASS_ENCODE(spa_sync_pass(tx->tx_pool->dp_spa)) |
526 	    SM_DEBUG_TXG_ENCODE(dmu_tx_get_txg(tx));
527 
528 	dmu_write(sm->sm_os, space_map_object(sm), sm->sm_phys->smp_length,
529 	    sizeof (dentry), &dentry, tx, DMU_READ_NO_PREFETCH);
530 
531 	sm->sm_phys->smp_length += sizeof (dentry);
532 }
533 
534 /*
535  * Writes one or more entries given a segment.
536  *
537  * Note: The function may release the dbuf from the pointer initially
538  * passed to it, and return a different dbuf. Also, the space map's
539  * dbuf must be dirty for the changes in sm_phys to take effect.
540  */
541 static void
space_map_write_seg(space_map_t * sm,uint64_t rstart,uint64_t rend,maptype_t maptype,uint64_t vdev_id,uint8_t words,dmu_buf_t ** dbp,const void * tag,dmu_tx_t * tx)542 space_map_write_seg(space_map_t *sm, uint64_t rstart, uint64_t rend,
543     maptype_t maptype, uint64_t vdev_id, uint8_t words, dmu_buf_t **dbp,
544     const void *tag, dmu_tx_t *tx)
545 {
546 	ASSERT3U(words, !=, 0);
547 	ASSERT3U(words, <=, 2);
548 
549 	/* ensure the vdev_id can be represented by the space map */
550 	ASSERT3U(vdev_id, <=, SM_NO_VDEVID);
551 
552 	/*
553 	 * if this is a single word entry, ensure that no vdev was
554 	 * specified.
555 	 */
556 	IMPLY(words == 1, vdev_id == SM_NO_VDEVID);
557 
558 	dmu_buf_t *db = *dbp;
559 	ASSERT3U(db->db_size, ==, sm->sm_blksz);
560 
561 	uint64_t *block_base = db->db_data;
562 	uint64_t *block_end = block_base + (sm->sm_blksz / sizeof (uint64_t));
563 	uint64_t *block_cursor = block_base +
564 	    (sm->sm_phys->smp_length - db->db_offset) / sizeof (uint64_t);
565 
566 	ASSERT3P(block_cursor, <=, block_end);
567 
568 	uint64_t size = (rend - rstart) >> sm->sm_shift;
569 	uint64_t start = (rstart - sm->sm_start) >> sm->sm_shift;
570 	uint64_t run_max = (words == 2) ? SM2_RUN_MAX : SM_RUN_MAX;
571 
572 	ASSERT3U(rstart, >=, sm->sm_start);
573 	ASSERT3U(rstart, <, sm->sm_start + sm->sm_size);
574 	ASSERT3U(rend - rstart, <=, sm->sm_size);
575 	ASSERT3U(rend, <=, sm->sm_start + sm->sm_size);
576 
577 	while (size != 0) {
578 		ASSERT3P(block_cursor, <=, block_end);
579 
580 		/*
581 		 * If we are at the end of this block, flush it and start
582 		 * writing again from the beginning.
583 		 */
584 		if (block_cursor == block_end) {
585 			dmu_buf_rele(db, tag);
586 
587 			uint64_t next_word_offset = sm->sm_phys->smp_length;
588 			VERIFY0(dmu_buf_hold(sm->sm_os,
589 			    space_map_object(sm), next_word_offset,
590 			    tag, &db, DMU_READ_PREFETCH));
591 			dmu_buf_will_dirty(db, tx);
592 
593 			/* update caller's dbuf */
594 			*dbp = db;
595 
596 			ASSERT3U(db->db_size, ==, sm->sm_blksz);
597 
598 			block_base = db->db_data;
599 			block_cursor = block_base;
600 			block_end = block_base +
601 			    (db->db_size / sizeof (uint64_t));
602 		}
603 
604 		/*
605 		 * If we are writing a two-word entry and we only have one
606 		 * word left on this block, just pad it with an empty debug
607 		 * entry and write the two-word entry in the next block.
608 		 */
609 		uint64_t *next_entry = block_cursor + 1;
610 		if (next_entry == block_end && words > 1) {
611 			ASSERT3U(words, ==, 2);
612 			*block_cursor = SM_PREFIX_ENCODE(SM_DEBUG_PREFIX) |
613 			    SM_DEBUG_ACTION_ENCODE(0) |
614 			    SM_DEBUG_SYNCPASS_ENCODE(0) |
615 			    SM_DEBUG_TXG_ENCODE(0);
616 			block_cursor++;
617 			sm->sm_phys->smp_length += sizeof (uint64_t);
618 			ASSERT3P(block_cursor, ==, block_end);
619 			continue;
620 		}
621 
622 		uint64_t run_len = MIN(size, run_max);
623 		switch (words) {
624 		case 1:
625 			*block_cursor = SM_OFFSET_ENCODE(start) |
626 			    SM_TYPE_ENCODE(maptype) |
627 			    SM_RUN_ENCODE(run_len);
628 			block_cursor++;
629 			break;
630 		case 2:
631 			/* write the first word of the entry */
632 			*block_cursor = SM_PREFIX_ENCODE(SM2_PREFIX) |
633 			    SM2_RUN_ENCODE(run_len) |
634 			    SM2_VDEV_ENCODE(vdev_id);
635 			block_cursor++;
636 
637 			/* move on to the second word of the entry */
638 			ASSERT3P(block_cursor, <, block_end);
639 			*block_cursor = SM2_TYPE_ENCODE(maptype) |
640 			    SM2_OFFSET_ENCODE(start);
641 			block_cursor++;
642 			break;
643 		default:
644 			panic("%d-word space map entries are not supported",
645 			    words);
646 			break;
647 		}
648 		sm->sm_phys->smp_length += words * sizeof (uint64_t);
649 
650 		start += run_len;
651 		size -= run_len;
652 	}
653 	ASSERT0(size);
654 
655 }
656 
657 /*
658  * Note: The space map's dbuf must be dirty for the changes in sm_phys to
659  * take effect.
660  */
661 static void
space_map_write_impl(space_map_t * sm,zfs_range_tree_t * rt,maptype_t maptype,uint64_t vdev_id,dmu_tx_t * tx)662 space_map_write_impl(space_map_t *sm, zfs_range_tree_t *rt, maptype_t maptype,
663     uint64_t vdev_id, dmu_tx_t *tx)
664 {
665 	spa_t *spa = tx->tx_pool->dp_spa;
666 	dmu_buf_t *db;
667 
668 	space_map_write_intro_debug(sm, maptype, tx);
669 
670 #ifdef ZFS_DEBUG
671 	/*
672 	 * We do this right after we write the intro debug entry
673 	 * because the estimate does not take it into account.
674 	 */
675 	uint64_t initial_objsize = sm->sm_phys->smp_length;
676 	uint64_t estimated_growth =
677 	    space_map_estimate_optimal_size(sm, rt, SM_NO_VDEVID);
678 	uint64_t estimated_final_objsize = initial_objsize + estimated_growth;
679 #endif
680 
681 	/*
682 	 * Find the offset right after the last word in the space map
683 	 * and use that to get a hold of the last block, so we can
684 	 * start appending to it.
685 	 */
686 	uint64_t next_word_offset = sm->sm_phys->smp_length;
687 	VERIFY0(dmu_buf_hold(sm->sm_os, space_map_object(sm),
688 	    next_word_offset, FTAG, &db, DMU_READ_PREFETCH));
689 	ASSERT3U(db->db_size, ==, sm->sm_blksz);
690 
691 	dmu_buf_will_dirty(db, tx);
692 
693 	zfs_btree_t *t = &rt->rt_root;
694 	zfs_btree_index_t where;
695 	for (zfs_range_seg_t *rs = zfs_btree_first(t, &where); rs != NULL;
696 	    rs = zfs_btree_next(t, &where, &where)) {
697 		uint64_t offset = (zfs_rs_get_start(rs, rt) - sm->sm_start) >>
698 		    sm->sm_shift;
699 		uint64_t length = (zfs_rs_get_end(rs, rt) -
700 		    zfs_rs_get_start(rs, rt)) >> sm->sm_shift;
701 		uint8_t words = 1;
702 
703 		/*
704 		 * We only write two-word entries when both of the following
705 		 * are true:
706 		 *
707 		 * [1] The feature is enabled.
708 		 * [2] The offset or run is too big for a single-word entry,
709 		 *	or the vdev_id is set (meaning not equal to
710 		 *	SM_NO_VDEVID).
711 		 *
712 		 * Note that for purposes of testing we've added the case that
713 		 * we write two-word entries occasionally when the feature is
714 		 * enabled and zfs_force_some_double_word_sm_entries has been
715 		 * set.
716 		 */
717 		if (spa_feature_is_active(spa, SPA_FEATURE_SPACEMAP_V2) &&
718 		    (offset >= (1ULL << SM_OFFSET_BITS) ||
719 		    length > SM_RUN_MAX ||
720 		    vdev_id != SM_NO_VDEVID ||
721 		    (zfs_force_some_double_word_sm_entries &&
722 		    random_in_range(100) == 0)))
723 			words = 2;
724 
725 		space_map_write_seg(sm, zfs_rs_get_start(rs, rt),
726 		    zfs_rs_get_end(rs, rt), maptype, vdev_id, words, &db,
727 		    FTAG, tx);
728 	}
729 
730 	dmu_buf_rele(db, FTAG);
731 
732 #ifdef ZFS_DEBUG
733 	/*
734 	 * We expect our estimation to be based on the worst case
735 	 * scenario [see comment in space_map_estimate_optimal_size()].
736 	 * Therefore we expect the actual objsize to be equal or less
737 	 * than whatever we estimated it to be.
738 	 */
739 	ASSERT3U(estimated_final_objsize, >=, sm->sm_phys->smp_length);
740 #endif
741 }
742 
743 /*
744  * Note: This function manipulates the state of the given space map but
745  * does not hold any locks implicitly. Thus the caller is responsible
746  * for synchronizing writes to the space map.
747  */
748 void
space_map_write(space_map_t * sm,zfs_range_tree_t * rt,maptype_t maptype,uint64_t vdev_id,dmu_tx_t * tx)749 space_map_write(space_map_t *sm, zfs_range_tree_t *rt, maptype_t maptype,
750     uint64_t vdev_id, dmu_tx_t *tx)
751 {
752 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(sm->sm_os)));
753 	VERIFY3U(space_map_object(sm), !=, 0);
754 
755 	dmu_buf_will_dirty(sm->sm_dbuf, tx);
756 
757 	/*
758 	 * This field is no longer necessary since the in-core space map
759 	 * now contains the object number but is maintained for backwards
760 	 * compatibility.
761 	 */
762 	sm->sm_phys->smp_object = sm->sm_object;
763 
764 	if (zfs_range_tree_is_empty(rt)) {
765 		VERIFY3U(sm->sm_object, ==, sm->sm_phys->smp_object);
766 		return;
767 	}
768 
769 	if (maptype == SM_ALLOC)
770 		sm->sm_phys->smp_alloc += zfs_range_tree_space(rt);
771 	else
772 		sm->sm_phys->smp_alloc -= zfs_range_tree_space(rt);
773 
774 	uint64_t nodes = zfs_btree_numnodes(&rt->rt_root);
775 	uint64_t rt_space = zfs_range_tree_space(rt);
776 
777 	space_map_write_impl(sm, rt, maptype, vdev_id, tx);
778 
779 	/*
780 	 * Ensure that the space_map's accounting wasn't changed
781 	 * while we were in the middle of writing it out.
782 	 */
783 	VERIFY3U(nodes, ==, zfs_btree_numnodes(&rt->rt_root));
784 	VERIFY3U(zfs_range_tree_space(rt), ==, rt_space);
785 }
786 
787 static int
space_map_open_impl(space_map_t * sm)788 space_map_open_impl(space_map_t *sm)
789 {
790 	int error;
791 	u_longlong_t blocks;
792 
793 	error = dmu_bonus_hold(sm->sm_os, sm->sm_object, sm, &sm->sm_dbuf);
794 	if (error)
795 		return (error);
796 
797 	dmu_object_size_from_db(sm->sm_dbuf, &sm->sm_blksz, &blocks);
798 	sm->sm_phys = sm->sm_dbuf->db_data;
799 	return (0);
800 }
801 
802 int
space_map_open(space_map_t ** smp,objset_t * os,uint64_t object,uint64_t start,uint64_t size,uint8_t shift)803 space_map_open(space_map_t **smp, objset_t *os, uint64_t object,
804     uint64_t start, uint64_t size, uint8_t shift)
805 {
806 	space_map_t *sm;
807 	int error;
808 
809 	ASSERT0P(*smp);
810 	ASSERT(os != NULL);
811 	ASSERT(object != 0);
812 
813 	sm = kmem_alloc(sizeof (space_map_t), KM_SLEEP);
814 
815 	sm->sm_start = start;
816 	sm->sm_size = size;
817 	sm->sm_shift = shift;
818 	sm->sm_os = os;
819 	sm->sm_object = object;
820 	sm->sm_blksz = 0;
821 	sm->sm_dbuf = NULL;
822 	sm->sm_phys = NULL;
823 
824 	error = space_map_open_impl(sm);
825 	if (error != 0) {
826 		space_map_close(sm);
827 		return (error);
828 	}
829 	*smp = sm;
830 
831 	return (0);
832 }
833 
834 void
space_map_close(space_map_t * sm)835 space_map_close(space_map_t *sm)
836 {
837 	if (sm == NULL)
838 		return;
839 
840 	if (sm->sm_dbuf != NULL)
841 		dmu_buf_rele(sm->sm_dbuf, sm);
842 	sm->sm_dbuf = NULL;
843 	sm->sm_phys = NULL;
844 
845 	kmem_free(sm, sizeof (*sm));
846 }
847 
848 void
space_map_truncate(space_map_t * sm,int blocksize,dmu_tx_t * tx)849 space_map_truncate(space_map_t *sm, int blocksize, dmu_tx_t *tx)
850 {
851 	objset_t *os = sm->sm_os;
852 	spa_t *spa = dmu_objset_spa(os);
853 	dmu_object_info_t doi;
854 
855 	ASSERT(dsl_pool_sync_context(dmu_objset_pool(os)));
856 	ASSERT(dmu_tx_is_syncing(tx));
857 	VERIFY3U(dmu_tx_get_txg(tx), <=, spa_final_dirty_txg(spa));
858 
859 	dmu_object_info_from_db(sm->sm_dbuf, &doi);
860 
861 	/*
862 	 * If the space map has the wrong bonus size (because
863 	 * SPA_FEATURE_SPACEMAP_HISTOGRAM has recently been enabled), or
864 	 * the wrong block size (because space_map_blksz has changed),
865 	 * free and re-allocate its object with the updated sizes.
866 	 *
867 	 * Otherwise, just truncate the current object.
868 	 */
869 	if ((spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM) &&
870 	    doi.doi_bonus_size != sizeof (space_map_phys_t)) ||
871 	    doi.doi_data_block_size != blocksize ||
872 	    doi.doi_metadata_block_size != 1 << space_map_ibs) {
873 		zfs_dbgmsg("txg %llu, spa %s, sm %px, reallocating "
874 		    "object[%llu]: old bonus %llu, old blocksz %u",
875 		    (u_longlong_t)dmu_tx_get_txg(tx), spa_name(spa), sm,
876 		    (u_longlong_t)sm->sm_object,
877 		    (u_longlong_t)doi.doi_bonus_size,
878 		    doi.doi_data_block_size);
879 
880 		space_map_free(sm, tx);
881 		dmu_buf_rele(sm->sm_dbuf, sm);
882 
883 		sm->sm_object = space_map_alloc(sm->sm_os, blocksize, tx);
884 		VERIFY0(space_map_open_impl(sm));
885 	} else {
886 		VERIFY0(dmu_free_range(os, space_map_object(sm), 0, -1ULL, tx));
887 
888 		/*
889 		 * If the spacemap is reallocated, its histogram
890 		 * will be reset.  Do the same in the common case so that
891 		 * bugs related to the uncommon case do not go unnoticed.
892 		 */
893 		memset(sm->sm_phys->smp_histogram, 0,
894 		    sizeof (sm->sm_phys->smp_histogram));
895 	}
896 
897 	dmu_buf_will_dirty(sm->sm_dbuf, tx);
898 	sm->sm_phys->smp_length = 0;
899 	sm->sm_phys->smp_alloc = 0;
900 }
901 
902 uint64_t
space_map_alloc(objset_t * os,int blocksize,dmu_tx_t * tx)903 space_map_alloc(objset_t *os, int blocksize, dmu_tx_t *tx)
904 {
905 	spa_t *spa = dmu_objset_spa(os);
906 	uint64_t object;
907 	int bonuslen;
908 
909 	if (spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
910 		spa_feature_incr(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM, tx);
911 		bonuslen = sizeof (space_map_phys_t);
912 		ASSERT3U(bonuslen, <=, dmu_bonus_max());
913 	} else {
914 		bonuslen = SPACE_MAP_SIZE_V0;
915 	}
916 
917 	object = dmu_object_alloc_ibs(os, DMU_OT_SPACE_MAP, blocksize,
918 	    space_map_ibs, DMU_OT_SPACE_MAP_HEADER, bonuslen, tx);
919 
920 	return (object);
921 }
922 
923 void
space_map_free_obj(objset_t * os,uint64_t smobj,dmu_tx_t * tx)924 space_map_free_obj(objset_t *os, uint64_t smobj, dmu_tx_t *tx)
925 {
926 	spa_t *spa = dmu_objset_spa(os);
927 	if (spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_HISTOGRAM)) {
928 		dmu_object_info_t doi;
929 
930 		VERIFY0(dmu_object_info(os, smobj, &doi));
931 		if (doi.doi_bonus_size != SPACE_MAP_SIZE_V0) {
932 			spa_feature_decr(spa,
933 			    SPA_FEATURE_SPACEMAP_HISTOGRAM, tx);
934 		}
935 	}
936 
937 	VERIFY0(dmu_object_free(os, smobj, tx));
938 }
939 
940 void
space_map_free(space_map_t * sm,dmu_tx_t * tx)941 space_map_free(space_map_t *sm, dmu_tx_t *tx)
942 {
943 	if (sm == NULL)
944 		return;
945 
946 	space_map_free_obj(sm->sm_os, space_map_object(sm), tx);
947 	sm->sm_object = 0;
948 }
949 
950 /*
951  * Given a range tree, it makes a worst-case estimate of how much
952  * space would the tree's segments take if they were written to
953  * the given space map.
954  */
955 uint64_t
space_map_estimate_optimal_size(space_map_t * sm,zfs_range_tree_t * rt,uint64_t vdev_id)956 space_map_estimate_optimal_size(space_map_t *sm, zfs_range_tree_t *rt,
957     uint64_t vdev_id)
958 {
959 	spa_t *spa = dmu_objset_spa(sm->sm_os);
960 	uint64_t shift = sm->sm_shift;
961 	uint64_t *histogram = rt->rt_histogram;
962 	uint64_t entries_for_seg = 0;
963 
964 	/*
965 	 * In order to get a quick estimate of the optimal size that this
966 	 * range tree would have on-disk as a space map, we iterate through
967 	 * its histogram buckets instead of iterating through its nodes.
968 	 *
969 	 * Note that this is a highest-bound/worst-case estimate for the
970 	 * following reasons:
971 	 *
972 	 * 1] We assume that we always add a debug padding for each block
973 	 *    we write and we also assume that we start at the last word
974 	 *    of a block attempting to write a two-word entry.
975 	 * 2] Rounding up errors due to the way segments are distributed
976 	 *    in the buckets of the range tree's histogram.
977 	 * 3] The activation of zfs_force_some_double_word_sm_entries
978 	 *    (tunable) when testing.
979 	 *
980 	 * = Math and Rounding Errors =
981 	 *
982 	 * rt_histogram[i] bucket of a range tree represents the number
983 	 * of entries in [2^i, (2^(i+1))-1] of that range_tree. Given
984 	 * that, we want to divide the buckets into groups: Buckets that
985 	 * can be represented using a single-word entry, ones that can
986 	 * be represented with a double-word entry, and ones that can
987 	 * only be represented with multiple two-word entries.
988 	 *
989 	 * [Note that if the new encoding feature is not enabled there
990 	 * are only two groups: single-word entry buckets and multiple
991 	 * single-word entry buckets. The information below assumes
992 	 * two-word entries enabled, but it can easily applied when
993 	 * the feature is not enabled]
994 	 *
995 	 * To find the highest bucket that can be represented with a
996 	 * single-word entry we look at the maximum run that such entry
997 	 * can have, which is 2^(SM_RUN_BITS + sm_shift) [remember that
998 	 * the run of a space map entry is shifted by sm_shift, thus we
999 	 * add it to the exponent]. This way, excluding the value of the
1000 	 * maximum run that can be represented by a single-word entry,
1001 	 * all runs that are smaller exist in buckets 0 to
1002 	 * SM_RUN_BITS + shift - 1.
1003 	 *
1004 	 * To find the highest bucket that can be represented with a
1005 	 * double-word entry, we follow the same approach. Finally, any
1006 	 * bucket higher than that are represented with multiple two-word
1007 	 * entries. To be more specific, if the highest bucket whose
1008 	 * segments can be represented with a single two-word entry is X,
1009 	 * then bucket X+1 will need 2 two-word entries for each of its
1010 	 * segments, X+2 will need 4, X+3 will need 8, ...etc.
1011 	 *
1012 	 * With all of the above we make our estimation based on bucket
1013 	 * groups. There is a rounding error though. As we mentioned in
1014 	 * the example with the one-word entry, the maximum run that can
1015 	 * be represented in a one-word entry 2^(SM_RUN_BITS + shift) is
1016 	 * not part of bucket SM_RUN_BITS + shift - 1. Thus, segments of
1017 	 * that length fall into the next bucket (and bucket group) where
1018 	 * we start counting two-word entries and this is one more reason
1019 	 * why the estimated size may end up being bigger than the actual
1020 	 * size written.
1021 	 */
1022 	uint64_t size = 0;
1023 	uint64_t idx = 0;
1024 
1025 	if (!spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2) ||
1026 	    (vdev_id == SM_NO_VDEVID && sm->sm_size < SM_OFFSET_MAX)) {
1027 
1028 		/*
1029 		 * If we are trying to force some double word entries just
1030 		 * assume the worst-case of every single word entry being
1031 		 * written as a double word entry.
1032 		 */
1033 		uint64_t entry_size =
1034 		    (spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2) &&
1035 		    zfs_force_some_double_word_sm_entries) ?
1036 		    (2 * sizeof (uint64_t)) : sizeof (uint64_t);
1037 
1038 		uint64_t single_entry_max_bucket = SM_RUN_BITS + shift - 1;
1039 		for (; idx <= single_entry_max_bucket; idx++)
1040 			size += histogram[idx] * entry_size;
1041 
1042 		if (!spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2)) {
1043 			for (; idx < ZFS_RANGE_TREE_HISTOGRAM_SIZE; idx++) {
1044 				ASSERT3U(idx, >=, single_entry_max_bucket);
1045 				entries_for_seg =
1046 				    1ULL << (idx - single_entry_max_bucket);
1047 				size += histogram[idx] *
1048 				    entries_for_seg * entry_size;
1049 			}
1050 			return (size);
1051 		}
1052 	}
1053 
1054 	ASSERT(spa_feature_is_enabled(spa, SPA_FEATURE_SPACEMAP_V2));
1055 
1056 	uint64_t double_entry_max_bucket = SM2_RUN_BITS + shift - 1;
1057 	for (; idx <= double_entry_max_bucket; idx++)
1058 		size += histogram[idx] * 2 * sizeof (uint64_t);
1059 
1060 	for (; idx < ZFS_RANGE_TREE_HISTOGRAM_SIZE; idx++) {
1061 		ASSERT3U(idx, >=, double_entry_max_bucket);
1062 		entries_for_seg = 1ULL << (idx - double_entry_max_bucket);
1063 		size += histogram[idx] *
1064 		    entries_for_seg * 2 * sizeof (uint64_t);
1065 	}
1066 
1067 	/*
1068 	 * Assume the worst case where we start with the padding at the end
1069 	 * of the current block and we add an extra padding entry at the end
1070 	 * of all subsequent blocks.
1071 	 */
1072 	size += ((size / sm->sm_blksz) + 1) * sizeof (uint64_t);
1073 
1074 	return (size);
1075 }
1076 
1077 uint64_t
space_map_object(space_map_t * sm)1078 space_map_object(space_map_t *sm)
1079 {
1080 	return (sm != NULL ? sm->sm_object : 0);
1081 }
1082 
1083 int64_t
space_map_allocated(space_map_t * sm)1084 space_map_allocated(space_map_t *sm)
1085 {
1086 	return (sm != NULL ? sm->sm_phys->smp_alloc : 0);
1087 }
1088 
1089 uint64_t
space_map_length(space_map_t * sm)1090 space_map_length(space_map_t *sm)
1091 {
1092 	return (sm != NULL ? sm->sm_phys->smp_length : 0);
1093 }
1094 
1095 uint64_t
space_map_nblocks(space_map_t * sm)1096 space_map_nblocks(space_map_t *sm)
1097 {
1098 	if (sm == NULL)
1099 		return (0);
1100 	return (DIV_ROUND_UP(space_map_length(sm), sm->sm_blksz));
1101 }
1102