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