btrfs: fix memory leaks after failure to lookup checksums during inode logging
[linux/fpc-iii.git] / fs / btrfs / tree-log.c
blob3c090549ed07d60b47adbdb247b75a6f45f88c40
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2008 Oracle. All rights reserved.
4 */
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/blkdev.h>
9 #include <linux/list_sort.h>
10 #include <linux/iversion.h>
11 #include "misc.h"
12 #include "ctree.h"
13 #include "tree-log.h"
14 #include "disk-io.h"
15 #include "locking.h"
16 #include "print-tree.h"
17 #include "backref.h"
18 #include "compression.h"
19 #include "qgroup.h"
20 #include "inode-map.h"
22 /* magic values for the inode_only field in btrfs_log_inode:
24 * LOG_INODE_ALL means to log everything
25 * LOG_INODE_EXISTS means to log just enough to recreate the inode
26 * during log replay
28 enum {
29 LOG_INODE_ALL,
30 LOG_INODE_EXISTS,
31 LOG_OTHER_INODE,
32 LOG_OTHER_INODE_ALL,
36 * directory trouble cases
38 * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
39 * log, we must force a full commit before doing an fsync of the directory
40 * where the unlink was done.
41 * ---> record transid of last unlink/rename per directory
43 * mkdir foo/some_dir
44 * normal commit
45 * rename foo/some_dir foo2/some_dir
46 * mkdir foo/some_dir
47 * fsync foo/some_dir/some_file
49 * The fsync above will unlink the original some_dir without recording
50 * it in its new location (foo2). After a crash, some_dir will be gone
51 * unless the fsync of some_file forces a full commit
53 * 2) we must log any new names for any file or dir that is in the fsync
54 * log. ---> check inode while renaming/linking.
56 * 2a) we must log any new names for any file or dir during rename
57 * when the directory they are being removed from was logged.
58 * ---> check inode and old parent dir during rename
60 * 2a is actually the more important variant. With the extra logging
61 * a crash might unlink the old name without recreating the new one
63 * 3) after a crash, we must go through any directories with a link count
64 * of zero and redo the rm -rf
66 * mkdir f1/foo
67 * normal commit
68 * rm -rf f1/foo
69 * fsync(f1)
71 * The directory f1 was fully removed from the FS, but fsync was never
72 * called on f1, only its parent dir. After a crash the rm -rf must
73 * be replayed. This must be able to recurse down the entire
74 * directory tree. The inode link count fixup code takes care of the
75 * ugly details.
79 * stages for the tree walking. The first
80 * stage (0) is to only pin down the blocks we find
81 * the second stage (1) is to make sure that all the inodes
82 * we find in the log are created in the subvolume.
84 * The last stage is to deal with directories and links and extents
85 * and all the other fun semantics
87 enum {
88 LOG_WALK_PIN_ONLY,
89 LOG_WALK_REPLAY_INODES,
90 LOG_WALK_REPLAY_DIR_INDEX,
91 LOG_WALK_REPLAY_ALL,
94 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
95 struct btrfs_root *root, struct btrfs_inode *inode,
96 int inode_only,
97 const loff_t start,
98 const loff_t end,
99 struct btrfs_log_ctx *ctx);
100 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
101 struct btrfs_root *root,
102 struct btrfs_path *path, u64 objectid);
103 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
104 struct btrfs_root *root,
105 struct btrfs_root *log,
106 struct btrfs_path *path,
107 u64 dirid, int del_all);
110 * tree logging is a special write ahead log used to make sure that
111 * fsyncs and O_SYNCs can happen without doing full tree commits.
113 * Full tree commits are expensive because they require commonly
114 * modified blocks to be recowed, creating many dirty pages in the
115 * extent tree an 4x-6x higher write load than ext3.
117 * Instead of doing a tree commit on every fsync, we use the
118 * key ranges and transaction ids to find items for a given file or directory
119 * that have changed in this transaction. Those items are copied into
120 * a special tree (one per subvolume root), that tree is written to disk
121 * and then the fsync is considered complete.
123 * After a crash, items are copied out of the log-tree back into the
124 * subvolume tree. Any file data extents found are recorded in the extent
125 * allocation tree, and the log-tree freed.
127 * The log tree is read three times, once to pin down all the extents it is
128 * using in ram and once, once to create all the inodes logged in the tree
129 * and once to do all the other items.
133 * start a sub transaction and setup the log tree
134 * this increments the log tree writer count to make the people
135 * syncing the tree wait for us to finish
137 static int start_log_trans(struct btrfs_trans_handle *trans,
138 struct btrfs_root *root,
139 struct btrfs_log_ctx *ctx)
141 struct btrfs_fs_info *fs_info = root->fs_info;
142 int ret = 0;
144 mutex_lock(&root->log_mutex);
146 if (root->log_root) {
147 if (btrfs_need_log_full_commit(trans)) {
148 ret = -EAGAIN;
149 goto out;
152 if (!root->log_start_pid) {
153 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
154 root->log_start_pid = current->pid;
155 } else if (root->log_start_pid != current->pid) {
156 set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
158 } else {
159 mutex_lock(&fs_info->tree_log_mutex);
160 if (!fs_info->log_root_tree)
161 ret = btrfs_init_log_root_tree(trans, fs_info);
162 mutex_unlock(&fs_info->tree_log_mutex);
163 if (ret)
164 goto out;
166 ret = btrfs_add_log_tree(trans, root);
167 if (ret)
168 goto out;
170 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
171 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
172 root->log_start_pid = current->pid;
175 atomic_inc(&root->log_batch);
176 atomic_inc(&root->log_writers);
177 if (ctx) {
178 int index = root->log_transid % 2;
179 list_add_tail(&ctx->list, &root->log_ctxs[index]);
180 ctx->log_transid = root->log_transid;
183 out:
184 mutex_unlock(&root->log_mutex);
185 return ret;
189 * returns 0 if there was a log transaction running and we were able
190 * to join, or returns -ENOENT if there were not transactions
191 * in progress
193 static int join_running_log_trans(struct btrfs_root *root)
195 int ret = -ENOENT;
197 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
198 return ret;
200 mutex_lock(&root->log_mutex);
201 if (root->log_root) {
202 ret = 0;
203 atomic_inc(&root->log_writers);
205 mutex_unlock(&root->log_mutex);
206 return ret;
210 * This either makes the current running log transaction wait
211 * until you call btrfs_end_log_trans() or it makes any future
212 * log transactions wait until you call btrfs_end_log_trans()
214 void btrfs_pin_log_trans(struct btrfs_root *root)
216 mutex_lock(&root->log_mutex);
217 atomic_inc(&root->log_writers);
218 mutex_unlock(&root->log_mutex);
222 * indicate we're done making changes to the log tree
223 * and wake up anyone waiting to do a sync
225 void btrfs_end_log_trans(struct btrfs_root *root)
227 if (atomic_dec_and_test(&root->log_writers)) {
228 /* atomic_dec_and_test implies a barrier */
229 cond_wake_up_nomb(&root->log_writer_wait);
233 static int btrfs_write_tree_block(struct extent_buffer *buf)
235 return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
236 buf->start + buf->len - 1);
239 static void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
241 filemap_fdatawait_range(buf->pages[0]->mapping,
242 buf->start, buf->start + buf->len - 1);
246 * the walk control struct is used to pass state down the chain when
247 * processing the log tree. The stage field tells us which part
248 * of the log tree processing we are currently doing. The others
249 * are state fields used for that specific part
251 struct walk_control {
252 /* should we free the extent on disk when done? This is used
253 * at transaction commit time while freeing a log tree
255 int free;
257 /* should we write out the extent buffer? This is used
258 * while flushing the log tree to disk during a sync
260 int write;
262 /* should we wait for the extent buffer io to finish? Also used
263 * while flushing the log tree to disk for a sync
265 int wait;
267 /* pin only walk, we record which extents on disk belong to the
268 * log trees
270 int pin;
272 /* what stage of the replay code we're currently in */
273 int stage;
276 * Ignore any items from the inode currently being processed. Needs
277 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
278 * the LOG_WALK_REPLAY_INODES stage.
280 bool ignore_cur_inode;
282 /* the root we are currently replaying */
283 struct btrfs_root *replay_dest;
285 /* the trans handle for the current replay */
286 struct btrfs_trans_handle *trans;
288 /* the function that gets used to process blocks we find in the
289 * tree. Note the extent_buffer might not be up to date when it is
290 * passed in, and it must be checked or read if you need the data
291 * inside it
293 int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
294 struct walk_control *wc, u64 gen, int level);
298 * process_func used to pin down extents, write them or wait on them
300 static int process_one_buffer(struct btrfs_root *log,
301 struct extent_buffer *eb,
302 struct walk_control *wc, u64 gen, int level)
304 struct btrfs_fs_info *fs_info = log->fs_info;
305 int ret = 0;
308 * If this fs is mixed then we need to be able to process the leaves to
309 * pin down any logged extents, so we have to read the block.
311 if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
312 ret = btrfs_read_buffer(eb, gen, level, NULL);
313 if (ret)
314 return ret;
317 if (wc->pin)
318 ret = btrfs_pin_extent_for_log_replay(fs_info, eb->start,
319 eb->len);
321 if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
322 if (wc->pin && btrfs_header_level(eb) == 0)
323 ret = btrfs_exclude_logged_extents(eb);
324 if (wc->write)
325 btrfs_write_tree_block(eb);
326 if (wc->wait)
327 btrfs_wait_tree_block_writeback(eb);
329 return ret;
333 * Item overwrite used by replay and tree logging. eb, slot and key all refer
334 * to the src data we are copying out.
336 * root is the tree we are copying into, and path is a scratch
337 * path for use in this function (it should be released on entry and
338 * will be released on exit).
340 * If the key is already in the destination tree the existing item is
341 * overwritten. If the existing item isn't big enough, it is extended.
342 * If it is too large, it is truncated.
344 * If the key isn't in the destination yet, a new item is inserted.
346 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
347 struct btrfs_root *root,
348 struct btrfs_path *path,
349 struct extent_buffer *eb, int slot,
350 struct btrfs_key *key)
352 int ret;
353 u32 item_size;
354 u64 saved_i_size = 0;
355 int save_old_i_size = 0;
356 unsigned long src_ptr;
357 unsigned long dst_ptr;
358 int overwrite_root = 0;
359 bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
361 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
362 overwrite_root = 1;
364 item_size = btrfs_item_size_nr(eb, slot);
365 src_ptr = btrfs_item_ptr_offset(eb, slot);
367 /* look for the key in the destination tree */
368 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
369 if (ret < 0)
370 return ret;
372 if (ret == 0) {
373 char *src_copy;
374 char *dst_copy;
375 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
376 path->slots[0]);
377 if (dst_size != item_size)
378 goto insert;
380 if (item_size == 0) {
381 btrfs_release_path(path);
382 return 0;
384 dst_copy = kmalloc(item_size, GFP_NOFS);
385 src_copy = kmalloc(item_size, GFP_NOFS);
386 if (!dst_copy || !src_copy) {
387 btrfs_release_path(path);
388 kfree(dst_copy);
389 kfree(src_copy);
390 return -ENOMEM;
393 read_extent_buffer(eb, src_copy, src_ptr, item_size);
395 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
396 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
397 item_size);
398 ret = memcmp(dst_copy, src_copy, item_size);
400 kfree(dst_copy);
401 kfree(src_copy);
403 * they have the same contents, just return, this saves
404 * us from cowing blocks in the destination tree and doing
405 * extra writes that may not have been done by a previous
406 * sync
408 if (ret == 0) {
409 btrfs_release_path(path);
410 return 0;
414 * We need to load the old nbytes into the inode so when we
415 * replay the extents we've logged we get the right nbytes.
417 if (inode_item) {
418 struct btrfs_inode_item *item;
419 u64 nbytes;
420 u32 mode;
422 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
423 struct btrfs_inode_item);
424 nbytes = btrfs_inode_nbytes(path->nodes[0], item);
425 item = btrfs_item_ptr(eb, slot,
426 struct btrfs_inode_item);
427 btrfs_set_inode_nbytes(eb, item, nbytes);
430 * If this is a directory we need to reset the i_size to
431 * 0 so that we can set it up properly when replaying
432 * the rest of the items in this log.
434 mode = btrfs_inode_mode(eb, item);
435 if (S_ISDIR(mode))
436 btrfs_set_inode_size(eb, item, 0);
438 } else if (inode_item) {
439 struct btrfs_inode_item *item;
440 u32 mode;
443 * New inode, set nbytes to 0 so that the nbytes comes out
444 * properly when we replay the extents.
446 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
447 btrfs_set_inode_nbytes(eb, item, 0);
450 * If this is a directory we need to reset the i_size to 0 so
451 * that we can set it up properly when replaying the rest of
452 * the items in this log.
454 mode = btrfs_inode_mode(eb, item);
455 if (S_ISDIR(mode))
456 btrfs_set_inode_size(eb, item, 0);
458 insert:
459 btrfs_release_path(path);
460 /* try to insert the key into the destination tree */
461 path->skip_release_on_error = 1;
462 ret = btrfs_insert_empty_item(trans, root, path,
463 key, item_size);
464 path->skip_release_on_error = 0;
466 /* make sure any existing item is the correct size */
467 if (ret == -EEXIST || ret == -EOVERFLOW) {
468 u32 found_size;
469 found_size = btrfs_item_size_nr(path->nodes[0],
470 path->slots[0]);
471 if (found_size > item_size)
472 btrfs_truncate_item(path, item_size, 1);
473 else if (found_size < item_size)
474 btrfs_extend_item(path, item_size - found_size);
475 } else if (ret) {
476 return ret;
478 dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
479 path->slots[0]);
481 /* don't overwrite an existing inode if the generation number
482 * was logged as zero. This is done when the tree logging code
483 * is just logging an inode to make sure it exists after recovery.
485 * Also, don't overwrite i_size on directories during replay.
486 * log replay inserts and removes directory items based on the
487 * state of the tree found in the subvolume, and i_size is modified
488 * as it goes
490 if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
491 struct btrfs_inode_item *src_item;
492 struct btrfs_inode_item *dst_item;
494 src_item = (struct btrfs_inode_item *)src_ptr;
495 dst_item = (struct btrfs_inode_item *)dst_ptr;
497 if (btrfs_inode_generation(eb, src_item) == 0) {
498 struct extent_buffer *dst_eb = path->nodes[0];
499 const u64 ino_size = btrfs_inode_size(eb, src_item);
502 * For regular files an ino_size == 0 is used only when
503 * logging that an inode exists, as part of a directory
504 * fsync, and the inode wasn't fsynced before. In this
505 * case don't set the size of the inode in the fs/subvol
506 * tree, otherwise we would be throwing valid data away.
508 if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
509 S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
510 ino_size != 0) {
511 struct btrfs_map_token token;
513 btrfs_init_map_token(&token, dst_eb);
514 btrfs_set_token_inode_size(dst_eb, dst_item,
515 ino_size, &token);
517 goto no_copy;
520 if (overwrite_root &&
521 S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
522 S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
523 save_old_i_size = 1;
524 saved_i_size = btrfs_inode_size(path->nodes[0],
525 dst_item);
529 copy_extent_buffer(path->nodes[0], eb, dst_ptr,
530 src_ptr, item_size);
532 if (save_old_i_size) {
533 struct btrfs_inode_item *dst_item;
534 dst_item = (struct btrfs_inode_item *)dst_ptr;
535 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
538 /* make sure the generation is filled in */
539 if (key->type == BTRFS_INODE_ITEM_KEY) {
540 struct btrfs_inode_item *dst_item;
541 dst_item = (struct btrfs_inode_item *)dst_ptr;
542 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
543 btrfs_set_inode_generation(path->nodes[0], dst_item,
544 trans->transid);
547 no_copy:
548 btrfs_mark_buffer_dirty(path->nodes[0]);
549 btrfs_release_path(path);
550 return 0;
554 * simple helper to read an inode off the disk from a given root
555 * This can only be called for subvolume roots and not for the log
557 static noinline struct inode *read_one_inode(struct btrfs_root *root,
558 u64 objectid)
560 struct btrfs_key key;
561 struct inode *inode;
563 key.objectid = objectid;
564 key.type = BTRFS_INODE_ITEM_KEY;
565 key.offset = 0;
566 inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
567 if (IS_ERR(inode))
568 inode = NULL;
569 return inode;
572 /* replays a single extent in 'eb' at 'slot' with 'key' into the
573 * subvolume 'root'. path is released on entry and should be released
574 * on exit.
576 * extents in the log tree have not been allocated out of the extent
577 * tree yet. So, this completes the allocation, taking a reference
578 * as required if the extent already exists or creating a new extent
579 * if it isn't in the extent allocation tree yet.
581 * The extent is inserted into the file, dropping any existing extents
582 * from the file that overlap the new one.
584 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
585 struct btrfs_root *root,
586 struct btrfs_path *path,
587 struct extent_buffer *eb, int slot,
588 struct btrfs_key *key)
590 struct btrfs_fs_info *fs_info = root->fs_info;
591 int found_type;
592 u64 extent_end;
593 u64 start = key->offset;
594 u64 nbytes = 0;
595 struct btrfs_file_extent_item *item;
596 struct inode *inode = NULL;
597 unsigned long size;
598 int ret = 0;
600 item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
601 found_type = btrfs_file_extent_type(eb, item);
603 if (found_type == BTRFS_FILE_EXTENT_REG ||
604 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
605 nbytes = btrfs_file_extent_num_bytes(eb, item);
606 extent_end = start + nbytes;
609 * We don't add to the inodes nbytes if we are prealloc or a
610 * hole.
612 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
613 nbytes = 0;
614 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
615 size = btrfs_file_extent_ram_bytes(eb, item);
616 nbytes = btrfs_file_extent_ram_bytes(eb, item);
617 extent_end = ALIGN(start + size,
618 fs_info->sectorsize);
619 } else {
620 ret = 0;
621 goto out;
624 inode = read_one_inode(root, key->objectid);
625 if (!inode) {
626 ret = -EIO;
627 goto out;
631 * first check to see if we already have this extent in the
632 * file. This must be done before the btrfs_drop_extents run
633 * so we don't try to drop this extent.
635 ret = btrfs_lookup_file_extent(trans, root, path,
636 btrfs_ino(BTRFS_I(inode)), start, 0);
638 if (ret == 0 &&
639 (found_type == BTRFS_FILE_EXTENT_REG ||
640 found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
641 struct btrfs_file_extent_item cmp1;
642 struct btrfs_file_extent_item cmp2;
643 struct btrfs_file_extent_item *existing;
644 struct extent_buffer *leaf;
646 leaf = path->nodes[0];
647 existing = btrfs_item_ptr(leaf, path->slots[0],
648 struct btrfs_file_extent_item);
650 read_extent_buffer(eb, &cmp1, (unsigned long)item,
651 sizeof(cmp1));
652 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
653 sizeof(cmp2));
656 * we already have a pointer to this exact extent,
657 * we don't have to do anything
659 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
660 btrfs_release_path(path);
661 goto out;
664 btrfs_release_path(path);
666 /* drop any overlapping extents */
667 ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
668 if (ret)
669 goto out;
671 if (found_type == BTRFS_FILE_EXTENT_REG ||
672 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
673 u64 offset;
674 unsigned long dest_offset;
675 struct btrfs_key ins;
677 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
678 btrfs_fs_incompat(fs_info, NO_HOLES))
679 goto update_inode;
681 ret = btrfs_insert_empty_item(trans, root, path, key,
682 sizeof(*item));
683 if (ret)
684 goto out;
685 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
686 path->slots[0]);
687 copy_extent_buffer(path->nodes[0], eb, dest_offset,
688 (unsigned long)item, sizeof(*item));
690 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
691 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
692 ins.type = BTRFS_EXTENT_ITEM_KEY;
693 offset = key->offset - btrfs_file_extent_offset(eb, item);
696 * Manually record dirty extent, as here we did a shallow
697 * file extent item copy and skip normal backref update,
698 * but modifying extent tree all by ourselves.
699 * So need to manually record dirty extent for qgroup,
700 * as the owner of the file extent changed from log tree
701 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
703 ret = btrfs_qgroup_trace_extent(trans,
704 btrfs_file_extent_disk_bytenr(eb, item),
705 btrfs_file_extent_disk_num_bytes(eb, item),
706 GFP_NOFS);
707 if (ret < 0)
708 goto out;
710 if (ins.objectid > 0) {
711 struct btrfs_ref ref = { 0 };
712 u64 csum_start;
713 u64 csum_end;
714 LIST_HEAD(ordered_sums);
717 * is this extent already allocated in the extent
718 * allocation tree? If so, just add a reference
720 ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
721 ins.offset);
722 if (ret == 0) {
723 btrfs_init_generic_ref(&ref,
724 BTRFS_ADD_DELAYED_REF,
725 ins.objectid, ins.offset, 0);
726 btrfs_init_data_ref(&ref,
727 root->root_key.objectid,
728 key->objectid, offset);
729 ret = btrfs_inc_extent_ref(trans, &ref);
730 if (ret)
731 goto out;
732 } else {
734 * insert the extent pointer in the extent
735 * allocation tree
737 ret = btrfs_alloc_logged_file_extent(trans,
738 root->root_key.objectid,
739 key->objectid, offset, &ins);
740 if (ret)
741 goto out;
743 btrfs_release_path(path);
745 if (btrfs_file_extent_compression(eb, item)) {
746 csum_start = ins.objectid;
747 csum_end = csum_start + ins.offset;
748 } else {
749 csum_start = ins.objectid +
750 btrfs_file_extent_offset(eb, item);
751 csum_end = csum_start +
752 btrfs_file_extent_num_bytes(eb, item);
755 ret = btrfs_lookup_csums_range(root->log_root,
756 csum_start, csum_end - 1,
757 &ordered_sums, 0);
758 if (ret)
759 goto out;
761 * Now delete all existing cums in the csum root that
762 * cover our range. We do this because we can have an
763 * extent that is completely referenced by one file
764 * extent item and partially referenced by another
765 * file extent item (like after using the clone or
766 * extent_same ioctls). In this case if we end up doing
767 * the replay of the one that partially references the
768 * extent first, and we do not do the csum deletion
769 * below, we can get 2 csum items in the csum tree that
770 * overlap each other. For example, imagine our log has
771 * the two following file extent items:
773 * key (257 EXTENT_DATA 409600)
774 * extent data disk byte 12845056 nr 102400
775 * extent data offset 20480 nr 20480 ram 102400
777 * key (257 EXTENT_DATA 819200)
778 * extent data disk byte 12845056 nr 102400
779 * extent data offset 0 nr 102400 ram 102400
781 * Where the second one fully references the 100K extent
782 * that starts at disk byte 12845056, and the log tree
783 * has a single csum item that covers the entire range
784 * of the extent:
786 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
788 * After the first file extent item is replayed, the
789 * csum tree gets the following csum item:
791 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
793 * Which covers the 20K sub-range starting at offset 20K
794 * of our extent. Now when we replay the second file
795 * extent item, if we do not delete existing csum items
796 * that cover any of its blocks, we end up getting two
797 * csum items in our csum tree that overlap each other:
799 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
800 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
802 * Which is a problem, because after this anyone trying
803 * to lookup up for the checksum of any block of our
804 * extent starting at an offset of 40K or higher, will
805 * end up looking at the second csum item only, which
806 * does not contain the checksum for any block starting
807 * at offset 40K or higher of our extent.
809 while (!list_empty(&ordered_sums)) {
810 struct btrfs_ordered_sum *sums;
811 sums = list_entry(ordered_sums.next,
812 struct btrfs_ordered_sum,
813 list);
814 if (!ret)
815 ret = btrfs_del_csums(trans,
816 fs_info->csum_root,
817 sums->bytenr,
818 sums->len);
819 if (!ret)
820 ret = btrfs_csum_file_blocks(trans,
821 fs_info->csum_root, sums);
822 list_del(&sums->list);
823 kfree(sums);
825 if (ret)
826 goto out;
827 } else {
828 btrfs_release_path(path);
830 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
831 /* inline extents are easy, we just overwrite them */
832 ret = overwrite_item(trans, root, path, eb, slot, key);
833 if (ret)
834 goto out;
837 inode_add_bytes(inode, nbytes);
838 update_inode:
839 ret = btrfs_update_inode(trans, root, inode);
840 out:
841 if (inode)
842 iput(inode);
843 return ret;
847 * when cleaning up conflicts between the directory names in the
848 * subvolume, directory names in the log and directory names in the
849 * inode back references, we may have to unlink inodes from directories.
851 * This is a helper function to do the unlink of a specific directory
852 * item
854 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
855 struct btrfs_root *root,
856 struct btrfs_path *path,
857 struct btrfs_inode *dir,
858 struct btrfs_dir_item *di)
860 struct inode *inode;
861 char *name;
862 int name_len;
863 struct extent_buffer *leaf;
864 struct btrfs_key location;
865 int ret;
867 leaf = path->nodes[0];
869 btrfs_dir_item_key_to_cpu(leaf, di, &location);
870 name_len = btrfs_dir_name_len(leaf, di);
871 name = kmalloc(name_len, GFP_NOFS);
872 if (!name)
873 return -ENOMEM;
875 read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
876 btrfs_release_path(path);
878 inode = read_one_inode(root, location.objectid);
879 if (!inode) {
880 ret = -EIO;
881 goto out;
884 ret = link_to_fixup_dir(trans, root, path, location.objectid);
885 if (ret)
886 goto out;
888 ret = btrfs_unlink_inode(trans, root, dir, BTRFS_I(inode), name,
889 name_len);
890 if (ret)
891 goto out;
892 else
893 ret = btrfs_run_delayed_items(trans);
894 out:
895 kfree(name);
896 iput(inode);
897 return ret;
901 * helper function to see if a given name and sequence number found
902 * in an inode back reference are already in a directory and correctly
903 * point to this inode
905 static noinline int inode_in_dir(struct btrfs_root *root,
906 struct btrfs_path *path,
907 u64 dirid, u64 objectid, u64 index,
908 const char *name, int name_len)
910 struct btrfs_dir_item *di;
911 struct btrfs_key location;
912 int match = 0;
914 di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
915 index, name, name_len, 0);
916 if (di && !IS_ERR(di)) {
917 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
918 if (location.objectid != objectid)
919 goto out;
920 } else
921 goto out;
922 btrfs_release_path(path);
924 di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
925 if (di && !IS_ERR(di)) {
926 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
927 if (location.objectid != objectid)
928 goto out;
929 } else
930 goto out;
931 match = 1;
932 out:
933 btrfs_release_path(path);
934 return match;
938 * helper function to check a log tree for a named back reference in
939 * an inode. This is used to decide if a back reference that is
940 * found in the subvolume conflicts with what we find in the log.
942 * inode backreferences may have multiple refs in a single item,
943 * during replay we process one reference at a time, and we don't
944 * want to delete valid links to a file from the subvolume if that
945 * link is also in the log.
947 static noinline int backref_in_log(struct btrfs_root *log,
948 struct btrfs_key *key,
949 u64 ref_objectid,
950 const char *name, int namelen)
952 struct btrfs_path *path;
953 struct btrfs_inode_ref *ref;
954 unsigned long ptr;
955 unsigned long ptr_end;
956 unsigned long name_ptr;
957 int found_name_len;
958 int item_size;
959 int ret;
960 int match = 0;
962 path = btrfs_alloc_path();
963 if (!path)
964 return -ENOMEM;
966 ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
967 if (ret != 0)
968 goto out;
970 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
972 if (key->type == BTRFS_INODE_EXTREF_KEY) {
973 if (btrfs_find_name_in_ext_backref(path->nodes[0],
974 path->slots[0],
975 ref_objectid,
976 name, namelen))
977 match = 1;
979 goto out;
982 item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
983 ptr_end = ptr + item_size;
984 while (ptr < ptr_end) {
985 ref = (struct btrfs_inode_ref *)ptr;
986 found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
987 if (found_name_len == namelen) {
988 name_ptr = (unsigned long)(ref + 1);
989 ret = memcmp_extent_buffer(path->nodes[0], name,
990 name_ptr, namelen);
991 if (ret == 0) {
992 match = 1;
993 goto out;
996 ptr = (unsigned long)(ref + 1) + found_name_len;
998 out:
999 btrfs_free_path(path);
1000 return match;
1003 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
1004 struct btrfs_root *root,
1005 struct btrfs_path *path,
1006 struct btrfs_root *log_root,
1007 struct btrfs_inode *dir,
1008 struct btrfs_inode *inode,
1009 u64 inode_objectid, u64 parent_objectid,
1010 u64 ref_index, char *name, int namelen,
1011 int *search_done)
1013 int ret;
1014 char *victim_name;
1015 int victim_name_len;
1016 struct extent_buffer *leaf;
1017 struct btrfs_dir_item *di;
1018 struct btrfs_key search_key;
1019 struct btrfs_inode_extref *extref;
1021 again:
1022 /* Search old style refs */
1023 search_key.objectid = inode_objectid;
1024 search_key.type = BTRFS_INODE_REF_KEY;
1025 search_key.offset = parent_objectid;
1026 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1027 if (ret == 0) {
1028 struct btrfs_inode_ref *victim_ref;
1029 unsigned long ptr;
1030 unsigned long ptr_end;
1032 leaf = path->nodes[0];
1034 /* are we trying to overwrite a back ref for the root directory
1035 * if so, just jump out, we're done
1037 if (search_key.objectid == search_key.offset)
1038 return 1;
1040 /* check all the names in this back reference to see
1041 * if they are in the log. if so, we allow them to stay
1042 * otherwise they must be unlinked as a conflict
1044 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1045 ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
1046 while (ptr < ptr_end) {
1047 victim_ref = (struct btrfs_inode_ref *)ptr;
1048 victim_name_len = btrfs_inode_ref_name_len(leaf,
1049 victim_ref);
1050 victim_name = kmalloc(victim_name_len, GFP_NOFS);
1051 if (!victim_name)
1052 return -ENOMEM;
1054 read_extent_buffer(leaf, victim_name,
1055 (unsigned long)(victim_ref + 1),
1056 victim_name_len);
1058 if (!backref_in_log(log_root, &search_key,
1059 parent_objectid,
1060 victim_name,
1061 victim_name_len)) {
1062 inc_nlink(&inode->vfs_inode);
1063 btrfs_release_path(path);
1065 ret = btrfs_unlink_inode(trans, root, dir, inode,
1066 victim_name, victim_name_len);
1067 kfree(victim_name);
1068 if (ret)
1069 return ret;
1070 ret = btrfs_run_delayed_items(trans);
1071 if (ret)
1072 return ret;
1073 *search_done = 1;
1074 goto again;
1076 kfree(victim_name);
1078 ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
1082 * NOTE: we have searched root tree and checked the
1083 * corresponding ref, it does not need to check again.
1085 *search_done = 1;
1087 btrfs_release_path(path);
1089 /* Same search but for extended refs */
1090 extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
1091 inode_objectid, parent_objectid, 0,
1093 if (!IS_ERR_OR_NULL(extref)) {
1094 u32 item_size;
1095 u32 cur_offset = 0;
1096 unsigned long base;
1097 struct inode *victim_parent;
1099 leaf = path->nodes[0];
1101 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1102 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1104 while (cur_offset < item_size) {
1105 extref = (struct btrfs_inode_extref *)(base + cur_offset);
1107 victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
1109 if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1110 goto next;
1112 victim_name = kmalloc(victim_name_len, GFP_NOFS);
1113 if (!victim_name)
1114 return -ENOMEM;
1115 read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1116 victim_name_len);
1118 search_key.objectid = inode_objectid;
1119 search_key.type = BTRFS_INODE_EXTREF_KEY;
1120 search_key.offset = btrfs_extref_hash(parent_objectid,
1121 victim_name,
1122 victim_name_len);
1123 ret = 0;
1124 if (!backref_in_log(log_root, &search_key,
1125 parent_objectid, victim_name,
1126 victim_name_len)) {
1127 ret = -ENOENT;
1128 victim_parent = read_one_inode(root,
1129 parent_objectid);
1130 if (victim_parent) {
1131 inc_nlink(&inode->vfs_inode);
1132 btrfs_release_path(path);
1134 ret = btrfs_unlink_inode(trans, root,
1135 BTRFS_I(victim_parent),
1136 inode,
1137 victim_name,
1138 victim_name_len);
1139 if (!ret)
1140 ret = btrfs_run_delayed_items(
1141 trans);
1143 iput(victim_parent);
1144 kfree(victim_name);
1145 if (ret)
1146 return ret;
1147 *search_done = 1;
1148 goto again;
1150 kfree(victim_name);
1151 next:
1152 cur_offset += victim_name_len + sizeof(*extref);
1154 *search_done = 1;
1156 btrfs_release_path(path);
1158 /* look for a conflicting sequence number */
1159 di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1160 ref_index, name, namelen, 0);
1161 if (di && !IS_ERR(di)) {
1162 ret = drop_one_dir_item(trans, root, path, dir, di);
1163 if (ret)
1164 return ret;
1166 btrfs_release_path(path);
1168 /* look for a conflicting name */
1169 di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
1170 name, namelen, 0);
1171 if (di && !IS_ERR(di)) {
1172 ret = drop_one_dir_item(trans, root, path, dir, di);
1173 if (ret)
1174 return ret;
1176 btrfs_release_path(path);
1178 return 0;
1181 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1182 u32 *namelen, char **name, u64 *index,
1183 u64 *parent_objectid)
1185 struct btrfs_inode_extref *extref;
1187 extref = (struct btrfs_inode_extref *)ref_ptr;
1189 *namelen = btrfs_inode_extref_name_len(eb, extref);
1190 *name = kmalloc(*namelen, GFP_NOFS);
1191 if (*name == NULL)
1192 return -ENOMEM;
1194 read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1195 *namelen);
1197 if (index)
1198 *index = btrfs_inode_extref_index(eb, extref);
1199 if (parent_objectid)
1200 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1202 return 0;
1205 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1206 u32 *namelen, char **name, u64 *index)
1208 struct btrfs_inode_ref *ref;
1210 ref = (struct btrfs_inode_ref *)ref_ptr;
1212 *namelen = btrfs_inode_ref_name_len(eb, ref);
1213 *name = kmalloc(*namelen, GFP_NOFS);
1214 if (*name == NULL)
1215 return -ENOMEM;
1217 read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1219 if (index)
1220 *index = btrfs_inode_ref_index(eb, ref);
1222 return 0;
1226 * Take an inode reference item from the log tree and iterate all names from the
1227 * inode reference item in the subvolume tree with the same key (if it exists).
1228 * For any name that is not in the inode reference item from the log tree, do a
1229 * proper unlink of that name (that is, remove its entry from the inode
1230 * reference item and both dir index keys).
1232 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1233 struct btrfs_root *root,
1234 struct btrfs_path *path,
1235 struct btrfs_inode *inode,
1236 struct extent_buffer *log_eb,
1237 int log_slot,
1238 struct btrfs_key *key)
1240 int ret;
1241 unsigned long ref_ptr;
1242 unsigned long ref_end;
1243 struct extent_buffer *eb;
1245 again:
1246 btrfs_release_path(path);
1247 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1248 if (ret > 0) {
1249 ret = 0;
1250 goto out;
1252 if (ret < 0)
1253 goto out;
1255 eb = path->nodes[0];
1256 ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1257 ref_end = ref_ptr + btrfs_item_size_nr(eb, path->slots[0]);
1258 while (ref_ptr < ref_end) {
1259 char *name = NULL;
1260 int namelen;
1261 u64 parent_id;
1263 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1264 ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1265 NULL, &parent_id);
1266 } else {
1267 parent_id = key->offset;
1268 ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1269 NULL);
1271 if (ret)
1272 goto out;
1274 if (key->type == BTRFS_INODE_EXTREF_KEY)
1275 ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
1276 parent_id, name,
1277 namelen);
1278 else
1279 ret = !!btrfs_find_name_in_backref(log_eb, log_slot,
1280 name, namelen);
1282 if (!ret) {
1283 struct inode *dir;
1285 btrfs_release_path(path);
1286 dir = read_one_inode(root, parent_id);
1287 if (!dir) {
1288 ret = -ENOENT;
1289 kfree(name);
1290 goto out;
1292 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
1293 inode, name, namelen);
1294 kfree(name);
1295 iput(dir);
1296 if (ret)
1297 goto out;
1298 goto again;
1301 kfree(name);
1302 ref_ptr += namelen;
1303 if (key->type == BTRFS_INODE_EXTREF_KEY)
1304 ref_ptr += sizeof(struct btrfs_inode_extref);
1305 else
1306 ref_ptr += sizeof(struct btrfs_inode_ref);
1308 ret = 0;
1309 out:
1310 btrfs_release_path(path);
1311 return ret;
1314 static int btrfs_inode_ref_exists(struct inode *inode, struct inode *dir,
1315 const u8 ref_type, const char *name,
1316 const int namelen)
1318 struct btrfs_key key;
1319 struct btrfs_path *path;
1320 const u64 parent_id = btrfs_ino(BTRFS_I(dir));
1321 int ret;
1323 path = btrfs_alloc_path();
1324 if (!path)
1325 return -ENOMEM;
1327 key.objectid = btrfs_ino(BTRFS_I(inode));
1328 key.type = ref_type;
1329 if (key.type == BTRFS_INODE_REF_KEY)
1330 key.offset = parent_id;
1331 else
1332 key.offset = btrfs_extref_hash(parent_id, name, namelen);
1334 ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
1335 if (ret < 0)
1336 goto out;
1337 if (ret > 0) {
1338 ret = 0;
1339 goto out;
1341 if (key.type == BTRFS_INODE_EXTREF_KEY)
1342 ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
1343 path->slots[0], parent_id, name, namelen);
1344 else
1345 ret = !!btrfs_find_name_in_backref(path->nodes[0], path->slots[0],
1346 name, namelen);
1348 out:
1349 btrfs_free_path(path);
1350 return ret;
1353 static int add_link(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1354 struct inode *dir, struct inode *inode, const char *name,
1355 int namelen, u64 ref_index)
1357 struct btrfs_dir_item *dir_item;
1358 struct btrfs_key key;
1359 struct btrfs_path *path;
1360 struct inode *other_inode = NULL;
1361 int ret;
1363 path = btrfs_alloc_path();
1364 if (!path)
1365 return -ENOMEM;
1367 dir_item = btrfs_lookup_dir_item(NULL, root, path,
1368 btrfs_ino(BTRFS_I(dir)),
1369 name, namelen, 0);
1370 if (!dir_item) {
1371 btrfs_release_path(path);
1372 goto add_link;
1373 } else if (IS_ERR(dir_item)) {
1374 ret = PTR_ERR(dir_item);
1375 goto out;
1379 * Our inode's dentry collides with the dentry of another inode which is
1380 * in the log but not yet processed since it has a higher inode number.
1381 * So delete that other dentry.
1383 btrfs_dir_item_key_to_cpu(path->nodes[0], dir_item, &key);
1384 btrfs_release_path(path);
1385 other_inode = read_one_inode(root, key.objectid);
1386 if (!other_inode) {
1387 ret = -ENOENT;
1388 goto out;
1390 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir), BTRFS_I(other_inode),
1391 name, namelen);
1392 if (ret)
1393 goto out;
1395 * If we dropped the link count to 0, bump it so that later the iput()
1396 * on the inode will not free it. We will fixup the link count later.
1398 if (other_inode->i_nlink == 0)
1399 inc_nlink(other_inode);
1401 ret = btrfs_run_delayed_items(trans);
1402 if (ret)
1403 goto out;
1404 add_link:
1405 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
1406 name, namelen, 0, ref_index);
1407 out:
1408 iput(other_inode);
1409 btrfs_free_path(path);
1411 return ret;
1415 * replay one inode back reference item found in the log tree.
1416 * eb, slot and key refer to the buffer and key found in the log tree.
1417 * root is the destination we are replaying into, and path is for temp
1418 * use by this function. (it should be released on return).
1420 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1421 struct btrfs_root *root,
1422 struct btrfs_root *log,
1423 struct btrfs_path *path,
1424 struct extent_buffer *eb, int slot,
1425 struct btrfs_key *key)
1427 struct inode *dir = NULL;
1428 struct inode *inode = NULL;
1429 unsigned long ref_ptr;
1430 unsigned long ref_end;
1431 char *name = NULL;
1432 int namelen;
1433 int ret;
1434 int search_done = 0;
1435 int log_ref_ver = 0;
1436 u64 parent_objectid;
1437 u64 inode_objectid;
1438 u64 ref_index = 0;
1439 int ref_struct_size;
1441 ref_ptr = btrfs_item_ptr_offset(eb, slot);
1442 ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1444 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1445 struct btrfs_inode_extref *r;
1447 ref_struct_size = sizeof(struct btrfs_inode_extref);
1448 log_ref_ver = 1;
1449 r = (struct btrfs_inode_extref *)ref_ptr;
1450 parent_objectid = btrfs_inode_extref_parent(eb, r);
1451 } else {
1452 ref_struct_size = sizeof(struct btrfs_inode_ref);
1453 parent_objectid = key->offset;
1455 inode_objectid = key->objectid;
1458 * it is possible that we didn't log all the parent directories
1459 * for a given inode. If we don't find the dir, just don't
1460 * copy the back ref in. The link count fixup code will take
1461 * care of the rest
1463 dir = read_one_inode(root, parent_objectid);
1464 if (!dir) {
1465 ret = -ENOENT;
1466 goto out;
1469 inode = read_one_inode(root, inode_objectid);
1470 if (!inode) {
1471 ret = -EIO;
1472 goto out;
1475 while (ref_ptr < ref_end) {
1476 if (log_ref_ver) {
1477 ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1478 &ref_index, &parent_objectid);
1480 * parent object can change from one array
1481 * item to another.
1483 if (!dir)
1484 dir = read_one_inode(root, parent_objectid);
1485 if (!dir) {
1486 ret = -ENOENT;
1487 goto out;
1489 } else {
1490 ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1491 &ref_index);
1493 if (ret)
1494 goto out;
1496 /* if we already have a perfect match, we're done */
1497 if (!inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1498 btrfs_ino(BTRFS_I(inode)), ref_index,
1499 name, namelen)) {
1501 * look for a conflicting back reference in the
1502 * metadata. if we find one we have to unlink that name
1503 * of the file before we add our new link. Later on, we
1504 * overwrite any existing back reference, and we don't
1505 * want to create dangling pointers in the directory.
1508 if (!search_done) {
1509 ret = __add_inode_ref(trans, root, path, log,
1510 BTRFS_I(dir),
1511 BTRFS_I(inode),
1512 inode_objectid,
1513 parent_objectid,
1514 ref_index, name, namelen,
1515 &search_done);
1516 if (ret) {
1517 if (ret == 1)
1518 ret = 0;
1519 goto out;
1524 * If a reference item already exists for this inode
1525 * with the same parent and name, but different index,
1526 * drop it and the corresponding directory index entries
1527 * from the parent before adding the new reference item
1528 * and dir index entries, otherwise we would fail with
1529 * -EEXIST returned from btrfs_add_link() below.
1531 ret = btrfs_inode_ref_exists(inode, dir, key->type,
1532 name, namelen);
1533 if (ret > 0) {
1534 ret = btrfs_unlink_inode(trans, root,
1535 BTRFS_I(dir),
1536 BTRFS_I(inode),
1537 name, namelen);
1539 * If we dropped the link count to 0, bump it so
1540 * that later the iput() on the inode will not
1541 * free it. We will fixup the link count later.
1543 if (!ret && inode->i_nlink == 0)
1544 inc_nlink(inode);
1546 if (ret < 0)
1547 goto out;
1549 /* insert our name */
1550 ret = add_link(trans, root, dir, inode, name, namelen,
1551 ref_index);
1552 if (ret)
1553 goto out;
1555 btrfs_update_inode(trans, root, inode);
1558 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1559 kfree(name);
1560 name = NULL;
1561 if (log_ref_ver) {
1562 iput(dir);
1563 dir = NULL;
1568 * Before we overwrite the inode reference item in the subvolume tree
1569 * with the item from the log tree, we must unlink all names from the
1570 * parent directory that are in the subvolume's tree inode reference
1571 * item, otherwise we end up with an inconsistent subvolume tree where
1572 * dir index entries exist for a name but there is no inode reference
1573 * item with the same name.
1575 ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1576 key);
1577 if (ret)
1578 goto out;
1580 /* finally write the back reference in the inode */
1581 ret = overwrite_item(trans, root, path, eb, slot, key);
1582 out:
1583 btrfs_release_path(path);
1584 kfree(name);
1585 iput(dir);
1586 iput(inode);
1587 return ret;
1590 static int insert_orphan_item(struct btrfs_trans_handle *trans,
1591 struct btrfs_root *root, u64 ino)
1593 int ret;
1595 ret = btrfs_insert_orphan_item(trans, root, ino);
1596 if (ret == -EEXIST)
1597 ret = 0;
1599 return ret;
1602 static int count_inode_extrefs(struct btrfs_root *root,
1603 struct btrfs_inode *inode, struct btrfs_path *path)
1605 int ret = 0;
1606 int name_len;
1607 unsigned int nlink = 0;
1608 u32 item_size;
1609 u32 cur_offset = 0;
1610 u64 inode_objectid = btrfs_ino(inode);
1611 u64 offset = 0;
1612 unsigned long ptr;
1613 struct btrfs_inode_extref *extref;
1614 struct extent_buffer *leaf;
1616 while (1) {
1617 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1618 &extref, &offset);
1619 if (ret)
1620 break;
1622 leaf = path->nodes[0];
1623 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1624 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1625 cur_offset = 0;
1627 while (cur_offset < item_size) {
1628 extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1629 name_len = btrfs_inode_extref_name_len(leaf, extref);
1631 nlink++;
1633 cur_offset += name_len + sizeof(*extref);
1636 offset++;
1637 btrfs_release_path(path);
1639 btrfs_release_path(path);
1641 if (ret < 0 && ret != -ENOENT)
1642 return ret;
1643 return nlink;
1646 static int count_inode_refs(struct btrfs_root *root,
1647 struct btrfs_inode *inode, struct btrfs_path *path)
1649 int ret;
1650 struct btrfs_key key;
1651 unsigned int nlink = 0;
1652 unsigned long ptr;
1653 unsigned long ptr_end;
1654 int name_len;
1655 u64 ino = btrfs_ino(inode);
1657 key.objectid = ino;
1658 key.type = BTRFS_INODE_REF_KEY;
1659 key.offset = (u64)-1;
1661 while (1) {
1662 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1663 if (ret < 0)
1664 break;
1665 if (ret > 0) {
1666 if (path->slots[0] == 0)
1667 break;
1668 path->slots[0]--;
1670 process_slot:
1671 btrfs_item_key_to_cpu(path->nodes[0], &key,
1672 path->slots[0]);
1673 if (key.objectid != ino ||
1674 key.type != BTRFS_INODE_REF_KEY)
1675 break;
1676 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1677 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1678 path->slots[0]);
1679 while (ptr < ptr_end) {
1680 struct btrfs_inode_ref *ref;
1682 ref = (struct btrfs_inode_ref *)ptr;
1683 name_len = btrfs_inode_ref_name_len(path->nodes[0],
1684 ref);
1685 ptr = (unsigned long)(ref + 1) + name_len;
1686 nlink++;
1689 if (key.offset == 0)
1690 break;
1691 if (path->slots[0] > 0) {
1692 path->slots[0]--;
1693 goto process_slot;
1695 key.offset--;
1696 btrfs_release_path(path);
1698 btrfs_release_path(path);
1700 return nlink;
1704 * There are a few corners where the link count of the file can't
1705 * be properly maintained during replay. So, instead of adding
1706 * lots of complexity to the log code, we just scan the backrefs
1707 * for any file that has been through replay.
1709 * The scan will update the link count on the inode to reflect the
1710 * number of back refs found. If it goes down to zero, the iput
1711 * will free the inode.
1713 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1714 struct btrfs_root *root,
1715 struct inode *inode)
1717 struct btrfs_path *path;
1718 int ret;
1719 u64 nlink = 0;
1720 u64 ino = btrfs_ino(BTRFS_I(inode));
1722 path = btrfs_alloc_path();
1723 if (!path)
1724 return -ENOMEM;
1726 ret = count_inode_refs(root, BTRFS_I(inode), path);
1727 if (ret < 0)
1728 goto out;
1730 nlink = ret;
1732 ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1733 if (ret < 0)
1734 goto out;
1736 nlink += ret;
1738 ret = 0;
1740 if (nlink != inode->i_nlink) {
1741 set_nlink(inode, nlink);
1742 btrfs_update_inode(trans, root, inode);
1744 BTRFS_I(inode)->index_cnt = (u64)-1;
1746 if (inode->i_nlink == 0) {
1747 if (S_ISDIR(inode->i_mode)) {
1748 ret = replay_dir_deletes(trans, root, NULL, path,
1749 ino, 1);
1750 if (ret)
1751 goto out;
1753 ret = insert_orphan_item(trans, root, ino);
1756 out:
1757 btrfs_free_path(path);
1758 return ret;
1761 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1762 struct btrfs_root *root,
1763 struct btrfs_path *path)
1765 int ret;
1766 struct btrfs_key key;
1767 struct inode *inode;
1769 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1770 key.type = BTRFS_ORPHAN_ITEM_KEY;
1771 key.offset = (u64)-1;
1772 while (1) {
1773 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1774 if (ret < 0)
1775 break;
1777 if (ret == 1) {
1778 if (path->slots[0] == 0)
1779 break;
1780 path->slots[0]--;
1783 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1784 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1785 key.type != BTRFS_ORPHAN_ITEM_KEY)
1786 break;
1788 ret = btrfs_del_item(trans, root, path);
1789 if (ret)
1790 goto out;
1792 btrfs_release_path(path);
1793 inode = read_one_inode(root, key.offset);
1794 if (!inode)
1795 return -EIO;
1797 ret = fixup_inode_link_count(trans, root, inode);
1798 iput(inode);
1799 if (ret)
1800 goto out;
1803 * fixup on a directory may create new entries,
1804 * make sure we always look for the highset possible
1805 * offset
1807 key.offset = (u64)-1;
1809 ret = 0;
1810 out:
1811 btrfs_release_path(path);
1812 return ret;
1817 * record a given inode in the fixup dir so we can check its link
1818 * count when replay is done. The link count is incremented here
1819 * so the inode won't go away until we check it
1821 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1822 struct btrfs_root *root,
1823 struct btrfs_path *path,
1824 u64 objectid)
1826 struct btrfs_key key;
1827 int ret = 0;
1828 struct inode *inode;
1830 inode = read_one_inode(root, objectid);
1831 if (!inode)
1832 return -EIO;
1834 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1835 key.type = BTRFS_ORPHAN_ITEM_KEY;
1836 key.offset = objectid;
1838 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1840 btrfs_release_path(path);
1841 if (ret == 0) {
1842 if (!inode->i_nlink)
1843 set_nlink(inode, 1);
1844 else
1845 inc_nlink(inode);
1846 ret = btrfs_update_inode(trans, root, inode);
1847 } else if (ret == -EEXIST) {
1848 ret = 0;
1849 } else {
1850 BUG(); /* Logic Error */
1852 iput(inode);
1854 return ret;
1858 * when replaying the log for a directory, we only insert names
1859 * for inodes that actually exist. This means an fsync on a directory
1860 * does not implicitly fsync all the new files in it
1862 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1863 struct btrfs_root *root,
1864 u64 dirid, u64 index,
1865 char *name, int name_len,
1866 struct btrfs_key *location)
1868 struct inode *inode;
1869 struct inode *dir;
1870 int ret;
1872 inode = read_one_inode(root, location->objectid);
1873 if (!inode)
1874 return -ENOENT;
1876 dir = read_one_inode(root, dirid);
1877 if (!dir) {
1878 iput(inode);
1879 return -EIO;
1882 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1883 name_len, 1, index);
1885 /* FIXME, put inode into FIXUP list */
1887 iput(inode);
1888 iput(dir);
1889 return ret;
1893 * Return true if an inode reference exists in the log for the given name,
1894 * inode and parent inode.
1896 static bool name_in_log_ref(struct btrfs_root *log_root,
1897 const char *name, const int name_len,
1898 const u64 dirid, const u64 ino)
1900 struct btrfs_key search_key;
1902 search_key.objectid = ino;
1903 search_key.type = BTRFS_INODE_REF_KEY;
1904 search_key.offset = dirid;
1905 if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1906 return true;
1908 search_key.type = BTRFS_INODE_EXTREF_KEY;
1909 search_key.offset = btrfs_extref_hash(dirid, name, name_len);
1910 if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1911 return true;
1913 return false;
1917 * take a single entry in a log directory item and replay it into
1918 * the subvolume.
1920 * if a conflicting item exists in the subdirectory already,
1921 * the inode it points to is unlinked and put into the link count
1922 * fix up tree.
1924 * If a name from the log points to a file or directory that does
1925 * not exist in the FS, it is skipped. fsyncs on directories
1926 * do not force down inodes inside that directory, just changes to the
1927 * names or unlinks in a directory.
1929 * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1930 * non-existing inode) and 1 if the name was replayed.
1932 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1933 struct btrfs_root *root,
1934 struct btrfs_path *path,
1935 struct extent_buffer *eb,
1936 struct btrfs_dir_item *di,
1937 struct btrfs_key *key)
1939 char *name;
1940 int name_len;
1941 struct btrfs_dir_item *dst_di;
1942 struct btrfs_key found_key;
1943 struct btrfs_key log_key;
1944 struct inode *dir;
1945 u8 log_type;
1946 int exists;
1947 int ret = 0;
1948 bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
1949 bool name_added = false;
1951 dir = read_one_inode(root, key->objectid);
1952 if (!dir)
1953 return -EIO;
1955 name_len = btrfs_dir_name_len(eb, di);
1956 name = kmalloc(name_len, GFP_NOFS);
1957 if (!name) {
1958 ret = -ENOMEM;
1959 goto out;
1962 log_type = btrfs_dir_type(eb, di);
1963 read_extent_buffer(eb, name, (unsigned long)(di + 1),
1964 name_len);
1966 btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1967 exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1968 if (exists == 0)
1969 exists = 1;
1970 else
1971 exists = 0;
1972 btrfs_release_path(path);
1974 if (key->type == BTRFS_DIR_ITEM_KEY) {
1975 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1976 name, name_len, 1);
1977 } else if (key->type == BTRFS_DIR_INDEX_KEY) {
1978 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1979 key->objectid,
1980 key->offset, name,
1981 name_len, 1);
1982 } else {
1983 /* Corruption */
1984 ret = -EINVAL;
1985 goto out;
1987 if (IS_ERR_OR_NULL(dst_di)) {
1988 /* we need a sequence number to insert, so we only
1989 * do inserts for the BTRFS_DIR_INDEX_KEY types
1991 if (key->type != BTRFS_DIR_INDEX_KEY)
1992 goto out;
1993 goto insert;
1996 btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1997 /* the existing item matches the logged item */
1998 if (found_key.objectid == log_key.objectid &&
1999 found_key.type == log_key.type &&
2000 found_key.offset == log_key.offset &&
2001 btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
2002 update_size = false;
2003 goto out;
2007 * don't drop the conflicting directory entry if the inode
2008 * for the new entry doesn't exist
2010 if (!exists)
2011 goto out;
2013 ret = drop_one_dir_item(trans, root, path, BTRFS_I(dir), dst_di);
2014 if (ret)
2015 goto out;
2017 if (key->type == BTRFS_DIR_INDEX_KEY)
2018 goto insert;
2019 out:
2020 btrfs_release_path(path);
2021 if (!ret && update_size) {
2022 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
2023 ret = btrfs_update_inode(trans, root, dir);
2025 kfree(name);
2026 iput(dir);
2027 if (!ret && name_added)
2028 ret = 1;
2029 return ret;
2031 insert:
2032 if (name_in_log_ref(root->log_root, name, name_len,
2033 key->objectid, log_key.objectid)) {
2034 /* The dentry will be added later. */
2035 ret = 0;
2036 update_size = false;
2037 goto out;
2039 btrfs_release_path(path);
2040 ret = insert_one_name(trans, root, key->objectid, key->offset,
2041 name, name_len, &log_key);
2042 if (ret && ret != -ENOENT && ret != -EEXIST)
2043 goto out;
2044 if (!ret)
2045 name_added = true;
2046 update_size = false;
2047 ret = 0;
2048 goto out;
2052 * find all the names in a directory item and reconcile them into
2053 * the subvolume. Only BTRFS_DIR_ITEM_KEY types will have more than
2054 * one name in a directory item, but the same code gets used for
2055 * both directory index types
2057 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
2058 struct btrfs_root *root,
2059 struct btrfs_path *path,
2060 struct extent_buffer *eb, int slot,
2061 struct btrfs_key *key)
2063 int ret = 0;
2064 u32 item_size = btrfs_item_size_nr(eb, slot);
2065 struct btrfs_dir_item *di;
2066 int name_len;
2067 unsigned long ptr;
2068 unsigned long ptr_end;
2069 struct btrfs_path *fixup_path = NULL;
2071 ptr = btrfs_item_ptr_offset(eb, slot);
2072 ptr_end = ptr + item_size;
2073 while (ptr < ptr_end) {
2074 di = (struct btrfs_dir_item *)ptr;
2075 name_len = btrfs_dir_name_len(eb, di);
2076 ret = replay_one_name(trans, root, path, eb, di, key);
2077 if (ret < 0)
2078 break;
2079 ptr = (unsigned long)(di + 1);
2080 ptr += name_len;
2083 * If this entry refers to a non-directory (directories can not
2084 * have a link count > 1) and it was added in the transaction
2085 * that was not committed, make sure we fixup the link count of
2086 * the inode it the entry points to. Otherwise something like
2087 * the following would result in a directory pointing to an
2088 * inode with a wrong link that does not account for this dir
2089 * entry:
2091 * mkdir testdir
2092 * touch testdir/foo
2093 * touch testdir/bar
2094 * sync
2096 * ln testdir/bar testdir/bar_link
2097 * ln testdir/foo testdir/foo_link
2098 * xfs_io -c "fsync" testdir/bar
2100 * <power failure>
2102 * mount fs, log replay happens
2104 * File foo would remain with a link count of 1 when it has two
2105 * entries pointing to it in the directory testdir. This would
2106 * make it impossible to ever delete the parent directory has
2107 * it would result in stale dentries that can never be deleted.
2109 if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
2110 struct btrfs_key di_key;
2112 if (!fixup_path) {
2113 fixup_path = btrfs_alloc_path();
2114 if (!fixup_path) {
2115 ret = -ENOMEM;
2116 break;
2120 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2121 ret = link_to_fixup_dir(trans, root, fixup_path,
2122 di_key.objectid);
2123 if (ret)
2124 break;
2126 ret = 0;
2128 btrfs_free_path(fixup_path);
2129 return ret;
2133 * directory replay has two parts. There are the standard directory
2134 * items in the log copied from the subvolume, and range items
2135 * created in the log while the subvolume was logged.
2137 * The range items tell us which parts of the key space the log
2138 * is authoritative for. During replay, if a key in the subvolume
2139 * directory is in a logged range item, but not actually in the log
2140 * that means it was deleted from the directory before the fsync
2141 * and should be removed.
2143 static noinline int find_dir_range(struct btrfs_root *root,
2144 struct btrfs_path *path,
2145 u64 dirid, int key_type,
2146 u64 *start_ret, u64 *end_ret)
2148 struct btrfs_key key;
2149 u64 found_end;
2150 struct btrfs_dir_log_item *item;
2151 int ret;
2152 int nritems;
2154 if (*start_ret == (u64)-1)
2155 return 1;
2157 key.objectid = dirid;
2158 key.type = key_type;
2159 key.offset = *start_ret;
2161 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2162 if (ret < 0)
2163 goto out;
2164 if (ret > 0) {
2165 if (path->slots[0] == 0)
2166 goto out;
2167 path->slots[0]--;
2169 if (ret != 0)
2170 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2172 if (key.type != key_type || key.objectid != dirid) {
2173 ret = 1;
2174 goto next;
2176 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2177 struct btrfs_dir_log_item);
2178 found_end = btrfs_dir_log_end(path->nodes[0], item);
2180 if (*start_ret >= key.offset && *start_ret <= found_end) {
2181 ret = 0;
2182 *start_ret = key.offset;
2183 *end_ret = found_end;
2184 goto out;
2186 ret = 1;
2187 next:
2188 /* check the next slot in the tree to see if it is a valid item */
2189 nritems = btrfs_header_nritems(path->nodes[0]);
2190 path->slots[0]++;
2191 if (path->slots[0] >= nritems) {
2192 ret = btrfs_next_leaf(root, path);
2193 if (ret)
2194 goto out;
2197 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2199 if (key.type != key_type || key.objectid != dirid) {
2200 ret = 1;
2201 goto out;
2203 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2204 struct btrfs_dir_log_item);
2205 found_end = btrfs_dir_log_end(path->nodes[0], item);
2206 *start_ret = key.offset;
2207 *end_ret = found_end;
2208 ret = 0;
2209 out:
2210 btrfs_release_path(path);
2211 return ret;
2215 * this looks for a given directory item in the log. If the directory
2216 * item is not in the log, the item is removed and the inode it points
2217 * to is unlinked
2219 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2220 struct btrfs_root *root,
2221 struct btrfs_root *log,
2222 struct btrfs_path *path,
2223 struct btrfs_path *log_path,
2224 struct inode *dir,
2225 struct btrfs_key *dir_key)
2227 int ret;
2228 struct extent_buffer *eb;
2229 int slot;
2230 u32 item_size;
2231 struct btrfs_dir_item *di;
2232 struct btrfs_dir_item *log_di;
2233 int name_len;
2234 unsigned long ptr;
2235 unsigned long ptr_end;
2236 char *name;
2237 struct inode *inode;
2238 struct btrfs_key location;
2240 again:
2241 eb = path->nodes[0];
2242 slot = path->slots[0];
2243 item_size = btrfs_item_size_nr(eb, slot);
2244 ptr = btrfs_item_ptr_offset(eb, slot);
2245 ptr_end = ptr + item_size;
2246 while (ptr < ptr_end) {
2247 di = (struct btrfs_dir_item *)ptr;
2248 name_len = btrfs_dir_name_len(eb, di);
2249 name = kmalloc(name_len, GFP_NOFS);
2250 if (!name) {
2251 ret = -ENOMEM;
2252 goto out;
2254 read_extent_buffer(eb, name, (unsigned long)(di + 1),
2255 name_len);
2256 log_di = NULL;
2257 if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
2258 log_di = btrfs_lookup_dir_item(trans, log, log_path,
2259 dir_key->objectid,
2260 name, name_len, 0);
2261 } else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
2262 log_di = btrfs_lookup_dir_index_item(trans, log,
2263 log_path,
2264 dir_key->objectid,
2265 dir_key->offset,
2266 name, name_len, 0);
2268 if (!log_di || log_di == ERR_PTR(-ENOENT)) {
2269 btrfs_dir_item_key_to_cpu(eb, di, &location);
2270 btrfs_release_path(path);
2271 btrfs_release_path(log_path);
2272 inode = read_one_inode(root, location.objectid);
2273 if (!inode) {
2274 kfree(name);
2275 return -EIO;
2278 ret = link_to_fixup_dir(trans, root,
2279 path, location.objectid);
2280 if (ret) {
2281 kfree(name);
2282 iput(inode);
2283 goto out;
2286 inc_nlink(inode);
2287 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
2288 BTRFS_I(inode), name, name_len);
2289 if (!ret)
2290 ret = btrfs_run_delayed_items(trans);
2291 kfree(name);
2292 iput(inode);
2293 if (ret)
2294 goto out;
2296 /* there might still be more names under this key
2297 * check and repeat if required
2299 ret = btrfs_search_slot(NULL, root, dir_key, path,
2300 0, 0);
2301 if (ret == 0)
2302 goto again;
2303 ret = 0;
2304 goto out;
2305 } else if (IS_ERR(log_di)) {
2306 kfree(name);
2307 return PTR_ERR(log_di);
2309 btrfs_release_path(log_path);
2310 kfree(name);
2312 ptr = (unsigned long)(di + 1);
2313 ptr += name_len;
2315 ret = 0;
2316 out:
2317 btrfs_release_path(path);
2318 btrfs_release_path(log_path);
2319 return ret;
2322 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2323 struct btrfs_root *root,
2324 struct btrfs_root *log,
2325 struct btrfs_path *path,
2326 const u64 ino)
2328 struct btrfs_key search_key;
2329 struct btrfs_path *log_path;
2330 int i;
2331 int nritems;
2332 int ret;
2334 log_path = btrfs_alloc_path();
2335 if (!log_path)
2336 return -ENOMEM;
2338 search_key.objectid = ino;
2339 search_key.type = BTRFS_XATTR_ITEM_KEY;
2340 search_key.offset = 0;
2341 again:
2342 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2343 if (ret < 0)
2344 goto out;
2345 process_leaf:
2346 nritems = btrfs_header_nritems(path->nodes[0]);
2347 for (i = path->slots[0]; i < nritems; i++) {
2348 struct btrfs_key key;
2349 struct btrfs_dir_item *di;
2350 struct btrfs_dir_item *log_di;
2351 u32 total_size;
2352 u32 cur;
2354 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2355 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2356 ret = 0;
2357 goto out;
2360 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2361 total_size = btrfs_item_size_nr(path->nodes[0], i);
2362 cur = 0;
2363 while (cur < total_size) {
2364 u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2365 u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2366 u32 this_len = sizeof(*di) + name_len + data_len;
2367 char *name;
2369 name = kmalloc(name_len, GFP_NOFS);
2370 if (!name) {
2371 ret = -ENOMEM;
2372 goto out;
2374 read_extent_buffer(path->nodes[0], name,
2375 (unsigned long)(di + 1), name_len);
2377 log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2378 name, name_len, 0);
2379 btrfs_release_path(log_path);
2380 if (!log_di) {
2381 /* Doesn't exist in log tree, so delete it. */
2382 btrfs_release_path(path);
2383 di = btrfs_lookup_xattr(trans, root, path, ino,
2384 name, name_len, -1);
2385 kfree(name);
2386 if (IS_ERR(di)) {
2387 ret = PTR_ERR(di);
2388 goto out;
2390 ASSERT(di);
2391 ret = btrfs_delete_one_dir_name(trans, root,
2392 path, di);
2393 if (ret)
2394 goto out;
2395 btrfs_release_path(path);
2396 search_key = key;
2397 goto again;
2399 kfree(name);
2400 if (IS_ERR(log_di)) {
2401 ret = PTR_ERR(log_di);
2402 goto out;
2404 cur += this_len;
2405 di = (struct btrfs_dir_item *)((char *)di + this_len);
2408 ret = btrfs_next_leaf(root, path);
2409 if (ret > 0)
2410 ret = 0;
2411 else if (ret == 0)
2412 goto process_leaf;
2413 out:
2414 btrfs_free_path(log_path);
2415 btrfs_release_path(path);
2416 return ret;
2421 * deletion replay happens before we copy any new directory items
2422 * out of the log or out of backreferences from inodes. It
2423 * scans the log to find ranges of keys that log is authoritative for,
2424 * and then scans the directory to find items in those ranges that are
2425 * not present in the log.
2427 * Anything we don't find in the log is unlinked and removed from the
2428 * directory.
2430 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2431 struct btrfs_root *root,
2432 struct btrfs_root *log,
2433 struct btrfs_path *path,
2434 u64 dirid, int del_all)
2436 u64 range_start;
2437 u64 range_end;
2438 int key_type = BTRFS_DIR_LOG_ITEM_KEY;
2439 int ret = 0;
2440 struct btrfs_key dir_key;
2441 struct btrfs_key found_key;
2442 struct btrfs_path *log_path;
2443 struct inode *dir;
2445 dir_key.objectid = dirid;
2446 dir_key.type = BTRFS_DIR_ITEM_KEY;
2447 log_path = btrfs_alloc_path();
2448 if (!log_path)
2449 return -ENOMEM;
2451 dir = read_one_inode(root, dirid);
2452 /* it isn't an error if the inode isn't there, that can happen
2453 * because we replay the deletes before we copy in the inode item
2454 * from the log
2456 if (!dir) {
2457 btrfs_free_path(log_path);
2458 return 0;
2460 again:
2461 range_start = 0;
2462 range_end = 0;
2463 while (1) {
2464 if (del_all)
2465 range_end = (u64)-1;
2466 else {
2467 ret = find_dir_range(log, path, dirid, key_type,
2468 &range_start, &range_end);
2469 if (ret != 0)
2470 break;
2473 dir_key.offset = range_start;
2474 while (1) {
2475 int nritems;
2476 ret = btrfs_search_slot(NULL, root, &dir_key, path,
2477 0, 0);
2478 if (ret < 0)
2479 goto out;
2481 nritems = btrfs_header_nritems(path->nodes[0]);
2482 if (path->slots[0] >= nritems) {
2483 ret = btrfs_next_leaf(root, path);
2484 if (ret == 1)
2485 break;
2486 else if (ret < 0)
2487 goto out;
2489 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2490 path->slots[0]);
2491 if (found_key.objectid != dirid ||
2492 found_key.type != dir_key.type)
2493 goto next_type;
2495 if (found_key.offset > range_end)
2496 break;
2498 ret = check_item_in_log(trans, root, log, path,
2499 log_path, dir,
2500 &found_key);
2501 if (ret)
2502 goto out;
2503 if (found_key.offset == (u64)-1)
2504 break;
2505 dir_key.offset = found_key.offset + 1;
2507 btrfs_release_path(path);
2508 if (range_end == (u64)-1)
2509 break;
2510 range_start = range_end + 1;
2513 next_type:
2514 ret = 0;
2515 if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
2516 key_type = BTRFS_DIR_LOG_INDEX_KEY;
2517 dir_key.type = BTRFS_DIR_INDEX_KEY;
2518 btrfs_release_path(path);
2519 goto again;
2521 out:
2522 btrfs_release_path(path);
2523 btrfs_free_path(log_path);
2524 iput(dir);
2525 return ret;
2529 * the process_func used to replay items from the log tree. This
2530 * gets called in two different stages. The first stage just looks
2531 * for inodes and makes sure they are all copied into the subvolume.
2533 * The second stage copies all the other item types from the log into
2534 * the subvolume. The two stage approach is slower, but gets rid of
2535 * lots of complexity around inodes referencing other inodes that exist
2536 * only in the log (references come from either directory items or inode
2537 * back refs).
2539 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2540 struct walk_control *wc, u64 gen, int level)
2542 int nritems;
2543 struct btrfs_path *path;
2544 struct btrfs_root *root = wc->replay_dest;
2545 struct btrfs_key key;
2546 int i;
2547 int ret;
2549 ret = btrfs_read_buffer(eb, gen, level, NULL);
2550 if (ret)
2551 return ret;
2553 level = btrfs_header_level(eb);
2555 if (level != 0)
2556 return 0;
2558 path = btrfs_alloc_path();
2559 if (!path)
2560 return -ENOMEM;
2562 nritems = btrfs_header_nritems(eb);
2563 for (i = 0; i < nritems; i++) {
2564 btrfs_item_key_to_cpu(eb, &key, i);
2566 /* inode keys are done during the first stage */
2567 if (key.type == BTRFS_INODE_ITEM_KEY &&
2568 wc->stage == LOG_WALK_REPLAY_INODES) {
2569 struct btrfs_inode_item *inode_item;
2570 u32 mode;
2572 inode_item = btrfs_item_ptr(eb, i,
2573 struct btrfs_inode_item);
2575 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2576 * and never got linked before the fsync, skip it, as
2577 * replaying it is pointless since it would be deleted
2578 * later. We skip logging tmpfiles, but it's always
2579 * possible we are replaying a log created with a kernel
2580 * that used to log tmpfiles.
2582 if (btrfs_inode_nlink(eb, inode_item) == 0) {
2583 wc->ignore_cur_inode = true;
2584 continue;
2585 } else {
2586 wc->ignore_cur_inode = false;
2588 ret = replay_xattr_deletes(wc->trans, root, log,
2589 path, key.objectid);
2590 if (ret)
2591 break;
2592 mode = btrfs_inode_mode(eb, inode_item);
2593 if (S_ISDIR(mode)) {
2594 ret = replay_dir_deletes(wc->trans,
2595 root, log, path, key.objectid, 0);
2596 if (ret)
2597 break;
2599 ret = overwrite_item(wc->trans, root, path,
2600 eb, i, &key);
2601 if (ret)
2602 break;
2605 * Before replaying extents, truncate the inode to its
2606 * size. We need to do it now and not after log replay
2607 * because before an fsync we can have prealloc extents
2608 * added beyond the inode's i_size. If we did it after,
2609 * through orphan cleanup for example, we would drop
2610 * those prealloc extents just after replaying them.
2612 if (S_ISREG(mode)) {
2613 struct inode *inode;
2614 u64 from;
2616 inode = read_one_inode(root, key.objectid);
2617 if (!inode) {
2618 ret = -EIO;
2619 break;
2621 from = ALIGN(i_size_read(inode),
2622 root->fs_info->sectorsize);
2623 ret = btrfs_drop_extents(wc->trans, root, inode,
2624 from, (u64)-1, 1);
2625 if (!ret) {
2626 /* Update the inode's nbytes. */
2627 ret = btrfs_update_inode(wc->trans,
2628 root, inode);
2630 iput(inode);
2631 if (ret)
2632 break;
2635 ret = link_to_fixup_dir(wc->trans, root,
2636 path, key.objectid);
2637 if (ret)
2638 break;
2641 if (wc->ignore_cur_inode)
2642 continue;
2644 if (key.type == BTRFS_DIR_INDEX_KEY &&
2645 wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2646 ret = replay_one_dir_item(wc->trans, root, path,
2647 eb, i, &key);
2648 if (ret)
2649 break;
2652 if (wc->stage < LOG_WALK_REPLAY_ALL)
2653 continue;
2655 /* these keys are simply copied */
2656 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2657 ret = overwrite_item(wc->trans, root, path,
2658 eb, i, &key);
2659 if (ret)
2660 break;
2661 } else if (key.type == BTRFS_INODE_REF_KEY ||
2662 key.type == BTRFS_INODE_EXTREF_KEY) {
2663 ret = add_inode_ref(wc->trans, root, log, path,
2664 eb, i, &key);
2665 if (ret && ret != -ENOENT)
2666 break;
2667 ret = 0;
2668 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2669 ret = replay_one_extent(wc->trans, root, path,
2670 eb, i, &key);
2671 if (ret)
2672 break;
2673 } else if (key.type == BTRFS_DIR_ITEM_KEY) {
2674 ret = replay_one_dir_item(wc->trans, root, path,
2675 eb, i, &key);
2676 if (ret)
2677 break;
2680 btrfs_free_path(path);
2681 return ret;
2684 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2685 struct btrfs_root *root,
2686 struct btrfs_path *path, int *level,
2687 struct walk_control *wc)
2689 struct btrfs_fs_info *fs_info = root->fs_info;
2690 u64 root_owner;
2691 u64 bytenr;
2692 u64 ptr_gen;
2693 struct extent_buffer *next;
2694 struct extent_buffer *cur;
2695 struct extent_buffer *parent;
2696 u32 blocksize;
2697 int ret = 0;
2699 WARN_ON(*level < 0);
2700 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2702 while (*level > 0) {
2703 struct btrfs_key first_key;
2705 WARN_ON(*level < 0);
2706 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2707 cur = path->nodes[*level];
2709 WARN_ON(btrfs_header_level(cur) != *level);
2711 if (path->slots[*level] >=
2712 btrfs_header_nritems(cur))
2713 break;
2715 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2716 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2717 btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2718 blocksize = fs_info->nodesize;
2720 parent = path->nodes[*level];
2721 root_owner = btrfs_header_owner(parent);
2723 next = btrfs_find_create_tree_block(fs_info, bytenr);
2724 if (IS_ERR(next))
2725 return PTR_ERR(next);
2727 if (*level == 1) {
2728 ret = wc->process_func(root, next, wc, ptr_gen,
2729 *level - 1);
2730 if (ret) {
2731 free_extent_buffer(next);
2732 return ret;
2735 path->slots[*level]++;
2736 if (wc->free) {
2737 ret = btrfs_read_buffer(next, ptr_gen,
2738 *level - 1, &first_key);
2739 if (ret) {
2740 free_extent_buffer(next);
2741 return ret;
2744 if (trans) {
2745 btrfs_tree_lock(next);
2746 btrfs_set_lock_blocking_write(next);
2747 btrfs_clean_tree_block(next);
2748 btrfs_wait_tree_block_writeback(next);
2749 btrfs_tree_unlock(next);
2750 } else {
2751 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2752 clear_extent_buffer_dirty(next);
2755 WARN_ON(root_owner !=
2756 BTRFS_TREE_LOG_OBJECTID);
2757 ret = btrfs_free_and_pin_reserved_extent(
2758 fs_info, bytenr,
2759 blocksize);
2760 if (ret) {
2761 free_extent_buffer(next);
2762 return ret;
2765 free_extent_buffer(next);
2766 continue;
2768 ret = btrfs_read_buffer(next, ptr_gen, *level - 1, &first_key);
2769 if (ret) {
2770 free_extent_buffer(next);
2771 return ret;
2774 WARN_ON(*level <= 0);
2775 if (path->nodes[*level-1])
2776 free_extent_buffer(path->nodes[*level-1]);
2777 path->nodes[*level-1] = next;
2778 *level = btrfs_header_level(next);
2779 path->slots[*level] = 0;
2780 cond_resched();
2782 WARN_ON(*level < 0);
2783 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2785 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2787 cond_resched();
2788 return 0;
2791 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2792 struct btrfs_root *root,
2793 struct btrfs_path *path, int *level,
2794 struct walk_control *wc)
2796 struct btrfs_fs_info *fs_info = root->fs_info;
2797 u64 root_owner;
2798 int i;
2799 int slot;
2800 int ret;
2802 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2803 slot = path->slots[i];
2804 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2805 path->slots[i]++;
2806 *level = i;
2807 WARN_ON(*level == 0);
2808 return 0;
2809 } else {
2810 struct extent_buffer *parent;
2811 if (path->nodes[*level] == root->node)
2812 parent = path->nodes[*level];
2813 else
2814 parent = path->nodes[*level + 1];
2816 root_owner = btrfs_header_owner(parent);
2817 ret = wc->process_func(root, path->nodes[*level], wc,
2818 btrfs_header_generation(path->nodes[*level]),
2819 *level);
2820 if (ret)
2821 return ret;
2823 if (wc->free) {
2824 struct extent_buffer *next;
2826 next = path->nodes[*level];
2828 if (trans) {
2829 btrfs_tree_lock(next);
2830 btrfs_set_lock_blocking_write(next);
2831 btrfs_clean_tree_block(next);
2832 btrfs_wait_tree_block_writeback(next);
2833 btrfs_tree_unlock(next);
2834 } else {
2835 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2836 clear_extent_buffer_dirty(next);
2839 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2840 ret = btrfs_free_and_pin_reserved_extent(
2841 fs_info,
2842 path->nodes[*level]->start,
2843 path->nodes[*level]->len);
2844 if (ret)
2845 return ret;
2847 free_extent_buffer(path->nodes[*level]);
2848 path->nodes[*level] = NULL;
2849 *level = i + 1;
2852 return 1;
2856 * drop the reference count on the tree rooted at 'snap'. This traverses
2857 * the tree freeing any blocks that have a ref count of zero after being
2858 * decremented.
2860 static int walk_log_tree(struct btrfs_trans_handle *trans,
2861 struct btrfs_root *log, struct walk_control *wc)
2863 struct btrfs_fs_info *fs_info = log->fs_info;
2864 int ret = 0;
2865 int wret;
2866 int level;
2867 struct btrfs_path *path;
2868 int orig_level;
2870 path = btrfs_alloc_path();
2871 if (!path)
2872 return -ENOMEM;
2874 level = btrfs_header_level(log->node);
2875 orig_level = level;
2876 path->nodes[level] = log->node;
2877 extent_buffer_get(log->node);
2878 path->slots[level] = 0;
2880 while (1) {
2881 wret = walk_down_log_tree(trans, log, path, &level, wc);
2882 if (wret > 0)
2883 break;
2884 if (wret < 0) {
2885 ret = wret;
2886 goto out;
2889 wret = walk_up_log_tree(trans, log, path, &level, wc);
2890 if (wret > 0)
2891 break;
2892 if (wret < 0) {
2893 ret = wret;
2894 goto out;
2898 /* was the root node processed? if not, catch it here */
2899 if (path->nodes[orig_level]) {
2900 ret = wc->process_func(log, path->nodes[orig_level], wc,
2901 btrfs_header_generation(path->nodes[orig_level]),
2902 orig_level);
2903 if (ret)
2904 goto out;
2905 if (wc->free) {
2906 struct extent_buffer *next;
2908 next = path->nodes[orig_level];
2910 if (trans) {
2911 btrfs_tree_lock(next);
2912 btrfs_set_lock_blocking_write(next);
2913 btrfs_clean_tree_block(next);
2914 btrfs_wait_tree_block_writeback(next);
2915 btrfs_tree_unlock(next);
2916 } else {
2917 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2918 clear_extent_buffer_dirty(next);
2921 WARN_ON(log->root_key.objectid !=
2922 BTRFS_TREE_LOG_OBJECTID);
2923 ret = btrfs_free_and_pin_reserved_extent(fs_info,
2924 next->start, next->len);
2925 if (ret)
2926 goto out;
2930 out:
2931 btrfs_free_path(path);
2932 return ret;
2936 * helper function to update the item for a given subvolumes log root
2937 * in the tree of log roots
2939 static int update_log_root(struct btrfs_trans_handle *trans,
2940 struct btrfs_root *log,
2941 struct btrfs_root_item *root_item)
2943 struct btrfs_fs_info *fs_info = log->fs_info;
2944 int ret;
2946 if (log->log_transid == 1) {
2947 /* insert root item on the first sync */
2948 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2949 &log->root_key, root_item);
2950 } else {
2951 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2952 &log->root_key, root_item);
2954 return ret;
2957 static void wait_log_commit(struct btrfs_root *root, int transid)
2959 DEFINE_WAIT(wait);
2960 int index = transid % 2;
2963 * we only allow two pending log transactions at a time,
2964 * so we know that if ours is more than 2 older than the
2965 * current transaction, we're done
2967 for (;;) {
2968 prepare_to_wait(&root->log_commit_wait[index],
2969 &wait, TASK_UNINTERRUPTIBLE);
2971 if (!(root->log_transid_committed < transid &&
2972 atomic_read(&root->log_commit[index])))
2973 break;
2975 mutex_unlock(&root->log_mutex);
2976 schedule();
2977 mutex_lock(&root->log_mutex);
2979 finish_wait(&root->log_commit_wait[index], &wait);
2982 static void wait_for_writer(struct btrfs_root *root)
2984 DEFINE_WAIT(wait);
2986 for (;;) {
2987 prepare_to_wait(&root->log_writer_wait, &wait,
2988 TASK_UNINTERRUPTIBLE);
2989 if (!atomic_read(&root->log_writers))
2990 break;
2992 mutex_unlock(&root->log_mutex);
2993 schedule();
2994 mutex_lock(&root->log_mutex);
2996 finish_wait(&root->log_writer_wait, &wait);
2999 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
3000 struct btrfs_log_ctx *ctx)
3002 if (!ctx)
3003 return;
3005 mutex_lock(&root->log_mutex);
3006 list_del_init(&ctx->list);
3007 mutex_unlock(&root->log_mutex);
3011 * Invoked in log mutex context, or be sure there is no other task which
3012 * can access the list.
3014 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
3015 int index, int error)
3017 struct btrfs_log_ctx *ctx;
3018 struct btrfs_log_ctx *safe;
3020 list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
3021 list_del_init(&ctx->list);
3022 ctx->log_ret = error;
3025 INIT_LIST_HEAD(&root->log_ctxs[index]);
3029 * btrfs_sync_log does sends a given tree log down to the disk and
3030 * updates the super blocks to record it. When this call is done,
3031 * you know that any inodes previously logged are safely on disk only
3032 * if it returns 0.
3034 * Any other return value means you need to call btrfs_commit_transaction.
3035 * Some of the edge cases for fsyncing directories that have had unlinks
3036 * or renames done in the past mean that sometimes the only safe
3037 * fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
3038 * that has happened.
3040 int btrfs_sync_log(struct btrfs_trans_handle *trans,
3041 struct btrfs_root *root, struct btrfs_log_ctx *ctx)
3043 int index1;
3044 int index2;
3045 int mark;
3046 int ret;
3047 struct btrfs_fs_info *fs_info = root->fs_info;
3048 struct btrfs_root *log = root->log_root;
3049 struct btrfs_root *log_root_tree = fs_info->log_root_tree;
3050 struct btrfs_root_item new_root_item;
3051 int log_transid = 0;
3052 struct btrfs_log_ctx root_log_ctx;
3053 struct blk_plug plug;
3055 mutex_lock(&root->log_mutex);
3056 log_transid = ctx->log_transid;
3057 if (root->log_transid_committed >= log_transid) {
3058 mutex_unlock(&root->log_mutex);
3059 return ctx->log_ret;
3062 index1 = log_transid % 2;
3063 if (atomic_read(&root->log_commit[index1])) {
3064 wait_log_commit(root, log_transid);
3065 mutex_unlock(&root->log_mutex);
3066 return ctx->log_ret;
3068 ASSERT(log_transid == root->log_transid);
3069 atomic_set(&root->log_commit[index1], 1);
3071 /* wait for previous tree log sync to complete */
3072 if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
3073 wait_log_commit(root, log_transid - 1);
3075 while (1) {
3076 int batch = atomic_read(&root->log_batch);
3077 /* when we're on an ssd, just kick the log commit out */
3078 if (!btrfs_test_opt(fs_info, SSD) &&
3079 test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
3080 mutex_unlock(&root->log_mutex);
3081 schedule_timeout_uninterruptible(1);
3082 mutex_lock(&root->log_mutex);
3084 wait_for_writer(root);
3085 if (batch == atomic_read(&root->log_batch))
3086 break;
3089 /* bail out if we need to do a full commit */
3090 if (btrfs_need_log_full_commit(trans)) {
3091 ret = -EAGAIN;
3092 mutex_unlock(&root->log_mutex);
3093 goto out;
3096 if (log_transid % 2 == 0)
3097 mark = EXTENT_DIRTY;
3098 else
3099 mark = EXTENT_NEW;
3101 /* we start IO on all the marked extents here, but we don't actually
3102 * wait for them until later.
3104 blk_start_plug(&plug);
3105 ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
3106 if (ret) {
3107 blk_finish_plug(&plug);
3108 btrfs_abort_transaction(trans, ret);
3109 btrfs_set_log_full_commit(trans);
3110 mutex_unlock(&root->log_mutex);
3111 goto out;
3115 * We _must_ update under the root->log_mutex in order to make sure we
3116 * have a consistent view of the log root we are trying to commit at
3117 * this moment.
3119 * We _must_ copy this into a local copy, because we are not holding the
3120 * log_root_tree->log_mutex yet. This is important because when we
3121 * commit the log_root_tree we must have a consistent view of the
3122 * log_root_tree when we update the super block to point at the
3123 * log_root_tree bytenr. If we update the log_root_tree here we'll race
3124 * with the commit and possibly point at the new block which we may not
3125 * have written out.
3127 btrfs_set_root_node(&log->root_item, log->node);
3128 memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3130 root->log_transid++;
3131 log->log_transid = root->log_transid;
3132 root->log_start_pid = 0;
3134 * IO has been started, blocks of the log tree have WRITTEN flag set
3135 * in their headers. new modifications of the log will be written to
3136 * new positions. so it's safe to allow log writers to go in.
3138 mutex_unlock(&root->log_mutex);
3140 btrfs_init_log_ctx(&root_log_ctx, NULL);
3142 mutex_lock(&log_root_tree->log_mutex);
3144 index2 = log_root_tree->log_transid % 2;
3145 list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3146 root_log_ctx.log_transid = log_root_tree->log_transid;
3149 * Now we are safe to update the log_root_tree because we're under the
3150 * log_mutex, and we're a current writer so we're holding the commit
3151 * open until we drop the log_mutex.
3153 ret = update_log_root(trans, log, &new_root_item);
3154 if (ret) {
3155 if (!list_empty(&root_log_ctx.list))
3156 list_del_init(&root_log_ctx.list);
3158 blk_finish_plug(&plug);
3159 btrfs_set_log_full_commit(trans);
3161 if (ret != -ENOSPC) {
3162 btrfs_abort_transaction(trans, ret);
3163 mutex_unlock(&log_root_tree->log_mutex);
3164 goto out;
3166 btrfs_wait_tree_log_extents(log, mark);
3167 mutex_unlock(&log_root_tree->log_mutex);
3168 ret = -EAGAIN;
3169 goto out;
3172 if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3173 blk_finish_plug(&plug);
3174 list_del_init(&root_log_ctx.list);
3175 mutex_unlock(&log_root_tree->log_mutex);
3176 ret = root_log_ctx.log_ret;
3177 goto out;
3180 index2 = root_log_ctx.log_transid % 2;
3181 if (atomic_read(&log_root_tree->log_commit[index2])) {
3182 blk_finish_plug(&plug);
3183 ret = btrfs_wait_tree_log_extents(log, mark);
3184 wait_log_commit(log_root_tree,
3185 root_log_ctx.log_transid);
3186 mutex_unlock(&log_root_tree->log_mutex);
3187 if (!ret)
3188 ret = root_log_ctx.log_ret;
3189 goto out;
3191 ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
3192 atomic_set(&log_root_tree->log_commit[index2], 1);
3194 if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3195 wait_log_commit(log_root_tree,
3196 root_log_ctx.log_transid - 1);
3200 * now that we've moved on to the tree of log tree roots,
3201 * check the full commit flag again
3203 if (btrfs_need_log_full_commit(trans)) {
3204 blk_finish_plug(&plug);
3205 btrfs_wait_tree_log_extents(log, mark);
3206 mutex_unlock(&log_root_tree->log_mutex);
3207 ret = -EAGAIN;
3208 goto out_wake_log_root;
3211 ret = btrfs_write_marked_extents(fs_info,
3212 &log_root_tree->dirty_log_pages,
3213 EXTENT_DIRTY | EXTENT_NEW);
3214 blk_finish_plug(&plug);
3215 if (ret) {
3216 btrfs_set_log_full_commit(trans);
3217 btrfs_abort_transaction(trans, ret);
3218 mutex_unlock(&log_root_tree->log_mutex);
3219 goto out_wake_log_root;
3221 ret = btrfs_wait_tree_log_extents(log, mark);
3222 if (!ret)
3223 ret = btrfs_wait_tree_log_extents(log_root_tree,
3224 EXTENT_NEW | EXTENT_DIRTY);
3225 if (ret) {
3226 btrfs_set_log_full_commit(trans);
3227 mutex_unlock(&log_root_tree->log_mutex);
3228 goto out_wake_log_root;
3231 btrfs_set_super_log_root(fs_info->super_for_commit,
3232 log_root_tree->node->start);
3233 btrfs_set_super_log_root_level(fs_info->super_for_commit,
3234 btrfs_header_level(log_root_tree->node));
3236 log_root_tree->log_transid++;
3237 mutex_unlock(&log_root_tree->log_mutex);
3240 * Nobody else is going to jump in and write the ctree
3241 * super here because the log_commit atomic below is protecting
3242 * us. We must be called with a transaction handle pinning
3243 * the running transaction open, so a full commit can't hop
3244 * in and cause problems either.
3246 ret = write_all_supers(fs_info, 1);
3247 if (ret) {
3248 btrfs_set_log_full_commit(trans);
3249 btrfs_abort_transaction(trans, ret);
3250 goto out_wake_log_root;
3253 mutex_lock(&root->log_mutex);
3254 if (root->last_log_commit < log_transid)
3255 root->last_log_commit = log_transid;
3256 mutex_unlock(&root->log_mutex);
3258 out_wake_log_root:
3259 mutex_lock(&log_root_tree->log_mutex);
3260 btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3262 log_root_tree->log_transid_committed++;
3263 atomic_set(&log_root_tree->log_commit[index2], 0);
3264 mutex_unlock(&log_root_tree->log_mutex);
3267 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3268 * all the updates above are seen by the woken threads. It might not be
3269 * necessary, but proving that seems to be hard.
3271 cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3272 out:
3273 mutex_lock(&root->log_mutex);
3274 btrfs_remove_all_log_ctxs(root, index1, ret);
3275 root->log_transid_committed++;
3276 atomic_set(&root->log_commit[index1], 0);
3277 mutex_unlock(&root->log_mutex);
3280 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3281 * all the updates above are seen by the woken threads. It might not be
3282 * necessary, but proving that seems to be hard.
3284 cond_wake_up(&root->log_commit_wait[index1]);
3285 return ret;
3288 static void free_log_tree(struct btrfs_trans_handle *trans,
3289 struct btrfs_root *log)
3291 int ret;
3292 struct walk_control wc = {
3293 .free = 1,
3294 .process_func = process_one_buffer
3297 ret = walk_log_tree(trans, log, &wc);
3298 if (ret) {
3299 if (trans)
3300 btrfs_abort_transaction(trans, ret);
3301 else
3302 btrfs_handle_fs_error(log->fs_info, ret, NULL);
3305 clear_extent_bits(&log->dirty_log_pages, 0, (u64)-1,
3306 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3307 free_extent_buffer(log->node);
3308 kfree(log);
3312 * free all the extents used by the tree log. This should be called
3313 * at commit time of the full transaction
3315 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3317 if (root->log_root) {
3318 free_log_tree(trans, root->log_root);
3319 root->log_root = NULL;
3320 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
3322 return 0;
3325 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3326 struct btrfs_fs_info *fs_info)
3328 if (fs_info->log_root_tree) {
3329 free_log_tree(trans, fs_info->log_root_tree);
3330 fs_info->log_root_tree = NULL;
3332 return 0;
3336 * Check if an inode was logged in the current transaction. We can't always rely
3337 * on an inode's logged_trans value, because it's an in-memory only field and
3338 * therefore not persisted. This means that its value is lost if the inode gets
3339 * evicted and loaded again from disk (in which case it has a value of 0, and
3340 * certainly it is smaller then any possible transaction ID), when that happens
3341 * the full_sync flag is set in the inode's runtime flags, so on that case we
3342 * assume eviction happened and ignore the logged_trans value, assuming the
3343 * worst case, that the inode was logged before in the current transaction.
3345 static bool inode_logged(struct btrfs_trans_handle *trans,
3346 struct btrfs_inode *inode)
3348 if (inode->logged_trans == trans->transid)
3349 return true;
3351 if (inode->last_trans == trans->transid &&
3352 test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) &&
3353 !test_bit(BTRFS_FS_LOG_RECOVERING, &trans->fs_info->flags))
3354 return true;
3356 return false;
3360 * If both a file and directory are logged, and unlinks or renames are
3361 * mixed in, we have a few interesting corners:
3363 * create file X in dir Y
3364 * link file X to X.link in dir Y
3365 * fsync file X
3366 * unlink file X but leave X.link
3367 * fsync dir Y
3369 * After a crash we would expect only X.link to exist. But file X
3370 * didn't get fsync'd again so the log has back refs for X and X.link.
3372 * We solve this by removing directory entries and inode backrefs from the
3373 * log when a file that was logged in the current transaction is
3374 * unlinked. Any later fsync will include the updated log entries, and
3375 * we'll be able to reconstruct the proper directory items from backrefs.
3377 * This optimizations allows us to avoid relogging the entire inode
3378 * or the entire directory.
3380 int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3381 struct btrfs_root *root,
3382 const char *name, int name_len,
3383 struct btrfs_inode *dir, u64 index)
3385 struct btrfs_root *log;
3386 struct btrfs_dir_item *di;
3387 struct btrfs_path *path;
3388 int ret;
3389 int err = 0;
3390 int bytes_del = 0;
3391 u64 dir_ino = btrfs_ino(dir);
3393 if (!inode_logged(trans, dir))
3394 return 0;
3396 ret = join_running_log_trans(root);
3397 if (ret)
3398 return 0;
3400 mutex_lock(&dir->log_mutex);
3402 log = root->log_root;
3403 path = btrfs_alloc_path();
3404 if (!path) {
3405 err = -ENOMEM;
3406 goto out_unlock;
3409 di = btrfs_lookup_dir_item(trans, log, path, dir_ino,
3410 name, name_len, -1);
3411 if (IS_ERR(di)) {
3412 err = PTR_ERR(di);
3413 goto fail;
3415 if (di) {
3416 ret = btrfs_delete_one_dir_name(trans, log, path, di);
3417 bytes_del += name_len;
3418 if (ret) {
3419 err = ret;
3420 goto fail;
3423 btrfs_release_path(path);
3424 di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3425 index, name, name_len, -1);
3426 if (IS_ERR(di)) {
3427 err = PTR_ERR(di);
3428 goto fail;
3430 if (di) {
3431 ret = btrfs_delete_one_dir_name(trans, log, path, di);
3432 bytes_del += name_len;
3433 if (ret) {
3434 err = ret;
3435 goto fail;
3439 /* update the directory size in the log to reflect the names
3440 * we have removed
3442 if (bytes_del) {
3443 struct btrfs_key key;
3445 key.objectid = dir_ino;
3446 key.offset = 0;
3447 key.type = BTRFS_INODE_ITEM_KEY;
3448 btrfs_release_path(path);
3450 ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
3451 if (ret < 0) {
3452 err = ret;
3453 goto fail;
3455 if (ret == 0) {
3456 struct btrfs_inode_item *item;
3457 u64 i_size;
3459 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3460 struct btrfs_inode_item);
3461 i_size = btrfs_inode_size(path->nodes[0], item);
3462 if (i_size > bytes_del)
3463 i_size -= bytes_del;
3464 else
3465 i_size = 0;
3466 btrfs_set_inode_size(path->nodes[0], item, i_size);
3467 btrfs_mark_buffer_dirty(path->nodes[0]);
3468 } else
3469 ret = 0;
3470 btrfs_release_path(path);
3472 fail:
3473 btrfs_free_path(path);
3474 out_unlock:
3475 mutex_unlock(&dir->log_mutex);
3476 if (ret == -ENOSPC) {
3477 btrfs_set_log_full_commit(trans);
3478 ret = 0;
3479 } else if (ret < 0)
3480 btrfs_abort_transaction(trans, ret);
3482 btrfs_end_log_trans(root);
3484 return err;
3487 /* see comments for btrfs_del_dir_entries_in_log */
3488 int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3489 struct btrfs_root *root,
3490 const char *name, int name_len,
3491 struct btrfs_inode *inode, u64 dirid)
3493 struct btrfs_root *log;
3494 u64 index;
3495 int ret;
3497 if (!inode_logged(trans, inode))
3498 return 0;
3500 ret = join_running_log_trans(root);
3501 if (ret)
3502 return 0;
3503 log = root->log_root;
3504 mutex_lock(&inode->log_mutex);
3506 ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
3507 dirid, &index);
3508 mutex_unlock(&inode->log_mutex);
3509 if (ret == -ENOSPC) {
3510 btrfs_set_log_full_commit(trans);
3511 ret = 0;
3512 } else if (ret < 0 && ret != -ENOENT)
3513 btrfs_abort_transaction(trans, ret);
3514 btrfs_end_log_trans(root);
3516 return ret;
3520 * creates a range item in the log for 'dirid'. first_offset and
3521 * last_offset tell us which parts of the key space the log should
3522 * be considered authoritative for.
3524 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3525 struct btrfs_root *log,
3526 struct btrfs_path *path,
3527 int key_type, u64 dirid,
3528 u64 first_offset, u64 last_offset)
3530 int ret;
3531 struct btrfs_key key;
3532 struct btrfs_dir_log_item *item;
3534 key.objectid = dirid;
3535 key.offset = first_offset;
3536 if (key_type == BTRFS_DIR_ITEM_KEY)
3537 key.type = BTRFS_DIR_LOG_ITEM_KEY;
3538 else
3539 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3540 ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3541 if (ret)
3542 return ret;
3544 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3545 struct btrfs_dir_log_item);
3546 btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3547 btrfs_mark_buffer_dirty(path->nodes[0]);
3548 btrfs_release_path(path);
3549 return 0;
3553 * log all the items included in the current transaction for a given
3554 * directory. This also creates the range items in the log tree required
3555 * to replay anything deleted before the fsync
3557 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3558 struct btrfs_root *root, struct btrfs_inode *inode,
3559 struct btrfs_path *path,
3560 struct btrfs_path *dst_path, int key_type,
3561 struct btrfs_log_ctx *ctx,
3562 u64 min_offset, u64 *last_offset_ret)
3564 struct btrfs_key min_key;
3565 struct btrfs_root *log = root->log_root;
3566 struct extent_buffer *src;
3567 int err = 0;
3568 int ret;
3569 int i;
3570 int nritems;
3571 u64 first_offset = min_offset;
3572 u64 last_offset = (u64)-1;
3573 u64 ino = btrfs_ino(inode);
3575 log = root->log_root;
3577 min_key.objectid = ino;
3578 min_key.type = key_type;
3579 min_key.offset = min_offset;
3581 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3584 * we didn't find anything from this transaction, see if there
3585 * is anything at all
3587 if (ret != 0 || min_key.objectid != ino || min_key.type != key_type) {
3588 min_key.objectid = ino;
3589 min_key.type = key_type;
3590 min_key.offset = (u64)-1;
3591 btrfs_release_path(path);
3592 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3593 if (ret < 0) {
3594 btrfs_release_path(path);
3595 return ret;
3597 ret = btrfs_previous_item(root, path, ino, key_type);
3599 /* if ret == 0 there are items for this type,
3600 * create a range to tell us the last key of this type.
3601 * otherwise, there are no items in this directory after
3602 * *min_offset, and we create a range to indicate that.
3604 if (ret == 0) {
3605 struct btrfs_key tmp;
3606 btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3607 path->slots[0]);
3608 if (key_type == tmp.type)
3609 first_offset = max(min_offset, tmp.offset) + 1;
3611 goto done;
3614 /* go backward to find any previous key */
3615 ret = btrfs_previous_item(root, path, ino, key_type);
3616 if (ret == 0) {
3617 struct btrfs_key tmp;
3618 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3619 if (key_type == tmp.type) {
3620 first_offset = tmp.offset;
3621 ret = overwrite_item(trans, log, dst_path,
3622 path->nodes[0], path->slots[0],
3623 &tmp);
3624 if (ret) {
3625 err = ret;
3626 goto done;
3630 btrfs_release_path(path);
3633 * Find the first key from this transaction again. See the note for
3634 * log_new_dir_dentries, if we're logging a directory recursively we
3635 * won't be holding its i_mutex, which means we can modify the directory
3636 * while we're logging it. If we remove an entry between our first
3637 * search and this search we'll not find the key again and can just
3638 * bail.
3640 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3641 if (ret != 0)
3642 goto done;
3645 * we have a block from this transaction, log every item in it
3646 * from our directory
3648 while (1) {
3649 struct btrfs_key tmp;
3650 src = path->nodes[0];
3651 nritems = btrfs_header_nritems(src);
3652 for (i = path->slots[0]; i < nritems; i++) {
3653 struct btrfs_dir_item *di;
3655 btrfs_item_key_to_cpu(src, &min_key, i);
3657 if (min_key.objectid != ino || min_key.type != key_type)
3658 goto done;
3659 ret = overwrite_item(trans, log, dst_path, src, i,
3660 &min_key);
3661 if (ret) {
3662 err = ret;
3663 goto done;
3667 * We must make sure that when we log a directory entry,
3668 * the corresponding inode, after log replay, has a
3669 * matching link count. For example:
3671 * touch foo
3672 * mkdir mydir
3673 * sync
3674 * ln foo mydir/bar
3675 * xfs_io -c "fsync" mydir
3676 * <crash>
3677 * <mount fs and log replay>
3679 * Would result in a fsync log that when replayed, our
3680 * file inode would have a link count of 1, but we get
3681 * two directory entries pointing to the same inode.
3682 * After removing one of the names, it would not be
3683 * possible to remove the other name, which resulted
3684 * always in stale file handle errors, and would not
3685 * be possible to rmdir the parent directory, since
3686 * its i_size could never decrement to the value
3687 * BTRFS_EMPTY_DIR_SIZE, resulting in -ENOTEMPTY errors.
3689 di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3690 btrfs_dir_item_key_to_cpu(src, di, &tmp);
3691 if (ctx &&
3692 (btrfs_dir_transid(src, di) == trans->transid ||
3693 btrfs_dir_type(src, di) == BTRFS_FT_DIR) &&
3694 tmp.type != BTRFS_ROOT_ITEM_KEY)
3695 ctx->log_new_dentries = true;
3697 path->slots[0] = nritems;
3700 * look ahead to the next item and see if it is also
3701 * from this directory and from this transaction
3703 ret = btrfs_next_leaf(root, path);
3704 if (ret) {
3705 if (ret == 1)
3706 last_offset = (u64)-1;
3707 else
3708 err = ret;
3709 goto done;
3711 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3712 if (tmp.objectid != ino || tmp.type != key_type) {
3713 last_offset = (u64)-1;
3714 goto done;
3716 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3717 ret = overwrite_item(trans, log, dst_path,
3718 path->nodes[0], path->slots[0],
3719 &tmp);
3720 if (ret)
3721 err = ret;
3722 else
3723 last_offset = tmp.offset;
3724 goto done;
3727 done:
3728 btrfs_release_path(path);
3729 btrfs_release_path(dst_path);
3731 if (err == 0) {
3732 *last_offset_ret = last_offset;
3734 * insert the log range keys to indicate where the log
3735 * is valid
3737 ret = insert_dir_log_key(trans, log, path, key_type,
3738 ino, first_offset, last_offset);
3739 if (ret)
3740 err = ret;
3742 return err;
3746 * logging directories is very similar to logging inodes, We find all the items
3747 * from the current transaction and write them to the log.
3749 * The recovery code scans the directory in the subvolume, and if it finds a
3750 * key in the range logged that is not present in the log tree, then it means
3751 * that dir entry was unlinked during the transaction.
3753 * In order for that scan to work, we must include one key smaller than
3754 * the smallest logged by this transaction and one key larger than the largest
3755 * key logged by this transaction.
3757 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
3758 struct btrfs_root *root, struct btrfs_inode *inode,
3759 struct btrfs_path *path,
3760 struct btrfs_path *dst_path,
3761 struct btrfs_log_ctx *ctx)
3763 u64 min_key;
3764 u64 max_key;
3765 int ret;
3766 int key_type = BTRFS_DIR_ITEM_KEY;
3768 again:
3769 min_key = 0;
3770 max_key = 0;
3771 while (1) {
3772 ret = log_dir_items(trans, root, inode, path, dst_path, key_type,
3773 ctx, min_key, &max_key);
3774 if (ret)
3775 return ret;
3776 if (max_key == (u64)-1)
3777 break;
3778 min_key = max_key + 1;
3781 if (key_type == BTRFS_DIR_ITEM_KEY) {
3782 key_type = BTRFS_DIR_INDEX_KEY;
3783 goto again;
3785 return 0;
3789 * a helper function to drop items from the log before we relog an
3790 * inode. max_key_type indicates the highest item type to remove.
3791 * This cannot be run for file data extents because it does not
3792 * free the extents they point to.
3794 static int drop_objectid_items(struct btrfs_trans_handle *trans,
3795 struct btrfs_root *log,
3796 struct btrfs_path *path,
3797 u64 objectid, int max_key_type)
3799 int ret;
3800 struct btrfs_key key;
3801 struct btrfs_key found_key;
3802 int start_slot;
3804 key.objectid = objectid;
3805 key.type = max_key_type;
3806 key.offset = (u64)-1;
3808 while (1) {
3809 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
3810 BUG_ON(ret == 0); /* Logic error */
3811 if (ret < 0)
3812 break;
3814 if (path->slots[0] == 0)
3815 break;
3817 path->slots[0]--;
3818 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
3819 path->slots[0]);
3821 if (found_key.objectid != objectid)
3822 break;
3824 found_key.offset = 0;
3825 found_key.type = 0;
3826 ret = btrfs_bin_search(path->nodes[0], &found_key, 0,
3827 &start_slot);
3828 if (ret < 0)
3829 break;
3831 ret = btrfs_del_items(trans, log, path, start_slot,
3832 path->slots[0] - start_slot + 1);
3834 * If start slot isn't 0 then we don't need to re-search, we've
3835 * found the last guy with the objectid in this tree.
3837 if (ret || start_slot != 0)
3838 break;
3839 btrfs_release_path(path);
3841 btrfs_release_path(path);
3842 if (ret > 0)
3843 ret = 0;
3844 return ret;
3847 static void fill_inode_item(struct btrfs_trans_handle *trans,
3848 struct extent_buffer *leaf,
3849 struct btrfs_inode_item *item,
3850 struct inode *inode, int log_inode_only,
3851 u64 logged_isize)
3853 struct btrfs_map_token token;
3855 btrfs_init_map_token(&token, leaf);
3857 if (log_inode_only) {
3858 /* set the generation to zero so the recover code
3859 * can tell the difference between an logging
3860 * just to say 'this inode exists' and a logging
3861 * to say 'update this inode with these values'
3863 btrfs_set_token_inode_generation(leaf, item, 0, &token);
3864 btrfs_set_token_inode_size(leaf, item, logged_isize, &token);
3865 } else {
3866 btrfs_set_token_inode_generation(leaf, item,
3867 BTRFS_I(inode)->generation,
3868 &token);
3869 btrfs_set_token_inode_size(leaf, item, inode->i_size, &token);
3872 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3873 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3874 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3875 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3877 btrfs_set_token_timespec_sec(leaf, &item->atime,
3878 inode->i_atime.tv_sec, &token);
3879 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3880 inode->i_atime.tv_nsec, &token);
3882 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3883 inode->i_mtime.tv_sec, &token);
3884 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3885 inode->i_mtime.tv_nsec, &token);
3887 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3888 inode->i_ctime.tv_sec, &token);
3889 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3890 inode->i_ctime.tv_nsec, &token);
3892 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3893 &token);
3895 btrfs_set_token_inode_sequence(leaf, item,
3896 inode_peek_iversion(inode), &token);
3897 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3898 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3899 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3900 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3903 static int log_inode_item(struct btrfs_trans_handle *trans,
3904 struct btrfs_root *log, struct btrfs_path *path,
3905 struct btrfs_inode *inode)
3907 struct btrfs_inode_item *inode_item;
3908 int ret;
3910 ret = btrfs_insert_empty_item(trans, log, path,
3911 &inode->location, sizeof(*inode_item));
3912 if (ret && ret != -EEXIST)
3913 return ret;
3914 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3915 struct btrfs_inode_item);
3916 fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
3917 0, 0);
3918 btrfs_release_path(path);
3919 return 0;
3922 static int log_csums(struct btrfs_trans_handle *trans,
3923 struct btrfs_root *log_root,
3924 struct btrfs_ordered_sum *sums)
3926 int ret;
3929 * Due to extent cloning, we might have logged a csum item that covers a
3930 * subrange of a cloned extent, and later we can end up logging a csum
3931 * item for a larger subrange of the same extent or the entire range.
3932 * This would leave csum items in the log tree that cover the same range
3933 * and break the searches for checksums in the log tree, resulting in
3934 * some checksums missing in the fs/subvolume tree. So just delete (or
3935 * trim and adjust) any existing csum items in the log for this range.
3937 ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
3938 if (ret)
3939 return ret;
3941 return btrfs_csum_file_blocks(trans, log_root, sums);
3944 static noinline int copy_items(struct btrfs_trans_handle *trans,
3945 struct btrfs_inode *inode,
3946 struct btrfs_path *dst_path,
3947 struct btrfs_path *src_path,
3948 int start_slot, int nr, int inode_only,
3949 u64 logged_isize)
3951 struct btrfs_fs_info *fs_info = trans->fs_info;
3952 unsigned long src_offset;
3953 unsigned long dst_offset;
3954 struct btrfs_root *log = inode->root->log_root;
3955 struct btrfs_file_extent_item *extent;
3956 struct btrfs_inode_item *inode_item;
3957 struct extent_buffer *src = src_path->nodes[0];
3958 int ret;
3959 struct btrfs_key *ins_keys;
3960 u32 *ins_sizes;
3961 char *ins_data;
3962 int i;
3963 struct list_head ordered_sums;
3964 int skip_csum = inode->flags & BTRFS_INODE_NODATASUM;
3966 INIT_LIST_HEAD(&ordered_sums);
3968 ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
3969 nr * sizeof(u32), GFP_NOFS);
3970 if (!ins_data)
3971 return -ENOMEM;
3973 ins_sizes = (u32 *)ins_data;
3974 ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
3976 for (i = 0; i < nr; i++) {
3977 ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
3978 btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
3980 ret = btrfs_insert_empty_items(trans, log, dst_path,
3981 ins_keys, ins_sizes, nr);
3982 if (ret) {
3983 kfree(ins_data);
3984 return ret;
3987 for (i = 0; i < nr; i++, dst_path->slots[0]++) {
3988 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
3989 dst_path->slots[0]);
3991 src_offset = btrfs_item_ptr_offset(src, start_slot + i);
3993 if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
3994 inode_item = btrfs_item_ptr(dst_path->nodes[0],
3995 dst_path->slots[0],
3996 struct btrfs_inode_item);
3997 fill_inode_item(trans, dst_path->nodes[0], inode_item,
3998 &inode->vfs_inode,
3999 inode_only == LOG_INODE_EXISTS,
4000 logged_isize);
4001 } else {
4002 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4003 src_offset, ins_sizes[i]);
4006 /* take a reference on file data extents so that truncates
4007 * or deletes of this inode don't have to relog the inode
4008 * again
4010 if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY &&
4011 !skip_csum) {
4012 int found_type;
4013 extent = btrfs_item_ptr(src, start_slot + i,
4014 struct btrfs_file_extent_item);
4016 if (btrfs_file_extent_generation(src, extent) < trans->transid)
4017 continue;
4019 found_type = btrfs_file_extent_type(src, extent);
4020 if (found_type == BTRFS_FILE_EXTENT_REG) {
4021 u64 ds, dl, cs, cl;
4022 ds = btrfs_file_extent_disk_bytenr(src,
4023 extent);
4024 /* ds == 0 is a hole */
4025 if (ds == 0)
4026 continue;
4028 dl = btrfs_file_extent_disk_num_bytes(src,
4029 extent);
4030 cs = btrfs_file_extent_offset(src, extent);
4031 cl = btrfs_file_extent_num_bytes(src,
4032 extent);
4033 if (btrfs_file_extent_compression(src,
4034 extent)) {
4035 cs = 0;
4036 cl = dl;
4039 ret = btrfs_lookup_csums_range(
4040 fs_info->csum_root,
4041 ds + cs, ds + cs + cl - 1,
4042 &ordered_sums, 0);
4043 if (ret)
4044 break;
4049 btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4050 btrfs_release_path(dst_path);
4051 kfree(ins_data);
4054 * we have to do this after the loop above to avoid changing the
4055 * log tree while trying to change the log tree.
4057 while (!list_empty(&ordered_sums)) {
4058 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4059 struct btrfs_ordered_sum,
4060 list);
4061 if (!ret)
4062 ret = log_csums(trans, log, sums);
4063 list_del(&sums->list);
4064 kfree(sums);
4067 return ret;
4070 static int extent_cmp(void *priv, struct list_head *a, struct list_head *b)
4072 struct extent_map *em1, *em2;
4074 em1 = list_entry(a, struct extent_map, list);
4075 em2 = list_entry(b, struct extent_map, list);
4077 if (em1->start < em2->start)
4078 return -1;
4079 else if (em1->start > em2->start)
4080 return 1;
4081 return 0;
4084 static int log_extent_csums(struct btrfs_trans_handle *trans,
4085 struct btrfs_inode *inode,
4086 struct btrfs_root *log_root,
4087 const struct extent_map *em)
4089 u64 csum_offset;
4090 u64 csum_len;
4091 LIST_HEAD(ordered_sums);
4092 int ret = 0;
4094 if (inode->flags & BTRFS_INODE_NODATASUM ||
4095 test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
4096 em->block_start == EXTENT_MAP_HOLE)
4097 return 0;
4099 /* If we're compressed we have to save the entire range of csums. */
4100 if (em->compress_type) {
4101 csum_offset = 0;
4102 csum_len = max(em->block_len, em->orig_block_len);
4103 } else {
4104 csum_offset = em->mod_start - em->start;
4105 csum_len = em->mod_len;
4108 /* block start is already adjusted for the file extent offset. */
4109 ret = btrfs_lookup_csums_range(trans->fs_info->csum_root,
4110 em->block_start + csum_offset,
4111 em->block_start + csum_offset +
4112 csum_len - 1, &ordered_sums, 0);
4113 if (ret)
4114 return ret;
4116 while (!list_empty(&ordered_sums)) {
4117 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4118 struct btrfs_ordered_sum,
4119 list);
4120 if (!ret)
4121 ret = log_csums(trans, log_root, sums);
4122 list_del(&sums->list);
4123 kfree(sums);
4126 return ret;
4129 static int log_one_extent(struct btrfs_trans_handle *trans,
4130 struct btrfs_inode *inode, struct btrfs_root *root,
4131 const struct extent_map *em,
4132 struct btrfs_path *path,
4133 struct btrfs_log_ctx *ctx)
4135 struct btrfs_root *log = root->log_root;
4136 struct btrfs_file_extent_item *fi;
4137 struct extent_buffer *leaf;
4138 struct btrfs_map_token token;
4139 struct btrfs_key key;
4140 u64 extent_offset = em->start - em->orig_start;
4141 u64 block_len;
4142 int ret;
4143 int extent_inserted = 0;
4145 ret = log_extent_csums(trans, inode, log, em);
4146 if (ret)
4147 return ret;
4149 ret = __btrfs_drop_extents(trans, log, &inode->vfs_inode, path, em->start,
4150 em->start + em->len, NULL, 0, 1,
4151 sizeof(*fi), &extent_inserted);
4152 if (ret)
4153 return ret;
4155 if (!extent_inserted) {
4156 key.objectid = btrfs_ino(inode);
4157 key.type = BTRFS_EXTENT_DATA_KEY;
4158 key.offset = em->start;
4160 ret = btrfs_insert_empty_item(trans, log, path, &key,
4161 sizeof(*fi));
4162 if (ret)
4163 return ret;
4165 leaf = path->nodes[0];
4166 btrfs_init_map_token(&token, leaf);
4167 fi = btrfs_item_ptr(leaf, path->slots[0],
4168 struct btrfs_file_extent_item);
4170 btrfs_set_token_file_extent_generation(leaf, fi, trans->transid,
4171 &token);
4172 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4173 btrfs_set_token_file_extent_type(leaf, fi,
4174 BTRFS_FILE_EXTENT_PREALLOC,
4175 &token);
4176 else
4177 btrfs_set_token_file_extent_type(leaf, fi,
4178 BTRFS_FILE_EXTENT_REG,
4179 &token);
4181 block_len = max(em->block_len, em->orig_block_len);
4182 if (em->compress_type != BTRFS_COMPRESS_NONE) {
4183 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4184 em->block_start,
4185 &token);
4186 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4187 &token);
4188 } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4189 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4190 em->block_start -
4191 extent_offset, &token);
4192 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4193 &token);
4194 } else {
4195 btrfs_set_token_file_extent_disk_bytenr(leaf, fi, 0, &token);
4196 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, 0,
4197 &token);
4200 btrfs_set_token_file_extent_offset(leaf, fi, extent_offset, &token);
4201 btrfs_set_token_file_extent_num_bytes(leaf, fi, em->len, &token);
4202 btrfs_set_token_file_extent_ram_bytes(leaf, fi, em->ram_bytes, &token);
4203 btrfs_set_token_file_extent_compression(leaf, fi, em->compress_type,
4204 &token);
4205 btrfs_set_token_file_extent_encryption(leaf, fi, 0, &token);
4206 btrfs_set_token_file_extent_other_encoding(leaf, fi, 0, &token);
4207 btrfs_mark_buffer_dirty(leaf);
4209 btrfs_release_path(path);
4211 return ret;
4215 * Log all prealloc extents beyond the inode's i_size to make sure we do not
4216 * lose them after doing a fast fsync and replaying the log. We scan the
4217 * subvolume's root instead of iterating the inode's extent map tree because
4218 * otherwise we can log incorrect extent items based on extent map conversion.
4219 * That can happen due to the fact that extent maps are merged when they
4220 * are not in the extent map tree's list of modified extents.
4222 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4223 struct btrfs_inode *inode,
4224 struct btrfs_path *path)
4226 struct btrfs_root *root = inode->root;
4227 struct btrfs_key key;
4228 const u64 i_size = i_size_read(&inode->vfs_inode);
4229 const u64 ino = btrfs_ino(inode);
4230 struct btrfs_path *dst_path = NULL;
4231 bool dropped_extents = false;
4232 u64 truncate_offset = i_size;
4233 struct extent_buffer *leaf;
4234 int slot;
4235 int ins_nr = 0;
4236 int start_slot;
4237 int ret;
4239 if (!(inode->flags & BTRFS_INODE_PREALLOC))
4240 return 0;
4242 key.objectid = ino;
4243 key.type = BTRFS_EXTENT_DATA_KEY;
4244 key.offset = i_size;
4245 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4246 if (ret < 0)
4247 goto out;
4250 * We must check if there is a prealloc extent that starts before the
4251 * i_size and crosses the i_size boundary. This is to ensure later we
4252 * truncate down to the end of that extent and not to the i_size, as
4253 * otherwise we end up losing part of the prealloc extent after a log
4254 * replay and with an implicit hole if there is another prealloc extent
4255 * that starts at an offset beyond i_size.
4257 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4258 if (ret < 0)
4259 goto out;
4261 if (ret == 0) {
4262 struct btrfs_file_extent_item *ei;
4264 leaf = path->nodes[0];
4265 slot = path->slots[0];
4266 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4268 if (btrfs_file_extent_type(leaf, ei) ==
4269 BTRFS_FILE_EXTENT_PREALLOC) {
4270 u64 extent_end;
4272 btrfs_item_key_to_cpu(leaf, &key, slot);
4273 extent_end = key.offset +
4274 btrfs_file_extent_num_bytes(leaf, ei);
4276 if (extent_end > i_size)
4277 truncate_offset = extent_end;
4279 } else {
4280 ret = 0;
4283 while (true) {
4284 leaf = path->nodes[0];
4285 slot = path->slots[0];
4287 if (slot >= btrfs_header_nritems(leaf)) {
4288 if (ins_nr > 0) {
4289 ret = copy_items(trans, inode, dst_path, path,
4290 start_slot, ins_nr, 1, 0);
4291 if (ret < 0)
4292 goto out;
4293 ins_nr = 0;
4295 ret = btrfs_next_leaf(root, path);
4296 if (ret < 0)
4297 goto out;
4298 if (ret > 0) {
4299 ret = 0;
4300 break;
4302 continue;
4305 btrfs_item_key_to_cpu(leaf, &key, slot);
4306 if (key.objectid > ino)
4307 break;
4308 if (WARN_ON_ONCE(key.objectid < ino) ||
4309 key.type < BTRFS_EXTENT_DATA_KEY ||
4310 key.offset < i_size) {
4311 path->slots[0]++;
4312 continue;
4314 if (!dropped_extents) {
4316 * Avoid logging extent items logged in past fsync calls
4317 * and leading to duplicate keys in the log tree.
4319 do {
4320 ret = btrfs_truncate_inode_items(trans,
4321 root->log_root,
4322 &inode->vfs_inode,
4323 truncate_offset,
4324 BTRFS_EXTENT_DATA_KEY);
4325 } while (ret == -EAGAIN);
4326 if (ret)
4327 goto out;
4328 dropped_extents = true;
4330 if (ins_nr == 0)
4331 start_slot = slot;
4332 ins_nr++;
4333 path->slots[0]++;
4334 if (!dst_path) {
4335 dst_path = btrfs_alloc_path();
4336 if (!dst_path) {
4337 ret = -ENOMEM;
4338 goto out;
4342 if (ins_nr > 0) {
4343 ret = copy_items(trans, inode, dst_path, path,
4344 start_slot, ins_nr, 1, 0);
4345 if (ret > 0)
4346 ret = 0;
4348 out:
4349 btrfs_release_path(path);
4350 btrfs_free_path(dst_path);
4351 return ret;
4354 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4355 struct btrfs_root *root,
4356 struct btrfs_inode *inode,
4357 struct btrfs_path *path,
4358 struct btrfs_log_ctx *ctx,
4359 const u64 start,
4360 const u64 end)
4362 struct extent_map *em, *n;
4363 struct list_head extents;
4364 struct extent_map_tree *tree = &inode->extent_tree;
4365 u64 test_gen;
4366 int ret = 0;
4367 int num = 0;
4369 INIT_LIST_HEAD(&extents);
4371 write_lock(&tree->lock);
4372 test_gen = root->fs_info->last_trans_committed;
4374 list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4376 * Skip extents outside our logging range. It's important to do
4377 * it for correctness because if we don't ignore them, we may
4378 * log them before their ordered extent completes, and therefore
4379 * we could log them without logging their respective checksums
4380 * (the checksum items are added to the csum tree at the very
4381 * end of btrfs_finish_ordered_io()). Also leave such extents
4382 * outside of our range in the list, since we may have another
4383 * ranged fsync in the near future that needs them. If an extent
4384 * outside our range corresponds to a hole, log it to avoid
4385 * leaving gaps between extents (fsck will complain when we are
4386 * not using the NO_HOLES feature).
4388 if ((em->start > end || em->start + em->len <= start) &&
4389 em->block_start != EXTENT_MAP_HOLE)
4390 continue;
4392 list_del_init(&em->list);
4394 * Just an arbitrary number, this can be really CPU intensive
4395 * once we start getting a lot of extents, and really once we
4396 * have a bunch of extents we just want to commit since it will
4397 * be faster.
4399 if (++num > 32768) {
4400 list_del_init(&tree->modified_extents);
4401 ret = -EFBIG;
4402 goto process;
4405 if (em->generation <= test_gen)
4406 continue;
4408 /* We log prealloc extents beyond eof later. */
4409 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
4410 em->start >= i_size_read(&inode->vfs_inode))
4411 continue;
4413 /* Need a ref to keep it from getting evicted from cache */
4414 refcount_inc(&em->refs);
4415 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
4416 list_add_tail(&em->list, &extents);
4417 num++;
4420 list_sort(NULL, &extents, extent_cmp);
4421 process:
4422 while (!list_empty(&extents)) {
4423 em = list_entry(extents.next, struct extent_map, list);
4425 list_del_init(&em->list);
4428 * If we had an error we just need to delete everybody from our
4429 * private list.
4431 if (ret) {
4432 clear_em_logging(tree, em);
4433 free_extent_map(em);
4434 continue;
4437 write_unlock(&tree->lock);
4439 ret = log_one_extent(trans, inode, root, em, path, ctx);
4440 write_lock(&tree->lock);
4441 clear_em_logging(tree, em);
4442 free_extent_map(em);
4444 WARN_ON(!list_empty(&extents));
4445 write_unlock(&tree->lock);
4447 btrfs_release_path(path);
4448 if (!ret)
4449 ret = btrfs_log_prealloc_extents(trans, inode, path);
4451 return ret;
4454 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
4455 struct btrfs_path *path, u64 *size_ret)
4457 struct btrfs_key key;
4458 int ret;
4460 key.objectid = btrfs_ino(inode);
4461 key.type = BTRFS_INODE_ITEM_KEY;
4462 key.offset = 0;
4464 ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4465 if (ret < 0) {
4466 return ret;
4467 } else if (ret > 0) {
4468 *size_ret = 0;
4469 } else {
4470 struct btrfs_inode_item *item;
4472 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4473 struct btrfs_inode_item);
4474 *size_ret = btrfs_inode_size(path->nodes[0], item);
4476 * If the in-memory inode's i_size is smaller then the inode
4477 * size stored in the btree, return the inode's i_size, so
4478 * that we get a correct inode size after replaying the log
4479 * when before a power failure we had a shrinking truncate
4480 * followed by addition of a new name (rename / new hard link).
4481 * Otherwise return the inode size from the btree, to avoid
4482 * data loss when replaying a log due to previously doing a
4483 * write that expands the inode's size and logging a new name
4484 * immediately after.
4486 if (*size_ret > inode->vfs_inode.i_size)
4487 *size_ret = inode->vfs_inode.i_size;
4490 btrfs_release_path(path);
4491 return 0;
4495 * At the moment we always log all xattrs. This is to figure out at log replay
4496 * time which xattrs must have their deletion replayed. If a xattr is missing
4497 * in the log tree and exists in the fs/subvol tree, we delete it. This is
4498 * because if a xattr is deleted, the inode is fsynced and a power failure
4499 * happens, causing the log to be replayed the next time the fs is mounted,
4500 * we want the xattr to not exist anymore (same behaviour as other filesystems
4501 * with a journal, ext3/4, xfs, f2fs, etc).
4503 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
4504 struct btrfs_root *root,
4505 struct btrfs_inode *inode,
4506 struct btrfs_path *path,
4507 struct btrfs_path *dst_path)
4509 int ret;
4510 struct btrfs_key key;
4511 const u64 ino = btrfs_ino(inode);
4512 int ins_nr = 0;
4513 int start_slot = 0;
4515 key.objectid = ino;
4516 key.type = BTRFS_XATTR_ITEM_KEY;
4517 key.offset = 0;
4519 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4520 if (ret < 0)
4521 return ret;
4523 while (true) {
4524 int slot = path->slots[0];
4525 struct extent_buffer *leaf = path->nodes[0];
4526 int nritems = btrfs_header_nritems(leaf);
4528 if (slot >= nritems) {
4529 if (ins_nr > 0) {
4530 ret = copy_items(trans, inode, dst_path, path,
4531 start_slot, ins_nr, 1, 0);
4532 if (ret < 0)
4533 return ret;
4534 ins_nr = 0;
4536 ret = btrfs_next_leaf(root, path);
4537 if (ret < 0)
4538 return ret;
4539 else if (ret > 0)
4540 break;
4541 continue;
4544 btrfs_item_key_to_cpu(leaf, &key, slot);
4545 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
4546 break;
4548 if (ins_nr == 0)
4549 start_slot = slot;
4550 ins_nr++;
4551 path->slots[0]++;
4552 cond_resched();
4554 if (ins_nr > 0) {
4555 ret = copy_items(trans, inode, dst_path, path,
4556 start_slot, ins_nr, 1, 0);
4557 if (ret < 0)
4558 return ret;
4561 return 0;
4565 * When using the NO_HOLES feature if we punched a hole that causes the
4566 * deletion of entire leafs or all the extent items of the first leaf (the one
4567 * that contains the inode item and references) we may end up not processing
4568 * any extents, because there are no leafs with a generation matching the
4569 * current transaction that have extent items for our inode. So we need to find
4570 * if any holes exist and then log them. We also need to log holes after any
4571 * truncate operation that changes the inode's size.
4573 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
4574 struct btrfs_root *root,
4575 struct btrfs_inode *inode,
4576 struct btrfs_path *path)
4578 struct btrfs_fs_info *fs_info = root->fs_info;
4579 struct btrfs_key key;
4580 const u64 ino = btrfs_ino(inode);
4581 const u64 i_size = i_size_read(&inode->vfs_inode);
4582 u64 prev_extent_end = 0;
4583 int ret;
4585 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
4586 return 0;
4588 key.objectid = ino;
4589 key.type = BTRFS_EXTENT_DATA_KEY;
4590 key.offset = 0;
4592 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4593 if (ret < 0)
4594 return ret;
4596 while (true) {
4597 struct btrfs_file_extent_item *extent;
4598 struct extent_buffer *leaf = path->nodes[0];
4599 u64 len;
4601 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4602 ret = btrfs_next_leaf(root, path);
4603 if (ret < 0)
4604 return ret;
4605 if (ret > 0) {
4606 ret = 0;
4607 break;
4609 leaf = path->nodes[0];
4612 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4613 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
4614 break;
4616 /* We have a hole, log it. */
4617 if (prev_extent_end < key.offset) {
4618 const u64 hole_len = key.offset - prev_extent_end;
4621 * Release the path to avoid deadlocks with other code
4622 * paths that search the root while holding locks on
4623 * leafs from the log root.
4625 btrfs_release_path(path);
4626 ret = btrfs_insert_file_extent(trans, root->log_root,
4627 ino, prev_extent_end, 0,
4628 0, hole_len, 0, hole_len,
4629 0, 0, 0);
4630 if (ret < 0)
4631 return ret;
4634 * Search for the same key again in the root. Since it's
4635 * an extent item and we are holding the inode lock, the
4636 * key must still exist. If it doesn't just emit warning
4637 * and return an error to fall back to a transaction
4638 * commit.
4640 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4641 if (ret < 0)
4642 return ret;
4643 if (WARN_ON(ret > 0))
4644 return -ENOENT;
4645 leaf = path->nodes[0];
4648 extent = btrfs_item_ptr(leaf, path->slots[0],
4649 struct btrfs_file_extent_item);
4650 if (btrfs_file_extent_type(leaf, extent) ==
4651 BTRFS_FILE_EXTENT_INLINE) {
4652 len = btrfs_file_extent_ram_bytes(leaf, extent);
4653 prev_extent_end = ALIGN(key.offset + len,
4654 fs_info->sectorsize);
4655 } else {
4656 len = btrfs_file_extent_num_bytes(leaf, extent);
4657 prev_extent_end = key.offset + len;
4660 path->slots[0]++;
4661 cond_resched();
4664 if (prev_extent_end < i_size) {
4665 u64 hole_len;
4667 btrfs_release_path(path);
4668 hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
4669 ret = btrfs_insert_file_extent(trans, root->log_root,
4670 ino, prev_extent_end, 0, 0,
4671 hole_len, 0, hole_len,
4672 0, 0, 0);
4673 if (ret < 0)
4674 return ret;
4677 return 0;
4681 * When we are logging a new inode X, check if it doesn't have a reference that
4682 * matches the reference from some other inode Y created in a past transaction
4683 * and that was renamed in the current transaction. If we don't do this, then at
4684 * log replay time we can lose inode Y (and all its files if it's a directory):
4686 * mkdir /mnt/x
4687 * echo "hello world" > /mnt/x/foobar
4688 * sync
4689 * mv /mnt/x /mnt/y
4690 * mkdir /mnt/x # or touch /mnt/x
4691 * xfs_io -c fsync /mnt/x
4692 * <power fail>
4693 * mount fs, trigger log replay
4695 * After the log replay procedure, we would lose the first directory and all its
4696 * files (file foobar).
4697 * For the case where inode Y is not a directory we simply end up losing it:
4699 * echo "123" > /mnt/foo
4700 * sync
4701 * mv /mnt/foo /mnt/bar
4702 * echo "abc" > /mnt/foo
4703 * xfs_io -c fsync /mnt/foo
4704 * <power fail>
4706 * We also need this for cases where a snapshot entry is replaced by some other
4707 * entry (file or directory) otherwise we end up with an unreplayable log due to
4708 * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
4709 * if it were a regular entry:
4711 * mkdir /mnt/x
4712 * btrfs subvolume snapshot /mnt /mnt/x/snap
4713 * btrfs subvolume delete /mnt/x/snap
4714 * rmdir /mnt/x
4715 * mkdir /mnt/x
4716 * fsync /mnt/x or fsync some new file inside it
4717 * <power fail>
4719 * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
4720 * the same transaction.
4722 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
4723 const int slot,
4724 const struct btrfs_key *key,
4725 struct btrfs_inode *inode,
4726 u64 *other_ino, u64 *other_parent)
4728 int ret;
4729 struct btrfs_path *search_path;
4730 char *name = NULL;
4731 u32 name_len = 0;
4732 u32 item_size = btrfs_item_size_nr(eb, slot);
4733 u32 cur_offset = 0;
4734 unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
4736 search_path = btrfs_alloc_path();
4737 if (!search_path)
4738 return -ENOMEM;
4739 search_path->search_commit_root = 1;
4740 search_path->skip_locking = 1;
4742 while (cur_offset < item_size) {
4743 u64 parent;
4744 u32 this_name_len;
4745 u32 this_len;
4746 unsigned long name_ptr;
4747 struct btrfs_dir_item *di;
4749 if (key->type == BTRFS_INODE_REF_KEY) {
4750 struct btrfs_inode_ref *iref;
4752 iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
4753 parent = key->offset;
4754 this_name_len = btrfs_inode_ref_name_len(eb, iref);
4755 name_ptr = (unsigned long)(iref + 1);
4756 this_len = sizeof(*iref) + this_name_len;
4757 } else {
4758 struct btrfs_inode_extref *extref;
4760 extref = (struct btrfs_inode_extref *)(ptr +
4761 cur_offset);
4762 parent = btrfs_inode_extref_parent(eb, extref);
4763 this_name_len = btrfs_inode_extref_name_len(eb, extref);
4764 name_ptr = (unsigned long)&extref->name;
4765 this_len = sizeof(*extref) + this_name_len;
4768 if (this_name_len > name_len) {
4769 char *new_name;
4771 new_name = krealloc(name, this_name_len, GFP_NOFS);
4772 if (!new_name) {
4773 ret = -ENOMEM;
4774 goto out;
4776 name_len = this_name_len;
4777 name = new_name;
4780 read_extent_buffer(eb, name, name_ptr, this_name_len);
4781 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
4782 parent, name, this_name_len, 0);
4783 if (di && !IS_ERR(di)) {
4784 struct btrfs_key di_key;
4786 btrfs_dir_item_key_to_cpu(search_path->nodes[0],
4787 di, &di_key);
4788 if (di_key.type == BTRFS_INODE_ITEM_KEY) {
4789 if (di_key.objectid != key->objectid) {
4790 ret = 1;
4791 *other_ino = di_key.objectid;
4792 *other_parent = parent;
4793 } else {
4794 ret = 0;
4796 } else {
4797 ret = -EAGAIN;
4799 goto out;
4800 } else if (IS_ERR(di)) {
4801 ret = PTR_ERR(di);
4802 goto out;
4804 btrfs_release_path(search_path);
4806 cur_offset += this_len;
4808 ret = 0;
4809 out:
4810 btrfs_free_path(search_path);
4811 kfree(name);
4812 return ret;
4815 struct btrfs_ino_list {
4816 u64 ino;
4817 u64 parent;
4818 struct list_head list;
4821 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
4822 struct btrfs_root *root,
4823 struct btrfs_path *path,
4824 struct btrfs_log_ctx *ctx,
4825 u64 ino, u64 parent)
4827 struct btrfs_ino_list *ino_elem;
4828 LIST_HEAD(inode_list);
4829 int ret = 0;
4831 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
4832 if (!ino_elem)
4833 return -ENOMEM;
4834 ino_elem->ino = ino;
4835 ino_elem->parent = parent;
4836 list_add_tail(&ino_elem->list, &inode_list);
4838 while (!list_empty(&inode_list)) {
4839 struct btrfs_fs_info *fs_info = root->fs_info;
4840 struct btrfs_key key;
4841 struct inode *inode;
4843 ino_elem = list_first_entry(&inode_list, struct btrfs_ino_list,
4844 list);
4845 ino = ino_elem->ino;
4846 parent = ino_elem->parent;
4847 list_del(&ino_elem->list);
4848 kfree(ino_elem);
4849 if (ret)
4850 continue;
4852 btrfs_release_path(path);
4854 key.objectid = ino;
4855 key.type = BTRFS_INODE_ITEM_KEY;
4856 key.offset = 0;
4857 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
4859 * If the other inode that had a conflicting dir entry was
4860 * deleted in the current transaction, we need to log its parent
4861 * directory.
4863 if (IS_ERR(inode)) {
4864 ret = PTR_ERR(inode);
4865 if (ret == -ENOENT) {
4866 key.objectid = parent;
4867 inode = btrfs_iget(fs_info->sb, &key, root,
4868 NULL);
4869 if (IS_ERR(inode)) {
4870 ret = PTR_ERR(inode);
4871 } else {
4872 ret = btrfs_log_inode(trans, root,
4873 BTRFS_I(inode),
4874 LOG_OTHER_INODE_ALL,
4875 0, LLONG_MAX, ctx);
4876 btrfs_add_delayed_iput(inode);
4879 continue;
4882 * If the inode was already logged skip it - otherwise we can
4883 * hit an infinite loop. Example:
4885 * From the commit root (previous transaction) we have the
4886 * following inodes:
4888 * inode 257 a directory
4889 * inode 258 with references "zz" and "zz_link" on inode 257
4890 * inode 259 with reference "a" on inode 257
4892 * And in the current (uncommitted) transaction we have:
4894 * inode 257 a directory, unchanged
4895 * inode 258 with references "a" and "a2" on inode 257
4896 * inode 259 with reference "zz_link" on inode 257
4897 * inode 261 with reference "zz" on inode 257
4899 * When logging inode 261 the following infinite loop could
4900 * happen if we don't skip already logged inodes:
4902 * - we detect inode 258 as a conflicting inode, with inode 261
4903 * on reference "zz", and log it;
4905 * - we detect inode 259 as a conflicting inode, with inode 258
4906 * on reference "a", and log it;
4908 * - we detect inode 258 as a conflicting inode, with inode 259
4909 * on reference "zz_link", and log it - again! After this we
4910 * repeat the above steps forever.
4912 spin_lock(&BTRFS_I(inode)->lock);
4914 * Check the inode's logged_trans only instead of
4915 * btrfs_inode_in_log(). This is because the last_log_commit of
4916 * the inode is not updated when we only log that it exists and
4917 * and it has the full sync bit set (see btrfs_log_inode()).
4919 if (BTRFS_I(inode)->logged_trans == trans->transid) {
4920 spin_unlock(&BTRFS_I(inode)->lock);
4921 btrfs_add_delayed_iput(inode);
4922 continue;
4924 spin_unlock(&BTRFS_I(inode)->lock);
4926 * We are safe logging the other inode without acquiring its
4927 * lock as long as we log with the LOG_INODE_EXISTS mode. We
4928 * are safe against concurrent renames of the other inode as
4929 * well because during a rename we pin the log and update the
4930 * log with the new name before we unpin it.
4932 ret = btrfs_log_inode(trans, root, BTRFS_I(inode),
4933 LOG_OTHER_INODE, 0, LLONG_MAX, ctx);
4934 if (ret) {
4935 btrfs_add_delayed_iput(inode);
4936 continue;
4939 key.objectid = ino;
4940 key.type = BTRFS_INODE_REF_KEY;
4941 key.offset = 0;
4942 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4943 if (ret < 0) {
4944 btrfs_add_delayed_iput(inode);
4945 continue;
4948 while (true) {
4949 struct extent_buffer *leaf = path->nodes[0];
4950 int slot = path->slots[0];
4951 u64 other_ino = 0;
4952 u64 other_parent = 0;
4954 if (slot >= btrfs_header_nritems(leaf)) {
4955 ret = btrfs_next_leaf(root, path);
4956 if (ret < 0) {
4957 break;
4958 } else if (ret > 0) {
4959 ret = 0;
4960 break;
4962 continue;
4965 btrfs_item_key_to_cpu(leaf, &key, slot);
4966 if (key.objectid != ino ||
4967 (key.type != BTRFS_INODE_REF_KEY &&
4968 key.type != BTRFS_INODE_EXTREF_KEY)) {
4969 ret = 0;
4970 break;
4973 ret = btrfs_check_ref_name_override(leaf, slot, &key,
4974 BTRFS_I(inode), &other_ino,
4975 &other_parent);
4976 if (ret < 0)
4977 break;
4978 if (ret > 0) {
4979 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
4980 if (!ino_elem) {
4981 ret = -ENOMEM;
4982 break;
4984 ino_elem->ino = other_ino;
4985 ino_elem->parent = other_parent;
4986 list_add_tail(&ino_elem->list, &inode_list);
4987 ret = 0;
4989 path->slots[0]++;
4991 btrfs_add_delayed_iput(inode);
4994 return ret;
4997 /* log a single inode in the tree log.
4998 * At least one parent directory for this inode must exist in the tree
4999 * or be logged already.
5001 * Any items from this inode changed by the current transaction are copied
5002 * to the log tree. An extra reference is taken on any extents in this
5003 * file, allowing us to avoid a whole pile of corner cases around logging
5004 * blocks that have been removed from the tree.
5006 * See LOG_INODE_ALL and related defines for a description of what inode_only
5007 * does.
5009 * This handles both files and directories.
5011 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
5012 struct btrfs_root *root, struct btrfs_inode *inode,
5013 int inode_only,
5014 const loff_t start,
5015 const loff_t end,
5016 struct btrfs_log_ctx *ctx)
5018 struct btrfs_fs_info *fs_info = root->fs_info;
5019 struct btrfs_path *path;
5020 struct btrfs_path *dst_path;
5021 struct btrfs_key min_key;
5022 struct btrfs_key max_key;
5023 struct btrfs_root *log = root->log_root;
5024 int err = 0;
5025 int ret;
5026 int nritems;
5027 int ins_start_slot = 0;
5028 int ins_nr;
5029 bool fast_search = false;
5030 u64 ino = btrfs_ino(inode);
5031 struct extent_map_tree *em_tree = &inode->extent_tree;
5032 u64 logged_isize = 0;
5033 bool need_log_inode_item = true;
5034 bool xattrs_logged = false;
5035 bool recursive_logging = false;
5037 path = btrfs_alloc_path();
5038 if (!path)
5039 return -ENOMEM;
5040 dst_path = btrfs_alloc_path();
5041 if (!dst_path) {
5042 btrfs_free_path(path);
5043 return -ENOMEM;
5046 min_key.objectid = ino;
5047 min_key.type = BTRFS_INODE_ITEM_KEY;
5048 min_key.offset = 0;
5050 max_key.objectid = ino;
5053 /* today the code can only do partial logging of directories */
5054 if (S_ISDIR(inode->vfs_inode.i_mode) ||
5055 (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5056 &inode->runtime_flags) &&
5057 inode_only >= LOG_INODE_EXISTS))
5058 max_key.type = BTRFS_XATTR_ITEM_KEY;
5059 else
5060 max_key.type = (u8)-1;
5061 max_key.offset = (u64)-1;
5064 * Only run delayed items if we are a dir or a new file.
5065 * Otherwise commit the delayed inode only, which is needed in
5066 * order for the log replay code to mark inodes for link count
5067 * fixup (create temporary BTRFS_TREE_LOG_FIXUP_OBJECTID items).
5069 if (S_ISDIR(inode->vfs_inode.i_mode) ||
5070 inode->generation > fs_info->last_trans_committed)
5071 ret = btrfs_commit_inode_delayed_items(trans, inode);
5072 else
5073 ret = btrfs_commit_inode_delayed_inode(inode);
5075 if (ret) {
5076 btrfs_free_path(path);
5077 btrfs_free_path(dst_path);
5078 return ret;
5081 if (inode_only == LOG_OTHER_INODE || inode_only == LOG_OTHER_INODE_ALL) {
5082 recursive_logging = true;
5083 if (inode_only == LOG_OTHER_INODE)
5084 inode_only = LOG_INODE_EXISTS;
5085 else
5086 inode_only = LOG_INODE_ALL;
5087 mutex_lock_nested(&inode->log_mutex, SINGLE_DEPTH_NESTING);
5088 } else {
5089 mutex_lock(&inode->log_mutex);
5093 * a brute force approach to making sure we get the most uptodate
5094 * copies of everything.
5096 if (S_ISDIR(inode->vfs_inode.i_mode)) {
5097 int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
5099 if (inode_only == LOG_INODE_EXISTS)
5100 max_key_type = BTRFS_XATTR_ITEM_KEY;
5101 ret = drop_objectid_items(trans, log, path, ino, max_key_type);
5102 } else {
5103 if (inode_only == LOG_INODE_EXISTS) {
5105 * Make sure the new inode item we write to the log has
5106 * the same isize as the current one (if it exists).
5107 * This is necessary to prevent data loss after log
5108 * replay, and also to prevent doing a wrong expanding
5109 * truncate - for e.g. create file, write 4K into offset
5110 * 0, fsync, write 4K into offset 4096, add hard link,
5111 * fsync some other file (to sync log), power fail - if
5112 * we use the inode's current i_size, after log replay
5113 * we get a 8Kb file, with the last 4Kb extent as a hole
5114 * (zeroes), as if an expanding truncate happened,
5115 * instead of getting a file of 4Kb only.
5117 err = logged_inode_size(log, inode, path, &logged_isize);
5118 if (err)
5119 goto out_unlock;
5121 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5122 &inode->runtime_flags)) {
5123 if (inode_only == LOG_INODE_EXISTS) {
5124 max_key.type = BTRFS_XATTR_ITEM_KEY;
5125 ret = drop_objectid_items(trans, log, path, ino,
5126 max_key.type);
5127 } else {
5128 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5129 &inode->runtime_flags);
5130 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
5131 &inode->runtime_flags);
5132 while(1) {
5133 ret = btrfs_truncate_inode_items(trans,
5134 log, &inode->vfs_inode, 0, 0);
5135 if (ret != -EAGAIN)
5136 break;
5139 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
5140 &inode->runtime_flags) ||
5141 inode_only == LOG_INODE_EXISTS) {
5142 if (inode_only == LOG_INODE_ALL)
5143 fast_search = true;
5144 max_key.type = BTRFS_XATTR_ITEM_KEY;
5145 ret = drop_objectid_items(trans, log, path, ino,
5146 max_key.type);
5147 } else {
5148 if (inode_only == LOG_INODE_ALL)
5149 fast_search = true;
5150 goto log_extents;
5154 if (ret) {
5155 err = ret;
5156 goto out_unlock;
5159 while (1) {
5160 ins_nr = 0;
5161 ret = btrfs_search_forward(root, &min_key,
5162 path, trans->transid);
5163 if (ret < 0) {
5164 err = ret;
5165 goto out_unlock;
5167 if (ret != 0)
5168 break;
5169 again:
5170 /* note, ins_nr might be > 0 here, cleanup outside the loop */
5171 if (min_key.objectid != ino)
5172 break;
5173 if (min_key.type > max_key.type)
5174 break;
5176 if (min_key.type == BTRFS_INODE_ITEM_KEY)
5177 need_log_inode_item = false;
5179 if ((min_key.type == BTRFS_INODE_REF_KEY ||
5180 min_key.type == BTRFS_INODE_EXTREF_KEY) &&
5181 inode->generation == trans->transid &&
5182 !recursive_logging) {
5183 u64 other_ino = 0;
5184 u64 other_parent = 0;
5186 ret = btrfs_check_ref_name_override(path->nodes[0],
5187 path->slots[0], &min_key, inode,
5188 &other_ino, &other_parent);
5189 if (ret < 0) {
5190 err = ret;
5191 goto out_unlock;
5192 } else if (ret > 0 && ctx &&
5193 other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5194 if (ins_nr > 0) {
5195 ins_nr++;
5196 } else {
5197 ins_nr = 1;
5198 ins_start_slot = path->slots[0];
5200 ret = copy_items(trans, inode, dst_path, path,
5201 ins_start_slot,
5202 ins_nr, inode_only,
5203 logged_isize);
5204 if (ret < 0) {
5205 err = ret;
5206 goto out_unlock;
5208 ins_nr = 0;
5210 err = log_conflicting_inodes(trans, root, path,
5211 ctx, other_ino, other_parent);
5212 if (err)
5213 goto out_unlock;
5214 btrfs_release_path(path);
5215 goto next_key;
5219 /* Skip xattrs, we log them later with btrfs_log_all_xattrs() */
5220 if (min_key.type == BTRFS_XATTR_ITEM_KEY) {
5221 if (ins_nr == 0)
5222 goto next_slot;
5223 ret = copy_items(trans, inode, dst_path, path,
5224 ins_start_slot,
5225 ins_nr, inode_only, logged_isize);
5226 if (ret < 0) {
5227 err = ret;
5228 goto out_unlock;
5230 ins_nr = 0;
5231 goto next_slot;
5234 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5235 ins_nr++;
5236 goto next_slot;
5237 } else if (!ins_nr) {
5238 ins_start_slot = path->slots[0];
5239 ins_nr = 1;
5240 goto next_slot;
5243 ret = copy_items(trans, inode, dst_path, path,
5244 ins_start_slot, ins_nr, inode_only,
5245 logged_isize);
5246 if (ret < 0) {
5247 err = ret;
5248 goto out_unlock;
5250 ins_nr = 1;
5251 ins_start_slot = path->slots[0];
5252 next_slot:
5254 nritems = btrfs_header_nritems(path->nodes[0]);
5255 path->slots[0]++;
5256 if (path->slots[0] < nritems) {
5257 btrfs_item_key_to_cpu(path->nodes[0], &min_key,
5258 path->slots[0]);
5259 goto again;
5261 if (ins_nr) {
5262 ret = copy_items(trans, inode, dst_path, path,
5263 ins_start_slot,
5264 ins_nr, inode_only, logged_isize);
5265 if (ret < 0) {
5266 err = ret;
5267 goto out_unlock;
5269 ins_nr = 0;
5271 btrfs_release_path(path);
5272 next_key:
5273 if (min_key.offset < (u64)-1) {
5274 min_key.offset++;
5275 } else if (min_key.type < max_key.type) {
5276 min_key.type++;
5277 min_key.offset = 0;
5278 } else {
5279 break;
5282 if (ins_nr) {
5283 ret = copy_items(trans, inode, dst_path, path,
5284 ins_start_slot, ins_nr, inode_only,
5285 logged_isize);
5286 if (ret < 0) {
5287 err = ret;
5288 goto out_unlock;
5290 ins_nr = 0;
5293 btrfs_release_path(path);
5294 btrfs_release_path(dst_path);
5295 err = btrfs_log_all_xattrs(trans, root, inode, path, dst_path);
5296 if (err)
5297 goto out_unlock;
5298 xattrs_logged = true;
5299 if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
5300 btrfs_release_path(path);
5301 btrfs_release_path(dst_path);
5302 err = btrfs_log_holes(trans, root, inode, path);
5303 if (err)
5304 goto out_unlock;
5306 log_extents:
5307 btrfs_release_path(path);
5308 btrfs_release_path(dst_path);
5309 if (need_log_inode_item) {
5310 err = log_inode_item(trans, log, dst_path, inode);
5311 if (!err && !xattrs_logged) {
5312 err = btrfs_log_all_xattrs(trans, root, inode, path,
5313 dst_path);
5314 btrfs_release_path(path);
5316 if (err)
5317 goto out_unlock;
5319 if (fast_search) {
5320 ret = btrfs_log_changed_extents(trans, root, inode, dst_path,
5321 ctx, start, end);
5322 if (ret) {
5323 err = ret;
5324 goto out_unlock;
5326 } else if (inode_only == LOG_INODE_ALL) {
5327 struct extent_map *em, *n;
5329 write_lock(&em_tree->lock);
5331 * We can't just remove every em if we're called for a ranged
5332 * fsync - that is, one that doesn't cover the whole possible
5333 * file range (0 to LLONG_MAX). This is because we can have
5334 * em's that fall outside the range we're logging and therefore
5335 * their ordered operations haven't completed yet
5336 * (btrfs_finish_ordered_io() not invoked yet). This means we
5337 * didn't get their respective file extent item in the fs/subvol
5338 * tree yet, and need to let the next fast fsync (one which
5339 * consults the list of modified extent maps) find the em so
5340 * that it logs a matching file extent item and waits for the
5341 * respective ordered operation to complete (if it's still
5342 * running).
5344 * Removing every em outside the range we're logging would make
5345 * the next fast fsync not log their matching file extent items,
5346 * therefore making us lose data after a log replay.
5348 list_for_each_entry_safe(em, n, &em_tree->modified_extents,
5349 list) {
5350 const u64 mod_end = em->mod_start + em->mod_len - 1;
5352 if (em->mod_start >= start && mod_end <= end)
5353 list_del_init(&em->list);
5355 write_unlock(&em_tree->lock);
5358 if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->vfs_inode.i_mode)) {
5359 ret = log_directory_changes(trans, root, inode, path, dst_path,
5360 ctx);
5361 if (ret) {
5362 err = ret;
5363 goto out_unlock;
5368 * Don't update last_log_commit if we logged that an inode exists after
5369 * it was loaded to memory (full_sync bit set).
5370 * This is to prevent data loss when we do a write to the inode, then
5371 * the inode gets evicted after all delalloc was flushed, then we log
5372 * it exists (due to a rename for example) and then fsync it. This last
5373 * fsync would do nothing (not logging the extents previously written).
5375 spin_lock(&inode->lock);
5376 inode->logged_trans = trans->transid;
5377 if (inode_only != LOG_INODE_EXISTS ||
5378 !test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags))
5379 inode->last_log_commit = inode->last_sub_trans;
5380 spin_unlock(&inode->lock);
5381 out_unlock:
5382 mutex_unlock(&inode->log_mutex);
5384 btrfs_free_path(path);
5385 btrfs_free_path(dst_path);
5386 return err;
5390 * Check if we must fallback to a transaction commit when logging an inode.
5391 * This must be called after logging the inode and is used only in the context
5392 * when fsyncing an inode requires the need to log some other inode - in which
5393 * case we can't lock the i_mutex of each other inode we need to log as that
5394 * can lead to deadlocks with concurrent fsync against other inodes (as we can
5395 * log inodes up or down in the hierarchy) or rename operations for example. So
5396 * we take the log_mutex of the inode after we have logged it and then check for
5397 * its last_unlink_trans value - this is safe because any task setting
5398 * last_unlink_trans must take the log_mutex and it must do this before it does
5399 * the actual unlink operation, so if we do this check before a concurrent task
5400 * sets last_unlink_trans it means we've logged a consistent version/state of
5401 * all the inode items, otherwise we are not sure and must do a transaction
5402 * commit (the concurrent task might have only updated last_unlink_trans before
5403 * we logged the inode or it might have also done the unlink).
5405 static bool btrfs_must_commit_transaction(struct btrfs_trans_handle *trans,
5406 struct btrfs_inode *inode)
5408 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5409 bool ret = false;
5411 mutex_lock(&inode->log_mutex);
5412 if (inode->last_unlink_trans > fs_info->last_trans_committed) {
5414 * Make sure any commits to the log are forced to be full
5415 * commits.
5417 btrfs_set_log_full_commit(trans);
5418 ret = true;
5420 mutex_unlock(&inode->log_mutex);
5422 return ret;
5426 * follow the dentry parent pointers up the chain and see if any
5427 * of the directories in it require a full commit before they can
5428 * be logged. Returns zero if nothing special needs to be done or 1 if
5429 * a full commit is required.
5431 static noinline int check_parent_dirs_for_sync(struct btrfs_trans_handle *trans,
5432 struct btrfs_inode *inode,
5433 struct dentry *parent,
5434 struct super_block *sb,
5435 u64 last_committed)
5437 int ret = 0;
5438 struct dentry *old_parent = NULL;
5441 * for regular files, if its inode is already on disk, we don't
5442 * have to worry about the parents at all. This is because
5443 * we can use the last_unlink_trans field to record renames
5444 * and other fun in this file.
5446 if (S_ISREG(inode->vfs_inode.i_mode) &&
5447 inode->generation <= last_committed &&
5448 inode->last_unlink_trans <= last_committed)
5449 goto out;
5451 if (!S_ISDIR(inode->vfs_inode.i_mode)) {
5452 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5453 goto out;
5454 inode = BTRFS_I(d_inode(parent));
5457 while (1) {
5458 if (btrfs_must_commit_transaction(trans, inode)) {
5459 ret = 1;
5460 break;
5463 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5464 break;
5466 if (IS_ROOT(parent)) {
5467 inode = BTRFS_I(d_inode(parent));
5468 if (btrfs_must_commit_transaction(trans, inode))
5469 ret = 1;
5470 break;
5473 parent = dget_parent(parent);
5474 dput(old_parent);
5475 old_parent = parent;
5476 inode = BTRFS_I(d_inode(parent));
5479 dput(old_parent);
5480 out:
5481 return ret;
5484 struct btrfs_dir_list {
5485 u64 ino;
5486 struct list_head list;
5490 * Log the inodes of the new dentries of a directory. See log_dir_items() for
5491 * details about the why it is needed.
5492 * This is a recursive operation - if an existing dentry corresponds to a
5493 * directory, that directory's new entries are logged too (same behaviour as
5494 * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5495 * the dentries point to we do not lock their i_mutex, otherwise lockdep
5496 * complains about the following circular lock dependency / possible deadlock:
5498 * CPU0 CPU1
5499 * ---- ----
5500 * lock(&type->i_mutex_dir_key#3/2);
5501 * lock(sb_internal#2);
5502 * lock(&type->i_mutex_dir_key#3/2);
5503 * lock(&sb->s_type->i_mutex_key#14);
5505 * Where sb_internal is the lock (a counter that works as a lock) acquired by
5506 * sb_start_intwrite() in btrfs_start_transaction().
5507 * Not locking i_mutex of the inodes is still safe because:
5509 * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5510 * that while logging the inode new references (names) are added or removed
5511 * from the inode, leaving the logged inode item with a link count that does
5512 * not match the number of logged inode reference items. This is fine because
5513 * at log replay time we compute the real number of links and correct the
5514 * link count in the inode item (see replay_one_buffer() and
5515 * link_to_fixup_dir());
5517 * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5518 * while logging the inode's items new items with keys BTRFS_DIR_ITEM_KEY and
5519 * BTRFS_DIR_INDEX_KEY are added to fs/subvol tree and the logged inode item
5520 * has a size that doesn't match the sum of the lengths of all the logged
5521 * names. This does not result in a problem because if a dir_item key is
5522 * logged but its matching dir_index key is not logged, at log replay time we
5523 * don't use it to replay the respective name (see replay_one_name()). On the
5524 * other hand if only the dir_index key ends up being logged, the respective
5525 * name is added to the fs/subvol tree with both the dir_item and dir_index
5526 * keys created (see replay_one_name()).
5527 * The directory's inode item with a wrong i_size is not a problem as well,
5528 * since we don't use it at log replay time to set the i_size in the inode
5529 * item of the fs/subvol tree (see overwrite_item()).
5531 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5532 struct btrfs_root *root,
5533 struct btrfs_inode *start_inode,
5534 struct btrfs_log_ctx *ctx)
5536 struct btrfs_fs_info *fs_info = root->fs_info;
5537 struct btrfs_root *log = root->log_root;
5538 struct btrfs_path *path;
5539 LIST_HEAD(dir_list);
5540 struct btrfs_dir_list *dir_elem;
5541 int ret = 0;
5543 path = btrfs_alloc_path();
5544 if (!path)
5545 return -ENOMEM;
5547 dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5548 if (!dir_elem) {
5549 btrfs_free_path(path);
5550 return -ENOMEM;
5552 dir_elem->ino = btrfs_ino(start_inode);
5553 list_add_tail(&dir_elem->list, &dir_list);
5555 while (!list_empty(&dir_list)) {
5556 struct extent_buffer *leaf;
5557 struct btrfs_key min_key;
5558 int nritems;
5559 int i;
5561 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list,
5562 list);
5563 if (ret)
5564 goto next_dir_inode;
5566 min_key.objectid = dir_elem->ino;
5567 min_key.type = BTRFS_DIR_ITEM_KEY;
5568 min_key.offset = 0;
5569 again:
5570 btrfs_release_path(path);
5571 ret = btrfs_search_forward(log, &min_key, path, trans->transid);
5572 if (ret < 0) {
5573 goto next_dir_inode;
5574 } else if (ret > 0) {
5575 ret = 0;
5576 goto next_dir_inode;
5579 process_leaf:
5580 leaf = path->nodes[0];
5581 nritems = btrfs_header_nritems(leaf);
5582 for (i = path->slots[0]; i < nritems; i++) {
5583 struct btrfs_dir_item *di;
5584 struct btrfs_key di_key;
5585 struct inode *di_inode;
5586 struct btrfs_dir_list *new_dir_elem;
5587 int log_mode = LOG_INODE_EXISTS;
5588 int type;
5590 btrfs_item_key_to_cpu(leaf, &min_key, i);
5591 if (min_key.objectid != dir_elem->ino ||
5592 min_key.type != BTRFS_DIR_ITEM_KEY)
5593 goto next_dir_inode;
5595 di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5596 type = btrfs_dir_type(leaf, di);
5597 if (btrfs_dir_transid(leaf, di) < trans->transid &&
5598 type != BTRFS_FT_DIR)
5599 continue;
5600 btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5601 if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5602 continue;
5604 btrfs_release_path(path);
5605 di_inode = btrfs_iget(fs_info->sb, &di_key, root, NULL);
5606 if (IS_ERR(di_inode)) {
5607 ret = PTR_ERR(di_inode);
5608 goto next_dir_inode;
5611 if (btrfs_inode_in_log(BTRFS_I(di_inode), trans->transid)) {
5612 btrfs_add_delayed_iput(di_inode);
5613 break;
5616 ctx->log_new_dentries = false;
5617 if (type == BTRFS_FT_DIR || type == BTRFS_FT_SYMLINK)
5618 log_mode = LOG_INODE_ALL;
5619 ret = btrfs_log_inode(trans, root, BTRFS_I(di_inode),
5620 log_mode, 0, LLONG_MAX, ctx);
5621 if (!ret &&
5622 btrfs_must_commit_transaction(trans, BTRFS_I(di_inode)))
5623 ret = 1;
5624 btrfs_add_delayed_iput(di_inode);
5625 if (ret)
5626 goto next_dir_inode;
5627 if (ctx->log_new_dentries) {
5628 new_dir_elem = kmalloc(sizeof(*new_dir_elem),
5629 GFP_NOFS);
5630 if (!new_dir_elem) {
5631 ret = -ENOMEM;
5632 goto next_dir_inode;
5634 new_dir_elem->ino = di_key.objectid;
5635 list_add_tail(&new_dir_elem->list, &dir_list);
5637 break;
5639 if (i == nritems) {
5640 ret = btrfs_next_leaf(log, path);
5641 if (ret < 0) {
5642 goto next_dir_inode;
5643 } else if (ret > 0) {
5644 ret = 0;
5645 goto next_dir_inode;
5647 goto process_leaf;
5649 if (min_key.offset < (u64)-1) {
5650 min_key.offset++;
5651 goto again;
5653 next_dir_inode:
5654 list_del(&dir_elem->list);
5655 kfree(dir_elem);
5658 btrfs_free_path(path);
5659 return ret;
5662 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
5663 struct btrfs_inode *inode,
5664 struct btrfs_log_ctx *ctx)
5666 struct btrfs_fs_info *fs_info = trans->fs_info;
5667 int ret;
5668 struct btrfs_path *path;
5669 struct btrfs_key key;
5670 struct btrfs_root *root = inode->root;
5671 const u64 ino = btrfs_ino(inode);
5673 path = btrfs_alloc_path();
5674 if (!path)
5675 return -ENOMEM;
5676 path->skip_locking = 1;
5677 path->search_commit_root = 1;
5679 key.objectid = ino;
5680 key.type = BTRFS_INODE_REF_KEY;
5681 key.offset = 0;
5682 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5683 if (ret < 0)
5684 goto out;
5686 while (true) {
5687 struct extent_buffer *leaf = path->nodes[0];
5688 int slot = path->slots[0];
5689 u32 cur_offset = 0;
5690 u32 item_size;
5691 unsigned long ptr;
5693 if (slot >= btrfs_header_nritems(leaf)) {
5694 ret = btrfs_next_leaf(root, path);
5695 if (ret < 0)
5696 goto out;
5697 else if (ret > 0)
5698 break;
5699 continue;
5702 btrfs_item_key_to_cpu(leaf, &key, slot);
5703 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
5704 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
5705 break;
5707 item_size = btrfs_item_size_nr(leaf, slot);
5708 ptr = btrfs_item_ptr_offset(leaf, slot);
5709 while (cur_offset < item_size) {
5710 struct btrfs_key inode_key;
5711 struct inode *dir_inode;
5713 inode_key.type = BTRFS_INODE_ITEM_KEY;
5714 inode_key.offset = 0;
5716 if (key.type == BTRFS_INODE_EXTREF_KEY) {
5717 struct btrfs_inode_extref *extref;
5719 extref = (struct btrfs_inode_extref *)
5720 (ptr + cur_offset);
5721 inode_key.objectid = btrfs_inode_extref_parent(
5722 leaf, extref);
5723 cur_offset += sizeof(*extref);
5724 cur_offset += btrfs_inode_extref_name_len(leaf,
5725 extref);
5726 } else {
5727 inode_key.objectid = key.offset;
5728 cur_offset = item_size;
5731 dir_inode = btrfs_iget(fs_info->sb, &inode_key,
5732 root, NULL);
5734 * If the parent inode was deleted, return an error to
5735 * fallback to a transaction commit. This is to prevent
5736 * getting an inode that was moved from one parent A to
5737 * a parent B, got its former parent A deleted and then
5738 * it got fsync'ed, from existing at both parents after
5739 * a log replay (and the old parent still existing).
5740 * Example:
5742 * mkdir /mnt/A
5743 * mkdir /mnt/B
5744 * touch /mnt/B/bar
5745 * sync
5746 * mv /mnt/B/bar /mnt/A/bar
5747 * mv -T /mnt/A /mnt/B
5748 * fsync /mnt/B/bar
5749 * <power fail>
5751 * If we ignore the old parent B which got deleted,
5752 * after a log replay we would have file bar linked
5753 * at both parents and the old parent B would still
5754 * exist.
5756 if (IS_ERR(dir_inode)) {
5757 ret = PTR_ERR(dir_inode);
5758 goto out;
5761 if (ctx)
5762 ctx->log_new_dentries = false;
5763 ret = btrfs_log_inode(trans, root, BTRFS_I(dir_inode),
5764 LOG_INODE_ALL, 0, LLONG_MAX, ctx);
5765 if (!ret &&
5766 btrfs_must_commit_transaction(trans, BTRFS_I(dir_inode)))
5767 ret = 1;
5768 if (!ret && ctx && ctx->log_new_dentries)
5769 ret = log_new_dir_dentries(trans, root,
5770 BTRFS_I(dir_inode), ctx);
5771 btrfs_add_delayed_iput(dir_inode);
5772 if (ret)
5773 goto out;
5775 path->slots[0]++;
5777 ret = 0;
5778 out:
5779 btrfs_free_path(path);
5780 return ret;
5783 static int log_new_ancestors(struct btrfs_trans_handle *trans,
5784 struct btrfs_root *root,
5785 struct btrfs_path *path,
5786 struct btrfs_log_ctx *ctx)
5788 struct btrfs_key found_key;
5790 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
5792 while (true) {
5793 struct btrfs_fs_info *fs_info = root->fs_info;
5794 const u64 last_committed = fs_info->last_trans_committed;
5795 struct extent_buffer *leaf = path->nodes[0];
5796 int slot = path->slots[0];
5797 struct btrfs_key search_key;
5798 struct inode *inode;
5799 int ret = 0;
5801 btrfs_release_path(path);
5803 search_key.objectid = found_key.offset;
5804 search_key.type = BTRFS_INODE_ITEM_KEY;
5805 search_key.offset = 0;
5806 inode = btrfs_iget(fs_info->sb, &search_key, root, NULL);
5807 if (IS_ERR(inode))
5808 return PTR_ERR(inode);
5810 if (BTRFS_I(inode)->generation > last_committed)
5811 ret = btrfs_log_inode(trans, root, BTRFS_I(inode),
5812 LOG_INODE_EXISTS,
5813 0, LLONG_MAX, ctx);
5814 btrfs_add_delayed_iput(inode);
5815 if (ret)
5816 return ret;
5818 if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
5819 break;
5821 search_key.type = BTRFS_INODE_REF_KEY;
5822 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5823 if (ret < 0)
5824 return ret;
5826 leaf = path->nodes[0];
5827 slot = path->slots[0];
5828 if (slot >= btrfs_header_nritems(leaf)) {
5829 ret = btrfs_next_leaf(root, path);
5830 if (ret < 0)
5831 return ret;
5832 else if (ret > 0)
5833 return -ENOENT;
5834 leaf = path->nodes[0];
5835 slot = path->slots[0];
5838 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5839 if (found_key.objectid != search_key.objectid ||
5840 found_key.type != BTRFS_INODE_REF_KEY)
5841 return -ENOENT;
5843 return 0;
5846 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
5847 struct btrfs_inode *inode,
5848 struct dentry *parent,
5849 struct btrfs_log_ctx *ctx)
5851 struct btrfs_root *root = inode->root;
5852 struct btrfs_fs_info *fs_info = root->fs_info;
5853 struct dentry *old_parent = NULL;
5854 struct super_block *sb = inode->vfs_inode.i_sb;
5855 int ret = 0;
5857 while (true) {
5858 if (!parent || d_really_is_negative(parent) ||
5859 sb != parent->d_sb)
5860 break;
5862 inode = BTRFS_I(d_inode(parent));
5863 if (root != inode->root)
5864 break;
5866 if (inode->generation > fs_info->last_trans_committed) {
5867 ret = btrfs_log_inode(trans, root, inode,
5868 LOG_INODE_EXISTS, 0, LLONG_MAX, ctx);
5869 if (ret)
5870 break;
5872 if (IS_ROOT(parent))
5873 break;
5875 parent = dget_parent(parent);
5876 dput(old_parent);
5877 old_parent = parent;
5879 dput(old_parent);
5881 return ret;
5884 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
5885 struct btrfs_inode *inode,
5886 struct dentry *parent,
5887 struct btrfs_log_ctx *ctx)
5889 struct btrfs_root *root = inode->root;
5890 const u64 ino = btrfs_ino(inode);
5891 struct btrfs_path *path;
5892 struct btrfs_key search_key;
5893 int ret;
5896 * For a single hard link case, go through a fast path that does not
5897 * need to iterate the fs/subvolume tree.
5899 if (inode->vfs_inode.i_nlink < 2)
5900 return log_new_ancestors_fast(trans, inode, parent, ctx);
5902 path = btrfs_alloc_path();
5903 if (!path)
5904 return -ENOMEM;
5906 search_key.objectid = ino;
5907 search_key.type = BTRFS_INODE_REF_KEY;
5908 search_key.offset = 0;
5909 again:
5910 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
5911 if (ret < 0)
5912 goto out;
5913 if (ret == 0)
5914 path->slots[0]++;
5916 while (true) {
5917 struct extent_buffer *leaf = path->nodes[0];
5918 int slot = path->slots[0];
5919 struct btrfs_key found_key;
5921 if (slot >= btrfs_header_nritems(leaf)) {
5922 ret = btrfs_next_leaf(root, path);
5923 if (ret < 0)
5924 goto out;
5925 else if (ret > 0)
5926 break;
5927 continue;
5930 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5931 if (found_key.objectid != ino ||
5932 found_key.type > BTRFS_INODE_EXTREF_KEY)
5933 break;
5936 * Don't deal with extended references because they are rare
5937 * cases and too complex to deal with (we would need to keep
5938 * track of which subitem we are processing for each item in
5939 * this loop, etc). So just return some error to fallback to
5940 * a transaction commit.
5942 if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
5943 ret = -EMLINK;
5944 goto out;
5948 * Logging ancestors needs to do more searches on the fs/subvol
5949 * tree, so it releases the path as needed to avoid deadlocks.
5950 * Keep track of the last inode ref key and resume from that key
5951 * after logging all new ancestors for the current hard link.
5953 memcpy(&search_key, &found_key, sizeof(search_key));
5955 ret = log_new_ancestors(trans, root, path, ctx);
5956 if (ret)
5957 goto out;
5958 btrfs_release_path(path);
5959 goto again;
5961 ret = 0;
5962 out:
5963 btrfs_free_path(path);
5964 return ret;
5968 * helper function around btrfs_log_inode to make sure newly created
5969 * parent directories also end up in the log. A minimal inode and backref
5970 * only logging is done of any parent directories that are older than
5971 * the last committed transaction
5973 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
5974 struct btrfs_inode *inode,
5975 struct dentry *parent,
5976 const loff_t start,
5977 const loff_t end,
5978 int inode_only,
5979 struct btrfs_log_ctx *ctx)
5981 struct btrfs_root *root = inode->root;
5982 struct btrfs_fs_info *fs_info = root->fs_info;
5983 struct super_block *sb;
5984 int ret = 0;
5985 u64 last_committed = fs_info->last_trans_committed;
5986 bool log_dentries = false;
5988 sb = inode->vfs_inode.i_sb;
5990 if (btrfs_test_opt(fs_info, NOTREELOG)) {
5991 ret = 1;
5992 goto end_no_trans;
5996 * The prev transaction commit doesn't complete, we need do
5997 * full commit by ourselves.
5999 if (fs_info->last_trans_log_full_commit >
6000 fs_info->last_trans_committed) {
6001 ret = 1;
6002 goto end_no_trans;
6005 if (btrfs_root_refs(&root->root_item) == 0) {
6006 ret = 1;
6007 goto end_no_trans;
6010 ret = check_parent_dirs_for_sync(trans, inode, parent, sb,
6011 last_committed);
6012 if (ret)
6013 goto end_no_trans;
6016 * Skip already logged inodes or inodes corresponding to tmpfiles
6017 * (since logging them is pointless, a link count of 0 means they
6018 * will never be accessible).
6020 if (btrfs_inode_in_log(inode, trans->transid) ||
6021 inode->vfs_inode.i_nlink == 0) {
6022 ret = BTRFS_NO_LOG_SYNC;
6023 goto end_no_trans;
6026 ret = start_log_trans(trans, root, ctx);
6027 if (ret)
6028 goto end_no_trans;
6030 ret = btrfs_log_inode(trans, root, inode, inode_only, start, end, ctx);
6031 if (ret)
6032 goto end_trans;
6035 * for regular files, if its inode is already on disk, we don't
6036 * have to worry about the parents at all. This is because
6037 * we can use the last_unlink_trans field to record renames
6038 * and other fun in this file.
6040 if (S_ISREG(inode->vfs_inode.i_mode) &&
6041 inode->generation <= last_committed &&
6042 inode->last_unlink_trans <= last_committed) {
6043 ret = 0;
6044 goto end_trans;
6047 if (S_ISDIR(inode->vfs_inode.i_mode) && ctx && ctx->log_new_dentries)
6048 log_dentries = true;
6051 * On unlink we must make sure all our current and old parent directory
6052 * inodes are fully logged. This is to prevent leaving dangling
6053 * directory index entries in directories that were our parents but are
6054 * not anymore. Not doing this results in old parent directory being
6055 * impossible to delete after log replay (rmdir will always fail with
6056 * error -ENOTEMPTY).
6058 * Example 1:
6060 * mkdir testdir
6061 * touch testdir/foo
6062 * ln testdir/foo testdir/bar
6063 * sync
6064 * unlink testdir/bar
6065 * xfs_io -c fsync testdir/foo
6066 * <power failure>
6067 * mount fs, triggers log replay
6069 * If we don't log the parent directory (testdir), after log replay the
6070 * directory still has an entry pointing to the file inode using the bar
6071 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
6072 * the file inode has a link count of 1.
6074 * Example 2:
6076 * mkdir testdir
6077 * touch foo
6078 * ln foo testdir/foo2
6079 * ln foo testdir/foo3
6080 * sync
6081 * unlink testdir/foo3
6082 * xfs_io -c fsync foo
6083 * <power failure>
6084 * mount fs, triggers log replay
6086 * Similar as the first example, after log replay the parent directory
6087 * testdir still has an entry pointing to the inode file with name foo3
6088 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
6089 * and has a link count of 2.
6091 if (inode->last_unlink_trans > last_committed) {
6092 ret = btrfs_log_all_parents(trans, inode, ctx);
6093 if (ret)
6094 goto end_trans;
6097 ret = log_all_new_ancestors(trans, inode, parent, ctx);
6098 if (ret)
6099 goto end_trans;
6101 if (log_dentries)
6102 ret = log_new_dir_dentries(trans, root, inode, ctx);
6103 else
6104 ret = 0;
6105 end_trans:
6106 if (ret < 0) {
6107 btrfs_set_log_full_commit(trans);
6108 ret = 1;
6111 if (ret)
6112 btrfs_remove_log_ctx(root, ctx);
6113 btrfs_end_log_trans(root);
6114 end_no_trans:
6115 return ret;
6119 * it is not safe to log dentry if the chunk root has added new
6120 * chunks. This returns 0 if the dentry was logged, and 1 otherwise.
6121 * If this returns 1, you must commit the transaction to safely get your
6122 * data on disk.
6124 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
6125 struct dentry *dentry,
6126 const loff_t start,
6127 const loff_t end,
6128 struct btrfs_log_ctx *ctx)
6130 struct dentry *parent = dget_parent(dentry);
6131 int ret;
6133 ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
6134 start, end, LOG_INODE_ALL, ctx);
6135 dput(parent);
6137 return ret;
6141 * should be called during mount to recover any replay any log trees
6142 * from the FS
6144 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
6146 int ret;
6147 struct btrfs_path *path;
6148 struct btrfs_trans_handle *trans;
6149 struct btrfs_key key;
6150 struct btrfs_key found_key;
6151 struct btrfs_key tmp_key;
6152 struct btrfs_root *log;
6153 struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
6154 struct walk_control wc = {
6155 .process_func = process_one_buffer,
6156 .stage = LOG_WALK_PIN_ONLY,
6159 path = btrfs_alloc_path();
6160 if (!path)
6161 return -ENOMEM;
6163 set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
6165 trans = btrfs_start_transaction(fs_info->tree_root, 0);
6166 if (IS_ERR(trans)) {
6167 ret = PTR_ERR(trans);
6168 goto error;
6171 wc.trans = trans;
6172 wc.pin = 1;
6174 ret = walk_log_tree(trans, log_root_tree, &wc);
6175 if (ret) {
6176 btrfs_handle_fs_error(fs_info, ret,
6177 "Failed to pin buffers while recovering log root tree.");
6178 goto error;
6181 again:
6182 key.objectid = BTRFS_TREE_LOG_OBJECTID;
6183 key.offset = (u64)-1;
6184 key.type = BTRFS_ROOT_ITEM_KEY;
6186 while (1) {
6187 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
6189 if (ret < 0) {
6190 btrfs_handle_fs_error(fs_info, ret,
6191 "Couldn't find tree log root.");
6192 goto error;
6194 if (ret > 0) {
6195 if (path->slots[0] == 0)
6196 break;
6197 path->slots[0]--;
6199 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
6200 path->slots[0]);
6201 btrfs_release_path(path);
6202 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
6203 break;
6205 log = btrfs_read_fs_root(log_root_tree, &found_key);
6206 if (IS_ERR(log)) {
6207 ret = PTR_ERR(log);
6208 btrfs_handle_fs_error(fs_info, ret,
6209 "Couldn't read tree log root.");
6210 goto error;
6213 tmp_key.objectid = found_key.offset;
6214 tmp_key.type = BTRFS_ROOT_ITEM_KEY;
6215 tmp_key.offset = (u64)-1;
6217 wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
6218 if (IS_ERR(wc.replay_dest)) {
6219 ret = PTR_ERR(wc.replay_dest);
6222 * We didn't find the subvol, likely because it was
6223 * deleted. This is ok, simply skip this log and go to
6224 * the next one.
6226 * We need to exclude the root because we can't have
6227 * other log replays overwriting this log as we'll read
6228 * it back in a few more times. This will keep our
6229 * block from being modified, and we'll just bail for
6230 * each subsequent pass.
6232 if (ret == -ENOENT)
6233 ret = btrfs_pin_extent_for_log_replay(fs_info,
6234 log->node->start,
6235 log->node->len);
6236 free_extent_buffer(log->node);
6237 free_extent_buffer(log->commit_root);
6238 kfree(log);
6240 if (!ret)
6241 goto next;
6242 btrfs_handle_fs_error(fs_info, ret,
6243 "Couldn't read target root for tree log recovery.");
6244 goto error;
6247 wc.replay_dest->log_root = log;
6248 btrfs_record_root_in_trans(trans, wc.replay_dest);
6249 ret = walk_log_tree(trans, log, &wc);
6251 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
6252 ret = fixup_inode_link_counts(trans, wc.replay_dest,
6253 path);
6256 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
6257 struct btrfs_root *root = wc.replay_dest;
6259 btrfs_release_path(path);
6262 * We have just replayed everything, and the highest
6263 * objectid of fs roots probably has changed in case
6264 * some inode_item's got replayed.
6266 * root->objectid_mutex is not acquired as log replay
6267 * could only happen during mount.
6269 ret = btrfs_find_highest_objectid(root,
6270 &root->highest_objectid);
6273 wc.replay_dest->log_root = NULL;
6274 free_extent_buffer(log->node);
6275 free_extent_buffer(log->commit_root);
6276 kfree(log);
6278 if (ret)
6279 goto error;
6280 next:
6281 if (found_key.offset == 0)
6282 break;
6283 key.offset = found_key.offset - 1;
6285 btrfs_release_path(path);
6287 /* step one is to pin it all, step two is to replay just inodes */
6288 if (wc.pin) {
6289 wc.pin = 0;
6290 wc.process_func = replay_one_buffer;
6291 wc.stage = LOG_WALK_REPLAY_INODES;
6292 goto again;
6294 /* step three is to replay everything */
6295 if (wc.stage < LOG_WALK_REPLAY_ALL) {
6296 wc.stage++;
6297 goto again;
6300 btrfs_free_path(path);
6302 /* step 4: commit the transaction, which also unpins the blocks */
6303 ret = btrfs_commit_transaction(trans);
6304 if (ret)
6305 return ret;
6307 free_extent_buffer(log_root_tree->node);
6308 log_root_tree->log_root = NULL;
6309 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
6310 kfree(log_root_tree);
6312 return 0;
6313 error:
6314 if (wc.trans)
6315 btrfs_end_transaction(wc.trans);
6316 btrfs_free_path(path);
6317 return ret;
6321 * there are some corner cases where we want to force a full
6322 * commit instead of allowing a directory to be logged.
6324 * They revolve around files there were unlinked from the directory, and
6325 * this function updates the parent directory so that a full commit is
6326 * properly done if it is fsync'd later after the unlinks are done.
6328 * Must be called before the unlink operations (updates to the subvolume tree,
6329 * inodes, etc) are done.
6331 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
6332 struct btrfs_inode *dir, struct btrfs_inode *inode,
6333 int for_rename)
6336 * when we're logging a file, if it hasn't been renamed
6337 * or unlinked, and its inode is fully committed on disk,
6338 * we don't have to worry about walking up the directory chain
6339 * to log its parents.
6341 * So, we use the last_unlink_trans field to put this transid
6342 * into the file. When the file is logged we check it and
6343 * don't log the parents if the file is fully on disk.
6345 mutex_lock(&inode->log_mutex);
6346 inode->last_unlink_trans = trans->transid;
6347 mutex_unlock(&inode->log_mutex);
6350 * if this directory was already logged any new
6351 * names for this file/dir will get recorded
6353 if (dir->logged_trans == trans->transid)
6354 return;
6357 * if the inode we're about to unlink was logged,
6358 * the log will be properly updated for any new names
6360 if (inode->logged_trans == trans->transid)
6361 return;
6364 * when renaming files across directories, if the directory
6365 * there we're unlinking from gets fsync'd later on, there's
6366 * no way to find the destination directory later and fsync it
6367 * properly. So, we have to be conservative and force commits
6368 * so the new name gets discovered.
6370 if (for_rename)
6371 goto record;
6373 /* we can safely do the unlink without any special recording */
6374 return;
6376 record:
6377 mutex_lock(&dir->log_mutex);
6378 dir->last_unlink_trans = trans->transid;
6379 mutex_unlock(&dir->log_mutex);
6383 * Make sure that if someone attempts to fsync the parent directory of a deleted
6384 * snapshot, it ends up triggering a transaction commit. This is to guarantee
6385 * that after replaying the log tree of the parent directory's root we will not
6386 * see the snapshot anymore and at log replay time we will not see any log tree
6387 * corresponding to the deleted snapshot's root, which could lead to replaying
6388 * it after replaying the log tree of the parent directory (which would replay
6389 * the snapshot delete operation).
6391 * Must be called before the actual snapshot destroy operation (updates to the
6392 * parent root and tree of tree roots trees, etc) are done.
6394 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
6395 struct btrfs_inode *dir)
6397 mutex_lock(&dir->log_mutex);
6398 dir->last_unlink_trans = trans->transid;
6399 mutex_unlock(&dir->log_mutex);
6403 * Call this after adding a new name for a file and it will properly
6404 * update the log to reflect the new name.
6406 * @ctx can not be NULL when @sync_log is false, and should be NULL when it's
6407 * true (because it's not used).
6409 * Return value depends on whether @sync_log is true or false.
6410 * When true: returns BTRFS_NEED_TRANS_COMMIT if the transaction needs to be
6411 * committed by the caller, and BTRFS_DONT_NEED_TRANS_COMMIT
6412 * otherwise.
6413 * When false: returns BTRFS_DONT_NEED_LOG_SYNC if the caller does not need to
6414 * to sync the log, BTRFS_NEED_LOG_SYNC if it needs to sync the log,
6415 * or BTRFS_NEED_TRANS_COMMIT if the transaction needs to be
6416 * committed (without attempting to sync the log).
6418 int btrfs_log_new_name(struct btrfs_trans_handle *trans,
6419 struct btrfs_inode *inode, struct btrfs_inode *old_dir,
6420 struct dentry *parent,
6421 bool sync_log, struct btrfs_log_ctx *ctx)
6423 struct btrfs_fs_info *fs_info = trans->fs_info;
6424 int ret;
6427 * this will force the logging code to walk the dentry chain
6428 * up for the file
6430 if (!S_ISDIR(inode->vfs_inode.i_mode))
6431 inode->last_unlink_trans = trans->transid;
6434 * if this inode hasn't been logged and directory we're renaming it
6435 * from hasn't been logged, we don't need to log it
6437 if (inode->logged_trans <= fs_info->last_trans_committed &&
6438 (!old_dir || old_dir->logged_trans <= fs_info->last_trans_committed))
6439 return sync_log ? BTRFS_DONT_NEED_TRANS_COMMIT :
6440 BTRFS_DONT_NEED_LOG_SYNC;
6442 if (sync_log) {
6443 struct btrfs_log_ctx ctx2;
6445 btrfs_init_log_ctx(&ctx2, &inode->vfs_inode);
6446 ret = btrfs_log_inode_parent(trans, inode, parent, 0, LLONG_MAX,
6447 LOG_INODE_EXISTS, &ctx2);
6448 if (ret == BTRFS_NO_LOG_SYNC)
6449 return BTRFS_DONT_NEED_TRANS_COMMIT;
6450 else if (ret)
6451 return BTRFS_NEED_TRANS_COMMIT;
6453 ret = btrfs_sync_log(trans, inode->root, &ctx2);
6454 if (ret)
6455 return BTRFS_NEED_TRANS_COMMIT;
6456 return BTRFS_DONT_NEED_TRANS_COMMIT;
6459 ASSERT(ctx);
6460 ret = btrfs_log_inode_parent(trans, inode, parent, 0, LLONG_MAX,
6461 LOG_INODE_EXISTS, ctx);
6462 if (ret == BTRFS_NO_LOG_SYNC)
6463 return BTRFS_DONT_NEED_LOG_SYNC;
6464 else if (ret)
6465 return BTRFS_NEED_TRANS_COMMIT;
6467 return BTRFS_NEED_LOG_SYNC;