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