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