xref: /freebsd/sys/contrib/openzfs/module/zfs/zil.c (revision 63f537551380d2dab29fa402ad1269feae17e594)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Integros [integros.com]
25  * Copyright (c) 2018 Datto Inc.
26  */
27 
28 /* Portions Copyright 2010 Robert Milkowski */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/spa.h>
32 #include <sys/spa_impl.h>
33 #include <sys/dmu.h>
34 #include <sys/zap.h>
35 #include <sys/arc.h>
36 #include <sys/stat.h>
37 #include <sys/zil.h>
38 #include <sys/zil_impl.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/vdev_impl.h>
41 #include <sys/dmu_tx.h>
42 #include <sys/dsl_pool.h>
43 #include <sys/metaslab.h>
44 #include <sys/trace_zfs.h>
45 #include <sys/abd.h>
46 #include <sys/brt.h>
47 #include <sys/wmsum.h>
48 
49 /*
50  * The ZFS Intent Log (ZIL) saves "transaction records" (itxs) of system
51  * calls that change the file system. Each itx has enough information to
52  * be able to replay them after a system crash, power loss, or
53  * equivalent failure mode. These are stored in memory until either:
54  *
55  *   1. they are committed to the pool by the DMU transaction group
56  *      (txg), at which point they can be discarded; or
57  *   2. they are committed to the on-disk ZIL for the dataset being
58  *      modified (e.g. due to an fsync, O_DSYNC, or other synchronous
59  *      requirement).
60  *
61  * In the event of a crash or power loss, the itxs contained by each
62  * dataset's on-disk ZIL will be replayed when that dataset is first
63  * instantiated (e.g. if the dataset is a normal filesystem, when it is
64  * first mounted).
65  *
66  * As hinted at above, there is one ZIL per dataset (both the in-memory
67  * representation, and the on-disk representation). The on-disk format
68  * consists of 3 parts:
69  *
70  * 	- a single, per-dataset, ZIL header; which points to a chain of
71  * 	- zero or more ZIL blocks; each of which contains
72  * 	- zero or more ZIL records
73  *
74  * A ZIL record holds the information necessary to replay a single
75  * system call transaction. A ZIL block can hold many ZIL records, and
76  * the blocks are chained together, similarly to a singly linked list.
77  *
78  * Each ZIL block contains a block pointer (blkptr_t) to the next ZIL
79  * block in the chain, and the ZIL header points to the first block in
80  * the chain.
81  *
82  * Note, there is not a fixed place in the pool to hold these ZIL
83  * blocks; they are dynamically allocated and freed as needed from the
84  * blocks available on the pool, though they can be preferentially
85  * allocated from a dedicated "log" vdev.
86  */
87 
88 /*
89  * This controls the amount of time that a ZIL block (lwb) will remain
90  * "open" when it isn't "full", and it has a thread waiting for it to be
91  * committed to stable storage. Please refer to the zil_commit_waiter()
92  * function (and the comments within it) for more details.
93  */
94 static uint_t zfs_commit_timeout_pct = 5;
95 
96 /*
97  * Minimal time we care to delay commit waiting for more ZIL records.
98  * At least FreeBSD kernel can't sleep for less than 2us at its best.
99  * So requests to sleep for less then 5us is a waste of CPU time with
100  * a risk of significant log latency increase due to oversleep.
101  */
102 static uint64_t zil_min_commit_timeout = 5000;
103 
104 /*
105  * See zil.h for more information about these fields.
106  */
107 static zil_kstat_values_t zil_stats = {
108 	{ "zil_commit_count",			KSTAT_DATA_UINT64 },
109 	{ "zil_commit_writer_count",		KSTAT_DATA_UINT64 },
110 	{ "zil_itx_count",			KSTAT_DATA_UINT64 },
111 	{ "zil_itx_indirect_count",		KSTAT_DATA_UINT64 },
112 	{ "zil_itx_indirect_bytes",		KSTAT_DATA_UINT64 },
113 	{ "zil_itx_copied_count",		KSTAT_DATA_UINT64 },
114 	{ "zil_itx_copied_bytes",		KSTAT_DATA_UINT64 },
115 	{ "zil_itx_needcopy_count",		KSTAT_DATA_UINT64 },
116 	{ "zil_itx_needcopy_bytes",		KSTAT_DATA_UINT64 },
117 	{ "zil_itx_metaslab_normal_count",	KSTAT_DATA_UINT64 },
118 	{ "zil_itx_metaslab_normal_bytes",	KSTAT_DATA_UINT64 },
119 	{ "zil_itx_metaslab_normal_write",	KSTAT_DATA_UINT64 },
120 	{ "zil_itx_metaslab_normal_alloc",	KSTAT_DATA_UINT64 },
121 	{ "zil_itx_metaslab_slog_count",	KSTAT_DATA_UINT64 },
122 	{ "zil_itx_metaslab_slog_bytes",	KSTAT_DATA_UINT64 },
123 	{ "zil_itx_metaslab_slog_write",	KSTAT_DATA_UINT64 },
124 	{ "zil_itx_metaslab_slog_alloc",	KSTAT_DATA_UINT64 },
125 };
126 
127 static zil_sums_t zil_sums_global;
128 static kstat_t *zil_kstats_global;
129 
130 /*
131  * Disable intent logging replay.  This global ZIL switch affects all pools.
132  */
133 int zil_replay_disable = 0;
134 
135 /*
136  * Disable the DKIOCFLUSHWRITECACHE commands that are normally sent to
137  * the disk(s) by the ZIL after an LWB write has completed. Setting this
138  * will cause ZIL corruption on power loss if a volatile out-of-order
139  * write cache is enabled.
140  */
141 static int zil_nocacheflush = 0;
142 
143 /*
144  * Limit SLOG write size per commit executed with synchronous priority.
145  * Any writes above that will be executed with lower (asynchronous) priority
146  * to limit potential SLOG device abuse by single active ZIL writer.
147  */
148 static uint64_t zil_slog_bulk = 768 * 1024;
149 
150 static kmem_cache_t *zil_lwb_cache;
151 static kmem_cache_t *zil_zcw_cache;
152 
153 static void zil_lwb_commit(zilog_t *zilog, lwb_t *lwb, itx_t *itx);
154 static itx_t *zil_itx_clone(itx_t *oitx);
155 
156 static int
157 zil_bp_compare(const void *x1, const void *x2)
158 {
159 	const dva_t *dva1 = &((zil_bp_node_t *)x1)->zn_dva;
160 	const dva_t *dva2 = &((zil_bp_node_t *)x2)->zn_dva;
161 
162 	int cmp = TREE_CMP(DVA_GET_VDEV(dva1), DVA_GET_VDEV(dva2));
163 	if (likely(cmp))
164 		return (cmp);
165 
166 	return (TREE_CMP(DVA_GET_OFFSET(dva1), DVA_GET_OFFSET(dva2)));
167 }
168 
169 static void
170 zil_bp_tree_init(zilog_t *zilog)
171 {
172 	avl_create(&zilog->zl_bp_tree, zil_bp_compare,
173 	    sizeof (zil_bp_node_t), offsetof(zil_bp_node_t, zn_node));
174 }
175 
176 static void
177 zil_bp_tree_fini(zilog_t *zilog)
178 {
179 	avl_tree_t *t = &zilog->zl_bp_tree;
180 	zil_bp_node_t *zn;
181 	void *cookie = NULL;
182 
183 	while ((zn = avl_destroy_nodes(t, &cookie)) != NULL)
184 		kmem_free(zn, sizeof (zil_bp_node_t));
185 
186 	avl_destroy(t);
187 }
188 
189 int
190 zil_bp_tree_add(zilog_t *zilog, const blkptr_t *bp)
191 {
192 	avl_tree_t *t = &zilog->zl_bp_tree;
193 	const dva_t *dva;
194 	zil_bp_node_t *zn;
195 	avl_index_t where;
196 
197 	if (BP_IS_EMBEDDED(bp))
198 		return (0);
199 
200 	dva = BP_IDENTITY(bp);
201 
202 	if (avl_find(t, dva, &where) != NULL)
203 		return (SET_ERROR(EEXIST));
204 
205 	zn = kmem_alloc(sizeof (zil_bp_node_t), KM_SLEEP);
206 	zn->zn_dva = *dva;
207 	avl_insert(t, zn, where);
208 
209 	return (0);
210 }
211 
212 static zil_header_t *
213 zil_header_in_syncing_context(zilog_t *zilog)
214 {
215 	return ((zil_header_t *)zilog->zl_header);
216 }
217 
218 static void
219 zil_init_log_chain(zilog_t *zilog, blkptr_t *bp)
220 {
221 	zio_cksum_t *zc = &bp->blk_cksum;
222 
223 	(void) random_get_pseudo_bytes((void *)&zc->zc_word[ZIL_ZC_GUID_0],
224 	    sizeof (zc->zc_word[ZIL_ZC_GUID_0]));
225 	(void) random_get_pseudo_bytes((void *)&zc->zc_word[ZIL_ZC_GUID_1],
226 	    sizeof (zc->zc_word[ZIL_ZC_GUID_1]));
227 	zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os);
228 	zc->zc_word[ZIL_ZC_SEQ] = 1ULL;
229 }
230 
231 static int
232 zil_kstats_global_update(kstat_t *ksp, int rw)
233 {
234 	zil_kstat_values_t *zs = ksp->ks_data;
235 	ASSERT3P(&zil_stats, ==, zs);
236 
237 	if (rw == KSTAT_WRITE) {
238 		return (SET_ERROR(EACCES));
239 	}
240 
241 	zil_kstat_values_update(zs, &zil_sums_global);
242 
243 	return (0);
244 }
245 
246 /*
247  * Read a log block and make sure it's valid.
248  */
249 static int
250 zil_read_log_block(zilog_t *zilog, boolean_t decrypt, const blkptr_t *bp,
251     blkptr_t *nbp, char **begin, char **end, arc_buf_t **abuf)
252 {
253 	zio_flag_t zio_flags = ZIO_FLAG_CANFAIL;
254 	arc_flags_t aflags = ARC_FLAG_WAIT;
255 	zbookmark_phys_t zb;
256 	int error;
257 
258 	if (zilog->zl_header->zh_claim_txg == 0)
259 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
260 
261 	if (!(zilog->zl_header->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
262 		zio_flags |= ZIO_FLAG_SPECULATIVE;
263 
264 	if (!decrypt)
265 		zio_flags |= ZIO_FLAG_RAW;
266 
267 	SET_BOOKMARK(&zb, bp->blk_cksum.zc_word[ZIL_ZC_OBJSET],
268 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
269 
270 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func,
271 	    abuf, ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
272 
273 	if (error == 0) {
274 		zio_cksum_t cksum = bp->blk_cksum;
275 
276 		/*
277 		 * Validate the checksummed log block.
278 		 *
279 		 * Sequence numbers should be... sequential.  The checksum
280 		 * verifier for the next block should be bp's checksum plus 1.
281 		 *
282 		 * Also check the log chain linkage and size used.
283 		 */
284 		cksum.zc_word[ZIL_ZC_SEQ]++;
285 
286 		uint64_t size = BP_GET_LSIZE(bp);
287 		if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) {
288 			zil_chain_t *zilc = (*abuf)->b_data;
289 			char *lr = (char *)(zilc + 1);
290 
291 			if (memcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
292 			    sizeof (cksum)) ||
293 			    zilc->zc_nused < sizeof (*zilc) ||
294 			    zilc->zc_nused > size) {
295 				error = SET_ERROR(ECKSUM);
296 			} else {
297 				*begin = lr;
298 				*end = lr + zilc->zc_nused - sizeof (*zilc);
299 				*nbp = zilc->zc_next_blk;
300 			}
301 		} else {
302 			char *lr = (*abuf)->b_data;
303 			zil_chain_t *zilc = (zil_chain_t *)(lr + size) - 1;
304 
305 			if (memcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
306 			    sizeof (cksum)) ||
307 			    (zilc->zc_nused > (size - sizeof (*zilc)))) {
308 				error = SET_ERROR(ECKSUM);
309 			} else {
310 				*begin = lr;
311 				*end = lr + zilc->zc_nused;
312 				*nbp = zilc->zc_next_blk;
313 			}
314 		}
315 	}
316 
317 	return (error);
318 }
319 
320 /*
321  * Read a TX_WRITE log data block.
322  */
323 static int
324 zil_read_log_data(zilog_t *zilog, const lr_write_t *lr, void *wbuf)
325 {
326 	zio_flag_t zio_flags = ZIO_FLAG_CANFAIL;
327 	const blkptr_t *bp = &lr->lr_blkptr;
328 	arc_flags_t aflags = ARC_FLAG_WAIT;
329 	arc_buf_t *abuf = NULL;
330 	zbookmark_phys_t zb;
331 	int error;
332 
333 	if (BP_IS_HOLE(bp)) {
334 		if (wbuf != NULL)
335 			memset(wbuf, 0, MAX(BP_GET_LSIZE(bp), lr->lr_length));
336 		return (0);
337 	}
338 
339 	if (zilog->zl_header->zh_claim_txg == 0)
340 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
341 
342 	/*
343 	 * If we are not using the resulting data, we are just checking that
344 	 * it hasn't been corrupted so we don't need to waste CPU time
345 	 * decompressing and decrypting it.
346 	 */
347 	if (wbuf == NULL)
348 		zio_flags |= ZIO_FLAG_RAW;
349 
350 	ASSERT3U(BP_GET_LSIZE(bp), !=, 0);
351 	SET_BOOKMARK(&zb, dmu_objset_id(zilog->zl_os), lr->lr_foid,
352 	    ZB_ZIL_LEVEL, lr->lr_offset / BP_GET_LSIZE(bp));
353 
354 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
355 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
356 
357 	if (error == 0) {
358 		if (wbuf != NULL)
359 			memcpy(wbuf, abuf->b_data, arc_buf_size(abuf));
360 		arc_buf_destroy(abuf, &abuf);
361 	}
362 
363 	return (error);
364 }
365 
366 void
367 zil_sums_init(zil_sums_t *zs)
368 {
369 	wmsum_init(&zs->zil_commit_count, 0);
370 	wmsum_init(&zs->zil_commit_writer_count, 0);
371 	wmsum_init(&zs->zil_itx_count, 0);
372 	wmsum_init(&zs->zil_itx_indirect_count, 0);
373 	wmsum_init(&zs->zil_itx_indirect_bytes, 0);
374 	wmsum_init(&zs->zil_itx_copied_count, 0);
375 	wmsum_init(&zs->zil_itx_copied_bytes, 0);
376 	wmsum_init(&zs->zil_itx_needcopy_count, 0);
377 	wmsum_init(&zs->zil_itx_needcopy_bytes, 0);
378 	wmsum_init(&zs->zil_itx_metaslab_normal_count, 0);
379 	wmsum_init(&zs->zil_itx_metaslab_normal_bytes, 0);
380 	wmsum_init(&zs->zil_itx_metaslab_normal_write, 0);
381 	wmsum_init(&zs->zil_itx_metaslab_normal_alloc, 0);
382 	wmsum_init(&zs->zil_itx_metaslab_slog_count, 0);
383 	wmsum_init(&zs->zil_itx_metaslab_slog_bytes, 0);
384 	wmsum_init(&zs->zil_itx_metaslab_slog_write, 0);
385 	wmsum_init(&zs->zil_itx_metaslab_slog_alloc, 0);
386 }
387 
388 void
389 zil_sums_fini(zil_sums_t *zs)
390 {
391 	wmsum_fini(&zs->zil_commit_count);
392 	wmsum_fini(&zs->zil_commit_writer_count);
393 	wmsum_fini(&zs->zil_itx_count);
394 	wmsum_fini(&zs->zil_itx_indirect_count);
395 	wmsum_fini(&zs->zil_itx_indirect_bytes);
396 	wmsum_fini(&zs->zil_itx_copied_count);
397 	wmsum_fini(&zs->zil_itx_copied_bytes);
398 	wmsum_fini(&zs->zil_itx_needcopy_count);
399 	wmsum_fini(&zs->zil_itx_needcopy_bytes);
400 	wmsum_fini(&zs->zil_itx_metaslab_normal_count);
401 	wmsum_fini(&zs->zil_itx_metaslab_normal_bytes);
402 	wmsum_fini(&zs->zil_itx_metaslab_normal_write);
403 	wmsum_fini(&zs->zil_itx_metaslab_normal_alloc);
404 	wmsum_fini(&zs->zil_itx_metaslab_slog_count);
405 	wmsum_fini(&zs->zil_itx_metaslab_slog_bytes);
406 	wmsum_fini(&zs->zil_itx_metaslab_slog_write);
407 	wmsum_fini(&zs->zil_itx_metaslab_slog_alloc);
408 }
409 
410 void
411 zil_kstat_values_update(zil_kstat_values_t *zs, zil_sums_t *zil_sums)
412 {
413 	zs->zil_commit_count.value.ui64 =
414 	    wmsum_value(&zil_sums->zil_commit_count);
415 	zs->zil_commit_writer_count.value.ui64 =
416 	    wmsum_value(&zil_sums->zil_commit_writer_count);
417 	zs->zil_itx_count.value.ui64 =
418 	    wmsum_value(&zil_sums->zil_itx_count);
419 	zs->zil_itx_indirect_count.value.ui64 =
420 	    wmsum_value(&zil_sums->zil_itx_indirect_count);
421 	zs->zil_itx_indirect_bytes.value.ui64 =
422 	    wmsum_value(&zil_sums->zil_itx_indirect_bytes);
423 	zs->zil_itx_copied_count.value.ui64 =
424 	    wmsum_value(&zil_sums->zil_itx_copied_count);
425 	zs->zil_itx_copied_bytes.value.ui64 =
426 	    wmsum_value(&zil_sums->zil_itx_copied_bytes);
427 	zs->zil_itx_needcopy_count.value.ui64 =
428 	    wmsum_value(&zil_sums->zil_itx_needcopy_count);
429 	zs->zil_itx_needcopy_bytes.value.ui64 =
430 	    wmsum_value(&zil_sums->zil_itx_needcopy_bytes);
431 	zs->zil_itx_metaslab_normal_count.value.ui64 =
432 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_count);
433 	zs->zil_itx_metaslab_normal_bytes.value.ui64 =
434 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_bytes);
435 	zs->zil_itx_metaslab_normal_write.value.ui64 =
436 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_write);
437 	zs->zil_itx_metaslab_normal_alloc.value.ui64 =
438 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_alloc);
439 	zs->zil_itx_metaslab_slog_count.value.ui64 =
440 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_count);
441 	zs->zil_itx_metaslab_slog_bytes.value.ui64 =
442 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_bytes);
443 	zs->zil_itx_metaslab_slog_write.value.ui64 =
444 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_write);
445 	zs->zil_itx_metaslab_slog_alloc.value.ui64 =
446 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_alloc);
447 }
448 
449 /*
450  * Parse the intent log, and call parse_func for each valid record within.
451  */
452 int
453 zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func,
454     zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg,
455     boolean_t decrypt)
456 {
457 	const zil_header_t *zh = zilog->zl_header;
458 	boolean_t claimed = !!zh->zh_claim_txg;
459 	uint64_t claim_blk_seq = claimed ? zh->zh_claim_blk_seq : UINT64_MAX;
460 	uint64_t claim_lr_seq = claimed ? zh->zh_claim_lr_seq : UINT64_MAX;
461 	uint64_t max_blk_seq = 0;
462 	uint64_t max_lr_seq = 0;
463 	uint64_t blk_count = 0;
464 	uint64_t lr_count = 0;
465 	blkptr_t blk, next_blk = {{{{0}}}};
466 	int error = 0;
467 
468 	/*
469 	 * Old logs didn't record the maximum zh_claim_lr_seq.
470 	 */
471 	if (!(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
472 		claim_lr_seq = UINT64_MAX;
473 
474 	/*
475 	 * Starting at the block pointed to by zh_log we read the log chain.
476 	 * For each block in the chain we strongly check that block to
477 	 * ensure its validity.  We stop when an invalid block is found.
478 	 * For each block pointer in the chain we call parse_blk_func().
479 	 * For each record in each valid block we call parse_lr_func().
480 	 * If the log has been claimed, stop if we encounter a sequence
481 	 * number greater than the highest claimed sequence number.
482 	 */
483 	zil_bp_tree_init(zilog);
484 
485 	for (blk = zh->zh_log; !BP_IS_HOLE(&blk); blk = next_blk) {
486 		uint64_t blk_seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
487 		int reclen;
488 		char *lrp, *end;
489 		arc_buf_t *abuf = NULL;
490 
491 		if (blk_seq > claim_blk_seq)
492 			break;
493 
494 		error = parse_blk_func(zilog, &blk, arg, txg);
495 		if (error != 0)
496 			break;
497 		ASSERT3U(max_blk_seq, <, blk_seq);
498 		max_blk_seq = blk_seq;
499 		blk_count++;
500 
501 		if (max_lr_seq == claim_lr_seq && max_blk_seq == claim_blk_seq)
502 			break;
503 
504 		error = zil_read_log_block(zilog, decrypt, &blk, &next_blk,
505 		    &lrp, &end, &abuf);
506 		if (error != 0) {
507 			if (abuf)
508 				arc_buf_destroy(abuf, &abuf);
509 			if (claimed) {
510 				char name[ZFS_MAX_DATASET_NAME_LEN];
511 
512 				dmu_objset_name(zilog->zl_os, name);
513 
514 				cmn_err(CE_WARN, "ZFS read log block error %d, "
515 				    "dataset %s, seq 0x%llx\n", error, name,
516 				    (u_longlong_t)blk_seq);
517 			}
518 			break;
519 		}
520 
521 		for (; lrp < end; lrp += reclen) {
522 			lr_t *lr = (lr_t *)lrp;
523 			reclen = lr->lrc_reclen;
524 			ASSERT3U(reclen, >=, sizeof (lr_t));
525 			if (lr->lrc_seq > claim_lr_seq) {
526 				arc_buf_destroy(abuf, &abuf);
527 				goto done;
528 			}
529 
530 			error = parse_lr_func(zilog, lr, arg, txg);
531 			if (error != 0) {
532 				arc_buf_destroy(abuf, &abuf);
533 				goto done;
534 			}
535 			ASSERT3U(max_lr_seq, <, lr->lrc_seq);
536 			max_lr_seq = lr->lrc_seq;
537 			lr_count++;
538 		}
539 		arc_buf_destroy(abuf, &abuf);
540 	}
541 done:
542 	zilog->zl_parse_error = error;
543 	zilog->zl_parse_blk_seq = max_blk_seq;
544 	zilog->zl_parse_lr_seq = max_lr_seq;
545 	zilog->zl_parse_blk_count = blk_count;
546 	zilog->zl_parse_lr_count = lr_count;
547 
548 	zil_bp_tree_fini(zilog);
549 
550 	return (error);
551 }
552 
553 static int
554 zil_clear_log_block(zilog_t *zilog, const blkptr_t *bp, void *tx,
555     uint64_t first_txg)
556 {
557 	(void) tx;
558 	ASSERT(!BP_IS_HOLE(bp));
559 
560 	/*
561 	 * As we call this function from the context of a rewind to a
562 	 * checkpoint, each ZIL block whose txg is later than the txg
563 	 * that we rewind to is invalid. Thus, we return -1 so
564 	 * zil_parse() doesn't attempt to read it.
565 	 */
566 	if (bp->blk_birth >= first_txg)
567 		return (-1);
568 
569 	if (zil_bp_tree_add(zilog, bp) != 0)
570 		return (0);
571 
572 	zio_free(zilog->zl_spa, first_txg, bp);
573 	return (0);
574 }
575 
576 static int
577 zil_noop_log_record(zilog_t *zilog, const lr_t *lrc, void *tx,
578     uint64_t first_txg)
579 {
580 	(void) zilog, (void) lrc, (void) tx, (void) first_txg;
581 	return (0);
582 }
583 
584 static int
585 zil_claim_log_block(zilog_t *zilog, const blkptr_t *bp, void *tx,
586     uint64_t first_txg)
587 {
588 	/*
589 	 * Claim log block if not already committed and not already claimed.
590 	 * If tx == NULL, just verify that the block is claimable.
591 	 */
592 	if (BP_IS_HOLE(bp) || bp->blk_birth < first_txg ||
593 	    zil_bp_tree_add(zilog, bp) != 0)
594 		return (0);
595 
596 	return (zio_wait(zio_claim(NULL, zilog->zl_spa,
597 	    tx == NULL ? 0 : first_txg, bp, spa_claim_notify, NULL,
598 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB)));
599 }
600 
601 static int
602 zil_claim_write(zilog_t *zilog, const lr_t *lrc, void *tx, uint64_t first_txg)
603 {
604 	lr_write_t *lr = (lr_write_t *)lrc;
605 	int error;
606 
607 	ASSERT(lrc->lrc_txtype == TX_WRITE);
608 
609 	/*
610 	 * If the block is not readable, don't claim it.  This can happen
611 	 * in normal operation when a log block is written to disk before
612 	 * some of the dmu_sync() blocks it points to.  In this case, the
613 	 * transaction cannot have been committed to anyone (we would have
614 	 * waited for all writes to be stable first), so it is semantically
615 	 * correct to declare this the end of the log.
616 	 */
617 	if (lr->lr_blkptr.blk_birth >= first_txg) {
618 		error = zil_read_log_data(zilog, lr, NULL);
619 		if (error != 0)
620 			return (error);
621 	}
622 
623 	return (zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg));
624 }
625 
626 static int
627 zil_claim_clone_range(zilog_t *zilog, const lr_t *lrc, void *tx)
628 {
629 	const lr_clone_range_t *lr = (const lr_clone_range_t *)lrc;
630 	const blkptr_t *bp;
631 	spa_t *spa;
632 	uint_t ii;
633 
634 	ASSERT(lrc->lrc_txtype == TX_CLONE_RANGE);
635 
636 	if (tx == NULL) {
637 		return (0);
638 	}
639 
640 	/*
641 	 * XXX: Do we need to byteswap lr?
642 	 */
643 
644 	spa = zilog->zl_spa;
645 
646 	for (ii = 0; ii < lr->lr_nbps; ii++) {
647 		bp = &lr->lr_bps[ii];
648 
649 		/*
650 		 * When data in embedded into BP there is no need to create
651 		 * BRT entry as there is no data block. Just copy the BP as
652 		 * it contains the data.
653 		 */
654 		if (!BP_IS_HOLE(bp) && !BP_IS_EMBEDDED(bp)) {
655 			brt_pending_add(spa, bp, tx);
656 		}
657 	}
658 
659 	return (0);
660 }
661 
662 static int
663 zil_claim_log_record(zilog_t *zilog, const lr_t *lrc, void *tx,
664     uint64_t first_txg)
665 {
666 
667 	switch (lrc->lrc_txtype) {
668 	case TX_WRITE:
669 		return (zil_claim_write(zilog, lrc, tx, first_txg));
670 	case TX_CLONE_RANGE:
671 		return (zil_claim_clone_range(zilog, lrc, tx));
672 	default:
673 		return (0);
674 	}
675 }
676 
677 static int
678 zil_free_log_block(zilog_t *zilog, const blkptr_t *bp, void *tx,
679     uint64_t claim_txg)
680 {
681 	(void) claim_txg;
682 
683 	zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
684 
685 	return (0);
686 }
687 
688 static int
689 zil_free_write(zilog_t *zilog, const lr_t *lrc, void *tx, uint64_t claim_txg)
690 {
691 	lr_write_t *lr = (lr_write_t *)lrc;
692 	blkptr_t *bp = &lr->lr_blkptr;
693 
694 	ASSERT(lrc->lrc_txtype == TX_WRITE);
695 
696 	/*
697 	 * If we previously claimed it, we need to free it.
698 	 */
699 	if (bp->blk_birth >= claim_txg && zil_bp_tree_add(zilog, bp) == 0 &&
700 	    !BP_IS_HOLE(bp)) {
701 		zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
702 	}
703 
704 	return (0);
705 }
706 
707 static int
708 zil_free_clone_range(zilog_t *zilog, const lr_t *lrc, void *tx)
709 {
710 	const lr_clone_range_t *lr = (const lr_clone_range_t *)lrc;
711 	const blkptr_t *bp;
712 	spa_t *spa;
713 	uint_t ii;
714 
715 	ASSERT(lrc->lrc_txtype == TX_CLONE_RANGE);
716 
717 	if (tx == NULL) {
718 		return (0);
719 	}
720 
721 	spa = zilog->zl_spa;
722 
723 	for (ii = 0; ii < lr->lr_nbps; ii++) {
724 		bp = &lr->lr_bps[ii];
725 
726 		if (!BP_IS_HOLE(bp)) {
727 			zio_free(spa, dmu_tx_get_txg(tx), bp);
728 		}
729 	}
730 
731 	return (0);
732 }
733 
734 static int
735 zil_free_log_record(zilog_t *zilog, const lr_t *lrc, void *tx,
736     uint64_t claim_txg)
737 {
738 
739 	if (claim_txg == 0) {
740 		return (0);
741 	}
742 
743 	switch (lrc->lrc_txtype) {
744 	case TX_WRITE:
745 		return (zil_free_write(zilog, lrc, tx, claim_txg));
746 	case TX_CLONE_RANGE:
747 		return (zil_free_clone_range(zilog, lrc, tx));
748 	default:
749 		return (0);
750 	}
751 }
752 
753 static int
754 zil_lwb_vdev_compare(const void *x1, const void *x2)
755 {
756 	const uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
757 	const uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
758 
759 	return (TREE_CMP(v1, v2));
760 }
761 
762 /*
763  * Allocate a new lwb.  We may already have a block pointer for it, in which
764  * case we get size and version from there.  Or we may not yet, in which case
765  * we choose them here and later make the block allocation match.
766  */
767 static lwb_t *
768 zil_alloc_lwb(zilog_t *zilog, int sz, blkptr_t *bp, boolean_t slog,
769     uint64_t txg, lwb_state_t state)
770 {
771 	lwb_t *lwb;
772 
773 	lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
774 	lwb->lwb_zilog = zilog;
775 	if (bp) {
776 		lwb->lwb_blk = *bp;
777 		lwb->lwb_slim = (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2);
778 		sz = BP_GET_LSIZE(bp);
779 	} else {
780 		BP_ZERO(&lwb->lwb_blk);
781 		lwb->lwb_slim = (spa_version(zilog->zl_spa) >=
782 		    SPA_VERSION_SLIM_ZIL);
783 	}
784 	lwb->lwb_slog = slog;
785 	lwb->lwb_error = 0;
786 	if (lwb->lwb_slim) {
787 		lwb->lwb_nmax = sz;
788 		lwb->lwb_nused = lwb->lwb_nfilled = sizeof (zil_chain_t);
789 	} else {
790 		lwb->lwb_nmax = sz - sizeof (zil_chain_t);
791 		lwb->lwb_nused = lwb->lwb_nfilled = 0;
792 	}
793 	lwb->lwb_sz = sz;
794 	lwb->lwb_state = state;
795 	lwb->lwb_buf = zio_buf_alloc(sz);
796 	lwb->lwb_child_zio = NULL;
797 	lwb->lwb_write_zio = NULL;
798 	lwb->lwb_root_zio = NULL;
799 	lwb->lwb_issued_timestamp = 0;
800 	lwb->lwb_issued_txg = 0;
801 	lwb->lwb_alloc_txg = txg;
802 	lwb->lwb_max_txg = 0;
803 
804 	mutex_enter(&zilog->zl_lock);
805 	list_insert_tail(&zilog->zl_lwb_list, lwb);
806 	if (state != LWB_STATE_NEW)
807 		zilog->zl_last_lwb_opened = lwb;
808 	mutex_exit(&zilog->zl_lock);
809 
810 	return (lwb);
811 }
812 
813 static void
814 zil_free_lwb(zilog_t *zilog, lwb_t *lwb)
815 {
816 	ASSERT(MUTEX_HELD(&zilog->zl_lock));
817 	ASSERT(lwb->lwb_state == LWB_STATE_NEW ||
818 	    lwb->lwb_state == LWB_STATE_FLUSH_DONE);
819 	ASSERT3P(lwb->lwb_child_zio, ==, NULL);
820 	ASSERT3P(lwb->lwb_write_zio, ==, NULL);
821 	ASSERT3P(lwb->lwb_root_zio, ==, NULL);
822 	ASSERT3U(lwb->lwb_alloc_txg, <=, spa_syncing_txg(zilog->zl_spa));
823 	ASSERT3U(lwb->lwb_max_txg, <=, spa_syncing_txg(zilog->zl_spa));
824 	VERIFY(list_is_empty(&lwb->lwb_itxs));
825 	VERIFY(list_is_empty(&lwb->lwb_waiters));
826 	ASSERT(avl_is_empty(&lwb->lwb_vdev_tree));
827 	ASSERT(!MUTEX_HELD(&lwb->lwb_vdev_lock));
828 
829 	/*
830 	 * Clear the zilog's field to indicate this lwb is no longer
831 	 * valid, and prevent use-after-free errors.
832 	 */
833 	if (zilog->zl_last_lwb_opened == lwb)
834 		zilog->zl_last_lwb_opened = NULL;
835 
836 	kmem_cache_free(zil_lwb_cache, lwb);
837 }
838 
839 /*
840  * Called when we create in-memory log transactions so that we know
841  * to cleanup the itxs at the end of spa_sync().
842  */
843 static void
844 zilog_dirty(zilog_t *zilog, uint64_t txg)
845 {
846 	dsl_pool_t *dp = zilog->zl_dmu_pool;
847 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
848 
849 	ASSERT(spa_writeable(zilog->zl_spa));
850 
851 	if (ds->ds_is_snapshot)
852 		panic("dirtying snapshot!");
853 
854 	if (txg_list_add(&dp->dp_dirty_zilogs, zilog, txg)) {
855 		/* up the hold count until we can be written out */
856 		dmu_buf_add_ref(ds->ds_dbuf, zilog);
857 
858 		zilog->zl_dirty_max_txg = MAX(txg, zilog->zl_dirty_max_txg);
859 	}
860 }
861 
862 /*
863  * Determine if the zil is dirty in the specified txg. Callers wanting to
864  * ensure that the dirty state does not change must hold the itxg_lock for
865  * the specified txg. Holding the lock will ensure that the zil cannot be
866  * dirtied (zil_itx_assign) or cleaned (zil_clean) while we check its current
867  * state.
868  */
869 static boolean_t __maybe_unused
870 zilog_is_dirty_in_txg(zilog_t *zilog, uint64_t txg)
871 {
872 	dsl_pool_t *dp = zilog->zl_dmu_pool;
873 
874 	if (txg_list_member(&dp->dp_dirty_zilogs, zilog, txg & TXG_MASK))
875 		return (B_TRUE);
876 	return (B_FALSE);
877 }
878 
879 /*
880  * Determine if the zil is dirty. The zil is considered dirty if it has
881  * any pending itx records that have not been cleaned by zil_clean().
882  */
883 static boolean_t
884 zilog_is_dirty(zilog_t *zilog)
885 {
886 	dsl_pool_t *dp = zilog->zl_dmu_pool;
887 
888 	for (int t = 0; t < TXG_SIZE; t++) {
889 		if (txg_list_member(&dp->dp_dirty_zilogs, zilog, t))
890 			return (B_TRUE);
891 	}
892 	return (B_FALSE);
893 }
894 
895 /*
896  * Its called in zil_commit context (zil_process_commit_list()/zil_create()).
897  * It activates SPA_FEATURE_ZILSAXATTR feature, if its enabled.
898  * Check dsl_dataset_feature_is_active to avoid txg_wait_synced() on every
899  * zil_commit.
900  */
901 static void
902 zil_commit_activate_saxattr_feature(zilog_t *zilog)
903 {
904 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
905 	uint64_t txg = 0;
906 	dmu_tx_t *tx = NULL;
907 
908 	if (spa_feature_is_enabled(zilog->zl_spa, SPA_FEATURE_ZILSAXATTR) &&
909 	    dmu_objset_type(zilog->zl_os) != DMU_OST_ZVOL &&
910 	    !dsl_dataset_feature_is_active(ds, SPA_FEATURE_ZILSAXATTR)) {
911 		tx = dmu_tx_create(zilog->zl_os);
912 		VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
913 		dsl_dataset_dirty(ds, tx);
914 		txg = dmu_tx_get_txg(tx);
915 
916 		mutex_enter(&ds->ds_lock);
917 		ds->ds_feature_activation[SPA_FEATURE_ZILSAXATTR] =
918 		    (void *)B_TRUE;
919 		mutex_exit(&ds->ds_lock);
920 		dmu_tx_commit(tx);
921 		txg_wait_synced(zilog->zl_dmu_pool, txg);
922 	}
923 }
924 
925 /*
926  * Create an on-disk intent log.
927  */
928 static lwb_t *
929 zil_create(zilog_t *zilog)
930 {
931 	const zil_header_t *zh = zilog->zl_header;
932 	lwb_t *lwb = NULL;
933 	uint64_t txg = 0;
934 	dmu_tx_t *tx = NULL;
935 	blkptr_t blk;
936 	int error = 0;
937 	boolean_t slog = FALSE;
938 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
939 
940 
941 	/*
942 	 * Wait for any previous destroy to complete.
943 	 */
944 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
945 
946 	ASSERT(zh->zh_claim_txg == 0);
947 	ASSERT(zh->zh_replay_seq == 0);
948 
949 	blk = zh->zh_log;
950 
951 	/*
952 	 * Allocate an initial log block if:
953 	 *    - there isn't one already
954 	 *    - the existing block is the wrong endianness
955 	 */
956 	if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) {
957 		tx = dmu_tx_create(zilog->zl_os);
958 		VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
959 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
960 		txg = dmu_tx_get_txg(tx);
961 
962 		if (!BP_IS_HOLE(&blk)) {
963 			zio_free(zilog->zl_spa, txg, &blk);
964 			BP_ZERO(&blk);
965 		}
966 
967 		error = zio_alloc_zil(zilog->zl_spa, zilog->zl_os, txg, &blk,
968 		    ZIL_MIN_BLKSZ, &slog);
969 		if (error == 0)
970 			zil_init_log_chain(zilog, &blk);
971 	}
972 
973 	/*
974 	 * Allocate a log write block (lwb) for the first log block.
975 	 */
976 	if (error == 0)
977 		lwb = zil_alloc_lwb(zilog, 0, &blk, slog, txg, LWB_STATE_NEW);
978 
979 	/*
980 	 * If we just allocated the first log block, commit our transaction
981 	 * and wait for zil_sync() to stuff the block pointer into zh_log.
982 	 * (zh is part of the MOS, so we cannot modify it in open context.)
983 	 */
984 	if (tx != NULL) {
985 		/*
986 		 * If "zilsaxattr" feature is enabled on zpool, then activate
987 		 * it now when we're creating the ZIL chain. We can't wait with
988 		 * this until we write the first xattr log record because we
989 		 * need to wait for the feature activation to sync out.
990 		 */
991 		if (spa_feature_is_enabled(zilog->zl_spa,
992 		    SPA_FEATURE_ZILSAXATTR) && dmu_objset_type(zilog->zl_os) !=
993 		    DMU_OST_ZVOL) {
994 			mutex_enter(&ds->ds_lock);
995 			ds->ds_feature_activation[SPA_FEATURE_ZILSAXATTR] =
996 			    (void *)B_TRUE;
997 			mutex_exit(&ds->ds_lock);
998 		}
999 
1000 		dmu_tx_commit(tx);
1001 		txg_wait_synced(zilog->zl_dmu_pool, txg);
1002 	} else {
1003 		/*
1004 		 * This branch covers the case where we enable the feature on a
1005 		 * zpool that has existing ZIL headers.
1006 		 */
1007 		zil_commit_activate_saxattr_feature(zilog);
1008 	}
1009 	IMPLY(spa_feature_is_enabled(zilog->zl_spa, SPA_FEATURE_ZILSAXATTR) &&
1010 	    dmu_objset_type(zilog->zl_os) != DMU_OST_ZVOL,
1011 	    dsl_dataset_feature_is_active(ds, SPA_FEATURE_ZILSAXATTR));
1012 
1013 	ASSERT(error != 0 || memcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
1014 	IMPLY(error == 0, lwb != NULL);
1015 
1016 	return (lwb);
1017 }
1018 
1019 /*
1020  * In one tx, free all log blocks and clear the log header. If keep_first
1021  * is set, then we're replaying a log with no content. We want to keep the
1022  * first block, however, so that the first synchronous transaction doesn't
1023  * require a txg_wait_synced() in zil_create(). We don't need to
1024  * txg_wait_synced() here either when keep_first is set, because both
1025  * zil_create() and zil_destroy() will wait for any in-progress destroys
1026  * to complete.
1027  * Return B_TRUE if there were any entries to replay.
1028  */
1029 boolean_t
1030 zil_destroy(zilog_t *zilog, boolean_t keep_first)
1031 {
1032 	const zil_header_t *zh = zilog->zl_header;
1033 	lwb_t *lwb;
1034 	dmu_tx_t *tx;
1035 	uint64_t txg;
1036 
1037 	/*
1038 	 * Wait for any previous destroy to complete.
1039 	 */
1040 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
1041 
1042 	zilog->zl_old_header = *zh;		/* debugging aid */
1043 
1044 	if (BP_IS_HOLE(&zh->zh_log))
1045 		return (B_FALSE);
1046 
1047 	tx = dmu_tx_create(zilog->zl_os);
1048 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
1049 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1050 	txg = dmu_tx_get_txg(tx);
1051 
1052 	mutex_enter(&zilog->zl_lock);
1053 
1054 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
1055 	zilog->zl_destroy_txg = txg;
1056 	zilog->zl_keep_first = keep_first;
1057 
1058 	if (!list_is_empty(&zilog->zl_lwb_list)) {
1059 		ASSERT(zh->zh_claim_txg == 0);
1060 		VERIFY(!keep_first);
1061 		while ((lwb = list_remove_head(&zilog->zl_lwb_list)) != NULL) {
1062 			if (lwb->lwb_buf != NULL)
1063 				zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1064 			if (!BP_IS_HOLE(&lwb->lwb_blk))
1065 				zio_free(zilog->zl_spa, txg, &lwb->lwb_blk);
1066 			zil_free_lwb(zilog, lwb);
1067 		}
1068 	} else if (!keep_first) {
1069 		zil_destroy_sync(zilog, tx);
1070 	}
1071 	mutex_exit(&zilog->zl_lock);
1072 
1073 	dmu_tx_commit(tx);
1074 
1075 	return (B_TRUE);
1076 }
1077 
1078 void
1079 zil_destroy_sync(zilog_t *zilog, dmu_tx_t *tx)
1080 {
1081 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
1082 	(void) zil_parse(zilog, zil_free_log_block,
1083 	    zil_free_log_record, tx, zilog->zl_header->zh_claim_txg, B_FALSE);
1084 }
1085 
1086 int
1087 zil_claim(dsl_pool_t *dp, dsl_dataset_t *ds, void *txarg)
1088 {
1089 	dmu_tx_t *tx = txarg;
1090 	zilog_t *zilog;
1091 	uint64_t first_txg;
1092 	zil_header_t *zh;
1093 	objset_t *os;
1094 	int error;
1095 
1096 	error = dmu_objset_own_obj(dp, ds->ds_object,
1097 	    DMU_OST_ANY, B_FALSE, B_FALSE, FTAG, &os);
1098 	if (error != 0) {
1099 		/*
1100 		 * EBUSY indicates that the objset is inconsistent, in which
1101 		 * case it can not have a ZIL.
1102 		 */
1103 		if (error != EBUSY) {
1104 			cmn_err(CE_WARN, "can't open objset for %llu, error %u",
1105 			    (unsigned long long)ds->ds_object, error);
1106 		}
1107 
1108 		return (0);
1109 	}
1110 
1111 	zilog = dmu_objset_zil(os);
1112 	zh = zil_header_in_syncing_context(zilog);
1113 	ASSERT3U(tx->tx_txg, ==, spa_first_txg(zilog->zl_spa));
1114 	first_txg = spa_min_claim_txg(zilog->zl_spa);
1115 
1116 	/*
1117 	 * If the spa_log_state is not set to be cleared, check whether
1118 	 * the current uberblock is a checkpoint one and if the current
1119 	 * header has been claimed before moving on.
1120 	 *
1121 	 * If the current uberblock is a checkpointed uberblock then
1122 	 * one of the following scenarios took place:
1123 	 *
1124 	 * 1] We are currently rewinding to the checkpoint of the pool.
1125 	 * 2] We crashed in the middle of a checkpoint rewind but we
1126 	 *    did manage to write the checkpointed uberblock to the
1127 	 *    vdev labels, so when we tried to import the pool again
1128 	 *    the checkpointed uberblock was selected from the import
1129 	 *    procedure.
1130 	 *
1131 	 * In both cases we want to zero out all the ZIL blocks, except
1132 	 * the ones that have been claimed at the time of the checkpoint
1133 	 * (their zh_claim_txg != 0). The reason is that these blocks
1134 	 * may be corrupted since we may have reused their locations on
1135 	 * disk after we took the checkpoint.
1136 	 *
1137 	 * We could try to set spa_log_state to SPA_LOG_CLEAR earlier
1138 	 * when we first figure out whether the current uberblock is
1139 	 * checkpointed or not. Unfortunately, that would discard all
1140 	 * the logs, including the ones that are claimed, and we would
1141 	 * leak space.
1142 	 */
1143 	if (spa_get_log_state(zilog->zl_spa) == SPA_LOG_CLEAR ||
1144 	    (zilog->zl_spa->spa_uberblock.ub_checkpoint_txg != 0 &&
1145 	    zh->zh_claim_txg == 0)) {
1146 		if (!BP_IS_HOLE(&zh->zh_log)) {
1147 			(void) zil_parse(zilog, zil_clear_log_block,
1148 			    zil_noop_log_record, tx, first_txg, B_FALSE);
1149 		}
1150 		BP_ZERO(&zh->zh_log);
1151 		if (os->os_encrypted)
1152 			os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1153 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
1154 		dmu_objset_disown(os, B_FALSE, FTAG);
1155 		return (0);
1156 	}
1157 
1158 	/*
1159 	 * If we are not rewinding and opening the pool normally, then
1160 	 * the min_claim_txg should be equal to the first txg of the pool.
1161 	 */
1162 	ASSERT3U(first_txg, ==, spa_first_txg(zilog->zl_spa));
1163 
1164 	/*
1165 	 * Claim all log blocks if we haven't already done so, and remember
1166 	 * the highest claimed sequence number.  This ensures that if we can
1167 	 * read only part of the log now (e.g. due to a missing device),
1168 	 * but we can read the entire log later, we will not try to replay
1169 	 * or destroy beyond the last block we successfully claimed.
1170 	 */
1171 	ASSERT3U(zh->zh_claim_txg, <=, first_txg);
1172 	if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
1173 		(void) zil_parse(zilog, zil_claim_log_block,
1174 		    zil_claim_log_record, tx, first_txg, B_FALSE);
1175 		zh->zh_claim_txg = first_txg;
1176 		zh->zh_claim_blk_seq = zilog->zl_parse_blk_seq;
1177 		zh->zh_claim_lr_seq = zilog->zl_parse_lr_seq;
1178 		if (zilog->zl_parse_lr_count || zilog->zl_parse_blk_count > 1)
1179 			zh->zh_flags |= ZIL_REPLAY_NEEDED;
1180 		zh->zh_flags |= ZIL_CLAIM_LR_SEQ_VALID;
1181 		if (os->os_encrypted)
1182 			os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1183 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
1184 	}
1185 
1186 	ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
1187 	dmu_objset_disown(os, B_FALSE, FTAG);
1188 	return (0);
1189 }
1190 
1191 /*
1192  * Check the log by walking the log chain.
1193  * Checksum errors are ok as they indicate the end of the chain.
1194  * Any other error (no device or read failure) returns an error.
1195  */
1196 int
1197 zil_check_log_chain(dsl_pool_t *dp, dsl_dataset_t *ds, void *tx)
1198 {
1199 	(void) dp;
1200 	zilog_t *zilog;
1201 	objset_t *os;
1202 	blkptr_t *bp;
1203 	int error;
1204 
1205 	ASSERT(tx == NULL);
1206 
1207 	error = dmu_objset_from_ds(ds, &os);
1208 	if (error != 0) {
1209 		cmn_err(CE_WARN, "can't open objset %llu, error %d",
1210 		    (unsigned long long)ds->ds_object, error);
1211 		return (0);
1212 	}
1213 
1214 	zilog = dmu_objset_zil(os);
1215 	bp = (blkptr_t *)&zilog->zl_header->zh_log;
1216 
1217 	if (!BP_IS_HOLE(bp)) {
1218 		vdev_t *vd;
1219 		boolean_t valid = B_TRUE;
1220 
1221 		/*
1222 		 * Check the first block and determine if it's on a log device
1223 		 * which may have been removed or faulted prior to loading this
1224 		 * pool.  If so, there's no point in checking the rest of the
1225 		 * log as its content should have already been synced to the
1226 		 * pool.
1227 		 */
1228 		spa_config_enter(os->os_spa, SCL_STATE, FTAG, RW_READER);
1229 		vd = vdev_lookup_top(os->os_spa, DVA_GET_VDEV(&bp->blk_dva[0]));
1230 		if (vd->vdev_islog && vdev_is_dead(vd))
1231 			valid = vdev_log_state_valid(vd);
1232 		spa_config_exit(os->os_spa, SCL_STATE, FTAG);
1233 
1234 		if (!valid)
1235 			return (0);
1236 
1237 		/*
1238 		 * Check whether the current uberblock is checkpointed (e.g.
1239 		 * we are rewinding) and whether the current header has been
1240 		 * claimed or not. If it hasn't then skip verifying it. We
1241 		 * do this because its ZIL blocks may be part of the pool's
1242 		 * state before the rewind, which is no longer valid.
1243 		 */
1244 		zil_header_t *zh = zil_header_in_syncing_context(zilog);
1245 		if (zilog->zl_spa->spa_uberblock.ub_checkpoint_txg != 0 &&
1246 		    zh->zh_claim_txg == 0)
1247 			return (0);
1248 	}
1249 
1250 	/*
1251 	 * Because tx == NULL, zil_claim_log_block() will not actually claim
1252 	 * any blocks, but just determine whether it is possible to do so.
1253 	 * In addition to checking the log chain, zil_claim_log_block()
1254 	 * will invoke zio_claim() with a done func of spa_claim_notify(),
1255 	 * which will update spa_max_claim_txg.  See spa_load() for details.
1256 	 */
1257 	error = zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx,
1258 	    zilog->zl_header->zh_claim_txg ? -1ULL :
1259 	    spa_min_claim_txg(os->os_spa), B_FALSE);
1260 
1261 	return ((error == ECKSUM || error == ENOENT) ? 0 : error);
1262 }
1263 
1264 /*
1265  * When an itx is "skipped", this function is used to properly mark the
1266  * waiter as "done, and signal any thread(s) waiting on it. An itx can
1267  * be skipped (and not committed to an lwb) for a variety of reasons,
1268  * one of them being that the itx was committed via spa_sync(), prior to
1269  * it being committed to an lwb; this can happen if a thread calling
1270  * zil_commit() is racing with spa_sync().
1271  */
1272 static void
1273 zil_commit_waiter_skip(zil_commit_waiter_t *zcw)
1274 {
1275 	mutex_enter(&zcw->zcw_lock);
1276 	ASSERT3B(zcw->zcw_done, ==, B_FALSE);
1277 	zcw->zcw_done = B_TRUE;
1278 	cv_broadcast(&zcw->zcw_cv);
1279 	mutex_exit(&zcw->zcw_lock);
1280 }
1281 
1282 /*
1283  * This function is used when the given waiter is to be linked into an
1284  * lwb's "lwb_waiter" list; i.e. when the itx is committed to the lwb.
1285  * At this point, the waiter will no longer be referenced by the itx,
1286  * and instead, will be referenced by the lwb.
1287  */
1288 static void
1289 zil_commit_waiter_link_lwb(zil_commit_waiter_t *zcw, lwb_t *lwb)
1290 {
1291 	/*
1292 	 * The lwb_waiters field of the lwb is protected by the zilog's
1293 	 * zl_issuer_lock while the lwb is open and zl_lock otherwise.
1294 	 * zl_issuer_lock also protects leaving the open state.
1295 	 * zcw_lwb setting is protected by zl_issuer_lock and state !=
1296 	 * flush_done, which transition is protected by zl_lock.
1297 	 */
1298 	ASSERT(MUTEX_HELD(&lwb->lwb_zilog->zl_issuer_lock));
1299 	IMPLY(lwb->lwb_state != LWB_STATE_OPENED,
1300 	    MUTEX_HELD(&lwb->lwb_zilog->zl_lock));
1301 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_NEW);
1302 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_FLUSH_DONE);
1303 
1304 	ASSERT(!list_link_active(&zcw->zcw_node));
1305 	list_insert_tail(&lwb->lwb_waiters, zcw);
1306 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
1307 	zcw->zcw_lwb = lwb;
1308 }
1309 
1310 /*
1311  * This function is used when zio_alloc_zil() fails to allocate a ZIL
1312  * block, and the given waiter must be linked to the "nolwb waiters"
1313  * list inside of zil_process_commit_list().
1314  */
1315 static void
1316 zil_commit_waiter_link_nolwb(zil_commit_waiter_t *zcw, list_t *nolwb)
1317 {
1318 	ASSERT(!list_link_active(&zcw->zcw_node));
1319 	list_insert_tail(nolwb, zcw);
1320 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
1321 }
1322 
1323 void
1324 zil_lwb_add_block(lwb_t *lwb, const blkptr_t *bp)
1325 {
1326 	avl_tree_t *t = &lwb->lwb_vdev_tree;
1327 	avl_index_t where;
1328 	zil_vdev_node_t *zv, zvsearch;
1329 	int ndvas = BP_GET_NDVAS(bp);
1330 	int i;
1331 
1332 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_WRITE_DONE);
1333 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_FLUSH_DONE);
1334 
1335 	if (zil_nocacheflush)
1336 		return;
1337 
1338 	mutex_enter(&lwb->lwb_vdev_lock);
1339 	for (i = 0; i < ndvas; i++) {
1340 		zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
1341 		if (avl_find(t, &zvsearch, &where) == NULL) {
1342 			zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
1343 			zv->zv_vdev = zvsearch.zv_vdev;
1344 			avl_insert(t, zv, where);
1345 		}
1346 	}
1347 	mutex_exit(&lwb->lwb_vdev_lock);
1348 }
1349 
1350 static void
1351 zil_lwb_flush_defer(lwb_t *lwb, lwb_t *nlwb)
1352 {
1353 	avl_tree_t *src = &lwb->lwb_vdev_tree;
1354 	avl_tree_t *dst = &nlwb->lwb_vdev_tree;
1355 	void *cookie = NULL;
1356 	zil_vdev_node_t *zv;
1357 
1358 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_WRITE_DONE);
1359 	ASSERT3S(nlwb->lwb_state, !=, LWB_STATE_WRITE_DONE);
1360 	ASSERT3S(nlwb->lwb_state, !=, LWB_STATE_FLUSH_DONE);
1361 
1362 	/*
1363 	 * While 'lwb' is at a point in its lifetime where lwb_vdev_tree does
1364 	 * not need the protection of lwb_vdev_lock (it will only be modified
1365 	 * while holding zilog->zl_lock) as its writes and those of its
1366 	 * children have all completed.  The younger 'nlwb' may be waiting on
1367 	 * future writes to additional vdevs.
1368 	 */
1369 	mutex_enter(&nlwb->lwb_vdev_lock);
1370 	/*
1371 	 * Tear down the 'lwb' vdev tree, ensuring that entries which do not
1372 	 * exist in 'nlwb' are moved to it, freeing any would-be duplicates.
1373 	 */
1374 	while ((zv = avl_destroy_nodes(src, &cookie)) != NULL) {
1375 		avl_index_t where;
1376 
1377 		if (avl_find(dst, zv, &where) == NULL) {
1378 			avl_insert(dst, zv, where);
1379 		} else {
1380 			kmem_free(zv, sizeof (*zv));
1381 		}
1382 	}
1383 	mutex_exit(&nlwb->lwb_vdev_lock);
1384 }
1385 
1386 void
1387 zil_lwb_add_txg(lwb_t *lwb, uint64_t txg)
1388 {
1389 	lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
1390 }
1391 
1392 /*
1393  * This function is a called after all vdevs associated with a given lwb
1394  * write have completed their DKIOCFLUSHWRITECACHE command; or as soon
1395  * as the lwb write completes, if "zil_nocacheflush" is set. Further,
1396  * all "previous" lwb's will have completed before this function is
1397  * called; i.e. this function is called for all previous lwbs before
1398  * it's called for "this" lwb (enforced via zio the dependencies
1399  * configured in zil_lwb_set_zio_dependency()).
1400  *
1401  * The intention is for this function to be called as soon as the
1402  * contents of an lwb are considered "stable" on disk, and will survive
1403  * any sudden loss of power. At this point, any threads waiting for the
1404  * lwb to reach this state are signalled, and the "waiter" structures
1405  * are marked "done".
1406  */
1407 static void
1408 zil_lwb_flush_vdevs_done(zio_t *zio)
1409 {
1410 	lwb_t *lwb = zio->io_private;
1411 	zilog_t *zilog = lwb->lwb_zilog;
1412 	zil_commit_waiter_t *zcw;
1413 	itx_t *itx;
1414 
1415 	spa_config_exit(zilog->zl_spa, SCL_STATE, lwb);
1416 
1417 	hrtime_t t = gethrtime() - lwb->lwb_issued_timestamp;
1418 
1419 	mutex_enter(&zilog->zl_lock);
1420 
1421 	zilog->zl_last_lwb_latency = (zilog->zl_last_lwb_latency * 7 + t) / 8;
1422 
1423 	lwb->lwb_root_zio = NULL;
1424 
1425 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_WRITE_DONE);
1426 	lwb->lwb_state = LWB_STATE_FLUSH_DONE;
1427 
1428 	if (zilog->zl_last_lwb_opened == lwb) {
1429 		/*
1430 		 * Remember the highest committed log sequence number
1431 		 * for ztest. We only update this value when all the log
1432 		 * writes succeeded, because ztest wants to ASSERT that
1433 		 * it got the whole log chain.
1434 		 */
1435 		zilog->zl_commit_lr_seq = zilog->zl_lr_seq;
1436 	}
1437 
1438 	while ((itx = list_remove_head(&lwb->lwb_itxs)) != NULL)
1439 		zil_itx_destroy(itx);
1440 
1441 	while ((zcw = list_remove_head(&lwb->lwb_waiters)) != NULL) {
1442 		mutex_enter(&zcw->zcw_lock);
1443 
1444 		ASSERT3P(zcw->zcw_lwb, ==, lwb);
1445 		zcw->zcw_lwb = NULL;
1446 		/*
1447 		 * We expect any ZIO errors from child ZIOs to have been
1448 		 * propagated "up" to this specific LWB's root ZIO, in
1449 		 * order for this error handling to work correctly. This
1450 		 * includes ZIO errors from either this LWB's write or
1451 		 * flush, as well as any errors from other dependent LWBs
1452 		 * (e.g. a root LWB ZIO that might be a child of this LWB).
1453 		 *
1454 		 * With that said, it's important to note that LWB flush
1455 		 * errors are not propagated up to the LWB root ZIO.
1456 		 * This is incorrect behavior, and results in VDEV flush
1457 		 * errors not being handled correctly here. See the
1458 		 * comment above the call to "zio_flush" for details.
1459 		 */
1460 
1461 		zcw->zcw_zio_error = zio->io_error;
1462 
1463 		ASSERT3B(zcw->zcw_done, ==, B_FALSE);
1464 		zcw->zcw_done = B_TRUE;
1465 		cv_broadcast(&zcw->zcw_cv);
1466 
1467 		mutex_exit(&zcw->zcw_lock);
1468 	}
1469 
1470 	uint64_t txg = lwb->lwb_issued_txg;
1471 
1472 	/* Once we drop the lock, lwb may be freed by zil_sync(). */
1473 	mutex_exit(&zilog->zl_lock);
1474 
1475 	mutex_enter(&zilog->zl_lwb_io_lock);
1476 	ASSERT3U(zilog->zl_lwb_inflight[txg & TXG_MASK], >, 0);
1477 	zilog->zl_lwb_inflight[txg & TXG_MASK]--;
1478 	if (zilog->zl_lwb_inflight[txg & TXG_MASK] == 0)
1479 		cv_broadcast(&zilog->zl_lwb_io_cv);
1480 	mutex_exit(&zilog->zl_lwb_io_lock);
1481 }
1482 
1483 /*
1484  * Wait for the completion of all issued write/flush of that txg provided.
1485  * It guarantees zil_lwb_flush_vdevs_done() is called and returned.
1486  */
1487 static void
1488 zil_lwb_flush_wait_all(zilog_t *zilog, uint64_t txg)
1489 {
1490 	ASSERT3U(txg, ==, spa_syncing_txg(zilog->zl_spa));
1491 
1492 	mutex_enter(&zilog->zl_lwb_io_lock);
1493 	while (zilog->zl_lwb_inflight[txg & TXG_MASK] > 0)
1494 		cv_wait(&zilog->zl_lwb_io_cv, &zilog->zl_lwb_io_lock);
1495 	mutex_exit(&zilog->zl_lwb_io_lock);
1496 
1497 #ifdef ZFS_DEBUG
1498 	mutex_enter(&zilog->zl_lock);
1499 	mutex_enter(&zilog->zl_lwb_io_lock);
1500 	lwb_t *lwb = list_head(&zilog->zl_lwb_list);
1501 	while (lwb != NULL) {
1502 		if (lwb->lwb_issued_txg <= txg) {
1503 			ASSERT(lwb->lwb_state != LWB_STATE_ISSUED);
1504 			ASSERT(lwb->lwb_state != LWB_STATE_WRITE_DONE);
1505 			IMPLY(lwb->lwb_issued_txg > 0,
1506 			    lwb->lwb_state == LWB_STATE_FLUSH_DONE);
1507 		}
1508 		IMPLY(lwb->lwb_state == LWB_STATE_WRITE_DONE ||
1509 		    lwb->lwb_state == LWB_STATE_FLUSH_DONE,
1510 		    lwb->lwb_buf == NULL);
1511 		lwb = list_next(&zilog->zl_lwb_list, lwb);
1512 	}
1513 	mutex_exit(&zilog->zl_lwb_io_lock);
1514 	mutex_exit(&zilog->zl_lock);
1515 #endif
1516 }
1517 
1518 /*
1519  * This is called when an lwb's write zio completes. The callback's
1520  * purpose is to issue the DKIOCFLUSHWRITECACHE commands for the vdevs
1521  * in the lwb's lwb_vdev_tree. The tree will contain the vdevs involved
1522  * in writing out this specific lwb's data, and in the case that cache
1523  * flushes have been deferred, vdevs involved in writing the data for
1524  * previous lwbs. The writes corresponding to all the vdevs in the
1525  * lwb_vdev_tree will have completed by the time this is called, due to
1526  * the zio dependencies configured in zil_lwb_set_zio_dependency(),
1527  * which takes deferred flushes into account. The lwb will be "done"
1528  * once zil_lwb_flush_vdevs_done() is called, which occurs in the zio
1529  * completion callback for the lwb's root zio.
1530  */
1531 static void
1532 zil_lwb_write_done(zio_t *zio)
1533 {
1534 	lwb_t *lwb = zio->io_private;
1535 	spa_t *spa = zio->io_spa;
1536 	zilog_t *zilog = lwb->lwb_zilog;
1537 	avl_tree_t *t = &lwb->lwb_vdev_tree;
1538 	void *cookie = NULL;
1539 	zil_vdev_node_t *zv;
1540 	lwb_t *nlwb;
1541 
1542 	ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), !=, 0);
1543 
1544 	abd_free(zio->io_abd);
1545 	zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1546 	lwb->lwb_buf = NULL;
1547 
1548 	mutex_enter(&zilog->zl_lock);
1549 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_ISSUED);
1550 	lwb->lwb_state = LWB_STATE_WRITE_DONE;
1551 	lwb->lwb_child_zio = NULL;
1552 	lwb->lwb_write_zio = NULL;
1553 
1554 	/*
1555 	 * If nlwb is not yet issued, zil_lwb_set_zio_dependency() is not
1556 	 * called for it yet, and when it will be, it won't be able to make
1557 	 * its write ZIO a parent this ZIO.  In such case we can not defer
1558 	 * our flushes or below may be a race between the done callbacks.
1559 	 */
1560 	nlwb = list_next(&zilog->zl_lwb_list, lwb);
1561 	if (nlwb && nlwb->lwb_state != LWB_STATE_ISSUED)
1562 		nlwb = NULL;
1563 	mutex_exit(&zilog->zl_lock);
1564 
1565 	if (avl_numnodes(t) == 0)
1566 		return;
1567 
1568 	/*
1569 	 * If there was an IO error, we're not going to call zio_flush()
1570 	 * on these vdevs, so we simply empty the tree and free the
1571 	 * nodes. We avoid calling zio_flush() since there isn't any
1572 	 * good reason for doing so, after the lwb block failed to be
1573 	 * written out.
1574 	 *
1575 	 * Additionally, we don't perform any further error handling at
1576 	 * this point (e.g. setting "zcw_zio_error" appropriately), as
1577 	 * we expect that to occur in "zil_lwb_flush_vdevs_done" (thus,
1578 	 * we expect any error seen here, to have been propagated to
1579 	 * that function).
1580 	 */
1581 	if (zio->io_error != 0) {
1582 		while ((zv = avl_destroy_nodes(t, &cookie)) != NULL)
1583 			kmem_free(zv, sizeof (*zv));
1584 		return;
1585 	}
1586 
1587 	/*
1588 	 * If this lwb does not have any threads waiting for it to
1589 	 * complete, we want to defer issuing the DKIOCFLUSHWRITECACHE
1590 	 * command to the vdevs written to by "this" lwb, and instead
1591 	 * rely on the "next" lwb to handle the DKIOCFLUSHWRITECACHE
1592 	 * command for those vdevs. Thus, we merge the vdev tree of
1593 	 * "this" lwb with the vdev tree of the "next" lwb in the list,
1594 	 * and assume the "next" lwb will handle flushing the vdevs (or
1595 	 * deferring the flush(s) again).
1596 	 *
1597 	 * This is a useful performance optimization, especially for
1598 	 * workloads with lots of async write activity and few sync
1599 	 * write and/or fsync activity, as it has the potential to
1600 	 * coalesce multiple flush commands to a vdev into one.
1601 	 */
1602 	if (list_is_empty(&lwb->lwb_waiters) && nlwb != NULL) {
1603 		zil_lwb_flush_defer(lwb, nlwb);
1604 		ASSERT(avl_is_empty(&lwb->lwb_vdev_tree));
1605 		return;
1606 	}
1607 
1608 	while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
1609 		vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
1610 		if (vd != NULL && !vd->vdev_nowritecache) {
1611 			/*
1612 			 * The "ZIO_FLAG_DONT_PROPAGATE" is currently
1613 			 * always used within "zio_flush". This means,
1614 			 * any errors when flushing the vdev(s), will
1615 			 * (unfortunately) not be handled correctly,
1616 			 * since these "zio_flush" errors will not be
1617 			 * propagated up to "zil_lwb_flush_vdevs_done".
1618 			 */
1619 			zio_flush(lwb->lwb_root_zio, vd);
1620 		}
1621 		kmem_free(zv, sizeof (*zv));
1622 	}
1623 }
1624 
1625 /*
1626  * Build the zio dependency chain, which is used to preserve the ordering of
1627  * lwb completions that is required by the semantics of the ZIL. Each new lwb
1628  * zio becomes a parent of the previous lwb zio, such that the new lwb's zio
1629  * cannot complete until the previous lwb's zio completes.
1630  *
1631  * This is required by the semantics of zil_commit(): the commit waiters
1632  * attached to the lwbs will be woken in the lwb zio's completion callback,
1633  * so this zio dependency graph ensures the waiters are woken in the correct
1634  * order (the same order the lwbs were created).
1635  */
1636 static void
1637 zil_lwb_set_zio_dependency(zilog_t *zilog, lwb_t *lwb)
1638 {
1639 	ASSERT(MUTEX_HELD(&zilog->zl_lock));
1640 
1641 	lwb_t *prev_lwb = list_prev(&zilog->zl_lwb_list, lwb);
1642 	if (prev_lwb == NULL ||
1643 	    prev_lwb->lwb_state == LWB_STATE_FLUSH_DONE)
1644 		return;
1645 
1646 	/*
1647 	 * If the previous lwb's write hasn't already completed, we also want
1648 	 * to order the completion of the lwb write zios (above, we only order
1649 	 * the completion of the lwb root zios). This is required because of
1650 	 * how we can defer the DKIOCFLUSHWRITECACHE commands for each lwb.
1651 	 *
1652 	 * When the DKIOCFLUSHWRITECACHE commands are deferred, the previous
1653 	 * lwb will rely on this lwb to flush the vdevs written to by that
1654 	 * previous lwb. Thus, we need to ensure this lwb doesn't issue the
1655 	 * flush until after the previous lwb's write completes. We ensure
1656 	 * this ordering by setting the zio parent/child relationship here.
1657 	 *
1658 	 * Without this relationship on the lwb's write zio, it's possible
1659 	 * for this lwb's write to complete prior to the previous lwb's write
1660 	 * completing; and thus, the vdevs for the previous lwb would be
1661 	 * flushed prior to that lwb's data being written to those vdevs (the
1662 	 * vdevs are flushed in the lwb write zio's completion handler,
1663 	 * zil_lwb_write_done()).
1664 	 */
1665 	if (prev_lwb->lwb_state == LWB_STATE_ISSUED) {
1666 		ASSERT3P(prev_lwb->lwb_write_zio, !=, NULL);
1667 		zio_add_child(lwb->lwb_write_zio, prev_lwb->lwb_write_zio);
1668 	} else {
1669 		ASSERT3S(prev_lwb->lwb_state, ==, LWB_STATE_WRITE_DONE);
1670 	}
1671 
1672 	ASSERT3P(prev_lwb->lwb_root_zio, !=, NULL);
1673 	zio_add_child(lwb->lwb_root_zio, prev_lwb->lwb_root_zio);
1674 }
1675 
1676 
1677 /*
1678  * This function's purpose is to "open" an lwb such that it is ready to
1679  * accept new itxs being committed to it. This function is idempotent; if
1680  * the passed in lwb has already been opened, it is essentially a no-op.
1681  */
1682 static void
1683 zil_lwb_write_open(zilog_t *zilog, lwb_t *lwb)
1684 {
1685 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1686 
1687 	if (lwb->lwb_state != LWB_STATE_NEW) {
1688 		ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
1689 		return;
1690 	}
1691 
1692 	mutex_enter(&zilog->zl_lock);
1693 	lwb->lwb_state = LWB_STATE_OPENED;
1694 	zilog->zl_last_lwb_opened = lwb;
1695 	mutex_exit(&zilog->zl_lock);
1696 }
1697 
1698 /*
1699  * Define a limited set of intent log block sizes.
1700  *
1701  * These must be a multiple of 4KB. Note only the amount used (again
1702  * aligned to 4KB) actually gets written. However, we can't always just
1703  * allocate SPA_OLD_MAXBLOCKSIZE as the slog space could be exhausted.
1704  */
1705 static const struct {
1706 	uint64_t	limit;
1707 	uint64_t	blksz;
1708 } zil_block_buckets[] = {
1709 	{ 4096,		4096 },			/* non TX_WRITE */
1710 	{ 8192 + 4096,	8192 + 4096 },		/* database */
1711 	{ 32768 + 4096,	32768 + 4096 },		/* NFS writes */
1712 	{ 65536 + 4096,	65536 + 4096 },		/* 64KB writes */
1713 	{ 131072,	131072 },		/* < 128KB writes */
1714 	{ 131072 +4096,	65536 + 4096 },		/* 128KB writes */
1715 	{ UINT64_MAX,	SPA_OLD_MAXBLOCKSIZE},	/* > 128KB writes */
1716 };
1717 
1718 /*
1719  * Maximum block size used by the ZIL.  This is picked up when the ZIL is
1720  * initialized.  Otherwise this should not be used directly; see
1721  * zl_max_block_size instead.
1722  */
1723 static uint_t zil_maxblocksize = SPA_OLD_MAXBLOCKSIZE;
1724 
1725 /*
1726  * Close the log block for being issued and allocate the next one.
1727  * Has to be called under zl_issuer_lock to chain more lwbs.
1728  */
1729 static lwb_t *
1730 zil_lwb_write_close(zilog_t *zilog, lwb_t *lwb, lwb_state_t state)
1731 {
1732 	int i;
1733 
1734 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1735 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
1736 	lwb->lwb_state = LWB_STATE_CLOSED;
1737 
1738 	/*
1739 	 * If there was an allocation failure then returned NULL will trigger
1740 	 * zil_commit_writer_stall() at the caller.  This is inherently racy,
1741 	 * since allocation may not have happened yet.
1742 	 */
1743 	if (lwb->lwb_error != 0)
1744 		return (NULL);
1745 
1746 	/*
1747 	 * Log blocks are pre-allocated. Here we select the size of the next
1748 	 * block, based on size used in the last block.
1749 	 * - first find the smallest bucket that will fit the block from a
1750 	 *   limited set of block sizes. This is because it's faster to write
1751 	 *   blocks allocated from the same metaslab as they are adjacent or
1752 	 *   close.
1753 	 * - next find the maximum from the new suggested size and an array of
1754 	 *   previous sizes. This lessens a picket fence effect of wrongly
1755 	 *   guessing the size if we have a stream of say 2k, 64k, 2k, 64k
1756 	 *   requests.
1757 	 *
1758 	 * Note we only write what is used, but we can't just allocate
1759 	 * the maximum block size because we can exhaust the available
1760 	 * pool log space.
1761 	 */
1762 	uint64_t zil_blksz = zilog->zl_cur_used + sizeof (zil_chain_t);
1763 	for (i = 0; zil_blksz > zil_block_buckets[i].limit; i++)
1764 		continue;
1765 	zil_blksz = MIN(zil_block_buckets[i].blksz, zilog->zl_max_block_size);
1766 	zilog->zl_prev_blks[zilog->zl_prev_rotor] = zil_blksz;
1767 	for (i = 0; i < ZIL_PREV_BLKS; i++)
1768 		zil_blksz = MAX(zil_blksz, zilog->zl_prev_blks[i]);
1769 	DTRACE_PROBE3(zil__block__size, zilog_t *, zilog,
1770 	    uint64_t, zil_blksz,
1771 	    uint64_t, zilog->zl_prev_blks[zilog->zl_prev_rotor]);
1772 	zilog->zl_prev_rotor = (zilog->zl_prev_rotor + 1) & (ZIL_PREV_BLKS - 1);
1773 
1774 	return (zil_alloc_lwb(zilog, zil_blksz, NULL, 0, 0, state));
1775 }
1776 
1777 /*
1778  * Finalize previously closed block and issue the write zio.
1779  */
1780 static void
1781 zil_lwb_write_issue(zilog_t *zilog, lwb_t *lwb)
1782 {
1783 	spa_t *spa = zilog->zl_spa;
1784 	zil_chain_t *zilc;
1785 	boolean_t slog;
1786 	zbookmark_phys_t zb;
1787 	zio_priority_t prio;
1788 	int error;
1789 
1790 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_CLOSED);
1791 
1792 	/* Actually fill the lwb with the data. */
1793 	for (itx_t *itx = list_head(&lwb->lwb_itxs); itx;
1794 	    itx = list_next(&lwb->lwb_itxs, itx))
1795 		zil_lwb_commit(zilog, lwb, itx);
1796 	lwb->lwb_nused = lwb->lwb_nfilled;
1797 
1798 	lwb->lwb_root_zio = zio_root(spa, zil_lwb_flush_vdevs_done, lwb,
1799 	    ZIO_FLAG_CANFAIL);
1800 
1801 	/*
1802 	 * The lwb is now ready to be issued, but it can be only if it already
1803 	 * got its block pointer allocated or the allocation has failed.
1804 	 * Otherwise leave it as-is, relying on some other thread to issue it
1805 	 * after allocating its block pointer via calling zil_lwb_write_issue()
1806 	 * for the previous lwb(s) in the chain.
1807 	 */
1808 	mutex_enter(&zilog->zl_lock);
1809 	lwb->lwb_state = LWB_STATE_READY;
1810 	if (BP_IS_HOLE(&lwb->lwb_blk) && lwb->lwb_error == 0) {
1811 		mutex_exit(&zilog->zl_lock);
1812 		return;
1813 	}
1814 	mutex_exit(&zilog->zl_lock);
1815 
1816 next_lwb:
1817 	if (lwb->lwb_slim)
1818 		zilc = (zil_chain_t *)lwb->lwb_buf;
1819 	else
1820 		zilc = (zil_chain_t *)(lwb->lwb_buf + lwb->lwb_nmax);
1821 	int wsz = lwb->lwb_sz;
1822 	if (lwb->lwb_error == 0) {
1823 		abd_t *lwb_abd = abd_get_from_buf(lwb->lwb_buf, lwb->lwb_sz);
1824 		if (!lwb->lwb_slog || zilog->zl_cur_used <= zil_slog_bulk)
1825 			prio = ZIO_PRIORITY_SYNC_WRITE;
1826 		else
1827 			prio = ZIO_PRIORITY_ASYNC_WRITE;
1828 		SET_BOOKMARK(&zb, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1829 		    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL,
1830 		    lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ]);
1831 		lwb->lwb_write_zio = zio_rewrite(lwb->lwb_root_zio, spa, 0,
1832 		    &lwb->lwb_blk, lwb_abd, lwb->lwb_sz, zil_lwb_write_done,
1833 		    lwb, prio, ZIO_FLAG_CANFAIL, &zb);
1834 		zil_lwb_add_block(lwb, &lwb->lwb_blk);
1835 
1836 		if (lwb->lwb_slim) {
1837 			/* For Slim ZIL only write what is used. */
1838 			wsz = P2ROUNDUP_TYPED(lwb->lwb_nused, ZIL_MIN_BLKSZ,
1839 			    int);
1840 			ASSERT3S(wsz, <=, lwb->lwb_sz);
1841 			zio_shrink(lwb->lwb_write_zio, wsz);
1842 			wsz = lwb->lwb_write_zio->io_size;
1843 		}
1844 		memset(lwb->lwb_buf + lwb->lwb_nused, 0, wsz - lwb->lwb_nused);
1845 		zilc->zc_pad = 0;
1846 		zilc->zc_nused = lwb->lwb_nused;
1847 		zilc->zc_eck.zec_cksum = lwb->lwb_blk.blk_cksum;
1848 	} else {
1849 		/*
1850 		 * We can't write the lwb if there was an allocation failure,
1851 		 * so create a null zio instead just to maintain dependencies.
1852 		 */
1853 		lwb->lwb_write_zio = zio_null(lwb->lwb_root_zio, spa, NULL,
1854 		    zil_lwb_write_done, lwb, ZIO_FLAG_CANFAIL);
1855 		lwb->lwb_write_zio->io_error = lwb->lwb_error;
1856 	}
1857 	if (lwb->lwb_child_zio)
1858 		zio_add_child(lwb->lwb_write_zio, lwb->lwb_child_zio);
1859 
1860 	/*
1861 	 * Open transaction to allocate the next block pointer.
1862 	 */
1863 	dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
1864 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT | TXG_NOTHROTTLE));
1865 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1866 	uint64_t txg = dmu_tx_get_txg(tx);
1867 
1868 	/*
1869 	 * Allocate next the block pointer unless we are already in error.
1870 	 */
1871 	lwb_t *nlwb = list_next(&zilog->zl_lwb_list, lwb);
1872 	blkptr_t *bp = &zilc->zc_next_blk;
1873 	BP_ZERO(bp);
1874 	error = lwb->lwb_error;
1875 	if (error == 0) {
1876 		error = zio_alloc_zil(spa, zilog->zl_os, txg, bp, nlwb->lwb_sz,
1877 		    &slog);
1878 	}
1879 	if (error == 0) {
1880 		ASSERT3U(bp->blk_birth, ==, txg);
1881 		BP_SET_CHECKSUM(bp, nlwb->lwb_slim ? ZIO_CHECKSUM_ZILOG2 :
1882 		    ZIO_CHECKSUM_ZILOG);
1883 		bp->blk_cksum = lwb->lwb_blk.blk_cksum;
1884 		bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
1885 	}
1886 
1887 	/*
1888 	 * Reduce TXG open time by incrementing inflight counter and committing
1889 	 * the transaciton.  zil_sync() will wait for it to return to zero.
1890 	 */
1891 	mutex_enter(&zilog->zl_lwb_io_lock);
1892 	lwb->lwb_issued_txg = txg;
1893 	zilog->zl_lwb_inflight[txg & TXG_MASK]++;
1894 	zilog->zl_lwb_max_issued_txg = MAX(txg, zilog->zl_lwb_max_issued_txg);
1895 	mutex_exit(&zilog->zl_lwb_io_lock);
1896 	dmu_tx_commit(tx);
1897 
1898 	spa_config_enter(spa, SCL_STATE, lwb, RW_READER);
1899 
1900 	/*
1901 	 * We've completed all potentially blocking operations.  Update the
1902 	 * nlwb and allow it proceed without possible lock order reversals.
1903 	 */
1904 	mutex_enter(&zilog->zl_lock);
1905 	zil_lwb_set_zio_dependency(zilog, lwb);
1906 	lwb->lwb_state = LWB_STATE_ISSUED;
1907 
1908 	if (nlwb) {
1909 		nlwb->lwb_blk = *bp;
1910 		nlwb->lwb_error = error;
1911 		nlwb->lwb_slog = slog;
1912 		nlwb->lwb_alloc_txg = txg;
1913 		if (nlwb->lwb_state != LWB_STATE_READY)
1914 			nlwb = NULL;
1915 	}
1916 	mutex_exit(&zilog->zl_lock);
1917 
1918 	if (lwb->lwb_slog) {
1919 		ZIL_STAT_BUMP(zilog, zil_itx_metaslab_slog_count);
1920 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_slog_bytes,
1921 		    lwb->lwb_nused);
1922 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_slog_write,
1923 		    wsz);
1924 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_slog_alloc,
1925 		    BP_GET_LSIZE(&lwb->lwb_blk));
1926 	} else {
1927 		ZIL_STAT_BUMP(zilog, zil_itx_metaslab_normal_count);
1928 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_normal_bytes,
1929 		    lwb->lwb_nused);
1930 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_normal_write,
1931 		    wsz);
1932 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_normal_alloc,
1933 		    BP_GET_LSIZE(&lwb->lwb_blk));
1934 	}
1935 	lwb->lwb_issued_timestamp = gethrtime();
1936 	if (lwb->lwb_child_zio)
1937 		zio_nowait(lwb->lwb_child_zio);
1938 	zio_nowait(lwb->lwb_write_zio);
1939 	zio_nowait(lwb->lwb_root_zio);
1940 
1941 	/*
1942 	 * If nlwb was ready when we gave it the block pointer,
1943 	 * it is on us to issue it and possibly following ones.
1944 	 */
1945 	lwb = nlwb;
1946 	if (lwb)
1947 		goto next_lwb;
1948 }
1949 
1950 /*
1951  * Maximum amount of data that can be put into single log block.
1952  */
1953 uint64_t
1954 zil_max_log_data(zilog_t *zilog, size_t hdrsize)
1955 {
1956 	return (zilog->zl_max_block_size - sizeof (zil_chain_t) - hdrsize);
1957 }
1958 
1959 /*
1960  * Maximum amount of log space we agree to waste to reduce number of
1961  * WR_NEED_COPY chunks to reduce zl_get_data() overhead (~6%).
1962  */
1963 static inline uint64_t
1964 zil_max_waste_space(zilog_t *zilog)
1965 {
1966 	return (zil_max_log_data(zilog, sizeof (lr_write_t)) / 16);
1967 }
1968 
1969 /*
1970  * Maximum amount of write data for WR_COPIED.  For correctness, consumers
1971  * must fall back to WR_NEED_COPY if we can't fit the entire record into one
1972  * maximum sized log block, because each WR_COPIED record must fit in a
1973  * single log block.  Below that it is a tradeoff of additional memory copy
1974  * and possibly worse log space efficiency vs additional range lock/unlock.
1975  */
1976 static uint_t zil_maxcopied = 7680;
1977 
1978 uint64_t
1979 zil_max_copied_data(zilog_t *zilog)
1980 {
1981 	uint64_t max_data = zil_max_log_data(zilog, sizeof (lr_write_t));
1982 	return (MIN(max_data, zil_maxcopied));
1983 }
1984 
1985 /*
1986  * Estimate space needed in the lwb for the itx.  Allocate more lwbs or
1987  * split the itx as needed, but don't touch the actual transaction data.
1988  * Has to be called under zl_issuer_lock to call zil_lwb_write_close()
1989  * to chain more lwbs.
1990  */
1991 static lwb_t *
1992 zil_lwb_assign(zilog_t *zilog, lwb_t *lwb, itx_t *itx, list_t *ilwbs)
1993 {
1994 	itx_t *citx;
1995 	lr_t *lr, *clr;
1996 	lr_write_t *lrw;
1997 	uint64_t dlen, dnow, lwb_sp, reclen, max_log_data;
1998 
1999 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2000 	ASSERT3P(lwb, !=, NULL);
2001 	ASSERT3P(lwb->lwb_buf, !=, NULL);
2002 
2003 	zil_lwb_write_open(zilog, lwb);
2004 
2005 	lr = &itx->itx_lr;
2006 	lrw = (lr_write_t *)lr;
2007 
2008 	/*
2009 	 * A commit itx doesn't represent any on-disk state; instead
2010 	 * it's simply used as a place holder on the commit list, and
2011 	 * provides a mechanism for attaching a "commit waiter" onto the
2012 	 * correct lwb (such that the waiter can be signalled upon
2013 	 * completion of that lwb). Thus, we don't process this itx's
2014 	 * log record if it's a commit itx (these itx's don't have log
2015 	 * records), and instead link the itx's waiter onto the lwb's
2016 	 * list of waiters.
2017 	 *
2018 	 * For more details, see the comment above zil_commit().
2019 	 */
2020 	if (lr->lrc_txtype == TX_COMMIT) {
2021 		zil_commit_waiter_link_lwb(itx->itx_private, lwb);
2022 		list_insert_tail(&lwb->lwb_itxs, itx);
2023 		return (lwb);
2024 	}
2025 
2026 	if (lr->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY) {
2027 		dlen = P2ROUNDUP_TYPED(
2028 		    lrw->lr_length, sizeof (uint64_t), uint64_t);
2029 	} else {
2030 		dlen = 0;
2031 	}
2032 	reclen = lr->lrc_reclen;
2033 	zilog->zl_cur_used += (reclen + dlen);
2034 
2035 cont:
2036 	/*
2037 	 * If this record won't fit in the current log block, start a new one.
2038 	 * For WR_NEED_COPY optimize layout for minimal number of chunks.
2039 	 */
2040 	lwb_sp = lwb->lwb_nmax - lwb->lwb_nused;
2041 	max_log_data = zil_max_log_data(zilog, sizeof (lr_write_t));
2042 	if (reclen > lwb_sp || (reclen + dlen > lwb_sp &&
2043 	    lwb_sp < zil_max_waste_space(zilog) &&
2044 	    (dlen % max_log_data == 0 ||
2045 	    lwb_sp < reclen + dlen % max_log_data))) {
2046 		list_insert_tail(ilwbs, lwb);
2047 		lwb = zil_lwb_write_close(zilog, lwb, LWB_STATE_OPENED);
2048 		if (lwb == NULL)
2049 			return (NULL);
2050 		lwb_sp = lwb->lwb_nmax - lwb->lwb_nused;
2051 
2052 		/*
2053 		 * There must be enough space in the new, empty log block to
2054 		 * hold reclen.  For WR_COPIED, we need to fit the whole
2055 		 * record in one block, and reclen is the header size + the
2056 		 * data size. For WR_NEED_COPY, we can create multiple
2057 		 * records, splitting the data into multiple blocks, so we
2058 		 * only need to fit one word of data per block; in this case
2059 		 * reclen is just the header size (no data).
2060 		 */
2061 		ASSERT3U(reclen + MIN(dlen, sizeof (uint64_t)), <=, lwb_sp);
2062 	}
2063 
2064 	dnow = MIN(dlen, lwb_sp - reclen);
2065 	if (dlen > dnow) {
2066 		ASSERT3U(lr->lrc_txtype, ==, TX_WRITE);
2067 		ASSERT3U(itx->itx_wr_state, ==, WR_NEED_COPY);
2068 		citx = zil_itx_clone(itx);
2069 		clr = &citx->itx_lr;
2070 		lr_write_t *clrw = (lr_write_t *)clr;
2071 		clrw->lr_length = dnow;
2072 		lrw->lr_offset += dnow;
2073 		lrw->lr_length -= dnow;
2074 	} else {
2075 		citx = itx;
2076 		clr = lr;
2077 	}
2078 
2079 	/*
2080 	 * We're actually making an entry, so update lrc_seq to be the
2081 	 * log record sequence number.  Note that this is generally not
2082 	 * equal to the itx sequence number because not all transactions
2083 	 * are synchronous, and sometimes spa_sync() gets there first.
2084 	 */
2085 	clr->lrc_seq = ++zilog->zl_lr_seq;
2086 
2087 	lwb->lwb_nused += reclen + dnow;
2088 	ASSERT3U(lwb->lwb_nused, <=, lwb->lwb_nmax);
2089 	ASSERT0(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)));
2090 
2091 	zil_lwb_add_txg(lwb, lr->lrc_txg);
2092 	list_insert_tail(&lwb->lwb_itxs, citx);
2093 
2094 	dlen -= dnow;
2095 	if (dlen > 0) {
2096 		zilog->zl_cur_used += reclen;
2097 		goto cont;
2098 	}
2099 
2100 	if (lr->lrc_txtype == TX_WRITE &&
2101 	    lr->lrc_txg > spa_freeze_txg(zilog->zl_spa))
2102 		txg_wait_synced(zilog->zl_dmu_pool, lr->lrc_txg);
2103 
2104 	return (lwb);
2105 }
2106 
2107 /*
2108  * Fill the actual transaction data into the lwb, following zil_lwb_assign().
2109  * Does not require locking.
2110  */
2111 static void
2112 zil_lwb_commit(zilog_t *zilog, lwb_t *lwb, itx_t *itx)
2113 {
2114 	lr_t *lr, *lrb;
2115 	lr_write_t *lrw, *lrwb;
2116 	char *lr_buf;
2117 	uint64_t dlen, reclen;
2118 
2119 	lr = &itx->itx_lr;
2120 	lrw = (lr_write_t *)lr;
2121 
2122 	if (lr->lrc_txtype == TX_COMMIT)
2123 		return;
2124 
2125 	if (lr->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY) {
2126 		dlen = P2ROUNDUP_TYPED(
2127 		    lrw->lr_length, sizeof (uint64_t), uint64_t);
2128 	} else {
2129 		dlen = 0;
2130 	}
2131 	reclen = lr->lrc_reclen;
2132 	ASSERT3U(reclen + dlen, <=, lwb->lwb_nused - lwb->lwb_nfilled);
2133 
2134 	lr_buf = lwb->lwb_buf + lwb->lwb_nfilled;
2135 	memcpy(lr_buf, lr, reclen);
2136 	lrb = (lr_t *)lr_buf;		/* Like lr, but inside lwb. */
2137 	lrwb = (lr_write_t *)lrb;	/* Like lrw, but inside lwb. */
2138 
2139 	ZIL_STAT_BUMP(zilog, zil_itx_count);
2140 
2141 	/*
2142 	 * If it's a write, fetch the data or get its blkptr as appropriate.
2143 	 */
2144 	if (lr->lrc_txtype == TX_WRITE) {
2145 		if (itx->itx_wr_state == WR_COPIED) {
2146 			ZIL_STAT_BUMP(zilog, zil_itx_copied_count);
2147 			ZIL_STAT_INCR(zilog, zil_itx_copied_bytes,
2148 			    lrw->lr_length);
2149 		} else {
2150 			char *dbuf;
2151 			int error;
2152 
2153 			if (itx->itx_wr_state == WR_NEED_COPY) {
2154 				dbuf = lr_buf + reclen;
2155 				lrb->lrc_reclen += dlen;
2156 				ZIL_STAT_BUMP(zilog, zil_itx_needcopy_count);
2157 				ZIL_STAT_INCR(zilog, zil_itx_needcopy_bytes,
2158 				    dlen);
2159 			} else {
2160 				ASSERT3S(itx->itx_wr_state, ==, WR_INDIRECT);
2161 				dbuf = NULL;
2162 				ZIL_STAT_BUMP(zilog, zil_itx_indirect_count);
2163 				ZIL_STAT_INCR(zilog, zil_itx_indirect_bytes,
2164 				    lrw->lr_length);
2165 				if (lwb->lwb_child_zio == NULL) {
2166 					lwb->lwb_child_zio = zio_root(
2167 					    zilog->zl_spa, NULL, NULL,
2168 					    ZIO_FLAG_CANFAIL);
2169 				}
2170 			}
2171 
2172 			/*
2173 			 * The "lwb_child_zio" we pass in will become a child of
2174 			 * "lwb_write_zio", when one is created, so one will be
2175 			 * a parent of any zio's created by the "zl_get_data".
2176 			 * This way "lwb_write_zio" will first wait for children
2177 			 * block pointers before own writing, and then for their
2178 			 * writing completion before the vdev cache flushing.
2179 			 */
2180 			error = zilog->zl_get_data(itx->itx_private,
2181 			    itx->itx_gen, lrwb, dbuf, lwb,
2182 			    lwb->lwb_child_zio);
2183 			if (dbuf != NULL && error == 0) {
2184 				/* Zero any padding bytes in the last block. */
2185 				memset((char *)dbuf + lrwb->lr_length, 0,
2186 				    dlen - lrwb->lr_length);
2187 			}
2188 
2189 			/*
2190 			 * Typically, the only return values we should see from
2191 			 * ->zl_get_data() are 0, EIO, ENOENT, EEXIST or
2192 			 *  EALREADY. However, it is also possible to see other
2193 			 *  error values such as ENOSPC or EINVAL from
2194 			 *  dmu_read() -> dnode_hold() -> dnode_hold_impl() or
2195 			 *  ENXIO as well as a multitude of others from the
2196 			 *  block layer through dmu_buf_hold() -> dbuf_read()
2197 			 *  -> zio_wait(), as well as through dmu_read() ->
2198 			 *  dnode_hold() -> dnode_hold_impl() -> dbuf_read() ->
2199 			 *  zio_wait(). When these errors happen, we can assume
2200 			 *  that neither an immediate write nor an indirect
2201 			 *  write occurred, so we need to fall back to
2202 			 *  txg_wait_synced(). This is unusual, so we print to
2203 			 *  dmesg whenever one of these errors occurs.
2204 			 */
2205 			switch (error) {
2206 			case 0:
2207 				break;
2208 			default:
2209 				cmn_err(CE_WARN, "zil_lwb_commit() received "
2210 				    "unexpected error %d from ->zl_get_data()"
2211 				    ". Falling back to txg_wait_synced().",
2212 				    error);
2213 				zfs_fallthrough;
2214 			case EIO:
2215 				txg_wait_synced(zilog->zl_dmu_pool,
2216 				    lr->lrc_txg);
2217 				zfs_fallthrough;
2218 			case ENOENT:
2219 				zfs_fallthrough;
2220 			case EEXIST:
2221 				zfs_fallthrough;
2222 			case EALREADY:
2223 				return;
2224 			}
2225 		}
2226 	}
2227 
2228 	lwb->lwb_nfilled += reclen + dlen;
2229 	ASSERT3S(lwb->lwb_nfilled, <=, lwb->lwb_nused);
2230 	ASSERT0(P2PHASE(lwb->lwb_nfilled, sizeof (uint64_t)));
2231 }
2232 
2233 itx_t *
2234 zil_itx_create(uint64_t txtype, size_t olrsize)
2235 {
2236 	size_t itxsize, lrsize;
2237 	itx_t *itx;
2238 
2239 	lrsize = P2ROUNDUP_TYPED(olrsize, sizeof (uint64_t), size_t);
2240 	itxsize = offsetof(itx_t, itx_lr) + lrsize;
2241 
2242 	itx = zio_data_buf_alloc(itxsize);
2243 	itx->itx_lr.lrc_txtype = txtype;
2244 	itx->itx_lr.lrc_reclen = lrsize;
2245 	itx->itx_lr.lrc_seq = 0;	/* defensive */
2246 	memset((char *)&itx->itx_lr + olrsize, 0, lrsize - olrsize);
2247 	itx->itx_sync = B_TRUE;		/* default is synchronous */
2248 	itx->itx_callback = NULL;
2249 	itx->itx_callback_data = NULL;
2250 	itx->itx_size = itxsize;
2251 
2252 	return (itx);
2253 }
2254 
2255 static itx_t *
2256 zil_itx_clone(itx_t *oitx)
2257 {
2258 	itx_t *itx = zio_data_buf_alloc(oitx->itx_size);
2259 	memcpy(itx, oitx, oitx->itx_size);
2260 	itx->itx_callback = NULL;
2261 	itx->itx_callback_data = NULL;
2262 	return (itx);
2263 }
2264 
2265 void
2266 zil_itx_destroy(itx_t *itx)
2267 {
2268 	IMPLY(itx->itx_lr.lrc_txtype == TX_COMMIT, itx->itx_callback == NULL);
2269 	IMPLY(itx->itx_callback != NULL, itx->itx_lr.lrc_txtype != TX_COMMIT);
2270 
2271 	if (itx->itx_callback != NULL)
2272 		itx->itx_callback(itx->itx_callback_data);
2273 
2274 	zio_data_buf_free(itx, itx->itx_size);
2275 }
2276 
2277 /*
2278  * Free up the sync and async itxs. The itxs_t has already been detached
2279  * so no locks are needed.
2280  */
2281 static void
2282 zil_itxg_clean(void *arg)
2283 {
2284 	itx_t *itx;
2285 	list_t *list;
2286 	avl_tree_t *t;
2287 	void *cookie;
2288 	itxs_t *itxs = arg;
2289 	itx_async_node_t *ian;
2290 
2291 	list = &itxs->i_sync_list;
2292 	while ((itx = list_remove_head(list)) != NULL) {
2293 		/*
2294 		 * In the general case, commit itxs will not be found
2295 		 * here, as they'll be committed to an lwb via
2296 		 * zil_lwb_assign(), and free'd in that function. Having
2297 		 * said that, it is still possible for commit itxs to be
2298 		 * found here, due to the following race:
2299 		 *
2300 		 *	- a thread calls zil_commit() which assigns the
2301 		 *	  commit itx to a per-txg i_sync_list
2302 		 *	- zil_itxg_clean() is called (e.g. via spa_sync())
2303 		 *	  while the waiter is still on the i_sync_list
2304 		 *
2305 		 * There's nothing to prevent syncing the txg while the
2306 		 * waiter is on the i_sync_list. This normally doesn't
2307 		 * happen because spa_sync() is slower than zil_commit(),
2308 		 * but if zil_commit() calls txg_wait_synced() (e.g.
2309 		 * because zil_create() or zil_commit_writer_stall() is
2310 		 * called) we will hit this case.
2311 		 */
2312 		if (itx->itx_lr.lrc_txtype == TX_COMMIT)
2313 			zil_commit_waiter_skip(itx->itx_private);
2314 
2315 		zil_itx_destroy(itx);
2316 	}
2317 
2318 	cookie = NULL;
2319 	t = &itxs->i_async_tree;
2320 	while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
2321 		list = &ian->ia_list;
2322 		while ((itx = list_remove_head(list)) != NULL) {
2323 			/* commit itxs should never be on the async lists. */
2324 			ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT);
2325 			zil_itx_destroy(itx);
2326 		}
2327 		list_destroy(list);
2328 		kmem_free(ian, sizeof (itx_async_node_t));
2329 	}
2330 	avl_destroy(t);
2331 
2332 	kmem_free(itxs, sizeof (itxs_t));
2333 }
2334 
2335 static int
2336 zil_aitx_compare(const void *x1, const void *x2)
2337 {
2338 	const uint64_t o1 = ((itx_async_node_t *)x1)->ia_foid;
2339 	const uint64_t o2 = ((itx_async_node_t *)x2)->ia_foid;
2340 
2341 	return (TREE_CMP(o1, o2));
2342 }
2343 
2344 /*
2345  * Remove all async itx with the given oid.
2346  */
2347 void
2348 zil_remove_async(zilog_t *zilog, uint64_t oid)
2349 {
2350 	uint64_t otxg, txg;
2351 	itx_async_node_t *ian;
2352 	avl_tree_t *t;
2353 	avl_index_t where;
2354 	list_t clean_list;
2355 	itx_t *itx;
2356 
2357 	ASSERT(oid != 0);
2358 	list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
2359 
2360 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
2361 		otxg = ZILTEST_TXG;
2362 	else
2363 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
2364 
2365 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
2366 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
2367 
2368 		mutex_enter(&itxg->itxg_lock);
2369 		if (itxg->itxg_txg != txg) {
2370 			mutex_exit(&itxg->itxg_lock);
2371 			continue;
2372 		}
2373 
2374 		/*
2375 		 * Locate the object node and append its list.
2376 		 */
2377 		t = &itxg->itxg_itxs->i_async_tree;
2378 		ian = avl_find(t, &oid, &where);
2379 		if (ian != NULL)
2380 			list_move_tail(&clean_list, &ian->ia_list);
2381 		mutex_exit(&itxg->itxg_lock);
2382 	}
2383 	while ((itx = list_remove_head(&clean_list)) != NULL) {
2384 		/* commit itxs should never be on the async lists. */
2385 		ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT);
2386 		zil_itx_destroy(itx);
2387 	}
2388 	list_destroy(&clean_list);
2389 }
2390 
2391 void
2392 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
2393 {
2394 	uint64_t txg;
2395 	itxg_t *itxg;
2396 	itxs_t *itxs, *clean = NULL;
2397 
2398 	/*
2399 	 * Ensure the data of a renamed file is committed before the rename.
2400 	 */
2401 	if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_RENAME)
2402 		zil_async_to_sync(zilog, itx->itx_oid);
2403 
2404 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX)
2405 		txg = ZILTEST_TXG;
2406 	else
2407 		txg = dmu_tx_get_txg(tx);
2408 
2409 	itxg = &zilog->zl_itxg[txg & TXG_MASK];
2410 	mutex_enter(&itxg->itxg_lock);
2411 	itxs = itxg->itxg_itxs;
2412 	if (itxg->itxg_txg != txg) {
2413 		if (itxs != NULL) {
2414 			/*
2415 			 * The zil_clean callback hasn't got around to cleaning
2416 			 * this itxg. Save the itxs for release below.
2417 			 * This should be rare.
2418 			 */
2419 			zfs_dbgmsg("zil_itx_assign: missed itx cleanup for "
2420 			    "txg %llu", (u_longlong_t)itxg->itxg_txg);
2421 			clean = itxg->itxg_itxs;
2422 		}
2423 		itxg->itxg_txg = txg;
2424 		itxs = itxg->itxg_itxs = kmem_zalloc(sizeof (itxs_t),
2425 		    KM_SLEEP);
2426 
2427 		list_create(&itxs->i_sync_list, sizeof (itx_t),
2428 		    offsetof(itx_t, itx_node));
2429 		avl_create(&itxs->i_async_tree, zil_aitx_compare,
2430 		    sizeof (itx_async_node_t),
2431 		    offsetof(itx_async_node_t, ia_node));
2432 	}
2433 	if (itx->itx_sync) {
2434 		list_insert_tail(&itxs->i_sync_list, itx);
2435 	} else {
2436 		avl_tree_t *t = &itxs->i_async_tree;
2437 		uint64_t foid =
2438 		    LR_FOID_GET_OBJ(((lr_ooo_t *)&itx->itx_lr)->lr_foid);
2439 		itx_async_node_t *ian;
2440 		avl_index_t where;
2441 
2442 		ian = avl_find(t, &foid, &where);
2443 		if (ian == NULL) {
2444 			ian = kmem_alloc(sizeof (itx_async_node_t),
2445 			    KM_SLEEP);
2446 			list_create(&ian->ia_list, sizeof (itx_t),
2447 			    offsetof(itx_t, itx_node));
2448 			ian->ia_foid = foid;
2449 			avl_insert(t, ian, where);
2450 		}
2451 		list_insert_tail(&ian->ia_list, itx);
2452 	}
2453 
2454 	itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
2455 
2456 	/*
2457 	 * We don't want to dirty the ZIL using ZILTEST_TXG, because
2458 	 * zil_clean() will never be called using ZILTEST_TXG. Thus, we
2459 	 * need to be careful to always dirty the ZIL using the "real"
2460 	 * TXG (not itxg_txg) even when the SPA is frozen.
2461 	 */
2462 	zilog_dirty(zilog, dmu_tx_get_txg(tx));
2463 	mutex_exit(&itxg->itxg_lock);
2464 
2465 	/* Release the old itxs now we've dropped the lock */
2466 	if (clean != NULL)
2467 		zil_itxg_clean(clean);
2468 }
2469 
2470 /*
2471  * If there are any in-memory intent log transactions which have now been
2472  * synced then start up a taskq to free them. We should only do this after we
2473  * have written out the uberblocks (i.e. txg has been committed) so that
2474  * don't inadvertently clean out in-memory log records that would be required
2475  * by zil_commit().
2476  */
2477 void
2478 zil_clean(zilog_t *zilog, uint64_t synced_txg)
2479 {
2480 	itxg_t *itxg = &zilog->zl_itxg[synced_txg & TXG_MASK];
2481 	itxs_t *clean_me;
2482 
2483 	ASSERT3U(synced_txg, <, ZILTEST_TXG);
2484 
2485 	mutex_enter(&itxg->itxg_lock);
2486 	if (itxg->itxg_itxs == NULL || itxg->itxg_txg == ZILTEST_TXG) {
2487 		mutex_exit(&itxg->itxg_lock);
2488 		return;
2489 	}
2490 	ASSERT3U(itxg->itxg_txg, <=, synced_txg);
2491 	ASSERT3U(itxg->itxg_txg, !=, 0);
2492 	clean_me = itxg->itxg_itxs;
2493 	itxg->itxg_itxs = NULL;
2494 	itxg->itxg_txg = 0;
2495 	mutex_exit(&itxg->itxg_lock);
2496 	/*
2497 	 * Preferably start a task queue to free up the old itxs but
2498 	 * if taskq_dispatch can't allocate resources to do that then
2499 	 * free it in-line. This should be rare. Note, using TQ_SLEEP
2500 	 * created a bad performance problem.
2501 	 */
2502 	ASSERT3P(zilog->zl_dmu_pool, !=, NULL);
2503 	ASSERT3P(zilog->zl_dmu_pool->dp_zil_clean_taskq, !=, NULL);
2504 	taskqid_t id = taskq_dispatch(zilog->zl_dmu_pool->dp_zil_clean_taskq,
2505 	    zil_itxg_clean, clean_me, TQ_NOSLEEP);
2506 	if (id == TASKQID_INVALID)
2507 		zil_itxg_clean(clean_me);
2508 }
2509 
2510 /*
2511  * This function will traverse the queue of itxs that need to be
2512  * committed, and move them onto the ZIL's zl_itx_commit_list.
2513  */
2514 static uint64_t
2515 zil_get_commit_list(zilog_t *zilog)
2516 {
2517 	uint64_t otxg, txg, wtxg = 0;
2518 	list_t *commit_list = &zilog->zl_itx_commit_list;
2519 
2520 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2521 
2522 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
2523 		otxg = ZILTEST_TXG;
2524 	else
2525 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
2526 
2527 	/*
2528 	 * This is inherently racy, since there is nothing to prevent
2529 	 * the last synced txg from changing. That's okay since we'll
2530 	 * only commit things in the future.
2531 	 */
2532 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
2533 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
2534 
2535 		mutex_enter(&itxg->itxg_lock);
2536 		if (itxg->itxg_txg != txg) {
2537 			mutex_exit(&itxg->itxg_lock);
2538 			continue;
2539 		}
2540 
2541 		/*
2542 		 * If we're adding itx records to the zl_itx_commit_list,
2543 		 * then the zil better be dirty in this "txg". We can assert
2544 		 * that here since we're holding the itxg_lock which will
2545 		 * prevent spa_sync from cleaning it. Once we add the itxs
2546 		 * to the zl_itx_commit_list we must commit it to disk even
2547 		 * if it's unnecessary (i.e. the txg was synced).
2548 		 */
2549 		ASSERT(zilog_is_dirty_in_txg(zilog, txg) ||
2550 		    spa_freeze_txg(zilog->zl_spa) != UINT64_MAX);
2551 		list_t *sync_list = &itxg->itxg_itxs->i_sync_list;
2552 		if (unlikely(zilog->zl_suspend > 0)) {
2553 			/*
2554 			 * ZIL was just suspended, but we lost the race.
2555 			 * Allow all earlier itxs to be committed, but ask
2556 			 * caller to do txg_wait_synced(txg) for any new.
2557 			 */
2558 			if (!list_is_empty(sync_list))
2559 				wtxg = MAX(wtxg, txg);
2560 		} else {
2561 			list_move_tail(commit_list, sync_list);
2562 		}
2563 
2564 		mutex_exit(&itxg->itxg_lock);
2565 	}
2566 	return (wtxg);
2567 }
2568 
2569 /*
2570  * Move the async itxs for a specified object to commit into sync lists.
2571  */
2572 void
2573 zil_async_to_sync(zilog_t *zilog, uint64_t foid)
2574 {
2575 	uint64_t otxg, txg;
2576 	itx_async_node_t *ian;
2577 	avl_tree_t *t;
2578 	avl_index_t where;
2579 
2580 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
2581 		otxg = ZILTEST_TXG;
2582 	else
2583 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
2584 
2585 	/*
2586 	 * This is inherently racy, since there is nothing to prevent
2587 	 * the last synced txg from changing.
2588 	 */
2589 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
2590 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
2591 
2592 		mutex_enter(&itxg->itxg_lock);
2593 		if (itxg->itxg_txg != txg) {
2594 			mutex_exit(&itxg->itxg_lock);
2595 			continue;
2596 		}
2597 
2598 		/*
2599 		 * If a foid is specified then find that node and append its
2600 		 * list. Otherwise walk the tree appending all the lists
2601 		 * to the sync list. We add to the end rather than the
2602 		 * beginning to ensure the create has happened.
2603 		 */
2604 		t = &itxg->itxg_itxs->i_async_tree;
2605 		if (foid != 0) {
2606 			ian = avl_find(t, &foid, &where);
2607 			if (ian != NULL) {
2608 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
2609 				    &ian->ia_list);
2610 			}
2611 		} else {
2612 			void *cookie = NULL;
2613 
2614 			while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
2615 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
2616 				    &ian->ia_list);
2617 				list_destroy(&ian->ia_list);
2618 				kmem_free(ian, sizeof (itx_async_node_t));
2619 			}
2620 		}
2621 		mutex_exit(&itxg->itxg_lock);
2622 	}
2623 }
2624 
2625 /*
2626  * This function will prune commit itxs that are at the head of the
2627  * commit list (it won't prune past the first non-commit itx), and
2628  * either: a) attach them to the last lwb that's still pending
2629  * completion, or b) skip them altogether.
2630  *
2631  * This is used as a performance optimization to prevent commit itxs
2632  * from generating new lwbs when it's unnecessary to do so.
2633  */
2634 static void
2635 zil_prune_commit_list(zilog_t *zilog)
2636 {
2637 	itx_t *itx;
2638 
2639 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2640 
2641 	while ((itx = list_head(&zilog->zl_itx_commit_list)) != NULL) {
2642 		lr_t *lrc = &itx->itx_lr;
2643 		if (lrc->lrc_txtype != TX_COMMIT)
2644 			break;
2645 
2646 		mutex_enter(&zilog->zl_lock);
2647 
2648 		lwb_t *last_lwb = zilog->zl_last_lwb_opened;
2649 		if (last_lwb == NULL ||
2650 		    last_lwb->lwb_state == LWB_STATE_FLUSH_DONE) {
2651 			/*
2652 			 * All of the itxs this waiter was waiting on
2653 			 * must have already completed (or there were
2654 			 * never any itx's for it to wait on), so it's
2655 			 * safe to skip this waiter and mark it done.
2656 			 */
2657 			zil_commit_waiter_skip(itx->itx_private);
2658 		} else {
2659 			zil_commit_waiter_link_lwb(itx->itx_private, last_lwb);
2660 		}
2661 
2662 		mutex_exit(&zilog->zl_lock);
2663 
2664 		list_remove(&zilog->zl_itx_commit_list, itx);
2665 		zil_itx_destroy(itx);
2666 	}
2667 
2668 	IMPLY(itx != NULL, itx->itx_lr.lrc_txtype != TX_COMMIT);
2669 }
2670 
2671 static void
2672 zil_commit_writer_stall(zilog_t *zilog)
2673 {
2674 	/*
2675 	 * When zio_alloc_zil() fails to allocate the next lwb block on
2676 	 * disk, we must call txg_wait_synced() to ensure all of the
2677 	 * lwbs in the zilog's zl_lwb_list are synced and then freed (in
2678 	 * zil_sync()), such that any subsequent ZIL writer (i.e. a call
2679 	 * to zil_process_commit_list()) will have to call zil_create(),
2680 	 * and start a new ZIL chain.
2681 	 *
2682 	 * Since zil_alloc_zil() failed, the lwb that was previously
2683 	 * issued does not have a pointer to the "next" lwb on disk.
2684 	 * Thus, if another ZIL writer thread was to allocate the "next"
2685 	 * on-disk lwb, that block could be leaked in the event of a
2686 	 * crash (because the previous lwb on-disk would not point to
2687 	 * it).
2688 	 *
2689 	 * We must hold the zilog's zl_issuer_lock while we do this, to
2690 	 * ensure no new threads enter zil_process_commit_list() until
2691 	 * all lwb's in the zl_lwb_list have been synced and freed
2692 	 * (which is achieved via the txg_wait_synced() call).
2693 	 */
2694 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2695 	txg_wait_synced(zilog->zl_dmu_pool, 0);
2696 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
2697 }
2698 
2699 /*
2700  * This function will traverse the commit list, creating new lwbs as
2701  * needed, and committing the itxs from the commit list to these newly
2702  * created lwbs. Additionally, as a new lwb is created, the previous
2703  * lwb will be issued to the zio layer to be written to disk.
2704  */
2705 static void
2706 zil_process_commit_list(zilog_t *zilog, zil_commit_waiter_t *zcw, list_t *ilwbs)
2707 {
2708 	spa_t *spa = zilog->zl_spa;
2709 	list_t nolwb_itxs;
2710 	list_t nolwb_waiters;
2711 	lwb_t *lwb, *plwb;
2712 	itx_t *itx;
2713 	boolean_t first = B_TRUE;
2714 
2715 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2716 
2717 	/*
2718 	 * Return if there's nothing to commit before we dirty the fs by
2719 	 * calling zil_create().
2720 	 */
2721 	if (list_is_empty(&zilog->zl_itx_commit_list))
2722 		return;
2723 
2724 	list_create(&nolwb_itxs, sizeof (itx_t), offsetof(itx_t, itx_node));
2725 	list_create(&nolwb_waiters, sizeof (zil_commit_waiter_t),
2726 	    offsetof(zil_commit_waiter_t, zcw_node));
2727 
2728 	lwb = list_tail(&zilog->zl_lwb_list);
2729 	if (lwb == NULL) {
2730 		lwb = zil_create(zilog);
2731 	} else {
2732 		/*
2733 		 * Activate SPA_FEATURE_ZILSAXATTR for the cases where ZIL will
2734 		 * have already been created (zl_lwb_list not empty).
2735 		 */
2736 		zil_commit_activate_saxattr_feature(zilog);
2737 		ASSERT(lwb->lwb_state == LWB_STATE_NEW ||
2738 		    lwb->lwb_state == LWB_STATE_OPENED);
2739 		first = (lwb->lwb_state == LWB_STATE_NEW) &&
2740 		    ((plwb = list_prev(&zilog->zl_lwb_list, lwb)) == NULL ||
2741 		    plwb->lwb_state == LWB_STATE_FLUSH_DONE);
2742 	}
2743 
2744 	while ((itx = list_remove_head(&zilog->zl_itx_commit_list)) != NULL) {
2745 		lr_t *lrc = &itx->itx_lr;
2746 		uint64_t txg = lrc->lrc_txg;
2747 
2748 		ASSERT3U(txg, !=, 0);
2749 
2750 		if (lrc->lrc_txtype == TX_COMMIT) {
2751 			DTRACE_PROBE2(zil__process__commit__itx,
2752 			    zilog_t *, zilog, itx_t *, itx);
2753 		} else {
2754 			DTRACE_PROBE2(zil__process__normal__itx,
2755 			    zilog_t *, zilog, itx_t *, itx);
2756 		}
2757 
2758 		boolean_t synced = txg <= spa_last_synced_txg(spa);
2759 		boolean_t frozen = txg > spa_freeze_txg(spa);
2760 
2761 		/*
2762 		 * If the txg of this itx has already been synced out, then
2763 		 * we don't need to commit this itx to an lwb. This is
2764 		 * because the data of this itx will have already been
2765 		 * written to the main pool. This is inherently racy, and
2766 		 * it's still ok to commit an itx whose txg has already
2767 		 * been synced; this will result in a write that's
2768 		 * unnecessary, but will do no harm.
2769 		 *
2770 		 * With that said, we always want to commit TX_COMMIT itxs
2771 		 * to an lwb, regardless of whether or not that itx's txg
2772 		 * has been synced out. We do this to ensure any OPENED lwb
2773 		 * will always have at least one zil_commit_waiter_t linked
2774 		 * to the lwb.
2775 		 *
2776 		 * As a counter-example, if we skipped TX_COMMIT itx's
2777 		 * whose txg had already been synced, the following
2778 		 * situation could occur if we happened to be racing with
2779 		 * spa_sync:
2780 		 *
2781 		 * 1. We commit a non-TX_COMMIT itx to an lwb, where the
2782 		 *    itx's txg is 10 and the last synced txg is 9.
2783 		 * 2. spa_sync finishes syncing out txg 10.
2784 		 * 3. We move to the next itx in the list, it's a TX_COMMIT
2785 		 *    whose txg is 10, so we skip it rather than committing
2786 		 *    it to the lwb used in (1).
2787 		 *
2788 		 * If the itx that is skipped in (3) is the last TX_COMMIT
2789 		 * itx in the commit list, than it's possible for the lwb
2790 		 * used in (1) to remain in the OPENED state indefinitely.
2791 		 *
2792 		 * To prevent the above scenario from occurring, ensuring
2793 		 * that once an lwb is OPENED it will transition to ISSUED
2794 		 * and eventually DONE, we always commit TX_COMMIT itx's to
2795 		 * an lwb here, even if that itx's txg has already been
2796 		 * synced.
2797 		 *
2798 		 * Finally, if the pool is frozen, we _always_ commit the
2799 		 * itx.  The point of freezing the pool is to prevent data
2800 		 * from being written to the main pool via spa_sync, and
2801 		 * instead rely solely on the ZIL to persistently store the
2802 		 * data; i.e.  when the pool is frozen, the last synced txg
2803 		 * value can't be trusted.
2804 		 */
2805 		if (frozen || !synced || lrc->lrc_txtype == TX_COMMIT) {
2806 			if (lwb != NULL) {
2807 				lwb = zil_lwb_assign(zilog, lwb, itx, ilwbs);
2808 				if (lwb == NULL) {
2809 					list_insert_tail(&nolwb_itxs, itx);
2810 				} else if ((zcw->zcw_lwb != NULL &&
2811 				    zcw->zcw_lwb != lwb) || zcw->zcw_done) {
2812 					/*
2813 					 * Our lwb is done, leave the rest of
2814 					 * itx list to somebody else who care.
2815 					 */
2816 					first = B_FALSE;
2817 					break;
2818 				}
2819 			} else {
2820 				if (lrc->lrc_txtype == TX_COMMIT) {
2821 					zil_commit_waiter_link_nolwb(
2822 					    itx->itx_private, &nolwb_waiters);
2823 				}
2824 				list_insert_tail(&nolwb_itxs, itx);
2825 			}
2826 		} else {
2827 			ASSERT3S(lrc->lrc_txtype, !=, TX_COMMIT);
2828 			zil_itx_destroy(itx);
2829 		}
2830 	}
2831 
2832 	if (lwb == NULL) {
2833 		/*
2834 		 * This indicates zio_alloc_zil() failed to allocate the
2835 		 * "next" lwb on-disk. When this happens, we must stall
2836 		 * the ZIL write pipeline; see the comment within
2837 		 * zil_commit_writer_stall() for more details.
2838 		 */
2839 		while ((lwb = list_remove_head(ilwbs)) != NULL)
2840 			zil_lwb_write_issue(zilog, lwb);
2841 		zil_commit_writer_stall(zilog);
2842 
2843 		/*
2844 		 * Additionally, we have to signal and mark the "nolwb"
2845 		 * waiters as "done" here, since without an lwb, we
2846 		 * can't do this via zil_lwb_flush_vdevs_done() like
2847 		 * normal.
2848 		 */
2849 		zil_commit_waiter_t *zcw;
2850 		while ((zcw = list_remove_head(&nolwb_waiters)) != NULL)
2851 			zil_commit_waiter_skip(zcw);
2852 
2853 		/*
2854 		 * And finally, we have to destroy the itx's that
2855 		 * couldn't be committed to an lwb; this will also call
2856 		 * the itx's callback if one exists for the itx.
2857 		 */
2858 		while ((itx = list_remove_head(&nolwb_itxs)) != NULL)
2859 			zil_itx_destroy(itx);
2860 	} else {
2861 		ASSERT(list_is_empty(&nolwb_waiters));
2862 		ASSERT3P(lwb, !=, NULL);
2863 		ASSERT(lwb->lwb_state == LWB_STATE_NEW ||
2864 		    lwb->lwb_state == LWB_STATE_OPENED);
2865 
2866 		/*
2867 		 * At this point, the ZIL block pointed at by the "lwb"
2868 		 * variable is in "new" or "opened" state.
2869 		 *
2870 		 * If it's "new", then no itxs have been committed to it, so
2871 		 * there's no point in issuing its zio (i.e. it's "empty").
2872 		 *
2873 		 * If it's "opened", then it contains one or more itxs that
2874 		 * eventually need to be committed to stable storage. In
2875 		 * this case we intentionally do not issue the lwb's zio
2876 		 * to disk yet, and instead rely on one of the following
2877 		 * two mechanisms for issuing the zio:
2878 		 *
2879 		 * 1. Ideally, there will be more ZIL activity occurring on
2880 		 * the system, such that this function will be immediately
2881 		 * called again by different thread and this lwb will be
2882 		 * closed by zil_lwb_assign().  This way, the lwb will be
2883 		 * "full" when it is issued to disk, and we'll make use of
2884 		 * the lwb's size the best we can.
2885 		 *
2886 		 * 2. If there isn't sufficient ZIL activity occurring on
2887 		 * the system, zil_commit_waiter() will close it and issue
2888 		 * the zio.  If this occurs, the lwb is not guaranteed
2889 		 * to be "full" by the time its zio is issued, and means
2890 		 * the size of the lwb was "too large" given the amount
2891 		 * of ZIL activity occurring on the system at that time.
2892 		 *
2893 		 * We do this for a couple of reasons:
2894 		 *
2895 		 * 1. To try and reduce the number of IOPs needed to
2896 		 * write the same number of itxs. If an lwb has space
2897 		 * available in its buffer for more itxs, and more itxs
2898 		 * will be committed relatively soon (relative to the
2899 		 * latency of performing a write), then it's beneficial
2900 		 * to wait for these "next" itxs. This way, more itxs
2901 		 * can be committed to stable storage with fewer writes.
2902 		 *
2903 		 * 2. To try and use the largest lwb block size that the
2904 		 * incoming rate of itxs can support. Again, this is to
2905 		 * try and pack as many itxs into as few lwbs as
2906 		 * possible, without significantly impacting the latency
2907 		 * of each individual itx.
2908 		 *
2909 		 * If we had no already running or open LWBs, it can be
2910 		 * the workload is single-threaded.  And if the ZIL write
2911 		 * latency is very small or if the LWB is almost full, it
2912 		 * may be cheaper to bypass the delay.
2913 		 */
2914 		if (lwb->lwb_state == LWB_STATE_OPENED && first) {
2915 			hrtime_t sleep = zilog->zl_last_lwb_latency *
2916 			    zfs_commit_timeout_pct / 100;
2917 			if (sleep < zil_min_commit_timeout ||
2918 			    lwb->lwb_nmax - lwb->lwb_nused <
2919 			    lwb->lwb_nmax / 8) {
2920 				list_insert_tail(ilwbs, lwb);
2921 				lwb = zil_lwb_write_close(zilog, lwb,
2922 				    LWB_STATE_NEW);
2923 				zilog->zl_cur_used = 0;
2924 				if (lwb == NULL) {
2925 					while ((lwb = list_remove_head(ilwbs))
2926 					    != NULL)
2927 						zil_lwb_write_issue(zilog, lwb);
2928 					zil_commit_writer_stall(zilog);
2929 				}
2930 			}
2931 		}
2932 	}
2933 }
2934 
2935 /*
2936  * This function is responsible for ensuring the passed in commit waiter
2937  * (and associated commit itx) is committed to an lwb. If the waiter is
2938  * not already committed to an lwb, all itxs in the zilog's queue of
2939  * itxs will be processed. The assumption is the passed in waiter's
2940  * commit itx will found in the queue just like the other non-commit
2941  * itxs, such that when the entire queue is processed, the waiter will
2942  * have been committed to an lwb.
2943  *
2944  * The lwb associated with the passed in waiter is not guaranteed to
2945  * have been issued by the time this function completes. If the lwb is
2946  * not issued, we rely on future calls to zil_commit_writer() to issue
2947  * the lwb, or the timeout mechanism found in zil_commit_waiter().
2948  */
2949 static uint64_t
2950 zil_commit_writer(zilog_t *zilog, zil_commit_waiter_t *zcw)
2951 {
2952 	list_t ilwbs;
2953 	lwb_t *lwb;
2954 	uint64_t wtxg = 0;
2955 
2956 	ASSERT(!MUTEX_HELD(&zilog->zl_lock));
2957 	ASSERT(spa_writeable(zilog->zl_spa));
2958 
2959 	list_create(&ilwbs, sizeof (lwb_t), offsetof(lwb_t, lwb_issue_node));
2960 	mutex_enter(&zilog->zl_issuer_lock);
2961 
2962 	if (zcw->zcw_lwb != NULL || zcw->zcw_done) {
2963 		/*
2964 		 * It's possible that, while we were waiting to acquire
2965 		 * the "zl_issuer_lock", another thread committed this
2966 		 * waiter to an lwb. If that occurs, we bail out early,
2967 		 * without processing any of the zilog's queue of itxs.
2968 		 *
2969 		 * On certain workloads and system configurations, the
2970 		 * "zl_issuer_lock" can become highly contended. In an
2971 		 * attempt to reduce this contention, we immediately drop
2972 		 * the lock if the waiter has already been processed.
2973 		 *
2974 		 * We've measured this optimization to reduce CPU spent
2975 		 * contending on this lock by up to 5%, using a system
2976 		 * with 32 CPUs, low latency storage (~50 usec writes),
2977 		 * and 1024 threads performing sync writes.
2978 		 */
2979 		goto out;
2980 	}
2981 
2982 	ZIL_STAT_BUMP(zilog, zil_commit_writer_count);
2983 
2984 	wtxg = zil_get_commit_list(zilog);
2985 	zil_prune_commit_list(zilog);
2986 	zil_process_commit_list(zilog, zcw, &ilwbs);
2987 
2988 out:
2989 	mutex_exit(&zilog->zl_issuer_lock);
2990 	while ((lwb = list_remove_head(&ilwbs)) != NULL)
2991 		zil_lwb_write_issue(zilog, lwb);
2992 	list_destroy(&ilwbs);
2993 	return (wtxg);
2994 }
2995 
2996 static void
2997 zil_commit_waiter_timeout(zilog_t *zilog, zil_commit_waiter_t *zcw)
2998 {
2999 	ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock));
3000 	ASSERT(MUTEX_HELD(&zcw->zcw_lock));
3001 	ASSERT3B(zcw->zcw_done, ==, B_FALSE);
3002 
3003 	lwb_t *lwb = zcw->zcw_lwb;
3004 	ASSERT3P(lwb, !=, NULL);
3005 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_NEW);
3006 
3007 	/*
3008 	 * If the lwb has already been issued by another thread, we can
3009 	 * immediately return since there's no work to be done (the
3010 	 * point of this function is to issue the lwb). Additionally, we
3011 	 * do this prior to acquiring the zl_issuer_lock, to avoid
3012 	 * acquiring it when it's not necessary to do so.
3013 	 */
3014 	if (lwb->lwb_state != LWB_STATE_OPENED)
3015 		return;
3016 
3017 	/*
3018 	 * In order to call zil_lwb_write_close() we must hold the
3019 	 * zilog's "zl_issuer_lock". We can't simply acquire that lock,
3020 	 * since we're already holding the commit waiter's "zcw_lock",
3021 	 * and those two locks are acquired in the opposite order
3022 	 * elsewhere.
3023 	 */
3024 	mutex_exit(&zcw->zcw_lock);
3025 	mutex_enter(&zilog->zl_issuer_lock);
3026 	mutex_enter(&zcw->zcw_lock);
3027 
3028 	/*
3029 	 * Since we just dropped and re-acquired the commit waiter's
3030 	 * lock, we have to re-check to see if the waiter was marked
3031 	 * "done" during that process. If the waiter was marked "done",
3032 	 * the "lwb" pointer is no longer valid (it can be free'd after
3033 	 * the waiter is marked "done"), so without this check we could
3034 	 * wind up with a use-after-free error below.
3035 	 */
3036 	if (zcw->zcw_done) {
3037 		mutex_exit(&zilog->zl_issuer_lock);
3038 		return;
3039 	}
3040 
3041 	ASSERT3P(lwb, ==, zcw->zcw_lwb);
3042 
3043 	/*
3044 	 * We've already checked this above, but since we hadn't acquired
3045 	 * the zilog's zl_issuer_lock, we have to perform this check a
3046 	 * second time while holding the lock.
3047 	 *
3048 	 * We don't need to hold the zl_lock since the lwb cannot transition
3049 	 * from OPENED to CLOSED while we hold the zl_issuer_lock. The lwb
3050 	 * _can_ transition from CLOSED to DONE, but it's OK to race with
3051 	 * that transition since we treat the lwb the same, whether it's in
3052 	 * the CLOSED, ISSUED or DONE states.
3053 	 *
3054 	 * The important thing, is we treat the lwb differently depending on
3055 	 * if it's OPENED or CLOSED, and block any other threads that might
3056 	 * attempt to close/issue this lwb. For that reason we hold the
3057 	 * zl_issuer_lock when checking the lwb_state; we must not call
3058 	 * zil_lwb_write_close() if the lwb had already been closed/issued.
3059 	 *
3060 	 * See the comment above the lwb_state_t structure definition for
3061 	 * more details on the lwb states, and locking requirements.
3062 	 */
3063 	if (lwb->lwb_state != LWB_STATE_OPENED) {
3064 		mutex_exit(&zilog->zl_issuer_lock);
3065 		return;
3066 	}
3067 
3068 	/*
3069 	 * We do not need zcw_lock once we hold zl_issuer_lock and know lwb
3070 	 * is still open.  But we have to drop it to avoid a deadlock in case
3071 	 * callback of zio issued by zil_lwb_write_issue() try to get it,
3072 	 * while zil_lwb_write_issue() is blocked on attempt to issue next
3073 	 * lwb it found in LWB_STATE_READY state.
3074 	 */
3075 	mutex_exit(&zcw->zcw_lock);
3076 
3077 	/*
3078 	 * As described in the comments above zil_commit_waiter() and
3079 	 * zil_process_commit_list(), we need to issue this lwb's zio
3080 	 * since we've reached the commit waiter's timeout and it still
3081 	 * hasn't been issued.
3082 	 */
3083 	lwb_t *nlwb = zil_lwb_write_close(zilog, lwb, LWB_STATE_NEW);
3084 
3085 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_CLOSED);
3086 
3087 	/*
3088 	 * Since the lwb's zio hadn't been issued by the time this thread
3089 	 * reached its timeout, we reset the zilog's "zl_cur_used" field
3090 	 * to influence the zil block size selection algorithm.
3091 	 *
3092 	 * By having to issue the lwb's zio here, it means the size of the
3093 	 * lwb was too large, given the incoming throughput of itxs.  By
3094 	 * setting "zl_cur_used" to zero, we communicate this fact to the
3095 	 * block size selection algorithm, so it can take this information
3096 	 * into account, and potentially select a smaller size for the
3097 	 * next lwb block that is allocated.
3098 	 */
3099 	zilog->zl_cur_used = 0;
3100 
3101 	if (nlwb == NULL) {
3102 		/*
3103 		 * When zil_lwb_write_close() returns NULL, this
3104 		 * indicates zio_alloc_zil() failed to allocate the
3105 		 * "next" lwb on-disk. When this occurs, the ZIL write
3106 		 * pipeline must be stalled; see the comment within the
3107 		 * zil_commit_writer_stall() function for more details.
3108 		 */
3109 		zil_lwb_write_issue(zilog, lwb);
3110 		zil_commit_writer_stall(zilog);
3111 		mutex_exit(&zilog->zl_issuer_lock);
3112 	} else {
3113 		mutex_exit(&zilog->zl_issuer_lock);
3114 		zil_lwb_write_issue(zilog, lwb);
3115 	}
3116 	mutex_enter(&zcw->zcw_lock);
3117 }
3118 
3119 /*
3120  * This function is responsible for performing the following two tasks:
3121  *
3122  * 1. its primary responsibility is to block until the given "commit
3123  *    waiter" is considered "done".
3124  *
3125  * 2. its secondary responsibility is to issue the zio for the lwb that
3126  *    the given "commit waiter" is waiting on, if this function has
3127  *    waited "long enough" and the lwb is still in the "open" state.
3128  *
3129  * Given a sufficient amount of itxs being generated and written using
3130  * the ZIL, the lwb's zio will be issued via the zil_lwb_assign()
3131  * function. If this does not occur, this secondary responsibility will
3132  * ensure the lwb is issued even if there is not other synchronous
3133  * activity on the system.
3134  *
3135  * For more details, see zil_process_commit_list(); more specifically,
3136  * the comment at the bottom of that function.
3137  */
3138 static void
3139 zil_commit_waiter(zilog_t *zilog, zil_commit_waiter_t *zcw)
3140 {
3141 	ASSERT(!MUTEX_HELD(&zilog->zl_lock));
3142 	ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock));
3143 	ASSERT(spa_writeable(zilog->zl_spa));
3144 
3145 	mutex_enter(&zcw->zcw_lock);
3146 
3147 	/*
3148 	 * The timeout is scaled based on the lwb latency to avoid
3149 	 * significantly impacting the latency of each individual itx.
3150 	 * For more details, see the comment at the bottom of the
3151 	 * zil_process_commit_list() function.
3152 	 */
3153 	int pct = MAX(zfs_commit_timeout_pct, 1);
3154 	hrtime_t sleep = (zilog->zl_last_lwb_latency * pct) / 100;
3155 	hrtime_t wakeup = gethrtime() + sleep;
3156 	boolean_t timedout = B_FALSE;
3157 
3158 	while (!zcw->zcw_done) {
3159 		ASSERT(MUTEX_HELD(&zcw->zcw_lock));
3160 
3161 		lwb_t *lwb = zcw->zcw_lwb;
3162 
3163 		/*
3164 		 * Usually, the waiter will have a non-NULL lwb field here,
3165 		 * but it's possible for it to be NULL as a result of
3166 		 * zil_commit() racing with spa_sync().
3167 		 *
3168 		 * When zil_clean() is called, it's possible for the itxg
3169 		 * list (which may be cleaned via a taskq) to contain
3170 		 * commit itxs. When this occurs, the commit waiters linked
3171 		 * off of these commit itxs will not be committed to an
3172 		 * lwb.  Additionally, these commit waiters will not be
3173 		 * marked done until zil_commit_waiter_skip() is called via
3174 		 * zil_itxg_clean().
3175 		 *
3176 		 * Thus, it's possible for this commit waiter (i.e. the
3177 		 * "zcw" variable) to be found in this "in between" state;
3178 		 * where it's "zcw_lwb" field is NULL, and it hasn't yet
3179 		 * been skipped, so it's "zcw_done" field is still B_FALSE.
3180 		 */
3181 		IMPLY(lwb != NULL, lwb->lwb_state != LWB_STATE_NEW);
3182 
3183 		if (lwb != NULL && lwb->lwb_state == LWB_STATE_OPENED) {
3184 			ASSERT3B(timedout, ==, B_FALSE);
3185 
3186 			/*
3187 			 * If the lwb hasn't been issued yet, then we
3188 			 * need to wait with a timeout, in case this
3189 			 * function needs to issue the lwb after the
3190 			 * timeout is reached; responsibility (2) from
3191 			 * the comment above this function.
3192 			 */
3193 			int rc = cv_timedwait_hires(&zcw->zcw_cv,
3194 			    &zcw->zcw_lock, wakeup, USEC2NSEC(1),
3195 			    CALLOUT_FLAG_ABSOLUTE);
3196 
3197 			if (rc != -1 || zcw->zcw_done)
3198 				continue;
3199 
3200 			timedout = B_TRUE;
3201 			zil_commit_waiter_timeout(zilog, zcw);
3202 
3203 			if (!zcw->zcw_done) {
3204 				/*
3205 				 * If the commit waiter has already been
3206 				 * marked "done", it's possible for the
3207 				 * waiter's lwb structure to have already
3208 				 * been freed.  Thus, we can only reliably
3209 				 * make these assertions if the waiter
3210 				 * isn't done.
3211 				 */
3212 				ASSERT3P(lwb, ==, zcw->zcw_lwb);
3213 				ASSERT3S(lwb->lwb_state, !=, LWB_STATE_OPENED);
3214 			}
3215 		} else {
3216 			/*
3217 			 * If the lwb isn't open, then it must have already
3218 			 * been issued. In that case, there's no need to
3219 			 * use a timeout when waiting for the lwb to
3220 			 * complete.
3221 			 *
3222 			 * Additionally, if the lwb is NULL, the waiter
3223 			 * will soon be signaled and marked done via
3224 			 * zil_clean() and zil_itxg_clean(), so no timeout
3225 			 * is required.
3226 			 */
3227 
3228 			IMPLY(lwb != NULL,
3229 			    lwb->lwb_state == LWB_STATE_CLOSED ||
3230 			    lwb->lwb_state == LWB_STATE_READY ||
3231 			    lwb->lwb_state == LWB_STATE_ISSUED ||
3232 			    lwb->lwb_state == LWB_STATE_WRITE_DONE ||
3233 			    lwb->lwb_state == LWB_STATE_FLUSH_DONE);
3234 			cv_wait(&zcw->zcw_cv, &zcw->zcw_lock);
3235 		}
3236 	}
3237 
3238 	mutex_exit(&zcw->zcw_lock);
3239 }
3240 
3241 static zil_commit_waiter_t *
3242 zil_alloc_commit_waiter(void)
3243 {
3244 	zil_commit_waiter_t *zcw = kmem_cache_alloc(zil_zcw_cache, KM_SLEEP);
3245 
3246 	cv_init(&zcw->zcw_cv, NULL, CV_DEFAULT, NULL);
3247 	mutex_init(&zcw->zcw_lock, NULL, MUTEX_DEFAULT, NULL);
3248 	list_link_init(&zcw->zcw_node);
3249 	zcw->zcw_lwb = NULL;
3250 	zcw->zcw_done = B_FALSE;
3251 	zcw->zcw_zio_error = 0;
3252 
3253 	return (zcw);
3254 }
3255 
3256 static void
3257 zil_free_commit_waiter(zil_commit_waiter_t *zcw)
3258 {
3259 	ASSERT(!list_link_active(&zcw->zcw_node));
3260 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
3261 	ASSERT3B(zcw->zcw_done, ==, B_TRUE);
3262 	mutex_destroy(&zcw->zcw_lock);
3263 	cv_destroy(&zcw->zcw_cv);
3264 	kmem_cache_free(zil_zcw_cache, zcw);
3265 }
3266 
3267 /*
3268  * This function is used to create a TX_COMMIT itx and assign it. This
3269  * way, it will be linked into the ZIL's list of synchronous itxs, and
3270  * then later committed to an lwb (or skipped) when
3271  * zil_process_commit_list() is called.
3272  */
3273 static void
3274 zil_commit_itx_assign(zilog_t *zilog, zil_commit_waiter_t *zcw)
3275 {
3276 	dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
3277 
3278 	/*
3279 	 * Since we are not going to create any new dirty data, and we
3280 	 * can even help with clearing the existing dirty data, we
3281 	 * should not be subject to the dirty data based delays. We
3282 	 * use TXG_NOTHROTTLE to bypass the delay mechanism.
3283 	 */
3284 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT | TXG_NOTHROTTLE));
3285 
3286 	itx_t *itx = zil_itx_create(TX_COMMIT, sizeof (lr_t));
3287 	itx->itx_sync = B_TRUE;
3288 	itx->itx_private = zcw;
3289 
3290 	zil_itx_assign(zilog, itx, tx);
3291 
3292 	dmu_tx_commit(tx);
3293 }
3294 
3295 /*
3296  * Commit ZFS Intent Log transactions (itxs) to stable storage.
3297  *
3298  * When writing ZIL transactions to the on-disk representation of the
3299  * ZIL, the itxs are committed to a Log Write Block (lwb). Multiple
3300  * itxs can be committed to a single lwb. Once a lwb is written and
3301  * committed to stable storage (i.e. the lwb is written, and vdevs have
3302  * been flushed), each itx that was committed to that lwb is also
3303  * considered to be committed to stable storage.
3304  *
3305  * When an itx is committed to an lwb, the log record (lr_t) contained
3306  * by the itx is copied into the lwb's zio buffer, and once this buffer
3307  * is written to disk, it becomes an on-disk ZIL block.
3308  *
3309  * As itxs are generated, they're inserted into the ZIL's queue of
3310  * uncommitted itxs. The semantics of zil_commit() are such that it will
3311  * block until all itxs that were in the queue when it was called, are
3312  * committed to stable storage.
3313  *
3314  * If "foid" is zero, this means all "synchronous" and "asynchronous"
3315  * itxs, for all objects in the dataset, will be committed to stable
3316  * storage prior to zil_commit() returning. If "foid" is non-zero, all
3317  * "synchronous" itxs for all objects, but only "asynchronous" itxs
3318  * that correspond to the foid passed in, will be committed to stable
3319  * storage prior to zil_commit() returning.
3320  *
3321  * Generally speaking, when zil_commit() is called, the consumer doesn't
3322  * actually care about _all_ of the uncommitted itxs. Instead, they're
3323  * simply trying to waiting for a specific itx to be committed to disk,
3324  * but the interface(s) for interacting with the ZIL don't allow such
3325  * fine-grained communication. A better interface would allow a consumer
3326  * to create and assign an itx, and then pass a reference to this itx to
3327  * zil_commit(); such that zil_commit() would return as soon as that
3328  * specific itx was committed to disk (instead of waiting for _all_
3329  * itxs to be committed).
3330  *
3331  * When a thread calls zil_commit() a special "commit itx" will be
3332  * generated, along with a corresponding "waiter" for this commit itx.
3333  * zil_commit() will wait on this waiter's CV, such that when the waiter
3334  * is marked done, and signaled, zil_commit() will return.
3335  *
3336  * This commit itx is inserted into the queue of uncommitted itxs. This
3337  * provides an easy mechanism for determining which itxs were in the
3338  * queue prior to zil_commit() having been called, and which itxs were
3339  * added after zil_commit() was called.
3340  *
3341  * The commit itx is special; it doesn't have any on-disk representation.
3342  * When a commit itx is "committed" to an lwb, the waiter associated
3343  * with it is linked onto the lwb's list of waiters. Then, when that lwb
3344  * completes, each waiter on the lwb's list is marked done and signaled
3345  * -- allowing the thread waiting on the waiter to return from zil_commit().
3346  *
3347  * It's important to point out a few critical factors that allow us
3348  * to make use of the commit itxs, commit waiters, per-lwb lists of
3349  * commit waiters, and zio completion callbacks like we're doing:
3350  *
3351  *   1. The list of waiters for each lwb is traversed, and each commit
3352  *      waiter is marked "done" and signaled, in the zio completion
3353  *      callback of the lwb's zio[*].
3354  *
3355  *      * Actually, the waiters are signaled in the zio completion
3356  *        callback of the root zio for the DKIOCFLUSHWRITECACHE commands
3357  *        that are sent to the vdevs upon completion of the lwb zio.
3358  *
3359  *   2. When the itxs are inserted into the ZIL's queue of uncommitted
3360  *      itxs, the order in which they are inserted is preserved[*]; as
3361  *      itxs are added to the queue, they are added to the tail of
3362  *      in-memory linked lists.
3363  *
3364  *      When committing the itxs to lwbs (to be written to disk), they
3365  *      are committed in the same order in which the itxs were added to
3366  *      the uncommitted queue's linked list(s); i.e. the linked list of
3367  *      itxs to commit is traversed from head to tail, and each itx is
3368  *      committed to an lwb in that order.
3369  *
3370  *      * To clarify:
3371  *
3372  *        - the order of "sync" itxs is preserved w.r.t. other
3373  *          "sync" itxs, regardless of the corresponding objects.
3374  *        - the order of "async" itxs is preserved w.r.t. other
3375  *          "async" itxs corresponding to the same object.
3376  *        - the order of "async" itxs is *not* preserved w.r.t. other
3377  *          "async" itxs corresponding to different objects.
3378  *        - the order of "sync" itxs w.r.t. "async" itxs (or vice
3379  *          versa) is *not* preserved, even for itxs that correspond
3380  *          to the same object.
3381  *
3382  *      For more details, see: zil_itx_assign(), zil_async_to_sync(),
3383  *      zil_get_commit_list(), and zil_process_commit_list().
3384  *
3385  *   3. The lwbs represent a linked list of blocks on disk. Thus, any
3386  *      lwb cannot be considered committed to stable storage, until its
3387  *      "previous" lwb is also committed to stable storage. This fact,
3388  *      coupled with the fact described above, means that itxs are
3389  *      committed in (roughly) the order in which they were generated.
3390  *      This is essential because itxs are dependent on prior itxs.
3391  *      Thus, we *must not* deem an itx as being committed to stable
3392  *      storage, until *all* prior itxs have also been committed to
3393  *      stable storage.
3394  *
3395  *      To enforce this ordering of lwb zio's, while still leveraging as
3396  *      much of the underlying storage performance as possible, we rely
3397  *      on two fundamental concepts:
3398  *
3399  *          1. The creation and issuance of lwb zio's is protected by
3400  *             the zilog's "zl_issuer_lock", which ensures only a single
3401  *             thread is creating and/or issuing lwb's at a time
3402  *          2. The "previous" lwb is a child of the "current" lwb
3403  *             (leveraging the zio parent-child dependency graph)
3404  *
3405  *      By relying on this parent-child zio relationship, we can have
3406  *      many lwb zio's concurrently issued to the underlying storage,
3407  *      but the order in which they complete will be the same order in
3408  *      which they were created.
3409  */
3410 void
3411 zil_commit(zilog_t *zilog, uint64_t foid)
3412 {
3413 	/*
3414 	 * We should never attempt to call zil_commit on a snapshot for
3415 	 * a couple of reasons:
3416 	 *
3417 	 * 1. A snapshot may never be modified, thus it cannot have any
3418 	 *    in-flight itxs that would have modified the dataset.
3419 	 *
3420 	 * 2. By design, when zil_commit() is called, a commit itx will
3421 	 *    be assigned to this zilog; as a result, the zilog will be
3422 	 *    dirtied. We must not dirty the zilog of a snapshot; there's
3423 	 *    checks in the code that enforce this invariant, and will
3424 	 *    cause a panic if it's not upheld.
3425 	 */
3426 	ASSERT3B(dmu_objset_is_snapshot(zilog->zl_os), ==, B_FALSE);
3427 
3428 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
3429 		return;
3430 
3431 	if (!spa_writeable(zilog->zl_spa)) {
3432 		/*
3433 		 * If the SPA is not writable, there should never be any
3434 		 * pending itxs waiting to be committed to disk. If that
3435 		 * weren't true, we'd skip writing those itxs out, and
3436 		 * would break the semantics of zil_commit(); thus, we're
3437 		 * verifying that truth before we return to the caller.
3438 		 */
3439 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3440 		ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL);
3441 		for (int i = 0; i < TXG_SIZE; i++)
3442 			ASSERT3P(zilog->zl_itxg[i].itxg_itxs, ==, NULL);
3443 		return;
3444 	}
3445 
3446 	/*
3447 	 * If the ZIL is suspended, we don't want to dirty it by calling
3448 	 * zil_commit_itx_assign() below, nor can we write out
3449 	 * lwbs like would be done in zil_commit_write(). Thus, we
3450 	 * simply rely on txg_wait_synced() to maintain the necessary
3451 	 * semantics, and avoid calling those functions altogether.
3452 	 */
3453 	if (zilog->zl_suspend > 0) {
3454 		txg_wait_synced(zilog->zl_dmu_pool, 0);
3455 		return;
3456 	}
3457 
3458 	zil_commit_impl(zilog, foid);
3459 }
3460 
3461 void
3462 zil_commit_impl(zilog_t *zilog, uint64_t foid)
3463 {
3464 	ZIL_STAT_BUMP(zilog, zil_commit_count);
3465 
3466 	/*
3467 	 * Move the "async" itxs for the specified foid to the "sync"
3468 	 * queues, such that they will be later committed (or skipped)
3469 	 * to an lwb when zil_process_commit_list() is called.
3470 	 *
3471 	 * Since these "async" itxs must be committed prior to this
3472 	 * call to zil_commit returning, we must perform this operation
3473 	 * before we call zil_commit_itx_assign().
3474 	 */
3475 	zil_async_to_sync(zilog, foid);
3476 
3477 	/*
3478 	 * We allocate a new "waiter" structure which will initially be
3479 	 * linked to the commit itx using the itx's "itx_private" field.
3480 	 * Since the commit itx doesn't represent any on-disk state,
3481 	 * when it's committed to an lwb, rather than copying the its
3482 	 * lr_t into the lwb's buffer, the commit itx's "waiter" will be
3483 	 * added to the lwb's list of waiters. Then, when the lwb is
3484 	 * committed to stable storage, each waiter in the lwb's list of
3485 	 * waiters will be marked "done", and signalled.
3486 	 *
3487 	 * We must create the waiter and assign the commit itx prior to
3488 	 * calling zil_commit_writer(), or else our specific commit itx
3489 	 * is not guaranteed to be committed to an lwb prior to calling
3490 	 * zil_commit_waiter().
3491 	 */
3492 	zil_commit_waiter_t *zcw = zil_alloc_commit_waiter();
3493 	zil_commit_itx_assign(zilog, zcw);
3494 
3495 	uint64_t wtxg = zil_commit_writer(zilog, zcw);
3496 	zil_commit_waiter(zilog, zcw);
3497 
3498 	if (zcw->zcw_zio_error != 0) {
3499 		/*
3500 		 * If there was an error writing out the ZIL blocks that
3501 		 * this thread is waiting on, then we fallback to
3502 		 * relying on spa_sync() to write out the data this
3503 		 * thread is waiting on. Obviously this has performance
3504 		 * implications, but the expectation is for this to be
3505 		 * an exceptional case, and shouldn't occur often.
3506 		 */
3507 		DTRACE_PROBE2(zil__commit__io__error,
3508 		    zilog_t *, zilog, zil_commit_waiter_t *, zcw);
3509 		txg_wait_synced(zilog->zl_dmu_pool, 0);
3510 	} else if (wtxg != 0) {
3511 		txg_wait_synced(zilog->zl_dmu_pool, wtxg);
3512 	}
3513 
3514 	zil_free_commit_waiter(zcw);
3515 }
3516 
3517 /*
3518  * Called in syncing context to free committed log blocks and update log header.
3519  */
3520 void
3521 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
3522 {
3523 	zil_header_t *zh = zil_header_in_syncing_context(zilog);
3524 	uint64_t txg = dmu_tx_get_txg(tx);
3525 	spa_t *spa = zilog->zl_spa;
3526 	uint64_t *replayed_seq = &zilog->zl_replayed_seq[txg & TXG_MASK];
3527 	lwb_t *lwb;
3528 
3529 	/*
3530 	 * We don't zero out zl_destroy_txg, so make sure we don't try
3531 	 * to destroy it twice.
3532 	 */
3533 	if (spa_sync_pass(spa) != 1)
3534 		return;
3535 
3536 	zil_lwb_flush_wait_all(zilog, txg);
3537 
3538 	mutex_enter(&zilog->zl_lock);
3539 
3540 	ASSERT(zilog->zl_stop_sync == 0);
3541 
3542 	if (*replayed_seq != 0) {
3543 		ASSERT(zh->zh_replay_seq < *replayed_seq);
3544 		zh->zh_replay_seq = *replayed_seq;
3545 		*replayed_seq = 0;
3546 	}
3547 
3548 	if (zilog->zl_destroy_txg == txg) {
3549 		blkptr_t blk = zh->zh_log;
3550 		dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
3551 
3552 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3553 
3554 		memset(zh, 0, sizeof (zil_header_t));
3555 		memset(zilog->zl_replayed_seq, 0,
3556 		    sizeof (zilog->zl_replayed_seq));
3557 
3558 		if (zilog->zl_keep_first) {
3559 			/*
3560 			 * If this block was part of log chain that couldn't
3561 			 * be claimed because a device was missing during
3562 			 * zil_claim(), but that device later returns,
3563 			 * then this block could erroneously appear valid.
3564 			 * To guard against this, assign a new GUID to the new
3565 			 * log chain so it doesn't matter what blk points to.
3566 			 */
3567 			zil_init_log_chain(zilog, &blk);
3568 			zh->zh_log = blk;
3569 		} else {
3570 			/*
3571 			 * A destroyed ZIL chain can't contain any TX_SETSAXATTR
3572 			 * records. So, deactivate the feature for this dataset.
3573 			 * We activate it again when we start a new ZIL chain.
3574 			 */
3575 			if (dsl_dataset_feature_is_active(ds,
3576 			    SPA_FEATURE_ZILSAXATTR))
3577 				dsl_dataset_deactivate_feature(ds,
3578 				    SPA_FEATURE_ZILSAXATTR, tx);
3579 		}
3580 	}
3581 
3582 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
3583 		zh->zh_log = lwb->lwb_blk;
3584 		if (lwb->lwb_state != LWB_STATE_FLUSH_DONE ||
3585 		    lwb->lwb_alloc_txg > txg || lwb->lwb_max_txg > txg)
3586 			break;
3587 		list_remove(&zilog->zl_lwb_list, lwb);
3588 		if (!BP_IS_HOLE(&lwb->lwb_blk))
3589 			zio_free(spa, txg, &lwb->lwb_blk);
3590 		zil_free_lwb(zilog, lwb);
3591 
3592 		/*
3593 		 * If we don't have anything left in the lwb list then
3594 		 * we've had an allocation failure and we need to zero
3595 		 * out the zil_header blkptr so that we don't end
3596 		 * up freeing the same block twice.
3597 		 */
3598 		if (list_is_empty(&zilog->zl_lwb_list))
3599 			BP_ZERO(&zh->zh_log);
3600 	}
3601 
3602 	mutex_exit(&zilog->zl_lock);
3603 }
3604 
3605 static int
3606 zil_lwb_cons(void *vbuf, void *unused, int kmflag)
3607 {
3608 	(void) unused, (void) kmflag;
3609 	lwb_t *lwb = vbuf;
3610 	list_create(&lwb->lwb_itxs, sizeof (itx_t), offsetof(itx_t, itx_node));
3611 	list_create(&lwb->lwb_waiters, sizeof (zil_commit_waiter_t),
3612 	    offsetof(zil_commit_waiter_t, zcw_node));
3613 	avl_create(&lwb->lwb_vdev_tree, zil_lwb_vdev_compare,
3614 	    sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
3615 	mutex_init(&lwb->lwb_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
3616 	return (0);
3617 }
3618 
3619 static void
3620 zil_lwb_dest(void *vbuf, void *unused)
3621 {
3622 	(void) unused;
3623 	lwb_t *lwb = vbuf;
3624 	mutex_destroy(&lwb->lwb_vdev_lock);
3625 	avl_destroy(&lwb->lwb_vdev_tree);
3626 	list_destroy(&lwb->lwb_waiters);
3627 	list_destroy(&lwb->lwb_itxs);
3628 }
3629 
3630 void
3631 zil_init(void)
3632 {
3633 	zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
3634 	    sizeof (lwb_t), 0, zil_lwb_cons, zil_lwb_dest, NULL, NULL, NULL, 0);
3635 
3636 	zil_zcw_cache = kmem_cache_create("zil_zcw_cache",
3637 	    sizeof (zil_commit_waiter_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
3638 
3639 	zil_sums_init(&zil_sums_global);
3640 	zil_kstats_global = kstat_create("zfs", 0, "zil", "misc",
3641 	    KSTAT_TYPE_NAMED, sizeof (zil_stats) / sizeof (kstat_named_t),
3642 	    KSTAT_FLAG_VIRTUAL);
3643 
3644 	if (zil_kstats_global != NULL) {
3645 		zil_kstats_global->ks_data = &zil_stats;
3646 		zil_kstats_global->ks_update = zil_kstats_global_update;
3647 		zil_kstats_global->ks_private = NULL;
3648 		kstat_install(zil_kstats_global);
3649 	}
3650 }
3651 
3652 void
3653 zil_fini(void)
3654 {
3655 	kmem_cache_destroy(zil_zcw_cache);
3656 	kmem_cache_destroy(zil_lwb_cache);
3657 
3658 	if (zil_kstats_global != NULL) {
3659 		kstat_delete(zil_kstats_global);
3660 		zil_kstats_global = NULL;
3661 	}
3662 
3663 	zil_sums_fini(&zil_sums_global);
3664 }
3665 
3666 void
3667 zil_set_sync(zilog_t *zilog, uint64_t sync)
3668 {
3669 	zilog->zl_sync = sync;
3670 }
3671 
3672 void
3673 zil_set_logbias(zilog_t *zilog, uint64_t logbias)
3674 {
3675 	zilog->zl_logbias = logbias;
3676 }
3677 
3678 zilog_t *
3679 zil_alloc(objset_t *os, zil_header_t *zh_phys)
3680 {
3681 	zilog_t *zilog;
3682 
3683 	zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
3684 
3685 	zilog->zl_header = zh_phys;
3686 	zilog->zl_os = os;
3687 	zilog->zl_spa = dmu_objset_spa(os);
3688 	zilog->zl_dmu_pool = dmu_objset_pool(os);
3689 	zilog->zl_destroy_txg = TXG_INITIAL - 1;
3690 	zilog->zl_logbias = dmu_objset_logbias(os);
3691 	zilog->zl_sync = dmu_objset_syncprop(os);
3692 	zilog->zl_dirty_max_txg = 0;
3693 	zilog->zl_last_lwb_opened = NULL;
3694 	zilog->zl_last_lwb_latency = 0;
3695 	zilog->zl_max_block_size = zil_maxblocksize;
3696 
3697 	mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
3698 	mutex_init(&zilog->zl_issuer_lock, NULL, MUTEX_DEFAULT, NULL);
3699 	mutex_init(&zilog->zl_lwb_io_lock, NULL, MUTEX_DEFAULT, NULL);
3700 
3701 	for (int i = 0; i < TXG_SIZE; i++) {
3702 		mutex_init(&zilog->zl_itxg[i].itxg_lock, NULL,
3703 		    MUTEX_DEFAULT, NULL);
3704 	}
3705 
3706 	list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
3707 	    offsetof(lwb_t, lwb_node));
3708 
3709 	list_create(&zilog->zl_itx_commit_list, sizeof (itx_t),
3710 	    offsetof(itx_t, itx_node));
3711 
3712 	cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
3713 	cv_init(&zilog->zl_lwb_io_cv, NULL, CV_DEFAULT, NULL);
3714 
3715 	return (zilog);
3716 }
3717 
3718 void
3719 zil_free(zilog_t *zilog)
3720 {
3721 	int i;
3722 
3723 	zilog->zl_stop_sync = 1;
3724 
3725 	ASSERT0(zilog->zl_suspend);
3726 	ASSERT0(zilog->zl_suspending);
3727 
3728 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
3729 	list_destroy(&zilog->zl_lwb_list);
3730 
3731 	ASSERT(list_is_empty(&zilog->zl_itx_commit_list));
3732 	list_destroy(&zilog->zl_itx_commit_list);
3733 
3734 	for (i = 0; i < TXG_SIZE; i++) {
3735 		/*
3736 		 * It's possible for an itx to be generated that doesn't dirty
3737 		 * a txg (e.g. ztest TX_TRUNCATE). So there's no zil_clean()
3738 		 * callback to remove the entry. We remove those here.
3739 		 *
3740 		 * Also free up the ziltest itxs.
3741 		 */
3742 		if (zilog->zl_itxg[i].itxg_itxs)
3743 			zil_itxg_clean(zilog->zl_itxg[i].itxg_itxs);
3744 		mutex_destroy(&zilog->zl_itxg[i].itxg_lock);
3745 	}
3746 
3747 	mutex_destroy(&zilog->zl_issuer_lock);
3748 	mutex_destroy(&zilog->zl_lock);
3749 	mutex_destroy(&zilog->zl_lwb_io_lock);
3750 
3751 	cv_destroy(&zilog->zl_cv_suspend);
3752 	cv_destroy(&zilog->zl_lwb_io_cv);
3753 
3754 	kmem_free(zilog, sizeof (zilog_t));
3755 }
3756 
3757 /*
3758  * Open an intent log.
3759  */
3760 zilog_t *
3761 zil_open(objset_t *os, zil_get_data_t *get_data, zil_sums_t *zil_sums)
3762 {
3763 	zilog_t *zilog = dmu_objset_zil(os);
3764 
3765 	ASSERT3P(zilog->zl_get_data, ==, NULL);
3766 	ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL);
3767 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
3768 
3769 	zilog->zl_get_data = get_data;
3770 	zilog->zl_sums = zil_sums;
3771 
3772 	return (zilog);
3773 }
3774 
3775 /*
3776  * Close an intent log.
3777  */
3778 void
3779 zil_close(zilog_t *zilog)
3780 {
3781 	lwb_t *lwb;
3782 	uint64_t txg;
3783 
3784 	if (!dmu_objset_is_snapshot(zilog->zl_os)) {
3785 		zil_commit(zilog, 0);
3786 	} else {
3787 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3788 		ASSERT0(zilog->zl_dirty_max_txg);
3789 		ASSERT3B(zilog_is_dirty(zilog), ==, B_FALSE);
3790 	}
3791 
3792 	mutex_enter(&zilog->zl_lock);
3793 	txg = zilog->zl_dirty_max_txg;
3794 	lwb = list_tail(&zilog->zl_lwb_list);
3795 	if (lwb != NULL) {
3796 		txg = MAX(txg, lwb->lwb_alloc_txg);
3797 		txg = MAX(txg, lwb->lwb_max_txg);
3798 	}
3799 	mutex_exit(&zilog->zl_lock);
3800 
3801 	/*
3802 	 * zl_lwb_max_issued_txg may be larger than lwb_max_txg. It depends
3803 	 * on the time when the dmu_tx transaction is assigned in
3804 	 * zil_lwb_write_issue().
3805 	 */
3806 	mutex_enter(&zilog->zl_lwb_io_lock);
3807 	txg = MAX(zilog->zl_lwb_max_issued_txg, txg);
3808 	mutex_exit(&zilog->zl_lwb_io_lock);
3809 
3810 	/*
3811 	 * We need to use txg_wait_synced() to wait until that txg is synced.
3812 	 * zil_sync() will guarantee all lwbs up to that txg have been
3813 	 * written out, flushed, and cleaned.
3814 	 */
3815 	if (txg != 0)
3816 		txg_wait_synced(zilog->zl_dmu_pool, txg);
3817 
3818 	if (zilog_is_dirty(zilog))
3819 		zfs_dbgmsg("zil (%px) is dirty, txg %llu", zilog,
3820 		    (u_longlong_t)txg);
3821 	if (txg < spa_freeze_txg(zilog->zl_spa))
3822 		VERIFY(!zilog_is_dirty(zilog));
3823 
3824 	zilog->zl_get_data = NULL;
3825 
3826 	/*
3827 	 * We should have only one lwb left on the list; remove it now.
3828 	 */
3829 	mutex_enter(&zilog->zl_lock);
3830 	lwb = list_remove_head(&zilog->zl_lwb_list);
3831 	if (lwb != NULL) {
3832 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3833 		ASSERT3S(lwb->lwb_state, ==, LWB_STATE_NEW);
3834 		zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
3835 		zil_free_lwb(zilog, lwb);
3836 	}
3837 	mutex_exit(&zilog->zl_lock);
3838 }
3839 
3840 static const char *suspend_tag = "zil suspending";
3841 
3842 /*
3843  * Suspend an intent log.  While in suspended mode, we still honor
3844  * synchronous semantics, but we rely on txg_wait_synced() to do it.
3845  * On old version pools, we suspend the log briefly when taking a
3846  * snapshot so that it will have an empty intent log.
3847  *
3848  * Long holds are not really intended to be used the way we do here --
3849  * held for such a short time.  A concurrent caller of dsl_dataset_long_held()
3850  * could fail.  Therefore we take pains to only put a long hold if it is
3851  * actually necessary.  Fortunately, it will only be necessary if the
3852  * objset is currently mounted (or the ZVOL equivalent).  In that case it
3853  * will already have a long hold, so we are not really making things any worse.
3854  *
3855  * Ideally, we would locate the existing long-holder (i.e. the zfsvfs_t or
3856  * zvol_state_t), and use their mechanism to prevent their hold from being
3857  * dropped (e.g. VFS_HOLD()).  However, that would be even more pain for
3858  * very little gain.
3859  *
3860  * if cookiep == NULL, this does both the suspend & resume.
3861  * Otherwise, it returns with the dataset "long held", and the cookie
3862  * should be passed into zil_resume().
3863  */
3864 int
3865 zil_suspend(const char *osname, void **cookiep)
3866 {
3867 	objset_t *os;
3868 	zilog_t *zilog;
3869 	const zil_header_t *zh;
3870 	int error;
3871 
3872 	error = dmu_objset_hold(osname, suspend_tag, &os);
3873 	if (error != 0)
3874 		return (error);
3875 	zilog = dmu_objset_zil(os);
3876 
3877 	mutex_enter(&zilog->zl_lock);
3878 	zh = zilog->zl_header;
3879 
3880 	if (zh->zh_flags & ZIL_REPLAY_NEEDED) {		/* unplayed log */
3881 		mutex_exit(&zilog->zl_lock);
3882 		dmu_objset_rele(os, suspend_tag);
3883 		return (SET_ERROR(EBUSY));
3884 	}
3885 
3886 	/*
3887 	 * Don't put a long hold in the cases where we can avoid it.  This
3888 	 * is when there is no cookie so we are doing a suspend & resume
3889 	 * (i.e. called from zil_vdev_offline()), and there's nothing to do
3890 	 * for the suspend because it's already suspended, or there's no ZIL.
3891 	 */
3892 	if (cookiep == NULL && !zilog->zl_suspending &&
3893 	    (zilog->zl_suspend > 0 || BP_IS_HOLE(&zh->zh_log))) {
3894 		mutex_exit(&zilog->zl_lock);
3895 		dmu_objset_rele(os, suspend_tag);
3896 		return (0);
3897 	}
3898 
3899 	dsl_dataset_long_hold(dmu_objset_ds(os), suspend_tag);
3900 	dsl_pool_rele(dmu_objset_pool(os), suspend_tag);
3901 
3902 	zilog->zl_suspend++;
3903 
3904 	if (zilog->zl_suspend > 1) {
3905 		/*
3906 		 * Someone else is already suspending it.
3907 		 * Just wait for them to finish.
3908 		 */
3909 
3910 		while (zilog->zl_suspending)
3911 			cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
3912 		mutex_exit(&zilog->zl_lock);
3913 
3914 		if (cookiep == NULL)
3915 			zil_resume(os);
3916 		else
3917 			*cookiep = os;
3918 		return (0);
3919 	}
3920 
3921 	/*
3922 	 * If there is no pointer to an on-disk block, this ZIL must not
3923 	 * be active (e.g. filesystem not mounted), so there's nothing
3924 	 * to clean up.
3925 	 */
3926 	if (BP_IS_HOLE(&zh->zh_log)) {
3927 		ASSERT(cookiep != NULL); /* fast path already handled */
3928 
3929 		*cookiep = os;
3930 		mutex_exit(&zilog->zl_lock);
3931 		return (0);
3932 	}
3933 
3934 	/*
3935 	 * The ZIL has work to do. Ensure that the associated encryption
3936 	 * key will remain mapped while we are committing the log by
3937 	 * grabbing a reference to it. If the key isn't loaded we have no
3938 	 * choice but to return an error until the wrapping key is loaded.
3939 	 */
3940 	if (os->os_encrypted &&
3941 	    dsl_dataset_create_key_mapping(dmu_objset_ds(os)) != 0) {
3942 		zilog->zl_suspend--;
3943 		mutex_exit(&zilog->zl_lock);
3944 		dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag);
3945 		dsl_dataset_rele(dmu_objset_ds(os), suspend_tag);
3946 		return (SET_ERROR(EACCES));
3947 	}
3948 
3949 	zilog->zl_suspending = B_TRUE;
3950 	mutex_exit(&zilog->zl_lock);
3951 
3952 	/*
3953 	 * We need to use zil_commit_impl to ensure we wait for all
3954 	 * LWB_STATE_OPENED, _CLOSED and _READY lwbs to be committed
3955 	 * to disk before proceeding. If we used zil_commit instead, it
3956 	 * would just call txg_wait_synced(), because zl_suspend is set.
3957 	 * txg_wait_synced() doesn't wait for these lwb's to be
3958 	 * LWB_STATE_FLUSH_DONE before returning.
3959 	 */
3960 	zil_commit_impl(zilog, 0);
3961 
3962 	/*
3963 	 * Now that we've ensured all lwb's are LWB_STATE_FLUSH_DONE, we
3964 	 * use txg_wait_synced() to ensure the data from the zilog has
3965 	 * migrated to the main pool before calling zil_destroy().
3966 	 */
3967 	txg_wait_synced(zilog->zl_dmu_pool, 0);
3968 
3969 	zil_destroy(zilog, B_FALSE);
3970 
3971 	mutex_enter(&zilog->zl_lock);
3972 	zilog->zl_suspending = B_FALSE;
3973 	cv_broadcast(&zilog->zl_cv_suspend);
3974 	mutex_exit(&zilog->zl_lock);
3975 
3976 	if (os->os_encrypted)
3977 		dsl_dataset_remove_key_mapping(dmu_objset_ds(os));
3978 
3979 	if (cookiep == NULL)
3980 		zil_resume(os);
3981 	else
3982 		*cookiep = os;
3983 	return (0);
3984 }
3985 
3986 void
3987 zil_resume(void *cookie)
3988 {
3989 	objset_t *os = cookie;
3990 	zilog_t *zilog = dmu_objset_zil(os);
3991 
3992 	mutex_enter(&zilog->zl_lock);
3993 	ASSERT(zilog->zl_suspend != 0);
3994 	zilog->zl_suspend--;
3995 	mutex_exit(&zilog->zl_lock);
3996 	dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag);
3997 	dsl_dataset_rele(dmu_objset_ds(os), suspend_tag);
3998 }
3999 
4000 typedef struct zil_replay_arg {
4001 	zil_replay_func_t *const *zr_replay;
4002 	void		*zr_arg;
4003 	boolean_t	zr_byteswap;
4004 	char		*zr_lr;
4005 } zil_replay_arg_t;
4006 
4007 static int
4008 zil_replay_error(zilog_t *zilog, const lr_t *lr, int error)
4009 {
4010 	char name[ZFS_MAX_DATASET_NAME_LEN];
4011 
4012 	zilog->zl_replaying_seq--;	/* didn't actually replay this one */
4013 
4014 	dmu_objset_name(zilog->zl_os, name);
4015 
4016 	cmn_err(CE_WARN, "ZFS replay transaction error %d, "
4017 	    "dataset %s, seq 0x%llx, txtype %llu %s\n", error, name,
4018 	    (u_longlong_t)lr->lrc_seq,
4019 	    (u_longlong_t)(lr->lrc_txtype & ~TX_CI),
4020 	    (lr->lrc_txtype & TX_CI) ? "CI" : "");
4021 
4022 	return (error);
4023 }
4024 
4025 static int
4026 zil_replay_log_record(zilog_t *zilog, const lr_t *lr, void *zra,
4027     uint64_t claim_txg)
4028 {
4029 	zil_replay_arg_t *zr = zra;
4030 	const zil_header_t *zh = zilog->zl_header;
4031 	uint64_t reclen = lr->lrc_reclen;
4032 	uint64_t txtype = lr->lrc_txtype;
4033 	int error = 0;
4034 
4035 	zilog->zl_replaying_seq = lr->lrc_seq;
4036 
4037 	if (lr->lrc_seq <= zh->zh_replay_seq)	/* already replayed */
4038 		return (0);
4039 
4040 	if (lr->lrc_txg < claim_txg)		/* already committed */
4041 		return (0);
4042 
4043 	/* Strip case-insensitive bit, still present in log record */
4044 	txtype &= ~TX_CI;
4045 
4046 	if (txtype == 0 || txtype >= TX_MAX_TYPE)
4047 		return (zil_replay_error(zilog, lr, EINVAL));
4048 
4049 	/*
4050 	 * If this record type can be logged out of order, the object
4051 	 * (lr_foid) may no longer exist.  That's legitimate, not an error.
4052 	 */
4053 	if (TX_OOO(txtype)) {
4054 		error = dmu_object_info(zilog->zl_os,
4055 		    LR_FOID_GET_OBJ(((lr_ooo_t *)lr)->lr_foid), NULL);
4056 		if (error == ENOENT || error == EEXIST)
4057 			return (0);
4058 	}
4059 
4060 	/*
4061 	 * Make a copy of the data so we can revise and extend it.
4062 	 */
4063 	memcpy(zr->zr_lr, lr, reclen);
4064 
4065 	/*
4066 	 * If this is a TX_WRITE with a blkptr, suck in the data.
4067 	 */
4068 	if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
4069 		error = zil_read_log_data(zilog, (lr_write_t *)lr,
4070 		    zr->zr_lr + reclen);
4071 		if (error != 0)
4072 			return (zil_replay_error(zilog, lr, error));
4073 	}
4074 
4075 	/*
4076 	 * The log block containing this lr may have been byteswapped
4077 	 * so that we can easily examine common fields like lrc_txtype.
4078 	 * However, the log is a mix of different record types, and only the
4079 	 * replay vectors know how to byteswap their records.  Therefore, if
4080 	 * the lr was byteswapped, undo it before invoking the replay vector.
4081 	 */
4082 	if (zr->zr_byteswap)
4083 		byteswap_uint64_array(zr->zr_lr, reclen);
4084 
4085 	/*
4086 	 * We must now do two things atomically: replay this log record,
4087 	 * and update the log header sequence number to reflect the fact that
4088 	 * we did so. At the end of each replay function the sequence number
4089 	 * is updated if we are in replay mode.
4090 	 */
4091 	error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, zr->zr_byteswap);
4092 	if (error != 0) {
4093 		/*
4094 		 * The DMU's dnode layer doesn't see removes until the txg
4095 		 * commits, so a subsequent claim can spuriously fail with
4096 		 * EEXIST. So if we receive any error we try syncing out
4097 		 * any removes then retry the transaction.  Note that we
4098 		 * specify B_FALSE for byteswap now, so we don't do it twice.
4099 		 */
4100 		txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
4101 		error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, B_FALSE);
4102 		if (error != 0)
4103 			return (zil_replay_error(zilog, lr, error));
4104 	}
4105 	return (0);
4106 }
4107 
4108 static int
4109 zil_incr_blks(zilog_t *zilog, const blkptr_t *bp, void *arg, uint64_t claim_txg)
4110 {
4111 	(void) bp, (void) arg, (void) claim_txg;
4112 
4113 	zilog->zl_replay_blks++;
4114 
4115 	return (0);
4116 }
4117 
4118 /*
4119  * If this dataset has a non-empty intent log, replay it and destroy it.
4120  * Return B_TRUE if there were any entries to replay.
4121  */
4122 boolean_t
4123 zil_replay(objset_t *os, void *arg,
4124     zil_replay_func_t *const replay_func[TX_MAX_TYPE])
4125 {
4126 	zilog_t *zilog = dmu_objset_zil(os);
4127 	const zil_header_t *zh = zilog->zl_header;
4128 	zil_replay_arg_t zr;
4129 
4130 	if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
4131 		return (zil_destroy(zilog, B_TRUE));
4132 	}
4133 
4134 	zr.zr_replay = replay_func;
4135 	zr.zr_arg = arg;
4136 	zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
4137 	zr.zr_lr = vmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
4138 
4139 	/*
4140 	 * Wait for in-progress removes to sync before starting replay.
4141 	 */
4142 	txg_wait_synced(zilog->zl_dmu_pool, 0);
4143 
4144 	zilog->zl_replay = B_TRUE;
4145 	zilog->zl_replay_time = ddi_get_lbolt();
4146 	ASSERT(zilog->zl_replay_blks == 0);
4147 	(void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
4148 	    zh->zh_claim_txg, B_TRUE);
4149 	vmem_free(zr.zr_lr, 2 * SPA_MAXBLOCKSIZE);
4150 
4151 	zil_destroy(zilog, B_FALSE);
4152 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
4153 	zilog->zl_replay = B_FALSE;
4154 
4155 	return (B_TRUE);
4156 }
4157 
4158 boolean_t
4159 zil_replaying(zilog_t *zilog, dmu_tx_t *tx)
4160 {
4161 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
4162 		return (B_TRUE);
4163 
4164 	if (zilog->zl_replay) {
4165 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
4166 		zilog->zl_replayed_seq[dmu_tx_get_txg(tx) & TXG_MASK] =
4167 		    zilog->zl_replaying_seq;
4168 		return (B_TRUE);
4169 	}
4170 
4171 	return (B_FALSE);
4172 }
4173 
4174 int
4175 zil_reset(const char *osname, void *arg)
4176 {
4177 	(void) arg;
4178 
4179 	int error = zil_suspend(osname, NULL);
4180 	/* EACCES means crypto key not loaded */
4181 	if ((error == EACCES) || (error == EBUSY))
4182 		return (SET_ERROR(error));
4183 	if (error != 0)
4184 		return (SET_ERROR(EEXIST));
4185 	return (0);
4186 }
4187 
4188 EXPORT_SYMBOL(zil_alloc);
4189 EXPORT_SYMBOL(zil_free);
4190 EXPORT_SYMBOL(zil_open);
4191 EXPORT_SYMBOL(zil_close);
4192 EXPORT_SYMBOL(zil_replay);
4193 EXPORT_SYMBOL(zil_replaying);
4194 EXPORT_SYMBOL(zil_destroy);
4195 EXPORT_SYMBOL(zil_destroy_sync);
4196 EXPORT_SYMBOL(zil_itx_create);
4197 EXPORT_SYMBOL(zil_itx_destroy);
4198 EXPORT_SYMBOL(zil_itx_assign);
4199 EXPORT_SYMBOL(zil_commit);
4200 EXPORT_SYMBOL(zil_claim);
4201 EXPORT_SYMBOL(zil_check_log_chain);
4202 EXPORT_SYMBOL(zil_sync);
4203 EXPORT_SYMBOL(zil_clean);
4204 EXPORT_SYMBOL(zil_suspend);
4205 EXPORT_SYMBOL(zil_resume);
4206 EXPORT_SYMBOL(zil_lwb_add_block);
4207 EXPORT_SYMBOL(zil_bp_tree_add);
4208 EXPORT_SYMBOL(zil_set_sync);
4209 EXPORT_SYMBOL(zil_set_logbias);
4210 EXPORT_SYMBOL(zil_sums_init);
4211 EXPORT_SYMBOL(zil_sums_fini);
4212 EXPORT_SYMBOL(zil_kstat_values_update);
4213 
4214 ZFS_MODULE_PARAM(zfs, zfs_, commit_timeout_pct, UINT, ZMOD_RW,
4215 	"ZIL block open timeout percentage");
4216 
4217 ZFS_MODULE_PARAM(zfs_zil, zil_, min_commit_timeout, U64, ZMOD_RW,
4218 	"Minimum delay we care for ZIL block commit");
4219 
4220 ZFS_MODULE_PARAM(zfs_zil, zil_, replay_disable, INT, ZMOD_RW,
4221 	"Disable intent logging replay");
4222 
4223 ZFS_MODULE_PARAM(zfs_zil, zil_, nocacheflush, INT, ZMOD_RW,
4224 	"Disable ZIL cache flushes");
4225 
4226 ZFS_MODULE_PARAM(zfs_zil, zil_, slog_bulk, U64, ZMOD_RW,
4227 	"Limit in bytes slog sync writes per commit");
4228 
4229 ZFS_MODULE_PARAM(zfs_zil, zil_, maxblocksize, UINT, ZMOD_RW,
4230 	"Limit in bytes of ZIL log block size");
4231 
4232 ZFS_MODULE_PARAM(zfs_zil, zil_, maxcopied, UINT, ZMOD_RW,
4233 	"Limit in bytes WR_COPIED size");
4234