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