]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zil.c
MFC r209962, r211970-r211972, r212050, r212605, r212611
[FreeBSD/stable/8.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 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25
26 #include <sys/zfs_context.h>
27 #include <sys/spa.h>
28 #include <sys/dmu.h>
29 #include <sys/zap.h>
30 #include <sys/arc.h>
31 #include <sys/stat.h>
32 #include <sys/resource.h>
33 #include <sys/zil.h>
34 #include <sys/zil_impl.h>
35 #include <sys/dsl_dataset.h>
36 #include <sys/vdev.h>
37 #include <sys/dmu_tx.h>
38
39 /*
40  * The zfs intent log (ZIL) saves transaction records of system calls
41  * that change the file system in memory with enough information
42  * to be able to replay them. These are stored in memory until
43  * either the DMU transaction group (txg) commits them to the stable pool
44  * and they can be discarded, or they are flushed to the stable log
45  * (also in the pool) due to a fsync, O_DSYNC or other synchronous
46  * requirement. In the event of a panic or power fail then those log
47  * records (transactions) are replayed.
48  *
49  * There is one ZIL per file system. Its on-disk (pool) format consists
50  * of 3 parts:
51  *
52  *      - ZIL header
53  *      - ZIL blocks
54  *      - ZIL records
55  *
56  * A log record holds a system call transaction. Log blocks can
57  * hold many log records and the blocks are chained together.
58  * Each ZIL block contains a block pointer (blkptr_t) to the next
59  * ZIL block in the chain. The ZIL header points to the first
60  * block in the chain. Note there is not a fixed place in the pool
61  * to hold blocks. They are dynamically allocated and freed as
62  * needed from the blocks available. Figure X shows the ZIL structure:
63  */
64
65 /*
66  * This global ZIL switch affects all pools
67  */
68 int zil_disable = 0;    /* disable intent logging */
69 SYSCTL_DECL(_vfs_zfs);
70 TUNABLE_INT("vfs.zfs.zil_disable", &zil_disable);
71 SYSCTL_INT(_vfs_zfs, OID_AUTO, zil_disable, CTLFLAG_RW, &zil_disable, 0,
72     "Disable ZFS Intent Log (ZIL)");
73
74 /*
75  * Tunable parameter for debugging or performance analysis.  Setting
76  * zfs_nocacheflush will cause corruption on power loss if a volatile
77  * out-of-order write cache is enabled.
78  */
79 boolean_t zfs_nocacheflush = B_FALSE;
80 TUNABLE_INT("vfs.zfs.cache_flush_disable", &zfs_nocacheflush);
81 SYSCTL_INT(_vfs_zfs, OID_AUTO, cache_flush_disable, CTLFLAG_RDTUN,
82     &zfs_nocacheflush, 0, "Disable cache flush");
83
84 static kmem_cache_t *zil_lwb_cache;
85
86 static int
87 zil_dva_compare(const void *x1, const void *x2)
88 {
89         const dva_t *dva1 = x1;
90         const dva_t *dva2 = x2;
91
92         if (DVA_GET_VDEV(dva1) < DVA_GET_VDEV(dva2))
93                 return (-1);
94         if (DVA_GET_VDEV(dva1) > DVA_GET_VDEV(dva2))
95                 return (1);
96
97         if (DVA_GET_OFFSET(dva1) < DVA_GET_OFFSET(dva2))
98                 return (-1);
99         if (DVA_GET_OFFSET(dva1) > DVA_GET_OFFSET(dva2))
100                 return (1);
101
102         return (0);
103 }
104
105 static void
106 zil_dva_tree_init(avl_tree_t *t)
107 {
108         avl_create(t, zil_dva_compare, sizeof (zil_dva_node_t),
109             offsetof(zil_dva_node_t, zn_node));
110 }
111
112 static void
113 zil_dva_tree_fini(avl_tree_t *t)
114 {
115         zil_dva_node_t *zn;
116         void *cookie = NULL;
117
118         while ((zn = avl_destroy_nodes(t, &cookie)) != NULL)
119                 kmem_free(zn, sizeof (zil_dva_node_t));
120
121         avl_destroy(t);
122 }
123
124 static int
125 zil_dva_tree_add(avl_tree_t *t, dva_t *dva)
126 {
127         zil_dva_node_t *zn;
128         avl_index_t where;
129
130         if (avl_find(t, dva, &where) != NULL)
131                 return (EEXIST);
132
133         zn = kmem_alloc(sizeof (zil_dva_node_t), KM_SLEEP);
134         zn->zn_dva = *dva;
135         avl_insert(t, zn, where);
136
137         return (0);
138 }
139
140 static zil_header_t *
141 zil_header_in_syncing_context(zilog_t *zilog)
142 {
143         return ((zil_header_t *)zilog->zl_header);
144 }
145
146 static void
147 zil_init_log_chain(zilog_t *zilog, blkptr_t *bp)
148 {
149         zio_cksum_t *zc = &bp->blk_cksum;
150
151         zc->zc_word[ZIL_ZC_GUID_0] = spa_get_random(-1ULL);
152         zc->zc_word[ZIL_ZC_GUID_1] = spa_get_random(-1ULL);
153         zc->zc_word[ZIL_ZC_OBJSET] = dmu_objset_id(zilog->zl_os);
154         zc->zc_word[ZIL_ZC_SEQ] = 1ULL;
155 }
156
157 /*
158  * Read a log block, make sure it's valid, and byteswap it if necessary.
159  */
160 static int
161 zil_read_log_block(zilog_t *zilog, const blkptr_t *bp, arc_buf_t **abufpp)
162 {
163         blkptr_t blk = *bp;
164         zbookmark_t zb;
165         uint32_t aflags = ARC_WAIT;
166         int error;
167
168         zb.zb_objset = bp->blk_cksum.zc_word[ZIL_ZC_OBJSET];
169         zb.zb_object = 0;
170         zb.zb_level = -1;
171         zb.zb_blkid = bp->blk_cksum.zc_word[ZIL_ZC_SEQ];
172
173         *abufpp = NULL;
174
175         /*
176          * We shouldn't be doing any scrubbing while we're doing log
177          * replay, it's OK to not lock.
178          */
179         error = arc_read_nolock(NULL, zilog->zl_spa, &blk,
180             arc_getbuf_func, abufpp, ZIO_PRIORITY_SYNC_READ, ZIO_FLAG_CANFAIL |
181             ZIO_FLAG_SPECULATIVE | ZIO_FLAG_SCRUB, &aflags, &zb);
182
183         if (error == 0) {
184                 char *data = (*abufpp)->b_data;
185                 uint64_t blksz = BP_GET_LSIZE(bp);
186                 zil_trailer_t *ztp = (zil_trailer_t *)(data + blksz) - 1;
187                 zio_cksum_t cksum = bp->blk_cksum;
188
189                 /*
190                  * Validate the checksummed log block.
191                  *
192                  * Sequence numbers should be... sequential.  The checksum
193                  * verifier for the next block should be bp's checksum plus 1.
194                  *
195                  * Also check the log chain linkage and size used.
196                  */
197                 cksum.zc_word[ZIL_ZC_SEQ]++;
198
199                 if (bcmp(&cksum, &ztp->zit_next_blk.blk_cksum,
200                     sizeof (cksum)) || BP_IS_HOLE(&ztp->zit_next_blk) ||
201                     (ztp->zit_nused > (blksz - sizeof (zil_trailer_t)))) {
202                         error = ECKSUM;
203                 }
204
205                 if (error) {
206                         VERIFY(arc_buf_remove_ref(*abufpp, abufpp) == 1);
207                         *abufpp = NULL;
208                 }
209         }
210
211         dprintf("error %d on %llu:%llu\n", error, zb.zb_objset, zb.zb_blkid);
212
213         return (error);
214 }
215
216 /*
217  * Parse the intent log, and call parse_func for each valid record within.
218  * Return the highest sequence number.
219  */
220 uint64_t
221 zil_parse(zilog_t *zilog, zil_parse_blk_func_t *parse_blk_func,
222     zil_parse_lr_func_t *parse_lr_func, void *arg, uint64_t txg)
223 {
224         const zil_header_t *zh = zilog->zl_header;
225         uint64_t claim_seq = zh->zh_claim_seq;
226         uint64_t seq = 0;
227         uint64_t max_seq = 0;
228         blkptr_t blk = zh->zh_log;
229         arc_buf_t *abuf;
230         char *lrbuf, *lrp;
231         zil_trailer_t *ztp;
232         int reclen, error;
233
234         if (BP_IS_HOLE(&blk))
235                 return (max_seq);
236
237         /*
238          * Starting at the block pointed to by zh_log we read the log chain.
239          * For each block in the chain we strongly check that block to
240          * ensure its validity.  We stop when an invalid block is found.
241          * For each block pointer in the chain we call parse_blk_func().
242          * For each record in each valid block we call parse_lr_func().
243          * If the log has been claimed, stop if we encounter a sequence
244          * number greater than the highest claimed sequence number.
245          */
246         zil_dva_tree_init(&zilog->zl_dva_tree);
247         for (;;) {
248                 seq = blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
249
250                 if (claim_seq != 0 && seq > claim_seq)
251                         break;
252
253                 ASSERT(max_seq < seq);
254                 max_seq = seq;
255
256                 error = zil_read_log_block(zilog, &blk, &abuf);
257
258                 if (parse_blk_func != NULL)
259                         parse_blk_func(zilog, &blk, arg, txg);
260
261                 if (error)
262                         break;
263
264                 lrbuf = abuf->b_data;
265                 ztp = (zil_trailer_t *)(lrbuf + BP_GET_LSIZE(&blk)) - 1;
266                 blk = ztp->zit_next_blk;
267
268                 if (parse_lr_func == NULL) {
269                         VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
270                         continue;
271                 }
272
273                 for (lrp = lrbuf; lrp < lrbuf + ztp->zit_nused; lrp += reclen) {
274                         lr_t *lr = (lr_t *)lrp;
275                         reclen = lr->lrc_reclen;
276                         ASSERT3U(reclen, >=, sizeof (lr_t));
277                         parse_lr_func(zilog, lr, arg, txg);
278                 }
279                 VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
280         }
281         zil_dva_tree_fini(&zilog->zl_dva_tree);
282
283         return (max_seq);
284 }
285
286 /* ARGSUSED */
287 static void
288 zil_claim_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t first_txg)
289 {
290         spa_t *spa = zilog->zl_spa;
291         int err;
292
293         /*
294          * Claim log block if not already committed and not already claimed.
295          */
296         if (bp->blk_birth >= first_txg &&
297             zil_dva_tree_add(&zilog->zl_dva_tree, BP_IDENTITY(bp)) == 0) {
298                 err = zio_wait(zio_claim(NULL, spa, first_txg, bp, NULL, NULL,
299                     ZIO_FLAG_MUSTSUCCEED));
300                 ASSERT(err == 0);
301         }
302 }
303
304 static void
305 zil_claim_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t first_txg)
306 {
307         if (lrc->lrc_txtype == TX_WRITE) {
308                 lr_write_t *lr = (lr_write_t *)lrc;
309                 zil_claim_log_block(zilog, &lr->lr_blkptr, tx, first_txg);
310         }
311 }
312
313 /* ARGSUSED */
314 static void
315 zil_free_log_block(zilog_t *zilog, blkptr_t *bp, void *tx, uint64_t claim_txg)
316 {
317         zio_free_blk(zilog->zl_spa, bp, dmu_tx_get_txg(tx));
318 }
319
320 static void
321 zil_free_log_record(zilog_t *zilog, lr_t *lrc, void *tx, uint64_t claim_txg)
322 {
323         /*
324          * If we previously claimed it, we need to free it.
325          */
326         if (claim_txg != 0 && lrc->lrc_txtype == TX_WRITE) {
327                 lr_write_t *lr = (lr_write_t *)lrc;
328                 blkptr_t *bp = &lr->lr_blkptr;
329                 if (bp->blk_birth >= claim_txg &&
330                     !zil_dva_tree_add(&zilog->zl_dva_tree, BP_IDENTITY(bp))) {
331                         (void) arc_free(NULL, zilog->zl_spa,
332                             dmu_tx_get_txg(tx), bp, NULL, NULL, ARC_WAIT);
333                 }
334         }
335 }
336
337 /*
338  * Create an on-disk intent log.
339  */
340 static void
341 zil_create(zilog_t *zilog)
342 {
343         const zil_header_t *zh = zilog->zl_header;
344         lwb_t *lwb;
345         uint64_t txg = 0;
346         dmu_tx_t *tx = NULL;
347         blkptr_t blk;
348         int error = 0;
349
350         /*
351          * Wait for any previous destroy to complete.
352          */
353         txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
354
355         ASSERT(zh->zh_claim_txg == 0);
356         ASSERT(zh->zh_replay_seq == 0);
357
358         blk = zh->zh_log;
359
360         /*
361          * If we don't already have an initial log block or we have one
362          * but it's the wrong endianness then allocate one.
363          */
364         if (BP_IS_HOLE(&blk) || BP_SHOULD_BYTESWAP(&blk)) {
365                 tx = dmu_tx_create(zilog->zl_os);
366                 (void) dmu_tx_assign(tx, TXG_WAIT);
367                 dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
368                 txg = dmu_tx_get_txg(tx);
369
370                 if (!BP_IS_HOLE(&blk)) {
371                         zio_free_blk(zilog->zl_spa, &blk, txg);
372                         BP_ZERO(&blk);
373                 }
374
375                 error = zio_alloc_blk(zilog->zl_spa, ZIL_MIN_BLKSZ, &blk,
376                     NULL, txg);
377
378                 if (error == 0)
379                         zil_init_log_chain(zilog, &blk);
380         }
381
382         /*
383          * Allocate a log write buffer (lwb) for the first log block.
384          */
385         if (error == 0) {
386                 lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
387                 lwb->lwb_zilog = zilog;
388                 lwb->lwb_blk = blk;
389                 lwb->lwb_nused = 0;
390                 lwb->lwb_sz = BP_GET_LSIZE(&lwb->lwb_blk);
391                 lwb->lwb_buf = zio_buf_alloc(lwb->lwb_sz);
392                 lwb->lwb_max_txg = txg;
393                 lwb->lwb_zio = NULL;
394
395                 mutex_enter(&zilog->zl_lock);
396                 list_insert_tail(&zilog->zl_lwb_list, lwb);
397                 mutex_exit(&zilog->zl_lock);
398         }
399
400         /*
401          * If we just allocated the first log block, commit our transaction
402          * and wait for zil_sync() to stuff the block poiner into zh_log.
403          * (zh is part of the MOS, so we cannot modify it in open context.)
404          */
405         if (tx != NULL) {
406                 dmu_tx_commit(tx);
407                 txg_wait_synced(zilog->zl_dmu_pool, txg);
408         }
409
410         ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
411 }
412
413 /*
414  * In one tx, free all log blocks and clear the log header.
415  * If keep_first is set, then we're replaying a log with no content.
416  * We want to keep the first block, however, so that the first
417  * synchronous transaction doesn't require a txg_wait_synced()
418  * in zil_create().  We don't need to txg_wait_synced() here either
419  * when keep_first is set, because both zil_create() and zil_destroy()
420  * will wait for any in-progress destroys to complete.
421  */
422 void
423 zil_destroy(zilog_t *zilog, boolean_t keep_first)
424 {
425         const zil_header_t *zh = zilog->zl_header;
426         lwb_t *lwb;
427         dmu_tx_t *tx;
428         uint64_t txg;
429
430         /*
431          * Wait for any previous destroy to complete.
432          */
433         txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
434
435         if (BP_IS_HOLE(&zh->zh_log))
436                 return;
437
438         tx = dmu_tx_create(zilog->zl_os);
439         (void) dmu_tx_assign(tx, TXG_WAIT);
440         dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
441         txg = dmu_tx_get_txg(tx);
442
443         mutex_enter(&zilog->zl_lock);
444
445         /*
446          * It is possible for the ZIL to get the previously mounted zilog
447          * structure of the same dataset if quickly remounted and the dbuf
448          * eviction has not completed. In this case we can see a non
449          * empty lwb list and keep_first will be set. We fix this by
450          * clearing the keep_first. This will be slower but it's very rare.
451          */
452         if (!list_is_empty(&zilog->zl_lwb_list) && keep_first)
453                 keep_first = B_FALSE;
454
455         ASSERT3U(zilog->zl_destroy_txg, <, txg);
456         zilog->zl_destroy_txg = txg;
457         zilog->zl_keep_first = keep_first;
458
459         if (!list_is_empty(&zilog->zl_lwb_list)) {
460                 ASSERT(zh->zh_claim_txg == 0);
461                 ASSERT(!keep_first);
462                 while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
463                         list_remove(&zilog->zl_lwb_list, lwb);
464                         if (lwb->lwb_buf != NULL)
465                                 zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
466                         zio_free_blk(zilog->zl_spa, &lwb->lwb_blk, txg);
467                         kmem_cache_free(zil_lwb_cache, lwb);
468                 }
469         } else {
470                 if (!keep_first) {
471                         (void) zil_parse(zilog, zil_free_log_block,
472                             zil_free_log_record, tx, zh->zh_claim_txg);
473                 }
474         }
475         mutex_exit(&zilog->zl_lock);
476
477         dmu_tx_commit(tx);
478 }
479
480 /*
481  * return true if the initial log block is not valid
482  */
483 static boolean_t
484 zil_empty(zilog_t *zilog)
485 {
486         const zil_header_t *zh = zilog->zl_header;
487         arc_buf_t *abuf = NULL;
488
489         if (BP_IS_HOLE(&zh->zh_log))
490                 return (B_TRUE);
491
492         if (zil_read_log_block(zilog, &zh->zh_log, &abuf) != 0)
493                 return (B_TRUE);
494
495         VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
496         return (B_FALSE);
497 }
498
499 int
500 zil_claim(char *osname, void *txarg)
501 {
502         dmu_tx_t *tx = txarg;
503         uint64_t first_txg = dmu_tx_get_txg(tx);
504         zilog_t *zilog;
505         zil_header_t *zh;
506         objset_t *os;
507         int error;
508
509         error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
510         if (error) {
511                 cmn_err(CE_WARN, "can't open objset for %s", osname);
512                 return (0);
513         }
514
515         zilog = dmu_objset_zil(os);
516         zh = zil_header_in_syncing_context(zilog);
517
518         /*
519          * Record here whether the zil has any records to replay.
520          * If the header block pointer is null or the block points
521          * to the stubby then we know there are no valid log records.
522          * We use the header to store this state as the the zilog gets
523          * freed later in dmu_objset_close().
524          * The flags (and the rest of the header fields) are cleared in
525          * zil_sync() as a result of a zil_destroy(), after replaying the log.
526          *
527          * Note, the intent log can be empty but still need the
528          * stubby to be claimed.
529          */
530         if (!zil_empty(zilog))
531                 zh->zh_flags |= ZIL_REPLAY_NEEDED;
532
533         /*
534          * Claim all log blocks if we haven't already done so, and remember
535          * the highest claimed sequence number.  This ensures that if we can
536          * read only part of the log now (e.g. due to a missing device),
537          * but we can read the entire log later, we will not try to replay
538          * or destroy beyond the last block we successfully claimed.
539          */
540         ASSERT3U(zh->zh_claim_txg, <=, first_txg);
541         if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
542                 zh->zh_claim_txg = first_txg;
543                 zh->zh_claim_seq = zil_parse(zilog, zil_claim_log_block,
544                     zil_claim_log_record, tx, first_txg);
545                 dsl_dataset_dirty(dmu_objset_ds(os), tx);
546         }
547
548         ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
549         dmu_objset_close(os);
550         return (0);
551 }
552
553 /*
554  * Check the log by walking the log chain.
555  * Checksum errors are ok as they indicate the end of the chain.
556  * Any other error (no device or read failure) returns an error.
557  */
558 /* ARGSUSED */
559 int
560 zil_check_log_chain(char *osname, void *txarg)
561 {
562         zilog_t *zilog;
563         zil_header_t *zh;
564         blkptr_t blk;
565         arc_buf_t *abuf;
566         objset_t *os;
567         char *lrbuf;
568         zil_trailer_t *ztp;
569         int error;
570
571         error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
572         if (error) {
573                 cmn_err(CE_WARN, "can't open objset for %s", osname);
574                 return (0);
575         }
576
577         zilog = dmu_objset_zil(os);
578         zh = zil_header_in_syncing_context(zilog);
579         blk = zh->zh_log;
580         if (BP_IS_HOLE(&blk)) {
581                 dmu_objset_close(os);
582                 return (0); /* no chain */
583         }
584
585         for (;;) {
586                 error = zil_read_log_block(zilog, &blk, &abuf);
587                 if (error)
588                         break;
589                 lrbuf = abuf->b_data;
590                 ztp = (zil_trailer_t *)(lrbuf + BP_GET_LSIZE(&blk)) - 1;
591                 blk = ztp->zit_next_blk;
592                 VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
593         }
594         dmu_objset_close(os);
595         if (error == ECKSUM)
596                 return (0); /* normal end of chain */
597         return (error);
598 }
599
600 /*
601  * Clear a log chain
602  */
603 /* ARGSUSED */
604 int
605 zil_clear_log_chain(char *osname, void *txarg)
606 {
607         zilog_t *zilog;
608         zil_header_t *zh;
609         objset_t *os;
610         dmu_tx_t *tx;
611         int error;
612
613         error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
614         if (error) {
615                 cmn_err(CE_WARN, "can't open objset for %s", osname);
616                 return (0);
617         }
618
619         zilog = dmu_objset_zil(os);
620         tx = dmu_tx_create(zilog->zl_os);
621         (void) dmu_tx_assign(tx, TXG_WAIT);
622         zh = zil_header_in_syncing_context(zilog);
623         BP_ZERO(&zh->zh_log);
624         dsl_dataset_dirty(dmu_objset_ds(os), tx);
625         dmu_tx_commit(tx);
626         dmu_objset_close(os);
627         return (0);
628 }
629
630 static int
631 zil_vdev_compare(const void *x1, const void *x2)
632 {
633         uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
634         uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
635
636         if (v1 < v2)
637                 return (-1);
638         if (v1 > v2)
639                 return (1);
640
641         return (0);
642 }
643
644 void
645 zil_add_block(zilog_t *zilog, blkptr_t *bp)
646 {
647         avl_tree_t *t = &zilog->zl_vdev_tree;
648         avl_index_t where;
649         zil_vdev_node_t *zv, zvsearch;
650         int ndvas = BP_GET_NDVAS(bp);
651         int i;
652
653         if (zfs_nocacheflush)
654                 return;
655
656         ASSERT(zilog->zl_writer);
657
658         /*
659          * Even though we're zl_writer, we still need a lock because the
660          * zl_get_data() callbacks may have dmu_sync() done callbacks
661          * that will run concurrently.
662          */
663         mutex_enter(&zilog->zl_vdev_lock);
664         for (i = 0; i < ndvas; i++) {
665                 zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
666                 if (avl_find(t, &zvsearch, &where) == NULL) {
667                         zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
668                         zv->zv_vdev = zvsearch.zv_vdev;
669                         avl_insert(t, zv, where);
670                 }
671         }
672         mutex_exit(&zilog->zl_vdev_lock);
673 }
674
675 void
676 zil_flush_vdevs(zilog_t *zilog)
677 {
678         spa_t *spa = zilog->zl_spa;
679         avl_tree_t *t = &zilog->zl_vdev_tree;
680         void *cookie = NULL;
681         zil_vdev_node_t *zv;
682         zio_t *zio;
683
684         ASSERT(zilog->zl_writer);
685
686         /*
687          * We don't need zl_vdev_lock here because we're the zl_writer,
688          * and all zl_get_data() callbacks are done.
689          */
690         if (avl_numnodes(t) == 0)
691                 return;
692
693         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
694
695         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
696
697         while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
698                 vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
699                 if (vd != NULL)
700                         zio_flush(zio, vd);
701                 kmem_free(zv, sizeof (*zv));
702         }
703
704         /*
705          * Wait for all the flushes to complete.  Not all devices actually
706          * support the DKIOCFLUSHWRITECACHE ioctl, so it's OK if it fails.
707          */
708         (void) zio_wait(zio);
709
710         spa_config_exit(spa, SCL_STATE, FTAG);
711 }
712
713 /*
714  * Function called when a log block write completes
715  */
716 static void
717 zil_lwb_write_done(zio_t *zio)
718 {
719         lwb_t *lwb = zio->io_private;
720         zilog_t *zilog = lwb->lwb_zilog;
721
722         ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
723         ASSERT(BP_GET_CHECKSUM(zio->io_bp) == ZIO_CHECKSUM_ZILOG);
724         ASSERT(BP_GET_TYPE(zio->io_bp) == DMU_OT_INTENT_LOG);
725         ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
726         ASSERT(BP_GET_BYTEORDER(zio->io_bp) == ZFS_HOST_BYTEORDER);
727         ASSERT(!BP_IS_GANG(zio->io_bp));
728         ASSERT(!BP_IS_HOLE(zio->io_bp));
729         ASSERT(zio->io_bp->blk_fill == 0);
730
731         /*
732          * Ensure the lwb buffer pointer is cleared before releasing
733          * the txg. If we have had an allocation failure and
734          * the txg is waiting to sync then we want want zil_sync()
735          * to remove the lwb so that it's not picked up as the next new
736          * one in zil_commit_writer(). zil_sync() will only remove
737          * the lwb if lwb_buf is null.
738          */
739         zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
740         mutex_enter(&zilog->zl_lock);
741         lwb->lwb_buf = NULL;
742         if (zio->io_error)
743                 zilog->zl_log_error = B_TRUE;
744
745         /*
746          * Now that we've written this log block, we have a stable pointer
747          * to the next block in the chain, so it's OK to let the txg in
748          * which we allocated the next block sync. We still have the
749          * zl_lock to ensure zil_sync doesn't kmem free the lwb.
750          */
751         txg_rele_to_sync(&lwb->lwb_txgh);
752         mutex_exit(&zilog->zl_lock);
753 }
754
755 /*
756  * Initialize the io for a log block.
757  */
758 static void
759 zil_lwb_write_init(zilog_t *zilog, lwb_t *lwb)
760 {
761         zbookmark_t zb;
762
763         zb.zb_objset = lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET];
764         zb.zb_object = 0;
765         zb.zb_level = -1;
766         zb.zb_blkid = lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
767
768         if (zilog->zl_root_zio == NULL) {
769                 zilog->zl_root_zio = zio_root(zilog->zl_spa, NULL, NULL,
770                     ZIO_FLAG_CANFAIL);
771         }
772         if (lwb->lwb_zio == NULL) {
773                 lwb->lwb_zio = zio_rewrite(zilog->zl_root_zio, zilog->zl_spa,
774                     0, &lwb->lwb_blk, lwb->lwb_buf,
775                     lwb->lwb_sz, zil_lwb_write_done, lwb,
776                     ZIO_PRIORITY_LOG_WRITE, ZIO_FLAG_CANFAIL, &zb);
777         }
778 }
779
780 /*
781  * Start a log block write and advance to the next log block.
782  * Calls are serialized.
783  */
784 static lwb_t *
785 zil_lwb_write_start(zilog_t *zilog, lwb_t *lwb)
786 {
787         lwb_t *nlwb;
788         zil_trailer_t *ztp = (zil_trailer_t *)(lwb->lwb_buf + lwb->lwb_sz) - 1;
789         spa_t *spa = zilog->zl_spa;
790         blkptr_t *bp = &ztp->zit_next_blk;
791         uint64_t txg;
792         uint64_t zil_blksz;
793         int error;
794
795         ASSERT(lwb->lwb_nused <= ZIL_BLK_DATA_SZ(lwb));
796
797         /*
798          * Allocate the next block and save its address in this block
799          * before writing it in order to establish the log chain.
800          * Note that if the allocation of nlwb synced before we wrote
801          * the block that points at it (lwb), we'd leak it if we crashed.
802          * Therefore, we don't do txg_rele_to_sync() until zil_lwb_write_done().
803          */
804         txg = txg_hold_open(zilog->zl_dmu_pool, &lwb->lwb_txgh);
805         txg_rele_to_quiesce(&lwb->lwb_txgh);
806
807         /*
808          * Pick a ZIL blocksize. We request a size that is the
809          * maximum of the previous used size, the current used size and
810          * the amount waiting in the queue.
811          */
812         zil_blksz = MAX(zilog->zl_prev_used,
813             zilog->zl_cur_used + sizeof (*ztp));
814         zil_blksz = MAX(zil_blksz, zilog->zl_itx_list_sz + sizeof (*ztp));
815         zil_blksz = P2ROUNDUP_TYPED(zil_blksz, ZIL_MIN_BLKSZ, uint64_t);
816         if (zil_blksz > ZIL_MAX_BLKSZ)
817                 zil_blksz = ZIL_MAX_BLKSZ;
818
819         BP_ZERO(bp);
820         /* pass the old blkptr in order to spread log blocks across devs */
821         error = zio_alloc_blk(spa, zil_blksz, bp, &lwb->lwb_blk, txg);
822         if (error) {
823                 dmu_tx_t *tx = dmu_tx_create_assigned(zilog->zl_dmu_pool, txg);
824
825                 /*
826                  * We dirty the dataset to ensure that zil_sync() will
827                  * be called to remove this lwb from our zl_lwb_list.
828                  * Failing to do so, may leave an lwb with a NULL lwb_buf
829                  * hanging around on the zl_lwb_list.
830                  */
831                 dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
832                 dmu_tx_commit(tx);
833
834                 /*
835                  * Since we've just experienced an allocation failure so we
836                  * terminate the current lwb and send it on its way.
837                  */
838                 ztp->zit_pad = 0;
839                 ztp->zit_nused = lwb->lwb_nused;
840                 ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
841                 zio_nowait(lwb->lwb_zio);
842
843                 /*
844                  * By returning NULL the caller will call tx_wait_synced()
845                  */
846                 return (NULL);
847         }
848
849         ASSERT3U(bp->blk_birth, ==, txg);
850         ztp->zit_pad = 0;
851         ztp->zit_nused = lwb->lwb_nused;
852         ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
853         bp->blk_cksum = lwb->lwb_blk.blk_cksum;
854         bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
855
856         /*
857          * Allocate a new log write buffer (lwb).
858          */
859         nlwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
860
861         nlwb->lwb_zilog = zilog;
862         nlwb->lwb_blk = *bp;
863         nlwb->lwb_nused = 0;
864         nlwb->lwb_sz = BP_GET_LSIZE(&nlwb->lwb_blk);
865         nlwb->lwb_buf = zio_buf_alloc(nlwb->lwb_sz);
866         nlwb->lwb_max_txg = txg;
867         nlwb->lwb_zio = NULL;
868
869         /*
870          * Put new lwb at the end of the log chain
871          */
872         mutex_enter(&zilog->zl_lock);
873         list_insert_tail(&zilog->zl_lwb_list, nlwb);
874         mutex_exit(&zilog->zl_lock);
875
876         /* Record the block for later vdev flushing */
877         zil_add_block(zilog, &lwb->lwb_blk);
878
879         /*
880          * kick off the write for the old log block
881          */
882         dprintf_bp(&lwb->lwb_blk, "lwb %p txg %llu: ", lwb, txg);
883         ASSERT(lwb->lwb_zio);
884         zio_nowait(lwb->lwb_zio);
885
886         return (nlwb);
887 }
888
889 static lwb_t *
890 zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb)
891 {
892         lr_t *lrc = &itx->itx_lr; /* common log record */
893         lr_write_t *lr = (lr_write_t *)lrc;
894         uint64_t txg = lrc->lrc_txg;
895         uint64_t reclen = lrc->lrc_reclen;
896         uint64_t dlen;
897
898         if (lwb == NULL)
899                 return (NULL);
900         ASSERT(lwb->lwb_buf != NULL);
901
902         if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY)
903                 dlen = P2ROUNDUP_TYPED(
904                     lr->lr_length, sizeof (uint64_t), uint64_t);
905         else
906                 dlen = 0;
907
908         zilog->zl_cur_used += (reclen + dlen);
909
910         zil_lwb_write_init(zilog, lwb);
911
912         /*
913          * If this record won't fit in the current log block, start a new one.
914          */
915         if (lwb->lwb_nused + reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
916                 lwb = zil_lwb_write_start(zilog, lwb);
917                 if (lwb == NULL)
918                         return (NULL);
919                 zil_lwb_write_init(zilog, lwb);
920                 ASSERT(lwb->lwb_nused == 0);
921                 if (reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
922                         txg_wait_synced(zilog->zl_dmu_pool, txg);
923                         return (lwb);
924                 }
925         }
926
927         /*
928          * Update the lrc_seq, to be log record sequence number. See zil.h
929          * Then copy the record to the log buffer.
930          */
931         lrc->lrc_seq = ++zilog->zl_lr_seq; /* we are single threaded */
932         bcopy(lrc, lwb->lwb_buf + lwb->lwb_nused, reclen);
933
934         /*
935          * If it's a write, fetch the data or get its blkptr as appropriate.
936          */
937         if (lrc->lrc_txtype == TX_WRITE) {
938                 if (txg > spa_freeze_txg(zilog->zl_spa))
939                         txg_wait_synced(zilog->zl_dmu_pool, txg);
940                 if (itx->itx_wr_state != WR_COPIED) {
941                         char *dbuf;
942                         int error;
943
944                         /* alignment is guaranteed */
945                         lr = (lr_write_t *)(lwb->lwb_buf + lwb->lwb_nused);
946                         if (dlen) {
947                                 ASSERT(itx->itx_wr_state == WR_NEED_COPY);
948                                 dbuf = lwb->lwb_buf + lwb->lwb_nused + reclen;
949                                 lr->lr_common.lrc_reclen += dlen;
950                         } else {
951                                 ASSERT(itx->itx_wr_state == WR_INDIRECT);
952                                 dbuf = NULL;
953                         }
954                         error = zilog->zl_get_data(
955                             itx->itx_private, lr, dbuf, lwb->lwb_zio);
956                         if (error) {
957                                 ASSERT(error == ENOENT || error == EEXIST ||
958                                     error == EALREADY);
959                                 return (lwb);
960                         }
961                 }
962         }
963
964         lwb->lwb_nused += reclen + dlen;
965         lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
966         ASSERT3U(lwb->lwb_nused, <=, ZIL_BLK_DATA_SZ(lwb));
967         ASSERT3U(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)), ==, 0);
968
969         return (lwb);
970 }
971
972 itx_t *
973 zil_itx_create(uint64_t txtype, size_t lrsize)
974 {
975         itx_t *itx;
976
977         lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t);
978
979         itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP);
980         itx->itx_lr.lrc_txtype = txtype;
981         itx->itx_lr.lrc_reclen = lrsize;
982         itx->itx_sod = lrsize; /* if write & WR_NEED_COPY will be increased */
983         itx->itx_lr.lrc_seq = 0;        /* defensive */
984
985         return (itx);
986 }
987
988 uint64_t
989 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
990 {
991         uint64_t seq;
992
993         ASSERT(itx->itx_lr.lrc_seq == 0);
994
995         mutex_enter(&zilog->zl_lock);
996         list_insert_tail(&zilog->zl_itx_list, itx);
997         zilog->zl_itx_list_sz += itx->itx_sod;
998         itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
999         itx->itx_lr.lrc_seq = seq = ++zilog->zl_itx_seq;
1000         mutex_exit(&zilog->zl_lock);
1001
1002         return (seq);
1003 }
1004
1005 /*
1006  * Free up all in-memory intent log transactions that have now been synced.
1007  */
1008 static void
1009 zil_itx_clean(zilog_t *zilog)
1010 {
1011         uint64_t synced_txg = spa_last_synced_txg(zilog->zl_spa);
1012         uint64_t freeze_txg = spa_freeze_txg(zilog->zl_spa);
1013         list_t clean_list;
1014         itx_t *itx;
1015
1016         list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
1017
1018         mutex_enter(&zilog->zl_lock);
1019         /* wait for a log writer to finish walking list */
1020         while (zilog->zl_writer) {
1021                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1022         }
1023
1024         /*
1025          * Move the sync'd log transactions to a separate list so we can call
1026          * kmem_free without holding the zl_lock.
1027          *
1028          * There is no need to set zl_writer as we don't drop zl_lock here
1029          */
1030         while ((itx = list_head(&zilog->zl_itx_list)) != NULL &&
1031             itx->itx_lr.lrc_txg <= MIN(synced_txg, freeze_txg)) {
1032                 list_remove(&zilog->zl_itx_list, itx);
1033                 zilog->zl_itx_list_sz -= itx->itx_sod;
1034                 list_insert_tail(&clean_list, itx);
1035         }
1036         cv_broadcast(&zilog->zl_cv_writer);
1037         mutex_exit(&zilog->zl_lock);
1038
1039         /* destroy sync'd log transactions */
1040         while ((itx = list_head(&clean_list)) != NULL) {
1041                 list_remove(&clean_list, itx);
1042                 kmem_free(itx, offsetof(itx_t, itx_lr)
1043                     + itx->itx_lr.lrc_reclen);
1044         }
1045         list_destroy(&clean_list);
1046 }
1047
1048 /*
1049  * If there are any in-memory intent log transactions which have now been
1050  * synced then start up a taskq to free them.
1051  */
1052 void
1053 zil_clean(zilog_t *zilog)
1054 {
1055         itx_t *itx;
1056
1057         mutex_enter(&zilog->zl_lock);
1058         itx = list_head(&zilog->zl_itx_list);
1059         if ((itx != NULL) &&
1060             (itx->itx_lr.lrc_txg <= spa_last_synced_txg(zilog->zl_spa))) {
1061                 (void) taskq_dispatch(zilog->zl_clean_taskq,
1062                     (task_func_t *)zil_itx_clean, zilog, TQ_SLEEP);
1063         }
1064         mutex_exit(&zilog->zl_lock);
1065 }
1066
1067 static void
1068 zil_commit_writer(zilog_t *zilog, uint64_t seq, uint64_t foid)
1069 {
1070         uint64_t txg;
1071         uint64_t commit_seq = 0;
1072         itx_t *itx, *itx_next = (itx_t *)-1;
1073         lwb_t *lwb;
1074         spa_t *spa;
1075
1076         zilog->zl_writer = B_TRUE;
1077         ASSERT(zilog->zl_root_zio == NULL);
1078         spa = zilog->zl_spa;
1079
1080         if (zilog->zl_suspend) {
1081                 lwb = NULL;
1082         } else {
1083                 lwb = list_tail(&zilog->zl_lwb_list);
1084                 if (lwb == NULL) {
1085                         /*
1086                          * Return if there's nothing to flush before we
1087                          * dirty the fs by calling zil_create()
1088                          */
1089                         if (list_is_empty(&zilog->zl_itx_list)) {
1090                                 zilog->zl_writer = B_FALSE;
1091                                 return;
1092                         }
1093                         mutex_exit(&zilog->zl_lock);
1094                         zil_create(zilog);
1095                         mutex_enter(&zilog->zl_lock);
1096                         lwb = list_tail(&zilog->zl_lwb_list);
1097                 }
1098         }
1099
1100         /* Loop through in-memory log transactions filling log blocks. */
1101         DTRACE_PROBE1(zil__cw1, zilog_t *, zilog);
1102         for (;;) {
1103                 /*
1104                  * Find the next itx to push:
1105                  * Push all transactions related to specified foid and all
1106                  * other transactions except TX_WRITE, TX_TRUNCATE,
1107                  * TX_SETATTR and TX_ACL for all other files.
1108                  */
1109                 if (itx_next != (itx_t *)-1)
1110                         itx = itx_next;
1111                 else
1112                         itx = list_head(&zilog->zl_itx_list);
1113                 for (; itx != NULL; itx = list_next(&zilog->zl_itx_list, itx)) {
1114                         if (foid == 0) /* push all foids? */
1115                                 break;
1116                         if (itx->itx_sync) /* push all O_[D]SYNC */
1117                                 break;
1118                         switch (itx->itx_lr.lrc_txtype) {
1119                         case TX_SETATTR:
1120                         case TX_WRITE:
1121                         case TX_TRUNCATE:
1122                         case TX_ACL:
1123                                 /* lr_foid is same offset for these records */
1124                                 if (((lr_write_t *)&itx->itx_lr)->lr_foid
1125                                     != foid) {
1126                                         continue; /* skip this record */
1127                                 }
1128                         }
1129                         break;
1130                 }
1131                 if (itx == NULL)
1132                         break;
1133
1134                 if ((itx->itx_lr.lrc_seq > seq) &&
1135                     ((lwb == NULL) || (lwb->lwb_nused == 0) ||
1136                     (lwb->lwb_nused + itx->itx_sod > ZIL_BLK_DATA_SZ(lwb)))) {
1137                         break;
1138                 }
1139
1140                 /*
1141                  * Save the next pointer.  Even though we soon drop
1142                  * zl_lock all threads that may change the list
1143                  * (another writer or zil_itx_clean) can't do so until
1144                  * they have zl_writer.
1145                  */
1146                 itx_next = list_next(&zilog->zl_itx_list, itx);
1147                 list_remove(&zilog->zl_itx_list, itx);
1148                 zilog->zl_itx_list_sz -= itx->itx_sod;
1149                 mutex_exit(&zilog->zl_lock);
1150                 txg = itx->itx_lr.lrc_txg;
1151                 ASSERT(txg);
1152
1153                 if (txg > spa_last_synced_txg(spa) ||
1154                     txg > spa_freeze_txg(spa))
1155                         lwb = zil_lwb_commit(zilog, itx, lwb);
1156                 kmem_free(itx, offsetof(itx_t, itx_lr)
1157                     + itx->itx_lr.lrc_reclen);
1158                 mutex_enter(&zilog->zl_lock);
1159         }
1160         DTRACE_PROBE1(zil__cw2, zilog_t *, zilog);
1161         /* determine commit sequence number */
1162         itx = list_head(&zilog->zl_itx_list);
1163         if (itx)
1164                 commit_seq = itx->itx_lr.lrc_seq;
1165         else
1166                 commit_seq = zilog->zl_itx_seq;
1167         mutex_exit(&zilog->zl_lock);
1168
1169         /* write the last block out */
1170         if (lwb != NULL && lwb->lwb_zio != NULL)
1171                 lwb = zil_lwb_write_start(zilog, lwb);
1172
1173         zilog->zl_prev_used = zilog->zl_cur_used;
1174         zilog->zl_cur_used = 0;
1175
1176         /*
1177          * Wait if necessary for the log blocks to be on stable storage.
1178          */
1179         if (zilog->zl_root_zio) {
1180                 DTRACE_PROBE1(zil__cw3, zilog_t *, zilog);
1181                 (void) zio_wait(zilog->zl_root_zio);
1182                 zilog->zl_root_zio = NULL;
1183                 DTRACE_PROBE1(zil__cw4, zilog_t *, zilog);
1184                 zil_flush_vdevs(zilog);
1185         }
1186
1187         if (zilog->zl_log_error || lwb == NULL) {
1188                 zilog->zl_log_error = 0;
1189                 txg_wait_synced(zilog->zl_dmu_pool, 0);
1190         }
1191
1192         mutex_enter(&zilog->zl_lock);
1193         zilog->zl_writer = B_FALSE;
1194
1195         ASSERT3U(commit_seq, >=, zilog->zl_commit_seq);
1196         zilog->zl_commit_seq = commit_seq;
1197 }
1198
1199 /*
1200  * Push zfs transactions to stable storage up to the supplied sequence number.
1201  * If foid is 0 push out all transactions, otherwise push only those
1202  * for that file or might have been used to create that file.
1203  */
1204 void
1205 zil_commit(zilog_t *zilog, uint64_t seq, uint64_t foid)
1206 {
1207         if (zilog == NULL || seq == 0)
1208                 return;
1209
1210         mutex_enter(&zilog->zl_lock);
1211
1212         seq = MIN(seq, zilog->zl_itx_seq);      /* cap seq at largest itx seq */
1213
1214         while (zilog->zl_writer) {
1215                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1216                 if (seq < zilog->zl_commit_seq) {
1217                         mutex_exit(&zilog->zl_lock);
1218                         return;
1219                 }
1220         }
1221         zil_commit_writer(zilog, seq, foid); /* drops zl_lock */
1222         /* wake up others waiting on the commit */
1223         cv_broadcast(&zilog->zl_cv_writer);
1224         mutex_exit(&zilog->zl_lock);
1225 }
1226
1227 /*
1228  * Called in syncing context to free committed log blocks and update log header.
1229  */
1230 void
1231 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
1232 {
1233         zil_header_t *zh = zil_header_in_syncing_context(zilog);
1234         uint64_t txg = dmu_tx_get_txg(tx);
1235         spa_t *spa = zilog->zl_spa;
1236         lwb_t *lwb;
1237
1238         /*
1239          * We don't zero out zl_destroy_txg, so make sure we don't try
1240          * to destroy it twice.
1241          */
1242         if (spa_sync_pass(spa) != 1)
1243                 return;
1244
1245         mutex_enter(&zilog->zl_lock);
1246
1247         ASSERT(zilog->zl_stop_sync == 0);
1248
1249         zh->zh_replay_seq = zilog->zl_replayed_seq[txg & TXG_MASK];
1250
1251         if (zilog->zl_destroy_txg == txg) {
1252                 blkptr_t blk = zh->zh_log;
1253
1254                 ASSERT(list_head(&zilog->zl_lwb_list) == NULL);
1255
1256                 bzero(zh, sizeof (zil_header_t));
1257                 bzero(zilog->zl_replayed_seq, sizeof (zilog->zl_replayed_seq));
1258
1259                 if (zilog->zl_keep_first) {
1260                         /*
1261                          * If this block was part of log chain that couldn't
1262                          * be claimed because a device was missing during
1263                          * zil_claim(), but that device later returns,
1264                          * then this block could erroneously appear valid.
1265                          * To guard against this, assign a new GUID to the new
1266                          * log chain so it doesn't matter what blk points to.
1267                          */
1268                         zil_init_log_chain(zilog, &blk);
1269                         zh->zh_log = blk;
1270                 }
1271         }
1272
1273         for (;;) {
1274                 lwb = list_head(&zilog->zl_lwb_list);
1275                 if (lwb == NULL) {
1276                         mutex_exit(&zilog->zl_lock);
1277                         return;
1278                 }
1279                 zh->zh_log = lwb->lwb_blk;
1280                 if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg)
1281                         break;
1282                 list_remove(&zilog->zl_lwb_list, lwb);
1283                 zio_free_blk(spa, &lwb->lwb_blk, txg);
1284                 kmem_cache_free(zil_lwb_cache, lwb);
1285
1286                 /*
1287                  * If we don't have anything left in the lwb list then
1288                  * we've had an allocation failure and we need to zero
1289                  * out the zil_header blkptr so that we don't end
1290                  * up freeing the same block twice.
1291                  */
1292                 if (list_head(&zilog->zl_lwb_list) == NULL)
1293                         BP_ZERO(&zh->zh_log);
1294         }
1295         mutex_exit(&zilog->zl_lock);
1296 }
1297
1298 void
1299 zil_init(void)
1300 {
1301         zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
1302             sizeof (struct lwb), 0, NULL, NULL, NULL, NULL, NULL, 0);
1303 }
1304
1305 void
1306 zil_fini(void)
1307 {
1308         kmem_cache_destroy(zil_lwb_cache);
1309 }
1310
1311 zilog_t *
1312 zil_alloc(objset_t *os, zil_header_t *zh_phys)
1313 {
1314         zilog_t *zilog;
1315
1316         zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
1317
1318         zilog->zl_header = zh_phys;
1319         zilog->zl_os = os;
1320         zilog->zl_spa = dmu_objset_spa(os);
1321         zilog->zl_dmu_pool = dmu_objset_pool(os);
1322         zilog->zl_destroy_txg = TXG_INITIAL - 1;
1323
1324         mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
1325
1326         list_create(&zilog->zl_itx_list, sizeof (itx_t),
1327             offsetof(itx_t, itx_node));
1328
1329         list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
1330             offsetof(lwb_t, lwb_node));
1331
1332         mutex_init(&zilog->zl_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
1333
1334         avl_create(&zilog->zl_vdev_tree, zil_vdev_compare,
1335             sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
1336
1337         cv_init(&zilog->zl_cv_writer, NULL, CV_DEFAULT, NULL);
1338         cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
1339
1340         return (zilog);
1341 }
1342
1343 void
1344 zil_free(zilog_t *zilog)
1345 {
1346         lwb_t *lwb;
1347
1348         zilog->zl_stop_sync = 1;
1349
1350         while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
1351                 list_remove(&zilog->zl_lwb_list, lwb);
1352                 if (lwb->lwb_buf != NULL)
1353                         zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1354                 kmem_cache_free(zil_lwb_cache, lwb);
1355         }
1356         list_destroy(&zilog->zl_lwb_list);
1357
1358         avl_destroy(&zilog->zl_vdev_tree);
1359         mutex_destroy(&zilog->zl_vdev_lock);
1360
1361         ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1362         list_destroy(&zilog->zl_itx_list);
1363         mutex_destroy(&zilog->zl_lock);
1364
1365         cv_destroy(&zilog->zl_cv_writer);
1366         cv_destroy(&zilog->zl_cv_suspend);
1367
1368         kmem_free(zilog, sizeof (zilog_t));
1369 }
1370
1371 /*
1372  * Open an intent log.
1373  */
1374 zilog_t *
1375 zil_open(objset_t *os, zil_get_data_t *get_data)
1376 {
1377         zilog_t *zilog = dmu_objset_zil(os);
1378
1379         zilog->zl_get_data = get_data;
1380         zilog->zl_clean_taskq = taskq_create("zil_clean", 1, minclsyspri,
1381             2, 2, TASKQ_PREPOPULATE);
1382
1383         return (zilog);
1384 }
1385
1386 /*
1387  * Close an intent log.
1388  */
1389 void
1390 zil_close(zilog_t *zilog)
1391 {
1392         /*
1393          * If the log isn't already committed, mark the objset dirty
1394          * (so zil_sync() will be called) and wait for that txg to sync.
1395          */
1396         if (!zil_is_committed(zilog)) {
1397                 uint64_t txg;
1398                 dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
1399                 (void) dmu_tx_assign(tx, TXG_WAIT);
1400                 dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1401                 txg = dmu_tx_get_txg(tx);
1402                 dmu_tx_commit(tx);
1403                 txg_wait_synced(zilog->zl_dmu_pool, txg);
1404         }
1405
1406         taskq_destroy(zilog->zl_clean_taskq);
1407         zilog->zl_clean_taskq = NULL;
1408         zilog->zl_get_data = NULL;
1409
1410         zil_itx_clean(zilog);
1411         ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1412 }
1413
1414 /*
1415  * Suspend an intent log.  While in suspended mode, we still honor
1416  * synchronous semantics, but we rely on txg_wait_synced() to do it.
1417  * We suspend the log briefly when taking a snapshot so that the snapshot
1418  * contains all the data it's supposed to, and has an empty intent log.
1419  */
1420 int
1421 zil_suspend(zilog_t *zilog)
1422 {
1423         const zil_header_t *zh = zilog->zl_header;
1424
1425         mutex_enter(&zilog->zl_lock);
1426         if (zh->zh_flags & ZIL_REPLAY_NEEDED) {         /* unplayed log */
1427                 mutex_exit(&zilog->zl_lock);
1428                 return (EBUSY);
1429         }
1430         if (zilog->zl_suspend++ != 0) {
1431                 /*
1432                  * Someone else already began a suspend.
1433                  * Just wait for them to finish.
1434                  */
1435                 while (zilog->zl_suspending)
1436                         cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
1437                 mutex_exit(&zilog->zl_lock);
1438                 return (0);
1439         }
1440         zilog->zl_suspending = B_TRUE;
1441         mutex_exit(&zilog->zl_lock);
1442
1443         zil_commit(zilog, UINT64_MAX, 0);
1444
1445         /*
1446          * Wait for any in-flight log writes to complete.
1447          */
1448         mutex_enter(&zilog->zl_lock);
1449         while (zilog->zl_writer)
1450                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1451         mutex_exit(&zilog->zl_lock);
1452
1453         zil_destroy(zilog, B_FALSE);
1454
1455         mutex_enter(&zilog->zl_lock);
1456         zilog->zl_suspending = B_FALSE;
1457         cv_broadcast(&zilog->zl_cv_suspend);
1458         mutex_exit(&zilog->zl_lock);
1459
1460         return (0);
1461 }
1462
1463 void
1464 zil_resume(zilog_t *zilog)
1465 {
1466         mutex_enter(&zilog->zl_lock);
1467         ASSERT(zilog->zl_suspend != 0);
1468         zilog->zl_suspend--;
1469         mutex_exit(&zilog->zl_lock);
1470 }
1471
1472 /*
1473  * Read in the data for the dmu_sync()ed block, and change the log
1474  * record to write this whole block.
1475  */
1476 void
1477 zil_get_replay_data(zilog_t *zilog, lr_write_t *lr)
1478 {
1479         blkptr_t *wbp = &lr->lr_blkptr;
1480         char *wbuf = (char *)(lr + 1); /* data follows lr_write_t */
1481         uint64_t blksz;
1482
1483         if (BP_IS_HOLE(wbp)) {  /* compressed to a hole */
1484                 blksz = BP_GET_LSIZE(&lr->lr_blkptr);
1485                 /*
1486                  * If the blksz is zero then we must be replaying a log
1487                  * from an version prior to setting the blksize of null blocks.
1488                  * So we just zero the actual write size reqeusted.
1489                  */
1490                 if (blksz == 0) {
1491                         bzero(wbuf, lr->lr_length);
1492                         return;
1493                 }
1494                 bzero(wbuf, blksz);
1495         } else {
1496                 /*
1497                  * A subsequent write may have overwritten this block, in which
1498                  * case wbp may have been been freed and reallocated, and our
1499                  * read of wbp may fail with a checksum error.  We can safely
1500                  * ignore this because the later write will provide the
1501                  * correct data.
1502                  */
1503                 zbookmark_t zb;
1504
1505                 zb.zb_objset = dmu_objset_id(zilog->zl_os);
1506                 zb.zb_object = lr->lr_foid;
1507                 zb.zb_level = 0;
1508                 zb.zb_blkid = -1; /* unknown */
1509
1510                 blksz = BP_GET_LSIZE(&lr->lr_blkptr);
1511                 (void) zio_wait(zio_read(NULL, zilog->zl_spa, wbp, wbuf, blksz,
1512                     NULL, NULL, ZIO_PRIORITY_SYNC_READ,
1513                     ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE, &zb));
1514         }
1515         lr->lr_offset -= lr->lr_offset % blksz;
1516         lr->lr_length = blksz;
1517 }
1518
1519 typedef struct zil_replay_arg {
1520         objset_t        *zr_os;
1521         zil_replay_func_t **zr_replay;
1522         void            *zr_arg;
1523         boolean_t       zr_byteswap;
1524         char            *zr_lrbuf;
1525 } zil_replay_arg_t;
1526
1527 static void
1528 zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg)
1529 {
1530         zil_replay_arg_t *zr = zra;
1531         const zil_header_t *zh = zilog->zl_header;
1532         uint64_t reclen = lr->lrc_reclen;
1533         uint64_t txtype = lr->lrc_txtype;
1534         char *name;
1535         int pass, error;
1536
1537         if (!zilog->zl_replay)                  /* giving up */
1538                 return;
1539
1540         if (lr->lrc_txg < claim_txg)            /* already committed */
1541                 return;
1542
1543         if (lr->lrc_seq <= zh->zh_replay_seq)   /* already replayed */
1544                 return;
1545
1546         /* Strip case-insensitive bit, still present in log record */
1547         txtype &= ~TX_CI;
1548
1549         if (txtype == 0 || txtype >= TX_MAX_TYPE) {
1550                 error = EINVAL;
1551                 goto bad;
1552         }
1553
1554         /*
1555          * Make a copy of the data so we can revise and extend it.
1556          */
1557         bcopy(lr, zr->zr_lrbuf, reclen);
1558
1559         /*
1560          * The log block containing this lr may have been byteswapped
1561          * so that we can easily examine common fields like lrc_txtype.
1562          * However, the log is a mix of different data types, and only the
1563          * replay vectors know how to byteswap their records.  Therefore, if
1564          * the lr was byteswapped, undo it before invoking the replay vector.
1565          */
1566         if (zr->zr_byteswap)
1567                 byteswap_uint64_array(zr->zr_lrbuf, reclen);
1568
1569         /*
1570          * We must now do two things atomically: replay this log record,
1571          * and update the log header sequence number to reflect the fact that
1572          * we did so. At the end of each replay function the sequence number
1573          * is updated if we are in replay mode.
1574          */
1575         for (pass = 1; pass <= 2; pass++) {
1576                 zilog->zl_replaying_seq = lr->lrc_seq;
1577                 /* Only byteswap (if needed) on the 1st pass.  */
1578                 error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lrbuf,
1579                     zr->zr_byteswap && pass == 1);
1580
1581                 if (!error)
1582                         return;
1583
1584                 /*
1585                  * The DMU's dnode layer doesn't see removes until the txg
1586                  * commits, so a subsequent claim can spuriously fail with
1587                  * EEXIST. So if we receive any error we try syncing out
1588                  * any removes then retry the transaction.
1589                  */
1590                 if (pass == 1)
1591                         txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
1592         }
1593
1594 bad:
1595         ASSERT(error);
1596         name = kmem_alloc(MAXNAMELEN, KM_SLEEP);
1597         dmu_objset_name(zr->zr_os, name);
1598         cmn_err(CE_WARN, "ZFS replay transaction error %d, "
1599             "dataset %s, seq 0x%llx, txtype %llu %s\n",
1600             error, name, (u_longlong_t)lr->lrc_seq, (u_longlong_t)txtype,
1601             (lr->lrc_txtype & TX_CI) ? "CI" : "");
1602         zilog->zl_replay = B_FALSE;
1603         kmem_free(name, MAXNAMELEN);
1604 }
1605
1606 /* ARGSUSED */
1607 static void
1608 zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1609 {
1610         zilog->zl_replay_blks++;
1611 }
1612
1613 /*
1614  * If this dataset has a non-empty intent log, replay it and destroy it.
1615  */
1616 void
1617 zil_replay(objset_t *os, void *arg, zil_replay_func_t *replay_func[TX_MAX_TYPE])
1618 {
1619         zilog_t *zilog = dmu_objset_zil(os);
1620         const zil_header_t *zh = zilog->zl_header;
1621         zil_replay_arg_t zr;
1622
1623         if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
1624                 zil_destroy(zilog, B_TRUE);
1625                 return;
1626         }
1627         //printf("ZFS: Replaying ZIL on %s...\n", os->os->os_spa->spa_name);
1628
1629         zr.zr_os = os;
1630         zr.zr_replay = replay_func;
1631         zr.zr_arg = arg;
1632         zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
1633         zr.zr_lrbuf = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
1634
1635         /*
1636          * Wait for in-progress removes to sync before starting replay.
1637          */
1638         txg_wait_synced(zilog->zl_dmu_pool, 0);
1639
1640         zilog->zl_replay = B_TRUE;
1641         zilog->zl_replay_time = LBOLT;
1642         ASSERT(zilog->zl_replay_blks == 0);
1643         (void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
1644             zh->zh_claim_txg);
1645         kmem_free(zr.zr_lrbuf, 2 * SPA_MAXBLOCKSIZE);
1646
1647         zil_destroy(zilog, B_FALSE);
1648         txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
1649         zilog->zl_replay = B_FALSE;
1650         //printf("ZFS: Replay of ZIL on %s finished.\n", os->os->os_spa->spa_name);
1651 }
1652
1653 /*
1654  * Report whether all transactions are committed
1655  */
1656 int
1657 zil_is_committed(zilog_t *zilog)
1658 {
1659         lwb_t *lwb;
1660         int ret;
1661
1662         mutex_enter(&zilog->zl_lock);
1663         while (zilog->zl_writer)
1664                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1665
1666         /* recent unpushed intent log transactions? */
1667         if (!list_is_empty(&zilog->zl_itx_list)) {
1668                 ret = B_FALSE;
1669                 goto out;
1670         }
1671
1672         /* intent log never used? */
1673         lwb = list_head(&zilog->zl_lwb_list);
1674         if (lwb == NULL) {
1675                 ret = B_TRUE;
1676                 goto out;
1677         }
1678
1679         /*
1680          * more than 1 log buffer means zil_sync() hasn't yet freed
1681          * entries after a txg has committed
1682          */
1683         if (list_next(&zilog->zl_lwb_list, lwb)) {
1684                 ret = B_FALSE;
1685                 goto out;
1686         }
1687
1688         ASSERT(zil_empty(zilog));
1689         ret = B_TRUE;
1690 out:
1691         cv_broadcast(&zilog->zl_cv_writer);
1692         mutex_exit(&zilog->zl_lock);
1693         return (ret);
1694 }