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