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