]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/cddl/contrib/opensolaris/uts/common/fs/zfs/zil.c
MFC r200724:
[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 2008 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, allocate one now.
362          */
363         if (BP_IS_HOLE(&blk)) {
364                 tx = dmu_tx_create(zilog->zl_os);
365                 (void) dmu_tx_assign(tx, TXG_WAIT);
366                 dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
367                 txg = dmu_tx_get_txg(tx);
368
369                 error = zio_alloc_blk(zilog->zl_spa, ZIL_MIN_BLKSZ, &blk,
370                     NULL, txg);
371
372                 if (error == 0)
373                         zil_init_log_chain(zilog, &blk);
374         }
375
376         /*
377          * Allocate a log write buffer (lwb) for the first log block.
378          */
379         if (error == 0) {
380                 lwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
381                 lwb->lwb_zilog = zilog;
382                 lwb->lwb_blk = blk;
383                 lwb->lwb_nused = 0;
384                 lwb->lwb_sz = BP_GET_LSIZE(&lwb->lwb_blk);
385                 lwb->lwb_buf = zio_buf_alloc(lwb->lwb_sz);
386                 lwb->lwb_max_txg = txg;
387                 lwb->lwb_zio = NULL;
388
389                 mutex_enter(&zilog->zl_lock);
390                 list_insert_tail(&zilog->zl_lwb_list, lwb);
391                 mutex_exit(&zilog->zl_lock);
392         }
393
394         /*
395          * If we just allocated the first log block, commit our transaction
396          * and wait for zil_sync() to stuff the block poiner into zh_log.
397          * (zh is part of the MOS, so we cannot modify it in open context.)
398          */
399         if (tx != NULL) {
400                 dmu_tx_commit(tx);
401                 txg_wait_synced(zilog->zl_dmu_pool, txg);
402         }
403
404         ASSERT(bcmp(&blk, &zh->zh_log, sizeof (blk)) == 0);
405 }
406
407 /*
408  * In one tx, free all log blocks and clear the log header.
409  * If keep_first is set, then we're replaying a log with no content.
410  * We want to keep the first block, however, so that the first
411  * synchronous transaction doesn't require a txg_wait_synced()
412  * in zil_create().  We don't need to txg_wait_synced() here either
413  * when keep_first is set, because both zil_create() and zil_destroy()
414  * will wait for any in-progress destroys to complete.
415  */
416 void
417 zil_destroy(zilog_t *zilog, boolean_t keep_first)
418 {
419         const zil_header_t *zh = zilog->zl_header;
420         lwb_t *lwb;
421         dmu_tx_t *tx;
422         uint64_t txg;
423
424         /*
425          * Wait for any previous destroy to complete.
426          */
427         txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
428
429         if (BP_IS_HOLE(&zh->zh_log))
430                 return;
431
432         tx = dmu_tx_create(zilog->zl_os);
433         (void) dmu_tx_assign(tx, TXG_WAIT);
434         dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
435         txg = dmu_tx_get_txg(tx);
436
437         mutex_enter(&zilog->zl_lock);
438
439         /*
440          * It is possible for the ZIL to get the previously mounted zilog
441          * structure of the same dataset if quickly remounted and the dbuf
442          * eviction has not completed. In this case we can see a non
443          * empty lwb list and keep_first will be set. We fix this by
444          * clearing the keep_first. This will be slower but it's very rare.
445          */
446         if (!list_is_empty(&zilog->zl_lwb_list) && keep_first)
447                 keep_first = B_FALSE;
448
449         ASSERT3U(zilog->zl_destroy_txg, <, txg);
450         zilog->zl_destroy_txg = txg;
451         zilog->zl_keep_first = keep_first;
452
453         if (!list_is_empty(&zilog->zl_lwb_list)) {
454                 ASSERT(zh->zh_claim_txg == 0);
455                 ASSERT(!keep_first);
456                 while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
457                         list_remove(&zilog->zl_lwb_list, lwb);
458                         if (lwb->lwb_buf != NULL)
459                                 zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
460                         zio_free_blk(zilog->zl_spa, &lwb->lwb_blk, txg);
461                         kmem_cache_free(zil_lwb_cache, lwb);
462                 }
463         } else {
464                 if (!keep_first) {
465                         (void) zil_parse(zilog, zil_free_log_block,
466                             zil_free_log_record, tx, zh->zh_claim_txg);
467                 }
468         }
469         mutex_exit(&zilog->zl_lock);
470
471         dmu_tx_commit(tx);
472 }
473
474 /*
475  * zil_rollback_destroy() is only called by the rollback code.
476  * We already have a syncing tx. Rollback has exclusive access to the
477  * dataset, so we don't have to worry about concurrent zil access.
478  * The actual freeing of any log blocks occurs in zil_sync() later in
479  * this txg syncing phase.
480  */
481 void
482 zil_rollback_destroy(zilog_t *zilog, dmu_tx_t *tx)
483 {
484         const zil_header_t *zh = zilog->zl_header;
485         uint64_t txg;
486
487         if (BP_IS_HOLE(&zh->zh_log))
488                 return;
489
490         txg = dmu_tx_get_txg(tx);
491         ASSERT3U(zilog->zl_destroy_txg, <, txg);
492         zilog->zl_destroy_txg = txg;
493         zilog->zl_keep_first = B_FALSE;
494
495         /*
496          * Ensure there's no outstanding ZIL IO.  No lwbs or just the
497          * unused one that allocated in advance is ok.
498          */
499         ASSERT(zilog->zl_lwb_list.list_head.list_next ==
500             zilog->zl_lwb_list.list_head.list_prev);
501         (void) zil_parse(zilog, zil_free_log_block, zil_free_log_record,
502             tx, zh->zh_claim_txg);
503 }
504
505 /*
506  * return true if the initial log block is not valid
507  */
508 static boolean_t
509 zil_empty(zilog_t *zilog)
510 {
511         const zil_header_t *zh = zilog->zl_header;
512         arc_buf_t *abuf = NULL;
513
514         if (BP_IS_HOLE(&zh->zh_log))
515                 return (B_TRUE);
516
517         if (zil_read_log_block(zilog, &zh->zh_log, &abuf) != 0)
518                 return (B_TRUE);
519
520         VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
521         return (B_FALSE);
522 }
523
524 int
525 zil_claim(char *osname, void *txarg)
526 {
527         dmu_tx_t *tx = txarg;
528         uint64_t first_txg = dmu_tx_get_txg(tx);
529         zilog_t *zilog;
530         zil_header_t *zh;
531         objset_t *os;
532         int error;
533
534         error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
535         if (error) {
536                 cmn_err(CE_WARN, "can't open objset for %s", osname);
537                 return (0);
538         }
539
540         zilog = dmu_objset_zil(os);
541         zh = zil_header_in_syncing_context(zilog);
542
543         /*
544          * Record here whether the zil has any records to replay.
545          * If the header block pointer is null or the block points
546          * to the stubby then we know there are no valid log records.
547          * We use the header to store this state as the the zilog gets
548          * freed later in dmu_objset_close().
549          * The flags (and the rest of the header fields) are cleared in
550          * zil_sync() as a result of a zil_destroy(), after replaying the log.
551          *
552          * Note, the intent log can be empty but still need the
553          * stubby to be claimed.
554          */
555         if (!zil_empty(zilog))
556                 zh->zh_flags |= ZIL_REPLAY_NEEDED;
557
558         /*
559          * Claim all log blocks if we haven't already done so, and remember
560          * the highest claimed sequence number.  This ensures that if we can
561          * read only part of the log now (e.g. due to a missing device),
562          * but we can read the entire log later, we will not try to replay
563          * or destroy beyond the last block we successfully claimed.
564          */
565         ASSERT3U(zh->zh_claim_txg, <=, first_txg);
566         if (zh->zh_claim_txg == 0 && !BP_IS_HOLE(&zh->zh_log)) {
567                 zh->zh_claim_txg = first_txg;
568                 zh->zh_claim_seq = zil_parse(zilog, zil_claim_log_block,
569                     zil_claim_log_record, tx, first_txg);
570                 dsl_dataset_dirty(dmu_objset_ds(os), tx);
571         }
572
573         ASSERT3U(first_txg, ==, (spa_last_synced_txg(zilog->zl_spa) + 1));
574         dmu_objset_close(os);
575         return (0);
576 }
577
578 /*
579  * Check the log by walking the log chain.
580  * Checksum errors are ok as they indicate the end of the chain.
581  * Any other error (no device or read failure) returns an error.
582  */
583 /* ARGSUSED */
584 int
585 zil_check_log_chain(char *osname, void *txarg)
586 {
587         zilog_t *zilog;
588         zil_header_t *zh;
589         blkptr_t blk;
590         arc_buf_t *abuf;
591         objset_t *os;
592         char *lrbuf;
593         zil_trailer_t *ztp;
594         int error;
595
596         error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
597         if (error) {
598                 cmn_err(CE_WARN, "can't open objset for %s", osname);
599                 return (0);
600         }
601
602         zilog = dmu_objset_zil(os);
603         zh = zil_header_in_syncing_context(zilog);
604         blk = zh->zh_log;
605         if (BP_IS_HOLE(&blk)) {
606                 dmu_objset_close(os);
607                 return (0); /* no chain */
608         }
609
610         for (;;) {
611                 error = zil_read_log_block(zilog, &blk, &abuf);
612                 if (error)
613                         break;
614                 lrbuf = abuf->b_data;
615                 ztp = (zil_trailer_t *)(lrbuf + BP_GET_LSIZE(&blk)) - 1;
616                 blk = ztp->zit_next_blk;
617                 VERIFY(arc_buf_remove_ref(abuf, &abuf) == 1);
618         }
619         dmu_objset_close(os);
620         if (error == ECKSUM)
621                 return (0); /* normal end of chain */
622         return (error);
623 }
624
625 /*
626  * Clear a log chain
627  */
628 /* ARGSUSED */
629 int
630 zil_clear_log_chain(char *osname, void *txarg)
631 {
632         zilog_t *zilog;
633         zil_header_t *zh;
634         objset_t *os;
635         dmu_tx_t *tx;
636         int error;
637
638         error = dmu_objset_open(osname, DMU_OST_ANY, DS_MODE_USER, &os);
639         if (error) {
640                 cmn_err(CE_WARN, "can't open objset for %s", osname);
641                 return (0);
642         }
643
644         zilog = dmu_objset_zil(os);
645         tx = dmu_tx_create(zilog->zl_os);
646         (void) dmu_tx_assign(tx, TXG_WAIT);
647         zh = zil_header_in_syncing_context(zilog);
648         BP_ZERO(&zh->zh_log);
649         dsl_dataset_dirty(dmu_objset_ds(os), tx);
650         dmu_tx_commit(tx);
651         dmu_objset_close(os);
652         return (0);
653 }
654
655 static int
656 zil_vdev_compare(const void *x1, const void *x2)
657 {
658         uint64_t v1 = ((zil_vdev_node_t *)x1)->zv_vdev;
659         uint64_t v2 = ((zil_vdev_node_t *)x2)->zv_vdev;
660
661         if (v1 < v2)
662                 return (-1);
663         if (v1 > v2)
664                 return (1);
665
666         return (0);
667 }
668
669 void
670 zil_add_block(zilog_t *zilog, blkptr_t *bp)
671 {
672         avl_tree_t *t = &zilog->zl_vdev_tree;
673         avl_index_t where;
674         zil_vdev_node_t *zv, zvsearch;
675         int ndvas = BP_GET_NDVAS(bp);
676         int i;
677
678         if (zfs_nocacheflush)
679                 return;
680
681         ASSERT(zilog->zl_writer);
682
683         /*
684          * Even though we're zl_writer, we still need a lock because the
685          * zl_get_data() callbacks may have dmu_sync() done callbacks
686          * that will run concurrently.
687          */
688         mutex_enter(&zilog->zl_vdev_lock);
689         for (i = 0; i < ndvas; i++) {
690                 zvsearch.zv_vdev = DVA_GET_VDEV(&bp->blk_dva[i]);
691                 if (avl_find(t, &zvsearch, &where) == NULL) {
692                         zv = kmem_alloc(sizeof (*zv), KM_SLEEP);
693                         zv->zv_vdev = zvsearch.zv_vdev;
694                         avl_insert(t, zv, where);
695                 }
696         }
697         mutex_exit(&zilog->zl_vdev_lock);
698 }
699
700 void
701 zil_flush_vdevs(zilog_t *zilog)
702 {
703         spa_t *spa = zilog->zl_spa;
704         avl_tree_t *t = &zilog->zl_vdev_tree;
705         void *cookie = NULL;
706         zil_vdev_node_t *zv;
707         zio_t *zio;
708
709         ASSERT(zilog->zl_writer);
710
711         /*
712          * We don't need zl_vdev_lock here because we're the zl_writer,
713          * and all zl_get_data() callbacks are done.
714          */
715         if (avl_numnodes(t) == 0)
716                 return;
717
718         spa_config_enter(spa, SCL_STATE, FTAG, RW_READER);
719
720         zio = zio_root(spa, NULL, NULL, ZIO_FLAG_CANFAIL);
721
722         while ((zv = avl_destroy_nodes(t, &cookie)) != NULL) {
723                 vdev_t *vd = vdev_lookup_top(spa, zv->zv_vdev);
724                 if (vd != NULL)
725                         zio_flush(zio, vd);
726                 kmem_free(zv, sizeof (*zv));
727         }
728
729         /*
730          * Wait for all the flushes to complete.  Not all devices actually
731          * support the DKIOCFLUSHWRITECACHE ioctl, so it's OK if it fails.
732          */
733         (void) zio_wait(zio);
734
735         spa_config_exit(spa, SCL_STATE, FTAG);
736 }
737
738 /*
739  * Function called when a log block write completes
740  */
741 static void
742 zil_lwb_write_done(zio_t *zio)
743 {
744         lwb_t *lwb = zio->io_private;
745         zilog_t *zilog = lwb->lwb_zilog;
746
747         ASSERT(BP_GET_COMPRESS(zio->io_bp) == ZIO_COMPRESS_OFF);
748         ASSERT(BP_GET_CHECKSUM(zio->io_bp) == ZIO_CHECKSUM_ZILOG);
749         ASSERT(BP_GET_TYPE(zio->io_bp) == DMU_OT_INTENT_LOG);
750         ASSERT(BP_GET_LEVEL(zio->io_bp) == 0);
751         ASSERT(BP_GET_BYTEORDER(zio->io_bp) == ZFS_HOST_BYTEORDER);
752         ASSERT(!BP_IS_GANG(zio->io_bp));
753         ASSERT(!BP_IS_HOLE(zio->io_bp));
754         ASSERT(zio->io_bp->blk_fill == 0);
755
756         /*
757          * Now that we've written this log block, we have a stable pointer
758          * to the next block in the chain, so it's OK to let the txg in
759          * which we allocated the next block sync.
760          */
761         txg_rele_to_sync(&lwb->lwb_txgh);
762
763         zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
764         mutex_enter(&zilog->zl_lock);
765         lwb->lwb_buf = NULL;
766         if (zio->io_error)
767                 zilog->zl_log_error = B_TRUE;
768         mutex_exit(&zilog->zl_lock);
769 }
770
771 /*
772  * Initialize the io for a log block.
773  */
774 static void
775 zil_lwb_write_init(zilog_t *zilog, lwb_t *lwb)
776 {
777         zbookmark_t zb;
778
779         zb.zb_objset = lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_OBJSET];
780         zb.zb_object = 0;
781         zb.zb_level = -1;
782         zb.zb_blkid = lwb->lwb_blk.blk_cksum.zc_word[ZIL_ZC_SEQ];
783
784         if (zilog->zl_root_zio == NULL) {
785                 zilog->zl_root_zio = zio_root(zilog->zl_spa, NULL, NULL,
786                     ZIO_FLAG_CANFAIL);
787         }
788         if (lwb->lwb_zio == NULL) {
789                 lwb->lwb_zio = zio_rewrite(zilog->zl_root_zio, zilog->zl_spa,
790                     0, &lwb->lwb_blk, lwb->lwb_buf,
791                     lwb->lwb_sz, zil_lwb_write_done, lwb,
792                     ZIO_PRIORITY_LOG_WRITE, ZIO_FLAG_CANFAIL, &zb);
793         }
794 }
795
796 /*
797  * Start a log block write and advance to the next log block.
798  * Calls are serialized.
799  */
800 static lwb_t *
801 zil_lwb_write_start(zilog_t *zilog, lwb_t *lwb)
802 {
803         lwb_t *nlwb;
804         zil_trailer_t *ztp = (zil_trailer_t *)(lwb->lwb_buf + lwb->lwb_sz) - 1;
805         spa_t *spa = zilog->zl_spa;
806         blkptr_t *bp = &ztp->zit_next_blk;
807         uint64_t txg;
808         uint64_t zil_blksz;
809         int error;
810
811         ASSERT(lwb->lwb_nused <= ZIL_BLK_DATA_SZ(lwb));
812
813         /*
814          * Allocate the next block and save its address in this block
815          * before writing it in order to establish the log chain.
816          * Note that if the allocation of nlwb synced before we wrote
817          * the block that points at it (lwb), we'd leak it if we crashed.
818          * Therefore, we don't do txg_rele_to_sync() until zil_lwb_write_done().
819          */
820         txg = txg_hold_open(zilog->zl_dmu_pool, &lwb->lwb_txgh);
821         txg_rele_to_quiesce(&lwb->lwb_txgh);
822
823         /*
824          * Pick a ZIL blocksize. We request a size that is the
825          * maximum of the previous used size, the current used size and
826          * the amount waiting in the queue.
827          */
828         zil_blksz = MAX(zilog->zl_prev_used,
829             zilog->zl_cur_used + sizeof (*ztp));
830         zil_blksz = MAX(zil_blksz, zilog->zl_itx_list_sz + sizeof (*ztp));
831         zil_blksz = P2ROUNDUP_TYPED(zil_blksz, ZIL_MIN_BLKSZ, uint64_t);
832         if (zil_blksz > ZIL_MAX_BLKSZ)
833                 zil_blksz = ZIL_MAX_BLKSZ;
834
835         BP_ZERO(bp);
836         /* pass the old blkptr in order to spread log blocks across devs */
837         error = zio_alloc_blk(spa, zil_blksz, bp, &lwb->lwb_blk, txg);
838         if (error) {
839                 dmu_tx_t *tx = dmu_tx_create_assigned(zilog->zl_dmu_pool, txg);
840
841                 /*
842                  * We dirty the dataset to ensure that zil_sync() will
843                  * be called to remove this lwb from our zl_lwb_list.
844                  * Failing to do so, may leave an lwb with a NULL lwb_buf
845                  * hanging around on the zl_lwb_list.
846                  */
847                 dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
848                 dmu_tx_commit(tx);
849
850                 /*
851                  * Since we've just experienced an allocation failure so we
852                  * terminate the current lwb and send it on its way.
853                  */
854                 ztp->zit_pad = 0;
855                 ztp->zit_nused = lwb->lwb_nused;
856                 ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
857                 zio_nowait(lwb->lwb_zio);
858
859                 /*
860                  * By returning NULL the caller will call tx_wait_synced()
861                  */
862                 return (NULL);
863         }
864
865         ASSERT3U(bp->blk_birth, ==, txg);
866         ztp->zit_pad = 0;
867         ztp->zit_nused = lwb->lwb_nused;
868         ztp->zit_bt.zbt_cksum = lwb->lwb_blk.blk_cksum;
869         bp->blk_cksum = lwb->lwb_blk.blk_cksum;
870         bp->blk_cksum.zc_word[ZIL_ZC_SEQ]++;
871
872         /*
873          * Allocate a new log write buffer (lwb).
874          */
875         nlwb = kmem_cache_alloc(zil_lwb_cache, KM_SLEEP);
876
877         nlwb->lwb_zilog = zilog;
878         nlwb->lwb_blk = *bp;
879         nlwb->lwb_nused = 0;
880         nlwb->lwb_sz = BP_GET_LSIZE(&nlwb->lwb_blk);
881         nlwb->lwb_buf = zio_buf_alloc(nlwb->lwb_sz);
882         nlwb->lwb_max_txg = txg;
883         nlwb->lwb_zio = NULL;
884
885         /*
886          * Put new lwb at the end of the log chain
887          */
888         mutex_enter(&zilog->zl_lock);
889         list_insert_tail(&zilog->zl_lwb_list, nlwb);
890         mutex_exit(&zilog->zl_lock);
891
892         /* Record the block for later vdev flushing */
893         zil_add_block(zilog, &lwb->lwb_blk);
894
895         /*
896          * kick off the write for the old log block
897          */
898         dprintf_bp(&lwb->lwb_blk, "lwb %p txg %llu: ", lwb, txg);
899         ASSERT(lwb->lwb_zio);
900         zio_nowait(lwb->lwb_zio);
901
902         return (nlwb);
903 }
904
905 static lwb_t *
906 zil_lwb_commit(zilog_t *zilog, itx_t *itx, lwb_t *lwb)
907 {
908         lr_t *lrc = &itx->itx_lr; /* common log record */
909         lr_write_t *lr = (lr_write_t *)lrc;
910         uint64_t txg = lrc->lrc_txg;
911         uint64_t reclen = lrc->lrc_reclen;
912         uint64_t dlen;
913
914         if (lwb == NULL)
915                 return (NULL);
916         ASSERT(lwb->lwb_buf != NULL);
917
918         if (lrc->lrc_txtype == TX_WRITE && itx->itx_wr_state == WR_NEED_COPY)
919                 dlen = P2ROUNDUP_TYPED(
920                     lr->lr_length, sizeof (uint64_t), uint64_t);
921         else
922                 dlen = 0;
923
924         zilog->zl_cur_used += (reclen + dlen);
925
926         zil_lwb_write_init(zilog, lwb);
927
928         /*
929          * If this record won't fit in the current log block, start a new one.
930          */
931         if (lwb->lwb_nused + reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
932                 lwb = zil_lwb_write_start(zilog, lwb);
933                 if (lwb == NULL)
934                         return (NULL);
935                 zil_lwb_write_init(zilog, lwb);
936                 ASSERT(lwb->lwb_nused == 0);
937                 if (reclen + dlen > ZIL_BLK_DATA_SZ(lwb)) {
938                         txg_wait_synced(zilog->zl_dmu_pool, txg);
939                         return (lwb);
940                 }
941         }
942
943         /*
944          * Update the lrc_seq, to be log record sequence number. See zil.h
945          * Then copy the record to the log buffer.
946          */
947         lrc->lrc_seq = ++zilog->zl_lr_seq; /* we are single threaded */
948         bcopy(lrc, lwb->lwb_buf + lwb->lwb_nused, reclen);
949
950         /*
951          * If it's a write, fetch the data or get its blkptr as appropriate.
952          */
953         if (lrc->lrc_txtype == TX_WRITE) {
954                 if (txg > spa_freeze_txg(zilog->zl_spa))
955                         txg_wait_synced(zilog->zl_dmu_pool, txg);
956                 if (itx->itx_wr_state != WR_COPIED) {
957                         char *dbuf;
958                         int error;
959
960                         /* alignment is guaranteed */
961                         lr = (lr_write_t *)(lwb->lwb_buf + lwb->lwb_nused);
962                         if (dlen) {
963                                 ASSERT(itx->itx_wr_state == WR_NEED_COPY);
964                                 dbuf = lwb->lwb_buf + lwb->lwb_nused + reclen;
965                                 lr->lr_common.lrc_reclen += dlen;
966                         } else {
967                                 ASSERT(itx->itx_wr_state == WR_INDIRECT);
968                                 dbuf = NULL;
969                         }
970                         error = zilog->zl_get_data(
971                             itx->itx_private, lr, dbuf, lwb->lwb_zio);
972                         if (error) {
973                                 ASSERT(error == ENOENT || error == EEXIST ||
974                                     error == EALREADY);
975                                 return (lwb);
976                         }
977                 }
978         }
979
980         lwb->lwb_nused += reclen + dlen;
981         lwb->lwb_max_txg = MAX(lwb->lwb_max_txg, txg);
982         ASSERT3U(lwb->lwb_nused, <=, ZIL_BLK_DATA_SZ(lwb));
983         ASSERT3U(P2PHASE(lwb->lwb_nused, sizeof (uint64_t)), ==, 0);
984
985         return (lwb);
986 }
987
988 itx_t *
989 zil_itx_create(uint64_t txtype, size_t lrsize)
990 {
991         itx_t *itx;
992
993         lrsize = P2ROUNDUP_TYPED(lrsize, sizeof (uint64_t), size_t);
994
995         itx = kmem_alloc(offsetof(itx_t, itx_lr) + lrsize, KM_SLEEP);
996         itx->itx_lr.lrc_txtype = txtype;
997         itx->itx_lr.lrc_reclen = lrsize;
998         itx->itx_sod = lrsize; /* if write & WR_NEED_COPY will be increased */
999         itx->itx_lr.lrc_seq = 0;        /* defensive */
1000
1001         return (itx);
1002 }
1003
1004 uint64_t
1005 zil_itx_assign(zilog_t *zilog, itx_t *itx, dmu_tx_t *tx)
1006 {
1007         uint64_t seq;
1008
1009         ASSERT(itx->itx_lr.lrc_seq == 0);
1010
1011         mutex_enter(&zilog->zl_lock);
1012         list_insert_tail(&zilog->zl_itx_list, itx);
1013         zilog->zl_itx_list_sz += itx->itx_sod;
1014         itx->itx_lr.lrc_txg = dmu_tx_get_txg(tx);
1015         itx->itx_lr.lrc_seq = seq = ++zilog->zl_itx_seq;
1016         mutex_exit(&zilog->zl_lock);
1017
1018         return (seq);
1019 }
1020
1021 /*
1022  * Free up all in-memory intent log transactions that have now been synced.
1023  */
1024 static void
1025 zil_itx_clean(zilog_t *zilog)
1026 {
1027         uint64_t synced_txg = spa_last_synced_txg(zilog->zl_spa);
1028         uint64_t freeze_txg = spa_freeze_txg(zilog->zl_spa);
1029         list_t clean_list;
1030         itx_t *itx;
1031
1032         list_create(&clean_list, sizeof (itx_t), offsetof(itx_t, itx_node));
1033
1034         mutex_enter(&zilog->zl_lock);
1035         /* wait for a log writer to finish walking list */
1036         while (zilog->zl_writer) {
1037                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1038         }
1039
1040         /*
1041          * Move the sync'd log transactions to a separate list so we can call
1042          * kmem_free without holding the zl_lock.
1043          *
1044          * There is no need to set zl_writer as we don't drop zl_lock here
1045          */
1046         while ((itx = list_head(&zilog->zl_itx_list)) != NULL &&
1047             itx->itx_lr.lrc_txg <= MIN(synced_txg, freeze_txg)) {
1048                 list_remove(&zilog->zl_itx_list, itx);
1049                 zilog->zl_itx_list_sz -= itx->itx_sod;
1050                 list_insert_tail(&clean_list, itx);
1051         }
1052         cv_broadcast(&zilog->zl_cv_writer);
1053         mutex_exit(&zilog->zl_lock);
1054
1055         /* destroy sync'd log transactions */
1056         while ((itx = list_head(&clean_list)) != NULL) {
1057                 list_remove(&clean_list, itx);
1058                 kmem_free(itx, offsetof(itx_t, itx_lr)
1059                     + itx->itx_lr.lrc_reclen);
1060         }
1061         list_destroy(&clean_list);
1062 }
1063
1064 /*
1065  * If there are any in-memory intent log transactions which have now been
1066  * synced then start up a taskq to free them.
1067  */
1068 void
1069 zil_clean(zilog_t *zilog)
1070 {
1071         itx_t *itx;
1072
1073         mutex_enter(&zilog->zl_lock);
1074         itx = list_head(&zilog->zl_itx_list);
1075         if ((itx != NULL) &&
1076             (itx->itx_lr.lrc_txg <= spa_last_synced_txg(zilog->zl_spa))) {
1077                 (void) taskq_dispatch(zilog->zl_clean_taskq,
1078                     (task_func_t *)zil_itx_clean, zilog, TQ_SLEEP);
1079         }
1080         mutex_exit(&zilog->zl_lock);
1081 }
1082
1083 static void
1084 zil_commit_writer(zilog_t *zilog, uint64_t seq, uint64_t foid)
1085 {
1086         uint64_t txg;
1087         uint64_t commit_seq = 0;
1088         itx_t *itx, *itx_next = (itx_t *)-1;
1089         lwb_t *lwb;
1090         spa_t *spa;
1091
1092         zilog->zl_writer = B_TRUE;
1093         ASSERT(zilog->zl_root_zio == NULL);
1094         spa = zilog->zl_spa;
1095
1096         if (zilog->zl_suspend) {
1097                 lwb = NULL;
1098         } else {
1099                 lwb = list_tail(&zilog->zl_lwb_list);
1100                 if (lwb == NULL) {
1101                         /*
1102                          * Return if there's nothing to flush before we
1103                          * dirty the fs by calling zil_create()
1104                          */
1105                         if (list_is_empty(&zilog->zl_itx_list)) {
1106                                 zilog->zl_writer = B_FALSE;
1107                                 return;
1108                         }
1109                         mutex_exit(&zilog->zl_lock);
1110                         zil_create(zilog);
1111                         mutex_enter(&zilog->zl_lock);
1112                         lwb = list_tail(&zilog->zl_lwb_list);
1113                 }
1114         }
1115
1116         /* Loop through in-memory log transactions filling log blocks. */
1117         DTRACE_PROBE1(zil__cw1, zilog_t *, zilog);
1118         for (;;) {
1119                 /*
1120                  * Find the next itx to push:
1121                  * Push all transactions related to specified foid and all
1122                  * other transactions except TX_WRITE, TX_TRUNCATE,
1123                  * TX_SETATTR and TX_ACL for all other files.
1124                  */
1125                 if (itx_next != (itx_t *)-1)
1126                         itx = itx_next;
1127                 else
1128                         itx = list_head(&zilog->zl_itx_list);
1129                 for (; itx != NULL; itx = list_next(&zilog->zl_itx_list, itx)) {
1130                         if (foid == 0) /* push all foids? */
1131                                 break;
1132                         if (itx->itx_sync) /* push all O_[D]SYNC */
1133                                 break;
1134                         switch (itx->itx_lr.lrc_txtype) {
1135                         case TX_SETATTR:
1136                         case TX_WRITE:
1137                         case TX_TRUNCATE:
1138                         case TX_ACL:
1139                                 /* lr_foid is same offset for these records */
1140                                 if (((lr_write_t *)&itx->itx_lr)->lr_foid
1141                                     != foid) {
1142                                         continue; /* skip this record */
1143                                 }
1144                         }
1145                         break;
1146                 }
1147                 if (itx == NULL)
1148                         break;
1149
1150                 if ((itx->itx_lr.lrc_seq > seq) &&
1151                     ((lwb == NULL) || (lwb->lwb_nused == 0) ||
1152                     (lwb->lwb_nused + itx->itx_sod > ZIL_BLK_DATA_SZ(lwb)))) {
1153                         break;
1154                 }
1155
1156                 /*
1157                  * Save the next pointer.  Even though we soon drop
1158                  * zl_lock all threads that may change the list
1159                  * (another writer or zil_itx_clean) can't do so until
1160                  * they have zl_writer.
1161                  */
1162                 itx_next = list_next(&zilog->zl_itx_list, itx);
1163                 list_remove(&zilog->zl_itx_list, itx);
1164                 zilog->zl_itx_list_sz -= itx->itx_sod;
1165                 mutex_exit(&zilog->zl_lock);
1166                 txg = itx->itx_lr.lrc_txg;
1167                 ASSERT(txg);
1168
1169                 if (txg > spa_last_synced_txg(spa) ||
1170                     txg > spa_freeze_txg(spa))
1171                         lwb = zil_lwb_commit(zilog, itx, lwb);
1172                 kmem_free(itx, offsetof(itx_t, itx_lr)
1173                     + itx->itx_lr.lrc_reclen);
1174                 mutex_enter(&zilog->zl_lock);
1175         }
1176         DTRACE_PROBE1(zil__cw2, zilog_t *, zilog);
1177         /* determine commit sequence number */
1178         itx = list_head(&zilog->zl_itx_list);
1179         if (itx)
1180                 commit_seq = itx->itx_lr.lrc_seq;
1181         else
1182                 commit_seq = zilog->zl_itx_seq;
1183         mutex_exit(&zilog->zl_lock);
1184
1185         /* write the last block out */
1186         if (lwb != NULL && lwb->lwb_zio != NULL)
1187                 lwb = zil_lwb_write_start(zilog, lwb);
1188
1189         zilog->zl_prev_used = zilog->zl_cur_used;
1190         zilog->zl_cur_used = 0;
1191
1192         /*
1193          * Wait if necessary for the log blocks to be on stable storage.
1194          */
1195         if (zilog->zl_root_zio) {
1196                 DTRACE_PROBE1(zil__cw3, zilog_t *, zilog);
1197                 (void) zio_wait(zilog->zl_root_zio);
1198                 zilog->zl_root_zio = NULL;
1199                 DTRACE_PROBE1(zil__cw4, zilog_t *, zilog);
1200                 zil_flush_vdevs(zilog);
1201         }
1202
1203         if (zilog->zl_log_error || lwb == NULL) {
1204                 zilog->zl_log_error = 0;
1205                 txg_wait_synced(zilog->zl_dmu_pool, 0);
1206         }
1207
1208         mutex_enter(&zilog->zl_lock);
1209         zilog->zl_writer = B_FALSE;
1210
1211         ASSERT3U(commit_seq, >=, zilog->zl_commit_seq);
1212         zilog->zl_commit_seq = commit_seq;
1213 }
1214
1215 /*
1216  * Push zfs transactions to stable storage up to the supplied sequence number.
1217  * If foid is 0 push out all transactions, otherwise push only those
1218  * for that file or might have been used to create that file.
1219  */
1220 void
1221 zil_commit(zilog_t *zilog, uint64_t seq, uint64_t foid)
1222 {
1223         if (zilog == NULL || seq == 0)
1224                 return;
1225
1226         mutex_enter(&zilog->zl_lock);
1227
1228         seq = MIN(seq, zilog->zl_itx_seq);      /* cap seq at largest itx seq */
1229
1230         while (zilog->zl_writer) {
1231                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1232                 if (seq < zilog->zl_commit_seq) {
1233                         mutex_exit(&zilog->zl_lock);
1234                         return;
1235                 }
1236         }
1237         zil_commit_writer(zilog, seq, foid); /* drops zl_lock */
1238         /* wake up others waiting on the commit */
1239         cv_broadcast(&zilog->zl_cv_writer);
1240         mutex_exit(&zilog->zl_lock);
1241 }
1242
1243 /*
1244  * Called in syncing context to free committed log blocks and update log header.
1245  */
1246 void
1247 zil_sync(zilog_t *zilog, dmu_tx_t *tx)
1248 {
1249         zil_header_t *zh = zil_header_in_syncing_context(zilog);
1250         uint64_t txg = dmu_tx_get_txg(tx);
1251         spa_t *spa = zilog->zl_spa;
1252         lwb_t *lwb;
1253
1254         mutex_enter(&zilog->zl_lock);
1255
1256         ASSERT(zilog->zl_stop_sync == 0);
1257
1258         zh->zh_replay_seq = zilog->zl_replay_seq[txg & TXG_MASK];
1259
1260         if (zilog->zl_destroy_txg == txg) {
1261                 blkptr_t blk = zh->zh_log;
1262
1263                 ASSERT(list_head(&zilog->zl_lwb_list) == NULL);
1264                 ASSERT(spa_sync_pass(spa) == 1);
1265
1266                 bzero(zh, sizeof (zil_header_t));
1267                 bzero(zilog->zl_replay_seq, sizeof (zilog->zl_replay_seq));
1268
1269                 if (zilog->zl_keep_first) {
1270                         /*
1271                          * If this block was part of log chain that couldn't
1272                          * be claimed because a device was missing during
1273                          * zil_claim(), but that device later returns,
1274                          * then this block could erroneously appear valid.
1275                          * To guard against this, assign a new GUID to the new
1276                          * log chain so it doesn't matter what blk points to.
1277                          */
1278                         zil_init_log_chain(zilog, &blk);
1279                         zh->zh_log = blk;
1280                 }
1281         }
1282
1283         for (;;) {
1284                 lwb = list_head(&zilog->zl_lwb_list);
1285                 if (lwb == NULL) {
1286                         mutex_exit(&zilog->zl_lock);
1287                         return;
1288                 }
1289                 zh->zh_log = lwb->lwb_blk;
1290                 if (lwb->lwb_buf != NULL || lwb->lwb_max_txg > txg)
1291                         break;
1292                 list_remove(&zilog->zl_lwb_list, lwb);
1293                 zio_free_blk(spa, &lwb->lwb_blk, txg);
1294                 kmem_cache_free(zil_lwb_cache, lwb);
1295
1296                 /*
1297                  * If we don't have anything left in the lwb list then
1298                  * we've had an allocation failure and we need to zero
1299                  * out the zil_header blkptr so that we don't end
1300                  * up freeing the same block twice.
1301                  */
1302                 if (list_head(&zilog->zl_lwb_list) == NULL)
1303                         BP_ZERO(&zh->zh_log);
1304         }
1305         mutex_exit(&zilog->zl_lock);
1306 }
1307
1308 void
1309 zil_init(void)
1310 {
1311         zil_lwb_cache = kmem_cache_create("zil_lwb_cache",
1312             sizeof (struct lwb), 0, NULL, NULL, NULL, NULL, NULL, 0);
1313 }
1314
1315 void
1316 zil_fini(void)
1317 {
1318         kmem_cache_destroy(zil_lwb_cache);
1319 }
1320
1321 zilog_t *
1322 zil_alloc(objset_t *os, zil_header_t *zh_phys)
1323 {
1324         zilog_t *zilog;
1325
1326         zilog = kmem_zalloc(sizeof (zilog_t), KM_SLEEP);
1327
1328         zilog->zl_header = zh_phys;
1329         zilog->zl_os = os;
1330         zilog->zl_spa = dmu_objset_spa(os);
1331         zilog->zl_dmu_pool = dmu_objset_pool(os);
1332         zilog->zl_destroy_txg = TXG_INITIAL - 1;
1333
1334         mutex_init(&zilog->zl_lock, NULL, MUTEX_DEFAULT, NULL);
1335
1336         list_create(&zilog->zl_itx_list, sizeof (itx_t),
1337             offsetof(itx_t, itx_node));
1338
1339         list_create(&zilog->zl_lwb_list, sizeof (lwb_t),
1340             offsetof(lwb_t, lwb_node));
1341
1342         mutex_init(&zilog->zl_vdev_lock, NULL, MUTEX_DEFAULT, NULL);
1343
1344         avl_create(&zilog->zl_vdev_tree, zil_vdev_compare,
1345             sizeof (zil_vdev_node_t), offsetof(zil_vdev_node_t, zv_node));
1346
1347         cv_init(&zilog->zl_cv_writer, NULL, CV_DEFAULT, NULL);
1348         cv_init(&zilog->zl_cv_suspend, NULL, CV_DEFAULT, NULL);
1349
1350         return (zilog);
1351 }
1352
1353 void
1354 zil_free(zilog_t *zilog)
1355 {
1356         lwb_t *lwb;
1357
1358         zilog->zl_stop_sync = 1;
1359
1360         while ((lwb = list_head(&zilog->zl_lwb_list)) != NULL) {
1361                 list_remove(&zilog->zl_lwb_list, lwb);
1362                 if (lwb->lwb_buf != NULL)
1363                         zio_buf_free(lwb->lwb_buf, lwb->lwb_sz);
1364                 kmem_cache_free(zil_lwb_cache, lwb);
1365         }
1366         list_destroy(&zilog->zl_lwb_list);
1367
1368         avl_destroy(&zilog->zl_vdev_tree);
1369         mutex_destroy(&zilog->zl_vdev_lock);
1370
1371         ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1372         list_destroy(&zilog->zl_itx_list);
1373         mutex_destroy(&zilog->zl_lock);
1374
1375         cv_destroy(&zilog->zl_cv_writer);
1376         cv_destroy(&zilog->zl_cv_suspend);
1377
1378         kmem_free(zilog, sizeof (zilog_t));
1379 }
1380
1381 /*
1382  * Open an intent log.
1383  */
1384 zilog_t *
1385 zil_open(objset_t *os, zil_get_data_t *get_data)
1386 {
1387         zilog_t *zilog = dmu_objset_zil(os);
1388
1389         zilog->zl_get_data = get_data;
1390         zilog->zl_clean_taskq = taskq_create("zil_clean", 1, minclsyspri,
1391             2, 2, TASKQ_PREPOPULATE);
1392
1393         return (zilog);
1394 }
1395
1396 /*
1397  * Close an intent log.
1398  */
1399 void
1400 zil_close(zilog_t *zilog)
1401 {
1402         /*
1403          * If the log isn't already committed, mark the objset dirty
1404          * (so zil_sync() will be called) and wait for that txg to sync.
1405          */
1406         if (!zil_is_committed(zilog)) {
1407                 uint64_t txg;
1408                 dmu_tx_t *tx = dmu_tx_create(zilog->zl_os);
1409                 (void) dmu_tx_assign(tx, TXG_WAIT);
1410                 dsl_dataset_dirty(dmu_objset_ds(zilog->zl_os), tx);
1411                 txg = dmu_tx_get_txg(tx);
1412                 dmu_tx_commit(tx);
1413                 txg_wait_synced(zilog->zl_dmu_pool, txg);
1414         }
1415
1416         taskq_destroy(zilog->zl_clean_taskq);
1417         zilog->zl_clean_taskq = NULL;
1418         zilog->zl_get_data = NULL;
1419
1420         zil_itx_clean(zilog);
1421         ASSERT(list_head(&zilog->zl_itx_list) == NULL);
1422 }
1423
1424 /*
1425  * Suspend an intent log.  While in suspended mode, we still honor
1426  * synchronous semantics, but we rely on txg_wait_synced() to do it.
1427  * We suspend the log briefly when taking a snapshot so that the snapshot
1428  * contains all the data it's supposed to, and has an empty intent log.
1429  */
1430 int
1431 zil_suspend(zilog_t *zilog)
1432 {
1433         const zil_header_t *zh = zilog->zl_header;
1434
1435         mutex_enter(&zilog->zl_lock);
1436         if (zh->zh_flags & ZIL_REPLAY_NEEDED) {         /* unplayed log */
1437                 mutex_exit(&zilog->zl_lock);
1438                 return (EBUSY);
1439         }
1440         if (zilog->zl_suspend++ != 0) {
1441                 /*
1442                  * Someone else already began a suspend.
1443                  * Just wait for them to finish.
1444                  */
1445                 while (zilog->zl_suspending)
1446                         cv_wait(&zilog->zl_cv_suspend, &zilog->zl_lock);
1447                 mutex_exit(&zilog->zl_lock);
1448                 return (0);
1449         }
1450         zilog->zl_suspending = B_TRUE;
1451         mutex_exit(&zilog->zl_lock);
1452
1453         zil_commit(zilog, UINT64_MAX, 0);
1454
1455         /*
1456          * Wait for any in-flight log writes to complete.
1457          */
1458         mutex_enter(&zilog->zl_lock);
1459         while (zilog->zl_writer)
1460                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1461         mutex_exit(&zilog->zl_lock);
1462
1463         zil_destroy(zilog, B_FALSE);
1464
1465         mutex_enter(&zilog->zl_lock);
1466         zilog->zl_suspending = B_FALSE;
1467         cv_broadcast(&zilog->zl_cv_suspend);
1468         mutex_exit(&zilog->zl_lock);
1469
1470         return (0);
1471 }
1472
1473 void
1474 zil_resume(zilog_t *zilog)
1475 {
1476         mutex_enter(&zilog->zl_lock);
1477         ASSERT(zilog->zl_suspend != 0);
1478         zilog->zl_suspend--;
1479         mutex_exit(&zilog->zl_lock);
1480 }
1481
1482 typedef struct zil_replay_arg {
1483         objset_t        *zr_os;
1484         zil_replay_func_t **zr_replay;
1485         zil_replay_cleaner_t *zr_replay_cleaner;
1486         void            *zr_arg;
1487         uint64_t        *zr_txgp;
1488         boolean_t       zr_byteswap;
1489         char            *zr_lrbuf;
1490 } zil_replay_arg_t;
1491
1492 static void
1493 zil_replay_log_record(zilog_t *zilog, lr_t *lr, void *zra, uint64_t claim_txg)
1494 {
1495         zil_replay_arg_t *zr = zra;
1496         const zil_header_t *zh = zilog->zl_header;
1497         uint64_t reclen = lr->lrc_reclen;
1498         uint64_t txtype = lr->lrc_txtype;
1499         char *name;
1500         int pass, error, sunk;
1501
1502         if (zilog->zl_stop_replay)
1503                 return;
1504
1505         if (lr->lrc_txg < claim_txg)            /* already committed */
1506                 return;
1507
1508         if (lr->lrc_seq <= zh->zh_replay_seq)   /* already replayed */
1509                 return;
1510
1511         /* Strip case-insensitive bit, still present in log record */
1512         txtype &= ~TX_CI;
1513
1514         /*
1515          * Make a copy of the data so we can revise and extend it.
1516          */
1517         bcopy(lr, zr->zr_lrbuf, reclen);
1518
1519         /*
1520          * The log block containing this lr may have been byteswapped
1521          * so that we can easily examine common fields like lrc_txtype.
1522          * However, the log is a mix of different data types, and only the
1523          * replay vectors know how to byteswap their records.  Therefore, if
1524          * the lr was byteswapped, undo it before invoking the replay vector.
1525          */
1526         if (zr->zr_byteswap)
1527                 byteswap_uint64_array(zr->zr_lrbuf, reclen);
1528
1529         /*
1530          * If this is a TX_WRITE with a blkptr, suck in the data.
1531          */
1532         if (txtype == TX_WRITE && reclen == sizeof (lr_write_t)) {
1533                 lr_write_t *lrw = (lr_write_t *)lr;
1534                 blkptr_t *wbp = &lrw->lr_blkptr;
1535                 uint64_t wlen = lrw->lr_length;
1536                 char *wbuf = zr->zr_lrbuf + reclen;
1537
1538                 if (BP_IS_HOLE(wbp)) {  /* compressed to a hole */
1539                         bzero(wbuf, wlen);
1540                 } else {
1541                         /*
1542                          * A subsequent write may have overwritten this block,
1543                          * in which case wbp may have been been freed and
1544                          * reallocated, and our read of wbp may fail with a
1545                          * checksum error.  We can safely ignore this because
1546                          * the later write will provide the correct data.
1547                          */
1548                         zbookmark_t zb;
1549
1550                         zb.zb_objset = dmu_objset_id(zilog->zl_os);
1551                         zb.zb_object = lrw->lr_foid;
1552                         zb.zb_level = -1;
1553                         zb.zb_blkid = lrw->lr_offset / BP_GET_LSIZE(wbp);
1554
1555                         (void) zio_wait(zio_read(NULL, zilog->zl_spa,
1556                             wbp, wbuf, BP_GET_LSIZE(wbp), NULL, NULL,
1557                             ZIO_PRIORITY_SYNC_READ,
1558                             ZIO_FLAG_CANFAIL | ZIO_FLAG_SPECULATIVE, &zb));
1559                         (void) memmove(wbuf, wbuf + lrw->lr_blkoff, wlen);
1560                 }
1561         }
1562
1563         /*
1564          * We must now do two things atomically: replay this log record,
1565          * and update the log header to reflect the fact that we did so.
1566          * We use the DMU's ability to assign into a specific txg to do this.
1567          */
1568         for (pass = 1, sunk = B_FALSE; /* CONSTANTCONDITION */; pass++) {
1569                 uint64_t replay_txg;
1570                 dmu_tx_t *replay_tx;
1571
1572                 replay_tx = dmu_tx_create(zr->zr_os);
1573                 error = dmu_tx_assign(replay_tx, TXG_WAIT);
1574                 if (error) {
1575                         dmu_tx_abort(replay_tx);
1576                         break;
1577                 }
1578
1579                 replay_txg = dmu_tx_get_txg(replay_tx);
1580
1581                 if (txtype == 0 || txtype >= TX_MAX_TYPE) {
1582                         error = EINVAL;
1583                 } else {
1584                         /*
1585                          * On the first pass, arrange for the replay vector
1586                          * to fail its dmu_tx_assign().  That's the only way
1587                          * to ensure that those code paths remain well tested.
1588                          *
1589                          * Only byteswap (if needed) on the 1st pass.
1590                          */
1591                         *zr->zr_txgp = replay_txg - (pass == 1);
1592                         error = zr->zr_replay[txtype](zr->zr_arg, zr->zr_lrbuf,
1593                             zr->zr_byteswap && pass == 1);
1594                         *zr->zr_txgp = TXG_NOWAIT;
1595                 }
1596
1597                 if (error == 0) {
1598                         dsl_dataset_dirty(dmu_objset_ds(zr->zr_os), replay_tx);
1599                         zilog->zl_replay_seq[replay_txg & TXG_MASK] =
1600                             lr->lrc_seq;
1601                 }
1602
1603                 dmu_tx_commit(replay_tx);
1604
1605                 if (!error)
1606                         return;
1607
1608                 /*
1609                  * The DMU's dnode layer doesn't see removes until the txg
1610                  * commits, so a subsequent claim can spuriously fail with
1611                  * EEXIST. So if we receive any error other than ERESTART
1612                  * we try syncing out any removes then retrying the
1613                  * transaction.
1614                  */
1615                 if (error != ERESTART && !sunk) {
1616                         if (zr->zr_replay_cleaner)
1617                                 zr->zr_replay_cleaner(zr->zr_arg);
1618                         txg_wait_synced(spa_get_dsl(zilog->zl_spa), 0);
1619                         sunk = B_TRUE;
1620                         continue; /* retry */
1621                 }
1622
1623                 if (error != ERESTART)
1624                         break;
1625
1626                 if (pass != 1)
1627                         txg_wait_open(spa_get_dsl(zilog->zl_spa),
1628                             replay_txg + 1);
1629
1630                 dprintf("pass %d, retrying\n", pass);
1631         }
1632
1633         ASSERT(error && error != ERESTART);
1634         name = kmem_alloc(MAXNAMELEN, KM_SLEEP);
1635         dmu_objset_name(zr->zr_os, name);
1636         cmn_err(CE_WARN, "ZFS replay transaction error %d, "
1637             "dataset %s, seq 0x%llx, txtype %llu %s\n",
1638             error, name, (u_longlong_t)lr->lrc_seq, (u_longlong_t)txtype,
1639             (lr->lrc_txtype & TX_CI) ? "CI" : "");
1640         zilog->zl_stop_replay = 1;
1641         kmem_free(name, MAXNAMELEN);
1642 }
1643
1644 /* ARGSUSED */
1645 static void
1646 zil_incr_blks(zilog_t *zilog, blkptr_t *bp, void *arg, uint64_t claim_txg)
1647 {
1648         zilog->zl_replay_blks++;
1649 }
1650
1651 /*
1652  * If this dataset has a non-empty intent log, replay it and destroy it.
1653  */
1654 void
1655 zil_replay(objset_t *os, void *arg, uint64_t *txgp,
1656         zil_replay_func_t *replay_func[TX_MAX_TYPE],
1657         zil_replay_cleaner_t *replay_cleaner)
1658 {
1659         zilog_t *zilog = dmu_objset_zil(os);
1660         const zil_header_t *zh = zilog->zl_header;
1661         zil_replay_arg_t zr;
1662
1663         if ((zh->zh_flags & ZIL_REPLAY_NEEDED) == 0) {
1664                 zil_destroy(zilog, B_TRUE);
1665                 return;
1666         }
1667         //printf("ZFS: Replaying ZIL on %s...\n", os->os->os_spa->spa_name);
1668
1669         zr.zr_os = os;
1670         zr.zr_replay = replay_func;
1671         zr.zr_replay_cleaner = replay_cleaner;
1672         zr.zr_arg = arg;
1673         zr.zr_txgp = txgp;
1674         zr.zr_byteswap = BP_SHOULD_BYTESWAP(&zh->zh_log);
1675         zr.zr_lrbuf = kmem_alloc(2 * SPA_MAXBLOCKSIZE, KM_SLEEP);
1676
1677         /*
1678          * Wait for in-progress removes to sync before starting replay.
1679          */
1680         txg_wait_synced(zilog->zl_dmu_pool, 0);
1681
1682         zilog->zl_stop_replay = 0;
1683         zilog->zl_replay_time = LBOLT;
1684         ASSERT(zilog->zl_replay_blks == 0);
1685         (void) zil_parse(zilog, zil_incr_blks, zil_replay_log_record, &zr,
1686             zh->zh_claim_txg);
1687         kmem_free(zr.zr_lrbuf, 2 * SPA_MAXBLOCKSIZE);
1688
1689         zil_destroy(zilog, B_FALSE);
1690         txg_wait_synced(zilog->zl_dmu_pool, zilog->zl_destroy_txg);
1691         //printf("ZFS: Replay of ZIL on %s finished.\n", os->os->os_spa->spa_name);
1692 }
1693
1694 /*
1695  * Report whether all transactions are committed
1696  */
1697 int
1698 zil_is_committed(zilog_t *zilog)
1699 {
1700         lwb_t *lwb;
1701         int ret;
1702
1703         mutex_enter(&zilog->zl_lock);
1704         while (zilog->zl_writer)
1705                 cv_wait(&zilog->zl_cv_writer, &zilog->zl_lock);
1706
1707         /* recent unpushed intent log transactions? */
1708         if (!list_is_empty(&zilog->zl_itx_list)) {
1709                 ret = B_FALSE;
1710                 goto out;
1711         }
1712
1713         /* intent log never used? */
1714         lwb = list_head(&zilog->zl_lwb_list);
1715         if (lwb == NULL) {
1716                 ret = B_TRUE;
1717                 goto out;
1718         }
1719
1720         /*
1721          * more than 1 log buffer means zil_sync() hasn't yet freed
1722          * entries after a txg has committed
1723          */
1724         if (list_next(&zilog->zl_lwb_list, lwb)) {
1725                 ret = B_FALSE;
1726                 goto out;
1727         }
1728
1729         ASSERT(zil_empty(zilog));
1730         ret = B_TRUE;
1731 out:
1732         cv_broadcast(&zilog->zl_cv_writer);
1733         mutex_exit(&zilog->zl_lock);
1734         return (ret);
1735 }