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