1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2008 Oracle. All rights reserved.
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>
16 #include "print-tree.h"
18 #include "compression.h"
20 #include "block-group.h"
21 #include "space-info.h"
23 #include "inode-item.h"
25 #include "accessors.h"
26 #include "extent-tree.h"
27 #include "root-tree.h"
30 #define MAX_CONFLICT_INODES 10
32 /* magic values for the inode_only field in btrfs_log_inode:
34 * LOG_INODE_ALL means to log everything
35 * LOG_INODE_EXISTS means to log just enough to recreate the inode
44 * directory trouble cases
46 * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
47 * log, we must force a full commit before doing an fsync of the directory
48 * where the unlink was done.
49 * ---> record transid of last unlink/rename per directory
53 * rename foo/some_dir foo2/some_dir
55 * fsync foo/some_dir/some_file
57 * The fsync above will unlink the original some_dir without recording
58 * it in its new location (foo2). After a crash, some_dir will be gone
59 * unless the fsync of some_file forces a full commit
61 * 2) we must log any new names for any file or dir that is in the fsync
62 * log. ---> check inode while renaming/linking.
64 * 2a) we must log any new names for any file or dir during rename
65 * when the directory they are being removed from was logged.
66 * ---> check inode and old parent dir during rename
68 * 2a is actually the more important variant. With the extra logging
69 * a crash might unlink the old name without recreating the new one
71 * 3) after a crash, we must go through any directories with a link count
72 * of zero and redo the rm -rf
79 * The directory f1 was fully removed from the FS, but fsync was never
80 * called on f1, only its parent dir. After a crash the rm -rf must
81 * be replayed. This must be able to recurse down the entire
82 * directory tree. The inode link count fixup code takes care of the
87 * stages for the tree walking. The first
88 * stage (0) is to only pin down the blocks we find
89 * the second stage (1) is to make sure that all the inodes
90 * we find in the log are created in the subvolume.
92 * The last stage is to deal with directories and links and extents
93 * and all the other fun semantics
97 LOG_WALK_REPLAY_INODES,
98 LOG_WALK_REPLAY_DIR_INDEX,
102 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
103 struct btrfs_inode *inode,
105 struct btrfs_log_ctx *ctx);
106 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
107 struct btrfs_root *root,
108 struct btrfs_path *path, u64 objectid);
109 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
110 struct btrfs_root *root,
111 struct btrfs_root *log,
112 struct btrfs_path *path,
113 u64 dirid, int del_all);
114 static void wait_log_commit(struct btrfs_root *root, int transid);
117 * tree logging is a special write ahead log used to make sure that
118 * fsyncs and O_SYNCs can happen without doing full tree commits.
120 * Full tree commits are expensive because they require commonly
121 * modified blocks to be recowed, creating many dirty pages in the
122 * extent tree an 4x-6x higher write load than ext3.
124 * Instead of doing a tree commit on every fsync, we use the
125 * key ranges and transaction ids to find items for a given file or directory
126 * that have changed in this transaction. Those items are copied into
127 * a special tree (one per subvolume root), that tree is written to disk
128 * and then the fsync is considered complete.
130 * After a crash, items are copied out of the log-tree back into the
131 * subvolume tree. Any file data extents found are recorded in the extent
132 * allocation tree, and the log-tree freed.
134 * The log tree is read three times, once to pin down all the extents it is
135 * using in ram and once, once to create all the inodes logged in the tree
136 * and once to do all the other items.
140 * start a sub transaction and setup the log tree
141 * this increments the log tree writer count to make the people
142 * syncing the tree wait for us to finish
144 static int start_log_trans(struct btrfs_trans_handle *trans,
145 struct btrfs_root *root,
146 struct btrfs_log_ctx *ctx)
148 struct btrfs_fs_info *fs_info = root->fs_info;
149 struct btrfs_root *tree_root = fs_info->tree_root;
150 const bool zoned = btrfs_is_zoned(fs_info);
152 bool created = false;
155 * First check if the log root tree was already created. If not, create
156 * it before locking the root's log_mutex, just to keep lockdep happy.
158 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
159 mutex_lock(&tree_root->log_mutex);
160 if (!fs_info->log_root_tree) {
161 ret = btrfs_init_log_root_tree(trans, fs_info);
163 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
167 mutex_unlock(&tree_root->log_mutex);
172 mutex_lock(&root->log_mutex);
175 if (root->log_root) {
176 int index = (root->log_transid + 1) % 2;
178 if (btrfs_need_log_full_commit(trans)) {
179 ret = BTRFS_LOG_FORCE_COMMIT;
183 if (zoned && atomic_read(&root->log_commit[index])) {
184 wait_log_commit(root, root->log_transid - 1);
188 if (!root->log_start_pid) {
189 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
190 root->log_start_pid = current->pid;
191 } else if (root->log_start_pid != current->pid) {
192 set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
196 * This means fs_info->log_root_tree was already created
197 * for some other FS trees. Do the full commit not to mix
198 * nodes from multiple log transactions to do sequential
201 if (zoned && !created) {
202 ret = BTRFS_LOG_FORCE_COMMIT;
206 ret = btrfs_add_log_tree(trans, root);
210 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
211 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
212 root->log_start_pid = current->pid;
215 atomic_inc(&root->log_writers);
216 if (!ctx->logging_new_name) {
217 int index = root->log_transid % 2;
218 list_add_tail(&ctx->list, &root->log_ctxs[index]);
219 ctx->log_transid = root->log_transid;
223 mutex_unlock(&root->log_mutex);
228 * returns 0 if there was a log transaction running and we were able
229 * to join, or returns -ENOENT if there were not transactions
232 static int join_running_log_trans(struct btrfs_root *root)
234 const bool zoned = btrfs_is_zoned(root->fs_info);
237 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
240 mutex_lock(&root->log_mutex);
242 if (root->log_root) {
243 int index = (root->log_transid + 1) % 2;
246 if (zoned && atomic_read(&root->log_commit[index])) {
247 wait_log_commit(root, root->log_transid - 1);
250 atomic_inc(&root->log_writers);
252 mutex_unlock(&root->log_mutex);
257 * This either makes the current running log transaction wait
258 * until you call btrfs_end_log_trans() or it makes any future
259 * log transactions wait until you call btrfs_end_log_trans()
261 void btrfs_pin_log_trans(struct btrfs_root *root)
263 atomic_inc(&root->log_writers);
267 * indicate we're done making changes to the log tree
268 * and wake up anyone waiting to do a sync
270 void btrfs_end_log_trans(struct btrfs_root *root)
272 if (atomic_dec_and_test(&root->log_writers)) {
273 /* atomic_dec_and_test implies a barrier */
274 cond_wake_up_nomb(&root->log_writer_wait);
278 static void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
280 filemap_fdatawait_range(buf->pages[0]->mapping,
281 buf->start, buf->start + buf->len - 1);
285 * the walk control struct is used to pass state down the chain when
286 * processing the log tree. The stage field tells us which part
287 * of the log tree processing we are currently doing. The others
288 * are state fields used for that specific part
290 struct walk_control {
291 /* should we free the extent on disk when done? This is used
292 * at transaction commit time while freeing a log tree
296 /* pin only walk, we record which extents on disk belong to the
301 /* what stage of the replay code we're currently in */
305 * Ignore any items from the inode currently being processed. Needs
306 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
307 * the LOG_WALK_REPLAY_INODES stage.
309 bool ignore_cur_inode;
311 /* the root we are currently replaying */
312 struct btrfs_root *replay_dest;
314 /* the trans handle for the current replay */
315 struct btrfs_trans_handle *trans;
317 /* the function that gets used to process blocks we find in the
318 * tree. Note the extent_buffer might not be up to date when it is
319 * passed in, and it must be checked or read if you need the data
322 int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
323 struct walk_control *wc, u64 gen, int level);
327 * process_func used to pin down extents, write them or wait on them
329 static int process_one_buffer(struct btrfs_root *log,
330 struct extent_buffer *eb,
331 struct walk_control *wc, u64 gen, int level)
333 struct btrfs_fs_info *fs_info = log->fs_info;
337 * If this fs is mixed then we need to be able to process the leaves to
338 * pin down any logged extents, so we have to read the block.
340 if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
341 ret = btrfs_read_extent_buffer(eb, gen, level, NULL);
347 ret = btrfs_pin_extent_for_log_replay(wc->trans, eb->start,
352 if (btrfs_buffer_uptodate(eb, gen, 0) &&
353 btrfs_header_level(eb) == 0)
354 ret = btrfs_exclude_logged_extents(eb);
359 static int do_overwrite_item(struct btrfs_trans_handle *trans,
360 struct btrfs_root *root,
361 struct btrfs_path *path,
362 struct extent_buffer *eb, int slot,
363 struct btrfs_key *key)
367 u64 saved_i_size = 0;
368 int save_old_i_size = 0;
369 unsigned long src_ptr;
370 unsigned long dst_ptr;
371 int overwrite_root = 0;
372 bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
374 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
377 item_size = btrfs_item_size(eb, slot);
378 src_ptr = btrfs_item_ptr_offset(eb, slot);
380 /* Our caller must have done a search for the key for us. */
381 ASSERT(path->nodes[0] != NULL);
384 * And the slot must point to the exact key or the slot where the key
385 * should be at (the first item with a key greater than 'key')
387 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
388 struct btrfs_key found_key;
390 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
391 ret = btrfs_comp_cpu_keys(&found_key, key);
400 u32 dst_size = btrfs_item_size(path->nodes[0],
402 if (dst_size != item_size)
405 if (item_size == 0) {
406 btrfs_release_path(path);
409 dst_copy = kmalloc(item_size, GFP_NOFS);
410 src_copy = kmalloc(item_size, GFP_NOFS);
411 if (!dst_copy || !src_copy) {
412 btrfs_release_path(path);
418 read_extent_buffer(eb, src_copy, src_ptr, item_size);
420 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
421 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
423 ret = memcmp(dst_copy, src_copy, item_size);
428 * they have the same contents, just return, this saves
429 * us from cowing blocks in the destination tree and doing
430 * extra writes that may not have been done by a previous
434 btrfs_release_path(path);
439 * We need to load the old nbytes into the inode so when we
440 * replay the extents we've logged we get the right nbytes.
443 struct btrfs_inode_item *item;
447 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
448 struct btrfs_inode_item);
449 nbytes = btrfs_inode_nbytes(path->nodes[0], item);
450 item = btrfs_item_ptr(eb, slot,
451 struct btrfs_inode_item);
452 btrfs_set_inode_nbytes(eb, item, nbytes);
455 * If this is a directory we need to reset the i_size to
456 * 0 so that we can set it up properly when replaying
457 * the rest of the items in this log.
459 mode = btrfs_inode_mode(eb, item);
461 btrfs_set_inode_size(eb, item, 0);
463 } else if (inode_item) {
464 struct btrfs_inode_item *item;
468 * New inode, set nbytes to 0 so that the nbytes comes out
469 * properly when we replay the extents.
471 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
472 btrfs_set_inode_nbytes(eb, item, 0);
475 * If this is a directory we need to reset the i_size to 0 so
476 * that we can set it up properly when replaying the rest of
477 * the items in this log.
479 mode = btrfs_inode_mode(eb, item);
481 btrfs_set_inode_size(eb, item, 0);
484 btrfs_release_path(path);
485 /* try to insert the key into the destination tree */
486 path->skip_release_on_error = 1;
487 ret = btrfs_insert_empty_item(trans, root, path,
489 path->skip_release_on_error = 0;
491 /* make sure any existing item is the correct size */
492 if (ret == -EEXIST || ret == -EOVERFLOW) {
494 found_size = btrfs_item_size(path->nodes[0],
496 if (found_size > item_size)
497 btrfs_truncate_item(path, item_size, 1);
498 else if (found_size < item_size)
499 btrfs_extend_item(path, item_size - found_size);
503 dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
506 /* don't overwrite an existing inode if the generation number
507 * was logged as zero. This is done when the tree logging code
508 * is just logging an inode to make sure it exists after recovery.
510 * Also, don't overwrite i_size on directories during replay.
511 * log replay inserts and removes directory items based on the
512 * state of the tree found in the subvolume, and i_size is modified
515 if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
516 struct btrfs_inode_item *src_item;
517 struct btrfs_inode_item *dst_item;
519 src_item = (struct btrfs_inode_item *)src_ptr;
520 dst_item = (struct btrfs_inode_item *)dst_ptr;
522 if (btrfs_inode_generation(eb, src_item) == 0) {
523 struct extent_buffer *dst_eb = path->nodes[0];
524 const u64 ino_size = btrfs_inode_size(eb, src_item);
527 * For regular files an ino_size == 0 is used only when
528 * logging that an inode exists, as part of a directory
529 * fsync, and the inode wasn't fsynced before. In this
530 * case don't set the size of the inode in the fs/subvol
531 * tree, otherwise we would be throwing valid data away.
533 if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
534 S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
536 btrfs_set_inode_size(dst_eb, dst_item, ino_size);
540 if (overwrite_root &&
541 S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
542 S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
544 saved_i_size = btrfs_inode_size(path->nodes[0],
549 copy_extent_buffer(path->nodes[0], eb, dst_ptr,
552 if (save_old_i_size) {
553 struct btrfs_inode_item *dst_item;
554 dst_item = (struct btrfs_inode_item *)dst_ptr;
555 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
558 /* make sure the generation is filled in */
559 if (key->type == BTRFS_INODE_ITEM_KEY) {
560 struct btrfs_inode_item *dst_item;
561 dst_item = (struct btrfs_inode_item *)dst_ptr;
562 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
563 btrfs_set_inode_generation(path->nodes[0], dst_item,
568 btrfs_mark_buffer_dirty(path->nodes[0]);
569 btrfs_release_path(path);
574 * Item overwrite used by replay and tree logging. eb, slot and key all refer
575 * to the src data we are copying out.
577 * root is the tree we are copying into, and path is a scratch
578 * path for use in this function (it should be released on entry and
579 * will be released on exit).
581 * If the key is already in the destination tree the existing item is
582 * overwritten. If the existing item isn't big enough, it is extended.
583 * If it is too large, it is truncated.
585 * If the key isn't in the destination yet, a new item is inserted.
587 static int overwrite_item(struct btrfs_trans_handle *trans,
588 struct btrfs_root *root,
589 struct btrfs_path *path,
590 struct extent_buffer *eb, int slot,
591 struct btrfs_key *key)
595 /* Look for the key in the destination tree. */
596 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
600 return do_overwrite_item(trans, root, path, eb, slot, key);
603 static int read_alloc_one_name(struct extent_buffer *eb, void *start, int len,
604 struct fscrypt_str *name)
608 buf = kmalloc(len, GFP_NOFS);
612 read_extent_buffer(eb, buf, (unsigned long)start, len);
619 * simple helper to read an inode off the disk from a given root
620 * This can only be called for subvolume roots and not for the log
622 static noinline struct inode *read_one_inode(struct btrfs_root *root,
627 inode = btrfs_iget(root->fs_info->sb, objectid, root);
633 /* replays a single extent in 'eb' at 'slot' with 'key' into the
634 * subvolume 'root'. path is released on entry and should be released
637 * extents in the log tree have not been allocated out of the extent
638 * tree yet. So, this completes the allocation, taking a reference
639 * as required if the extent already exists or creating a new extent
640 * if it isn't in the extent allocation tree yet.
642 * The extent is inserted into the file, dropping any existing extents
643 * from the file that overlap the new one.
645 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
646 struct btrfs_root *root,
647 struct btrfs_path *path,
648 struct extent_buffer *eb, int slot,
649 struct btrfs_key *key)
651 struct btrfs_drop_extents_args drop_args = { 0 };
652 struct btrfs_fs_info *fs_info = root->fs_info;
655 u64 start = key->offset;
657 struct btrfs_file_extent_item *item;
658 struct inode *inode = NULL;
662 item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
663 found_type = btrfs_file_extent_type(eb, item);
665 if (found_type == BTRFS_FILE_EXTENT_REG ||
666 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
667 nbytes = btrfs_file_extent_num_bytes(eb, item);
668 extent_end = start + nbytes;
671 * We don't add to the inodes nbytes if we are prealloc or a
674 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
676 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
677 size = btrfs_file_extent_ram_bytes(eb, item);
678 nbytes = btrfs_file_extent_ram_bytes(eb, item);
679 extent_end = ALIGN(start + size,
680 fs_info->sectorsize);
686 inode = read_one_inode(root, key->objectid);
693 * first check to see if we already have this extent in the
694 * file. This must be done before the btrfs_drop_extents run
695 * so we don't try to drop this extent.
697 ret = btrfs_lookup_file_extent(trans, root, path,
698 btrfs_ino(BTRFS_I(inode)), start, 0);
701 (found_type == BTRFS_FILE_EXTENT_REG ||
702 found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
703 struct btrfs_file_extent_item cmp1;
704 struct btrfs_file_extent_item cmp2;
705 struct btrfs_file_extent_item *existing;
706 struct extent_buffer *leaf;
708 leaf = path->nodes[0];
709 existing = btrfs_item_ptr(leaf, path->slots[0],
710 struct btrfs_file_extent_item);
712 read_extent_buffer(eb, &cmp1, (unsigned long)item,
714 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
718 * we already have a pointer to this exact extent,
719 * we don't have to do anything
721 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
722 btrfs_release_path(path);
726 btrfs_release_path(path);
728 /* drop any overlapping extents */
729 drop_args.start = start;
730 drop_args.end = extent_end;
731 drop_args.drop_cache = true;
732 ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
736 if (found_type == BTRFS_FILE_EXTENT_REG ||
737 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
739 unsigned long dest_offset;
740 struct btrfs_key ins;
742 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
743 btrfs_fs_incompat(fs_info, NO_HOLES))
746 ret = btrfs_insert_empty_item(trans, root, path, key,
750 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
752 copy_extent_buffer(path->nodes[0], eb, dest_offset,
753 (unsigned long)item, sizeof(*item));
755 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
756 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
757 ins.type = BTRFS_EXTENT_ITEM_KEY;
758 offset = key->offset - btrfs_file_extent_offset(eb, item);
761 * Manually record dirty extent, as here we did a shallow
762 * file extent item copy and skip normal backref update,
763 * but modifying extent tree all by ourselves.
764 * So need to manually record dirty extent for qgroup,
765 * as the owner of the file extent changed from log tree
766 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
768 ret = btrfs_qgroup_trace_extent(trans,
769 btrfs_file_extent_disk_bytenr(eb, item),
770 btrfs_file_extent_disk_num_bytes(eb, item));
774 if (ins.objectid > 0) {
775 struct btrfs_ref ref = { 0 };
778 LIST_HEAD(ordered_sums);
781 * is this extent already allocated in the extent
782 * allocation tree? If so, just add a reference
784 ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
788 } else if (ret == 0) {
789 btrfs_init_generic_ref(&ref,
790 BTRFS_ADD_DELAYED_REF,
791 ins.objectid, ins.offset, 0);
792 btrfs_init_data_ref(&ref,
793 root->root_key.objectid,
794 key->objectid, offset, 0, false);
795 ret = btrfs_inc_extent_ref(trans, &ref);
800 * insert the extent pointer in the extent
803 ret = btrfs_alloc_logged_file_extent(trans,
804 root->root_key.objectid,
805 key->objectid, offset, &ins);
809 btrfs_release_path(path);
811 if (btrfs_file_extent_compression(eb, item)) {
812 csum_start = ins.objectid;
813 csum_end = csum_start + ins.offset;
815 csum_start = ins.objectid +
816 btrfs_file_extent_offset(eb, item);
817 csum_end = csum_start +
818 btrfs_file_extent_num_bytes(eb, item);
821 ret = btrfs_lookup_csums_range(root->log_root,
822 csum_start, csum_end - 1,
823 &ordered_sums, 0, false);
827 * Now delete all existing cums in the csum root that
828 * cover our range. We do this because we can have an
829 * extent that is completely referenced by one file
830 * extent item and partially referenced by another
831 * file extent item (like after using the clone or
832 * extent_same ioctls). In this case if we end up doing
833 * the replay of the one that partially references the
834 * extent first, and we do not do the csum deletion
835 * below, we can get 2 csum items in the csum tree that
836 * overlap each other. For example, imagine our log has
837 * the two following file extent items:
839 * key (257 EXTENT_DATA 409600)
840 * extent data disk byte 12845056 nr 102400
841 * extent data offset 20480 nr 20480 ram 102400
843 * key (257 EXTENT_DATA 819200)
844 * extent data disk byte 12845056 nr 102400
845 * extent data offset 0 nr 102400 ram 102400
847 * Where the second one fully references the 100K extent
848 * that starts at disk byte 12845056, and the log tree
849 * has a single csum item that covers the entire range
852 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
854 * After the first file extent item is replayed, the
855 * csum tree gets the following csum item:
857 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
859 * Which covers the 20K sub-range starting at offset 20K
860 * of our extent. Now when we replay the second file
861 * extent item, if we do not delete existing csum items
862 * that cover any of its blocks, we end up getting two
863 * csum items in our csum tree that overlap each other:
865 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
866 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
868 * Which is a problem, because after this anyone trying
869 * to lookup up for the checksum of any block of our
870 * extent starting at an offset of 40K or higher, will
871 * end up looking at the second csum item only, which
872 * does not contain the checksum for any block starting
873 * at offset 40K or higher of our extent.
875 while (!list_empty(&ordered_sums)) {
876 struct btrfs_ordered_sum *sums;
877 struct btrfs_root *csum_root;
879 sums = list_entry(ordered_sums.next,
880 struct btrfs_ordered_sum,
882 csum_root = btrfs_csum_root(fs_info,
885 ret = btrfs_del_csums(trans, csum_root,
889 ret = btrfs_csum_file_blocks(trans,
892 list_del(&sums->list);
898 btrfs_release_path(path);
900 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
901 /* inline extents are easy, we just overwrite them */
902 ret = overwrite_item(trans, root, path, eb, slot, key);
907 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start,
913 btrfs_update_inode_bytes(BTRFS_I(inode), nbytes, drop_args.bytes_found);
914 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
920 static int unlink_inode_for_log_replay(struct btrfs_trans_handle *trans,
921 struct btrfs_inode *dir,
922 struct btrfs_inode *inode,
923 const struct fscrypt_str *name)
927 ret = btrfs_unlink_inode(trans, dir, inode, name);
931 * Whenever we need to check if a name exists or not, we check the
932 * fs/subvolume tree. So after an unlink we must run delayed items, so
933 * that future checks for a name during log replay see that the name
934 * does not exists anymore.
936 return btrfs_run_delayed_items(trans);
940 * when cleaning up conflicts between the directory names in the
941 * subvolume, directory names in the log and directory names in the
942 * inode back references, we may have to unlink inodes from directories.
944 * This is a helper function to do the unlink of a specific directory
947 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
948 struct btrfs_path *path,
949 struct btrfs_inode *dir,
950 struct btrfs_dir_item *di)
952 struct btrfs_root *root = dir->root;
954 struct fscrypt_str name;
955 struct extent_buffer *leaf;
956 struct btrfs_key location;
959 leaf = path->nodes[0];
961 btrfs_dir_item_key_to_cpu(leaf, di, &location);
962 ret = read_alloc_one_name(leaf, di + 1, btrfs_dir_name_len(leaf, di), &name);
966 btrfs_release_path(path);
968 inode = read_one_inode(root, location.objectid);
974 ret = link_to_fixup_dir(trans, root, path, location.objectid);
978 ret = unlink_inode_for_log_replay(trans, dir, BTRFS_I(inode), &name);
986 * See if a given name and sequence number found in an inode back reference are
987 * already in a directory and correctly point to this inode.
989 * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
992 static noinline int inode_in_dir(struct btrfs_root *root,
993 struct btrfs_path *path,
994 u64 dirid, u64 objectid, u64 index,
995 struct fscrypt_str *name)
997 struct btrfs_dir_item *di;
998 struct btrfs_key location;
1001 di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
1007 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1008 if (location.objectid != objectid)
1014 btrfs_release_path(path);
1015 di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, 0);
1020 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1021 if (location.objectid == objectid)
1025 btrfs_release_path(path);
1030 * helper function to check a log tree for a named back reference in
1031 * an inode. This is used to decide if a back reference that is
1032 * found in the subvolume conflicts with what we find in the log.
1034 * inode backreferences may have multiple refs in a single item,
1035 * during replay we process one reference at a time, and we don't
1036 * want to delete valid links to a file from the subvolume if that
1037 * link is also in the log.
1039 static noinline int backref_in_log(struct btrfs_root *log,
1040 struct btrfs_key *key,
1042 const struct fscrypt_str *name)
1044 struct btrfs_path *path;
1047 path = btrfs_alloc_path();
1051 ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1054 } else if (ret == 1) {
1059 if (key->type == BTRFS_INODE_EXTREF_KEY)
1060 ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
1062 ref_objectid, name);
1064 ret = !!btrfs_find_name_in_backref(path->nodes[0],
1065 path->slots[0], name);
1067 btrfs_free_path(path);
1071 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
1072 struct btrfs_root *root,
1073 struct btrfs_path *path,
1074 struct btrfs_root *log_root,
1075 struct btrfs_inode *dir,
1076 struct btrfs_inode *inode,
1077 u64 inode_objectid, u64 parent_objectid,
1078 u64 ref_index, struct fscrypt_str *name)
1081 struct extent_buffer *leaf;
1082 struct btrfs_dir_item *di;
1083 struct btrfs_key search_key;
1084 struct btrfs_inode_extref *extref;
1087 /* Search old style refs */
1088 search_key.objectid = inode_objectid;
1089 search_key.type = BTRFS_INODE_REF_KEY;
1090 search_key.offset = parent_objectid;
1091 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1093 struct btrfs_inode_ref *victim_ref;
1095 unsigned long ptr_end;
1097 leaf = path->nodes[0];
1099 /* are we trying to overwrite a back ref for the root directory
1100 * if so, just jump out, we're done
1102 if (search_key.objectid == search_key.offset)
1105 /* check all the names in this back reference to see
1106 * if they are in the log. if so, we allow them to stay
1107 * otherwise they must be unlinked as a conflict
1109 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1110 ptr_end = ptr + btrfs_item_size(leaf, path->slots[0]);
1111 while (ptr < ptr_end) {
1112 struct fscrypt_str victim_name;
1114 victim_ref = (struct btrfs_inode_ref *)ptr;
1115 ret = read_alloc_one_name(leaf, (victim_ref + 1),
1116 btrfs_inode_ref_name_len(leaf, victim_ref),
1121 ret = backref_in_log(log_root, &search_key,
1122 parent_objectid, &victim_name);
1124 kfree(victim_name.name);
1127 inc_nlink(&inode->vfs_inode);
1128 btrfs_release_path(path);
1130 ret = unlink_inode_for_log_replay(trans, dir, inode,
1132 kfree(victim_name.name);
1137 kfree(victim_name.name);
1139 ptr = (unsigned long)(victim_ref + 1) + victim_name.len;
1142 btrfs_release_path(path);
1144 /* Same search but for extended refs */
1145 extref = btrfs_lookup_inode_extref(NULL, root, path, name,
1146 inode_objectid, parent_objectid, 0,
1148 if (IS_ERR(extref)) {
1149 return PTR_ERR(extref);
1150 } else if (extref) {
1154 struct inode *victim_parent;
1156 leaf = path->nodes[0];
1158 item_size = btrfs_item_size(leaf, path->slots[0]);
1159 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1161 while (cur_offset < item_size) {
1162 struct fscrypt_str victim_name;
1164 extref = (struct btrfs_inode_extref *)(base + cur_offset);
1166 if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1169 ret = read_alloc_one_name(leaf, &extref->name,
1170 btrfs_inode_extref_name_len(leaf, extref),
1175 search_key.objectid = inode_objectid;
1176 search_key.type = BTRFS_INODE_EXTREF_KEY;
1177 search_key.offset = btrfs_extref_hash(parent_objectid,
1180 ret = backref_in_log(log_root, &search_key,
1181 parent_objectid, &victim_name);
1183 kfree(victim_name.name);
1187 victim_parent = read_one_inode(root,
1189 if (victim_parent) {
1190 inc_nlink(&inode->vfs_inode);
1191 btrfs_release_path(path);
1193 ret = unlink_inode_for_log_replay(trans,
1194 BTRFS_I(victim_parent),
1195 inode, &victim_name);
1197 iput(victim_parent);
1198 kfree(victim_name.name);
1203 kfree(victim_name.name);
1205 cur_offset += victim_name.len + sizeof(*extref);
1208 btrfs_release_path(path);
1210 /* look for a conflicting sequence number */
1211 di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1212 ref_index, name, 0);
1216 ret = drop_one_dir_item(trans, path, dir, di);
1220 btrfs_release_path(path);
1222 /* look for a conflicting name */
1223 di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir), name, 0);
1227 ret = drop_one_dir_item(trans, path, dir, di);
1231 btrfs_release_path(path);
1236 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1237 struct fscrypt_str *name, u64 *index,
1238 u64 *parent_objectid)
1240 struct btrfs_inode_extref *extref;
1243 extref = (struct btrfs_inode_extref *)ref_ptr;
1245 ret = read_alloc_one_name(eb, &extref->name,
1246 btrfs_inode_extref_name_len(eb, extref), name);
1251 *index = btrfs_inode_extref_index(eb, extref);
1252 if (parent_objectid)
1253 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1258 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1259 struct fscrypt_str *name, u64 *index)
1261 struct btrfs_inode_ref *ref;
1264 ref = (struct btrfs_inode_ref *)ref_ptr;
1266 ret = read_alloc_one_name(eb, ref + 1, btrfs_inode_ref_name_len(eb, ref),
1272 *index = btrfs_inode_ref_index(eb, ref);
1278 * Take an inode reference item from the log tree and iterate all names from the
1279 * inode reference item in the subvolume tree with the same key (if it exists).
1280 * For any name that is not in the inode reference item from the log tree, do a
1281 * proper unlink of that name (that is, remove its entry from the inode
1282 * reference item and both dir index keys).
1284 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1285 struct btrfs_root *root,
1286 struct btrfs_path *path,
1287 struct btrfs_inode *inode,
1288 struct extent_buffer *log_eb,
1290 struct btrfs_key *key)
1293 unsigned long ref_ptr;
1294 unsigned long ref_end;
1295 struct extent_buffer *eb;
1298 btrfs_release_path(path);
1299 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1307 eb = path->nodes[0];
1308 ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1309 ref_end = ref_ptr + btrfs_item_size(eb, path->slots[0]);
1310 while (ref_ptr < ref_end) {
1311 struct fscrypt_str name;
1314 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1315 ret = extref_get_fields(eb, ref_ptr, &name,
1318 parent_id = key->offset;
1319 ret = ref_get_fields(eb, ref_ptr, &name, NULL);
1324 if (key->type == BTRFS_INODE_EXTREF_KEY)
1325 ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
1328 ret = !!btrfs_find_name_in_backref(log_eb, log_slot, &name);
1333 btrfs_release_path(path);
1334 dir = read_one_inode(root, parent_id);
1340 ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir),
1350 ref_ptr += name.len;
1351 if (key->type == BTRFS_INODE_EXTREF_KEY)
1352 ref_ptr += sizeof(struct btrfs_inode_extref);
1354 ref_ptr += sizeof(struct btrfs_inode_ref);
1358 btrfs_release_path(path);
1363 * replay one inode back reference item found in the log tree.
1364 * eb, slot and key refer to the buffer and key found in the log tree.
1365 * root is the destination we are replaying into, and path is for temp
1366 * use by this function. (it should be released on return).
1368 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1369 struct btrfs_root *root,
1370 struct btrfs_root *log,
1371 struct btrfs_path *path,
1372 struct extent_buffer *eb, int slot,
1373 struct btrfs_key *key)
1375 struct inode *dir = NULL;
1376 struct inode *inode = NULL;
1377 unsigned long ref_ptr;
1378 unsigned long ref_end;
1379 struct fscrypt_str name;
1381 int log_ref_ver = 0;
1382 u64 parent_objectid;
1385 int ref_struct_size;
1387 ref_ptr = btrfs_item_ptr_offset(eb, slot);
1388 ref_end = ref_ptr + btrfs_item_size(eb, slot);
1390 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1391 struct btrfs_inode_extref *r;
1393 ref_struct_size = sizeof(struct btrfs_inode_extref);
1395 r = (struct btrfs_inode_extref *)ref_ptr;
1396 parent_objectid = btrfs_inode_extref_parent(eb, r);
1398 ref_struct_size = sizeof(struct btrfs_inode_ref);
1399 parent_objectid = key->offset;
1401 inode_objectid = key->objectid;
1404 * it is possible that we didn't log all the parent directories
1405 * for a given inode. If we don't find the dir, just don't
1406 * copy the back ref in. The link count fixup code will take
1409 dir = read_one_inode(root, parent_objectid);
1415 inode = read_one_inode(root, inode_objectid);
1421 while (ref_ptr < ref_end) {
1423 ret = extref_get_fields(eb, ref_ptr, &name,
1424 &ref_index, &parent_objectid);
1426 * parent object can change from one array
1430 dir = read_one_inode(root, parent_objectid);
1436 ret = ref_get_fields(eb, ref_ptr, &name, &ref_index);
1441 ret = inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1442 btrfs_ino(BTRFS_I(inode)), ref_index, &name);
1445 } else if (ret == 0) {
1447 * look for a conflicting back reference in the
1448 * metadata. if we find one we have to unlink that name
1449 * of the file before we add our new link. Later on, we
1450 * overwrite any existing back reference, and we don't
1451 * want to create dangling pointers in the directory.
1453 ret = __add_inode_ref(trans, root, path, log,
1454 BTRFS_I(dir), BTRFS_I(inode),
1455 inode_objectid, parent_objectid,
1463 /* insert our name */
1464 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
1465 &name, 0, ref_index);
1469 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1473 /* Else, ret == 1, we already have a perfect match, we're done. */
1475 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + name.len;
1485 * Before we overwrite the inode reference item in the subvolume tree
1486 * with the item from the log tree, we must unlink all names from the
1487 * parent directory that are in the subvolume's tree inode reference
1488 * item, otherwise we end up with an inconsistent subvolume tree where
1489 * dir index entries exist for a name but there is no inode reference
1490 * item with the same name.
1492 ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1497 /* finally write the back reference in the inode */
1498 ret = overwrite_item(trans, root, path, eb, slot, key);
1500 btrfs_release_path(path);
1507 static int count_inode_extrefs(struct btrfs_root *root,
1508 struct btrfs_inode *inode, struct btrfs_path *path)
1512 unsigned int nlink = 0;
1515 u64 inode_objectid = btrfs_ino(inode);
1518 struct btrfs_inode_extref *extref;
1519 struct extent_buffer *leaf;
1522 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1527 leaf = path->nodes[0];
1528 item_size = btrfs_item_size(leaf, path->slots[0]);
1529 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1532 while (cur_offset < item_size) {
1533 extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1534 name_len = btrfs_inode_extref_name_len(leaf, extref);
1538 cur_offset += name_len + sizeof(*extref);
1542 btrfs_release_path(path);
1544 btrfs_release_path(path);
1546 if (ret < 0 && ret != -ENOENT)
1551 static int count_inode_refs(struct btrfs_root *root,
1552 struct btrfs_inode *inode, struct btrfs_path *path)
1555 struct btrfs_key key;
1556 unsigned int nlink = 0;
1558 unsigned long ptr_end;
1560 u64 ino = btrfs_ino(inode);
1563 key.type = BTRFS_INODE_REF_KEY;
1564 key.offset = (u64)-1;
1567 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1571 if (path->slots[0] == 0)
1576 btrfs_item_key_to_cpu(path->nodes[0], &key,
1578 if (key.objectid != ino ||
1579 key.type != BTRFS_INODE_REF_KEY)
1581 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1582 ptr_end = ptr + btrfs_item_size(path->nodes[0],
1584 while (ptr < ptr_end) {
1585 struct btrfs_inode_ref *ref;
1587 ref = (struct btrfs_inode_ref *)ptr;
1588 name_len = btrfs_inode_ref_name_len(path->nodes[0],
1590 ptr = (unsigned long)(ref + 1) + name_len;
1594 if (key.offset == 0)
1596 if (path->slots[0] > 0) {
1601 btrfs_release_path(path);
1603 btrfs_release_path(path);
1609 * There are a few corners where the link count of the file can't
1610 * be properly maintained during replay. So, instead of adding
1611 * lots of complexity to the log code, we just scan the backrefs
1612 * for any file that has been through replay.
1614 * The scan will update the link count on the inode to reflect the
1615 * number of back refs found. If it goes down to zero, the iput
1616 * will free the inode.
1618 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1619 struct btrfs_root *root,
1620 struct inode *inode)
1622 struct btrfs_path *path;
1625 u64 ino = btrfs_ino(BTRFS_I(inode));
1627 path = btrfs_alloc_path();
1631 ret = count_inode_refs(root, BTRFS_I(inode), path);
1637 ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1645 if (nlink != inode->i_nlink) {
1646 set_nlink(inode, nlink);
1647 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1651 BTRFS_I(inode)->index_cnt = (u64)-1;
1653 if (inode->i_nlink == 0) {
1654 if (S_ISDIR(inode->i_mode)) {
1655 ret = replay_dir_deletes(trans, root, NULL, path,
1660 ret = btrfs_insert_orphan_item(trans, root, ino);
1666 btrfs_free_path(path);
1670 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1671 struct btrfs_root *root,
1672 struct btrfs_path *path)
1675 struct btrfs_key key;
1676 struct inode *inode;
1678 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1679 key.type = BTRFS_ORPHAN_ITEM_KEY;
1680 key.offset = (u64)-1;
1682 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1688 if (path->slots[0] == 0)
1693 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1694 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1695 key.type != BTRFS_ORPHAN_ITEM_KEY)
1698 ret = btrfs_del_item(trans, root, path);
1702 btrfs_release_path(path);
1703 inode = read_one_inode(root, key.offset);
1709 ret = fixup_inode_link_count(trans, root, inode);
1715 * fixup on a directory may create new entries,
1716 * make sure we always look for the highset possible
1719 key.offset = (u64)-1;
1721 btrfs_release_path(path);
1727 * record a given inode in the fixup dir so we can check its link
1728 * count when replay is done. The link count is incremented here
1729 * so the inode won't go away until we check it
1731 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1732 struct btrfs_root *root,
1733 struct btrfs_path *path,
1736 struct btrfs_key key;
1738 struct inode *inode;
1740 inode = read_one_inode(root, objectid);
1744 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1745 key.type = BTRFS_ORPHAN_ITEM_KEY;
1746 key.offset = objectid;
1748 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1750 btrfs_release_path(path);
1752 if (!inode->i_nlink)
1753 set_nlink(inode, 1);
1756 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1757 } else if (ret == -EEXIST) {
1766 * when replaying the log for a directory, we only insert names
1767 * for inodes that actually exist. This means an fsync on a directory
1768 * does not implicitly fsync all the new files in it
1770 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1771 struct btrfs_root *root,
1772 u64 dirid, u64 index,
1773 const struct fscrypt_str *name,
1774 struct btrfs_key *location)
1776 struct inode *inode;
1780 inode = read_one_inode(root, location->objectid);
1784 dir = read_one_inode(root, dirid);
1790 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1793 /* FIXME, put inode into FIXUP list */
1800 static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
1801 struct btrfs_inode *dir,
1802 struct btrfs_path *path,
1803 struct btrfs_dir_item *dst_di,
1804 const struct btrfs_key *log_key,
1808 struct btrfs_key found_key;
1810 btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1811 /* The existing dentry points to the same inode, don't delete it. */
1812 if (found_key.objectid == log_key->objectid &&
1813 found_key.type == log_key->type &&
1814 found_key.offset == log_key->offset &&
1815 btrfs_dir_flags(path->nodes[0], dst_di) == log_flags)
1819 * Don't drop the conflicting directory entry if the inode for the new
1820 * entry doesn't exist.
1825 return drop_one_dir_item(trans, path, dir, dst_di);
1829 * take a single entry in a log directory item and replay it into
1832 * if a conflicting item exists in the subdirectory already,
1833 * the inode it points to is unlinked and put into the link count
1836 * If a name from the log points to a file or directory that does
1837 * not exist in the FS, it is skipped. fsyncs on directories
1838 * do not force down inodes inside that directory, just changes to the
1839 * names or unlinks in a directory.
1841 * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1842 * non-existing inode) and 1 if the name was replayed.
1844 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1845 struct btrfs_root *root,
1846 struct btrfs_path *path,
1847 struct extent_buffer *eb,
1848 struct btrfs_dir_item *di,
1849 struct btrfs_key *key)
1851 struct fscrypt_str name;
1852 struct btrfs_dir_item *dir_dst_di;
1853 struct btrfs_dir_item *index_dst_di;
1854 bool dir_dst_matches = false;
1855 bool index_dst_matches = false;
1856 struct btrfs_key log_key;
1857 struct btrfs_key search_key;
1862 bool update_size = true;
1863 bool name_added = false;
1865 dir = read_one_inode(root, key->objectid);
1869 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
1873 log_flags = btrfs_dir_flags(eb, di);
1874 btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1875 ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1876 btrfs_release_path(path);
1879 exists = (ret == 0);
1882 dir_dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1884 if (IS_ERR(dir_dst_di)) {
1885 ret = PTR_ERR(dir_dst_di);
1887 } else if (dir_dst_di) {
1888 ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1889 dir_dst_di, &log_key,
1893 dir_dst_matches = (ret == 1);
1896 btrfs_release_path(path);
1898 index_dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1899 key->objectid, key->offset,
1901 if (IS_ERR(index_dst_di)) {
1902 ret = PTR_ERR(index_dst_di);
1904 } else if (index_dst_di) {
1905 ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1906 index_dst_di, &log_key,
1910 index_dst_matches = (ret == 1);
1913 btrfs_release_path(path);
1915 if (dir_dst_matches && index_dst_matches) {
1917 update_size = false;
1922 * Check if the inode reference exists in the log for the given name,
1923 * inode and parent inode
1925 search_key.objectid = log_key.objectid;
1926 search_key.type = BTRFS_INODE_REF_KEY;
1927 search_key.offset = key->objectid;
1928 ret = backref_in_log(root->log_root, &search_key, 0, &name);
1932 /* The dentry will be added later. */
1934 update_size = false;
1938 search_key.objectid = log_key.objectid;
1939 search_key.type = BTRFS_INODE_EXTREF_KEY;
1940 search_key.offset = key->objectid;
1941 ret = backref_in_log(root->log_root, &search_key, key->objectid, &name);
1945 /* The dentry will be added later. */
1947 update_size = false;
1950 btrfs_release_path(path);
1951 ret = insert_one_name(trans, root, key->objectid, key->offset,
1953 if (ret && ret != -ENOENT && ret != -EEXIST)
1957 update_size = false;
1961 if (!ret && update_size) {
1962 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name.len * 2);
1963 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
1967 if (!ret && name_added)
1972 /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
1973 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1974 struct btrfs_root *root,
1975 struct btrfs_path *path,
1976 struct extent_buffer *eb, int slot,
1977 struct btrfs_key *key)
1980 struct btrfs_dir_item *di;
1982 /* We only log dir index keys, which only contain a single dir item. */
1983 ASSERT(key->type == BTRFS_DIR_INDEX_KEY);
1985 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1986 ret = replay_one_name(trans, root, path, eb, di, key);
1991 * If this entry refers to a non-directory (directories can not have a
1992 * link count > 1) and it was added in the transaction that was not
1993 * committed, make sure we fixup the link count of the inode the entry
1994 * points to. Otherwise something like the following would result in a
1995 * directory pointing to an inode with a wrong link that does not account
1996 * for this dir entry:
2003 * ln testdir/bar testdir/bar_link
2004 * ln testdir/foo testdir/foo_link
2005 * xfs_io -c "fsync" testdir/bar
2009 * mount fs, log replay happens
2011 * File foo would remain with a link count of 1 when it has two entries
2012 * pointing to it in the directory testdir. This would make it impossible
2013 * to ever delete the parent directory has it would result in stale
2014 * dentries that can never be deleted.
2016 if (ret == 1 && btrfs_dir_ftype(eb, di) != BTRFS_FT_DIR) {
2017 struct btrfs_path *fixup_path;
2018 struct btrfs_key di_key;
2020 fixup_path = btrfs_alloc_path();
2024 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2025 ret = link_to_fixup_dir(trans, root, fixup_path, di_key.objectid);
2026 btrfs_free_path(fixup_path);
2033 * directory replay has two parts. There are the standard directory
2034 * items in the log copied from the subvolume, and range items
2035 * created in the log while the subvolume was logged.
2037 * The range items tell us which parts of the key space the log
2038 * is authoritative for. During replay, if a key in the subvolume
2039 * directory is in a logged range item, but not actually in the log
2040 * that means it was deleted from the directory before the fsync
2041 * and should be removed.
2043 static noinline int find_dir_range(struct btrfs_root *root,
2044 struct btrfs_path *path,
2046 u64 *start_ret, u64 *end_ret)
2048 struct btrfs_key key;
2050 struct btrfs_dir_log_item *item;
2054 if (*start_ret == (u64)-1)
2057 key.objectid = dirid;
2058 key.type = BTRFS_DIR_LOG_INDEX_KEY;
2059 key.offset = *start_ret;
2061 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2065 if (path->slots[0] == 0)
2070 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2072 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2076 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2077 struct btrfs_dir_log_item);
2078 found_end = btrfs_dir_log_end(path->nodes[0], item);
2080 if (*start_ret >= key.offset && *start_ret <= found_end) {
2082 *start_ret = key.offset;
2083 *end_ret = found_end;
2088 /* check the next slot in the tree to see if it is a valid item */
2089 nritems = btrfs_header_nritems(path->nodes[0]);
2091 if (path->slots[0] >= nritems) {
2092 ret = btrfs_next_leaf(root, path);
2097 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2099 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2103 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2104 struct btrfs_dir_log_item);
2105 found_end = btrfs_dir_log_end(path->nodes[0], item);
2106 *start_ret = key.offset;
2107 *end_ret = found_end;
2110 btrfs_release_path(path);
2115 * this looks for a given directory item in the log. If the directory
2116 * item is not in the log, the item is removed and the inode it points
2119 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2120 struct btrfs_root *log,
2121 struct btrfs_path *path,
2122 struct btrfs_path *log_path,
2124 struct btrfs_key *dir_key)
2126 struct btrfs_root *root = BTRFS_I(dir)->root;
2128 struct extent_buffer *eb;
2130 struct btrfs_dir_item *di;
2131 struct fscrypt_str name;
2132 struct inode *inode = NULL;
2133 struct btrfs_key location;
2136 * Currently we only log dir index keys. Even if we replay a log created
2137 * by an older kernel that logged both dir index and dir item keys, all
2138 * we need to do is process the dir index keys, we (and our caller) can
2139 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2141 ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY);
2143 eb = path->nodes[0];
2144 slot = path->slots[0];
2145 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2146 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
2151 struct btrfs_dir_item *log_di;
2153 log_di = btrfs_lookup_dir_index_item(trans, log, log_path,
2155 dir_key->offset, &name, 0);
2156 if (IS_ERR(log_di)) {
2157 ret = PTR_ERR(log_di);
2159 } else if (log_di) {
2160 /* The dentry exists in the log, we have nothing to do. */
2166 btrfs_dir_item_key_to_cpu(eb, di, &location);
2167 btrfs_release_path(path);
2168 btrfs_release_path(log_path);
2169 inode = read_one_inode(root, location.objectid);
2175 ret = link_to_fixup_dir(trans, root, path, location.objectid);
2180 ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir), BTRFS_I(inode),
2183 * Unlike dir item keys, dir index keys can only have one name (entry) in
2184 * them, as there are no key collisions since each key has a unique offset
2185 * (an index number), so we're done.
2188 btrfs_release_path(path);
2189 btrfs_release_path(log_path);
2195 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2196 struct btrfs_root *root,
2197 struct btrfs_root *log,
2198 struct btrfs_path *path,
2201 struct btrfs_key search_key;
2202 struct btrfs_path *log_path;
2207 log_path = btrfs_alloc_path();
2211 search_key.objectid = ino;
2212 search_key.type = BTRFS_XATTR_ITEM_KEY;
2213 search_key.offset = 0;
2215 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2219 nritems = btrfs_header_nritems(path->nodes[0]);
2220 for (i = path->slots[0]; i < nritems; i++) {
2221 struct btrfs_key key;
2222 struct btrfs_dir_item *di;
2223 struct btrfs_dir_item *log_di;
2227 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2228 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2233 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2234 total_size = btrfs_item_size(path->nodes[0], i);
2236 while (cur < total_size) {
2237 u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2238 u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2239 u32 this_len = sizeof(*di) + name_len + data_len;
2242 name = kmalloc(name_len, GFP_NOFS);
2247 read_extent_buffer(path->nodes[0], name,
2248 (unsigned long)(di + 1), name_len);
2250 log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2252 btrfs_release_path(log_path);
2254 /* Doesn't exist in log tree, so delete it. */
2255 btrfs_release_path(path);
2256 di = btrfs_lookup_xattr(trans, root, path, ino,
2257 name, name_len, -1);
2264 ret = btrfs_delete_one_dir_name(trans, root,
2268 btrfs_release_path(path);
2273 if (IS_ERR(log_di)) {
2274 ret = PTR_ERR(log_di);
2278 di = (struct btrfs_dir_item *)((char *)di + this_len);
2281 ret = btrfs_next_leaf(root, path);
2287 btrfs_free_path(log_path);
2288 btrfs_release_path(path);
2294 * deletion replay happens before we copy any new directory items
2295 * out of the log or out of backreferences from inodes. It
2296 * scans the log to find ranges of keys that log is authoritative for,
2297 * and then scans the directory to find items in those ranges that are
2298 * not present in the log.
2300 * Anything we don't find in the log is unlinked and removed from the
2303 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2304 struct btrfs_root *root,
2305 struct btrfs_root *log,
2306 struct btrfs_path *path,
2307 u64 dirid, int del_all)
2312 struct btrfs_key dir_key;
2313 struct btrfs_key found_key;
2314 struct btrfs_path *log_path;
2317 dir_key.objectid = dirid;
2318 dir_key.type = BTRFS_DIR_INDEX_KEY;
2319 log_path = btrfs_alloc_path();
2323 dir = read_one_inode(root, dirid);
2324 /* it isn't an error if the inode isn't there, that can happen
2325 * because we replay the deletes before we copy in the inode item
2329 btrfs_free_path(log_path);
2337 range_end = (u64)-1;
2339 ret = find_dir_range(log, path, dirid,
2340 &range_start, &range_end);
2347 dir_key.offset = range_start;
2350 ret = btrfs_search_slot(NULL, root, &dir_key, path,
2355 nritems = btrfs_header_nritems(path->nodes[0]);
2356 if (path->slots[0] >= nritems) {
2357 ret = btrfs_next_leaf(root, path);
2363 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2365 if (found_key.objectid != dirid ||
2366 found_key.type != dir_key.type) {
2371 if (found_key.offset > range_end)
2374 ret = check_item_in_log(trans, log, path,
2379 if (found_key.offset == (u64)-1)
2381 dir_key.offset = found_key.offset + 1;
2383 btrfs_release_path(path);
2384 if (range_end == (u64)-1)
2386 range_start = range_end + 1;
2390 btrfs_release_path(path);
2391 btrfs_free_path(log_path);
2397 * the process_func used to replay items from the log tree. This
2398 * gets called in two different stages. The first stage just looks
2399 * for inodes and makes sure they are all copied into the subvolume.
2401 * The second stage copies all the other item types from the log into
2402 * the subvolume. The two stage approach is slower, but gets rid of
2403 * lots of complexity around inodes referencing other inodes that exist
2404 * only in the log (references come from either directory items or inode
2407 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2408 struct walk_control *wc, u64 gen, int level)
2411 struct btrfs_path *path;
2412 struct btrfs_root *root = wc->replay_dest;
2413 struct btrfs_key key;
2417 ret = btrfs_read_extent_buffer(eb, gen, level, NULL);
2421 level = btrfs_header_level(eb);
2426 path = btrfs_alloc_path();
2430 nritems = btrfs_header_nritems(eb);
2431 for (i = 0; i < nritems; i++) {
2432 btrfs_item_key_to_cpu(eb, &key, i);
2434 /* inode keys are done during the first stage */
2435 if (key.type == BTRFS_INODE_ITEM_KEY &&
2436 wc->stage == LOG_WALK_REPLAY_INODES) {
2437 struct btrfs_inode_item *inode_item;
2440 inode_item = btrfs_item_ptr(eb, i,
2441 struct btrfs_inode_item);
2443 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2444 * and never got linked before the fsync, skip it, as
2445 * replaying it is pointless since it would be deleted
2446 * later. We skip logging tmpfiles, but it's always
2447 * possible we are replaying a log created with a kernel
2448 * that used to log tmpfiles.
2450 if (btrfs_inode_nlink(eb, inode_item) == 0) {
2451 wc->ignore_cur_inode = true;
2454 wc->ignore_cur_inode = false;
2456 ret = replay_xattr_deletes(wc->trans, root, log,
2457 path, key.objectid);
2460 mode = btrfs_inode_mode(eb, inode_item);
2461 if (S_ISDIR(mode)) {
2462 ret = replay_dir_deletes(wc->trans,
2463 root, log, path, key.objectid, 0);
2467 ret = overwrite_item(wc->trans, root, path,
2473 * Before replaying extents, truncate the inode to its
2474 * size. We need to do it now and not after log replay
2475 * because before an fsync we can have prealloc extents
2476 * added beyond the inode's i_size. If we did it after,
2477 * through orphan cleanup for example, we would drop
2478 * those prealloc extents just after replaying them.
2480 if (S_ISREG(mode)) {
2481 struct btrfs_drop_extents_args drop_args = { 0 };
2482 struct inode *inode;
2485 inode = read_one_inode(root, key.objectid);
2490 from = ALIGN(i_size_read(inode),
2491 root->fs_info->sectorsize);
2492 drop_args.start = from;
2493 drop_args.end = (u64)-1;
2494 drop_args.drop_cache = true;
2495 ret = btrfs_drop_extents(wc->trans, root,
2499 inode_sub_bytes(inode,
2500 drop_args.bytes_found);
2501 /* Update the inode's nbytes. */
2502 ret = btrfs_update_inode(wc->trans,
2503 root, BTRFS_I(inode));
2510 ret = link_to_fixup_dir(wc->trans, root,
2511 path, key.objectid);
2516 if (wc->ignore_cur_inode)
2519 if (key.type == BTRFS_DIR_INDEX_KEY &&
2520 wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2521 ret = replay_one_dir_item(wc->trans, root, path,
2527 if (wc->stage < LOG_WALK_REPLAY_ALL)
2530 /* these keys are simply copied */
2531 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2532 ret = overwrite_item(wc->trans, root, path,
2536 } else if (key.type == BTRFS_INODE_REF_KEY ||
2537 key.type == BTRFS_INODE_EXTREF_KEY) {
2538 ret = add_inode_ref(wc->trans, root, log, path,
2540 if (ret && ret != -ENOENT)
2543 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2544 ret = replay_one_extent(wc->trans, root, path,
2550 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2551 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2552 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2553 * older kernel with such keys, ignore them.
2556 btrfs_free_path(path);
2561 * Correctly adjust the reserved bytes occupied by a log tree extent buffer
2563 static void unaccount_log_buffer(struct btrfs_fs_info *fs_info, u64 start)
2565 struct btrfs_block_group *cache;
2567 cache = btrfs_lookup_block_group(fs_info, start);
2569 btrfs_err(fs_info, "unable to find block group for %llu", start);
2573 spin_lock(&cache->space_info->lock);
2574 spin_lock(&cache->lock);
2575 cache->reserved -= fs_info->nodesize;
2576 cache->space_info->bytes_reserved -= fs_info->nodesize;
2577 spin_unlock(&cache->lock);
2578 spin_unlock(&cache->space_info->lock);
2580 btrfs_put_block_group(cache);
2583 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2584 struct btrfs_root *root,
2585 struct btrfs_path *path, int *level,
2586 struct walk_control *wc)
2588 struct btrfs_fs_info *fs_info = root->fs_info;
2591 struct extent_buffer *next;
2592 struct extent_buffer *cur;
2596 while (*level > 0) {
2597 struct btrfs_key first_key;
2599 cur = path->nodes[*level];
2601 WARN_ON(btrfs_header_level(cur) != *level);
2603 if (path->slots[*level] >=
2604 btrfs_header_nritems(cur))
2607 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2608 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2609 btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2610 blocksize = fs_info->nodesize;
2612 next = btrfs_find_create_tree_block(fs_info, bytenr,
2613 btrfs_header_owner(cur),
2616 return PTR_ERR(next);
2619 ret = wc->process_func(root, next, wc, ptr_gen,
2622 free_extent_buffer(next);
2626 path->slots[*level]++;
2628 ret = btrfs_read_extent_buffer(next, ptr_gen,
2629 *level - 1, &first_key);
2631 free_extent_buffer(next);
2636 btrfs_tree_lock(next);
2637 btrfs_clean_tree_block(next);
2638 btrfs_wait_tree_block_writeback(next);
2639 btrfs_tree_unlock(next);
2640 ret = btrfs_pin_reserved_extent(trans,
2643 free_extent_buffer(next);
2646 btrfs_redirty_list_add(
2647 trans->transaction, next);
2649 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2650 clear_extent_buffer_dirty(next);
2651 unaccount_log_buffer(fs_info, bytenr);
2654 free_extent_buffer(next);
2657 ret = btrfs_read_extent_buffer(next, ptr_gen, *level - 1, &first_key);
2659 free_extent_buffer(next);
2663 if (path->nodes[*level-1])
2664 free_extent_buffer(path->nodes[*level-1]);
2665 path->nodes[*level-1] = next;
2666 *level = btrfs_header_level(next);
2667 path->slots[*level] = 0;
2670 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2676 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2677 struct btrfs_root *root,
2678 struct btrfs_path *path, int *level,
2679 struct walk_control *wc)
2681 struct btrfs_fs_info *fs_info = root->fs_info;
2686 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2687 slot = path->slots[i];
2688 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2691 WARN_ON(*level == 0);
2694 ret = wc->process_func(root, path->nodes[*level], wc,
2695 btrfs_header_generation(path->nodes[*level]),
2701 struct extent_buffer *next;
2703 next = path->nodes[*level];
2706 btrfs_tree_lock(next);
2707 btrfs_clean_tree_block(next);
2708 btrfs_wait_tree_block_writeback(next);
2709 btrfs_tree_unlock(next);
2710 ret = btrfs_pin_reserved_extent(trans,
2711 path->nodes[*level]->start,
2712 path->nodes[*level]->len);
2715 btrfs_redirty_list_add(trans->transaction,
2718 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2719 clear_extent_buffer_dirty(next);
2721 unaccount_log_buffer(fs_info,
2722 path->nodes[*level]->start);
2725 free_extent_buffer(path->nodes[*level]);
2726 path->nodes[*level] = NULL;
2734 * drop the reference count on the tree rooted at 'snap'. This traverses
2735 * the tree freeing any blocks that have a ref count of zero after being
2738 static int walk_log_tree(struct btrfs_trans_handle *trans,
2739 struct btrfs_root *log, struct walk_control *wc)
2741 struct btrfs_fs_info *fs_info = log->fs_info;
2745 struct btrfs_path *path;
2748 path = btrfs_alloc_path();
2752 level = btrfs_header_level(log->node);
2754 path->nodes[level] = log->node;
2755 atomic_inc(&log->node->refs);
2756 path->slots[level] = 0;
2759 wret = walk_down_log_tree(trans, log, path, &level, wc);
2767 wret = walk_up_log_tree(trans, log, path, &level, wc);
2776 /* was the root node processed? if not, catch it here */
2777 if (path->nodes[orig_level]) {
2778 ret = wc->process_func(log, path->nodes[orig_level], wc,
2779 btrfs_header_generation(path->nodes[orig_level]),
2784 struct extent_buffer *next;
2786 next = path->nodes[orig_level];
2789 btrfs_tree_lock(next);
2790 btrfs_clean_tree_block(next);
2791 btrfs_wait_tree_block_writeback(next);
2792 btrfs_tree_unlock(next);
2793 ret = btrfs_pin_reserved_extent(trans,
2794 next->start, next->len);
2797 btrfs_redirty_list_add(trans->transaction, next);
2799 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2800 clear_extent_buffer_dirty(next);
2801 unaccount_log_buffer(fs_info, next->start);
2807 btrfs_free_path(path);
2812 * helper function to update the item for a given subvolumes log root
2813 * in the tree of log roots
2815 static int update_log_root(struct btrfs_trans_handle *trans,
2816 struct btrfs_root *log,
2817 struct btrfs_root_item *root_item)
2819 struct btrfs_fs_info *fs_info = log->fs_info;
2822 if (log->log_transid == 1) {
2823 /* insert root item on the first sync */
2824 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2825 &log->root_key, root_item);
2827 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2828 &log->root_key, root_item);
2833 static void wait_log_commit(struct btrfs_root *root, int transid)
2836 int index = transid % 2;
2839 * we only allow two pending log transactions at a time,
2840 * so we know that if ours is more than 2 older than the
2841 * current transaction, we're done
2844 prepare_to_wait(&root->log_commit_wait[index],
2845 &wait, TASK_UNINTERRUPTIBLE);
2847 if (!(root->log_transid_committed < transid &&
2848 atomic_read(&root->log_commit[index])))
2851 mutex_unlock(&root->log_mutex);
2853 mutex_lock(&root->log_mutex);
2855 finish_wait(&root->log_commit_wait[index], &wait);
2858 static void wait_for_writer(struct btrfs_root *root)
2863 prepare_to_wait(&root->log_writer_wait, &wait,
2864 TASK_UNINTERRUPTIBLE);
2865 if (!atomic_read(&root->log_writers))
2868 mutex_unlock(&root->log_mutex);
2870 mutex_lock(&root->log_mutex);
2872 finish_wait(&root->log_writer_wait, &wait);
2875 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2876 struct btrfs_log_ctx *ctx)
2878 mutex_lock(&root->log_mutex);
2879 list_del_init(&ctx->list);
2880 mutex_unlock(&root->log_mutex);
2884 * Invoked in log mutex context, or be sure there is no other task which
2885 * can access the list.
2887 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2888 int index, int error)
2890 struct btrfs_log_ctx *ctx;
2891 struct btrfs_log_ctx *safe;
2893 list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2894 list_del_init(&ctx->list);
2895 ctx->log_ret = error;
2900 * btrfs_sync_log does sends a given tree log down to the disk and
2901 * updates the super blocks to record it. When this call is done,
2902 * you know that any inodes previously logged are safely on disk only
2905 * Any other return value means you need to call btrfs_commit_transaction.
2906 * Some of the edge cases for fsyncing directories that have had unlinks
2907 * or renames done in the past mean that sometimes the only safe
2908 * fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
2909 * that has happened.
2911 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2912 struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2918 struct btrfs_fs_info *fs_info = root->fs_info;
2919 struct btrfs_root *log = root->log_root;
2920 struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2921 struct btrfs_root_item new_root_item;
2922 int log_transid = 0;
2923 struct btrfs_log_ctx root_log_ctx;
2924 struct blk_plug plug;
2928 mutex_lock(&root->log_mutex);
2929 log_transid = ctx->log_transid;
2930 if (root->log_transid_committed >= log_transid) {
2931 mutex_unlock(&root->log_mutex);
2932 return ctx->log_ret;
2935 index1 = log_transid % 2;
2936 if (atomic_read(&root->log_commit[index1])) {
2937 wait_log_commit(root, log_transid);
2938 mutex_unlock(&root->log_mutex);
2939 return ctx->log_ret;
2941 ASSERT(log_transid == root->log_transid);
2942 atomic_set(&root->log_commit[index1], 1);
2944 /* wait for previous tree log sync to complete */
2945 if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2946 wait_log_commit(root, log_transid - 1);
2949 int batch = atomic_read(&root->log_batch);
2950 /* when we're on an ssd, just kick the log commit out */
2951 if (!btrfs_test_opt(fs_info, SSD) &&
2952 test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
2953 mutex_unlock(&root->log_mutex);
2954 schedule_timeout_uninterruptible(1);
2955 mutex_lock(&root->log_mutex);
2957 wait_for_writer(root);
2958 if (batch == atomic_read(&root->log_batch))
2962 /* bail out if we need to do a full commit */
2963 if (btrfs_need_log_full_commit(trans)) {
2964 ret = BTRFS_LOG_FORCE_COMMIT;
2965 mutex_unlock(&root->log_mutex);
2969 if (log_transid % 2 == 0)
2970 mark = EXTENT_DIRTY;
2974 /* we start IO on all the marked extents here, but we don't actually
2975 * wait for them until later.
2977 blk_start_plug(&plug);
2978 ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2980 * -EAGAIN happens when someone, e.g., a concurrent transaction
2981 * commit, writes a dirty extent in this tree-log commit. This
2982 * concurrent write will create a hole writing out the extents,
2983 * and we cannot proceed on a zoned filesystem, requiring
2984 * sequential writing. While we can bail out to a full commit
2985 * here, but we can continue hoping the concurrent writing fills
2988 if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
2991 blk_finish_plug(&plug);
2992 btrfs_abort_transaction(trans, ret);
2993 btrfs_set_log_full_commit(trans);
2994 mutex_unlock(&root->log_mutex);
2999 * We _must_ update under the root->log_mutex in order to make sure we
3000 * have a consistent view of the log root we are trying to commit at
3003 * We _must_ copy this into a local copy, because we are not holding the
3004 * log_root_tree->log_mutex yet. This is important because when we
3005 * commit the log_root_tree we must have a consistent view of the
3006 * log_root_tree when we update the super block to point at the
3007 * log_root_tree bytenr. If we update the log_root_tree here we'll race
3008 * with the commit and possibly point at the new block which we may not
3011 btrfs_set_root_node(&log->root_item, log->node);
3012 memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3014 root->log_transid++;
3015 log->log_transid = root->log_transid;
3016 root->log_start_pid = 0;
3018 * IO has been started, blocks of the log tree have WRITTEN flag set
3019 * in their headers. new modifications of the log will be written to
3020 * new positions. so it's safe to allow log writers to go in.
3022 mutex_unlock(&root->log_mutex);
3024 if (btrfs_is_zoned(fs_info)) {
3025 mutex_lock(&fs_info->tree_root->log_mutex);
3026 if (!log_root_tree->node) {
3027 ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
3029 mutex_unlock(&fs_info->tree_root->log_mutex);
3030 blk_finish_plug(&plug);
3034 mutex_unlock(&fs_info->tree_root->log_mutex);
3037 btrfs_init_log_ctx(&root_log_ctx, NULL);
3039 mutex_lock(&log_root_tree->log_mutex);
3041 index2 = log_root_tree->log_transid % 2;
3042 list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3043 root_log_ctx.log_transid = log_root_tree->log_transid;
3046 * Now we are safe to update the log_root_tree because we're under the
3047 * log_mutex, and we're a current writer so we're holding the commit
3048 * open until we drop the log_mutex.
3050 ret = update_log_root(trans, log, &new_root_item);
3052 if (!list_empty(&root_log_ctx.list))
3053 list_del_init(&root_log_ctx.list);
3055 blk_finish_plug(&plug);
3056 btrfs_set_log_full_commit(trans);
3058 if (ret != -ENOSPC) {
3059 btrfs_abort_transaction(trans, ret);
3060 mutex_unlock(&log_root_tree->log_mutex);
3063 btrfs_wait_tree_log_extents(log, mark);
3064 mutex_unlock(&log_root_tree->log_mutex);
3065 ret = BTRFS_LOG_FORCE_COMMIT;
3069 if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3070 blk_finish_plug(&plug);
3071 list_del_init(&root_log_ctx.list);
3072 mutex_unlock(&log_root_tree->log_mutex);
3073 ret = root_log_ctx.log_ret;
3077 index2 = root_log_ctx.log_transid % 2;
3078 if (atomic_read(&log_root_tree->log_commit[index2])) {
3079 blk_finish_plug(&plug);
3080 ret = btrfs_wait_tree_log_extents(log, mark);
3081 wait_log_commit(log_root_tree,
3082 root_log_ctx.log_transid);
3083 mutex_unlock(&log_root_tree->log_mutex);
3085 ret = root_log_ctx.log_ret;
3088 ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
3089 atomic_set(&log_root_tree->log_commit[index2], 1);
3091 if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3092 wait_log_commit(log_root_tree,
3093 root_log_ctx.log_transid - 1);
3097 * now that we've moved on to the tree of log tree roots,
3098 * check the full commit flag again
3100 if (btrfs_need_log_full_commit(trans)) {
3101 blk_finish_plug(&plug);
3102 btrfs_wait_tree_log_extents(log, mark);
3103 mutex_unlock(&log_root_tree->log_mutex);
3104 ret = BTRFS_LOG_FORCE_COMMIT;
3105 goto out_wake_log_root;
3108 ret = btrfs_write_marked_extents(fs_info,
3109 &log_root_tree->dirty_log_pages,
3110 EXTENT_DIRTY | EXTENT_NEW);
3111 blk_finish_plug(&plug);
3113 * As described above, -EAGAIN indicates a hole in the extents. We
3114 * cannot wait for these write outs since the waiting cause a
3115 * deadlock. Bail out to the full commit instead.
3117 if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3118 btrfs_set_log_full_commit(trans);
3119 btrfs_wait_tree_log_extents(log, mark);
3120 mutex_unlock(&log_root_tree->log_mutex);
3121 goto out_wake_log_root;
3123 btrfs_set_log_full_commit(trans);
3124 btrfs_abort_transaction(trans, ret);
3125 mutex_unlock(&log_root_tree->log_mutex);
3126 goto out_wake_log_root;
3128 ret = btrfs_wait_tree_log_extents(log, mark);
3130 ret = btrfs_wait_tree_log_extents(log_root_tree,
3131 EXTENT_NEW | EXTENT_DIRTY);
3133 btrfs_set_log_full_commit(trans);
3134 mutex_unlock(&log_root_tree->log_mutex);
3135 goto out_wake_log_root;
3138 log_root_start = log_root_tree->node->start;
3139 log_root_level = btrfs_header_level(log_root_tree->node);
3140 log_root_tree->log_transid++;
3141 mutex_unlock(&log_root_tree->log_mutex);
3144 * Here we are guaranteed that nobody is going to write the superblock
3145 * for the current transaction before us and that neither we do write
3146 * our superblock before the previous transaction finishes its commit
3147 * and writes its superblock, because:
3149 * 1) We are holding a handle on the current transaction, so no body
3150 * can commit it until we release the handle;
3152 * 2) Before writing our superblock we acquire the tree_log_mutex, so
3153 * if the previous transaction is still committing, and hasn't yet
3154 * written its superblock, we wait for it to do it, because a
3155 * transaction commit acquires the tree_log_mutex when the commit
3156 * begins and releases it only after writing its superblock.
3158 mutex_lock(&fs_info->tree_log_mutex);
3161 * The previous transaction writeout phase could have failed, and thus
3162 * marked the fs in an error state. We must not commit here, as we
3163 * could have updated our generation in the super_for_commit and
3164 * writing the super here would result in transid mismatches. If there
3165 * is an error here just bail.
3167 if (BTRFS_FS_ERROR(fs_info)) {
3169 btrfs_set_log_full_commit(trans);
3170 btrfs_abort_transaction(trans, ret);
3171 mutex_unlock(&fs_info->tree_log_mutex);
3172 goto out_wake_log_root;
3175 btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
3176 btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3177 ret = write_all_supers(fs_info, 1);
3178 mutex_unlock(&fs_info->tree_log_mutex);
3180 btrfs_set_log_full_commit(trans);
3181 btrfs_abort_transaction(trans, ret);
3182 goto out_wake_log_root;
3186 * We know there can only be one task here, since we have not yet set
3187 * root->log_commit[index1] to 0 and any task attempting to sync the
3188 * log must wait for the previous log transaction to commit if it's
3189 * still in progress or wait for the current log transaction commit if
3190 * someone else already started it. We use <= and not < because the
3191 * first log transaction has an ID of 0.
3193 ASSERT(root->last_log_commit <= log_transid);
3194 root->last_log_commit = log_transid;
3197 mutex_lock(&log_root_tree->log_mutex);
3198 btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3200 log_root_tree->log_transid_committed++;
3201 atomic_set(&log_root_tree->log_commit[index2], 0);
3202 mutex_unlock(&log_root_tree->log_mutex);
3205 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3206 * all the updates above are seen by the woken threads. It might not be
3207 * necessary, but proving that seems to be hard.
3209 cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3211 mutex_lock(&root->log_mutex);
3212 btrfs_remove_all_log_ctxs(root, index1, ret);
3213 root->log_transid_committed++;
3214 atomic_set(&root->log_commit[index1], 0);
3215 mutex_unlock(&root->log_mutex);
3218 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3219 * all the updates above are seen by the woken threads. It might not be
3220 * necessary, but proving that seems to be hard.
3222 cond_wake_up(&root->log_commit_wait[index1]);
3226 static void free_log_tree(struct btrfs_trans_handle *trans,
3227 struct btrfs_root *log)
3230 struct walk_control wc = {
3232 .process_func = process_one_buffer
3236 ret = walk_log_tree(trans, log, &wc);
3239 * We weren't able to traverse the entire log tree, the
3240 * typical scenario is getting an -EIO when reading an
3241 * extent buffer of the tree, due to a previous writeback
3244 set_bit(BTRFS_FS_STATE_LOG_CLEANUP_ERROR,
3245 &log->fs_info->fs_state);
3248 * Some extent buffers of the log tree may still be dirty
3249 * and not yet written back to storage, because we may
3250 * have updates to a log tree without syncing a log tree,
3251 * such as during rename and link operations. So flush
3252 * them out and wait for their writeback to complete, so
3253 * that we properly cleanup their state and pages.
3255 btrfs_write_marked_extents(log->fs_info,
3256 &log->dirty_log_pages,
3257 EXTENT_DIRTY | EXTENT_NEW);
3258 btrfs_wait_tree_log_extents(log,
3259 EXTENT_DIRTY | EXTENT_NEW);
3262 btrfs_abort_transaction(trans, ret);
3264 btrfs_handle_fs_error(log->fs_info, ret, NULL);
3268 clear_extent_bits(&log->dirty_log_pages, 0, (u64)-1,
3269 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3270 extent_io_tree_release(&log->log_csum_range);
3272 btrfs_put_root(log);
3276 * free all the extents used by the tree log. This should be called
3277 * at commit time of the full transaction
3279 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3281 if (root->log_root) {
3282 free_log_tree(trans, root->log_root);
3283 root->log_root = NULL;
3284 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
3289 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3290 struct btrfs_fs_info *fs_info)
3292 if (fs_info->log_root_tree) {
3293 free_log_tree(trans, fs_info->log_root_tree);
3294 fs_info->log_root_tree = NULL;
3295 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
3301 * Check if an inode was logged in the current transaction. This correctly deals
3302 * with the case where the inode was logged but has a logged_trans of 0, which
3303 * happens if the inode is evicted and loaded again, as logged_trans is an in
3304 * memory only field (not persisted).
3306 * Returns 1 if the inode was logged before in the transaction, 0 if it was not,
3309 static int inode_logged(struct btrfs_trans_handle *trans,
3310 struct btrfs_inode *inode,
3311 struct btrfs_path *path_in)
3313 struct btrfs_path *path = path_in;
3314 struct btrfs_key key;
3317 if (inode->logged_trans == trans->transid)
3321 * If logged_trans is not 0, then we know the inode logged was not logged
3322 * in this transaction, so we can return false right away.
3324 if (inode->logged_trans > 0)
3328 * If no log tree was created for this root in this transaction, then
3329 * the inode can not have been logged in this transaction. In that case
3330 * set logged_trans to anything greater than 0 and less than the current
3331 * transaction's ID, to avoid the search below in a future call in case
3332 * a log tree gets created after this.
3334 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state)) {
3335 inode->logged_trans = trans->transid - 1;
3340 * We have a log tree and the inode's logged_trans is 0. We can't tell
3341 * for sure if the inode was logged before in this transaction by looking
3342 * only at logged_trans. We could be pessimistic and assume it was, but
3343 * that can lead to unnecessarily logging an inode during rename and link
3344 * operations, and then further updating the log in followup rename and
3345 * link operations, specially if it's a directory, which adds latency
3346 * visible to applications doing a series of rename or link operations.
3348 * A logged_trans of 0 here can mean several things:
3350 * 1) The inode was never logged since the filesystem was mounted, and may
3351 * or may have not been evicted and loaded again;
3353 * 2) The inode was logged in a previous transaction, then evicted and
3354 * then loaded again;
3356 * 3) The inode was logged in the current transaction, then evicted and
3357 * then loaded again.
3359 * For cases 1) and 2) we don't want to return true, but we need to detect
3360 * case 3) and return true. So we do a search in the log root for the inode
3363 key.objectid = btrfs_ino(inode);
3364 key.type = BTRFS_INODE_ITEM_KEY;
3368 path = btrfs_alloc_path();
3373 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3376 btrfs_release_path(path);
3378 btrfs_free_path(path);
3381 * Logging an inode always results in logging its inode item. So if we
3382 * did not find the item we know the inode was not logged for sure.
3386 } else if (ret > 0) {
3388 * Set logged_trans to a value greater than 0 and less then the
3389 * current transaction to avoid doing the search in future calls.
3391 inode->logged_trans = trans->transid - 1;
3396 * The inode was previously logged and then evicted, set logged_trans to
3397 * the current transacion's ID, to avoid future tree searches as long as
3398 * the inode is not evicted again.
3400 inode->logged_trans = trans->transid;
3403 * If it's a directory, then we must set last_dir_index_offset to the
3404 * maximum possible value, so that the next attempt to log the inode does
3405 * not skip checking if dir index keys found in modified subvolume tree
3406 * leaves have been logged before, otherwise it would result in attempts
3407 * to insert duplicate dir index keys in the log tree. This must be done
3408 * because last_dir_index_offset is an in-memory only field, not persisted
3409 * in the inode item or any other on-disk structure, so its value is lost
3410 * once the inode is evicted.
3412 if (S_ISDIR(inode->vfs_inode.i_mode))
3413 inode->last_dir_index_offset = (u64)-1;
3419 * Delete a directory entry from the log if it exists.
3421 * Returns < 0 on error
3422 * 1 if the entry does not exists
3423 * 0 if the entry existed and was successfully deleted
3425 static int del_logged_dentry(struct btrfs_trans_handle *trans,
3426 struct btrfs_root *log,
3427 struct btrfs_path *path,
3429 const struct fscrypt_str *name,
3432 struct btrfs_dir_item *di;
3435 * We only log dir index items of a directory, so we don't need to look
3436 * for dir item keys.
3438 di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3446 * We do not need to update the size field of the directory's
3447 * inode item because on log replay we update the field to reflect
3448 * all existing entries in the directory (see overwrite_item()).
3450 return btrfs_delete_one_dir_name(trans, log, path, di);
3454 * If both a file and directory are logged, and unlinks or renames are
3455 * mixed in, we have a few interesting corners:
3457 * create file X in dir Y
3458 * link file X to X.link in dir Y
3460 * unlink file X but leave X.link
3463 * After a crash we would expect only X.link to exist. But file X
3464 * didn't get fsync'd again so the log has back refs for X and X.link.
3466 * We solve this by removing directory entries and inode backrefs from the
3467 * log when a file that was logged in the current transaction is
3468 * unlinked. Any later fsync will include the updated log entries, and
3469 * we'll be able to reconstruct the proper directory items from backrefs.
3471 * This optimizations allows us to avoid relogging the entire inode
3472 * or the entire directory.
3474 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3475 struct btrfs_root *root,
3476 const struct fscrypt_str *name,
3477 struct btrfs_inode *dir, u64 index)
3479 struct btrfs_path *path;
3482 ret = inode_logged(trans, dir, NULL);
3486 btrfs_set_log_full_commit(trans);
3490 ret = join_running_log_trans(root);
3494 mutex_lock(&dir->log_mutex);
3496 path = btrfs_alloc_path();
3502 ret = del_logged_dentry(trans, root->log_root, path, btrfs_ino(dir),
3504 btrfs_free_path(path);
3506 mutex_unlock(&dir->log_mutex);
3508 btrfs_set_log_full_commit(trans);
3509 btrfs_end_log_trans(root);
3512 /* see comments for btrfs_del_dir_entries_in_log */
3513 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3514 struct btrfs_root *root,
3515 const struct fscrypt_str *name,
3516 struct btrfs_inode *inode, u64 dirid)
3518 struct btrfs_root *log;
3522 ret = inode_logged(trans, inode, NULL);
3526 btrfs_set_log_full_commit(trans);
3530 ret = join_running_log_trans(root);
3533 log = root->log_root;
3534 mutex_lock(&inode->log_mutex);
3536 ret = btrfs_del_inode_ref(trans, log, name, btrfs_ino(inode),
3538 mutex_unlock(&inode->log_mutex);
3539 if (ret < 0 && ret != -ENOENT)
3540 btrfs_set_log_full_commit(trans);
3541 btrfs_end_log_trans(root);
3545 * creates a range item in the log for 'dirid'. first_offset and
3546 * last_offset tell us which parts of the key space the log should
3547 * be considered authoritative for.
3549 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3550 struct btrfs_root *log,
3551 struct btrfs_path *path,
3553 u64 first_offset, u64 last_offset)
3556 struct btrfs_key key;
3557 struct btrfs_dir_log_item *item;
3559 key.objectid = dirid;
3560 key.offset = first_offset;
3561 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3562 ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3564 * -EEXIST is fine and can happen sporadically when we are logging a
3565 * directory and have concurrent insertions in the subvolume's tree for
3566 * items from other inodes and that result in pushing off some dir items
3567 * from one leaf to another in order to accommodate for the new items.
3568 * This results in logging the same dir index range key.
3570 if (ret && ret != -EEXIST)
3573 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3574 struct btrfs_dir_log_item);
3575 if (ret == -EEXIST) {
3576 const u64 curr_end = btrfs_dir_log_end(path->nodes[0], item);
3579 * btrfs_del_dir_entries_in_log() might have been called during
3580 * an unlink between the initial insertion of this key and the
3581 * current update, or we might be logging a single entry deletion
3582 * during a rename, so set the new last_offset to the max value.
3584 last_offset = max(last_offset, curr_end);
3586 btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3587 btrfs_mark_buffer_dirty(path->nodes[0]);
3588 btrfs_release_path(path);
3592 static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
3593 struct btrfs_root *log,
3594 struct extent_buffer *src,
3595 struct btrfs_path *dst_path,
3599 char *ins_data = NULL;
3600 struct btrfs_item_batch batch;
3601 struct extent_buffer *dst;
3602 unsigned long src_offset;
3603 unsigned long dst_offset;
3604 struct btrfs_key key;
3613 btrfs_item_key_to_cpu(src, &key, start_slot);
3614 item_size = btrfs_item_size(src, start_slot);
3616 batch.data_sizes = &item_size;
3617 batch.total_data_size = item_size;
3619 struct btrfs_key *ins_keys;
3622 ins_data = kmalloc(count * sizeof(u32) +
3623 count * sizeof(struct btrfs_key), GFP_NOFS);
3627 ins_sizes = (u32 *)ins_data;
3628 ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
3629 batch.keys = ins_keys;
3630 batch.data_sizes = ins_sizes;
3631 batch.total_data_size = 0;
3633 for (i = 0; i < count; i++) {
3634 const int slot = start_slot + i;
3636 btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
3637 ins_sizes[i] = btrfs_item_size(src, slot);
3638 batch.total_data_size += ins_sizes[i];
3642 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
3646 dst = dst_path->nodes[0];
3648 * Copy all the items in bulk, in a single copy operation. Item data is
3649 * organized such that it's placed at the end of a leaf and from right
3650 * to left. For example, the data for the second item ends at an offset
3651 * that matches the offset where the data for the first item starts, the
3652 * data for the third item ends at an offset that matches the offset
3653 * where the data of the second items starts, and so on.
3654 * Therefore our source and destination start offsets for copy match the
3655 * offsets of the last items (highest slots).
3657 dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
3658 src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
3659 copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
3660 btrfs_release_path(dst_path);
3667 static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
3668 struct btrfs_inode *inode,
3669 struct btrfs_path *path,
3670 struct btrfs_path *dst_path,
3671 struct btrfs_log_ctx *ctx,
3672 u64 *last_old_dentry_offset)
3674 struct btrfs_root *log = inode->root->log_root;
3675 struct extent_buffer *src;
3676 const int nritems = btrfs_header_nritems(path->nodes[0]);
3677 const u64 ino = btrfs_ino(inode);
3678 bool last_found = false;
3679 int batch_start = 0;
3684 * We need to clone the leaf, release the read lock on it, and use the
3685 * clone before modifying the log tree. See the comment at copy_items()
3686 * about why we need to do this.
3688 src = btrfs_clone_extent_buffer(path->nodes[0]);
3693 btrfs_release_path(path);
3694 path->nodes[0] = src;
3697 for (; i < nritems; i++) {
3698 struct btrfs_dir_item *di;
3699 struct btrfs_key key;
3702 btrfs_item_key_to_cpu(src, &key, i);
3704 if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
3709 di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3710 ctx->last_dir_item_offset = key.offset;
3713 * Skip ranges of items that consist only of dir item keys created
3714 * in past transactions. However if we find a gap, we must log a
3715 * dir index range item for that gap, so that index keys in that
3716 * gap are deleted during log replay.
3718 if (btrfs_dir_transid(src, di) < trans->transid) {
3719 if (key.offset > *last_old_dentry_offset + 1) {
3720 ret = insert_dir_log_key(trans, log, dst_path,
3721 ino, *last_old_dentry_offset + 1,
3727 *last_old_dentry_offset = key.offset;
3731 /* If we logged this dir index item before, we can skip it. */
3732 if (key.offset <= inode->last_dir_index_offset)
3736 * We must make sure that when we log a directory entry, the
3737 * corresponding inode, after log replay, has a matching link
3738 * count. For example:
3744 * xfs_io -c "fsync" mydir
3746 * <mount fs and log replay>
3748 * Would result in a fsync log that when replayed, our file inode
3749 * would have a link count of 1, but we get two directory entries
3750 * pointing to the same inode. After removing one of the names,
3751 * it would not be possible to remove the other name, which
3752 * resulted always in stale file handle errors, and would not be
3753 * possible to rmdir the parent directory, since its i_size could
3754 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
3755 * resulting in -ENOTEMPTY errors.
3757 if (!ctx->log_new_dentries) {
3758 struct btrfs_key di_key;
3760 btrfs_dir_item_key_to_cpu(src, di, &di_key);
3761 if (di_key.type != BTRFS_ROOT_ITEM_KEY)
3762 ctx->log_new_dentries = true;
3765 if (batch_size == 0)
3770 if (batch_size > 0) {
3773 ret = flush_dir_items_batch(trans, log, src, dst_path,
3774 batch_start, batch_size);
3779 return last_found ? 1 : 0;
3783 * log all the items included in the current transaction for a given
3784 * directory. This also creates the range items in the log tree required
3785 * to replay anything deleted before the fsync
3787 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3788 struct btrfs_inode *inode,
3789 struct btrfs_path *path,
3790 struct btrfs_path *dst_path,
3791 struct btrfs_log_ctx *ctx,
3792 u64 min_offset, u64 *last_offset_ret)
3794 struct btrfs_key min_key;
3795 struct btrfs_root *root = inode->root;
3796 struct btrfs_root *log = root->log_root;
3799 u64 last_old_dentry_offset = min_offset - 1;
3800 u64 last_offset = (u64)-1;
3801 u64 ino = btrfs_ino(inode);
3803 min_key.objectid = ino;
3804 min_key.type = BTRFS_DIR_INDEX_KEY;
3805 min_key.offset = min_offset;
3807 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3810 * we didn't find anything from this transaction, see if there
3811 * is anything at all
3813 if (ret != 0 || min_key.objectid != ino ||
3814 min_key.type != BTRFS_DIR_INDEX_KEY) {
3815 min_key.objectid = ino;
3816 min_key.type = BTRFS_DIR_INDEX_KEY;
3817 min_key.offset = (u64)-1;
3818 btrfs_release_path(path);
3819 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3821 btrfs_release_path(path);
3824 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3826 /* if ret == 0 there are items for this type,
3827 * create a range to tell us the last key of this type.
3828 * otherwise, there are no items in this directory after
3829 * *min_offset, and we create a range to indicate that.
3832 struct btrfs_key tmp;
3834 btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3836 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3837 last_old_dentry_offset = tmp.offset;
3842 /* go backward to find any previous key */
3843 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3845 struct btrfs_key tmp;
3847 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3849 * The dir index key before the first one we found that needs to
3850 * be logged might be in a previous leaf, and there might be a
3851 * gap between these keys, meaning that we had deletions that
3852 * happened. So the key range item we log (key type
3853 * BTRFS_DIR_LOG_INDEX_KEY) must cover a range that starts at the
3854 * previous key's offset plus 1, so that those deletes are replayed.
3856 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3857 last_old_dentry_offset = tmp.offset;
3859 btrfs_release_path(path);
3862 * Find the first key from this transaction again. See the note for
3863 * log_new_dir_dentries, if we're logging a directory recursively we
3864 * won't be holding its i_mutex, which means we can modify the directory
3865 * while we're logging it. If we remove an entry between our first
3866 * search and this search we'll not find the key again and can just
3870 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3875 * we have a block from this transaction, log every item in it
3876 * from our directory
3879 ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx,
3880 &last_old_dentry_offset);
3886 path->slots[0] = btrfs_header_nritems(path->nodes[0]);
3889 * look ahead to the next item and see if it is also
3890 * from this directory and from this transaction
3892 ret = btrfs_next_leaf(root, path);
3895 last_offset = (u64)-1;
3900 btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
3901 if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
3902 last_offset = (u64)-1;
3905 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3907 * The next leaf was not changed in the current transaction
3908 * and has at least one dir index key.
3909 * We check for the next key because there might have been
3910 * one or more deletions between the last key we logged and
3911 * that next key. So the key range item we log (key type
3912 * BTRFS_DIR_LOG_INDEX_KEY) must end at the next key's
3913 * offset minus 1, so that those deletes are replayed.
3915 last_offset = min_key.offset - 1;
3918 if (need_resched()) {
3919 btrfs_release_path(path);
3925 btrfs_release_path(path);
3926 btrfs_release_path(dst_path);
3929 *last_offset_ret = last_offset;
3931 * In case the leaf was changed in the current transaction but
3932 * all its dir items are from a past transaction, the last item
3933 * in the leaf is a dir item and there's no gap between that last
3934 * dir item and the first one on the next leaf (which did not
3935 * change in the current transaction), then we don't need to log
3936 * a range, last_old_dentry_offset is == to last_offset.
3938 ASSERT(last_old_dentry_offset <= last_offset);
3939 if (last_old_dentry_offset < last_offset) {
3940 ret = insert_dir_log_key(trans, log, path, ino,
3941 last_old_dentry_offset + 1,
3951 * If the inode was logged before and it was evicted, then its
3952 * last_dir_index_offset is (u64)-1, so we don't the value of the last index
3953 * key offset. If that's the case, search for it and update the inode. This
3954 * is to avoid lookups in the log tree every time we try to insert a dir index
3955 * key from a leaf changed in the current transaction, and to allow us to always
3956 * do batch insertions of dir index keys.
3958 static int update_last_dir_index_offset(struct btrfs_inode *inode,
3959 struct btrfs_path *path,
3960 const struct btrfs_log_ctx *ctx)
3962 const u64 ino = btrfs_ino(inode);
3963 struct btrfs_key key;
3966 lockdep_assert_held(&inode->log_mutex);
3968 if (inode->last_dir_index_offset != (u64)-1)
3971 if (!ctx->logged_before) {
3972 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
3977 key.type = BTRFS_DIR_INDEX_KEY;
3978 key.offset = (u64)-1;
3980 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3982 * An error happened or we actually have an index key with an offset
3983 * value of (u64)-1. Bail out, we're done.
3989 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
3992 * No dir index items, bail out and leave last_dir_index_offset with
3993 * the value right before the first valid index value.
3995 if (path->slots[0] == 0)
3999 * btrfs_search_slot() left us at one slot beyond the slot with the last
4000 * index key, or beyond the last key of the directory that is not an
4001 * index key. If we have an index key before, set last_dir_index_offset
4002 * to its offset value, otherwise leave it with a value right before the
4003 * first valid index value, as it means we have an empty directory.
4005 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
4006 if (key.objectid == ino && key.type == BTRFS_DIR_INDEX_KEY)
4007 inode->last_dir_index_offset = key.offset;
4010 btrfs_release_path(path);
4016 * logging directories is very similar to logging inodes, We find all the items
4017 * from the current transaction and write them to the log.
4019 * The recovery code scans the directory in the subvolume, and if it finds a
4020 * key in the range logged that is not present in the log tree, then it means
4021 * that dir entry was unlinked during the transaction.
4023 * In order for that scan to work, we must include one key smaller than
4024 * the smallest logged by this transaction and one key larger than the largest
4025 * key logged by this transaction.
4027 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
4028 struct btrfs_inode *inode,
4029 struct btrfs_path *path,
4030 struct btrfs_path *dst_path,
4031 struct btrfs_log_ctx *ctx)
4037 ret = update_last_dir_index_offset(inode, path, ctx);
4041 min_key = BTRFS_DIR_START_INDEX;
4043 ctx->last_dir_item_offset = inode->last_dir_index_offset;
4046 ret = log_dir_items(trans, inode, path, dst_path,
4047 ctx, min_key, &max_key);
4050 if (max_key == (u64)-1)
4052 min_key = max_key + 1;
4055 inode->last_dir_index_offset = ctx->last_dir_item_offset;
4061 * a helper function to drop items from the log before we relog an
4062 * inode. max_key_type indicates the highest item type to remove.
4063 * This cannot be run for file data extents because it does not
4064 * free the extents they point to.
4066 static int drop_inode_items(struct btrfs_trans_handle *trans,
4067 struct btrfs_root *log,
4068 struct btrfs_path *path,
4069 struct btrfs_inode *inode,
4073 struct btrfs_key key;
4074 struct btrfs_key found_key;
4077 key.objectid = btrfs_ino(inode);
4078 key.type = max_key_type;
4079 key.offset = (u64)-1;
4082 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
4083 BUG_ON(ret == 0); /* Logic error */
4087 if (path->slots[0] == 0)
4091 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4094 if (found_key.objectid != key.objectid)
4097 found_key.offset = 0;
4099 ret = btrfs_bin_search(path->nodes[0], &found_key, &start_slot);
4103 ret = btrfs_del_items(trans, log, path, start_slot,
4104 path->slots[0] - start_slot + 1);
4106 * If start slot isn't 0 then we don't need to re-search, we've
4107 * found the last guy with the objectid in this tree.
4109 if (ret || start_slot != 0)
4111 btrfs_release_path(path);
4113 btrfs_release_path(path);
4119 static int truncate_inode_items(struct btrfs_trans_handle *trans,
4120 struct btrfs_root *log_root,
4121 struct btrfs_inode *inode,
4122 u64 new_size, u32 min_type)
4124 struct btrfs_truncate_control control = {
4125 .new_size = new_size,
4126 .ino = btrfs_ino(inode),
4127 .min_type = min_type,
4128 .skip_ref_updates = true,
4131 return btrfs_truncate_inode_items(trans, log_root, &control);
4134 static void fill_inode_item(struct btrfs_trans_handle *trans,
4135 struct extent_buffer *leaf,
4136 struct btrfs_inode_item *item,
4137 struct inode *inode, int log_inode_only,
4140 struct btrfs_map_token token;
4143 btrfs_init_map_token(&token, leaf);
4145 if (log_inode_only) {
4146 /* set the generation to zero so the recover code
4147 * can tell the difference between an logging
4148 * just to say 'this inode exists' and a logging
4149 * to say 'update this inode with these values'
4151 btrfs_set_token_inode_generation(&token, item, 0);
4152 btrfs_set_token_inode_size(&token, item, logged_isize);
4154 btrfs_set_token_inode_generation(&token, item,
4155 BTRFS_I(inode)->generation);
4156 btrfs_set_token_inode_size(&token, item, inode->i_size);
4159 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4160 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4161 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4162 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4164 btrfs_set_token_timespec_sec(&token, &item->atime,
4165 inode->i_atime.tv_sec);
4166 btrfs_set_token_timespec_nsec(&token, &item->atime,
4167 inode->i_atime.tv_nsec);
4169 btrfs_set_token_timespec_sec(&token, &item->mtime,
4170 inode->i_mtime.tv_sec);
4171 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4172 inode->i_mtime.tv_nsec);
4174 btrfs_set_token_timespec_sec(&token, &item->ctime,
4175 inode->i_ctime.tv_sec);
4176 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4177 inode->i_ctime.tv_nsec);
4180 * We do not need to set the nbytes field, in fact during a fast fsync
4181 * its value may not even be correct, since a fast fsync does not wait
4182 * for ordered extent completion, which is where we update nbytes, it
4183 * only waits for writeback to complete. During log replay as we find
4184 * file extent items and replay them, we adjust the nbytes field of the
4185 * inode item in subvolume tree as needed (see overwrite_item()).
4188 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4189 btrfs_set_token_inode_transid(&token, item, trans->transid);
4190 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4191 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4192 BTRFS_I(inode)->ro_flags);
4193 btrfs_set_token_inode_flags(&token, item, flags);
4194 btrfs_set_token_inode_block_group(&token, item, 0);
4197 static int log_inode_item(struct btrfs_trans_handle *trans,
4198 struct btrfs_root *log, struct btrfs_path *path,
4199 struct btrfs_inode *inode, bool inode_item_dropped)
4201 struct btrfs_inode_item *inode_item;
4205 * If we are doing a fast fsync and the inode was logged before in the
4206 * current transaction, then we know the inode was previously logged and
4207 * it exists in the log tree. For performance reasons, in this case use
4208 * btrfs_search_slot() directly with ins_len set to 0 so that we never
4209 * attempt a write lock on the leaf's parent, which adds unnecessary lock
4210 * contention in case there are concurrent fsyncs for other inodes of the
4211 * same subvolume. Using btrfs_insert_empty_item() when the inode item
4212 * already exists can also result in unnecessarily splitting a leaf.
4214 if (!inode_item_dropped && inode->logged_trans == trans->transid) {
4215 ret = btrfs_search_slot(trans, log, &inode->location, path, 0, 1);
4221 * This means it is the first fsync in the current transaction,
4222 * so the inode item is not in the log and we need to insert it.
4223 * We can never get -EEXIST because we are only called for a fast
4224 * fsync and in case an inode eviction happens after the inode was
4225 * logged before in the current transaction, when we load again
4226 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
4227 * flags and set ->logged_trans to 0.
4229 ret = btrfs_insert_empty_item(trans, log, path, &inode->location,
4230 sizeof(*inode_item));
4231 ASSERT(ret != -EEXIST);
4235 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4236 struct btrfs_inode_item);
4237 fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
4239 btrfs_release_path(path);
4243 static int log_csums(struct btrfs_trans_handle *trans,
4244 struct btrfs_inode *inode,
4245 struct btrfs_root *log_root,
4246 struct btrfs_ordered_sum *sums)
4248 const u64 lock_end = sums->bytenr + sums->len - 1;
4249 struct extent_state *cached_state = NULL;
4253 * If this inode was not used for reflink operations in the current
4254 * transaction with new extents, then do the fast path, no need to
4255 * worry about logging checksum items with overlapping ranges.
4257 if (inode->last_reflink_trans < trans->transid)
4258 return btrfs_csum_file_blocks(trans, log_root, sums);
4261 * Serialize logging for checksums. This is to avoid racing with the
4262 * same checksum being logged by another task that is logging another
4263 * file which happens to refer to the same extent as well. Such races
4264 * can leave checksum items in the log with overlapping ranges.
4266 ret = lock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4271 * Due to extent cloning, we might have logged a csum item that covers a
4272 * subrange of a cloned extent, and later we can end up logging a csum
4273 * item for a larger subrange of the same extent or the entire range.
4274 * This would leave csum items in the log tree that cover the same range
4275 * and break the searches for checksums in the log tree, resulting in
4276 * some checksums missing in the fs/subvolume tree. So just delete (or
4277 * trim and adjust) any existing csum items in the log for this range.
4279 ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
4281 ret = btrfs_csum_file_blocks(trans, log_root, sums);
4283 unlock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4289 static noinline int copy_items(struct btrfs_trans_handle *trans,
4290 struct btrfs_inode *inode,
4291 struct btrfs_path *dst_path,
4292 struct btrfs_path *src_path,
4293 int start_slot, int nr, int inode_only,
4296 struct btrfs_root *log = inode->root->log_root;
4297 struct btrfs_file_extent_item *extent;
4298 struct extent_buffer *src;
4300 struct btrfs_key *ins_keys;
4302 struct btrfs_item_batch batch;
4306 const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
4307 const u64 i_size = i_size_read(&inode->vfs_inode);
4310 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4311 * use the clone. This is because otherwise we would be changing the log
4312 * tree, to insert items from the subvolume tree or insert csum items,
4313 * while holding a read lock on a leaf from the subvolume tree, which
4314 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4316 * 1) Modifying the log tree triggers an extent buffer allocation while
4317 * holding a write lock on a parent extent buffer from the log tree.
4318 * Allocating the pages for an extent buffer, or the extent buffer
4319 * struct, can trigger inode eviction and finally the inode eviction
4320 * will trigger a release/remove of a delayed node, which requires
4321 * taking the delayed node's mutex;
4323 * 2) Allocating a metadata extent for a log tree can trigger the async
4324 * reclaim thread and make us wait for it to release enough space and
4325 * unblock our reservation ticket. The reclaim thread can start
4326 * flushing delayed items, and that in turn results in the need to
4327 * lock delayed node mutexes and in the need to write lock extent
4328 * buffers of a subvolume tree - all this while holding a write lock
4329 * on the parent extent buffer in the log tree.
4331 * So one task in scenario 1) running in parallel with another task in
4332 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4333 * node mutex while having a read lock on a leaf from the subvolume,
4334 * while the other is holding the delayed node's mutex and wants to
4335 * write lock the same subvolume leaf for flushing delayed items.
4337 src = btrfs_clone_extent_buffer(src_path->nodes[0]);
4341 i = src_path->slots[0];
4342 btrfs_release_path(src_path);
4343 src_path->nodes[0] = src;
4344 src_path->slots[0] = i;
4346 ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
4347 nr * sizeof(u32), GFP_NOFS);
4351 ins_sizes = (u32 *)ins_data;
4352 ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4353 batch.keys = ins_keys;
4354 batch.data_sizes = ins_sizes;
4355 batch.total_data_size = 0;
4359 for (i = 0; i < nr; i++) {
4360 const int src_slot = start_slot + i;
4361 struct btrfs_root *csum_root;
4362 struct btrfs_ordered_sum *sums;
4363 struct btrfs_ordered_sum *sums_next;
4364 LIST_HEAD(ordered_sums);
4368 u64 extent_num_bytes;
4371 btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
4373 if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
4376 extent = btrfs_item_ptr(src, src_slot,
4377 struct btrfs_file_extent_item);
4379 is_old_extent = (btrfs_file_extent_generation(src, extent) <
4383 * Don't copy extents from past generations. That would make us
4384 * log a lot more metadata for common cases like doing only a
4385 * few random writes into a file and then fsync it for the first
4386 * time or after the full sync flag is set on the inode. We can
4387 * get leaves full of extent items, most of which are from past
4388 * generations, so we can skip them - as long as the inode has
4389 * not been the target of a reflink operation in this transaction,
4390 * as in that case it might have had file extent items with old
4391 * generations copied into it. We also must always log prealloc
4392 * extents that start at or beyond eof, otherwise we would lose
4393 * them on log replay.
4395 if (is_old_extent &&
4396 ins_keys[dst_index].offset < i_size &&
4397 inode->last_reflink_trans < trans->transid)
4403 /* Only regular extents have checksums. */
4404 if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
4408 * If it's an extent created in a past transaction, then its
4409 * checksums are already accessible from the committed csum tree,
4410 * no need to log them.
4415 disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
4416 /* If it's an explicit hole, there are no checksums. */
4417 if (disk_bytenr == 0)
4420 disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
4422 if (btrfs_file_extent_compression(src, extent)) {
4424 extent_num_bytes = disk_num_bytes;
4426 extent_offset = btrfs_file_extent_offset(src, extent);
4427 extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
4430 csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
4431 disk_bytenr += extent_offset;
4432 ret = btrfs_lookup_csums_range(csum_root, disk_bytenr,
4433 disk_bytenr + extent_num_bytes - 1,
4434 &ordered_sums, 0, false);
4438 list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
4440 ret = log_csums(trans, inode, log, sums);
4441 list_del(&sums->list);
4448 ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
4449 batch.total_data_size += ins_sizes[dst_index];
4455 * We have a leaf full of old extent items that don't need to be logged,
4456 * so we don't need to do anything.
4461 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4466 for (i = 0; i < nr; i++) {
4467 const int src_slot = start_slot + i;
4468 const int dst_slot = dst_path->slots[0] + dst_index;
4469 struct btrfs_key key;
4470 unsigned long src_offset;
4471 unsigned long dst_offset;
4474 * We're done, all the remaining items in the source leaf
4475 * correspond to old file extent items.
4477 if (dst_index >= batch.nr)
4480 btrfs_item_key_to_cpu(src, &key, src_slot);
4482 if (key.type != BTRFS_EXTENT_DATA_KEY)
4485 extent = btrfs_item_ptr(src, src_slot,
4486 struct btrfs_file_extent_item);
4488 /* See the comment in the previous loop, same logic. */
4489 if (btrfs_file_extent_generation(src, extent) < trans->transid &&
4490 key.offset < i_size &&
4491 inode->last_reflink_trans < trans->transid)
4495 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
4496 src_offset = btrfs_item_ptr_offset(src, src_slot);
4498 if (key.type == BTRFS_INODE_ITEM_KEY) {
4499 struct btrfs_inode_item *inode_item;
4501 inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
4502 struct btrfs_inode_item);
4503 fill_inode_item(trans, dst_path->nodes[0], inode_item,
4505 inode_only == LOG_INODE_EXISTS,
4508 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4509 src_offset, ins_sizes[dst_index]);
4515 btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4516 btrfs_release_path(dst_path);
4523 static int extent_cmp(void *priv, const struct list_head *a,
4524 const struct list_head *b)
4526 const struct extent_map *em1, *em2;
4528 em1 = list_entry(a, struct extent_map, list);
4529 em2 = list_entry(b, struct extent_map, list);
4531 if (em1->start < em2->start)
4533 else if (em1->start > em2->start)
4538 static int log_extent_csums(struct btrfs_trans_handle *trans,
4539 struct btrfs_inode *inode,
4540 struct btrfs_root *log_root,
4541 const struct extent_map *em,
4542 struct btrfs_log_ctx *ctx)
4544 struct btrfs_ordered_extent *ordered;
4545 struct btrfs_root *csum_root;
4548 u64 mod_start = em->mod_start;
4549 u64 mod_len = em->mod_len;
4550 LIST_HEAD(ordered_sums);
4553 if (inode->flags & BTRFS_INODE_NODATASUM ||
4554 test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
4555 em->block_start == EXTENT_MAP_HOLE)
4558 list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
4559 const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
4560 const u64 mod_end = mod_start + mod_len;
4561 struct btrfs_ordered_sum *sums;
4566 if (ordered_end <= mod_start)
4568 if (mod_end <= ordered->file_offset)
4572 * We are going to copy all the csums on this ordered extent, so
4573 * go ahead and adjust mod_start and mod_len in case this ordered
4574 * extent has already been logged.
4576 if (ordered->file_offset > mod_start) {
4577 if (ordered_end >= mod_end)
4578 mod_len = ordered->file_offset - mod_start;
4580 * If we have this case
4582 * |--------- logged extent ---------|
4583 * |----- ordered extent ----|
4585 * Just don't mess with mod_start and mod_len, we'll
4586 * just end up logging more csums than we need and it
4590 if (ordered_end < mod_end) {
4591 mod_len = mod_end - ordered_end;
4592 mod_start = ordered_end;
4599 * To keep us from looping for the above case of an ordered
4600 * extent that falls inside of the logged extent.
4602 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
4605 list_for_each_entry(sums, &ordered->list, list) {
4606 ret = log_csums(trans, inode, log_root, sums);
4612 /* We're done, found all csums in the ordered extents. */
4616 /* If we're compressed we have to save the entire range of csums. */
4617 if (em->compress_type) {
4619 csum_len = max(em->block_len, em->orig_block_len);
4621 csum_offset = mod_start - em->start;
4625 /* block start is already adjusted for the file extent offset. */
4626 csum_root = btrfs_csum_root(trans->fs_info, em->block_start);
4627 ret = btrfs_lookup_csums_range(csum_root,
4628 em->block_start + csum_offset,
4629 em->block_start + csum_offset +
4630 csum_len - 1, &ordered_sums, 0, false);
4634 while (!list_empty(&ordered_sums)) {
4635 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4636 struct btrfs_ordered_sum,
4639 ret = log_csums(trans, inode, log_root, sums);
4640 list_del(&sums->list);
4647 static int log_one_extent(struct btrfs_trans_handle *trans,
4648 struct btrfs_inode *inode,
4649 const struct extent_map *em,
4650 struct btrfs_path *path,
4651 struct btrfs_log_ctx *ctx)
4653 struct btrfs_drop_extents_args drop_args = { 0 };
4654 struct btrfs_root *log = inode->root->log_root;
4655 struct btrfs_file_extent_item fi = { 0 };
4656 struct extent_buffer *leaf;
4657 struct btrfs_key key;
4658 u64 extent_offset = em->start - em->orig_start;
4662 btrfs_set_stack_file_extent_generation(&fi, trans->transid);
4663 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4664 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
4666 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
4668 block_len = max(em->block_len, em->orig_block_len);
4669 if (em->compress_type != BTRFS_COMPRESS_NONE) {
4670 btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start);
4671 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4672 } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4673 btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start -
4675 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4678 btrfs_set_stack_file_extent_offset(&fi, extent_offset);
4679 btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
4680 btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
4681 btrfs_set_stack_file_extent_compression(&fi, em->compress_type);
4683 ret = log_extent_csums(trans, inode, log, em, ctx);
4688 * If this is the first time we are logging the inode in the current
4689 * transaction, we can avoid btrfs_drop_extents(), which is expensive
4690 * because it does a deletion search, which always acquires write locks
4691 * for extent buffers at levels 2, 1 and 0. This not only wastes time
4692 * but also adds significant contention in a log tree, since log trees
4693 * are small, with a root at level 2 or 3 at most, due to their short
4696 if (ctx->logged_before) {
4697 drop_args.path = path;
4698 drop_args.start = em->start;
4699 drop_args.end = em->start + em->len;
4700 drop_args.replace_extent = true;
4701 drop_args.extent_item_size = sizeof(fi);
4702 ret = btrfs_drop_extents(trans, log, inode, &drop_args);
4707 if (!drop_args.extent_inserted) {
4708 key.objectid = btrfs_ino(inode);
4709 key.type = BTRFS_EXTENT_DATA_KEY;
4710 key.offset = em->start;
4712 ret = btrfs_insert_empty_item(trans, log, path, &key,
4717 leaf = path->nodes[0];
4718 write_extent_buffer(leaf, &fi,
4719 btrfs_item_ptr_offset(leaf, path->slots[0]),
4721 btrfs_mark_buffer_dirty(leaf);
4723 btrfs_release_path(path);
4729 * Log all prealloc extents beyond the inode's i_size to make sure we do not
4730 * lose them after doing a full/fast fsync and replaying the log. We scan the
4731 * subvolume's root instead of iterating the inode's extent map tree because
4732 * otherwise we can log incorrect extent items based on extent map conversion.
4733 * That can happen due to the fact that extent maps are merged when they
4734 * are not in the extent map tree's list of modified extents.
4736 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4737 struct btrfs_inode *inode,
4738 struct btrfs_path *path)
4740 struct btrfs_root *root = inode->root;
4741 struct btrfs_key key;
4742 const u64 i_size = i_size_read(&inode->vfs_inode);
4743 const u64 ino = btrfs_ino(inode);
4744 struct btrfs_path *dst_path = NULL;
4745 bool dropped_extents = false;
4746 u64 truncate_offset = i_size;
4747 struct extent_buffer *leaf;
4753 if (!(inode->flags & BTRFS_INODE_PREALLOC))
4757 key.type = BTRFS_EXTENT_DATA_KEY;
4758 key.offset = i_size;
4759 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4764 * We must check if there is a prealloc extent that starts before the
4765 * i_size and crosses the i_size boundary. This is to ensure later we
4766 * truncate down to the end of that extent and not to the i_size, as
4767 * otherwise we end up losing part of the prealloc extent after a log
4768 * replay and with an implicit hole if there is another prealloc extent
4769 * that starts at an offset beyond i_size.
4771 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4776 struct btrfs_file_extent_item *ei;
4778 leaf = path->nodes[0];
4779 slot = path->slots[0];
4780 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4782 if (btrfs_file_extent_type(leaf, ei) ==
4783 BTRFS_FILE_EXTENT_PREALLOC) {
4786 btrfs_item_key_to_cpu(leaf, &key, slot);
4787 extent_end = key.offset +
4788 btrfs_file_extent_num_bytes(leaf, ei);
4790 if (extent_end > i_size)
4791 truncate_offset = extent_end;
4798 leaf = path->nodes[0];
4799 slot = path->slots[0];
4801 if (slot >= btrfs_header_nritems(leaf)) {
4803 ret = copy_items(trans, inode, dst_path, path,
4804 start_slot, ins_nr, 1, 0);
4809 ret = btrfs_next_leaf(root, path);
4819 btrfs_item_key_to_cpu(leaf, &key, slot);
4820 if (key.objectid > ino)
4822 if (WARN_ON_ONCE(key.objectid < ino) ||
4823 key.type < BTRFS_EXTENT_DATA_KEY ||
4824 key.offset < i_size) {
4828 if (!dropped_extents) {
4830 * Avoid logging extent items logged in past fsync calls
4831 * and leading to duplicate keys in the log tree.
4833 ret = truncate_inode_items(trans, root->log_root, inode,
4835 BTRFS_EXTENT_DATA_KEY);
4838 dropped_extents = true;
4845 dst_path = btrfs_alloc_path();
4853 ret = copy_items(trans, inode, dst_path, path,
4854 start_slot, ins_nr, 1, 0);
4856 btrfs_release_path(path);
4857 btrfs_free_path(dst_path);
4861 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4862 struct btrfs_inode *inode,
4863 struct btrfs_path *path,
4864 struct btrfs_log_ctx *ctx)
4866 struct btrfs_ordered_extent *ordered;
4867 struct btrfs_ordered_extent *tmp;
4868 struct extent_map *em, *n;
4869 struct list_head extents;
4870 struct extent_map_tree *tree = &inode->extent_tree;
4874 INIT_LIST_HEAD(&extents);
4876 write_lock(&tree->lock);
4878 list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4879 list_del_init(&em->list);
4881 * Just an arbitrary number, this can be really CPU intensive
4882 * once we start getting a lot of extents, and really once we
4883 * have a bunch of extents we just want to commit since it will
4886 if (++num > 32768) {
4887 list_del_init(&tree->modified_extents);
4892 if (em->generation < trans->transid)
4895 /* We log prealloc extents beyond eof later. */
4896 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
4897 em->start >= i_size_read(&inode->vfs_inode))
4900 /* Need a ref to keep it from getting evicted from cache */
4901 refcount_inc(&em->refs);
4902 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
4903 list_add_tail(&em->list, &extents);
4907 list_sort(NULL, &extents, extent_cmp);
4909 while (!list_empty(&extents)) {
4910 em = list_entry(extents.next, struct extent_map, list);
4912 list_del_init(&em->list);
4915 * If we had an error we just need to delete everybody from our
4919 clear_em_logging(tree, em);
4920 free_extent_map(em);
4924 write_unlock(&tree->lock);
4926 ret = log_one_extent(trans, inode, em, path, ctx);
4927 write_lock(&tree->lock);
4928 clear_em_logging(tree, em);
4929 free_extent_map(em);
4931 WARN_ON(!list_empty(&extents));
4932 write_unlock(&tree->lock);
4935 ret = btrfs_log_prealloc_extents(trans, inode, path);
4940 * We have logged all extents successfully, now make sure the commit of
4941 * the current transaction waits for the ordered extents to complete
4942 * before it commits and wipes out the log trees, otherwise we would
4943 * lose data if an ordered extents completes after the transaction
4944 * commits and a power failure happens after the transaction commit.
4946 list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
4947 list_del_init(&ordered->log_list);
4948 set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
4950 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4951 spin_lock_irq(&inode->ordered_tree.lock);
4952 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4953 set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
4954 atomic_inc(&trans->transaction->pending_ordered);
4956 spin_unlock_irq(&inode->ordered_tree.lock);
4958 btrfs_put_ordered_extent(ordered);
4964 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
4965 struct btrfs_path *path, u64 *size_ret)
4967 struct btrfs_key key;
4970 key.objectid = btrfs_ino(inode);
4971 key.type = BTRFS_INODE_ITEM_KEY;
4974 ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4977 } else if (ret > 0) {
4980 struct btrfs_inode_item *item;
4982 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4983 struct btrfs_inode_item);
4984 *size_ret = btrfs_inode_size(path->nodes[0], item);
4986 * If the in-memory inode's i_size is smaller then the inode
4987 * size stored in the btree, return the inode's i_size, so
4988 * that we get a correct inode size after replaying the log
4989 * when before a power failure we had a shrinking truncate
4990 * followed by addition of a new name (rename / new hard link).
4991 * Otherwise return the inode size from the btree, to avoid
4992 * data loss when replaying a log due to previously doing a
4993 * write that expands the inode's size and logging a new name
4994 * immediately after.
4996 if (*size_ret > inode->vfs_inode.i_size)
4997 *size_ret = inode->vfs_inode.i_size;
5000 btrfs_release_path(path);
5005 * At the moment we always log all xattrs. This is to figure out at log replay
5006 * time which xattrs must have their deletion replayed. If a xattr is missing
5007 * in the log tree and exists in the fs/subvol tree, we delete it. This is
5008 * because if a xattr is deleted, the inode is fsynced and a power failure
5009 * happens, causing the log to be replayed the next time the fs is mounted,
5010 * we want the xattr to not exist anymore (same behaviour as other filesystems
5011 * with a journal, ext3/4, xfs, f2fs, etc).
5013 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
5014 struct btrfs_inode *inode,
5015 struct btrfs_path *path,
5016 struct btrfs_path *dst_path)
5018 struct btrfs_root *root = inode->root;
5020 struct btrfs_key key;
5021 const u64 ino = btrfs_ino(inode);
5024 bool found_xattrs = false;
5026 if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5030 key.type = BTRFS_XATTR_ITEM_KEY;
5033 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5038 int slot = path->slots[0];
5039 struct extent_buffer *leaf = path->nodes[0];
5040 int nritems = btrfs_header_nritems(leaf);
5042 if (slot >= nritems) {
5044 ret = copy_items(trans, inode, dst_path, path,
5045 start_slot, ins_nr, 1, 0);
5050 ret = btrfs_next_leaf(root, path);
5058 btrfs_item_key_to_cpu(leaf, &key, slot);
5059 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
5066 found_xattrs = true;
5070 ret = copy_items(trans, inode, dst_path, path,
5071 start_slot, ins_nr, 1, 0);
5077 set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5083 * When using the NO_HOLES feature if we punched a hole that causes the
5084 * deletion of entire leafs or all the extent items of the first leaf (the one
5085 * that contains the inode item and references) we may end up not processing
5086 * any extents, because there are no leafs with a generation matching the
5087 * current transaction that have extent items for our inode. So we need to find
5088 * if any holes exist and then log them. We also need to log holes after any
5089 * truncate operation that changes the inode's size.
5091 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5092 struct btrfs_inode *inode,
5093 struct btrfs_path *path)
5095 struct btrfs_root *root = inode->root;
5096 struct btrfs_fs_info *fs_info = root->fs_info;
5097 struct btrfs_key key;
5098 const u64 ino = btrfs_ino(inode);
5099 const u64 i_size = i_size_read(&inode->vfs_inode);
5100 u64 prev_extent_end = 0;
5103 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5107 key.type = BTRFS_EXTENT_DATA_KEY;
5110 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5115 struct extent_buffer *leaf = path->nodes[0];
5117 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5118 ret = btrfs_next_leaf(root, path);
5125 leaf = path->nodes[0];
5128 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5129 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
5132 /* We have a hole, log it. */
5133 if (prev_extent_end < key.offset) {
5134 const u64 hole_len = key.offset - prev_extent_end;
5137 * Release the path to avoid deadlocks with other code
5138 * paths that search the root while holding locks on
5139 * leafs from the log root.
5141 btrfs_release_path(path);
5142 ret = btrfs_insert_hole_extent(trans, root->log_root,
5143 ino, prev_extent_end,
5149 * Search for the same key again in the root. Since it's
5150 * an extent item and we are holding the inode lock, the
5151 * key must still exist. If it doesn't just emit warning
5152 * and return an error to fall back to a transaction
5155 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5158 if (WARN_ON(ret > 0))
5160 leaf = path->nodes[0];
5163 prev_extent_end = btrfs_file_extent_end(path);
5168 if (prev_extent_end < i_size) {
5171 btrfs_release_path(path);
5172 hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5173 ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5174 prev_extent_end, hole_len);
5183 * When we are logging a new inode X, check if it doesn't have a reference that
5184 * matches the reference from some other inode Y created in a past transaction
5185 * and that was renamed in the current transaction. If we don't do this, then at
5186 * log replay time we can lose inode Y (and all its files if it's a directory):
5189 * echo "hello world" > /mnt/x/foobar
5192 * mkdir /mnt/x # or touch /mnt/x
5193 * xfs_io -c fsync /mnt/x
5195 * mount fs, trigger log replay
5197 * After the log replay procedure, we would lose the first directory and all its
5198 * files (file foobar).
5199 * For the case where inode Y is not a directory we simply end up losing it:
5201 * echo "123" > /mnt/foo
5203 * mv /mnt/foo /mnt/bar
5204 * echo "abc" > /mnt/foo
5205 * xfs_io -c fsync /mnt/foo
5208 * We also need this for cases where a snapshot entry is replaced by some other
5209 * entry (file or directory) otherwise we end up with an unreplayable log due to
5210 * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
5211 * if it were a regular entry:
5214 * btrfs subvolume snapshot /mnt /mnt/x/snap
5215 * btrfs subvolume delete /mnt/x/snap
5218 * fsync /mnt/x or fsync some new file inside it
5221 * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
5222 * the same transaction.
5224 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
5226 const struct btrfs_key *key,
5227 struct btrfs_inode *inode,
5228 u64 *other_ino, u64 *other_parent)
5231 struct btrfs_path *search_path;
5234 u32 item_size = btrfs_item_size(eb, slot);
5236 unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
5238 search_path = btrfs_alloc_path();
5241 search_path->search_commit_root = 1;
5242 search_path->skip_locking = 1;
5244 while (cur_offset < item_size) {
5248 unsigned long name_ptr;
5249 struct btrfs_dir_item *di;
5250 struct fscrypt_str name_str;
5252 if (key->type == BTRFS_INODE_REF_KEY) {
5253 struct btrfs_inode_ref *iref;
5255 iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
5256 parent = key->offset;
5257 this_name_len = btrfs_inode_ref_name_len(eb, iref);
5258 name_ptr = (unsigned long)(iref + 1);
5259 this_len = sizeof(*iref) + this_name_len;
5261 struct btrfs_inode_extref *extref;
5263 extref = (struct btrfs_inode_extref *)(ptr +
5265 parent = btrfs_inode_extref_parent(eb, extref);
5266 this_name_len = btrfs_inode_extref_name_len(eb, extref);
5267 name_ptr = (unsigned long)&extref->name;
5268 this_len = sizeof(*extref) + this_name_len;
5271 if (this_name_len > name_len) {
5274 new_name = krealloc(name, this_name_len, GFP_NOFS);
5279 name_len = this_name_len;
5283 read_extent_buffer(eb, name, name_ptr, this_name_len);
5285 name_str.name = name;
5286 name_str.len = this_name_len;
5287 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5288 parent, &name_str, 0);
5289 if (di && !IS_ERR(di)) {
5290 struct btrfs_key di_key;
5292 btrfs_dir_item_key_to_cpu(search_path->nodes[0],
5294 if (di_key.type == BTRFS_INODE_ITEM_KEY) {
5295 if (di_key.objectid != key->objectid) {
5297 *other_ino = di_key.objectid;
5298 *other_parent = parent;
5306 } else if (IS_ERR(di)) {
5310 btrfs_release_path(search_path);
5312 cur_offset += this_len;
5316 btrfs_free_path(search_path);
5322 * Check if we need to log an inode. This is used in contexts where while
5323 * logging an inode we need to log another inode (either that it exists or in
5324 * full mode). This is used instead of btrfs_inode_in_log() because the later
5325 * requires the inode to be in the log and have the log transaction committed,
5326 * while here we do not care if the log transaction was already committed - our
5327 * caller will commit the log later - and we want to avoid logging an inode
5328 * multiple times when multiple tasks have joined the same log transaction.
5330 static bool need_log_inode(const struct btrfs_trans_handle *trans,
5331 const struct btrfs_inode *inode)
5334 * If a directory was not modified, no dentries added or removed, we can
5335 * and should avoid logging it.
5337 if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5341 * If this inode does not have new/updated/deleted xattrs since the last
5342 * time it was logged and is flagged as logged in the current transaction,
5343 * we can skip logging it. As for new/deleted names, those are updated in
5344 * the log by link/unlink/rename operations.
5345 * In case the inode was logged and then evicted and reloaded, its
5346 * logged_trans will be 0, in which case we have to fully log it since
5347 * logged_trans is a transient field, not persisted.
5349 if (inode->logged_trans == trans->transid &&
5350 !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5356 struct btrfs_dir_list {
5358 struct list_head list;
5362 * Log the inodes of the new dentries of a directory.
5363 * See process_dir_items_leaf() for details about why it is needed.
5364 * This is a recursive operation - if an existing dentry corresponds to a
5365 * directory, that directory's new entries are logged too (same behaviour as
5366 * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5367 * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5368 * complains about the following circular lock dependency / possible deadlock:
5372 * lock(&type->i_mutex_dir_key#3/2);
5373 * lock(sb_internal#2);
5374 * lock(&type->i_mutex_dir_key#3/2);
5375 * lock(&sb->s_type->i_mutex_key#14);
5377 * Where sb_internal is the lock (a counter that works as a lock) acquired by
5378 * sb_start_intwrite() in btrfs_start_transaction().
5379 * Not acquiring the VFS lock of the inodes is still safe because:
5381 * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5382 * that while logging the inode new references (names) are added or removed
5383 * from the inode, leaving the logged inode item with a link count that does
5384 * not match the number of logged inode reference items. This is fine because
5385 * at log replay time we compute the real number of links and correct the
5386 * link count in the inode item (see replay_one_buffer() and
5387 * link_to_fixup_dir());
5389 * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5390 * while logging the inode's items new index items (key type
5391 * BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5392 * has a size that doesn't match the sum of the lengths of all the logged
5393 * names - this is ok, not a problem, because at log replay time we set the
5394 * directory's i_size to the correct value (see replay_one_name() and
5395 * do_overwrite_item()).
5397 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5398 struct btrfs_inode *start_inode,
5399 struct btrfs_log_ctx *ctx)
5401 struct btrfs_root *root = start_inode->root;
5402 struct btrfs_fs_info *fs_info = root->fs_info;
5403 struct btrfs_path *path;
5404 LIST_HEAD(dir_list);
5405 struct btrfs_dir_list *dir_elem;
5406 u64 ino = btrfs_ino(start_inode);
5410 * If we are logging a new name, as part of a link or rename operation,
5411 * don't bother logging new dentries, as we just want to log the names
5412 * of an inode and that any new parents exist.
5414 if (ctx->logging_new_name)
5417 path = btrfs_alloc_path();
5422 struct extent_buffer *leaf;
5423 struct btrfs_key min_key;
5424 bool continue_curr_inode = true;
5428 min_key.objectid = ino;
5429 min_key.type = BTRFS_DIR_INDEX_KEY;
5432 btrfs_release_path(path);
5433 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
5436 } else if (ret > 0) {
5441 leaf = path->nodes[0];
5442 nritems = btrfs_header_nritems(leaf);
5443 for (i = path->slots[0]; i < nritems; i++) {
5444 struct btrfs_dir_item *di;
5445 struct btrfs_key di_key;
5446 struct inode *di_inode;
5447 int log_mode = LOG_INODE_EXISTS;
5450 btrfs_item_key_to_cpu(leaf, &min_key, i);
5451 if (min_key.objectid != ino ||
5452 min_key.type != BTRFS_DIR_INDEX_KEY) {
5453 continue_curr_inode = false;
5457 di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5458 type = btrfs_dir_ftype(leaf, di);
5459 if (btrfs_dir_transid(leaf, di) < trans->transid)
5461 btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5462 if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5465 btrfs_release_path(path);
5466 di_inode = btrfs_iget(fs_info->sb, di_key.objectid, root);
5467 if (IS_ERR(di_inode)) {
5468 ret = PTR_ERR(di_inode);
5472 if (!need_log_inode(trans, BTRFS_I(di_inode))) {
5473 btrfs_add_delayed_iput(di_inode);
5477 ctx->log_new_dentries = false;
5478 if (type == BTRFS_FT_DIR)
5479 log_mode = LOG_INODE_ALL;
5480 ret = btrfs_log_inode(trans, BTRFS_I(di_inode),
5482 btrfs_add_delayed_iput(di_inode);
5485 if (ctx->log_new_dentries) {
5486 dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5491 dir_elem->ino = di_key.objectid;
5492 list_add_tail(&dir_elem->list, &dir_list);
5497 if (continue_curr_inode && min_key.offset < (u64)-1) {
5503 if (list_empty(&dir_list))
5506 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
5507 ino = dir_elem->ino;
5508 list_del(&dir_elem->list);
5512 btrfs_free_path(path);
5514 struct btrfs_dir_list *next;
5516 list_for_each_entry_safe(dir_elem, next, &dir_list, list)
5523 struct btrfs_ino_list {
5526 struct list_head list;
5529 static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
5531 struct btrfs_ino_list *curr;
5532 struct btrfs_ino_list *next;
5534 list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
5535 list_del(&curr->list);
5540 static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
5541 struct btrfs_path *path)
5543 struct btrfs_key key;
5547 key.type = BTRFS_INODE_ITEM_KEY;
5550 path->search_commit_root = 1;
5551 path->skip_locking = 1;
5553 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5554 if (WARN_ON_ONCE(ret > 0)) {
5556 * We have previously found the inode through the commit root
5557 * so this should not happen. If it does, just error out and
5558 * fallback to a transaction commit.
5561 } else if (ret == 0) {
5562 struct btrfs_inode_item *item;
5564 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5565 struct btrfs_inode_item);
5566 if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
5570 btrfs_release_path(path);
5571 path->search_commit_root = 0;
5572 path->skip_locking = 0;
5577 static int add_conflicting_inode(struct btrfs_trans_handle *trans,
5578 struct btrfs_root *root,
5579 struct btrfs_path *path,
5580 u64 ino, u64 parent,
5581 struct btrfs_log_ctx *ctx)
5583 struct btrfs_ino_list *ino_elem;
5584 struct inode *inode;
5587 * It's rare to have a lot of conflicting inodes, in practice it is not
5588 * common to have more than 1 or 2. We don't want to collect too many,
5589 * as we could end up logging too many inodes (even if only in
5590 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
5593 if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES)
5594 return BTRFS_LOG_FORCE_COMMIT;
5596 inode = btrfs_iget(root->fs_info->sb, ino, root);
5598 * If the other inode that had a conflicting dir entry was deleted in
5599 * the current transaction then we either:
5601 * 1) Log the parent directory (later after adding it to the list) if
5602 * the inode is a directory. This is because it may be a deleted
5603 * subvolume/snapshot or it may be a regular directory that had
5604 * deleted subvolumes/snapshots (or subdirectories that had them),
5605 * and at the moment we can't deal with dropping subvolumes/snapshots
5606 * during log replay. So we just log the parent, which will result in
5607 * a fallback to a transaction commit if we are dealing with those
5608 * cases (last_unlink_trans will match the current transaction);
5610 * 2) Do nothing if it's not a directory. During log replay we simply
5611 * unlink the conflicting dentry from the parent directory and then
5612 * add the dentry for our inode. Like this we can avoid logging the
5613 * parent directory (and maybe fallback to a transaction commit in
5614 * case it has a last_unlink_trans == trans->transid, due to moving
5615 * some inode from it to some other directory).
5617 if (IS_ERR(inode)) {
5618 int ret = PTR_ERR(inode);
5623 ret = conflicting_inode_is_dir(root, ino, path);
5624 /* Not a directory or we got an error. */
5628 /* Conflicting inode is a directory, so we'll log its parent. */
5629 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5632 ino_elem->ino = ino;
5633 ino_elem->parent = parent;
5634 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5635 ctx->num_conflict_inodes++;
5641 * If the inode was already logged skip it - otherwise we can hit an
5642 * infinite loop. Example:
5644 * From the commit root (previous transaction) we have the following
5647 * inode 257 a directory
5648 * inode 258 with references "zz" and "zz_link" on inode 257
5649 * inode 259 with reference "a" on inode 257
5651 * And in the current (uncommitted) transaction we have:
5653 * inode 257 a directory, unchanged
5654 * inode 258 with references "a" and "a2" on inode 257
5655 * inode 259 with reference "zz_link" on inode 257
5656 * inode 261 with reference "zz" on inode 257
5658 * When logging inode 261 the following infinite loop could
5659 * happen if we don't skip already logged inodes:
5661 * - we detect inode 258 as a conflicting inode, with inode 261
5662 * on reference "zz", and log it;
5664 * - we detect inode 259 as a conflicting inode, with inode 258
5665 * on reference "a", and log it;
5667 * - we detect inode 258 as a conflicting inode, with inode 259
5668 * on reference "zz_link", and log it - again! After this we
5669 * repeat the above steps forever.
5671 * Here we can use need_log_inode() because we only need to log the
5672 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
5673 * so that the log ends up with the new name and without the old name.
5675 if (!need_log_inode(trans, BTRFS_I(inode))) {
5676 btrfs_add_delayed_iput(inode);
5680 btrfs_add_delayed_iput(inode);
5682 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5685 ino_elem->ino = ino;
5686 ino_elem->parent = parent;
5687 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5688 ctx->num_conflict_inodes++;
5693 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
5694 struct btrfs_root *root,
5695 struct btrfs_log_ctx *ctx)
5697 struct btrfs_fs_info *fs_info = root->fs_info;
5701 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
5702 * otherwise we could have unbounded recursion of btrfs_log_inode()
5703 * calls. This check guarantees we can have only 1 level of recursion.
5705 if (ctx->logging_conflict_inodes)
5708 ctx->logging_conflict_inodes = true;
5711 * New conflicting inodes may be found and added to the list while we
5712 * are logging a conflicting inode, so keep iterating while the list is
5715 while (!list_empty(&ctx->conflict_inodes)) {
5716 struct btrfs_ino_list *curr;
5717 struct inode *inode;
5721 curr = list_first_entry(&ctx->conflict_inodes,
5722 struct btrfs_ino_list, list);
5724 parent = curr->parent;
5725 list_del(&curr->list);
5728 inode = btrfs_iget(fs_info->sb, ino, root);
5730 * If the other inode that had a conflicting dir entry was
5731 * deleted in the current transaction, we need to log its parent
5732 * directory. See the comment at add_conflicting_inode().
5734 if (IS_ERR(inode)) {
5735 ret = PTR_ERR(inode);
5739 inode = btrfs_iget(fs_info->sb, parent, root);
5740 if (IS_ERR(inode)) {
5741 ret = PTR_ERR(inode);
5746 * Always log the directory, we cannot make this
5747 * conditional on need_log_inode() because the directory
5748 * might have been logged in LOG_INODE_EXISTS mode or
5749 * the dir index of the conflicting inode is not in a
5750 * dir index key range logged for the directory. So we
5751 * must make sure the deletion is recorded.
5753 ret = btrfs_log_inode(trans, BTRFS_I(inode),
5754 LOG_INODE_ALL, ctx);
5755 btrfs_add_delayed_iput(inode);
5762 * Here we can use need_log_inode() because we only need to log
5763 * the inode in LOG_INODE_EXISTS mode and rename operations
5764 * update the log, so that the log ends up with the new name and
5765 * without the old name.
5767 * We did this check at add_conflicting_inode(), but here we do
5768 * it again because if some other task logged the inode after
5769 * that, we can avoid doing it again.
5771 if (!need_log_inode(trans, BTRFS_I(inode))) {
5772 btrfs_add_delayed_iput(inode);
5777 * We are safe logging the other inode without acquiring its
5778 * lock as long as we log with the LOG_INODE_EXISTS mode. We
5779 * are safe against concurrent renames of the other inode as
5780 * well because during a rename we pin the log and update the
5781 * log with the new name before we unpin it.
5783 ret = btrfs_log_inode(trans, BTRFS_I(inode), LOG_INODE_EXISTS, ctx);
5784 btrfs_add_delayed_iput(inode);
5789 ctx->logging_conflict_inodes = false;
5791 free_conflicting_inodes(ctx);
5796 static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
5797 struct btrfs_inode *inode,
5798 struct btrfs_key *min_key,
5799 const struct btrfs_key *max_key,
5800 struct btrfs_path *path,
5801 struct btrfs_path *dst_path,
5802 const u64 logged_isize,
5803 const int inode_only,
5804 struct btrfs_log_ctx *ctx,
5805 bool *need_log_inode_item)
5807 const u64 i_size = i_size_read(&inode->vfs_inode);
5808 struct btrfs_root *root = inode->root;
5809 int ins_start_slot = 0;
5814 ret = btrfs_search_forward(root, min_key, path, trans->transid);
5822 /* Note, ins_nr might be > 0 here, cleanup outside the loop */
5823 if (min_key->objectid != max_key->objectid)
5825 if (min_key->type > max_key->type)
5828 if (min_key->type == BTRFS_INODE_ITEM_KEY) {
5829 *need_log_inode_item = false;
5830 } else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
5831 min_key->offset >= i_size) {
5833 * Extents at and beyond eof are logged with
5834 * btrfs_log_prealloc_extents().
5835 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
5836 * and no keys greater than that, so bail out.
5839 } else if ((min_key->type == BTRFS_INODE_REF_KEY ||
5840 min_key->type == BTRFS_INODE_EXTREF_KEY) &&
5841 (inode->generation == trans->transid ||
5842 ctx->logging_conflict_inodes)) {
5844 u64 other_parent = 0;
5846 ret = btrfs_check_ref_name_override(path->nodes[0],
5847 path->slots[0], min_key, inode,
5848 &other_ino, &other_parent);
5851 } else if (ret > 0 &&
5852 other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5857 ins_start_slot = path->slots[0];
5859 ret = copy_items(trans, inode, dst_path, path,
5860 ins_start_slot, ins_nr,
5861 inode_only, logged_isize);
5866 btrfs_release_path(path);
5867 ret = add_conflicting_inode(trans, root, path,
5874 } else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
5875 /* Skip xattrs, logged later with btrfs_log_all_xattrs() */
5878 ret = copy_items(trans, inode, dst_path, path,
5880 ins_nr, inode_only, logged_isize);
5887 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5890 } else if (!ins_nr) {
5891 ins_start_slot = path->slots[0];
5896 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5897 ins_nr, inode_only, logged_isize);
5901 ins_start_slot = path->slots[0];
5904 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
5905 btrfs_item_key_to_cpu(path->nodes[0], min_key,
5910 ret = copy_items(trans, inode, dst_path, path,
5911 ins_start_slot, ins_nr, inode_only,
5917 btrfs_release_path(path);
5919 if (min_key->offset < (u64)-1) {
5921 } else if (min_key->type < max_key->type) {
5923 min_key->offset = 0;
5929 * We may process many leaves full of items for our inode, so
5930 * avoid monopolizing a cpu for too long by rescheduling while
5931 * not holding locks on any tree.
5936 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5937 ins_nr, inode_only, logged_isize);
5942 if (inode_only == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
5944 * Release the path because otherwise we might attempt to double
5945 * lock the same leaf with btrfs_log_prealloc_extents() below.
5947 btrfs_release_path(path);
5948 ret = btrfs_log_prealloc_extents(trans, inode, dst_path);
5954 static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
5955 struct btrfs_root *log,
5956 struct btrfs_path *path,
5957 const struct btrfs_item_batch *batch,
5958 const struct btrfs_delayed_item *first_item)
5960 const struct btrfs_delayed_item *curr = first_item;
5963 ret = btrfs_insert_empty_items(trans, log, path, batch);
5967 for (int i = 0; i < batch->nr; i++) {
5970 data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
5971 write_extent_buffer(path->nodes[0], &curr->data,
5972 (unsigned long)data_ptr, curr->data_len);
5973 curr = list_next_entry(curr, log_list);
5977 btrfs_release_path(path);
5982 static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
5983 struct btrfs_inode *inode,
5984 struct btrfs_path *path,
5985 const struct list_head *delayed_ins_list,
5986 struct btrfs_log_ctx *ctx)
5988 /* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
5989 const int max_batch_size = 195;
5990 const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
5991 const u64 ino = btrfs_ino(inode);
5992 struct btrfs_root *log = inode->root->log_root;
5993 struct btrfs_item_batch batch = {
5995 .total_data_size = 0,
5997 const struct btrfs_delayed_item *first = NULL;
5998 const struct btrfs_delayed_item *curr;
6000 struct btrfs_key *ins_keys;
6002 u64 curr_batch_size = 0;
6006 /* We are adding dir index items to the log tree. */
6007 lockdep_assert_held(&inode->log_mutex);
6010 * We collect delayed items before copying index keys from the subvolume
6011 * to the log tree. However just after we collected them, they may have
6012 * been flushed (all of them or just some of them), and therefore we
6013 * could have copied them from the subvolume tree to the log tree.
6014 * So find the first delayed item that was not yet logged (they are
6015 * sorted by index number).
6017 list_for_each_entry(curr, delayed_ins_list, log_list) {
6018 if (curr->index > inode->last_dir_index_offset) {
6024 /* Empty list or all delayed items were already logged. */
6028 ins_data = kmalloc(max_batch_size * sizeof(u32) +
6029 max_batch_size * sizeof(struct btrfs_key), GFP_NOFS);
6032 ins_sizes = (u32 *)ins_data;
6033 batch.data_sizes = ins_sizes;
6034 ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
6035 batch.keys = ins_keys;
6038 while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
6039 const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
6041 if (curr_batch_size + curr_size > leaf_data_size ||
6042 batch.nr == max_batch_size) {
6043 ret = insert_delayed_items_batch(trans, log, path,
6049 batch.total_data_size = 0;
6050 curr_batch_size = 0;
6054 ins_sizes[batch_idx] = curr->data_len;
6055 ins_keys[batch_idx].objectid = ino;
6056 ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
6057 ins_keys[batch_idx].offset = curr->index;
6058 curr_batch_size += curr_size;
6059 batch.total_data_size += curr->data_len;
6062 curr = list_next_entry(curr, log_list);
6065 ASSERT(batch.nr >= 1);
6066 ret = insert_delayed_items_batch(trans, log, path, &batch, first);
6068 curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
6070 inode->last_dir_index_offset = curr->index;
6077 static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
6078 struct btrfs_inode *inode,
6079 struct btrfs_path *path,
6080 const struct list_head *delayed_del_list,
6081 struct btrfs_log_ctx *ctx)
6083 const u64 ino = btrfs_ino(inode);
6084 const struct btrfs_delayed_item *curr;
6086 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6089 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6090 u64 first_dir_index = curr->index;
6092 const struct btrfs_delayed_item *next;
6096 * Find a range of consecutive dir index items to delete. Like
6097 * this we log a single dir range item spanning several contiguous
6098 * dir items instead of logging one range item per dir index item.
6100 next = list_next_entry(curr, log_list);
6101 while (!list_entry_is_head(next, delayed_del_list, log_list)) {
6102 if (next->index != curr->index + 1)
6105 next = list_next_entry(next, log_list);
6108 last_dir_index = curr->index;
6109 ASSERT(last_dir_index >= first_dir_index);
6111 ret = insert_dir_log_key(trans, inode->root->log_root, path,
6112 ino, first_dir_index, last_dir_index);
6115 curr = list_next_entry(curr, log_list);
6121 static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
6122 struct btrfs_inode *inode,
6123 struct btrfs_path *path,
6124 struct btrfs_log_ctx *ctx,
6125 const struct list_head *delayed_del_list,
6126 const struct btrfs_delayed_item *first,
6127 const struct btrfs_delayed_item **last_ret)
6129 const struct btrfs_delayed_item *next;
6130 struct extent_buffer *leaf = path->nodes[0];
6131 const int last_slot = btrfs_header_nritems(leaf) - 1;
6132 int slot = path->slots[0] + 1;
6133 const u64 ino = btrfs_ino(inode);
6135 next = list_next_entry(first, log_list);
6137 while (slot < last_slot &&
6138 !list_entry_is_head(next, delayed_del_list, log_list)) {
6139 struct btrfs_key key;
6141 btrfs_item_key_to_cpu(leaf, &key, slot);
6142 if (key.objectid != ino ||
6143 key.type != BTRFS_DIR_INDEX_KEY ||
6144 key.offset != next->index)
6149 next = list_next_entry(next, log_list);
6152 return btrfs_del_items(trans, inode->root->log_root, path,
6153 path->slots[0], slot - path->slots[0]);
6156 static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
6157 struct btrfs_inode *inode,
6158 struct btrfs_path *path,
6159 const struct list_head *delayed_del_list,
6160 struct btrfs_log_ctx *ctx)
6162 struct btrfs_root *log = inode->root->log_root;
6163 const struct btrfs_delayed_item *curr;
6164 u64 last_range_start;
6165 u64 last_range_end = 0;
6166 struct btrfs_key key;
6168 key.objectid = btrfs_ino(inode);
6169 key.type = BTRFS_DIR_INDEX_KEY;
6170 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6173 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6174 const struct btrfs_delayed_item *last = curr;
6175 u64 first_dir_index = curr->index;
6177 bool deleted_items = false;
6180 key.offset = curr->index;
6181 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
6184 } else if (ret == 0) {
6185 ret = batch_delete_dir_index_items(trans, inode, path, ctx,
6186 delayed_del_list, curr,
6190 deleted_items = true;
6193 btrfs_release_path(path);
6196 * If we deleted items from the leaf, it means we have a range
6197 * item logging their range, so no need to add one or update an
6198 * existing one. Otherwise we have to log a dir range item.
6203 last_dir_index = last->index;
6204 ASSERT(last_dir_index >= first_dir_index);
6206 * If this range starts right after where the previous one ends,
6207 * then we want to reuse the previous range item and change its
6208 * end offset to the end of this range. This is just to minimize
6209 * leaf space usage, by avoiding adding a new range item.
6211 if (last_range_end != 0 && first_dir_index == last_range_end + 1)
6212 first_dir_index = last_range_start;
6214 ret = insert_dir_log_key(trans, log, path, key.objectid,
6215 first_dir_index, last_dir_index);
6219 last_range_start = first_dir_index;
6220 last_range_end = last_dir_index;
6222 curr = list_next_entry(last, log_list);
6228 static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
6229 struct btrfs_inode *inode,
6230 struct btrfs_path *path,
6231 const struct list_head *delayed_del_list,
6232 struct btrfs_log_ctx *ctx)
6235 * We are deleting dir index items from the log tree or adding range
6238 lockdep_assert_held(&inode->log_mutex);
6240 if (list_empty(delayed_del_list))
6243 if (ctx->logged_before)
6244 return log_delayed_deletions_incremental(trans, inode, path,
6245 delayed_del_list, ctx);
6247 return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
6252 * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
6253 * items instead of the subvolume tree.
6255 static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
6256 struct btrfs_inode *inode,
6257 const struct list_head *delayed_ins_list,
6258 struct btrfs_log_ctx *ctx)
6260 const bool orig_log_new_dentries = ctx->log_new_dentries;
6261 struct btrfs_fs_info *fs_info = trans->fs_info;
6262 struct btrfs_delayed_item *item;
6266 * No need for the log mutex, plus to avoid potential deadlocks or
6267 * lockdep annotations due to nesting of delayed inode mutexes and log
6270 lockdep_assert_not_held(&inode->log_mutex);
6272 ASSERT(!ctx->logging_new_delayed_dentries);
6273 ctx->logging_new_delayed_dentries = true;
6275 list_for_each_entry(item, delayed_ins_list, log_list) {
6276 struct btrfs_dir_item *dir_item;
6277 struct inode *di_inode;
6278 struct btrfs_key key;
6279 int log_mode = LOG_INODE_EXISTS;
6281 dir_item = (struct btrfs_dir_item *)item->data;
6282 btrfs_disk_key_to_cpu(&key, &dir_item->location);
6284 if (key.type == BTRFS_ROOT_ITEM_KEY)
6287 di_inode = btrfs_iget(fs_info->sb, key.objectid, inode->root);
6288 if (IS_ERR(di_inode)) {
6289 ret = PTR_ERR(di_inode);
6293 if (!need_log_inode(trans, BTRFS_I(di_inode))) {
6294 btrfs_add_delayed_iput(di_inode);
6298 if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
6299 log_mode = LOG_INODE_ALL;
6301 ctx->log_new_dentries = false;
6302 ret = btrfs_log_inode(trans, BTRFS_I(di_inode), log_mode, ctx);
6304 if (!ret && ctx->log_new_dentries)
6305 ret = log_new_dir_dentries(trans, BTRFS_I(di_inode), ctx);
6307 btrfs_add_delayed_iput(di_inode);
6313 ctx->log_new_dentries = orig_log_new_dentries;
6314 ctx->logging_new_delayed_dentries = false;
6319 /* log a single inode in the tree log.
6320 * At least one parent directory for this inode must exist in the tree
6321 * or be logged already.
6323 * Any items from this inode changed by the current transaction are copied
6324 * to the log tree. An extra reference is taken on any extents in this
6325 * file, allowing us to avoid a whole pile of corner cases around logging
6326 * blocks that have been removed from the tree.
6328 * See LOG_INODE_ALL and related defines for a description of what inode_only
6331 * This handles both files and directories.
6333 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
6334 struct btrfs_inode *inode,
6336 struct btrfs_log_ctx *ctx)
6338 struct btrfs_path *path;
6339 struct btrfs_path *dst_path;
6340 struct btrfs_key min_key;
6341 struct btrfs_key max_key;
6342 struct btrfs_root *log = inode->root->log_root;
6344 bool fast_search = false;
6345 u64 ino = btrfs_ino(inode);
6346 struct extent_map_tree *em_tree = &inode->extent_tree;
6347 u64 logged_isize = 0;
6348 bool need_log_inode_item = true;
6349 bool xattrs_logged = false;
6350 bool inode_item_dropped = true;
6351 bool full_dir_logging = false;
6352 LIST_HEAD(delayed_ins_list);
6353 LIST_HEAD(delayed_del_list);
6355 path = btrfs_alloc_path();
6358 dst_path = btrfs_alloc_path();
6360 btrfs_free_path(path);
6364 min_key.objectid = ino;
6365 min_key.type = BTRFS_INODE_ITEM_KEY;
6368 max_key.objectid = ino;
6371 /* today the code can only do partial logging of directories */
6372 if (S_ISDIR(inode->vfs_inode.i_mode) ||
6373 (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6374 &inode->runtime_flags) &&
6375 inode_only >= LOG_INODE_EXISTS))
6376 max_key.type = BTRFS_XATTR_ITEM_KEY;
6378 max_key.type = (u8)-1;
6379 max_key.offset = (u64)-1;
6381 if (S_ISDIR(inode->vfs_inode.i_mode) && inode_only == LOG_INODE_ALL)
6382 full_dir_logging = true;
6385 * If we are logging a directory while we are logging dentries of the
6386 * delayed items of some other inode, then we need to flush the delayed
6387 * items of this directory and not log the delayed items directly. This
6388 * is to prevent more than one level of recursion into btrfs_log_inode()
6389 * by having something like this:
6391 * $ mkdir -p a/b/c/d/e/f/g/h/...
6392 * $ xfs_io -c "fsync" a
6394 * Where all directories in the path did not exist before and are
6395 * created in the current transaction.
6396 * So in such a case we directly log the delayed items of the main
6397 * directory ("a") without flushing them first, while for each of its
6398 * subdirectories we flush their delayed items before logging them.
6399 * This prevents a potential unbounded recursion like this:
6402 * log_new_delayed_dentries()
6404 * log_new_delayed_dentries()
6406 * log_new_delayed_dentries()
6409 * We have thresholds for the maximum number of delayed items to have in
6410 * memory, and once they are hit, the items are flushed asynchronously.
6411 * However the limit is quite high, so lets prevent deep levels of
6412 * recursion to happen by limiting the maximum depth to be 1.
6414 if (full_dir_logging && ctx->logging_new_delayed_dentries) {
6415 ret = btrfs_commit_inode_delayed_items(trans, inode);
6420 mutex_lock(&inode->log_mutex);
6423 * For symlinks, we must always log their content, which is stored in an
6424 * inline extent, otherwise we could end up with an empty symlink after
6425 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
6426 * one attempts to create an empty symlink).
6427 * We don't need to worry about flushing delalloc, because when we create
6428 * the inline extent when the symlink is created (we never have delalloc
6431 if (S_ISLNK(inode->vfs_inode.i_mode))
6432 inode_only = LOG_INODE_ALL;
6435 * Before logging the inode item, cache the value returned by
6436 * inode_logged(), because after that we have the need to figure out if
6437 * the inode was previously logged in this transaction.
6439 ret = inode_logged(trans, inode, path);
6442 ctx->logged_before = (ret == 1);
6446 * This is for cases where logging a directory could result in losing a
6447 * a file after replaying the log. For example, if we move a file from a
6448 * directory A to a directory B, then fsync directory A, we have no way
6449 * to known the file was moved from A to B, so logging just A would
6450 * result in losing the file after a log replay.
6452 if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
6453 btrfs_set_log_full_commit(trans);
6454 ret = BTRFS_LOG_FORCE_COMMIT;
6459 * a brute force approach to making sure we get the most uptodate
6460 * copies of everything.
6462 if (S_ISDIR(inode->vfs_inode.i_mode)) {
6463 clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
6464 if (ctx->logged_before)
6465 ret = drop_inode_items(trans, log, path, inode,
6466 BTRFS_XATTR_ITEM_KEY);
6468 if (inode_only == LOG_INODE_EXISTS && ctx->logged_before) {
6470 * Make sure the new inode item we write to the log has
6471 * the same isize as the current one (if it exists).
6472 * This is necessary to prevent data loss after log
6473 * replay, and also to prevent doing a wrong expanding
6474 * truncate - for e.g. create file, write 4K into offset
6475 * 0, fsync, write 4K into offset 4096, add hard link,
6476 * fsync some other file (to sync log), power fail - if
6477 * we use the inode's current i_size, after log replay
6478 * we get a 8Kb file, with the last 4Kb extent as a hole
6479 * (zeroes), as if an expanding truncate happened,
6480 * instead of getting a file of 4Kb only.
6482 ret = logged_inode_size(log, inode, path, &logged_isize);
6486 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6487 &inode->runtime_flags)) {
6488 if (inode_only == LOG_INODE_EXISTS) {
6489 max_key.type = BTRFS_XATTR_ITEM_KEY;
6490 if (ctx->logged_before)
6491 ret = drop_inode_items(trans, log, path,
6492 inode, max_key.type);
6494 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6495 &inode->runtime_flags);
6496 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6497 &inode->runtime_flags);
6498 if (ctx->logged_before)
6499 ret = truncate_inode_items(trans, log,
6502 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6503 &inode->runtime_flags) ||
6504 inode_only == LOG_INODE_EXISTS) {
6505 if (inode_only == LOG_INODE_ALL)
6507 max_key.type = BTRFS_XATTR_ITEM_KEY;
6508 if (ctx->logged_before)
6509 ret = drop_inode_items(trans, log, path, inode,
6512 if (inode_only == LOG_INODE_ALL)
6514 inode_item_dropped = false;
6523 * If we are logging a directory in full mode, collect the delayed items
6524 * before iterating the subvolume tree, so that we don't miss any new
6525 * dir index items in case they get flushed while or right after we are
6526 * iterating the subvolume tree.
6528 if (full_dir_logging && !ctx->logging_new_delayed_dentries)
6529 btrfs_log_get_delayed_items(inode, &delayed_ins_list,
6532 ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
6533 path, dst_path, logged_isize,
6535 &need_log_inode_item);
6539 btrfs_release_path(path);
6540 btrfs_release_path(dst_path);
6541 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
6544 xattrs_logged = true;
6545 if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
6546 btrfs_release_path(path);
6547 btrfs_release_path(dst_path);
6548 ret = btrfs_log_holes(trans, inode, path);
6553 btrfs_release_path(path);
6554 btrfs_release_path(dst_path);
6555 if (need_log_inode_item) {
6556 ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
6560 * If we are doing a fast fsync and the inode was logged before
6561 * in this transaction, we don't need to log the xattrs because
6562 * they were logged before. If xattrs were added, changed or
6563 * deleted since the last time we logged the inode, then we have
6564 * already logged them because the inode had the runtime flag
6565 * BTRFS_INODE_COPY_EVERYTHING set.
6567 if (!xattrs_logged && inode->logged_trans < trans->transid) {
6568 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
6571 btrfs_release_path(path);
6575 ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
6578 } else if (inode_only == LOG_INODE_ALL) {
6579 struct extent_map *em, *n;
6581 write_lock(&em_tree->lock);
6582 list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
6583 list_del_init(&em->list);
6584 write_unlock(&em_tree->lock);
6587 if (full_dir_logging) {
6588 ret = log_directory_changes(trans, inode, path, dst_path, ctx);
6591 ret = log_delayed_insertion_items(trans, inode, path,
6592 &delayed_ins_list, ctx);
6595 ret = log_delayed_deletion_items(trans, inode, path,
6596 &delayed_del_list, ctx);
6601 spin_lock(&inode->lock);
6602 inode->logged_trans = trans->transid;
6604 * Don't update last_log_commit if we logged that an inode exists.
6605 * We do this for three reasons:
6607 * 1) We might have had buffered writes to this inode that were
6608 * flushed and had their ordered extents completed in this
6609 * transaction, but we did not previously log the inode with
6610 * LOG_INODE_ALL. Later the inode was evicted and after that
6611 * it was loaded again and this LOG_INODE_EXISTS log operation
6612 * happened. We must make sure that if an explicit fsync against
6613 * the inode is performed later, it logs the new extents, an
6614 * updated inode item, etc, and syncs the log. The same logic
6615 * applies to direct IO writes instead of buffered writes.
6617 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
6618 * is logged with an i_size of 0 or whatever value was logged
6619 * before. If later the i_size of the inode is increased by a
6620 * truncate operation, the log is synced through an fsync of
6621 * some other inode and then finally an explicit fsync against
6622 * this inode is made, we must make sure this fsync logs the
6623 * inode with the new i_size, the hole between old i_size and
6624 * the new i_size, and syncs the log.
6626 * 3) If we are logging that an ancestor inode exists as part of
6627 * logging a new name from a link or rename operation, don't update
6628 * its last_log_commit - otherwise if an explicit fsync is made
6629 * against an ancestor, the fsync considers the inode in the log
6630 * and doesn't sync the log, resulting in the ancestor missing after
6631 * a power failure unless the log was synced as part of an fsync
6632 * against any other unrelated inode.
6634 if (inode_only != LOG_INODE_EXISTS)
6635 inode->last_log_commit = inode->last_sub_trans;
6636 spin_unlock(&inode->lock);
6639 * Reset the last_reflink_trans so that the next fsync does not need to
6640 * go through the slower path when logging extents and their checksums.
6642 if (inode_only == LOG_INODE_ALL)
6643 inode->last_reflink_trans = 0;
6646 mutex_unlock(&inode->log_mutex);
6648 btrfs_free_path(path);
6649 btrfs_free_path(dst_path);
6652 free_conflicting_inodes(ctx);
6654 ret = log_conflicting_inodes(trans, inode->root, ctx);
6656 if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
6658 ret = log_new_delayed_dentries(trans, inode,
6659 &delayed_ins_list, ctx);
6661 btrfs_log_put_delayed_items(inode, &delayed_ins_list,
6668 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
6669 struct btrfs_inode *inode,
6670 struct btrfs_log_ctx *ctx)
6672 struct btrfs_fs_info *fs_info = trans->fs_info;
6674 struct btrfs_path *path;
6675 struct btrfs_key key;
6676 struct btrfs_root *root = inode->root;
6677 const u64 ino = btrfs_ino(inode);
6679 path = btrfs_alloc_path();
6682 path->skip_locking = 1;
6683 path->search_commit_root = 1;
6686 key.type = BTRFS_INODE_REF_KEY;
6688 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6693 struct extent_buffer *leaf = path->nodes[0];
6694 int slot = path->slots[0];
6699 if (slot >= btrfs_header_nritems(leaf)) {
6700 ret = btrfs_next_leaf(root, path);
6708 btrfs_item_key_to_cpu(leaf, &key, slot);
6709 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
6710 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
6713 item_size = btrfs_item_size(leaf, slot);
6714 ptr = btrfs_item_ptr_offset(leaf, slot);
6715 while (cur_offset < item_size) {
6716 struct btrfs_key inode_key;
6717 struct inode *dir_inode;
6719 inode_key.type = BTRFS_INODE_ITEM_KEY;
6720 inode_key.offset = 0;
6722 if (key.type == BTRFS_INODE_EXTREF_KEY) {
6723 struct btrfs_inode_extref *extref;
6725 extref = (struct btrfs_inode_extref *)
6727 inode_key.objectid = btrfs_inode_extref_parent(
6729 cur_offset += sizeof(*extref);
6730 cur_offset += btrfs_inode_extref_name_len(leaf,
6733 inode_key.objectid = key.offset;
6734 cur_offset = item_size;
6737 dir_inode = btrfs_iget(fs_info->sb, inode_key.objectid,
6740 * If the parent inode was deleted, return an error to
6741 * fallback to a transaction commit. This is to prevent
6742 * getting an inode that was moved from one parent A to
6743 * a parent B, got its former parent A deleted and then
6744 * it got fsync'ed, from existing at both parents after
6745 * a log replay (and the old parent still existing).
6752 * mv /mnt/B/bar /mnt/A/bar
6753 * mv -T /mnt/A /mnt/B
6757 * If we ignore the old parent B which got deleted,
6758 * after a log replay we would have file bar linked
6759 * at both parents and the old parent B would still
6762 if (IS_ERR(dir_inode)) {
6763 ret = PTR_ERR(dir_inode);
6767 if (!need_log_inode(trans, BTRFS_I(dir_inode))) {
6768 btrfs_add_delayed_iput(dir_inode);
6772 ctx->log_new_dentries = false;
6773 ret = btrfs_log_inode(trans, BTRFS_I(dir_inode),
6774 LOG_INODE_ALL, ctx);
6775 if (!ret && ctx->log_new_dentries)
6776 ret = log_new_dir_dentries(trans,
6777 BTRFS_I(dir_inode), ctx);
6778 btrfs_add_delayed_iput(dir_inode);
6786 btrfs_free_path(path);
6790 static int log_new_ancestors(struct btrfs_trans_handle *trans,
6791 struct btrfs_root *root,
6792 struct btrfs_path *path,
6793 struct btrfs_log_ctx *ctx)
6795 struct btrfs_key found_key;
6797 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
6800 struct btrfs_fs_info *fs_info = root->fs_info;
6801 struct extent_buffer *leaf = path->nodes[0];
6802 int slot = path->slots[0];
6803 struct btrfs_key search_key;
6804 struct inode *inode;
6808 btrfs_release_path(path);
6810 ino = found_key.offset;
6812 search_key.objectid = found_key.offset;
6813 search_key.type = BTRFS_INODE_ITEM_KEY;
6814 search_key.offset = 0;
6815 inode = btrfs_iget(fs_info->sb, ino, root);
6817 return PTR_ERR(inode);
6819 if (BTRFS_I(inode)->generation >= trans->transid &&
6820 need_log_inode(trans, BTRFS_I(inode)))
6821 ret = btrfs_log_inode(trans, BTRFS_I(inode),
6822 LOG_INODE_EXISTS, ctx);
6823 btrfs_add_delayed_iput(inode);
6827 if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
6830 search_key.type = BTRFS_INODE_REF_KEY;
6831 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6835 leaf = path->nodes[0];
6836 slot = path->slots[0];
6837 if (slot >= btrfs_header_nritems(leaf)) {
6838 ret = btrfs_next_leaf(root, path);
6843 leaf = path->nodes[0];
6844 slot = path->slots[0];
6847 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6848 if (found_key.objectid != search_key.objectid ||
6849 found_key.type != BTRFS_INODE_REF_KEY)
6855 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
6856 struct btrfs_inode *inode,
6857 struct dentry *parent,
6858 struct btrfs_log_ctx *ctx)
6860 struct btrfs_root *root = inode->root;
6861 struct dentry *old_parent = NULL;
6862 struct super_block *sb = inode->vfs_inode.i_sb;
6866 if (!parent || d_really_is_negative(parent) ||
6870 inode = BTRFS_I(d_inode(parent));
6871 if (root != inode->root)
6874 if (inode->generation >= trans->transid &&
6875 need_log_inode(trans, inode)) {
6876 ret = btrfs_log_inode(trans, inode,
6877 LOG_INODE_EXISTS, ctx);
6881 if (IS_ROOT(parent))
6884 parent = dget_parent(parent);
6886 old_parent = parent;
6893 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
6894 struct btrfs_inode *inode,
6895 struct dentry *parent,
6896 struct btrfs_log_ctx *ctx)
6898 struct btrfs_root *root = inode->root;
6899 const u64 ino = btrfs_ino(inode);
6900 struct btrfs_path *path;
6901 struct btrfs_key search_key;
6905 * For a single hard link case, go through a fast path that does not
6906 * need to iterate the fs/subvolume tree.
6908 if (inode->vfs_inode.i_nlink < 2)
6909 return log_new_ancestors_fast(trans, inode, parent, ctx);
6911 path = btrfs_alloc_path();
6915 search_key.objectid = ino;
6916 search_key.type = BTRFS_INODE_REF_KEY;
6917 search_key.offset = 0;
6919 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6926 struct extent_buffer *leaf = path->nodes[0];
6927 int slot = path->slots[0];
6928 struct btrfs_key found_key;
6930 if (slot >= btrfs_header_nritems(leaf)) {
6931 ret = btrfs_next_leaf(root, path);
6939 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6940 if (found_key.objectid != ino ||
6941 found_key.type > BTRFS_INODE_EXTREF_KEY)
6945 * Don't deal with extended references because they are rare
6946 * cases and too complex to deal with (we would need to keep
6947 * track of which subitem we are processing for each item in
6948 * this loop, etc). So just return some error to fallback to
6949 * a transaction commit.
6951 if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
6957 * Logging ancestors needs to do more searches on the fs/subvol
6958 * tree, so it releases the path as needed to avoid deadlocks.
6959 * Keep track of the last inode ref key and resume from that key
6960 * after logging all new ancestors for the current hard link.
6962 memcpy(&search_key, &found_key, sizeof(search_key));
6964 ret = log_new_ancestors(trans, root, path, ctx);
6967 btrfs_release_path(path);
6972 btrfs_free_path(path);
6977 * helper function around btrfs_log_inode to make sure newly created
6978 * parent directories also end up in the log. A minimal inode and backref
6979 * only logging is done of any parent directories that are older than
6980 * the last committed transaction
6982 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
6983 struct btrfs_inode *inode,
6984 struct dentry *parent,
6986 struct btrfs_log_ctx *ctx)
6988 struct btrfs_root *root = inode->root;
6989 struct btrfs_fs_info *fs_info = root->fs_info;
6991 bool log_dentries = false;
6993 if (btrfs_test_opt(fs_info, NOTREELOG)) {
6994 ret = BTRFS_LOG_FORCE_COMMIT;
6998 if (btrfs_root_refs(&root->root_item) == 0) {
6999 ret = BTRFS_LOG_FORCE_COMMIT;
7004 * Skip already logged inodes or inodes corresponding to tmpfiles
7005 * (since logging them is pointless, a link count of 0 means they
7006 * will never be accessible).
7008 if ((btrfs_inode_in_log(inode, trans->transid) &&
7009 list_empty(&ctx->ordered_extents)) ||
7010 inode->vfs_inode.i_nlink == 0) {
7011 ret = BTRFS_NO_LOG_SYNC;
7015 ret = start_log_trans(trans, root, ctx);
7019 ret = btrfs_log_inode(trans, inode, inode_only, ctx);
7024 * for regular files, if its inode is already on disk, we don't
7025 * have to worry about the parents at all. This is because
7026 * we can use the last_unlink_trans field to record renames
7027 * and other fun in this file.
7029 if (S_ISREG(inode->vfs_inode.i_mode) &&
7030 inode->generation < trans->transid &&
7031 inode->last_unlink_trans < trans->transid) {
7036 if (S_ISDIR(inode->vfs_inode.i_mode) && ctx->log_new_dentries)
7037 log_dentries = true;
7040 * On unlink we must make sure all our current and old parent directory
7041 * inodes are fully logged. This is to prevent leaving dangling
7042 * directory index entries in directories that were our parents but are
7043 * not anymore. Not doing this results in old parent directory being
7044 * impossible to delete after log replay (rmdir will always fail with
7045 * error -ENOTEMPTY).
7051 * ln testdir/foo testdir/bar
7053 * unlink testdir/bar
7054 * xfs_io -c fsync testdir/foo
7056 * mount fs, triggers log replay
7058 * If we don't log the parent directory (testdir), after log replay the
7059 * directory still has an entry pointing to the file inode using the bar
7060 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
7061 * the file inode has a link count of 1.
7067 * ln foo testdir/foo2
7068 * ln foo testdir/foo3
7070 * unlink testdir/foo3
7071 * xfs_io -c fsync foo
7073 * mount fs, triggers log replay
7075 * Similar as the first example, after log replay the parent directory
7076 * testdir still has an entry pointing to the inode file with name foo3
7077 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
7078 * and has a link count of 2.
7080 if (inode->last_unlink_trans >= trans->transid) {
7081 ret = btrfs_log_all_parents(trans, inode, ctx);
7086 ret = log_all_new_ancestors(trans, inode, parent, ctx);
7091 ret = log_new_dir_dentries(trans, inode, ctx);
7096 btrfs_set_log_full_commit(trans);
7097 ret = BTRFS_LOG_FORCE_COMMIT;
7101 btrfs_remove_log_ctx(root, ctx);
7102 btrfs_end_log_trans(root);
7108 * it is not safe to log dentry if the chunk root has added new
7109 * chunks. This returns 0 if the dentry was logged, and 1 otherwise.
7110 * If this returns 1, you must commit the transaction to safely get your
7113 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7114 struct dentry *dentry,
7115 struct btrfs_log_ctx *ctx)
7117 struct dentry *parent = dget_parent(dentry);
7120 ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
7121 LOG_INODE_ALL, ctx);
7128 * should be called during mount to recover any replay any log trees
7131 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7134 struct btrfs_path *path;
7135 struct btrfs_trans_handle *trans;
7136 struct btrfs_key key;
7137 struct btrfs_key found_key;
7138 struct btrfs_root *log;
7139 struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7140 struct walk_control wc = {
7141 .process_func = process_one_buffer,
7142 .stage = LOG_WALK_PIN_ONLY,
7145 path = btrfs_alloc_path();
7149 set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7151 trans = btrfs_start_transaction(fs_info->tree_root, 0);
7152 if (IS_ERR(trans)) {
7153 ret = PTR_ERR(trans);
7160 ret = walk_log_tree(trans, log_root_tree, &wc);
7162 btrfs_abort_transaction(trans, ret);
7167 key.objectid = BTRFS_TREE_LOG_OBJECTID;
7168 key.offset = (u64)-1;
7169 key.type = BTRFS_ROOT_ITEM_KEY;
7172 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
7175 btrfs_abort_transaction(trans, ret);
7179 if (path->slots[0] == 0)
7183 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7185 btrfs_release_path(path);
7186 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7189 log = btrfs_read_tree_root(log_root_tree, &found_key);
7192 btrfs_abort_transaction(trans, ret);
7196 wc.replay_dest = btrfs_get_fs_root(fs_info, found_key.offset,
7198 if (IS_ERR(wc.replay_dest)) {
7199 ret = PTR_ERR(wc.replay_dest);
7202 * We didn't find the subvol, likely because it was
7203 * deleted. This is ok, simply skip this log and go to
7206 * We need to exclude the root because we can't have
7207 * other log replays overwriting this log as we'll read
7208 * it back in a few more times. This will keep our
7209 * block from being modified, and we'll just bail for
7210 * each subsequent pass.
7213 ret = btrfs_pin_extent_for_log_replay(trans,
7216 btrfs_put_root(log);
7220 btrfs_abort_transaction(trans, ret);
7224 wc.replay_dest->log_root = log;
7225 ret = btrfs_record_root_in_trans(trans, wc.replay_dest);
7227 /* The loop needs to continue due to the root refs */
7228 btrfs_abort_transaction(trans, ret);
7230 ret = walk_log_tree(trans, log, &wc);
7232 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7233 ret = fixup_inode_link_counts(trans, wc.replay_dest,
7236 btrfs_abort_transaction(trans, ret);
7239 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7240 struct btrfs_root *root = wc.replay_dest;
7242 btrfs_release_path(path);
7245 * We have just replayed everything, and the highest
7246 * objectid of fs roots probably has changed in case
7247 * some inode_item's got replayed.
7249 * root->objectid_mutex is not acquired as log replay
7250 * could only happen during mount.
7252 ret = btrfs_init_root_free_objectid(root);
7254 btrfs_abort_transaction(trans, ret);
7257 wc.replay_dest->log_root = NULL;
7258 btrfs_put_root(wc.replay_dest);
7259 btrfs_put_root(log);
7264 if (found_key.offset == 0)
7266 key.offset = found_key.offset - 1;
7268 btrfs_release_path(path);
7270 /* step one is to pin it all, step two is to replay just inodes */
7273 wc.process_func = replay_one_buffer;
7274 wc.stage = LOG_WALK_REPLAY_INODES;
7277 /* step three is to replay everything */
7278 if (wc.stage < LOG_WALK_REPLAY_ALL) {
7283 btrfs_free_path(path);
7285 /* step 4: commit the transaction, which also unpins the blocks */
7286 ret = btrfs_commit_transaction(trans);
7290 log_root_tree->log_root = NULL;
7291 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7292 btrfs_put_root(log_root_tree);
7297 btrfs_end_transaction(wc.trans);
7298 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7299 btrfs_free_path(path);
7304 * there are some corner cases where we want to force a full
7305 * commit instead of allowing a directory to be logged.
7307 * They revolve around files there were unlinked from the directory, and
7308 * this function updates the parent directory so that a full commit is
7309 * properly done if it is fsync'd later after the unlinks are done.
7311 * Must be called before the unlink operations (updates to the subvolume tree,
7312 * inodes, etc) are done.
7314 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
7315 struct btrfs_inode *dir, struct btrfs_inode *inode,
7319 * when we're logging a file, if it hasn't been renamed
7320 * or unlinked, and its inode is fully committed on disk,
7321 * we don't have to worry about walking up the directory chain
7322 * to log its parents.
7324 * So, we use the last_unlink_trans field to put this transid
7325 * into the file. When the file is logged we check it and
7326 * don't log the parents if the file is fully on disk.
7328 mutex_lock(&inode->log_mutex);
7329 inode->last_unlink_trans = trans->transid;
7330 mutex_unlock(&inode->log_mutex);
7333 * if this directory was already logged any new
7334 * names for this file/dir will get recorded
7336 if (dir->logged_trans == trans->transid)
7340 * if the inode we're about to unlink was logged,
7341 * the log will be properly updated for any new names
7343 if (inode->logged_trans == trans->transid)
7347 * when renaming files across directories, if the directory
7348 * there we're unlinking from gets fsync'd later on, there's
7349 * no way to find the destination directory later and fsync it
7350 * properly. So, we have to be conservative and force commits
7351 * so the new name gets discovered.
7356 /* we can safely do the unlink without any special recording */
7360 mutex_lock(&dir->log_mutex);
7361 dir->last_unlink_trans = trans->transid;
7362 mutex_unlock(&dir->log_mutex);
7366 * Make sure that if someone attempts to fsync the parent directory of a deleted
7367 * snapshot, it ends up triggering a transaction commit. This is to guarantee
7368 * that after replaying the log tree of the parent directory's root we will not
7369 * see the snapshot anymore and at log replay time we will not see any log tree
7370 * corresponding to the deleted snapshot's root, which could lead to replaying
7371 * it after replaying the log tree of the parent directory (which would replay
7372 * the snapshot delete operation).
7374 * Must be called before the actual snapshot destroy operation (updates to the
7375 * parent root and tree of tree roots trees, etc) are done.
7377 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
7378 struct btrfs_inode *dir)
7380 mutex_lock(&dir->log_mutex);
7381 dir->last_unlink_trans = trans->transid;
7382 mutex_unlock(&dir->log_mutex);
7386 * Update the log after adding a new name for an inode.
7388 * @trans: Transaction handle.
7389 * @old_dentry: The dentry associated with the old name and the old
7391 * @old_dir: The inode of the previous parent directory for the case
7392 * of a rename. For a link operation, it must be NULL.
7393 * @old_dir_index: The index number associated with the old name, meaningful
7394 * only for rename operations (when @old_dir is not NULL).
7395 * Ignored for link operations.
7396 * @parent: The dentry associated with the directory under which the
7397 * new name is located.
7399 * Call this after adding a new name for an inode, as a result of a link or
7400 * rename operation, and it will properly update the log to reflect the new name.
7402 void btrfs_log_new_name(struct btrfs_trans_handle *trans,
7403 struct dentry *old_dentry, struct btrfs_inode *old_dir,
7404 u64 old_dir_index, struct dentry *parent)
7406 struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
7407 struct btrfs_root *root = inode->root;
7408 struct btrfs_log_ctx ctx;
7409 bool log_pinned = false;
7413 * this will force the logging code to walk the dentry chain
7416 if (!S_ISDIR(inode->vfs_inode.i_mode))
7417 inode->last_unlink_trans = trans->transid;
7420 * if this inode hasn't been logged and directory we're renaming it
7421 * from hasn't been logged, we don't need to log it
7423 ret = inode_logged(trans, inode, NULL);
7426 } else if (ret == 0) {
7430 * If the inode was not logged and we are doing a rename (old_dir is not
7431 * NULL), check if old_dir was logged - if it was not we can return and
7434 ret = inode_logged(trans, old_dir, NULL);
7443 * If we are doing a rename (old_dir is not NULL) from a directory that
7444 * was previously logged, make sure that on log replay we get the old
7445 * dir entry deleted. This is needed because we will also log the new
7446 * name of the renamed inode, so we need to make sure that after log
7447 * replay we don't end up with both the new and old dir entries existing.
7449 if (old_dir && old_dir->logged_trans == trans->transid) {
7450 struct btrfs_root *log = old_dir->root->log_root;
7451 struct btrfs_path *path;
7452 struct fscrypt_name fname;
7454 ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
7456 ret = fscrypt_setup_filename(&old_dir->vfs_inode,
7457 &old_dentry->d_name, 0, &fname);
7461 * We have two inodes to update in the log, the old directory and
7462 * the inode that got renamed, so we must pin the log to prevent
7463 * anyone from syncing the log until we have updated both inodes
7466 ret = join_running_log_trans(root);
7468 * At least one of the inodes was logged before, so this should
7469 * not fail, but if it does, it's not serious, just bail out and
7470 * mark the log for a full commit.
7472 if (WARN_ON_ONCE(ret < 0))
7476 path = btrfs_alloc_path();
7479 fscrypt_free_filename(&fname);
7484 * Other concurrent task might be logging the old directory,
7485 * as it can be triggered when logging other inode that had or
7486 * still has a dentry in the old directory. We lock the old
7487 * directory's log_mutex to ensure the deletion of the old
7488 * name is persisted, because during directory logging we
7489 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
7490 * the old name's dir index item is in the delayed items, so
7491 * it could be missed by an in progress directory logging.
7493 mutex_lock(&old_dir->log_mutex);
7494 ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
7495 &fname.disk_name, old_dir_index);
7498 * The dentry does not exist in the log, so record its
7501 btrfs_release_path(path);
7502 ret = insert_dir_log_key(trans, log, path,
7504 old_dir_index, old_dir_index);
7506 mutex_unlock(&old_dir->log_mutex);
7508 btrfs_free_path(path);
7509 fscrypt_free_filename(&fname);
7514 btrfs_init_log_ctx(&ctx, &inode->vfs_inode);
7515 ctx.logging_new_name = true;
7517 * We don't care about the return value. If we fail to log the new name
7518 * then we know the next attempt to sync the log will fallback to a full
7519 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
7520 * we don't need to worry about getting a log committed that has an
7521 * inconsistent state after a rename operation.
7523 btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
7524 ASSERT(list_empty(&ctx.conflict_inodes));
7527 * If an error happened mark the log for a full commit because it's not
7528 * consistent and up to date or we couldn't find out if one of the
7529 * inodes was logged before in this transaction. Do it before unpinning
7530 * the log, to avoid any races with someone else trying to commit it.
7533 btrfs_set_log_full_commit(trans);
7535 btrfs_end_log_trans(root);