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