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