xref: /illumos-gate/usr/src/uts/common/fs/zfs/zil.c (revision 598f4ceed9327d2d6c2325dd67cae3aa06f7fea6)
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) 2013 by Delphix. All rights reserved.
24  */
25 
26 /* Portions Copyright 2010 Robert Milkowski */
27 
28 #include <sys/zfs_context.h>
29 #include <sys/spa.h>
30 #include <sys/dmu.h>
31 #include <sys/zap.h>
32 #include <sys/arc.h>
33 #include <sys/stat.h>
34 #include <sys/resource.h>
35 #include <sys/zil.h>
36 #include <sys/zil_impl.h>
37 #include <sys/dsl_dataset.h>
38 #include <sys/vdev_impl.h>
39 #include <sys/dmu_tx.h>
40 #include <sys/dsl_pool.h>
41 
42 /*
43  * The zfs intent log (ZIL) saves transaction records of system calls
44  * that change the file system in memory with enough information
45  * to be able to replay them. These are stored in memory until
46  * either the DMU transaction group (txg) commits them to the stable pool
47  * and they can be discarded, or they are flushed to the stable log
48  * (also in the pool) due to a fsync, O_DSYNC or other synchronous
49  * requirement. In the event of a panic or power fail then those log
50  * records (transactions) are replayed.
51  *
52  * There is one ZIL per file system. Its on-disk (pool) format consists
53  * of 3 parts:
54  *
55  * 	- ZIL header
56  * 	- ZIL blocks
57  * 	- ZIL records
58  *
59  * A log record holds a system call transaction. Log blocks can
60  * hold many log records and the blocks are chained together.
61  * Each ZIL block contains a block pointer (blkptr_t) to the next
62  * ZIL block in the chain. The ZIL header points to the first
63  * block in the chain. Note there is not a fixed place in the pool
64  * to hold blocks. They are dynamically allocated and freed as
65  * needed from the blocks available. Figure X shows the ZIL structure:
66  */
67 
68 /*
69  * Disable intent logging replay.  This global ZIL switch affects all pools.
70  */
71 int zil_replay_disable = 0;
72 
73 /*
74  * Tunable parameter for debugging or performance analysis.  Setting
75  * zfs_nocacheflush will cause corruption on power loss if a volatile
76  * out-of-order write cache is enabled.
77  */
78 boolean_t zfs_nocacheflush = B_FALSE;
79 
80 static kmem_cache_t *zil_lwb_cache;
81 
82 static void zil_async_to_sync(zilog_t *zilog, uint64_t foid);
83 
84 #define	LWB_EMPTY(lwb) ((BP_GET_LSIZE(&lwb->lwb_blk) - \
85     sizeof (zil_chain_t)) == (lwb->lwb_sz - lwb->lwb_nused))
86 
87 
88 /*
89  * ziltest is by and large an ugly hack, but very useful in
90  * checking replay without tedious work.
91  * When running ziltest we want to keep all itx's and so maintain
92  * a single list in the zl_itxg[] that uses a high txg: ZILTEST_TXG
93  * We subtract TXG_CONCURRENT_STATES to allow for common code.
94  */
95 #define	ZILTEST_TXG (UINT64_MAX - TXG_CONCURRENT_STATES)
96 
97 static int
98 zil_bp_compare(const void *x1, const void *x2)
99 {
100 	const dva_t *dva1 = &((zil_bp_node_t *)x1)->zn_dva;
101 	const dva_t *dva2 = &((zil_bp_node_t *)x2)->zn_dva;
102 
103 	if (DVA_GET_VDEV(dva1) < DVA_GET_VDEV(dva2))
104 		return (-1);
105 	if (DVA_GET_VDEV(dva1) > DVA_GET_VDEV(dva2))
106 		return (1);
107 
108 	if (DVA_GET_OFFSET(dva1) < DVA_GET_OFFSET(dva2))
109 		return (-1);
110 	if (DVA_GET_OFFSET(dva1) > DVA_GET_OFFSET(dva2))
111 		return (1);
112 
113 	return (0);
114 }
115 
116 static void
117 zil_bp_tree_init(zilog_t *zilog)
118 {
119 	avl_create(&zilog->zl_bp_tree, zil_bp_compare,
120 	    sizeof (zil_bp_node_t), offsetof(zil_bp_node_t, zn_node));
121 }
122 
123 static void
124 zil_bp_tree_fini(zilog_t *zilog)
125 {
126 	avl_tree_t *t = &zilog->zl_bp_tree;
127 	zil_bp_node_t *zn;
128 	void *cookie = NULL;
129 
130 	while ((zn = avl_destroy_nodes(t, &cookie)) != NULL)
131 		kmem_free(zn, sizeof (zil_bp_node_t));
132 
133 	avl_destroy(t);
134 }
135 
136 int
137 zil_bp_tree_add(zilog_t *zilog, const blkptr_t *bp)
138 {
139 	avl_tree_t *t = &zilog->zl_bp_tree;
140 	const dva_t *dva = BP_IDENTITY(bp);
141 	zil_bp_node_t *zn;
142 	avl_index_t where;
143 
144 	if (avl_find(t, dva, &where) != NULL)
145 		return (SET_ERROR(EEXIST));
146 
147 	zn = kmem_alloc(sizeof (zil_bp_node_t), KM_SLEEP);
148 	zn->zn_dva = *dva;
149 	avl_insert(t, zn, where);
150 
151 	return (0);
152 }
153 
154 static zil_header_t *
155 zil_header_in_syncing_context(zilog_t *zilog)
156 {
157 	return ((zil_header_t *)zilog->zl_header);
158 }
159 
160 static void
161 zil_init_log_chain(zilog_t *zilog, blkptr_t *bp)
162 {
163 	zio_cksum_t *zc = &bp->blk_cksum;
164 
165 	zc->zc_word[ZIL_ZC_GUID_0] = spa_get_random(-1ULL);
166 	zc->zc_word[ZIL_ZC_GUID_1] = spa_get_random(-1ULL);
167 	zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os);
168 	zc->zc_word[ZIL_ZC_SEQ] = 1ULL;
169 }
170 
171 /*
172  * Read a log block and make sure it's valid.
173  */
174 static int
175 zil_read_log_block(zilog_t *zilog, const blkptr_t *bp, blkptr_t *nbp, void *dst,
176     char **end)
177 {
178 	enum zio_flag zio_flags = ZIO_FLAG_CANFAIL;
179 	uint32_t aflags = ARC_WAIT;
180 	arc_buf_t *abuf = NULL;
181 	zbookmark_t zb;
182 	int error;
183 
184 	if (zilog->zl_header->zh_claim_txg == 0)
185 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
186 
187 	if (!(zilog->zl_header->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
188 		zio_flags |= ZIO_FLAG_SPECULATIVE;
189 
190 	SET_BOOKMARK(&zb, bp->blk_cksum.zc_word[ZIL_ZC_OBJSET],
191 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
192 
193 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
194 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
195 
196 	if (error == 0) {
197 		zio_cksum_t cksum = bp->blk_cksum;
198 
199 		/*
200 		 * Validate the checksummed log block.
201 		 *
202 		 * Sequence numbers should be... sequential.  The checksum
203 		 * verifier for the next block should be bp's checksum plus 1.
204 		 *
205 		 * Also check the log chain linkage and size used.
206 		 */
207 		cksum.zc_word[ZIL_ZC_SEQ]++;
208 
209 		if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) {
210 			zil_chain_t *zilc = abuf->b_data;
211 			char *lr = (char *)(zilc + 1);
212 			uint64_t len = zilc->zc_nused - sizeof (zil_chain_t);
213 
214 			if (bcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
215 			    sizeof (cksum)) || BP_IS_HOLE(&zilc->zc_next_blk)) {
216 				error = SET_ERROR(ECKSUM);
217 			} else {
218 				bcopy(lr, dst, len);
219 				*end = (char *)dst + len;
220 				*nbp = zilc->zc_next_blk;
221 			}
222 		} else {
223 			char *lr = abuf->b_data;
224 			uint64_t size = BP_GET_LSIZE(bp);
225 			zil_chain_t *zilc = (zil_chain_t *)(lr + size) - 1;
226 
227 			if (bcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
228 			    sizeof (cksum)) || BP_IS_HOLE(&zilc->zc_next_blk) ||
229 			    (zilc->zc_nused > (size - sizeof (*zilc)))) {
230 				error = SET_ERROR(ECKSUM);
231 			} else {
232 				bcopy(lr, dst, zilc->zc_nused);
233 				*end = (char *)dst + zilc->zc_nused;
234 				*nbp = zilc->zc_next_blk;
235 			}
236 		}
237 
238 		VERIFY(arc_buf_remove_ref(abuf, &abuf));
239 	}
240 
241 	return (error);
242 }
243 
244 /*
245  * Read a TX_WRITE log data block.
246  */
247 static int
248 zil_read_log_data(zilog_t *zilog, const lr_write_t *lr, void *wbuf)
249 {
250 	enum zio_flag zio_flags = ZIO_FLAG_CANFAIL;
251 	const blkptr_t *bp = &lr->lr_blkptr;
252 	uint32_t aflags = ARC_WAIT;
253 	arc_buf_t *abuf = NULL;
254 	zbookmark_t zb;
255 	int error;
256 
257 	if (BP_IS_HOLE(bp)) {
258 		if (wbuf != NULL)
259 			bzero(wbuf, MAX(BP_GET_LSIZE(bp), lr->lr_length));
260 		return (0);
261 	}
262 
263 	if (zilog->zl_header->zh_claim_txg == 0)
264 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
265 
266 	SET_BOOKMARK(&zb, dmu_objset_id(zilog->zl_os), lr->lr_foid,
267 	    ZB_ZIL_LEVEL, lr->lr_offset / BP_GET_LSIZE(bp));
268 
269 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
270 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
271 
272 	if (error == 0) {
273 		if (wbuf != NULL)
274 			bcopy(abuf->b_data, wbuf, arc_buf_size(abuf));
275 		(void) arc_buf_remove_ref(abuf, &abuf);
276 	}
277 
278 	return (error);
279 }
280 
281 /*
282  * Parse the intent log, and call parse_func for each valid record within.
283  */
284 int
285 zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func,
286     zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg)
287 {
288 	const zil_header_t *zh = zilog->zl_header;
289 	boolean_t claimed = !!zh->zh_claim_txg;
290 	uint64_t claim_blk_seq = claimed ? zh->zh_claim_blk_seq : UINT64_MAX;
291 	uint64_t claim_lr_seq = claimed ? zh->zh_claim_lr_seq : UINT64_MAX;
292 	uint64_t max_blk_seq = 0;
293 	uint64_t max_lr_seq = 0;
294 	uint64_t blk_count = 0;
295 	uint64_t lr_count = 0;
296 	blkptr_t blk, next_blk;
297 	char *lrbuf, *lrp;
298 	int error = 0;
299 
300 	/*
301 	 * Old logs didn't record the maximum zh_claim_lr_seq.
302 	 */
303 	if (!(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
304 		claim_lr_seq = UINT64_MAX;
305 
306 	/*
307 	 * Starting at the block pointed to by zh_log we read the log chain.
308 	 * For each block in the chain we strongly check that block to
309 	 * ensure its validity.  We stop when an invalid block is found.
310 	 * For each block pointer in the chain we call parse_blk_func().
311 	 * For each record in each valid block we call parse_lr_func().
312 	 * If the log has been claimed, stop if we encounter a sequence
313 	 * number greater than the highest claimed sequence number.
314 	 */
315 	lrbuf = zio_buf_alloc(SPA_MAXBLOCKSIZE);
316 	zil_bp_tree_init(zilog);
317 
318 	for (blk = zh->zh_log; !BP_IS_HOLE(&blk); blk = next_blk) {
319 		uint64_t blk_seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
320 		int reclen;
321 		char *end;
322 
323 		if (blk_seq > claim_blk_seq)
324 			break;
325 		if ((error = parse_blk_func(zilog, &blk, arg, txg)) != 0)
326 			break;
327 		ASSERT3U(max_blk_seq, <, blk_seq);
328 		max_blk_seq = blk_seq;
329 		blk_count++;
330 
331 		if (max_lr_seq == claim_lr_seq && max_blk_seq == claim_blk_seq)
332 			break;
333 
334 		error = zil_read_log_block(zilog, &blk, &next_blk, lrbuf, &end);
335 		if (error != 0)
336 			break;
337 
338 		for (lrp = lrbuf; lrp < end; lrp += reclen) {
339 			lr_t *lr = (lr_t *)lrp;
340 			reclen = lr->lrc_reclen;
341 			ASSERT3U(reclen, >=, sizeof (lr_t));
342 			if (lr->lrc_seq > claim_lr_seq)
343 				goto done;
344 			if ((error = parse_lr_func(zilog, lr, arg, txg)) != 0)
345 				goto done;
346 			ASSERT3U(max_lr_seq, <, lr->lrc_seq);
347 			max_lr_seq = lr->lrc_seq;
348 			lr_count++;
349 		}
350 	}
351 done:
352 	zilog->zl_parse_error = error;
353 	zilog->zl_parse_blk_seq = max_blk_seq;
354 	zilog->zl_parse_lr_seq = max_lr_seq;
355 	zilog->zl_parse_blk_count = blk_count;
356 	zilog->zl_parse_lr_count = lr_count;
357 
358 	ASSERT(!claimed || !(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID) ||
359 	    (max_blk_seq == claim_blk_seq && max_lr_seq == claim_lr_seq));
360 
361 	zil_bp_tree_fini(zilog);
362 	zio_buf_free(lrbuf, SPA_MAXBLOCKSIZE);
363 
364 	return (error);
365 }
366 
367 static int
368 zil_claim_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t first_txg)
369 {
370 	/*
371 	 * Claim log block if not already committed and not already claimed.
372 	 * If tx == NULL, just verify that the block is claimable.
373 	 */
374 	if (BP_IS_HOLE(bp) || bp->blk_birth < first_txg ||
375 	    zil_bp_tree_add(zilog, bp) != 0)
376 		return (0);
377 
378 	return (zio_wait(zio_claim(NULL, zilog->zl_spa,
379 	    tx == NULL ? 0 : first_txg, bp, spa_claim_notify, NULL,
380 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB)));
381 }
382 
383 static int
384 zil_claim_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg)
385 {
386 	lr_write_t *lr = (lr_write_t *)lrc;
387 	int error;
388 
389 	if (lrc->lrc_txtype != TX_WRITE)
390 		return (0);
391 
392 	/*
393 	 * If the block is not readable, don't claim it.  This can happen
394 	 * in normal operation when a log block is written to disk before
395 	 * some of the dmu_sync() blocks it points to.  In this case, the
396 	 * transaction cannot have been committed to anyone (we would have
397 	 * waited for all writes to be stable first), so it is semantically
398 	 * correct to declare this the end of the log.
399 	 */
400 	if (lr->lr_blkptr.blk_birth >= first_txg &&
401 	    (error = zil_read_log_data(zilog, lr, NULL)) != 0)
402 		return (error);
403 	return (zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg));
404 }
405 
406 /* ARGSUSED */
407 static int
408 zil_free_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t claim_txg)
409 {
410 	zio_free_zil(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
411 
412 	return (0);
413 }
414 
415 static int
416 zil_free_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t claim_txg)
417 {
418 	lr_write_t *lr = (lr_write_t *)lrc;
419 	blkptr_t *bp = &lr->lr_blkptr;
420 
421 	/*
422 	 * If we previously claimed it, we need to free it.
423 	 */
424 	if (claim_txg != 0 && lrc->lrc_txtype == TX_WRITE &&
425 	    bp->blk_birth >= claim_txg && zil_bp_tree_add(zilog, bp) == 0 &&
426 	    !BP_IS_HOLE(bp))
427 		zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
428 
429 	return (0);
430 }
431 
432 static lwb_t *
433 zil_alloc_lwb(zilog_t *zilog, blkptr_t *bp, uint64_t txg)
434 {
435 	lwb_t *lwb;
436 
437 	lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
438 	lwb->lwb_zilog = zilog;
439 	lwb->lwb_blk = *bp;
440 	lwb->lwb_buf = zio_buf_alloc(BP_GET_LSIZE(bp));
441 	lwb->lwb_max_txg = txg;
442 	lwb->lwb_zio = NULL;
443 	lwb->lwb_tx = NULL;
444 	if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) {
445 		lwb->lwb_nused = sizeof (zil_chain_t);
446 		lwb->lwb_sz = BP_GET_LSIZE(bp);
447 	} else {
448 		lwb->lwb_nused = 0;
449 		lwb->lwb_sz = BP_GET_LSIZE(bp) - sizeof (zil_chain_t);
450 	}
451 
452 	mutex_enter(&zilog->zl_lock);
453 	list_insert_tail(&zilog->zl_lwb_list, lwb);
454 	mutex_exit(&zilog->zl_lock);
455 
456 	return (lwb);
457 }
458 
459 /*
460  * Called when we create in-memory log transactions so that we know
461  * to cleanup the itxs at the end of spa_sync().
462  */
463 void
464 zilog_dirty(zilog_t *zilog, uint64_t txg)
465 {
466 	dsl_pool_t *dp = zilog->zl_dmu_pool;
467 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
468 
469 	if (dsl_dataset_is_snapshot(ds))
470 		panic("dirtying snapshot!");
471 
472 	if (txg_list_add(&dp->dp_dirty_zilogs, zilog, txg)) {
473 		/* up the hold count until we can be written out */
474 		dmu_buf_add_ref(ds->ds_dbuf, zilog);
475 	}
476 }
477 
478 boolean_t
479 zilog_is_dirty(zilog_t *zilog)
480 {
481 	dsl_pool_t *dp = zilog->zl_dmu_pool;
482 
483 	for (int t = 0; t < TXG_SIZE; t++) {
484 		if (txg_list_member(&dp->dp_dirty_zilogs, zilog, t))
485 			return (B_TRUE);
486 	}
487 	return (B_FALSE);
488 }
489 
490 /*
491  * Create an on-disk intent log.
492  */
493 static lwb_t *
494 zil_create(zilog_t *zilog)
495 {
496 	const zil_header_t *zh = zilog->zl_header;
497 	lwb_t *lwb = NULL;
498 	uint64_t txg = 0;
499 	dmu_tx_t *tx = NULL;
500 	blkptr_t blk;
501 	int error = 0;
502 
503 	/*
504 	 * Wait for any previous destroy to complete.
505 	 */
506 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
507 
508 	ASSERT(zh->zh_claim_txg == 0);
509 	ASSERT(zh->zh_replay_seq == 0);
510 
511 	blk = zh->zh_log;
512 
513 	/*
514 	 * Allocate an initial log block if:
515 	 *    - there isn't one already
516 	 *    - the existing block is the wrong endianess
517 	 */
518 	if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) {
519 		tx = dmu_tx_create(zilog->zl_os);
520 		VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
521 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
522 		txg = dmu_tx_get_txg(tx);
523 
524 		if (!BP_IS_HOLE(&blk)) {
525 			zio_free_zil(zilog->zl_spa, txg, &blk);
526 			BP_ZERO(&blk);
527 		}
528 
529 		error = zio_alloc_zil(zilog->zl_spa, txg, &blk, NULL,
530 		    ZIL_MIN_BLKSZ, zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
531 
532 		if (error == 0)
533 			zil_init_log_chain(zilog, &blk);
534 	}
535 
536 	/*
537 	 * Allocate a log write buffer (lwb) for the first log block.
538 	 */
539 	if (error == 0)
540 		lwb = zil_alloc_lwb(zilog, &blk, txg);
541 
542 	/*
543 	 * If we just allocated the first log block, commit our transaction
544 	 * and wait for zil_sync() to stuff the block poiner into zh_log.
545 	 * (zh is part of the MOS, so we cannot modify it in open context.)
546 	 */
547 	if (tx != NULL) {
548 		dmu_tx_commit(tx);
549 		txg_wait_synced(zilog->zl_dmu_pool, txg);
550 	}
551 
552 	ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
553 
554 	return (lwb);
555 }
556 
557 /*
558  * In one tx, free all log blocks and clear the log header.
559  * If keep_first is set, then we're replaying a log with no content.
560  * We want to keep the first block, however, so that the first
561  * synchronous transaction doesn't require a txg_wait_synced()
562  * in zil_create().  We don't need to txg_wait_synced() here either
563  * when keep_first is set, because both zil_create() and zil_destroy()
564  * will wait for any in-progress destroys to complete.
565  */
566 void
567 zil_destroy(zilog_t *zilog, boolean_t keep_first)
568 {
569 	const zil_header_t *zh = zilog->zl_header;
570 	lwb_t *lwb;
571 	dmu_tx_t *tx;
572 	uint64_t txg;
573 
574 	/*
575 	 * Wait for any previous destroy to complete.
576 	 */
577 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
578 
579 	zilog->zl_old_header = *zh;		/* debugging aid */
580 
581 	if (BP_IS_HOLE(&zh->zh_log))
582 		return;
583 
584 	tx = dmu_tx_create(zilog->zl_os);
585 	VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
586 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
587 	txg = dmu_tx_get_txg(tx);
588 
589 	mutex_enter(&zilog->zl_lock);
590 
591 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
592 	zilog->zl_destroy_txg = txg;
593 	zilog->zl_keep_first = keep_first;
594 
595 	if (!list_is_empty(&zilog->zl_lwb_list)) {
596 		ASSERT(zh->zh_claim_txg == 0);
597 		VERIFY(!keep_first);
598 		while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
599 			list_remove(&zilog->zl_lwb_list, lwb);
600 			if (lwb->lwb_buf != NULL)
601 				zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
602 			zio_free_zil(zilog->zl_spa, txg, &lwb->lwb_blk);
603 			kmem_cache_free(zil_lwb_cache, lwb);
604 		}
605 	} else if (!keep_first) {
606 		zil_destroy_sync(zilog, tx);
607 	}
608 	mutex_exit(&zilog->zl_lock);
609 
610 	dmu_tx_commit(tx);
611 }
612 
613 void
614 zil_destroy_sync(zilog_t *zilog, dmu_tx_t *tx)
615 {
616 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
617 	(void) zil_parse(zilog, zil_free_log_block,
618 	    zil_free_log_record, tx, zilog->zl_header->zh_claim_txg);
619 }
620 
621 int
622 zil_claim(const char *osname, void *txarg)
623 {
624 	dmu_tx_t *tx = txarg;
625 	uint64_t first_txg = dmu_tx_get_txg(tx);
626 	zilog_t *zilog;
627 	zil_header_t *zh;
628 	objset_t *os;
629 	int error;
630 
631 	error = dmu_objset_own(osname, DMU_OST_ANY, B_FALSE, FTAG, &os);
632 	if (error != 0) {
633 		cmn_err(CE_WARN, "can't open objset for %s", osname);
634 		return (0);
635 	}
636 
637 	zilog = dmu_objset_zil(os);
638 	zh = zil_header_in_syncing_context(zilog);
639 
640 	if (spa_get_log_state(zilog->zl_spa) == SPA_LOG_CLEAR) {
641 		if (!BP_IS_HOLE(&zh->zh_log))
642 			zio_free_zil(zilog->zl_spa, first_txg, &zh->zh_log);
643 		BP_ZERO(&zh->zh_log);
644 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
645 		dmu_objset_disown(os, FTAG);
646 		return (0);
647 	}
648 
649 	/*
650 	 * Claim all log blocks if we haven't already done so, and remember
651 	 * the highest claimed sequence number.  This ensures that if we can
652 	 * read only part of the log now (e.g. due to a missing device),
653 	 * but we can read the entire log later, we will not try to replay
654 	 * or destroy beyond the last block we successfully claimed.
655 	 */
656 	ASSERT3U(zh->zh_claim_txg, <=, first_txg);
657 	if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
658 		(void) zil_parse(zilog, zil_claim_log_block,
659 		    zil_claim_log_record, tx, first_txg);
660 		zh->zh_claim_txg = first_txg;
661 		zh->zh_claim_blk_seq = zilog->zl_parse_blk_seq;
662 		zh->zh_claim_lr_seq = zilog->zl_parse_lr_seq;
663 		if (zilog->zl_parse_lr_count || zilog->zl_parse_blk_count > 1)
664 			zh->zh_flags |= ZIL_REPLAY_NEEDED;
665 		zh->zh_flags |= ZIL_CLAIM_LR_SEQ_VALID;
666 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
667 	}
668 
669 	ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
670 	dmu_objset_disown(os, FTAG);
671 	return (0);
672 }
673 
674 /*
675  * Check the log by walking the log chain.
676  * Checksum errors are ok as they indicate the end of the chain.
677  * Any other error (no device or read failure) returns an error.
678  */
679 int
680 zil_check_log_chain(const char *osname, void *tx)
681 {
682 	zilog_t *zilog;
683 	objset_t *os;
684 	blkptr_t *bp;
685 	int error;
686 
687 	ASSERT(tx == NULL);
688 
689 	error = dmu_objset_hold(osname, FTAG, &os);
690 	if (error != 0) {
691 		cmn_err(CE_WARN, "can't open objset for %s", osname);
692 		return (0);
693 	}
694 
695 	zilog = dmu_objset_zil(os);
696 	bp = (blkptr_t *)&zilog->zl_header->zh_log;
697 
698 	/*
699 	 * Check the first block and determine if it's on a log device
700 	 * which may have been removed or faulted prior to loading this
701 	 * pool.  If so, there's no point in checking the rest of the log
702 	 * as its content should have already been synced to the pool.
703 	 */
704 	if (!BP_IS_HOLE(bp)) {
705 		vdev_t *vd;
706 		boolean_t valid = B_TRUE;
707 
708 		spa_config_enter(os->os_spa, SCL_STATE, FTAG, RW_READER);
709 		vd = vdev_lookup_top(os->os_spa, DVA_GET_VDEV(&bp->blk_dva[0]));
710 		if (vd->vdev_islog && vdev_is_dead(vd))
711 			valid = vdev_log_state_valid(vd);
712 		spa_config_exit(os->os_spa, SCL_STATE, FTAG);
713 
714 		if (!valid) {
715 			dmu_objset_rele(os, FTAG);
716 			return (0);
717 		}
718 	}
719 
720 	/*
721 	 * Because tx == NULL, zil_claim_log_block() will not actually claim
722 	 * any blocks, but just determine whether it is possible to do so.
723 	 * In addition to checking the log chain, zil_claim_log_block()
724 	 * will invoke zio_claim() with a done func of spa_claim_notify(),
725 	 * which will update spa_max_claim_txg.  See spa_load() for details.
726 	 */
727 	error = zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx,
728 	    zilog->zl_header->zh_claim_txg ? -1ULL : spa_first_txg(os->os_spa));
729 
730 	dmu_objset_rele(os, FTAG);
731 
732 	return ((error == ECKSUM || error == ENOENT) ? 0 : error);
733 }
734 
735 static int
736 zil_vdev_compare(const void *x1, const void *x2)
737 {
738 	const uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
739 	const uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
740 
741 	if (v1 < v2)
742 		return (-1);
743 	if (v1 > v2)
744 		return (1);
745 
746 	return (0);
747 }
748 
749 void
750 zil_add_block(zilog_t *zilog, const blkptr_t *bp)
751 {
752 	avl_tree_t *t = &zilog->zl_vdev_tree;
753 	avl_index_t where;
754 	zil_vdev_node_t *zv, zvsearch;
755 	int ndvas = BP_GET_NDVAS(bp);
756 	int i;
757 
758 	if (zfs_nocacheflush)
759 		return;
760 
761 	ASSERT(zilog->zl_writer);
762 
763 	/*
764 	 * Even though we're zl_writer, we still need a lock because the
765 	 * zl_get_data() callbacks may have dmu_sync() done callbacks
766 	 * that will run concurrently.
767 	 */
768 	mutex_enter(&zilog->zl_vdev_lock);
769 	for (i = 0; i < ndvas; i++) {
770 		zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
771 		if (avl_find(t, &zvsearch, &where) == NULL) {
772 			zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
773 			zv->zv_vdev = zvsearch.zv_vdev;
774 			avl_insert(t, zv, where);
775 		}
776 	}
777 	mutex_exit(&zilog->zl_vdev_lock);
778 }
779 
780 static void
781 zil_flush_vdevs(zilog_t *zilog)
782 {
783 	spa_t *spa = zilog->zl_spa;
784 	avl_tree_t *t = &zilog->zl_vdev_tree;
785 	void *cookie = NULL;
786 	zil_vdev_node_t *zv;
787 	zio_t *zio;
788 
789 	ASSERT(zilog->zl_writer);
790 
791 	/*
792 	 * We don't need zl_vdev_lock here because we're the zl_writer,
793 	 * and all zl_get_data() callbacks are done.
794 	 */
795 	if (avl_numnodes(t) == 0)
796 		return;
797 
798 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
799 
800 	zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
801 
802 	while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
803 		vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
804 		if (vd != NULL)
805 			zio_flush(zio, vd);
806 		kmem_free(zv, sizeof (*zv));
807 	}
808 
809 	/*
810 	 * Wait for all the flushes to complete.  Not all devices actually
811 	 * support the DKIOCFLUSHWRITECACHE ioctl, so it's OK if it fails.
812 	 */
813 	(void) zio_wait(zio);
814 
815 	spa_config_exit(spa, SCL_STATE, FTAG);
816 }
817 
818 /*
819  * Function called when a log block write completes
820  */
821 static void
822 zil_lwb_write_done(zio_t *zio)
823 {
824 	lwb_t *lwb = zio->io_private;
825 	zilog_t *zilog = lwb->lwb_zilog;
826 	dmu_tx_t *tx = lwb->lwb_tx;
827 
828 	ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
829 	ASSERT(BP_GET_TYPE(zio->io_bp) == DMU_OT_INTENT_LOG);
830 	ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
831 	ASSERT(BP_GET_BYTEORDER(zio->io_bp) == ZFS_HOST_BYTEORDER);
832 	ASSERT(!BP_IS_GANG(zio->io_bp));
833 	ASSERT(!BP_IS_HOLE(zio->io_bp));
834 	ASSERT(zio->io_bp->blk_fill == 0);
835 
836 	/*
837 	 * Ensure the lwb buffer pointer is cleared before releasing
838 	 * the txg. If we have had an allocation failure and
839 	 * the txg is waiting to sync then we want want zil_sync()
840 	 * to remove the lwb so that it's not picked up as the next new
841 	 * one in zil_commit_writer(). zil_sync() will only remove
842 	 * the lwb if lwb_buf is null.
843 	 */
844 	zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
845 	mutex_enter(&zilog->zl_lock);
846 	lwb->lwb_buf = NULL;
847 	lwb->lwb_tx = NULL;
848 	mutex_exit(&zilog->zl_lock);
849 
850 	/*
851 	 * Now that we've written this log block, we have a stable pointer
852 	 * to the next block in the chain, so it's OK to let the txg in
853 	 * which we allocated the next block sync.
854 	 */
855 	dmu_tx_commit(tx);
856 }
857 
858 /*
859  * Initialize the io for a log block.
860  */
861 static void
862 zil_lwb_write_init(zilog_t *zilog, lwb_t *lwb)
863 {
864 	zbookmark_t zb;
865 
866 	SET_BOOKMARK(&zb, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET],
867 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL,
868 	    lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ]);
869 
870 	if (zilog->zl_root_zio == NULL) {
871 		zilog->zl_root_zio = zio_root(zilog->zl_spa, NULL, NULL,
872 		    ZIO_FLAG_CANFAIL);
873 	}
874 	if (lwb->lwb_zio == NULL) {
875 		lwb->lwb_zio = zio_rewrite(zilog->zl_root_zio, zilog->zl_spa,
876 		    0, &lwb->lwb_blk, lwb->lwb_buf, BP_GET_LSIZE(&lwb->lwb_blk),
877 		    zil_lwb_write_done, lwb, ZIO_PRIORITY_SYNC_WRITE,
878 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE, &zb);
879 	}
880 }
881 
882 /*
883  * Define a limited set of intent log block sizes.
884  *
885  * These must be a multiple of 4KB. Note only the amount used (again
886  * aligned to 4KB) actually gets written. However, we can't always just
887  * allocate SPA_MAXBLOCKSIZE as the slog space could be exhausted.
888  */
889 uint64_t zil_block_buckets[] = {
890     4096,		/* non TX_WRITE */
891     8192+4096,		/* data base */
892     32*1024 + 4096, 	/* NFS writes */
893     UINT64_MAX
894 };
895 
896 /*
897  * Use the slog as long as the logbias is 'latency' and the current commit size
898  * is less than the limit or the total list size is less than 2X the limit.
899  * Limit checking is disabled by setting zil_slog_limit to UINT64_MAX.
900  */
901 uint64_t zil_slog_limit = 1024 * 1024;
902 #define	USE_SLOG(zilog) (((zilog)->zl_logbias == ZFS_LOGBIAS_LATENCY) && \
903 	(((zilog)->zl_cur_used < zil_slog_limit) || \
904 	((zilog)->zl_itx_list_sz < (zil_slog_limit << 1))))
905 
906 /*
907  * Start a log block write and advance to the next log block.
908  * Calls are serialized.
909  */
910 static lwb_t *
911 zil_lwb_write_start(zilog_t *zilog, lwb_t *lwb)
912 {
913 	lwb_t *nlwb = NULL;
914 	zil_chain_t *zilc;
915 	spa_t *spa = zilog->zl_spa;
916 	blkptr_t *bp;
917 	dmu_tx_t *tx;
918 	uint64_t txg;
919 	uint64_t zil_blksz, wsz;
920 	int i, error;
921 
922 	if (BP_GET_CHECKSUM(&lwb->lwb_blk) == ZIO_CHECKSUM_ZILOG2) {
923 		zilc = (zil_chain_t *)lwb->lwb_buf;
924 		bp = &zilc->zc_next_blk;
925 	} else {
926 		zilc = (zil_chain_t *)(lwb->lwb_buf + lwb->lwb_sz);
927 		bp = &zilc->zc_next_blk;
928 	}
929 
930 	ASSERT(lwb->lwb_nused <= lwb->lwb_sz);
931 
932 	/*
933 	 * Allocate the next block and save its address in this block
934 	 * before writing it in order to establish the log chain.
935 	 * Note that if the allocation of nlwb synced before we wrote
936 	 * the block that points at it (lwb), we'd leak it if we crashed.
937 	 * Therefore, we don't do dmu_tx_commit() until zil_lwb_write_done().
938 	 * We dirty the dataset to ensure that zil_sync() will be called
939 	 * to clean up in the event of allocation failure or I/O failure.
940 	 */
941 	tx = dmu_tx_create(zilog->zl_os);
942 	VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
943 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
944 	txg = dmu_tx_get_txg(tx);
945 
946 	lwb->lwb_tx = tx;
947 
948 	/*
949 	 * Log blocks are pre-allocated. Here we select the size of the next
950 	 * block, based on size used in the last block.
951 	 * - first find the smallest bucket that will fit the block from a
952 	 *   limited set of block sizes. This is because it's faster to write
953 	 *   blocks allocated from the same metaslab as they are adjacent or
954 	 *   close.
955 	 * - next find the maximum from the new suggested size and an array of
956 	 *   previous sizes. This lessens a picket fence effect of wrongly
957 	 *   guesssing the size if we have a stream of say 2k, 64k, 2k, 64k
958 	 *   requests.
959 	 *
960 	 * Note we only write what is used, but we can't just allocate
961 	 * the maximum block size because we can exhaust the available
962 	 * pool log space.
963 	 */
964 	zil_blksz = zilog->zl_cur_used + sizeof (zil_chain_t);
965 	for (i = 0; zil_blksz > zil_block_buckets[i]; i++)
966 		continue;
967 	zil_blksz = zil_block_buckets[i];
968 	if (zil_blksz == UINT64_MAX)
969 		zil_blksz = SPA_MAXBLOCKSIZE;
970 	zilog->zl_prev_blks[zilog->zl_prev_rotor] = zil_blksz;
971 	for (i = 0; i < ZIL_PREV_BLKS; i++)
972 		zil_blksz = MAX(zil_blksz, zilog->zl_prev_blks[i]);
973 	zilog->zl_prev_rotor = (zilog->zl_prev_rotor + 1) & (ZIL_PREV_BLKS - 1);
974 
975 	BP_ZERO(bp);
976 	/* pass the old blkptr in order to spread log blocks across devs */
977 	error = zio_alloc_zil(spa, txg, bp, &lwb->lwb_blk, zil_blksz,
978 	    USE_SLOG(zilog));
979 	if (error == 0) {
980 		ASSERT3U(bp->blk_birth, ==, txg);
981 		bp->blk_cksum = lwb->lwb_blk.blk_cksum;
982 		bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
983 
984 		/*
985 		 * Allocate a new log write buffer (lwb).
986 		 */
987 		nlwb = zil_alloc_lwb(zilog, bp, txg);
988 
989 		/* Record the block for later vdev flushing */
990 		zil_add_block(zilog, &lwb->lwb_blk);
991 	}
992 
993 	if (BP_GET_CHECKSUM(&lwb->lwb_blk) == ZIO_CHECKSUM_ZILOG2) {
994 		/* For Slim ZIL only write what is used. */
995 		wsz = P2ROUNDUP_TYPED(lwb->lwb_nused, ZIL_MIN_BLKSZ, uint64_t);
996 		ASSERT3U(wsz, <=, lwb->lwb_sz);
997 		zio_shrink(lwb->lwb_zio, wsz);
998 
999 	} else {
1000 		wsz = lwb->lwb_sz;
1001 	}
1002 
1003 	zilc->zc_pad = 0;
1004 	zilc->zc_nused = lwb->lwb_nused;
1005 	zilc->zc_eck.zec_cksum = lwb->lwb_blk.blk_cksum;
1006 
1007 	/*
1008 	 * clear unused data for security
1009 	 */
1010 	bzero(lwb->lwb_buf + lwb->lwb_nused, wsz - lwb->lwb_nused);
1011 
1012 	zio_nowait(lwb->lwb_zio); /* Kick off the write for the old log block */
1013 
1014 	/*
1015 	 * If there was an allocation failure then nlwb will be null which
1016 	 * forces a txg_wait_synced().
1017 	 */
1018 	return (nlwb);
1019 }
1020 
1021 static lwb_t *
1022 zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb)
1023 {
1024 	lr_t *lrc = &itx->itx_lr; /* common log record */
1025 	lr_write_t *lrw = (lr_write_t *)lrc;
1026 	char *lr_buf;
1027 	uint64_t txg = lrc->lrc_txg;
1028 	uint64_t reclen = lrc->lrc_reclen;
1029 	uint64_t dlen = 0;
1030 
1031 	if (lwb == NULL)
1032 		return (NULL);
1033 
1034 	ASSERT(lwb->lwb_buf != NULL);
1035 	ASSERT(zilog_is_dirty(zilog) ||
1036 	    spa_freeze_txg(zilog->zl_spa) != UINT64_MAX);
1037 
1038 	if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY)
1039 		dlen = P2ROUNDUP_TYPED(
1040 		    lrw->lr_length, sizeof (uint64_t), uint64_t);
1041 
1042 	zilog->zl_cur_used += (reclen + dlen);
1043 
1044 	zil_lwb_write_init(zilog, lwb);
1045 
1046 	/*
1047 	 * If this record won't fit in the current log block, start a new one.
1048 	 */
1049 	if (lwb->lwb_nused + reclen + dlen > lwb->lwb_sz) {
1050 		lwb = zil_lwb_write_start(zilog, lwb);
1051 		if (lwb == NULL)
1052 			return (NULL);
1053 		zil_lwb_write_init(zilog, lwb);
1054 		ASSERT(LWB_EMPTY(lwb));
1055 		if (lwb->lwb_nused + reclen + dlen > lwb->lwb_sz) {
1056 			txg_wait_synced(zilog->zl_dmu_pool, txg);
1057 			return (lwb);
1058 		}
1059 	}
1060 
1061 	lr_buf = lwb->lwb_buf + lwb->lwb_nused;
1062 	bcopy(lrc, lr_buf, reclen);
1063 	lrc = (lr_t *)lr_buf;
1064 	lrw = (lr_write_t *)lrc;
1065 
1066 	/*
1067 	 * If it's a write, fetch the data or get its blkptr as appropriate.
1068 	 */
1069 	if (lrc->lrc_txtype == TX_WRITE) {
1070 		if (txg > spa_freeze_txg(zilog->zl_spa))
1071 			txg_wait_synced(zilog->zl_dmu_pool, txg);
1072 		if (itx->itx_wr_state != WR_COPIED) {
1073 			char *dbuf;
1074 			int error;
1075 
1076 			if (dlen) {
1077 				ASSERT(itx->itx_wr_state == WR_NEED_COPY);
1078 				dbuf = lr_buf + reclen;
1079 				lrw->lr_common.lrc_reclen += dlen;
1080 			} else {
1081 				ASSERT(itx->itx_wr_state == WR_INDIRECT);
1082 				dbuf = NULL;
1083 			}
1084 			error = zilog->zl_get_data(
1085 			    itx->itx_private, lrw, dbuf, lwb->lwb_zio);
1086 			if (error == EIO) {
1087 				txg_wait_synced(zilog->zl_dmu_pool, txg);
1088 				return (lwb);
1089 			}
1090 			if (error != 0) {
1091 				ASSERT(error == ENOENT || error == EEXIST ||
1092 				    error == EALREADY);
1093 				return (lwb);
1094 			}
1095 		}
1096 	}
1097 
1098 	/*
1099 	 * We're actually making an entry, so update lrc_seq to be the
1100 	 * log record sequence number.  Note that this is generally not
1101 	 * equal to the itx sequence number because not all transactions
1102 	 * are synchronous, and sometimes spa_sync() gets there first.
1103 	 */
1104 	lrc->lrc_seq = ++zilog->zl_lr_seq; /* we are single threaded */
1105 	lwb->lwb_nused += reclen + dlen;
1106 	lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
1107 	ASSERT3U(lwb->lwb_nused, <=, lwb->lwb_sz);
1108 	ASSERT0(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)));
1109 
1110 	return (lwb);
1111 }
1112 
1113 itx_t *
1114 zil_itx_create(uint64_t txtype, size_t lrsize)
1115 {
1116 	itx_t *itx;
1117 
1118 	lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t);
1119 
1120 	itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP);
1121 	itx->itx_lr.lrc_txtype = txtype;
1122 	itx->itx_lr.lrc_reclen = lrsize;
1123 	itx->itx_sod = lrsize; /* if write & WR_NEED_COPY will be increased */
1124 	itx->itx_lr.lrc_seq = 0;	/* defensive */
1125 	itx->itx_sync = B_TRUE;		/* default is synchronous */
1126 
1127 	return (itx);
1128 }
1129 
1130 void
1131 zil_itx_destroy(itx_t *itx)
1132 {
1133 	kmem_free(itx, offsetof(itx_t, itx_lr) + itx->itx_lr.lrc_reclen);
1134 }
1135 
1136 /*
1137  * Free up the sync and async itxs. The itxs_t has already been detached
1138  * so no locks are needed.
1139  */
1140 static void
1141 zil_itxg_clean(itxs_t *itxs)
1142 {
1143 	itx_t *itx;
1144 	list_t *list;
1145 	avl_tree_t *t;
1146 	void *cookie;
1147 	itx_async_node_t *ian;
1148 
1149 	list = &itxs->i_sync_list;
1150 	while ((itx = list_head(list)) != NULL) {
1151 		list_remove(list, itx);
1152 		kmem_free(itx, offsetof(itx_t, itx_lr) +
1153 		    itx->itx_lr.lrc_reclen);
1154 	}
1155 
1156 	cookie = NULL;
1157 	t = &itxs->i_async_tree;
1158 	while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
1159 		list = &ian->ia_list;
1160 		while ((itx = list_head(list)) != NULL) {
1161 			list_remove(list, itx);
1162 			kmem_free(itx, offsetof(itx_t, itx_lr) +
1163 			    itx->itx_lr.lrc_reclen);
1164 		}
1165 		list_destroy(list);
1166 		kmem_free(ian, sizeof (itx_async_node_t));
1167 	}
1168 	avl_destroy(t);
1169 
1170 	kmem_free(itxs, sizeof (itxs_t));
1171 }
1172 
1173 static int
1174 zil_aitx_compare(const void *x1, const void *x2)
1175 {
1176 	const uint64_t o1 = ((itx_async_node_t *)x1)->ia_foid;
1177 	const uint64_t o2 = ((itx_async_node_t *)x2)->ia_foid;
1178 
1179 	if (o1 < o2)
1180 		return (-1);
1181 	if (o1 > o2)
1182 		return (1);
1183 
1184 	return (0);
1185 }
1186 
1187 /*
1188  * Remove all async itx with the given oid.
1189  */
1190 static void
1191 zil_remove_async(zilog_t *zilog, uint64_t oid)
1192 {
1193 	uint64_t otxg, txg;
1194 	itx_async_node_t *ian;
1195 	avl_tree_t *t;
1196 	avl_index_t where;
1197 	list_t clean_list;
1198 	itx_t *itx;
1199 
1200 	ASSERT(oid != 0);
1201 	list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
1202 
1203 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
1204 		otxg = ZILTEST_TXG;
1205 	else
1206 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
1207 
1208 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
1209 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
1210 
1211 		mutex_enter(&itxg->itxg_lock);
1212 		if (itxg->itxg_txg != txg) {
1213 			mutex_exit(&itxg->itxg_lock);
1214 			continue;
1215 		}
1216 
1217 		/*
1218 		 * Locate the object node and append its list.
1219 		 */
1220 		t = &itxg->itxg_itxs->i_async_tree;
1221 		ian = avl_find(t, &oid, &where);
1222 		if (ian != NULL)
1223 			list_move_tail(&clean_list, &ian->ia_list);
1224 		mutex_exit(&itxg->itxg_lock);
1225 	}
1226 	while ((itx = list_head(&clean_list)) != NULL) {
1227 		list_remove(&clean_list, itx);
1228 		kmem_free(itx, offsetof(itx_t, itx_lr) +
1229 		    itx->itx_lr.lrc_reclen);
1230 	}
1231 	list_destroy(&clean_list);
1232 }
1233 
1234 void
1235 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
1236 {
1237 	uint64_t txg;
1238 	itxg_t *itxg;
1239 	itxs_t *itxs, *clean = NULL;
1240 
1241 	/*
1242 	 * Object ids can be re-instantiated in the next txg so
1243 	 * remove any async transactions to avoid future leaks.
1244 	 * This can happen if a fsync occurs on the re-instantiated
1245 	 * object for a WR_INDIRECT or WR_NEED_COPY write, which gets
1246 	 * the new file data and flushes a write record for the old object.
1247 	 */
1248 	if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_REMOVE)
1249 		zil_remove_async(zilog, itx->itx_oid);
1250 
1251 	/*
1252 	 * Ensure the data of a renamed file is committed before the rename.
1253 	 */
1254 	if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_RENAME)
1255 		zil_async_to_sync(zilog, itx->itx_oid);
1256 
1257 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX)
1258 		txg = ZILTEST_TXG;
1259 	else
1260 		txg = dmu_tx_get_txg(tx);
1261 
1262 	itxg = &zilog->zl_itxg[txg & TXG_MASK];
1263 	mutex_enter(&itxg->itxg_lock);
1264 	itxs = itxg->itxg_itxs;
1265 	if (itxg->itxg_txg != txg) {
1266 		if (itxs != NULL) {
1267 			/*
1268 			 * The zil_clean callback hasn't got around to cleaning
1269 			 * this itxg. Save the itxs for release below.
1270 			 * This should be rare.
1271 			 */
1272 			atomic_add_64(&zilog->zl_itx_list_sz, -itxg->itxg_sod);
1273 			itxg->itxg_sod = 0;
1274 			clean = itxg->itxg_itxs;
1275 		}
1276 		ASSERT(itxg->itxg_sod == 0);
1277 		itxg->itxg_txg = txg;
1278 		itxs = itxg->itxg_itxs = kmem_zalloc(sizeof (itxs_t), KM_SLEEP);
1279 
1280 		list_create(&itxs->i_sync_list, sizeof (itx_t),
1281 		    offsetof(itx_t, itx_node));
1282 		avl_create(&itxs->i_async_tree, zil_aitx_compare,
1283 		    sizeof (itx_async_node_t),
1284 		    offsetof(itx_async_node_t, ia_node));
1285 	}
1286 	if (itx->itx_sync) {
1287 		list_insert_tail(&itxs->i_sync_list, itx);
1288 		atomic_add_64(&zilog->zl_itx_list_sz, itx->itx_sod);
1289 		itxg->itxg_sod += itx->itx_sod;
1290 	} else {
1291 		avl_tree_t *t = &itxs->i_async_tree;
1292 		uint64_t foid = ((lr_ooo_t *)&itx->itx_lr)->lr_foid;
1293 		itx_async_node_t *ian;
1294 		avl_index_t where;
1295 
1296 		ian = avl_find(t, &foid, &where);
1297 		if (ian == NULL) {
1298 			ian = kmem_alloc(sizeof (itx_async_node_t), KM_SLEEP);
1299 			list_create(&ian->ia_list, sizeof (itx_t),
1300 			    offsetof(itx_t, itx_node));
1301 			ian->ia_foid = foid;
1302 			avl_insert(t, ian, where);
1303 		}
1304 		list_insert_tail(&ian->ia_list, itx);
1305 	}
1306 
1307 	itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
1308 	zilog_dirty(zilog, txg);
1309 	mutex_exit(&itxg->itxg_lock);
1310 
1311 	/* Release the old itxs now we've dropped the lock */
1312 	if (clean != NULL)
1313 		zil_itxg_clean(clean);
1314 }
1315 
1316 /*
1317  * If there are any in-memory intent log transactions which have now been
1318  * synced then start up a taskq to free them. We should only do this after we
1319  * have written out the uberblocks (i.e. txg has been comitted) so that
1320  * don't inadvertently clean out in-memory log records that would be required
1321  * by zil_commit().
1322  */
1323 void
1324 zil_clean(zilog_t *zilog, uint64_t synced_txg)
1325 {
1326 	itxg_t *itxg = &zilog->zl_itxg[synced_txg & TXG_MASK];
1327 	itxs_t *clean_me;
1328 
1329 	mutex_enter(&itxg->itxg_lock);
1330 	if (itxg->itxg_itxs == NULL || itxg->itxg_txg == ZILTEST_TXG) {
1331 		mutex_exit(&itxg->itxg_lock);
1332 		return;
1333 	}
1334 	ASSERT3U(itxg->itxg_txg, <=, synced_txg);
1335 	ASSERT(itxg->itxg_txg != 0);
1336 	ASSERT(zilog->zl_clean_taskq != NULL);
1337 	atomic_add_64(&zilog->zl_itx_list_sz, -itxg->itxg_sod);
1338 	itxg->itxg_sod = 0;
1339 	clean_me = itxg->itxg_itxs;
1340 	itxg->itxg_itxs = NULL;
1341 	itxg->itxg_txg = 0;
1342 	mutex_exit(&itxg->itxg_lock);
1343 	/*
1344 	 * Preferably start a task queue to free up the old itxs but
1345 	 * if taskq_dispatch can't allocate resources to do that then
1346 	 * free it in-line. This should be rare. Note, using TQ_SLEEP
1347 	 * created a bad performance problem.
1348 	 */
1349 	if (taskq_dispatch(zilog->zl_clean_taskq,
1350 	    (void (*)(void *))zil_itxg_clean, clean_me, TQ_NOSLEEP) == NULL)
1351 		zil_itxg_clean(clean_me);
1352 }
1353 
1354 /*
1355  * Get the list of itxs to commit into zl_itx_commit_list.
1356  */
1357 static void
1358 zil_get_commit_list(zilog_t *zilog)
1359 {
1360 	uint64_t otxg, txg;
1361 	list_t *commit_list = &zilog->zl_itx_commit_list;
1362 	uint64_t push_sod = 0;
1363 
1364 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
1365 		otxg = ZILTEST_TXG;
1366 	else
1367 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
1368 
1369 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
1370 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
1371 
1372 		mutex_enter(&itxg->itxg_lock);
1373 		if (itxg->itxg_txg != txg) {
1374 			mutex_exit(&itxg->itxg_lock);
1375 			continue;
1376 		}
1377 
1378 		list_move_tail(commit_list, &itxg->itxg_itxs->i_sync_list);
1379 		push_sod += itxg->itxg_sod;
1380 		itxg->itxg_sod = 0;
1381 
1382 		mutex_exit(&itxg->itxg_lock);
1383 	}
1384 	atomic_add_64(&zilog->zl_itx_list_sz, -push_sod);
1385 }
1386 
1387 /*
1388  * Move the async itxs for a specified object to commit into sync lists.
1389  */
1390 static void
1391 zil_async_to_sync(zilog_t *zilog, uint64_t foid)
1392 {
1393 	uint64_t otxg, txg;
1394 	itx_async_node_t *ian;
1395 	avl_tree_t *t;
1396 	avl_index_t where;
1397 
1398 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
1399 		otxg = ZILTEST_TXG;
1400 	else
1401 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
1402 
1403 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
1404 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
1405 
1406 		mutex_enter(&itxg->itxg_lock);
1407 		if (itxg->itxg_txg != txg) {
1408 			mutex_exit(&itxg->itxg_lock);
1409 			continue;
1410 		}
1411 
1412 		/*
1413 		 * If a foid is specified then find that node and append its
1414 		 * list. Otherwise walk the tree appending all the lists
1415 		 * to the sync list. We add to the end rather than the
1416 		 * beginning to ensure the create has happened.
1417 		 */
1418 		t = &itxg->itxg_itxs->i_async_tree;
1419 		if (foid != 0) {
1420 			ian = avl_find(t, &foid, &where);
1421 			if (ian != NULL) {
1422 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
1423 				    &ian->ia_list);
1424 			}
1425 		} else {
1426 			void *cookie = NULL;
1427 
1428 			while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
1429 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
1430 				    &ian->ia_list);
1431 				list_destroy(&ian->ia_list);
1432 				kmem_free(ian, sizeof (itx_async_node_t));
1433 			}
1434 		}
1435 		mutex_exit(&itxg->itxg_lock);
1436 	}
1437 }
1438 
1439 static void
1440 zil_commit_writer(zilog_t *zilog)
1441 {
1442 	uint64_t txg;
1443 	itx_t *itx;
1444 	lwb_t *lwb;
1445 	spa_t *spa = zilog->zl_spa;
1446 	int error = 0;
1447 
1448 	ASSERT(zilog->zl_root_zio == NULL);
1449 
1450 	mutex_exit(&zilog->zl_lock);
1451 
1452 	zil_get_commit_list(zilog);
1453 
1454 	/*
1455 	 * Return if there's nothing to commit before we dirty the fs by
1456 	 * calling zil_create().
1457 	 */
1458 	if (list_head(&zilog->zl_itx_commit_list) == NULL) {
1459 		mutex_enter(&zilog->zl_lock);
1460 		return;
1461 	}
1462 
1463 	if (zilog->zl_suspend) {
1464 		lwb = NULL;
1465 	} else {
1466 		lwb = list_tail(&zilog->zl_lwb_list);
1467 		if (lwb == NULL)
1468 			lwb = zil_create(zilog);
1469 	}
1470 
1471 	DTRACE_PROBE1(zil__cw1, zilog_t *, zilog);
1472 	while (itx = list_head(&zilog->zl_itx_commit_list)) {
1473 		txg = itx->itx_lr.lrc_txg;
1474 		ASSERT(txg);
1475 
1476 		if (txg > spa_last_synced_txg(spa) || txg > spa_freeze_txg(spa))
1477 			lwb = zil_lwb_commit(zilog, itx, lwb);
1478 		list_remove(&zilog->zl_itx_commit_list, itx);
1479 		kmem_free(itx, offsetof(itx_t, itx_lr)
1480 		    + itx->itx_lr.lrc_reclen);
1481 	}
1482 	DTRACE_PROBE1(zil__cw2, zilog_t *, zilog);
1483 
1484 	/* write the last block out */
1485 	if (lwb != NULL && lwb->lwb_zio != NULL)
1486 		lwb = zil_lwb_write_start(zilog, lwb);
1487 
1488 	zilog->zl_cur_used = 0;
1489 
1490 	/*
1491 	 * Wait if necessary for the log blocks to be on stable storage.
1492 	 */
1493 	if (zilog->zl_root_zio) {
1494 		error = zio_wait(zilog->zl_root_zio);
1495 		zilog->zl_root_zio = NULL;
1496 		zil_flush_vdevs(zilog);
1497 	}
1498 
1499 	if (error || lwb == NULL)
1500 		txg_wait_synced(zilog->zl_dmu_pool, 0);
1501 
1502 	mutex_enter(&zilog->zl_lock);
1503 
1504 	/*
1505 	 * Remember the highest committed log sequence number for ztest.
1506 	 * We only update this value when all the log writes succeeded,
1507 	 * because ztest wants to ASSERT that it got the whole log chain.
1508 	 */
1509 	if (error == 0 && lwb != NULL)
1510 		zilog->zl_commit_lr_seq = zilog->zl_lr_seq;
1511 }
1512 
1513 /*
1514  * Commit zfs transactions to stable storage.
1515  * If foid is 0 push out all transactions, otherwise push only those
1516  * for that object or might reference that object.
1517  *
1518  * itxs are committed in batches. In a heavily stressed zil there will be
1519  * a commit writer thread who is writing out a bunch of itxs to the log
1520  * for a set of committing threads (cthreads) in the same batch as the writer.
1521  * Those cthreads are all waiting on the same cv for that batch.
1522  *
1523  * There will also be a different and growing batch of threads that are
1524  * waiting to commit (qthreads). When the committing batch completes
1525  * a transition occurs such that the cthreads exit and the qthreads become
1526  * cthreads. One of the new cthreads becomes the writer thread for the
1527  * batch. Any new threads arriving become new qthreads.
1528  *
1529  * Only 2 condition variables are needed and there's no transition
1530  * between the two cvs needed. They just flip-flop between qthreads
1531  * and cthreads.
1532  *
1533  * Using this scheme we can efficiently wakeup up only those threads
1534  * that have been committed.
1535  */
1536 void
1537 zil_commit(zilog_t *zilog, uint64_t foid)
1538 {
1539 	uint64_t mybatch;
1540 
1541 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
1542 		return;
1543 
1544 	/* move the async itxs for the foid to the sync queues */
1545 	zil_async_to_sync(zilog, foid);
1546 
1547 	mutex_enter(&zilog->zl_lock);
1548 	mybatch = zilog->zl_next_batch;
1549 	while (zilog->zl_writer) {
1550 		cv_wait(&zilog->zl_cv_batch[mybatch & 1], &zilog->zl_lock);
1551 		if (mybatch <= zilog->zl_com_batch) {
1552 			mutex_exit(&zilog->zl_lock);
1553 			return;
1554 		}
1555 	}
1556 
1557 	zilog->zl_next_batch++;
1558 	zilog->zl_writer = B_TRUE;
1559 	zil_commit_writer(zilog);
1560 	zilog->zl_com_batch = mybatch;
1561 	zilog->zl_writer = B_FALSE;
1562 	mutex_exit(&zilog->zl_lock);
1563 
1564 	/* wake up one thread to become the next writer */
1565 	cv_signal(&zilog->zl_cv_batch[(mybatch+1) & 1]);
1566 
1567 	/* wake up all threads waiting for this batch to be committed */
1568 	cv_broadcast(&zilog->zl_cv_batch[mybatch & 1]);
1569 }
1570 
1571 /*
1572  * Called in syncing context to free committed log blocks and update log header.
1573  */
1574 void
1575 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
1576 {
1577 	zil_header_t *zh = zil_header_in_syncing_context(zilog);
1578 	uint64_t txg = dmu_tx_get_txg(tx);
1579 	spa_t *spa = zilog->zl_spa;
1580 	uint64_t *replayed_seq = &zilog->zl_replayed_seq[txg & TXG_MASK];
1581 	lwb_t *lwb;
1582 
1583 	/*
1584 	 * We don't zero out zl_destroy_txg, so make sure we don't try
1585 	 * to destroy it twice.
1586 	 */
1587 	if (spa_sync_pass(spa) != 1)
1588 		return;
1589 
1590 	mutex_enter(&zilog->zl_lock);
1591 
1592 	ASSERT(zilog->zl_stop_sync == 0);
1593 
1594 	if (*replayed_seq != 0) {
1595 		ASSERT(zh->zh_replay_seq < *replayed_seq);
1596 		zh->zh_replay_seq = *replayed_seq;
1597 		*replayed_seq = 0;
1598 	}
1599 
1600 	if (zilog->zl_destroy_txg == txg) {
1601 		blkptr_t blk = zh->zh_log;
1602 
1603 		ASSERT(list_head(&zilog->zl_lwb_list) == NULL);
1604 
1605 		bzero(zh, sizeof (zil_header_t));
1606 		bzero(zilog->zl_replayed_seq, sizeof (zilog->zl_replayed_seq));
1607 
1608 		if (zilog->zl_keep_first) {
1609 			/*
1610 			 * If this block was part of log chain that couldn't
1611 			 * be claimed because a device was missing during
1612 			 * zil_claim(), but that device later returns,
1613 			 * then this block could erroneously appear valid.
1614 			 * To guard against this, assign a new GUID to the new
1615 			 * log chain so it doesn't matter what blk points to.
1616 			 */
1617 			zil_init_log_chain(zilog, &blk);
1618 			zh->zh_log = blk;
1619 		}
1620 	}
1621 
1622 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
1623 		zh->zh_log = lwb->lwb_blk;
1624 		if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg)
1625 			break;
1626 		list_remove(&zilog->zl_lwb_list, lwb);
1627 		zio_free_zil(spa, txg, &lwb->lwb_blk);
1628 		kmem_cache_free(zil_lwb_cache, lwb);
1629 
1630 		/*
1631 		 * If we don't have anything left in the lwb list then
1632 		 * we've had an allocation failure and we need to zero
1633 		 * out the zil_header blkptr so that we don't end
1634 		 * up freeing the same block twice.
1635 		 */
1636 		if (list_head(&zilog->zl_lwb_list) == NULL)
1637 			BP_ZERO(&zh->zh_log);
1638 	}
1639 	mutex_exit(&zilog->zl_lock);
1640 }
1641 
1642 void
1643 zil_init(void)
1644 {
1645 	zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
1646 	    sizeof (struct lwb), 0, NULL, NULL, NULL, NULL, NULL, 0);
1647 }
1648 
1649 void
1650 zil_fini(void)
1651 {
1652 	kmem_cache_destroy(zil_lwb_cache);
1653 }
1654 
1655 void
1656 zil_set_sync(zilog_t *zilog, uint64_t sync)
1657 {
1658 	zilog->zl_sync = sync;
1659 }
1660 
1661 void
1662 zil_set_logbias(zilog_t *zilog, uint64_t logbias)
1663 {
1664 	zilog->zl_logbias = logbias;
1665 }
1666 
1667 zilog_t *
1668 zil_alloc(objset_t *os, zil_header_t *zh_phys)
1669 {
1670 	zilog_t *zilog;
1671 
1672 	zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
1673 
1674 	zilog->zl_header = zh_phys;
1675 	zilog->zl_os = os;
1676 	zilog->zl_spa = dmu_objset_spa(os);
1677 	zilog->zl_dmu_pool = dmu_objset_pool(os);
1678 	zilog->zl_destroy_txg = TXG_INITIAL - 1;
1679 	zilog->zl_logbias = dmu_objset_logbias(os);
1680 	zilog->zl_sync = dmu_objset_syncprop(os);
1681 	zilog->zl_next_batch = 1;
1682 
1683 	mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
1684 
1685 	for (int i = 0; i < TXG_SIZE; i++) {
1686 		mutex_init(&zilog->zl_itxg[i].itxg_lock, NULL,
1687 		    MUTEX_DEFAULT, NULL);
1688 	}
1689 
1690 	list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
1691 	    offsetof(lwb_t, lwb_node));
1692 
1693 	list_create(&zilog->zl_itx_commit_list, sizeof (itx_t),
1694 	    offsetof(itx_t, itx_node));
1695 
1696 	mutex_init(&zilog->zl_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
1697 
1698 	avl_create(&zilog->zl_vdev_tree, zil_vdev_compare,
1699 	    sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
1700 
1701 	cv_init(&zilog->zl_cv_writer, NULL, CV_DEFAULT, NULL);
1702 	cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
1703 	cv_init(&zilog->zl_cv_batch[0], NULL, CV_DEFAULT, NULL);
1704 	cv_init(&zilog->zl_cv_batch[1], NULL, CV_DEFAULT, NULL);
1705 
1706 	return (zilog);
1707 }
1708 
1709 void
1710 zil_free(zilog_t *zilog)
1711 {
1712 	zilog->zl_stop_sync = 1;
1713 
1714 	ASSERT0(zilog->zl_suspend);
1715 	ASSERT0(zilog->zl_suspending);
1716 
1717 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
1718 	list_destroy(&zilog->zl_lwb_list);
1719 
1720 	avl_destroy(&zilog->zl_vdev_tree);
1721 	mutex_destroy(&zilog->zl_vdev_lock);
1722 
1723 	ASSERT(list_is_empty(&zilog->zl_itx_commit_list));
1724 	list_destroy(&zilog->zl_itx_commit_list);
1725 
1726 	for (int i = 0; i < TXG_SIZE; i++) {
1727 		/*
1728 		 * It's possible for an itx to be generated that doesn't dirty
1729 		 * a txg (e.g. ztest TX_TRUNCATE). So there's no zil_clean()
1730 		 * callback to remove the entry. We remove those here.
1731 		 *
1732 		 * Also free up the ziltest itxs.
1733 		 */
1734 		if (zilog->zl_itxg[i].itxg_itxs)
1735 			zil_itxg_clean(zilog->zl_itxg[i].itxg_itxs);
1736 		mutex_destroy(&zilog->zl_itxg[i].itxg_lock);
1737 	}
1738 
1739 	mutex_destroy(&zilog->zl_lock);
1740 
1741 	cv_destroy(&zilog->zl_cv_writer);
1742 	cv_destroy(&zilog->zl_cv_suspend);
1743 	cv_destroy(&zilog->zl_cv_batch[0]);
1744 	cv_destroy(&zilog->zl_cv_batch[1]);
1745 
1746 	kmem_free(zilog, sizeof (zilog_t));
1747 }
1748 
1749 /*
1750  * Open an intent log.
1751  */
1752 zilog_t *
1753 zil_open(objset_t *os, zil_get_data_t *get_data)
1754 {
1755 	zilog_t *zilog = dmu_objset_zil(os);
1756 
1757 	ASSERT(zilog->zl_clean_taskq == NULL);
1758 	ASSERT(zilog->zl_get_data == NULL);
1759 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
1760 
1761 	zilog->zl_get_data = get_data;
1762 	zilog->zl_clean_taskq = taskq_create("zil_clean", 1, minclsyspri,
1763 	    2, 2, TASKQ_PREPOPULATE);
1764 
1765 	return (zilog);
1766 }
1767 
1768 /*
1769  * Close an intent log.
1770  */
1771 void
1772 zil_close(zilog_t *zilog)
1773 {
1774 	lwb_t *lwb;
1775 	uint64_t txg = 0;
1776 
1777 	zil_commit(zilog, 0); /* commit all itx */
1778 
1779 	/*
1780 	 * The lwb_max_txg for the stubby lwb will reflect the last activity
1781 	 * for the zil.  After a txg_wait_synced() on the txg we know all the
1782 	 * callbacks have occurred that may clean the zil.  Only then can we
1783 	 * destroy the zl_clean_taskq.
1784 	 */
1785 	mutex_enter(&zilog->zl_lock);
1786 	lwb = list_tail(&zilog->zl_lwb_list);
1787 	if (lwb != NULL)
1788 		txg = lwb->lwb_max_txg;
1789 	mutex_exit(&zilog->zl_lock);
1790 	if (txg)
1791 		txg_wait_synced(zilog->zl_dmu_pool, txg);
1792 	ASSERT(!zilog_is_dirty(zilog));
1793 
1794 	taskq_destroy(zilog->zl_clean_taskq);
1795 	zilog->zl_clean_taskq = NULL;
1796 	zilog->zl_get_data = NULL;
1797 
1798 	/*
1799 	 * We should have only one LWB left on the list; remove it now.
1800 	 */
1801 	mutex_enter(&zilog->zl_lock);
1802 	lwb = list_head(&zilog->zl_lwb_list);
1803 	if (lwb != NULL) {
1804 		ASSERT(lwb == list_tail(&zilog->zl_lwb_list));
1805 		list_remove(&zilog->zl_lwb_list, lwb);
1806 		zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1807 		kmem_cache_free(zil_lwb_cache, lwb);
1808 	}
1809 	mutex_exit(&zilog->zl_lock);
1810 }
1811 
1812 static char *suspend_tag = "zil suspending";
1813 
1814 /*
1815  * Suspend an intent log.  While in suspended mode, we still honor
1816  * synchronous semantics, but we rely on txg_wait_synced() to do it.
1817  * On old version pools, we suspend the log briefly when taking a
1818  * snapshot so that it will have an empty intent log.
1819  *
1820  * Long holds are not really intended to be used the way we do here --
1821  * held for such a short time.  A concurrent caller of dsl_dataset_long_held()
1822  * could fail.  Therefore we take pains to only put a long hold if it is
1823  * actually necessary.  Fortunately, it will only be necessary if the
1824  * objset is currently mounted (or the ZVOL equivalent).  In that case it
1825  * will already have a long hold, so we are not really making things any worse.
1826  *
1827  * Ideally, we would locate the existing long-holder (i.e. the zfsvfs_t or
1828  * zvol_state_t), and use their mechanism to prevent their hold from being
1829  * dropped (e.g. VFS_HOLD()).  However, that would be even more pain for
1830  * very little gain.
1831  *
1832  * if cookiep == NULL, this does both the suspend & resume.
1833  * Otherwise, it returns with the dataset "long held", and the cookie
1834  * should be passed into zil_resume().
1835  */
1836 int
1837 zil_suspend(const char *osname, void **cookiep)
1838 {
1839 	objset_t *os;
1840 	zilog_t *zilog;
1841 	const zil_header_t *zh;
1842 	int error;
1843 
1844 	error = dmu_objset_hold(osname, suspend_tag, &os);
1845 	if (error != 0)
1846 		return (error);
1847 	zilog = dmu_objset_zil(os);
1848 
1849 	mutex_enter(&zilog->zl_lock);
1850 	zh = zilog->zl_header;
1851 
1852 	if (zh->zh_flags & ZIL_REPLAY_NEEDED) {		/* unplayed log */
1853 		mutex_exit(&zilog->zl_lock);
1854 		dmu_objset_rele(os, suspend_tag);
1855 		return (SET_ERROR(EBUSY));
1856 	}
1857 
1858 	/*
1859 	 * Don't put a long hold in the cases where we can avoid it.  This
1860 	 * is when there is no cookie so we are doing a suspend & resume
1861 	 * (i.e. called from zil_vdev_offline()), and there's nothing to do
1862 	 * for the suspend because it's already suspended, or there's no ZIL.
1863 	 */
1864 	if (cookiep == NULL && !zilog->zl_suspending &&
1865 	    (zilog->zl_suspend > 0 || BP_IS_HOLE(&zh->zh_log))) {
1866 		mutex_exit(&zilog->zl_lock);
1867 		dmu_objset_rele(os, suspend_tag);
1868 		return (0);
1869 	}
1870 
1871 	dsl_dataset_long_hold(dmu_objset_ds(os), suspend_tag);
1872 	dsl_pool_rele(dmu_objset_pool(os), suspend_tag);
1873 
1874 	zilog->zl_suspend++;
1875 
1876 	if (zilog->zl_suspend > 1) {
1877 		/*
1878 		 * Someone else is already suspending it.
1879 		 * Just wait for them to finish.
1880 		 */
1881 
1882 		while (zilog->zl_suspending)
1883 			cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
1884 		mutex_exit(&zilog->zl_lock);
1885 
1886 		if (cookiep == NULL)
1887 			zil_resume(os);
1888 		else
1889 			*cookiep = os;
1890 		return (0);
1891 	}
1892 
1893 	/*
1894 	 * If there is no pointer to an on-disk block, this ZIL must not
1895 	 * be active (e.g. filesystem not mounted), so there's nothing
1896 	 * to clean up.
1897 	 */
1898 	if (BP_IS_HOLE(&zh->zh_log)) {
1899 		ASSERT(cookiep != NULL); /* fast path already handled */
1900 
1901 		*cookiep = os;
1902 		mutex_exit(&zilog->zl_lock);
1903 		return (0);
1904 	}
1905 
1906 	zilog->zl_suspending = B_TRUE;
1907 	mutex_exit(&zilog->zl_lock);
1908 
1909 	zil_commit(zilog, 0);
1910 
1911 	zil_destroy(zilog, B_FALSE);
1912 
1913 	mutex_enter(&zilog->zl_lock);
1914 	zilog->zl_suspending = B_FALSE;
1915 	cv_broadcast(&zilog->zl_cv_suspend);
1916 	mutex_exit(&zilog->zl_lock);
1917 
1918 	if (cookiep == NULL)
1919 		zil_resume(os);
1920 	else
1921 		*cookiep = os;
1922 	return (0);
1923 }
1924 
1925 void
1926 zil_resume(void *cookie)
1927 {
1928 	objset_t *os = cookie;
1929 	zilog_t *zilog = dmu_objset_zil(os);
1930 
1931 	mutex_enter(&zilog->zl_lock);
1932 	ASSERT(zilog->zl_suspend != 0);
1933 	zilog->zl_suspend--;
1934 	mutex_exit(&zilog->zl_lock);
1935 	dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag);
1936 	dsl_dataset_rele(dmu_objset_ds(os), suspend_tag);
1937 }
1938 
1939 typedef struct zil_replay_arg {
1940 	zil_replay_func_t **zr_replay;
1941 	void		*zr_arg;
1942 	boolean_t	zr_byteswap;
1943 	char		*zr_lr;
1944 } zil_replay_arg_t;
1945 
1946 static int
1947 zil_replay_error(zilog_t *zilog, lr_t *lr, int error)
1948 {
1949 	char name[MAXNAMELEN];
1950 
1951 	zilog->zl_replaying_seq--;	/* didn't actually replay this one */
1952 
1953 	dmu_objset_name(zilog->zl_os, name);
1954 
1955 	cmn_err(CE_WARN, "ZFS replay transaction error %d, "
1956 	    "dataset %s, seq 0x%llx, txtype %llu %s\n", error, name,
1957 	    (u_longlong_t)lr->lrc_seq,
1958 	    (u_longlong_t)(lr->lrc_txtype & ~TX_CI),
1959 	    (lr->lrc_txtype & TX_CI) ? "CI" : "");
1960 
1961 	return (error);
1962 }
1963 
1964 static int
1965 zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg)
1966 {
1967 	zil_replay_arg_t *zr = zra;
1968 	const zil_header_t *zh = zilog->zl_header;
1969 	uint64_t reclen = lr->lrc_reclen;
1970 	uint64_t txtype = lr->lrc_txtype;
1971 	int error = 0;
1972 
1973 	zilog->zl_replaying_seq = lr->lrc_seq;
1974 
1975 	if (lr->lrc_seq <= zh->zh_replay_seq)	/* already replayed */
1976 		return (0);
1977 
1978 	if (lr->lrc_txg < claim_txg)		/* already committed */
1979 		return (0);
1980 
1981 	/* Strip case-insensitive bit, still present in log record */
1982 	txtype &= ~TX_CI;
1983 
1984 	if (txtype == 0 || txtype >= TX_MAX_TYPE)
1985 		return (zil_replay_error(zilog, lr, EINVAL));
1986 
1987 	/*
1988 	 * If this record type can be logged out of order, the object
1989 	 * (lr_foid) may no longer exist.  That's legitimate, not an error.
1990 	 */
1991 	if (TX_OOO(txtype)) {
1992 		error = dmu_object_info(zilog->zl_os,
1993 		    ((lr_ooo_t *)lr)->lr_foid, NULL);
1994 		if (error == ENOENT || error == EEXIST)
1995 			return (0);
1996 	}
1997 
1998 	/*
1999 	 * Make a copy of the data so we can revise and extend it.
2000 	 */
2001 	bcopy(lr, zr->zr_lr, reclen);
2002 
2003 	/*
2004 	 * If this is a TX_WRITE with a blkptr, suck in the data.
2005 	 */
2006 	if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
2007 		error = zil_read_log_data(zilog, (lr_write_t *)lr,
2008 		    zr->zr_lr + reclen);
2009 		if (error != 0)
2010 			return (zil_replay_error(zilog, lr, error));
2011 	}
2012 
2013 	/*
2014 	 * The log block containing this lr may have been byteswapped
2015 	 * so that we can easily examine common fields like lrc_txtype.
2016 	 * However, the log is a mix of different record types, and only the
2017 	 * replay vectors know how to byteswap their records.  Therefore, if
2018 	 * the lr was byteswapped, undo it before invoking the replay vector.
2019 	 */
2020 	if (zr->zr_byteswap)
2021 		byteswap_uint64_array(zr->zr_lr, reclen);
2022 
2023 	/*
2024 	 * We must now do two things atomically: replay this log record,
2025 	 * and update the log header sequence number to reflect the fact that
2026 	 * we did so. At the end of each replay function the sequence number
2027 	 * is updated if we are in replay mode.
2028 	 */
2029 	error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, zr->zr_byteswap);
2030 	if (error != 0) {
2031 		/*
2032 		 * The DMU's dnode layer doesn't see removes until the txg
2033 		 * commits, so a subsequent claim can spuriously fail with
2034 		 * EEXIST. So if we receive any error we try syncing out
2035 		 * any removes then retry the transaction.  Note that we
2036 		 * specify B_FALSE for byteswap now, so we don't do it twice.
2037 		 */
2038 		txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
2039 		error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, B_FALSE);
2040 		if (error != 0)
2041 			return (zil_replay_error(zilog, lr, error));
2042 	}
2043 	return (0);
2044 }
2045 
2046 /* ARGSUSED */
2047 static int
2048 zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
2049 {
2050 	zilog->zl_replay_blks++;
2051 
2052 	return (0);
2053 }
2054 
2055 /*
2056  * If this dataset has a non-empty intent log, replay it and destroy it.
2057  */
2058 void
2059 zil_replay(objset_t *os, void *arg, zil_replay_func_t *replay_func[TX_MAX_TYPE])
2060 {
2061 	zilog_t *zilog = dmu_objset_zil(os);
2062 	const zil_header_t *zh = zilog->zl_header;
2063 	zil_replay_arg_t zr;
2064 
2065 	if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
2066 		zil_destroy(zilog, B_TRUE);
2067 		return;
2068 	}
2069 
2070 	zr.zr_replay = replay_func;
2071 	zr.zr_arg = arg;
2072 	zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
2073 	zr.zr_lr = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
2074 
2075 	/*
2076 	 * Wait for in-progress removes to sync before starting replay.
2077 	 */
2078 	txg_wait_synced(zilog->zl_dmu_pool, 0);
2079 
2080 	zilog->zl_replay = B_TRUE;
2081 	zilog->zl_replay_time = ddi_get_lbolt();
2082 	ASSERT(zilog->zl_replay_blks == 0);
2083 	(void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
2084 	    zh->zh_claim_txg);
2085 	kmem_free(zr.zr_lr, 2 * SPA_MAXBLOCKSIZE);
2086 
2087 	zil_destroy(zilog, B_FALSE);
2088 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
2089 	zilog->zl_replay = B_FALSE;
2090 }
2091 
2092 boolean_t
2093 zil_replaying(zilog_t *zilog, dmu_tx_t *tx)
2094 {
2095 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
2096 		return (B_TRUE);
2097 
2098 	if (zilog->zl_replay) {
2099 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
2100 		zilog->zl_replayed_seq[dmu_tx_get_txg(tx) & TXG_MASK] =
2101 		    zilog->zl_replaying_seq;
2102 		return (B_TRUE);
2103 	}
2104 
2105 	return (B_FALSE);
2106 }
2107 
2108 /* ARGSUSED */
2109 int
2110 zil_vdev_offline(const char *osname, void *arg)
2111 {
2112 	int error;
2113 
2114 	error = zil_suspend(osname, NULL);
2115 	if (error != 0)
2116 		return (SET_ERROR(EEXIST));
2117 	return (0);
2118 }
2119