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