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