xref: /titanic_51/usr/src/uts/common/fs/zfs/zil.c (revision e4b86885570d77af552e9cf94f142f4d744fb8c8)
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 2008 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 		ASSERT(err == 0);
293 	}
294 }
295 
296 static void
297 zil_claim_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg)
298 {
299 	if (lrc->lrc_txtype == TX_WRITE) {
300 		lr_write_t *lr = (lr_write_t *)lrc;
301 		zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg);
302 	}
303 }
304 
305 /* ARGSUSED */
306 static void
307 zil_free_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t claim_txg)
308 {
309 	zio_free_blk(zilog->zl_spa, bp, dmu_tx_get_txg(tx));
310 }
311 
312 static void
313 zil_free_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t claim_txg)
314 {
315 	/*
316 	 * If we previously claimed it, we need to free it.
317 	 */
318 	if (claim_txg != 0 && lrc->lrc_txtype == TX_WRITE) {
319 		lr_write_t *lr = (lr_write_t *)lrc;
320 		blkptr_t *bp = &lr->lr_blkptr;
321 		if (bp->blk_birth >= claim_txg &&
322 		    !zil_dva_tree_add(&zilog->zl_dva_tree, BP_IDENTITY(bp))) {
323 			(void) arc_free(NULL, zilog->zl_spa,
324 			    dmu_tx_get_txg(tx), bp, NULL, NULL, ARC_WAIT);
325 		}
326 	}
327 }
328 
329 /*
330  * Create an on-disk intent log.
331  */
332 static void
333 zil_create(zilog_t *zilog)
334 {
335 	const zil_header_t *zh = zilog->zl_header;
336 	lwb_t *lwb;
337 	uint64_t txg = 0;
338 	dmu_tx_t *tx = NULL;
339 	blkptr_t blk;
340 	int error = 0;
341 
342 	/*
343 	 * Wait for any previous destroy to complete.
344 	 */
345 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
346 
347 	ASSERT(zh->zh_claim_txg == 0);
348 	ASSERT(zh->zh_replay_seq == 0);
349 
350 	blk = zh->zh_log;
351 
352 	/*
353 	 * If we don't already have an initial log block, allocate one now.
354 	 */
355 	if (BP_IS_HOLE(&blk)) {
356 		tx = dmu_tx_create(zilog->zl_os);
357 		(void) dmu_tx_assign(tx, TXG_WAIT);
358 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
359 		txg = dmu_tx_get_txg(tx);
360 
361 		error = zio_alloc_blk(zilog->zl_spa, ZIL_MIN_BLKSZ, &blk,
362 		    NULL, txg);
363 
364 		if (error == 0)
365 			zil_init_log_chain(zilog, &blk);
366 	}
367 
368 	/*
369 	 * Allocate a log write buffer (lwb) for the first log block.
370 	 */
371 	if (error == 0) {
372 		lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
373 		lwb->lwb_zilog = zilog;
374 		lwb->lwb_blk = blk;
375 		lwb->lwb_nused = 0;
376 		lwb->lwb_sz = BP_GET_LSIZE(&lwb->lwb_blk);
377 		lwb->lwb_buf = zio_buf_alloc(lwb->lwb_sz);
378 		lwb->lwb_max_txg = txg;
379 		lwb->lwb_zio = NULL;
380 
381 		mutex_enter(&zilog->zl_lock);
382 		list_insert_tail(&zilog->zl_lwb_list, lwb);
383 		mutex_exit(&zilog->zl_lock);
384 	}
385 
386 	/*
387 	 * If we just allocated the first log block, commit our transaction
388 	 * and wait for zil_sync() to stuff the block poiner into zh_log.
389 	 * (zh is part of the MOS, so we cannot modify it in open context.)
390 	 */
391 	if (tx != NULL) {
392 		dmu_tx_commit(tx);
393 		txg_wait_synced(zilog->zl_dmu_pool, txg);
394 	}
395 
396 	ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
397 }
398 
399 /*
400  * In one tx, free all log blocks and clear the log header.
401  * If keep_first is set, then we're replaying a log with no content.
402  * We want to keep the first block, however, so that the first
403  * synchronous transaction doesn't require a txg_wait_synced()
404  * in zil_create().  We don't need to txg_wait_synced() here either
405  * when keep_first is set, because both zil_create() and zil_destroy()
406  * will wait for any in-progress destroys to complete.
407  */
408 void
409 zil_destroy(zilog_t *zilog, boolean_t keep_first)
410 {
411 	const zil_header_t *zh = zilog->zl_header;
412 	lwb_t *lwb;
413 	dmu_tx_t *tx;
414 	uint64_t txg;
415 
416 	/*
417 	 * Wait for any previous destroy to complete.
418 	 */
419 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
420 
421 	if (BP_IS_HOLE(&zh->zh_log))
422 		return;
423 
424 	tx = dmu_tx_create(zilog->zl_os);
425 	(void) dmu_tx_assign(tx, TXG_WAIT);
426 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
427 	txg = dmu_tx_get_txg(tx);
428 
429 	mutex_enter(&zilog->zl_lock);
430 
431 	/*
432 	 * It is possible for the ZIL to get the previously mounted zilog
433 	 * structure of the same dataset if quickly remounted and the dbuf
434 	 * eviction has not completed. In this case we can see a non
435 	 * empty lwb list and keep_first will be set. We fix this by
436 	 * clearing the keep_first. This will be slower but it's very rare.
437 	 */
438 	if (!list_is_empty(&zilog->zl_lwb_list) && keep_first)
439 		keep_first = B_FALSE;
440 
441 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
442 	zilog->zl_destroy_txg = txg;
443 	zilog->zl_keep_first = keep_first;
444 
445 	if (!list_is_empty(&zilog->zl_lwb_list)) {
446 		ASSERT(zh->zh_claim_txg == 0);
447 		ASSERT(!keep_first);
448 		while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
449 			list_remove(&zilog->zl_lwb_list, lwb);
450 			if (lwb->lwb_buf != NULL)
451 				zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
452 			zio_free_blk(zilog->zl_spa, &lwb->lwb_blk, txg);
453 			kmem_cache_free(zil_lwb_cache, lwb);
454 		}
455 	} else {
456 		if (!keep_first) {
457 			(void) zil_parse(zilog, zil_free_log_block,
458 			    zil_free_log_record, tx, zh->zh_claim_txg);
459 		}
460 	}
461 	mutex_exit(&zilog->zl_lock);
462 
463 	dmu_tx_commit(tx);
464 }
465 
466 /*
467  * zil_rollback_destroy() is only called by the rollback code.
468  * We already have a syncing tx. Rollback has exclusive access to the
469  * dataset, so we don't have to worry about concurrent zil access.
470  * The actual freeing of any log blocks occurs in zil_sync() later in
471  * this txg syncing phase.
472  */
473 void
474 zil_rollback_destroy(zilog_t *zilog, dmu_tx_t *tx)
475 {
476 	const zil_header_t *zh = zilog->zl_header;
477 	uint64_t txg;
478 
479 	if (BP_IS_HOLE(&zh->zh_log))
480 		return;
481 
482 	txg = dmu_tx_get_txg(tx);
483 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
484 	zilog->zl_destroy_txg = txg;
485 	zilog->zl_keep_first = B_FALSE;
486 
487 	/*
488 	 * Ensure there's no outstanding ZIL IO.  No lwbs or just the
489 	 * unused one that allocated in advance is ok.
490 	 */
491 	ASSERT(zilog->zl_lwb_list.list_head.list_next ==
492 	    zilog->zl_lwb_list.list_head.list_prev);
493 	(void) zil_parse(zilog, zil_free_log_block, zil_free_log_record,
494 	    tx, zh->zh_claim_txg);
495 }
496 
497 int
498 zil_claim(char *osname, void *txarg)
499 {
500 	dmu_tx_t *tx = txarg;
501 	uint64_t first_txg = dmu_tx_get_txg(tx);
502 	zilog_t *zilog;
503 	zil_header_t *zh;
504 	objset_t *os;
505 	int error;
506 
507 	error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
508 	if (error) {
509 		cmn_err(CE_WARN, "can't open objset for %s", osname);
510 		return (0);
511 	}
512 
513 	zilog = dmu_objset_zil(os);
514 	zh = zil_header_in_syncing_context(zilog);
515 
516 	/*
517 	 * Claim all log blocks if we haven't already done so, and remember
518 	 * the highest claimed sequence number.  This ensures that if we can
519 	 * read only part of the log now (e.g. due to a missing device),
520 	 * but we can read the entire log later, we will not try to replay
521 	 * or destroy beyond the last block we successfully claimed.
522 	 */
523 	ASSERT3U(zh->zh_claim_txg, <=, first_txg);
524 	if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
525 		zh->zh_claim_txg = first_txg;
526 		zh->zh_claim_seq = zil_parse(zilog, zil_claim_log_block,
527 		    zil_claim_log_record, tx, first_txg);
528 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
529 	}
530 
531 	ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
532 	dmu_objset_close(os);
533 	return (0);
534 }
535 
536 /*
537  * Check the log by walking the log chain.
538  * Checksum errors are ok as they indicate the end of the chain.
539  * Any other error (no device or read failure) returns an error.
540  */
541 /* ARGSUSED */
542 int
543 zil_check_log_chain(char *osname, void *txarg)
544 {
545 	zilog_t *zilog;
546 	zil_header_t *zh;
547 	blkptr_t blk;
548 	arc_buf_t *abuf;
549 	objset_t *os;
550 	char *lrbuf;
551 	zil_trailer_t *ztp;
552 	int error;
553 
554 	error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
555 	if (error) {
556 		cmn_err(CE_WARN, "can't open objset for %s", osname);
557 		return (0);
558 	}
559 
560 	zilog = dmu_objset_zil(os);
561 	zh = zil_header_in_syncing_context(zilog);
562 	blk = zh->zh_log;
563 	if (BP_IS_HOLE(&blk)) {
564 		dmu_objset_close(os);
565 		return (0); /* no chain */
566 	}
567 
568 	for (;;) {
569 		error = zil_read_log_block(zilog, &blk, &abuf);
570 		if (error)
571 			break;
572 		lrbuf = abuf->b_data;
573 		ztp = (zil_trailer_t *)(lrbuf + BP_GET_LSIZE(&blk)) - 1;
574 		blk = ztp->zit_next_blk;
575 		VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
576 	}
577 	dmu_objset_close(os);
578 	if (error == ECKSUM)
579 		return (0); /* normal end of chain */
580 	return (error);
581 }
582 
583 /*
584  * Clear a log chain
585  */
586 /* ARGSUSED */
587 int
588 zil_clear_log_chain(char *osname, void *txarg)
589 {
590 	zilog_t *zilog;
591 	zil_header_t *zh;
592 	objset_t *os;
593 	dmu_tx_t *tx;
594 	int error;
595 
596 	error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
597 	if (error) {
598 		cmn_err(CE_WARN, "can't open objset for %s", osname);
599 		return (0);
600 	}
601 
602 	zilog = dmu_objset_zil(os);
603 	tx = dmu_tx_create(zilog->zl_os);
604 	(void) dmu_tx_assign(tx, TXG_WAIT);
605 	zh = zil_header_in_syncing_context(zilog);
606 	BP_ZERO(&zh->zh_log);
607 	dsl_dataset_dirty(dmu_objset_ds(os), tx);
608 	dmu_tx_commit(tx);
609 	dmu_objset_close(os);
610 	return (0);
611 }
612 
613 static int
614 zil_vdev_compare(const void *x1, const void *x2)
615 {
616 	uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
617 	uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
618 
619 	if (v1 < v2)
620 		return (-1);
621 	if (v1 > v2)
622 		return (1);
623 
624 	return (0);
625 }
626 
627 void
628 zil_add_block(zilog_t *zilog, blkptr_t *bp)
629 {
630 	avl_tree_t *t = &zilog->zl_vdev_tree;
631 	avl_index_t where;
632 	zil_vdev_node_t *zv, zvsearch;
633 	int ndvas = BP_GET_NDVAS(bp);
634 	int i;
635 
636 	if (zfs_nocacheflush)
637 		return;
638 
639 	ASSERT(zilog->zl_writer);
640 
641 	/*
642 	 * Even though we're zl_writer, we still need a lock because the
643 	 * zl_get_data() callbacks may have dmu_sync() done callbacks
644 	 * that will run concurrently.
645 	 */
646 	mutex_enter(&zilog->zl_vdev_lock);
647 	for (i = 0; i < ndvas; i++) {
648 		zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
649 		if (avl_find(t, &zvsearch, &where) == NULL) {
650 			zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
651 			zv->zv_vdev = zvsearch.zv_vdev;
652 			avl_insert(t, zv, where);
653 		}
654 	}
655 	mutex_exit(&zilog->zl_vdev_lock);
656 }
657 
658 void
659 zil_flush_vdevs(zilog_t *zilog)
660 {
661 	spa_t *spa = zilog->zl_spa;
662 	avl_tree_t *t = &zilog->zl_vdev_tree;
663 	void *cookie = NULL;
664 	zil_vdev_node_t *zv;
665 	zio_t *zio;
666 
667 	ASSERT(zilog->zl_writer);
668 
669 	/*
670 	 * We don't need zl_vdev_lock here because we're the zl_writer,
671 	 * and all zl_get_data() callbacks are done.
672 	 */
673 	if (avl_numnodes(t) == 0)
674 		return;
675 
676 	spa_config_enter(spa, RW_READER, FTAG);
677 
678 	zio = zio_root(spa, NULL, NULL,
679 	    ZIO_FLAG_CONFIG_HELD | ZIO_FLAG_CANFAIL);
680 
681 	while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
682 		vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
683 		if (vd != NULL)
684 			zio_flush(zio, vd);
685 		kmem_free(zv, sizeof (*zv));
686 	}
687 
688 	/*
689 	 * Wait for all the flushes to complete.  Not all devices actually
690 	 * support the DKIOCFLUSHWRITECACHE ioctl, so it's OK if it fails.
691 	 */
692 	(void) zio_wait(zio);
693 
694 	spa_config_exit(spa, FTAG);
695 }
696 
697 /*
698  * Function called when a log block write completes
699  */
700 static void
701 zil_lwb_write_done(zio_t *zio)
702 {
703 	lwb_t *lwb = zio->io_private;
704 	zilog_t *zilog = lwb->lwb_zilog;
705 
706 	/*
707 	 * Now that we've written this log block, we have a stable pointer
708 	 * to the next block in the chain, so it's OK to let the txg in
709 	 * which we allocated the next block sync.
710 	 */
711 	txg_rele_to_sync(&lwb->lwb_txgh);
712 
713 	zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
714 	mutex_enter(&zilog->zl_lock);
715 	lwb->lwb_buf = NULL;
716 	if (zio->io_error)
717 		zilog->zl_log_error = B_TRUE;
718 	mutex_exit(&zilog->zl_lock);
719 }
720 
721 /*
722  * Initialize the io for a log block.
723  *
724  * Note, we should not initialize the IO until we are about
725  * to use it, since zio_rewrite() does a spa_config_enter().
726  */
727 static void
728 zil_lwb_write_init(zilog_t *zilog, lwb_t *lwb)
729 {
730 	zbookmark_t zb;
731 
732 	zb.zb_objset = lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET];
733 	zb.zb_object = 0;
734 	zb.zb_level = -1;
735 	zb.zb_blkid = lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
736 
737 	if (zilog->zl_root_zio == NULL) {
738 		zilog->zl_root_zio = zio_root(zilog->zl_spa, NULL, NULL,
739 		    ZIO_FLAG_CANFAIL);
740 	}
741 	if (lwb->lwb_zio == NULL) {
742 		lwb->lwb_zio = zio_rewrite(zilog->zl_root_zio, zilog->zl_spa,
743 		    ZIO_CHECKSUM_ZILOG, 0, &lwb->lwb_blk, lwb->lwb_buf,
744 		    lwb->lwb_sz, zil_lwb_write_done, lwb,
745 		    ZIO_PRIORITY_LOG_WRITE, ZIO_FLAG_CANFAIL, &zb);
746 	}
747 }
748 
749 /*
750  * Start a log block write and advance to the next log block.
751  * Calls are serialized.
752  */
753 static lwb_t *
754 zil_lwb_write_start(zilog_t *zilog, lwb_t *lwb)
755 {
756 	lwb_t *nlwb;
757 	zil_trailer_t *ztp = (zil_trailer_t *)(lwb->lwb_buf + lwb->lwb_sz) - 1;
758 	spa_t *spa = zilog->zl_spa;
759 	blkptr_t *bp = &ztp->zit_next_blk;
760 	uint64_t txg;
761 	uint64_t zil_blksz;
762 	int error;
763 
764 	ASSERT(lwb->lwb_nused <= ZIL_BLK_DATA_SZ(lwb));
765 
766 	/*
767 	 * Allocate the next block and save its address in this block
768 	 * before writing it in order to establish the log chain.
769 	 * Note that if the allocation of nlwb synced before we wrote
770 	 * the block that points at it (lwb), we'd leak it if we crashed.
771 	 * Therefore, we don't do txg_rele_to_sync() until zil_lwb_write_done().
772 	 */
773 	txg = txg_hold_open(zilog->zl_dmu_pool, &lwb->lwb_txgh);
774 	txg_rele_to_quiesce(&lwb->lwb_txgh);
775 
776 	/*
777 	 * Pick a ZIL blocksize. We request a size that is the
778 	 * maximum of the previous used size, the current used size and
779 	 * the amount waiting in the queue.
780 	 */
781 	zil_blksz = MAX(zilog->zl_prev_used,
782 	    zilog->zl_cur_used + sizeof (*ztp));
783 	zil_blksz = MAX(zil_blksz, zilog->zl_itx_list_sz + sizeof (*ztp));
784 	zil_blksz = P2ROUNDUP_TYPED(zil_blksz, ZIL_MIN_BLKSZ, uint64_t);
785 	if (zil_blksz > ZIL_MAX_BLKSZ)
786 		zil_blksz = ZIL_MAX_BLKSZ;
787 
788 	BP_ZERO(bp);
789 	/* pass the old blkptr in order to spread log blocks across devs */
790 	error = zio_alloc_blk(spa, zil_blksz, bp, &lwb->lwb_blk, txg);
791 	if (error) {
792 		dmu_tx_t *tx = dmu_tx_create_assigned(zilog->zl_dmu_pool, txg);
793 
794 		/*
795 		 * We dirty the dataset to ensure that zil_sync() will
796 		 * be called to remove this lwb from our zl_lwb_list.
797 		 * Failing to do so, may leave an lwb with a NULL lwb_buf
798 		 * hanging around on the zl_lwb_list.
799 		 */
800 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
801 		dmu_tx_commit(tx);
802 
803 		/*
804 		 * Since we've just experienced an allocation failure so we
805 		 * terminate the current lwb and send it on its way.
806 		 */
807 		ztp->zit_pad = 0;
808 		ztp->zit_nused = lwb->lwb_nused;
809 		ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
810 		zio_nowait(lwb->lwb_zio);
811 
812 		/*
813 		 * By returning NULL the caller will call tx_wait_synced()
814 		 */
815 		return (NULL);
816 	}
817 
818 	ASSERT3U(bp->blk_birth, ==, txg);
819 	ztp->zit_pad = 0;
820 	ztp->zit_nused = lwb->lwb_nused;
821 	ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
822 	bp->blk_cksum = lwb->lwb_blk.blk_cksum;
823 	bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
824 
825 	/*
826 	 * Allocate a new log write buffer (lwb).
827 	 */
828 	nlwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
829 
830 	nlwb->lwb_zilog = zilog;
831 	nlwb->lwb_blk = *bp;
832 	nlwb->lwb_nused = 0;
833 	nlwb->lwb_sz = BP_GET_LSIZE(&nlwb->lwb_blk);
834 	nlwb->lwb_buf = zio_buf_alloc(nlwb->lwb_sz);
835 	nlwb->lwb_max_txg = txg;
836 	nlwb->lwb_zio = NULL;
837 
838 	/*
839 	 * Put new lwb at the end of the log chain
840 	 */
841 	mutex_enter(&zilog->zl_lock);
842 	list_insert_tail(&zilog->zl_lwb_list, nlwb);
843 	mutex_exit(&zilog->zl_lock);
844 
845 	/* Record the block for later vdev flushing */
846 	zil_add_block(zilog, &lwb->lwb_blk);
847 
848 	/*
849 	 * kick off the write for the old log block
850 	 */
851 	dprintf_bp(&lwb->lwb_blk, "lwb %p txg %llu: ", lwb, txg);
852 	ASSERT(lwb->lwb_zio);
853 	zio_nowait(lwb->lwb_zio);
854 
855 	return (nlwb);
856 }
857 
858 static lwb_t *
859 zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb)
860 {
861 	lr_t *lrc = &itx->itx_lr; /* common log record */
862 	lr_write_t *lr = (lr_write_t *)lrc;
863 	uint64_t txg = lrc->lrc_txg;
864 	uint64_t reclen = lrc->lrc_reclen;
865 	uint64_t dlen;
866 
867 	if (lwb == NULL)
868 		return (NULL);
869 	ASSERT(lwb->lwb_buf != NULL);
870 
871 	if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY)
872 		dlen = P2ROUNDUP_TYPED(
873 		    lr->lr_length, sizeof (uint64_t), uint64_t);
874 	else
875 		dlen = 0;
876 
877 	zilog->zl_cur_used += (reclen + dlen);
878 
879 	zil_lwb_write_init(zilog, lwb);
880 
881 	/*
882 	 * If this record won't fit in the current log block, start a new one.
883 	 */
884 	if (lwb->lwb_nused + reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
885 		lwb = zil_lwb_write_start(zilog, lwb);
886 		if (lwb == NULL)
887 			return (NULL);
888 		zil_lwb_write_init(zilog, lwb);
889 		ASSERT(lwb->lwb_nused == 0);
890 		if (reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
891 			txg_wait_synced(zilog->zl_dmu_pool, txg);
892 			return (lwb);
893 		}
894 	}
895 
896 	/*
897 	 * Update the lrc_seq, to be log record sequence number. See zil.h
898 	 * Then copy the record to the log buffer.
899 	 */
900 	lrc->lrc_seq = ++zilog->zl_lr_seq; /* we are single threaded */
901 	bcopy(lrc, lwb->lwb_buf + lwb->lwb_nused, reclen);
902 
903 	/*
904 	 * If it's a write, fetch the data or get its blkptr as appropriate.
905 	 */
906 	if (lrc->lrc_txtype == TX_WRITE) {
907 		if (txg > spa_freeze_txg(zilog->zl_spa))
908 			txg_wait_synced(zilog->zl_dmu_pool, txg);
909 		if (itx->itx_wr_state != WR_COPIED) {
910 			char *dbuf;
911 			int error;
912 
913 			/* alignment is guaranteed */
914 			lr = (lr_write_t *)(lwb->lwb_buf + lwb->lwb_nused);
915 			if (dlen) {
916 				ASSERT(itx->itx_wr_state == WR_NEED_COPY);
917 				dbuf = lwb->lwb_buf + lwb->lwb_nused + reclen;
918 				lr->lr_common.lrc_reclen += dlen;
919 			} else {
920 				ASSERT(itx->itx_wr_state == WR_INDIRECT);
921 				dbuf = NULL;
922 			}
923 			error = zilog->zl_get_data(
924 			    itx->itx_private, lr, dbuf, lwb->lwb_zio);
925 			if (error) {
926 				ASSERT(error == ENOENT || error == EEXIST ||
927 				    error == EALREADY);
928 				return (lwb);
929 			}
930 		}
931 	}
932 
933 	lwb->lwb_nused += reclen + dlen;
934 	lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
935 	ASSERT3U(lwb->lwb_nused, <=, ZIL_BLK_DATA_SZ(lwb));
936 	ASSERT3U(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)), ==, 0);
937 
938 	return (lwb);
939 }
940 
941 itx_t *
942 zil_itx_create(uint64_t txtype, size_t lrsize)
943 {
944 	itx_t *itx;
945 
946 	lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t);
947 
948 	itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP);
949 	itx->itx_lr.lrc_txtype = txtype;
950 	itx->itx_lr.lrc_reclen = lrsize;
951 	itx->itx_sod = lrsize; /* if write & WR_NEED_COPY will be increased */
952 	itx->itx_lr.lrc_seq = 0;	/* defensive */
953 
954 	return (itx);
955 }
956 
957 uint64_t
958 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
959 {
960 	uint64_t seq;
961 
962 	ASSERT(itx->itx_lr.lrc_seq == 0);
963 
964 	mutex_enter(&zilog->zl_lock);
965 	list_insert_tail(&zilog->zl_itx_list, itx);
966 	zilog->zl_itx_list_sz += itx->itx_sod;
967 	itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
968 	itx->itx_lr.lrc_seq = seq = ++zilog->zl_itx_seq;
969 	mutex_exit(&zilog->zl_lock);
970 
971 	return (seq);
972 }
973 
974 /*
975  * Free up all in-memory intent log transactions that have now been synced.
976  */
977 static void
978 zil_itx_clean(zilog_t *zilog)
979 {
980 	uint64_t synced_txg = spa_last_synced_txg(zilog->zl_spa);
981 	uint64_t freeze_txg = spa_freeze_txg(zilog->zl_spa);
982 	list_t clean_list;
983 	itx_t *itx;
984 
985 	list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
986 
987 	mutex_enter(&zilog->zl_lock);
988 	/* wait for a log writer to finish walking list */
989 	while (zilog->zl_writer) {
990 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
991 	}
992 
993 	/*
994 	 * Move the sync'd log transactions to a separate list so we can call
995 	 * kmem_free without holding the zl_lock.
996 	 *
997 	 * There is no need to set zl_writer as we don't drop zl_lock here
998 	 */
999 	while ((itx = list_head(&zilog->zl_itx_list)) != NULL &&
1000 	    itx->itx_lr.lrc_txg <= MIN(synced_txg, freeze_txg)) {
1001 		list_remove(&zilog->zl_itx_list, itx);
1002 		zilog->zl_itx_list_sz -= itx->itx_sod;
1003 		list_insert_tail(&clean_list, itx);
1004 	}
1005 	cv_broadcast(&zilog->zl_cv_writer);
1006 	mutex_exit(&zilog->zl_lock);
1007 
1008 	/* destroy sync'd log transactions */
1009 	while ((itx = list_head(&clean_list)) != NULL) {
1010 		list_remove(&clean_list, itx);
1011 		kmem_free(itx, offsetof(itx_t, itx_lr)
1012 		    + itx->itx_lr.lrc_reclen);
1013 	}
1014 	list_destroy(&clean_list);
1015 }
1016 
1017 /*
1018  * If there are any in-memory intent log transactions which have now been
1019  * synced then start up a taskq to free them.
1020  */
1021 void
1022 zil_clean(zilog_t *zilog)
1023 {
1024 	itx_t *itx;
1025 
1026 	mutex_enter(&zilog->zl_lock);
1027 	itx = list_head(&zilog->zl_itx_list);
1028 	if ((itx != NULL) &&
1029 	    (itx->itx_lr.lrc_txg <= spa_last_synced_txg(zilog->zl_spa))) {
1030 		(void) taskq_dispatch(zilog->zl_clean_taskq,
1031 		    (void (*)(void *))zil_itx_clean, zilog, TQ_NOSLEEP);
1032 	}
1033 	mutex_exit(&zilog->zl_lock);
1034 }
1035 
1036 void
1037 zil_commit_writer(zilog_t *zilog, uint64_t seq, uint64_t foid)
1038 {
1039 	uint64_t txg;
1040 	uint64_t commit_seq = 0;
1041 	itx_t *itx, *itx_next = (itx_t *)-1;
1042 	lwb_t *lwb;
1043 	spa_t *spa;
1044 
1045 	zilog->zl_writer = B_TRUE;
1046 	zilog->zl_root_zio = NULL;
1047 	spa = zilog->zl_spa;
1048 
1049 	if (zilog->zl_suspend) {
1050 		lwb = NULL;
1051 	} else {
1052 		lwb = list_tail(&zilog->zl_lwb_list);
1053 		if (lwb == NULL) {
1054 			/*
1055 			 * Return if there's nothing to flush before we
1056 			 * dirty the fs by calling zil_create()
1057 			 */
1058 			if (list_is_empty(&zilog->zl_itx_list)) {
1059 				zilog->zl_writer = B_FALSE;
1060 				return;
1061 			}
1062 			mutex_exit(&zilog->zl_lock);
1063 			zil_create(zilog);
1064 			mutex_enter(&zilog->zl_lock);
1065 			lwb = list_tail(&zilog->zl_lwb_list);
1066 		}
1067 	}
1068 
1069 	/* Loop through in-memory log transactions filling log blocks. */
1070 	DTRACE_PROBE1(zil__cw1, zilog_t *, zilog);
1071 	for (;;) {
1072 		/*
1073 		 * Find the next itx to push:
1074 		 * Push all transactions related to specified foid and all
1075 		 * other transactions except TX_WRITE, TX_TRUNCATE,
1076 		 * TX_SETATTR and TX_ACL for all other files.
1077 		 */
1078 		if (itx_next != (itx_t *)-1)
1079 			itx = itx_next;
1080 		else
1081 			itx = list_head(&zilog->zl_itx_list);
1082 		for (; itx != NULL; itx = list_next(&zilog->zl_itx_list, itx)) {
1083 			if (foid == 0) /* push all foids? */
1084 				break;
1085 			if (itx->itx_sync) /* push all O_[D]SYNC */
1086 				break;
1087 			switch (itx->itx_lr.lrc_txtype) {
1088 			case TX_SETATTR:
1089 			case TX_WRITE:
1090 			case TX_TRUNCATE:
1091 			case TX_ACL:
1092 				/* lr_foid is same offset for these records */
1093 				if (((lr_write_t *)&itx->itx_lr)->lr_foid
1094 				    != foid) {
1095 					continue; /* skip this record */
1096 				}
1097 			}
1098 			break;
1099 		}
1100 		if (itx == NULL)
1101 			break;
1102 
1103 		if ((itx->itx_lr.lrc_seq > seq) &&
1104 		    ((lwb == NULL) || (lwb->lwb_nused == 0) ||
1105 		    (lwb->lwb_nused + itx->itx_sod > ZIL_BLK_DATA_SZ(lwb)))) {
1106 			break;
1107 		}
1108 
1109 		/*
1110 		 * Save the next pointer.  Even though we soon drop
1111 		 * zl_lock all threads that may change the list
1112 		 * (another writer or zil_itx_clean) can't do so until
1113 		 * they have zl_writer.
1114 		 */
1115 		itx_next = list_next(&zilog->zl_itx_list, itx);
1116 		list_remove(&zilog->zl_itx_list, itx);
1117 		zilog->zl_itx_list_sz -= itx->itx_sod;
1118 		mutex_exit(&zilog->zl_lock);
1119 		txg = itx->itx_lr.lrc_txg;
1120 		ASSERT(txg);
1121 
1122 		if (txg > spa_last_synced_txg(spa) ||
1123 		    txg > spa_freeze_txg(spa))
1124 			lwb = zil_lwb_commit(zilog, itx, lwb);
1125 		kmem_free(itx, offsetof(itx_t, itx_lr)
1126 		    + itx->itx_lr.lrc_reclen);
1127 		mutex_enter(&zilog->zl_lock);
1128 	}
1129 	DTRACE_PROBE1(zil__cw2, zilog_t *, zilog);
1130 	/* determine commit sequence number */
1131 	itx = list_head(&zilog->zl_itx_list);
1132 	if (itx)
1133 		commit_seq = itx->itx_lr.lrc_seq;
1134 	else
1135 		commit_seq = zilog->zl_itx_seq;
1136 	mutex_exit(&zilog->zl_lock);
1137 
1138 	/* write the last block out */
1139 	if (lwb != NULL && lwb->lwb_zio != NULL)
1140 		lwb = zil_lwb_write_start(zilog, lwb);
1141 
1142 	zilog->zl_prev_used = zilog->zl_cur_used;
1143 	zilog->zl_cur_used = 0;
1144 
1145 	/*
1146 	 * Wait if necessary for the log blocks to be on stable storage.
1147 	 */
1148 	if (zilog->zl_root_zio) {
1149 		DTRACE_PROBE1(zil__cw3, zilog_t *, zilog);
1150 		(void) zio_wait(zilog->zl_root_zio);
1151 		DTRACE_PROBE1(zil__cw4, zilog_t *, zilog);
1152 		zil_flush_vdevs(zilog);
1153 	}
1154 
1155 	if (zilog->zl_log_error || lwb == NULL) {
1156 		zilog->zl_log_error = 0;
1157 		txg_wait_synced(zilog->zl_dmu_pool, 0);
1158 	}
1159 
1160 	mutex_enter(&zilog->zl_lock);
1161 	zilog->zl_writer = B_FALSE;
1162 
1163 	ASSERT3U(commit_seq, >=, zilog->zl_commit_seq);
1164 	zilog->zl_commit_seq = commit_seq;
1165 }
1166 
1167 /*
1168  * Push zfs transactions to stable storage up to the supplied sequence number.
1169  * If foid is 0 push out all transactions, otherwise push only those
1170  * for that file or might have been used to create that file.
1171  */
1172 void
1173 zil_commit(zilog_t *zilog, uint64_t seq, uint64_t foid)
1174 {
1175 	if (zilog == NULL || seq == 0)
1176 		return;
1177 
1178 	mutex_enter(&zilog->zl_lock);
1179 
1180 	seq = MIN(seq, zilog->zl_itx_seq);	/* cap seq at largest itx seq */
1181 
1182 	while (zilog->zl_writer) {
1183 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1184 		if (seq < zilog->zl_commit_seq) {
1185 			mutex_exit(&zilog->zl_lock);
1186 			return;
1187 		}
1188 	}
1189 	zil_commit_writer(zilog, seq, foid); /* drops zl_lock */
1190 	/* wake up others waiting on the commit */
1191 	cv_broadcast(&zilog->zl_cv_writer);
1192 	mutex_exit(&zilog->zl_lock);
1193 }
1194 
1195 /*
1196  * Called in syncing context to free committed log blocks and update log header.
1197  */
1198 void
1199 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
1200 {
1201 	zil_header_t *zh = zil_header_in_syncing_context(zilog);
1202 	uint64_t txg = dmu_tx_get_txg(tx);
1203 	spa_t *spa = zilog->zl_spa;
1204 	lwb_t *lwb;
1205 
1206 	mutex_enter(&zilog->zl_lock);
1207 
1208 	ASSERT(zilog->zl_stop_sync == 0);
1209 
1210 	zh->zh_replay_seq = zilog->zl_replay_seq[txg & TXG_MASK];
1211 
1212 	if (zilog->zl_destroy_txg == txg) {
1213 		blkptr_t blk = zh->zh_log;
1214 
1215 		ASSERT(list_head(&zilog->zl_lwb_list) == NULL);
1216 		ASSERT(spa_sync_pass(spa) == 1);
1217 
1218 		bzero(zh, sizeof (zil_header_t));
1219 		bzero(zilog->zl_replay_seq, sizeof (zilog->zl_replay_seq));
1220 
1221 		if (zilog->zl_keep_first) {
1222 			/*
1223 			 * If this block was part of log chain that couldn't
1224 			 * be claimed because a device was missing during
1225 			 * zil_claim(), but that device later returns,
1226 			 * then this block could erroneously appear valid.
1227 			 * To guard against this, assign a new GUID to the new
1228 			 * log chain so it doesn't matter what blk points to.
1229 			 */
1230 			zil_init_log_chain(zilog, &blk);
1231 			zh->zh_log = blk;
1232 		}
1233 	}
1234 
1235 	for (;;) {
1236 		lwb = list_head(&zilog->zl_lwb_list);
1237 		if (lwb == NULL) {
1238 			mutex_exit(&zilog->zl_lock);
1239 			return;
1240 		}
1241 		zh->zh_log = lwb->lwb_blk;
1242 		if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg)
1243 			break;
1244 		list_remove(&zilog->zl_lwb_list, lwb);
1245 		zio_free_blk(spa, &lwb->lwb_blk, txg);
1246 		kmem_cache_free(zil_lwb_cache, lwb);
1247 
1248 		/*
1249 		 * If we don't have anything left in the lwb list then
1250 		 * we've had an allocation failure and we need to zero
1251 		 * out the zil_header blkptr so that we don't end
1252 		 * up freeing the same block twice.
1253 		 */
1254 		if (list_head(&zilog->zl_lwb_list) == NULL)
1255 			BP_ZERO(&zh->zh_log);
1256 	}
1257 	mutex_exit(&zilog->zl_lock);
1258 }
1259 
1260 void
1261 zil_init(void)
1262 {
1263 	zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
1264 	    sizeof (struct lwb), 0, NULL, NULL, NULL, NULL, NULL, 0);
1265 }
1266 
1267 void
1268 zil_fini(void)
1269 {
1270 	kmem_cache_destroy(zil_lwb_cache);
1271 }
1272 
1273 zilog_t *
1274 zil_alloc(objset_t *os, zil_header_t *zh_phys)
1275 {
1276 	zilog_t *zilog;
1277 
1278 	zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
1279 
1280 	zilog->zl_header = zh_phys;
1281 	zilog->zl_os = os;
1282 	zilog->zl_spa = dmu_objset_spa(os);
1283 	zilog->zl_dmu_pool = dmu_objset_pool(os);
1284 	zilog->zl_destroy_txg = TXG_INITIAL - 1;
1285 
1286 	mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
1287 
1288 	list_create(&zilog->zl_itx_list, sizeof (itx_t),
1289 	    offsetof(itx_t, itx_node));
1290 
1291 	list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
1292 	    offsetof(lwb_t, lwb_node));
1293 
1294 	mutex_init(&zilog->zl_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
1295 
1296 	avl_create(&zilog->zl_vdev_tree, zil_vdev_compare,
1297 	    sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
1298 
1299 	cv_init(&zilog->zl_cv_writer, NULL, CV_DEFAULT, NULL);
1300 	cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
1301 
1302 	return (zilog);
1303 }
1304 
1305 void
1306 zil_free(zilog_t *zilog)
1307 {
1308 	lwb_t *lwb;
1309 
1310 	zilog->zl_stop_sync = 1;
1311 
1312 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
1313 		list_remove(&zilog->zl_lwb_list, lwb);
1314 		if (lwb->lwb_buf != NULL)
1315 			zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1316 		kmem_cache_free(zil_lwb_cache, lwb);
1317 	}
1318 	list_destroy(&zilog->zl_lwb_list);
1319 
1320 	avl_destroy(&zilog->zl_vdev_tree);
1321 	mutex_destroy(&zilog->zl_vdev_lock);
1322 
1323 	ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1324 	list_destroy(&zilog->zl_itx_list);
1325 	mutex_destroy(&zilog->zl_lock);
1326 
1327 	cv_destroy(&zilog->zl_cv_writer);
1328 	cv_destroy(&zilog->zl_cv_suspend);
1329 
1330 	kmem_free(zilog, sizeof (zilog_t));
1331 }
1332 
1333 /*
1334  * return true if the initial log block is not valid
1335  */
1336 static boolean_t
1337 zil_empty(zilog_t *zilog)
1338 {
1339 	const zil_header_t *zh = zilog->zl_header;
1340 	arc_buf_t *abuf = NULL;
1341 
1342 	if (BP_IS_HOLE(&zh->zh_log))
1343 		return (B_TRUE);
1344 
1345 	if (zil_read_log_block(zilog, &zh->zh_log, &abuf) != 0)
1346 		return (B_TRUE);
1347 
1348 	VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
1349 	return (B_FALSE);
1350 }
1351 
1352 /*
1353  * Open an intent log.
1354  */
1355 zilog_t *
1356 zil_open(objset_t *os, zil_get_data_t *get_data)
1357 {
1358 	zilog_t *zilog = dmu_objset_zil(os);
1359 
1360 	zilog->zl_get_data = get_data;
1361 	zilog->zl_clean_taskq = taskq_create("zil_clean", 1, minclsyspri,
1362 	    2, 2, TASKQ_PREPOPULATE);
1363 
1364 	return (zilog);
1365 }
1366 
1367 /*
1368  * Close an intent log.
1369  */
1370 void
1371 zil_close(zilog_t *zilog)
1372 {
1373 	/*
1374 	 * If the log isn't already committed, mark the objset dirty
1375 	 * (so zil_sync() will be called) and wait for that txg to sync.
1376 	 */
1377 	if (!zil_is_committed(zilog)) {
1378 		uint64_t txg;
1379 		dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
1380 		(void) dmu_tx_assign(tx, TXG_WAIT);
1381 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1382 		txg = dmu_tx_get_txg(tx);
1383 		dmu_tx_commit(tx);
1384 		txg_wait_synced(zilog->zl_dmu_pool, txg);
1385 	}
1386 
1387 	taskq_destroy(zilog->zl_clean_taskq);
1388 	zilog->zl_clean_taskq = NULL;
1389 	zilog->zl_get_data = NULL;
1390 
1391 	zil_itx_clean(zilog);
1392 	ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1393 }
1394 
1395 /*
1396  * Suspend an intent log.  While in suspended mode, we still honor
1397  * synchronous semantics, but we rely on txg_wait_synced() to do it.
1398  * We suspend the log briefly when taking a snapshot so that the snapshot
1399  * contains all the data it's supposed to, and has an empty intent log.
1400  */
1401 int
1402 zil_suspend(zilog_t *zilog)
1403 {
1404 	const zil_header_t *zh = zilog->zl_header;
1405 
1406 	mutex_enter(&zilog->zl_lock);
1407 	if (zh->zh_claim_txg != 0) {		/* unplayed log */
1408 		mutex_exit(&zilog->zl_lock);
1409 		return (EBUSY);
1410 	}
1411 	if (zilog->zl_suspend++ != 0) {
1412 		/*
1413 		 * Someone else already began a suspend.
1414 		 * Just wait for them to finish.
1415 		 */
1416 		while (zilog->zl_suspending)
1417 			cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
1418 		mutex_exit(&zilog->zl_lock);
1419 		return (0);
1420 	}
1421 	zilog->zl_suspending = B_TRUE;
1422 	mutex_exit(&zilog->zl_lock);
1423 
1424 	zil_commit(zilog, UINT64_MAX, 0);
1425 
1426 	/*
1427 	 * Wait for any in-flight log writes to complete.
1428 	 */
1429 	mutex_enter(&zilog->zl_lock);
1430 	while (zilog->zl_writer)
1431 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1432 	mutex_exit(&zilog->zl_lock);
1433 
1434 	zil_destroy(zilog, B_FALSE);
1435 
1436 	mutex_enter(&zilog->zl_lock);
1437 	zilog->zl_suspending = B_FALSE;
1438 	cv_broadcast(&zilog->zl_cv_suspend);
1439 	mutex_exit(&zilog->zl_lock);
1440 
1441 	return (0);
1442 }
1443 
1444 void
1445 zil_resume(zilog_t *zilog)
1446 {
1447 	mutex_enter(&zilog->zl_lock);
1448 	ASSERT(zilog->zl_suspend != 0);
1449 	zilog->zl_suspend--;
1450 	mutex_exit(&zilog->zl_lock);
1451 }
1452 
1453 typedef struct zil_replay_arg {
1454 	objset_t	*zr_os;
1455 	zil_replay_func_t **zr_replay;
1456 	void		*zr_arg;
1457 	uint64_t	*zr_txgp;
1458 	boolean_t	zr_byteswap;
1459 	char		*zr_lrbuf;
1460 } zil_replay_arg_t;
1461 
1462 static void
1463 zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg)
1464 {
1465 	zil_replay_arg_t *zr = zra;
1466 	const zil_header_t *zh = zilog->zl_header;
1467 	uint64_t reclen = lr->lrc_reclen;
1468 	uint64_t txtype = lr->lrc_txtype;
1469 	char *name;
1470 	int pass, error, sunk;
1471 
1472 	if (zilog->zl_stop_replay)
1473 		return;
1474 
1475 	if (lr->lrc_txg < claim_txg)		/* already committed */
1476 		return;
1477 
1478 	if (lr->lrc_seq <= zh->zh_replay_seq)	/* already replayed */
1479 		return;
1480 
1481 	/* Strip case-insensitive bit, still present in log record */
1482 	txtype &= ~TX_CI;
1483 
1484 	/*
1485 	 * Make a copy of the data so we can revise and extend it.
1486 	 */
1487 	bcopy(lr, zr->zr_lrbuf, reclen);
1488 
1489 	/*
1490 	 * The log block containing this lr may have been byteswapped
1491 	 * so that we can easily examine common fields like lrc_txtype.
1492 	 * However, the log is a mix of different data types, and only the
1493 	 * replay vectors know how to byteswap their records.  Therefore, if
1494 	 * the lr was byteswapped, undo it before invoking the replay vector.
1495 	 */
1496 	if (zr->zr_byteswap)
1497 		byteswap_uint64_array(zr->zr_lrbuf, reclen);
1498 
1499 	/*
1500 	 * If this is a TX_WRITE with a blkptr, suck in the data.
1501 	 */
1502 	if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
1503 		lr_write_t *lrw = (lr_write_t *)lr;
1504 		blkptr_t *wbp = &lrw->lr_blkptr;
1505 		uint64_t wlen = lrw->lr_length;
1506 		char *wbuf = zr->zr_lrbuf + reclen;
1507 
1508 		if (BP_IS_HOLE(wbp)) {	/* compressed to a hole */
1509 			bzero(wbuf, wlen);
1510 		} else {
1511 			/*
1512 			 * A subsequent write may have overwritten this block,
1513 			 * in which case wbp may have been been freed and
1514 			 * reallocated, and our read of wbp may fail with a
1515 			 * checksum error.  We can safely ignore this because
1516 			 * the later write will provide the correct data.
1517 			 */
1518 			zbookmark_t zb;
1519 
1520 			zb.zb_objset = dmu_objset_id(zilog->zl_os);
1521 			zb.zb_object = lrw->lr_foid;
1522 			zb.zb_level = -1;
1523 			zb.zb_blkid = lrw->lr_offset / BP_GET_LSIZE(wbp);
1524 
1525 			(void) zio_wait(zio_read(NULL, zilog->zl_spa,
1526 			    wbp, wbuf, BP_GET_LSIZE(wbp), NULL, NULL,
1527 			    ZIO_PRIORITY_SYNC_READ,
1528 			    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE, &zb));
1529 			(void) memmove(wbuf, wbuf + lrw->lr_blkoff, wlen);
1530 		}
1531 	}
1532 
1533 	/*
1534 	 * We must now do two things atomically: replay this log record,
1535 	 * and update the log header to reflect the fact that we did so.
1536 	 * We use the DMU's ability to assign into a specific txg to do this.
1537 	 */
1538 	for (pass = 1, sunk = B_FALSE; /* CONSTANTCONDITION */; pass++) {
1539 		uint64_t replay_txg;
1540 		dmu_tx_t *replay_tx;
1541 
1542 		replay_tx = dmu_tx_create(zr->zr_os);
1543 		error = dmu_tx_assign(replay_tx, TXG_WAIT);
1544 		if (error) {
1545 			dmu_tx_abort(replay_tx);
1546 			break;
1547 		}
1548 
1549 		replay_txg = dmu_tx_get_txg(replay_tx);
1550 
1551 		if (txtype == 0 || txtype >= TX_MAX_TYPE) {
1552 			error = EINVAL;
1553 		} else {
1554 			/*
1555 			 * On the first pass, arrange for the replay vector
1556 			 * to fail its dmu_tx_assign().  That's the only way
1557 			 * to ensure that those code paths remain well tested.
1558 			 *
1559 			 * Only byteswap (if needed) on the 1st pass.
1560 			 */
1561 			*zr->zr_txgp = replay_txg - (pass == 1);
1562 			error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lrbuf,
1563 			    zr->zr_byteswap && pass == 1);
1564 			*zr->zr_txgp = TXG_NOWAIT;
1565 		}
1566 
1567 		if (error == 0) {
1568 			dsl_dataset_dirty(dmu_objset_ds(zr->zr_os), replay_tx);
1569 			zilog->zl_replay_seq[replay_txg & TXG_MASK] =
1570 			    lr->lrc_seq;
1571 		}
1572 
1573 		dmu_tx_commit(replay_tx);
1574 
1575 		if (!error)
1576 			return;
1577 
1578 		/*
1579 		 * The DMU's dnode layer doesn't see removes until the txg
1580 		 * commits, so a subsequent claim can spuriously fail with
1581 		 * EEXIST. So if we receive any error other than ERESTART
1582 		 * we try syncing out any removes then retrying the
1583 		 * transaction.
1584 		 */
1585 		if (error != ERESTART && !sunk) {
1586 			txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
1587 			sunk = B_TRUE;
1588 			continue; /* retry */
1589 		}
1590 
1591 		if (error != ERESTART)
1592 			break;
1593 
1594 		if (pass != 1)
1595 			txg_wait_open(spa_get_dsl(zilog->zl_spa),
1596 			    replay_txg + 1);
1597 
1598 		dprintf("pass %d, retrying\n", pass);
1599 	}
1600 
1601 	ASSERT(error && error != ERESTART);
1602 	name = kmem_alloc(MAXNAMELEN, KM_SLEEP);
1603 	dmu_objset_name(zr->zr_os, name);
1604 	cmn_err(CE_WARN, "ZFS replay transaction error %d, "
1605 	    "dataset %s, seq 0x%llx, txtype %llu %s\n",
1606 	    error, name, (u_longlong_t)lr->lrc_seq, (u_longlong_t)txtype,
1607 	    (lr->lrc_txtype & TX_CI) ? "CI" : "");
1608 	zilog->zl_stop_replay = 1;
1609 	kmem_free(name, MAXNAMELEN);
1610 }
1611 
1612 /* ARGSUSED */
1613 static void
1614 zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1615 {
1616 	zilog->zl_replay_blks++;
1617 }
1618 
1619 /*
1620  * If this dataset has a non-empty intent log, replay it and destroy it.
1621  */
1622 void
1623 zil_replay(objset_t *os, void *arg, uint64_t *txgp,
1624 	zil_replay_func_t *replay_func[TX_MAX_TYPE])
1625 {
1626 	zilog_t *zilog = dmu_objset_zil(os);
1627 	const zil_header_t *zh = zilog->zl_header;
1628 	zil_replay_arg_t zr;
1629 
1630 	if (zil_empty(zilog)) {
1631 		zil_destroy(zilog, B_TRUE);
1632 		return;
1633 	}
1634 
1635 	zr.zr_os = os;
1636 	zr.zr_replay = replay_func;
1637 	zr.zr_arg = arg;
1638 	zr.zr_txgp = txgp;
1639 	zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
1640 	zr.zr_lrbuf = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
1641 
1642 	/*
1643 	 * Wait for in-progress removes to sync before starting replay.
1644 	 */
1645 	txg_wait_synced(zilog->zl_dmu_pool, 0);
1646 
1647 	zilog->zl_stop_replay = 0;
1648 	zilog->zl_replay_time = lbolt;
1649 	ASSERT(zilog->zl_replay_blks == 0);
1650 	(void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
1651 	    zh->zh_claim_txg);
1652 	kmem_free(zr.zr_lrbuf, 2 * SPA_MAXBLOCKSIZE);
1653 
1654 	zil_destroy(zilog, B_FALSE);
1655 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
1656 }
1657 
1658 /*
1659  * Report whether all transactions are committed
1660  */
1661 int
1662 zil_is_committed(zilog_t *zilog)
1663 {
1664 	lwb_t *lwb;
1665 	int ret;
1666 
1667 	mutex_enter(&zilog->zl_lock);
1668 	while (zilog->zl_writer)
1669 		cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1670 
1671 	/* recent unpushed intent log transactions? */
1672 	if (!list_is_empty(&zilog->zl_itx_list)) {
1673 		ret = B_FALSE;
1674 		goto out;
1675 	}
1676 
1677 	/* intent log never used? */
1678 	lwb = list_head(&zilog->zl_lwb_list);
1679 	if (lwb == NULL) {
1680 		ret = B_TRUE;
1681 		goto out;
1682 	}
1683 
1684 	/*
1685 	 * more than 1 log buffer means zil_sync() hasn't yet freed
1686 	 * entries after a txg has committed
1687 	 */
1688 	if (list_next(&zilog->zl_lwb_list, lwb)) {
1689 		ret = B_FALSE;
1690 		goto out;
1691 	}
1692 
1693 	ASSERT(zil_empty(zilog));
1694 	ret = B_TRUE;
1695 out:
1696 	cv_broadcast(&zilog->zl_cv_writer);
1697 	mutex_exit(&zilog->zl_lock);
1698 	return (ret);
1699 }
1700