xref: /titanic_41/usr/src/uts/common/fs/zfs/zil.c (revision d24234c24aeaca4ca56ee3ac2794507968f274c4)
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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/zfs_context.h>
27 #include <sys/spa.h>
28 #include <sys/dmu.h>
29 #include <sys/zap.h>
30 #include <sys/arc.h>
31 #include <sys/stat.h>
32 #include <sys/resource.h>
33 #include <sys/zil.h>
34 #include <sys/zil_impl.h>
35 #include <sys/dsl_dataset.h>
36 #include <sys/vdev.h>
37 #include <sys/dmu_tx.h>
38 
39 /*
40  * The zfs intent log (ZIL) saves transaction records of system calls
41  * that change the file system in memory with enough information
42  * to be able to replay them. These are stored in memory until
43  * either the DMU transaction group (txg) commits them to the stable pool
44  * and they can be discarded, or they are flushed to the stable log
45  * (also in the pool) due to a fsync, O_DSYNC or other synchronous
46  * requirement. In the event of a panic or power fail then those log
47  * records (transactions) are replayed.
48  *
49  * There is one ZIL per file system. Its on-disk (pool) format consists
50  * of 3 parts:
51  *
52  * 	- ZIL header
53  * 	- ZIL blocks
54  * 	- ZIL records
55  *
56  * A log record holds a system call transaction. Log blocks can
57  * hold many log records and the blocks are chained together.
58  * Each ZIL block contains a block pointer (blkptr_t) to the next
59  * ZIL block in the chain. The ZIL header points to the first
60  * block in the chain. Note there is not a fixed place in the pool
61  * to hold blocks. They are dynamically allocated and freed as
62  * needed from the blocks available. Figure X shows the ZIL structure:
63  */
64 
65 /*
66  * This global ZIL switch affects all pools
67  */
68 int zil_disable = 0;	/* disable intent logging */
69 
70 /*
71  * Tunable parameter for debugging or performance analysis.  Setting
72  * zfs_nocacheflush will cause corruption on power loss if a volatile
73  * out-of-order write cache is enabled.
74  */
75 boolean_t zfs_nocacheflush = B_FALSE;
76 
77 static kmem_cache_t *zil_lwb_cache;
78 
79 static boolean_t zil_empty(zilog_t *zilog);
80 
81 static int
82 zil_bp_compare(const void *x1, const void *x2)
83 {
84 	const dva_t *dva1 = &((zil_bp_node_t *)x1)->zn_dva;
85 	const dva_t *dva2 = &((zil_bp_node_t *)x2)->zn_dva;
86 
87 	if (DVA_GET_VDEV(dva1) < DVA_GET_VDEV(dva2))
88 		return (-1);
89 	if (DVA_GET_VDEV(dva1) > DVA_GET_VDEV(dva2))
90 		return (1);
91 
92 	if (DVA_GET_OFFSET(dva1) < DVA_GET_OFFSET(dva2))
93 		return (-1);
94 	if (DVA_GET_OFFSET(dva1) > DVA_GET_OFFSET(dva2))
95 		return (1);
96 
97 	return (0);
98 }
99 
100 static void
101 zil_bp_tree_init(zilog_t *zilog)
102 {
103 	avl_create(&zilog->zl_bp_tree, zil_bp_compare,
104 	    sizeof (zil_bp_node_t), offsetof(zil_bp_node_t, zn_node));
105 }
106 
107 static void
108 zil_bp_tree_fini(zilog_t *zilog)
109 {
110 	avl_tree_t *t = &zilog->zl_bp_tree;
111 	zil_bp_node_t *zn;
112 	void *cookie = NULL;
113 
114 	while ((zn = avl_destroy_nodes(t, &cookie)) != NULL)
115 		kmem_free(zn, sizeof (zil_bp_node_t));
116 
117 	avl_destroy(t);
118 }
119 
120 int
121 zil_bp_tree_add(zilog_t *zilog, const blkptr_t *bp)
122 {
123 	avl_tree_t *t = &zilog->zl_bp_tree;
124 	const dva_t *dva = BP_IDENTITY(bp);
125 	zil_bp_node_t *zn;
126 	avl_index_t where;
127 
128 	if (avl_find(t, dva, &where) != NULL)
129 		return (EEXIST);
130 
131 	zn = kmem_alloc(sizeof (zil_bp_node_t), KM_SLEEP);
132 	zn->zn_dva = *dva;
133 	avl_insert(t, zn, where);
134 
135 	return (0);
136 }
137 
138 static zil_header_t *
139 zil_header_in_syncing_context(zilog_t *zilog)
140 {
141 	return ((zil_header_t *)zilog->zl_header);
142 }
143 
144 static void
145 zil_init_log_chain(zilog_t *zilog, blkptr_t *bp)
146 {
147 	zio_cksum_t *zc = &bp->blk_cksum;
148 
149 	zc->zc_word[ZIL_ZC_GUID_0] = spa_get_random(-1ULL);
150 	zc->zc_word[ZIL_ZC_GUID_1] = spa_get_random(-1ULL);
151 	zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os);
152 	zc->zc_word[ZIL_ZC_SEQ] = 1ULL;
153 }
154 
155 /*
156  * Read a log block and make sure it's valid.
157  */
158 static int
159 zil_read_log_block(zilog_t *zilog, const blkptr_t *bp, blkptr_t *nbp, void *dst)
160 {
161 	enum zio_flag zio_flags = ZIO_FLAG_CANFAIL;
162 	uint32_t aflags = ARC_WAIT;
163 	arc_buf_t *abuf = NULL;
164 	zbookmark_t zb;
165 	int error;
166 
167 	if (zilog->zl_header->zh_claim_txg == 0)
168 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
169 
170 	if (!(zilog->zl_header->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
171 		zio_flags |= ZIO_FLAG_SPECULATIVE;
172 
173 	SET_BOOKMARK(&zb, bp->blk_cksum.zc_word[ZIL_ZC_OBJSET],
174 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
175 
176 	error = arc_read_nolock(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
177 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
178 
179 	if (error == 0) {
180 		char *data = abuf->b_data;
181 		uint64_t size = BP_GET_LSIZE(bp);
182 		zil_trailer_t *ztp = (zil_trailer_t *)(data + size) - 1;
183 		zio_cksum_t cksum = bp->blk_cksum;
184 
185 		bcopy(data, dst, size);
186 		*nbp = ztp->zit_next_blk;
187 
188 		/*
189 		 * Validate the checksummed log block.
190 		 *
191 		 * Sequence numbers should be... sequential.  The checksum
192 		 * verifier for the next block should be bp's checksum plus 1.
193 		 *
194 		 * Also check the log chain linkage and size used.
195 		 */
196 		cksum.zc_word[ZIL_ZC_SEQ]++;
197 
198 		if (bcmp(&cksum, &ztp->zit_next_blk.blk_cksum,
199 		    sizeof (cksum)) || BP_IS_HOLE(&ztp->zit_next_blk) ||
200 		    (ztp->zit_nused > (size - sizeof (zil_trailer_t))))
201 			error = ECKSUM;
202 
203 		VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
204 	}
205 
206 	return (error);
207 }
208 
209 /*
210  * Read a TX_WRITE log data block.
211  */
212 static int
213 zil_read_log_data(zilog_t *zilog, const lr_write_t *lr, void *wbuf)
214 {
215 	enum zio_flag zio_flags = ZIO_FLAG_CANFAIL;
216 	const blkptr_t *bp = &lr->lr_blkptr;
217 	uint32_t aflags = ARC_WAIT;
218 	arc_buf_t *abuf = NULL;
219 	zbookmark_t zb;
220 	int error;
221 
222 	if (BP_IS_HOLE(bp)) {
223 		if (wbuf != NULL)
224 			bzero(wbuf, MAX(BP_GET_LSIZE(bp), lr->lr_length));
225 		return (0);
226 	}
227 
228 	if (zilog->zl_header->zh_claim_txg == 0)
229 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
230 
231 	SET_BOOKMARK(&zb, dmu_objset_id(zilog->zl_os), lr->lr_foid,
232 	    ZB_ZIL_LEVEL, lr->lr_offset / BP_GET_LSIZE(bp));
233 
234 	error = arc_read_nolock(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
235 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
236 
237 	if (error == 0) {
238 		if (wbuf != NULL)
239 			bcopy(abuf->b_data, wbuf, arc_buf_size(abuf));
240 		(void) arc_buf_remove_ref(abuf, &abuf);
241 	}
242 
243 	return (error);
244 }
245 
246 /*
247  * Parse the intent log, and call parse_func for each valid record within.
248  */
249 int
250 zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func,
251     zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg)
252 {
253 	const zil_header_t *zh = zilog->zl_header;
254 	boolean_t claimed = !!zh->zh_claim_txg;
255 	uint64_t claim_blk_seq = claimed ? zh->zh_claim_blk_seq : UINT64_MAX;
256 	uint64_t claim_lr_seq = claimed ? zh->zh_claim_lr_seq : UINT64_MAX;
257 	uint64_t max_blk_seq = 0;
258 	uint64_t max_lr_seq = 0;
259 	uint64_t blk_count = 0;
260 	uint64_t lr_count = 0;
261 	blkptr_t blk, next_blk;
262 	char *lrbuf, *lrp;
263 	int error = 0;
264 
265 	/*
266 	 * Old logs didn't record the maximum zh_claim_lr_seq.
267 	 */
268 	if (!(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
269 		claim_lr_seq = UINT64_MAX;
270 
271 	/*
272 	 * Starting at the block pointed to by zh_log we read the log chain.
273 	 * For each block in the chain we strongly check that block to
274 	 * ensure its validity.  We stop when an invalid block is found.
275 	 * For each block pointer in the chain we call parse_blk_func().
276 	 * For each record in each valid block we call parse_lr_func().
277 	 * If the log has been claimed, stop if we encounter a sequence
278 	 * number greater than the highest claimed sequence number.
279 	 */
280 	lrbuf = zio_buf_alloc(SPA_MAXBLOCKSIZE);
281 	zil_bp_tree_init(zilog);
282 
283 	for (blk = zh->zh_log; !BP_IS_HOLE(&blk); blk = next_blk) {
284 		zil_trailer_t *ztp =
285 		    (zil_trailer_t *)(lrbuf + BP_GET_LSIZE(&blk)) - 1;
286 		uint64_t blk_seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
287 		int reclen;
288 
289 		if (blk_seq > claim_blk_seq)
290 			break;
291 		if ((error = parse_blk_func(zilog, &blk, arg, txg)) != 0)
292 			break;
293 		ASSERT(max_blk_seq < blk_seq);
294 		max_blk_seq = blk_seq;
295 		blk_count++;
296 
297 		if (max_lr_seq == claim_lr_seq && max_blk_seq == claim_blk_seq)
298 			break;
299 
300 		error = zil_read_log_block(zilog, &blk, &next_blk, lrbuf);
301 		if (error)
302 			break;
303 
304 		for (lrp = lrbuf; lrp < lrbuf + ztp->zit_nused; lrp += reclen) {
305 			lr_t *lr = (lr_t *)lrp;
306 			reclen = lr->lrc_reclen;
307 			ASSERT3U(reclen, >=, sizeof (lr_t));
308 			if (lr->lrc_seq > claim_lr_seq)
309 				goto done;
310 			if ((error = parse_lr_func(zilog, lr, arg, txg)) != 0)
311 				goto done;
312 			ASSERT(max_lr_seq < lr->lrc_seq);
313 			max_lr_seq = lr->lrc_seq;
314 			lr_count++;
315 		}
316 	}
317 done:
318 	zilog->zl_parse_error = error;
319 	zilog->zl_parse_blk_seq = max_blk_seq;
320 	zilog->zl_parse_lr_seq = max_lr_seq;
321 	zilog->zl_parse_blk_count = blk_count;
322 	zilog->zl_parse_lr_count = lr_count;
323 
324 	ASSERT(!claimed || !(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID) ||
325 	    (max_blk_seq == claim_blk_seq && max_lr_seq == claim_lr_seq));
326 
327 	zil_bp_tree_fini(zilog);
328 	zio_buf_free(lrbuf, SPA_MAXBLOCKSIZE);
329 
330 	return (error);
331 }
332 
333 static int
334 zil_claim_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t first_txg)
335 {
336 	/*
337 	 * Claim log block if not already committed and not already claimed.
338 	 * If tx == NULL, just verify that the block is claimable.
339 	 */
340 	if (bp->blk_birth < first_txg || zil_bp_tree_add(zilog, bp) != 0)
341 		return (0);
342 
343 	return (zio_wait(zio_claim(NULL, zilog->zl_spa,
344 	    tx == NULL ? 0 : first_txg, bp, spa_claim_notify, NULL,
345 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB)));
346 }
347 
348 static int
349 zil_claim_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg)
350 {
351 	lr_write_t *lr = (lr_write_t *)lrc;
352 	int error;
353 
354 	if (lrc->lrc_txtype != TX_WRITE)
355 		return (0);
356 
357 	/*
358 	 * If the block is not readable, don't claim it.  This can happen
359 	 * in normal operation when a log block is written to disk before
360 	 * some of the dmu_sync() blocks it points to.  In this case, the
361 	 * transaction cannot have been committed to anyone (we would have
362 	 * waited for all writes to be stable first), so it is semantically
363 	 * correct to declare this the end of the log.
364 	 */
365 	if (lr->lr_blkptr.blk_birth >= first_txg &&
366 	    (error = zil_read_log_data(zilog, lr, NULL)) != 0)
367 		return (error);
368 
369 	return (zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg));
370 }
371 
372 /* ARGSUSED */
373 static int
374 zil_free_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t claim_txg)
375 {
376 	zio_free_zil(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
377 
378 	return (0);
379 }
380 
381 static int
382 zil_free_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t claim_txg)
383 {
384 	lr_write_t *lr = (lr_write_t *)lrc;
385 	blkptr_t *bp = &lr->lr_blkptr;
386 
387 	/*
388 	 * If we previously claimed it, we need to free it.
389 	 */
390 	if (claim_txg != 0 && lrc->lrc_txtype == TX_WRITE &&
391 	    bp->blk_birth >= claim_txg && zil_bp_tree_add(zilog, bp) == 0)
392 		zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
393 
394 	return (0);
395 }
396 
397 /*
398  * Create an on-disk intent log.
399  */
400 static void
401 zil_create(zilog_t *zilog)
402 {
403 	const zil_header_t *zh = zilog->zl_header;
404 	lwb_t *lwb;
405 	uint64_t txg = 0;
406 	dmu_tx_t *tx = NULL;
407 	blkptr_t blk;
408 	int error = 0;
409 
410 	/*
411 	 * Wait for any previous destroy to complete.
412 	 */
413 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
414 
415 	ASSERT(zh->zh_claim_txg == 0);
416 	ASSERT(zh->zh_replay_seq == 0);
417 
418 	blk = zh->zh_log;
419 
420 	/*
421 	 * If we don't already have an initial log block or we have one
422 	 * but it's the wrong endianness then allocate one.
423 	 */
424 	if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) {
425 		tx = dmu_tx_create(zilog->zl_os);
426 		VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
427 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
428 		txg = dmu_tx_get_txg(tx);
429 
430 		if (!BP_IS_HOLE(&blk)) {
431 			zio_free_zil(zilog->zl_spa, txg, &blk);
432 			BP_ZERO(&blk);
433 		}
434 
435 		error = zio_alloc_zil(zilog->zl_spa, txg, &blk, NULL,
436 		    ZIL_MIN_BLKSZ, zilog->zl_logbias == ZFS_LOGBIAS_LATENCY);
437 
438 		if (error == 0)
439 			zil_init_log_chain(zilog, &blk);
440 	}
441 
442 	/*
443 	 * Allocate a log write buffer (lwb) for the first log block.
444 	 */
445 	if (error == 0) {
446 		lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
447 		lwb->lwb_zilog = zilog;
448 		lwb->lwb_blk = blk;
449 		lwb->lwb_nused = 0;
450 		lwb->lwb_sz = BP_GET_LSIZE(&lwb->lwb_blk);
451 		lwb->lwb_buf = zio_buf_alloc(lwb->lwb_sz);
452 		lwb->lwb_max_txg = txg;
453 		lwb->lwb_zio = NULL;
454 		lwb->lwb_tx = NULL;
455 
456 		mutex_enter(&zilog->zl_lock);
457 		list_insert_tail(&zilog->zl_lwb_list, lwb);
458 		mutex_exit(&zilog->zl_lock);
459 	}
460 
461 	/*
462 	 * If we just allocated the first log block, commit our transaction
463 	 * and wait for zil_sync() to stuff the block poiner into zh_log.
464 	 * (zh is part of the MOS, so we cannot modify it in open context.)
465 	 */
466 	if (tx != NULL) {
467 		dmu_tx_commit(tx);
468 		txg_wait_synced(zilog->zl_dmu_pool, txg);
469 	}
470 
471 	ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
472 }
473 
474 /*
475  * In one tx, free all log blocks and clear the log header.
476  * If keep_first is set, then we're replaying a log with no content.
477  * We want to keep the first block, however, so that the first
478  * synchronous transaction doesn't require a txg_wait_synced()
479  * in zil_create().  We don't need to txg_wait_synced() here either
480  * when keep_first is set, because both zil_create() and zil_destroy()
481  * will wait for any in-progress destroys to complete.
482  */
483 void
484 zil_destroy(zilog_t *zilog, boolean_t keep_first)
485 {
486 	const zil_header_t *zh = zilog->zl_header;
487 	lwb_t *lwb;
488 	dmu_tx_t *tx;
489 	uint64_t txg;
490 
491 	/*
492 	 * Wait for any previous destroy to complete.
493 	 */
494 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
495 
496 	zilog->zl_old_header = *zh;		/* debugging aid */
497 
498 	if (BP_IS_HOLE(&zh->zh_log))
499 		return;
500 
501 	tx = dmu_tx_create(zilog->zl_os);
502 	VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
503 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
504 	txg = dmu_tx_get_txg(tx);
505 
506 	mutex_enter(&zilog->zl_lock);
507 
508 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
509 	zilog->zl_destroy_txg = txg;
510 	zilog->zl_keep_first = keep_first;
511 
512 	if (!list_is_empty(&zilog->zl_lwb_list)) {
513 		ASSERT(zh->zh_claim_txg == 0);
514 		ASSERT(!keep_first);
515 		while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
516 			list_remove(&zilog->zl_lwb_list, lwb);
517 			if (lwb->lwb_buf != NULL)
518 				zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
519 			zio_free_zil(zilog->zl_spa, txg, &lwb->lwb_blk);
520 			kmem_cache_free(zil_lwb_cache, lwb);
521 		}
522 	} else if (!keep_first) {
523 		(void) zil_parse(zilog, zil_free_log_block,
524 		    zil_free_log_record, tx, zh->zh_claim_txg);
525 	}
526 	mutex_exit(&zilog->zl_lock);
527 
528 	dmu_tx_commit(tx);
529 }
530 
531 int
532 zil_claim(const char *osname, void *txarg)
533 {
534 	dmu_tx_t *tx = txarg;
535 	uint64_t first_txg = dmu_tx_get_txg(tx);
536 	zilog_t *zilog;
537 	zil_header_t *zh;
538 	objset_t *os;
539 	int error;
540 
541 	error = dmu_objset_hold(osname, FTAG, &os);
542 	if (error) {
543 		cmn_err(CE_WARN, "can't open objset for %s", osname);
544 		return (0);
545 	}
546 
547 	zilog = dmu_objset_zil(os);
548 	zh = zil_header_in_syncing_context(zilog);
549 
550 	if (spa_get_log_state(zilog->zl_spa) == SPA_LOG_CLEAR) {
551 		if (!BP_IS_HOLE(&zh->zh_log))
552 			zio_free_zil(zilog->zl_spa, first_txg, &zh->zh_log);
553 		BP_ZERO(&zh->zh_log);
554 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
555 		dmu_objset_rele(os, FTAG);
556 		return (0);
557 	}
558 
559 	/*
560 	 * Claim all log blocks if we haven't already done so, and remember
561 	 * the highest claimed sequence number.  This ensures that if we can
562 	 * read only part of the log now (e.g. due to a missing device),
563 	 * but we can read the entire log later, we will not try to replay
564 	 * or destroy beyond the last block we successfully claimed.
565 	 */
566 	ASSERT3U(zh->zh_claim_txg, <=, first_txg);
567 	if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
568 		(void) zil_parse(zilog, zil_claim_log_block,
569 		    zil_claim_log_record, tx, first_txg);
570 		zh->zh_claim_txg = first_txg;
571 		zh->zh_claim_blk_seq = zilog->zl_parse_blk_seq;
572 		zh->zh_claim_lr_seq = zilog->zl_parse_lr_seq;
573 		if (zilog->zl_parse_lr_count || zilog->zl_parse_blk_count > 1)
574 			zh->zh_flags |= ZIL_REPLAY_NEEDED;
575 		zh->zh_flags |= ZIL_CLAIM_LR_SEQ_VALID;
576 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
577 	}
578 
579 	ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
580 	dmu_objset_rele(os, FTAG);
581 	return (0);
582 }
583 
584 /*
585  * Check the log by walking the log chain.
586  * Checksum errors are ok as they indicate the end of the chain.
587  * Any other error (no device or read failure) returns an error.
588  */
589 int
590 zil_check_log_chain(const char *osname, void *tx)
591 {
592 	zilog_t *zilog;
593 	objset_t *os;
594 	int error;
595 
596 	ASSERT(tx == NULL);
597 
598 	error = dmu_objset_hold(osname, FTAG, &os);
599 	if (error) {
600 		cmn_err(CE_WARN, "can't open objset for %s", osname);
601 		return (0);
602 	}
603 
604 	zilog = dmu_objset_zil(os);
605 
606 	/*
607 	 * Because tx == NULL, zil_claim_log_block() will not actually claim
608 	 * any blocks, but just determine whether it is possible to do so.
609 	 * In addition to checking the log chain, zil_claim_log_block()
610 	 * will invoke zio_claim() with a done func of spa_claim_notify(),
611 	 * which will update spa_max_claim_txg.  See spa_load() for details.
612 	 */
613 	error = zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx,
614 	    zilog->zl_header->zh_claim_txg ? -1ULL : spa_first_txg(os->os_spa));
615 
616 	dmu_objset_rele(os, FTAG);
617 
618 	return ((error == ECKSUM || error == ENOENT) ? 0 : error);
619 }
620 
621 static int
622 zil_vdev_compare(const void *x1, const void *x2)
623 {
624 	uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
625 	uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
626 
627 	if (v1 < v2)
628 		return (-1);
629 	if (v1 > v2)
630 		return (1);
631 
632 	return (0);
633 }
634 
635 void
636 zil_add_block(zilog_t *zilog, const blkptr_t *bp)
637 {
638 	avl_tree_t *t = &zilog->zl_vdev_tree;
639 	avl_index_t where;
640 	zil_vdev_node_t *zv, zvsearch;
641 	int ndvas = BP_GET_NDVAS(bp);
642 	int i;
643 
644 	if (zfs_nocacheflush)
645 		return;
646 
647 	ASSERT(zilog->zl_writer);
648 
649 	/*
650 	 * Even though we're zl_writer, we still need a lock because the
651 	 * zl_get_data() callbacks may have dmu_sync() done callbacks
652 	 * that will run concurrently.
653 	 */
654 	mutex_enter(&zilog->zl_vdev_lock);
655 	for (i = 0; i < ndvas; i++) {
656 		zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
657 		if (avl_find(t, &zvsearch, &where) == NULL) {
658 			zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
659 			zv->zv_vdev = zvsearch.zv_vdev;
660 			avl_insert(t, zv, where);
661 		}
662 	}
663 	mutex_exit(&zilog->zl_vdev_lock);
664 }
665 
666 void
667 zil_flush_vdevs(zilog_t *zilog)
668 {
669 	spa_t *spa = zilog->zl_spa;
670 	avl_tree_t *t = &zilog->zl_vdev_tree;
671 	void *cookie = NULL;
672 	zil_vdev_node_t *zv;
673 	zio_t *zio;
674 
675 	ASSERT(zilog->zl_writer);
676 
677 	/*
678 	 * We don't need zl_vdev_lock here because we're the zl_writer,
679 	 * and all zl_get_data() callbacks are done.
680 	 */
681 	if (avl_numnodes(t) == 0)
682 		return;
683 
684 	spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
685 
686 	zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
687 
688 	while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
689 		vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
690 		if (vd != NULL)
691 			zio_flush(zio, vd);
692 		kmem_free(zv, sizeof (*zv));
693 	}
694 
695 	/*
696 	 * Wait for all the flushes to complete.  Not all devices actually
697 	 * support the DKIOCFLUSHWRITECACHE ioctl, so it's OK if it fails.
698 	 */
699 	(void) zio_wait(zio);
700 
701 	spa_config_exit(spa, SCL_STATE, FTAG);
702 }
703 
704 /*
705  * Function called when a log block write completes
706  */
707 static void
708 zil_lwb_write_done(zio_t *zio)
709 {
710 	lwb_t *lwb = zio->io_private;
711 	zilog_t *zilog = lwb->lwb_zilog;
712 	dmu_tx_t *tx = lwb->lwb_tx;
713 
714 	ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
715 	ASSERT(BP_GET_CHECKSUM(zio->io_bp) == ZIO_CHECKSUM_ZILOG);
716 	ASSERT(BP_GET_TYPE(zio->io_bp) == DMU_OT_INTENT_LOG);
717 	ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
718 	ASSERT(BP_GET_BYTEORDER(zio->io_bp) == ZFS_HOST_BYTEORDER);
719 	ASSERT(!BP_IS_GANG(zio->io_bp));
720 	ASSERT(!BP_IS_HOLE(zio->io_bp));
721 	ASSERT(zio->io_bp->blk_fill == 0);
722 
723 	/*
724 	 * Ensure the lwb buffer pointer is cleared before releasing
725 	 * the txg. If we have had an allocation failure and
726 	 * the txg is waiting to sync then we want want zil_sync()
727 	 * to remove the lwb so that it's not picked up as the next new
728 	 * one in zil_commit_writer(). zil_sync() will only remove
729 	 * the lwb if lwb_buf is null.
730 	 */
731 	zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
732 	mutex_enter(&zilog->zl_lock);
733 	lwb->lwb_buf = NULL;
734 	lwb->lwb_tx = NULL;
735 	mutex_exit(&zilog->zl_lock);
736 
737 	/*
738 	 * Now that we've written this log block, we have a stable pointer
739 	 * to the next block in the chain, so it's OK to let the txg in
740 	 * which we allocated the next block sync.
741 	 */
742 	dmu_tx_commit(tx);
743 }
744 
745 /*
746  * Initialize the io for a log block.
747  */
748 static void
749 zil_lwb_write_init(zilog_t *zilog, lwb_t *lwb)
750 {
751 	zbookmark_t zb;
752 
753 	SET_BOOKMARK(&zb, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET],
754 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL,
755 	    lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ]);
756 
757 	if (zilog->zl_root_zio == NULL) {
758 		zilog->zl_root_zio = zio_root(zilog->zl_spa, NULL, NULL,
759 		    ZIO_FLAG_CANFAIL);
760 	}
761 	if (lwb->lwb_zio == NULL) {
762 		lwb->lwb_zio = zio_rewrite(zilog->zl_root_zio, zilog->zl_spa,
763 		    0, &lwb->lwb_blk, lwb->lwb_buf, lwb->lwb_sz,
764 		    zil_lwb_write_done, lwb, ZIO_PRIORITY_LOG_WRITE,
765 		    ZIO_FLAG_CANFAIL | ZIO_FLAG_DONT_PROPAGATE, &zb);
766 	}
767 }
768 
769 /*
770  * Use the slog as long as the logbias is 'latency' and the current commit size
771  * is less than the limit or the total list size is less than 2X the limit.
772  * Limit checking is disabled by setting zil_slog_limit to UINT64_MAX.
773  */
774 uint64_t zil_slog_limit = 1024 * 1024;
775 #define	USE_SLOG(zilog) (((zilog)->zl_logbias == ZFS_LOGBIAS_LATENCY) && \
776 	(((zilog)->zl_cur_used < zil_slog_limit) || \
777 	((zilog)->zl_itx_list_sz < (zil_slog_limit << 1))))
778 
779 /*
780  * Start a log block write and advance to the next log block.
781  * Calls are serialized.
782  */
783 static lwb_t *
784 zil_lwb_write_start(zilog_t *zilog, lwb_t *lwb)
785 {
786 	lwb_t *nlwb;
787 	zil_trailer_t *ztp = (zil_trailer_t *)(lwb->lwb_buf + lwb->lwb_sz) - 1;
788 	spa_t *spa = zilog->zl_spa;
789 	blkptr_t *bp = &ztp->zit_next_blk;
790 	dmu_tx_t *tx;
791 	uint64_t txg;
792 	uint64_t zil_blksz;
793 	int error;
794 
795 	ASSERT(lwb->lwb_nused <= ZIL_BLK_DATA_SZ(lwb));
796 
797 	/*
798 	 * Allocate the next block and save its address in this block
799 	 * before writing it in order to establish the log chain.
800 	 * Note that if the allocation of nlwb synced before we wrote
801 	 * the block that points at it (lwb), we'd leak it if we crashed.
802 	 * Therefore, we don't do dmu_tx_commit() until zil_lwb_write_done().
803 	 * We dirty the dataset to ensure that zil_sync() will be called
804 	 * to clean up in the event of allocation failure or I/O failure.
805 	 */
806 	tx = dmu_tx_create(zilog->zl_os);
807 	VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
808 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
809 	txg = dmu_tx_get_txg(tx);
810 
811 	lwb->lwb_tx = tx;
812 
813 	/*
814 	 * Pick a ZIL blocksize. We request a size that is the
815 	 * maximum of the previous used size, the current used size and
816 	 * the amount waiting in the queue.
817 	 */
818 	zil_blksz = MAX(zilog->zl_prev_used,
819 	    zilog->zl_cur_used + sizeof (*ztp));
820 	zil_blksz = MAX(zil_blksz, zilog->zl_itx_list_sz + sizeof (*ztp));
821 	zil_blksz = P2ROUNDUP_TYPED(zil_blksz, ZIL_MIN_BLKSZ, uint64_t);
822 	if (zil_blksz > ZIL_MAX_BLKSZ)
823 		zil_blksz = ZIL_MAX_BLKSZ;
824 
825 	BP_ZERO(bp);
826 	/* pass the old blkptr in order to spread log blocks across devs */
827 	error = zio_alloc_zil(spa, txg, bp, &lwb->lwb_blk, zil_blksz,
828 	    USE_SLOG(zilog));
829 	if (error) {
830 		/*
831 		 * Since we've just experienced an allocation failure,
832 		 * terminate the current lwb and send it on its way.
833 		 */
834 		ztp->zit_pad = 0;
835 		ztp->zit_nused = lwb->lwb_nused;
836 		ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
837 		zio_nowait(lwb->lwb_zio);
838 
839 		/*
840 		 * By returning NULL the caller will call tx_wait_synced()
841 		 */
842 		return (NULL);
843 	}
844 
845 	ASSERT3U(bp->blk_birth, ==, txg);
846 	ztp->zit_pad = 0;
847 	ztp->zit_nused = lwb->lwb_nused;
848 	ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
849 	bp->blk_cksum = lwb->lwb_blk.blk_cksum;
850 	bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
851 
852 	/*
853 	 * Allocate a new log write buffer (lwb).
854 	 */
855 	nlwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
856 	nlwb->lwb_zilog = zilog;
857 	nlwb->lwb_blk = *bp;
858 	nlwb->lwb_nused = 0;
859 	nlwb->lwb_sz = BP_GET_LSIZE(&nlwb->lwb_blk);
860 	nlwb->lwb_buf = zio_buf_alloc(nlwb->lwb_sz);
861 	nlwb->lwb_max_txg = txg;
862 	nlwb->lwb_zio = NULL;
863 	nlwb->lwb_tx = NULL;
864 
865 	/*
866 	 * Put new lwb at the end of the log chain
867 	 */
868 	mutex_enter(&zilog->zl_lock);
869 	list_insert_tail(&zilog->zl_lwb_list, nlwb);
870 	mutex_exit(&zilog->zl_lock);
871 
872 	/* Record the block for later vdev flushing */
873 	zil_add_block(zilog, &lwb->lwb_blk);
874 
875 	/*
876 	 * kick off the write for the old log block
877 	 */
878 	ASSERT(lwb->lwb_zio);
879 	zio_nowait(lwb->lwb_zio);
880 
881 	return (nlwb);
882 }
883 
884 static lwb_t *
885 zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb)
886 {
887 	lr_t *lrc = &itx->itx_lr; /* common log record */
888 	lr_write_t *lrw = (lr_write_t *)lrc;
889 	char *lr_buf;
890 	uint64_t txg = lrc->lrc_txg;
891 	uint64_t reclen = lrc->lrc_reclen;
892 	uint64_t dlen = 0;
893 
894 	if (lwb == NULL)
895 		return (NULL);
896 
897 	ASSERT(lwb->lwb_buf != NULL);
898 
899 	if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY)
900 		dlen = P2ROUNDUP_TYPED(
901 		    lrw->lr_length, sizeof (uint64_t), uint64_t);
902 
903 	zilog->zl_cur_used += (reclen + dlen);
904 
905 	zil_lwb_write_init(zilog, lwb);
906 
907 	/*
908 	 * If this record won't fit in the current log block, start a new one.
909 	 */
910 	if (lwb->lwb_nused + reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
911 		lwb = zil_lwb_write_start(zilog, lwb);
912 		if (lwb == NULL)
913 			return (NULL);
914 		zil_lwb_write_init(zilog, lwb);
915 		ASSERT(lwb->lwb_nused == 0);
916 		if (reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
917 			txg_wait_synced(zilog->zl_dmu_pool, txg);
918 			return (lwb);
919 		}
920 	}
921 
922 	lr_buf = lwb->lwb_buf + lwb->lwb_nused;
923 	bcopy(lrc, lr_buf, reclen);
924 	lrc = (lr_t *)lr_buf;
925 	lrw = (lr_write_t *)lrc;
926 
927 	/*
928 	 * If it's a write, fetch the data or get its blkptr as appropriate.
929 	 */
930 	if (lrc->lrc_txtype == TX_WRITE) {
931 		if (txg > spa_freeze_txg(zilog->zl_spa))
932 			txg_wait_synced(zilog->zl_dmu_pool, txg);
933 		if (itx->itx_wr_state != WR_COPIED) {
934 			char *dbuf;
935 			int error;
936 
937 			if (dlen) {
938 				ASSERT(itx->itx_wr_state == WR_NEED_COPY);
939 				dbuf = lr_buf + reclen;
940 				lrw->lr_common.lrc_reclen += dlen;
941 			} else {
942 				ASSERT(itx->itx_wr_state == WR_INDIRECT);
943 				dbuf = NULL;
944 			}
945 			error = zilog->zl_get_data(
946 			    itx->itx_private, lrw, dbuf, lwb->lwb_zio);
947 			if (error == EIO) {
948 				txg_wait_synced(zilog->zl_dmu_pool, txg);
949 				return (lwb);
950 			}
951 			if (error) {
952 				ASSERT(error == ENOENT || error == EEXIST ||
953 				    error == EALREADY);
954 				return (lwb);
955 			}
956 		}
957 	}
958 
959 	/*
960 	 * We're actually making an entry, so update lrc_seq to be the
961 	 * log record sequence number.  Note that this is generally not
962 	 * equal to the itx sequence number because not all transactions
963 	 * are synchronous, and sometimes spa_sync() gets there first.
964 	 */
965 	lrc->lrc_seq = ++zilog->zl_lr_seq; /* we are single threaded */
966 	lwb->lwb_nused += reclen + dlen;
967 	lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
968 	ASSERT3U(lwb->lwb_nused, <=, ZIL_BLK_DATA_SZ(lwb));
969 	ASSERT3U(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)), ==, 0);
970 
971 	return (lwb);
972 }
973 
974 itx_t *
975 zil_itx_create(uint64_t txtype, size_t lrsize)
976 {
977 	itx_t *itx;
978 
979 	lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t);
980 
981 	itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP);
982 	itx->itx_lr.lrc_txtype = txtype;
983 	itx->itx_lr.lrc_reclen = lrsize;
984 	itx->itx_sod = lrsize; /* if write & WR_NEED_COPY will be increased */
985 	itx->itx_lr.lrc_seq = 0;	/* defensive */
986 
987 	return (itx);
988 }
989 
990 void
991 zil_itx_destroy(itx_t *itx)
992 {
993 	kmem_free(itx, offsetof(itx_t, itx_lr) + itx->itx_lr.lrc_reclen);
994 }
995 
996 uint64_t
997 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
998 {
999 	uint64_t seq;
1000 
1001 	ASSERT(itx->itx_lr.lrc_seq == 0);
1002 	ASSERT(!zilog->zl_replay);
1003 
1004 	mutex_enter(&zilog->zl_lock);
1005 	list_insert_tail(&zilog->zl_itx_list, itx);
1006 	zilog->zl_itx_list_sz += itx->itx_sod;
1007 	itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
1008 	itx->itx_lr.lrc_seq = seq = ++zilog->zl_itx_seq;
1009 	mutex_exit(&zilog->zl_lock);
1010 
1011 	return (seq);
1012 }
1013 
1014 /*
1015  * Free up all in-memory intent log transactions that have now been synced.
1016  */
1017 static void
1018 zil_itx_clean(zilog_t *zilog)
1019 {
1020 	uint64_t synced_txg = spa_last_synced_txg(zilog->zl_spa);
1021 	uint64_t freeze_txg = spa_freeze_txg(zilog->zl_spa);
1022 	list_t clean_list;
1023 	itx_t *itx;
1024 
1025 	list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
1026 
1027 	mutex_enter(&zilog->zl_lock);
1028 	/* wait for a log writer to finish walking list */
1029 	while (zilog->zl_writer) {
1030 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1031 	}
1032 
1033 	/*
1034 	 * Move the sync'd log transactions to a separate list so we can call
1035 	 * kmem_free without holding the zl_lock.
1036 	 *
1037 	 * There is no need to set zl_writer as we don't drop zl_lock here
1038 	 */
1039 	while ((itx = list_head(&zilog->zl_itx_list)) != NULL &&
1040 	    itx->itx_lr.lrc_txg <= MIN(synced_txg, freeze_txg)) {
1041 		list_remove(&zilog->zl_itx_list, itx);
1042 		zilog->zl_itx_list_sz -= itx->itx_sod;
1043 		list_insert_tail(&clean_list, itx);
1044 	}
1045 	cv_broadcast(&zilog->zl_cv_writer);
1046 	mutex_exit(&zilog->zl_lock);
1047 
1048 	/* destroy sync'd log transactions */
1049 	while ((itx = list_head(&clean_list)) != NULL) {
1050 		list_remove(&clean_list, itx);
1051 		zil_itx_destroy(itx);
1052 	}
1053 	list_destroy(&clean_list);
1054 }
1055 
1056 /*
1057  * If there are any in-memory intent log transactions which have now been
1058  * synced then start up a taskq to free them.
1059  */
1060 void
1061 zil_clean(zilog_t *zilog)
1062 {
1063 	itx_t *itx;
1064 
1065 	mutex_enter(&zilog->zl_lock);
1066 	itx = list_head(&zilog->zl_itx_list);
1067 	if ((itx != NULL) &&
1068 	    (itx->itx_lr.lrc_txg <= spa_last_synced_txg(zilog->zl_spa))) {
1069 		(void) taskq_dispatch(zilog->zl_clean_taskq,
1070 		    (task_func_t *)zil_itx_clean, zilog, TQ_NOSLEEP);
1071 	}
1072 	mutex_exit(&zilog->zl_lock);
1073 }
1074 
1075 static void
1076 zil_commit_writer(zilog_t *zilog, uint64_t seq, uint64_t foid)
1077 {
1078 	uint64_t txg;
1079 	uint64_t commit_seq = 0;
1080 	itx_t *itx, *itx_next;
1081 	lwb_t *lwb;
1082 	spa_t *spa;
1083 	int error = 0;
1084 
1085 	zilog->zl_writer = B_TRUE;
1086 	ASSERT(zilog->zl_root_zio == NULL);
1087 	spa = zilog->zl_spa;
1088 
1089 	if (zilog->zl_suspend) {
1090 		lwb = NULL;
1091 	} else {
1092 		lwb = list_tail(&zilog->zl_lwb_list);
1093 		if (lwb == NULL) {
1094 			/*
1095 			 * Return if there's nothing to flush before we
1096 			 * dirty the fs by calling zil_create()
1097 			 */
1098 			if (list_is_empty(&zilog->zl_itx_list)) {
1099 				zilog->zl_writer = B_FALSE;
1100 				return;
1101 			}
1102 			mutex_exit(&zilog->zl_lock);
1103 			zil_create(zilog);
1104 			mutex_enter(&zilog->zl_lock);
1105 			lwb = list_tail(&zilog->zl_lwb_list);
1106 		}
1107 	}
1108 
1109 	/* Loop through in-memory log transactions filling log blocks. */
1110 	DTRACE_PROBE1(zil__cw1, zilog_t *, zilog);
1111 
1112 	for (itx = list_head(&zilog->zl_itx_list); itx; itx = itx_next) {
1113 		/*
1114 		 * Save the next pointer.  Even though we drop zl_lock below,
1115 		 * all threads that can remove itx list entries (other writers
1116 		 * and zil_itx_clean()) can't do so until they have zl_writer.
1117 		 */
1118 		itx_next = list_next(&zilog->zl_itx_list, itx);
1119 
1120 		/*
1121 		 * Determine whether to push this itx.
1122 		 * Push all transactions related to specified foid and
1123 		 * all other transactions except those that can be logged
1124 		 * out of order (TX_WRITE, TX_TRUNCATE, TX_SETATTR, TX_ACL)
1125 		 * for all other files.
1126 		 *
1127 		 * If foid == 0 (meaning "push all foids") or
1128 		 * itx->itx_sync is set (meaning O_[D]SYNC), push regardless.
1129 		 */
1130 		if (foid != 0 && !itx->itx_sync &&
1131 		    TX_OOO(itx->itx_lr.lrc_txtype) &&
1132 		    ((lr_ooo_t *)&itx->itx_lr)->lr_foid != foid)
1133 			continue; /* skip this record */
1134 
1135 		if ((itx->itx_lr.lrc_seq > seq) &&
1136 		    ((lwb == NULL) || (lwb->lwb_nused == 0) ||
1137 		    (lwb->lwb_nused + itx->itx_sod > ZIL_BLK_DATA_SZ(lwb))))
1138 			break;
1139 
1140 		list_remove(&zilog->zl_itx_list, itx);
1141 		zilog->zl_itx_list_sz -= itx->itx_sod;
1142 
1143 		mutex_exit(&zilog->zl_lock);
1144 
1145 		txg = itx->itx_lr.lrc_txg;
1146 		ASSERT(txg);
1147 
1148 		if (txg > spa_last_synced_txg(spa) ||
1149 		    txg > spa_freeze_txg(spa))
1150 			lwb = zil_lwb_commit(zilog, itx, lwb);
1151 
1152 		zil_itx_destroy(itx);
1153 
1154 		mutex_enter(&zilog->zl_lock);
1155 	}
1156 	DTRACE_PROBE1(zil__cw2, zilog_t *, zilog);
1157 	/* determine commit sequence number */
1158 	itx = list_head(&zilog->zl_itx_list);
1159 	if (itx)
1160 		commit_seq = itx->itx_lr.lrc_seq - 1;
1161 	else
1162 		commit_seq = zilog->zl_itx_seq;
1163 	mutex_exit(&zilog->zl_lock);
1164 
1165 	/* write the last block out */
1166 	if (lwb != NULL && lwb->lwb_zio != NULL)
1167 		lwb = zil_lwb_write_start(zilog, lwb);
1168 
1169 	zilog->zl_prev_used = zilog->zl_cur_used;
1170 	zilog->zl_cur_used = 0;
1171 
1172 	/*
1173 	 * Wait if necessary for the log blocks to be on stable storage.
1174 	 */
1175 	if (zilog->zl_root_zio) {
1176 		DTRACE_PROBE1(zil__cw3, zilog_t *, zilog);
1177 		error = zio_wait(zilog->zl_root_zio);
1178 		zilog->zl_root_zio = NULL;
1179 		DTRACE_PROBE1(zil__cw4, zilog_t *, zilog);
1180 		zil_flush_vdevs(zilog);
1181 	}
1182 
1183 	if (error || lwb == NULL)
1184 		txg_wait_synced(zilog->zl_dmu_pool, 0);
1185 
1186 	mutex_enter(&zilog->zl_lock);
1187 	zilog->zl_writer = B_FALSE;
1188 
1189 	ASSERT3U(commit_seq, >=, zilog->zl_commit_seq);
1190 	zilog->zl_commit_seq = commit_seq;
1191 
1192 	/*
1193 	 * Remember the highest committed log sequence number for ztest.
1194 	 * We only update this value when all the log writes succeeded,
1195 	 * because ztest wants to ASSERT that it got the whole log chain.
1196 	 */
1197 	if (error == 0 && lwb != NULL)
1198 		zilog->zl_commit_lr_seq = zilog->zl_lr_seq;
1199 }
1200 
1201 /*
1202  * Push zfs transactions to stable storage up to the supplied sequence number.
1203  * If foid is 0 push out all transactions, otherwise push only those
1204  * for that file or might have been used to create that file.
1205  */
1206 void
1207 zil_commit(zilog_t *zilog, uint64_t seq, uint64_t foid)
1208 {
1209 	if (zilog == NULL || seq == 0)
1210 		return;
1211 
1212 	mutex_enter(&zilog->zl_lock);
1213 
1214 	seq = MIN(seq, zilog->zl_itx_seq);	/* cap seq at largest itx seq */
1215 
1216 	while (zilog->zl_writer) {
1217 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1218 		if (seq <= zilog->zl_commit_seq) {
1219 			mutex_exit(&zilog->zl_lock);
1220 			return;
1221 		}
1222 	}
1223 	zil_commit_writer(zilog, seq, foid); /* drops zl_lock */
1224 	/* wake up others waiting on the commit */
1225 	cv_broadcast(&zilog->zl_cv_writer);
1226 	mutex_exit(&zilog->zl_lock);
1227 }
1228 
1229 /*
1230  * Report whether all transactions are committed.
1231  */
1232 static boolean_t
1233 zil_is_committed(zilog_t *zilog)
1234 {
1235 	lwb_t *lwb;
1236 	boolean_t committed;
1237 
1238 	mutex_enter(&zilog->zl_lock);
1239 
1240 	while (zilog->zl_writer)
1241 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1242 
1243 	if (!list_is_empty(&zilog->zl_itx_list))
1244 		committed = B_FALSE;		/* unpushed transactions */
1245 	else if ((lwb = list_head(&zilog->zl_lwb_list)) == NULL)
1246 		committed = B_TRUE;		/* intent log never used */
1247 	else if (list_next(&zilog->zl_lwb_list, lwb) != NULL)
1248 		committed = B_FALSE;		/* zil_sync() not done yet */
1249 	else
1250 		committed = B_TRUE;		/* everything synced */
1251 
1252 	mutex_exit(&zilog->zl_lock);
1253 	return (committed);
1254 }
1255 
1256 /*
1257  * Called in syncing context to free committed log blocks and update log header.
1258  */
1259 void
1260 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
1261 {
1262 	zil_header_t *zh = zil_header_in_syncing_context(zilog);
1263 	uint64_t txg = dmu_tx_get_txg(tx);
1264 	spa_t *spa = zilog->zl_spa;
1265 	uint64_t *replayed_seq = &zilog->zl_replayed_seq[txg & TXG_MASK];
1266 	lwb_t *lwb;
1267 
1268 	/*
1269 	 * We don't zero out zl_destroy_txg, so make sure we don't try
1270 	 * to destroy it twice.
1271 	 */
1272 	if (spa_sync_pass(spa) != 1)
1273 		return;
1274 
1275 	mutex_enter(&zilog->zl_lock);
1276 
1277 	ASSERT(zilog->zl_stop_sync == 0);
1278 
1279 	if (*replayed_seq != 0) {
1280 		ASSERT(zh->zh_replay_seq < *replayed_seq);
1281 		zh->zh_replay_seq = *replayed_seq;
1282 		*replayed_seq = 0;
1283 	}
1284 
1285 	if (zilog->zl_destroy_txg == txg) {
1286 		blkptr_t blk = zh->zh_log;
1287 
1288 		ASSERT(list_head(&zilog->zl_lwb_list) == NULL);
1289 
1290 		bzero(zh, sizeof (zil_header_t));
1291 		bzero(zilog->zl_replayed_seq, sizeof (zilog->zl_replayed_seq));
1292 
1293 		if (zilog->zl_keep_first) {
1294 			/*
1295 			 * If this block was part of log chain that couldn't
1296 			 * be claimed because a device was missing during
1297 			 * zil_claim(), but that device later returns,
1298 			 * then this block could erroneously appear valid.
1299 			 * To guard against this, assign a new GUID to the new
1300 			 * log chain so it doesn't matter what blk points to.
1301 			 */
1302 			zil_init_log_chain(zilog, &blk);
1303 			zh->zh_log = blk;
1304 		}
1305 	}
1306 
1307 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
1308 		zh->zh_log = lwb->lwb_blk;
1309 		if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg)
1310 			break;
1311 		list_remove(&zilog->zl_lwb_list, lwb);
1312 		zio_free_zil(spa, txg, &lwb->lwb_blk);
1313 		kmem_cache_free(zil_lwb_cache, lwb);
1314 
1315 		/*
1316 		 * If we don't have anything left in the lwb list then
1317 		 * we've had an allocation failure and we need to zero
1318 		 * out the zil_header blkptr so that we don't end
1319 		 * up freeing the same block twice.
1320 		 */
1321 		if (list_head(&zilog->zl_lwb_list) == NULL)
1322 			BP_ZERO(&zh->zh_log);
1323 	}
1324 	mutex_exit(&zilog->zl_lock);
1325 }
1326 
1327 void
1328 zil_init(void)
1329 {
1330 	zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
1331 	    sizeof (struct lwb), 0, NULL, NULL, NULL, NULL, NULL, 0);
1332 }
1333 
1334 void
1335 zil_fini(void)
1336 {
1337 	kmem_cache_destroy(zil_lwb_cache);
1338 }
1339 
1340 void
1341 zil_set_logbias(zilog_t *zilog, uint64_t logbias)
1342 {
1343 	zilog->zl_logbias = logbias;
1344 }
1345 
1346 zilog_t *
1347 zil_alloc(objset_t *os, zil_header_t *zh_phys)
1348 {
1349 	zilog_t *zilog;
1350 
1351 	zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
1352 
1353 	zilog->zl_header = zh_phys;
1354 	zilog->zl_os = os;
1355 	zilog->zl_spa = dmu_objset_spa(os);
1356 	zilog->zl_dmu_pool = dmu_objset_pool(os);
1357 	zilog->zl_destroy_txg = TXG_INITIAL - 1;
1358 	zilog->zl_logbias = dmu_objset_logbias(os);
1359 
1360 	mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
1361 
1362 	list_create(&zilog->zl_itx_list, sizeof (itx_t),
1363 	    offsetof(itx_t, itx_node));
1364 
1365 	list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
1366 	    offsetof(lwb_t, lwb_node));
1367 
1368 	mutex_init(&zilog->zl_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
1369 
1370 	avl_create(&zilog->zl_vdev_tree, zil_vdev_compare,
1371 	    sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
1372 
1373 	cv_init(&zilog->zl_cv_writer, NULL, CV_DEFAULT, NULL);
1374 	cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
1375 
1376 	return (zilog);
1377 }
1378 
1379 void
1380 zil_free(zilog_t *zilog)
1381 {
1382 	lwb_t *lwb;
1383 
1384 	zilog->zl_stop_sync = 1;
1385 
1386 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
1387 		list_remove(&zilog->zl_lwb_list, lwb);
1388 		if (lwb->lwb_buf != NULL)
1389 			zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1390 		kmem_cache_free(zil_lwb_cache, lwb);
1391 	}
1392 	list_destroy(&zilog->zl_lwb_list);
1393 
1394 	avl_destroy(&zilog->zl_vdev_tree);
1395 	mutex_destroy(&zilog->zl_vdev_lock);
1396 
1397 	ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1398 	list_destroy(&zilog->zl_itx_list);
1399 	mutex_destroy(&zilog->zl_lock);
1400 
1401 	cv_destroy(&zilog->zl_cv_writer);
1402 	cv_destroy(&zilog->zl_cv_suspend);
1403 
1404 	kmem_free(zilog, sizeof (zilog_t));
1405 }
1406 
1407 /*
1408  * Open an intent log.
1409  */
1410 zilog_t *
1411 zil_open(objset_t *os, zil_get_data_t *get_data)
1412 {
1413 	zilog_t *zilog = dmu_objset_zil(os);
1414 
1415 	zilog->zl_get_data = get_data;
1416 	zilog->zl_clean_taskq = taskq_create("zil_clean", 1, minclsyspri,
1417 	    2, 2, TASKQ_PREPOPULATE);
1418 
1419 	return (zilog);
1420 }
1421 
1422 /*
1423  * Close an intent log.
1424  */
1425 void
1426 zil_close(zilog_t *zilog)
1427 {
1428 	/*
1429 	 * If the log isn't already committed, mark the objset dirty
1430 	 * (so zil_sync() will be called) and wait for that txg to sync.
1431 	 */
1432 	if (!zil_is_committed(zilog)) {
1433 		uint64_t txg;
1434 		dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
1435 		VERIFY(dmu_tx_assign(tx, TXG_WAIT) == 0);
1436 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1437 		txg = dmu_tx_get_txg(tx);
1438 		dmu_tx_commit(tx);
1439 		txg_wait_synced(zilog->zl_dmu_pool, txg);
1440 	}
1441 
1442 	taskq_destroy(zilog->zl_clean_taskq);
1443 	zilog->zl_clean_taskq = NULL;
1444 	zilog->zl_get_data = NULL;
1445 
1446 	zil_itx_clean(zilog);
1447 	ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1448 }
1449 
1450 /*
1451  * Suspend an intent log.  While in suspended mode, we still honor
1452  * synchronous semantics, but we rely on txg_wait_synced() to do it.
1453  * We suspend the log briefly when taking a snapshot so that the snapshot
1454  * contains all the data it's supposed to, and has an empty intent log.
1455  */
1456 int
1457 zil_suspend(zilog_t *zilog)
1458 {
1459 	const zil_header_t *zh = zilog->zl_header;
1460 
1461 	mutex_enter(&zilog->zl_lock);
1462 	if (zh->zh_flags & ZIL_REPLAY_NEEDED) {		/* unplayed log */
1463 		mutex_exit(&zilog->zl_lock);
1464 		return (EBUSY);
1465 	}
1466 	if (zilog->zl_suspend++ != 0) {
1467 		/*
1468 		 * Someone else already began a suspend.
1469 		 * Just wait for them to finish.
1470 		 */
1471 		while (zilog->zl_suspending)
1472 			cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
1473 		mutex_exit(&zilog->zl_lock);
1474 		return (0);
1475 	}
1476 	zilog->zl_suspending = B_TRUE;
1477 	mutex_exit(&zilog->zl_lock);
1478 
1479 	zil_commit(zilog, UINT64_MAX, 0);
1480 
1481 	/*
1482 	 * Wait for any in-flight log writes to complete.
1483 	 */
1484 	mutex_enter(&zilog->zl_lock);
1485 	while (zilog->zl_writer)
1486 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1487 	mutex_exit(&zilog->zl_lock);
1488 
1489 	zil_destroy(zilog, B_FALSE);
1490 
1491 	mutex_enter(&zilog->zl_lock);
1492 	zilog->zl_suspending = B_FALSE;
1493 	cv_broadcast(&zilog->zl_cv_suspend);
1494 	mutex_exit(&zilog->zl_lock);
1495 
1496 	return (0);
1497 }
1498 
1499 void
1500 zil_resume(zilog_t *zilog)
1501 {
1502 	mutex_enter(&zilog->zl_lock);
1503 	ASSERT(zilog->zl_suspend != 0);
1504 	zilog->zl_suspend--;
1505 	mutex_exit(&zilog->zl_lock);
1506 }
1507 
1508 typedef struct zil_replay_arg {
1509 	zil_replay_func_t **zr_replay;
1510 	void		*zr_arg;
1511 	boolean_t	zr_byteswap;
1512 	char		*zr_lr;
1513 } zil_replay_arg_t;
1514 
1515 static int
1516 zil_replay_error(zilog_t *zilog, lr_t *lr, int error)
1517 {
1518 	char name[MAXNAMELEN];
1519 
1520 	zilog->zl_replaying_seq--;	/* didn't actually replay this one */
1521 
1522 	dmu_objset_name(zilog->zl_os, name);
1523 
1524 	cmn_err(CE_WARN, "ZFS replay transaction error %d, "
1525 	    "dataset %s, seq 0x%llx, txtype %llu %s\n", error, name,
1526 	    (u_longlong_t)lr->lrc_seq,
1527 	    (u_longlong_t)(lr->lrc_txtype & ~TX_CI),
1528 	    (lr->lrc_txtype & TX_CI) ? "CI" : "");
1529 
1530 	return (error);
1531 }
1532 
1533 static int
1534 zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg)
1535 {
1536 	zil_replay_arg_t *zr = zra;
1537 	const zil_header_t *zh = zilog->zl_header;
1538 	uint64_t reclen = lr->lrc_reclen;
1539 	uint64_t txtype = lr->lrc_txtype;
1540 	int error = 0;
1541 
1542 	zilog->zl_replaying_seq = lr->lrc_seq;
1543 
1544 	if (lr->lrc_seq <= zh->zh_replay_seq)	/* already replayed */
1545 		return (0);
1546 
1547 	if (lr->lrc_txg < claim_txg)		/* already committed */
1548 		return (0);
1549 
1550 	/* Strip case-insensitive bit, still present in log record */
1551 	txtype &= ~TX_CI;
1552 
1553 	if (txtype == 0 || txtype >= TX_MAX_TYPE)
1554 		return (zil_replay_error(zilog, lr, EINVAL));
1555 
1556 	/*
1557 	 * If this record type can be logged out of order, the object
1558 	 * (lr_foid) may no longer exist.  That's legitimate, not an error.
1559 	 */
1560 	if (TX_OOO(txtype)) {
1561 		error = dmu_object_info(zilog->zl_os,
1562 		    ((lr_ooo_t *)lr)->lr_foid, NULL);
1563 		if (error == ENOENT || error == EEXIST)
1564 			return (0);
1565 	}
1566 
1567 	/*
1568 	 * Make a copy of the data so we can revise and extend it.
1569 	 */
1570 	bcopy(lr, zr->zr_lr, reclen);
1571 
1572 	/*
1573 	 * If this is a TX_WRITE with a blkptr, suck in the data.
1574 	 */
1575 	if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
1576 		error = zil_read_log_data(zilog, (lr_write_t *)lr,
1577 		    zr->zr_lr + reclen);
1578 		if (error)
1579 			return (zil_replay_error(zilog, lr, error));
1580 	}
1581 
1582 	/*
1583 	 * The log block containing this lr may have been byteswapped
1584 	 * so that we can easily examine common fields like lrc_txtype.
1585 	 * However, the log is a mix of different record types, and only the
1586 	 * replay vectors know how to byteswap their records.  Therefore, if
1587 	 * the lr was byteswapped, undo it before invoking the replay vector.
1588 	 */
1589 	if (zr->zr_byteswap)
1590 		byteswap_uint64_array(zr->zr_lr, reclen);
1591 
1592 	/*
1593 	 * We must now do two things atomically: replay this log record,
1594 	 * and update the log header sequence number to reflect the fact that
1595 	 * we did so. At the end of each replay function the sequence number
1596 	 * is updated if we are in replay mode.
1597 	 */
1598 	error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, zr->zr_byteswap);
1599 	if (error) {
1600 		/*
1601 		 * The DMU's dnode layer doesn't see removes until the txg
1602 		 * commits, so a subsequent claim can spuriously fail with
1603 		 * EEXIST. So if we receive any error we try syncing out
1604 		 * any removes then retry the transaction.  Note that we
1605 		 * specify B_FALSE for byteswap now, so we don't do it twice.
1606 		 */
1607 		txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
1608 		error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, B_FALSE);
1609 		if (error)
1610 			return (zil_replay_error(zilog, lr, error));
1611 	}
1612 	return (0);
1613 }
1614 
1615 /* ARGSUSED */
1616 static int
1617 zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1618 {
1619 	zilog->zl_replay_blks++;
1620 
1621 	return (0);
1622 }
1623 
1624 /*
1625  * If this dataset has a non-empty intent log, replay it and destroy it.
1626  */
1627 void
1628 zil_replay(objset_t *os, void *arg, zil_replay_func_t *replay_func[TX_MAX_TYPE])
1629 {
1630 	zilog_t *zilog = dmu_objset_zil(os);
1631 	const zil_header_t *zh = zilog->zl_header;
1632 	zil_replay_arg_t zr;
1633 
1634 	if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
1635 		zil_destroy(zilog, B_TRUE);
1636 		return;
1637 	}
1638 
1639 	zr.zr_replay = replay_func;
1640 	zr.zr_arg = arg;
1641 	zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
1642 	zr.zr_lr = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
1643 
1644 	/*
1645 	 * Wait for in-progress removes to sync before starting replay.
1646 	 */
1647 	txg_wait_synced(zilog->zl_dmu_pool, 0);
1648 
1649 	zilog->zl_replay = B_TRUE;
1650 	zilog->zl_replay_time = ddi_get_lbolt();
1651 	ASSERT(zilog->zl_replay_blks == 0);
1652 	(void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
1653 	    zh->zh_claim_txg);
1654 	kmem_free(zr.zr_lr, 2 * SPA_MAXBLOCKSIZE);
1655 
1656 	zil_destroy(zilog, B_FALSE);
1657 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
1658 	zilog->zl_replay = B_FALSE;
1659 }
1660 
1661 boolean_t
1662 zil_replaying(zilog_t *zilog, dmu_tx_t *tx)
1663 {
1664 	if (zilog == NULL)
1665 		return (B_TRUE);
1666 
1667 	if (zilog->zl_replay) {
1668 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1669 		zilog->zl_replayed_seq[dmu_tx_get_txg(tx) & TXG_MASK] =
1670 		    zilog->zl_replaying_seq;
1671 		return (B_TRUE);
1672 	}
1673 
1674 	return (B_FALSE);
1675 }
1676 
1677 /* ARGSUSED */
1678 int
1679 zil_vdev_offline(const char *osname, void *arg)
1680 {
1681 	objset_t *os;
1682 	zilog_t *zilog;
1683 	int error;
1684 
1685 	error = dmu_objset_hold(osname, FTAG, &os);
1686 	if (error)
1687 		return (error);
1688 
1689 	zilog = dmu_objset_zil(os);
1690 	if (zil_suspend(zilog) != 0)
1691 		error = EEXIST;
1692 	else
1693 		zil_resume(zilog);
1694 	dmu_objset_rele(os, FTAG);
1695 	return (error);
1696 }
1697