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 https://opensource.org/licenses/CDDL-1.0.
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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright (c) 2011, 2018 by Delphix. All rights reserved.
24  * Copyright (c) 2014 Integros [integros.com]
25  * Copyright (c) 2018 Datto Inc.
26  */
27 
28 /* Portions Copyright 2010 Robert Milkowski */
29 
30 #include <sys/zfs_context.h>
31 #include <sys/spa.h>
32 #include <sys/spa_impl.h>
33 #include <sys/dmu.h>
34 #include <sys/zap.h>
35 #include <sys/arc.h>
36 #include <sys/stat.h>
37 #include <sys/zil.h>
38 #include <sys/zil_impl.h>
39 #include <sys/dsl_dataset.h>
40 #include <sys/vdev_impl.h>
41 #include <sys/dmu_tx.h>
42 #include <sys/dsl_pool.h>
43 #include <sys/metaslab.h>
44 #include <sys/trace_zfs.h>
45 #include <sys/abd.h>
46 #include <sys/brt.h>
47 #include <sys/wmsum.h>
48 
49 /*
50  * The ZFS Intent Log (ZIL) saves "transaction records" (itxs) of system
51  * calls that change the file system. Each itx has enough information to
52  * be able to replay them after a system crash, power loss, or
53  * equivalent failure mode. These are stored in memory until either:
54  *
55  *   1. they are committed to the pool by the DMU transaction group
56  *      (txg), at which point they can be discarded; or
57  *   2. they are committed to the on-disk ZIL for the dataset being
58  *      modified (e.g. due to an fsync, O_DSYNC, or other synchronous
59  *      requirement).
60  *
61  * In the event of a crash or power loss, the itxs contained by each
62  * dataset's on-disk ZIL will be replayed when that dataset is first
63  * instantiated (e.g. if the dataset is a normal filesystem, when it is
64  * first mounted).
65  *
66  * As hinted at above, there is one ZIL per dataset (both the in-memory
67  * representation, and the on-disk representation). The on-disk format
68  * consists of 3 parts:
69  *
70  * 	- a single, per-dataset, ZIL header; which points to a chain of
71  * 	- zero or more ZIL blocks; each of which contains
72  * 	- zero or more ZIL records
73  *
74  * A ZIL record holds the information necessary to replay a single
75  * system call transaction. A ZIL block can hold many ZIL records, and
76  * the blocks are chained together, similarly to a singly linked list.
77  *
78  * Each ZIL block contains a block pointer (blkptr_t) to the next ZIL
79  * block in the chain, and the ZIL header points to the first block in
80  * the chain.
81  *
82  * Note, there is not a fixed place in the pool to hold these ZIL
83  * blocks; they are dynamically allocated and freed as needed from the
84  * blocks available on the pool, though they can be preferentially
85  * allocated from a dedicated "log" vdev.
86  */
87 
88 /*
89  * This controls the amount of time that a ZIL block (lwb) will remain
90  * "open" when it isn't "full", and it has a thread waiting for it to be
91  * committed to stable storage. Please refer to the zil_commit_waiter()
92  * function (and the comments within it) for more details.
93  */
94 static uint_t zfs_commit_timeout_pct = 10;
95 
96 /*
97  * See zil.h for more information about these fields.
98  */
99 static zil_kstat_values_t zil_stats = {
100 	{ "zil_commit_count",			KSTAT_DATA_UINT64 },
101 	{ "zil_commit_writer_count",		KSTAT_DATA_UINT64 },
102 	{ "zil_itx_count",			KSTAT_DATA_UINT64 },
103 	{ "zil_itx_indirect_count",		KSTAT_DATA_UINT64 },
104 	{ "zil_itx_indirect_bytes",		KSTAT_DATA_UINT64 },
105 	{ "zil_itx_copied_count",		KSTAT_DATA_UINT64 },
106 	{ "zil_itx_copied_bytes",		KSTAT_DATA_UINT64 },
107 	{ "zil_itx_needcopy_count",		KSTAT_DATA_UINT64 },
108 	{ "zil_itx_needcopy_bytes",		KSTAT_DATA_UINT64 },
109 	{ "zil_itx_metaslab_normal_count",	KSTAT_DATA_UINT64 },
110 	{ "zil_itx_metaslab_normal_bytes",	KSTAT_DATA_UINT64 },
111 	{ "zil_itx_metaslab_normal_write",	KSTAT_DATA_UINT64 },
112 	{ "zil_itx_metaslab_normal_alloc",	KSTAT_DATA_UINT64 },
113 	{ "zil_itx_metaslab_slog_count",	KSTAT_DATA_UINT64 },
114 	{ "zil_itx_metaslab_slog_bytes",	KSTAT_DATA_UINT64 },
115 	{ "zil_itx_metaslab_slog_write",	KSTAT_DATA_UINT64 },
116 	{ "zil_itx_metaslab_slog_alloc",	KSTAT_DATA_UINT64 },
117 };
118 
119 static zil_sums_t zil_sums_global;
120 static kstat_t *zil_kstats_global;
121 
122 /*
123  * Disable intent logging replay.  This global ZIL switch affects all pools.
124  */
125 int zil_replay_disable = 0;
126 
127 /*
128  * Disable the DKIOCFLUSHWRITECACHE commands that are normally sent to
129  * the disk(s) by the ZIL after an LWB write has completed. Setting this
130  * will cause ZIL corruption on power loss if a volatile out-of-order
131  * write cache is enabled.
132  */
133 static int zil_nocacheflush = 0;
134 
135 /*
136  * Limit SLOG write size per commit executed with synchronous priority.
137  * Any writes above that will be executed with lower (asynchronous) priority
138  * to limit potential SLOG device abuse by single active ZIL writer.
139  */
140 static uint64_t zil_slog_bulk = 64 * 1024 * 1024;
141 
142 static kmem_cache_t *zil_lwb_cache;
143 static kmem_cache_t *zil_zcw_cache;
144 
145 static void zil_lwb_commit(zilog_t *zilog, lwb_t *lwb, itx_t *itx);
146 static itx_t *zil_itx_clone(itx_t *oitx);
147 static uint64_t zil_max_waste_space(zilog_t *zilog);
148 
149 static int
zil_bp_compare(const void * x1,const void * x2)150 zil_bp_compare(const void *x1, const void *x2)
151 {
152 	const dva_t *dva1 = &((zil_bp_node_t *)x1)->zn_dva;
153 	const dva_t *dva2 = &((zil_bp_node_t *)x2)->zn_dva;
154 
155 	int cmp = TREE_CMP(DVA_GET_VDEV(dva1), DVA_GET_VDEV(dva2));
156 	if (likely(cmp))
157 		return (cmp);
158 
159 	return (TREE_CMP(DVA_GET_OFFSET(dva1), DVA_GET_OFFSET(dva2)));
160 }
161 
162 static void
zil_bp_tree_init(zilog_t * zilog)163 zil_bp_tree_init(zilog_t *zilog)
164 {
165 	avl_create(&zilog->zl_bp_tree, zil_bp_compare,
166 	    sizeof (zil_bp_node_t), offsetof(zil_bp_node_t, zn_node));
167 }
168 
169 static void
zil_bp_tree_fini(zilog_t * zilog)170 zil_bp_tree_fini(zilog_t *zilog)
171 {
172 	avl_tree_t *t = &zilog->zl_bp_tree;
173 	zil_bp_node_t *zn;
174 	void *cookie = NULL;
175 
176 	while ((zn = avl_destroy_nodes(t, &cookie)) != NULL)
177 		kmem_free(zn, sizeof (zil_bp_node_t));
178 
179 	avl_destroy(t);
180 }
181 
182 int
zil_bp_tree_add(zilog_t * zilog,const blkptr_t * bp)183 zil_bp_tree_add(zilog_t *zilog, const blkptr_t *bp)
184 {
185 	avl_tree_t *t = &zilog->zl_bp_tree;
186 	const dva_t *dva;
187 	zil_bp_node_t *zn;
188 	avl_index_t where;
189 
190 	if (BP_IS_EMBEDDED(bp))
191 		return (0);
192 
193 	dva = BP_IDENTITY(bp);
194 
195 	if (avl_find(t, dva, &where) != NULL)
196 		return (SET_ERROR(EEXIST));
197 
198 	zn = kmem_alloc(sizeof (zil_bp_node_t), KM_SLEEP);
199 	zn->zn_dva = *dva;
200 	avl_insert(t, zn, where);
201 
202 	return (0);
203 }
204 
205 static zil_header_t *
zil_header_in_syncing_context(zilog_t * zilog)206 zil_header_in_syncing_context(zilog_t *zilog)
207 {
208 	return ((zil_header_t *)zilog->zl_header);
209 }
210 
211 static void
zil_init_log_chain(zilog_t * zilog,blkptr_t * bp)212 zil_init_log_chain(zilog_t *zilog, blkptr_t *bp)
213 {
214 	zio_cksum_t *zc = &bp->blk_cksum;
215 
216 	(void) random_get_pseudo_bytes((void *)&zc->zc_word[ZIL_ZC_GUID_0],
217 	    sizeof (zc->zc_word[ZIL_ZC_GUID_0]));
218 	(void) random_get_pseudo_bytes((void *)&zc->zc_word[ZIL_ZC_GUID_1],
219 	    sizeof (zc->zc_word[ZIL_ZC_GUID_1]));
220 	zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os);
221 	zc->zc_word[ZIL_ZC_SEQ] = 1ULL;
222 }
223 
224 static int
zil_kstats_global_update(kstat_t * ksp,int rw)225 zil_kstats_global_update(kstat_t *ksp, int rw)
226 {
227 	zil_kstat_values_t *zs = ksp->ks_data;
228 	ASSERT3P(&zil_stats, ==, zs);
229 
230 	if (rw == KSTAT_WRITE) {
231 		return (SET_ERROR(EACCES));
232 	}
233 
234 	zil_kstat_values_update(zs, &zil_sums_global);
235 
236 	return (0);
237 }
238 
239 /*
240  * Read a log block and make sure it's valid.
241  */
242 static int
zil_read_log_block(zilog_t * zilog,boolean_t decrypt,const blkptr_t * bp,blkptr_t * nbp,char ** begin,char ** end,arc_buf_t ** abuf)243 zil_read_log_block(zilog_t *zilog, boolean_t decrypt, const blkptr_t *bp,
244     blkptr_t *nbp, char **begin, char **end, arc_buf_t **abuf)
245 {
246 	zio_flag_t zio_flags = ZIO_FLAG_CANFAIL;
247 	arc_flags_t aflags = ARC_FLAG_WAIT;
248 	zbookmark_phys_t zb;
249 	int error;
250 
251 	if (zilog->zl_header->zh_claim_txg == 0)
252 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
253 
254 	if (!(zilog->zl_header->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
255 		zio_flags |= ZIO_FLAG_SPECULATIVE;
256 
257 	if (!decrypt)
258 		zio_flags |= ZIO_FLAG_RAW;
259 
260 	SET_BOOKMARK(&zb, bp->blk_cksum.zc_word[ZIL_ZC_OBJSET],
261 	    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL, bp->blk_cksum.zc_word[ZIL_ZC_SEQ]);
262 
263 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func,
264 	    abuf, ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
265 
266 	if (error == 0) {
267 		zio_cksum_t cksum = bp->blk_cksum;
268 
269 		/*
270 		 * Validate the checksummed log block.
271 		 *
272 		 * Sequence numbers should be... sequential.  The checksum
273 		 * verifier for the next block should be bp's checksum plus 1.
274 		 *
275 		 * Also check the log chain linkage and size used.
276 		 */
277 		cksum.zc_word[ZIL_ZC_SEQ]++;
278 
279 		uint64_t size = BP_GET_LSIZE(bp);
280 		if (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2) {
281 			zil_chain_t *zilc = (*abuf)->b_data;
282 			char *lr = (char *)(zilc + 1);
283 
284 			if (memcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
285 			    sizeof (cksum)) ||
286 			    zilc->zc_nused < sizeof (*zilc) ||
287 			    zilc->zc_nused > size) {
288 				error = SET_ERROR(ECKSUM);
289 			} else {
290 				*begin = lr;
291 				*end = lr + zilc->zc_nused - sizeof (*zilc);
292 				*nbp = zilc->zc_next_blk;
293 			}
294 		} else {
295 			char *lr = (*abuf)->b_data;
296 			zil_chain_t *zilc = (zil_chain_t *)(lr + size) - 1;
297 
298 			if (memcmp(&cksum, &zilc->zc_next_blk.blk_cksum,
299 			    sizeof (cksum)) ||
300 			    (zilc->zc_nused > (size - sizeof (*zilc)))) {
301 				error = SET_ERROR(ECKSUM);
302 			} else {
303 				*begin = lr;
304 				*end = lr + zilc->zc_nused;
305 				*nbp = zilc->zc_next_blk;
306 			}
307 		}
308 	}
309 
310 	return (error);
311 }
312 
313 /*
314  * Read a TX_WRITE log data block.
315  */
316 static int
zil_read_log_data(zilog_t * zilog,const lr_write_t * lr,void * wbuf)317 zil_read_log_data(zilog_t *zilog, const lr_write_t *lr, void *wbuf)
318 {
319 	zio_flag_t zio_flags = ZIO_FLAG_CANFAIL;
320 	const blkptr_t *bp = &lr->lr_blkptr;
321 	arc_flags_t aflags = ARC_FLAG_WAIT;
322 	arc_buf_t *abuf = NULL;
323 	zbookmark_phys_t zb;
324 	int error;
325 
326 	if (BP_IS_HOLE(bp)) {
327 		if (wbuf != NULL)
328 			memset(wbuf, 0, MAX(BP_GET_LSIZE(bp), lr->lr_length));
329 		return (0);
330 	}
331 
332 	if (zilog->zl_header->zh_claim_txg == 0)
333 		zio_flags |= ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB;
334 
335 	/*
336 	 * If we are not using the resulting data, we are just checking that
337 	 * it hasn't been corrupted so we don't need to waste CPU time
338 	 * decompressing and decrypting it.
339 	 */
340 	if (wbuf == NULL)
341 		zio_flags |= ZIO_FLAG_RAW;
342 
343 	ASSERT3U(BP_GET_LSIZE(bp), !=, 0);
344 	SET_BOOKMARK(&zb, dmu_objset_id(zilog->zl_os), lr->lr_foid,
345 	    ZB_ZIL_LEVEL, lr->lr_offset / BP_GET_LSIZE(bp));
346 
347 	error = arc_read(NULL, zilog->zl_spa, bp, arc_getbuf_func, &abuf,
348 	    ZIO_PRIORITY_SYNC_READ, zio_flags, &aflags, &zb);
349 
350 	if (error == 0) {
351 		if (wbuf != NULL)
352 			memcpy(wbuf, abuf->b_data, arc_buf_size(abuf));
353 		arc_buf_destroy(abuf, &abuf);
354 	}
355 
356 	return (error);
357 }
358 
359 void
zil_sums_init(zil_sums_t * zs)360 zil_sums_init(zil_sums_t *zs)
361 {
362 	wmsum_init(&zs->zil_commit_count, 0);
363 	wmsum_init(&zs->zil_commit_writer_count, 0);
364 	wmsum_init(&zs->zil_itx_count, 0);
365 	wmsum_init(&zs->zil_itx_indirect_count, 0);
366 	wmsum_init(&zs->zil_itx_indirect_bytes, 0);
367 	wmsum_init(&zs->zil_itx_copied_count, 0);
368 	wmsum_init(&zs->zil_itx_copied_bytes, 0);
369 	wmsum_init(&zs->zil_itx_needcopy_count, 0);
370 	wmsum_init(&zs->zil_itx_needcopy_bytes, 0);
371 	wmsum_init(&zs->zil_itx_metaslab_normal_count, 0);
372 	wmsum_init(&zs->zil_itx_metaslab_normal_bytes, 0);
373 	wmsum_init(&zs->zil_itx_metaslab_normal_write, 0);
374 	wmsum_init(&zs->zil_itx_metaslab_normal_alloc, 0);
375 	wmsum_init(&zs->zil_itx_metaslab_slog_count, 0);
376 	wmsum_init(&zs->zil_itx_metaslab_slog_bytes, 0);
377 	wmsum_init(&zs->zil_itx_metaslab_slog_write, 0);
378 	wmsum_init(&zs->zil_itx_metaslab_slog_alloc, 0);
379 }
380 
381 void
zil_sums_fini(zil_sums_t * zs)382 zil_sums_fini(zil_sums_t *zs)
383 {
384 	wmsum_fini(&zs->zil_commit_count);
385 	wmsum_fini(&zs->zil_commit_writer_count);
386 	wmsum_fini(&zs->zil_itx_count);
387 	wmsum_fini(&zs->zil_itx_indirect_count);
388 	wmsum_fini(&zs->zil_itx_indirect_bytes);
389 	wmsum_fini(&zs->zil_itx_copied_count);
390 	wmsum_fini(&zs->zil_itx_copied_bytes);
391 	wmsum_fini(&zs->zil_itx_needcopy_count);
392 	wmsum_fini(&zs->zil_itx_needcopy_bytes);
393 	wmsum_fini(&zs->zil_itx_metaslab_normal_count);
394 	wmsum_fini(&zs->zil_itx_metaslab_normal_bytes);
395 	wmsum_fini(&zs->zil_itx_metaslab_normal_write);
396 	wmsum_fini(&zs->zil_itx_metaslab_normal_alloc);
397 	wmsum_fini(&zs->zil_itx_metaslab_slog_count);
398 	wmsum_fini(&zs->zil_itx_metaslab_slog_bytes);
399 	wmsum_fini(&zs->zil_itx_metaslab_slog_write);
400 	wmsum_fini(&zs->zil_itx_metaslab_slog_alloc);
401 }
402 
403 void
zil_kstat_values_update(zil_kstat_values_t * zs,zil_sums_t * zil_sums)404 zil_kstat_values_update(zil_kstat_values_t *zs, zil_sums_t *zil_sums)
405 {
406 	zs->zil_commit_count.value.ui64 =
407 	    wmsum_value(&zil_sums->zil_commit_count);
408 	zs->zil_commit_writer_count.value.ui64 =
409 	    wmsum_value(&zil_sums->zil_commit_writer_count);
410 	zs->zil_itx_count.value.ui64 =
411 	    wmsum_value(&zil_sums->zil_itx_count);
412 	zs->zil_itx_indirect_count.value.ui64 =
413 	    wmsum_value(&zil_sums->zil_itx_indirect_count);
414 	zs->zil_itx_indirect_bytes.value.ui64 =
415 	    wmsum_value(&zil_sums->zil_itx_indirect_bytes);
416 	zs->zil_itx_copied_count.value.ui64 =
417 	    wmsum_value(&zil_sums->zil_itx_copied_count);
418 	zs->zil_itx_copied_bytes.value.ui64 =
419 	    wmsum_value(&zil_sums->zil_itx_copied_bytes);
420 	zs->zil_itx_needcopy_count.value.ui64 =
421 	    wmsum_value(&zil_sums->zil_itx_needcopy_count);
422 	zs->zil_itx_needcopy_bytes.value.ui64 =
423 	    wmsum_value(&zil_sums->zil_itx_needcopy_bytes);
424 	zs->zil_itx_metaslab_normal_count.value.ui64 =
425 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_count);
426 	zs->zil_itx_metaslab_normal_bytes.value.ui64 =
427 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_bytes);
428 	zs->zil_itx_metaslab_normal_write.value.ui64 =
429 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_write);
430 	zs->zil_itx_metaslab_normal_alloc.value.ui64 =
431 	    wmsum_value(&zil_sums->zil_itx_metaslab_normal_alloc);
432 	zs->zil_itx_metaslab_slog_count.value.ui64 =
433 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_count);
434 	zs->zil_itx_metaslab_slog_bytes.value.ui64 =
435 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_bytes);
436 	zs->zil_itx_metaslab_slog_write.value.ui64 =
437 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_write);
438 	zs->zil_itx_metaslab_slog_alloc.value.ui64 =
439 	    wmsum_value(&zil_sums->zil_itx_metaslab_slog_alloc);
440 }
441 
442 /*
443  * Parse the intent log, and call parse_func for each valid record within.
444  */
445 int
zil_parse(zilog_t * zilog,zil_parse_blk_func_t * parse_blk_func,zil_parse_lr_func_t * parse_lr_func,void * arg,uint64_t txg,boolean_t decrypt)446 zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func,
447     zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg,
448     boolean_t decrypt)
449 {
450 	const zil_header_t *zh = zilog->zl_header;
451 	boolean_t claimed = !!zh->zh_claim_txg;
452 	uint64_t claim_blk_seq = claimed ? zh->zh_claim_blk_seq : UINT64_MAX;
453 	uint64_t claim_lr_seq = claimed ? zh->zh_claim_lr_seq : UINT64_MAX;
454 	uint64_t max_blk_seq = 0;
455 	uint64_t max_lr_seq = 0;
456 	uint64_t blk_count = 0;
457 	uint64_t lr_count = 0;
458 	blkptr_t blk, next_blk = {{{{0}}}};
459 	int error = 0;
460 
461 	/*
462 	 * Old logs didn't record the maximum zh_claim_lr_seq.
463 	 */
464 	if (!(zh->zh_flags & ZIL_CLAIM_LR_SEQ_VALID))
465 		claim_lr_seq = UINT64_MAX;
466 
467 	/*
468 	 * Starting at the block pointed to by zh_log we read the log chain.
469 	 * For each block in the chain we strongly check that block to
470 	 * ensure its validity.  We stop when an invalid block is found.
471 	 * For each block pointer in the chain we call parse_blk_func().
472 	 * For each record in each valid block we call parse_lr_func().
473 	 * If the log has been claimed, stop if we encounter a sequence
474 	 * number greater than the highest claimed sequence number.
475 	 */
476 	zil_bp_tree_init(zilog);
477 
478 	for (blk = zh->zh_log; !BP_IS_HOLE(&blk); blk = next_blk) {
479 		uint64_t blk_seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
480 		int reclen;
481 		char *lrp, *end;
482 		arc_buf_t *abuf = NULL;
483 
484 		if (blk_seq > claim_blk_seq)
485 			break;
486 
487 		error = parse_blk_func(zilog, &blk, arg, txg);
488 		if (error != 0)
489 			break;
490 		ASSERT3U(max_blk_seq, <, blk_seq);
491 		max_blk_seq = blk_seq;
492 		blk_count++;
493 
494 		if (max_lr_seq == claim_lr_seq && max_blk_seq == claim_blk_seq)
495 			break;
496 
497 		error = zil_read_log_block(zilog, decrypt, &blk, &next_blk,
498 		    &lrp, &end, &abuf);
499 		if (error != 0) {
500 			if (abuf)
501 				arc_buf_destroy(abuf, &abuf);
502 			if (claimed) {
503 				char name[ZFS_MAX_DATASET_NAME_LEN];
504 
505 				dmu_objset_name(zilog->zl_os, name);
506 
507 				cmn_err(CE_WARN, "ZFS read log block error %d, "
508 				    "dataset %s, seq 0x%llx\n", error, name,
509 				    (u_longlong_t)blk_seq);
510 			}
511 			break;
512 		}
513 
514 		for (; lrp < end; lrp += reclen) {
515 			lr_t *lr = (lr_t *)lrp;
516 
517 			/*
518 			 * Are the remaining bytes large enough to hold an
519 			 * log record?
520 			 */
521 			if ((char *)(lr + 1) > end) {
522 				cmn_err(CE_WARN, "zil_parse: lr_t overrun");
523 				error = SET_ERROR(ECKSUM);
524 				arc_buf_destroy(abuf, &abuf);
525 				goto done;
526 			}
527 			reclen = lr->lrc_reclen;
528 			if (reclen < sizeof (lr_t) || reclen > end - lrp) {
529 				cmn_err(CE_WARN,
530 				    "zil_parse: lr_t has an invalid reclen");
531 				error = SET_ERROR(ECKSUM);
532 				arc_buf_destroy(abuf, &abuf);
533 				goto done;
534 			}
535 
536 			if (lr->lrc_seq > claim_lr_seq) {
537 				arc_buf_destroy(abuf, &abuf);
538 				goto done;
539 			}
540 
541 			error = parse_lr_func(zilog, lr, arg, txg);
542 			if (error != 0) {
543 				arc_buf_destroy(abuf, &abuf);
544 				goto done;
545 			}
546 			ASSERT3U(max_lr_seq, <, lr->lrc_seq);
547 			max_lr_seq = lr->lrc_seq;
548 			lr_count++;
549 		}
550 		arc_buf_destroy(abuf, &abuf);
551 	}
552 done:
553 	zilog->zl_parse_error = error;
554 	zilog->zl_parse_blk_seq = max_blk_seq;
555 	zilog->zl_parse_lr_seq = max_lr_seq;
556 	zilog->zl_parse_blk_count = blk_count;
557 	zilog->zl_parse_lr_count = lr_count;
558 
559 	zil_bp_tree_fini(zilog);
560 
561 	return (error);
562 }
563 
564 static int
zil_clear_log_block(zilog_t * zilog,const blkptr_t * bp,void * tx,uint64_t first_txg)565 zil_clear_log_block(zilog_t *zilog, const blkptr_t *bp, void *tx,
566     uint64_t first_txg)
567 {
568 	(void) tx;
569 	ASSERT(!BP_IS_HOLE(bp));
570 
571 	/*
572 	 * As we call this function from the context of a rewind to a
573 	 * checkpoint, each ZIL block whose txg is later than the txg
574 	 * that we rewind to is invalid. Thus, we return -1 so
575 	 * zil_parse() doesn't attempt to read it.
576 	 */
577 	if (bp->blk_birth >= first_txg)
578 		return (-1);
579 
580 	if (zil_bp_tree_add(zilog, bp) != 0)
581 		return (0);
582 
583 	zio_free(zilog->zl_spa, first_txg, bp);
584 	return (0);
585 }
586 
587 static int
zil_noop_log_record(zilog_t * zilog,const lr_t * lrc,void * tx,uint64_t first_txg)588 zil_noop_log_record(zilog_t *zilog, const lr_t *lrc, void *tx,
589     uint64_t first_txg)
590 {
591 	(void) zilog, (void) lrc, (void) tx, (void) first_txg;
592 	return (0);
593 }
594 
595 static int
zil_claim_log_block(zilog_t * zilog,const blkptr_t * bp,void * tx,uint64_t first_txg)596 zil_claim_log_block(zilog_t *zilog, const blkptr_t *bp, void *tx,
597     uint64_t first_txg)
598 {
599 	/*
600 	 * Claim log block if not already committed and not already claimed.
601 	 * If tx == NULL, just verify that the block is claimable.
602 	 */
603 	if (BP_IS_HOLE(bp) || bp->blk_birth < first_txg ||
604 	    zil_bp_tree_add(zilog, bp) != 0)
605 		return (0);
606 
607 	return (zio_wait(zio_claim(NULL, zilog->zl_spa,
608 	    tx == NULL ? 0 : first_txg, bp, spa_claim_notify, NULL,
609 	    ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB)));
610 }
611 
612 static int
zil_claim_write(zilog_t * zilog,const lr_t * lrc,void * tx,uint64_t first_txg)613 zil_claim_write(zilog_t *zilog, const lr_t *lrc, void *tx, uint64_t first_txg)
614 {
615 	lr_write_t *lr = (lr_write_t *)lrc;
616 	int error;
617 
618 	ASSERT3U(lrc->lrc_reclen, >=, sizeof (*lr));
619 
620 	/*
621 	 * If the block is not readable, don't claim it.  This can happen
622 	 * in normal operation when a log block is written to disk before
623 	 * some of the dmu_sync() blocks it points to.  In this case, the
624 	 * transaction cannot have been committed to anyone (we would have
625 	 * waited for all writes to be stable first), so it is semantically
626 	 * correct to declare this the end of the log.
627 	 */
628 	if (lr->lr_blkptr.blk_birth >= first_txg) {
629 		error = zil_read_log_data(zilog, lr, NULL);
630 		if (error != 0)
631 			return (error);
632 	}
633 
634 	return (zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg));
635 }
636 
637 static int
zil_claim_clone_range(zilog_t * zilog,const lr_t * lrc,void * tx,uint64_t first_txg)638 zil_claim_clone_range(zilog_t *zilog, const lr_t *lrc, void *tx,
639     uint64_t first_txg)
640 {
641 	const lr_clone_range_t *lr = (const lr_clone_range_t *)lrc;
642 	const blkptr_t *bp;
643 	spa_t *spa = zilog->zl_spa;
644 	uint_t ii;
645 
646 	ASSERT3U(lrc->lrc_reclen, >=, sizeof (*lr));
647 	ASSERT3U(lrc->lrc_reclen, >=, offsetof(lr_clone_range_t,
648 	    lr_bps[lr->lr_nbps]));
649 
650 	if (tx == NULL) {
651 		return (0);
652 	}
653 
654 	/*
655 	 * XXX: Do we need to byteswap lr?
656 	 */
657 
658 	for (ii = 0; ii < lr->lr_nbps; ii++) {
659 		bp = &lr->lr_bps[ii];
660 
661 		/*
662 		 * When data is embedded into the BP there is no need to create
663 		 * BRT entry as there is no data block.  Just copy the BP as it
664 		 * contains the data.
665 		 */
666 		if (BP_IS_HOLE(bp) || BP_IS_EMBEDDED(bp))
667 			continue;
668 
669 		/*
670 		 * We can not handle block pointers from the future, since they
671 		 * are not yet allocated.  It should not normally happen, but
672 		 * just in case lets be safe and just stop here now instead of
673 		 * corrupting the pool.
674 		 */
675 		if (BP_PHYSICAL_BIRTH(bp) >= first_txg)
676 			return (SET_ERROR(ENOENT));
677 
678 		/*
679 		 * Assert the block is really allocated before we reference it.
680 		 */
681 		metaslab_check_free(spa, bp);
682 	}
683 
684 	for (ii = 0; ii < lr->lr_nbps; ii++) {
685 		bp = &lr->lr_bps[ii];
686 		if (!BP_IS_HOLE(bp) && !BP_IS_EMBEDDED(bp))
687 			brt_pending_add(spa, bp, tx);
688 	}
689 
690 	return (0);
691 }
692 
693 static int
zil_claim_log_record(zilog_t * zilog,const lr_t * lrc,void * tx,uint64_t first_txg)694 zil_claim_log_record(zilog_t *zilog, const lr_t *lrc, void *tx,
695     uint64_t first_txg)
696 {
697 
698 	switch (lrc->lrc_txtype) {
699 	case TX_WRITE:
700 		return (zil_claim_write(zilog, lrc, tx, first_txg));
701 	case TX_CLONE_RANGE:
702 		return (zil_claim_clone_range(zilog, lrc, tx, first_txg));
703 	default:
704 		return (0);
705 	}
706 }
707 
708 static int
zil_free_log_block(zilog_t * zilog,const blkptr_t * bp,void * tx,uint64_t claim_txg)709 zil_free_log_block(zilog_t *zilog, const blkptr_t *bp, void *tx,
710     uint64_t claim_txg)
711 {
712 	(void) claim_txg;
713 
714 	zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
715 
716 	return (0);
717 }
718 
719 static int
zil_free_write(zilog_t * zilog,const lr_t * lrc,void * tx,uint64_t claim_txg)720 zil_free_write(zilog_t *zilog, const lr_t *lrc, void *tx, uint64_t claim_txg)
721 {
722 	lr_write_t *lr = (lr_write_t *)lrc;
723 	blkptr_t *bp = &lr->lr_blkptr;
724 
725 	ASSERT3U(lrc->lrc_reclen, >=, sizeof (*lr));
726 
727 	/*
728 	 * If we previously claimed it, we need to free it.
729 	 */
730 	if (bp->blk_birth >= claim_txg && zil_bp_tree_add(zilog, bp) == 0 &&
731 	    !BP_IS_HOLE(bp)) {
732 		zio_free(zilog->zl_spa, dmu_tx_get_txg(tx), bp);
733 	}
734 
735 	return (0);
736 }
737 
738 static int
zil_free_clone_range(zilog_t * zilog,const lr_t * lrc,void * tx)739 zil_free_clone_range(zilog_t *zilog, const lr_t *lrc, void *tx)
740 {
741 	const lr_clone_range_t *lr = (const lr_clone_range_t *)lrc;
742 	const blkptr_t *bp;
743 	spa_t *spa;
744 	uint_t ii;
745 
746 	ASSERT3U(lrc->lrc_reclen, >=, sizeof (*lr));
747 	ASSERT3U(lrc->lrc_reclen, >=, offsetof(lr_clone_range_t,
748 	    lr_bps[lr->lr_nbps]));
749 
750 	if (tx == NULL) {
751 		return (0);
752 	}
753 
754 	spa = zilog->zl_spa;
755 
756 	for (ii = 0; ii < lr->lr_nbps; ii++) {
757 		bp = &lr->lr_bps[ii];
758 
759 		if (!BP_IS_HOLE(bp)) {
760 			zio_free(spa, dmu_tx_get_txg(tx), bp);
761 		}
762 	}
763 
764 	return (0);
765 }
766 
767 static int
zil_free_log_record(zilog_t * zilog,const lr_t * lrc,void * tx,uint64_t claim_txg)768 zil_free_log_record(zilog_t *zilog, const lr_t *lrc, void *tx,
769     uint64_t claim_txg)
770 {
771 
772 	if (claim_txg == 0) {
773 		return (0);
774 	}
775 
776 	switch (lrc->lrc_txtype) {
777 	case TX_WRITE:
778 		return (zil_free_write(zilog, lrc, tx, claim_txg));
779 	case TX_CLONE_RANGE:
780 		return (zil_free_clone_range(zilog, lrc, tx));
781 	default:
782 		return (0);
783 	}
784 }
785 
786 static int
zil_lwb_vdev_compare(const void * x1,const void * x2)787 zil_lwb_vdev_compare(const void *x1, const void *x2)
788 {
789 	const uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
790 	const uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
791 
792 	return (TREE_CMP(v1, v2));
793 }
794 
795 /*
796  * Allocate a new lwb.  We may already have a block pointer for it, in which
797  * case we get size and version from there.  Or we may not yet, in which case
798  * we choose them here and later make the block allocation match.
799  */
800 static lwb_t *
zil_alloc_lwb(zilog_t * zilog,int sz,blkptr_t * bp,boolean_t slog,uint64_t txg,lwb_state_t state)801 zil_alloc_lwb(zilog_t *zilog, int sz, blkptr_t *bp, boolean_t slog,
802     uint64_t txg, lwb_state_t state)
803 {
804 	lwb_t *lwb;
805 
806 	lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
807 	lwb->lwb_zilog = zilog;
808 	if (bp) {
809 		lwb->lwb_blk = *bp;
810 		lwb->lwb_slim = (BP_GET_CHECKSUM(bp) == ZIO_CHECKSUM_ZILOG2);
811 		sz = BP_GET_LSIZE(bp);
812 	} else {
813 		BP_ZERO(&lwb->lwb_blk);
814 		lwb->lwb_slim = (spa_version(zilog->zl_spa) >=
815 		    SPA_VERSION_SLIM_ZIL);
816 	}
817 	lwb->lwb_slog = slog;
818 	lwb->lwb_error = 0;
819 	if (lwb->lwb_slim) {
820 		lwb->lwb_nmax = sz;
821 		lwb->lwb_nused = lwb->lwb_nfilled = sizeof (zil_chain_t);
822 	} else {
823 		lwb->lwb_nmax = sz - sizeof (zil_chain_t);
824 		lwb->lwb_nused = lwb->lwb_nfilled = 0;
825 	}
826 	lwb->lwb_sz = sz;
827 	lwb->lwb_state = state;
828 	lwb->lwb_buf = zio_buf_alloc(sz);
829 	lwb->lwb_child_zio = NULL;
830 	lwb->lwb_write_zio = NULL;
831 	lwb->lwb_root_zio = NULL;
832 	lwb->lwb_issued_timestamp = 0;
833 	lwb->lwb_issued_txg = 0;
834 	lwb->lwb_alloc_txg = txg;
835 	lwb->lwb_max_txg = 0;
836 
837 	mutex_enter(&zilog->zl_lock);
838 	list_insert_tail(&zilog->zl_lwb_list, lwb);
839 	if (state != LWB_STATE_NEW)
840 		zilog->zl_last_lwb_opened = lwb;
841 	mutex_exit(&zilog->zl_lock);
842 
843 	return (lwb);
844 }
845 
846 static void
zil_free_lwb(zilog_t * zilog,lwb_t * lwb)847 zil_free_lwb(zilog_t *zilog, lwb_t *lwb)
848 {
849 	ASSERT(MUTEX_HELD(&zilog->zl_lock));
850 	ASSERT(lwb->lwb_state == LWB_STATE_NEW ||
851 	    lwb->lwb_state == LWB_STATE_FLUSH_DONE);
852 	ASSERT3P(lwb->lwb_child_zio, ==, NULL);
853 	ASSERT3P(lwb->lwb_write_zio, ==, NULL);
854 	ASSERT3P(lwb->lwb_root_zio, ==, NULL);
855 	ASSERT3U(lwb->lwb_alloc_txg, <=, spa_syncing_txg(zilog->zl_spa));
856 	ASSERT3U(lwb->lwb_max_txg, <=, spa_syncing_txg(zilog->zl_spa));
857 	VERIFY(list_is_empty(&lwb->lwb_itxs));
858 	VERIFY(list_is_empty(&lwb->lwb_waiters));
859 	ASSERT(avl_is_empty(&lwb->lwb_vdev_tree));
860 	ASSERT(!MUTEX_HELD(&lwb->lwb_vdev_lock));
861 
862 	/*
863 	 * Clear the zilog's field to indicate this lwb is no longer
864 	 * valid, and prevent use-after-free errors.
865 	 */
866 	if (zilog->zl_last_lwb_opened == lwb)
867 		zilog->zl_last_lwb_opened = NULL;
868 
869 	kmem_cache_free(zil_lwb_cache, lwb);
870 }
871 
872 /*
873  * Called when we create in-memory log transactions so that we know
874  * to cleanup the itxs at the end of spa_sync().
875  */
876 static void
zilog_dirty(zilog_t * zilog,uint64_t txg)877 zilog_dirty(zilog_t *zilog, uint64_t txg)
878 {
879 	dsl_pool_t *dp = zilog->zl_dmu_pool;
880 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
881 
882 	ASSERT(spa_writeable(zilog->zl_spa));
883 
884 	if (ds->ds_is_snapshot)
885 		panic("dirtying snapshot!");
886 
887 	if (txg_list_add(&dp->dp_dirty_zilogs, zilog, txg)) {
888 		/* up the hold count until we can be written out */
889 		dmu_buf_add_ref(ds->ds_dbuf, zilog);
890 
891 		zilog->zl_dirty_max_txg = MAX(txg, zilog->zl_dirty_max_txg);
892 	}
893 }
894 
895 /*
896  * Determine if the zil is dirty in the specified txg. Callers wanting to
897  * ensure that the dirty state does not change must hold the itxg_lock for
898  * the specified txg. Holding the lock will ensure that the zil cannot be
899  * dirtied (zil_itx_assign) or cleaned (zil_clean) while we check its current
900  * state.
901  */
902 static boolean_t __maybe_unused
zilog_is_dirty_in_txg(zilog_t * zilog,uint64_t txg)903 zilog_is_dirty_in_txg(zilog_t *zilog, uint64_t txg)
904 {
905 	dsl_pool_t *dp = zilog->zl_dmu_pool;
906 
907 	if (txg_list_member(&dp->dp_dirty_zilogs, zilog, txg & TXG_MASK))
908 		return (B_TRUE);
909 	return (B_FALSE);
910 }
911 
912 /*
913  * Determine if the zil is dirty. The zil is considered dirty if it has
914  * any pending itx records that have not been cleaned by zil_clean().
915  */
916 static boolean_t
zilog_is_dirty(zilog_t * zilog)917 zilog_is_dirty(zilog_t *zilog)
918 {
919 	dsl_pool_t *dp = zilog->zl_dmu_pool;
920 
921 	for (int t = 0; t < TXG_SIZE; t++) {
922 		if (txg_list_member(&dp->dp_dirty_zilogs, zilog, t))
923 			return (B_TRUE);
924 	}
925 	return (B_FALSE);
926 }
927 
928 /*
929  * Its called in zil_commit context (zil_process_commit_list()/zil_create()).
930  * It activates SPA_FEATURE_ZILSAXATTR feature, if its enabled.
931  * Check dsl_dataset_feature_is_active to avoid txg_wait_synced() on every
932  * zil_commit.
933  */
934 static void
zil_commit_activate_saxattr_feature(zilog_t * zilog)935 zil_commit_activate_saxattr_feature(zilog_t *zilog)
936 {
937 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
938 	uint64_t txg = 0;
939 	dmu_tx_t *tx = NULL;
940 
941 	if (spa_feature_is_enabled(zilog->zl_spa, SPA_FEATURE_ZILSAXATTR) &&
942 	    dmu_objset_type(zilog->zl_os) != DMU_OST_ZVOL &&
943 	    !dsl_dataset_feature_is_active(ds, SPA_FEATURE_ZILSAXATTR)) {
944 		tx = dmu_tx_create(zilog->zl_os);
945 		VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
946 		dsl_dataset_dirty(ds, tx);
947 		txg = dmu_tx_get_txg(tx);
948 
949 		mutex_enter(&ds->ds_lock);
950 		ds->ds_feature_activation[SPA_FEATURE_ZILSAXATTR] =
951 		    (void *)B_TRUE;
952 		mutex_exit(&ds->ds_lock);
953 		dmu_tx_commit(tx);
954 		txg_wait_synced(zilog->zl_dmu_pool, txg);
955 	}
956 }
957 
958 /*
959  * Create an on-disk intent log.
960  */
961 static lwb_t *
zil_create(zilog_t * zilog)962 zil_create(zilog_t *zilog)
963 {
964 	const zil_header_t *zh = zilog->zl_header;
965 	lwb_t *lwb = NULL;
966 	uint64_t txg = 0;
967 	dmu_tx_t *tx = NULL;
968 	blkptr_t blk;
969 	int error = 0;
970 	boolean_t slog = FALSE;
971 	dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
972 
973 
974 	/*
975 	 * Wait for any previous destroy to complete.
976 	 */
977 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
978 
979 	ASSERT(zh->zh_claim_txg == 0);
980 	ASSERT(zh->zh_replay_seq == 0);
981 
982 	blk = zh->zh_log;
983 
984 	/*
985 	 * Allocate an initial log block if:
986 	 *    - there isn't one already
987 	 *    - the existing block is the wrong endianness
988 	 */
989 	if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) {
990 		tx = dmu_tx_create(zilog->zl_os);
991 		VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
992 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
993 		txg = dmu_tx_get_txg(tx);
994 
995 		if (!BP_IS_HOLE(&blk)) {
996 			zio_free(zilog->zl_spa, txg, &blk);
997 			BP_ZERO(&blk);
998 		}
999 
1000 		error = zio_alloc_zil(zilog->zl_spa, zilog->zl_os, txg, &blk,
1001 		    ZIL_MIN_BLKSZ, &slog);
1002 		if (error == 0)
1003 			zil_init_log_chain(zilog, &blk);
1004 	}
1005 
1006 	/*
1007 	 * Allocate a log write block (lwb) for the first log block.
1008 	 */
1009 	if (error == 0)
1010 		lwb = zil_alloc_lwb(zilog, 0, &blk, slog, txg, LWB_STATE_NEW);
1011 
1012 	/*
1013 	 * If we just allocated the first log block, commit our transaction
1014 	 * and wait for zil_sync() to stuff the block pointer into zh_log.
1015 	 * (zh is part of the MOS, so we cannot modify it in open context.)
1016 	 */
1017 	if (tx != NULL) {
1018 		/*
1019 		 * If "zilsaxattr" feature is enabled on zpool, then activate
1020 		 * it now when we're creating the ZIL chain. We can't wait with
1021 		 * this until we write the first xattr log record because we
1022 		 * need to wait for the feature activation to sync out.
1023 		 */
1024 		if (spa_feature_is_enabled(zilog->zl_spa,
1025 		    SPA_FEATURE_ZILSAXATTR) && dmu_objset_type(zilog->zl_os) !=
1026 		    DMU_OST_ZVOL) {
1027 			mutex_enter(&ds->ds_lock);
1028 			ds->ds_feature_activation[SPA_FEATURE_ZILSAXATTR] =
1029 			    (void *)B_TRUE;
1030 			mutex_exit(&ds->ds_lock);
1031 		}
1032 
1033 		dmu_tx_commit(tx);
1034 		txg_wait_synced(zilog->zl_dmu_pool, txg);
1035 	} else {
1036 		/*
1037 		 * This branch covers the case where we enable the feature on a
1038 		 * zpool that has existing ZIL headers.
1039 		 */
1040 		zil_commit_activate_saxattr_feature(zilog);
1041 	}
1042 	IMPLY(spa_feature_is_enabled(zilog->zl_spa, SPA_FEATURE_ZILSAXATTR) &&
1043 	    dmu_objset_type(zilog->zl_os) != DMU_OST_ZVOL,
1044 	    dsl_dataset_feature_is_active(ds, SPA_FEATURE_ZILSAXATTR));
1045 
1046 	ASSERT(error != 0 || memcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
1047 	IMPLY(error == 0, lwb != NULL);
1048 
1049 	return (lwb);
1050 }
1051 
1052 /*
1053  * In one tx, free all log blocks and clear the log header. If keep_first
1054  * is set, then we're replaying a log with no content. We want to keep the
1055  * first block, however, so that the first synchronous transaction doesn't
1056  * require a txg_wait_synced() in zil_create(). We don't need to
1057  * txg_wait_synced() here either when keep_first is set, because both
1058  * zil_create() and zil_destroy() will wait for any in-progress destroys
1059  * to complete.
1060  * Return B_TRUE if there were any entries to replay.
1061  */
1062 boolean_t
zil_destroy(zilog_t * zilog,boolean_t keep_first)1063 zil_destroy(zilog_t *zilog, boolean_t keep_first)
1064 {
1065 	const zil_header_t *zh = zilog->zl_header;
1066 	lwb_t *lwb;
1067 	dmu_tx_t *tx;
1068 	uint64_t txg;
1069 
1070 	/*
1071 	 * Wait for any previous destroy to complete.
1072 	 */
1073 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
1074 
1075 	zilog->zl_old_header = *zh;		/* debugging aid */
1076 
1077 	if (BP_IS_HOLE(&zh->zh_log))
1078 		return (B_FALSE);
1079 
1080 	tx = dmu_tx_create(zilog->zl_os);
1081 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT));
1082 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1083 	txg = dmu_tx_get_txg(tx);
1084 
1085 	mutex_enter(&zilog->zl_lock);
1086 
1087 	ASSERT3U(zilog->zl_destroy_txg, <, txg);
1088 	zilog->zl_destroy_txg = txg;
1089 	zilog->zl_keep_first = keep_first;
1090 
1091 	if (!list_is_empty(&zilog->zl_lwb_list)) {
1092 		ASSERT(zh->zh_claim_txg == 0);
1093 		VERIFY(!keep_first);
1094 		while ((lwb = list_remove_head(&zilog->zl_lwb_list)) != NULL) {
1095 			if (lwb->lwb_buf != NULL)
1096 				zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1097 			if (!BP_IS_HOLE(&lwb->lwb_blk))
1098 				zio_free(zilog->zl_spa, txg, &lwb->lwb_blk);
1099 			zil_free_lwb(zilog, lwb);
1100 		}
1101 	} else if (!keep_first) {
1102 		zil_destroy_sync(zilog, tx);
1103 	}
1104 	mutex_exit(&zilog->zl_lock);
1105 
1106 	dmu_tx_commit(tx);
1107 
1108 	return (B_TRUE);
1109 }
1110 
1111 void
zil_destroy_sync(zilog_t * zilog,dmu_tx_t * tx)1112 zil_destroy_sync(zilog_t *zilog, dmu_tx_t *tx)
1113 {
1114 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
1115 	(void) zil_parse(zilog, zil_free_log_block,
1116 	    zil_free_log_record, tx, zilog->zl_header->zh_claim_txg, B_FALSE);
1117 }
1118 
1119 int
zil_claim(dsl_pool_t * dp,dsl_dataset_t * ds,void * txarg)1120 zil_claim(dsl_pool_t *dp, dsl_dataset_t *ds, void *txarg)
1121 {
1122 	dmu_tx_t *tx = txarg;
1123 	zilog_t *zilog;
1124 	uint64_t first_txg;
1125 	zil_header_t *zh;
1126 	objset_t *os;
1127 	int error;
1128 
1129 	error = dmu_objset_own_obj(dp, ds->ds_object,
1130 	    DMU_OST_ANY, B_FALSE, B_FALSE, FTAG, &os);
1131 	if (error != 0) {
1132 		/*
1133 		 * EBUSY indicates that the objset is inconsistent, in which
1134 		 * case it can not have a ZIL.
1135 		 */
1136 		if (error != EBUSY) {
1137 			cmn_err(CE_WARN, "can't open objset for %llu, error %u",
1138 			    (unsigned long long)ds->ds_object, error);
1139 		}
1140 
1141 		return (0);
1142 	}
1143 
1144 	zilog = dmu_objset_zil(os);
1145 	zh = zil_header_in_syncing_context(zilog);
1146 	ASSERT3U(tx->tx_txg, ==, spa_first_txg(zilog->zl_spa));
1147 	first_txg = spa_min_claim_txg(zilog->zl_spa);
1148 
1149 	/*
1150 	 * If the spa_log_state is not set to be cleared, check whether
1151 	 * the current uberblock is a checkpoint one and if the current
1152 	 * header has been claimed before moving on.
1153 	 *
1154 	 * If the current uberblock is a checkpointed uberblock then
1155 	 * one of the following scenarios took place:
1156 	 *
1157 	 * 1] We are currently rewinding to the checkpoint of the pool.
1158 	 * 2] We crashed in the middle of a checkpoint rewind but we
1159 	 *    did manage to write the checkpointed uberblock to the
1160 	 *    vdev labels, so when we tried to import the pool again
1161 	 *    the checkpointed uberblock was selected from the import
1162 	 *    procedure.
1163 	 *
1164 	 * In both cases we want to zero out all the ZIL blocks, except
1165 	 * the ones that have been claimed at the time of the checkpoint
1166 	 * (their zh_claim_txg != 0). The reason is that these blocks
1167 	 * may be corrupted since we may have reused their locations on
1168 	 * disk after we took the checkpoint.
1169 	 *
1170 	 * We could try to set spa_log_state to SPA_LOG_CLEAR earlier
1171 	 * when we first figure out whether the current uberblock is
1172 	 * checkpointed or not. Unfortunately, that would discard all
1173 	 * the logs, including the ones that are claimed, and we would
1174 	 * leak space.
1175 	 */
1176 	if (spa_get_log_state(zilog->zl_spa) == SPA_LOG_CLEAR ||
1177 	    (zilog->zl_spa->spa_uberblock.ub_checkpoint_txg != 0 &&
1178 	    zh->zh_claim_txg == 0)) {
1179 		if (!BP_IS_HOLE(&zh->zh_log)) {
1180 			(void) zil_parse(zilog, zil_clear_log_block,
1181 			    zil_noop_log_record, tx, first_txg, B_FALSE);
1182 		}
1183 		BP_ZERO(&zh->zh_log);
1184 		if (os->os_encrypted)
1185 			os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1186 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
1187 		dmu_objset_disown(os, B_FALSE, FTAG);
1188 		return (0);
1189 	}
1190 
1191 	/*
1192 	 * If we are not rewinding and opening the pool normally, then
1193 	 * the min_claim_txg should be equal to the first txg of the pool.
1194 	 */
1195 	ASSERT3U(first_txg, ==, spa_first_txg(zilog->zl_spa));
1196 
1197 	/*
1198 	 * Claim all log blocks if we haven't already done so, and remember
1199 	 * the highest claimed sequence number.  This ensures that if we can
1200 	 * read only part of the log now (e.g. due to a missing device),
1201 	 * but we can read the entire log later, we will not try to replay
1202 	 * or destroy beyond the last block we successfully claimed.
1203 	 */
1204 	ASSERT3U(zh->zh_claim_txg, <=, first_txg);
1205 	if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
1206 		(void) zil_parse(zilog, zil_claim_log_block,
1207 		    zil_claim_log_record, tx, first_txg, B_FALSE);
1208 		zh->zh_claim_txg = first_txg;
1209 		zh->zh_claim_blk_seq = zilog->zl_parse_blk_seq;
1210 		zh->zh_claim_lr_seq = zilog->zl_parse_lr_seq;
1211 		if (zilog->zl_parse_lr_count || zilog->zl_parse_blk_count > 1)
1212 			zh->zh_flags |= ZIL_REPLAY_NEEDED;
1213 		zh->zh_flags |= ZIL_CLAIM_LR_SEQ_VALID;
1214 		if (os->os_encrypted)
1215 			os->os_next_write_raw[tx->tx_txg & TXG_MASK] = B_TRUE;
1216 		dsl_dataset_dirty(dmu_objset_ds(os), tx);
1217 	}
1218 
1219 	ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
1220 	dmu_objset_disown(os, B_FALSE, FTAG);
1221 	return (0);
1222 }
1223 
1224 /*
1225  * Check the log by walking the log chain.
1226  * Checksum errors are ok as they indicate the end of the chain.
1227  * Any other error (no device or read failure) returns an error.
1228  */
1229 int
zil_check_log_chain(dsl_pool_t * dp,dsl_dataset_t * ds,void * tx)1230 zil_check_log_chain(dsl_pool_t *dp, dsl_dataset_t *ds, void *tx)
1231 {
1232 	(void) dp;
1233 	zilog_t *zilog;
1234 	objset_t *os;
1235 	blkptr_t *bp;
1236 	int error;
1237 
1238 	ASSERT(tx == NULL);
1239 
1240 	error = dmu_objset_from_ds(ds, &os);
1241 	if (error != 0) {
1242 		cmn_err(CE_WARN, "can't open objset %llu, error %d",
1243 		    (unsigned long long)ds->ds_object, error);
1244 		return (0);
1245 	}
1246 
1247 	zilog = dmu_objset_zil(os);
1248 	bp = (blkptr_t *)&zilog->zl_header->zh_log;
1249 
1250 	if (!BP_IS_HOLE(bp)) {
1251 		vdev_t *vd;
1252 		boolean_t valid = B_TRUE;
1253 
1254 		/*
1255 		 * Check the first block and determine if it's on a log device
1256 		 * which may have been removed or faulted prior to loading this
1257 		 * pool.  If so, there's no point in checking the rest of the
1258 		 * log as its content should have already been synced to the
1259 		 * pool.
1260 		 */
1261 		spa_config_enter(os->os_spa, SCL_STATE, FTAG, RW_READER);
1262 		vd = vdev_lookup_top(os->os_spa, DVA_GET_VDEV(&bp->blk_dva[0]));
1263 		if (vd->vdev_islog && vdev_is_dead(vd))
1264 			valid = vdev_log_state_valid(vd);
1265 		spa_config_exit(os->os_spa, SCL_STATE, FTAG);
1266 
1267 		if (!valid)
1268 			return (0);
1269 
1270 		/*
1271 		 * Check whether the current uberblock is checkpointed (e.g.
1272 		 * we are rewinding) and whether the current header has been
1273 		 * claimed or not. If it hasn't then skip verifying it. We
1274 		 * do this because its ZIL blocks may be part of the pool's
1275 		 * state before the rewind, which is no longer valid.
1276 		 */
1277 		zil_header_t *zh = zil_header_in_syncing_context(zilog);
1278 		if (zilog->zl_spa->spa_uberblock.ub_checkpoint_txg != 0 &&
1279 		    zh->zh_claim_txg == 0)
1280 			return (0);
1281 	}
1282 
1283 	/*
1284 	 * Because tx == NULL, zil_claim_log_block() will not actually claim
1285 	 * any blocks, but just determine whether it is possible to do so.
1286 	 * In addition to checking the log chain, zil_claim_log_block()
1287 	 * will invoke zio_claim() with a done func of spa_claim_notify(),
1288 	 * which will update spa_max_claim_txg.  See spa_load() for details.
1289 	 */
1290 	error = zil_parse(zilog, zil_claim_log_block, zil_claim_log_record, tx,
1291 	    zilog->zl_header->zh_claim_txg ? -1ULL :
1292 	    spa_min_claim_txg(os->os_spa), B_FALSE);
1293 
1294 	return ((error == ECKSUM || error == ENOENT) ? 0 : error);
1295 }
1296 
1297 /*
1298  * When an itx is "skipped", this function is used to properly mark the
1299  * waiter as "done, and signal any thread(s) waiting on it. An itx can
1300  * be skipped (and not committed to an lwb) for a variety of reasons,
1301  * one of them being that the itx was committed via spa_sync(), prior to
1302  * it being committed to an lwb; this can happen if a thread calling
1303  * zil_commit() is racing with spa_sync().
1304  */
1305 static void
zil_commit_waiter_skip(zil_commit_waiter_t * zcw)1306 zil_commit_waiter_skip(zil_commit_waiter_t *zcw)
1307 {
1308 	mutex_enter(&zcw->zcw_lock);
1309 	ASSERT3B(zcw->zcw_done, ==, B_FALSE);
1310 	zcw->zcw_done = B_TRUE;
1311 	cv_broadcast(&zcw->zcw_cv);
1312 	mutex_exit(&zcw->zcw_lock);
1313 }
1314 
1315 /*
1316  * This function is used when the given waiter is to be linked into an
1317  * lwb's "lwb_waiter" list; i.e. when the itx is committed to the lwb.
1318  * At this point, the waiter will no longer be referenced by the itx,
1319  * and instead, will be referenced by the lwb.
1320  */
1321 static void
zil_commit_waiter_link_lwb(zil_commit_waiter_t * zcw,lwb_t * lwb)1322 zil_commit_waiter_link_lwb(zil_commit_waiter_t *zcw, lwb_t *lwb)
1323 {
1324 	/*
1325 	 * The lwb_waiters field of the lwb is protected by the zilog's
1326 	 * zl_issuer_lock while the lwb is open and zl_lock otherwise.
1327 	 * zl_issuer_lock also protects leaving the open state.
1328 	 * zcw_lwb setting is protected by zl_issuer_lock and state !=
1329 	 * flush_done, which transition is protected by zl_lock.
1330 	 */
1331 	ASSERT(MUTEX_HELD(&lwb->lwb_zilog->zl_issuer_lock));
1332 	IMPLY(lwb->lwb_state != LWB_STATE_OPENED,
1333 	    MUTEX_HELD(&lwb->lwb_zilog->zl_lock));
1334 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_NEW);
1335 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_FLUSH_DONE);
1336 
1337 	ASSERT(!list_link_active(&zcw->zcw_node));
1338 	list_insert_tail(&lwb->lwb_waiters, zcw);
1339 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
1340 	zcw->zcw_lwb = lwb;
1341 }
1342 
1343 /*
1344  * This function is used when zio_alloc_zil() fails to allocate a ZIL
1345  * block, and the given waiter must be linked to the "nolwb waiters"
1346  * list inside of zil_process_commit_list().
1347  */
1348 static void
zil_commit_waiter_link_nolwb(zil_commit_waiter_t * zcw,list_t * nolwb)1349 zil_commit_waiter_link_nolwb(zil_commit_waiter_t *zcw, list_t *nolwb)
1350 {
1351 	ASSERT(!list_link_active(&zcw->zcw_node));
1352 	list_insert_tail(nolwb, zcw);
1353 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
1354 }
1355 
1356 void
zil_lwb_add_block(lwb_t * lwb,const blkptr_t * bp)1357 zil_lwb_add_block(lwb_t *lwb, const blkptr_t *bp)
1358 {
1359 	avl_tree_t *t = &lwb->lwb_vdev_tree;
1360 	avl_index_t where;
1361 	zil_vdev_node_t *zv, zvsearch;
1362 	int ndvas = BP_GET_NDVAS(bp);
1363 	int i;
1364 
1365 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_WRITE_DONE);
1366 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_FLUSH_DONE);
1367 
1368 	if (zil_nocacheflush)
1369 		return;
1370 
1371 	mutex_enter(&lwb->lwb_vdev_lock);
1372 	for (i = 0; i < ndvas; i++) {
1373 		zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
1374 		if (avl_find(t, &zvsearch, &where) == NULL) {
1375 			zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
1376 			zv->zv_vdev = zvsearch.zv_vdev;
1377 			avl_insert(t, zv, where);
1378 		}
1379 	}
1380 	mutex_exit(&lwb->lwb_vdev_lock);
1381 }
1382 
1383 static void
zil_lwb_flush_defer(lwb_t * lwb,lwb_t * nlwb)1384 zil_lwb_flush_defer(lwb_t *lwb, lwb_t *nlwb)
1385 {
1386 	avl_tree_t *src = &lwb->lwb_vdev_tree;
1387 	avl_tree_t *dst = &nlwb->lwb_vdev_tree;
1388 	void *cookie = NULL;
1389 	zil_vdev_node_t *zv;
1390 
1391 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_WRITE_DONE);
1392 	ASSERT3S(nlwb->lwb_state, !=, LWB_STATE_WRITE_DONE);
1393 	ASSERT3S(nlwb->lwb_state, !=, LWB_STATE_FLUSH_DONE);
1394 
1395 	/*
1396 	 * While 'lwb' is at a point in its lifetime where lwb_vdev_tree does
1397 	 * not need the protection of lwb_vdev_lock (it will only be modified
1398 	 * while holding zilog->zl_lock) as its writes and those of its
1399 	 * children have all completed.  The younger 'nlwb' may be waiting on
1400 	 * future writes to additional vdevs.
1401 	 */
1402 	mutex_enter(&nlwb->lwb_vdev_lock);
1403 	/*
1404 	 * Tear down the 'lwb' vdev tree, ensuring that entries which do not
1405 	 * exist in 'nlwb' are moved to it, freeing any would-be duplicates.
1406 	 */
1407 	while ((zv = avl_destroy_nodes(src, &cookie)) != NULL) {
1408 		avl_index_t where;
1409 
1410 		if (avl_find(dst, zv, &where) == NULL) {
1411 			avl_insert(dst, zv, where);
1412 		} else {
1413 			kmem_free(zv, sizeof (*zv));
1414 		}
1415 	}
1416 	mutex_exit(&nlwb->lwb_vdev_lock);
1417 }
1418 
1419 void
zil_lwb_add_txg(lwb_t * lwb,uint64_t txg)1420 zil_lwb_add_txg(lwb_t *lwb, uint64_t txg)
1421 {
1422 	lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
1423 }
1424 
1425 /*
1426  * This function is a called after all vdevs associated with a given lwb
1427  * write have completed their DKIOCFLUSHWRITECACHE command; or as soon
1428  * as the lwb write completes, if "zil_nocacheflush" is set. Further,
1429  * all "previous" lwb's will have completed before this function is
1430  * called; i.e. this function is called for all previous lwbs before
1431  * it's called for "this" lwb (enforced via zio the dependencies
1432  * configured in zil_lwb_set_zio_dependency()).
1433  *
1434  * The intention is for this function to be called as soon as the
1435  * contents of an lwb are considered "stable" on disk, and will survive
1436  * any sudden loss of power. At this point, any threads waiting for the
1437  * lwb to reach this state are signalled, and the "waiter" structures
1438  * are marked "done".
1439  */
1440 static void
zil_lwb_flush_vdevs_done(zio_t * zio)1441 zil_lwb_flush_vdevs_done(zio_t *zio)
1442 {
1443 	lwb_t *lwb = zio->io_private;
1444 	zilog_t *zilog = lwb->lwb_zilog;
1445 	zil_commit_waiter_t *zcw;
1446 	itx_t *itx;
1447 
1448 	spa_config_exit(zilog->zl_spa, SCL_STATE, lwb);
1449 
1450 	hrtime_t t = gethrtime() - lwb->lwb_issued_timestamp;
1451 
1452 	mutex_enter(&zilog->zl_lock);
1453 
1454 	zilog->zl_last_lwb_latency = (zilog->zl_last_lwb_latency * 7 + t) / 8;
1455 
1456 	lwb->lwb_root_zio = NULL;
1457 
1458 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_WRITE_DONE);
1459 	lwb->lwb_state = LWB_STATE_FLUSH_DONE;
1460 
1461 	if (zilog->zl_last_lwb_opened == lwb) {
1462 		/*
1463 		 * Remember the highest committed log sequence number
1464 		 * for ztest. We only update this value when all the log
1465 		 * writes succeeded, because ztest wants to ASSERT that
1466 		 * it got the whole log chain.
1467 		 */
1468 		zilog->zl_commit_lr_seq = zilog->zl_lr_seq;
1469 	}
1470 
1471 	while ((itx = list_remove_head(&lwb->lwb_itxs)) != NULL)
1472 		zil_itx_destroy(itx);
1473 
1474 	while ((zcw = list_remove_head(&lwb->lwb_waiters)) != NULL) {
1475 		mutex_enter(&zcw->zcw_lock);
1476 
1477 		ASSERT3P(zcw->zcw_lwb, ==, lwb);
1478 		zcw->zcw_lwb = NULL;
1479 		/*
1480 		 * We expect any ZIO errors from child ZIOs to have been
1481 		 * propagated "up" to this specific LWB's root ZIO, in
1482 		 * order for this error handling to work correctly. This
1483 		 * includes ZIO errors from either this LWB's write or
1484 		 * flush, as well as any errors from other dependent LWBs
1485 		 * (e.g. a root LWB ZIO that might be a child of this LWB).
1486 		 *
1487 		 * With that said, it's important to note that LWB flush
1488 		 * errors are not propagated up to the LWB root ZIO.
1489 		 * This is incorrect behavior, and results in VDEV flush
1490 		 * errors not being handled correctly here. See the
1491 		 * comment above the call to "zio_flush" for details.
1492 		 */
1493 
1494 		zcw->zcw_zio_error = zio->io_error;
1495 
1496 		ASSERT3B(zcw->zcw_done, ==, B_FALSE);
1497 		zcw->zcw_done = B_TRUE;
1498 		cv_broadcast(&zcw->zcw_cv);
1499 
1500 		mutex_exit(&zcw->zcw_lock);
1501 	}
1502 
1503 	uint64_t txg = lwb->lwb_issued_txg;
1504 
1505 	/* Once we drop the lock, lwb may be freed by zil_sync(). */
1506 	mutex_exit(&zilog->zl_lock);
1507 
1508 	mutex_enter(&zilog->zl_lwb_io_lock);
1509 	ASSERT3U(zilog->zl_lwb_inflight[txg & TXG_MASK], >, 0);
1510 	zilog->zl_lwb_inflight[txg & TXG_MASK]--;
1511 	if (zilog->zl_lwb_inflight[txg & TXG_MASK] == 0)
1512 		cv_broadcast(&zilog->zl_lwb_io_cv);
1513 	mutex_exit(&zilog->zl_lwb_io_lock);
1514 }
1515 
1516 /*
1517  * Wait for the completion of all issued write/flush of that txg provided.
1518  * It guarantees zil_lwb_flush_vdevs_done() is called and returned.
1519  */
1520 static void
zil_lwb_flush_wait_all(zilog_t * zilog,uint64_t txg)1521 zil_lwb_flush_wait_all(zilog_t *zilog, uint64_t txg)
1522 {
1523 	ASSERT3U(txg, ==, spa_syncing_txg(zilog->zl_spa));
1524 
1525 	mutex_enter(&zilog->zl_lwb_io_lock);
1526 	while (zilog->zl_lwb_inflight[txg & TXG_MASK] > 0)
1527 		cv_wait(&zilog->zl_lwb_io_cv, &zilog->zl_lwb_io_lock);
1528 	mutex_exit(&zilog->zl_lwb_io_lock);
1529 
1530 #ifdef ZFS_DEBUG
1531 	mutex_enter(&zilog->zl_lock);
1532 	mutex_enter(&zilog->zl_lwb_io_lock);
1533 	lwb_t *lwb = list_head(&zilog->zl_lwb_list);
1534 	while (lwb != NULL) {
1535 		if (lwb->lwb_issued_txg <= txg) {
1536 			ASSERT(lwb->lwb_state != LWB_STATE_ISSUED);
1537 			ASSERT(lwb->lwb_state != LWB_STATE_WRITE_DONE);
1538 			IMPLY(lwb->lwb_issued_txg > 0,
1539 			    lwb->lwb_state == LWB_STATE_FLUSH_DONE);
1540 		}
1541 		IMPLY(lwb->lwb_state == LWB_STATE_WRITE_DONE ||
1542 		    lwb->lwb_state == LWB_STATE_FLUSH_DONE,
1543 		    lwb->lwb_buf == NULL);
1544 		lwb = list_next(&zilog->zl_lwb_list, lwb);
1545 	}
1546 	mutex_exit(&zilog->zl_lwb_io_lock);
1547 	mutex_exit(&zilog->zl_lock);
1548 #endif
1549 }
1550 
1551 /*
1552  * This is called when an lwb's write zio completes. The callback's
1553  * purpose is to issue the DKIOCFLUSHWRITECACHE commands for the vdevs
1554  * in the lwb's lwb_vdev_tree. The tree will contain the vdevs involved
1555  * in writing out this specific lwb's data, and in the case that cache
1556  * flushes have been deferred, vdevs involved in writing the data for
1557  * previous lwbs. The writes corresponding to all the vdevs in the
1558  * lwb_vdev_tree will have completed by the time this is called, due to
1559  * the zio dependencies configured in zil_lwb_set_zio_dependency(),
1560  * which takes deferred flushes into account. The lwb will be "done"
1561  * once zil_lwb_flush_vdevs_done() is called, which occurs in the zio
1562  * completion callback for the lwb's root zio.
1563  */
1564 static void
zil_lwb_write_done(zio_t * zio)1565 zil_lwb_write_done(zio_t *zio)
1566 {
1567 	lwb_t *lwb = zio->io_private;
1568 	spa_t *spa = zio->io_spa;
1569 	zilog_t *zilog = lwb->lwb_zilog;
1570 	avl_tree_t *t = &lwb->lwb_vdev_tree;
1571 	void *cookie = NULL;
1572 	zil_vdev_node_t *zv;
1573 	lwb_t *nlwb;
1574 
1575 	ASSERT3S(spa_config_held(spa, SCL_STATE, RW_READER), !=, 0);
1576 
1577 	abd_free(zio->io_abd);
1578 	zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1579 	lwb->lwb_buf = NULL;
1580 
1581 	mutex_enter(&zilog->zl_lock);
1582 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_ISSUED);
1583 	lwb->lwb_state = LWB_STATE_WRITE_DONE;
1584 	lwb->lwb_child_zio = NULL;
1585 	lwb->lwb_write_zio = NULL;
1586 
1587 	/*
1588 	 * If nlwb is not yet issued, zil_lwb_set_zio_dependency() is not
1589 	 * called for it yet, and when it will be, it won't be able to make
1590 	 * its write ZIO a parent this ZIO.  In such case we can not defer
1591 	 * our flushes or below may be a race between the done callbacks.
1592 	 */
1593 	nlwb = list_next(&zilog->zl_lwb_list, lwb);
1594 	if (nlwb && nlwb->lwb_state != LWB_STATE_ISSUED)
1595 		nlwb = NULL;
1596 	mutex_exit(&zilog->zl_lock);
1597 
1598 	if (avl_numnodes(t) == 0)
1599 		return;
1600 
1601 	/*
1602 	 * If there was an IO error, we're not going to call zio_flush()
1603 	 * on these vdevs, so we simply empty the tree and free the
1604 	 * nodes. We avoid calling zio_flush() since there isn't any
1605 	 * good reason for doing so, after the lwb block failed to be
1606 	 * written out.
1607 	 *
1608 	 * Additionally, we don't perform any further error handling at
1609 	 * this point (e.g. setting "zcw_zio_error" appropriately), as
1610 	 * we expect that to occur in "zil_lwb_flush_vdevs_done" (thus,
1611 	 * we expect any error seen here, to have been propagated to
1612 	 * that function).
1613 	 */
1614 	if (zio->io_error != 0) {
1615 		while ((zv = avl_destroy_nodes(t, &cookie)) != NULL)
1616 			kmem_free(zv, sizeof (*zv));
1617 		return;
1618 	}
1619 
1620 	/*
1621 	 * If this lwb does not have any threads waiting for it to
1622 	 * complete, we want to defer issuing the DKIOCFLUSHWRITECACHE
1623 	 * command to the vdevs written to by "this" lwb, and instead
1624 	 * rely on the "next" lwb to handle the DKIOCFLUSHWRITECACHE
1625 	 * command for those vdevs. Thus, we merge the vdev tree of
1626 	 * "this" lwb with the vdev tree of the "next" lwb in the list,
1627 	 * and assume the "next" lwb will handle flushing the vdevs (or
1628 	 * deferring the flush(s) again).
1629 	 *
1630 	 * This is a useful performance optimization, especially for
1631 	 * workloads with lots of async write activity and few sync
1632 	 * write and/or fsync activity, as it has the potential to
1633 	 * coalesce multiple flush commands to a vdev into one.
1634 	 */
1635 	if (list_is_empty(&lwb->lwb_waiters) && nlwb != NULL) {
1636 		zil_lwb_flush_defer(lwb, nlwb);
1637 		ASSERT(avl_is_empty(&lwb->lwb_vdev_tree));
1638 		return;
1639 	}
1640 
1641 	while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
1642 		vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
1643 		if (vd != NULL) {
1644 			/*
1645 			 * The "ZIO_FLAG_DONT_PROPAGATE" is currently
1646 			 * always used within "zio_flush". This means,
1647 			 * any errors when flushing the vdev(s), will
1648 			 * (unfortunately) not be handled correctly,
1649 			 * since these "zio_flush" errors will not be
1650 			 * propagated up to "zil_lwb_flush_vdevs_done".
1651 			 */
1652 			zio_flush(lwb->lwb_root_zio, vd);
1653 		}
1654 		kmem_free(zv, sizeof (*zv));
1655 	}
1656 }
1657 
1658 /*
1659  * Build the zio dependency chain, which is used to preserve the ordering of
1660  * lwb completions that is required by the semantics of the ZIL. Each new lwb
1661  * zio becomes a parent of the previous lwb zio, such that the new lwb's zio
1662  * cannot complete until the previous lwb's zio completes.
1663  *
1664  * This is required by the semantics of zil_commit(): the commit waiters
1665  * attached to the lwbs will be woken in the lwb zio's completion callback,
1666  * so this zio dependency graph ensures the waiters are woken in the correct
1667  * order (the same order the lwbs were created).
1668  */
1669 static void
zil_lwb_set_zio_dependency(zilog_t * zilog,lwb_t * lwb)1670 zil_lwb_set_zio_dependency(zilog_t *zilog, lwb_t *lwb)
1671 {
1672 	ASSERT(MUTEX_HELD(&zilog->zl_lock));
1673 
1674 	lwb_t *prev_lwb = list_prev(&zilog->zl_lwb_list, lwb);
1675 	if (prev_lwb == NULL ||
1676 	    prev_lwb->lwb_state == LWB_STATE_FLUSH_DONE)
1677 		return;
1678 
1679 	/*
1680 	 * If the previous lwb's write hasn't already completed, we also want
1681 	 * to order the completion of the lwb write zios (above, we only order
1682 	 * the completion of the lwb root zios). This is required because of
1683 	 * how we can defer the DKIOCFLUSHWRITECACHE commands for each lwb.
1684 	 *
1685 	 * When the DKIOCFLUSHWRITECACHE commands are deferred, the previous
1686 	 * lwb will rely on this lwb to flush the vdevs written to by that
1687 	 * previous lwb. Thus, we need to ensure this lwb doesn't issue the
1688 	 * flush until after the previous lwb's write completes. We ensure
1689 	 * this ordering by setting the zio parent/child relationship here.
1690 	 *
1691 	 * Without this relationship on the lwb's write zio, it's possible
1692 	 * for this lwb's write to complete prior to the previous lwb's write
1693 	 * completing; and thus, the vdevs for the previous lwb would be
1694 	 * flushed prior to that lwb's data being written to those vdevs (the
1695 	 * vdevs are flushed in the lwb write zio's completion handler,
1696 	 * zil_lwb_write_done()).
1697 	 */
1698 	if (prev_lwb->lwb_state == LWB_STATE_ISSUED) {
1699 		ASSERT3P(prev_lwb->lwb_write_zio, !=, NULL);
1700 		zio_add_child(lwb->lwb_write_zio, prev_lwb->lwb_write_zio);
1701 	} else {
1702 		ASSERT3S(prev_lwb->lwb_state, ==, LWB_STATE_WRITE_DONE);
1703 	}
1704 
1705 	ASSERT3P(prev_lwb->lwb_root_zio, !=, NULL);
1706 	zio_add_child(lwb->lwb_root_zio, prev_lwb->lwb_root_zio);
1707 }
1708 
1709 
1710 /*
1711  * This function's purpose is to "open" an lwb such that it is ready to
1712  * accept new itxs being committed to it. This function is idempotent; if
1713  * the passed in lwb has already been opened, it is essentially a no-op.
1714  */
1715 static void
zil_lwb_write_open(zilog_t * zilog,lwb_t * lwb)1716 zil_lwb_write_open(zilog_t *zilog, lwb_t *lwb)
1717 {
1718 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1719 
1720 	if (lwb->lwb_state != LWB_STATE_NEW) {
1721 		ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
1722 		return;
1723 	}
1724 
1725 	mutex_enter(&zilog->zl_lock);
1726 	lwb->lwb_state = LWB_STATE_OPENED;
1727 	zilog->zl_last_lwb_opened = lwb;
1728 	mutex_exit(&zilog->zl_lock);
1729 }
1730 
1731 /*
1732  * Maximum block size used by the ZIL.  This is picked up when the ZIL is
1733  * initialized.  Otherwise this should not be used directly; see
1734  * zl_max_block_size instead.
1735  */
1736 static uint_t zil_maxblocksize = SPA_OLD_MAXBLOCKSIZE;
1737 
1738 /*
1739  * Plan splitting of the provided burst size between several blocks.
1740  */
1741 static uint_t
zil_lwb_plan(zilog_t * zilog,uint64_t size,uint_t * minsize)1742 zil_lwb_plan(zilog_t *zilog, uint64_t size, uint_t *minsize)
1743 {
1744 	uint_t md = zilog->zl_max_block_size - sizeof (zil_chain_t);
1745 
1746 	if (size <= md) {
1747 		/*
1748 		 * Small bursts are written as-is in one block.
1749 		 */
1750 		*minsize = size;
1751 		return (size);
1752 	} else if (size > 8 * md) {
1753 		/*
1754 		 * Big bursts use maximum blocks.  The first block size
1755 		 * is hard to predict, but it does not really matter.
1756 		 */
1757 		*minsize = 0;
1758 		return (md);
1759 	}
1760 
1761 	/*
1762 	 * Medium bursts try to divide evenly to better utilize several SLOG
1763 	 * VDEVs.  The first block size we predict assuming the worst case of
1764 	 * maxing out others.  Fall back to using maximum blocks if due to
1765 	 * large records or wasted space we can not predict anything better.
1766 	 */
1767 	uint_t s = size;
1768 	uint_t n = DIV_ROUND_UP(s, md - sizeof (lr_write_t));
1769 	uint_t chunk = DIV_ROUND_UP(s, n);
1770 	uint_t waste = zil_max_waste_space(zilog);
1771 	waste = MAX(waste, zilog->zl_cur_max);
1772 	if (chunk <= md - waste) {
1773 		*minsize = MAX(s - (md - waste) * (n - 1), waste);
1774 		return (chunk);
1775 	} else {
1776 		*minsize = 0;
1777 		return (md);
1778 	}
1779 }
1780 
1781 /*
1782  * Try to predict next block size based on previous history.  Make prediction
1783  * sufficient for 7 of 8 previous bursts.  Don't try to save if the saving is
1784  * less then 50%, extra writes may cost more, but we don't want single spike
1785  * to badly affect our predictions.
1786  */
1787 static uint_t
zil_lwb_predict(zilog_t * zilog)1788 zil_lwb_predict(zilog_t *zilog)
1789 {
1790 	uint_t m, o;
1791 
1792 	/* If we are in the middle of a burst, take it into account also. */
1793 	if (zilog->zl_cur_size > 0) {
1794 		o = zil_lwb_plan(zilog, zilog->zl_cur_size, &m);
1795 	} else {
1796 		o = UINT_MAX;
1797 		m = 0;
1798 	}
1799 
1800 	/* Find minimum optimal size.  We don't need to go below that. */
1801 	for (int i = 0; i < ZIL_BURSTS; i++)
1802 		o = MIN(o, zilog->zl_prev_opt[i]);
1803 
1804 	/* Find two biggest minimal first block sizes above the optimal. */
1805 	uint_t m1 = MAX(m, o), m2 = o;
1806 	for (int i = 0; i < ZIL_BURSTS; i++) {
1807 		m = zilog->zl_prev_min[i];
1808 		if (m >= m1) {
1809 			m2 = m1;
1810 			m1 = m;
1811 		} else if (m > m2) {
1812 			m2 = m;
1813 		}
1814 	}
1815 
1816 	/*
1817 	 * If second minimum size gives 50% saving -- use it.  It may cost us
1818 	 * one additional write later, but the space saving is just too big.
1819 	 */
1820 	return ((m1 < m2 * 2) ? m1 : m2);
1821 }
1822 
1823 /*
1824  * Close the log block for being issued and allocate the next one.
1825  * Has to be called under zl_issuer_lock to chain more lwbs.
1826  */
1827 static lwb_t *
zil_lwb_write_close(zilog_t * zilog,lwb_t * lwb,lwb_state_t state)1828 zil_lwb_write_close(zilog_t *zilog, lwb_t *lwb, lwb_state_t state)
1829 {
1830 	uint64_t blksz, plan, plan2;
1831 
1832 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
1833 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_OPENED);
1834 	lwb->lwb_state = LWB_STATE_CLOSED;
1835 
1836 	/*
1837 	 * If there was an allocation failure then returned NULL will trigger
1838 	 * zil_commit_writer_stall() at the caller.  This is inherently racy,
1839 	 * since allocation may not have happened yet.
1840 	 */
1841 	if (lwb->lwb_error != 0)
1842 		return (NULL);
1843 
1844 	/*
1845 	 * Log blocks are pre-allocated.  Here we select the size of the next
1846 	 * block, based on what's left of this burst and the previous history.
1847 	 * While we try to only write used part of the block, we can't just
1848 	 * always allocate the maximum block size because we can exhaust all
1849 	 * available pool log space, so we try to be reasonable.
1850 	 */
1851 	if (zilog->zl_cur_left > 0) {
1852 		/*
1853 		 * We are in the middle of a burst and know how much is left.
1854 		 * But if workload is multi-threaded there may be more soon.
1855 		 * Try to predict what can it be and plan for the worst case.
1856 		 */
1857 		uint_t m;
1858 		plan = zil_lwb_plan(zilog, zilog->zl_cur_left, &m);
1859 		if (zilog->zl_parallel) {
1860 			plan2 = zil_lwb_plan(zilog, zilog->zl_cur_left +
1861 			    zil_lwb_predict(zilog), &m);
1862 			if (plan < plan2)
1863 				plan = plan2;
1864 		}
1865 	} else {
1866 		/*
1867 		 * The previous burst is done and we can only predict what
1868 		 * will come next.
1869 		 */
1870 		plan = zil_lwb_predict(zilog);
1871 	}
1872 	blksz = plan + sizeof (zil_chain_t);
1873 	blksz = P2ROUNDUP_TYPED(blksz, ZIL_MIN_BLKSZ, uint64_t);
1874 	blksz = MIN(blksz, zilog->zl_max_block_size);
1875 	DTRACE_PROBE3(zil__block__size, zilog_t *, zilog, uint64_t, blksz,
1876 	    uint64_t, plan);
1877 
1878 	return (zil_alloc_lwb(zilog, blksz, NULL, 0, 0, state));
1879 }
1880 
1881 /*
1882  * Finalize previously closed block and issue the write zio.
1883  */
1884 static void
zil_lwb_write_issue(zilog_t * zilog,lwb_t * lwb)1885 zil_lwb_write_issue(zilog_t *zilog, lwb_t *lwb)
1886 {
1887 	spa_t *spa = zilog->zl_spa;
1888 	zil_chain_t *zilc;
1889 	boolean_t slog;
1890 	zbookmark_phys_t zb;
1891 	zio_priority_t prio;
1892 	int error;
1893 
1894 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_CLOSED);
1895 
1896 	/* Actually fill the lwb with the data. */
1897 	for (itx_t *itx = list_head(&lwb->lwb_itxs); itx;
1898 	    itx = list_next(&lwb->lwb_itxs, itx))
1899 		zil_lwb_commit(zilog, lwb, itx);
1900 	lwb->lwb_nused = lwb->lwb_nfilled;
1901 	ASSERT3U(lwb->lwb_nused, <=, lwb->lwb_nmax);
1902 
1903 	lwb->lwb_root_zio = zio_root(spa, zil_lwb_flush_vdevs_done, lwb,
1904 	    ZIO_FLAG_CANFAIL);
1905 
1906 	/*
1907 	 * The lwb is now ready to be issued, but it can be only if it already
1908 	 * got its block pointer allocated or the allocation has failed.
1909 	 * Otherwise leave it as-is, relying on some other thread to issue it
1910 	 * after allocating its block pointer via calling zil_lwb_write_issue()
1911 	 * for the previous lwb(s) in the chain.
1912 	 */
1913 	mutex_enter(&zilog->zl_lock);
1914 	lwb->lwb_state = LWB_STATE_READY;
1915 	if (BP_IS_HOLE(&lwb->lwb_blk) && lwb->lwb_error == 0) {
1916 		mutex_exit(&zilog->zl_lock);
1917 		return;
1918 	}
1919 	mutex_exit(&zilog->zl_lock);
1920 
1921 next_lwb:
1922 	if (lwb->lwb_slim)
1923 		zilc = (zil_chain_t *)lwb->lwb_buf;
1924 	else
1925 		zilc = (zil_chain_t *)(lwb->lwb_buf + lwb->lwb_nmax);
1926 	int wsz = lwb->lwb_sz;
1927 	if (lwb->lwb_error == 0) {
1928 		abd_t *lwb_abd = abd_get_from_buf(lwb->lwb_buf, lwb->lwb_sz);
1929 		if (!lwb->lwb_slog || zilog->zl_cur_size <= zil_slog_bulk)
1930 			prio = ZIO_PRIORITY_SYNC_WRITE;
1931 		else
1932 			prio = ZIO_PRIORITY_ASYNC_WRITE;
1933 		SET_BOOKMARK(&zb, lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET],
1934 		    ZB_ZIL_OBJECT, ZB_ZIL_LEVEL,
1935 		    lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ]);
1936 		lwb->lwb_write_zio = zio_rewrite(lwb->lwb_root_zio, spa, 0,
1937 		    &lwb->lwb_blk, lwb_abd, lwb->lwb_sz, zil_lwb_write_done,
1938 		    lwb, prio, ZIO_FLAG_CANFAIL, &zb);
1939 		zil_lwb_add_block(lwb, &lwb->lwb_blk);
1940 
1941 		if (lwb->lwb_slim) {
1942 			/* For Slim ZIL only write what is used. */
1943 			wsz = P2ROUNDUP_TYPED(lwb->lwb_nused, ZIL_MIN_BLKSZ,
1944 			    int);
1945 			ASSERT3S(wsz, <=, lwb->lwb_sz);
1946 			zio_shrink(lwb->lwb_write_zio, wsz);
1947 			wsz = lwb->lwb_write_zio->io_size;
1948 		}
1949 		memset(lwb->lwb_buf + lwb->lwb_nused, 0, wsz - lwb->lwb_nused);
1950 		zilc->zc_pad = 0;
1951 		zilc->zc_nused = lwb->lwb_nused;
1952 		zilc->zc_eck.zec_cksum = lwb->lwb_blk.blk_cksum;
1953 	} else {
1954 		/*
1955 		 * We can't write the lwb if there was an allocation failure,
1956 		 * so create a null zio instead just to maintain dependencies.
1957 		 */
1958 		lwb->lwb_write_zio = zio_null(lwb->lwb_root_zio, spa, NULL,
1959 		    zil_lwb_write_done, lwb, ZIO_FLAG_CANFAIL);
1960 		lwb->lwb_write_zio->io_error = lwb->lwb_error;
1961 	}
1962 	if (lwb->lwb_child_zio)
1963 		zio_add_child(lwb->lwb_write_zio, lwb->lwb_child_zio);
1964 
1965 	/*
1966 	 * Open transaction to allocate the next block pointer.
1967 	 */
1968 	dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
1969 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT | TXG_NOTHROTTLE));
1970 	dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1971 	uint64_t txg = dmu_tx_get_txg(tx);
1972 
1973 	/*
1974 	 * Allocate next the block pointer unless we are already in error.
1975 	 */
1976 	lwb_t *nlwb = list_next(&zilog->zl_lwb_list, lwb);
1977 	blkptr_t *bp = &zilc->zc_next_blk;
1978 	BP_ZERO(bp);
1979 	error = lwb->lwb_error;
1980 	if (error == 0) {
1981 		error = zio_alloc_zil(spa, zilog->zl_os, txg, bp, nlwb->lwb_sz,
1982 		    &slog);
1983 	}
1984 	if (error == 0) {
1985 		ASSERT3U(bp->blk_birth, ==, txg);
1986 		BP_SET_CHECKSUM(bp, nlwb->lwb_slim ? ZIO_CHECKSUM_ZILOG2 :
1987 		    ZIO_CHECKSUM_ZILOG);
1988 		bp->blk_cksum = lwb->lwb_blk.blk_cksum;
1989 		bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
1990 	}
1991 
1992 	/*
1993 	 * Reduce TXG open time by incrementing inflight counter and committing
1994 	 * the transaciton.  zil_sync() will wait for it to return to zero.
1995 	 */
1996 	mutex_enter(&zilog->zl_lwb_io_lock);
1997 	lwb->lwb_issued_txg = txg;
1998 	zilog->zl_lwb_inflight[txg & TXG_MASK]++;
1999 	zilog->zl_lwb_max_issued_txg = MAX(txg, zilog->zl_lwb_max_issued_txg);
2000 	mutex_exit(&zilog->zl_lwb_io_lock);
2001 	dmu_tx_commit(tx);
2002 
2003 	spa_config_enter(spa, SCL_STATE, lwb, RW_READER);
2004 
2005 	/*
2006 	 * We've completed all potentially blocking operations.  Update the
2007 	 * nlwb and allow it proceed without possible lock order reversals.
2008 	 */
2009 	mutex_enter(&zilog->zl_lock);
2010 	zil_lwb_set_zio_dependency(zilog, lwb);
2011 	lwb->lwb_state = LWB_STATE_ISSUED;
2012 
2013 	if (nlwb) {
2014 		nlwb->lwb_blk = *bp;
2015 		nlwb->lwb_error = error;
2016 		nlwb->lwb_slog = slog;
2017 		nlwb->lwb_alloc_txg = txg;
2018 		if (nlwb->lwb_state != LWB_STATE_READY)
2019 			nlwb = NULL;
2020 	}
2021 	mutex_exit(&zilog->zl_lock);
2022 
2023 	if (lwb->lwb_slog) {
2024 		ZIL_STAT_BUMP(zilog, zil_itx_metaslab_slog_count);
2025 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_slog_bytes,
2026 		    lwb->lwb_nused);
2027 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_slog_write,
2028 		    wsz);
2029 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_slog_alloc,
2030 		    BP_GET_LSIZE(&lwb->lwb_blk));
2031 	} else {
2032 		ZIL_STAT_BUMP(zilog, zil_itx_metaslab_normal_count);
2033 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_normal_bytes,
2034 		    lwb->lwb_nused);
2035 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_normal_write,
2036 		    wsz);
2037 		ZIL_STAT_INCR(zilog, zil_itx_metaslab_normal_alloc,
2038 		    BP_GET_LSIZE(&lwb->lwb_blk));
2039 	}
2040 	lwb->lwb_issued_timestamp = gethrtime();
2041 	if (lwb->lwb_child_zio)
2042 		zio_nowait(lwb->lwb_child_zio);
2043 	zio_nowait(lwb->lwb_write_zio);
2044 	zio_nowait(lwb->lwb_root_zio);
2045 
2046 	/*
2047 	 * If nlwb was ready when we gave it the block pointer,
2048 	 * it is on us to issue it and possibly following ones.
2049 	 */
2050 	lwb = nlwb;
2051 	if (lwb)
2052 		goto next_lwb;
2053 }
2054 
2055 /*
2056  * Maximum amount of data that can be put into single log block.
2057  */
2058 uint64_t
zil_max_log_data(zilog_t * zilog,size_t hdrsize)2059 zil_max_log_data(zilog_t *zilog, size_t hdrsize)
2060 {
2061 	return (zilog->zl_max_block_size - sizeof (zil_chain_t) - hdrsize);
2062 }
2063 
2064 /*
2065  * Maximum amount of log space we agree to waste to reduce number of
2066  * WR_NEED_COPY chunks to reduce zl_get_data() overhead (~6%).
2067  */
2068 static inline uint64_t
zil_max_waste_space(zilog_t * zilog)2069 zil_max_waste_space(zilog_t *zilog)
2070 {
2071 	return (zil_max_log_data(zilog, sizeof (lr_write_t)) / 16);
2072 }
2073 
2074 /*
2075  * Maximum amount of write data for WR_COPIED.  For correctness, consumers
2076  * must fall back to WR_NEED_COPY if we can't fit the entire record into one
2077  * maximum sized log block, because each WR_COPIED record must fit in a
2078  * single log block.  Below that it is a tradeoff of additional memory copy
2079  * and possibly worse log space efficiency vs additional range lock/unlock.
2080  */
2081 static uint_t zil_maxcopied = 7680;
2082 
2083 uint64_t
zil_max_copied_data(zilog_t * zilog)2084 zil_max_copied_data(zilog_t *zilog)
2085 {
2086 	uint64_t max_data = zil_max_log_data(zilog, sizeof (lr_write_t));
2087 	return (MIN(max_data, zil_maxcopied));
2088 }
2089 
2090 static uint64_t
zil_itx_record_size(itx_t * itx)2091 zil_itx_record_size(itx_t *itx)
2092 {
2093 	lr_t *lr = &itx->itx_lr;
2094 
2095 	if (lr->lrc_txtype == TX_COMMIT)
2096 		return (0);
2097 	ASSERT3U(lr->lrc_reclen, >=, sizeof (lr_t));
2098 	return (lr->lrc_reclen);
2099 }
2100 
2101 static uint64_t
zil_itx_data_size(itx_t * itx)2102 zil_itx_data_size(itx_t *itx)
2103 {
2104 	lr_t *lr = &itx->itx_lr;
2105 	lr_write_t *lrw = (lr_write_t *)lr;
2106 
2107 	if (lr->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY) {
2108 		ASSERT3U(lr->lrc_reclen, ==, sizeof (lr_write_t));
2109 		return (P2ROUNDUP_TYPED(lrw->lr_length, sizeof (uint64_t),
2110 		    uint64_t));
2111 	}
2112 	return (0);
2113 }
2114 
2115 static uint64_t
zil_itx_full_size(itx_t * itx)2116 zil_itx_full_size(itx_t *itx)
2117 {
2118 	lr_t *lr = &itx->itx_lr;
2119 
2120 	if (lr->lrc_txtype == TX_COMMIT)
2121 		return (0);
2122 	ASSERT3U(lr->lrc_reclen, >=, sizeof (lr_t));
2123 	return (lr->lrc_reclen + zil_itx_data_size(itx));
2124 }
2125 
2126 /*
2127  * Estimate space needed in the lwb for the itx.  Allocate more lwbs or
2128  * split the itx as needed, but don't touch the actual transaction data.
2129  * Has to be called under zl_issuer_lock to call zil_lwb_write_close()
2130  * to chain more lwbs.
2131  */
2132 static lwb_t *
zil_lwb_assign(zilog_t * zilog,lwb_t * lwb,itx_t * itx,list_t * ilwbs)2133 zil_lwb_assign(zilog_t *zilog, lwb_t *lwb, itx_t *itx, list_t *ilwbs)
2134 {
2135 	itx_t *citx;
2136 	lr_t *lr, *clr;
2137 	lr_write_t *lrw;
2138 	uint64_t dlen, dnow, lwb_sp, reclen, max_log_data;
2139 
2140 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2141 	ASSERT3P(lwb, !=, NULL);
2142 	ASSERT3P(lwb->lwb_buf, !=, NULL);
2143 
2144 	zil_lwb_write_open(zilog, lwb);
2145 
2146 	lr = &itx->itx_lr;
2147 	lrw = (lr_write_t *)lr;
2148 
2149 	/*
2150 	 * A commit itx doesn't represent any on-disk state; instead
2151 	 * it's simply used as a place holder on the commit list, and
2152 	 * provides a mechanism for attaching a "commit waiter" onto the
2153 	 * correct lwb (such that the waiter can be signalled upon
2154 	 * completion of that lwb). Thus, we don't process this itx's
2155 	 * log record if it's a commit itx (these itx's don't have log
2156 	 * records), and instead link the itx's waiter onto the lwb's
2157 	 * list of waiters.
2158 	 *
2159 	 * For more details, see the comment above zil_commit().
2160 	 */
2161 	if (lr->lrc_txtype == TX_COMMIT) {
2162 		zil_commit_waiter_link_lwb(itx->itx_private, lwb);
2163 		list_insert_tail(&lwb->lwb_itxs, itx);
2164 		return (lwb);
2165 	}
2166 
2167 	reclen = lr->lrc_reclen;
2168 	ASSERT3U(reclen, >=, sizeof (lr_t));
2169 	ASSERT3U(reclen, <=, zil_max_log_data(zilog, 0));
2170 	dlen = zil_itx_data_size(itx);
2171 
2172 cont:
2173 	/*
2174 	 * If this record won't fit in the current log block, start a new one.
2175 	 * For WR_NEED_COPY optimize layout for minimal number of chunks.
2176 	 */
2177 	lwb_sp = lwb->lwb_nmax - lwb->lwb_nused;
2178 	max_log_data = zil_max_log_data(zilog, sizeof (lr_write_t));
2179 	if (reclen > lwb_sp || (reclen + dlen > lwb_sp &&
2180 	    lwb_sp < zil_max_waste_space(zilog) &&
2181 	    (dlen % max_log_data == 0 ||
2182 	    lwb_sp < reclen + dlen % max_log_data))) {
2183 		list_insert_tail(ilwbs, lwb);
2184 		lwb = zil_lwb_write_close(zilog, lwb, LWB_STATE_OPENED);
2185 		if (lwb == NULL)
2186 			return (NULL);
2187 		lwb_sp = lwb->lwb_nmax - lwb->lwb_nused;
2188 	}
2189 
2190 	/*
2191 	 * There must be enough space in the log block to hold reclen.
2192 	 * For WR_COPIED, we need to fit the whole record in one block,
2193 	 * and reclen is the write record header size + the data size.
2194 	 * For WR_NEED_COPY, we can create multiple records, splitting
2195 	 * the data into multiple blocks, so we only need to fit one
2196 	 * word of data per block; in this case reclen is just the header
2197 	 * size (no data).
2198 	 */
2199 	ASSERT3U(reclen + MIN(dlen, sizeof (uint64_t)), <=, lwb_sp);
2200 
2201 	dnow = MIN(dlen, lwb_sp - reclen);
2202 	if (dlen > dnow) {
2203 		ASSERT3U(lr->lrc_txtype, ==, TX_WRITE);
2204 		ASSERT3U(itx->itx_wr_state, ==, WR_NEED_COPY);
2205 		citx = zil_itx_clone(itx);
2206 		clr = &citx->itx_lr;
2207 		lr_write_t *clrw = (lr_write_t *)clr;
2208 		clrw->lr_length = dnow;
2209 		lrw->lr_offset += dnow;
2210 		lrw->lr_length -= dnow;
2211 		zilog->zl_cur_left -= dnow;
2212 	} else {
2213 		citx = itx;
2214 		clr = lr;
2215 	}
2216 
2217 	/*
2218 	 * We're actually making an entry, so update lrc_seq to be the
2219 	 * log record sequence number.  Note that this is generally not
2220 	 * equal to the itx sequence number because not all transactions
2221 	 * are synchronous, and sometimes spa_sync() gets there first.
2222 	 */
2223 	clr->lrc_seq = ++zilog->zl_lr_seq;
2224 
2225 	lwb->lwb_nused += reclen + dnow;
2226 	ASSERT3U(lwb->lwb_nused, <=, lwb->lwb_nmax);
2227 	ASSERT0(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)));
2228 
2229 	zil_lwb_add_txg(lwb, lr->lrc_txg);
2230 	list_insert_tail(&lwb->lwb_itxs, citx);
2231 
2232 	dlen -= dnow;
2233 	if (dlen > 0)
2234 		goto cont;
2235 
2236 	if (lr->lrc_txtype == TX_WRITE &&
2237 	    lr->lrc_txg > spa_freeze_txg(zilog->zl_spa))
2238 		txg_wait_synced(zilog->zl_dmu_pool, lr->lrc_txg);
2239 
2240 	return (lwb);
2241 }
2242 
2243 /*
2244  * Fill the actual transaction data into the lwb, following zil_lwb_assign().
2245  * Does not require locking.
2246  */
2247 static void
zil_lwb_commit(zilog_t * zilog,lwb_t * lwb,itx_t * itx)2248 zil_lwb_commit(zilog_t *zilog, lwb_t *lwb, itx_t *itx)
2249 {
2250 	lr_t *lr, *lrb;
2251 	lr_write_t *lrw, *lrwb;
2252 	char *lr_buf;
2253 	uint64_t dlen, reclen;
2254 
2255 	lr = &itx->itx_lr;
2256 	lrw = (lr_write_t *)lr;
2257 
2258 	if (lr->lrc_txtype == TX_COMMIT)
2259 		return;
2260 
2261 	reclen = lr->lrc_reclen;
2262 	dlen = zil_itx_data_size(itx);
2263 	ASSERT3U(reclen + dlen, <=, lwb->lwb_nused - lwb->lwb_nfilled);
2264 
2265 	lr_buf = lwb->lwb_buf + lwb->lwb_nfilled;
2266 	memcpy(lr_buf, lr, reclen);
2267 	lrb = (lr_t *)lr_buf;		/* Like lr, but inside lwb. */
2268 	lrwb = (lr_write_t *)lrb;	/* Like lrw, but inside lwb. */
2269 
2270 	ZIL_STAT_BUMP(zilog, zil_itx_count);
2271 
2272 	/*
2273 	 * If it's a write, fetch the data or get its blkptr as appropriate.
2274 	 */
2275 	if (lr->lrc_txtype == TX_WRITE) {
2276 		if (itx->itx_wr_state == WR_COPIED) {
2277 			ZIL_STAT_BUMP(zilog, zil_itx_copied_count);
2278 			ZIL_STAT_INCR(zilog, zil_itx_copied_bytes,
2279 			    lrw->lr_length);
2280 		} else {
2281 			char *dbuf;
2282 			int error;
2283 
2284 			if (itx->itx_wr_state == WR_NEED_COPY) {
2285 				dbuf = lr_buf + reclen;
2286 				lrb->lrc_reclen += dlen;
2287 				ZIL_STAT_BUMP(zilog, zil_itx_needcopy_count);
2288 				ZIL_STAT_INCR(zilog, zil_itx_needcopy_bytes,
2289 				    dlen);
2290 			} else {
2291 				ASSERT3S(itx->itx_wr_state, ==, WR_INDIRECT);
2292 				dbuf = NULL;
2293 				ZIL_STAT_BUMP(zilog, zil_itx_indirect_count);
2294 				ZIL_STAT_INCR(zilog, zil_itx_indirect_bytes,
2295 				    lrw->lr_length);
2296 				if (lwb->lwb_child_zio == NULL) {
2297 					lwb->lwb_child_zio = zio_root(
2298 					    zilog->zl_spa, NULL, NULL,
2299 					    ZIO_FLAG_CANFAIL);
2300 				}
2301 			}
2302 
2303 			/*
2304 			 * The "lwb_child_zio" we pass in will become a child of
2305 			 * "lwb_write_zio", when one is created, so one will be
2306 			 * a parent of any zio's created by the "zl_get_data".
2307 			 * This way "lwb_write_zio" will first wait for children
2308 			 * block pointers before own writing, and then for their
2309 			 * writing completion before the vdev cache flushing.
2310 			 */
2311 			error = zilog->zl_get_data(itx->itx_private,
2312 			    itx->itx_gen, lrwb, dbuf, lwb,
2313 			    lwb->lwb_child_zio);
2314 			if (dbuf != NULL && error == 0) {
2315 				/* Zero any padding bytes in the last block. */
2316 				memset((char *)dbuf + lrwb->lr_length, 0,
2317 				    dlen - lrwb->lr_length);
2318 			}
2319 
2320 			/*
2321 			 * Typically, the only return values we should see from
2322 			 * ->zl_get_data() are 0, EIO, ENOENT, EEXIST or
2323 			 *  EALREADY. However, it is also possible to see other
2324 			 *  error values such as ENOSPC or EINVAL from
2325 			 *  dmu_read() -> dnode_hold() -> dnode_hold_impl() or
2326 			 *  ENXIO as well as a multitude of others from the
2327 			 *  block layer through dmu_buf_hold() -> dbuf_read()
2328 			 *  -> zio_wait(), as well as through dmu_read() ->
2329 			 *  dnode_hold() -> dnode_hold_impl() -> dbuf_read() ->
2330 			 *  zio_wait(). When these errors happen, we can assume
2331 			 *  that neither an immediate write nor an indirect
2332 			 *  write occurred, so we need to fall back to
2333 			 *  txg_wait_synced(). This is unusual, so we print to
2334 			 *  dmesg whenever one of these errors occurs.
2335 			 */
2336 			switch (error) {
2337 			case 0:
2338 				break;
2339 			default:
2340 				cmn_err(CE_WARN, "zil_lwb_commit() received "
2341 				    "unexpected error %d from ->zl_get_data()"
2342 				    ". Falling back to txg_wait_synced().",
2343 				    error);
2344 				zfs_fallthrough;
2345 			case EIO:
2346 				txg_wait_synced(zilog->zl_dmu_pool,
2347 				    lr->lrc_txg);
2348 				zfs_fallthrough;
2349 			case ENOENT:
2350 				zfs_fallthrough;
2351 			case EEXIST:
2352 				zfs_fallthrough;
2353 			case EALREADY:
2354 				return;
2355 			}
2356 		}
2357 	}
2358 
2359 	lwb->lwb_nfilled += reclen + dlen;
2360 	ASSERT3S(lwb->lwb_nfilled, <=, lwb->lwb_nused);
2361 	ASSERT0(P2PHASE(lwb->lwb_nfilled, sizeof (uint64_t)));
2362 }
2363 
2364 itx_t *
zil_itx_create(uint64_t txtype,size_t olrsize)2365 zil_itx_create(uint64_t txtype, size_t olrsize)
2366 {
2367 	size_t itxsize, lrsize;
2368 	itx_t *itx;
2369 
2370 	ASSERT3U(olrsize, >=, sizeof (lr_t));
2371 	lrsize = P2ROUNDUP_TYPED(olrsize, sizeof (uint64_t), size_t);
2372 	ASSERT3U(lrsize, >=, olrsize);
2373 	itxsize = offsetof(itx_t, itx_lr) + lrsize;
2374 
2375 	itx = zio_data_buf_alloc(itxsize);
2376 	itx->itx_lr.lrc_txtype = txtype;
2377 	itx->itx_lr.lrc_reclen = lrsize;
2378 	itx->itx_lr.lrc_seq = 0;	/* defensive */
2379 	memset((char *)&itx->itx_lr + olrsize, 0, lrsize - olrsize);
2380 	itx->itx_sync = B_TRUE;		/* default is synchronous */
2381 	itx->itx_callback = NULL;
2382 	itx->itx_callback_data = NULL;
2383 	itx->itx_size = itxsize;
2384 
2385 	return (itx);
2386 }
2387 
2388 static itx_t *
zil_itx_clone(itx_t * oitx)2389 zil_itx_clone(itx_t *oitx)
2390 {
2391 	ASSERT3U(oitx->itx_size, >=, sizeof (itx_t));
2392 	ASSERT3U(oitx->itx_size, ==,
2393 	    offsetof(itx_t, itx_lr) + oitx->itx_lr.lrc_reclen);
2394 
2395 	itx_t *itx = zio_data_buf_alloc(oitx->itx_size);
2396 	memcpy(itx, oitx, oitx->itx_size);
2397 	itx->itx_callback = NULL;
2398 	itx->itx_callback_data = NULL;
2399 	return (itx);
2400 }
2401 
2402 void
zil_itx_destroy(itx_t * itx)2403 zil_itx_destroy(itx_t *itx)
2404 {
2405 	ASSERT3U(itx->itx_size, >=, sizeof (itx_t));
2406 	ASSERT3U(itx->itx_lr.lrc_reclen, ==,
2407 	    itx->itx_size - offsetof(itx_t, itx_lr));
2408 	IMPLY(itx->itx_lr.lrc_txtype == TX_COMMIT, itx->itx_callback == NULL);
2409 	IMPLY(itx->itx_callback != NULL, itx->itx_lr.lrc_txtype != TX_COMMIT);
2410 
2411 	if (itx->itx_callback != NULL)
2412 		itx->itx_callback(itx->itx_callback_data);
2413 
2414 	zio_data_buf_free(itx, itx->itx_size);
2415 }
2416 
2417 /*
2418  * Free up the sync and async itxs. The itxs_t has already been detached
2419  * so no locks are needed.
2420  */
2421 static void
zil_itxg_clean(void * arg)2422 zil_itxg_clean(void *arg)
2423 {
2424 	itx_t *itx;
2425 	list_t *list;
2426 	avl_tree_t *t;
2427 	void *cookie;
2428 	itxs_t *itxs = arg;
2429 	itx_async_node_t *ian;
2430 
2431 	list = &itxs->i_sync_list;
2432 	while ((itx = list_remove_head(list)) != NULL) {
2433 		/*
2434 		 * In the general case, commit itxs will not be found
2435 		 * here, as they'll be committed to an lwb via
2436 		 * zil_lwb_assign(), and free'd in that function. Having
2437 		 * said that, it is still possible for commit itxs to be
2438 		 * found here, due to the following race:
2439 		 *
2440 		 *	- a thread calls zil_commit() which assigns the
2441 		 *	  commit itx to a per-txg i_sync_list
2442 		 *	- zil_itxg_clean() is called (e.g. via spa_sync())
2443 		 *	  while the waiter is still on the i_sync_list
2444 		 *
2445 		 * There's nothing to prevent syncing the txg while the
2446 		 * waiter is on the i_sync_list. This normally doesn't
2447 		 * happen because spa_sync() is slower than zil_commit(),
2448 		 * but if zil_commit() calls txg_wait_synced() (e.g.
2449 		 * because zil_create() or zil_commit_writer_stall() is
2450 		 * called) we will hit this case.
2451 		 */
2452 		if (itx->itx_lr.lrc_txtype == TX_COMMIT)
2453 			zil_commit_waiter_skip(itx->itx_private);
2454 
2455 		zil_itx_destroy(itx);
2456 	}
2457 
2458 	cookie = NULL;
2459 	t = &itxs->i_async_tree;
2460 	while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
2461 		list = &ian->ia_list;
2462 		while ((itx = list_remove_head(list)) != NULL) {
2463 			/* commit itxs should never be on the async lists. */
2464 			ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT);
2465 			zil_itx_destroy(itx);
2466 		}
2467 		list_destroy(list);
2468 		kmem_free(ian, sizeof (itx_async_node_t));
2469 	}
2470 	avl_destroy(t);
2471 
2472 	kmem_free(itxs, sizeof (itxs_t));
2473 }
2474 
2475 static int
zil_aitx_compare(const void * x1,const void * x2)2476 zil_aitx_compare(const void *x1, const void *x2)
2477 {
2478 	const uint64_t o1 = ((itx_async_node_t *)x1)->ia_foid;
2479 	const uint64_t o2 = ((itx_async_node_t *)x2)->ia_foid;
2480 
2481 	return (TREE_CMP(o1, o2));
2482 }
2483 
2484 /*
2485  * Remove all async itx with the given oid.
2486  */
2487 void
zil_remove_async(zilog_t * zilog,uint64_t oid)2488 zil_remove_async(zilog_t *zilog, uint64_t oid)
2489 {
2490 	uint64_t otxg, txg;
2491 	itx_async_node_t *ian, ian_search;
2492 	avl_tree_t *t;
2493 	avl_index_t where;
2494 	list_t clean_list;
2495 	itx_t *itx;
2496 
2497 	ASSERT(oid != 0);
2498 	list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
2499 
2500 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
2501 		otxg = ZILTEST_TXG;
2502 	else
2503 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
2504 
2505 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
2506 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
2507 
2508 		mutex_enter(&itxg->itxg_lock);
2509 		if (itxg->itxg_txg != txg) {
2510 			mutex_exit(&itxg->itxg_lock);
2511 			continue;
2512 		}
2513 
2514 		/*
2515 		 * Locate the object node and append its list.
2516 		 */
2517 		t = &itxg->itxg_itxs->i_async_tree;
2518 		ian_search.ia_foid = oid;
2519 		ian = avl_find(t, &ian_search, &where);
2520 		if (ian != NULL)
2521 			list_move_tail(&clean_list, &ian->ia_list);
2522 		mutex_exit(&itxg->itxg_lock);
2523 	}
2524 	while ((itx = list_remove_head(&clean_list)) != NULL) {
2525 		/* commit itxs should never be on the async lists. */
2526 		ASSERT3U(itx->itx_lr.lrc_txtype, !=, TX_COMMIT);
2527 		zil_itx_destroy(itx);
2528 	}
2529 	list_destroy(&clean_list);
2530 }
2531 
2532 void
zil_itx_assign(zilog_t * zilog,itx_t * itx,dmu_tx_t * tx)2533 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
2534 {
2535 	uint64_t txg;
2536 	itxg_t *itxg;
2537 	itxs_t *itxs, *clean = NULL;
2538 
2539 	/*
2540 	 * Ensure the data of a renamed file is committed before the rename.
2541 	 */
2542 	if ((itx->itx_lr.lrc_txtype & ~TX_CI) == TX_RENAME)
2543 		zil_async_to_sync(zilog, itx->itx_oid);
2544 
2545 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX)
2546 		txg = ZILTEST_TXG;
2547 	else
2548 		txg = dmu_tx_get_txg(tx);
2549 
2550 	itxg = &zilog->zl_itxg[txg & TXG_MASK];
2551 	mutex_enter(&itxg->itxg_lock);
2552 	itxs = itxg->itxg_itxs;
2553 	if (itxg->itxg_txg != txg) {
2554 		if (itxs != NULL) {
2555 			/*
2556 			 * The zil_clean callback hasn't got around to cleaning
2557 			 * this itxg. Save the itxs for release below.
2558 			 * This should be rare.
2559 			 */
2560 			zfs_dbgmsg("zil_itx_assign: missed itx cleanup for "
2561 			    "txg %llu", (u_longlong_t)itxg->itxg_txg);
2562 			clean = itxg->itxg_itxs;
2563 		}
2564 		itxg->itxg_txg = txg;
2565 		itxs = itxg->itxg_itxs = kmem_zalloc(sizeof (itxs_t),
2566 		    KM_SLEEP);
2567 
2568 		list_create(&itxs->i_sync_list, sizeof (itx_t),
2569 		    offsetof(itx_t, itx_node));
2570 		avl_create(&itxs->i_async_tree, zil_aitx_compare,
2571 		    sizeof (itx_async_node_t),
2572 		    offsetof(itx_async_node_t, ia_node));
2573 	}
2574 	if (itx->itx_sync) {
2575 		list_insert_tail(&itxs->i_sync_list, itx);
2576 	} else {
2577 		avl_tree_t *t = &itxs->i_async_tree;
2578 		uint64_t foid =
2579 		    LR_FOID_GET_OBJ(((lr_ooo_t *)&itx->itx_lr)->lr_foid);
2580 		itx_async_node_t *ian;
2581 		avl_index_t where;
2582 
2583 		ian = avl_find(t, &foid, &where);
2584 		if (ian == NULL) {
2585 			ian = kmem_alloc(sizeof (itx_async_node_t),
2586 			    KM_SLEEP);
2587 			list_create(&ian->ia_list, sizeof (itx_t),
2588 			    offsetof(itx_t, itx_node));
2589 			ian->ia_foid = foid;
2590 			avl_insert(t, ian, where);
2591 		}
2592 		list_insert_tail(&ian->ia_list, itx);
2593 	}
2594 
2595 	itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
2596 
2597 	/*
2598 	 * We don't want to dirty the ZIL using ZILTEST_TXG, because
2599 	 * zil_clean() will never be called using ZILTEST_TXG. Thus, we
2600 	 * need to be careful to always dirty the ZIL using the "real"
2601 	 * TXG (not itxg_txg) even when the SPA is frozen.
2602 	 */
2603 	zilog_dirty(zilog, dmu_tx_get_txg(tx));
2604 	mutex_exit(&itxg->itxg_lock);
2605 
2606 	/* Release the old itxs now we've dropped the lock */
2607 	if (clean != NULL)
2608 		zil_itxg_clean(clean);
2609 }
2610 
2611 /*
2612  * If there are any in-memory intent log transactions which have now been
2613  * synced then start up a taskq to free them. We should only do this after we
2614  * have written out the uberblocks (i.e. txg has been committed) so that
2615  * don't inadvertently clean out in-memory log records that would be required
2616  * by zil_commit().
2617  */
2618 void
zil_clean(zilog_t * zilog,uint64_t synced_txg)2619 zil_clean(zilog_t *zilog, uint64_t synced_txg)
2620 {
2621 	itxg_t *itxg = &zilog->zl_itxg[synced_txg & TXG_MASK];
2622 	itxs_t *clean_me;
2623 
2624 	ASSERT3U(synced_txg, <, ZILTEST_TXG);
2625 
2626 	mutex_enter(&itxg->itxg_lock);
2627 	if (itxg->itxg_itxs == NULL || itxg->itxg_txg == ZILTEST_TXG) {
2628 		mutex_exit(&itxg->itxg_lock);
2629 		return;
2630 	}
2631 	ASSERT3U(itxg->itxg_txg, <=, synced_txg);
2632 	ASSERT3U(itxg->itxg_txg, !=, 0);
2633 	clean_me = itxg->itxg_itxs;
2634 	itxg->itxg_itxs = NULL;
2635 	itxg->itxg_txg = 0;
2636 	mutex_exit(&itxg->itxg_lock);
2637 	/*
2638 	 * Preferably start a task queue to free up the old itxs but
2639 	 * if taskq_dispatch can't allocate resources to do that then
2640 	 * free it in-line. This should be rare. Note, using TQ_SLEEP
2641 	 * created a bad performance problem.
2642 	 */
2643 	ASSERT3P(zilog->zl_dmu_pool, !=, NULL);
2644 	ASSERT3P(zilog->zl_dmu_pool->dp_zil_clean_taskq, !=, NULL);
2645 	taskqid_t id = taskq_dispatch(zilog->zl_dmu_pool->dp_zil_clean_taskq,
2646 	    zil_itxg_clean, clean_me, TQ_NOSLEEP);
2647 	if (id == TASKQID_INVALID)
2648 		zil_itxg_clean(clean_me);
2649 }
2650 
2651 /*
2652  * This function will traverse the queue of itxs that need to be
2653  * committed, and move them onto the ZIL's zl_itx_commit_list.
2654  */
2655 static uint64_t
zil_get_commit_list(zilog_t * zilog)2656 zil_get_commit_list(zilog_t *zilog)
2657 {
2658 	uint64_t otxg, txg, wtxg = 0;
2659 	list_t *commit_list = &zilog->zl_itx_commit_list;
2660 
2661 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2662 
2663 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
2664 		otxg = ZILTEST_TXG;
2665 	else
2666 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
2667 
2668 	/*
2669 	 * This is inherently racy, since there is nothing to prevent
2670 	 * the last synced txg from changing. That's okay since we'll
2671 	 * only commit things in the future.
2672 	 */
2673 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
2674 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
2675 
2676 		mutex_enter(&itxg->itxg_lock);
2677 		if (itxg->itxg_txg != txg) {
2678 			mutex_exit(&itxg->itxg_lock);
2679 			continue;
2680 		}
2681 
2682 		/*
2683 		 * If we're adding itx records to the zl_itx_commit_list,
2684 		 * then the zil better be dirty in this "txg". We can assert
2685 		 * that here since we're holding the itxg_lock which will
2686 		 * prevent spa_sync from cleaning it. Once we add the itxs
2687 		 * to the zl_itx_commit_list we must commit it to disk even
2688 		 * if it's unnecessary (i.e. the txg was synced).
2689 		 */
2690 		ASSERT(zilog_is_dirty_in_txg(zilog, txg) ||
2691 		    spa_freeze_txg(zilog->zl_spa) != UINT64_MAX);
2692 		list_t *sync_list = &itxg->itxg_itxs->i_sync_list;
2693 		itx_t *itx = NULL;
2694 		if (unlikely(zilog->zl_suspend > 0)) {
2695 			/*
2696 			 * ZIL was just suspended, but we lost the race.
2697 			 * Allow all earlier itxs to be committed, but ask
2698 			 * caller to do txg_wait_synced(txg) for any new.
2699 			 */
2700 			if (!list_is_empty(sync_list))
2701 				wtxg = MAX(wtxg, txg);
2702 		} else {
2703 			itx = list_head(sync_list);
2704 			list_move_tail(commit_list, sync_list);
2705 		}
2706 
2707 		mutex_exit(&itxg->itxg_lock);
2708 
2709 		while (itx != NULL) {
2710 			uint64_t s = zil_itx_full_size(itx);
2711 			zilog->zl_cur_size += s;
2712 			zilog->zl_cur_left += s;
2713 			s = zil_itx_record_size(itx);
2714 			zilog->zl_cur_max = MAX(zilog->zl_cur_max, s);
2715 			itx = list_next(commit_list, itx);
2716 		}
2717 	}
2718 	return (wtxg);
2719 }
2720 
2721 /*
2722  * Move the async itxs for a specified object to commit into sync lists.
2723  */
2724 void
zil_async_to_sync(zilog_t * zilog,uint64_t foid)2725 zil_async_to_sync(zilog_t *zilog, uint64_t foid)
2726 {
2727 	uint64_t otxg, txg;
2728 	itx_async_node_t *ian, ian_search;
2729 	avl_tree_t *t;
2730 	avl_index_t where;
2731 
2732 	if (spa_freeze_txg(zilog->zl_spa) != UINT64_MAX) /* ziltest support */
2733 		otxg = ZILTEST_TXG;
2734 	else
2735 		otxg = spa_last_synced_txg(zilog->zl_spa) + 1;
2736 
2737 	/*
2738 	 * This is inherently racy, since there is nothing to prevent
2739 	 * the last synced txg from changing.
2740 	 */
2741 	for (txg = otxg; txg < (otxg + TXG_CONCURRENT_STATES); txg++) {
2742 		itxg_t *itxg = &zilog->zl_itxg[txg & TXG_MASK];
2743 
2744 		mutex_enter(&itxg->itxg_lock);
2745 		if (itxg->itxg_txg != txg) {
2746 			mutex_exit(&itxg->itxg_lock);
2747 			continue;
2748 		}
2749 
2750 		/*
2751 		 * If a foid is specified then find that node and append its
2752 		 * list. Otherwise walk the tree appending all the lists
2753 		 * to the sync list. We add to the end rather than the
2754 		 * beginning to ensure the create has happened.
2755 		 */
2756 		t = &itxg->itxg_itxs->i_async_tree;
2757 		if (foid != 0) {
2758 			ian_search.ia_foid = foid;
2759 			ian = avl_find(t, &ian_search, &where);
2760 			if (ian != NULL) {
2761 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
2762 				    &ian->ia_list);
2763 			}
2764 		} else {
2765 			void *cookie = NULL;
2766 
2767 			while ((ian = avl_destroy_nodes(t, &cookie)) != NULL) {
2768 				list_move_tail(&itxg->itxg_itxs->i_sync_list,
2769 				    &ian->ia_list);
2770 				list_destroy(&ian->ia_list);
2771 				kmem_free(ian, sizeof (itx_async_node_t));
2772 			}
2773 		}
2774 		mutex_exit(&itxg->itxg_lock);
2775 	}
2776 }
2777 
2778 /*
2779  * This function will prune commit itxs that are at the head of the
2780  * commit list (it won't prune past the first non-commit itx), and
2781  * either: a) attach them to the last lwb that's still pending
2782  * completion, or b) skip them altogether.
2783  *
2784  * This is used as a performance optimization to prevent commit itxs
2785  * from generating new lwbs when it's unnecessary to do so.
2786  */
2787 static void
zil_prune_commit_list(zilog_t * zilog)2788 zil_prune_commit_list(zilog_t *zilog)
2789 {
2790 	itx_t *itx;
2791 
2792 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2793 
2794 	while ((itx = list_head(&zilog->zl_itx_commit_list)) != NULL) {
2795 		lr_t *lrc = &itx->itx_lr;
2796 		if (lrc->lrc_txtype != TX_COMMIT)
2797 			break;
2798 
2799 		mutex_enter(&zilog->zl_lock);
2800 
2801 		lwb_t *last_lwb = zilog->zl_last_lwb_opened;
2802 		if (last_lwb == NULL ||
2803 		    last_lwb->lwb_state == LWB_STATE_FLUSH_DONE) {
2804 			/*
2805 			 * All of the itxs this waiter was waiting on
2806 			 * must have already completed (or there were
2807 			 * never any itx's for it to wait on), so it's
2808 			 * safe to skip this waiter and mark it done.
2809 			 */
2810 			zil_commit_waiter_skip(itx->itx_private);
2811 		} else {
2812 			zil_commit_waiter_link_lwb(itx->itx_private, last_lwb);
2813 		}
2814 
2815 		mutex_exit(&zilog->zl_lock);
2816 
2817 		list_remove(&zilog->zl_itx_commit_list, itx);
2818 		zil_itx_destroy(itx);
2819 	}
2820 
2821 	IMPLY(itx != NULL, itx->itx_lr.lrc_txtype != TX_COMMIT);
2822 }
2823 
2824 static void
zil_commit_writer_stall(zilog_t * zilog)2825 zil_commit_writer_stall(zilog_t *zilog)
2826 {
2827 	/*
2828 	 * When zio_alloc_zil() fails to allocate the next lwb block on
2829 	 * disk, we must call txg_wait_synced() to ensure all of the
2830 	 * lwbs in the zilog's zl_lwb_list are synced and then freed (in
2831 	 * zil_sync()), such that any subsequent ZIL writer (i.e. a call
2832 	 * to zil_process_commit_list()) will have to call zil_create(),
2833 	 * and start a new ZIL chain.
2834 	 *
2835 	 * Since zil_alloc_zil() failed, the lwb that was previously
2836 	 * issued does not have a pointer to the "next" lwb on disk.
2837 	 * Thus, if another ZIL writer thread was to allocate the "next"
2838 	 * on-disk lwb, that block could be leaked in the event of a
2839 	 * crash (because the previous lwb on-disk would not point to
2840 	 * it).
2841 	 *
2842 	 * We must hold the zilog's zl_issuer_lock while we do this, to
2843 	 * ensure no new threads enter zil_process_commit_list() until
2844 	 * all lwb's in the zl_lwb_list have been synced and freed
2845 	 * (which is achieved via the txg_wait_synced() call).
2846 	 */
2847 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2848 	txg_wait_synced(zilog->zl_dmu_pool, 0);
2849 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
2850 }
2851 
2852 static void
zil_burst_done(zilog_t * zilog)2853 zil_burst_done(zilog_t *zilog)
2854 {
2855 	if (!list_is_empty(&zilog->zl_itx_commit_list) ||
2856 	    zilog->zl_cur_size == 0)
2857 		return;
2858 
2859 	if (zilog->zl_parallel)
2860 		zilog->zl_parallel--;
2861 
2862 	uint_t r = (zilog->zl_prev_rotor + 1) & (ZIL_BURSTS - 1);
2863 	zilog->zl_prev_rotor = r;
2864 	zilog->zl_prev_opt[r] = zil_lwb_plan(zilog, zilog->zl_cur_size,
2865 	    &zilog->zl_prev_min[r]);
2866 
2867 	zilog->zl_cur_size = 0;
2868 	zilog->zl_cur_max = 0;
2869 	zilog->zl_cur_left = 0;
2870 }
2871 
2872 /*
2873  * This function will traverse the commit list, creating new lwbs as
2874  * needed, and committing the itxs from the commit list to these newly
2875  * created lwbs. Additionally, as a new lwb is created, the previous
2876  * lwb will be issued to the zio layer to be written to disk.
2877  */
2878 static void
zil_process_commit_list(zilog_t * zilog,zil_commit_waiter_t * zcw,list_t * ilwbs)2879 zil_process_commit_list(zilog_t *zilog, zil_commit_waiter_t *zcw, list_t *ilwbs)
2880 {
2881 	spa_t *spa = zilog->zl_spa;
2882 	list_t nolwb_itxs;
2883 	list_t nolwb_waiters;
2884 	lwb_t *lwb, *plwb;
2885 	itx_t *itx;
2886 
2887 	ASSERT(MUTEX_HELD(&zilog->zl_issuer_lock));
2888 
2889 	/*
2890 	 * Return if there's nothing to commit before we dirty the fs by
2891 	 * calling zil_create().
2892 	 */
2893 	if (list_is_empty(&zilog->zl_itx_commit_list))
2894 		return;
2895 
2896 	list_create(&nolwb_itxs, sizeof (itx_t), offsetof(itx_t, itx_node));
2897 	list_create(&nolwb_waiters, sizeof (zil_commit_waiter_t),
2898 	    offsetof(zil_commit_waiter_t, zcw_node));
2899 
2900 	lwb = list_tail(&zilog->zl_lwb_list);
2901 	if (lwb == NULL) {
2902 		lwb = zil_create(zilog);
2903 	} else {
2904 		/*
2905 		 * Activate SPA_FEATURE_ZILSAXATTR for the cases where ZIL will
2906 		 * have already been created (zl_lwb_list not empty).
2907 		 */
2908 		zil_commit_activate_saxattr_feature(zilog);
2909 		ASSERT(lwb->lwb_state == LWB_STATE_NEW ||
2910 		    lwb->lwb_state == LWB_STATE_OPENED);
2911 
2912 		/*
2913 		 * If the lwb is still opened, it means the workload is really
2914 		 * multi-threaded and we won the chance of write aggregation.
2915 		 * If it is not opened yet, but previous lwb is still not
2916 		 * flushed, it still means the workload is multi-threaded, but
2917 		 * there was too much time between the commits to aggregate, so
2918 		 * we try aggregation next times, but without too much hopes.
2919 		 */
2920 		if (lwb->lwb_state == LWB_STATE_OPENED) {
2921 			zilog->zl_parallel = ZIL_BURSTS;
2922 		} else if ((plwb = list_prev(&zilog->zl_lwb_list, lwb))
2923 		    != NULL && plwb->lwb_state != LWB_STATE_FLUSH_DONE) {
2924 			zilog->zl_parallel = MAX(zilog->zl_parallel,
2925 			    ZIL_BURSTS / 2);
2926 		}
2927 	}
2928 
2929 	while ((itx = list_remove_head(&zilog->zl_itx_commit_list)) != NULL) {
2930 		lr_t *lrc = &itx->itx_lr;
2931 		uint64_t txg = lrc->lrc_txg;
2932 
2933 		ASSERT3U(txg, !=, 0);
2934 
2935 		if (lrc->lrc_txtype == TX_COMMIT) {
2936 			DTRACE_PROBE2(zil__process__commit__itx,
2937 			    zilog_t *, zilog, itx_t *, itx);
2938 		} else {
2939 			DTRACE_PROBE2(zil__process__normal__itx,
2940 			    zilog_t *, zilog, itx_t *, itx);
2941 		}
2942 
2943 		boolean_t synced = txg <= spa_last_synced_txg(spa);
2944 		boolean_t frozen = txg > spa_freeze_txg(spa);
2945 
2946 		/*
2947 		 * If the txg of this itx has already been synced out, then
2948 		 * we don't need to commit this itx to an lwb. This is
2949 		 * because the data of this itx will have already been
2950 		 * written to the main pool. This is inherently racy, and
2951 		 * it's still ok to commit an itx whose txg has already
2952 		 * been synced; this will result in a write that's
2953 		 * unnecessary, but will do no harm.
2954 		 *
2955 		 * With that said, we always want to commit TX_COMMIT itxs
2956 		 * to an lwb, regardless of whether or not that itx's txg
2957 		 * has been synced out. We do this to ensure any OPENED lwb
2958 		 * will always have at least one zil_commit_waiter_t linked
2959 		 * to the lwb.
2960 		 *
2961 		 * As a counter-example, if we skipped TX_COMMIT itx's
2962 		 * whose txg had already been synced, the following
2963 		 * situation could occur if we happened to be racing with
2964 		 * spa_sync:
2965 		 *
2966 		 * 1. We commit a non-TX_COMMIT itx to an lwb, where the
2967 		 *    itx's txg is 10 and the last synced txg is 9.
2968 		 * 2. spa_sync finishes syncing out txg 10.
2969 		 * 3. We move to the next itx in the list, it's a TX_COMMIT
2970 		 *    whose txg is 10, so we skip it rather than committing
2971 		 *    it to the lwb used in (1).
2972 		 *
2973 		 * If the itx that is skipped in (3) is the last TX_COMMIT
2974 		 * itx in the commit list, than it's possible for the lwb
2975 		 * used in (1) to remain in the OPENED state indefinitely.
2976 		 *
2977 		 * To prevent the above scenario from occurring, ensuring
2978 		 * that once an lwb is OPENED it will transition to ISSUED
2979 		 * and eventually DONE, we always commit TX_COMMIT itx's to
2980 		 * an lwb here, even if that itx's txg has already been
2981 		 * synced.
2982 		 *
2983 		 * Finally, if the pool is frozen, we _always_ commit the
2984 		 * itx.  The point of freezing the pool is to prevent data
2985 		 * from being written to the main pool via spa_sync, and
2986 		 * instead rely solely on the ZIL to persistently store the
2987 		 * data; i.e.  when the pool is frozen, the last synced txg
2988 		 * value can't be trusted.
2989 		 */
2990 		if (frozen || !synced || lrc->lrc_txtype == TX_COMMIT) {
2991 			if (lwb != NULL) {
2992 				lwb = zil_lwb_assign(zilog, lwb, itx, ilwbs);
2993 				if (lwb == NULL) {
2994 					list_insert_tail(&nolwb_itxs, itx);
2995 				} else if ((zcw->zcw_lwb != NULL &&
2996 				    zcw->zcw_lwb != lwb) || zcw->zcw_done) {
2997 					/*
2998 					 * Our lwb is done, leave the rest of
2999 					 * itx list to somebody else who care.
3000 					 */
3001 					zilog->zl_parallel = ZIL_BURSTS;
3002 					zilog->zl_cur_left -=
3003 					    zil_itx_full_size(itx);
3004 					break;
3005 				}
3006 			} else {
3007 				if (lrc->lrc_txtype == TX_COMMIT) {
3008 					zil_commit_waiter_link_nolwb(
3009 					    itx->itx_private, &nolwb_waiters);
3010 				}
3011 				list_insert_tail(&nolwb_itxs, itx);
3012 			}
3013 			zilog->zl_cur_left -= zil_itx_full_size(itx);
3014 		} else {
3015 			ASSERT3S(lrc->lrc_txtype, !=, TX_COMMIT);
3016 			zilog->zl_cur_left -= zil_itx_full_size(itx);
3017 			zil_itx_destroy(itx);
3018 		}
3019 	}
3020 
3021 	if (lwb == NULL) {
3022 		/*
3023 		 * This indicates zio_alloc_zil() failed to allocate the
3024 		 * "next" lwb on-disk. When this happens, we must stall
3025 		 * the ZIL write pipeline; see the comment within
3026 		 * zil_commit_writer_stall() for more details.
3027 		 */
3028 		while ((lwb = list_remove_head(ilwbs)) != NULL)
3029 			zil_lwb_write_issue(zilog, lwb);
3030 		zil_commit_writer_stall(zilog);
3031 
3032 		/*
3033 		 * Additionally, we have to signal and mark the "nolwb"
3034 		 * waiters as "done" here, since without an lwb, we
3035 		 * can't do this via zil_lwb_flush_vdevs_done() like
3036 		 * normal.
3037 		 */
3038 		zil_commit_waiter_t *zcw;
3039 		while ((zcw = list_remove_head(&nolwb_waiters)) != NULL)
3040 			zil_commit_waiter_skip(zcw);
3041 
3042 		/*
3043 		 * And finally, we have to destroy the itx's that
3044 		 * couldn't be committed to an lwb; this will also call
3045 		 * the itx's callback if one exists for the itx.
3046 		 */
3047 		while ((itx = list_remove_head(&nolwb_itxs)) != NULL)
3048 			zil_itx_destroy(itx);
3049 	} else {
3050 		ASSERT(list_is_empty(&nolwb_waiters));
3051 		ASSERT3P(lwb, !=, NULL);
3052 		ASSERT(lwb->lwb_state == LWB_STATE_NEW ||
3053 		    lwb->lwb_state == LWB_STATE_OPENED);
3054 
3055 		/*
3056 		 * At this point, the ZIL block pointed at by the "lwb"
3057 		 * variable is in "new" or "opened" state.
3058 		 *
3059 		 * If it's "new", then no itxs have been committed to it, so
3060 		 * there's no point in issuing its zio (i.e. it's "empty").
3061 		 *
3062 		 * If it's "opened", then it contains one or more itxs that
3063 		 * eventually need to be committed to stable storage. In
3064 		 * this case we intentionally do not issue the lwb's zio
3065 		 * to disk yet, and instead rely on one of the following
3066 		 * two mechanisms for issuing the zio:
3067 		 *
3068 		 * 1. Ideally, there will be more ZIL activity occurring on
3069 		 * the system, such that this function will be immediately
3070 		 * called again by different thread and this lwb will be
3071 		 * closed by zil_lwb_assign().  This way, the lwb will be
3072 		 * "full" when it is issued to disk, and we'll make use of
3073 		 * the lwb's size the best we can.
3074 		 *
3075 		 * 2. If there isn't sufficient ZIL activity occurring on
3076 		 * the system, zil_commit_waiter() will close it and issue
3077 		 * the zio.  If this occurs, the lwb is not guaranteed
3078 		 * to be "full" by the time its zio is issued, and means
3079 		 * the size of the lwb was "too large" given the amount
3080 		 * of ZIL activity occurring on the system at that time.
3081 		 *
3082 		 * We do this for a couple of reasons:
3083 		 *
3084 		 * 1. To try and reduce the number of IOPs needed to
3085 		 * write the same number of itxs. If an lwb has space
3086 		 * available in its buffer for more itxs, and more itxs
3087 		 * will be committed relatively soon (relative to the
3088 		 * latency of performing a write), then it's beneficial
3089 		 * to wait for these "next" itxs. This way, more itxs
3090 		 * can be committed to stable storage with fewer writes.
3091 		 *
3092 		 * 2. To try and use the largest lwb block size that the
3093 		 * incoming rate of itxs can support. Again, this is to
3094 		 * try and pack as many itxs into as few lwbs as
3095 		 * possible, without significantly impacting the latency
3096 		 * of each individual itx.
3097 		 */
3098 		if (lwb->lwb_state == LWB_STATE_OPENED && !zilog->zl_parallel) {
3099 			zil_burst_done(zilog);
3100 			list_insert_tail(ilwbs, lwb);
3101 			lwb = zil_lwb_write_close(zilog, lwb, LWB_STATE_NEW);
3102 			if (lwb == NULL) {
3103 				while ((lwb = list_remove_head(ilwbs)) != NULL)
3104 					zil_lwb_write_issue(zilog, lwb);
3105 				zil_commit_writer_stall(zilog);
3106 			}
3107 		}
3108 	}
3109 }
3110 
3111 /*
3112  * This function is responsible for ensuring the passed in commit waiter
3113  * (and associated commit itx) is committed to an lwb. If the waiter is
3114  * not already committed to an lwb, all itxs in the zilog's queue of
3115  * itxs will be processed. The assumption is the passed in waiter's
3116  * commit itx will found in the queue just like the other non-commit
3117  * itxs, such that when the entire queue is processed, the waiter will
3118  * have been committed to an lwb.
3119  *
3120  * The lwb associated with the passed in waiter is not guaranteed to
3121  * have been issued by the time this function completes. If the lwb is
3122  * not issued, we rely on future calls to zil_commit_writer() to issue
3123  * the lwb, or the timeout mechanism found in zil_commit_waiter().
3124  */
3125 static uint64_t
zil_commit_writer(zilog_t * zilog,zil_commit_waiter_t * zcw)3126 zil_commit_writer(zilog_t *zilog, zil_commit_waiter_t *zcw)
3127 {
3128 	list_t ilwbs;
3129 	lwb_t *lwb;
3130 	uint64_t wtxg = 0;
3131 
3132 	ASSERT(!MUTEX_HELD(&zilog->zl_lock));
3133 	ASSERT(spa_writeable(zilog->zl_spa));
3134 
3135 	list_create(&ilwbs, sizeof (lwb_t), offsetof(lwb_t, lwb_issue_node));
3136 	mutex_enter(&zilog->zl_issuer_lock);
3137 
3138 	if (zcw->zcw_lwb != NULL || zcw->zcw_done) {
3139 		/*
3140 		 * It's possible that, while we were waiting to acquire
3141 		 * the "zl_issuer_lock", another thread committed this
3142 		 * waiter to an lwb. If that occurs, we bail out early,
3143 		 * without processing any of the zilog's queue of itxs.
3144 		 *
3145 		 * On certain workloads and system configurations, the
3146 		 * "zl_issuer_lock" can become highly contended. In an
3147 		 * attempt to reduce this contention, we immediately drop
3148 		 * the lock if the waiter has already been processed.
3149 		 *
3150 		 * We've measured this optimization to reduce CPU spent
3151 		 * contending on this lock by up to 5%, using a system
3152 		 * with 32 CPUs, low latency storage (~50 usec writes),
3153 		 * and 1024 threads performing sync writes.
3154 		 */
3155 		goto out;
3156 	}
3157 
3158 	ZIL_STAT_BUMP(zilog, zil_commit_writer_count);
3159 
3160 	wtxg = zil_get_commit_list(zilog);
3161 	zil_prune_commit_list(zilog);
3162 	zil_process_commit_list(zilog, zcw, &ilwbs);
3163 
3164 out:
3165 	mutex_exit(&zilog->zl_issuer_lock);
3166 	while ((lwb = list_remove_head(&ilwbs)) != NULL)
3167 		zil_lwb_write_issue(zilog, lwb);
3168 	list_destroy(&ilwbs);
3169 	return (wtxg);
3170 }
3171 
3172 static void
zil_commit_waiter_timeout(zilog_t * zilog,zil_commit_waiter_t * zcw)3173 zil_commit_waiter_timeout(zilog_t *zilog, zil_commit_waiter_t *zcw)
3174 {
3175 	ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock));
3176 	ASSERT(MUTEX_HELD(&zcw->zcw_lock));
3177 	ASSERT3B(zcw->zcw_done, ==, B_FALSE);
3178 
3179 	lwb_t *lwb = zcw->zcw_lwb;
3180 	ASSERT3P(lwb, !=, NULL);
3181 	ASSERT3S(lwb->lwb_state, !=, LWB_STATE_NEW);
3182 
3183 	/*
3184 	 * If the lwb has already been issued by another thread, we can
3185 	 * immediately return since there's no work to be done (the
3186 	 * point of this function is to issue the lwb). Additionally, we
3187 	 * do this prior to acquiring the zl_issuer_lock, to avoid
3188 	 * acquiring it when it's not necessary to do so.
3189 	 */
3190 	if (lwb->lwb_state != LWB_STATE_OPENED)
3191 		return;
3192 
3193 	/*
3194 	 * In order to call zil_lwb_write_close() we must hold the
3195 	 * zilog's "zl_issuer_lock". We can't simply acquire that lock,
3196 	 * since we're already holding the commit waiter's "zcw_lock",
3197 	 * and those two locks are acquired in the opposite order
3198 	 * elsewhere.
3199 	 */
3200 	mutex_exit(&zcw->zcw_lock);
3201 	mutex_enter(&zilog->zl_issuer_lock);
3202 	mutex_enter(&zcw->zcw_lock);
3203 
3204 	/*
3205 	 * Since we just dropped and re-acquired the commit waiter's
3206 	 * lock, we have to re-check to see if the waiter was marked
3207 	 * "done" during that process. If the waiter was marked "done",
3208 	 * the "lwb" pointer is no longer valid (it can be free'd after
3209 	 * the waiter is marked "done"), so without this check we could
3210 	 * wind up with a use-after-free error below.
3211 	 */
3212 	if (zcw->zcw_done) {
3213 		mutex_exit(&zilog->zl_issuer_lock);
3214 		return;
3215 	}
3216 
3217 	ASSERT3P(lwb, ==, zcw->zcw_lwb);
3218 
3219 	/*
3220 	 * We've already checked this above, but since we hadn't acquired
3221 	 * the zilog's zl_issuer_lock, we have to perform this check a
3222 	 * second time while holding the lock.
3223 	 *
3224 	 * We don't need to hold the zl_lock since the lwb cannot transition
3225 	 * from OPENED to CLOSED while we hold the zl_issuer_lock. The lwb
3226 	 * _can_ transition from CLOSED to DONE, but it's OK to race with
3227 	 * that transition since we treat the lwb the same, whether it's in
3228 	 * the CLOSED, ISSUED or DONE states.
3229 	 *
3230 	 * The important thing, is we treat the lwb differently depending on
3231 	 * if it's OPENED or CLOSED, and block any other threads that might
3232 	 * attempt to close/issue this lwb. For that reason we hold the
3233 	 * zl_issuer_lock when checking the lwb_state; we must not call
3234 	 * zil_lwb_write_close() if the lwb had already been closed/issued.
3235 	 *
3236 	 * See the comment above the lwb_state_t structure definition for
3237 	 * more details on the lwb states, and locking requirements.
3238 	 */
3239 	if (lwb->lwb_state != LWB_STATE_OPENED) {
3240 		mutex_exit(&zilog->zl_issuer_lock);
3241 		return;
3242 	}
3243 
3244 	/*
3245 	 * We do not need zcw_lock once we hold zl_issuer_lock and know lwb
3246 	 * is still open.  But we have to drop it to avoid a deadlock in case
3247 	 * callback of zio issued by zil_lwb_write_issue() try to get it,
3248 	 * while zil_lwb_write_issue() is blocked on attempt to issue next
3249 	 * lwb it found in LWB_STATE_READY state.
3250 	 */
3251 	mutex_exit(&zcw->zcw_lock);
3252 
3253 	/*
3254 	 * As described in the comments above zil_commit_waiter() and
3255 	 * zil_process_commit_list(), we need to issue this lwb's zio
3256 	 * since we've reached the commit waiter's timeout and it still
3257 	 * hasn't been issued.
3258 	 */
3259 	zil_burst_done(zilog);
3260 	lwb_t *nlwb = zil_lwb_write_close(zilog, lwb, LWB_STATE_NEW);
3261 
3262 	ASSERT3S(lwb->lwb_state, ==, LWB_STATE_CLOSED);
3263 
3264 	if (nlwb == NULL) {
3265 		/*
3266 		 * When zil_lwb_write_close() returns NULL, this
3267 		 * indicates zio_alloc_zil() failed to allocate the
3268 		 * "next" lwb on-disk. When this occurs, the ZIL write
3269 		 * pipeline must be stalled; see the comment within the
3270 		 * zil_commit_writer_stall() function for more details.
3271 		 */
3272 		zil_lwb_write_issue(zilog, lwb);
3273 		zil_commit_writer_stall(zilog);
3274 		mutex_exit(&zilog->zl_issuer_lock);
3275 	} else {
3276 		mutex_exit(&zilog->zl_issuer_lock);
3277 		zil_lwb_write_issue(zilog, lwb);
3278 	}
3279 	mutex_enter(&zcw->zcw_lock);
3280 }
3281 
3282 /*
3283  * This function is responsible for performing the following two tasks:
3284  *
3285  * 1. its primary responsibility is to block until the given "commit
3286  *    waiter" is considered "done".
3287  *
3288  * 2. its secondary responsibility is to issue the zio for the lwb that
3289  *    the given "commit waiter" is waiting on, if this function has
3290  *    waited "long enough" and the lwb is still in the "open" state.
3291  *
3292  * Given a sufficient amount of itxs being generated and written using
3293  * the ZIL, the lwb's zio will be issued via the zil_lwb_assign()
3294  * function. If this does not occur, this secondary responsibility will
3295  * ensure the lwb is issued even if there is not other synchronous
3296  * activity on the system.
3297  *
3298  * For more details, see zil_process_commit_list(); more specifically,
3299  * the comment at the bottom of that function.
3300  */
3301 static void
zil_commit_waiter(zilog_t * zilog,zil_commit_waiter_t * zcw)3302 zil_commit_waiter(zilog_t *zilog, zil_commit_waiter_t *zcw)
3303 {
3304 	ASSERT(!MUTEX_HELD(&zilog->zl_lock));
3305 	ASSERT(!MUTEX_HELD(&zilog->zl_issuer_lock));
3306 	ASSERT(spa_writeable(zilog->zl_spa));
3307 
3308 	mutex_enter(&zcw->zcw_lock);
3309 
3310 	/*
3311 	 * The timeout is scaled based on the lwb latency to avoid
3312 	 * significantly impacting the latency of each individual itx.
3313 	 * For more details, see the comment at the bottom of the
3314 	 * zil_process_commit_list() function.
3315 	 */
3316 	int pct = MAX(zfs_commit_timeout_pct, 1);
3317 	hrtime_t sleep = (zilog->zl_last_lwb_latency * pct) / 100;
3318 	hrtime_t wakeup = gethrtime() + sleep;
3319 	boolean_t timedout = B_FALSE;
3320 
3321 	while (!zcw->zcw_done) {
3322 		ASSERT(MUTEX_HELD(&zcw->zcw_lock));
3323 
3324 		lwb_t *lwb = zcw->zcw_lwb;
3325 
3326 		/*
3327 		 * Usually, the waiter will have a non-NULL lwb field here,
3328 		 * but it's possible for it to be NULL as a result of
3329 		 * zil_commit() racing with spa_sync().
3330 		 *
3331 		 * When zil_clean() is called, it's possible for the itxg
3332 		 * list (which may be cleaned via a taskq) to contain
3333 		 * commit itxs. When this occurs, the commit waiters linked
3334 		 * off of these commit itxs will not be committed to an
3335 		 * lwb.  Additionally, these commit waiters will not be
3336 		 * marked done until zil_commit_waiter_skip() is called via
3337 		 * zil_itxg_clean().
3338 		 *
3339 		 * Thus, it's possible for this commit waiter (i.e. the
3340 		 * "zcw" variable) to be found in this "in between" state;
3341 		 * where it's "zcw_lwb" field is NULL, and it hasn't yet
3342 		 * been skipped, so it's "zcw_done" field is still B_FALSE.
3343 		 */
3344 		IMPLY(lwb != NULL, lwb->lwb_state != LWB_STATE_NEW);
3345 
3346 		if (lwb != NULL && lwb->lwb_state == LWB_STATE_OPENED) {
3347 			ASSERT3B(timedout, ==, B_FALSE);
3348 
3349 			/*
3350 			 * If the lwb hasn't been issued yet, then we
3351 			 * need to wait with a timeout, in case this
3352 			 * function needs to issue the lwb after the
3353 			 * timeout is reached; responsibility (2) from
3354 			 * the comment above this function.
3355 			 */
3356 			int rc = cv_timedwait_hires(&zcw->zcw_cv,
3357 			    &zcw->zcw_lock, wakeup, USEC2NSEC(1),
3358 			    CALLOUT_FLAG_ABSOLUTE);
3359 
3360 			if (rc != -1 || zcw->zcw_done)
3361 				continue;
3362 
3363 			timedout = B_TRUE;
3364 			zil_commit_waiter_timeout(zilog, zcw);
3365 
3366 			if (!zcw->zcw_done) {
3367 				/*
3368 				 * If the commit waiter has already been
3369 				 * marked "done", it's possible for the
3370 				 * waiter's lwb structure to have already
3371 				 * been freed.  Thus, we can only reliably
3372 				 * make these assertions if the waiter
3373 				 * isn't done.
3374 				 */
3375 				ASSERT3P(lwb, ==, zcw->zcw_lwb);
3376 				ASSERT3S(lwb->lwb_state, !=, LWB_STATE_OPENED);
3377 			}
3378 		} else {
3379 			/*
3380 			 * If the lwb isn't open, then it must have already
3381 			 * been issued. In that case, there's no need to
3382 			 * use a timeout when waiting for the lwb to
3383 			 * complete.
3384 			 *
3385 			 * Additionally, if the lwb is NULL, the waiter
3386 			 * will soon be signaled and marked done via
3387 			 * zil_clean() and zil_itxg_clean(), so no timeout
3388 			 * is required.
3389 			 */
3390 
3391 			IMPLY(lwb != NULL,
3392 			    lwb->lwb_state == LWB_STATE_CLOSED ||
3393 			    lwb->lwb_state == LWB_STATE_READY ||
3394 			    lwb->lwb_state == LWB_STATE_ISSUED ||
3395 			    lwb->lwb_state == LWB_STATE_WRITE_DONE ||
3396 			    lwb->lwb_state == LWB_STATE_FLUSH_DONE);
3397 			cv_wait(&zcw->zcw_cv, &zcw->zcw_lock);
3398 		}
3399 	}
3400 
3401 	mutex_exit(&zcw->zcw_lock);
3402 }
3403 
3404 static zil_commit_waiter_t *
zil_alloc_commit_waiter(void)3405 zil_alloc_commit_waiter(void)
3406 {
3407 	zil_commit_waiter_t *zcw = kmem_cache_alloc(zil_zcw_cache, KM_SLEEP);
3408 
3409 	cv_init(&zcw->zcw_cv, NULL, CV_DEFAULT, NULL);
3410 	mutex_init(&zcw->zcw_lock, NULL, MUTEX_DEFAULT, NULL);
3411 	list_link_init(&zcw->zcw_node);
3412 	zcw->zcw_lwb = NULL;
3413 	zcw->zcw_done = B_FALSE;
3414 	zcw->zcw_zio_error = 0;
3415 
3416 	return (zcw);
3417 }
3418 
3419 static void
zil_free_commit_waiter(zil_commit_waiter_t * zcw)3420 zil_free_commit_waiter(zil_commit_waiter_t *zcw)
3421 {
3422 	ASSERT(!list_link_active(&zcw->zcw_node));
3423 	ASSERT3P(zcw->zcw_lwb, ==, NULL);
3424 	ASSERT3B(zcw->zcw_done, ==, B_TRUE);
3425 	mutex_destroy(&zcw->zcw_lock);
3426 	cv_destroy(&zcw->zcw_cv);
3427 	kmem_cache_free(zil_zcw_cache, zcw);
3428 }
3429 
3430 /*
3431  * This function is used to create a TX_COMMIT itx and assign it. This
3432  * way, it will be linked into the ZIL's list of synchronous itxs, and
3433  * then later committed to an lwb (or skipped) when
3434  * zil_process_commit_list() is called.
3435  */
3436 static void
zil_commit_itx_assign(zilog_t * zilog,zil_commit_waiter_t * zcw)3437 zil_commit_itx_assign(zilog_t *zilog, zil_commit_waiter_t *zcw)
3438 {
3439 	dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
3440 
3441 	/*
3442 	 * Since we are not going to create any new dirty data, and we
3443 	 * can even help with clearing the existing dirty data, we
3444 	 * should not be subject to the dirty data based delays. We
3445 	 * use TXG_NOTHROTTLE to bypass the delay mechanism.
3446 	 */
3447 	VERIFY0(dmu_tx_assign(tx, TXG_WAIT | TXG_NOTHROTTLE));
3448 
3449 	itx_t *itx = zil_itx_create(TX_COMMIT, sizeof (lr_t));
3450 	itx->itx_sync = B_TRUE;
3451 	itx->itx_private = zcw;
3452 
3453 	zil_itx_assign(zilog, itx, tx);
3454 
3455 	dmu_tx_commit(tx);
3456 }
3457 
3458 /*
3459  * Commit ZFS Intent Log transactions (itxs) to stable storage.
3460  *
3461  * When writing ZIL transactions to the on-disk representation of the
3462  * ZIL, the itxs are committed to a Log Write Block (lwb). Multiple
3463  * itxs can be committed to a single lwb. Once a lwb is written and
3464  * committed to stable storage (i.e. the lwb is written, and vdevs have
3465  * been flushed), each itx that was committed to that lwb is also
3466  * considered to be committed to stable storage.
3467  *
3468  * When an itx is committed to an lwb, the log record (lr_t) contained
3469  * by the itx is copied into the lwb's zio buffer, and once this buffer
3470  * is written to disk, it becomes an on-disk ZIL block.
3471  *
3472  * As itxs are generated, they're inserted into the ZIL's queue of
3473  * uncommitted itxs. The semantics of zil_commit() are such that it will
3474  * block until all itxs that were in the queue when it was called, are
3475  * committed to stable storage.
3476  *
3477  * If "foid" is zero, this means all "synchronous" and "asynchronous"
3478  * itxs, for all objects in the dataset, will be committed to stable
3479  * storage prior to zil_commit() returning. If "foid" is non-zero, all
3480  * "synchronous" itxs for all objects, but only "asynchronous" itxs
3481  * that correspond to the foid passed in, will be committed to stable
3482  * storage prior to zil_commit() returning.
3483  *
3484  * Generally speaking, when zil_commit() is called, the consumer doesn't
3485  * actually care about _all_ of the uncommitted itxs. Instead, they're
3486  * simply trying to waiting for a specific itx to be committed to disk,
3487  * but the interface(s) for interacting with the ZIL don't allow such
3488  * fine-grained communication. A better interface would allow a consumer
3489  * to create and assign an itx, and then pass a reference to this itx to
3490  * zil_commit(); such that zil_commit() would return as soon as that
3491  * specific itx was committed to disk (instead of waiting for _all_
3492  * itxs to be committed).
3493  *
3494  * When a thread calls zil_commit() a special "commit itx" will be
3495  * generated, along with a corresponding "waiter" for this commit itx.
3496  * zil_commit() will wait on this waiter's CV, such that when the waiter
3497  * is marked done, and signaled, zil_commit() will return.
3498  *
3499  * This commit itx is inserted into the queue of uncommitted itxs. This
3500  * provides an easy mechanism for determining which itxs were in the
3501  * queue prior to zil_commit() having been called, and which itxs were
3502  * added after zil_commit() was called.
3503  *
3504  * The commit itx is special; it doesn't have any on-disk representation.
3505  * When a commit itx is "committed" to an lwb, the waiter associated
3506  * with it is linked onto the lwb's list of waiters. Then, when that lwb
3507  * completes, each waiter on the lwb's list is marked done and signaled
3508  * -- allowing the thread waiting on the waiter to return from zil_commit().
3509  *
3510  * It's important to point out a few critical factors that allow us
3511  * to make use of the commit itxs, commit waiters, per-lwb lists of
3512  * commit waiters, and zio completion callbacks like we're doing:
3513  *
3514  *   1. The list of waiters for each lwb is traversed, and each commit
3515  *      waiter is marked "done" and signaled, in the zio completion
3516  *      callback of the lwb's zio[*].
3517  *
3518  *      * Actually, the waiters are signaled in the zio completion
3519  *        callback of the root zio for the DKIOCFLUSHWRITECACHE commands
3520  *        that are sent to the vdevs upon completion of the lwb zio.
3521  *
3522  *   2. When the itxs are inserted into the ZIL's queue of uncommitted
3523  *      itxs, the order in which they are inserted is preserved[*]; as
3524  *      itxs are added to the queue, they are added to the tail of
3525  *      in-memory linked lists.
3526  *
3527  *      When committing the itxs to lwbs (to be written to disk), they
3528  *      are committed in the same order in which the itxs were added to
3529  *      the uncommitted queue's linked list(s); i.e. the linked list of
3530  *      itxs to commit is traversed from head to tail, and each itx is
3531  *      committed to an lwb in that order.
3532  *
3533  *      * To clarify:
3534  *
3535  *        - the order of "sync" itxs is preserved w.r.t. other
3536  *          "sync" itxs, regardless of the corresponding objects.
3537  *        - the order of "async" itxs is preserved w.r.t. other
3538  *          "async" itxs corresponding to the same object.
3539  *        - the order of "async" itxs is *not* preserved w.r.t. other
3540  *          "async" itxs corresponding to different objects.
3541  *        - the order of "sync" itxs w.r.t. "async" itxs (or vice
3542  *          versa) is *not* preserved, even for itxs that correspond
3543  *          to the same object.
3544  *
3545  *      For more details, see: zil_itx_assign(), zil_async_to_sync(),
3546  *      zil_get_commit_list(), and zil_process_commit_list().
3547  *
3548  *   3. The lwbs represent a linked list of blocks on disk. Thus, any
3549  *      lwb cannot be considered committed to stable storage, until its
3550  *      "previous" lwb is also committed to stable storage. This fact,
3551  *      coupled with the fact described above, means that itxs are
3552  *      committed in (roughly) the order in which they were generated.
3553  *      This is essential because itxs are dependent on prior itxs.
3554  *      Thus, we *must not* deem an itx as being committed to stable
3555  *      storage, until *all* prior itxs have also been committed to
3556  *      stable storage.
3557  *
3558  *      To enforce this ordering of lwb zio's, while still leveraging as
3559  *      much of the underlying storage performance as possible, we rely
3560  *      on two fundamental concepts:
3561  *
3562  *          1. The creation and issuance of lwb zio's is protected by
3563  *             the zilog's "zl_issuer_lock", which ensures only a single
3564  *             thread is creating and/or issuing lwb's at a time
3565  *          2. The "previous" lwb is a child of the "current" lwb
3566  *             (leveraging the zio parent-child dependency graph)
3567  *
3568  *      By relying on this parent-child zio relationship, we can have
3569  *      many lwb zio's concurrently issued to the underlying storage,
3570  *      but the order in which they complete will be the same order in
3571  *      which they were created.
3572  */
3573 void
zil_commit(zilog_t * zilog,uint64_t foid)3574 zil_commit(zilog_t *zilog, uint64_t foid)
3575 {
3576 	/*
3577 	 * We should never attempt to call zil_commit on a snapshot for
3578 	 * a couple of reasons:
3579 	 *
3580 	 * 1. A snapshot may never be modified, thus it cannot have any
3581 	 *    in-flight itxs that would have modified the dataset.
3582 	 *
3583 	 * 2. By design, when zil_commit() is called, a commit itx will
3584 	 *    be assigned to this zilog; as a result, the zilog will be
3585 	 *    dirtied. We must not dirty the zilog of a snapshot; there's
3586 	 *    checks in the code that enforce this invariant, and will
3587 	 *    cause a panic if it's not upheld.
3588 	 */
3589 	ASSERT3B(dmu_objset_is_snapshot(zilog->zl_os), ==, B_FALSE);
3590 
3591 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
3592 		return;
3593 
3594 	if (!spa_writeable(zilog->zl_spa)) {
3595 		/*
3596 		 * If the SPA is not writable, there should never be any
3597 		 * pending itxs waiting to be committed to disk. If that
3598 		 * weren't true, we'd skip writing those itxs out, and
3599 		 * would break the semantics of zil_commit(); thus, we're
3600 		 * verifying that truth before we return to the caller.
3601 		 */
3602 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3603 		ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL);
3604 		for (int i = 0; i < TXG_SIZE; i++)
3605 			ASSERT3P(zilog->zl_itxg[i].itxg_itxs, ==, NULL);
3606 		return;
3607 	}
3608 
3609 	/*
3610 	 * If the ZIL is suspended, we don't want to dirty it by calling
3611 	 * zil_commit_itx_assign() below, nor can we write out
3612 	 * lwbs like would be done in zil_commit_write(). Thus, we
3613 	 * simply rely on txg_wait_synced() to maintain the necessary
3614 	 * semantics, and avoid calling those functions altogether.
3615 	 */
3616 	if (zilog->zl_suspend > 0) {
3617 		txg_wait_synced(zilog->zl_dmu_pool, 0);
3618 		return;
3619 	}
3620 
3621 	zil_commit_impl(zilog, foid);
3622 }
3623 
3624 void
zil_commit_impl(zilog_t * zilog,uint64_t foid)3625 zil_commit_impl(zilog_t *zilog, uint64_t foid)
3626 {
3627 	ZIL_STAT_BUMP(zilog, zil_commit_count);
3628 
3629 	/*
3630 	 * Move the "async" itxs for the specified foid to the "sync"
3631 	 * queues, such that they will be later committed (or skipped)
3632 	 * to an lwb when zil_process_commit_list() is called.
3633 	 *
3634 	 * Since these "async" itxs must be committed prior to this
3635 	 * call to zil_commit returning, we must perform this operation
3636 	 * before we call zil_commit_itx_assign().
3637 	 */
3638 	zil_async_to_sync(zilog, foid);
3639 
3640 	/*
3641 	 * We allocate a new "waiter" structure which will initially be
3642 	 * linked to the commit itx using the itx's "itx_private" field.
3643 	 * Since the commit itx doesn't represent any on-disk state,
3644 	 * when it's committed to an lwb, rather than copying the its
3645 	 * lr_t into the lwb's buffer, the commit itx's "waiter" will be
3646 	 * added to the lwb's list of waiters. Then, when the lwb is
3647 	 * committed to stable storage, each waiter in the lwb's list of
3648 	 * waiters will be marked "done", and signalled.
3649 	 *
3650 	 * We must create the waiter and assign the commit itx prior to
3651 	 * calling zil_commit_writer(), or else our specific commit itx
3652 	 * is not guaranteed to be committed to an lwb prior to calling
3653 	 * zil_commit_waiter().
3654 	 */
3655 	zil_commit_waiter_t *zcw = zil_alloc_commit_waiter();
3656 	zil_commit_itx_assign(zilog, zcw);
3657 
3658 	uint64_t wtxg = zil_commit_writer(zilog, zcw);
3659 	zil_commit_waiter(zilog, zcw);
3660 
3661 	if (zcw->zcw_zio_error != 0) {
3662 		/*
3663 		 * If there was an error writing out the ZIL blocks that
3664 		 * this thread is waiting on, then we fallback to
3665 		 * relying on spa_sync() to write out the data this
3666 		 * thread is waiting on. Obviously this has performance
3667 		 * implications, but the expectation is for this to be
3668 		 * an exceptional case, and shouldn't occur often.
3669 		 */
3670 		DTRACE_PROBE2(zil__commit__io__error,
3671 		    zilog_t *, zilog, zil_commit_waiter_t *, zcw);
3672 		txg_wait_synced(zilog->zl_dmu_pool, 0);
3673 	} else if (wtxg != 0) {
3674 		txg_wait_synced(zilog->zl_dmu_pool, wtxg);
3675 	}
3676 
3677 	zil_free_commit_waiter(zcw);
3678 }
3679 
3680 /*
3681  * Called in syncing context to free committed log blocks and update log header.
3682  */
3683 void
zil_sync(zilog_t * zilog,dmu_tx_t * tx)3684 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
3685 {
3686 	zil_header_t *zh = zil_header_in_syncing_context(zilog);
3687 	uint64_t txg = dmu_tx_get_txg(tx);
3688 	spa_t *spa = zilog->zl_spa;
3689 	uint64_t *replayed_seq = &zilog->zl_replayed_seq[txg & TXG_MASK];
3690 	lwb_t *lwb;
3691 
3692 	/*
3693 	 * We don't zero out zl_destroy_txg, so make sure we don't try
3694 	 * to destroy it twice.
3695 	 */
3696 	if (spa_sync_pass(spa) != 1)
3697 		return;
3698 
3699 	zil_lwb_flush_wait_all(zilog, txg);
3700 
3701 	mutex_enter(&zilog->zl_lock);
3702 
3703 	ASSERT(zilog->zl_stop_sync == 0);
3704 
3705 	if (*replayed_seq != 0) {
3706 		ASSERT(zh->zh_replay_seq < *replayed_seq);
3707 		zh->zh_replay_seq = *replayed_seq;
3708 		*replayed_seq = 0;
3709 	}
3710 
3711 	if (zilog->zl_destroy_txg == txg) {
3712 		blkptr_t blk = zh->zh_log;
3713 		dsl_dataset_t *ds = dmu_objset_ds(zilog->zl_os);
3714 
3715 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3716 
3717 		memset(zh, 0, sizeof (zil_header_t));
3718 		memset(zilog->zl_replayed_seq, 0,
3719 		    sizeof (zilog->zl_replayed_seq));
3720 
3721 		if (zilog->zl_keep_first) {
3722 			/*
3723 			 * If this block was part of log chain that couldn't
3724 			 * be claimed because a device was missing during
3725 			 * zil_claim(), but that device later returns,
3726 			 * then this block could erroneously appear valid.
3727 			 * To guard against this, assign a new GUID to the new
3728 			 * log chain so it doesn't matter what blk points to.
3729 			 */
3730 			zil_init_log_chain(zilog, &blk);
3731 			zh->zh_log = blk;
3732 		} else {
3733 			/*
3734 			 * A destroyed ZIL chain can't contain any TX_SETSAXATTR
3735 			 * records. So, deactivate the feature for this dataset.
3736 			 * We activate it again when we start a new ZIL chain.
3737 			 */
3738 			if (dsl_dataset_feature_is_active(ds,
3739 			    SPA_FEATURE_ZILSAXATTR))
3740 				dsl_dataset_deactivate_feature(ds,
3741 				    SPA_FEATURE_ZILSAXATTR, tx);
3742 		}
3743 	}
3744 
3745 	while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
3746 		zh->zh_log = lwb->lwb_blk;
3747 		if (lwb->lwb_state != LWB_STATE_FLUSH_DONE ||
3748 		    lwb->lwb_alloc_txg > txg || lwb->lwb_max_txg > txg)
3749 			break;
3750 		list_remove(&zilog->zl_lwb_list, lwb);
3751 		if (!BP_IS_HOLE(&lwb->lwb_blk))
3752 			zio_free(spa, txg, &lwb->lwb_blk);
3753 		zil_free_lwb(zilog, lwb);
3754 
3755 		/*
3756 		 * If we don't have anything left in the lwb list then
3757 		 * we've had an allocation failure and we need to zero
3758 		 * out the zil_header blkptr so that we don't end
3759 		 * up freeing the same block twice.
3760 		 */
3761 		if (list_is_empty(&zilog->zl_lwb_list))
3762 			BP_ZERO(&zh->zh_log);
3763 	}
3764 
3765 	mutex_exit(&zilog->zl_lock);
3766 }
3767 
3768 static int
zil_lwb_cons(void * vbuf,void * unused,int kmflag)3769 zil_lwb_cons(void *vbuf, void *unused, int kmflag)
3770 {
3771 	(void) unused, (void) kmflag;
3772 	lwb_t *lwb = vbuf;
3773 	list_create(&lwb->lwb_itxs, sizeof (itx_t), offsetof(itx_t, itx_node));
3774 	list_create(&lwb->lwb_waiters, sizeof (zil_commit_waiter_t),
3775 	    offsetof(zil_commit_waiter_t, zcw_node));
3776 	avl_create(&lwb->lwb_vdev_tree, zil_lwb_vdev_compare,
3777 	    sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
3778 	mutex_init(&lwb->lwb_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
3779 	return (0);
3780 }
3781 
3782 static void
zil_lwb_dest(void * vbuf,void * unused)3783 zil_lwb_dest(void *vbuf, void *unused)
3784 {
3785 	(void) unused;
3786 	lwb_t *lwb = vbuf;
3787 	mutex_destroy(&lwb->lwb_vdev_lock);
3788 	avl_destroy(&lwb->lwb_vdev_tree);
3789 	list_destroy(&lwb->lwb_waiters);
3790 	list_destroy(&lwb->lwb_itxs);
3791 }
3792 
3793 void
zil_init(void)3794 zil_init(void)
3795 {
3796 	zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
3797 	    sizeof (lwb_t), 0, zil_lwb_cons, zil_lwb_dest, NULL, NULL, NULL, 0);
3798 
3799 	zil_zcw_cache = kmem_cache_create("zil_zcw_cache",
3800 	    sizeof (zil_commit_waiter_t), 0, NULL, NULL, NULL, NULL, NULL, 0);
3801 
3802 	zil_sums_init(&zil_sums_global);
3803 	zil_kstats_global = kstat_create("zfs", 0, "zil", "misc",
3804 	    KSTAT_TYPE_NAMED, sizeof (zil_stats) / sizeof (kstat_named_t),
3805 	    KSTAT_FLAG_VIRTUAL);
3806 
3807 	if (zil_kstats_global != NULL) {
3808 		zil_kstats_global->ks_data = &zil_stats;
3809 		zil_kstats_global->ks_update = zil_kstats_global_update;
3810 		zil_kstats_global->ks_private = NULL;
3811 		kstat_install(zil_kstats_global);
3812 	}
3813 }
3814 
3815 void
zil_fini(void)3816 zil_fini(void)
3817 {
3818 	kmem_cache_destroy(zil_zcw_cache);
3819 	kmem_cache_destroy(zil_lwb_cache);
3820 
3821 	if (zil_kstats_global != NULL) {
3822 		kstat_delete(zil_kstats_global);
3823 		zil_kstats_global = NULL;
3824 	}
3825 
3826 	zil_sums_fini(&zil_sums_global);
3827 }
3828 
3829 void
zil_set_sync(zilog_t * zilog,uint64_t sync)3830 zil_set_sync(zilog_t *zilog, uint64_t sync)
3831 {
3832 	zilog->zl_sync = sync;
3833 }
3834 
3835 void
zil_set_logbias(zilog_t * zilog,uint64_t logbias)3836 zil_set_logbias(zilog_t *zilog, uint64_t logbias)
3837 {
3838 	zilog->zl_logbias = logbias;
3839 }
3840 
3841 zilog_t *
zil_alloc(objset_t * os,zil_header_t * zh_phys)3842 zil_alloc(objset_t *os, zil_header_t *zh_phys)
3843 {
3844 	zilog_t *zilog;
3845 
3846 	zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
3847 
3848 	zilog->zl_header = zh_phys;
3849 	zilog->zl_os = os;
3850 	zilog->zl_spa = dmu_objset_spa(os);
3851 	zilog->zl_dmu_pool = dmu_objset_pool(os);
3852 	zilog->zl_destroy_txg = TXG_INITIAL - 1;
3853 	zilog->zl_logbias = dmu_objset_logbias(os);
3854 	zilog->zl_sync = dmu_objset_syncprop(os);
3855 	zilog->zl_dirty_max_txg = 0;
3856 	zilog->zl_last_lwb_opened = NULL;
3857 	zilog->zl_last_lwb_latency = 0;
3858 	zilog->zl_max_block_size = MIN(MAX(P2ALIGN_TYPED(zil_maxblocksize,
3859 	    ZIL_MIN_BLKSZ, uint64_t), ZIL_MIN_BLKSZ),
3860 	    spa_maxblocksize(dmu_objset_spa(os)));
3861 
3862 	mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
3863 	mutex_init(&zilog->zl_issuer_lock, NULL, MUTEX_DEFAULT, NULL);
3864 	mutex_init(&zilog->zl_lwb_io_lock, NULL, MUTEX_DEFAULT, NULL);
3865 
3866 	for (int i = 0; i < TXG_SIZE; i++) {
3867 		mutex_init(&zilog->zl_itxg[i].itxg_lock, NULL,
3868 		    MUTEX_DEFAULT, NULL);
3869 	}
3870 
3871 	list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
3872 	    offsetof(lwb_t, lwb_node));
3873 
3874 	list_create(&zilog->zl_itx_commit_list, sizeof (itx_t),
3875 	    offsetof(itx_t, itx_node));
3876 
3877 	cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
3878 	cv_init(&zilog->zl_lwb_io_cv, NULL, CV_DEFAULT, NULL);
3879 
3880 	for (int i = 0; i < ZIL_BURSTS; i++) {
3881 		zilog->zl_prev_opt[i] = zilog->zl_max_block_size -
3882 		    sizeof (zil_chain_t);
3883 	}
3884 
3885 	return (zilog);
3886 }
3887 
3888 void
zil_free(zilog_t * zilog)3889 zil_free(zilog_t *zilog)
3890 {
3891 	int i;
3892 
3893 	zilog->zl_stop_sync = 1;
3894 
3895 	ASSERT0(zilog->zl_suspend);
3896 	ASSERT0(zilog->zl_suspending);
3897 
3898 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
3899 	list_destroy(&zilog->zl_lwb_list);
3900 
3901 	ASSERT(list_is_empty(&zilog->zl_itx_commit_list));
3902 	list_destroy(&zilog->zl_itx_commit_list);
3903 
3904 	for (i = 0; i < TXG_SIZE; i++) {
3905 		/*
3906 		 * It's possible for an itx to be generated that doesn't dirty
3907 		 * a txg (e.g. ztest TX_TRUNCATE). So there's no zil_clean()
3908 		 * callback to remove the entry. We remove those here.
3909 		 *
3910 		 * Also free up the ziltest itxs.
3911 		 */
3912 		if (zilog->zl_itxg[i].itxg_itxs)
3913 			zil_itxg_clean(zilog->zl_itxg[i].itxg_itxs);
3914 		mutex_destroy(&zilog->zl_itxg[i].itxg_lock);
3915 	}
3916 
3917 	mutex_destroy(&zilog->zl_issuer_lock);
3918 	mutex_destroy(&zilog->zl_lock);
3919 	mutex_destroy(&zilog->zl_lwb_io_lock);
3920 
3921 	cv_destroy(&zilog->zl_cv_suspend);
3922 	cv_destroy(&zilog->zl_lwb_io_cv);
3923 
3924 	kmem_free(zilog, sizeof (zilog_t));
3925 }
3926 
3927 /*
3928  * Open an intent log.
3929  */
3930 zilog_t *
zil_open(objset_t * os,zil_get_data_t * get_data,zil_sums_t * zil_sums)3931 zil_open(objset_t *os, zil_get_data_t *get_data, zil_sums_t *zil_sums)
3932 {
3933 	zilog_t *zilog = dmu_objset_zil(os);
3934 
3935 	ASSERT3P(zilog->zl_get_data, ==, NULL);
3936 	ASSERT3P(zilog->zl_last_lwb_opened, ==, NULL);
3937 	ASSERT(list_is_empty(&zilog->zl_lwb_list));
3938 
3939 	zilog->zl_get_data = get_data;
3940 	zilog->zl_sums = zil_sums;
3941 
3942 	return (zilog);
3943 }
3944 
3945 /*
3946  * Close an intent log.
3947  */
3948 void
zil_close(zilog_t * zilog)3949 zil_close(zilog_t *zilog)
3950 {
3951 	lwb_t *lwb;
3952 	uint64_t txg;
3953 
3954 	if (!dmu_objset_is_snapshot(zilog->zl_os)) {
3955 		zil_commit(zilog, 0);
3956 	} else {
3957 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
3958 		ASSERT0(zilog->zl_dirty_max_txg);
3959 		ASSERT3B(zilog_is_dirty(zilog), ==, B_FALSE);
3960 	}
3961 
3962 	mutex_enter(&zilog->zl_lock);
3963 	txg = zilog->zl_dirty_max_txg;
3964 	lwb = list_tail(&zilog->zl_lwb_list);
3965 	if (lwb != NULL) {
3966 		txg = MAX(txg, lwb->lwb_alloc_txg);
3967 		txg = MAX(txg, lwb->lwb_max_txg);
3968 	}
3969 	mutex_exit(&zilog->zl_lock);
3970 
3971 	/*
3972 	 * zl_lwb_max_issued_txg may be larger than lwb_max_txg. It depends
3973 	 * on the time when the dmu_tx transaction is assigned in
3974 	 * zil_lwb_write_issue().
3975 	 */
3976 	mutex_enter(&zilog->zl_lwb_io_lock);
3977 	txg = MAX(zilog->zl_lwb_max_issued_txg, txg);
3978 	mutex_exit(&zilog->zl_lwb_io_lock);
3979 
3980 	/*
3981 	 * We need to use txg_wait_synced() to wait until that txg is synced.
3982 	 * zil_sync() will guarantee all lwbs up to that txg have been
3983 	 * written out, flushed, and cleaned.
3984 	 */
3985 	if (txg != 0)
3986 		txg_wait_synced(zilog->zl_dmu_pool, txg);
3987 
3988 	if (zilog_is_dirty(zilog))
3989 		zfs_dbgmsg("zil (%px) is dirty, txg %llu", zilog,
3990 		    (u_longlong_t)txg);
3991 	if (txg < spa_freeze_txg(zilog->zl_spa))
3992 		VERIFY(!zilog_is_dirty(zilog));
3993 
3994 	zilog->zl_get_data = NULL;
3995 
3996 	/*
3997 	 * We should have only one lwb left on the list; remove it now.
3998 	 */
3999 	mutex_enter(&zilog->zl_lock);
4000 	lwb = list_remove_head(&zilog->zl_lwb_list);
4001 	if (lwb != NULL) {
4002 		ASSERT(list_is_empty(&zilog->zl_lwb_list));
4003 		ASSERT3S(lwb->lwb_state, ==, LWB_STATE_NEW);
4004 		zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
4005 		zil_free_lwb(zilog, lwb);
4006 	}
4007 	mutex_exit(&zilog->zl_lock);
4008 }
4009 
4010 static const char *suspend_tag = "zil suspending";
4011 
4012 /*
4013  * Suspend an intent log.  While in suspended mode, we still honor
4014  * synchronous semantics, but we rely on txg_wait_synced() to do it.
4015  * On old version pools, we suspend the log briefly when taking a
4016  * snapshot so that it will have an empty intent log.
4017  *
4018  * Long holds are not really intended to be used the way we do here --
4019  * held for such a short time.  A concurrent caller of dsl_dataset_long_held()
4020  * could fail.  Therefore we take pains to only put a long hold if it is
4021  * actually necessary.  Fortunately, it will only be necessary if the
4022  * objset is currently mounted (or the ZVOL equivalent).  In that case it
4023  * will already have a long hold, so we are not really making things any worse.
4024  *
4025  * Ideally, we would locate the existing long-holder (i.e. the zfsvfs_t or
4026  * zvol_state_t), and use their mechanism to prevent their hold from being
4027  * dropped (e.g. VFS_HOLD()).  However, that would be even more pain for
4028  * very little gain.
4029  *
4030  * if cookiep == NULL, this does both the suspend & resume.
4031  * Otherwise, it returns with the dataset "long held", and the cookie
4032  * should be passed into zil_resume().
4033  */
4034 int
zil_suspend(const char * osname,void ** cookiep)4035 zil_suspend(const char *osname, void **cookiep)
4036 {
4037 	objset_t *os;
4038 	zilog_t *zilog;
4039 	const zil_header_t *zh;
4040 	int error;
4041 
4042 	error = dmu_objset_hold(osname, suspend_tag, &os);
4043 	if (error != 0)
4044 		return (error);
4045 	zilog = dmu_objset_zil(os);
4046 
4047 	mutex_enter(&zilog->zl_lock);
4048 	zh = zilog->zl_header;
4049 
4050 	if (zh->zh_flags & ZIL_REPLAY_NEEDED) {		/* unplayed log */
4051 		mutex_exit(&zilog->zl_lock);
4052 		dmu_objset_rele(os, suspend_tag);
4053 		return (SET_ERROR(EBUSY));
4054 	}
4055 
4056 	/*
4057 	 * Don't put a long hold in the cases where we can avoid it.  This
4058 	 * is when there is no cookie so we are doing a suspend & resume
4059 	 * (i.e. called from zil_vdev_offline()), and there's nothing to do
4060 	 * for the suspend because it's already suspended, or there's no ZIL.
4061 	 */
4062 	if (cookiep == NULL && !zilog->zl_suspending &&
4063 	    (zilog->zl_suspend > 0 || BP_IS_HOLE(&zh->zh_log))) {
4064 		mutex_exit(&zilog->zl_lock);
4065 		dmu_objset_rele(os, suspend_tag);
4066 		return (0);
4067 	}
4068 
4069 	dsl_dataset_long_hold(dmu_objset_ds(os), suspend_tag);
4070 	dsl_pool_rele(dmu_objset_pool(os), suspend_tag);
4071 
4072 	zilog->zl_suspend++;
4073 
4074 	if (zilog->zl_suspend > 1) {
4075 		/*
4076 		 * Someone else is already suspending it.
4077 		 * Just wait for them to finish.
4078 		 */
4079 
4080 		while (zilog->zl_suspending)
4081 			cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
4082 		mutex_exit(&zilog->zl_lock);
4083 
4084 		if (cookiep == NULL)
4085 			zil_resume(os);
4086 		else
4087 			*cookiep = os;
4088 		return (0);
4089 	}
4090 
4091 	/*
4092 	 * If there is no pointer to an on-disk block, this ZIL must not
4093 	 * be active (e.g. filesystem not mounted), so there's nothing
4094 	 * to clean up.
4095 	 */
4096 	if (BP_IS_HOLE(&zh->zh_log)) {
4097 		ASSERT(cookiep != NULL); /* fast path already handled */
4098 
4099 		*cookiep = os;
4100 		mutex_exit(&zilog->zl_lock);
4101 		return (0);
4102 	}
4103 
4104 	/*
4105 	 * The ZIL has work to do. Ensure that the associated encryption
4106 	 * key will remain mapped while we are committing the log by
4107 	 * grabbing a reference to it. If the key isn't loaded we have no
4108 	 * choice but to return an error until the wrapping key is loaded.
4109 	 */
4110 	if (os->os_encrypted &&
4111 	    dsl_dataset_create_key_mapping(dmu_objset_ds(os)) != 0) {
4112 		zilog->zl_suspend--;
4113 		mutex_exit(&zilog->zl_lock);
4114 		dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag);
4115 		dsl_dataset_rele(dmu_objset_ds(os), suspend_tag);
4116 		return (SET_ERROR(EACCES));
4117 	}
4118 
4119 	zilog->zl_suspending = B_TRUE;
4120 	mutex_exit(&zilog->zl_lock);
4121 
4122 	/*
4123 	 * We need to use zil_commit_impl to ensure we wait for all
4124 	 * LWB_STATE_OPENED, _CLOSED and _READY lwbs to be committed
4125 	 * to disk before proceeding. If we used zil_commit instead, it
4126 	 * would just call txg_wait_synced(), because zl_suspend is set.
4127 	 * txg_wait_synced() doesn't wait for these lwb's to be
4128 	 * LWB_STATE_FLUSH_DONE before returning.
4129 	 */
4130 	zil_commit_impl(zilog, 0);
4131 
4132 	/*
4133 	 * Now that we've ensured all lwb's are LWB_STATE_FLUSH_DONE, we
4134 	 * use txg_wait_synced() to ensure the data from the zilog has
4135 	 * migrated to the main pool before calling zil_destroy().
4136 	 */
4137 	txg_wait_synced(zilog->zl_dmu_pool, 0);
4138 
4139 	zil_destroy(zilog, B_FALSE);
4140 
4141 	mutex_enter(&zilog->zl_lock);
4142 	zilog->zl_suspending = B_FALSE;
4143 	cv_broadcast(&zilog->zl_cv_suspend);
4144 	mutex_exit(&zilog->zl_lock);
4145 
4146 	if (os->os_encrypted)
4147 		dsl_dataset_remove_key_mapping(dmu_objset_ds(os));
4148 
4149 	if (cookiep == NULL)
4150 		zil_resume(os);
4151 	else
4152 		*cookiep = os;
4153 	return (0);
4154 }
4155 
4156 void
zil_resume(void * cookie)4157 zil_resume(void *cookie)
4158 {
4159 	objset_t *os = cookie;
4160 	zilog_t *zilog = dmu_objset_zil(os);
4161 
4162 	mutex_enter(&zilog->zl_lock);
4163 	ASSERT(zilog->zl_suspend != 0);
4164 	zilog->zl_suspend--;
4165 	mutex_exit(&zilog->zl_lock);
4166 	dsl_dataset_long_rele(dmu_objset_ds(os), suspend_tag);
4167 	dsl_dataset_rele(dmu_objset_ds(os), suspend_tag);
4168 }
4169 
4170 typedef struct zil_replay_arg {
4171 	zil_replay_func_t *const *zr_replay;
4172 	void		*zr_arg;
4173 	boolean_t	zr_byteswap;
4174 	char		*zr_lr;
4175 } zil_replay_arg_t;
4176 
4177 static int
zil_replay_error(zilog_t * zilog,const lr_t * lr,int error)4178 zil_replay_error(zilog_t *zilog, const lr_t *lr, int error)
4179 {
4180 	char name[ZFS_MAX_DATASET_NAME_LEN];
4181 
4182 	zilog->zl_replaying_seq--;	/* didn't actually replay this one */
4183 
4184 	dmu_objset_name(zilog->zl_os, name);
4185 
4186 	cmn_err(CE_WARN, "ZFS replay transaction error %d, "
4187 	    "dataset %s, seq 0x%llx, txtype %llu %s\n", error, name,
4188 	    (u_longlong_t)lr->lrc_seq,
4189 	    (u_longlong_t)(lr->lrc_txtype & ~TX_CI),
4190 	    (lr->lrc_txtype & TX_CI) ? "CI" : "");
4191 
4192 	return (error);
4193 }
4194 
4195 static int
zil_replay_log_record(zilog_t * zilog,const lr_t * lr,void * zra,uint64_t claim_txg)4196 zil_replay_log_record(zilog_t *zilog, const lr_t *lr, void *zra,
4197     uint64_t claim_txg)
4198 {
4199 	zil_replay_arg_t *zr = zra;
4200 	const zil_header_t *zh = zilog->zl_header;
4201 	uint64_t reclen = lr->lrc_reclen;
4202 	uint64_t txtype = lr->lrc_txtype;
4203 	int error = 0;
4204 
4205 	zilog->zl_replaying_seq = lr->lrc_seq;
4206 
4207 	if (lr->lrc_seq <= zh->zh_replay_seq)	/* already replayed */
4208 		return (0);
4209 
4210 	if (lr->lrc_txg < claim_txg)		/* already committed */
4211 		return (0);
4212 
4213 	/* Strip case-insensitive bit, still present in log record */
4214 	txtype &= ~TX_CI;
4215 
4216 	if (txtype == 0 || txtype >= TX_MAX_TYPE)
4217 		return (zil_replay_error(zilog, lr, EINVAL));
4218 
4219 	/*
4220 	 * If this record type can be logged out of order, the object
4221 	 * (lr_foid) may no longer exist.  That's legitimate, not an error.
4222 	 */
4223 	if (TX_OOO(txtype)) {
4224 		error = dmu_object_info(zilog->zl_os,
4225 		    LR_FOID_GET_OBJ(((lr_ooo_t *)lr)->lr_foid), NULL);
4226 		if (error == ENOENT || error == EEXIST)
4227 			return (0);
4228 	}
4229 
4230 	/*
4231 	 * Make a copy of the data so we can revise and extend it.
4232 	 */
4233 	memcpy(zr->zr_lr, lr, reclen);
4234 
4235 	/*
4236 	 * If this is a TX_WRITE with a blkptr, suck in the data.
4237 	 */
4238 	if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
4239 		error = zil_read_log_data(zilog, (lr_write_t *)lr,
4240 		    zr->zr_lr + reclen);
4241 		if (error != 0)
4242 			return (zil_replay_error(zilog, lr, error));
4243 	}
4244 
4245 	/*
4246 	 * The log block containing this lr may have been byteswapped
4247 	 * so that we can easily examine common fields like lrc_txtype.
4248 	 * However, the log is a mix of different record types, and only the
4249 	 * replay vectors know how to byteswap their records.  Therefore, if
4250 	 * the lr was byteswapped, undo it before invoking the replay vector.
4251 	 */
4252 	if (zr->zr_byteswap)
4253 		byteswap_uint64_array(zr->zr_lr, reclen);
4254 
4255 	/*
4256 	 * We must now do two things atomically: replay this log record,
4257 	 * and update the log header sequence number to reflect the fact that
4258 	 * we did so. At the end of each replay function the sequence number
4259 	 * is updated if we are in replay mode.
4260 	 */
4261 	error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, zr->zr_byteswap);
4262 	if (error != 0) {
4263 		/*
4264 		 * The DMU's dnode layer doesn't see removes until the txg
4265 		 * commits, so a subsequent claim can spuriously fail with
4266 		 * EEXIST. So if we receive any error we try syncing out
4267 		 * any removes then retry the transaction.  Note that we
4268 		 * specify B_FALSE for byteswap now, so we don't do it twice.
4269 		 */
4270 		txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
4271 		error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lr, B_FALSE);
4272 		if (error != 0)
4273 			return (zil_replay_error(zilog, lr, error));
4274 	}
4275 	return (0);
4276 }
4277 
4278 static int
zil_incr_blks(zilog_t * zilog,const blkptr_t * bp,void * arg,uint64_t claim_txg)4279 zil_incr_blks(zilog_t *zilog, const blkptr_t *bp, void *arg, uint64_t claim_txg)
4280 {
4281 	(void) bp, (void) arg, (void) claim_txg;
4282 
4283 	zilog->zl_replay_blks++;
4284 
4285 	return (0);
4286 }
4287 
4288 /*
4289  * If this dataset has a non-empty intent log, replay it and destroy it.
4290  * Return B_TRUE if there were any entries to replay.
4291  */
4292 boolean_t
zil_replay(objset_t * os,void * arg,zil_replay_func_t * const replay_func[TX_MAX_TYPE])4293 zil_replay(objset_t *os, void *arg,
4294     zil_replay_func_t *const replay_func[TX_MAX_TYPE])
4295 {
4296 	zilog_t *zilog = dmu_objset_zil(os);
4297 	const zil_header_t *zh = zilog->zl_header;
4298 	zil_replay_arg_t zr;
4299 
4300 	if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
4301 		return (zil_destroy(zilog, B_TRUE));
4302 	}
4303 
4304 	zr.zr_replay = replay_func;
4305 	zr.zr_arg = arg;
4306 	zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
4307 	zr.zr_lr = vmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
4308 
4309 	/*
4310 	 * Wait for in-progress removes to sync before starting replay.
4311 	 */
4312 	txg_wait_synced(zilog->zl_dmu_pool, 0);
4313 
4314 	zilog->zl_replay = B_TRUE;
4315 	zilog->zl_replay_time = ddi_get_lbolt();
4316 	ASSERT(zilog->zl_replay_blks == 0);
4317 	(void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
4318 	    zh->zh_claim_txg, B_TRUE);
4319 	vmem_free(zr.zr_lr, 2 * SPA_MAXBLOCKSIZE);
4320 
4321 	zil_destroy(zilog, B_FALSE);
4322 	txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
4323 	zilog->zl_replay = B_FALSE;
4324 
4325 	return (B_TRUE);
4326 }
4327 
4328 boolean_t
zil_replaying(zilog_t * zilog,dmu_tx_t * tx)4329 zil_replaying(zilog_t *zilog, dmu_tx_t *tx)
4330 {
4331 	if (zilog->zl_sync == ZFS_SYNC_DISABLED)
4332 		return (B_TRUE);
4333 
4334 	if (zilog->zl_replay) {
4335 		dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
4336 		zilog->zl_replayed_seq[dmu_tx_get_txg(tx) & TXG_MASK] =
4337 		    zilog->zl_replaying_seq;
4338 		return (B_TRUE);
4339 	}
4340 
4341 	return (B_FALSE);
4342 }
4343 
4344 int
zil_reset(const char * osname,void * arg)4345 zil_reset(const char *osname, void *arg)
4346 {
4347 	(void) arg;
4348 
4349 	int error = zil_suspend(osname, NULL);
4350 	/* EACCES means crypto key not loaded */
4351 	if ((error == EACCES) || (error == EBUSY))
4352 		return (SET_ERROR(error));
4353 	if (error != 0)
4354 		return (SET_ERROR(EEXIST));
4355 	return (0);
4356 }
4357 
4358 EXPORT_SYMBOL(zil_alloc);
4359 EXPORT_SYMBOL(zil_free);
4360 EXPORT_SYMBOL(zil_open);
4361 EXPORT_SYMBOL(zil_close);
4362 EXPORT_SYMBOL(zil_replay);
4363 EXPORT_SYMBOL(zil_replaying);
4364 EXPORT_SYMBOL(zil_destroy);
4365 EXPORT_SYMBOL(zil_destroy_sync);
4366 EXPORT_SYMBOL(zil_itx_create);
4367 EXPORT_SYMBOL(zil_itx_destroy);
4368 EXPORT_SYMBOL(zil_itx_assign);
4369 EXPORT_SYMBOL(zil_commit);
4370 EXPORT_SYMBOL(zil_claim);
4371 EXPORT_SYMBOL(zil_check_log_chain);
4372 EXPORT_SYMBOL(zil_sync);
4373 EXPORT_SYMBOL(zil_clean);
4374 EXPORT_SYMBOL(zil_suspend);
4375 EXPORT_SYMBOL(zil_resume);
4376 EXPORT_SYMBOL(zil_lwb_add_block);
4377 EXPORT_SYMBOL(zil_bp_tree_add);
4378 EXPORT_SYMBOL(zil_set_sync);
4379 EXPORT_SYMBOL(zil_set_logbias);
4380 EXPORT_SYMBOL(zil_sums_init);
4381 EXPORT_SYMBOL(zil_sums_fini);
4382 EXPORT_SYMBOL(zil_kstat_values_update);
4383 
4384 ZFS_MODULE_PARAM(zfs, zfs_, commit_timeout_pct, UINT, ZMOD_RW,
4385 	"ZIL block open timeout percentage");
4386 
4387 ZFS_MODULE_PARAM(zfs_zil, zil_, replay_disable, INT, ZMOD_RW,
4388 	"Disable intent logging replay");
4389 
4390 ZFS_MODULE_PARAM(zfs_zil, zil_, nocacheflush, INT, ZMOD_RW,
4391 	"Disable ZIL cache flushes");
4392 
4393 ZFS_MODULE_PARAM(zfs_zil, zil_, slog_bulk, U64, ZMOD_RW,
4394 	"Limit in bytes slog sync writes per commit");
4395 
4396 ZFS_MODULE_PARAM(zfs_zil, zil_, maxblocksize, UINT, ZMOD_RW,
4397 	"Limit in bytes of ZIL log block size");
4398 
4399 ZFS_MODULE_PARAM(zfs_zil, zil_, maxcopied, UINT, ZMOD_RW,
4400 	"Limit in bytes WR_COPIED size");
4401