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