xref: /illumos-gate/usr/src/uts/common/fs/zfs/zil.c (revision 5cabbc6b49070407fb9610cfe73d4c0e0dea3e77)
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 http://www.opensolaris.org/os/licensing.
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, 2017 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Integros [integros.com]
25  */
26 
27 /* Portions Copyright 2010 Robert Milkowski */
28 
29 #include <sys/zfs_context.h>
30 #include <sys/spa.h>
31 #include <sys/dmu.h>
32 #include <sys/zap.h>
33 #include <sys/arc.h>
34 #include <sys/stat.h>
35 #include <sys/resource.h>
36 #include <sys/zil.h>
37 #include <sys/zil_impl.h>
38 #include <sys/dsl_dataset.h>
39 #include <sys/vdev_impl.h>
40 #include <sys/dmu_tx.h>
41 #include <sys/dsl_pool.h>
42 #include <sys/abd.h>
43 
44 /*
45  * The ZFS Intent Log (ZIL) saves "transaction records" (itxs) of system
46  * calls that change the file system. Each itx has enough information to
47  * be able to replay them after a system crash, power loss, or
48  * equivalent failure mode. These are stored in memory until either:
49  *
50  *   1. they are committed to the pool by the DMU transaction group
51  *      (txg), at which point they can be discarded; or
52  *   2. they are committed to the on-disk ZIL for the dataset being
53  *      modified (e.g. due to an fsync, O_DSYNC, or other synchronous
54  *      requirement).
55  *
56  * In the event of a crash or power loss, the itxs contained by each
57  * dataset's on-disk ZIL will be replayed when that dataset is first
58  * instantianted (e.g. if the dataset is a normal fileystem, when it is
59  * first mounted).
60  *
61  * As hinted at above, there is one ZIL per dataset (both the in-memory
62  * representation, and the on-disk representation). The on-disk format
63  * consists of 3 parts:
64  *
65  * 	- a single, per-dataset, ZIL header; which points to a chain of
66  * 	- zero or more ZIL blocks; each of which contains
67  * 	- zero or more ZIL records
68  *
69  * A ZIL record holds the information necessary to replay a single
70  * system call transaction. A ZIL block can hold many ZIL records, and
71  * the blocks are chained together, similarly to a singly linked list.
72  *
73  * Each ZIL block contains a block pointer (blkptr_t) to the next ZIL
74  * block in the chain, and the ZIL header points to the first block in
75  * the chain.
76  *
77  * Note, there is not a fixed place in the pool to hold these ZIL
78  * blocks; they are dynamically allocated and freed as needed from the
79  * blocks available on the pool, though they can be preferentially
80  * allocated from a dedicated "log" vdev.
81  */
82 
83 /*
84  * This controls the amount of time that a ZIL block (lwb) will remain
85  * "open" when it isn't "full", and it has a thread waiting for it to be
86  * committed to stable storage. Please refer to the zil_commit_waiter()
87  * function (and the comments within it) for more details.
88  */
89 int zfs_commit_timeout_pct = 5;
90 
91 /*
92  * Disable intent logging replay.  This global ZIL switch affects all pools.
93  */
94 int zil_replay_disable = 0;
95 
96 /*
97  * Tunable parameter for debugging or performance analysis.  Setting
98  * zfs_nocacheflush will cause corruption on power loss if a volatile
99  * out-of-order write cache is enabled.
100  */
101 boolean_t zfs_nocacheflush = B_FALSE;
102 
103 /*
104  * Limit SLOG write size per commit executed with synchronous priority.
105  * Any writes above that will be executed with lower (asynchronous) priority
106  * to limit potential SLOG device abuse by single active ZIL writer.
107  */
108 uint64_t zil_slog_bulk = 768 * 1024;
109 
110 static kmem_cache_t *zil_lwb_cache;
111 static kmem_cache_t *zil_zcw_cache;
112 
113 static void zil_async_to_sync(zilog_t *zilog, uint64_t foid);
114 
115 #define	LWB_EMPTY(lwb) ((BP_GET_LSIZE(&lwb->lwb_blk) - \
116     sizeof (zil_chain_t)) == (lwb->lwb_sz - lwb->lwb_nused))
117 
118 static int
119 zil_bp_compare(const void *x1, const void *x2)
120 {
121 	const dva_t *dva1 = &((zil_bp_node_t *)x1)->zn_dva;
122 	const dva_t *dva2 = &((zil_bp_node_t *)x2)->zn_dva;
123 
124 	if (DVA_GET_VDEV(dva1) < DVA_GET_VDEV(dva2))
125 		return (-1);
126 	if (DVA_GET_VDEV(dva1) > DVA_GET_VDEV(dva2))
127 		return (1);
128 
129 	if (DVA_GET_OFFSET(dva1) < DVA_GET_OFFSET(dva2))
130 		return (-1);
131 	if (DVA_GET_OFFSET(dva1) > DVA_GET_OFFSET(dva2))
132 		return (1);
133 
134 	return (0);
135 }
136 
137 static void
138 zil_bp_tree_init(zilog_t *zilog)
139 {
140 	avl_create(&zilog->zl_bp_tree, zil_bp_compare,
141 	    sizeof (zil_bp_node_t), offsetof(zil_bp_node_t, zn_node));
142 }
143 
144 static void
145 zil_bp_tree_fini(zilog_t *zilog)
146 {
147 	avl_tree_t *t = &zilog->zl_bp_tree;
148 	zil_bp_node_t *zn;
149 	void *cookie = NULL;
150 
151 	while ((zn = avl_destroy_nodes(t, &cookie)) != NULL)
152 		kmem_free(zn, sizeof (zil_bp_node_t));
153 
154 	avl_destroy(t);
155 }
156 
157 int
158 zil_bp_tree_add(zilog_t *zilog, const blkptr_t *bp)
159 {
160 	avl_tree_t *t = &zilog->zl_bp_tree;
161 	const dva_t *dva;
162 	zil_bp_node_t *zn;
163 	avl_index_t where;
164 
165 	if (BP_IS_EMBEDDED(bp))
166 		return (0);
167 
168 	dva = BP_IDENTITY(bp);
169 
170 	if (avl_find(t, dva, &where) != NULL)
171 		return (SET_ERROR(EEXIST));
172 
173 	zn = kmem_alloc(sizeof (zil_bp_node_t), KM_SLEEP);
174 	zn->zn_dva = *dva;
175 	avl_insert(t, zn, where);
176 
177 	return (0);
178 }
179 
180 static zil_header_t *
181 zil_header_in_syncing_context(zilog_t *zilog)
182 {
183 	return ((zil_header_t *)zilog->zl_header);
184 }
185 
186 static void
187 zil_init_log_chain(zilog_t *zilog, blkptr_t *bp)
188 {
189 	zio_cksum_t *zc = &bp->blk_cksum;
190 
191 	zc->zc_word[ZIL_ZC_GUID_0] = spa_get_random(-1ULL);
192 	zc->zc_word[ZIL_ZC_GUID_1] = spa_get_random(-1ULL);
193 	zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os);
194 	zc->zc_word[ZIL_ZC_SEQ] = 1ULL;
195 }
196 
197 /*
198  * Read a log block and make sure it's valid.
199  */
200 static int
201 zil_read_log_block(zilog_t *zilog, const blkptr_t *bp, blkptr_t *nbp, void *dst,
202     char **end)
203 {
204 	enum zio_flag zio_flags = ZIO_FLAG_CANFAIL;
205 	arc_flags_t aflags = ARC_FLAG_WAIT;
206 	arc_buf_t *abuf = NULL;
207 	zbookmark_phys_t zb;
208 	int error;
209 
210 	if (zilog->zl_header->zh_claim_txg == 0)
211 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
212 
213 	if (!(zilog->zl_header->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
214 		zio_flags |= ZIO_FLAG_SPECULATIVE;
215 
216 	SET_BOOKMARK(&zb, bp->blk_cksum.zc_word[ZIL_ZC_OBJSET],
217 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
218 
219 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
220 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
221 
222 	if (error == 0) {
223 		zio_cksum_t cksum = bp->blk_cksum;
224 
225 		/*
226 		 * Validate the checksummed log block.
227 		 *
228 		 * Sequence numbers should be... sequential.  The checksum
229 		 * verifier for the next block should be bp's checksum plus 1.
230 		 *
231 		 * Also check the log chain linkage and size used.
232 		 */
233 		cksum.zc_word[ZIL_ZC_SEQ]++;
234 
235 		if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) {
236 			zil_chain_t *zilc = abuf->b_data;
237 			char *lr = (char *)(zilc + 1);
238 			uint64_t len = zilc->zc_nused - sizeof (zil_chain_t);
239 
240 			if (bcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
241 			    sizeof (cksum)) || BP_IS_HOLE(&zilc->zc_next_blk)) {
242 				error = SET_ERROR(ECKSUM);
243 			} else {
244 				ASSERT3U(len, <=, SPA_OLD_MAXBLOCKSIZE);
245 				bcopy(lr, dst, len);
246 				*end = (char *)dst + len;
247 				*nbp = zilc->zc_next_blk;
248 			}
249 		} else {
250 			char *lr = abuf->b_data;
251 			uint64_t size = BP_GET_LSIZE(bp);
252 			zil_chain_t *zilc = (zil_chain_t *)(lr + size) - 1;
253 
254 			if (bcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
255 			    sizeof (cksum)) || BP_IS_HOLE(&zilc->zc_next_blk) ||
256 			    (zilc->zc_nused > (size - sizeof (*zilc)))) {
257 				error = SET_ERROR(ECKSUM);
258 			} else {
259 				ASSERT3U(zilc->zc_nused, <=,
260 				    SPA_OLD_MAXBLOCKSIZE);
261 				bcopy(lr, dst, zilc->zc_nused);
262 				*end = (char *)dst + zilc->zc_nused;
263 				*nbp = zilc->zc_next_blk;
264 			}
265 		}
266 
267 		arc_buf_destroy(abuf, &abuf);
268 	}
269 
270 	return (error);
271 }
272 
273 /*
274  * Read a TX_WRITE log data block.
275  */
276 static int
277 zil_read_log_data(zilog_t *zilog, const lr_write_t *lr, void *wbuf)
278 {
279 	enum zio_flag zio_flags = ZIO_FLAG_CANFAIL;
280 	const blkptr_t *bp = &lr->lr_blkptr;
281 	arc_flags_t aflags = ARC_FLAG_WAIT;
282 	arc_buf_t *abuf = NULL;
283 	zbookmark_phys_t zb;
284 	int error;
285 
286 	if (BP_IS_HOLE(bp)) {
287 		if (wbuf != NULL)
288 			bzero(wbuf, MAX(BP_GET_LSIZE(bp), lr->lr_length));
289 		return (0);
290 	}
291 
292 	if (zilog->zl_header->zh_claim_txg == 0)
293 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
294 
295 	SET_BOOKMARK(&zb, dmu_objset_id(zilog->zl_os), lr->lr_foid,
296 	    ZB_ZIL_LEVEL, lr->lr_offset / BP_GET_LSIZE(bp));
297 
298 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
299 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
300 
301 	if (error == 0) {
302 		if (wbuf != NULL)
303 			bcopy(abuf->b_data, wbuf, arc_buf_size(abuf));
304 		arc_buf_destroy(abuf, &abuf);
305 	}
306 
307 	return (error);
308 }
309 
310 /*
311  * Parse the intent log, and call parse_func for each valid record within.
312  */
313 int
314 zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func,
315     zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg)
316 {
317 	const zil_header_t *zh = zilog->zl_header;
318 	boolean_t claimed = !!zh->zh_claim_txg;
319 	uint64_t claim_blk_seq = claimed ? zh->zh_claim_blk_seq : UINT64_MAX;
320 	uint64_t claim_lr_seq = claimed ? zh->zh_claim_lr_seq : UINT64_MAX;
321 	uint64_t max_blk_seq = 0;
322 	uint64_t max_lr_seq = 0;
323 	uint64_t blk_count = 0;
324 	uint64_t lr_count = 0;
325 	blkptr_t blk, next_blk;
326 	char *lrbuf, *lrp;
327 	int error = 0;
328 
329 	/*
330 	 * Old logs didn't record the maximum zh_claim_lr_seq.
331 	 */
332 	if (!(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
333 		claim_lr_seq = UINT64_MAX;
334 
335 	/*
336 	 * Starting at the block pointed to by zh_log we read the log chain.
337 	 * For each block in the chain we strongly check that block to
338 	 * ensure its validity.  We stop when an invalid block is found.
339 	 * For each block pointer in the chain we call parse_blk_func().
340 	 * For each record in each valid block we call parse_lr_func().
341 	 * If the log has been claimed, stop if we encounter a sequence
342 	 * number greater than the highest claimed sequence number.
343 	 */
344 	lrbuf = zio_buf_alloc(SPA_OLD_MAXBLOCKSIZE);
345 	zil_bp_tree_init(zilog);
346 
347 	for (blk = zh->zh_log; !BP_IS_HOLE(&blk); blk = next_blk) {
348 		uint64_t blk_seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
349 		int reclen;
350 		char *end;
351 
352 		if (blk_seq > claim_blk_seq)
353 			break;
354 		if ((error = parse_blk_func(zilog, &blk, arg, txg)) != 0)
355 			break;
356 		ASSERT3U(max_blk_seq, <, blk_seq);
357 		max_blk_seq = blk_seq;
358 		blk_count++;
359 
360 		if (max_lr_seq == claim_lr_seq && max_blk_seq == claim_blk_seq)
361 			break;
362 
363 		error = zil_read_log_block(zilog, &blk, &next_blk, lrbuf, &end);
364 		if (error != 0)
365 			break;
366 
367 		for (lrp = lrbuf; lrp < end; lrp += reclen) {
368 			lr_t *lr = (lr_t *)lrp;
369 			reclen = lr->lrc_reclen;
370 			ASSERT3U(reclen, >=, sizeof (lr_t));
371 			if (lr->lrc_seq > claim_lr_seq)
372 				goto done;
373 			if ((error = parse_lr_func(zilog, lr, arg, txg)) != 0)
374 				goto done;
375 			ASSERT3U(max_lr_seq, <, lr->lrc_seq);
376 			max_lr_seq = lr->lrc_seq;
377 			lr_count++;
378 		}
379 	}
380 done:
381 	zilog->zl_parse_error = error;
382 	zilog->zl_parse_blk_seq = max_blk_seq;
383 	zilog->zl_parse_lr_seq = max_lr_seq;
384 	zilog->zl_parse_blk_count = blk_count;
385 	zilog->zl_parse_lr_count = lr_count;
386 
387 	ASSERT(!claimed || !(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID) ||
388 	    (max_blk_seq == claim_blk_seq && max_lr_seq == claim_lr_seq));
389 
390 	zil_bp_tree_fini(zilog);
391 	zio_buf_free(lrbuf, SPA_OLD_MAXBLOCKSIZE);
392 
393 	return (error);
394 }
395 
396 static int
397 zil_claim_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t first_txg)
398 {
399 	/*
400 	 * Claim log block if not already committed and not already claimed.
401 	 * If tx == NULL, just verify that the block is claimable.
402 	 */
403 	if (BP_IS_HOLE(bp) || bp->blk_birth < first_txg ||
404 	    zil_bp_tree_add(zilog, bp) != 0)
405 		return (0);
406 
407 	return (zio_wait(zio_claim(NULL, zilog->zl_spa,
408 	    tx == NULL ? 0 : first_txg, bp, spa_claim_notify, NULL,
409 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB)));
410 }
411 
412 static int
413 zil_claim_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg)
414 {
415 	lr_write_t *lr = (lr_write_t *)lrc;
416 	int error;
417 
418 	if (lrc->lrc_txtype != TX_WRITE)
419 		return (0);
420 
421 	/*
422 	 * If the block is not readable, don't claim it.  This can happen
423 	 * in normal operation when a log block is written to disk before
424 	 * some of the dmu_sync() blocks it points to.  In this case, the
425 	 * transaction cannot have been committed to anyone (we would have
426 	 * waited for all writes to be stable first), so it is semantically
427 	 * correct to declare this the end of the log.
428 	 */
429 	if (lr->lr_blkptr.blk_birth >= first_txg &&
430 	    (error = zil_read_log_data(zilog, lr, NULL)) != 0)
431 		return (error);
432 	return (zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg));
433 }
434 
435 /* ARGSUSED */
436 static int
437 zil_free_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t claim_txg)
438 {
439 	zio_free_zil(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
440 
441 	return (0);
442 }
443 
444 static int
445 zil_free_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t claim_txg)
446 {
447 	lr_write_t *lr = (lr_write_t *)lrc;
448 	blkptr_t *bp = &lr->lr_blkptr;
449 
450 	/*
451 	 * If we previously claimed it, we need to free it.
452 	 */
453 	if (claim_txg != 0 && lrc->lrc_txtype == TX_WRITE &&
454 	    bp->blk_birth >= claim_txg && zil_bp_tree_add(zilog, bp) == 0 &&
455 	    !BP_IS_HOLE(bp))
456 		zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
457 
458 	return (0);
459 }
460 
461 static int
462 zil_lwb_vdev_compare(const void *x1, const void *x2)
463 {
464 	const uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
465 	const uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
466 
467 	if (v1 < v2)
468 		return (-1);
469 	if (v1 > v2)
470 		return (1);
471 
472 	return (0);
473 }
474 
475 static lwb_t *
476 zil_alloc_lwb(zilog_t *zilog, blkptr_t *bp, boolean_t slog, uint64_t txg)
477 {
478 	lwb_t *lwb;
479 
480 	lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
481 	lwb->lwb_zilog = zilog;
482 	lwb->lwb_blk = *bp;
483 	lwb->lwb_slog = slog;
484 	lwb->lwb_state = LWB_STATE_CLOSED;
485 	lwb->lwb_buf = zio_buf_alloc(BP_GET_LSIZE(bp));
486 	lwb->lwb_max_txg = txg;
487 	lwb->lwb_write_zio = NULL;
488 	lwb->lwb_root_zio = NULL;
489 	lwb->lwb_tx = NULL;
490 	lwb->lwb_issued_timestamp = 0;
491 	if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) {
492 		lwb->lwb_nused = sizeof (zil_chain_t);
493 		lwb->lwb_sz = BP_GET_LSIZE(bp);
494 	} else {
495 		lwb->lwb_nused = 0;
496 		lwb->lwb_sz = BP_GET_LSIZE(bp) - sizeof (zil_chain_t);
497 	}
498 
499 	mutex_enter(&zilog->zl_lock);
500 	list_insert_tail(&zilog->zl_lwb_list, lwb);
501 	mutex_exit(&zilog->zl_lock);
502 
503 	ASSERT(!MUTEX_HELD(&lwb->lwb_vdev_lock));
504 	ASSERT(avl_is_empty(&lwb->lwb_vdev_tree));
505 	VERIFY(list_is_empty(&lwb->lwb_waiters));
506 
507 	return (lwb);
508 }
509 
510 static void
511 zil_free_lwb(zilog_t *zilog, lwb_t *lwb)
512 {
513 	ASSERT(MUTEX_HELD(&zilog->zl_lock));
514 	ASSERT(!MUTEX_HELD(&lwb->lwb_vdev_lock));
515 	VERIFY(list_is_empty(&lwb->lwb_waiters));
516 	ASSERT(avl_is_empty(&lwb->lwb_vdev_tree));
517 	ASSERT3P(lwb->lwb_write_zio, ==, NULL);
518 	ASSERT3P(lwb->lwb_root_zio, ==, NULL);
519 	ASSERT3U(lwb->lwb_max_txg, <=, spa_syncing_txg(zilog->zl_spa));
520 	ASSERT(lwb->lwb_state == LWB_STATE_CLOSED ||
521 	    lwb->lwb_state == LWB_STATE_DONE);
522 
523 	/*
524 	 * Clear the zilog's field to indicate this lwb is no longer
525 	 * valid, and prevent use-after-free errors.
526 	 */
527 	if (zilog->zl_last_lwb_opened == lwb)
528 		zilog->zl_last_lwb_opened = NULL;
529 
530 	kmem_cache_free(zil_lwb_cache, lwb);
531 }
532 
533 /*
534  * Called when we create in-memory log transactions so that we know
535  * to cleanup the itxs at the end of spa_sync().
536  */
537 void
538 zilog_dirty(zilog_t *zilog, uint64_t txg)
539 {
540 	dsl_pool_t *dp = zilog->zl_dmu_pool;
541 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
542 
543 	ASSERT(spa_writeable(zilog->zl_spa));
544 
545 	if (ds->ds_is_snapshot)
546 		panic("dirtying snapshot!");
547 
548 	if (txg_list_add(&dp->dp_dirty_zilogs, zilog, txg)) {
549 		/* up the hold count until we can be written out */
550 		dmu_buf_add_ref(ds->ds_dbuf, zilog);
551 
552 		zilog->zl_dirty_max_txg = MAX(txg, zilog->zl_dirty_max_txg);
553 	}
554 }
555 
556 /*
557  * Determine if the zil is dirty in the specified txg. Callers wanting to
558  * ensure that the dirty state does not change must hold the itxg_lock for
559  * the specified txg. Holding the lock will ensure that the zil cannot be
560  * dirtied (zil_itx_assign) or cleaned (zil_clean) while we check its current
561  * state.
562  */
563 boolean_t
564 zilog_is_dirty_in_txg(zilog_t *zilog, uint64_t txg)
565 {
566 	dsl_pool_t *dp = zilog->zl_dmu_pool;
567 
568 	if (txg_list_member(&dp->dp_dirty_zilogs, zilog, txg & TXG_MASK))
569 		return (B_TRUE);
570 	return (B_FALSE);
571 }
572 
573 /*
574  * Determine if the zil is dirty. The zil is considered dirty if it has
575  * any pending itx records that have not been cleaned by zil_clean().
576  */
577 boolean_t
578 zilog_is_dirty(zilog_t *zilog)
579 {
580 	dsl_pool_t *dp = zilog->zl_dmu_pool;
581 
582 	for (int t = 0; t < TXG_SIZE; t++) {
583 		if (txg_list_member(&dp->dp_dirty_zilogs, zilog, t))
584 			return (B_TRUE);
585 	}
586 	return (B_FALSE);
587 }
588 
589 /*
590  * Create an on-disk intent log.
591  */
592 static lwb_t *
593 zil_create(zilog_t *zilog)
594 {
595 	const zil_header_t *zh = zilog->zl_header;
596 	lwb_t *lwb = NULL;
597 	uint64_t txg = 0;
598 	dmu_tx_t *tx = NULL;
599 	blkptr_t blk;
600 	int error = 0;
601 	boolean_t slog = FALSE;
602 
603 	/*
604 	 * Wait for any previous destroy to complete.
605 	 */
606 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
607 
608 	ASSERT(zh->zh_claim_txg == 0);
609 	ASSERT(zh->zh_replay_seq == 0);
610 
611 	blk = zh->zh_log;
612 
613 	/*
614 	 * Allocate an initial log block if:
615 	 *    - there isn't one already
616 	 *    - the existing block is the wrong endianess
617 	 */
618 	if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) {
619 		tx = dmu_tx_create(zilog->zl_os);
620 		VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
621 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
622 		txg = dmu_tx_get_txg(tx);
623 
624 		if (!BP_IS_HOLE(&blk)) {
625 			zio_free_zil(zilog->zl_spa, txg, &blk);
626 			BP_ZERO(&blk);
627 		}
628 
629 		error = zio_alloc_zil(zilog->zl_spa, txg, &blk, NULL,
630 		    ZIL_MIN_BLKSZ, &slog);
631 
632 		if (error == 0)
633 			zil_init_log_chain(zilog, &blk);
634 	}
635 
636 	/*
637 	 * Allocate a log write block (lwb) for the first log block.
638 	 */
639 	if (error == 0)
640 		lwb = zil_alloc_lwb(zilog, &blk, slog, txg);
641 
642 	/*
643 	 * If we just allocated the first log block, commit our transaction
644 	 * and wait for zil_sync() to stuff the block poiner into zh_log.
645 	 * (zh is part of the MOS, so we cannot modify it in open context.)
646 	 */
647 	if (tx != NULL) {
648 		dmu_tx_commit(tx);
649 		txg_wait_synced(zilog->zl_dmu_pool, txg);
650 	}
651 
652 	ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
653 
654 	return (lwb);
655 }
656 
657 /*
658  * In one tx, free all log blocks and clear the log header. If keep_first
659  * is set, then we're replaying a log with no content. We want to keep the
660  * first block, however, so that the first synchronous transaction doesn't
661  * require a txg_wait_synced() in zil_create(). We don't need to
662  * txg_wait_synced() here either when keep_first is set, because both
663  * zil_create() and zil_destroy() will wait for any in-progress destroys
664  * to complete.
665  */
666 void
667 zil_destroy(zilog_t *zilog, boolean_t keep_first)
668 {
669 	const zil_header_t *zh = zilog->zl_header;
670 	lwb_t *lwb;
671 	dmu_tx_t *tx;
672 	uint64_t txg;
673 
674 	/*
675 	 * Wait for any previous destroy to complete.
676 	 */
677 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
678 
679 	zilog->zl_old_header = *zh;		/* debugging aid */
680 
681 	if (BP_IS_HOLE(&zh->zh_log))
682 		return;
683 
684 	tx = dmu_tx_create(zilog->zl_os);
685 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
686 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
687 	txg = dmu_tx_get_txg(tx);
688 
689 	mutex_enter(&zilog->zl_lock);
690 
691 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
692 	zilog->zl_destroy_txg = txg;
693 	zilog->zl_keep_first = keep_first;
694 
695 	if (!list_is_empty(&zilog->zl_lwb_list)) {
696 		ASSERT(zh->zh_claim_txg == 0);
697 		VERIFY(!keep_first);
698 		while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
699 			list_remove(&zilog->zl_lwb_list, lwb);
700 			if (lwb->lwb_buf != NULL)
701 				zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
702 			zio_free(zilog->zl_spa, txg, &lwb->lwb_blk);
703 			zil_free_lwb(zilog, lwb);
704 		}
705 	} else if (!keep_first) {
706 		zil_destroy_sync(zilog, tx);
707 	}
708 	mutex_exit(&zilog->zl_lock);
709 
710 	dmu_tx_commit(tx);
711 }
712 
713 void
714 zil_destroy_sync(zilog_t *zilog, dmu_tx_t *tx)
715 {
716 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
717 	(void) zil_parse(zilog, zil_free_log_block,
718 	    zil_free_log_record, tx, zilog->zl_header->zh_claim_txg);
719 }
720 
721 int
722 zil_claim(dsl_pool_t *dp, dsl_dataset_t *ds, void *txarg)
723 {
724 	dmu_tx_t *tx = txarg;
725 	uint64_t first_txg = dmu_tx_get_txg(tx);
726 	zilog_t *zilog;
727 	zil_header_t *zh;
728 	objset_t *os;
729 	int error;
730 
731 	error = dmu_objset_own_obj(dp, ds->ds_object,
732 	    DMU_OST_ANY, B_FALSE, FTAG, &os);
733 	if (error != 0) {
734 		/*
735 		 * EBUSY indicates that the objset is inconsistent, in which
736 		 * case it can not have a ZIL.
737 		 */
738 		if (error != EBUSY) {
739 			cmn_err(CE_WARN, "can't open objset for %llu, error %u",
740 			    (unsigned long long)ds->ds_object, error);
741 		}
742 		return (0);
743 	}
744 
745 	zilog = dmu_objset_zil(os);
746 	zh = zil_header_in_syncing_context(zilog);
747 
748 	if (spa_get_log_state(zilog->zl_spa) == SPA_LOG_CLEAR) {
749 		if (!BP_IS_HOLE(&zh->zh_log))
750 			zio_free_zil(zilog->zl_spa, first_txg, &zh->zh_log);
751 		BP_ZERO(&zh->zh_log);
752 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
753 		dmu_objset_disown(os, FTAG);
754 		return (0);
755 	}
756 
757 	/*
758 	 * Claim all log blocks if we haven't already done so, and remember
759 	 * the highest claimed sequence number.  This ensures that if we can
760 	 * read only part of the log now (e.g. due to a missing device),
761 	 * but we can read the entire log later, we will not try to replay
762 	 * or destroy beyond the last block we successfully claimed.
763 	 */
764 	ASSERT3U(zh->zh_claim_txg, <=, first_txg);
765 	if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
766 		(void) zil_parse(zilog, zil_claim_log_block,
767 		    zil_claim_log_record, tx, first_txg);
768 		zh->zh_claim_txg = first_txg;
769 		zh->zh_claim_blk_seq = zilog->zl_parse_blk_seq;
770 		zh->zh_claim_lr_seq = zilog->zl_parse_lr_seq;
771 		if (zilog->zl_parse_lr_count || zilog->zl_parse_blk_count > 1)
772 			zh->zh_flags |= ZIL_REPLAY_NEEDED;
773 		zh->zh_flags |= ZIL_CLAIM_LR_SEQ_VALID;
774 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
775 	}
776 
777 	ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
778 	dmu_objset_disown(os, FTAG);
779 	return (0);
780 }
781 
782 /*
783  * Check the log by walking the log chain.
784  * Checksum errors are ok as they indicate the end of the chain.
785  * Any other error (no device or read failure) returns an error.
786  */
787 /* ARGSUSED */
788 int
789 zil_check_log_chain(dsl_pool_t *dp, dsl_dataset_t *ds, void *tx)
790 {
791 	zilog_t *zilog;
792 	objset_t *os;
793 	blkptr_t *bp;
794 	int error;
795 
796 	ASSERT(tx == NULL);
797 
798 	error = dmu_objset_from_ds(ds, &os);
799 	if (error != 0) {
800 		cmn_err(CE_WARN, "can't open objset %llu, error %d",
801 		    (unsigned long long)ds->ds_object, error);
802 		return (0);
803 	}
804 
805 	zilog = dmu_objset_zil(os);
806 	bp = (blkptr_t *)&zilog->zl_header->zh_log;
807 
808 	/*
809 	 * Check the first block and determine if it's on a log device
810 	 * which may have been removed or faulted prior to loading this
811 	 * pool.  If so, there's no point in checking the rest of the log
812 	 * as its content should have already been synced to the pool.
813 	 */
814 	if (!BP_IS_HOLE(bp)) {
815 		vdev_t *vd;
816 		boolean_t valid = B_TRUE;
817 
818 		spa_config_enter(os->os_spa, SCL_STATE, FTAG, RW_READER);
819 		vd = vdev_lookup_top(os->os_spa, DVA_GET_VDEV(&bp->blk_dva[0]));
820 		if (vd->vdev_islog && vdev_is_dead(vd))
821 			valid = vdev_log_state_valid(vd);
822 		spa_config_exit(os->os_spa, SCL_STATE, FTAG);
823 
824 		if (!valid)
825 			return (0);
826 	}
827 
828 	/*
829 	 * Because tx == NULL, zil_claim_log_block() will not actually claim
830 	 * any blocks, but just determine whether it is possible to do so.
831 	 * In addition to checking the log chain, zil_claim_log_block()
832 	 * will invoke zio_claim() with a done func of spa_claim_notify(),
833 	 * which will update spa_max_claim_txg.  See spa_load() for details.
834 	 */
835 	error = zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx,
836 	    zilog->zl_header->zh_claim_txg ? -1ULL : spa_first_txg(os->os_spa));
837 
838 	return ((error == ECKSUM || error == ENOENT) ? 0 : error);
839 }
840 
841 /*
842  * When an itx is "skipped", this function is used to properly mark the
843  * waiter as "done, and signal any thread(s) waiting on it. An itx can
844  * be skipped (and not committed to an lwb) for a variety of reasons,
845  * one of them being that the itx was committed via spa_sync(), prior to
846  * it being committed to an lwb; this can happen if a thread calling
847  * zil_commit() is racing with spa_sync().
848  */
849 static void
850 zil_commit_waiter_skip(zil_commit_waiter_t *zcw)
851 {
852 	mutex_enter(&zcw->zcw_lock);
853 	ASSERT3B(zcw->zcw_done, ==, B_FALSE);
854 	zcw->zcw_done = B_TRUE;
855 	cv_broadcast(&zcw->zcw_cv);
856 	mutex_exit(&zcw->zcw_lock);
857 }
858 
859 /*
860  * This function is used when the given waiter is to be linked into an
861  * lwb's "lwb_waiter" list; i.e. when the itx is committed to the lwb.
862  * At this point, the waiter will no longer be referenced by the itx,
863  * and instead, will be referenced by the lwb.
864  */
865 static void
866 zil_commit_waiter_link_lwb(zil_commit_waiter_t *zcw, lwb_t *lwb)
867 {
868 	/*
869 	 * The lwb_waiters field of the lwb is protected by the zilog's
870 	 * zl_lock, thus it must be held when calling this function.
871 	 */
872 	ASSERT(MUTEX_HELD(&lwb->lwb_zilog->zl_lock));
873 
874 	mutex_enter(&zcw->zcw_lock);
875 	ASSERT(!list_link_active(&zcw->zcw_node));
876 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
877 	ASSERT3P(lwb, !=, NULL);
878 	ASSERT(lwb->lwb_state == LWB_STATE_OPENED ||
879 	    lwb->lwb_state == LWB_STATE_ISSUED);
880 
881 	list_insert_tail(&lwb->lwb_waiters, zcw);
882 	zcw->zcw_lwb = lwb;
883 	mutex_exit(&zcw->zcw_lock);
884 }
885 
886 /*
887  * This function is used when zio_alloc_zil() fails to allocate a ZIL
888  * block, and the given waiter must be linked to the "nolwb waiters"
889  * list inside of zil_process_commit_list().
890  */
891 static void
892 zil_commit_waiter_link_nolwb(zil_commit_waiter_t *zcw, list_t *nolwb)
893 {
894 	mutex_enter(&zcw->zcw_lock);
895 	ASSERT(!list_link_active(&zcw->zcw_node));
896 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
897 	list_insert_tail(nolwb, zcw);
898 	mutex_exit(&zcw->zcw_lock);
899 }
900 
901 void
902 zil_lwb_add_block(lwb_t *lwb, const blkptr_t *bp)
903 {
904 	avl_tree_t *t = &lwb->lwb_vdev_tree;
905 	avl_index_t where;
906 	zil_vdev_node_t *zv, zvsearch;
907 	int ndvas = BP_GET_NDVAS(bp);
908 	int i;
909 
910 	if (zfs_nocacheflush)
911 		return;
912 
913 	mutex_enter(&lwb->lwb_vdev_lock);
914 	for (i = 0; i < ndvas; i++) {
915 		zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
916 		if (avl_find(t, &zvsearch, &where) == NULL) {
917 			zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
918 			zv->zv_vdev = zvsearch.zv_vdev;
919 			avl_insert(t, zv, where);
920 		}
921 	}
922 	mutex_exit(&lwb->lwb_vdev_lock);
923 }
924 
925 void
926 zil_lwb_add_txg(lwb_t *lwb, uint64_t txg)
927 {
928 	lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
929 }
930 
931 /*
932  * This function is a called after all VDEVs associated with a given lwb
933  * write have completed their DKIOCFLUSHWRITECACHE command; or as soon
934  * as the lwb write completes, if "zfs_nocacheflush" is set.
935  *
936  * The intention is for this function to be called as soon as the
937  * contents of an lwb are considered "stable" on disk, and will survive
938  * any sudden loss of power. At this point, any threads waiting for the
939  * lwb to reach this state are signalled, and the "waiter" structures
940  * are marked "done".
941  */
942 static void
943 zil_lwb_flush_vdevs_done(zio_t *zio)
944 {
945 	lwb_t *lwb = zio->io_private;
946 	zilog_t *zilog = lwb->lwb_zilog;
947 	dmu_tx_t *tx = lwb->lwb_tx;
948 	zil_commit_waiter_t *zcw;
949 
950 	spa_config_exit(zilog->zl_spa, SCL_STATE, lwb);
951 
952 	zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
953 
954 	mutex_enter(&zilog->zl_lock);
955 
956 	/*
957 	 * Ensure the lwb buffer pointer is cleared before releasing the
958 	 * txg. If we have had an allocation failure and the txg is
959 	 * waiting to sync then we want zil_sync() to remove the lwb so
960 	 * that it's not picked up as the next new one in
961 	 * zil_process_commit_list(). zil_sync() will only remove the
962 	 * lwb if lwb_buf is null.
963 	 */
964 	lwb->lwb_buf = NULL;
965 	lwb->lwb_tx = NULL;
966 
967 	ASSERT3U(lwb->lwb_issued_timestamp, >, 0);
968 	zilog->zl_last_lwb_latency = gethrtime() - lwb->lwb_issued_timestamp;
969 
970 	lwb->lwb_root_zio = NULL;
971 	lwb->lwb_state = LWB_STATE_DONE;
972 
973 	if (zilog->zl_last_lwb_opened == lwb) {
974 		/*
975 		 * Remember the highest committed log sequence number
976 		 * for ztest. We only update this value when all the log
977 		 * writes succeeded, because ztest wants to ASSERT that
978 		 * it got the whole log chain.
979 		 */
980 		zilog->zl_commit_lr_seq = zilog->zl_lr_seq;
981 	}
982 
983 	while ((zcw = list_head(&lwb->lwb_waiters)) != NULL) {
984 		mutex_enter(&zcw->zcw_lock);
985 
986 		ASSERT(list_link_active(&zcw->zcw_node));
987 		list_remove(&lwb->lwb_waiters, zcw);
988 
989 		ASSERT3P(zcw->zcw_lwb, ==, lwb);
990 		zcw->zcw_lwb = NULL;
991 
992 		zcw->zcw_zio_error = zio->io_error;
993 
994 		ASSERT3B(zcw->zcw_done, ==, B_FALSE);
995 		zcw->zcw_done = B_TRUE;
996 		cv_broadcast(&zcw->zcw_cv);
997 
998 		mutex_exit(&zcw->zcw_lock);
999 	}
1000 
1001 	mutex_exit(&zilog->zl_lock);
1002 
1003 	/*
1004 	 * Now that we've written this log block, we have a stable pointer
1005 	 * to the next block in the chain, so it's OK to let the txg in
1006 	 * which we allocated the next block sync.
1007 	 */
1008 	dmu_tx_commit(tx);
1009 }
1010 
1011 /*
1012  * This is called when an lwb write completes. This means, this specific
1013  * lwb was written to disk, and all dependent lwb have also been
1014  * written to disk.
1015  *
1016  * At this point, a DKIOCFLUSHWRITECACHE command hasn't been issued to
1017  * the VDEVs involved in writing out this specific lwb. The lwb will be
1018  * "done" once zil_lwb_flush_vdevs_done() is called, which occurs in the
1019  * zio completion callback for the lwb's root zio.
1020  */
1021 static void
1022 zil_lwb_write_done(zio_t *zio)
1023 {
1024 	lwb_t *lwb = zio->io_private;
1025 	spa_t *spa = zio->io_spa;
1026 	zilog_t *zilog = lwb->lwb_zilog;
1027 	avl_tree_t *t = &lwb->lwb_vdev_tree;
1028 	void *cookie = NULL;
1029 	zil_vdev_node_t *zv;
1030 
1031 	ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), !=, 0);
1032 
1033 	ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
1034 	ASSERT(BP_GET_TYPE(zio->io_bp) == DMU_OT_INTENT_LOG);
1035 	ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
1036 	ASSERT(BP_GET_BYTEORDER(zio->io_bp) == ZFS_HOST_BYTEORDER);
1037 	ASSERT(!BP_IS_GANG(zio->io_bp));
1038 	ASSERT(!BP_IS_HOLE(zio->io_bp));
1039 	ASSERT(BP_GET_FILL(zio->io_bp) == 0);
1040 
1041 	abd_put(zio->io_abd);
1042 
1043 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_ISSUED);
1044 
1045 	mutex_enter(&zilog->zl_lock);
1046 	lwb->lwb_write_zio = NULL;
1047 	mutex_exit(&zilog->zl_lock);
1048 
1049 	if (avl_numnodes(t) == 0)
1050 		return;
1051 
1052 	/*
1053 	 * If there was an IO error, we're not going to call zio_flush()
1054 	 * on these vdevs, so we simply empty the tree and free the
1055 	 * nodes. We avoid calling zio_flush() since there isn't any
1056 	 * good reason for doing so, after the lwb block failed to be
1057 	 * written out.
1058 	 */
1059 	if (zio->io_error != 0) {
1060 		while ((zv = avl_destroy_nodes(t, &cookie)) != NULL)
1061 			kmem_free(zv, sizeof (*zv));
1062 		return;
1063 	}
1064 
1065 	while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
1066 		vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
1067 		if (vd != NULL)
1068 			zio_flush(lwb->lwb_root_zio, vd);
1069 		kmem_free(zv, sizeof (*zv));
1070 	}
1071 }
1072 
1073 /*
1074  * This function's purpose is to "open" an lwb such that it is ready to
1075  * accept new itxs being committed to it. To do this, the lwb's zio
1076  * structures are created, and linked to the lwb. This function is
1077  * idempotent; if the passed in lwb has already been opened, this
1078  * function is essentially a no-op.
1079  */
1080 static void
1081 zil_lwb_write_open(zilog_t *zilog, lwb_t *lwb)
1082 {
1083 	zbookmark_phys_t zb;
1084 	zio_priority_t prio;
1085 
1086 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1087 	ASSERT3P(lwb, !=, NULL);
1088 	EQUIV(lwb->lwb_root_zio == NULL, lwb->lwb_state == LWB_STATE_CLOSED);
1089 	EQUIV(lwb->lwb_root_zio != NULL, lwb->lwb_state == LWB_STATE_OPENED);
1090 
1091 	SET_BOOKMARK(&zb, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1092 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL,
1093 	    lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ]);
1094 
1095 	if (lwb->lwb_root_zio == NULL) {
1096 		abd_t *lwb_abd = abd_get_from_buf(lwb->lwb_buf,
1097 		    BP_GET_LSIZE(&lwb->lwb_blk));
1098 
1099 		if (!lwb->lwb_slog || zilog->zl_cur_used <= zil_slog_bulk)
1100 			prio = ZIO_PRIORITY_SYNC_WRITE;
1101 		else
1102 			prio = ZIO_PRIORITY_ASYNC_WRITE;
1103 
1104 		lwb->lwb_root_zio = zio_root(zilog->zl_spa,
1105 		    zil_lwb_flush_vdevs_done, lwb, ZIO_FLAG_CANFAIL);
1106 		ASSERT3P(lwb->lwb_root_zio, !=, NULL);
1107 
1108 		lwb->lwb_write_zio = zio_rewrite(lwb->lwb_root_zio,
1109 		    zilog->zl_spa, 0, &lwb->lwb_blk, lwb_abd,
1110 		    BP_GET_LSIZE(&lwb->lwb_blk), zil_lwb_write_done, lwb,
1111 		    prio, ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE, &zb);
1112 		ASSERT3P(lwb->lwb_write_zio, !=, NULL);
1113 
1114 		lwb->lwb_state = LWB_STATE_OPENED;
1115 
1116 		mutex_enter(&zilog->zl_lock);
1117 
1118 		/*
1119 		 * The zilog's "zl_last_lwb_opened" field is used to
1120 		 * build the lwb/zio dependency chain, which is used to
1121 		 * preserve the ordering of lwb completions that is
1122 		 * required by the semantics of the ZIL. Each new lwb
1123 		 * zio becomes a parent of the "previous" lwb zio, such
1124 		 * that the new lwb's zio cannot complete until the
1125 		 * "previous" lwb's zio completes.
1126 		 *
1127 		 * This is required by the semantics of zil_commit();
1128 		 * the commit waiters attached to the lwbs will be woken
1129 		 * in the lwb zio's completion callback, so this zio
1130 		 * dependency graph ensures the waiters are woken in the
1131 		 * correct order (the same order the lwbs were created).
1132 		 */
1133 		lwb_t *last_lwb_opened = zilog->zl_last_lwb_opened;
1134 		if (last_lwb_opened != NULL &&
1135 		    last_lwb_opened->lwb_state != LWB_STATE_DONE) {
1136 			ASSERT(last_lwb_opened->lwb_state == LWB_STATE_OPENED ||
1137 			    last_lwb_opened->lwb_state == LWB_STATE_ISSUED);
1138 			ASSERT3P(last_lwb_opened->lwb_root_zio, !=, NULL);
1139 			zio_add_child(lwb->lwb_root_zio,
1140 			    last_lwb_opened->lwb_root_zio);
1141 		}
1142 		zilog->zl_last_lwb_opened = lwb;
1143 
1144 		mutex_exit(&zilog->zl_lock);
1145 	}
1146 
1147 	ASSERT3P(lwb->lwb_root_zio, !=, NULL);
1148 	ASSERT3P(lwb->lwb_write_zio, !=, NULL);
1149 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
1150 }
1151 
1152 /*
1153  * Define a limited set of intent log block sizes.
1154  *
1155  * These must be a multiple of 4KB. Note only the amount used (again
1156  * aligned to 4KB) actually gets written. However, we can't always just
1157  * allocate SPA_OLD_MAXBLOCKSIZE as the slog space could be exhausted.
1158  */
1159 uint64_t zil_block_buckets[] = {
1160     4096,		/* non TX_WRITE */
1161     8192+4096,		/* data base */
1162     32*1024 + 4096, 	/* NFS writes */
1163     UINT64_MAX
1164 };
1165 
1166 /*
1167  * Start a log block write and advance to the next log block.
1168  * Calls are serialized.
1169  */
1170 static lwb_t *
1171 zil_lwb_write_issue(zilog_t *zilog, lwb_t *lwb)
1172 {
1173 	lwb_t *nlwb = NULL;
1174 	zil_chain_t *zilc;
1175 	spa_t *spa = zilog->zl_spa;
1176 	blkptr_t *bp;
1177 	dmu_tx_t *tx;
1178 	uint64_t txg;
1179 	uint64_t zil_blksz, wsz;
1180 	int i, error;
1181 	boolean_t slog;
1182 
1183 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1184 	ASSERT3P(lwb->lwb_root_zio, !=, NULL);
1185 	ASSERT3P(lwb->lwb_write_zio, !=, NULL);
1186 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
1187 
1188 	if (BP_GET_CHECKSUM(&lwb->lwb_blk) == ZIO_CHECKSUM_ZILOG2) {
1189 		zilc = (zil_chain_t *)lwb->lwb_buf;
1190 		bp = &zilc->zc_next_blk;
1191 	} else {
1192 		zilc = (zil_chain_t *)(lwb->lwb_buf + lwb->lwb_sz);
1193 		bp = &zilc->zc_next_blk;
1194 	}
1195 
1196 	ASSERT(lwb->lwb_nused <= lwb->lwb_sz);
1197 
1198 	/*
1199 	 * Allocate the next block and save its address in this block
1200 	 * before writing it in order to establish the log chain.
1201 	 * Note that if the allocation of nlwb synced before we wrote
1202 	 * the block that points at it (lwb), we'd leak it if we crashed.
1203 	 * Therefore, we don't do dmu_tx_commit() until zil_lwb_write_done().
1204 	 * We dirty the dataset to ensure that zil_sync() will be called
1205 	 * to clean up in the event of allocation failure or I/O failure.
1206 	 */
1207 
1208 	tx = dmu_tx_create(zilog->zl_os);
1209 
1210 	/*
1211 	 * Since we are not going to create any new dirty data and we can even
1212 	 * help with clearing the existing dirty data, we should not be subject
1213 	 * to the dirty data based delays.
1214 	 * We (ab)use TXG_WAITED to bypass the delay mechanism.
1215 	 * One side effect from using TXG_WAITED is that dmu_tx_assign() can
1216 	 * fail if the pool is suspended.  Those are dramatic circumstances,
1217 	 * so we return NULL to signal that the normal ZIL processing is not
1218 	 * possible and txg_wait_synced() should be used to ensure that the data
1219 	 * is on disk.
1220 	 */
1221 	error = dmu_tx_assign(tx, TXG_WAITED);
1222 	if (error != 0) {
1223 		ASSERT3S(error, ==, EIO);
1224 		dmu_tx_abort(tx);
1225 		return (NULL);
1226 	}
1227 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1228 	txg = dmu_tx_get_txg(tx);
1229 
1230 	lwb->lwb_tx = tx;
1231 
1232 	/*
1233 	 * Log blocks are pre-allocated. Here we select the size of the next
1234 	 * block, based on size used in the last block.
1235 	 * - first find the smallest bucket that will fit the block from a
1236 	 *   limited set of block sizes. This is because it's faster to write
1237 	 *   blocks allocated from the same metaslab as they are adjacent or
1238 	 *   close.
1239 	 * - next find the maximum from the new suggested size and an array of
1240 	 *   previous sizes. This lessens a picket fence effect of wrongly
1241 	 *   guesssing the size if we have a stream of say 2k, 64k, 2k, 64k
1242 	 *   requests.
1243 	 *
1244 	 * Note we only write what is used, but we can't just allocate
1245 	 * the maximum block size because we can exhaust the available
1246 	 * pool log space.
1247 	 */
1248 	zil_blksz = zilog->zl_cur_used + sizeof (zil_chain_t);
1249 	for (i = 0; zil_blksz > zil_block_buckets[i]; i++)
1250 		continue;
1251 	zil_blksz = zil_block_buckets[i];
1252 	if (zil_blksz == UINT64_MAX)
1253 		zil_blksz = SPA_OLD_MAXBLOCKSIZE;
1254 	zilog->zl_prev_blks[zilog->zl_prev_rotor] = zil_blksz;
1255 	for (i = 0; i < ZIL_PREV_BLKS; i++)
1256 		zil_blksz = MAX(zil_blksz, zilog->zl_prev_blks[i]);
1257 	zilog->zl_prev_rotor = (zilog->zl_prev_rotor + 1) & (ZIL_PREV_BLKS - 1);
1258 
1259 	BP_ZERO(bp);
1260 
1261 	/* pass the old blkptr in order to spread log blocks across devs */
1262 	error = zio_alloc_zil(spa, txg, bp, &lwb->lwb_blk, zil_blksz, &slog);
1263 	if (error == 0) {
1264 		ASSERT3U(bp->blk_birth, ==, txg);
1265 		bp->blk_cksum = lwb->lwb_blk.blk_cksum;
1266 		bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
1267 
1268 		/*
1269 		 * Allocate a new log write block (lwb).
1270 		 */
1271 		nlwb = zil_alloc_lwb(zilog, bp, slog, txg);
1272 	}
1273 
1274 	if (BP_GET_CHECKSUM(&lwb->lwb_blk) == ZIO_CHECKSUM_ZILOG2) {
1275 		/* For Slim ZIL only write what is used. */
1276 		wsz = P2ROUNDUP_TYPED(lwb->lwb_nused, ZIL_MIN_BLKSZ, uint64_t);
1277 		ASSERT3U(wsz, <=, lwb->lwb_sz);
1278 		zio_shrink(lwb->lwb_write_zio, wsz);
1279 
1280 	} else {
1281 		wsz = lwb->lwb_sz;
1282 	}
1283 
1284 	zilc->zc_pad = 0;
1285 	zilc->zc_nused = lwb->lwb_nused;
1286 	zilc->zc_eck.zec_cksum = lwb->lwb_blk.blk_cksum;
1287 
1288 	/*
1289 	 * clear unused data for security
1290 	 */
1291 	bzero(lwb->lwb_buf + lwb->lwb_nused, wsz - lwb->lwb_nused);
1292 
1293 	spa_config_enter(zilog->zl_spa, SCL_STATE, lwb, RW_READER);
1294 
1295 	zil_lwb_add_block(lwb, &lwb->lwb_blk);
1296 	lwb->lwb_issued_timestamp = gethrtime();
1297 	lwb->lwb_state = LWB_STATE_ISSUED;
1298 
1299 	zio_nowait(lwb->lwb_root_zio);
1300 	zio_nowait(lwb->lwb_write_zio);
1301 
1302 	/*
1303 	 * If there was an allocation failure then nlwb will be null which
1304 	 * forces a txg_wait_synced().
1305 	 */
1306 	return (nlwb);
1307 }
1308 
1309 static lwb_t *
1310 zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb)
1311 {
1312 	lr_t *lrcb, *lrc;
1313 	lr_write_t *lrwb, *lrw;
1314 	char *lr_buf;
1315 	uint64_t dlen, dnow, lwb_sp, reclen, txg;
1316 
1317 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1318 	ASSERT3P(lwb, !=, NULL);
1319 	ASSERT3P(lwb->lwb_buf, !=, NULL);
1320 
1321 	zil_lwb_write_open(zilog, lwb);
1322 
1323 	lrc = &itx->itx_lr;
1324 	lrw = (lr_write_t *)lrc;
1325 
1326 	/*
1327 	 * A commit itx doesn't represent any on-disk state; instead
1328 	 * it's simply used as a place holder on the commit list, and
1329 	 * provides a mechanism for attaching a "commit waiter" onto the
1330 	 * correct lwb (such that the waiter can be signalled upon
1331 	 * completion of that lwb). Thus, we don't process this itx's
1332 	 * log record if it's a commit itx (these itx's don't have log
1333 	 * records), and instead link the itx's waiter onto the lwb's
1334 	 * list of waiters.
1335 	 *
1336 	 * For more details, see the comment above zil_commit().
1337 	 */
1338 	if (lrc->lrc_txtype == TX_COMMIT) {
1339 		mutex_enter(&zilog->zl_lock);
1340 		zil_commit_waiter_link_lwb(itx->itx_private, lwb);
1341 		itx->itx_private = NULL;
1342 		mutex_exit(&zilog->zl_lock);
1343 		return (lwb);
1344 	}
1345 
1346 	if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY) {
1347 		dlen = P2ROUNDUP_TYPED(
1348 		    lrw->lr_length, sizeof (uint64_t), uint64_t);
1349 	} else {
1350 		dlen = 0;
1351 	}
1352 	reclen = lrc->lrc_reclen;
1353 	zilog->zl_cur_used += (reclen + dlen);
1354 	txg = lrc->lrc_txg;
1355 
1356 	ASSERT3U(zilog->zl_cur_used, <, UINT64_MAX - (reclen + dlen));
1357 
1358 cont:
1359 	/*
1360 	 * If this record won't fit in the current log block, start a new one.
1361 	 * For WR_NEED_COPY optimize layout for minimal number of chunks.
1362 	 */
1363 	lwb_sp = lwb->lwb_sz - lwb->lwb_nused;
1364 	if (reclen > lwb_sp || (reclen + dlen > lwb_sp &&
1365 	    lwb_sp < ZIL_MAX_WASTE_SPACE && (dlen % ZIL_MAX_LOG_DATA == 0 ||
1366 	    lwb_sp < reclen + dlen % ZIL_MAX_LOG_DATA))) {
1367 		lwb = zil_lwb_write_issue(zilog, lwb);
1368 		if (lwb == NULL)
1369 			return (NULL);
1370 		zil_lwb_write_open(zilog, lwb);
1371 		ASSERT(LWB_EMPTY(lwb));
1372 		lwb_sp = lwb->lwb_sz - lwb->lwb_nused;
1373 		ASSERT3U(reclen + MIN(dlen, sizeof (uint64_t)), <=, lwb_sp);
1374 	}
1375 
1376 	dnow = MIN(dlen, lwb_sp - reclen);
1377 	lr_buf = lwb->lwb_buf + lwb->lwb_nused;
1378 	bcopy(lrc, lr_buf, reclen);
1379 	lrcb = (lr_t *)lr_buf;		/* Like lrc, but inside lwb. */
1380 	lrwb = (lr_write_t *)lrcb;	/* Like lrw, but inside lwb. */
1381 
1382 	/*
1383 	 * If it's a write, fetch the data or get its blkptr as appropriate.
1384 	 */
1385 	if (lrc->lrc_txtype == TX_WRITE) {
1386 		if (txg > spa_freeze_txg(zilog->zl_spa))
1387 			txg_wait_synced(zilog->zl_dmu_pool, txg);
1388 		if (itx->itx_wr_state != WR_COPIED) {
1389 			char *dbuf;
1390 			int error;
1391 
1392 			if (itx->itx_wr_state == WR_NEED_COPY) {
1393 				dbuf = lr_buf + reclen;
1394 				lrcb->lrc_reclen += dnow;
1395 				if (lrwb->lr_length > dnow)
1396 					lrwb->lr_length = dnow;
1397 				lrw->lr_offset += dnow;
1398 				lrw->lr_length -= dnow;
1399 			} else {
1400 				ASSERT(itx->itx_wr_state == WR_INDIRECT);
1401 				dbuf = NULL;
1402 			}
1403 
1404 			/*
1405 			 * We pass in the "lwb_write_zio" rather than
1406 			 * "lwb_root_zio" so that the "lwb_write_zio"
1407 			 * becomes the parent of any zio's created by
1408 			 * the "zl_get_data" callback. The vdevs are
1409 			 * flushed after the "lwb_write_zio" completes,
1410 			 * so we want to make sure that completion
1411 			 * callback waits for these additional zio's,
1412 			 * such that the vdevs used by those zio's will
1413 			 * be included in the lwb's vdev tree, and those
1414 			 * vdevs will be properly flushed. If we passed
1415 			 * in "lwb_root_zio" here, then these additional
1416 			 * vdevs may not be flushed; e.g. if these zio's
1417 			 * completed after "lwb_write_zio" completed.
1418 			 */
1419 			error = zilog->zl_get_data(itx->itx_private,
1420 			    lrwb, dbuf, lwb, lwb->lwb_write_zio);
1421 
1422 			if (error == EIO) {
1423 				txg_wait_synced(zilog->zl_dmu_pool, txg);
1424 				return (lwb);
1425 			}
1426 			if (error != 0) {
1427 				ASSERT(error == ENOENT || error == EEXIST ||
1428 				    error == EALREADY);
1429 				return (lwb);
1430 			}
1431 		}
1432 	}
1433 
1434 	/*
1435 	 * We're actually making an entry, so update lrc_seq to be the
1436 	 * log record sequence number.  Note that this is generally not
1437 	 * equal to the itx sequence number because not all transactions
1438 	 * are synchronous, and sometimes spa_sync() gets there first.
1439 	 */
1440 	lrcb->lrc_seq = ++zilog->zl_lr_seq;
1441 	lwb->lwb_nused += reclen + dnow;
1442 
1443 	zil_lwb_add_txg(lwb, txg);
1444 
1445 	ASSERT3U(lwb->lwb_nused, <=, lwb->lwb_sz);
1446 	ASSERT0(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)));
1447 
1448 	dlen -= dnow;
1449 	if (dlen > 0) {
1450 		zilog->zl_cur_used += reclen;
1451 		goto cont;
1452 	}
1453 
1454 	return (lwb);
1455 }
1456 
1457 itx_t *
1458 zil_itx_create(uint64_t txtype, size_t lrsize)
1459 {
1460 	itx_t *itx;
1461 
1462 	lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t);
1463 
1464 	itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP);
1465 	itx->itx_lr.lrc_txtype = txtype;
1466 	itx->itx_lr.lrc_reclen = lrsize;
1467 	itx->itx_lr.lrc_seq = 0;	/* defensive */
1468 	itx->itx_sync = B_TRUE;		/* default is synchronous */
1469 
1470 	return (itx);
1471 }
1472 
1473 void
1474 zil_itx_destroy(itx_t *itx)
1475 {
1476 	kmem_free(itx, offsetof(itx_t, itx_lr) + itx->itx_lr.lrc_reclen);
1477 }
1478 
1479 /*
1480  * Free up the sync and async itxs. The itxs_t has already been detached
1481  * so no locks are needed.
1482  */
1483 static void
1484 zil_itxg_clean(itxs_t *itxs)
1485 {
1486 	itx_t *itx;
1487 	list_t *list;
1488 	avl_tree_t *t;
1489 	void *cookie;
1490 	itx_async_node_t *ian;
1491 
1492 	list = &itxs->i_sync_list;
1493 	while ((itx = list_head(list)) != NULL) {
1494 		/*
1495 		 * In the general case, commit itxs will not be found
1496 		 * here, as they'll be committed to an lwb via
1497 		 * zil_lwb_commit(), and free'd in that function. Having
1498 		 * said that, it is still possible for commit itxs to be
1499 		 * found here, due to the following race:
1500 		 *
1501 		 *	- a thread calls zil_commit() which assigns the
1502 		 *	  commit itx to a per-txg i_sync_list
1503 		 *	- zil_itxg_clean() is called (e.g. via spa_sync())
1504 		 *	  while the waiter is still on the i_sync_list
1505 		 *
1506 		 * There's nothing to prevent syncing the txg while the
1507 		 * waiter is on the i_sync_list. This normally doesn't
1508 		 * happen because spa_sync() is slower than zil_commit(),
1509 		 * but if zil_commit() calls txg_wait_synced() (e.g.
1510 		 * because zil_create() or zil_commit_writer_stall() is
1511 		 * called) we will hit this case.
1512 		 */
1513 		if (itx->itx_lr.lrc_txtype == TX_COMMIT)
1514 			zil_commit_waiter_skip(itx->itx_private);
1515 
1516 		list_remove(list, itx);
1517 		zil_itx_destroy(itx);
1518 	}
1519 
1520 	cookie = NULL;
1521 	t = &itxs->i_async_tree;
1522 	while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
1523 		list = &ian->ia_list;
1524 		while ((itx = list_head(list)) != NULL) {
1525 			list_remove(list, itx);
1526 			/* commit itxs should never be on the async lists. */
1527 			ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT);
1528 			zil_itx_destroy(itx);
1529 		}
1530 		list_destroy(list);
1531 		kmem_free(ian, sizeof (itx_async_node_t));
1532 	}
1533 	avl_destroy(t);
1534 
1535 	kmem_free(itxs, sizeof (itxs_t));
1536 }
1537 
1538 static int
1539 zil_aitx_compare(const void *x1, const void *x2)
1540 {
1541 	const uint64_t o1 = ((itx_async_node_t *)x1)->ia_foid;
1542 	const uint64_t o2 = ((itx_async_node_t *)x2)->ia_foid;
1543 
1544 	if (o1 < o2)
1545 		return (-1);
1546 	if (o1 > o2)
1547 		return (1);
1548 
1549 	return (0);
1550 }
1551 
1552 /*
1553  * Remove all async itx with the given oid.
1554  */
1555 static void
1556 zil_remove_async(zilog_t *zilog, uint64_t oid)
1557 {
1558 	uint64_t otxg, txg;
1559 	itx_async_node_t *ian;
1560 	avl_tree_t *t;
1561 	avl_index_t where;
1562 	list_t clean_list;
1563 	itx_t *itx;
1564 
1565 	ASSERT(oid != 0);
1566 	list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
1567 
1568 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
1569 		otxg = ZILTEST_TXG;
1570 	else
1571 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
1572 
1573 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
1574 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
1575 
1576 		mutex_enter(&itxg->itxg_lock);
1577 		if (itxg->itxg_txg != txg) {
1578 			mutex_exit(&itxg->itxg_lock);
1579 			continue;
1580 		}
1581 
1582 		/*
1583 		 * Locate the object node and append its list.
1584 		 */
1585 		t = &itxg->itxg_itxs->i_async_tree;
1586 		ian = avl_find(t, &oid, &where);
1587 		if (ian != NULL)
1588 			list_move_tail(&clean_list, &ian->ia_list);
1589 		mutex_exit(&itxg->itxg_lock);
1590 	}
1591 	while ((itx = list_head(&clean_list)) != NULL) {
1592 		list_remove(&clean_list, itx);
1593 		/* commit itxs should never be on the async lists. */
1594 		ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT);
1595 		zil_itx_destroy(itx);
1596 	}
1597 	list_destroy(&clean_list);
1598 }
1599 
1600 void
1601 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
1602 {
1603 	uint64_t txg;
1604 	itxg_t *itxg;
1605 	itxs_t *itxs, *clean = NULL;
1606 
1607 	/*
1608 	 * Object ids can be re-instantiated in the next txg so
1609 	 * remove any async transactions to avoid future leaks.
1610 	 * This can happen if a fsync occurs on the re-instantiated
1611 	 * object for a WR_INDIRECT or WR_NEED_COPY write, which gets
1612 	 * the new file data and flushes a write record for the old object.
1613 	 */
1614 	if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_REMOVE)
1615 		zil_remove_async(zilog, itx->itx_oid);
1616 
1617 	/*
1618 	 * Ensure the data of a renamed file is committed before the rename.
1619 	 */
1620 	if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_RENAME)
1621 		zil_async_to_sync(zilog, itx->itx_oid);
1622 
1623 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX)
1624 		txg = ZILTEST_TXG;
1625 	else
1626 		txg = dmu_tx_get_txg(tx);
1627 
1628 	itxg = &zilog->zl_itxg[txg & TXG_MASK];
1629 	mutex_enter(&itxg->itxg_lock);
1630 	itxs = itxg->itxg_itxs;
1631 	if (itxg->itxg_txg != txg) {
1632 		if (itxs != NULL) {
1633 			/*
1634 			 * The zil_clean callback hasn't got around to cleaning
1635 			 * this itxg. Save the itxs for release below.
1636 			 * This should be rare.
1637 			 */
1638 			zfs_dbgmsg("zil_itx_assign: missed itx cleanup for "
1639 			    "txg %llu", itxg->itxg_txg);
1640 			clean = itxg->itxg_itxs;
1641 		}
1642 		itxg->itxg_txg = txg;
1643 		itxs = itxg->itxg_itxs = kmem_zalloc(sizeof (itxs_t), KM_SLEEP);
1644 
1645 		list_create(&itxs->i_sync_list, sizeof (itx_t),
1646 		    offsetof(itx_t, itx_node));
1647 		avl_create(&itxs->i_async_tree, zil_aitx_compare,
1648 		    sizeof (itx_async_node_t),
1649 		    offsetof(itx_async_node_t, ia_node));
1650 	}
1651 	if (itx->itx_sync) {
1652 		list_insert_tail(&itxs->i_sync_list, itx);
1653 	} else {
1654 		avl_tree_t *t = &itxs->i_async_tree;
1655 		uint64_t foid = ((lr_ooo_t *)&itx->itx_lr)->lr_foid;
1656 		itx_async_node_t *ian;
1657 		avl_index_t where;
1658 
1659 		ian = avl_find(t, &foid, &where);
1660 		if (ian == NULL) {
1661 			ian = kmem_alloc(sizeof (itx_async_node_t), KM_SLEEP);
1662 			list_create(&ian->ia_list, sizeof (itx_t),
1663 			    offsetof(itx_t, itx_node));
1664 			ian->ia_foid = foid;
1665 			avl_insert(t, ian, where);
1666 		}
1667 		list_insert_tail(&ian->ia_list, itx);
1668 	}
1669 
1670 	itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
1671 
1672 	/*
1673 	 * We don't want to dirty the ZIL using ZILTEST_TXG, because
1674 	 * zil_clean() will never be called using ZILTEST_TXG. Thus, we
1675 	 * need to be careful to always dirty the ZIL using the "real"
1676 	 * TXG (not itxg_txg) even when the SPA is frozen.
1677 	 */
1678 	zilog_dirty(zilog, dmu_tx_get_txg(tx));
1679 	mutex_exit(&itxg->itxg_lock);
1680 
1681 	/* Release the old itxs now we've dropped the lock */
1682 	if (clean != NULL)
1683 		zil_itxg_clean(clean);
1684 }
1685 
1686 /*
1687  * If there are any in-memory intent log transactions which have now been
1688  * synced then start up a taskq to free them. We should only do this after we
1689  * have written out the uberblocks (i.e. txg has been comitted) so that
1690  * don't inadvertently clean out in-memory log records that would be required
1691  * by zil_commit().
1692  */
1693 void
1694 zil_clean(zilog_t *zilog, uint64_t synced_txg)
1695 {
1696 	itxg_t *itxg = &zilog->zl_itxg[synced_txg & TXG_MASK];
1697 	itxs_t *clean_me;
1698 
1699 	ASSERT3U(synced_txg, <, ZILTEST_TXG);
1700 
1701 	mutex_enter(&itxg->itxg_lock);
1702 	if (itxg->itxg_itxs == NULL || itxg->itxg_txg == ZILTEST_TXG) {
1703 		mutex_exit(&itxg->itxg_lock);
1704 		return;
1705 	}
1706 	ASSERT3U(itxg->itxg_txg, <=, synced_txg);
1707 	ASSERT3U(itxg->itxg_txg, !=, 0);
1708 	clean_me = itxg->itxg_itxs;
1709 	itxg->itxg_itxs = NULL;
1710 	itxg->itxg_txg = 0;
1711 	mutex_exit(&itxg->itxg_lock);
1712 	/*
1713 	 * Preferably start a task queue to free up the old itxs but
1714 	 * if taskq_dispatch can't allocate resources to do that then
1715 	 * free it in-line. This should be rare. Note, using TQ_SLEEP
1716 	 * created a bad performance problem.
1717 	 */
1718 	ASSERT3P(zilog->zl_dmu_pool, !=, NULL);
1719 	ASSERT3P(zilog->zl_dmu_pool->dp_zil_clean_taskq, !=, NULL);
1720 	if (taskq_dispatch(zilog->zl_dmu_pool->dp_zil_clean_taskq,
1721 	    (void (*)(void *))zil_itxg_clean, clean_me, TQ_NOSLEEP) == NULL)
1722 		zil_itxg_clean(clean_me);
1723 }
1724 
1725 /*
1726  * This function will traverse the queue of itxs that need to be
1727  * committed, and move them onto the ZIL's zl_itx_commit_list.
1728  */
1729 static void
1730 zil_get_commit_list(zilog_t *zilog)
1731 {
1732 	uint64_t otxg, txg;
1733 	list_t *commit_list = &zilog->zl_itx_commit_list;
1734 
1735 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1736 
1737 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
1738 		otxg = ZILTEST_TXG;
1739 	else
1740 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
1741 
1742 	/*
1743 	 * This is inherently racy, since there is nothing to prevent
1744 	 * the last synced txg from changing. That's okay since we'll
1745 	 * only commit things in the future.
1746 	 */
1747 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
1748 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
1749 
1750 		mutex_enter(&itxg->itxg_lock);
1751 		if (itxg->itxg_txg != txg) {
1752 			mutex_exit(&itxg->itxg_lock);
1753 			continue;
1754 		}
1755 
1756 		/*
1757 		 * If we're adding itx records to the zl_itx_commit_list,
1758 		 * then the zil better be dirty in this "txg". We can assert
1759 		 * that here since we're holding the itxg_lock which will
1760 		 * prevent spa_sync from cleaning it. Once we add the itxs
1761 		 * to the zl_itx_commit_list we must commit it to disk even
1762 		 * if it's unnecessary (i.e. the txg was synced).
1763 		 */
1764 		ASSERT(zilog_is_dirty_in_txg(zilog, txg) ||
1765 		    spa_freeze_txg(zilog->zl_spa) != UINT64_MAX);
1766 		list_move_tail(commit_list, &itxg->itxg_itxs->i_sync_list);
1767 
1768 		mutex_exit(&itxg->itxg_lock);
1769 	}
1770 }
1771 
1772 /*
1773  * Move the async itxs for a specified object to commit into sync lists.
1774  */
1775 static void
1776 zil_async_to_sync(zilog_t *zilog, uint64_t foid)
1777 {
1778 	uint64_t otxg, txg;
1779 	itx_async_node_t *ian;
1780 	avl_tree_t *t;
1781 	avl_index_t where;
1782 
1783 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
1784 		otxg = ZILTEST_TXG;
1785 	else
1786 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
1787 
1788 	/*
1789 	 * This is inherently racy, since there is nothing to prevent
1790 	 * the last synced txg from changing.
1791 	 */
1792 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
1793 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
1794 
1795 		mutex_enter(&itxg->itxg_lock);
1796 		if (itxg->itxg_txg != txg) {
1797 			mutex_exit(&itxg->itxg_lock);
1798 			continue;
1799 		}
1800 
1801 		/*
1802 		 * If a foid is specified then find that node and append its
1803 		 * list. Otherwise walk the tree appending all the lists
1804 		 * to the sync list. We add to the end rather than the
1805 		 * beginning to ensure the create has happened.
1806 		 */
1807 		t = &itxg->itxg_itxs->i_async_tree;
1808 		if (foid != 0) {
1809 			ian = avl_find(t, &foid, &where);
1810 			if (ian != NULL) {
1811 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
1812 				    &ian->ia_list);
1813 			}
1814 		} else {
1815 			void *cookie = NULL;
1816 
1817 			while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
1818 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
1819 				    &ian->ia_list);
1820 				list_destroy(&ian->ia_list);
1821 				kmem_free(ian, sizeof (itx_async_node_t));
1822 			}
1823 		}
1824 		mutex_exit(&itxg->itxg_lock);
1825 	}
1826 }
1827 
1828 /*
1829  * This function will prune commit itxs that are at the head of the
1830  * commit list (it won't prune past the first non-commit itx), and
1831  * either: a) attach them to the last lwb that's still pending
1832  * completion, or b) skip them altogether.
1833  *
1834  * This is used as a performance optimization to prevent commit itxs
1835  * from generating new lwbs when it's unnecessary to do so.
1836  */
1837 static void
1838 zil_prune_commit_list(zilog_t *zilog)
1839 {
1840 	itx_t *itx;
1841 
1842 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1843 
1844 	while (itx = list_head(&zilog->zl_itx_commit_list)) {
1845 		lr_t *lrc = &itx->itx_lr;
1846 		if (lrc->lrc_txtype != TX_COMMIT)
1847 			break;
1848 
1849 		mutex_enter(&zilog->zl_lock);
1850 
1851 		lwb_t *last_lwb = zilog->zl_last_lwb_opened;
1852 		if (last_lwb == NULL || last_lwb->lwb_state == LWB_STATE_DONE) {
1853 			/*
1854 			 * All of the itxs this waiter was waiting on
1855 			 * must have already completed (or there were
1856 			 * never any itx's for it to wait on), so it's
1857 			 * safe to skip this waiter and mark it done.
1858 			 */
1859 			zil_commit_waiter_skip(itx->itx_private);
1860 		} else {
1861 			zil_commit_waiter_link_lwb(itx->itx_private, last_lwb);
1862 			itx->itx_private = NULL;
1863 		}
1864 
1865 		mutex_exit(&zilog->zl_lock);
1866 
1867 		list_remove(&zilog->zl_itx_commit_list, itx);
1868 		zil_itx_destroy(itx);
1869 	}
1870 
1871 	IMPLY(itx != NULL, itx->itx_lr.lrc_txtype != TX_COMMIT);
1872 }
1873 
1874 static void
1875 zil_commit_writer_stall(zilog_t *zilog)
1876 {
1877 	/*
1878 	 * When zio_alloc_zil() fails to allocate the next lwb block on
1879 	 * disk, we must call txg_wait_synced() to ensure all of the
1880 	 * lwbs in the zilog's zl_lwb_list are synced and then freed (in
1881 	 * zil_sync()), such that any subsequent ZIL writer (i.e. a call
1882 	 * to zil_process_commit_list()) will have to call zil_create(),
1883 	 * and start a new ZIL chain.
1884 	 *
1885 	 * Since zil_alloc_zil() failed, the lwb that was previously
1886 	 * issued does not have a pointer to the "next" lwb on disk.
1887 	 * Thus, if another ZIL writer thread was to allocate the "next"
1888 	 * on-disk lwb, that block could be leaked in the event of a
1889 	 * crash (because the previous lwb on-disk would not point to
1890 	 * it).
1891 	 *
1892 	 * We must hold the zilog's zl_issuer_lock while we do this, to
1893 	 * ensure no new threads enter zil_process_commit_list() until
1894 	 * all lwb's in the zl_lwb_list have been synced and freed
1895 	 * (which is achieved via the txg_wait_synced() call).
1896 	 */
1897 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1898 	txg_wait_synced(zilog->zl_dmu_pool, 0);
1899 	ASSERT3P(list_tail(&zilog->zl_lwb_list), ==, NULL);
1900 }
1901 
1902 /*
1903  * This function will traverse the commit list, creating new lwbs as
1904  * needed, and committing the itxs from the commit list to these newly
1905  * created lwbs. Additionally, as a new lwb is created, the previous
1906  * lwb will be issued to the zio layer to be written to disk.
1907  */
1908 static void
1909 zil_process_commit_list(zilog_t *zilog)
1910 {
1911 	spa_t *spa = zilog->zl_spa;
1912 	list_t nolwb_waiters;
1913 	lwb_t *lwb;
1914 	itx_t *itx;
1915 
1916 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1917 
1918 	/*
1919 	 * Return if there's nothing to commit before we dirty the fs by
1920 	 * calling zil_create().
1921 	 */
1922 	if (list_head(&zilog->zl_itx_commit_list) == NULL)
1923 		return;
1924 
1925 	list_create(&nolwb_waiters, sizeof (zil_commit_waiter_t),
1926 	    offsetof(zil_commit_waiter_t, zcw_node));
1927 
1928 	lwb = list_tail(&zilog->zl_lwb_list);
1929 	if (lwb == NULL) {
1930 		lwb = zil_create(zilog);
1931 	} else {
1932 		ASSERT3S(lwb->lwb_state, !=, LWB_STATE_ISSUED);
1933 		ASSERT3S(lwb->lwb_state, !=, LWB_STATE_DONE);
1934 	}
1935 
1936 	while (itx = list_head(&zilog->zl_itx_commit_list)) {
1937 		lr_t *lrc = &itx->itx_lr;
1938 		uint64_t txg = lrc->lrc_txg;
1939 
1940 		ASSERT3U(txg, !=, 0);
1941 
1942 		if (lrc->lrc_txtype == TX_COMMIT) {
1943 			DTRACE_PROBE2(zil__process__commit__itx,
1944 			    zilog_t *, zilog, itx_t *, itx);
1945 		} else {
1946 			DTRACE_PROBE2(zil__process__normal__itx,
1947 			    zilog_t *, zilog, itx_t *, itx);
1948 		}
1949 
1950 		boolean_t synced = txg <= spa_last_synced_txg(spa);
1951 		boolean_t frozen = txg > spa_freeze_txg(spa);
1952 
1953 		/*
1954 		 * If the txg of this itx has already been synced out, then
1955 		 * we don't need to commit this itx to an lwb. This is
1956 		 * because the data of this itx will have already been
1957 		 * written to the main pool. This is inherently racy, and
1958 		 * it's still ok to commit an itx whose txg has already
1959 		 * been synced; this will result in a write that's
1960 		 * unnecessary, but will do no harm.
1961 		 *
1962 		 * With that said, we always want to commit TX_COMMIT itxs
1963 		 * to an lwb, regardless of whether or not that itx's txg
1964 		 * has been synced out. We do this to ensure any OPENED lwb
1965 		 * will always have at least one zil_commit_waiter_t linked
1966 		 * to the lwb.
1967 		 *
1968 		 * As a counter-example, if we skipped TX_COMMIT itx's
1969 		 * whose txg had already been synced, the following
1970 		 * situation could occur if we happened to be racing with
1971 		 * spa_sync:
1972 		 *
1973 		 * 1. we commit a non-TX_COMMIT itx to an lwb, where the
1974 		 *    itx's txg is 10 and the last synced txg is 9.
1975 		 * 2. spa_sync finishes syncing out txg 10.
1976 		 * 3. we move to the next itx in the list, it's a TX_COMMIT
1977 		 *    whose txg is 10, so we skip it rather than committing
1978 		 *    it to the lwb used in (1).
1979 		 *
1980 		 * If the itx that is skipped in (3) is the last TX_COMMIT
1981 		 * itx in the commit list, than it's possible for the lwb
1982 		 * used in (1) to remain in the OPENED state indefinitely.
1983 		 *
1984 		 * To prevent the above scenario from occuring, ensuring
1985 		 * that once an lwb is OPENED it will transition to ISSUED
1986 		 * and eventually DONE, we always commit TX_COMMIT itx's to
1987 		 * an lwb here, even if that itx's txg has already been
1988 		 * synced.
1989 		 *
1990 		 * Finally, if the pool is frozen, we _always_ commit the
1991 		 * itx.  The point of freezing the pool is to prevent data
1992 		 * from being written to the main pool via spa_sync, and
1993 		 * instead rely solely on the ZIL to persistently store the
1994 		 * data; i.e.  when the pool is frozen, the last synced txg
1995 		 * value can't be trusted.
1996 		 */
1997 		if (frozen || !synced || lrc->lrc_txtype == TX_COMMIT) {
1998 			if (lwb != NULL) {
1999 				lwb = zil_lwb_commit(zilog, itx, lwb);
2000 			} else if (lrc->lrc_txtype == TX_COMMIT) {
2001 				ASSERT3P(lwb, ==, NULL);
2002 				zil_commit_waiter_link_nolwb(
2003 				    itx->itx_private, &nolwb_waiters);
2004 			}
2005 		}
2006 
2007 		list_remove(&zilog->zl_itx_commit_list, itx);
2008 		zil_itx_destroy(itx);
2009 	}
2010 
2011 	if (lwb == NULL) {
2012 		/*
2013 		 * This indicates zio_alloc_zil() failed to allocate the
2014 		 * "next" lwb on-disk. When this happens, we must stall
2015 		 * the ZIL write pipeline; see the comment within
2016 		 * zil_commit_writer_stall() for more details.
2017 		 */
2018 		zil_commit_writer_stall(zilog);
2019 
2020 		/*
2021 		 * Additionally, we have to signal and mark the "nolwb"
2022 		 * waiters as "done" here, since without an lwb, we
2023 		 * can't do this via zil_lwb_flush_vdevs_done() like
2024 		 * normal.
2025 		 */
2026 		zil_commit_waiter_t *zcw;
2027 		while (zcw = list_head(&nolwb_waiters)) {
2028 			zil_commit_waiter_skip(zcw);
2029 			list_remove(&nolwb_waiters, zcw);
2030 		}
2031 	} else {
2032 		ASSERT(list_is_empty(&nolwb_waiters));
2033 		ASSERT3P(lwb, !=, NULL);
2034 		ASSERT3S(lwb->lwb_state, !=, LWB_STATE_ISSUED);
2035 		ASSERT3S(lwb->lwb_state, !=, LWB_STATE_DONE);
2036 
2037 		/*
2038 		 * At this point, the ZIL block pointed at by the "lwb"
2039 		 * variable is in one of the following states: "closed"
2040 		 * or "open".
2041 		 *
2042 		 * If its "closed", then no itxs have been committed to
2043 		 * it, so there's no point in issuing its zio (i.e.
2044 		 * it's "empty").
2045 		 *
2046 		 * If its "open" state, then it contains one or more
2047 		 * itxs that eventually need to be committed to stable
2048 		 * storage. In this case we intentionally do not issue
2049 		 * the lwb's zio to disk yet, and instead rely on one of
2050 		 * the following two mechanisms for issuing the zio:
2051 		 *
2052 		 * 1. Ideally, there will be more ZIL activity occuring
2053 		 * on the system, such that this function will be
2054 		 * immediately called again (not necessarily by the same
2055 		 * thread) and this lwb's zio will be issued via
2056 		 * zil_lwb_commit(). This way, the lwb is guaranteed to
2057 		 * be "full" when it is issued to disk, and we'll make
2058 		 * use of the lwb's size the best we can.
2059 		 *
2060 		 * 2. If there isn't sufficient ZIL activity occuring on
2061 		 * the system, such that this lwb's zio isn't issued via
2062 		 * zil_lwb_commit(), zil_commit_waiter() will issue the
2063 		 * lwb's zio. If this occurs, the lwb is not guaranteed
2064 		 * to be "full" by the time its zio is issued, and means
2065 		 * the size of the lwb was "too large" given the amount
2066 		 * of ZIL activity occuring on the system at that time.
2067 		 *
2068 		 * We do this for a couple of reasons:
2069 		 *
2070 		 * 1. To try and reduce the number of IOPs needed to
2071 		 * write the same number of itxs. If an lwb has space
2072 		 * available in it's buffer for more itxs, and more itxs
2073 		 * will be committed relatively soon (relative to the
2074 		 * latency of performing a write), then it's beneficial
2075 		 * to wait for these "next" itxs. This way, more itxs
2076 		 * can be committed to stable storage with fewer writes.
2077 		 *
2078 		 * 2. To try and use the largest lwb block size that the
2079 		 * incoming rate of itxs can support. Again, this is to
2080 		 * try and pack as many itxs into as few lwbs as
2081 		 * possible, without significantly impacting the latency
2082 		 * of each individual itx.
2083 		 */
2084 	}
2085 }
2086 
2087 /*
2088  * This function is responsible for ensuring the passed in commit waiter
2089  * (and associated commit itx) is committed to an lwb. If the waiter is
2090  * not already committed to an lwb, all itxs in the zilog's queue of
2091  * itxs will be processed. The assumption is the passed in waiter's
2092  * commit itx will found in the queue just like the other non-commit
2093  * itxs, such that when the entire queue is processed, the waiter will
2094  * have been commited to an lwb.
2095  *
2096  * The lwb associated with the passed in waiter is not guaranteed to
2097  * have been issued by the time this function completes. If the lwb is
2098  * not issued, we rely on future calls to zil_commit_writer() to issue
2099  * the lwb, or the timeout mechanism found in zil_commit_waiter().
2100  */
2101 static void
2102 zil_commit_writer(zilog_t *zilog, zil_commit_waiter_t *zcw)
2103 {
2104 	ASSERT(!MUTEX_HELD(&zilog->zl_lock));
2105 	ASSERT(spa_writeable(zilog->zl_spa));
2106 
2107 	mutex_enter(&zilog->zl_issuer_lock);
2108 
2109 	if (zcw->zcw_lwb != NULL || zcw->zcw_done) {
2110 		/*
2111 		 * It's possible that, while we were waiting to acquire
2112 		 * the "zl_issuer_lock", another thread committed this
2113 		 * waiter to an lwb. If that occurs, we bail out early,
2114 		 * without processing any of the zilog's queue of itxs.
2115 		 *
2116 		 * On certain workloads and system configurations, the
2117 		 * "zl_issuer_lock" can become highly contended. In an
2118 		 * attempt to reduce this contention, we immediately drop
2119 		 * the lock if the waiter has already been processed.
2120 		 *
2121 		 * We've measured this optimization to reduce CPU spent
2122 		 * contending on this lock by up to 5%, using a system
2123 		 * with 32 CPUs, low latency storage (~50 usec writes),
2124 		 * and 1024 threads performing sync writes.
2125 		 */
2126 		goto out;
2127 	}
2128 
2129 	zil_get_commit_list(zilog);
2130 	zil_prune_commit_list(zilog);
2131 	zil_process_commit_list(zilog);
2132 
2133 out:
2134 	mutex_exit(&zilog->zl_issuer_lock);
2135 }
2136 
2137 static void
2138 zil_commit_waiter_timeout(zilog_t *zilog, zil_commit_waiter_t *zcw)
2139 {
2140 	ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock));
2141 	ASSERT(MUTEX_HELD(&zcw->zcw_lock));
2142 	ASSERT3B(zcw->zcw_done, ==, B_FALSE);
2143 
2144 	lwb_t *lwb = zcw->zcw_lwb;
2145 	ASSERT3P(lwb, !=, NULL);
2146 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_CLOSED);
2147 
2148 	/*
2149 	 * If the lwb has already been issued by another thread, we can
2150 	 * immediately return since there's no work to be done (the
2151 	 * point of this function is to issue the lwb). Additionally, we
2152 	 * do this prior to acquiring the zl_issuer_lock, to avoid
2153 	 * acquiring it when it's not necessary to do so.
2154 	 */
2155 	if (lwb->lwb_state == LWB_STATE_ISSUED ||
2156 	    lwb->lwb_state == LWB_STATE_DONE)
2157 		return;
2158 
2159 	/*
2160 	 * In order to call zil_lwb_write_issue() we must hold the
2161 	 * zilog's "zl_issuer_lock". We can't simply acquire that lock,
2162 	 * since we're already holding the commit waiter's "zcw_lock",
2163 	 * and those two locks are aquired in the opposite order
2164 	 * elsewhere.
2165 	 */
2166 	mutex_exit(&zcw->zcw_lock);
2167 	mutex_enter(&zilog->zl_issuer_lock);
2168 	mutex_enter(&zcw->zcw_lock);
2169 
2170 	/*
2171 	 * Since we just dropped and re-acquired the commit waiter's
2172 	 * lock, we have to re-check to see if the waiter was marked
2173 	 * "done" during that process. If the waiter was marked "done",
2174 	 * the "lwb" pointer is no longer valid (it can be free'd after
2175 	 * the waiter is marked "done"), so without this check we could
2176 	 * wind up with a use-after-free error below.
2177 	 */
2178 	if (zcw->zcw_done)
2179 		goto out;
2180 
2181 	ASSERT3P(lwb, ==, zcw->zcw_lwb);
2182 
2183 	/*
2184 	 * We've already checked this above, but since we hadn't acquired
2185 	 * the zilog's zl_issuer_lock, we have to perform this check a
2186 	 * second time while holding the lock.
2187 	 *
2188 	 * We don't need to hold the zl_lock since the lwb cannot transition
2189 	 * from OPENED to ISSUED while we hold the zl_issuer_lock. The lwb
2190 	 * _can_ transition from ISSUED to DONE, but it's OK to race with
2191 	 * that transition since we treat the lwb the same, whether it's in
2192 	 * the ISSUED or DONE states.
2193 	 *
2194 	 * The important thing, is we treat the lwb differently depending on
2195 	 * if it's ISSUED or OPENED, and block any other threads that might
2196 	 * attempt to issue this lwb. For that reason we hold the
2197 	 * zl_issuer_lock when checking the lwb_state; we must not call
2198 	 * zil_lwb_write_issue() if the lwb had already been issued.
2199 	 *
2200 	 * See the comment above the lwb_state_t structure definition for
2201 	 * more details on the lwb states, and locking requirements.
2202 	 */
2203 	if (lwb->lwb_state == LWB_STATE_ISSUED ||
2204 	    lwb->lwb_state == LWB_STATE_DONE)
2205 		goto out;
2206 
2207 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
2208 
2209 	/*
2210 	 * As described in the comments above zil_commit_waiter() and
2211 	 * zil_process_commit_list(), we need to issue this lwb's zio
2212 	 * since we've reached the commit waiter's timeout and it still
2213 	 * hasn't been issued.
2214 	 */
2215 	lwb_t *nlwb = zil_lwb_write_issue(zilog, lwb);
2216 
2217 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_OPENED);
2218 
2219 	/*
2220 	 * Since the lwb's zio hadn't been issued by the time this thread
2221 	 * reached its timeout, we reset the zilog's "zl_cur_used" field
2222 	 * to influence the zil block size selection algorithm.
2223 	 *
2224 	 * By having to issue the lwb's zio here, it means the size of the
2225 	 * lwb was too large, given the incoming throughput of itxs.  By
2226 	 * setting "zl_cur_used" to zero, we communicate this fact to the
2227 	 * block size selection algorithm, so it can take this informaiton
2228 	 * into account, and potentially select a smaller size for the
2229 	 * next lwb block that is allocated.
2230 	 */
2231 	zilog->zl_cur_used = 0;
2232 
2233 	if (nlwb == NULL) {
2234 		/*
2235 		 * When zil_lwb_write_issue() returns NULL, this
2236 		 * indicates zio_alloc_zil() failed to allocate the
2237 		 * "next" lwb on-disk. When this occurs, the ZIL write
2238 		 * pipeline must be stalled; see the comment within the
2239 		 * zil_commit_writer_stall() function for more details.
2240 		 *
2241 		 * We must drop the commit waiter's lock prior to
2242 		 * calling zil_commit_writer_stall() or else we can wind
2243 		 * up with the following deadlock:
2244 		 *
2245 		 * - This thread is waiting for the txg to sync while
2246 		 *   holding the waiter's lock; txg_wait_synced() is
2247 		 *   used within txg_commit_writer_stall().
2248 		 *
2249 		 * - The txg can't sync because it is waiting for this
2250 		 *   lwb's zio callback to call dmu_tx_commit().
2251 		 *
2252 		 * - The lwb's zio callback can't call dmu_tx_commit()
2253 		 *   because it's blocked trying to acquire the waiter's
2254 		 *   lock, which occurs prior to calling dmu_tx_commit()
2255 		 */
2256 		mutex_exit(&zcw->zcw_lock);
2257 		zil_commit_writer_stall(zilog);
2258 		mutex_enter(&zcw->zcw_lock);
2259 	}
2260 
2261 out:
2262 	mutex_exit(&zilog->zl_issuer_lock);
2263 	ASSERT(MUTEX_HELD(&zcw->zcw_lock));
2264 }
2265 
2266 /*
2267  * This function is responsible for performing the following two tasks:
2268  *
2269  * 1. its primary responsibility is to block until the given "commit
2270  *    waiter" is considered "done".
2271  *
2272  * 2. its secondary responsibility is to issue the zio for the lwb that
2273  *    the given "commit waiter" is waiting on, if this function has
2274  *    waited "long enough" and the lwb is still in the "open" state.
2275  *
2276  * Given a sufficient amount of itxs being generated and written using
2277  * the ZIL, the lwb's zio will be issued via the zil_lwb_commit()
2278  * function. If this does not occur, this secondary responsibility will
2279  * ensure the lwb is issued even if there is not other synchronous
2280  * activity on the system.
2281  *
2282  * For more details, see zil_process_commit_list(); more specifically,
2283  * the comment at the bottom of that function.
2284  */
2285 static void
2286 zil_commit_waiter(zilog_t *zilog, zil_commit_waiter_t *zcw)
2287 {
2288 	ASSERT(!MUTEX_HELD(&zilog->zl_lock));
2289 	ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock));
2290 	ASSERT(spa_writeable(zilog->zl_spa));
2291 
2292 	mutex_enter(&zcw->zcw_lock);
2293 
2294 	/*
2295 	 * The timeout is scaled based on the lwb latency to avoid
2296 	 * significantly impacting the latency of each individual itx.
2297 	 * For more details, see the comment at the bottom of the
2298 	 * zil_process_commit_list() function.
2299 	 */
2300 	int pct = MAX(zfs_commit_timeout_pct, 1);
2301 	hrtime_t sleep = (zilog->zl_last_lwb_latency * pct) / 100;
2302 	hrtime_t wakeup = gethrtime() + sleep;
2303 	boolean_t timedout = B_FALSE;
2304 
2305 	while (!zcw->zcw_done) {
2306 		ASSERT(MUTEX_HELD(&zcw->zcw_lock));
2307 
2308 		lwb_t *lwb = zcw->zcw_lwb;
2309 
2310 		/*
2311 		 * Usually, the waiter will have a non-NULL lwb field here,
2312 		 * but it's possible for it to be NULL as a result of
2313 		 * zil_commit() racing with spa_sync().
2314 		 *
2315 		 * When zil_clean() is called, it's possible for the itxg
2316 		 * list (which may be cleaned via a taskq) to contain
2317 		 * commit itxs. When this occurs, the commit waiters linked
2318 		 * off of these commit itxs will not be committed to an
2319 		 * lwb.  Additionally, these commit waiters will not be
2320 		 * marked done until zil_commit_waiter_skip() is called via
2321 		 * zil_itxg_clean().
2322 		 *
2323 		 * Thus, it's possible for this commit waiter (i.e. the
2324 		 * "zcw" variable) to be found in this "in between" state;
2325 		 * where it's "zcw_lwb" field is NULL, and it hasn't yet
2326 		 * been skipped, so it's "zcw_done" field is still B_FALSE.
2327 		 */
2328 		IMPLY(lwb != NULL, lwb->lwb_state != LWB_STATE_CLOSED);
2329 
2330 		if (lwb != NULL && lwb->lwb_state == LWB_STATE_OPENED) {
2331 			ASSERT3B(timedout, ==, B_FALSE);
2332 
2333 			/*
2334 			 * If the lwb hasn't been issued yet, then we
2335 			 * need to wait with a timeout, in case this
2336 			 * function needs to issue the lwb after the
2337 			 * timeout is reached; responsibility (2) from
2338 			 * the comment above this function.
2339 			 */
2340 			clock_t timeleft = cv_timedwait_hires(&zcw->zcw_cv,
2341 			    &zcw->zcw_lock, wakeup, USEC2NSEC(1),
2342 			    CALLOUT_FLAG_ABSOLUTE);
2343 
2344 			if (timeleft >= 0 || zcw->zcw_done)
2345 				continue;
2346 
2347 			timedout = B_TRUE;
2348 			zil_commit_waiter_timeout(zilog, zcw);
2349 
2350 			if (!zcw->zcw_done) {
2351 				/*
2352 				 * If the commit waiter has already been
2353 				 * marked "done", it's possible for the
2354 				 * waiter's lwb structure to have already
2355 				 * been freed.  Thus, we can only reliably
2356 				 * make these assertions if the waiter
2357 				 * isn't done.
2358 				 */
2359 				ASSERT3P(lwb, ==, zcw->zcw_lwb);
2360 				ASSERT3S(lwb->lwb_state, !=, LWB_STATE_OPENED);
2361 			}
2362 		} else {
2363 			/*
2364 			 * If the lwb isn't open, then it must have already
2365 			 * been issued. In that case, there's no need to
2366 			 * use a timeout when waiting for the lwb to
2367 			 * complete.
2368 			 *
2369 			 * Additionally, if the lwb is NULL, the waiter
2370 			 * will soon be signalled and marked done via
2371 			 * zil_clean() and zil_itxg_clean(), so no timeout
2372 			 * is required.
2373 			 */
2374 
2375 			IMPLY(lwb != NULL,
2376 			    lwb->lwb_state == LWB_STATE_ISSUED ||
2377 			    lwb->lwb_state == LWB_STATE_DONE);
2378 			cv_wait(&zcw->zcw_cv, &zcw->zcw_lock);
2379 		}
2380 	}
2381 
2382 	mutex_exit(&zcw->zcw_lock);
2383 }
2384 
2385 static zil_commit_waiter_t *
2386 zil_alloc_commit_waiter()
2387 {
2388 	zil_commit_waiter_t *zcw = kmem_cache_alloc(zil_zcw_cache, KM_SLEEP);
2389 
2390 	cv_init(&zcw->zcw_cv, NULL, CV_DEFAULT, NULL);
2391 	mutex_init(&zcw->zcw_lock, NULL, MUTEX_DEFAULT, NULL);
2392 	list_link_init(&zcw->zcw_node);
2393 	zcw->zcw_lwb = NULL;
2394 	zcw->zcw_done = B_FALSE;
2395 	zcw->zcw_zio_error = 0;
2396 
2397 	return (zcw);
2398 }
2399 
2400 static void
2401 zil_free_commit_waiter(zil_commit_waiter_t *zcw)
2402 {
2403 	ASSERT(!list_link_active(&zcw->zcw_node));
2404 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
2405 	ASSERT3B(zcw->zcw_done, ==, B_TRUE);
2406 	mutex_destroy(&zcw->zcw_lock);
2407 	cv_destroy(&zcw->zcw_cv);
2408 	kmem_cache_free(zil_zcw_cache, zcw);
2409 }
2410 
2411 /*
2412  * This function is used to create a TX_COMMIT itx and assign it. This
2413  * way, it will be linked into the ZIL's list of synchronous itxs, and
2414  * then later committed to an lwb (or skipped) when
2415  * zil_process_commit_list() is called.
2416  */
2417 static void
2418 zil_commit_itx_assign(zilog_t *zilog, zil_commit_waiter_t *zcw)
2419 {
2420 	dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
2421 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
2422 
2423 	itx_t *itx = zil_itx_create(TX_COMMIT, sizeof (lr_t));
2424 	itx->itx_sync = B_TRUE;
2425 	itx->itx_private = zcw;
2426 
2427 	zil_itx_assign(zilog, itx, tx);
2428 
2429 	dmu_tx_commit(tx);
2430 }
2431 
2432 /*
2433  * Commit ZFS Intent Log transactions (itxs) to stable storage.
2434  *
2435  * When writing ZIL transactions to the on-disk representation of the
2436  * ZIL, the itxs are committed to a Log Write Block (lwb). Multiple
2437  * itxs can be committed to a single lwb. Once a lwb is written and
2438  * committed to stable storage (i.e. the lwb is written, and vdevs have
2439  * been flushed), each itx that was committed to that lwb is also
2440  * considered to be committed to stable storage.
2441  *
2442  * When an itx is committed to an lwb, the log record (lr_t) contained
2443  * by the itx is copied into the lwb's zio buffer, and once this buffer
2444  * is written to disk, it becomes an on-disk ZIL block.
2445  *
2446  * As itxs are generated, they're inserted into the ZIL's queue of
2447  * uncommitted itxs. The semantics of zil_commit() are such that it will
2448  * block until all itxs that were in the queue when it was called, are
2449  * committed to stable storage.
2450  *
2451  * If "foid" is zero, this means all "synchronous" and "asynchronous"
2452  * itxs, for all objects in the dataset, will be committed to stable
2453  * storage prior to zil_commit() returning. If "foid" is non-zero, all
2454  * "synchronous" itxs for all objects, but only "asynchronous" itxs
2455  * that correspond to the foid passed in, will be committed to stable
2456  * storage prior to zil_commit() returning.
2457  *
2458  * Generally speaking, when zil_commit() is called, the consumer doesn't
2459  * actually care about _all_ of the uncommitted itxs. Instead, they're
2460  * simply trying to waiting for a specific itx to be committed to disk,
2461  * but the interface(s) for interacting with the ZIL don't allow such
2462  * fine-grained communication. A better interface would allow a consumer
2463  * to create and assign an itx, and then pass a reference to this itx to
2464  * zil_commit(); such that zil_commit() would return as soon as that
2465  * specific itx was committed to disk (instead of waiting for _all_
2466  * itxs to be committed).
2467  *
2468  * When a thread calls zil_commit() a special "commit itx" will be
2469  * generated, along with a corresponding "waiter" for this commit itx.
2470  * zil_commit() will wait on this waiter's CV, such that when the waiter
2471  * is marked done, and signalled, zil_commit() will return.
2472  *
2473  * This commit itx is inserted into the queue of uncommitted itxs. This
2474  * provides an easy mechanism for determining which itxs were in the
2475  * queue prior to zil_commit() having been called, and which itxs were
2476  * added after zil_commit() was called.
2477  *
2478  * The commit it is special; it doesn't have any on-disk representation.
2479  * When a commit itx is "committed" to an lwb, the waiter associated
2480  * with it is linked onto the lwb's list of waiters. Then, when that lwb
2481  * completes, each waiter on the lwb's list is marked done and signalled
2482  * -- allowing the thread waiting on the waiter to return from zil_commit().
2483  *
2484  * It's important to point out a few critical factors that allow us
2485  * to make use of the commit itxs, commit waiters, per-lwb lists of
2486  * commit waiters, and zio completion callbacks like we're doing:
2487  *
2488  *   1. The list of waiters for each lwb is traversed, and each commit
2489  *      waiter is marked "done" and signalled, in the zio completion
2490  *      callback of the lwb's zio[*].
2491  *
2492  *      * Actually, the waiters are signalled in the zio completion
2493  *        callback of the root zio for the DKIOCFLUSHWRITECACHE commands
2494  *        that are sent to the vdevs upon completion of the lwb zio.
2495  *
2496  *   2. When the itxs are inserted into the ZIL's queue of uncommitted
2497  *      itxs, the order in which they are inserted is preserved[*]; as
2498  *      itxs are added to the queue, they are added to the tail of
2499  *      in-memory linked lists.
2500  *
2501  *      When committing the itxs to lwbs (to be written to disk), they
2502  *      are committed in the same order in which the itxs were added to
2503  *      the uncommitted queue's linked list(s); i.e. the linked list of
2504  *      itxs to commit is traversed from head to tail, and each itx is
2505  *      committed to an lwb in that order.
2506  *
2507  *      * To clarify:
2508  *
2509  *        - the order of "sync" itxs is preserved w.r.t. other
2510  *          "sync" itxs, regardless of the corresponding objects.
2511  *        - the order of "async" itxs is preserved w.r.t. other
2512  *          "async" itxs corresponding to the same object.
2513  *        - the order of "async" itxs is *not* preserved w.r.t. other
2514  *          "async" itxs corresponding to different objects.
2515  *        - the order of "sync" itxs w.r.t. "async" itxs (or vice
2516  *          versa) is *not* preserved, even for itxs that correspond
2517  *          to the same object.
2518  *
2519  *      For more details, see: zil_itx_assign(), zil_async_to_sync(),
2520  *      zil_get_commit_list(), and zil_process_commit_list().
2521  *
2522  *   3. The lwbs represent a linked list of blocks on disk. Thus, any
2523  *      lwb cannot be considered committed to stable storage, until its
2524  *      "previous" lwb is also committed to stable storage. This fact,
2525  *      coupled with the fact described above, means that itxs are
2526  *      committed in (roughly) the order in which they were generated.
2527  *      This is essential because itxs are dependent on prior itxs.
2528  *      Thus, we *must not* deem an itx as being committed to stable
2529  *      storage, until *all* prior itxs have also been committed to
2530  *      stable storage.
2531  *
2532  *      To enforce this ordering of lwb zio's, while still leveraging as
2533  *      much of the underlying storage performance as possible, we rely
2534  *      on two fundamental concepts:
2535  *
2536  *          1. The creation and issuance of lwb zio's is protected by
2537  *             the zilog's "zl_issuer_lock", which ensures only a single
2538  *             thread is creating and/or issuing lwb's at a time
2539  *          2. The "previous" lwb is a child of the "current" lwb
2540  *             (leveraging the zio parent-child depenency graph)
2541  *
2542  *      By relying on this parent-child zio relationship, we can have
2543  *      many lwb zio's concurrently issued to the underlying storage,
2544  *      but the order in which they complete will be the same order in
2545  *      which they were created.
2546  */
2547 void
2548 zil_commit(zilog_t *zilog, uint64_t foid)
2549 {
2550 	/*
2551 	 * We should never attempt to call zil_commit on a snapshot for
2552 	 * a couple of reasons:
2553 	 *
2554 	 * 1. A snapshot may never be modified, thus it cannot have any
2555 	 *    in-flight itxs that would have modified the dataset.
2556 	 *
2557 	 * 2. By design, when zil_commit() is called, a commit itx will
2558 	 *    be assigned to this zilog; as a result, the zilog will be
2559 	 *    dirtied. We must not dirty the zilog of a snapshot; there's
2560 	 *    checks in the code that enforce this invariant, and will
2561 	 *    cause a panic if it's not upheld.
2562 	 */
2563 	ASSERT3B(dmu_objset_is_snapshot(zilog->zl_os), ==, B_FALSE);
2564 
2565 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
2566 		return;
2567 
2568 	if (!spa_writeable(zilog->zl_spa)) {
2569 		/*
2570 		 * If the SPA is not writable, there should never be any
2571 		 * pending itxs waiting to be committed to disk. If that
2572 		 * weren't true, we'd skip writing those itxs out, and
2573 		 * would break the sematics of zil_commit(); thus, we're
2574 		 * verifying that truth before we return to the caller.
2575 		 */
2576 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
2577 		ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL);
2578 		for (int i = 0; i < TXG_SIZE; i++)
2579 			ASSERT3P(zilog->zl_itxg[i].itxg_itxs, ==, NULL);
2580 		return;
2581 	}
2582 
2583 	/*
2584 	 * If the ZIL is suspended, we don't want to dirty it by calling
2585 	 * zil_commit_itx_assign() below, nor can we write out
2586 	 * lwbs like would be done in zil_commit_write(). Thus, we
2587 	 * simply rely on txg_wait_synced() to maintain the necessary
2588 	 * semantics, and avoid calling those functions altogether.
2589 	 */
2590 	if (zilog->zl_suspend > 0) {
2591 		txg_wait_synced(zilog->zl_dmu_pool, 0);
2592 		return;
2593 	}
2594 
2595 	zil_commit_impl(zilog, foid);
2596 }
2597 
2598 void
2599 zil_commit_impl(zilog_t *zilog, uint64_t foid)
2600 {
2601 	/*
2602 	 * Move the "async" itxs for the specified foid to the "sync"
2603 	 * queues, such that they will be later committed (or skipped)
2604 	 * to an lwb when zil_process_commit_list() is called.
2605 	 *
2606 	 * Since these "async" itxs must be committed prior to this
2607 	 * call to zil_commit returning, we must perform this operation
2608 	 * before we call zil_commit_itx_assign().
2609 	 */
2610 	zil_async_to_sync(zilog, foid);
2611 
2612 	/*
2613 	 * We allocate a new "waiter" structure which will initially be
2614 	 * linked to the commit itx using the itx's "itx_private" field.
2615 	 * Since the commit itx doesn't represent any on-disk state,
2616 	 * when it's committed to an lwb, rather than copying the its
2617 	 * lr_t into the lwb's buffer, the commit itx's "waiter" will be
2618 	 * added to the lwb's list of waiters. Then, when the lwb is
2619 	 * committed to stable storage, each waiter in the lwb's list of
2620 	 * waiters will be marked "done", and signalled.
2621 	 *
2622 	 * We must create the waiter and assign the commit itx prior to
2623 	 * calling zil_commit_writer(), or else our specific commit itx
2624 	 * is not guaranteed to be committed to an lwb prior to calling
2625 	 * zil_commit_waiter().
2626 	 */
2627 	zil_commit_waiter_t *zcw = zil_alloc_commit_waiter();
2628 	zil_commit_itx_assign(zilog, zcw);
2629 
2630 	zil_commit_writer(zilog, zcw);
2631 	zil_commit_waiter(zilog, zcw);
2632 
2633 	if (zcw->zcw_zio_error != 0) {
2634 		/*
2635 		 * If there was an error writing out the ZIL blocks that
2636 		 * this thread is waiting on, then we fallback to
2637 		 * relying on spa_sync() to write out the data this
2638 		 * thread is waiting on. Obviously this has performance
2639 		 * implications, but the expectation is for this to be
2640 		 * an exceptional case, and shouldn't occur often.
2641 		 */
2642 		DTRACE_PROBE2(zil__commit__io__error,
2643 		    zilog_t *, zilog, zil_commit_waiter_t *, zcw);
2644 		txg_wait_synced(zilog->zl_dmu_pool, 0);
2645 	}
2646 
2647 	zil_free_commit_waiter(zcw);
2648 }
2649 
2650 /*
2651  * Called in syncing context to free committed log blocks and update log header.
2652  */
2653 void
2654 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
2655 {
2656 	zil_header_t *zh = zil_header_in_syncing_context(zilog);
2657 	uint64_t txg = dmu_tx_get_txg(tx);
2658 	spa_t *spa = zilog->zl_spa;
2659 	uint64_t *replayed_seq = &zilog->zl_replayed_seq[txg & TXG_MASK];
2660 	lwb_t *lwb;
2661 
2662 	/*
2663 	 * We don't zero out zl_destroy_txg, so make sure we don't try
2664 	 * to destroy it twice.
2665 	 */
2666 	if (spa_sync_pass(spa) != 1)
2667 		return;
2668 
2669 	mutex_enter(&zilog->zl_lock);
2670 
2671 	ASSERT(zilog->zl_stop_sync == 0);
2672 
2673 	if (*replayed_seq != 0) {
2674 		ASSERT(zh->zh_replay_seq < *replayed_seq);
2675 		zh->zh_replay_seq = *replayed_seq;
2676 		*replayed_seq = 0;
2677 	}
2678 
2679 	if (zilog->zl_destroy_txg == txg) {
2680 		blkptr_t blk = zh->zh_log;
2681 
2682 		ASSERT(list_head(&zilog->zl_lwb_list) == NULL);
2683 
2684 		bzero(zh, sizeof (zil_header_t));
2685 		bzero(zilog->zl_replayed_seq, sizeof (zilog->zl_replayed_seq));
2686 
2687 		if (zilog->zl_keep_first) {
2688 			/*
2689 			 * If this block was part of log chain that couldn't
2690 			 * be claimed because a device was missing during
2691 			 * zil_claim(), but that device later returns,
2692 			 * then this block could erroneously appear valid.
2693 			 * To guard against this, assign a new GUID to the new
2694 			 * log chain so it doesn't matter what blk points to.
2695 			 */
2696 			zil_init_log_chain(zilog, &blk);
2697 			zh->zh_log = blk;
2698 		}
2699 	}
2700 
2701 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
2702 		zh->zh_log = lwb->lwb_blk;
2703 		if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg)
2704 			break;
2705 		list_remove(&zilog->zl_lwb_list, lwb);
2706 		zio_free(spa, txg, &lwb->lwb_blk);
2707 		zil_free_lwb(zilog, lwb);
2708 
2709 		/*
2710 		 * If we don't have anything left in the lwb list then
2711 		 * we've had an allocation failure and we need to zero
2712 		 * out the zil_header blkptr so that we don't end
2713 		 * up freeing the same block twice.
2714 		 */
2715 		if (list_head(&zilog->zl_lwb_list) == NULL)
2716 			BP_ZERO(&zh->zh_log);
2717 	}
2718 	mutex_exit(&zilog->zl_lock);
2719 }
2720 
2721 /* ARGSUSED */
2722 static int
2723 zil_lwb_cons(void *vbuf, void *unused, int kmflag)
2724 {
2725 	lwb_t *lwb = vbuf;
2726 	list_create(&lwb->lwb_waiters, sizeof (zil_commit_waiter_t),
2727 	    offsetof(zil_commit_waiter_t, zcw_node));
2728 	avl_create(&lwb->lwb_vdev_tree, zil_lwb_vdev_compare,
2729 	    sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
2730 	mutex_init(&lwb->lwb_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
2731 	return (0);
2732 }
2733 
2734 /* ARGSUSED */
2735 static void
2736 zil_lwb_dest(void *vbuf, void *unused)
2737 {
2738 	lwb_t *lwb = vbuf;
2739 	mutex_destroy(&lwb->lwb_vdev_lock);
2740 	avl_destroy(&lwb->lwb_vdev_tree);
2741 	list_destroy(&lwb->lwb_waiters);
2742 }
2743 
2744 void
2745 zil_init(void)
2746 {
2747 	zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
2748 	    sizeof (lwb_t), 0, zil_lwb_cons, zil_lwb_dest, NULL, NULL, NULL, 0);
2749 
2750 	zil_zcw_cache = kmem_cache_create("zil_zcw_cache",
2751 	    sizeof (zil_commit_waiter_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
2752 }
2753 
2754 void
2755 zil_fini(void)
2756 {
2757 	kmem_cache_destroy(zil_zcw_cache);
2758 	kmem_cache_destroy(zil_lwb_cache);
2759 }
2760 
2761 void
2762 zil_set_sync(zilog_t *zilog, uint64_t sync)
2763 {
2764 	zilog->zl_sync = sync;
2765 }
2766 
2767 void
2768 zil_set_logbias(zilog_t *zilog, uint64_t logbias)
2769 {
2770 	zilog->zl_logbias = logbias;
2771 }
2772 
2773 zilog_t *
2774 zil_alloc(objset_t *os, zil_header_t *zh_phys)
2775 {
2776 	zilog_t *zilog;
2777 
2778 	zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
2779 
2780 	zilog->zl_header = zh_phys;
2781 	zilog->zl_os = os;
2782 	zilog->zl_spa = dmu_objset_spa(os);
2783 	zilog->zl_dmu_pool = dmu_objset_pool(os);
2784 	zilog->zl_destroy_txg = TXG_INITIAL - 1;
2785 	zilog->zl_logbias = dmu_objset_logbias(os);
2786 	zilog->zl_sync = dmu_objset_syncprop(os);
2787 	zilog->zl_dirty_max_txg = 0;
2788 	zilog->zl_last_lwb_opened = NULL;
2789 	zilog->zl_last_lwb_latency = 0;
2790 
2791 	mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
2792 	mutex_init(&zilog->zl_issuer_lock, NULL, MUTEX_DEFAULT, NULL);
2793 
2794 	for (int i = 0; i < TXG_SIZE; i++) {
2795 		mutex_init(&zilog->zl_itxg[i].itxg_lock, NULL,
2796 		    MUTEX_DEFAULT, NULL);
2797 	}
2798 
2799 	list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
2800 	    offsetof(lwb_t, lwb_node));
2801 
2802 	list_create(&zilog->zl_itx_commit_list, sizeof (itx_t),
2803 	    offsetof(itx_t, itx_node));
2804 
2805 	cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
2806 
2807 	return (zilog);
2808 }
2809 
2810 void
2811 zil_free(zilog_t *zilog)
2812 {
2813 	zilog->zl_stop_sync = 1;
2814 
2815 	ASSERT0(zilog->zl_suspend);
2816 	ASSERT0(zilog->zl_suspending);
2817 
2818 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
2819 	list_destroy(&zilog->zl_lwb_list);
2820 
2821 	ASSERT(list_is_empty(&zilog->zl_itx_commit_list));
2822 	list_destroy(&zilog->zl_itx_commit_list);
2823 
2824 	for (int i = 0; i < TXG_SIZE; i++) {
2825 		/*
2826 		 * It's possible for an itx to be generated that doesn't dirty
2827 		 * a txg (e.g. ztest TX_TRUNCATE). So there's no zil_clean()
2828 		 * callback to remove the entry. We remove those here.
2829 		 *
2830 		 * Also free up the ziltest itxs.
2831 		 */
2832 		if (zilog->zl_itxg[i].itxg_itxs)
2833 			zil_itxg_clean(zilog->zl_itxg[i].itxg_itxs);
2834 		mutex_destroy(&zilog->zl_itxg[i].itxg_lock);
2835 	}
2836 
2837 	mutex_destroy(&zilog->zl_issuer_lock);
2838 	mutex_destroy(&zilog->zl_lock);
2839 
2840 	cv_destroy(&zilog->zl_cv_suspend);
2841 
2842 	kmem_free(zilog, sizeof (zilog_t));
2843 }
2844 
2845 /*
2846  * Open an intent log.
2847  */
2848 zilog_t *
2849 zil_open(objset_t *os, zil_get_data_t *get_data)
2850 {
2851 	zilog_t *zilog = dmu_objset_zil(os);
2852 
2853 	ASSERT3P(zilog->zl_get_data, ==, NULL);
2854 	ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL);
2855 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
2856 
2857 	zilog->zl_get_data = get_data;
2858 
2859 	return (zilog);
2860 }
2861 
2862 /*
2863  * Close an intent log.
2864  */
2865 void
2866 zil_close(zilog_t *zilog)
2867 {
2868 	lwb_t *lwb;
2869 	uint64_t txg;
2870 
2871 	if (!dmu_objset_is_snapshot(zilog->zl_os)) {
2872 		zil_commit(zilog, 0);
2873 	} else {
2874 		ASSERT3P(list_tail(&zilog->zl_lwb_list), ==, NULL);
2875 		ASSERT0(zilog->zl_dirty_max_txg);
2876 		ASSERT3B(zilog_is_dirty(zilog), ==, B_FALSE);
2877 	}
2878 
2879 	mutex_enter(&zilog->zl_lock);
2880 	lwb = list_tail(&zilog->zl_lwb_list);
2881 	if (lwb == NULL)
2882 		txg = zilog->zl_dirty_max_txg;
2883 	else
2884 		txg = MAX(zilog->zl_dirty_max_txg, lwb->lwb_max_txg);
2885 	mutex_exit(&zilog->zl_lock);
2886 
2887 	/*
2888 	 * We need to use txg_wait_synced() to wait long enough for the
2889 	 * ZIL to be clean, and to wait for all pending lwbs to be
2890 	 * written out.
2891 	 */
2892 	if (txg != 0)
2893 		txg_wait_synced(zilog->zl_dmu_pool, txg);
2894 
2895 	if (zilog_is_dirty(zilog))
2896 		zfs_dbgmsg("zil (%p) is dirty, txg %llu", zilog, txg);
2897 	VERIFY(!zilog_is_dirty(zilog));
2898 
2899 	zilog->zl_get_data = NULL;
2900 
2901 	/*
2902 	 * We should have only one lwb left on the list; remove it now.
2903 	 */
2904 	mutex_enter(&zilog->zl_lock);
2905 	lwb = list_head(&zilog->zl_lwb_list);
2906 	if (lwb != NULL) {
2907 		ASSERT3P(lwb, ==, list_tail(&zilog->zl_lwb_list));
2908 		ASSERT3S(lwb->lwb_state, !=, LWB_STATE_ISSUED);
2909 		list_remove(&zilog->zl_lwb_list, lwb);
2910 		zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
2911 		zil_free_lwb(zilog, lwb);
2912 	}
2913 	mutex_exit(&zilog->zl_lock);
2914 }
2915 
2916 static char *suspend_tag = "zil suspending";
2917 
2918 /*
2919  * Suspend an intent log.  While in suspended mode, we still honor
2920  * synchronous semantics, but we rely on txg_wait_synced() to do it.
2921  * On old version pools, we suspend the log briefly when taking a
2922  * snapshot so that it will have an empty intent log.
2923  *
2924  * Long holds are not really intended to be used the way we do here --
2925  * held for such a short time.  A concurrent caller of dsl_dataset_long_held()
2926  * could fail.  Therefore we take pains to only put a long hold if it is
2927  * actually necessary.  Fortunately, it will only be necessary if the
2928  * objset is currently mounted (or the ZVOL equivalent).  In that case it
2929  * will already have a long hold, so we are not really making things any worse.
2930  *
2931  * Ideally, we would locate the existing long-holder (i.e. the zfsvfs_t or
2932  * zvol_state_t), and use their mechanism to prevent their hold from being
2933  * dropped (e.g. VFS_HOLD()).  However, that would be even more pain for
2934  * very little gain.
2935  *
2936  * if cookiep == NULL, this does both the suspend & resume.
2937  * Otherwise, it returns with the dataset "long held", and the cookie
2938  * should be passed into zil_resume().
2939  */
2940 int
2941 zil_suspend(const char *osname, void **cookiep)
2942 {
2943 	objset_t *os;
2944 	zilog_t *zilog;
2945 	const zil_header_t *zh;
2946 	int error;
2947 
2948 	error = dmu_objset_hold(osname, suspend_tag, &os);
2949 	if (error != 0)
2950 		return (error);
2951 	zilog = dmu_objset_zil(os);
2952 
2953 	mutex_enter(&zilog->zl_lock);
2954 	zh = zilog->zl_header;
2955 
2956 	if (zh->zh_flags & ZIL_REPLAY_NEEDED) {		/* unplayed log */
2957 		mutex_exit(&zilog->zl_lock);
2958 		dmu_objset_rele(os, suspend_tag);
2959 		return (SET_ERROR(EBUSY));
2960 	}
2961 
2962 	/*
2963 	 * Don't put a long hold in the cases where we can avoid it.  This
2964 	 * is when there is no cookie so we are doing a suspend & resume
2965 	 * (i.e. called from zil_vdev_offline()), and there's nothing to do
2966 	 * for the suspend because it's already suspended, or there's no ZIL.
2967 	 */
2968 	if (cookiep == NULL && !zilog->zl_suspending &&
2969 	    (zilog->zl_suspend > 0 || BP_IS_HOLE(&zh->zh_log))) {
2970 		mutex_exit(&zilog->zl_lock);
2971 		dmu_objset_rele(os, suspend_tag);
2972 		return (0);
2973 	}
2974 
2975 	dsl_dataset_long_hold(dmu_objset_ds(os), suspend_tag);
2976 	dsl_pool_rele(dmu_objset_pool(os), suspend_tag);
2977 
2978 	zilog->zl_suspend++;
2979 
2980 	if (zilog->zl_suspend > 1) {
2981 		/*
2982 		 * Someone else is already suspending it.
2983 		 * Just wait for them to finish.
2984 		 */
2985 
2986 		while (zilog->zl_suspending)
2987 			cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
2988 		mutex_exit(&zilog->zl_lock);
2989 
2990 		if (cookiep == NULL)
2991 			zil_resume(os);
2992 		else
2993 			*cookiep = os;
2994 		return (0);
2995 	}
2996 
2997 	/*
2998 	 * If there is no pointer to an on-disk block, this ZIL must not
2999 	 * be active (e.g. filesystem not mounted), so there's nothing
3000 	 * to clean up.
3001 	 */
3002 	if (BP_IS_HOLE(&zh->zh_log)) {
3003 		ASSERT(cookiep != NULL); /* fast path already handled */
3004 
3005 		*cookiep = os;
3006 		mutex_exit(&zilog->zl_lock);
3007 		return (0);
3008 	}
3009 
3010 	zilog->zl_suspending = B_TRUE;
3011 	mutex_exit(&zilog->zl_lock);
3012 
3013 	/*
3014 	 * We need to use zil_commit_impl to ensure we wait for all
3015 	 * LWB_STATE_OPENED and LWB_STATE_ISSUED lwb's to be committed
3016 	 * to disk before proceeding. If we used zil_commit instead, it
3017 	 * would just call txg_wait_synced(), because zl_suspend is set.
3018 	 * txg_wait_synced() doesn't wait for these lwb's to be
3019 	 * LWB_STATE_DONE before returning.
3020 	 */
3021 	zil_commit_impl(zilog, 0);
3022 
3023 	/*
3024 	 * Now that we've ensured all lwb's are LWB_STATE_DONE, we use
3025 	 * txg_wait_synced() to ensure the data from the zilog has
3026 	 * migrated to the main pool before calling zil_destroy().
3027 	 */
3028 	txg_wait_synced(zilog->zl_dmu_pool, 0);
3029 
3030 	zil_destroy(zilog, B_FALSE);
3031 
3032 	mutex_enter(&zilog->zl_lock);
3033 	zilog->zl_suspending = B_FALSE;
3034 	cv_broadcast(&zilog->zl_cv_suspend);
3035 	mutex_exit(&zilog->zl_lock);
3036 
3037 	if (cookiep == NULL)
3038 		zil_resume(os);
3039 	else
3040 		*cookiep = os;
3041 	return (0);
3042 }
3043 
3044 void
3045 zil_resume(void *cookie)
3046 {
3047 	objset_t *os = cookie;
3048 	zilog_t *zilog = dmu_objset_zil(os);
3049 
3050 	mutex_enter(&zilog->zl_lock);
3051 	ASSERT(zilog->zl_suspend != 0);
3052 	zilog->zl_suspend--;
3053 	mutex_exit(&zilog->zl_lock);
3054 	dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag);
3055 	dsl_dataset_rele(dmu_objset_ds(os), suspend_tag);
3056 }
3057 
3058 typedef struct zil_replay_arg {
3059 	zil_replay_func_t **zr_replay;
3060 	void		*zr_arg;
3061 	boolean_t	zr_byteswap;
3062 	char		*zr_lr;
3063 } zil_replay_arg_t;
3064 
3065 static int
3066 zil_replay_error(zilog_t *zilog, lr_t *lr, int error)
3067 {
3068 	char name[ZFS_MAX_DATASET_NAME_LEN];
3069 
3070 	zilog->zl_replaying_seq--;	/* didn't actually replay this one */
3071 
3072 	dmu_objset_name(zilog->zl_os, name);
3073 
3074 	cmn_err(CE_WARN, "ZFS replay transaction error %d, "
3075 	    "dataset %s, seq 0x%llx, txtype %llu %s\n", error, name,
3076 	    (u_longlong_t)lr->lrc_seq,
3077 	    (u_longlong_t)(lr->lrc_txtype & ~TX_CI),
3078 	    (lr->lrc_txtype & TX_CI) ? "CI" : "");
3079 
3080 	return (error);
3081 }
3082 
3083 static int
3084 zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg)
3085 {
3086 	zil_replay_arg_t *zr = zra;
3087 	const zil_header_t *zh = zilog->zl_header;
3088 	uint64_t reclen = lr->lrc_reclen;
3089 	uint64_t txtype = lr->lrc_txtype;
3090 	int error = 0;
3091 
3092 	zilog->zl_replaying_seq = lr->lrc_seq;
3093 
3094 	if (lr->lrc_seq <= zh->zh_replay_seq)	/* already replayed */
3095 		return (0);
3096 
3097 	if (lr->lrc_txg < claim_txg)		/* already committed */
3098 		return (0);
3099 
3100 	/* Strip case-insensitive bit, still present in log record */
3101 	txtype &= ~TX_CI;
3102 
3103 	if (txtype == 0 || txtype >= TX_MAX_TYPE)
3104 		return (zil_replay_error(zilog, lr, EINVAL));
3105 
3106 	/*
3107 	 * If this record type can be logged out of order, the object
3108 	 * (lr_foid) may no longer exist.  That's legitimate, not an error.
3109 	 */
3110 	if (TX_OOO(txtype)) {
3111 		error = dmu_object_info(zilog->zl_os,
3112 		    ((lr_ooo_t *)lr)->lr_foid, NULL);
3113 		if (error == ENOENT || error == EEXIST)
3114 			return (0);
3115 	}
3116 
3117 	/*
3118 	 * Make a copy of the data so we can revise and extend it.
3119 	 */
3120 	bcopy(lr, zr->zr_lr, reclen);
3121 
3122 	/*
3123 	 * If this is a TX_WRITE with a blkptr, suck in the data.
3124 	 */
3125 	if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
3126 		error = zil_read_log_data(zilog, (lr_write_t *)lr,
3127 		    zr->zr_lr + reclen);
3128 		if (error != 0)
3129 			return (zil_replay_error(zilog, lr, error));
3130 	}
3131 
3132 	/*
3133 	 * The log block containing this lr may have been byteswapped
3134 	 * so that we can easily examine common fields like lrc_txtype.
3135 	 * However, the log is a mix of different record types, and only the
3136 	 * replay vectors know how to byteswap their records.  Therefore, if
3137 	 * the lr was byteswapped, undo it before invoking the replay vector.
3138 	 */
3139 	if (zr->zr_byteswap)
3140 		byteswap_uint64_array(zr->zr_lr, reclen);
3141 
3142 	/*
3143 	 * We must now do two things atomically: replay this log record,
3144 	 * and update the log header sequence number to reflect the fact that
3145 	 * we did so. At the end of each replay function the sequence number
3146 	 * is updated if we are in replay mode.
3147 	 */
3148 	error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, zr->zr_byteswap);
3149 	if (error != 0) {
3150 		/*
3151 		 * The DMU's dnode layer doesn't see removes until the txg
3152 		 * commits, so a subsequent claim can spuriously fail with
3153 		 * EEXIST. So if we receive any error we try syncing out
3154 		 * any removes then retry the transaction.  Note that we
3155 		 * specify B_FALSE for byteswap now, so we don't do it twice.
3156 		 */
3157 		txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
3158 		error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, B_FALSE);
3159 		if (error != 0)
3160 			return (zil_replay_error(zilog, lr, error));
3161 	}
3162 	return (0);
3163 }
3164 
3165 /* ARGSUSED */
3166 static int
3167 zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
3168 {
3169 	zilog->zl_replay_blks++;
3170 
3171 	return (0);
3172 }
3173 
3174 /*
3175  * If this dataset has a non-empty intent log, replay it and destroy it.
3176  */
3177 void
3178 zil_replay(objset_t *os, void *arg, zil_replay_func_t *replay_func[TX_MAX_TYPE])
3179 {
3180 	zilog_t *zilog = dmu_objset_zil(os);
3181 	const zil_header_t *zh = zilog->zl_header;
3182 	zil_replay_arg_t zr;
3183 
3184 	if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
3185 		zil_destroy(zilog, B_TRUE);
3186 		return;
3187 	}
3188 
3189 	zr.zr_replay = replay_func;
3190 	zr.zr_arg = arg;
3191 	zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
3192 	zr.zr_lr = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
3193 
3194 	/*
3195 	 * Wait for in-progress removes to sync before starting replay.
3196 	 */
3197 	txg_wait_synced(zilog->zl_dmu_pool, 0);
3198 
3199 	zilog->zl_replay = B_TRUE;
3200 	zilog->zl_replay_time = ddi_get_lbolt();
3201 	ASSERT(zilog->zl_replay_blks == 0);
3202 	(void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
3203 	    zh->zh_claim_txg);
3204 	kmem_free(zr.zr_lr, 2 * SPA_MAXBLOCKSIZE);
3205 
3206 	zil_destroy(zilog, B_FALSE);
3207 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
3208 	zilog->zl_replay = B_FALSE;
3209 }
3210 
3211 boolean_t
3212 zil_replaying(zilog_t *zilog, dmu_tx_t *tx)
3213 {
3214 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
3215 		return (B_TRUE);
3216 
3217 	if (zilog->zl_replay) {
3218 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
3219 		zilog->zl_replayed_seq[dmu_tx_get_txg(tx) & TXG_MASK] =
3220 		    zilog->zl_replaying_seq;
3221 		return (B_TRUE);
3222 	}
3223 
3224 	return (B_FALSE);
3225 }
3226 
3227 /* ARGSUSED */
3228 int
3229 zil_reset(const char *osname, void *arg)
3230 {
3231 	int error;
3232 
3233 	error = zil_suspend(osname, NULL);
3234 	if (error != 0)
3235 		return (SET_ERROR(EEXIST));
3236 	return (0);
3237 }
3238