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 #define MAX_CONFLICT_INODES 10
27 /* magic values for the inode_only field in btrfs_log_inode:
29 * LOG_INODE_ALL means to log everything
30 * LOG_INODE_EXISTS means to log just enough to recreate the inode
39 * directory trouble cases
41 * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
42 * log, we must force a full commit before doing an fsync of the directory
43 * where the unlink was done.
44 * ---> record transid of last unlink/rename per directory
48 * rename foo/some_dir foo2/some_dir
50 * fsync foo/some_dir/some_file
52 * The fsync above will unlink the original some_dir without recording
53 * it in its new location (foo2). After a crash, some_dir will be gone
54 * unless the fsync of some_file forces a full commit
56 * 2) we must log any new names for any file or dir that is in the fsync
57 * log. ---> check inode while renaming/linking.
59 * 2a) we must log any new names for any file or dir during rename
60 * when the directory they are being removed from was logged.
61 * ---> check inode and old parent dir during rename
63 * 2a is actually the more important variant. With the extra logging
64 * a crash might unlink the old name without recreating the new one
66 * 3) after a crash, we must go through any directories with a link count
67 * of zero and redo the rm -rf
74 * The directory f1 was fully removed from the FS, but fsync was never
75 * called on f1, only its parent dir. After a crash the rm -rf must
76 * be replayed. This must be able to recurse down the entire
77 * directory tree. The inode link count fixup code takes care of the
82 * stages for the tree walking. The first
83 * stage (0) is to only pin down the blocks we find
84 * the second stage (1) is to make sure that all the inodes
85 * we find in the log are created in the subvolume.
87 * The last stage is to deal with directories and links and extents
88 * and all the other fun semantics
92 LOG_WALK_REPLAY_INODES,
93 LOG_WALK_REPLAY_DIR_INDEX,
97 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
98 struct btrfs_inode *inode,
100 struct btrfs_log_ctx *ctx);
101 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
102 struct btrfs_root *root,
103 struct btrfs_path *path, u64 objectid);
104 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
105 struct btrfs_root *root,
106 struct btrfs_root *log,
107 struct btrfs_path *path,
108 u64 dirid, int del_all);
109 static void wait_log_commit(struct btrfs_root *root, int transid);
112 * tree logging is a special write ahead log used to make sure that
113 * fsyncs and O_SYNCs can happen without doing full tree commits.
115 * Full tree commits are expensive because they require commonly
116 * modified blocks to be recowed, creating many dirty pages in the
117 * extent tree an 4x-6x higher write load than ext3.
119 * Instead of doing a tree commit on every fsync, we use the
120 * key ranges and transaction ids to find items for a given file or directory
121 * that have changed in this transaction. Those items are copied into
122 * a special tree (one per subvolume root), that tree is written to disk
123 * and then the fsync is considered complete.
125 * After a crash, items are copied out of the log-tree back into the
126 * subvolume tree. Any file data extents found are recorded in the extent
127 * allocation tree, and the log-tree freed.
129 * The log tree is read three times, once to pin down all the extents it is
130 * using in ram and once, once to create all the inodes logged in the tree
131 * and once to do all the other items.
135 * start a sub transaction and setup the log tree
136 * this increments the log tree writer count to make the people
137 * syncing the tree wait for us to finish
139 static int start_log_trans(struct btrfs_trans_handle *trans,
140 struct btrfs_root *root,
141 struct btrfs_log_ctx *ctx)
143 struct btrfs_fs_info *fs_info = root->fs_info;
144 struct btrfs_root *tree_root = fs_info->tree_root;
145 const bool zoned = btrfs_is_zoned(fs_info);
147 bool created = false;
150 * First check if the log root tree was already created. If not, create
151 * it before locking the root's log_mutex, just to keep lockdep happy.
153 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
154 mutex_lock(&tree_root->log_mutex);
155 if (!fs_info->log_root_tree) {
156 ret = btrfs_init_log_root_tree(trans, fs_info);
158 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
162 mutex_unlock(&tree_root->log_mutex);
167 mutex_lock(&root->log_mutex);
170 if (root->log_root) {
171 int index = (root->log_transid + 1) % 2;
173 if (btrfs_need_log_full_commit(trans)) {
174 ret = BTRFS_LOG_FORCE_COMMIT;
178 if (zoned && atomic_read(&root->log_commit[index])) {
179 wait_log_commit(root, root->log_transid - 1);
183 if (!root->log_start_pid) {
184 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
185 root->log_start_pid = current->pid;
186 } else if (root->log_start_pid != current->pid) {
187 set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
191 * This means fs_info->log_root_tree was already created
192 * for some other FS trees. Do the full commit not to mix
193 * nodes from multiple log transactions to do sequential
196 if (zoned && !created) {
197 ret = BTRFS_LOG_FORCE_COMMIT;
201 ret = btrfs_add_log_tree(trans, root);
205 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
206 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
207 root->log_start_pid = current->pid;
210 atomic_inc(&root->log_writers);
211 if (!ctx->logging_new_name) {
212 int index = root->log_transid % 2;
213 list_add_tail(&ctx->list, &root->log_ctxs[index]);
214 ctx->log_transid = root->log_transid;
218 mutex_unlock(&root->log_mutex);
223 * returns 0 if there was a log transaction running and we were able
224 * to join, or returns -ENOENT if there were not transactions
227 static int join_running_log_trans(struct btrfs_root *root)
229 const bool zoned = btrfs_is_zoned(root->fs_info);
232 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
235 mutex_lock(&root->log_mutex);
237 if (root->log_root) {
238 int index = (root->log_transid + 1) % 2;
241 if (zoned && atomic_read(&root->log_commit[index])) {
242 wait_log_commit(root, root->log_transid - 1);
245 atomic_inc(&root->log_writers);
247 mutex_unlock(&root->log_mutex);
252 * This either makes the current running log transaction wait
253 * until you call btrfs_end_log_trans() or it makes any future
254 * log transactions wait until you call btrfs_end_log_trans()
256 void btrfs_pin_log_trans(struct btrfs_root *root)
258 atomic_inc(&root->log_writers);
262 * indicate we're done making changes to the log tree
263 * and wake up anyone waiting to do a sync
265 void btrfs_end_log_trans(struct btrfs_root *root)
267 if (atomic_dec_and_test(&root->log_writers)) {
268 /* atomic_dec_and_test implies a barrier */
269 cond_wake_up_nomb(&root->log_writer_wait);
273 static void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
275 filemap_fdatawait_range(buf->pages[0]->mapping,
276 buf->start, buf->start + buf->len - 1);
280 * the walk control struct is used to pass state down the chain when
281 * processing the log tree. The stage field tells us which part
282 * of the log tree processing we are currently doing. The others
283 * are state fields used for that specific part
285 struct walk_control {
286 /* should we free the extent on disk when done? This is used
287 * at transaction commit time while freeing a log tree
291 /* pin only walk, we record which extents on disk belong to the
296 /* what stage of the replay code we're currently in */
300 * Ignore any items from the inode currently being processed. Needs
301 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
302 * the LOG_WALK_REPLAY_INODES stage.
304 bool ignore_cur_inode;
306 /* the root we are currently replaying */
307 struct btrfs_root *replay_dest;
309 /* the trans handle for the current replay */
310 struct btrfs_trans_handle *trans;
312 /* the function that gets used to process blocks we find in the
313 * tree. Note the extent_buffer might not be up to date when it is
314 * passed in, and it must be checked or read if you need the data
317 int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
318 struct walk_control *wc, u64 gen, int level);
322 * process_func used to pin down extents, write them or wait on them
324 static int process_one_buffer(struct btrfs_root *log,
325 struct extent_buffer *eb,
326 struct walk_control *wc, u64 gen, int level)
328 struct btrfs_fs_info *fs_info = log->fs_info;
332 * If this fs is mixed then we need to be able to process the leaves to
333 * pin down any logged extents, so we have to read the block.
335 if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
336 ret = btrfs_read_extent_buffer(eb, gen, level, NULL);
342 ret = btrfs_pin_extent_for_log_replay(wc->trans, eb->start,
347 if (btrfs_buffer_uptodate(eb, gen, 0) &&
348 btrfs_header_level(eb) == 0)
349 ret = btrfs_exclude_logged_extents(eb);
354 static int do_overwrite_item(struct btrfs_trans_handle *trans,
355 struct btrfs_root *root,
356 struct btrfs_path *path,
357 struct extent_buffer *eb, int slot,
358 struct btrfs_key *key)
362 u64 saved_i_size = 0;
363 int save_old_i_size = 0;
364 unsigned long src_ptr;
365 unsigned long dst_ptr;
366 int overwrite_root = 0;
367 bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
369 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
372 item_size = btrfs_item_size(eb, slot);
373 src_ptr = btrfs_item_ptr_offset(eb, slot);
375 /* Our caller must have done a search for the key for us. */
376 ASSERT(path->nodes[0] != NULL);
379 * And the slot must point to the exact key or the slot where the key
380 * should be at (the first item with a key greater than 'key')
382 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
383 struct btrfs_key found_key;
385 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
386 ret = btrfs_comp_cpu_keys(&found_key, key);
395 u32 dst_size = btrfs_item_size(path->nodes[0],
397 if (dst_size != item_size)
400 if (item_size == 0) {
401 btrfs_release_path(path);
404 dst_copy = kmalloc(item_size, GFP_NOFS);
405 src_copy = kmalloc(item_size, GFP_NOFS);
406 if (!dst_copy || !src_copy) {
407 btrfs_release_path(path);
413 read_extent_buffer(eb, src_copy, src_ptr, item_size);
415 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
416 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
418 ret = memcmp(dst_copy, src_copy, item_size);
423 * they have the same contents, just return, this saves
424 * us from cowing blocks in the destination tree and doing
425 * extra writes that may not have been done by a previous
429 btrfs_release_path(path);
434 * We need to load the old nbytes into the inode so when we
435 * replay the extents we've logged we get the right nbytes.
438 struct btrfs_inode_item *item;
442 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
443 struct btrfs_inode_item);
444 nbytes = btrfs_inode_nbytes(path->nodes[0], item);
445 item = btrfs_item_ptr(eb, slot,
446 struct btrfs_inode_item);
447 btrfs_set_inode_nbytes(eb, item, nbytes);
450 * If this is a directory we need to reset the i_size to
451 * 0 so that we can set it up properly when replaying
452 * the rest of the items in this log.
454 mode = btrfs_inode_mode(eb, item);
456 btrfs_set_inode_size(eb, item, 0);
458 } else if (inode_item) {
459 struct btrfs_inode_item *item;
463 * New inode, set nbytes to 0 so that the nbytes comes out
464 * properly when we replay the extents.
466 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
467 btrfs_set_inode_nbytes(eb, item, 0);
470 * If this is a directory we need to reset the i_size to 0 so
471 * that we can set it up properly when replaying the rest of
472 * the items in this log.
474 mode = btrfs_inode_mode(eb, item);
476 btrfs_set_inode_size(eb, item, 0);
479 btrfs_release_path(path);
480 /* try to insert the key into the destination tree */
481 path->skip_release_on_error = 1;
482 ret = btrfs_insert_empty_item(trans, root, path,
484 path->skip_release_on_error = 0;
486 /* make sure any existing item is the correct size */
487 if (ret == -EEXIST || ret == -EOVERFLOW) {
489 found_size = btrfs_item_size(path->nodes[0],
491 if (found_size > item_size)
492 btrfs_truncate_item(path, item_size, 1);
493 else if (found_size < item_size)
494 btrfs_extend_item(path, item_size - found_size);
498 dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
501 /* don't overwrite an existing inode if the generation number
502 * was logged as zero. This is done when the tree logging code
503 * is just logging an inode to make sure it exists after recovery.
505 * Also, don't overwrite i_size on directories during replay.
506 * log replay inserts and removes directory items based on the
507 * state of the tree found in the subvolume, and i_size is modified
510 if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
511 struct btrfs_inode_item *src_item;
512 struct btrfs_inode_item *dst_item;
514 src_item = (struct btrfs_inode_item *)src_ptr;
515 dst_item = (struct btrfs_inode_item *)dst_ptr;
517 if (btrfs_inode_generation(eb, src_item) == 0) {
518 struct extent_buffer *dst_eb = path->nodes[0];
519 const u64 ino_size = btrfs_inode_size(eb, src_item);
522 * For regular files an ino_size == 0 is used only when
523 * logging that an inode exists, as part of a directory
524 * fsync, and the inode wasn't fsynced before. In this
525 * case don't set the size of the inode in the fs/subvol
526 * tree, otherwise we would be throwing valid data away.
528 if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
529 S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
531 btrfs_set_inode_size(dst_eb, dst_item, ino_size);
535 if (overwrite_root &&
536 S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
537 S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
539 saved_i_size = btrfs_inode_size(path->nodes[0],
544 copy_extent_buffer(path->nodes[0], eb, dst_ptr,
547 if (save_old_i_size) {
548 struct btrfs_inode_item *dst_item;
549 dst_item = (struct btrfs_inode_item *)dst_ptr;
550 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
553 /* make sure the generation is filled in */
554 if (key->type == BTRFS_INODE_ITEM_KEY) {
555 struct btrfs_inode_item *dst_item;
556 dst_item = (struct btrfs_inode_item *)dst_ptr;
557 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
558 btrfs_set_inode_generation(path->nodes[0], dst_item,
563 btrfs_mark_buffer_dirty(path->nodes[0]);
564 btrfs_release_path(path);
569 * Item overwrite used by replay and tree logging. eb, slot and key all refer
570 * to the src data we are copying out.
572 * root is the tree we are copying into, and path is a scratch
573 * path for use in this function (it should be released on entry and
574 * will be released on exit).
576 * If the key is already in the destination tree the existing item is
577 * overwritten. If the existing item isn't big enough, it is extended.
578 * If it is too large, it is truncated.
580 * If the key isn't in the destination yet, a new item is inserted.
582 static int overwrite_item(struct btrfs_trans_handle *trans,
583 struct btrfs_root *root,
584 struct btrfs_path *path,
585 struct extent_buffer *eb, int slot,
586 struct btrfs_key *key)
590 /* Look for the key in the destination tree. */
591 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
595 return do_overwrite_item(trans, root, path, eb, slot, key);
598 static int read_alloc_one_name(struct extent_buffer *eb, void *start, int len,
599 struct fscrypt_str *name)
603 buf = kmalloc(len, GFP_NOFS);
607 read_extent_buffer(eb, buf, (unsigned long)start, len);
614 * simple helper to read an inode off the disk from a given root
615 * This can only be called for subvolume roots and not for the log
617 static noinline struct inode *read_one_inode(struct btrfs_root *root,
622 inode = btrfs_iget(root->fs_info->sb, objectid, root);
628 /* replays a single extent in 'eb' at 'slot' with 'key' into the
629 * subvolume 'root'. path is released on entry and should be released
632 * extents in the log tree have not been allocated out of the extent
633 * tree yet. So, this completes the allocation, taking a reference
634 * as required if the extent already exists or creating a new extent
635 * if it isn't in the extent allocation tree yet.
637 * The extent is inserted into the file, dropping any existing extents
638 * from the file that overlap the new one.
640 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
641 struct btrfs_root *root,
642 struct btrfs_path *path,
643 struct extent_buffer *eb, int slot,
644 struct btrfs_key *key)
646 struct btrfs_drop_extents_args drop_args = { 0 };
647 struct btrfs_fs_info *fs_info = root->fs_info;
650 u64 start = key->offset;
652 struct btrfs_file_extent_item *item;
653 struct inode *inode = NULL;
657 item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
658 found_type = btrfs_file_extent_type(eb, item);
660 if (found_type == BTRFS_FILE_EXTENT_REG ||
661 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
662 nbytes = btrfs_file_extent_num_bytes(eb, item);
663 extent_end = start + nbytes;
666 * We don't add to the inodes nbytes if we are prealloc or a
669 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
671 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
672 size = btrfs_file_extent_ram_bytes(eb, item);
673 nbytes = btrfs_file_extent_ram_bytes(eb, item);
674 extent_end = ALIGN(start + size,
675 fs_info->sectorsize);
681 inode = read_one_inode(root, key->objectid);
688 * first check to see if we already have this extent in the
689 * file. This must be done before the btrfs_drop_extents run
690 * so we don't try to drop this extent.
692 ret = btrfs_lookup_file_extent(trans, root, path,
693 btrfs_ino(BTRFS_I(inode)), start, 0);
696 (found_type == BTRFS_FILE_EXTENT_REG ||
697 found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
698 struct btrfs_file_extent_item cmp1;
699 struct btrfs_file_extent_item cmp2;
700 struct btrfs_file_extent_item *existing;
701 struct extent_buffer *leaf;
703 leaf = path->nodes[0];
704 existing = btrfs_item_ptr(leaf, path->slots[0],
705 struct btrfs_file_extent_item);
707 read_extent_buffer(eb, &cmp1, (unsigned long)item,
709 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
713 * we already have a pointer to this exact extent,
714 * we don't have to do anything
716 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
717 btrfs_release_path(path);
721 btrfs_release_path(path);
723 /* drop any overlapping extents */
724 drop_args.start = start;
725 drop_args.end = extent_end;
726 drop_args.drop_cache = true;
727 ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
731 if (found_type == BTRFS_FILE_EXTENT_REG ||
732 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
734 unsigned long dest_offset;
735 struct btrfs_key ins;
737 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
738 btrfs_fs_incompat(fs_info, NO_HOLES))
741 ret = btrfs_insert_empty_item(trans, root, path, key,
745 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
747 copy_extent_buffer(path->nodes[0], eb, dest_offset,
748 (unsigned long)item, sizeof(*item));
750 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
751 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
752 ins.type = BTRFS_EXTENT_ITEM_KEY;
753 offset = key->offset - btrfs_file_extent_offset(eb, item);
756 * Manually record dirty extent, as here we did a shallow
757 * file extent item copy and skip normal backref update,
758 * but modifying extent tree all by ourselves.
759 * So need to manually record dirty extent for qgroup,
760 * as the owner of the file extent changed from log tree
761 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
763 ret = btrfs_qgroup_trace_extent(trans,
764 btrfs_file_extent_disk_bytenr(eb, item),
765 btrfs_file_extent_disk_num_bytes(eb, item),
770 if (ins.objectid > 0) {
771 struct btrfs_ref ref = { 0 };
774 LIST_HEAD(ordered_sums);
777 * is this extent already allocated in the extent
778 * allocation tree? If so, just add a reference
780 ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
784 } else if (ret == 0) {
785 btrfs_init_generic_ref(&ref,
786 BTRFS_ADD_DELAYED_REF,
787 ins.objectid, ins.offset, 0);
788 btrfs_init_data_ref(&ref,
789 root->root_key.objectid,
790 key->objectid, offset, 0, false);
791 ret = btrfs_inc_extent_ref(trans, &ref);
796 * insert the extent pointer in the extent
799 ret = btrfs_alloc_logged_file_extent(trans,
800 root->root_key.objectid,
801 key->objectid, offset, &ins);
805 btrfs_release_path(path);
807 if (btrfs_file_extent_compression(eb, item)) {
808 csum_start = ins.objectid;
809 csum_end = csum_start + ins.offset;
811 csum_start = ins.objectid +
812 btrfs_file_extent_offset(eb, item);
813 csum_end = csum_start +
814 btrfs_file_extent_num_bytes(eb, item);
817 ret = btrfs_lookup_csums_range(root->log_root,
818 csum_start, csum_end - 1,
819 &ordered_sums, 0, false);
823 * Now delete all existing cums in the csum root that
824 * cover our range. We do this because we can have an
825 * extent that is completely referenced by one file
826 * extent item and partially referenced by another
827 * file extent item (like after using the clone or
828 * extent_same ioctls). In this case if we end up doing
829 * the replay of the one that partially references the
830 * extent first, and we do not do the csum deletion
831 * below, we can get 2 csum items in the csum tree that
832 * overlap each other. For example, imagine our log has
833 * the two following file extent items:
835 * key (257 EXTENT_DATA 409600)
836 * extent data disk byte 12845056 nr 102400
837 * extent data offset 20480 nr 20480 ram 102400
839 * key (257 EXTENT_DATA 819200)
840 * extent data disk byte 12845056 nr 102400
841 * extent data offset 0 nr 102400 ram 102400
843 * Where the second one fully references the 100K extent
844 * that starts at disk byte 12845056, and the log tree
845 * has a single csum item that covers the entire range
848 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
850 * After the first file extent item is replayed, the
851 * csum tree gets the following csum item:
853 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
855 * Which covers the 20K sub-range starting at offset 20K
856 * of our extent. Now when we replay the second file
857 * extent item, if we do not delete existing csum items
858 * that cover any of its blocks, we end up getting two
859 * csum items in our csum tree that overlap each other:
861 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
862 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
864 * Which is a problem, because after this anyone trying
865 * to lookup up for the checksum of any block of our
866 * extent starting at an offset of 40K or higher, will
867 * end up looking at the second csum item only, which
868 * does not contain the checksum for any block starting
869 * at offset 40K or higher of our extent.
871 while (!list_empty(&ordered_sums)) {
872 struct btrfs_ordered_sum *sums;
873 struct btrfs_root *csum_root;
875 sums = list_entry(ordered_sums.next,
876 struct btrfs_ordered_sum,
878 csum_root = btrfs_csum_root(fs_info,
881 ret = btrfs_del_csums(trans, csum_root,
885 ret = btrfs_csum_file_blocks(trans,
888 list_del(&sums->list);
894 btrfs_release_path(path);
896 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
897 /* inline extents are easy, we just overwrite them */
898 ret = overwrite_item(trans, root, path, eb, slot, key);
903 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start,
909 btrfs_update_inode_bytes(BTRFS_I(inode), nbytes, drop_args.bytes_found);
910 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
916 static int unlink_inode_for_log_replay(struct btrfs_trans_handle *trans,
917 struct btrfs_inode *dir,
918 struct btrfs_inode *inode,
919 const struct fscrypt_str *name)
923 ret = btrfs_unlink_inode(trans, dir, inode, name);
927 * Whenever we need to check if a name exists or not, we check the
928 * fs/subvolume tree. So after an unlink we must run delayed items, so
929 * that future checks for a name during log replay see that the name
930 * does not exists anymore.
932 return btrfs_run_delayed_items(trans);
936 * when cleaning up conflicts between the directory names in the
937 * subvolume, directory names in the log and directory names in the
938 * inode back references, we may have to unlink inodes from directories.
940 * This is a helper function to do the unlink of a specific directory
943 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
944 struct btrfs_path *path,
945 struct btrfs_inode *dir,
946 struct btrfs_dir_item *di)
948 struct btrfs_root *root = dir->root;
950 struct fscrypt_str name;
951 struct extent_buffer *leaf;
952 struct btrfs_key location;
955 leaf = path->nodes[0];
957 btrfs_dir_item_key_to_cpu(leaf, di, &location);
958 ret = read_alloc_one_name(leaf, di + 1, btrfs_dir_name_len(leaf, di), &name);
962 btrfs_release_path(path);
964 inode = read_one_inode(root, location.objectid);
970 ret = link_to_fixup_dir(trans, root, path, location.objectid);
974 ret = unlink_inode_for_log_replay(trans, dir, BTRFS_I(inode), &name);
982 * See if a given name and sequence number found in an inode back reference are
983 * already in a directory and correctly point to this inode.
985 * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
988 static noinline int inode_in_dir(struct btrfs_root *root,
989 struct btrfs_path *path,
990 u64 dirid, u64 objectid, u64 index,
991 struct fscrypt_str *name)
993 struct btrfs_dir_item *di;
994 struct btrfs_key location;
997 di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
1003 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1004 if (location.objectid != objectid)
1010 btrfs_release_path(path);
1011 di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, 0);
1016 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1017 if (location.objectid == objectid)
1021 btrfs_release_path(path);
1026 * helper function to check a log tree for a named back reference in
1027 * an inode. This is used to decide if a back reference that is
1028 * found in the subvolume conflicts with what we find in the log.
1030 * inode backreferences may have multiple refs in a single item,
1031 * during replay we process one reference at a time, and we don't
1032 * want to delete valid links to a file from the subvolume if that
1033 * link is also in the log.
1035 static noinline int backref_in_log(struct btrfs_root *log,
1036 struct btrfs_key *key,
1038 const struct fscrypt_str *name)
1040 struct btrfs_path *path;
1043 path = btrfs_alloc_path();
1047 ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1050 } else if (ret == 1) {
1055 if (key->type == BTRFS_INODE_EXTREF_KEY)
1056 ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
1058 ref_objectid, name);
1060 ret = !!btrfs_find_name_in_backref(path->nodes[0],
1061 path->slots[0], name);
1063 btrfs_free_path(path);
1067 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
1068 struct btrfs_root *root,
1069 struct btrfs_path *path,
1070 struct btrfs_root *log_root,
1071 struct btrfs_inode *dir,
1072 struct btrfs_inode *inode,
1073 u64 inode_objectid, u64 parent_objectid,
1074 u64 ref_index, struct fscrypt_str *name)
1077 struct extent_buffer *leaf;
1078 struct btrfs_dir_item *di;
1079 struct btrfs_key search_key;
1080 struct btrfs_inode_extref *extref;
1083 /* Search old style refs */
1084 search_key.objectid = inode_objectid;
1085 search_key.type = BTRFS_INODE_REF_KEY;
1086 search_key.offset = parent_objectid;
1087 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1089 struct btrfs_inode_ref *victim_ref;
1091 unsigned long ptr_end;
1093 leaf = path->nodes[0];
1095 /* are we trying to overwrite a back ref for the root directory
1096 * if so, just jump out, we're done
1098 if (search_key.objectid == search_key.offset)
1101 /* check all the names in this back reference to see
1102 * if they are in the log. if so, we allow them to stay
1103 * otherwise they must be unlinked as a conflict
1105 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1106 ptr_end = ptr + btrfs_item_size(leaf, path->slots[0]);
1107 while (ptr < ptr_end) {
1108 struct fscrypt_str victim_name;
1110 victim_ref = (struct btrfs_inode_ref *)ptr;
1111 ret = read_alloc_one_name(leaf, (victim_ref + 1),
1112 btrfs_inode_ref_name_len(leaf, victim_ref),
1117 ret = backref_in_log(log_root, &search_key,
1118 parent_objectid, &victim_name);
1120 kfree(victim_name.name);
1123 inc_nlink(&inode->vfs_inode);
1124 btrfs_release_path(path);
1126 ret = unlink_inode_for_log_replay(trans, dir, inode,
1128 kfree(victim_name.name);
1133 kfree(victim_name.name);
1135 ptr = (unsigned long)(victim_ref + 1) + victim_name.len;
1138 btrfs_release_path(path);
1140 /* Same search but for extended refs */
1141 extref = btrfs_lookup_inode_extref(NULL, root, path, name,
1142 inode_objectid, parent_objectid, 0,
1144 if (IS_ERR(extref)) {
1145 return PTR_ERR(extref);
1146 } else if (extref) {
1150 struct inode *victim_parent;
1152 leaf = path->nodes[0];
1154 item_size = btrfs_item_size(leaf, path->slots[0]);
1155 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1157 while (cur_offset < item_size) {
1158 struct fscrypt_str victim_name;
1160 extref = (struct btrfs_inode_extref *)(base + cur_offset);
1162 if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1165 ret = read_alloc_one_name(leaf, &extref->name,
1166 btrfs_inode_extref_name_len(leaf, extref),
1171 search_key.objectid = inode_objectid;
1172 search_key.type = BTRFS_INODE_EXTREF_KEY;
1173 search_key.offset = btrfs_extref_hash(parent_objectid,
1176 ret = backref_in_log(log_root, &search_key,
1177 parent_objectid, &victim_name);
1179 kfree(victim_name.name);
1183 victim_parent = read_one_inode(root,
1185 if (victim_parent) {
1186 inc_nlink(&inode->vfs_inode);
1187 btrfs_release_path(path);
1189 ret = unlink_inode_for_log_replay(trans,
1190 BTRFS_I(victim_parent),
1191 inode, &victim_name);
1193 iput(victim_parent);
1194 kfree(victim_name.name);
1199 kfree(victim_name.name);
1201 cur_offset += victim_name.len + sizeof(*extref);
1204 btrfs_release_path(path);
1206 /* look for a conflicting sequence number */
1207 di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1208 ref_index, name, 0);
1212 ret = drop_one_dir_item(trans, path, dir, di);
1216 btrfs_release_path(path);
1218 /* look for a conflicting name */
1219 di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir), name, 0);
1223 ret = drop_one_dir_item(trans, path, dir, di);
1227 btrfs_release_path(path);
1232 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1233 struct fscrypt_str *name, u64 *index,
1234 u64 *parent_objectid)
1236 struct btrfs_inode_extref *extref;
1239 extref = (struct btrfs_inode_extref *)ref_ptr;
1241 ret = read_alloc_one_name(eb, &extref->name,
1242 btrfs_inode_extref_name_len(eb, extref), name);
1247 *index = btrfs_inode_extref_index(eb, extref);
1248 if (parent_objectid)
1249 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1254 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1255 struct fscrypt_str *name, u64 *index)
1257 struct btrfs_inode_ref *ref;
1260 ref = (struct btrfs_inode_ref *)ref_ptr;
1262 ret = read_alloc_one_name(eb, ref + 1, btrfs_inode_ref_name_len(eb, ref),
1268 *index = btrfs_inode_ref_index(eb, ref);
1274 * Take an inode reference item from the log tree and iterate all names from the
1275 * inode reference item in the subvolume tree with the same key (if it exists).
1276 * For any name that is not in the inode reference item from the log tree, do a
1277 * proper unlink of that name (that is, remove its entry from the inode
1278 * reference item and both dir index keys).
1280 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1281 struct btrfs_root *root,
1282 struct btrfs_path *path,
1283 struct btrfs_inode *inode,
1284 struct extent_buffer *log_eb,
1286 struct btrfs_key *key)
1289 unsigned long ref_ptr;
1290 unsigned long ref_end;
1291 struct extent_buffer *eb;
1294 btrfs_release_path(path);
1295 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1303 eb = path->nodes[0];
1304 ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1305 ref_end = ref_ptr + btrfs_item_size(eb, path->slots[0]);
1306 while (ref_ptr < ref_end) {
1307 struct fscrypt_str name;
1310 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1311 ret = extref_get_fields(eb, ref_ptr, &name,
1314 parent_id = key->offset;
1315 ret = ref_get_fields(eb, ref_ptr, &name, NULL);
1320 if (key->type == BTRFS_INODE_EXTREF_KEY)
1321 ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
1324 ret = !!btrfs_find_name_in_backref(log_eb, log_slot, &name);
1329 btrfs_release_path(path);
1330 dir = read_one_inode(root, parent_id);
1336 ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir),
1346 ref_ptr += name.len;
1347 if (key->type == BTRFS_INODE_EXTREF_KEY)
1348 ref_ptr += sizeof(struct btrfs_inode_extref);
1350 ref_ptr += sizeof(struct btrfs_inode_ref);
1354 btrfs_release_path(path);
1359 * replay one inode back reference item found in the log tree.
1360 * eb, slot and key refer to the buffer and key found in the log tree.
1361 * root is the destination we are replaying into, and path is for temp
1362 * use by this function. (it should be released on return).
1364 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1365 struct btrfs_root *root,
1366 struct btrfs_root *log,
1367 struct btrfs_path *path,
1368 struct extent_buffer *eb, int slot,
1369 struct btrfs_key *key)
1371 struct inode *dir = NULL;
1372 struct inode *inode = NULL;
1373 unsigned long ref_ptr;
1374 unsigned long ref_end;
1375 struct fscrypt_str name;
1377 int log_ref_ver = 0;
1378 u64 parent_objectid;
1381 int ref_struct_size;
1383 ref_ptr = btrfs_item_ptr_offset(eb, slot);
1384 ref_end = ref_ptr + btrfs_item_size(eb, slot);
1386 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1387 struct btrfs_inode_extref *r;
1389 ref_struct_size = sizeof(struct btrfs_inode_extref);
1391 r = (struct btrfs_inode_extref *)ref_ptr;
1392 parent_objectid = btrfs_inode_extref_parent(eb, r);
1394 ref_struct_size = sizeof(struct btrfs_inode_ref);
1395 parent_objectid = key->offset;
1397 inode_objectid = key->objectid;
1400 * it is possible that we didn't log all the parent directories
1401 * for a given inode. If we don't find the dir, just don't
1402 * copy the back ref in. The link count fixup code will take
1405 dir = read_one_inode(root, parent_objectid);
1411 inode = read_one_inode(root, inode_objectid);
1417 while (ref_ptr < ref_end) {
1419 ret = extref_get_fields(eb, ref_ptr, &name,
1420 &ref_index, &parent_objectid);
1422 * parent object can change from one array
1426 dir = read_one_inode(root, parent_objectid);
1432 ret = ref_get_fields(eb, ref_ptr, &name, &ref_index);
1437 ret = inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1438 btrfs_ino(BTRFS_I(inode)), ref_index, &name);
1441 } else if (ret == 0) {
1443 * look for a conflicting back reference in the
1444 * metadata. if we find one we have to unlink that name
1445 * of the file before we add our new link. Later on, we
1446 * overwrite any existing back reference, and we don't
1447 * want to create dangling pointers in the directory.
1449 ret = __add_inode_ref(trans, root, path, log,
1450 BTRFS_I(dir), BTRFS_I(inode),
1451 inode_objectid, parent_objectid,
1459 /* insert our name */
1460 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
1461 &name, 0, ref_index);
1465 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1469 /* Else, ret == 1, we already have a perfect match, we're done. */
1471 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + name.len;
1481 * Before we overwrite the inode reference item in the subvolume tree
1482 * with the item from the log tree, we must unlink all names from the
1483 * parent directory that are in the subvolume's tree inode reference
1484 * item, otherwise we end up with an inconsistent subvolume tree where
1485 * dir index entries exist for a name but there is no inode reference
1486 * item with the same name.
1488 ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1493 /* finally write the back reference in the inode */
1494 ret = overwrite_item(trans, root, path, eb, slot, key);
1496 btrfs_release_path(path);
1503 static int count_inode_extrefs(struct btrfs_root *root,
1504 struct btrfs_inode *inode, struct btrfs_path *path)
1508 unsigned int nlink = 0;
1511 u64 inode_objectid = btrfs_ino(inode);
1514 struct btrfs_inode_extref *extref;
1515 struct extent_buffer *leaf;
1518 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1523 leaf = path->nodes[0];
1524 item_size = btrfs_item_size(leaf, path->slots[0]);
1525 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1528 while (cur_offset < item_size) {
1529 extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1530 name_len = btrfs_inode_extref_name_len(leaf, extref);
1534 cur_offset += name_len + sizeof(*extref);
1538 btrfs_release_path(path);
1540 btrfs_release_path(path);
1542 if (ret < 0 && ret != -ENOENT)
1547 static int count_inode_refs(struct btrfs_root *root,
1548 struct btrfs_inode *inode, struct btrfs_path *path)
1551 struct btrfs_key key;
1552 unsigned int nlink = 0;
1554 unsigned long ptr_end;
1556 u64 ino = btrfs_ino(inode);
1559 key.type = BTRFS_INODE_REF_KEY;
1560 key.offset = (u64)-1;
1563 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1567 if (path->slots[0] == 0)
1572 btrfs_item_key_to_cpu(path->nodes[0], &key,
1574 if (key.objectid != ino ||
1575 key.type != BTRFS_INODE_REF_KEY)
1577 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1578 ptr_end = ptr + btrfs_item_size(path->nodes[0],
1580 while (ptr < ptr_end) {
1581 struct btrfs_inode_ref *ref;
1583 ref = (struct btrfs_inode_ref *)ptr;
1584 name_len = btrfs_inode_ref_name_len(path->nodes[0],
1586 ptr = (unsigned long)(ref + 1) + name_len;
1590 if (key.offset == 0)
1592 if (path->slots[0] > 0) {
1597 btrfs_release_path(path);
1599 btrfs_release_path(path);
1605 * There are a few corners where the link count of the file can't
1606 * be properly maintained during replay. So, instead of adding
1607 * lots of complexity to the log code, we just scan the backrefs
1608 * for any file that has been through replay.
1610 * The scan will update the link count on the inode to reflect the
1611 * number of back refs found. If it goes down to zero, the iput
1612 * will free the inode.
1614 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1615 struct btrfs_root *root,
1616 struct inode *inode)
1618 struct btrfs_path *path;
1621 u64 ino = btrfs_ino(BTRFS_I(inode));
1623 path = btrfs_alloc_path();
1627 ret = count_inode_refs(root, BTRFS_I(inode), path);
1633 ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1641 if (nlink != inode->i_nlink) {
1642 set_nlink(inode, nlink);
1643 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1647 BTRFS_I(inode)->index_cnt = (u64)-1;
1649 if (inode->i_nlink == 0) {
1650 if (S_ISDIR(inode->i_mode)) {
1651 ret = replay_dir_deletes(trans, root, NULL, path,
1656 ret = btrfs_insert_orphan_item(trans, root, ino);
1662 btrfs_free_path(path);
1666 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1667 struct btrfs_root *root,
1668 struct btrfs_path *path)
1671 struct btrfs_key key;
1672 struct inode *inode;
1674 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1675 key.type = BTRFS_ORPHAN_ITEM_KEY;
1676 key.offset = (u64)-1;
1678 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1684 if (path->slots[0] == 0)
1689 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1690 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1691 key.type != BTRFS_ORPHAN_ITEM_KEY)
1694 ret = btrfs_del_item(trans, root, path);
1698 btrfs_release_path(path);
1699 inode = read_one_inode(root, key.offset);
1705 ret = fixup_inode_link_count(trans, root, inode);
1711 * fixup on a directory may create new entries,
1712 * make sure we always look for the highset possible
1715 key.offset = (u64)-1;
1717 btrfs_release_path(path);
1723 * record a given inode in the fixup dir so we can check its link
1724 * count when replay is done. The link count is incremented here
1725 * so the inode won't go away until we check it
1727 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1728 struct btrfs_root *root,
1729 struct btrfs_path *path,
1732 struct btrfs_key key;
1734 struct inode *inode;
1736 inode = read_one_inode(root, objectid);
1740 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1741 key.type = BTRFS_ORPHAN_ITEM_KEY;
1742 key.offset = objectid;
1744 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1746 btrfs_release_path(path);
1748 if (!inode->i_nlink)
1749 set_nlink(inode, 1);
1752 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1753 } else if (ret == -EEXIST) {
1762 * when replaying the log for a directory, we only insert names
1763 * for inodes that actually exist. This means an fsync on a directory
1764 * does not implicitly fsync all the new files in it
1766 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1767 struct btrfs_root *root,
1768 u64 dirid, u64 index,
1769 const struct fscrypt_str *name,
1770 struct btrfs_key *location)
1772 struct inode *inode;
1776 inode = read_one_inode(root, location->objectid);
1780 dir = read_one_inode(root, dirid);
1786 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1789 /* FIXME, put inode into FIXUP list */
1796 static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
1797 struct btrfs_inode *dir,
1798 struct btrfs_path *path,
1799 struct btrfs_dir_item *dst_di,
1800 const struct btrfs_key *log_key,
1804 struct btrfs_key found_key;
1806 btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1807 /* The existing dentry points to the same inode, don't delete it. */
1808 if (found_key.objectid == log_key->objectid &&
1809 found_key.type == log_key->type &&
1810 found_key.offset == log_key->offset &&
1811 btrfs_dir_type(path->nodes[0], dst_di) == log_type)
1815 * Don't drop the conflicting directory entry if the inode for the new
1816 * entry doesn't exist.
1821 return drop_one_dir_item(trans, path, dir, dst_di);
1825 * take a single entry in a log directory item and replay it into
1828 * if a conflicting item exists in the subdirectory already,
1829 * the inode it points to is unlinked and put into the link count
1832 * If a name from the log points to a file or directory that does
1833 * not exist in the FS, it is skipped. fsyncs on directories
1834 * do not force down inodes inside that directory, just changes to the
1835 * names or unlinks in a directory.
1837 * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1838 * non-existing inode) and 1 if the name was replayed.
1840 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1841 struct btrfs_root *root,
1842 struct btrfs_path *path,
1843 struct extent_buffer *eb,
1844 struct btrfs_dir_item *di,
1845 struct btrfs_key *key)
1847 struct fscrypt_str name;
1848 struct btrfs_dir_item *dir_dst_di;
1849 struct btrfs_dir_item *index_dst_di;
1850 bool dir_dst_matches = false;
1851 bool index_dst_matches = false;
1852 struct btrfs_key log_key;
1853 struct btrfs_key search_key;
1858 bool update_size = true;
1859 bool name_added = false;
1861 dir = read_one_inode(root, key->objectid);
1865 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
1869 log_type = btrfs_dir_type(eb, di);
1870 btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1871 ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1872 btrfs_release_path(path);
1875 exists = (ret == 0);
1878 dir_dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1880 if (IS_ERR(dir_dst_di)) {
1881 ret = PTR_ERR(dir_dst_di);
1883 } else if (dir_dst_di) {
1884 ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1885 dir_dst_di, &log_key, log_type,
1889 dir_dst_matches = (ret == 1);
1892 btrfs_release_path(path);
1894 index_dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1895 key->objectid, key->offset,
1897 if (IS_ERR(index_dst_di)) {
1898 ret = PTR_ERR(index_dst_di);
1900 } else if (index_dst_di) {
1901 ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1902 index_dst_di, &log_key,
1906 index_dst_matches = (ret == 1);
1909 btrfs_release_path(path);
1911 if (dir_dst_matches && index_dst_matches) {
1913 update_size = false;
1918 * Check if the inode reference exists in the log for the given name,
1919 * inode and parent inode
1921 search_key.objectid = log_key.objectid;
1922 search_key.type = BTRFS_INODE_REF_KEY;
1923 search_key.offset = key->objectid;
1924 ret = backref_in_log(root->log_root, &search_key, 0, &name);
1928 /* The dentry will be added later. */
1930 update_size = false;
1934 search_key.objectid = log_key.objectid;
1935 search_key.type = BTRFS_INODE_EXTREF_KEY;
1936 search_key.offset = key->objectid;
1937 ret = backref_in_log(root->log_root, &search_key, key->objectid, &name);
1941 /* The dentry will be added later. */
1943 update_size = false;
1946 btrfs_release_path(path);
1947 ret = insert_one_name(trans, root, key->objectid, key->offset,
1949 if (ret && ret != -ENOENT && ret != -EEXIST)
1953 update_size = false;
1957 if (!ret && update_size) {
1958 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name.len * 2);
1959 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
1963 if (!ret && name_added)
1968 /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
1969 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1970 struct btrfs_root *root,
1971 struct btrfs_path *path,
1972 struct extent_buffer *eb, int slot,
1973 struct btrfs_key *key)
1976 struct btrfs_dir_item *di;
1978 /* We only log dir index keys, which only contain a single dir item. */
1979 ASSERT(key->type == BTRFS_DIR_INDEX_KEY);
1981 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1982 ret = replay_one_name(trans, root, path, eb, di, key);
1987 * If this entry refers to a non-directory (directories can not have a
1988 * link count > 1) and it was added in the transaction that was not
1989 * committed, make sure we fixup the link count of the inode the entry
1990 * points to. Otherwise something like the following would result in a
1991 * directory pointing to an inode with a wrong link that does not account
1992 * for this dir entry:
1999 * ln testdir/bar testdir/bar_link
2000 * ln testdir/foo testdir/foo_link
2001 * xfs_io -c "fsync" testdir/bar
2005 * mount fs, log replay happens
2007 * File foo would remain with a link count of 1 when it has two entries
2008 * pointing to it in the directory testdir. This would make it impossible
2009 * to ever delete the parent directory has it would result in stale
2010 * dentries that can never be deleted.
2012 if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
2013 struct btrfs_path *fixup_path;
2014 struct btrfs_key di_key;
2016 fixup_path = btrfs_alloc_path();
2020 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2021 ret = link_to_fixup_dir(trans, root, fixup_path, di_key.objectid);
2022 btrfs_free_path(fixup_path);
2029 * directory replay has two parts. There are the standard directory
2030 * items in the log copied from the subvolume, and range items
2031 * created in the log while the subvolume was logged.
2033 * The range items tell us which parts of the key space the log
2034 * is authoritative for. During replay, if a key in the subvolume
2035 * directory is in a logged range item, but not actually in the log
2036 * that means it was deleted from the directory before the fsync
2037 * and should be removed.
2039 static noinline int find_dir_range(struct btrfs_root *root,
2040 struct btrfs_path *path,
2042 u64 *start_ret, u64 *end_ret)
2044 struct btrfs_key key;
2046 struct btrfs_dir_log_item *item;
2050 if (*start_ret == (u64)-1)
2053 key.objectid = dirid;
2054 key.type = BTRFS_DIR_LOG_INDEX_KEY;
2055 key.offset = *start_ret;
2057 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2061 if (path->slots[0] == 0)
2066 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2068 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2072 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2073 struct btrfs_dir_log_item);
2074 found_end = btrfs_dir_log_end(path->nodes[0], item);
2076 if (*start_ret >= key.offset && *start_ret <= found_end) {
2078 *start_ret = key.offset;
2079 *end_ret = found_end;
2084 /* check the next slot in the tree to see if it is a valid item */
2085 nritems = btrfs_header_nritems(path->nodes[0]);
2087 if (path->slots[0] >= nritems) {
2088 ret = btrfs_next_leaf(root, path);
2093 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2095 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2099 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2100 struct btrfs_dir_log_item);
2101 found_end = btrfs_dir_log_end(path->nodes[0], item);
2102 *start_ret = key.offset;
2103 *end_ret = found_end;
2106 btrfs_release_path(path);
2111 * this looks for a given directory item in the log. If the directory
2112 * item is not in the log, the item is removed and the inode it points
2115 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2116 struct btrfs_root *log,
2117 struct btrfs_path *path,
2118 struct btrfs_path *log_path,
2120 struct btrfs_key *dir_key)
2122 struct btrfs_root *root = BTRFS_I(dir)->root;
2124 struct extent_buffer *eb;
2126 struct btrfs_dir_item *di;
2127 struct fscrypt_str name;
2128 struct inode *inode = NULL;
2129 struct btrfs_key location;
2132 * Currently we only log dir index keys. Even if we replay a log created
2133 * by an older kernel that logged both dir index and dir item keys, all
2134 * we need to do is process the dir index keys, we (and our caller) can
2135 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2137 ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY);
2139 eb = path->nodes[0];
2140 slot = path->slots[0];
2141 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2142 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
2147 struct btrfs_dir_item *log_di;
2149 log_di = btrfs_lookup_dir_index_item(trans, log, log_path,
2151 dir_key->offset, &name, 0);
2152 if (IS_ERR(log_di)) {
2153 ret = PTR_ERR(log_di);
2155 } else if (log_di) {
2156 /* The dentry exists in the log, we have nothing to do. */
2162 btrfs_dir_item_key_to_cpu(eb, di, &location);
2163 btrfs_release_path(path);
2164 btrfs_release_path(log_path);
2165 inode = read_one_inode(root, location.objectid);
2171 ret = link_to_fixup_dir(trans, root, path, location.objectid);
2176 ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir), BTRFS_I(inode),
2179 * Unlike dir item keys, dir index keys can only have one name (entry) in
2180 * them, as there are no key collisions since each key has a unique offset
2181 * (an index number), so we're done.
2184 btrfs_release_path(path);
2185 btrfs_release_path(log_path);
2191 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2192 struct btrfs_root *root,
2193 struct btrfs_root *log,
2194 struct btrfs_path *path,
2197 struct btrfs_key search_key;
2198 struct btrfs_path *log_path;
2203 log_path = btrfs_alloc_path();
2207 search_key.objectid = ino;
2208 search_key.type = BTRFS_XATTR_ITEM_KEY;
2209 search_key.offset = 0;
2211 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2215 nritems = btrfs_header_nritems(path->nodes[0]);
2216 for (i = path->slots[0]; i < nritems; i++) {
2217 struct btrfs_key key;
2218 struct btrfs_dir_item *di;
2219 struct btrfs_dir_item *log_di;
2223 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2224 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2229 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2230 total_size = btrfs_item_size(path->nodes[0], i);
2232 while (cur < total_size) {
2233 u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2234 u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2235 u32 this_len = sizeof(*di) + name_len + data_len;
2238 name = kmalloc(name_len, GFP_NOFS);
2243 read_extent_buffer(path->nodes[0], name,
2244 (unsigned long)(di + 1), name_len);
2246 log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2248 btrfs_release_path(log_path);
2250 /* Doesn't exist in log tree, so delete it. */
2251 btrfs_release_path(path);
2252 di = btrfs_lookup_xattr(trans, root, path, ino,
2253 name, name_len, -1);
2260 ret = btrfs_delete_one_dir_name(trans, root,
2264 btrfs_release_path(path);
2269 if (IS_ERR(log_di)) {
2270 ret = PTR_ERR(log_di);
2274 di = (struct btrfs_dir_item *)((char *)di + this_len);
2277 ret = btrfs_next_leaf(root, path);
2283 btrfs_free_path(log_path);
2284 btrfs_release_path(path);
2290 * deletion replay happens before we copy any new directory items
2291 * out of the log or out of backreferences from inodes. It
2292 * scans the log to find ranges of keys that log is authoritative for,
2293 * and then scans the directory to find items in those ranges that are
2294 * not present in the log.
2296 * Anything we don't find in the log is unlinked and removed from the
2299 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2300 struct btrfs_root *root,
2301 struct btrfs_root *log,
2302 struct btrfs_path *path,
2303 u64 dirid, int del_all)
2308 struct btrfs_key dir_key;
2309 struct btrfs_key found_key;
2310 struct btrfs_path *log_path;
2313 dir_key.objectid = dirid;
2314 dir_key.type = BTRFS_DIR_INDEX_KEY;
2315 log_path = btrfs_alloc_path();
2319 dir = read_one_inode(root, dirid);
2320 /* it isn't an error if the inode isn't there, that can happen
2321 * because we replay the deletes before we copy in the inode item
2325 btrfs_free_path(log_path);
2333 range_end = (u64)-1;
2335 ret = find_dir_range(log, path, dirid,
2336 &range_start, &range_end);
2343 dir_key.offset = range_start;
2346 ret = btrfs_search_slot(NULL, root, &dir_key, path,
2351 nritems = btrfs_header_nritems(path->nodes[0]);
2352 if (path->slots[0] >= nritems) {
2353 ret = btrfs_next_leaf(root, path);
2359 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2361 if (found_key.objectid != dirid ||
2362 found_key.type != dir_key.type) {
2367 if (found_key.offset > range_end)
2370 ret = check_item_in_log(trans, log, path,
2375 if (found_key.offset == (u64)-1)
2377 dir_key.offset = found_key.offset + 1;
2379 btrfs_release_path(path);
2380 if (range_end == (u64)-1)
2382 range_start = range_end + 1;
2386 btrfs_release_path(path);
2387 btrfs_free_path(log_path);
2393 * the process_func used to replay items from the log tree. This
2394 * gets called in two different stages. The first stage just looks
2395 * for inodes and makes sure they are all copied into the subvolume.
2397 * The second stage copies all the other item types from the log into
2398 * the subvolume. The two stage approach is slower, but gets rid of
2399 * lots of complexity around inodes referencing other inodes that exist
2400 * only in the log (references come from either directory items or inode
2403 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2404 struct walk_control *wc, u64 gen, int level)
2407 struct btrfs_path *path;
2408 struct btrfs_root *root = wc->replay_dest;
2409 struct btrfs_key key;
2413 ret = btrfs_read_extent_buffer(eb, gen, level, NULL);
2417 level = btrfs_header_level(eb);
2422 path = btrfs_alloc_path();
2426 nritems = btrfs_header_nritems(eb);
2427 for (i = 0; i < nritems; i++) {
2428 btrfs_item_key_to_cpu(eb, &key, i);
2430 /* inode keys are done during the first stage */
2431 if (key.type == BTRFS_INODE_ITEM_KEY &&
2432 wc->stage == LOG_WALK_REPLAY_INODES) {
2433 struct btrfs_inode_item *inode_item;
2436 inode_item = btrfs_item_ptr(eb, i,
2437 struct btrfs_inode_item);
2439 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2440 * and never got linked before the fsync, skip it, as
2441 * replaying it is pointless since it would be deleted
2442 * later. We skip logging tmpfiles, but it's always
2443 * possible we are replaying a log created with a kernel
2444 * that used to log tmpfiles.
2446 if (btrfs_inode_nlink(eb, inode_item) == 0) {
2447 wc->ignore_cur_inode = true;
2450 wc->ignore_cur_inode = false;
2452 ret = replay_xattr_deletes(wc->trans, root, log,
2453 path, key.objectid);
2456 mode = btrfs_inode_mode(eb, inode_item);
2457 if (S_ISDIR(mode)) {
2458 ret = replay_dir_deletes(wc->trans,
2459 root, log, path, key.objectid, 0);
2463 ret = overwrite_item(wc->trans, root, path,
2469 * Before replaying extents, truncate the inode to its
2470 * size. We need to do it now and not after log replay
2471 * because before an fsync we can have prealloc extents
2472 * added beyond the inode's i_size. If we did it after,
2473 * through orphan cleanup for example, we would drop
2474 * those prealloc extents just after replaying them.
2476 if (S_ISREG(mode)) {
2477 struct btrfs_drop_extents_args drop_args = { 0 };
2478 struct inode *inode;
2481 inode = read_one_inode(root, key.objectid);
2486 from = ALIGN(i_size_read(inode),
2487 root->fs_info->sectorsize);
2488 drop_args.start = from;
2489 drop_args.end = (u64)-1;
2490 drop_args.drop_cache = true;
2491 ret = btrfs_drop_extents(wc->trans, root,
2495 inode_sub_bytes(inode,
2496 drop_args.bytes_found);
2497 /* Update the inode's nbytes. */
2498 ret = btrfs_update_inode(wc->trans,
2499 root, BTRFS_I(inode));
2506 ret = link_to_fixup_dir(wc->trans, root,
2507 path, key.objectid);
2512 if (wc->ignore_cur_inode)
2515 if (key.type == BTRFS_DIR_INDEX_KEY &&
2516 wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2517 ret = replay_one_dir_item(wc->trans, root, path,
2523 if (wc->stage < LOG_WALK_REPLAY_ALL)
2526 /* these keys are simply copied */
2527 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2528 ret = overwrite_item(wc->trans, root, path,
2532 } else if (key.type == BTRFS_INODE_REF_KEY ||
2533 key.type == BTRFS_INODE_EXTREF_KEY) {
2534 ret = add_inode_ref(wc->trans, root, log, path,
2536 if (ret && ret != -ENOENT)
2539 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2540 ret = replay_one_extent(wc->trans, root, path,
2546 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2547 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2548 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2549 * older kernel with such keys, ignore them.
2552 btrfs_free_path(path);
2557 * Correctly adjust the reserved bytes occupied by a log tree extent buffer
2559 static void unaccount_log_buffer(struct btrfs_fs_info *fs_info, u64 start)
2561 struct btrfs_block_group *cache;
2563 cache = btrfs_lookup_block_group(fs_info, start);
2565 btrfs_err(fs_info, "unable to find block group for %llu", start);
2569 spin_lock(&cache->space_info->lock);
2570 spin_lock(&cache->lock);
2571 cache->reserved -= fs_info->nodesize;
2572 cache->space_info->bytes_reserved -= fs_info->nodesize;
2573 spin_unlock(&cache->lock);
2574 spin_unlock(&cache->space_info->lock);
2576 btrfs_put_block_group(cache);
2579 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2580 struct btrfs_root *root,
2581 struct btrfs_path *path, int *level,
2582 struct walk_control *wc)
2584 struct btrfs_fs_info *fs_info = root->fs_info;
2587 struct extent_buffer *next;
2588 struct extent_buffer *cur;
2592 while (*level > 0) {
2593 struct btrfs_key first_key;
2595 cur = path->nodes[*level];
2597 WARN_ON(btrfs_header_level(cur) != *level);
2599 if (path->slots[*level] >=
2600 btrfs_header_nritems(cur))
2603 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2604 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2605 btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2606 blocksize = fs_info->nodesize;
2608 next = btrfs_find_create_tree_block(fs_info, bytenr,
2609 btrfs_header_owner(cur),
2612 return PTR_ERR(next);
2615 ret = wc->process_func(root, next, wc, ptr_gen,
2618 free_extent_buffer(next);
2622 path->slots[*level]++;
2624 ret = btrfs_read_extent_buffer(next, ptr_gen,
2625 *level - 1, &first_key);
2627 free_extent_buffer(next);
2632 btrfs_tree_lock(next);
2633 btrfs_clean_tree_block(next);
2634 btrfs_wait_tree_block_writeback(next);
2635 btrfs_tree_unlock(next);
2636 ret = btrfs_pin_reserved_extent(trans,
2639 free_extent_buffer(next);
2642 btrfs_redirty_list_add(
2643 trans->transaction, next);
2645 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2646 clear_extent_buffer_dirty(next);
2647 unaccount_log_buffer(fs_info, bytenr);
2650 free_extent_buffer(next);
2653 ret = btrfs_read_extent_buffer(next, ptr_gen, *level - 1, &first_key);
2655 free_extent_buffer(next);
2659 if (path->nodes[*level-1])
2660 free_extent_buffer(path->nodes[*level-1]);
2661 path->nodes[*level-1] = next;
2662 *level = btrfs_header_level(next);
2663 path->slots[*level] = 0;
2666 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2672 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2673 struct btrfs_root *root,
2674 struct btrfs_path *path, int *level,
2675 struct walk_control *wc)
2677 struct btrfs_fs_info *fs_info = root->fs_info;
2682 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2683 slot = path->slots[i];
2684 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2687 WARN_ON(*level == 0);
2690 ret = wc->process_func(root, path->nodes[*level], wc,
2691 btrfs_header_generation(path->nodes[*level]),
2697 struct extent_buffer *next;
2699 next = path->nodes[*level];
2702 btrfs_tree_lock(next);
2703 btrfs_clean_tree_block(next);
2704 btrfs_wait_tree_block_writeback(next);
2705 btrfs_tree_unlock(next);
2706 ret = btrfs_pin_reserved_extent(trans,
2707 path->nodes[*level]->start,
2708 path->nodes[*level]->len);
2711 btrfs_redirty_list_add(trans->transaction,
2714 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2715 clear_extent_buffer_dirty(next);
2717 unaccount_log_buffer(fs_info,
2718 path->nodes[*level]->start);
2721 free_extent_buffer(path->nodes[*level]);
2722 path->nodes[*level] = NULL;
2730 * drop the reference count on the tree rooted at 'snap'. This traverses
2731 * the tree freeing any blocks that have a ref count of zero after being
2734 static int walk_log_tree(struct btrfs_trans_handle *trans,
2735 struct btrfs_root *log, struct walk_control *wc)
2737 struct btrfs_fs_info *fs_info = log->fs_info;
2741 struct btrfs_path *path;
2744 path = btrfs_alloc_path();
2748 level = btrfs_header_level(log->node);
2750 path->nodes[level] = log->node;
2751 atomic_inc(&log->node->refs);
2752 path->slots[level] = 0;
2755 wret = walk_down_log_tree(trans, log, path, &level, wc);
2763 wret = walk_up_log_tree(trans, log, path, &level, wc);
2772 /* was the root node processed? if not, catch it here */
2773 if (path->nodes[orig_level]) {
2774 ret = wc->process_func(log, path->nodes[orig_level], wc,
2775 btrfs_header_generation(path->nodes[orig_level]),
2780 struct extent_buffer *next;
2782 next = path->nodes[orig_level];
2785 btrfs_tree_lock(next);
2786 btrfs_clean_tree_block(next);
2787 btrfs_wait_tree_block_writeback(next);
2788 btrfs_tree_unlock(next);
2789 ret = btrfs_pin_reserved_extent(trans,
2790 next->start, next->len);
2793 btrfs_redirty_list_add(trans->transaction, next);
2795 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2796 clear_extent_buffer_dirty(next);
2797 unaccount_log_buffer(fs_info, next->start);
2803 btrfs_free_path(path);
2808 * helper function to update the item for a given subvolumes log root
2809 * in the tree of log roots
2811 static int update_log_root(struct btrfs_trans_handle *trans,
2812 struct btrfs_root *log,
2813 struct btrfs_root_item *root_item)
2815 struct btrfs_fs_info *fs_info = log->fs_info;
2818 if (log->log_transid == 1) {
2819 /* insert root item on the first sync */
2820 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2821 &log->root_key, root_item);
2823 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2824 &log->root_key, root_item);
2829 static void wait_log_commit(struct btrfs_root *root, int transid)
2832 int index = transid % 2;
2835 * we only allow two pending log transactions at a time,
2836 * so we know that if ours is more than 2 older than the
2837 * current transaction, we're done
2840 prepare_to_wait(&root->log_commit_wait[index],
2841 &wait, TASK_UNINTERRUPTIBLE);
2843 if (!(root->log_transid_committed < transid &&
2844 atomic_read(&root->log_commit[index])))
2847 mutex_unlock(&root->log_mutex);
2849 mutex_lock(&root->log_mutex);
2851 finish_wait(&root->log_commit_wait[index], &wait);
2854 static void wait_for_writer(struct btrfs_root *root)
2859 prepare_to_wait(&root->log_writer_wait, &wait,
2860 TASK_UNINTERRUPTIBLE);
2861 if (!atomic_read(&root->log_writers))
2864 mutex_unlock(&root->log_mutex);
2866 mutex_lock(&root->log_mutex);
2868 finish_wait(&root->log_writer_wait, &wait);
2871 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2872 struct btrfs_log_ctx *ctx)
2874 mutex_lock(&root->log_mutex);
2875 list_del_init(&ctx->list);
2876 mutex_unlock(&root->log_mutex);
2880 * Invoked in log mutex context, or be sure there is no other task which
2881 * can access the list.
2883 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2884 int index, int error)
2886 struct btrfs_log_ctx *ctx;
2887 struct btrfs_log_ctx *safe;
2889 list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2890 list_del_init(&ctx->list);
2891 ctx->log_ret = error;
2896 * btrfs_sync_log does sends a given tree log down to the disk and
2897 * updates the super blocks to record it. When this call is done,
2898 * you know that any inodes previously logged are safely on disk only
2901 * Any other return value means you need to call btrfs_commit_transaction.
2902 * Some of the edge cases for fsyncing directories that have had unlinks
2903 * or renames done in the past mean that sometimes the only safe
2904 * fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
2905 * that has happened.
2907 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2908 struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2914 struct btrfs_fs_info *fs_info = root->fs_info;
2915 struct btrfs_root *log = root->log_root;
2916 struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2917 struct btrfs_root_item new_root_item;
2918 int log_transid = 0;
2919 struct btrfs_log_ctx root_log_ctx;
2920 struct blk_plug plug;
2924 mutex_lock(&root->log_mutex);
2925 log_transid = ctx->log_transid;
2926 if (root->log_transid_committed >= log_transid) {
2927 mutex_unlock(&root->log_mutex);
2928 return ctx->log_ret;
2931 index1 = log_transid % 2;
2932 if (atomic_read(&root->log_commit[index1])) {
2933 wait_log_commit(root, log_transid);
2934 mutex_unlock(&root->log_mutex);
2935 return ctx->log_ret;
2937 ASSERT(log_transid == root->log_transid);
2938 atomic_set(&root->log_commit[index1], 1);
2940 /* wait for previous tree log sync to complete */
2941 if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2942 wait_log_commit(root, log_transid - 1);
2945 int batch = atomic_read(&root->log_batch);
2946 /* when we're on an ssd, just kick the log commit out */
2947 if (!btrfs_test_opt(fs_info, SSD) &&
2948 test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
2949 mutex_unlock(&root->log_mutex);
2950 schedule_timeout_uninterruptible(1);
2951 mutex_lock(&root->log_mutex);
2953 wait_for_writer(root);
2954 if (batch == atomic_read(&root->log_batch))
2958 /* bail out if we need to do a full commit */
2959 if (btrfs_need_log_full_commit(trans)) {
2960 ret = BTRFS_LOG_FORCE_COMMIT;
2961 mutex_unlock(&root->log_mutex);
2965 if (log_transid % 2 == 0)
2966 mark = EXTENT_DIRTY;
2970 /* we start IO on all the marked extents here, but we don't actually
2971 * wait for them until later.
2973 blk_start_plug(&plug);
2974 ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2976 * -EAGAIN happens when someone, e.g., a concurrent transaction
2977 * commit, writes a dirty extent in this tree-log commit. This
2978 * concurrent write will create a hole writing out the extents,
2979 * and we cannot proceed on a zoned filesystem, requiring
2980 * sequential writing. While we can bail out to a full commit
2981 * here, but we can continue hoping the concurrent writing fills
2984 if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
2987 blk_finish_plug(&plug);
2988 btrfs_set_log_full_commit(trans);
2989 mutex_unlock(&root->log_mutex);
2994 * We _must_ update under the root->log_mutex in order to make sure we
2995 * have a consistent view of the log root we are trying to commit at
2998 * We _must_ copy this into a local copy, because we are not holding the
2999 * log_root_tree->log_mutex yet. This is important because when we
3000 * commit the log_root_tree we must have a consistent view of the
3001 * log_root_tree when we update the super block to point at the
3002 * log_root_tree bytenr. If we update the log_root_tree here we'll race
3003 * with the commit and possibly point at the new block which we may not
3006 btrfs_set_root_node(&log->root_item, log->node);
3007 memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3009 root->log_transid++;
3010 log->log_transid = root->log_transid;
3011 root->log_start_pid = 0;
3013 * IO has been started, blocks of the log tree have WRITTEN flag set
3014 * in their headers. new modifications of the log will be written to
3015 * new positions. so it's safe to allow log writers to go in.
3017 mutex_unlock(&root->log_mutex);
3019 if (btrfs_is_zoned(fs_info)) {
3020 mutex_lock(&fs_info->tree_root->log_mutex);
3021 if (!log_root_tree->node) {
3022 ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
3024 mutex_unlock(&fs_info->tree_root->log_mutex);
3025 blk_finish_plug(&plug);
3029 mutex_unlock(&fs_info->tree_root->log_mutex);
3032 btrfs_init_log_ctx(&root_log_ctx, NULL);
3034 mutex_lock(&log_root_tree->log_mutex);
3036 index2 = log_root_tree->log_transid % 2;
3037 list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3038 root_log_ctx.log_transid = log_root_tree->log_transid;
3041 * Now we are safe to update the log_root_tree because we're under the
3042 * log_mutex, and we're a current writer so we're holding the commit
3043 * open until we drop the log_mutex.
3045 ret = update_log_root(trans, log, &new_root_item);
3047 if (!list_empty(&root_log_ctx.list))
3048 list_del_init(&root_log_ctx.list);
3050 blk_finish_plug(&plug);
3051 btrfs_set_log_full_commit(trans);
3054 "failed to update log for root %llu ret %d",
3055 root->root_key.objectid, ret);
3056 btrfs_wait_tree_log_extents(log, mark);
3057 mutex_unlock(&log_root_tree->log_mutex);
3061 if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3062 blk_finish_plug(&plug);
3063 list_del_init(&root_log_ctx.list);
3064 mutex_unlock(&log_root_tree->log_mutex);
3065 ret = root_log_ctx.log_ret;
3069 index2 = root_log_ctx.log_transid % 2;
3070 if (atomic_read(&log_root_tree->log_commit[index2])) {
3071 blk_finish_plug(&plug);
3072 ret = btrfs_wait_tree_log_extents(log, mark);
3073 wait_log_commit(log_root_tree,
3074 root_log_ctx.log_transid);
3075 mutex_unlock(&log_root_tree->log_mutex);
3077 ret = root_log_ctx.log_ret;
3080 ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
3081 atomic_set(&log_root_tree->log_commit[index2], 1);
3083 if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3084 wait_log_commit(log_root_tree,
3085 root_log_ctx.log_transid - 1);
3089 * now that we've moved on to the tree of log tree roots,
3090 * check the full commit flag again
3092 if (btrfs_need_log_full_commit(trans)) {
3093 blk_finish_plug(&plug);
3094 btrfs_wait_tree_log_extents(log, mark);
3095 mutex_unlock(&log_root_tree->log_mutex);
3096 ret = BTRFS_LOG_FORCE_COMMIT;
3097 goto out_wake_log_root;
3100 ret = btrfs_write_marked_extents(fs_info,
3101 &log_root_tree->dirty_log_pages,
3102 EXTENT_DIRTY | EXTENT_NEW);
3103 blk_finish_plug(&plug);
3105 * As described above, -EAGAIN indicates a hole in the extents. We
3106 * cannot wait for these write outs since the waiting cause a
3107 * deadlock. Bail out to the full commit instead.
3109 if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3110 btrfs_set_log_full_commit(trans);
3111 btrfs_wait_tree_log_extents(log, mark);
3112 mutex_unlock(&log_root_tree->log_mutex);
3113 goto out_wake_log_root;
3115 btrfs_set_log_full_commit(trans);
3116 mutex_unlock(&log_root_tree->log_mutex);
3117 goto out_wake_log_root;
3119 ret = btrfs_wait_tree_log_extents(log, mark);
3121 ret = btrfs_wait_tree_log_extents(log_root_tree,
3122 EXTENT_NEW | EXTENT_DIRTY);
3124 btrfs_set_log_full_commit(trans);
3125 mutex_unlock(&log_root_tree->log_mutex);
3126 goto out_wake_log_root;
3129 log_root_start = log_root_tree->node->start;
3130 log_root_level = btrfs_header_level(log_root_tree->node);
3131 log_root_tree->log_transid++;
3132 mutex_unlock(&log_root_tree->log_mutex);
3135 * Here we are guaranteed that nobody is going to write the superblock
3136 * for the current transaction before us and that neither we do write
3137 * our superblock before the previous transaction finishes its commit
3138 * and writes its superblock, because:
3140 * 1) We are holding a handle on the current transaction, so no body
3141 * can commit it until we release the handle;
3143 * 2) Before writing our superblock we acquire the tree_log_mutex, so
3144 * if the previous transaction is still committing, and hasn't yet
3145 * written its superblock, we wait for it to do it, because a
3146 * transaction commit acquires the tree_log_mutex when the commit
3147 * begins and releases it only after writing its superblock.
3149 mutex_lock(&fs_info->tree_log_mutex);
3152 * The previous transaction writeout phase could have failed, and thus
3153 * marked the fs in an error state. We must not commit here, as we
3154 * could have updated our generation in the super_for_commit and
3155 * writing the super here would result in transid mismatches. If there
3156 * is an error here just bail.
3158 if (BTRFS_FS_ERROR(fs_info)) {
3160 btrfs_set_log_full_commit(trans);
3161 btrfs_abort_transaction(trans, ret);
3162 mutex_unlock(&fs_info->tree_log_mutex);
3163 goto out_wake_log_root;
3166 btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
3167 btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3168 ret = write_all_supers(fs_info, 1);
3169 mutex_unlock(&fs_info->tree_log_mutex);
3171 btrfs_set_log_full_commit(trans);
3172 btrfs_abort_transaction(trans, ret);
3173 goto out_wake_log_root;
3177 * We know there can only be one task here, since we have not yet set
3178 * root->log_commit[index1] to 0 and any task attempting to sync the
3179 * log must wait for the previous log transaction to commit if it's
3180 * still in progress or wait for the current log transaction commit if
3181 * someone else already started it. We use <= and not < because the
3182 * first log transaction has an ID of 0.
3184 ASSERT(root->last_log_commit <= log_transid);
3185 root->last_log_commit = log_transid;
3188 mutex_lock(&log_root_tree->log_mutex);
3189 btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3191 log_root_tree->log_transid_committed++;
3192 atomic_set(&log_root_tree->log_commit[index2], 0);
3193 mutex_unlock(&log_root_tree->log_mutex);
3196 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3197 * all the updates above are seen by the woken threads. It might not be
3198 * necessary, but proving that seems to be hard.
3200 cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3202 mutex_lock(&root->log_mutex);
3203 btrfs_remove_all_log_ctxs(root, index1, ret);
3204 root->log_transid_committed++;
3205 atomic_set(&root->log_commit[index1], 0);
3206 mutex_unlock(&root->log_mutex);
3209 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3210 * all the updates above are seen by the woken threads. It might not be
3211 * necessary, but proving that seems to be hard.
3213 cond_wake_up(&root->log_commit_wait[index1]);
3217 static void free_log_tree(struct btrfs_trans_handle *trans,
3218 struct btrfs_root *log)
3221 struct walk_control wc = {
3223 .process_func = process_one_buffer
3227 ret = walk_log_tree(trans, log, &wc);
3230 * We weren't able to traverse the entire log tree, the
3231 * typical scenario is getting an -EIO when reading an
3232 * extent buffer of the tree, due to a previous writeback
3235 set_bit(BTRFS_FS_STATE_LOG_CLEANUP_ERROR,
3236 &log->fs_info->fs_state);
3239 * Some extent buffers of the log tree may still be dirty
3240 * and not yet written back to storage, because we may
3241 * have updates to a log tree without syncing a log tree,
3242 * such as during rename and link operations. So flush
3243 * them out and wait for their writeback to complete, so
3244 * that we properly cleanup their state and pages.
3246 btrfs_write_marked_extents(log->fs_info,
3247 &log->dirty_log_pages,
3248 EXTENT_DIRTY | EXTENT_NEW);
3249 btrfs_wait_tree_log_extents(log,
3250 EXTENT_DIRTY | EXTENT_NEW);
3253 btrfs_abort_transaction(trans, ret);
3255 btrfs_handle_fs_error(log->fs_info, ret, NULL);
3259 clear_extent_bits(&log->dirty_log_pages, 0, (u64)-1,
3260 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3261 extent_io_tree_release(&log->log_csum_range);
3263 btrfs_put_root(log);
3267 * free all the extents used by the tree log. This should be called
3268 * at commit time of the full transaction
3270 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3272 if (root->log_root) {
3273 free_log_tree(trans, root->log_root);
3274 root->log_root = NULL;
3275 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
3280 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3281 struct btrfs_fs_info *fs_info)
3283 if (fs_info->log_root_tree) {
3284 free_log_tree(trans, fs_info->log_root_tree);
3285 fs_info->log_root_tree = NULL;
3286 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
3292 * Check if an inode was logged in the current transaction. This correctly deals
3293 * with the case where the inode was logged but has a logged_trans of 0, which
3294 * happens if the inode is evicted and loaded again, as logged_trans is an in
3295 * memory only field (not persisted).
3297 * Returns 1 if the inode was logged before in the transaction, 0 if it was not,
3300 static int inode_logged(struct btrfs_trans_handle *trans,
3301 struct btrfs_inode *inode,
3302 struct btrfs_path *path_in)
3304 struct btrfs_path *path = path_in;
3305 struct btrfs_key key;
3308 if (inode->logged_trans == trans->transid)
3312 * If logged_trans is not 0, then we know the inode logged was not logged
3313 * in this transaction, so we can return false right away.
3315 if (inode->logged_trans > 0)
3319 * If no log tree was created for this root in this transaction, then
3320 * the inode can not have been logged in this transaction. In that case
3321 * set logged_trans to anything greater than 0 and less than the current
3322 * transaction's ID, to avoid the search below in a future call in case
3323 * a log tree gets created after this.
3325 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state)) {
3326 inode->logged_trans = trans->transid - 1;
3331 * We have a log tree and the inode's logged_trans is 0. We can't tell
3332 * for sure if the inode was logged before in this transaction by looking
3333 * only at logged_trans. We could be pessimistic and assume it was, but
3334 * that can lead to unnecessarily logging an inode during rename and link
3335 * operations, and then further updating the log in followup rename and
3336 * link operations, specially if it's a directory, which adds latency
3337 * visible to applications doing a series of rename or link operations.
3339 * A logged_trans of 0 here can mean several things:
3341 * 1) The inode was never logged since the filesystem was mounted, and may
3342 * or may have not been evicted and loaded again;
3344 * 2) The inode was logged in a previous transaction, then evicted and
3345 * then loaded again;
3347 * 3) The inode was logged in the current transaction, then evicted and
3348 * then loaded again.
3350 * For cases 1) and 2) we don't want to return true, but we need to detect
3351 * case 3) and return true. So we do a search in the log root for the inode
3354 key.objectid = btrfs_ino(inode);
3355 key.type = BTRFS_INODE_ITEM_KEY;
3359 path = btrfs_alloc_path();
3364 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3367 btrfs_release_path(path);
3369 btrfs_free_path(path);
3372 * Logging an inode always results in logging its inode item. So if we
3373 * did not find the item we know the inode was not logged for sure.
3377 } else if (ret > 0) {
3379 * Set logged_trans to a value greater than 0 and less then the
3380 * current transaction to avoid doing the search in future calls.
3382 inode->logged_trans = trans->transid - 1;
3387 * The inode was previously logged and then evicted, set logged_trans to
3388 * the current transacion's ID, to avoid future tree searches as long as
3389 * the inode is not evicted again.
3391 inode->logged_trans = trans->transid;
3394 * If it's a directory, then we must set last_dir_index_offset to the
3395 * maximum possible value, so that the next attempt to log the inode does
3396 * not skip checking if dir index keys found in modified subvolume tree
3397 * leaves have been logged before, otherwise it would result in attempts
3398 * to insert duplicate dir index keys in the log tree. This must be done
3399 * because last_dir_index_offset is an in-memory only field, not persisted
3400 * in the inode item or any other on-disk structure, so its value is lost
3401 * once the inode is evicted.
3403 if (S_ISDIR(inode->vfs_inode.i_mode))
3404 inode->last_dir_index_offset = (u64)-1;
3410 * Delete a directory entry from the log if it exists.
3412 * Returns < 0 on error
3413 * 1 if the entry does not exists
3414 * 0 if the entry existed and was successfully deleted
3416 static int del_logged_dentry(struct btrfs_trans_handle *trans,
3417 struct btrfs_root *log,
3418 struct btrfs_path *path,
3420 const struct fscrypt_str *name,
3423 struct btrfs_dir_item *di;
3426 * We only log dir index items of a directory, so we don't need to look
3427 * for dir item keys.
3429 di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3437 * We do not need to update the size field of the directory's
3438 * inode item because on log replay we update the field to reflect
3439 * all existing entries in the directory (see overwrite_item()).
3441 return btrfs_delete_one_dir_name(trans, log, path, di);
3445 * If both a file and directory are logged, and unlinks or renames are
3446 * mixed in, we have a few interesting corners:
3448 * create file X in dir Y
3449 * link file X to X.link in dir Y
3451 * unlink file X but leave X.link
3454 * After a crash we would expect only X.link to exist. But file X
3455 * didn't get fsync'd again so the log has back refs for X and X.link.
3457 * We solve this by removing directory entries and inode backrefs from the
3458 * log when a file that was logged in the current transaction is
3459 * unlinked. Any later fsync will include the updated log entries, and
3460 * we'll be able to reconstruct the proper directory items from backrefs.
3462 * This optimizations allows us to avoid relogging the entire inode
3463 * or the entire directory.
3465 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3466 struct btrfs_root *root,
3467 const struct fscrypt_str *name,
3468 struct btrfs_inode *dir, u64 index)
3470 struct btrfs_path *path;
3473 ret = inode_logged(trans, dir, NULL);
3477 btrfs_set_log_full_commit(trans);
3481 ret = join_running_log_trans(root);
3485 mutex_lock(&dir->log_mutex);
3487 path = btrfs_alloc_path();
3493 ret = del_logged_dentry(trans, root->log_root, path, btrfs_ino(dir),
3495 btrfs_free_path(path);
3497 mutex_unlock(&dir->log_mutex);
3499 btrfs_set_log_full_commit(trans);
3500 btrfs_end_log_trans(root);
3503 /* see comments for btrfs_del_dir_entries_in_log */
3504 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3505 struct btrfs_root *root,
3506 const struct fscrypt_str *name,
3507 struct btrfs_inode *inode, u64 dirid)
3509 struct btrfs_root *log;
3513 ret = inode_logged(trans, inode, NULL);
3517 btrfs_set_log_full_commit(trans);
3521 ret = join_running_log_trans(root);
3524 log = root->log_root;
3525 mutex_lock(&inode->log_mutex);
3527 ret = btrfs_del_inode_ref(trans, log, name, btrfs_ino(inode),
3529 mutex_unlock(&inode->log_mutex);
3530 if (ret < 0 && ret != -ENOENT)
3531 btrfs_set_log_full_commit(trans);
3532 btrfs_end_log_trans(root);
3536 * creates a range item in the log for 'dirid'. first_offset and
3537 * last_offset tell us which parts of the key space the log should
3538 * be considered authoritative for.
3540 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3541 struct btrfs_root *log,
3542 struct btrfs_path *path,
3544 u64 first_offset, u64 last_offset)
3547 struct btrfs_key key;
3548 struct btrfs_dir_log_item *item;
3550 key.objectid = dirid;
3551 key.offset = first_offset;
3552 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3553 ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3555 * -EEXIST is fine and can happen sporadically when we are logging a
3556 * directory and have concurrent insertions in the subvolume's tree for
3557 * items from other inodes and that result in pushing off some dir items
3558 * from one leaf to another in order to accommodate for the new items.
3559 * This results in logging the same dir index range key.
3561 if (ret && ret != -EEXIST)
3564 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3565 struct btrfs_dir_log_item);
3566 if (ret == -EEXIST) {
3567 const u64 curr_end = btrfs_dir_log_end(path->nodes[0], item);
3570 * btrfs_del_dir_entries_in_log() might have been called during
3571 * an unlink between the initial insertion of this key and the
3572 * current update, or we might be logging a single entry deletion
3573 * during a rename, so set the new last_offset to the max value.
3575 last_offset = max(last_offset, curr_end);
3577 btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3578 btrfs_mark_buffer_dirty(path->nodes[0]);
3579 btrfs_release_path(path);
3583 static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
3584 struct btrfs_inode *inode,
3585 struct extent_buffer *src,
3586 struct btrfs_path *dst_path,
3590 struct btrfs_root *log = inode->root->log_root;
3591 char *ins_data = NULL;
3592 struct btrfs_item_batch batch;
3593 struct extent_buffer *dst;
3594 unsigned long src_offset;
3595 unsigned long dst_offset;
3597 struct btrfs_key key;
3606 btrfs_item_key_to_cpu(src, &key, start_slot);
3607 item_size = btrfs_item_size(src, start_slot);
3609 batch.data_sizes = &item_size;
3610 batch.total_data_size = item_size;
3612 struct btrfs_key *ins_keys;
3615 ins_data = kmalloc(count * sizeof(u32) +
3616 count * sizeof(struct btrfs_key), GFP_NOFS);
3620 ins_sizes = (u32 *)ins_data;
3621 ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
3622 batch.keys = ins_keys;
3623 batch.data_sizes = ins_sizes;
3624 batch.total_data_size = 0;
3626 for (i = 0; i < count; i++) {
3627 const int slot = start_slot + i;
3629 btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
3630 ins_sizes[i] = btrfs_item_size(src, slot);
3631 batch.total_data_size += ins_sizes[i];
3635 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
3639 dst = dst_path->nodes[0];
3641 * Copy all the items in bulk, in a single copy operation. Item data is
3642 * organized such that it's placed at the end of a leaf and from right
3643 * to left. For example, the data for the second item ends at an offset
3644 * that matches the offset where the data for the first item starts, the
3645 * data for the third item ends at an offset that matches the offset
3646 * where the data of the second items starts, and so on.
3647 * Therefore our source and destination start offsets for copy match the
3648 * offsets of the last items (highest slots).
3650 dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
3651 src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
3652 copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
3653 btrfs_release_path(dst_path);
3655 last_index = batch.keys[count - 1].offset;
3656 ASSERT(last_index > inode->last_dir_index_offset);
3659 * If for some unexpected reason the last item's index is not greater
3660 * than the last index we logged, warn and return an error to fallback
3661 * to a transaction commit.
3663 if (WARN_ON(last_index <= inode->last_dir_index_offset))
3666 inode->last_dir_index_offset = last_index;
3673 static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
3674 struct btrfs_inode *inode,
3675 struct btrfs_path *path,
3676 struct btrfs_path *dst_path,
3677 struct btrfs_log_ctx *ctx,
3678 u64 *last_old_dentry_offset)
3680 struct btrfs_root *log = inode->root->log_root;
3681 struct extent_buffer *src;
3682 const int nritems = btrfs_header_nritems(path->nodes[0]);
3683 const u64 ino = btrfs_ino(inode);
3684 bool last_found = false;
3685 int batch_start = 0;
3690 * We need to clone the leaf, release the read lock on it, and use the
3691 * clone before modifying the log tree. See the comment at copy_items()
3692 * about why we need to do this.
3694 src = btrfs_clone_extent_buffer(path->nodes[0]);
3699 btrfs_release_path(path);
3700 path->nodes[0] = src;
3703 for (; i < nritems; i++) {
3704 struct btrfs_dir_item *di;
3705 struct btrfs_key key;
3708 btrfs_item_key_to_cpu(src, &key, i);
3710 if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
3715 di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3718 * Skip ranges of items that consist only of dir item keys created
3719 * in past transactions. However if we find a gap, we must log a
3720 * dir index range item for that gap, so that index keys in that
3721 * gap are deleted during log replay.
3723 if (btrfs_dir_transid(src, di) < trans->transid) {
3724 if (key.offset > *last_old_dentry_offset + 1) {
3725 ret = insert_dir_log_key(trans, log, dst_path,
3726 ino, *last_old_dentry_offset + 1,
3732 *last_old_dentry_offset = key.offset;
3736 /* If we logged this dir index item before, we can skip it. */
3737 if (key.offset <= inode->last_dir_index_offset)
3741 * We must make sure that when we log a directory entry, the
3742 * corresponding inode, after log replay, has a matching link
3743 * count. For example:
3749 * xfs_io -c "fsync" mydir
3751 * <mount fs and log replay>
3753 * Would result in a fsync log that when replayed, our file inode
3754 * would have a link count of 1, but we get two directory entries
3755 * pointing to the same inode. After removing one of the names,
3756 * it would not be possible to remove the other name, which
3757 * resulted always in stale file handle errors, and would not be
3758 * possible to rmdir the parent directory, since its i_size could
3759 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
3760 * resulting in -ENOTEMPTY errors.
3762 if (!ctx->log_new_dentries) {
3763 struct btrfs_key di_key;
3765 btrfs_dir_item_key_to_cpu(src, di, &di_key);
3766 if (di_key.type != BTRFS_ROOT_ITEM_KEY)
3767 ctx->log_new_dentries = true;
3770 if (batch_size == 0)
3775 if (batch_size > 0) {
3778 ret = flush_dir_items_batch(trans, inode, src, dst_path,
3779 batch_start, batch_size);
3784 return last_found ? 1 : 0;
3788 * log all the items included in the current transaction for a given
3789 * directory. This also creates the range items in the log tree required
3790 * to replay anything deleted before the fsync
3792 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3793 struct btrfs_inode *inode,
3794 struct btrfs_path *path,
3795 struct btrfs_path *dst_path,
3796 struct btrfs_log_ctx *ctx,
3797 u64 min_offset, u64 *last_offset_ret)
3799 struct btrfs_key min_key;
3800 struct btrfs_root *root = inode->root;
3801 struct btrfs_root *log = root->log_root;
3804 u64 last_old_dentry_offset = min_offset - 1;
3805 u64 last_offset = (u64)-1;
3806 u64 ino = btrfs_ino(inode);
3808 min_key.objectid = ino;
3809 min_key.type = BTRFS_DIR_INDEX_KEY;
3810 min_key.offset = min_offset;
3812 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3815 * we didn't find anything from this transaction, see if there
3816 * is anything at all
3818 if (ret != 0 || min_key.objectid != ino ||
3819 min_key.type != BTRFS_DIR_INDEX_KEY) {
3820 min_key.objectid = ino;
3821 min_key.type = BTRFS_DIR_INDEX_KEY;
3822 min_key.offset = (u64)-1;
3823 btrfs_release_path(path);
3824 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3826 btrfs_release_path(path);
3829 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3831 /* if ret == 0 there are items for this type,
3832 * create a range to tell us the last key of this type.
3833 * otherwise, there are no items in this directory after
3834 * *min_offset, and we create a range to indicate that.
3837 struct btrfs_key tmp;
3839 btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3841 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3842 last_old_dentry_offset = tmp.offset;
3843 } else if (ret < 0) {
3850 /* go backward to find any previous key */
3851 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3853 struct btrfs_key tmp;
3855 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3857 * The dir index key before the first one we found that needs to
3858 * be logged might be in a previous leaf, and there might be a
3859 * gap between these keys, meaning that we had deletions that
3860 * happened. So the key range item we log (key type
3861 * BTRFS_DIR_LOG_INDEX_KEY) must cover a range that starts at the
3862 * previous key's offset plus 1, so that those deletes are replayed.
3864 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3865 last_old_dentry_offset = tmp.offset;
3866 } else if (ret < 0) {
3871 btrfs_release_path(path);
3874 * Find the first key from this transaction again or the one we were at
3875 * in the loop below in case we had to reschedule. We may be logging the
3876 * directory without holding its VFS lock, which happen when logging new
3877 * dentries (through log_new_dir_dentries()) or in some cases when we
3878 * need to log the parent directory of an inode. This means a dir index
3879 * key might be deleted from the inode's root, and therefore we may not
3880 * find it anymore. If we can't find it, just move to the next key. We
3881 * can not bail out and ignore, because if we do that we will simply
3882 * not log dir index keys that come after the one that was just deleted
3883 * and we can end up logging a dir index range that ends at (u64)-1
3884 * (@last_offset is initialized to that), resulting in removing dir
3885 * entries we should not remove at log replay time.
3888 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3890 ret = btrfs_next_item(root, path);
3893 /* If ret is 1, there are no more keys in the inode's root. */
3898 * we have a block from this transaction, log every item in it
3899 * from our directory
3902 ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx,
3903 &last_old_dentry_offset);
3909 path->slots[0] = btrfs_header_nritems(path->nodes[0]);
3912 * look ahead to the next item and see if it is also
3913 * from this directory and from this transaction
3915 ret = btrfs_next_leaf(root, path);
3918 last_offset = (u64)-1;
3923 btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
3924 if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
3925 last_offset = (u64)-1;
3928 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3930 * The next leaf was not changed in the current transaction
3931 * and has at least one dir index key.
3932 * We check for the next key because there might have been
3933 * one or more deletions between the last key we logged and
3934 * that next key. So the key range item we log (key type
3935 * BTRFS_DIR_LOG_INDEX_KEY) must end at the next key's
3936 * offset minus 1, so that those deletes are replayed.
3938 last_offset = min_key.offset - 1;
3941 if (need_resched()) {
3942 btrfs_release_path(path);
3948 btrfs_release_path(path);
3949 btrfs_release_path(dst_path);
3952 *last_offset_ret = last_offset;
3954 * In case the leaf was changed in the current transaction but
3955 * all its dir items are from a past transaction, the last item
3956 * in the leaf is a dir item and there's no gap between that last
3957 * dir item and the first one on the next leaf (which did not
3958 * change in the current transaction), then we don't need to log
3959 * a range, last_old_dentry_offset is == to last_offset.
3961 ASSERT(last_old_dentry_offset <= last_offset);
3962 if (last_old_dentry_offset < last_offset) {
3963 ret = insert_dir_log_key(trans, log, path, ino,
3964 last_old_dentry_offset + 1,
3974 * If the inode was logged before and it was evicted, then its
3975 * last_dir_index_offset is (u64)-1, so we don't the value of the last index
3976 * key offset. If that's the case, search for it and update the inode. This
3977 * is to avoid lookups in the log tree every time we try to insert a dir index
3978 * key from a leaf changed in the current transaction, and to allow us to always
3979 * do batch insertions of dir index keys.
3981 static int update_last_dir_index_offset(struct btrfs_inode *inode,
3982 struct btrfs_path *path,
3983 const struct btrfs_log_ctx *ctx)
3985 const u64 ino = btrfs_ino(inode);
3986 struct btrfs_key key;
3989 lockdep_assert_held(&inode->log_mutex);
3991 if (inode->last_dir_index_offset != (u64)-1)
3994 if (!ctx->logged_before) {
3995 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
4000 key.type = BTRFS_DIR_INDEX_KEY;
4001 key.offset = (u64)-1;
4003 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
4005 * An error happened or we actually have an index key with an offset
4006 * value of (u64)-1. Bail out, we're done.
4012 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
4015 * No dir index items, bail out and leave last_dir_index_offset with
4016 * the value right before the first valid index value.
4018 if (path->slots[0] == 0)
4022 * btrfs_search_slot() left us at one slot beyond the slot with the last
4023 * index key, or beyond the last key of the directory that is not an
4024 * index key. If we have an index key before, set last_dir_index_offset
4025 * to its offset value, otherwise leave it with a value right before the
4026 * first valid index value, as it means we have an empty directory.
4028 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
4029 if (key.objectid == ino && key.type == BTRFS_DIR_INDEX_KEY)
4030 inode->last_dir_index_offset = key.offset;
4033 btrfs_release_path(path);
4039 * logging directories is very similar to logging inodes, We find all the items
4040 * from the current transaction and write them to the log.
4042 * The recovery code scans the directory in the subvolume, and if it finds a
4043 * key in the range logged that is not present in the log tree, then it means
4044 * that dir entry was unlinked during the transaction.
4046 * In order for that scan to work, we must include one key smaller than
4047 * the smallest logged by this transaction and one key larger than the largest
4048 * key logged by this transaction.
4050 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
4051 struct btrfs_inode *inode,
4052 struct btrfs_path *path,
4053 struct btrfs_path *dst_path,
4054 struct btrfs_log_ctx *ctx)
4060 ret = update_last_dir_index_offset(inode, path, ctx);
4064 min_key = BTRFS_DIR_START_INDEX;
4068 ret = log_dir_items(trans, inode, path, dst_path,
4069 ctx, min_key, &max_key);
4072 if (max_key == (u64)-1)
4074 min_key = max_key + 1;
4081 * a helper function to drop items from the log before we relog an
4082 * inode. max_key_type indicates the highest item type to remove.
4083 * This cannot be run for file data extents because it does not
4084 * free the extents they point to.
4086 static int drop_inode_items(struct btrfs_trans_handle *trans,
4087 struct btrfs_root *log,
4088 struct btrfs_path *path,
4089 struct btrfs_inode *inode,
4093 struct btrfs_key key;
4094 struct btrfs_key found_key;
4097 key.objectid = btrfs_ino(inode);
4098 key.type = max_key_type;
4099 key.offset = (u64)-1;
4102 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
4103 BUG_ON(ret == 0); /* Logic error */
4107 if (path->slots[0] == 0)
4111 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4114 if (found_key.objectid != key.objectid)
4117 found_key.offset = 0;
4119 ret = btrfs_bin_search(path->nodes[0], &found_key, &start_slot);
4123 ret = btrfs_del_items(trans, log, path, start_slot,
4124 path->slots[0] - start_slot + 1);
4126 * If start slot isn't 0 then we don't need to re-search, we've
4127 * found the last guy with the objectid in this tree.
4129 if (ret || start_slot != 0)
4131 btrfs_release_path(path);
4133 btrfs_release_path(path);
4139 static int truncate_inode_items(struct btrfs_trans_handle *trans,
4140 struct btrfs_root *log_root,
4141 struct btrfs_inode *inode,
4142 u64 new_size, u32 min_type)
4144 struct btrfs_truncate_control control = {
4145 .new_size = new_size,
4146 .ino = btrfs_ino(inode),
4147 .min_type = min_type,
4148 .skip_ref_updates = true,
4151 return btrfs_truncate_inode_items(trans, log_root, &control);
4154 static void fill_inode_item(struct btrfs_trans_handle *trans,
4155 struct extent_buffer *leaf,
4156 struct btrfs_inode_item *item,
4157 struct inode *inode, int log_inode_only,
4160 struct btrfs_map_token token;
4163 btrfs_init_map_token(&token, leaf);
4165 if (log_inode_only) {
4166 /* set the generation to zero so the recover code
4167 * can tell the difference between an logging
4168 * just to say 'this inode exists' and a logging
4169 * to say 'update this inode with these values'
4171 btrfs_set_token_inode_generation(&token, item, 0);
4172 btrfs_set_token_inode_size(&token, item, logged_isize);
4174 btrfs_set_token_inode_generation(&token, item,
4175 BTRFS_I(inode)->generation);
4176 btrfs_set_token_inode_size(&token, item, inode->i_size);
4179 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4180 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4181 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4182 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4184 btrfs_set_token_timespec_sec(&token, &item->atime,
4185 inode->i_atime.tv_sec);
4186 btrfs_set_token_timespec_nsec(&token, &item->atime,
4187 inode->i_atime.tv_nsec);
4189 btrfs_set_token_timespec_sec(&token, &item->mtime,
4190 inode->i_mtime.tv_sec);
4191 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4192 inode->i_mtime.tv_nsec);
4194 btrfs_set_token_timespec_sec(&token, &item->ctime,
4195 inode->i_ctime.tv_sec);
4196 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4197 inode->i_ctime.tv_nsec);
4200 * We do not need to set the nbytes field, in fact during a fast fsync
4201 * its value may not even be correct, since a fast fsync does not wait
4202 * for ordered extent completion, which is where we update nbytes, it
4203 * only waits for writeback to complete. During log replay as we find
4204 * file extent items and replay them, we adjust the nbytes field of the
4205 * inode item in subvolume tree as needed (see overwrite_item()).
4208 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4209 btrfs_set_token_inode_transid(&token, item, trans->transid);
4210 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4211 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4212 BTRFS_I(inode)->ro_flags);
4213 btrfs_set_token_inode_flags(&token, item, flags);
4214 btrfs_set_token_inode_block_group(&token, item, 0);
4217 static int log_inode_item(struct btrfs_trans_handle *trans,
4218 struct btrfs_root *log, struct btrfs_path *path,
4219 struct btrfs_inode *inode, bool inode_item_dropped)
4221 struct btrfs_inode_item *inode_item;
4225 * If we are doing a fast fsync and the inode was logged before in the
4226 * current transaction, then we know the inode was previously logged and
4227 * it exists in the log tree. For performance reasons, in this case use
4228 * btrfs_search_slot() directly with ins_len set to 0 so that we never
4229 * attempt a write lock on the leaf's parent, which adds unnecessary lock
4230 * contention in case there are concurrent fsyncs for other inodes of the
4231 * same subvolume. Using btrfs_insert_empty_item() when the inode item
4232 * already exists can also result in unnecessarily splitting a leaf.
4234 if (!inode_item_dropped && inode->logged_trans == trans->transid) {
4235 ret = btrfs_search_slot(trans, log, &inode->location, path, 0, 1);
4241 * This means it is the first fsync in the current transaction,
4242 * so the inode item is not in the log and we need to insert it.
4243 * We can never get -EEXIST because we are only called for a fast
4244 * fsync and in case an inode eviction happens after the inode was
4245 * logged before in the current transaction, when we load again
4246 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
4247 * flags and set ->logged_trans to 0.
4249 ret = btrfs_insert_empty_item(trans, log, path, &inode->location,
4250 sizeof(*inode_item));
4251 ASSERT(ret != -EEXIST);
4255 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4256 struct btrfs_inode_item);
4257 fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
4259 btrfs_release_path(path);
4263 static int log_csums(struct btrfs_trans_handle *trans,
4264 struct btrfs_inode *inode,
4265 struct btrfs_root *log_root,
4266 struct btrfs_ordered_sum *sums)
4268 const u64 lock_end = sums->bytenr + sums->len - 1;
4269 struct extent_state *cached_state = NULL;
4273 * If this inode was not used for reflink operations in the current
4274 * transaction with new extents, then do the fast path, no need to
4275 * worry about logging checksum items with overlapping ranges.
4277 if (inode->last_reflink_trans < trans->transid)
4278 return btrfs_csum_file_blocks(trans, log_root, sums);
4281 * Serialize logging for checksums. This is to avoid racing with the
4282 * same checksum being logged by another task that is logging another
4283 * file which happens to refer to the same extent as well. Such races
4284 * can leave checksum items in the log with overlapping ranges.
4286 ret = lock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4291 * Due to extent cloning, we might have logged a csum item that covers a
4292 * subrange of a cloned extent, and later we can end up logging a csum
4293 * item for a larger subrange of the same extent or the entire range.
4294 * This would leave csum items in the log tree that cover the same range
4295 * and break the searches for checksums in the log tree, resulting in
4296 * some checksums missing in the fs/subvolume tree. So just delete (or
4297 * trim and adjust) any existing csum items in the log for this range.
4299 ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
4301 ret = btrfs_csum_file_blocks(trans, log_root, sums);
4303 unlock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4309 static noinline int copy_items(struct btrfs_trans_handle *trans,
4310 struct btrfs_inode *inode,
4311 struct btrfs_path *dst_path,
4312 struct btrfs_path *src_path,
4313 int start_slot, int nr, int inode_only,
4316 struct btrfs_root *log = inode->root->log_root;
4317 struct btrfs_file_extent_item *extent;
4318 struct extent_buffer *src;
4320 struct btrfs_key *ins_keys;
4322 struct btrfs_item_batch batch;
4326 const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
4327 const u64 i_size = i_size_read(&inode->vfs_inode);
4330 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4331 * use the clone. This is because otherwise we would be changing the log
4332 * tree, to insert items from the subvolume tree or insert csum items,
4333 * while holding a read lock on a leaf from the subvolume tree, which
4334 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4336 * 1) Modifying the log tree triggers an extent buffer allocation while
4337 * holding a write lock on a parent extent buffer from the log tree.
4338 * Allocating the pages for an extent buffer, or the extent buffer
4339 * struct, can trigger inode eviction and finally the inode eviction
4340 * will trigger a release/remove of a delayed node, which requires
4341 * taking the delayed node's mutex;
4343 * 2) Allocating a metadata extent for a log tree can trigger the async
4344 * reclaim thread and make us wait for it to release enough space and
4345 * unblock our reservation ticket. The reclaim thread can start
4346 * flushing delayed items, and that in turn results in the need to
4347 * lock delayed node mutexes and in the need to write lock extent
4348 * buffers of a subvolume tree - all this while holding a write lock
4349 * on the parent extent buffer in the log tree.
4351 * So one task in scenario 1) running in parallel with another task in
4352 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4353 * node mutex while having a read lock on a leaf from the subvolume,
4354 * while the other is holding the delayed node's mutex and wants to
4355 * write lock the same subvolume leaf for flushing delayed items.
4357 src = btrfs_clone_extent_buffer(src_path->nodes[0]);
4361 i = src_path->slots[0];
4362 btrfs_release_path(src_path);
4363 src_path->nodes[0] = src;
4364 src_path->slots[0] = i;
4366 ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
4367 nr * sizeof(u32), GFP_NOFS);
4371 ins_sizes = (u32 *)ins_data;
4372 ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4373 batch.keys = ins_keys;
4374 batch.data_sizes = ins_sizes;
4375 batch.total_data_size = 0;
4379 for (i = 0; i < nr; i++) {
4380 const int src_slot = start_slot + i;
4381 struct btrfs_root *csum_root;
4382 struct btrfs_ordered_sum *sums;
4383 struct btrfs_ordered_sum *sums_next;
4384 LIST_HEAD(ordered_sums);
4388 u64 extent_num_bytes;
4391 btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
4393 if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
4396 extent = btrfs_item_ptr(src, src_slot,
4397 struct btrfs_file_extent_item);
4399 is_old_extent = (btrfs_file_extent_generation(src, extent) <
4403 * Don't copy extents from past generations. That would make us
4404 * log a lot more metadata for common cases like doing only a
4405 * few random writes into a file and then fsync it for the first
4406 * time or after the full sync flag is set on the inode. We can
4407 * get leaves full of extent items, most of which are from past
4408 * generations, so we can skip them - as long as the inode has
4409 * not been the target of a reflink operation in this transaction,
4410 * as in that case it might have had file extent items with old
4411 * generations copied into it. We also must always log prealloc
4412 * extents that start at or beyond eof, otherwise we would lose
4413 * them on log replay.
4415 if (is_old_extent &&
4416 ins_keys[dst_index].offset < i_size &&
4417 inode->last_reflink_trans < trans->transid)
4423 /* Only regular extents have checksums. */
4424 if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
4428 * If it's an extent created in a past transaction, then its
4429 * checksums are already accessible from the committed csum tree,
4430 * no need to log them.
4435 disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
4436 /* If it's an explicit hole, there are no checksums. */
4437 if (disk_bytenr == 0)
4440 disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
4442 if (btrfs_file_extent_compression(src, extent)) {
4444 extent_num_bytes = disk_num_bytes;
4446 extent_offset = btrfs_file_extent_offset(src, extent);
4447 extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
4450 csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
4451 disk_bytenr += extent_offset;
4452 ret = btrfs_lookup_csums_range(csum_root, disk_bytenr,
4453 disk_bytenr + extent_num_bytes - 1,
4454 &ordered_sums, 0, false);
4458 list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
4460 ret = log_csums(trans, inode, log, sums);
4461 list_del(&sums->list);
4468 ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
4469 batch.total_data_size += ins_sizes[dst_index];
4475 * We have a leaf full of old extent items that don't need to be logged,
4476 * so we don't need to do anything.
4481 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4486 for (i = 0; i < nr; i++) {
4487 const int src_slot = start_slot + i;
4488 const int dst_slot = dst_path->slots[0] + dst_index;
4489 struct btrfs_key key;
4490 unsigned long src_offset;
4491 unsigned long dst_offset;
4494 * We're done, all the remaining items in the source leaf
4495 * correspond to old file extent items.
4497 if (dst_index >= batch.nr)
4500 btrfs_item_key_to_cpu(src, &key, src_slot);
4502 if (key.type != BTRFS_EXTENT_DATA_KEY)
4505 extent = btrfs_item_ptr(src, src_slot,
4506 struct btrfs_file_extent_item);
4508 /* See the comment in the previous loop, same logic. */
4509 if (btrfs_file_extent_generation(src, extent) < trans->transid &&
4510 key.offset < i_size &&
4511 inode->last_reflink_trans < trans->transid)
4515 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
4516 src_offset = btrfs_item_ptr_offset(src, src_slot);
4518 if (key.type == BTRFS_INODE_ITEM_KEY) {
4519 struct btrfs_inode_item *inode_item;
4521 inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
4522 struct btrfs_inode_item);
4523 fill_inode_item(trans, dst_path->nodes[0], inode_item,
4525 inode_only == LOG_INODE_EXISTS,
4528 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4529 src_offset, ins_sizes[dst_index]);
4535 btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4536 btrfs_release_path(dst_path);
4543 static int extent_cmp(void *priv, const struct list_head *a,
4544 const struct list_head *b)
4546 const struct extent_map *em1, *em2;
4548 em1 = list_entry(a, struct extent_map, list);
4549 em2 = list_entry(b, struct extent_map, list);
4551 if (em1->start < em2->start)
4553 else if (em1->start > em2->start)
4558 static int log_extent_csums(struct btrfs_trans_handle *trans,
4559 struct btrfs_inode *inode,
4560 struct btrfs_root *log_root,
4561 const struct extent_map *em,
4562 struct btrfs_log_ctx *ctx)
4564 struct btrfs_ordered_extent *ordered;
4565 struct btrfs_root *csum_root;
4568 u64 mod_start = em->mod_start;
4569 u64 mod_len = em->mod_len;
4570 LIST_HEAD(ordered_sums);
4573 if (inode->flags & BTRFS_INODE_NODATASUM ||
4574 test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
4575 em->block_start == EXTENT_MAP_HOLE)
4578 list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
4579 const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
4580 const u64 mod_end = mod_start + mod_len;
4581 struct btrfs_ordered_sum *sums;
4586 if (ordered_end <= mod_start)
4588 if (mod_end <= ordered->file_offset)
4592 * We are going to copy all the csums on this ordered extent, so
4593 * go ahead and adjust mod_start and mod_len in case this ordered
4594 * extent has already been logged.
4596 if (ordered->file_offset > mod_start) {
4597 if (ordered_end >= mod_end)
4598 mod_len = ordered->file_offset - mod_start;
4600 * If we have this case
4602 * |--------- logged extent ---------|
4603 * |----- ordered extent ----|
4605 * Just don't mess with mod_start and mod_len, we'll
4606 * just end up logging more csums than we need and it
4610 if (ordered_end < mod_end) {
4611 mod_len = mod_end - ordered_end;
4612 mod_start = ordered_end;
4619 * To keep us from looping for the above case of an ordered
4620 * extent that falls inside of the logged extent.
4622 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
4625 list_for_each_entry(sums, &ordered->list, list) {
4626 ret = log_csums(trans, inode, log_root, sums);
4632 /* We're done, found all csums in the ordered extents. */
4636 /* If we're compressed we have to save the entire range of csums. */
4637 if (em->compress_type) {
4639 csum_len = max(em->block_len, em->orig_block_len);
4641 csum_offset = mod_start - em->start;
4645 /* block start is already adjusted for the file extent offset. */
4646 csum_root = btrfs_csum_root(trans->fs_info, em->block_start);
4647 ret = btrfs_lookup_csums_range(csum_root,
4648 em->block_start + csum_offset,
4649 em->block_start + csum_offset +
4650 csum_len - 1, &ordered_sums, 0, false);
4654 while (!list_empty(&ordered_sums)) {
4655 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4656 struct btrfs_ordered_sum,
4659 ret = log_csums(trans, inode, log_root, sums);
4660 list_del(&sums->list);
4667 static int log_one_extent(struct btrfs_trans_handle *trans,
4668 struct btrfs_inode *inode,
4669 const struct extent_map *em,
4670 struct btrfs_path *path,
4671 struct btrfs_log_ctx *ctx)
4673 struct btrfs_drop_extents_args drop_args = { 0 };
4674 struct btrfs_root *log = inode->root->log_root;
4675 struct btrfs_file_extent_item fi = { 0 };
4676 struct extent_buffer *leaf;
4677 struct btrfs_key key;
4678 u64 extent_offset = em->start - em->orig_start;
4682 btrfs_set_stack_file_extent_generation(&fi, trans->transid);
4683 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4684 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
4686 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
4688 block_len = max(em->block_len, em->orig_block_len);
4689 if (em->compress_type != BTRFS_COMPRESS_NONE) {
4690 btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start);
4691 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4692 } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4693 btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start -
4695 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4698 btrfs_set_stack_file_extent_offset(&fi, extent_offset);
4699 btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
4700 btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
4701 btrfs_set_stack_file_extent_compression(&fi, em->compress_type);
4703 ret = log_extent_csums(trans, inode, log, em, ctx);
4708 * If this is the first time we are logging the inode in the current
4709 * transaction, we can avoid btrfs_drop_extents(), which is expensive
4710 * because it does a deletion search, which always acquires write locks
4711 * for extent buffers at levels 2, 1 and 0. This not only wastes time
4712 * but also adds significant contention in a log tree, since log trees
4713 * are small, with a root at level 2 or 3 at most, due to their short
4716 if (ctx->logged_before) {
4717 drop_args.path = path;
4718 drop_args.start = em->start;
4719 drop_args.end = em->start + em->len;
4720 drop_args.replace_extent = true;
4721 drop_args.extent_item_size = sizeof(fi);
4722 ret = btrfs_drop_extents(trans, log, inode, &drop_args);
4727 if (!drop_args.extent_inserted) {
4728 key.objectid = btrfs_ino(inode);
4729 key.type = BTRFS_EXTENT_DATA_KEY;
4730 key.offset = em->start;
4732 ret = btrfs_insert_empty_item(trans, log, path, &key,
4737 leaf = path->nodes[0];
4738 write_extent_buffer(leaf, &fi,
4739 btrfs_item_ptr_offset(leaf, path->slots[0]),
4741 btrfs_mark_buffer_dirty(leaf);
4743 btrfs_release_path(path);
4749 * Log all prealloc extents beyond the inode's i_size to make sure we do not
4750 * lose them after doing a full/fast fsync and replaying the log. We scan the
4751 * subvolume's root instead of iterating the inode's extent map tree because
4752 * otherwise we can log incorrect extent items based on extent map conversion.
4753 * That can happen due to the fact that extent maps are merged when they
4754 * are not in the extent map tree's list of modified extents.
4756 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4757 struct btrfs_inode *inode,
4758 struct btrfs_path *path)
4760 struct btrfs_root *root = inode->root;
4761 struct btrfs_key key;
4762 const u64 i_size = i_size_read(&inode->vfs_inode);
4763 const u64 ino = btrfs_ino(inode);
4764 struct btrfs_path *dst_path = NULL;
4765 bool dropped_extents = false;
4766 u64 truncate_offset = i_size;
4767 struct extent_buffer *leaf;
4773 if (!(inode->flags & BTRFS_INODE_PREALLOC))
4777 key.type = BTRFS_EXTENT_DATA_KEY;
4778 key.offset = i_size;
4779 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4784 * We must check if there is a prealloc extent that starts before the
4785 * i_size and crosses the i_size boundary. This is to ensure later we
4786 * truncate down to the end of that extent and not to the i_size, as
4787 * otherwise we end up losing part of the prealloc extent after a log
4788 * replay and with an implicit hole if there is another prealloc extent
4789 * that starts at an offset beyond i_size.
4791 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4796 struct btrfs_file_extent_item *ei;
4798 leaf = path->nodes[0];
4799 slot = path->slots[0];
4800 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4802 if (btrfs_file_extent_type(leaf, ei) ==
4803 BTRFS_FILE_EXTENT_PREALLOC) {
4806 btrfs_item_key_to_cpu(leaf, &key, slot);
4807 extent_end = key.offset +
4808 btrfs_file_extent_num_bytes(leaf, ei);
4810 if (extent_end > i_size)
4811 truncate_offset = extent_end;
4818 leaf = path->nodes[0];
4819 slot = path->slots[0];
4821 if (slot >= btrfs_header_nritems(leaf)) {
4823 ret = copy_items(trans, inode, dst_path, path,
4824 start_slot, ins_nr, 1, 0);
4829 ret = btrfs_next_leaf(root, path);
4839 btrfs_item_key_to_cpu(leaf, &key, slot);
4840 if (key.objectid > ino)
4842 if (WARN_ON_ONCE(key.objectid < ino) ||
4843 key.type < BTRFS_EXTENT_DATA_KEY ||
4844 key.offset < i_size) {
4848 if (!dropped_extents) {
4850 * Avoid logging extent items logged in past fsync calls
4851 * and leading to duplicate keys in the log tree.
4853 ret = truncate_inode_items(trans, root->log_root, inode,
4855 BTRFS_EXTENT_DATA_KEY);
4858 dropped_extents = true;
4865 dst_path = btrfs_alloc_path();
4873 ret = copy_items(trans, inode, dst_path, path,
4874 start_slot, ins_nr, 1, 0);
4876 btrfs_release_path(path);
4877 btrfs_free_path(dst_path);
4881 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4882 struct btrfs_inode *inode,
4883 struct btrfs_path *path,
4884 struct btrfs_log_ctx *ctx)
4886 struct btrfs_ordered_extent *ordered;
4887 struct btrfs_ordered_extent *tmp;
4888 struct extent_map *em, *n;
4889 struct list_head extents;
4890 struct extent_map_tree *tree = &inode->extent_tree;
4894 INIT_LIST_HEAD(&extents);
4896 write_lock(&tree->lock);
4898 list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4899 list_del_init(&em->list);
4901 * Just an arbitrary number, this can be really CPU intensive
4902 * once we start getting a lot of extents, and really once we
4903 * have a bunch of extents we just want to commit since it will
4906 if (++num > 32768) {
4907 list_del_init(&tree->modified_extents);
4912 if (em->generation < trans->transid)
4915 /* We log prealloc extents beyond eof later. */
4916 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
4917 em->start >= i_size_read(&inode->vfs_inode))
4920 /* Need a ref to keep it from getting evicted from cache */
4921 refcount_inc(&em->refs);
4922 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
4923 list_add_tail(&em->list, &extents);
4927 list_sort(NULL, &extents, extent_cmp);
4929 while (!list_empty(&extents)) {
4930 em = list_entry(extents.next, struct extent_map, list);
4932 list_del_init(&em->list);
4935 * If we had an error we just need to delete everybody from our
4939 clear_em_logging(tree, em);
4940 free_extent_map(em);
4944 write_unlock(&tree->lock);
4946 ret = log_one_extent(trans, inode, em, path, ctx);
4947 write_lock(&tree->lock);
4948 clear_em_logging(tree, em);
4949 free_extent_map(em);
4951 WARN_ON(!list_empty(&extents));
4952 write_unlock(&tree->lock);
4955 ret = btrfs_log_prealloc_extents(trans, inode, path);
4960 * We have logged all extents successfully, now make sure the commit of
4961 * the current transaction waits for the ordered extents to complete
4962 * before it commits and wipes out the log trees, otherwise we would
4963 * lose data if an ordered extents completes after the transaction
4964 * commits and a power failure happens after the transaction commit.
4966 list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
4967 list_del_init(&ordered->log_list);
4968 set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
4970 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4971 spin_lock_irq(&inode->ordered_tree.lock);
4972 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4973 set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
4974 atomic_inc(&trans->transaction->pending_ordered);
4976 spin_unlock_irq(&inode->ordered_tree.lock);
4978 btrfs_put_ordered_extent(ordered);
4984 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
4985 struct btrfs_path *path, u64 *size_ret)
4987 struct btrfs_key key;
4990 key.objectid = btrfs_ino(inode);
4991 key.type = BTRFS_INODE_ITEM_KEY;
4994 ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4997 } else if (ret > 0) {
5000 struct btrfs_inode_item *item;
5002 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5003 struct btrfs_inode_item);
5004 *size_ret = btrfs_inode_size(path->nodes[0], item);
5006 * If the in-memory inode's i_size is smaller then the inode
5007 * size stored in the btree, return the inode's i_size, so
5008 * that we get a correct inode size after replaying the log
5009 * when before a power failure we had a shrinking truncate
5010 * followed by addition of a new name (rename / new hard link).
5011 * Otherwise return the inode size from the btree, to avoid
5012 * data loss when replaying a log due to previously doing a
5013 * write that expands the inode's size and logging a new name
5014 * immediately after.
5016 if (*size_ret > inode->vfs_inode.i_size)
5017 *size_ret = inode->vfs_inode.i_size;
5020 btrfs_release_path(path);
5025 * At the moment we always log all xattrs. This is to figure out at log replay
5026 * time which xattrs must have their deletion replayed. If a xattr is missing
5027 * in the log tree and exists in the fs/subvol tree, we delete it. This is
5028 * because if a xattr is deleted, the inode is fsynced and a power failure
5029 * happens, causing the log to be replayed the next time the fs is mounted,
5030 * we want the xattr to not exist anymore (same behaviour as other filesystems
5031 * with a journal, ext3/4, xfs, f2fs, etc).
5033 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
5034 struct btrfs_inode *inode,
5035 struct btrfs_path *path,
5036 struct btrfs_path *dst_path)
5038 struct btrfs_root *root = inode->root;
5040 struct btrfs_key key;
5041 const u64 ino = btrfs_ino(inode);
5044 bool found_xattrs = false;
5046 if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5050 key.type = BTRFS_XATTR_ITEM_KEY;
5053 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5058 int slot = path->slots[0];
5059 struct extent_buffer *leaf = path->nodes[0];
5060 int nritems = btrfs_header_nritems(leaf);
5062 if (slot >= nritems) {
5064 ret = copy_items(trans, inode, dst_path, path,
5065 start_slot, ins_nr, 1, 0);
5070 ret = btrfs_next_leaf(root, path);
5078 btrfs_item_key_to_cpu(leaf, &key, slot);
5079 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
5086 found_xattrs = true;
5090 ret = copy_items(trans, inode, dst_path, path,
5091 start_slot, ins_nr, 1, 0);
5097 set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5103 * When using the NO_HOLES feature if we punched a hole that causes the
5104 * deletion of entire leafs or all the extent items of the first leaf (the one
5105 * that contains the inode item and references) we may end up not processing
5106 * any extents, because there are no leafs with a generation matching the
5107 * current transaction that have extent items for our inode. So we need to find
5108 * if any holes exist and then log them. We also need to log holes after any
5109 * truncate operation that changes the inode's size.
5111 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5112 struct btrfs_inode *inode,
5113 struct btrfs_path *path)
5115 struct btrfs_root *root = inode->root;
5116 struct btrfs_fs_info *fs_info = root->fs_info;
5117 struct btrfs_key key;
5118 const u64 ino = btrfs_ino(inode);
5119 const u64 i_size = i_size_read(&inode->vfs_inode);
5120 u64 prev_extent_end = 0;
5123 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5127 key.type = BTRFS_EXTENT_DATA_KEY;
5130 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5135 struct extent_buffer *leaf = path->nodes[0];
5137 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5138 ret = btrfs_next_leaf(root, path);
5145 leaf = path->nodes[0];
5148 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5149 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
5152 /* We have a hole, log it. */
5153 if (prev_extent_end < key.offset) {
5154 const u64 hole_len = key.offset - prev_extent_end;
5157 * Release the path to avoid deadlocks with other code
5158 * paths that search the root while holding locks on
5159 * leafs from the log root.
5161 btrfs_release_path(path);
5162 ret = btrfs_insert_hole_extent(trans, root->log_root,
5163 ino, prev_extent_end,
5169 * Search for the same key again in the root. Since it's
5170 * an extent item and we are holding the inode lock, the
5171 * key must still exist. If it doesn't just emit warning
5172 * and return an error to fall back to a transaction
5175 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5178 if (WARN_ON(ret > 0))
5180 leaf = path->nodes[0];
5183 prev_extent_end = btrfs_file_extent_end(path);
5188 if (prev_extent_end < i_size) {
5191 btrfs_release_path(path);
5192 hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5193 ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5194 prev_extent_end, hole_len);
5203 * When we are logging a new inode X, check if it doesn't have a reference that
5204 * matches the reference from some other inode Y created in a past transaction
5205 * and that was renamed in the current transaction. If we don't do this, then at
5206 * log replay time we can lose inode Y (and all its files if it's a directory):
5209 * echo "hello world" > /mnt/x/foobar
5212 * mkdir /mnt/x # or touch /mnt/x
5213 * xfs_io -c fsync /mnt/x
5215 * mount fs, trigger log replay
5217 * After the log replay procedure, we would lose the first directory and all its
5218 * files (file foobar).
5219 * For the case where inode Y is not a directory we simply end up losing it:
5221 * echo "123" > /mnt/foo
5223 * mv /mnt/foo /mnt/bar
5224 * echo "abc" > /mnt/foo
5225 * xfs_io -c fsync /mnt/foo
5228 * We also need this for cases where a snapshot entry is replaced by some other
5229 * entry (file or directory) otherwise we end up with an unreplayable log due to
5230 * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
5231 * if it were a regular entry:
5234 * btrfs subvolume snapshot /mnt /mnt/x/snap
5235 * btrfs subvolume delete /mnt/x/snap
5238 * fsync /mnt/x or fsync some new file inside it
5241 * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
5242 * the same transaction.
5244 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
5246 const struct btrfs_key *key,
5247 struct btrfs_inode *inode,
5248 u64 *other_ino, u64 *other_parent)
5251 struct btrfs_path *search_path;
5254 u32 item_size = btrfs_item_size(eb, slot);
5256 unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
5258 search_path = btrfs_alloc_path();
5261 search_path->search_commit_root = 1;
5262 search_path->skip_locking = 1;
5264 while (cur_offset < item_size) {
5268 unsigned long name_ptr;
5269 struct btrfs_dir_item *di;
5270 struct fscrypt_str name_str;
5272 if (key->type == BTRFS_INODE_REF_KEY) {
5273 struct btrfs_inode_ref *iref;
5275 iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
5276 parent = key->offset;
5277 this_name_len = btrfs_inode_ref_name_len(eb, iref);
5278 name_ptr = (unsigned long)(iref + 1);
5279 this_len = sizeof(*iref) + this_name_len;
5281 struct btrfs_inode_extref *extref;
5283 extref = (struct btrfs_inode_extref *)(ptr +
5285 parent = btrfs_inode_extref_parent(eb, extref);
5286 this_name_len = btrfs_inode_extref_name_len(eb, extref);
5287 name_ptr = (unsigned long)&extref->name;
5288 this_len = sizeof(*extref) + this_name_len;
5291 if (this_name_len > name_len) {
5294 new_name = krealloc(name, this_name_len, GFP_NOFS);
5299 name_len = this_name_len;
5303 read_extent_buffer(eb, name, name_ptr, this_name_len);
5305 name_str.name = name;
5306 name_str.len = this_name_len;
5307 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5308 parent, &name_str, 0);
5309 if (di && !IS_ERR(di)) {
5310 struct btrfs_key di_key;
5312 btrfs_dir_item_key_to_cpu(search_path->nodes[0],
5314 if (di_key.type == BTRFS_INODE_ITEM_KEY) {
5315 if (di_key.objectid != key->objectid) {
5317 *other_ino = di_key.objectid;
5318 *other_parent = parent;
5326 } else if (IS_ERR(di)) {
5330 btrfs_release_path(search_path);
5332 cur_offset += this_len;
5336 btrfs_free_path(search_path);
5342 * Check if we need to log an inode. This is used in contexts where while
5343 * logging an inode we need to log another inode (either that it exists or in
5344 * full mode). This is used instead of btrfs_inode_in_log() because the later
5345 * requires the inode to be in the log and have the log transaction committed,
5346 * while here we do not care if the log transaction was already committed - our
5347 * caller will commit the log later - and we want to avoid logging an inode
5348 * multiple times when multiple tasks have joined the same log transaction.
5350 static bool need_log_inode(const struct btrfs_trans_handle *trans,
5351 const struct btrfs_inode *inode)
5354 * If a directory was not modified, no dentries added or removed, we can
5355 * and should avoid logging it.
5357 if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5361 * If this inode does not have new/updated/deleted xattrs since the last
5362 * time it was logged and is flagged as logged in the current transaction,
5363 * we can skip logging it. As for new/deleted names, those are updated in
5364 * the log by link/unlink/rename operations.
5365 * In case the inode was logged and then evicted and reloaded, its
5366 * logged_trans will be 0, in which case we have to fully log it since
5367 * logged_trans is a transient field, not persisted.
5369 if (inode->logged_trans == trans->transid &&
5370 !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5376 struct btrfs_dir_list {
5378 struct list_head list;
5382 * Log the inodes of the new dentries of a directory.
5383 * See process_dir_items_leaf() for details about why it is needed.
5384 * This is a recursive operation - if an existing dentry corresponds to a
5385 * directory, that directory's new entries are logged too (same behaviour as
5386 * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5387 * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5388 * complains about the following circular lock dependency / possible deadlock:
5392 * lock(&type->i_mutex_dir_key#3/2);
5393 * lock(sb_internal#2);
5394 * lock(&type->i_mutex_dir_key#3/2);
5395 * lock(&sb->s_type->i_mutex_key#14);
5397 * Where sb_internal is the lock (a counter that works as a lock) acquired by
5398 * sb_start_intwrite() in btrfs_start_transaction().
5399 * Not acquiring the VFS lock of the inodes is still safe because:
5401 * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5402 * that while logging the inode new references (names) are added or removed
5403 * from the inode, leaving the logged inode item with a link count that does
5404 * not match the number of logged inode reference items. This is fine because
5405 * at log replay time we compute the real number of links and correct the
5406 * link count in the inode item (see replay_one_buffer() and
5407 * link_to_fixup_dir());
5409 * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5410 * while logging the inode's items new index items (key type
5411 * BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5412 * has a size that doesn't match the sum of the lengths of all the logged
5413 * names - this is ok, not a problem, because at log replay time we set the
5414 * directory's i_size to the correct value (see replay_one_name() and
5415 * do_overwrite_item()).
5417 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5418 struct btrfs_inode *start_inode,
5419 struct btrfs_log_ctx *ctx)
5421 struct btrfs_root *root = start_inode->root;
5422 struct btrfs_fs_info *fs_info = root->fs_info;
5423 struct btrfs_path *path;
5424 LIST_HEAD(dir_list);
5425 struct btrfs_dir_list *dir_elem;
5426 u64 ino = btrfs_ino(start_inode);
5430 * If we are logging a new name, as part of a link or rename operation,
5431 * don't bother logging new dentries, as we just want to log the names
5432 * of an inode and that any new parents exist.
5434 if (ctx->logging_new_name)
5437 path = btrfs_alloc_path();
5442 struct extent_buffer *leaf;
5443 struct btrfs_key min_key;
5444 bool continue_curr_inode = true;
5448 min_key.objectid = ino;
5449 min_key.type = BTRFS_DIR_INDEX_KEY;
5452 btrfs_release_path(path);
5453 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
5456 } else if (ret > 0) {
5461 leaf = path->nodes[0];
5462 nritems = btrfs_header_nritems(leaf);
5463 for (i = path->slots[0]; i < nritems; i++) {
5464 struct btrfs_dir_item *di;
5465 struct btrfs_key di_key;
5466 struct inode *di_inode;
5467 int log_mode = LOG_INODE_EXISTS;
5470 btrfs_item_key_to_cpu(leaf, &min_key, i);
5471 if (min_key.objectid != ino ||
5472 min_key.type != BTRFS_DIR_INDEX_KEY) {
5473 continue_curr_inode = false;
5477 di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5478 type = btrfs_dir_type(leaf, di);
5479 if (btrfs_dir_transid(leaf, di) < trans->transid)
5481 btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5482 if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5485 btrfs_release_path(path);
5486 di_inode = btrfs_iget(fs_info->sb, di_key.objectid, root);
5487 if (IS_ERR(di_inode)) {
5488 ret = PTR_ERR(di_inode);
5492 if (!need_log_inode(trans, BTRFS_I(di_inode))) {
5493 btrfs_add_delayed_iput(di_inode);
5497 ctx->log_new_dentries = false;
5498 if (type == BTRFS_FT_DIR)
5499 log_mode = LOG_INODE_ALL;
5500 ret = btrfs_log_inode(trans, BTRFS_I(di_inode),
5502 btrfs_add_delayed_iput(di_inode);
5505 if (ctx->log_new_dentries) {
5506 dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5511 dir_elem->ino = di_key.objectid;
5512 list_add_tail(&dir_elem->list, &dir_list);
5517 if (continue_curr_inode && min_key.offset < (u64)-1) {
5523 if (list_empty(&dir_list))
5526 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
5527 ino = dir_elem->ino;
5528 list_del(&dir_elem->list);
5532 btrfs_free_path(path);
5534 struct btrfs_dir_list *next;
5536 list_for_each_entry_safe(dir_elem, next, &dir_list, list)
5543 struct btrfs_ino_list {
5546 struct list_head list;
5549 static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
5551 struct btrfs_ino_list *curr;
5552 struct btrfs_ino_list *next;
5554 list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
5555 list_del(&curr->list);
5560 static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
5561 struct btrfs_path *path)
5563 struct btrfs_key key;
5567 key.type = BTRFS_INODE_ITEM_KEY;
5570 path->search_commit_root = 1;
5571 path->skip_locking = 1;
5573 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5574 if (WARN_ON_ONCE(ret > 0)) {
5576 * We have previously found the inode through the commit root
5577 * so this should not happen. If it does, just error out and
5578 * fallback to a transaction commit.
5581 } else if (ret == 0) {
5582 struct btrfs_inode_item *item;
5584 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5585 struct btrfs_inode_item);
5586 if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
5590 btrfs_release_path(path);
5591 path->search_commit_root = 0;
5592 path->skip_locking = 0;
5597 static int add_conflicting_inode(struct btrfs_trans_handle *trans,
5598 struct btrfs_root *root,
5599 struct btrfs_path *path,
5600 u64 ino, u64 parent,
5601 struct btrfs_log_ctx *ctx)
5603 struct btrfs_ino_list *ino_elem;
5604 struct inode *inode;
5607 * It's rare to have a lot of conflicting inodes, in practice it is not
5608 * common to have more than 1 or 2. We don't want to collect too many,
5609 * as we could end up logging too many inodes (even if only in
5610 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
5613 if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES) {
5614 btrfs_set_log_full_commit(trans);
5615 return BTRFS_LOG_FORCE_COMMIT;
5618 inode = btrfs_iget(root->fs_info->sb, ino, root);
5620 * If the other inode that had a conflicting dir entry was deleted in
5621 * the current transaction then we either:
5623 * 1) Log the parent directory (later after adding it to the list) if
5624 * the inode is a directory. This is because it may be a deleted
5625 * subvolume/snapshot or it may be a regular directory that had
5626 * deleted subvolumes/snapshots (or subdirectories that had them),
5627 * and at the moment we can't deal with dropping subvolumes/snapshots
5628 * during log replay. So we just log the parent, which will result in
5629 * a fallback to a transaction commit if we are dealing with those
5630 * cases (last_unlink_trans will match the current transaction);
5632 * 2) Do nothing if it's not a directory. During log replay we simply
5633 * unlink the conflicting dentry from the parent directory and then
5634 * add the dentry for our inode. Like this we can avoid logging the
5635 * parent directory (and maybe fallback to a transaction commit in
5636 * case it has a last_unlink_trans == trans->transid, due to moving
5637 * some inode from it to some other directory).
5639 if (IS_ERR(inode)) {
5640 int ret = PTR_ERR(inode);
5645 ret = conflicting_inode_is_dir(root, ino, path);
5646 /* Not a directory or we got an error. */
5650 /* Conflicting inode is a directory, so we'll log its parent. */
5651 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5654 ino_elem->ino = ino;
5655 ino_elem->parent = parent;
5656 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5657 ctx->num_conflict_inodes++;
5663 * If the inode was already logged skip it - otherwise we can hit an
5664 * infinite loop. Example:
5666 * From the commit root (previous transaction) we have the following
5669 * inode 257 a directory
5670 * inode 258 with references "zz" and "zz_link" on inode 257
5671 * inode 259 with reference "a" on inode 257
5673 * And in the current (uncommitted) transaction we have:
5675 * inode 257 a directory, unchanged
5676 * inode 258 with references "a" and "a2" on inode 257
5677 * inode 259 with reference "zz_link" on inode 257
5678 * inode 261 with reference "zz" on inode 257
5680 * When logging inode 261 the following infinite loop could
5681 * happen if we don't skip already logged inodes:
5683 * - we detect inode 258 as a conflicting inode, with inode 261
5684 * on reference "zz", and log it;
5686 * - we detect inode 259 as a conflicting inode, with inode 258
5687 * on reference "a", and log it;
5689 * - we detect inode 258 as a conflicting inode, with inode 259
5690 * on reference "zz_link", and log it - again! After this we
5691 * repeat the above steps forever.
5693 * Here we can use need_log_inode() because we only need to log the
5694 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
5695 * so that the log ends up with the new name and without the old name.
5697 if (!need_log_inode(trans, BTRFS_I(inode))) {
5698 btrfs_add_delayed_iput(inode);
5702 btrfs_add_delayed_iput(inode);
5704 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5707 ino_elem->ino = ino;
5708 ino_elem->parent = parent;
5709 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5710 ctx->num_conflict_inodes++;
5715 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
5716 struct btrfs_root *root,
5717 struct btrfs_log_ctx *ctx)
5719 struct btrfs_fs_info *fs_info = root->fs_info;
5723 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
5724 * otherwise we could have unbounded recursion of btrfs_log_inode()
5725 * calls. This check guarantees we can have only 1 level of recursion.
5727 if (ctx->logging_conflict_inodes)
5730 ctx->logging_conflict_inodes = true;
5733 * New conflicting inodes may be found and added to the list while we
5734 * are logging a conflicting inode, so keep iterating while the list is
5737 while (!list_empty(&ctx->conflict_inodes)) {
5738 struct btrfs_ino_list *curr;
5739 struct inode *inode;
5743 curr = list_first_entry(&ctx->conflict_inodes,
5744 struct btrfs_ino_list, list);
5746 parent = curr->parent;
5747 list_del(&curr->list);
5750 inode = btrfs_iget(fs_info->sb, ino, root);
5752 * If the other inode that had a conflicting dir entry was
5753 * deleted in the current transaction, we need to log its parent
5754 * directory. See the comment at add_conflicting_inode().
5756 if (IS_ERR(inode)) {
5757 ret = PTR_ERR(inode);
5761 inode = btrfs_iget(fs_info->sb, parent, root);
5762 if (IS_ERR(inode)) {
5763 ret = PTR_ERR(inode);
5768 * Always log the directory, we cannot make this
5769 * conditional on need_log_inode() because the directory
5770 * might have been logged in LOG_INODE_EXISTS mode or
5771 * the dir index of the conflicting inode is not in a
5772 * dir index key range logged for the directory. So we
5773 * must make sure the deletion is recorded.
5775 ret = btrfs_log_inode(trans, BTRFS_I(inode),
5776 LOG_INODE_ALL, ctx);
5777 btrfs_add_delayed_iput(inode);
5784 * Here we can use need_log_inode() because we only need to log
5785 * the inode in LOG_INODE_EXISTS mode and rename operations
5786 * update the log, so that the log ends up with the new name and
5787 * without the old name.
5789 * We did this check at add_conflicting_inode(), but here we do
5790 * it again because if some other task logged the inode after
5791 * that, we can avoid doing it again.
5793 if (!need_log_inode(trans, BTRFS_I(inode))) {
5794 btrfs_add_delayed_iput(inode);
5799 * We are safe logging the other inode without acquiring its
5800 * lock as long as we log with the LOG_INODE_EXISTS mode. We
5801 * are safe against concurrent renames of the other inode as
5802 * well because during a rename we pin the log and update the
5803 * log with the new name before we unpin it.
5805 ret = btrfs_log_inode(trans, BTRFS_I(inode), LOG_INODE_EXISTS, ctx);
5806 btrfs_add_delayed_iput(inode);
5811 ctx->logging_conflict_inodes = false;
5813 free_conflicting_inodes(ctx);
5818 static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
5819 struct btrfs_inode *inode,
5820 struct btrfs_key *min_key,
5821 const struct btrfs_key *max_key,
5822 struct btrfs_path *path,
5823 struct btrfs_path *dst_path,
5824 const u64 logged_isize,
5825 const int inode_only,
5826 struct btrfs_log_ctx *ctx,
5827 bool *need_log_inode_item)
5829 const u64 i_size = i_size_read(&inode->vfs_inode);
5830 struct btrfs_root *root = inode->root;
5831 int ins_start_slot = 0;
5836 ret = btrfs_search_forward(root, min_key, path, trans->transid);
5844 /* Note, ins_nr might be > 0 here, cleanup outside the loop */
5845 if (min_key->objectid != max_key->objectid)
5847 if (min_key->type > max_key->type)
5850 if (min_key->type == BTRFS_INODE_ITEM_KEY) {
5851 *need_log_inode_item = false;
5852 } else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
5853 min_key->offset >= i_size) {
5855 * Extents at and beyond eof are logged with
5856 * btrfs_log_prealloc_extents().
5857 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
5858 * and no keys greater than that, so bail out.
5861 } else if ((min_key->type == BTRFS_INODE_REF_KEY ||
5862 min_key->type == BTRFS_INODE_EXTREF_KEY) &&
5863 (inode->generation == trans->transid ||
5864 ctx->logging_conflict_inodes)) {
5866 u64 other_parent = 0;
5868 ret = btrfs_check_ref_name_override(path->nodes[0],
5869 path->slots[0], min_key, inode,
5870 &other_ino, &other_parent);
5873 } else if (ret > 0 &&
5874 other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5879 ins_start_slot = path->slots[0];
5881 ret = copy_items(trans, inode, dst_path, path,
5882 ins_start_slot, ins_nr,
5883 inode_only, logged_isize);
5888 btrfs_release_path(path);
5889 ret = add_conflicting_inode(trans, root, path,
5896 } else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
5897 /* Skip xattrs, logged later with btrfs_log_all_xattrs() */
5900 ret = copy_items(trans, inode, dst_path, path,
5902 ins_nr, inode_only, logged_isize);
5909 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5912 } else if (!ins_nr) {
5913 ins_start_slot = path->slots[0];
5918 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5919 ins_nr, inode_only, logged_isize);
5923 ins_start_slot = path->slots[0];
5926 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
5927 btrfs_item_key_to_cpu(path->nodes[0], min_key,
5932 ret = copy_items(trans, inode, dst_path, path,
5933 ins_start_slot, ins_nr, inode_only,
5939 btrfs_release_path(path);
5941 if (min_key->offset < (u64)-1) {
5943 } else if (min_key->type < max_key->type) {
5945 min_key->offset = 0;
5951 * We may process many leaves full of items for our inode, so
5952 * avoid monopolizing a cpu for too long by rescheduling while
5953 * not holding locks on any tree.
5958 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5959 ins_nr, inode_only, logged_isize);
5964 if (inode_only == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
5966 * Release the path because otherwise we might attempt to double
5967 * lock the same leaf with btrfs_log_prealloc_extents() below.
5969 btrfs_release_path(path);
5970 ret = btrfs_log_prealloc_extents(trans, inode, dst_path);
5976 static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
5977 struct btrfs_root *log,
5978 struct btrfs_path *path,
5979 const struct btrfs_item_batch *batch,
5980 const struct btrfs_delayed_item *first_item)
5982 const struct btrfs_delayed_item *curr = first_item;
5985 ret = btrfs_insert_empty_items(trans, log, path, batch);
5989 for (int i = 0; i < batch->nr; i++) {
5992 data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
5993 write_extent_buffer(path->nodes[0], &curr->data,
5994 (unsigned long)data_ptr, curr->data_len);
5995 curr = list_next_entry(curr, log_list);
5999 btrfs_release_path(path);
6004 static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
6005 struct btrfs_inode *inode,
6006 struct btrfs_path *path,
6007 const struct list_head *delayed_ins_list,
6008 struct btrfs_log_ctx *ctx)
6010 /* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
6011 const int max_batch_size = 195;
6012 const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
6013 const u64 ino = btrfs_ino(inode);
6014 struct btrfs_root *log = inode->root->log_root;
6015 struct btrfs_item_batch batch = {
6017 .total_data_size = 0,
6019 const struct btrfs_delayed_item *first = NULL;
6020 const struct btrfs_delayed_item *curr;
6022 struct btrfs_key *ins_keys;
6024 u64 curr_batch_size = 0;
6028 /* We are adding dir index items to the log tree. */
6029 lockdep_assert_held(&inode->log_mutex);
6032 * We collect delayed items before copying index keys from the subvolume
6033 * to the log tree. However just after we collected them, they may have
6034 * been flushed (all of them or just some of them), and therefore we
6035 * could have copied them from the subvolume tree to the log tree.
6036 * So find the first delayed item that was not yet logged (they are
6037 * sorted by index number).
6039 list_for_each_entry(curr, delayed_ins_list, log_list) {
6040 if (curr->index > inode->last_dir_index_offset) {
6046 /* Empty list or all delayed items were already logged. */
6050 ins_data = kmalloc(max_batch_size * sizeof(u32) +
6051 max_batch_size * sizeof(struct btrfs_key), GFP_NOFS);
6054 ins_sizes = (u32 *)ins_data;
6055 batch.data_sizes = ins_sizes;
6056 ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
6057 batch.keys = ins_keys;
6060 while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
6061 const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
6063 if (curr_batch_size + curr_size > leaf_data_size ||
6064 batch.nr == max_batch_size) {
6065 ret = insert_delayed_items_batch(trans, log, path,
6071 batch.total_data_size = 0;
6072 curr_batch_size = 0;
6076 ins_sizes[batch_idx] = curr->data_len;
6077 ins_keys[batch_idx].objectid = ino;
6078 ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
6079 ins_keys[batch_idx].offset = curr->index;
6080 curr_batch_size += curr_size;
6081 batch.total_data_size += curr->data_len;
6084 curr = list_next_entry(curr, log_list);
6087 ASSERT(batch.nr >= 1);
6088 ret = insert_delayed_items_batch(trans, log, path, &batch, first);
6090 curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
6092 inode->last_dir_index_offset = curr->index;
6099 static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
6100 struct btrfs_inode *inode,
6101 struct btrfs_path *path,
6102 const struct list_head *delayed_del_list,
6103 struct btrfs_log_ctx *ctx)
6105 const u64 ino = btrfs_ino(inode);
6106 const struct btrfs_delayed_item *curr;
6108 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6111 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6112 u64 first_dir_index = curr->index;
6114 const struct btrfs_delayed_item *next;
6118 * Find a range of consecutive dir index items to delete. Like
6119 * this we log a single dir range item spanning several contiguous
6120 * dir items instead of logging one range item per dir index item.
6122 next = list_next_entry(curr, log_list);
6123 while (!list_entry_is_head(next, delayed_del_list, log_list)) {
6124 if (next->index != curr->index + 1)
6127 next = list_next_entry(next, log_list);
6130 last_dir_index = curr->index;
6131 ASSERT(last_dir_index >= first_dir_index);
6133 ret = insert_dir_log_key(trans, inode->root->log_root, path,
6134 ino, first_dir_index, last_dir_index);
6137 curr = list_next_entry(curr, log_list);
6143 static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
6144 struct btrfs_inode *inode,
6145 struct btrfs_path *path,
6146 struct btrfs_log_ctx *ctx,
6147 const struct list_head *delayed_del_list,
6148 const struct btrfs_delayed_item *first,
6149 const struct btrfs_delayed_item **last_ret)
6151 const struct btrfs_delayed_item *next;
6152 struct extent_buffer *leaf = path->nodes[0];
6153 const int last_slot = btrfs_header_nritems(leaf) - 1;
6154 int slot = path->slots[0] + 1;
6155 const u64 ino = btrfs_ino(inode);
6157 next = list_next_entry(first, log_list);
6159 while (slot < last_slot &&
6160 !list_entry_is_head(next, delayed_del_list, log_list)) {
6161 struct btrfs_key key;
6163 btrfs_item_key_to_cpu(leaf, &key, slot);
6164 if (key.objectid != ino ||
6165 key.type != BTRFS_DIR_INDEX_KEY ||
6166 key.offset != next->index)
6171 next = list_next_entry(next, log_list);
6174 return btrfs_del_items(trans, inode->root->log_root, path,
6175 path->slots[0], slot - path->slots[0]);
6178 static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
6179 struct btrfs_inode *inode,
6180 struct btrfs_path *path,
6181 const struct list_head *delayed_del_list,
6182 struct btrfs_log_ctx *ctx)
6184 struct btrfs_root *log = inode->root->log_root;
6185 const struct btrfs_delayed_item *curr;
6186 u64 last_range_start = 0;
6187 u64 last_range_end = 0;
6188 struct btrfs_key key;
6190 key.objectid = btrfs_ino(inode);
6191 key.type = BTRFS_DIR_INDEX_KEY;
6192 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6195 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6196 const struct btrfs_delayed_item *last = curr;
6197 u64 first_dir_index = curr->index;
6199 bool deleted_items = false;
6202 key.offset = curr->index;
6203 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
6206 } else if (ret == 0) {
6207 ret = batch_delete_dir_index_items(trans, inode, path, ctx,
6208 delayed_del_list, curr,
6212 deleted_items = true;
6215 btrfs_release_path(path);
6218 * If we deleted items from the leaf, it means we have a range
6219 * item logging their range, so no need to add one or update an
6220 * existing one. Otherwise we have to log a dir range item.
6225 last_dir_index = last->index;
6226 ASSERT(last_dir_index >= first_dir_index);
6228 * If this range starts right after where the previous one ends,
6229 * then we want to reuse the previous range item and change its
6230 * end offset to the end of this range. This is just to minimize
6231 * leaf space usage, by avoiding adding a new range item.
6233 if (last_range_end != 0 && first_dir_index == last_range_end + 1)
6234 first_dir_index = last_range_start;
6236 ret = insert_dir_log_key(trans, log, path, key.objectid,
6237 first_dir_index, last_dir_index);
6241 last_range_start = first_dir_index;
6242 last_range_end = last_dir_index;
6244 curr = list_next_entry(last, log_list);
6250 static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
6251 struct btrfs_inode *inode,
6252 struct btrfs_path *path,
6253 const struct list_head *delayed_del_list,
6254 struct btrfs_log_ctx *ctx)
6257 * We are deleting dir index items from the log tree or adding range
6260 lockdep_assert_held(&inode->log_mutex);
6262 if (list_empty(delayed_del_list))
6265 if (ctx->logged_before)
6266 return log_delayed_deletions_incremental(trans, inode, path,
6267 delayed_del_list, ctx);
6269 return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
6274 * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
6275 * items instead of the subvolume tree.
6277 static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
6278 struct btrfs_inode *inode,
6279 const struct list_head *delayed_ins_list,
6280 struct btrfs_log_ctx *ctx)
6282 const bool orig_log_new_dentries = ctx->log_new_dentries;
6283 struct btrfs_fs_info *fs_info = trans->fs_info;
6284 struct btrfs_delayed_item *item;
6288 * No need for the log mutex, plus to avoid potential deadlocks or
6289 * lockdep annotations due to nesting of delayed inode mutexes and log
6292 lockdep_assert_not_held(&inode->log_mutex);
6294 ASSERT(!ctx->logging_new_delayed_dentries);
6295 ctx->logging_new_delayed_dentries = true;
6297 list_for_each_entry(item, delayed_ins_list, log_list) {
6298 struct btrfs_dir_item *dir_item;
6299 struct inode *di_inode;
6300 struct btrfs_key key;
6301 int log_mode = LOG_INODE_EXISTS;
6303 dir_item = (struct btrfs_dir_item *)item->data;
6304 btrfs_disk_key_to_cpu(&key, &dir_item->location);
6306 if (key.type == BTRFS_ROOT_ITEM_KEY)
6309 di_inode = btrfs_iget(fs_info->sb, key.objectid, inode->root);
6310 if (IS_ERR(di_inode)) {
6311 ret = PTR_ERR(di_inode);
6315 if (!need_log_inode(trans, BTRFS_I(di_inode))) {
6316 btrfs_add_delayed_iput(di_inode);
6320 if (btrfs_stack_dir_type(dir_item) == BTRFS_FT_DIR)
6321 log_mode = LOG_INODE_ALL;
6323 ctx->log_new_dentries = false;
6324 ret = btrfs_log_inode(trans, BTRFS_I(di_inode), log_mode, ctx);
6326 if (!ret && ctx->log_new_dentries)
6327 ret = log_new_dir_dentries(trans, BTRFS_I(di_inode), ctx);
6329 btrfs_add_delayed_iput(di_inode);
6335 ctx->log_new_dentries = orig_log_new_dentries;
6336 ctx->logging_new_delayed_dentries = false;
6341 /* log a single inode in the tree log.
6342 * At least one parent directory for this inode must exist in the tree
6343 * or be logged already.
6345 * Any items from this inode changed by the current transaction are copied
6346 * to the log tree. An extra reference is taken on any extents in this
6347 * file, allowing us to avoid a whole pile of corner cases around logging
6348 * blocks that have been removed from the tree.
6350 * See LOG_INODE_ALL and related defines for a description of what inode_only
6353 * This handles both files and directories.
6355 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
6356 struct btrfs_inode *inode,
6358 struct btrfs_log_ctx *ctx)
6360 struct btrfs_path *path;
6361 struct btrfs_path *dst_path;
6362 struct btrfs_key min_key;
6363 struct btrfs_key max_key;
6364 struct btrfs_root *log = inode->root->log_root;
6366 bool fast_search = false;
6367 u64 ino = btrfs_ino(inode);
6368 struct extent_map_tree *em_tree = &inode->extent_tree;
6369 u64 logged_isize = 0;
6370 bool need_log_inode_item = true;
6371 bool xattrs_logged = false;
6372 bool inode_item_dropped = true;
6373 bool full_dir_logging = false;
6374 LIST_HEAD(delayed_ins_list);
6375 LIST_HEAD(delayed_del_list);
6377 path = btrfs_alloc_path();
6380 dst_path = btrfs_alloc_path();
6382 btrfs_free_path(path);
6386 min_key.objectid = ino;
6387 min_key.type = BTRFS_INODE_ITEM_KEY;
6390 max_key.objectid = ino;
6393 /* today the code can only do partial logging of directories */
6394 if (S_ISDIR(inode->vfs_inode.i_mode) ||
6395 (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6396 &inode->runtime_flags) &&
6397 inode_only >= LOG_INODE_EXISTS))
6398 max_key.type = BTRFS_XATTR_ITEM_KEY;
6400 max_key.type = (u8)-1;
6401 max_key.offset = (u64)-1;
6403 if (S_ISDIR(inode->vfs_inode.i_mode) && inode_only == LOG_INODE_ALL)
6404 full_dir_logging = true;
6407 * If we are logging a directory while we are logging dentries of the
6408 * delayed items of some other inode, then we need to flush the delayed
6409 * items of this directory and not log the delayed items directly. This
6410 * is to prevent more than one level of recursion into btrfs_log_inode()
6411 * by having something like this:
6413 * $ mkdir -p a/b/c/d/e/f/g/h/...
6414 * $ xfs_io -c "fsync" a
6416 * Where all directories in the path did not exist before and are
6417 * created in the current transaction.
6418 * So in such a case we directly log the delayed items of the main
6419 * directory ("a") without flushing them first, while for each of its
6420 * subdirectories we flush their delayed items before logging them.
6421 * This prevents a potential unbounded recursion like this:
6424 * log_new_delayed_dentries()
6426 * log_new_delayed_dentries()
6428 * log_new_delayed_dentries()
6431 * We have thresholds for the maximum number of delayed items to have in
6432 * memory, and once they are hit, the items are flushed asynchronously.
6433 * However the limit is quite high, so lets prevent deep levels of
6434 * recursion to happen by limiting the maximum depth to be 1.
6436 if (full_dir_logging && ctx->logging_new_delayed_dentries) {
6437 ret = btrfs_commit_inode_delayed_items(trans, inode);
6442 mutex_lock(&inode->log_mutex);
6445 * For symlinks, we must always log their content, which is stored in an
6446 * inline extent, otherwise we could end up with an empty symlink after
6447 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
6448 * one attempts to create an empty symlink).
6449 * We don't need to worry about flushing delalloc, because when we create
6450 * the inline extent when the symlink is created (we never have delalloc
6453 if (S_ISLNK(inode->vfs_inode.i_mode))
6454 inode_only = LOG_INODE_ALL;
6457 * Before logging the inode item, cache the value returned by
6458 * inode_logged(), because after that we have the need to figure out if
6459 * the inode was previously logged in this transaction.
6461 ret = inode_logged(trans, inode, path);
6464 ctx->logged_before = (ret == 1);
6468 * This is for cases where logging a directory could result in losing a
6469 * a file after replaying the log. For example, if we move a file from a
6470 * directory A to a directory B, then fsync directory A, we have no way
6471 * to known the file was moved from A to B, so logging just A would
6472 * result in losing the file after a log replay.
6474 if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
6475 btrfs_set_log_full_commit(trans);
6476 ret = BTRFS_LOG_FORCE_COMMIT;
6481 * a brute force approach to making sure we get the most uptodate
6482 * copies of everything.
6484 if (S_ISDIR(inode->vfs_inode.i_mode)) {
6485 clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
6486 if (ctx->logged_before)
6487 ret = drop_inode_items(trans, log, path, inode,
6488 BTRFS_XATTR_ITEM_KEY);
6490 if (inode_only == LOG_INODE_EXISTS && ctx->logged_before) {
6492 * Make sure the new inode item we write to the log has
6493 * the same isize as the current one (if it exists).
6494 * This is necessary to prevent data loss after log
6495 * replay, and also to prevent doing a wrong expanding
6496 * truncate - for e.g. create file, write 4K into offset
6497 * 0, fsync, write 4K into offset 4096, add hard link,
6498 * fsync some other file (to sync log), power fail - if
6499 * we use the inode's current i_size, after log replay
6500 * we get a 8Kb file, with the last 4Kb extent as a hole
6501 * (zeroes), as if an expanding truncate happened,
6502 * instead of getting a file of 4Kb only.
6504 ret = logged_inode_size(log, inode, path, &logged_isize);
6508 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6509 &inode->runtime_flags)) {
6510 if (inode_only == LOG_INODE_EXISTS) {
6511 max_key.type = BTRFS_XATTR_ITEM_KEY;
6512 if (ctx->logged_before)
6513 ret = drop_inode_items(trans, log, path,
6514 inode, max_key.type);
6516 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6517 &inode->runtime_flags);
6518 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6519 &inode->runtime_flags);
6520 if (ctx->logged_before)
6521 ret = truncate_inode_items(trans, log,
6524 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6525 &inode->runtime_flags) ||
6526 inode_only == LOG_INODE_EXISTS) {
6527 if (inode_only == LOG_INODE_ALL)
6529 max_key.type = BTRFS_XATTR_ITEM_KEY;
6530 if (ctx->logged_before)
6531 ret = drop_inode_items(trans, log, path, inode,
6534 if (inode_only == LOG_INODE_ALL)
6536 inode_item_dropped = false;
6545 * If we are logging a directory in full mode, collect the delayed items
6546 * before iterating the subvolume tree, so that we don't miss any new
6547 * dir index items in case they get flushed while or right after we are
6548 * iterating the subvolume tree.
6550 if (full_dir_logging && !ctx->logging_new_delayed_dentries)
6551 btrfs_log_get_delayed_items(inode, &delayed_ins_list,
6554 ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
6555 path, dst_path, logged_isize,
6557 &need_log_inode_item);
6561 btrfs_release_path(path);
6562 btrfs_release_path(dst_path);
6563 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
6566 xattrs_logged = true;
6567 if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
6568 btrfs_release_path(path);
6569 btrfs_release_path(dst_path);
6570 ret = btrfs_log_holes(trans, inode, path);
6575 btrfs_release_path(path);
6576 btrfs_release_path(dst_path);
6577 if (need_log_inode_item) {
6578 ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
6582 * If we are doing a fast fsync and the inode was logged before
6583 * in this transaction, we don't need to log the xattrs because
6584 * they were logged before. If xattrs were added, changed or
6585 * deleted since the last time we logged the inode, then we have
6586 * already logged them because the inode had the runtime flag
6587 * BTRFS_INODE_COPY_EVERYTHING set.
6589 if (!xattrs_logged && inode->logged_trans < trans->transid) {
6590 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
6593 btrfs_release_path(path);
6597 ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
6600 } else if (inode_only == LOG_INODE_ALL) {
6601 struct extent_map *em, *n;
6603 write_lock(&em_tree->lock);
6604 list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
6605 list_del_init(&em->list);
6606 write_unlock(&em_tree->lock);
6609 if (full_dir_logging) {
6610 ret = log_directory_changes(trans, inode, path, dst_path, ctx);
6613 ret = log_delayed_insertion_items(trans, inode, path,
6614 &delayed_ins_list, ctx);
6617 ret = log_delayed_deletion_items(trans, inode, path,
6618 &delayed_del_list, ctx);
6623 spin_lock(&inode->lock);
6624 inode->logged_trans = trans->transid;
6626 * Don't update last_log_commit if we logged that an inode exists.
6627 * We do this for three reasons:
6629 * 1) We might have had buffered writes to this inode that were
6630 * flushed and had their ordered extents completed in this
6631 * transaction, but we did not previously log the inode with
6632 * LOG_INODE_ALL. Later the inode was evicted and after that
6633 * it was loaded again and this LOG_INODE_EXISTS log operation
6634 * happened. We must make sure that if an explicit fsync against
6635 * the inode is performed later, it logs the new extents, an
6636 * updated inode item, etc, and syncs the log. The same logic
6637 * applies to direct IO writes instead of buffered writes.
6639 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
6640 * is logged with an i_size of 0 or whatever value was logged
6641 * before. If later the i_size of the inode is increased by a
6642 * truncate operation, the log is synced through an fsync of
6643 * some other inode and then finally an explicit fsync against
6644 * this inode is made, we must make sure this fsync logs the
6645 * inode with the new i_size, the hole between old i_size and
6646 * the new i_size, and syncs the log.
6648 * 3) If we are logging that an ancestor inode exists as part of
6649 * logging a new name from a link or rename operation, don't update
6650 * its last_log_commit - otherwise if an explicit fsync is made
6651 * against an ancestor, the fsync considers the inode in the log
6652 * and doesn't sync the log, resulting in the ancestor missing after
6653 * a power failure unless the log was synced as part of an fsync
6654 * against any other unrelated inode.
6656 if (inode_only != LOG_INODE_EXISTS)
6657 inode->last_log_commit = inode->last_sub_trans;
6658 spin_unlock(&inode->lock);
6661 * Reset the last_reflink_trans so that the next fsync does not need to
6662 * go through the slower path when logging extents and their checksums.
6664 if (inode_only == LOG_INODE_ALL)
6665 inode->last_reflink_trans = 0;
6668 mutex_unlock(&inode->log_mutex);
6670 btrfs_free_path(path);
6671 btrfs_free_path(dst_path);
6674 free_conflicting_inodes(ctx);
6676 ret = log_conflicting_inodes(trans, inode->root, ctx);
6678 if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
6680 ret = log_new_delayed_dentries(trans, inode,
6681 &delayed_ins_list, ctx);
6683 btrfs_log_put_delayed_items(inode, &delayed_ins_list,
6690 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
6691 struct btrfs_inode *inode,
6692 struct btrfs_log_ctx *ctx)
6694 struct btrfs_fs_info *fs_info = trans->fs_info;
6696 struct btrfs_path *path;
6697 struct btrfs_key key;
6698 struct btrfs_root *root = inode->root;
6699 const u64 ino = btrfs_ino(inode);
6701 path = btrfs_alloc_path();
6704 path->skip_locking = 1;
6705 path->search_commit_root = 1;
6708 key.type = BTRFS_INODE_REF_KEY;
6710 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6715 struct extent_buffer *leaf = path->nodes[0];
6716 int slot = path->slots[0];
6721 if (slot >= btrfs_header_nritems(leaf)) {
6722 ret = btrfs_next_leaf(root, path);
6730 btrfs_item_key_to_cpu(leaf, &key, slot);
6731 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
6732 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
6735 item_size = btrfs_item_size(leaf, slot);
6736 ptr = btrfs_item_ptr_offset(leaf, slot);
6737 while (cur_offset < item_size) {
6738 struct btrfs_key inode_key;
6739 struct inode *dir_inode;
6741 inode_key.type = BTRFS_INODE_ITEM_KEY;
6742 inode_key.offset = 0;
6744 if (key.type == BTRFS_INODE_EXTREF_KEY) {
6745 struct btrfs_inode_extref *extref;
6747 extref = (struct btrfs_inode_extref *)
6749 inode_key.objectid = btrfs_inode_extref_parent(
6751 cur_offset += sizeof(*extref);
6752 cur_offset += btrfs_inode_extref_name_len(leaf,
6755 inode_key.objectid = key.offset;
6756 cur_offset = item_size;
6759 dir_inode = btrfs_iget(fs_info->sb, inode_key.objectid,
6762 * If the parent inode was deleted, return an error to
6763 * fallback to a transaction commit. This is to prevent
6764 * getting an inode that was moved from one parent A to
6765 * a parent B, got its former parent A deleted and then
6766 * it got fsync'ed, from existing at both parents after
6767 * a log replay (and the old parent still existing).
6774 * mv /mnt/B/bar /mnt/A/bar
6775 * mv -T /mnt/A /mnt/B
6779 * If we ignore the old parent B which got deleted,
6780 * after a log replay we would have file bar linked
6781 * at both parents and the old parent B would still
6784 if (IS_ERR(dir_inode)) {
6785 ret = PTR_ERR(dir_inode);
6789 if (!need_log_inode(trans, BTRFS_I(dir_inode))) {
6790 btrfs_add_delayed_iput(dir_inode);
6794 ctx->log_new_dentries = false;
6795 ret = btrfs_log_inode(trans, BTRFS_I(dir_inode),
6796 LOG_INODE_ALL, ctx);
6797 if (!ret && ctx->log_new_dentries)
6798 ret = log_new_dir_dentries(trans,
6799 BTRFS_I(dir_inode), ctx);
6800 btrfs_add_delayed_iput(dir_inode);
6808 btrfs_free_path(path);
6812 static int log_new_ancestors(struct btrfs_trans_handle *trans,
6813 struct btrfs_root *root,
6814 struct btrfs_path *path,
6815 struct btrfs_log_ctx *ctx)
6817 struct btrfs_key found_key;
6819 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
6822 struct btrfs_fs_info *fs_info = root->fs_info;
6823 struct extent_buffer *leaf = path->nodes[0];
6824 int slot = path->slots[0];
6825 struct btrfs_key search_key;
6826 struct inode *inode;
6830 btrfs_release_path(path);
6832 ino = found_key.offset;
6834 search_key.objectid = found_key.offset;
6835 search_key.type = BTRFS_INODE_ITEM_KEY;
6836 search_key.offset = 0;
6837 inode = btrfs_iget(fs_info->sb, ino, root);
6839 return PTR_ERR(inode);
6841 if (BTRFS_I(inode)->generation >= trans->transid &&
6842 need_log_inode(trans, BTRFS_I(inode)))
6843 ret = btrfs_log_inode(trans, BTRFS_I(inode),
6844 LOG_INODE_EXISTS, ctx);
6845 btrfs_add_delayed_iput(inode);
6849 if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
6852 search_key.type = BTRFS_INODE_REF_KEY;
6853 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6857 leaf = path->nodes[0];
6858 slot = path->slots[0];
6859 if (slot >= btrfs_header_nritems(leaf)) {
6860 ret = btrfs_next_leaf(root, path);
6865 leaf = path->nodes[0];
6866 slot = path->slots[0];
6869 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6870 if (found_key.objectid != search_key.objectid ||
6871 found_key.type != BTRFS_INODE_REF_KEY)
6877 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
6878 struct btrfs_inode *inode,
6879 struct dentry *parent,
6880 struct btrfs_log_ctx *ctx)
6882 struct btrfs_root *root = inode->root;
6883 struct dentry *old_parent = NULL;
6884 struct super_block *sb = inode->vfs_inode.i_sb;
6888 if (!parent || d_really_is_negative(parent) ||
6892 inode = BTRFS_I(d_inode(parent));
6893 if (root != inode->root)
6896 if (inode->generation >= trans->transid &&
6897 need_log_inode(trans, inode)) {
6898 ret = btrfs_log_inode(trans, inode,
6899 LOG_INODE_EXISTS, ctx);
6903 if (IS_ROOT(parent))
6906 parent = dget_parent(parent);
6908 old_parent = parent;
6915 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
6916 struct btrfs_inode *inode,
6917 struct dentry *parent,
6918 struct btrfs_log_ctx *ctx)
6920 struct btrfs_root *root = inode->root;
6921 const u64 ino = btrfs_ino(inode);
6922 struct btrfs_path *path;
6923 struct btrfs_key search_key;
6927 * For a single hard link case, go through a fast path that does not
6928 * need to iterate the fs/subvolume tree.
6930 if (inode->vfs_inode.i_nlink < 2)
6931 return log_new_ancestors_fast(trans, inode, parent, ctx);
6933 path = btrfs_alloc_path();
6937 search_key.objectid = ino;
6938 search_key.type = BTRFS_INODE_REF_KEY;
6939 search_key.offset = 0;
6941 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6948 struct extent_buffer *leaf = path->nodes[0];
6949 int slot = path->slots[0];
6950 struct btrfs_key found_key;
6952 if (slot >= btrfs_header_nritems(leaf)) {
6953 ret = btrfs_next_leaf(root, path);
6961 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6962 if (found_key.objectid != ino ||
6963 found_key.type > BTRFS_INODE_EXTREF_KEY)
6967 * Don't deal with extended references because they are rare
6968 * cases and too complex to deal with (we would need to keep
6969 * track of which subitem we are processing for each item in
6970 * this loop, etc). So just return some error to fallback to
6971 * a transaction commit.
6973 if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
6979 * Logging ancestors needs to do more searches on the fs/subvol
6980 * tree, so it releases the path as needed to avoid deadlocks.
6981 * Keep track of the last inode ref key and resume from that key
6982 * after logging all new ancestors for the current hard link.
6984 memcpy(&search_key, &found_key, sizeof(search_key));
6986 ret = log_new_ancestors(trans, root, path, ctx);
6989 btrfs_release_path(path);
6994 btrfs_free_path(path);
6999 * helper function around btrfs_log_inode to make sure newly created
7000 * parent directories also end up in the log. A minimal inode and backref
7001 * only logging is done of any parent directories that are older than
7002 * the last committed transaction
7004 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
7005 struct btrfs_inode *inode,
7006 struct dentry *parent,
7008 struct btrfs_log_ctx *ctx)
7010 struct btrfs_root *root = inode->root;
7011 struct btrfs_fs_info *fs_info = root->fs_info;
7013 bool log_dentries = false;
7015 if (btrfs_test_opt(fs_info, NOTREELOG)) {
7016 ret = BTRFS_LOG_FORCE_COMMIT;
7020 if (btrfs_root_refs(&root->root_item) == 0) {
7021 ret = BTRFS_LOG_FORCE_COMMIT;
7026 * Skip already logged inodes or inodes corresponding to tmpfiles
7027 * (since logging them is pointless, a link count of 0 means they
7028 * will never be accessible).
7030 if ((btrfs_inode_in_log(inode, trans->transid) &&
7031 list_empty(&ctx->ordered_extents)) ||
7032 inode->vfs_inode.i_nlink == 0) {
7033 ret = BTRFS_NO_LOG_SYNC;
7037 ret = start_log_trans(trans, root, ctx);
7041 ret = btrfs_log_inode(trans, inode, inode_only, ctx);
7046 * for regular files, if its inode is already on disk, we don't
7047 * have to worry about the parents at all. This is because
7048 * we can use the last_unlink_trans field to record renames
7049 * and other fun in this file.
7051 if (S_ISREG(inode->vfs_inode.i_mode) &&
7052 inode->generation < trans->transid &&
7053 inode->last_unlink_trans < trans->transid) {
7058 if (S_ISDIR(inode->vfs_inode.i_mode) && ctx->log_new_dentries)
7059 log_dentries = true;
7062 * On unlink we must make sure all our current and old parent directory
7063 * inodes are fully logged. This is to prevent leaving dangling
7064 * directory index entries in directories that were our parents but are
7065 * not anymore. Not doing this results in old parent directory being
7066 * impossible to delete after log replay (rmdir will always fail with
7067 * error -ENOTEMPTY).
7073 * ln testdir/foo testdir/bar
7075 * unlink testdir/bar
7076 * xfs_io -c fsync testdir/foo
7078 * mount fs, triggers log replay
7080 * If we don't log the parent directory (testdir), after log replay the
7081 * directory still has an entry pointing to the file inode using the bar
7082 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
7083 * the file inode has a link count of 1.
7089 * ln foo testdir/foo2
7090 * ln foo testdir/foo3
7092 * unlink testdir/foo3
7093 * xfs_io -c fsync foo
7095 * mount fs, triggers log replay
7097 * Similar as the first example, after log replay the parent directory
7098 * testdir still has an entry pointing to the inode file with name foo3
7099 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
7100 * and has a link count of 2.
7102 if (inode->last_unlink_trans >= trans->transid) {
7103 ret = btrfs_log_all_parents(trans, inode, ctx);
7108 ret = log_all_new_ancestors(trans, inode, parent, ctx);
7113 ret = log_new_dir_dentries(trans, inode, ctx);
7118 btrfs_set_log_full_commit(trans);
7119 ret = BTRFS_LOG_FORCE_COMMIT;
7123 btrfs_remove_log_ctx(root, ctx);
7124 btrfs_end_log_trans(root);
7130 * it is not safe to log dentry if the chunk root has added new
7131 * chunks. This returns 0 if the dentry was logged, and 1 otherwise.
7132 * If this returns 1, you must commit the transaction to safely get your
7135 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7136 struct dentry *dentry,
7137 struct btrfs_log_ctx *ctx)
7139 struct dentry *parent = dget_parent(dentry);
7142 ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
7143 LOG_INODE_ALL, ctx);
7150 * should be called during mount to recover any replay any log trees
7153 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7156 struct btrfs_path *path;
7157 struct btrfs_trans_handle *trans;
7158 struct btrfs_key key;
7159 struct btrfs_key found_key;
7160 struct btrfs_root *log;
7161 struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7162 struct walk_control wc = {
7163 .process_func = process_one_buffer,
7164 .stage = LOG_WALK_PIN_ONLY,
7167 path = btrfs_alloc_path();
7171 set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7173 trans = btrfs_start_transaction(fs_info->tree_root, 0);
7174 if (IS_ERR(trans)) {
7175 ret = PTR_ERR(trans);
7182 ret = walk_log_tree(trans, log_root_tree, &wc);
7184 btrfs_abort_transaction(trans, ret);
7189 key.objectid = BTRFS_TREE_LOG_OBJECTID;
7190 key.offset = (u64)-1;
7191 key.type = BTRFS_ROOT_ITEM_KEY;
7194 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
7197 btrfs_abort_transaction(trans, ret);
7201 if (path->slots[0] == 0)
7205 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7207 btrfs_release_path(path);
7208 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7211 log = btrfs_read_tree_root(log_root_tree, &found_key);
7214 btrfs_abort_transaction(trans, ret);
7218 wc.replay_dest = btrfs_get_fs_root(fs_info, found_key.offset,
7220 if (IS_ERR(wc.replay_dest)) {
7221 ret = PTR_ERR(wc.replay_dest);
7224 * We didn't find the subvol, likely because it was
7225 * deleted. This is ok, simply skip this log and go to
7228 * We need to exclude the root because we can't have
7229 * other log replays overwriting this log as we'll read
7230 * it back in a few more times. This will keep our
7231 * block from being modified, and we'll just bail for
7232 * each subsequent pass.
7235 ret = btrfs_pin_extent_for_log_replay(trans,
7238 btrfs_put_root(log);
7242 btrfs_abort_transaction(trans, ret);
7246 wc.replay_dest->log_root = log;
7247 ret = btrfs_record_root_in_trans(trans, wc.replay_dest);
7249 /* The loop needs to continue due to the root refs */
7250 btrfs_abort_transaction(trans, ret);
7252 ret = walk_log_tree(trans, log, &wc);
7254 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7255 ret = fixup_inode_link_counts(trans, wc.replay_dest,
7258 btrfs_abort_transaction(trans, ret);
7261 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7262 struct btrfs_root *root = wc.replay_dest;
7264 btrfs_release_path(path);
7267 * We have just replayed everything, and the highest
7268 * objectid of fs roots probably has changed in case
7269 * some inode_item's got replayed.
7271 * root->objectid_mutex is not acquired as log replay
7272 * could only happen during mount.
7274 ret = btrfs_init_root_free_objectid(root);
7276 btrfs_abort_transaction(trans, ret);
7279 wc.replay_dest->log_root = NULL;
7280 btrfs_put_root(wc.replay_dest);
7281 btrfs_put_root(log);
7286 if (found_key.offset == 0)
7288 key.offset = found_key.offset - 1;
7290 btrfs_release_path(path);
7292 /* step one is to pin it all, step two is to replay just inodes */
7295 wc.process_func = replay_one_buffer;
7296 wc.stage = LOG_WALK_REPLAY_INODES;
7299 /* step three is to replay everything */
7300 if (wc.stage < LOG_WALK_REPLAY_ALL) {
7305 btrfs_free_path(path);
7307 /* step 4: commit the transaction, which also unpins the blocks */
7308 ret = btrfs_commit_transaction(trans);
7312 log_root_tree->log_root = NULL;
7313 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7314 btrfs_put_root(log_root_tree);
7319 btrfs_end_transaction(wc.trans);
7320 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7321 btrfs_free_path(path);
7326 * there are some corner cases where we want to force a full
7327 * commit instead of allowing a directory to be logged.
7329 * They revolve around files there were unlinked from the directory, and
7330 * this function updates the parent directory so that a full commit is
7331 * properly done if it is fsync'd later after the unlinks are done.
7333 * Must be called before the unlink operations (updates to the subvolume tree,
7334 * inodes, etc) are done.
7336 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
7337 struct btrfs_inode *dir, struct btrfs_inode *inode,
7341 * when we're logging a file, if it hasn't been renamed
7342 * or unlinked, and its inode is fully committed on disk,
7343 * we don't have to worry about walking up the directory chain
7344 * to log its parents.
7346 * So, we use the last_unlink_trans field to put this transid
7347 * into the file. When the file is logged we check it and
7348 * don't log the parents if the file is fully on disk.
7350 mutex_lock(&inode->log_mutex);
7351 inode->last_unlink_trans = trans->transid;
7352 mutex_unlock(&inode->log_mutex);
7355 * if this directory was already logged any new
7356 * names for this file/dir will get recorded
7358 if (dir->logged_trans == trans->transid)
7362 * if the inode we're about to unlink was logged,
7363 * the log will be properly updated for any new names
7365 if (inode->logged_trans == trans->transid)
7369 * when renaming files across directories, if the directory
7370 * there we're unlinking from gets fsync'd later on, there's
7371 * no way to find the destination directory later and fsync it
7372 * properly. So, we have to be conservative and force commits
7373 * so the new name gets discovered.
7378 /* we can safely do the unlink without any special recording */
7382 mutex_lock(&dir->log_mutex);
7383 dir->last_unlink_trans = trans->transid;
7384 mutex_unlock(&dir->log_mutex);
7388 * Make sure that if someone attempts to fsync the parent directory of a deleted
7389 * snapshot, it ends up triggering a transaction commit. This is to guarantee
7390 * that after replaying the log tree of the parent directory's root we will not
7391 * see the snapshot anymore and at log replay time we will not see any log tree
7392 * corresponding to the deleted snapshot's root, which could lead to replaying
7393 * it after replaying the log tree of the parent directory (which would replay
7394 * the snapshot delete operation).
7396 * Must be called before the actual snapshot destroy operation (updates to the
7397 * parent root and tree of tree roots trees, etc) are done.
7399 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
7400 struct btrfs_inode *dir)
7402 mutex_lock(&dir->log_mutex);
7403 dir->last_unlink_trans = trans->transid;
7404 mutex_unlock(&dir->log_mutex);
7408 * Update the log after adding a new name for an inode.
7410 * @trans: Transaction handle.
7411 * @old_dentry: The dentry associated with the old name and the old
7413 * @old_dir: The inode of the previous parent directory for the case
7414 * of a rename. For a link operation, it must be NULL.
7415 * @old_dir_index: The index number associated with the old name, meaningful
7416 * only for rename operations (when @old_dir is not NULL).
7417 * Ignored for link operations.
7418 * @parent: The dentry associated with the directory under which the
7419 * new name is located.
7421 * Call this after adding a new name for an inode, as a result of a link or
7422 * rename operation, and it will properly update the log to reflect the new name.
7424 void btrfs_log_new_name(struct btrfs_trans_handle *trans,
7425 struct dentry *old_dentry, struct btrfs_inode *old_dir,
7426 u64 old_dir_index, struct dentry *parent)
7428 struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
7429 struct btrfs_root *root = inode->root;
7430 struct btrfs_log_ctx ctx;
7431 bool log_pinned = false;
7435 * this will force the logging code to walk the dentry chain
7438 if (!S_ISDIR(inode->vfs_inode.i_mode))
7439 inode->last_unlink_trans = trans->transid;
7442 * if this inode hasn't been logged and directory we're renaming it
7443 * from hasn't been logged, we don't need to log it
7445 ret = inode_logged(trans, inode, NULL);
7448 } else if (ret == 0) {
7452 * If the inode was not logged and we are doing a rename (old_dir is not
7453 * NULL), check if old_dir was logged - if it was not we can return and
7456 ret = inode_logged(trans, old_dir, NULL);
7465 * If we are doing a rename (old_dir is not NULL) from a directory that
7466 * was previously logged, make sure that on log replay we get the old
7467 * dir entry deleted. This is needed because we will also log the new
7468 * name of the renamed inode, so we need to make sure that after log
7469 * replay we don't end up with both the new and old dir entries existing.
7471 if (old_dir && old_dir->logged_trans == trans->transid) {
7472 struct btrfs_root *log = old_dir->root->log_root;
7473 struct btrfs_path *path;
7474 struct fscrypt_name fname;
7476 ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
7478 ret = fscrypt_setup_filename(&old_dir->vfs_inode,
7479 &old_dentry->d_name, 0, &fname);
7483 * We have two inodes to update in the log, the old directory and
7484 * the inode that got renamed, so we must pin the log to prevent
7485 * anyone from syncing the log until we have updated both inodes
7488 ret = join_running_log_trans(root);
7490 * At least one of the inodes was logged before, so this should
7491 * not fail, but if it does, it's not serious, just bail out and
7492 * mark the log for a full commit.
7494 if (WARN_ON_ONCE(ret < 0)) {
7495 fscrypt_free_filename(&fname);
7501 path = btrfs_alloc_path();
7504 fscrypt_free_filename(&fname);
7509 * Other concurrent task might be logging the old directory,
7510 * as it can be triggered when logging other inode that had or
7511 * still has a dentry in the old directory. We lock the old
7512 * directory's log_mutex to ensure the deletion of the old
7513 * name is persisted, because during directory logging we
7514 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
7515 * the old name's dir index item is in the delayed items, so
7516 * it could be missed by an in progress directory logging.
7518 mutex_lock(&old_dir->log_mutex);
7519 ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
7520 &fname.disk_name, old_dir_index);
7523 * The dentry does not exist in the log, so record its
7526 btrfs_release_path(path);
7527 ret = insert_dir_log_key(trans, log, path,
7529 old_dir_index, old_dir_index);
7531 mutex_unlock(&old_dir->log_mutex);
7533 btrfs_free_path(path);
7534 fscrypt_free_filename(&fname);
7539 btrfs_init_log_ctx(&ctx, &inode->vfs_inode);
7540 ctx.logging_new_name = true;
7542 * We don't care about the return value. If we fail to log the new name
7543 * then we know the next attempt to sync the log will fallback to a full
7544 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
7545 * we don't need to worry about getting a log committed that has an
7546 * inconsistent state after a rename operation.
7548 btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
7549 ASSERT(list_empty(&ctx.conflict_inodes));
7552 * If an error happened mark the log for a full commit because it's not
7553 * consistent and up to date or we couldn't find out if one of the
7554 * inodes was logged before in this transaction. Do it before unpinning
7555 * the log, to avoid any races with someone else trying to commit it.
7558 btrfs_set_log_full_commit(trans);
7560 btrfs_end_log_trans(root);