xref: /freebsd/sys/contrib/openzfs/module/zfs/ddt_log.c (revision 88b8b7f0c4e9948667a2279e78e975a784049cba)
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 /*
24  * Copyright (c) 2023, Klara Inc.
25  */
26 
27 #include <sys/zfs_context.h>
28 #include <sys/spa.h>
29 #include <sys/ddt.h>
30 #include <sys/dmu_tx.h>
31 #include <sys/dmu.h>
32 #include <sys/ddt_impl.h>
33 #include <sys/dnode.h>
34 #include <sys/dbuf.h>
35 #include <sys/zap.h>
36 #include <sys/zio_checksum.h>
37 
38 /*
39  * No more than this many txgs before swapping logs.
40  */
41 uint_t zfs_dedup_log_txg_max = 8;
42 
43 /*
44  * Max memory for the log AVL trees. If zfs_dedup_log_mem_max is zero at module
45  * load, it will be set to zfs_dedup_log_mem_max_percent% of total memory.
46  */
47 uint64_t zfs_dedup_log_mem_max = 0;
48 uint_t zfs_dedup_log_mem_max_percent = 1;
49 
50 
51 static kmem_cache_t *ddt_log_entry_flat_cache;
52 static kmem_cache_t *ddt_log_entry_trad_cache;
53 
54 #define	DDT_LOG_ENTRY_FLAT_SIZE	\
55 	(sizeof (ddt_log_entry_t) + DDT_FLAT_PHYS_SIZE)
56 #define	DDT_LOG_ENTRY_TRAD_SIZE	\
57 	(sizeof (ddt_log_entry_t) + DDT_TRAD_PHYS_SIZE)
58 
59 #define	DDT_LOG_ENTRY_SIZE(ddt)	\
60 	_DDT_PHYS_SWITCH(ddt, DDT_LOG_ENTRY_FLAT_SIZE, DDT_LOG_ENTRY_TRAD_SIZE)
61 
62 void
63 ddt_log_init(void)
64 {
65 	ddt_log_entry_flat_cache = kmem_cache_create("ddt_log_entry_flat_cache",
66 	    DDT_LOG_ENTRY_FLAT_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
67 	ddt_log_entry_trad_cache = kmem_cache_create("ddt_log_entry_trad_cache",
68 	    DDT_LOG_ENTRY_TRAD_SIZE, 0, NULL, NULL, NULL, NULL, NULL, 0);
69 
70 	/*
71 	 * Max memory for log AVL entries. At least 1M, because we need
72 	 * something (that's ~3800 entries per tree). They can say 100% if they
73 	 * want; it just means they're at the mercy of the the txg flush limit.
74 	 */
75 	if (zfs_dedup_log_mem_max == 0) {
76 		zfs_dedup_log_mem_max_percent =
77 		    MIN(zfs_dedup_log_mem_max_percent, 100);
78 		zfs_dedup_log_mem_max = (physmem * PAGESIZE) *
79 		    zfs_dedup_log_mem_max_percent / 100;
80 	}
81 	zfs_dedup_log_mem_max = MAX(zfs_dedup_log_mem_max, 1*1024*1024);
82 }
83 
84 void
85 ddt_log_fini(void)
86 {
87 	kmem_cache_destroy(ddt_log_entry_trad_cache);
88 	kmem_cache_destroy(ddt_log_entry_flat_cache);
89 }
90 
91 static void
92 ddt_log_name(ddt_t *ddt, char *name, uint_t n)
93 {
94 	snprintf(name, DDT_NAMELEN, DMU_POOL_DDT_LOG,
95 	    zio_checksum_table[ddt->ddt_checksum].ci_name, n);
96 }
97 
98 static void
99 ddt_log_update_header(ddt_t *ddt, ddt_log_t *ddl, dmu_tx_t *tx)
100 {
101 	dmu_buf_t *db;
102 	VERIFY0(dmu_bonus_hold(ddt->ddt_os, ddl->ddl_object, FTAG, &db));
103 	dmu_buf_will_dirty(db, tx);
104 
105 	ddt_log_header_t *hdr = (ddt_log_header_t *)db->db_data;
106 	DLH_SET_VERSION(hdr, 1);
107 	DLH_SET_FLAGS(hdr, ddl->ddl_flags);
108 	hdr->dlh_length = ddl->ddl_length;
109 	hdr->dlh_first_txg = ddl->ddl_first_txg;
110 	hdr->dlh_checkpoint = ddl->ddl_checkpoint;
111 
112 	dmu_buf_rele(db, FTAG);
113 }
114 
115 static void
116 ddt_log_create_one(ddt_t *ddt, ddt_log_t *ddl, uint_t n, dmu_tx_t *tx)
117 {
118 	ASSERT3U(ddt->ddt_dir_object, >, 0);
119 	ASSERT0(ddl->ddl_object);
120 
121 	char name[DDT_NAMELEN];
122 	ddt_log_name(ddt, name, n);
123 
124 	ddl->ddl_object = dmu_object_alloc(ddt->ddt_os,
125 	    DMU_OTN_UINT64_METADATA, SPA_OLD_MAXBLOCKSIZE,
126 	    DMU_OTN_UINT64_METADATA, sizeof (ddt_log_header_t), tx);
127 	VERIFY0(zap_add(ddt->ddt_os, ddt->ddt_dir_object, name,
128 	    sizeof (uint64_t), 1, &ddl->ddl_object, tx));
129 	ddl->ddl_length = 0;
130 	ddl->ddl_first_txg = tx->tx_txg;
131 	ddt_log_update_header(ddt, ddl, tx);
132 }
133 
134 static void
135 ddt_log_create(ddt_t *ddt, dmu_tx_t *tx)
136 {
137 	ddt_log_create_one(ddt, ddt->ddt_log_active, 0, tx);
138 	ddt_log_create_one(ddt, ddt->ddt_log_flushing, 1, tx);
139 }
140 
141 static void
142 ddt_log_destroy_one(ddt_t *ddt, ddt_log_t *ddl, uint_t n, dmu_tx_t *tx)
143 {
144 	ASSERT3U(ddt->ddt_dir_object, >, 0);
145 
146 	if (ddl->ddl_object == 0)
147 		return;
148 
149 	ASSERT0(ddl->ddl_length);
150 
151 	char name[DDT_NAMELEN];
152 	ddt_log_name(ddt, name, n);
153 
154 	VERIFY0(zap_remove(ddt->ddt_os, ddt->ddt_dir_object, name, tx));
155 	VERIFY0(dmu_object_free(ddt->ddt_os, ddl->ddl_object, tx));
156 
157 	ddl->ddl_object = 0;
158 }
159 
160 void
161 ddt_log_destroy(ddt_t *ddt, dmu_tx_t *tx)
162 {
163 	ddt_log_destroy_one(ddt, ddt->ddt_log_active, 0, tx);
164 	ddt_log_destroy_one(ddt, ddt->ddt_log_flushing, 1, tx);
165 }
166 
167 static void
168 ddt_log_update_stats(ddt_t *ddt)
169 {
170 	/*
171 	 * Log object stats. We count the number of live entries in the log
172 	 * tree, even if there are more than on disk, and even if the same
173 	 * entry is on both append and flush trees, because that's more what
174 	 * the user expects to see. This does mean the on-disk size is not
175 	 * really correlated with the number of entries, but I don't think
176 	 * that's reasonable to expect anyway.
177 	 */
178 	dmu_object_info_t doi;
179 	uint64_t nblocks = 0;
180 	if (dmu_object_info(ddt->ddt_os, ddt->ddt_log_active->ddl_object,
181 	    &doi) == 0)
182 		nblocks += doi.doi_physical_blocks_512;
183 	if (dmu_object_info(ddt->ddt_os, ddt->ddt_log_flushing->ddl_object,
184 	    &doi) == 0)
185 		nblocks += doi.doi_physical_blocks_512;
186 
187 	ddt_object_t *ddo = &ddt->ddt_log_stats;
188 	ddo->ddo_count =
189 	    avl_numnodes(&ddt->ddt_log_active->ddl_tree) +
190 	    avl_numnodes(&ddt->ddt_log_flushing->ddl_tree);
191 	ddo->ddo_mspace = ddo->ddo_count * DDT_LOG_ENTRY_SIZE(ddt);
192 	ddo->ddo_dspace = nblocks << 9;
193 }
194 
195 void
196 ddt_log_begin(ddt_t *ddt, size_t nentries, dmu_tx_t *tx, ddt_log_update_t *dlu)
197 {
198 	ASSERT3U(nentries, >, 0);
199 	ASSERT0P(dlu->dlu_dbp);
200 
201 	if (ddt->ddt_log_active->ddl_object == 0)
202 		ddt_log_create(ddt, tx);
203 
204 	/*
205 	 * We want to store as many entries as we can in a block, but never
206 	 * split an entry across block boundaries.
207 	 */
208 	size_t reclen = P2ALIGN_TYPED(
209 	    sizeof (ddt_log_record_t) + sizeof (ddt_log_record_entry_t) +
210 	    DDT_PHYS_SIZE(ddt), sizeof (uint64_t), size_t);
211 	ASSERT3U(reclen, <=, UINT16_MAX);
212 	dlu->dlu_reclen = reclen;
213 
214 	VERIFY0(dnode_hold(ddt->ddt_os, ddt->ddt_log_active->ddl_object, FTAG,
215 	    &dlu->dlu_dn));
216 	dnode_set_storage_type(dlu->dlu_dn, DMU_OT_DDT_ZAP);
217 
218 	uint64_t nblocks = howmany(nentries,
219 	    dlu->dlu_dn->dn_datablksz / dlu->dlu_reclen);
220 	uint64_t offset = ddt->ddt_log_active->ddl_length;
221 	uint64_t length = nblocks * dlu->dlu_dn->dn_datablksz;
222 
223 	VERIFY0(dmu_buf_hold_array_by_dnode(dlu->dlu_dn, offset, length,
224 	    B_FALSE, FTAG, &dlu->dlu_ndbp, &dlu->dlu_dbp,
225 	    DMU_READ_NO_PREFETCH));
226 
227 	dlu->dlu_tx = tx;
228 	dlu->dlu_block = dlu->dlu_offset = 0;
229 }
230 
231 static ddt_log_entry_t *
232 ddt_log_alloc_entry(ddt_t *ddt)
233 {
234 	ddt_log_entry_t *ddle;
235 
236 	if (ddt->ddt_flags & DDT_FLAG_FLAT) {
237 		ddle = kmem_cache_alloc(ddt_log_entry_flat_cache, KM_SLEEP);
238 		memset(ddle, 0, DDT_LOG_ENTRY_FLAT_SIZE);
239 	} else {
240 		ddle = kmem_cache_alloc(ddt_log_entry_trad_cache, KM_SLEEP);
241 		memset(ddle, 0, DDT_LOG_ENTRY_TRAD_SIZE);
242 	}
243 
244 	return (ddle);
245 }
246 
247 static void
248 ddt_log_free_entry(ddt_t *ddt, ddt_log_entry_t *ddle)
249 {
250 	kmem_cache_free(ddt->ddt_flags & DDT_FLAG_FLAT ?
251 	    ddt_log_entry_flat_cache : ddt_log_entry_trad_cache, ddle);
252 }
253 
254 static void
255 ddt_log_update_entry(ddt_t *ddt, ddt_log_t *ddl, ddt_lightweight_entry_t *ddlwe)
256 {
257 	/* Create the log tree entry from a live or stored entry */
258 	avl_index_t where;
259 	ddt_log_entry_t *ddle =
260 	    avl_find(&ddl->ddl_tree, &ddlwe->ddlwe_key, &where);
261 	if (ddle == NULL) {
262 		ddle = ddt_log_alloc_entry(ddt);
263 		ddle->ddle_key = ddlwe->ddlwe_key;
264 		avl_insert(&ddl->ddl_tree, ddle, where);
265 	}
266 	ddle->ddle_type = ddlwe->ddlwe_type;
267 	ddle->ddle_class = ddlwe->ddlwe_class;
268 	memcpy(ddle->ddle_phys, &ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt));
269 }
270 
271 void
272 ddt_log_entry(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, ddt_log_update_t *dlu)
273 {
274 	ASSERT3U(dlu->dlu_dbp, !=, NULL);
275 
276 	ddt_log_update_entry(ddt, ddt->ddt_log_active, ddlwe);
277 	ddt_histogram_add_entry(ddt, &ddt->ddt_log_histogram, ddlwe);
278 
279 	/* Get our block */
280 	ASSERT3U(dlu->dlu_block, <, dlu->dlu_ndbp);
281 	dmu_buf_t *db = dlu->dlu_dbp[dlu->dlu_block];
282 
283 	/*
284 	 * If this would take us past the end of the block, finish it and
285 	 * move to the next one.
286 	 */
287 	if (db->db_size < (dlu->dlu_offset + dlu->dlu_reclen)) {
288 		ASSERT3U(dlu->dlu_offset, >, 0);
289 		dmu_buf_fill_done(db, dlu->dlu_tx, B_FALSE);
290 		dlu->dlu_block++;
291 		dlu->dlu_offset = 0;
292 		ASSERT3U(dlu->dlu_block, <, dlu->dlu_ndbp);
293 		db = dlu->dlu_dbp[dlu->dlu_block];
294 	}
295 
296 	/*
297 	 * If this is the first time touching the block, inform the DMU that
298 	 * we will fill it, and zero it out.
299 	 */
300 	if (dlu->dlu_offset == 0) {
301 		dmu_buf_will_fill(db, dlu->dlu_tx, B_FALSE);
302 		memset(db->db_data, 0, db->db_size);
303 	}
304 
305 	/* Create the log record directly in the buffer */
306 	ddt_log_record_t *dlr = (db->db_data + dlu->dlu_offset);
307 	DLR_SET_TYPE(dlr, DLR_ENTRY);
308 	DLR_SET_RECLEN(dlr, dlu->dlu_reclen);
309 	DLR_SET_ENTRY_TYPE(dlr, ddlwe->ddlwe_type);
310 	DLR_SET_ENTRY_CLASS(dlr, ddlwe->ddlwe_class);
311 
312 	ddt_log_record_entry_t *dlre =
313 	    (ddt_log_record_entry_t *)&dlr->dlr_payload;
314 	dlre->dlre_key = ddlwe->ddlwe_key;
315 	memcpy(dlre->dlre_phys, &ddlwe->ddlwe_phys, DDT_PHYS_SIZE(ddt));
316 
317 	/* Advance offset for next record. */
318 	dlu->dlu_offset += dlu->dlu_reclen;
319 }
320 
321 void
322 ddt_log_commit(ddt_t *ddt, ddt_log_update_t *dlu)
323 {
324 	ASSERT3U(dlu->dlu_dbp, !=, NULL);
325 	ASSERT3U(dlu->dlu_block+1, ==, dlu->dlu_ndbp);
326 	ASSERT3U(dlu->dlu_offset, >, 0);
327 
328 	/*
329 	 * Close out the last block. Whatever we haven't used will be zeroed,
330 	 * which matches DLR_INVALID, so we can detect this during load.
331 	 */
332 	dmu_buf_fill_done(dlu->dlu_dbp[dlu->dlu_block], dlu->dlu_tx, B_FALSE);
333 
334 	dmu_buf_rele_array(dlu->dlu_dbp, dlu->dlu_ndbp, FTAG);
335 
336 	ddt->ddt_log_active->ddl_length +=
337 	    dlu->dlu_ndbp * (uint64_t)dlu->dlu_dn->dn_datablksz;
338 	dnode_rele(dlu->dlu_dn, FTAG);
339 
340 	ddt_log_update_header(ddt, ddt->ddt_log_active, dlu->dlu_tx);
341 
342 	memset(dlu, 0, sizeof (ddt_log_update_t));
343 
344 	ddt_log_update_stats(ddt);
345 }
346 
347 boolean_t
348 ddt_log_take_first(ddt_t *ddt, ddt_log_t *ddl, ddt_lightweight_entry_t *ddlwe)
349 {
350 	ddt_log_entry_t *ddle = avl_first(&ddl->ddl_tree);
351 	if (ddle == NULL)
352 		return (B_FALSE);
353 
354 	DDT_LOG_ENTRY_TO_LIGHTWEIGHT(ddt, ddle, ddlwe);
355 
356 	ddt_histogram_sub_entry(ddt, &ddt->ddt_log_histogram, ddlwe);
357 
358 	avl_remove(&ddl->ddl_tree, ddle);
359 	ddt_log_free_entry(ddt, ddle);
360 
361 	return (B_TRUE);
362 }
363 
364 boolean_t
365 ddt_log_remove_key(ddt_t *ddt, ddt_log_t *ddl, const ddt_key_t *ddk)
366 {
367 	ddt_log_entry_t *ddle = avl_find(&ddl->ddl_tree, ddk, NULL);
368 	if (ddle == NULL)
369 		return (B_FALSE);
370 
371 	ddt_lightweight_entry_t ddlwe;
372 	DDT_LOG_ENTRY_TO_LIGHTWEIGHT(ddt, ddle, &ddlwe);
373 	ddt_histogram_sub_entry(ddt, &ddt->ddt_log_histogram, &ddlwe);
374 
375 	avl_remove(&ddl->ddl_tree, ddle);
376 	ddt_log_free_entry(ddt, ddle);
377 
378 	return (B_TRUE);
379 }
380 
381 boolean_t
382 ddt_log_find_key(ddt_t *ddt, const ddt_key_t *ddk,
383     ddt_lightweight_entry_t *ddlwe)
384 {
385 	ddt_log_entry_t *ddle =
386 	    avl_find(&ddt->ddt_log_active->ddl_tree, ddk, NULL);
387 	if (!ddle)
388 		ddle = avl_find(&ddt->ddt_log_flushing->ddl_tree, ddk, NULL);
389 	if (!ddle)
390 		return (B_FALSE);
391 	if (ddlwe)
392 		DDT_LOG_ENTRY_TO_LIGHTWEIGHT(ddt, ddle, ddlwe);
393 	return (B_TRUE);
394 }
395 
396 void
397 ddt_log_checkpoint(ddt_t *ddt, ddt_lightweight_entry_t *ddlwe, dmu_tx_t *tx)
398 {
399 	ddt_log_t *ddl = ddt->ddt_log_flushing;
400 
401 	ASSERT3U(ddl->ddl_object, !=, 0);
402 
403 #ifdef ZFS_DEBUG
404 	/*
405 	 * There should not be any entries on the log tree before the given
406 	 * checkpoint. Assert that this is the case.
407 	 */
408 	ddt_log_entry_t *ddle = avl_first(&ddl->ddl_tree);
409 	if (ddle != NULL)
410 		VERIFY3U(ddt_key_compare(&ddle->ddle_key, &ddlwe->ddlwe_key),
411 		    >, 0);
412 #endif
413 
414 	ddl->ddl_flags |= DDL_FLAG_CHECKPOINT;
415 	ddl->ddl_checkpoint = ddlwe->ddlwe_key;
416 	ddt_log_update_header(ddt, ddl, tx);
417 
418 	ddt_log_update_stats(ddt);
419 }
420 
421 void
422 ddt_log_truncate(ddt_t *ddt, dmu_tx_t *tx)
423 {
424 	ddt_log_t *ddl = ddt->ddt_log_flushing;
425 
426 	if (ddl->ddl_object == 0)
427 		return;
428 
429 	ASSERT(avl_is_empty(&ddl->ddl_tree));
430 
431 	/* Eject the entire object */
432 	dmu_free_range(ddt->ddt_os, ddl->ddl_object, 0, DMU_OBJECT_END, tx);
433 
434 	ddl->ddl_length = 0;
435 	ddl->ddl_flags &= ~DDL_FLAG_CHECKPOINT;
436 	memset(&ddl->ddl_checkpoint, 0, sizeof (ddt_key_t));
437 	ddt_log_update_header(ddt, ddl, tx);
438 
439 	ddt_log_update_stats(ddt);
440 }
441 
442 boolean_t
443 ddt_log_swap(ddt_t *ddt, dmu_tx_t *tx)
444 {
445 	/* Swap the logs. The old flushing one must be empty */
446 	VERIFY(avl_is_empty(&ddt->ddt_log_flushing->ddl_tree));
447 
448 	/*
449 	 * If there are still blocks on the flushing log, truncate it first.
450 	 * This can happen if there were entries on the flushing log that were
451 	 * removed in memory via ddt_lookup(); their vestigal remains are
452 	 * on disk.
453 	 */
454 	if (ddt->ddt_log_flushing->ddl_length > 0)
455 		ddt_log_truncate(ddt, tx);
456 
457 	/*
458 	 * Swap policy. We swap the logs (and so begin flushing) when the
459 	 * active tree grows too large, or when we haven't swapped it in
460 	 * some amount of time, or if something has requested the logs be
461 	 * flushed ASAP (see ddt_walk_init()).
462 	 */
463 
464 	/*
465 	 * The log tree is too large if the memory usage of its entries is over
466 	 * half of the memory limit. This effectively gives each log tree half
467 	 * the available memory.
468 	 */
469 	const boolean_t too_large =
470 	    (avl_numnodes(&ddt->ddt_log_active->ddl_tree) *
471 	    DDT_LOG_ENTRY_SIZE(ddt)) >= (zfs_dedup_log_mem_max >> 1);
472 
473 	const boolean_t too_old =
474 	    tx->tx_txg >=
475 	    (ddt->ddt_log_active->ddl_first_txg +
476 	    MAX(1, zfs_dedup_log_txg_max));
477 
478 	const boolean_t force =
479 	    ddt->ddt_log_active->ddl_first_txg <= ddt->ddt_flush_force_txg;
480 
481 	if (!(too_large || too_old || force))
482 		return (B_FALSE);
483 
484 	ddt_log_t *swap = ddt->ddt_log_active;
485 	ddt->ddt_log_active = ddt->ddt_log_flushing;
486 	ddt->ddt_log_flushing = swap;
487 
488 	ASSERT(ddt->ddt_log_active->ddl_flags & DDL_FLAG_FLUSHING);
489 	ddt->ddt_log_active->ddl_flags &=
490 	    ~(DDL_FLAG_FLUSHING | DDL_FLAG_CHECKPOINT);
491 
492 	ASSERT(!(ddt->ddt_log_flushing->ddl_flags & DDL_FLAG_FLUSHING));
493 	ddt->ddt_log_flushing->ddl_flags |= DDL_FLAG_FLUSHING;
494 
495 	ddt->ddt_log_active->ddl_first_txg = tx->tx_txg;
496 
497 	ddt_log_update_header(ddt, ddt->ddt_log_active, tx);
498 	ddt_log_update_header(ddt, ddt->ddt_log_flushing, tx);
499 
500 	ddt_log_update_stats(ddt);
501 
502 	return (B_TRUE);
503 }
504 
505 static inline void
506 ddt_log_load_entry(ddt_t *ddt, ddt_log_t *ddl, ddt_log_record_t *dlr,
507     const ddt_key_t *checkpoint)
508 {
509 	ASSERT3U(DLR_GET_TYPE(dlr), ==, DLR_ENTRY);
510 
511 	ddt_log_record_entry_t *dlre =
512 	    (ddt_log_record_entry_t *)dlr->dlr_payload;
513 	if (checkpoint != NULL &&
514 	    ddt_key_compare(&dlre->dlre_key, checkpoint) <= 0) {
515 		/* Skip pre-checkpoint entries; they're already flushed. */
516 		return;
517 	}
518 
519 	ddt_lightweight_entry_t ddlwe;
520 	ddlwe.ddlwe_type = DLR_GET_ENTRY_TYPE(dlr);
521 	ddlwe.ddlwe_class = DLR_GET_ENTRY_CLASS(dlr);
522 
523 	ddlwe.ddlwe_key = dlre->dlre_key;
524 	memcpy(&ddlwe.ddlwe_phys, dlre->dlre_phys, DDT_PHYS_SIZE(ddt));
525 
526 	ddt_log_update_entry(ddt, ddl, &ddlwe);
527 }
528 
529 static void
530 ddt_log_empty(ddt_t *ddt, ddt_log_t *ddl)
531 {
532 	void *cookie = NULL;
533 	ddt_log_entry_t *ddle;
534 	IMPLY(ddt->ddt_version == UINT64_MAX, avl_is_empty(&ddl->ddl_tree));
535 	while ((ddle =
536 	    avl_destroy_nodes(&ddl->ddl_tree, &cookie)) != NULL) {
537 		ddt_log_free_entry(ddt, ddle);
538 	}
539 	ASSERT(avl_is_empty(&ddl->ddl_tree));
540 }
541 
542 static int
543 ddt_log_load_one(ddt_t *ddt, uint_t n)
544 {
545 	ASSERT3U(n, <, 2);
546 
547 	ddt_log_t *ddl = &ddt->ddt_log[n];
548 
549 	char name[DDT_NAMELEN];
550 	ddt_log_name(ddt, name, n);
551 
552 	uint64_t obj;
553 	int err = zap_lookup(ddt->ddt_os, ddt->ddt_dir_object, name,
554 	    sizeof (uint64_t), 1, &obj);
555 	if (err == ENOENT)
556 		return (0);
557 	if (err != 0)
558 		return (err);
559 
560 	dnode_t *dn;
561 	err = dnode_hold(ddt->ddt_os, obj, FTAG, &dn);
562 	if (err != 0)
563 		return (err);
564 
565 	ddt_log_header_t hdr;
566 	dmu_buf_t *db;
567 	err = dmu_bonus_hold_by_dnode(dn, FTAG, &db, DMU_READ_NO_PREFETCH);
568 	if (err != 0) {
569 		dnode_rele(dn, FTAG);
570 		return (err);
571 	}
572 	memcpy(&hdr, db->db_data, sizeof (ddt_log_header_t));
573 	dmu_buf_rele(db, FTAG);
574 
575 	if (DLH_GET_VERSION(&hdr) != 1) {
576 		dnode_rele(dn, FTAG);
577 		zfs_dbgmsg("ddt_log_load: spa=%s ddt_log=%s "
578 		    "unknown version=%llu", spa_name(ddt->ddt_spa), name,
579 		    (u_longlong_t)DLH_GET_VERSION(&hdr));
580 		return (SET_ERROR(EINVAL));
581 	}
582 
583 	ddt_key_t *checkpoint = NULL;
584 	if (DLH_GET_FLAGS(&hdr) & DDL_FLAG_CHECKPOINT) {
585 		/*
586 		 * If the log has a checkpoint, then we can ignore any entries
587 		 * that have already been flushed.
588 		 */
589 		ASSERT(DLH_GET_FLAGS(&hdr) & DDL_FLAG_FLUSHING);
590 		checkpoint = &hdr.dlh_checkpoint;
591 	}
592 
593 	if (hdr.dlh_length > 0) {
594 		dmu_prefetch_by_dnode(dn, 0, 0, hdr.dlh_length,
595 		    ZIO_PRIORITY_SYNC_READ);
596 
597 		for (uint64_t offset = 0; offset < hdr.dlh_length;
598 		    offset += dn->dn_datablksz) {
599 			err = dmu_buf_hold_by_dnode(dn, offset, FTAG, &db,
600 			    DMU_READ_PREFETCH);
601 			if (err != 0) {
602 				dnode_rele(dn, FTAG);
603 				ddt_log_empty(ddt, ddl);
604 				return (err);
605 			}
606 
607 			uint64_t boffset = 0;
608 			while (boffset < db->db_size) {
609 				ddt_log_record_t *dlr =
610 				    (ddt_log_record_t *)(db->db_data + boffset);
611 
612 				/* Partially-filled block, skip the rest */
613 				if (DLR_GET_TYPE(dlr) == DLR_INVALID)
614 					break;
615 
616 				switch (DLR_GET_TYPE(dlr)) {
617 				case DLR_ENTRY:
618 					ddt_log_load_entry(ddt, ddl, dlr,
619 					    checkpoint);
620 					break;
621 
622 				default:
623 					dmu_buf_rele(db, FTAG);
624 					dnode_rele(dn, FTAG);
625 					ddt_log_empty(ddt, ddl);
626 					return (SET_ERROR(EINVAL));
627 				}
628 
629 				boffset += DLR_GET_RECLEN(dlr);
630 			}
631 
632 			dmu_buf_rele(db, FTAG);
633 		}
634 	}
635 
636 	dnode_rele(dn, FTAG);
637 
638 	ddl->ddl_object = obj;
639 	ddl->ddl_flags = DLH_GET_FLAGS(&hdr);
640 	ddl->ddl_length = hdr.dlh_length;
641 	ddl->ddl_first_txg = hdr.dlh_first_txg;
642 
643 	if (ddl->ddl_flags & DDL_FLAG_FLUSHING)
644 		ddt->ddt_log_flushing = ddl;
645 	else
646 		ddt->ddt_log_active = ddl;
647 
648 	return (0);
649 }
650 
651 int
652 ddt_log_load(ddt_t *ddt)
653 {
654 	int err;
655 
656 	if (spa_load_state(ddt->ddt_spa) == SPA_LOAD_TRYIMPORT) {
657 		/*
658 		 * The DDT is going to be freed again in a moment, so there's
659 		 * no point loading the log; it'll just slow down import.
660 		 */
661 		return (0);
662 	}
663 
664 	ASSERT0(ddt->ddt_log[0].ddl_object);
665 	ASSERT0(ddt->ddt_log[1].ddl_object);
666 	if (ddt->ddt_dir_object == 0) {
667 		/*
668 		 * If we're configured but the containing dir doesn't exist
669 		 * yet, then the log object can't possibly exist either.
670 		 */
671 		ASSERT3U(ddt->ddt_version, !=, UINT64_MAX);
672 		return (SET_ERROR(ENOENT));
673 	}
674 
675 	if ((err = ddt_log_load_one(ddt, 0)) != 0)
676 		return (err);
677 	if ((err = ddt_log_load_one(ddt, 1)) != 0)
678 		return (err);
679 
680 	VERIFY3P(ddt->ddt_log_active, !=, ddt->ddt_log_flushing);
681 	VERIFY(!(ddt->ddt_log_active->ddl_flags & DDL_FLAG_FLUSHING));
682 	VERIFY(!(ddt->ddt_log_active->ddl_flags & DDL_FLAG_CHECKPOINT));
683 	VERIFY(ddt->ddt_log_flushing->ddl_flags & DDL_FLAG_FLUSHING);
684 
685 	/*
686 	 * We have two finalisation tasks:
687 	 *
688 	 * - rebuild the histogram. We do this at the end rather than while
689 	 *   we're loading so we don't need to uncount and recount entries that
690 	 *   appear multiple times in the log.
691 	 *
692 	 * - remove entries from the flushing tree that are on both trees. This
693 	 *   happens when ddt_lookup() rehydrates an entry from the flushing
694 	 *   tree, as ddt_log_take_key() removes the entry from the in-memory
695 	 *   tree but doesn't remove it from disk.
696 	 */
697 
698 	/*
699 	 * We don't technically need a config lock here, since there shouldn't
700 	 * be pool config changes during DDT load. dva_get_dsize_sync() via
701 	 * ddt_stat_generate() is expecting it though, and it won't hurt
702 	 * anything, so we take it.
703 	 */
704 	spa_config_enter(ddt->ddt_spa, SCL_STATE, FTAG, RW_READER);
705 
706 	avl_tree_t *al = &ddt->ddt_log_active->ddl_tree;
707 	avl_tree_t *fl = &ddt->ddt_log_flushing->ddl_tree;
708 	ddt_log_entry_t *ae = avl_first(al);
709 	ddt_log_entry_t *fe = avl_first(fl);
710 	while (ae != NULL || fe != NULL) {
711 		ddt_log_entry_t *ddle;
712 		if (ae == NULL) {
713 			/* active exhausted, take flushing */
714 			ddle = fe;
715 			fe = AVL_NEXT(fl, fe);
716 		} else if (fe == NULL) {
717 			/* flushing exuhausted, take active */
718 			ddle = ae;
719 			ae = AVL_NEXT(al, ae);
720 		} else {
721 			/* compare active and flushing */
722 			int c = ddt_key_compare(&ae->ddle_key, &fe->ddle_key);
723 			if (c < 0) {
724 				/* active behind, take and advance */
725 				ddle = ae;
726 				ae = AVL_NEXT(al, ae);
727 			} else if (c > 0) {
728 				/* flushing behind, take and advance */
729 				ddle = fe;
730 				fe = AVL_NEXT(fl, fe);
731 			} else {
732 				/* match. remove from flushing, take active */
733 				ddle = fe;
734 				fe = AVL_NEXT(fl, fe);
735 				avl_remove(fl, ddle);
736 				ddt_log_free_entry(ddt, ddle);
737 				ddle = ae;
738 				ae = AVL_NEXT(al, ae);
739 			}
740 		}
741 
742 		ddt_lightweight_entry_t ddlwe;
743 		DDT_LOG_ENTRY_TO_LIGHTWEIGHT(ddt, ddle, &ddlwe);
744 		ddt_histogram_add_entry(ddt, &ddt->ddt_log_histogram, &ddlwe);
745 	}
746 
747 	spa_config_exit(ddt->ddt_spa, SCL_STATE, FTAG);
748 
749 	ddt_log_update_stats(ddt);
750 
751 	return (0);
752 }
753 
754 void
755 ddt_log_alloc(ddt_t *ddt)
756 {
757 	ASSERT0P(ddt->ddt_log_active);
758 	ASSERT0P(ddt->ddt_log_flushing);
759 
760 	avl_create(&ddt->ddt_log[0].ddl_tree, ddt_key_compare,
761 	    sizeof (ddt_log_entry_t), offsetof(ddt_log_entry_t, ddle_node));
762 	avl_create(&ddt->ddt_log[1].ddl_tree, ddt_key_compare,
763 	    sizeof (ddt_log_entry_t), offsetof(ddt_log_entry_t, ddle_node));
764 	ddt->ddt_log_active = &ddt->ddt_log[0];
765 	ddt->ddt_log_flushing = &ddt->ddt_log[1];
766 	ddt->ddt_log_flushing->ddl_flags |= DDL_FLAG_FLUSHING;
767 }
768 
769 void
770 ddt_log_free(ddt_t *ddt)
771 {
772 	ddt_log_empty(ddt, &ddt->ddt_log[0]);
773 	ddt_log_empty(ddt, &ddt->ddt_log[1]);
774 	avl_destroy(&ddt->ddt_log[0].ddl_tree);
775 	avl_destroy(&ddt->ddt_log[1].ddl_tree);
776 }
777 
778 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_txg_max, UINT, ZMOD_RW,
779 	"Max transactions before starting to flush dedup logs");
780 
781 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_mem_max, U64, ZMOD_RD,
782 	"Max memory for dedup logs");
783 
784 ZFS_MODULE_PARAM(zfs_dedup, zfs_dedup_, log_mem_max_percent, UINT, ZMOD_RD,
785 	"Max memory for dedup logs, as % of total memory");
786