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