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