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