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