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