1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2008 Oracle. All rights reserved.
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/blkdev.h>
9 #include <linux/list_sort.h>
10 #include <linux/iversion.h>
16 #include "print-tree.h"
18 #include "compression.h"
20 #include "block-group.h"
21 #include "space-info.h"
23 #include "inode-item.h"
25 #include "accessors.h"
26 #include "extent-tree.h"
27 #include "root-tree.h"
29 #include "file-item.h"
33 #define MAX_CONFLICT_INODES 10
35 /* magic values for the inode_only field in btrfs_log_inode:
37 * LOG_INODE_ALL means to log everything
38 * LOG_INODE_EXISTS means to log just enough to recreate the inode
47 * directory trouble cases
49 * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
50 * log, we must force a full commit before doing an fsync of the directory
51 * where the unlink was done.
52 * ---> record transid of last unlink/rename per directory
56 * rename foo/some_dir foo2/some_dir
58 * fsync foo/some_dir/some_file
60 * The fsync above will unlink the original some_dir without recording
61 * it in its new location (foo2). After a crash, some_dir will be gone
62 * unless the fsync of some_file forces a full commit
64 * 2) we must log any new names for any file or dir that is in the fsync
65 * log. ---> check inode while renaming/linking.
67 * 2a) we must log any new names for any file or dir during rename
68 * when the directory they are being removed from was logged.
69 * ---> check inode and old parent dir during rename
71 * 2a is actually the more important variant. With the extra logging
72 * a crash might unlink the old name without recreating the new one
74 * 3) after a crash, we must go through any directories with a link count
75 * of zero and redo the rm -rf
82 * The directory f1 was fully removed from the FS, but fsync was never
83 * called on f1, only its parent dir. After a crash the rm -rf must
84 * be replayed. This must be able to recurse down the entire
85 * directory tree. The inode link count fixup code takes care of the
90 * stages for the tree walking. The first
91 * stage (0) is to only pin down the blocks we find
92 * the second stage (1) is to make sure that all the inodes
93 * we find in the log are created in the subvolume.
95 * The last stage is to deal with directories and links and extents
96 * and all the other fun semantics
100 LOG_WALK_REPLAY_INODES,
101 LOG_WALK_REPLAY_DIR_INDEX,
105 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
106 struct btrfs_inode *inode,
108 struct btrfs_log_ctx *ctx);
109 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
110 struct btrfs_root *root,
111 struct btrfs_path *path, u64 objectid);
112 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
113 struct btrfs_root *root,
114 struct btrfs_root *log,
115 struct btrfs_path *path,
116 u64 dirid, int del_all);
117 static void wait_log_commit(struct btrfs_root *root, int transid);
120 * tree logging is a special write ahead log used to make sure that
121 * fsyncs and O_SYNCs can happen without doing full tree commits.
123 * Full tree commits are expensive because they require commonly
124 * modified blocks to be recowed, creating many dirty pages in the
125 * extent tree an 4x-6x higher write load than ext3.
127 * Instead of doing a tree commit on every fsync, we use the
128 * key ranges and transaction ids to find items for a given file or directory
129 * that have changed in this transaction. Those items are copied into
130 * a special tree (one per subvolume root), that tree is written to disk
131 * and then the fsync is considered complete.
133 * After a crash, items are copied out of the log-tree back into the
134 * subvolume tree. Any file data extents found are recorded in the extent
135 * allocation tree, and the log-tree freed.
137 * The log tree is read three times, once to pin down all the extents it is
138 * using in ram and once, once to create all the inodes logged in the tree
139 * and once to do all the other items.
143 * start a sub transaction and setup the log tree
144 * this increments the log tree writer count to make the people
145 * syncing the tree wait for us to finish
147 static int start_log_trans(struct btrfs_trans_handle *trans,
148 struct btrfs_root *root,
149 struct btrfs_log_ctx *ctx)
151 struct btrfs_fs_info *fs_info = root->fs_info;
152 struct btrfs_root *tree_root = fs_info->tree_root;
153 const bool zoned = btrfs_is_zoned(fs_info);
155 bool created = false;
158 * First check if the log root tree was already created. If not, create
159 * it before locking the root's log_mutex, just to keep lockdep happy.
161 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
162 mutex_lock(&tree_root->log_mutex);
163 if (!fs_info->log_root_tree) {
164 ret = btrfs_init_log_root_tree(trans, fs_info);
166 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
170 mutex_unlock(&tree_root->log_mutex);
175 mutex_lock(&root->log_mutex);
178 if (root->log_root) {
179 int index = (root->log_transid + 1) % 2;
181 if (btrfs_need_log_full_commit(trans)) {
182 ret = BTRFS_LOG_FORCE_COMMIT;
186 if (zoned && atomic_read(&root->log_commit[index])) {
187 wait_log_commit(root, root->log_transid - 1);
191 if (!root->log_start_pid) {
192 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
193 root->log_start_pid = current->pid;
194 } else if (root->log_start_pid != current->pid) {
195 set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
199 * This means fs_info->log_root_tree was already created
200 * for some other FS trees. Do the full commit not to mix
201 * nodes from multiple log transactions to do sequential
204 if (zoned && !created) {
205 ret = BTRFS_LOG_FORCE_COMMIT;
209 ret = btrfs_add_log_tree(trans, root);
213 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
214 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
215 root->log_start_pid = current->pid;
218 atomic_inc(&root->log_writers);
219 if (!ctx->logging_new_name) {
220 int index = root->log_transid % 2;
221 list_add_tail(&ctx->list, &root->log_ctxs[index]);
222 ctx->log_transid = root->log_transid;
226 mutex_unlock(&root->log_mutex);
231 * returns 0 if there was a log transaction running and we were able
232 * to join, or returns -ENOENT if there were not transactions
235 static int join_running_log_trans(struct btrfs_root *root)
237 const bool zoned = btrfs_is_zoned(root->fs_info);
240 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
243 mutex_lock(&root->log_mutex);
245 if (root->log_root) {
246 int index = (root->log_transid + 1) % 2;
249 if (zoned && atomic_read(&root->log_commit[index])) {
250 wait_log_commit(root, root->log_transid - 1);
253 atomic_inc(&root->log_writers);
255 mutex_unlock(&root->log_mutex);
260 * This either makes the current running log transaction wait
261 * until you call btrfs_end_log_trans() or it makes any future
262 * log transactions wait until you call btrfs_end_log_trans()
264 void btrfs_pin_log_trans(struct btrfs_root *root)
266 atomic_inc(&root->log_writers);
270 * indicate we're done making changes to the log tree
271 * and wake up anyone waiting to do a sync
273 void btrfs_end_log_trans(struct btrfs_root *root)
275 if (atomic_dec_and_test(&root->log_writers)) {
276 /* atomic_dec_and_test implies a barrier */
277 cond_wake_up_nomb(&root->log_writer_wait);
281 static void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
283 filemap_fdatawait_range(buf->pages[0]->mapping,
284 buf->start, buf->start + buf->len - 1);
288 * the walk control struct is used to pass state down the chain when
289 * processing the log tree. The stage field tells us which part
290 * of the log tree processing we are currently doing. The others
291 * are state fields used for that specific part
293 struct walk_control {
294 /* should we free the extent on disk when done? This is used
295 * at transaction commit time while freeing a log tree
299 /* pin only walk, we record which extents on disk belong to the
304 /* what stage of the replay code we're currently in */
308 * Ignore any items from the inode currently being processed. Needs
309 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
310 * the LOG_WALK_REPLAY_INODES stage.
312 bool ignore_cur_inode;
314 /* the root we are currently replaying */
315 struct btrfs_root *replay_dest;
317 /* the trans handle for the current replay */
318 struct btrfs_trans_handle *trans;
320 /* the function that gets used to process blocks we find in the
321 * tree. Note the extent_buffer might not be up to date when it is
322 * passed in, and it must be checked or read if you need the data
325 int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
326 struct walk_control *wc, u64 gen, int level);
330 * process_func used to pin down extents, write them or wait on them
332 static int process_one_buffer(struct btrfs_root *log,
333 struct extent_buffer *eb,
334 struct walk_control *wc, u64 gen, int level)
336 struct btrfs_fs_info *fs_info = log->fs_info;
340 * If this fs is mixed then we need to be able to process the leaves to
341 * pin down any logged extents, so we have to read the block.
343 if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
344 ret = btrfs_read_extent_buffer(eb, gen, level, NULL);
350 ret = btrfs_pin_extent_for_log_replay(wc->trans, eb->start,
355 if (btrfs_buffer_uptodate(eb, gen, 0) &&
356 btrfs_header_level(eb) == 0)
357 ret = btrfs_exclude_logged_extents(eb);
362 static int do_overwrite_item(struct btrfs_trans_handle *trans,
363 struct btrfs_root *root,
364 struct btrfs_path *path,
365 struct extent_buffer *eb, int slot,
366 struct btrfs_key *key)
370 u64 saved_i_size = 0;
371 int save_old_i_size = 0;
372 unsigned long src_ptr;
373 unsigned long dst_ptr;
374 int overwrite_root = 0;
375 bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
377 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
380 item_size = btrfs_item_size(eb, slot);
381 src_ptr = btrfs_item_ptr_offset(eb, slot);
383 /* Our caller must have done a search for the key for us. */
384 ASSERT(path->nodes[0] != NULL);
387 * And the slot must point to the exact key or the slot where the key
388 * should be at (the first item with a key greater than 'key')
390 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
391 struct btrfs_key found_key;
393 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
394 ret = btrfs_comp_cpu_keys(&found_key, key);
403 u32 dst_size = btrfs_item_size(path->nodes[0],
405 if (dst_size != item_size)
408 if (item_size == 0) {
409 btrfs_release_path(path);
412 dst_copy = kmalloc(item_size, GFP_NOFS);
413 src_copy = kmalloc(item_size, GFP_NOFS);
414 if (!dst_copy || !src_copy) {
415 btrfs_release_path(path);
421 read_extent_buffer(eb, src_copy, src_ptr, item_size);
423 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
424 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
426 ret = memcmp(dst_copy, src_copy, item_size);
431 * they have the same contents, just return, this saves
432 * us from cowing blocks in the destination tree and doing
433 * extra writes that may not have been done by a previous
437 btrfs_release_path(path);
442 * We need to load the old nbytes into the inode so when we
443 * replay the extents we've logged we get the right nbytes.
446 struct btrfs_inode_item *item;
450 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
451 struct btrfs_inode_item);
452 nbytes = btrfs_inode_nbytes(path->nodes[0], item);
453 item = btrfs_item_ptr(eb, slot,
454 struct btrfs_inode_item);
455 btrfs_set_inode_nbytes(eb, item, nbytes);
458 * If this is a directory we need to reset the i_size to
459 * 0 so that we can set it up properly when replaying
460 * the rest of the items in this log.
462 mode = btrfs_inode_mode(eb, item);
464 btrfs_set_inode_size(eb, item, 0);
466 } else if (inode_item) {
467 struct btrfs_inode_item *item;
471 * New inode, set nbytes to 0 so that the nbytes comes out
472 * properly when we replay the extents.
474 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
475 btrfs_set_inode_nbytes(eb, item, 0);
478 * If this is a directory we need to reset the i_size to 0 so
479 * that we can set it up properly when replaying the rest of
480 * the items in this log.
482 mode = btrfs_inode_mode(eb, item);
484 btrfs_set_inode_size(eb, item, 0);
487 btrfs_release_path(path);
488 /* try to insert the key into the destination tree */
489 path->skip_release_on_error = 1;
490 ret = btrfs_insert_empty_item(trans, root, path,
492 path->skip_release_on_error = 0;
494 /* make sure any existing item is the correct size */
495 if (ret == -EEXIST || ret == -EOVERFLOW) {
497 found_size = btrfs_item_size(path->nodes[0],
499 if (found_size > item_size)
500 btrfs_truncate_item(path, item_size, 1);
501 else if (found_size < item_size)
502 btrfs_extend_item(path, item_size - found_size);
506 dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
509 /* don't overwrite an existing inode if the generation number
510 * was logged as zero. This is done when the tree logging code
511 * is just logging an inode to make sure it exists after recovery.
513 * Also, don't overwrite i_size on directories during replay.
514 * log replay inserts and removes directory items based on the
515 * state of the tree found in the subvolume, and i_size is modified
518 if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
519 struct btrfs_inode_item *src_item;
520 struct btrfs_inode_item *dst_item;
522 src_item = (struct btrfs_inode_item *)src_ptr;
523 dst_item = (struct btrfs_inode_item *)dst_ptr;
525 if (btrfs_inode_generation(eb, src_item) == 0) {
526 struct extent_buffer *dst_eb = path->nodes[0];
527 const u64 ino_size = btrfs_inode_size(eb, src_item);
530 * For regular files an ino_size == 0 is used only when
531 * logging that an inode exists, as part of a directory
532 * fsync, and the inode wasn't fsynced before. In this
533 * case don't set the size of the inode in the fs/subvol
534 * tree, otherwise we would be throwing valid data away.
536 if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
537 S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
539 btrfs_set_inode_size(dst_eb, dst_item, ino_size);
543 if (overwrite_root &&
544 S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
545 S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
547 saved_i_size = btrfs_inode_size(path->nodes[0],
552 copy_extent_buffer(path->nodes[0], eb, dst_ptr,
555 if (save_old_i_size) {
556 struct btrfs_inode_item *dst_item;
557 dst_item = (struct btrfs_inode_item *)dst_ptr;
558 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
561 /* make sure the generation is filled in */
562 if (key->type == BTRFS_INODE_ITEM_KEY) {
563 struct btrfs_inode_item *dst_item;
564 dst_item = (struct btrfs_inode_item *)dst_ptr;
565 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
566 btrfs_set_inode_generation(path->nodes[0], dst_item,
571 btrfs_mark_buffer_dirty(path->nodes[0]);
572 btrfs_release_path(path);
577 * Item overwrite used by replay and tree logging. eb, slot and key all refer
578 * to the src data we are copying out.
580 * root is the tree we are copying into, and path is a scratch
581 * path for use in this function (it should be released on entry and
582 * will be released on exit).
584 * If the key is already in the destination tree the existing item is
585 * overwritten. If the existing item isn't big enough, it is extended.
586 * If it is too large, it is truncated.
588 * If the key isn't in the destination yet, a new item is inserted.
590 static int overwrite_item(struct btrfs_trans_handle *trans,
591 struct btrfs_root *root,
592 struct btrfs_path *path,
593 struct extent_buffer *eb, int slot,
594 struct btrfs_key *key)
598 /* Look for the key in the destination tree. */
599 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
603 return do_overwrite_item(trans, root, path, eb, slot, key);
606 static int read_alloc_one_name(struct extent_buffer *eb, void *start, int len,
607 struct fscrypt_str *name)
611 buf = kmalloc(len, GFP_NOFS);
615 read_extent_buffer(eb, buf, (unsigned long)start, len);
622 * simple helper to read an inode off the disk from a given root
623 * This can only be called for subvolume roots and not for the log
625 static noinline struct inode *read_one_inode(struct btrfs_root *root,
630 inode = btrfs_iget(root->fs_info->sb, objectid, root);
636 /* replays a single extent in 'eb' at 'slot' with 'key' into the
637 * subvolume 'root'. path is released on entry and should be released
640 * extents in the log tree have not been allocated out of the extent
641 * tree yet. So, this completes the allocation, taking a reference
642 * as required if the extent already exists or creating a new extent
643 * if it isn't in the extent allocation tree yet.
645 * The extent is inserted into the file, dropping any existing extents
646 * from the file that overlap the new one.
648 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
649 struct btrfs_root *root,
650 struct btrfs_path *path,
651 struct extent_buffer *eb, int slot,
652 struct btrfs_key *key)
654 struct btrfs_drop_extents_args drop_args = { 0 };
655 struct btrfs_fs_info *fs_info = root->fs_info;
658 u64 start = key->offset;
660 struct btrfs_file_extent_item *item;
661 struct inode *inode = NULL;
665 item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
666 found_type = btrfs_file_extent_type(eb, item);
668 if (found_type == BTRFS_FILE_EXTENT_REG ||
669 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
670 nbytes = btrfs_file_extent_num_bytes(eb, item);
671 extent_end = start + nbytes;
674 * We don't add to the inodes nbytes if we are prealloc or a
677 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
679 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
680 size = btrfs_file_extent_ram_bytes(eb, item);
681 nbytes = btrfs_file_extent_ram_bytes(eb, item);
682 extent_end = ALIGN(start + size,
683 fs_info->sectorsize);
689 inode = read_one_inode(root, key->objectid);
696 * first check to see if we already have this extent in the
697 * file. This must be done before the btrfs_drop_extents run
698 * so we don't try to drop this extent.
700 ret = btrfs_lookup_file_extent(trans, root, path,
701 btrfs_ino(BTRFS_I(inode)), start, 0);
704 (found_type == BTRFS_FILE_EXTENT_REG ||
705 found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
706 struct btrfs_file_extent_item cmp1;
707 struct btrfs_file_extent_item cmp2;
708 struct btrfs_file_extent_item *existing;
709 struct extent_buffer *leaf;
711 leaf = path->nodes[0];
712 existing = btrfs_item_ptr(leaf, path->slots[0],
713 struct btrfs_file_extent_item);
715 read_extent_buffer(eb, &cmp1, (unsigned long)item,
717 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
721 * we already have a pointer to this exact extent,
722 * we don't have to do anything
724 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
725 btrfs_release_path(path);
729 btrfs_release_path(path);
731 /* drop any overlapping extents */
732 drop_args.start = start;
733 drop_args.end = extent_end;
734 drop_args.drop_cache = true;
735 ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
739 if (found_type == BTRFS_FILE_EXTENT_REG ||
740 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
742 unsigned long dest_offset;
743 struct btrfs_key ins;
745 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
746 btrfs_fs_incompat(fs_info, NO_HOLES))
749 ret = btrfs_insert_empty_item(trans, root, path, key,
753 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
755 copy_extent_buffer(path->nodes[0], eb, dest_offset,
756 (unsigned long)item, sizeof(*item));
758 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
759 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
760 ins.type = BTRFS_EXTENT_ITEM_KEY;
761 offset = key->offset - btrfs_file_extent_offset(eb, item);
764 * Manually record dirty extent, as here we did a shallow
765 * file extent item copy and skip normal backref update,
766 * but modifying extent tree all by ourselves.
767 * So need to manually record dirty extent for qgroup,
768 * as the owner of the file extent changed from log tree
769 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
771 ret = btrfs_qgroup_trace_extent(trans,
772 btrfs_file_extent_disk_bytenr(eb, item),
773 btrfs_file_extent_disk_num_bytes(eb, item));
777 if (ins.objectid > 0) {
778 struct btrfs_ref ref = { 0 };
781 LIST_HEAD(ordered_sums);
784 * is this extent already allocated in the extent
785 * allocation tree? If so, just add a reference
787 ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
791 } else if (ret == 0) {
792 btrfs_init_generic_ref(&ref,
793 BTRFS_ADD_DELAYED_REF,
794 ins.objectid, ins.offset, 0);
795 btrfs_init_data_ref(&ref,
796 root->root_key.objectid,
797 key->objectid, offset, 0, false);
798 ret = btrfs_inc_extent_ref(trans, &ref);
803 * insert the extent pointer in the extent
806 ret = btrfs_alloc_logged_file_extent(trans,
807 root->root_key.objectid,
808 key->objectid, offset, &ins);
812 btrfs_release_path(path);
814 if (btrfs_file_extent_compression(eb, item)) {
815 csum_start = ins.objectid;
816 csum_end = csum_start + ins.offset;
818 csum_start = ins.objectid +
819 btrfs_file_extent_offset(eb, item);
820 csum_end = csum_start +
821 btrfs_file_extent_num_bytes(eb, item);
824 ret = btrfs_lookup_csums_range(root->log_root,
825 csum_start, csum_end - 1,
826 &ordered_sums, 0, false);
830 * Now delete all existing cums in the csum root that
831 * cover our range. We do this because we can have an
832 * extent that is completely referenced by one file
833 * extent item and partially referenced by another
834 * file extent item (like after using the clone or
835 * extent_same ioctls). In this case if we end up doing
836 * the replay of the one that partially references the
837 * extent first, and we do not do the csum deletion
838 * below, we can get 2 csum items in the csum tree that
839 * overlap each other. For example, imagine our log has
840 * the two following file extent items:
842 * key (257 EXTENT_DATA 409600)
843 * extent data disk byte 12845056 nr 102400
844 * extent data offset 20480 nr 20480 ram 102400
846 * key (257 EXTENT_DATA 819200)
847 * extent data disk byte 12845056 nr 102400
848 * extent data offset 0 nr 102400 ram 102400
850 * Where the second one fully references the 100K extent
851 * that starts at disk byte 12845056, and the log tree
852 * has a single csum item that covers the entire range
855 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
857 * After the first file extent item is replayed, the
858 * csum tree gets the following csum item:
860 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
862 * Which covers the 20K sub-range starting at offset 20K
863 * of our extent. Now when we replay the second file
864 * extent item, if we do not delete existing csum items
865 * that cover any of its blocks, we end up getting two
866 * csum items in our csum tree that overlap each other:
868 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
869 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
871 * Which is a problem, because after this anyone trying
872 * to lookup up for the checksum of any block of our
873 * extent starting at an offset of 40K or higher, will
874 * end up looking at the second csum item only, which
875 * does not contain the checksum for any block starting
876 * at offset 40K or higher of our extent.
878 while (!list_empty(&ordered_sums)) {
879 struct btrfs_ordered_sum *sums;
880 struct btrfs_root *csum_root;
882 sums = list_entry(ordered_sums.next,
883 struct btrfs_ordered_sum,
885 csum_root = btrfs_csum_root(fs_info,
888 ret = btrfs_del_csums(trans, csum_root,
892 ret = btrfs_csum_file_blocks(trans,
895 list_del(&sums->list);
901 btrfs_release_path(path);
903 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
904 /* inline extents are easy, we just overwrite them */
905 ret = overwrite_item(trans, root, path, eb, slot, key);
910 ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start,
916 btrfs_update_inode_bytes(BTRFS_I(inode), nbytes, drop_args.bytes_found);
917 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
923 static int unlink_inode_for_log_replay(struct btrfs_trans_handle *trans,
924 struct btrfs_inode *dir,
925 struct btrfs_inode *inode,
926 const struct fscrypt_str *name)
930 ret = btrfs_unlink_inode(trans, dir, inode, name);
934 * Whenever we need to check if a name exists or not, we check the
935 * fs/subvolume tree. So after an unlink we must run delayed items, so
936 * that future checks for a name during log replay see that the name
937 * does not exists anymore.
939 return btrfs_run_delayed_items(trans);
943 * when cleaning up conflicts between the directory names in the
944 * subvolume, directory names in the log and directory names in the
945 * inode back references, we may have to unlink inodes from directories.
947 * This is a helper function to do the unlink of a specific directory
950 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
951 struct btrfs_path *path,
952 struct btrfs_inode *dir,
953 struct btrfs_dir_item *di)
955 struct btrfs_root *root = dir->root;
957 struct fscrypt_str name;
958 struct extent_buffer *leaf;
959 struct btrfs_key location;
962 leaf = path->nodes[0];
964 btrfs_dir_item_key_to_cpu(leaf, di, &location);
965 ret = read_alloc_one_name(leaf, di + 1, btrfs_dir_name_len(leaf, di), &name);
969 btrfs_release_path(path);
971 inode = read_one_inode(root, location.objectid);
977 ret = link_to_fixup_dir(trans, root, path, location.objectid);
981 ret = unlink_inode_for_log_replay(trans, dir, BTRFS_I(inode), &name);
989 * See if a given name and sequence number found in an inode back reference are
990 * already in a directory and correctly point to this inode.
992 * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
995 static noinline int inode_in_dir(struct btrfs_root *root,
996 struct btrfs_path *path,
997 u64 dirid, u64 objectid, u64 index,
998 struct fscrypt_str *name)
1000 struct btrfs_dir_item *di;
1001 struct btrfs_key location;
1004 di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
1010 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1011 if (location.objectid != objectid)
1017 btrfs_release_path(path);
1018 di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, 0);
1023 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1024 if (location.objectid == objectid)
1028 btrfs_release_path(path);
1033 * helper function to check a log tree for a named back reference in
1034 * an inode. This is used to decide if a back reference that is
1035 * found in the subvolume conflicts with what we find in the log.
1037 * inode backreferences may have multiple refs in a single item,
1038 * during replay we process one reference at a time, and we don't
1039 * want to delete valid links to a file from the subvolume if that
1040 * link is also in the log.
1042 static noinline int backref_in_log(struct btrfs_root *log,
1043 struct btrfs_key *key,
1045 const struct fscrypt_str *name)
1047 struct btrfs_path *path;
1050 path = btrfs_alloc_path();
1054 ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1057 } else if (ret == 1) {
1062 if (key->type == BTRFS_INODE_EXTREF_KEY)
1063 ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
1065 ref_objectid, name);
1067 ret = !!btrfs_find_name_in_backref(path->nodes[0],
1068 path->slots[0], name);
1070 btrfs_free_path(path);
1074 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
1075 struct btrfs_root *root,
1076 struct btrfs_path *path,
1077 struct btrfs_root *log_root,
1078 struct btrfs_inode *dir,
1079 struct btrfs_inode *inode,
1080 u64 inode_objectid, u64 parent_objectid,
1081 u64 ref_index, struct fscrypt_str *name)
1084 struct extent_buffer *leaf;
1085 struct btrfs_dir_item *di;
1086 struct btrfs_key search_key;
1087 struct btrfs_inode_extref *extref;
1090 /* Search old style refs */
1091 search_key.objectid = inode_objectid;
1092 search_key.type = BTRFS_INODE_REF_KEY;
1093 search_key.offset = parent_objectid;
1094 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1096 struct btrfs_inode_ref *victim_ref;
1098 unsigned long ptr_end;
1100 leaf = path->nodes[0];
1102 /* are we trying to overwrite a back ref for the root directory
1103 * if so, just jump out, we're done
1105 if (search_key.objectid == search_key.offset)
1108 /* check all the names in this back reference to see
1109 * if they are in the log. if so, we allow them to stay
1110 * otherwise they must be unlinked as a conflict
1112 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1113 ptr_end = ptr + btrfs_item_size(leaf, path->slots[0]);
1114 while (ptr < ptr_end) {
1115 struct fscrypt_str victim_name;
1117 victim_ref = (struct btrfs_inode_ref *)ptr;
1118 ret = read_alloc_one_name(leaf, (victim_ref + 1),
1119 btrfs_inode_ref_name_len(leaf, victim_ref),
1124 ret = backref_in_log(log_root, &search_key,
1125 parent_objectid, &victim_name);
1127 kfree(victim_name.name);
1130 inc_nlink(&inode->vfs_inode);
1131 btrfs_release_path(path);
1133 ret = unlink_inode_for_log_replay(trans, dir, inode,
1135 kfree(victim_name.name);
1140 kfree(victim_name.name);
1142 ptr = (unsigned long)(victim_ref + 1) + victim_name.len;
1145 btrfs_release_path(path);
1147 /* Same search but for extended refs */
1148 extref = btrfs_lookup_inode_extref(NULL, root, path, name,
1149 inode_objectid, parent_objectid, 0,
1151 if (IS_ERR(extref)) {
1152 return PTR_ERR(extref);
1153 } else if (extref) {
1157 struct inode *victim_parent;
1159 leaf = path->nodes[0];
1161 item_size = btrfs_item_size(leaf, path->slots[0]);
1162 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1164 while (cur_offset < item_size) {
1165 struct fscrypt_str victim_name;
1167 extref = (struct btrfs_inode_extref *)(base + cur_offset);
1169 if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1172 ret = read_alloc_one_name(leaf, &extref->name,
1173 btrfs_inode_extref_name_len(leaf, extref),
1178 search_key.objectid = inode_objectid;
1179 search_key.type = BTRFS_INODE_EXTREF_KEY;
1180 search_key.offset = btrfs_extref_hash(parent_objectid,
1183 ret = backref_in_log(log_root, &search_key,
1184 parent_objectid, &victim_name);
1186 kfree(victim_name.name);
1190 victim_parent = read_one_inode(root,
1192 if (victim_parent) {
1193 inc_nlink(&inode->vfs_inode);
1194 btrfs_release_path(path);
1196 ret = unlink_inode_for_log_replay(trans,
1197 BTRFS_I(victim_parent),
1198 inode, &victim_name);
1200 iput(victim_parent);
1201 kfree(victim_name.name);
1206 kfree(victim_name.name);
1208 cur_offset += victim_name.len + sizeof(*extref);
1211 btrfs_release_path(path);
1213 /* look for a conflicting sequence number */
1214 di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1215 ref_index, name, 0);
1219 ret = drop_one_dir_item(trans, path, dir, di);
1223 btrfs_release_path(path);
1225 /* look for a conflicting name */
1226 di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir), name, 0);
1230 ret = drop_one_dir_item(trans, path, dir, di);
1234 btrfs_release_path(path);
1239 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1240 struct fscrypt_str *name, u64 *index,
1241 u64 *parent_objectid)
1243 struct btrfs_inode_extref *extref;
1246 extref = (struct btrfs_inode_extref *)ref_ptr;
1248 ret = read_alloc_one_name(eb, &extref->name,
1249 btrfs_inode_extref_name_len(eb, extref), name);
1254 *index = btrfs_inode_extref_index(eb, extref);
1255 if (parent_objectid)
1256 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1261 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1262 struct fscrypt_str *name, u64 *index)
1264 struct btrfs_inode_ref *ref;
1267 ref = (struct btrfs_inode_ref *)ref_ptr;
1269 ret = read_alloc_one_name(eb, ref + 1, btrfs_inode_ref_name_len(eb, ref),
1275 *index = btrfs_inode_ref_index(eb, ref);
1281 * Take an inode reference item from the log tree and iterate all names from the
1282 * inode reference item in the subvolume tree with the same key (if it exists).
1283 * For any name that is not in the inode reference item from the log tree, do a
1284 * proper unlink of that name (that is, remove its entry from the inode
1285 * reference item and both dir index keys).
1287 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1288 struct btrfs_root *root,
1289 struct btrfs_path *path,
1290 struct btrfs_inode *inode,
1291 struct extent_buffer *log_eb,
1293 struct btrfs_key *key)
1296 unsigned long ref_ptr;
1297 unsigned long ref_end;
1298 struct extent_buffer *eb;
1301 btrfs_release_path(path);
1302 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1310 eb = path->nodes[0];
1311 ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1312 ref_end = ref_ptr + btrfs_item_size(eb, path->slots[0]);
1313 while (ref_ptr < ref_end) {
1314 struct fscrypt_str name;
1317 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1318 ret = extref_get_fields(eb, ref_ptr, &name,
1321 parent_id = key->offset;
1322 ret = ref_get_fields(eb, ref_ptr, &name, NULL);
1327 if (key->type == BTRFS_INODE_EXTREF_KEY)
1328 ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
1331 ret = !!btrfs_find_name_in_backref(log_eb, log_slot, &name);
1336 btrfs_release_path(path);
1337 dir = read_one_inode(root, parent_id);
1343 ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir),
1353 ref_ptr += name.len;
1354 if (key->type == BTRFS_INODE_EXTREF_KEY)
1355 ref_ptr += sizeof(struct btrfs_inode_extref);
1357 ref_ptr += sizeof(struct btrfs_inode_ref);
1361 btrfs_release_path(path);
1366 * replay one inode back reference item found in the log tree.
1367 * eb, slot and key refer to the buffer and key found in the log tree.
1368 * root is the destination we are replaying into, and path is for temp
1369 * use by this function. (it should be released on return).
1371 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1372 struct btrfs_root *root,
1373 struct btrfs_root *log,
1374 struct btrfs_path *path,
1375 struct extent_buffer *eb, int slot,
1376 struct btrfs_key *key)
1378 struct inode *dir = NULL;
1379 struct inode *inode = NULL;
1380 unsigned long ref_ptr;
1381 unsigned long ref_end;
1382 struct fscrypt_str name;
1384 int log_ref_ver = 0;
1385 u64 parent_objectid;
1388 int ref_struct_size;
1390 ref_ptr = btrfs_item_ptr_offset(eb, slot);
1391 ref_end = ref_ptr + btrfs_item_size(eb, slot);
1393 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1394 struct btrfs_inode_extref *r;
1396 ref_struct_size = sizeof(struct btrfs_inode_extref);
1398 r = (struct btrfs_inode_extref *)ref_ptr;
1399 parent_objectid = btrfs_inode_extref_parent(eb, r);
1401 ref_struct_size = sizeof(struct btrfs_inode_ref);
1402 parent_objectid = key->offset;
1404 inode_objectid = key->objectid;
1407 * it is possible that we didn't log all the parent directories
1408 * for a given inode. If we don't find the dir, just don't
1409 * copy the back ref in. The link count fixup code will take
1412 dir = read_one_inode(root, parent_objectid);
1418 inode = read_one_inode(root, inode_objectid);
1424 while (ref_ptr < ref_end) {
1426 ret = extref_get_fields(eb, ref_ptr, &name,
1427 &ref_index, &parent_objectid);
1429 * parent object can change from one array
1433 dir = read_one_inode(root, parent_objectid);
1439 ret = ref_get_fields(eb, ref_ptr, &name, &ref_index);
1444 ret = inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1445 btrfs_ino(BTRFS_I(inode)), ref_index, &name);
1448 } else if (ret == 0) {
1450 * look for a conflicting back reference in the
1451 * metadata. if we find one we have to unlink that name
1452 * of the file before we add our new link. Later on, we
1453 * overwrite any existing back reference, and we don't
1454 * want to create dangling pointers in the directory.
1456 ret = __add_inode_ref(trans, root, path, log,
1457 BTRFS_I(dir), BTRFS_I(inode),
1458 inode_objectid, parent_objectid,
1466 /* insert our name */
1467 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
1468 &name, 0, ref_index);
1472 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1476 /* Else, ret == 1, we already have a perfect match, we're done. */
1478 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + name.len;
1488 * Before we overwrite the inode reference item in the subvolume tree
1489 * with the item from the log tree, we must unlink all names from the
1490 * parent directory that are in the subvolume's tree inode reference
1491 * item, otherwise we end up with an inconsistent subvolume tree where
1492 * dir index entries exist for a name but there is no inode reference
1493 * item with the same name.
1495 ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1500 /* finally write the back reference in the inode */
1501 ret = overwrite_item(trans, root, path, eb, slot, key);
1503 btrfs_release_path(path);
1510 static int count_inode_extrefs(struct btrfs_root *root,
1511 struct btrfs_inode *inode, struct btrfs_path *path)
1515 unsigned int nlink = 0;
1518 u64 inode_objectid = btrfs_ino(inode);
1521 struct btrfs_inode_extref *extref;
1522 struct extent_buffer *leaf;
1525 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1530 leaf = path->nodes[0];
1531 item_size = btrfs_item_size(leaf, path->slots[0]);
1532 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1535 while (cur_offset < item_size) {
1536 extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1537 name_len = btrfs_inode_extref_name_len(leaf, extref);
1541 cur_offset += name_len + sizeof(*extref);
1545 btrfs_release_path(path);
1547 btrfs_release_path(path);
1549 if (ret < 0 && ret != -ENOENT)
1554 static int count_inode_refs(struct btrfs_root *root,
1555 struct btrfs_inode *inode, struct btrfs_path *path)
1558 struct btrfs_key key;
1559 unsigned int nlink = 0;
1561 unsigned long ptr_end;
1563 u64 ino = btrfs_ino(inode);
1566 key.type = BTRFS_INODE_REF_KEY;
1567 key.offset = (u64)-1;
1570 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1574 if (path->slots[0] == 0)
1579 btrfs_item_key_to_cpu(path->nodes[0], &key,
1581 if (key.objectid != ino ||
1582 key.type != BTRFS_INODE_REF_KEY)
1584 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1585 ptr_end = ptr + btrfs_item_size(path->nodes[0],
1587 while (ptr < ptr_end) {
1588 struct btrfs_inode_ref *ref;
1590 ref = (struct btrfs_inode_ref *)ptr;
1591 name_len = btrfs_inode_ref_name_len(path->nodes[0],
1593 ptr = (unsigned long)(ref + 1) + name_len;
1597 if (key.offset == 0)
1599 if (path->slots[0] > 0) {
1604 btrfs_release_path(path);
1606 btrfs_release_path(path);
1612 * There are a few corners where the link count of the file can't
1613 * be properly maintained during replay. So, instead of adding
1614 * lots of complexity to the log code, we just scan the backrefs
1615 * for any file that has been through replay.
1617 * The scan will update the link count on the inode to reflect the
1618 * number of back refs found. If it goes down to zero, the iput
1619 * will free the inode.
1621 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1622 struct btrfs_root *root,
1623 struct inode *inode)
1625 struct btrfs_path *path;
1628 u64 ino = btrfs_ino(BTRFS_I(inode));
1630 path = btrfs_alloc_path();
1634 ret = count_inode_refs(root, BTRFS_I(inode), path);
1640 ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1648 if (nlink != inode->i_nlink) {
1649 set_nlink(inode, nlink);
1650 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1654 BTRFS_I(inode)->index_cnt = (u64)-1;
1656 if (inode->i_nlink == 0) {
1657 if (S_ISDIR(inode->i_mode)) {
1658 ret = replay_dir_deletes(trans, root, NULL, path,
1663 ret = btrfs_insert_orphan_item(trans, root, ino);
1669 btrfs_free_path(path);
1673 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1674 struct btrfs_root *root,
1675 struct btrfs_path *path)
1678 struct btrfs_key key;
1679 struct inode *inode;
1681 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1682 key.type = BTRFS_ORPHAN_ITEM_KEY;
1683 key.offset = (u64)-1;
1685 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1691 if (path->slots[0] == 0)
1696 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1697 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1698 key.type != BTRFS_ORPHAN_ITEM_KEY)
1701 ret = btrfs_del_item(trans, root, path);
1705 btrfs_release_path(path);
1706 inode = read_one_inode(root, key.offset);
1712 ret = fixup_inode_link_count(trans, root, inode);
1718 * fixup on a directory may create new entries,
1719 * make sure we always look for the highset possible
1722 key.offset = (u64)-1;
1724 btrfs_release_path(path);
1730 * record a given inode in the fixup dir so we can check its link
1731 * count when replay is done. The link count is incremented here
1732 * so the inode won't go away until we check it
1734 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1735 struct btrfs_root *root,
1736 struct btrfs_path *path,
1739 struct btrfs_key key;
1741 struct inode *inode;
1743 inode = read_one_inode(root, objectid);
1747 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1748 key.type = BTRFS_ORPHAN_ITEM_KEY;
1749 key.offset = objectid;
1751 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1753 btrfs_release_path(path);
1755 if (!inode->i_nlink)
1756 set_nlink(inode, 1);
1759 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1760 } else if (ret == -EEXIST) {
1769 * when replaying the log for a directory, we only insert names
1770 * for inodes that actually exist. This means an fsync on a directory
1771 * does not implicitly fsync all the new files in it
1773 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1774 struct btrfs_root *root,
1775 u64 dirid, u64 index,
1776 const struct fscrypt_str *name,
1777 struct btrfs_key *location)
1779 struct inode *inode;
1783 inode = read_one_inode(root, location->objectid);
1787 dir = read_one_inode(root, dirid);
1793 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1796 /* FIXME, put inode into FIXUP list */
1803 static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
1804 struct btrfs_inode *dir,
1805 struct btrfs_path *path,
1806 struct btrfs_dir_item *dst_di,
1807 const struct btrfs_key *log_key,
1811 struct btrfs_key found_key;
1813 btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1814 /* The existing dentry points to the same inode, don't delete it. */
1815 if (found_key.objectid == log_key->objectid &&
1816 found_key.type == log_key->type &&
1817 found_key.offset == log_key->offset &&
1818 btrfs_dir_flags(path->nodes[0], dst_di) == log_flags)
1822 * Don't drop the conflicting directory entry if the inode for the new
1823 * entry doesn't exist.
1828 return drop_one_dir_item(trans, path, dir, dst_di);
1832 * take a single entry in a log directory item and replay it into
1835 * if a conflicting item exists in the subdirectory already,
1836 * the inode it points to is unlinked and put into the link count
1839 * If a name from the log points to a file or directory that does
1840 * not exist in the FS, it is skipped. fsyncs on directories
1841 * do not force down inodes inside that directory, just changes to the
1842 * names or unlinks in a directory.
1844 * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1845 * non-existing inode) and 1 if the name was replayed.
1847 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1848 struct btrfs_root *root,
1849 struct btrfs_path *path,
1850 struct extent_buffer *eb,
1851 struct btrfs_dir_item *di,
1852 struct btrfs_key *key)
1854 struct fscrypt_str name;
1855 struct btrfs_dir_item *dir_dst_di;
1856 struct btrfs_dir_item *index_dst_di;
1857 bool dir_dst_matches = false;
1858 bool index_dst_matches = false;
1859 struct btrfs_key log_key;
1860 struct btrfs_key search_key;
1865 bool update_size = true;
1866 bool name_added = false;
1868 dir = read_one_inode(root, key->objectid);
1872 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
1876 log_flags = btrfs_dir_flags(eb, di);
1877 btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1878 ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1879 btrfs_release_path(path);
1882 exists = (ret == 0);
1885 dir_dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1887 if (IS_ERR(dir_dst_di)) {
1888 ret = PTR_ERR(dir_dst_di);
1890 } else if (dir_dst_di) {
1891 ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1892 dir_dst_di, &log_key,
1896 dir_dst_matches = (ret == 1);
1899 btrfs_release_path(path);
1901 index_dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1902 key->objectid, key->offset,
1904 if (IS_ERR(index_dst_di)) {
1905 ret = PTR_ERR(index_dst_di);
1907 } else if (index_dst_di) {
1908 ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1909 index_dst_di, &log_key,
1913 index_dst_matches = (ret == 1);
1916 btrfs_release_path(path);
1918 if (dir_dst_matches && index_dst_matches) {
1920 update_size = false;
1925 * Check if the inode reference exists in the log for the given name,
1926 * inode and parent inode
1928 search_key.objectid = log_key.objectid;
1929 search_key.type = BTRFS_INODE_REF_KEY;
1930 search_key.offset = key->objectid;
1931 ret = backref_in_log(root->log_root, &search_key, 0, &name);
1935 /* The dentry will be added later. */
1937 update_size = false;
1941 search_key.objectid = log_key.objectid;
1942 search_key.type = BTRFS_INODE_EXTREF_KEY;
1943 search_key.offset = key->objectid;
1944 ret = backref_in_log(root->log_root, &search_key, key->objectid, &name);
1948 /* The dentry will be added later. */
1950 update_size = false;
1953 btrfs_release_path(path);
1954 ret = insert_one_name(trans, root, key->objectid, key->offset,
1956 if (ret && ret != -ENOENT && ret != -EEXIST)
1960 update_size = false;
1964 if (!ret && update_size) {
1965 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name.len * 2);
1966 ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
1970 if (!ret && name_added)
1975 /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
1976 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1977 struct btrfs_root *root,
1978 struct btrfs_path *path,
1979 struct extent_buffer *eb, int slot,
1980 struct btrfs_key *key)
1983 struct btrfs_dir_item *di;
1985 /* We only log dir index keys, which only contain a single dir item. */
1986 ASSERT(key->type == BTRFS_DIR_INDEX_KEY);
1988 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1989 ret = replay_one_name(trans, root, path, eb, di, key);
1994 * If this entry refers to a non-directory (directories can not have a
1995 * link count > 1) and it was added in the transaction that was not
1996 * committed, make sure we fixup the link count of the inode the entry
1997 * points to. Otherwise something like the following would result in a
1998 * directory pointing to an inode with a wrong link that does not account
1999 * for this dir entry:
2006 * ln testdir/bar testdir/bar_link
2007 * ln testdir/foo testdir/foo_link
2008 * xfs_io -c "fsync" testdir/bar
2012 * mount fs, log replay happens
2014 * File foo would remain with a link count of 1 when it has two entries
2015 * pointing to it in the directory testdir. This would make it impossible
2016 * to ever delete the parent directory has it would result in stale
2017 * dentries that can never be deleted.
2019 if (ret == 1 && btrfs_dir_ftype(eb, di) != BTRFS_FT_DIR) {
2020 struct btrfs_path *fixup_path;
2021 struct btrfs_key di_key;
2023 fixup_path = btrfs_alloc_path();
2027 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2028 ret = link_to_fixup_dir(trans, root, fixup_path, di_key.objectid);
2029 btrfs_free_path(fixup_path);
2036 * directory replay has two parts. There are the standard directory
2037 * items in the log copied from the subvolume, and range items
2038 * created in the log while the subvolume was logged.
2040 * The range items tell us which parts of the key space the log
2041 * is authoritative for. During replay, if a key in the subvolume
2042 * directory is in a logged range item, but not actually in the log
2043 * that means it was deleted from the directory before the fsync
2044 * and should be removed.
2046 static noinline int find_dir_range(struct btrfs_root *root,
2047 struct btrfs_path *path,
2049 u64 *start_ret, u64 *end_ret)
2051 struct btrfs_key key;
2053 struct btrfs_dir_log_item *item;
2057 if (*start_ret == (u64)-1)
2060 key.objectid = dirid;
2061 key.type = BTRFS_DIR_LOG_INDEX_KEY;
2062 key.offset = *start_ret;
2064 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2068 if (path->slots[0] == 0)
2073 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2075 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2079 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2080 struct btrfs_dir_log_item);
2081 found_end = btrfs_dir_log_end(path->nodes[0], item);
2083 if (*start_ret >= key.offset && *start_ret <= found_end) {
2085 *start_ret = key.offset;
2086 *end_ret = found_end;
2091 /* check the next slot in the tree to see if it is a valid item */
2092 nritems = btrfs_header_nritems(path->nodes[0]);
2094 if (path->slots[0] >= nritems) {
2095 ret = btrfs_next_leaf(root, path);
2100 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2102 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2106 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2107 struct btrfs_dir_log_item);
2108 found_end = btrfs_dir_log_end(path->nodes[0], item);
2109 *start_ret = key.offset;
2110 *end_ret = found_end;
2113 btrfs_release_path(path);
2118 * this looks for a given directory item in the log. If the directory
2119 * item is not in the log, the item is removed and the inode it points
2122 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2123 struct btrfs_root *log,
2124 struct btrfs_path *path,
2125 struct btrfs_path *log_path,
2127 struct btrfs_key *dir_key)
2129 struct btrfs_root *root = BTRFS_I(dir)->root;
2131 struct extent_buffer *eb;
2133 struct btrfs_dir_item *di;
2134 struct fscrypt_str name;
2135 struct inode *inode = NULL;
2136 struct btrfs_key location;
2139 * Currently we only log dir index keys. Even if we replay a log created
2140 * by an older kernel that logged both dir index and dir item keys, all
2141 * we need to do is process the dir index keys, we (and our caller) can
2142 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2144 ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY);
2146 eb = path->nodes[0];
2147 slot = path->slots[0];
2148 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2149 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
2154 struct btrfs_dir_item *log_di;
2156 log_di = btrfs_lookup_dir_index_item(trans, log, log_path,
2158 dir_key->offset, &name, 0);
2159 if (IS_ERR(log_di)) {
2160 ret = PTR_ERR(log_di);
2162 } else if (log_di) {
2163 /* The dentry exists in the log, we have nothing to do. */
2169 btrfs_dir_item_key_to_cpu(eb, di, &location);
2170 btrfs_release_path(path);
2171 btrfs_release_path(log_path);
2172 inode = read_one_inode(root, location.objectid);
2178 ret = link_to_fixup_dir(trans, root, path, location.objectid);
2183 ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir), BTRFS_I(inode),
2186 * Unlike dir item keys, dir index keys can only have one name (entry) in
2187 * them, as there are no key collisions since each key has a unique offset
2188 * (an index number), so we're done.
2191 btrfs_release_path(path);
2192 btrfs_release_path(log_path);
2198 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2199 struct btrfs_root *root,
2200 struct btrfs_root *log,
2201 struct btrfs_path *path,
2204 struct btrfs_key search_key;
2205 struct btrfs_path *log_path;
2210 log_path = btrfs_alloc_path();
2214 search_key.objectid = ino;
2215 search_key.type = BTRFS_XATTR_ITEM_KEY;
2216 search_key.offset = 0;
2218 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2222 nritems = btrfs_header_nritems(path->nodes[0]);
2223 for (i = path->slots[0]; i < nritems; i++) {
2224 struct btrfs_key key;
2225 struct btrfs_dir_item *di;
2226 struct btrfs_dir_item *log_di;
2230 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2231 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2236 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2237 total_size = btrfs_item_size(path->nodes[0], i);
2239 while (cur < total_size) {
2240 u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2241 u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2242 u32 this_len = sizeof(*di) + name_len + data_len;
2245 name = kmalloc(name_len, GFP_NOFS);
2250 read_extent_buffer(path->nodes[0], name,
2251 (unsigned long)(di + 1), name_len);
2253 log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2255 btrfs_release_path(log_path);
2257 /* Doesn't exist in log tree, so delete it. */
2258 btrfs_release_path(path);
2259 di = btrfs_lookup_xattr(trans, root, path, ino,
2260 name, name_len, -1);
2267 ret = btrfs_delete_one_dir_name(trans, root,
2271 btrfs_release_path(path);
2276 if (IS_ERR(log_di)) {
2277 ret = PTR_ERR(log_di);
2281 di = (struct btrfs_dir_item *)((char *)di + this_len);
2284 ret = btrfs_next_leaf(root, path);
2290 btrfs_free_path(log_path);
2291 btrfs_release_path(path);
2297 * deletion replay happens before we copy any new directory items
2298 * out of the log or out of backreferences from inodes. It
2299 * scans the log to find ranges of keys that log is authoritative for,
2300 * and then scans the directory to find items in those ranges that are
2301 * not present in the log.
2303 * Anything we don't find in the log is unlinked and removed from the
2306 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2307 struct btrfs_root *root,
2308 struct btrfs_root *log,
2309 struct btrfs_path *path,
2310 u64 dirid, int del_all)
2315 struct btrfs_key dir_key;
2316 struct btrfs_key found_key;
2317 struct btrfs_path *log_path;
2320 dir_key.objectid = dirid;
2321 dir_key.type = BTRFS_DIR_INDEX_KEY;
2322 log_path = btrfs_alloc_path();
2326 dir = read_one_inode(root, dirid);
2327 /* it isn't an error if the inode isn't there, that can happen
2328 * because we replay the deletes before we copy in the inode item
2332 btrfs_free_path(log_path);
2340 range_end = (u64)-1;
2342 ret = find_dir_range(log, path, dirid,
2343 &range_start, &range_end);
2350 dir_key.offset = range_start;
2353 ret = btrfs_search_slot(NULL, root, &dir_key, path,
2358 nritems = btrfs_header_nritems(path->nodes[0]);
2359 if (path->slots[0] >= nritems) {
2360 ret = btrfs_next_leaf(root, path);
2366 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2368 if (found_key.objectid != dirid ||
2369 found_key.type != dir_key.type) {
2374 if (found_key.offset > range_end)
2377 ret = check_item_in_log(trans, log, path,
2382 if (found_key.offset == (u64)-1)
2384 dir_key.offset = found_key.offset + 1;
2386 btrfs_release_path(path);
2387 if (range_end == (u64)-1)
2389 range_start = range_end + 1;
2393 btrfs_release_path(path);
2394 btrfs_free_path(log_path);
2400 * the process_func used to replay items from the log tree. This
2401 * gets called in two different stages. The first stage just looks
2402 * for inodes and makes sure they are all copied into the subvolume.
2404 * The second stage copies all the other item types from the log into
2405 * the subvolume. The two stage approach is slower, but gets rid of
2406 * lots of complexity around inodes referencing other inodes that exist
2407 * only in the log (references come from either directory items or inode
2410 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2411 struct walk_control *wc, u64 gen, int level)
2414 struct btrfs_path *path;
2415 struct btrfs_root *root = wc->replay_dest;
2416 struct btrfs_key key;
2420 ret = btrfs_read_extent_buffer(eb, gen, level, NULL);
2424 level = btrfs_header_level(eb);
2429 path = btrfs_alloc_path();
2433 nritems = btrfs_header_nritems(eb);
2434 for (i = 0; i < nritems; i++) {
2435 btrfs_item_key_to_cpu(eb, &key, i);
2437 /* inode keys are done during the first stage */
2438 if (key.type == BTRFS_INODE_ITEM_KEY &&
2439 wc->stage == LOG_WALK_REPLAY_INODES) {
2440 struct btrfs_inode_item *inode_item;
2443 inode_item = btrfs_item_ptr(eb, i,
2444 struct btrfs_inode_item);
2446 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2447 * and never got linked before the fsync, skip it, as
2448 * replaying it is pointless since it would be deleted
2449 * later. We skip logging tmpfiles, but it's always
2450 * possible we are replaying a log created with a kernel
2451 * that used to log tmpfiles.
2453 if (btrfs_inode_nlink(eb, inode_item) == 0) {
2454 wc->ignore_cur_inode = true;
2457 wc->ignore_cur_inode = false;
2459 ret = replay_xattr_deletes(wc->trans, root, log,
2460 path, key.objectid);
2463 mode = btrfs_inode_mode(eb, inode_item);
2464 if (S_ISDIR(mode)) {
2465 ret = replay_dir_deletes(wc->trans,
2466 root, log, path, key.objectid, 0);
2470 ret = overwrite_item(wc->trans, root, path,
2476 * Before replaying extents, truncate the inode to its
2477 * size. We need to do it now and not after log replay
2478 * because before an fsync we can have prealloc extents
2479 * added beyond the inode's i_size. If we did it after,
2480 * through orphan cleanup for example, we would drop
2481 * those prealloc extents just after replaying them.
2483 if (S_ISREG(mode)) {
2484 struct btrfs_drop_extents_args drop_args = { 0 };
2485 struct inode *inode;
2488 inode = read_one_inode(root, key.objectid);
2493 from = ALIGN(i_size_read(inode),
2494 root->fs_info->sectorsize);
2495 drop_args.start = from;
2496 drop_args.end = (u64)-1;
2497 drop_args.drop_cache = true;
2498 ret = btrfs_drop_extents(wc->trans, root,
2502 inode_sub_bytes(inode,
2503 drop_args.bytes_found);
2504 /* Update the inode's nbytes. */
2505 ret = btrfs_update_inode(wc->trans,
2506 root, BTRFS_I(inode));
2513 ret = link_to_fixup_dir(wc->trans, root,
2514 path, key.objectid);
2519 if (wc->ignore_cur_inode)
2522 if (key.type == BTRFS_DIR_INDEX_KEY &&
2523 wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2524 ret = replay_one_dir_item(wc->trans, root, path,
2530 if (wc->stage < LOG_WALK_REPLAY_ALL)
2533 /* these keys are simply copied */
2534 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2535 ret = overwrite_item(wc->trans, root, path,
2539 } else if (key.type == BTRFS_INODE_REF_KEY ||
2540 key.type == BTRFS_INODE_EXTREF_KEY) {
2541 ret = add_inode_ref(wc->trans, root, log, path,
2543 if (ret && ret != -ENOENT)
2546 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2547 ret = replay_one_extent(wc->trans, root, path,
2553 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2554 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2555 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2556 * older kernel with such keys, ignore them.
2559 btrfs_free_path(path);
2564 * Correctly adjust the reserved bytes occupied by a log tree extent buffer
2566 static void unaccount_log_buffer(struct btrfs_fs_info *fs_info, u64 start)
2568 struct btrfs_block_group *cache;
2570 cache = btrfs_lookup_block_group(fs_info, start);
2572 btrfs_err(fs_info, "unable to find block group for %llu", start);
2576 spin_lock(&cache->space_info->lock);
2577 spin_lock(&cache->lock);
2578 cache->reserved -= fs_info->nodesize;
2579 cache->space_info->bytes_reserved -= fs_info->nodesize;
2580 spin_unlock(&cache->lock);
2581 spin_unlock(&cache->space_info->lock);
2583 btrfs_put_block_group(cache);
2586 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2587 struct btrfs_root *root,
2588 struct btrfs_path *path, int *level,
2589 struct walk_control *wc)
2591 struct btrfs_fs_info *fs_info = root->fs_info;
2594 struct extent_buffer *next;
2595 struct extent_buffer *cur;
2599 while (*level > 0) {
2600 struct btrfs_key first_key;
2602 cur = path->nodes[*level];
2604 WARN_ON(btrfs_header_level(cur) != *level);
2606 if (path->slots[*level] >=
2607 btrfs_header_nritems(cur))
2610 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2611 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2612 btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2613 blocksize = fs_info->nodesize;
2615 next = btrfs_find_create_tree_block(fs_info, bytenr,
2616 btrfs_header_owner(cur),
2619 return PTR_ERR(next);
2622 ret = wc->process_func(root, next, wc, ptr_gen,
2625 free_extent_buffer(next);
2629 path->slots[*level]++;
2631 ret = btrfs_read_extent_buffer(next, ptr_gen,
2632 *level - 1, &first_key);
2634 free_extent_buffer(next);
2639 btrfs_tree_lock(next);
2640 btrfs_clean_tree_block(next);
2641 btrfs_wait_tree_block_writeback(next);
2642 btrfs_tree_unlock(next);
2643 ret = btrfs_pin_reserved_extent(trans,
2646 free_extent_buffer(next);
2649 btrfs_redirty_list_add(
2650 trans->transaction, next);
2652 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2653 clear_extent_buffer_dirty(next);
2654 unaccount_log_buffer(fs_info, bytenr);
2657 free_extent_buffer(next);
2660 ret = btrfs_read_extent_buffer(next, ptr_gen, *level - 1, &first_key);
2662 free_extent_buffer(next);
2666 if (path->nodes[*level-1])
2667 free_extent_buffer(path->nodes[*level-1]);
2668 path->nodes[*level-1] = next;
2669 *level = btrfs_header_level(next);
2670 path->slots[*level] = 0;
2673 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2679 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2680 struct btrfs_root *root,
2681 struct btrfs_path *path, int *level,
2682 struct walk_control *wc)
2684 struct btrfs_fs_info *fs_info = root->fs_info;
2689 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2690 slot = path->slots[i];
2691 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2694 WARN_ON(*level == 0);
2697 ret = wc->process_func(root, path->nodes[*level], wc,
2698 btrfs_header_generation(path->nodes[*level]),
2704 struct extent_buffer *next;
2706 next = path->nodes[*level];
2709 btrfs_tree_lock(next);
2710 btrfs_clean_tree_block(next);
2711 btrfs_wait_tree_block_writeback(next);
2712 btrfs_tree_unlock(next);
2713 ret = btrfs_pin_reserved_extent(trans,
2714 path->nodes[*level]->start,
2715 path->nodes[*level]->len);
2718 btrfs_redirty_list_add(trans->transaction,
2721 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2722 clear_extent_buffer_dirty(next);
2724 unaccount_log_buffer(fs_info,
2725 path->nodes[*level]->start);
2728 free_extent_buffer(path->nodes[*level]);
2729 path->nodes[*level] = NULL;
2737 * drop the reference count on the tree rooted at 'snap'. This traverses
2738 * the tree freeing any blocks that have a ref count of zero after being
2741 static int walk_log_tree(struct btrfs_trans_handle *trans,
2742 struct btrfs_root *log, struct walk_control *wc)
2744 struct btrfs_fs_info *fs_info = log->fs_info;
2748 struct btrfs_path *path;
2751 path = btrfs_alloc_path();
2755 level = btrfs_header_level(log->node);
2757 path->nodes[level] = log->node;
2758 atomic_inc(&log->node->refs);
2759 path->slots[level] = 0;
2762 wret = walk_down_log_tree(trans, log, path, &level, wc);
2770 wret = walk_up_log_tree(trans, log, path, &level, wc);
2779 /* was the root node processed? if not, catch it here */
2780 if (path->nodes[orig_level]) {
2781 ret = wc->process_func(log, path->nodes[orig_level], wc,
2782 btrfs_header_generation(path->nodes[orig_level]),
2787 struct extent_buffer *next;
2789 next = path->nodes[orig_level];
2792 btrfs_tree_lock(next);
2793 btrfs_clean_tree_block(next);
2794 btrfs_wait_tree_block_writeback(next);
2795 btrfs_tree_unlock(next);
2796 ret = btrfs_pin_reserved_extent(trans,
2797 next->start, next->len);
2800 btrfs_redirty_list_add(trans->transaction, next);
2802 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2803 clear_extent_buffer_dirty(next);
2804 unaccount_log_buffer(fs_info, next->start);
2810 btrfs_free_path(path);
2815 * helper function to update the item for a given subvolumes log root
2816 * in the tree of log roots
2818 static int update_log_root(struct btrfs_trans_handle *trans,
2819 struct btrfs_root *log,
2820 struct btrfs_root_item *root_item)
2822 struct btrfs_fs_info *fs_info = log->fs_info;
2825 if (log->log_transid == 1) {
2826 /* insert root item on the first sync */
2827 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2828 &log->root_key, root_item);
2830 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2831 &log->root_key, root_item);
2836 static void wait_log_commit(struct btrfs_root *root, int transid)
2839 int index = transid % 2;
2842 * we only allow two pending log transactions at a time,
2843 * so we know that if ours is more than 2 older than the
2844 * current transaction, we're done
2847 prepare_to_wait(&root->log_commit_wait[index],
2848 &wait, TASK_UNINTERRUPTIBLE);
2850 if (!(root->log_transid_committed < transid &&
2851 atomic_read(&root->log_commit[index])))
2854 mutex_unlock(&root->log_mutex);
2856 mutex_lock(&root->log_mutex);
2858 finish_wait(&root->log_commit_wait[index], &wait);
2861 static void wait_for_writer(struct btrfs_root *root)
2866 prepare_to_wait(&root->log_writer_wait, &wait,
2867 TASK_UNINTERRUPTIBLE);
2868 if (!atomic_read(&root->log_writers))
2871 mutex_unlock(&root->log_mutex);
2873 mutex_lock(&root->log_mutex);
2875 finish_wait(&root->log_writer_wait, &wait);
2878 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2879 struct btrfs_log_ctx *ctx)
2881 mutex_lock(&root->log_mutex);
2882 list_del_init(&ctx->list);
2883 mutex_unlock(&root->log_mutex);
2887 * Invoked in log mutex context, or be sure there is no other task which
2888 * can access the list.
2890 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2891 int index, int error)
2893 struct btrfs_log_ctx *ctx;
2894 struct btrfs_log_ctx *safe;
2896 list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2897 list_del_init(&ctx->list);
2898 ctx->log_ret = error;
2903 * btrfs_sync_log does sends a given tree log down to the disk and
2904 * updates the super blocks to record it. When this call is done,
2905 * you know that any inodes previously logged are safely on disk only
2908 * Any other return value means you need to call btrfs_commit_transaction.
2909 * Some of the edge cases for fsyncing directories that have had unlinks
2910 * or renames done in the past mean that sometimes the only safe
2911 * fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
2912 * that has happened.
2914 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2915 struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2921 struct btrfs_fs_info *fs_info = root->fs_info;
2922 struct btrfs_root *log = root->log_root;
2923 struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2924 struct btrfs_root_item new_root_item;
2925 int log_transid = 0;
2926 struct btrfs_log_ctx root_log_ctx;
2927 struct blk_plug plug;
2931 mutex_lock(&root->log_mutex);
2932 log_transid = ctx->log_transid;
2933 if (root->log_transid_committed >= log_transid) {
2934 mutex_unlock(&root->log_mutex);
2935 return ctx->log_ret;
2938 index1 = log_transid % 2;
2939 if (atomic_read(&root->log_commit[index1])) {
2940 wait_log_commit(root, log_transid);
2941 mutex_unlock(&root->log_mutex);
2942 return ctx->log_ret;
2944 ASSERT(log_transid == root->log_transid);
2945 atomic_set(&root->log_commit[index1], 1);
2947 /* wait for previous tree log sync to complete */
2948 if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2949 wait_log_commit(root, log_transid - 1);
2952 int batch = atomic_read(&root->log_batch);
2953 /* when we're on an ssd, just kick the log commit out */
2954 if (!btrfs_test_opt(fs_info, SSD) &&
2955 test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
2956 mutex_unlock(&root->log_mutex);
2957 schedule_timeout_uninterruptible(1);
2958 mutex_lock(&root->log_mutex);
2960 wait_for_writer(root);
2961 if (batch == atomic_read(&root->log_batch))
2965 /* bail out if we need to do a full commit */
2966 if (btrfs_need_log_full_commit(trans)) {
2967 ret = BTRFS_LOG_FORCE_COMMIT;
2968 mutex_unlock(&root->log_mutex);
2972 if (log_transid % 2 == 0)
2973 mark = EXTENT_DIRTY;
2977 /* we start IO on all the marked extents here, but we don't actually
2978 * wait for them until later.
2980 blk_start_plug(&plug);
2981 ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2983 * -EAGAIN happens when someone, e.g., a concurrent transaction
2984 * commit, writes a dirty extent in this tree-log commit. This
2985 * concurrent write will create a hole writing out the extents,
2986 * and we cannot proceed on a zoned filesystem, requiring
2987 * sequential writing. While we can bail out to a full commit
2988 * here, but we can continue hoping the concurrent writing fills
2991 if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
2994 blk_finish_plug(&plug);
2995 btrfs_abort_transaction(trans, ret);
2996 btrfs_set_log_full_commit(trans);
2997 mutex_unlock(&root->log_mutex);
3002 * We _must_ update under the root->log_mutex in order to make sure we
3003 * have a consistent view of the log root we are trying to commit at
3006 * We _must_ copy this into a local copy, because we are not holding the
3007 * log_root_tree->log_mutex yet. This is important because when we
3008 * commit the log_root_tree we must have a consistent view of the
3009 * log_root_tree when we update the super block to point at the
3010 * log_root_tree bytenr. If we update the log_root_tree here we'll race
3011 * with the commit and possibly point at the new block which we may not
3014 btrfs_set_root_node(&log->root_item, log->node);
3015 memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3017 root->log_transid++;
3018 log->log_transid = root->log_transid;
3019 root->log_start_pid = 0;
3021 * IO has been started, blocks of the log tree have WRITTEN flag set
3022 * in their headers. new modifications of the log will be written to
3023 * new positions. so it's safe to allow log writers to go in.
3025 mutex_unlock(&root->log_mutex);
3027 if (btrfs_is_zoned(fs_info)) {
3028 mutex_lock(&fs_info->tree_root->log_mutex);
3029 if (!log_root_tree->node) {
3030 ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
3032 mutex_unlock(&fs_info->tree_root->log_mutex);
3033 blk_finish_plug(&plug);
3037 mutex_unlock(&fs_info->tree_root->log_mutex);
3040 btrfs_init_log_ctx(&root_log_ctx, NULL);
3042 mutex_lock(&log_root_tree->log_mutex);
3044 index2 = log_root_tree->log_transid % 2;
3045 list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3046 root_log_ctx.log_transid = log_root_tree->log_transid;
3049 * Now we are safe to update the log_root_tree because we're under the
3050 * log_mutex, and we're a current writer so we're holding the commit
3051 * open until we drop the log_mutex.
3053 ret = update_log_root(trans, log, &new_root_item);
3055 if (!list_empty(&root_log_ctx.list))
3056 list_del_init(&root_log_ctx.list);
3058 blk_finish_plug(&plug);
3059 btrfs_set_log_full_commit(trans);
3061 if (ret != -ENOSPC) {
3062 btrfs_abort_transaction(trans, ret);
3063 mutex_unlock(&log_root_tree->log_mutex);
3066 btrfs_wait_tree_log_extents(log, mark);
3067 mutex_unlock(&log_root_tree->log_mutex);
3068 ret = BTRFS_LOG_FORCE_COMMIT;
3072 if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3073 blk_finish_plug(&plug);
3074 list_del_init(&root_log_ctx.list);
3075 mutex_unlock(&log_root_tree->log_mutex);
3076 ret = root_log_ctx.log_ret;
3080 index2 = root_log_ctx.log_transid % 2;
3081 if (atomic_read(&log_root_tree->log_commit[index2])) {
3082 blk_finish_plug(&plug);
3083 ret = btrfs_wait_tree_log_extents(log, mark);
3084 wait_log_commit(log_root_tree,
3085 root_log_ctx.log_transid);
3086 mutex_unlock(&log_root_tree->log_mutex);
3088 ret = root_log_ctx.log_ret;
3091 ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
3092 atomic_set(&log_root_tree->log_commit[index2], 1);
3094 if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3095 wait_log_commit(log_root_tree,
3096 root_log_ctx.log_transid - 1);
3100 * now that we've moved on to the tree of log tree roots,
3101 * check the full commit flag again
3103 if (btrfs_need_log_full_commit(trans)) {
3104 blk_finish_plug(&plug);
3105 btrfs_wait_tree_log_extents(log, mark);
3106 mutex_unlock(&log_root_tree->log_mutex);
3107 ret = BTRFS_LOG_FORCE_COMMIT;
3108 goto out_wake_log_root;
3111 ret = btrfs_write_marked_extents(fs_info,
3112 &log_root_tree->dirty_log_pages,
3113 EXTENT_DIRTY | EXTENT_NEW);
3114 blk_finish_plug(&plug);
3116 * As described above, -EAGAIN indicates a hole in the extents. We
3117 * cannot wait for these write outs since the waiting cause a
3118 * deadlock. Bail out to the full commit instead.
3120 if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3121 btrfs_set_log_full_commit(trans);
3122 btrfs_wait_tree_log_extents(log, mark);
3123 mutex_unlock(&log_root_tree->log_mutex);
3124 goto out_wake_log_root;
3126 btrfs_set_log_full_commit(trans);
3127 btrfs_abort_transaction(trans, ret);
3128 mutex_unlock(&log_root_tree->log_mutex);
3129 goto out_wake_log_root;
3131 ret = btrfs_wait_tree_log_extents(log, mark);
3133 ret = btrfs_wait_tree_log_extents(log_root_tree,
3134 EXTENT_NEW | EXTENT_DIRTY);
3136 btrfs_set_log_full_commit(trans);
3137 mutex_unlock(&log_root_tree->log_mutex);
3138 goto out_wake_log_root;
3141 log_root_start = log_root_tree->node->start;
3142 log_root_level = btrfs_header_level(log_root_tree->node);
3143 log_root_tree->log_transid++;
3144 mutex_unlock(&log_root_tree->log_mutex);
3147 * Here we are guaranteed that nobody is going to write the superblock
3148 * for the current transaction before us and that neither we do write
3149 * our superblock before the previous transaction finishes its commit
3150 * and writes its superblock, because:
3152 * 1) We are holding a handle on the current transaction, so no body
3153 * can commit it until we release the handle;
3155 * 2) Before writing our superblock we acquire the tree_log_mutex, so
3156 * if the previous transaction is still committing, and hasn't yet
3157 * written its superblock, we wait for it to do it, because a
3158 * transaction commit acquires the tree_log_mutex when the commit
3159 * begins and releases it only after writing its superblock.
3161 mutex_lock(&fs_info->tree_log_mutex);
3164 * The previous transaction writeout phase could have failed, and thus
3165 * marked the fs in an error state. We must not commit here, as we
3166 * could have updated our generation in the super_for_commit and
3167 * writing the super here would result in transid mismatches. If there
3168 * is an error here just bail.
3170 if (BTRFS_FS_ERROR(fs_info)) {
3172 btrfs_set_log_full_commit(trans);
3173 btrfs_abort_transaction(trans, ret);
3174 mutex_unlock(&fs_info->tree_log_mutex);
3175 goto out_wake_log_root;
3178 btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
3179 btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3180 ret = write_all_supers(fs_info, 1);
3181 mutex_unlock(&fs_info->tree_log_mutex);
3183 btrfs_set_log_full_commit(trans);
3184 btrfs_abort_transaction(trans, ret);
3185 goto out_wake_log_root;
3189 * We know there can only be one task here, since we have not yet set
3190 * root->log_commit[index1] to 0 and any task attempting to sync the
3191 * log must wait for the previous log transaction to commit if it's
3192 * still in progress or wait for the current log transaction commit if
3193 * someone else already started it. We use <= and not < because the
3194 * first log transaction has an ID of 0.
3196 ASSERT(root->last_log_commit <= log_transid);
3197 root->last_log_commit = log_transid;
3200 mutex_lock(&log_root_tree->log_mutex);
3201 btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3203 log_root_tree->log_transid_committed++;
3204 atomic_set(&log_root_tree->log_commit[index2], 0);
3205 mutex_unlock(&log_root_tree->log_mutex);
3208 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3209 * all the updates above are seen by the woken threads. It might not be
3210 * necessary, but proving that seems to be hard.
3212 cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3214 mutex_lock(&root->log_mutex);
3215 btrfs_remove_all_log_ctxs(root, index1, ret);
3216 root->log_transid_committed++;
3217 atomic_set(&root->log_commit[index1], 0);
3218 mutex_unlock(&root->log_mutex);
3221 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3222 * all the updates above are seen by the woken threads. It might not be
3223 * necessary, but proving that seems to be hard.
3225 cond_wake_up(&root->log_commit_wait[index1]);
3229 static void free_log_tree(struct btrfs_trans_handle *trans,
3230 struct btrfs_root *log)
3233 struct walk_control wc = {
3235 .process_func = process_one_buffer
3239 ret = walk_log_tree(trans, log, &wc);
3242 * We weren't able to traverse the entire log tree, the
3243 * typical scenario is getting an -EIO when reading an
3244 * extent buffer of the tree, due to a previous writeback
3247 set_bit(BTRFS_FS_STATE_LOG_CLEANUP_ERROR,
3248 &log->fs_info->fs_state);
3251 * Some extent buffers of the log tree may still be dirty
3252 * and not yet written back to storage, because we may
3253 * have updates to a log tree without syncing a log tree,
3254 * such as during rename and link operations. So flush
3255 * them out and wait for their writeback to complete, so
3256 * that we properly cleanup their state and pages.
3258 btrfs_write_marked_extents(log->fs_info,
3259 &log->dirty_log_pages,
3260 EXTENT_DIRTY | EXTENT_NEW);
3261 btrfs_wait_tree_log_extents(log,
3262 EXTENT_DIRTY | EXTENT_NEW);
3265 btrfs_abort_transaction(trans, ret);
3267 btrfs_handle_fs_error(log->fs_info, ret, NULL);
3271 clear_extent_bits(&log->dirty_log_pages, 0, (u64)-1,
3272 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3273 extent_io_tree_release(&log->log_csum_range);
3275 btrfs_put_root(log);
3279 * free all the extents used by the tree log. This should be called
3280 * at commit time of the full transaction
3282 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3284 if (root->log_root) {
3285 free_log_tree(trans, root->log_root);
3286 root->log_root = NULL;
3287 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
3292 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3293 struct btrfs_fs_info *fs_info)
3295 if (fs_info->log_root_tree) {
3296 free_log_tree(trans, fs_info->log_root_tree);
3297 fs_info->log_root_tree = NULL;
3298 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
3304 * Check if an inode was logged in the current transaction. This correctly deals
3305 * with the case where the inode was logged but has a logged_trans of 0, which
3306 * happens if the inode is evicted and loaded again, as logged_trans is an in
3307 * memory only field (not persisted).
3309 * Returns 1 if the inode was logged before in the transaction, 0 if it was not,
3312 static int inode_logged(struct btrfs_trans_handle *trans,
3313 struct btrfs_inode *inode,
3314 struct btrfs_path *path_in)
3316 struct btrfs_path *path = path_in;
3317 struct btrfs_key key;
3320 if (inode->logged_trans == trans->transid)
3324 * If logged_trans is not 0, then we know the inode logged was not logged
3325 * in this transaction, so we can return false right away.
3327 if (inode->logged_trans > 0)
3331 * If no log tree was created for this root in this transaction, then
3332 * the inode can not have been logged in this transaction. In that case
3333 * set logged_trans to anything greater than 0 and less than the current
3334 * transaction's ID, to avoid the search below in a future call in case
3335 * a log tree gets created after this.
3337 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state)) {
3338 inode->logged_trans = trans->transid - 1;
3343 * We have a log tree and the inode's logged_trans is 0. We can't tell
3344 * for sure if the inode was logged before in this transaction by looking
3345 * only at logged_trans. We could be pessimistic and assume it was, but
3346 * that can lead to unnecessarily logging an inode during rename and link
3347 * operations, and then further updating the log in followup rename and
3348 * link operations, specially if it's a directory, which adds latency
3349 * visible to applications doing a series of rename or link operations.
3351 * A logged_trans of 0 here can mean several things:
3353 * 1) The inode was never logged since the filesystem was mounted, and may
3354 * or may have not been evicted and loaded again;
3356 * 2) The inode was logged in a previous transaction, then evicted and
3357 * then loaded again;
3359 * 3) The inode was logged in the current transaction, then evicted and
3360 * then loaded again.
3362 * For cases 1) and 2) we don't want to return true, but we need to detect
3363 * case 3) and return true. So we do a search in the log root for the inode
3366 key.objectid = btrfs_ino(inode);
3367 key.type = BTRFS_INODE_ITEM_KEY;
3371 path = btrfs_alloc_path();
3376 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3379 btrfs_release_path(path);
3381 btrfs_free_path(path);
3384 * Logging an inode always results in logging its inode item. So if we
3385 * did not find the item we know the inode was not logged for sure.
3389 } else if (ret > 0) {
3391 * Set logged_trans to a value greater than 0 and less then the
3392 * current transaction to avoid doing the search in future calls.
3394 inode->logged_trans = trans->transid - 1;
3399 * The inode was previously logged and then evicted, set logged_trans to
3400 * the current transacion's ID, to avoid future tree searches as long as
3401 * the inode is not evicted again.
3403 inode->logged_trans = trans->transid;
3406 * If it's a directory, then we must set last_dir_index_offset to the
3407 * maximum possible value, so that the next attempt to log the inode does
3408 * not skip checking if dir index keys found in modified subvolume tree
3409 * leaves have been logged before, otherwise it would result in attempts
3410 * to insert duplicate dir index keys in the log tree. This must be done
3411 * because last_dir_index_offset is an in-memory only field, not persisted
3412 * in the inode item or any other on-disk structure, so its value is lost
3413 * once the inode is evicted.
3415 if (S_ISDIR(inode->vfs_inode.i_mode))
3416 inode->last_dir_index_offset = (u64)-1;
3422 * Delete a directory entry from the log if it exists.
3424 * Returns < 0 on error
3425 * 1 if the entry does not exists
3426 * 0 if the entry existed and was successfully deleted
3428 static int del_logged_dentry(struct btrfs_trans_handle *trans,
3429 struct btrfs_root *log,
3430 struct btrfs_path *path,
3432 const struct fscrypt_str *name,
3435 struct btrfs_dir_item *di;
3438 * We only log dir index items of a directory, so we don't need to look
3439 * for dir item keys.
3441 di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3449 * We do not need to update the size field of the directory's
3450 * inode item because on log replay we update the field to reflect
3451 * all existing entries in the directory (see overwrite_item()).
3453 return btrfs_delete_one_dir_name(trans, log, path, di);
3457 * If both a file and directory are logged, and unlinks or renames are
3458 * mixed in, we have a few interesting corners:
3460 * create file X in dir Y
3461 * link file X to X.link in dir Y
3463 * unlink file X but leave X.link
3466 * After a crash we would expect only X.link to exist. But file X
3467 * didn't get fsync'd again so the log has back refs for X and X.link.
3469 * We solve this by removing directory entries and inode backrefs from the
3470 * log when a file that was logged in the current transaction is
3471 * unlinked. Any later fsync will include the updated log entries, and
3472 * we'll be able to reconstruct the proper directory items from backrefs.
3474 * This optimizations allows us to avoid relogging the entire inode
3475 * or the entire directory.
3477 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3478 struct btrfs_root *root,
3479 const struct fscrypt_str *name,
3480 struct btrfs_inode *dir, u64 index)
3482 struct btrfs_path *path;
3485 ret = inode_logged(trans, dir, NULL);
3489 btrfs_set_log_full_commit(trans);
3493 ret = join_running_log_trans(root);
3497 mutex_lock(&dir->log_mutex);
3499 path = btrfs_alloc_path();
3505 ret = del_logged_dentry(trans, root->log_root, path, btrfs_ino(dir),
3507 btrfs_free_path(path);
3509 mutex_unlock(&dir->log_mutex);
3511 btrfs_set_log_full_commit(trans);
3512 btrfs_end_log_trans(root);
3515 /* see comments for btrfs_del_dir_entries_in_log */
3516 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3517 struct btrfs_root *root,
3518 const struct fscrypt_str *name,
3519 struct btrfs_inode *inode, u64 dirid)
3521 struct btrfs_root *log;
3525 ret = inode_logged(trans, inode, NULL);
3529 btrfs_set_log_full_commit(trans);
3533 ret = join_running_log_trans(root);
3536 log = root->log_root;
3537 mutex_lock(&inode->log_mutex);
3539 ret = btrfs_del_inode_ref(trans, log, name, btrfs_ino(inode),
3541 mutex_unlock(&inode->log_mutex);
3542 if (ret < 0 && ret != -ENOENT)
3543 btrfs_set_log_full_commit(trans);
3544 btrfs_end_log_trans(root);
3548 * creates a range item in the log for 'dirid'. first_offset and
3549 * last_offset tell us which parts of the key space the log should
3550 * be considered authoritative for.
3552 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3553 struct btrfs_root *log,
3554 struct btrfs_path *path,
3556 u64 first_offset, u64 last_offset)
3559 struct btrfs_key key;
3560 struct btrfs_dir_log_item *item;
3562 key.objectid = dirid;
3563 key.offset = first_offset;
3564 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3565 ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3567 * -EEXIST is fine and can happen sporadically when we are logging a
3568 * directory and have concurrent insertions in the subvolume's tree for
3569 * items from other inodes and that result in pushing off some dir items
3570 * from one leaf to another in order to accommodate for the new items.
3571 * This results in logging the same dir index range key.
3573 if (ret && ret != -EEXIST)
3576 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3577 struct btrfs_dir_log_item);
3578 if (ret == -EEXIST) {
3579 const u64 curr_end = btrfs_dir_log_end(path->nodes[0], item);
3582 * btrfs_del_dir_entries_in_log() might have been called during
3583 * an unlink between the initial insertion of this key and the
3584 * current update, or we might be logging a single entry deletion
3585 * during a rename, so set the new last_offset to the max value.
3587 last_offset = max(last_offset, curr_end);
3589 btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3590 btrfs_mark_buffer_dirty(path->nodes[0]);
3591 btrfs_release_path(path);
3595 static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
3596 struct btrfs_root *log,
3597 struct extent_buffer *src,
3598 struct btrfs_path *dst_path,
3602 char *ins_data = NULL;
3603 struct btrfs_item_batch batch;
3604 struct extent_buffer *dst;
3605 unsigned long src_offset;
3606 unsigned long dst_offset;
3607 struct btrfs_key key;
3616 btrfs_item_key_to_cpu(src, &key, start_slot);
3617 item_size = btrfs_item_size(src, start_slot);
3619 batch.data_sizes = &item_size;
3620 batch.total_data_size = item_size;
3622 struct btrfs_key *ins_keys;
3625 ins_data = kmalloc(count * sizeof(u32) +
3626 count * sizeof(struct btrfs_key), GFP_NOFS);
3630 ins_sizes = (u32 *)ins_data;
3631 ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
3632 batch.keys = ins_keys;
3633 batch.data_sizes = ins_sizes;
3634 batch.total_data_size = 0;
3636 for (i = 0; i < count; i++) {
3637 const int slot = start_slot + i;
3639 btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
3640 ins_sizes[i] = btrfs_item_size(src, slot);
3641 batch.total_data_size += ins_sizes[i];
3645 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
3649 dst = dst_path->nodes[0];
3651 * Copy all the items in bulk, in a single copy operation. Item data is
3652 * organized such that it's placed at the end of a leaf and from right
3653 * to left. For example, the data for the second item ends at an offset
3654 * that matches the offset where the data for the first item starts, the
3655 * data for the third item ends at an offset that matches the offset
3656 * where the data of the second items starts, and so on.
3657 * Therefore our source and destination start offsets for copy match the
3658 * offsets of the last items (highest slots).
3660 dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
3661 src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
3662 copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
3663 btrfs_release_path(dst_path);
3670 static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
3671 struct btrfs_inode *inode,
3672 struct btrfs_path *path,
3673 struct btrfs_path *dst_path,
3674 struct btrfs_log_ctx *ctx,
3675 u64 *last_old_dentry_offset)
3677 struct btrfs_root *log = inode->root->log_root;
3678 struct extent_buffer *src;
3679 const int nritems = btrfs_header_nritems(path->nodes[0]);
3680 const u64 ino = btrfs_ino(inode);
3681 bool last_found = false;
3682 int batch_start = 0;
3687 * We need to clone the leaf, release the read lock on it, and use the
3688 * clone before modifying the log tree. See the comment at copy_items()
3689 * about why we need to do this.
3691 src = btrfs_clone_extent_buffer(path->nodes[0]);
3696 btrfs_release_path(path);
3697 path->nodes[0] = src;
3700 for (; i < nritems; i++) {
3701 struct btrfs_dir_item *di;
3702 struct btrfs_key key;
3705 btrfs_item_key_to_cpu(src, &key, i);
3707 if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
3712 di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3713 ctx->last_dir_item_offset = key.offset;
3716 * Skip ranges of items that consist only of dir item keys created
3717 * in past transactions. However if we find a gap, we must log a
3718 * dir index range item for that gap, so that index keys in that
3719 * gap are deleted during log replay.
3721 if (btrfs_dir_transid(src, di) < trans->transid) {
3722 if (key.offset > *last_old_dentry_offset + 1) {
3723 ret = insert_dir_log_key(trans, log, dst_path,
3724 ino, *last_old_dentry_offset + 1,
3730 *last_old_dentry_offset = key.offset;
3734 /* If we logged this dir index item before, we can skip it. */
3735 if (key.offset <= inode->last_dir_index_offset)
3739 * We must make sure that when we log a directory entry, the
3740 * corresponding inode, after log replay, has a matching link
3741 * count. For example:
3747 * xfs_io -c "fsync" mydir
3749 * <mount fs and log replay>
3751 * Would result in a fsync log that when replayed, our file inode
3752 * would have a link count of 1, but we get two directory entries
3753 * pointing to the same inode. After removing one of the names,
3754 * it would not be possible to remove the other name, which
3755 * resulted always in stale file handle errors, and would not be
3756 * possible to rmdir the parent directory, since its i_size could
3757 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
3758 * resulting in -ENOTEMPTY errors.
3760 if (!ctx->log_new_dentries) {
3761 struct btrfs_key di_key;
3763 btrfs_dir_item_key_to_cpu(src, di, &di_key);
3764 if (di_key.type != BTRFS_ROOT_ITEM_KEY)
3765 ctx->log_new_dentries = true;
3768 if (batch_size == 0)
3773 if (batch_size > 0) {
3776 ret = flush_dir_items_batch(trans, log, src, dst_path,
3777 batch_start, batch_size);
3782 return last_found ? 1 : 0;
3786 * log all the items included in the current transaction for a given
3787 * directory. This also creates the range items in the log tree required
3788 * to replay anything deleted before the fsync
3790 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3791 struct btrfs_inode *inode,
3792 struct btrfs_path *path,
3793 struct btrfs_path *dst_path,
3794 struct btrfs_log_ctx *ctx,
3795 u64 min_offset, u64 *last_offset_ret)
3797 struct btrfs_key min_key;
3798 struct btrfs_root *root = inode->root;
3799 struct btrfs_root *log = root->log_root;
3802 u64 last_old_dentry_offset = min_offset - 1;
3803 u64 last_offset = (u64)-1;
3804 u64 ino = btrfs_ino(inode);
3806 min_key.objectid = ino;
3807 min_key.type = BTRFS_DIR_INDEX_KEY;
3808 min_key.offset = min_offset;
3810 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3813 * we didn't find anything from this transaction, see if there
3814 * is anything at all
3816 if (ret != 0 || min_key.objectid != ino ||
3817 min_key.type != BTRFS_DIR_INDEX_KEY) {
3818 min_key.objectid = ino;
3819 min_key.type = BTRFS_DIR_INDEX_KEY;
3820 min_key.offset = (u64)-1;
3821 btrfs_release_path(path);
3822 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3824 btrfs_release_path(path);
3827 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3829 /* if ret == 0 there are items for this type,
3830 * create a range to tell us the last key of this type.
3831 * otherwise, there are no items in this directory after
3832 * *min_offset, and we create a range to indicate that.
3835 struct btrfs_key tmp;
3837 btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3839 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3840 last_old_dentry_offset = tmp.offset;
3845 /* go backward to find any previous key */
3846 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3848 struct btrfs_key tmp;
3850 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3852 * The dir index key before the first one we found that needs to
3853 * be logged might be in a previous leaf, and there might be a
3854 * gap between these keys, meaning that we had deletions that
3855 * happened. So the key range item we log (key type
3856 * BTRFS_DIR_LOG_INDEX_KEY) must cover a range that starts at the
3857 * previous key's offset plus 1, so that those deletes are replayed.
3859 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3860 last_old_dentry_offset = tmp.offset;
3862 btrfs_release_path(path);
3865 * Find the first key from this transaction again. See the note for
3866 * log_new_dir_dentries, if we're logging a directory recursively we
3867 * won't be holding its i_mutex, which means we can modify the directory
3868 * while we're logging it. If we remove an entry between our first
3869 * search and this search we'll not find the key again and can just
3873 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3878 * we have a block from this transaction, log every item in it
3879 * from our directory
3882 ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx,
3883 &last_old_dentry_offset);
3889 path->slots[0] = btrfs_header_nritems(path->nodes[0]);
3892 * look ahead to the next item and see if it is also
3893 * from this directory and from this transaction
3895 ret = btrfs_next_leaf(root, path);
3898 last_offset = (u64)-1;
3903 btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
3904 if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
3905 last_offset = (u64)-1;
3908 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3910 * The next leaf was not changed in the current transaction
3911 * and has at least one dir index key.
3912 * We check for the next key because there might have been
3913 * one or more deletions between the last key we logged and
3914 * that next key. So the key range item we log (key type
3915 * BTRFS_DIR_LOG_INDEX_KEY) must end at the next key's
3916 * offset minus 1, so that those deletes are replayed.
3918 last_offset = min_key.offset - 1;
3921 if (need_resched()) {
3922 btrfs_release_path(path);
3928 btrfs_release_path(path);
3929 btrfs_release_path(dst_path);
3932 *last_offset_ret = last_offset;
3934 * In case the leaf was changed in the current transaction but
3935 * all its dir items are from a past transaction, the last item
3936 * in the leaf is a dir item and there's no gap between that last
3937 * dir item and the first one on the next leaf (which did not
3938 * change in the current transaction), then we don't need to log
3939 * a range, last_old_dentry_offset is == to last_offset.
3941 ASSERT(last_old_dentry_offset <= last_offset);
3942 if (last_old_dentry_offset < last_offset) {
3943 ret = insert_dir_log_key(trans, log, path, ino,
3944 last_old_dentry_offset + 1,
3954 * If the inode was logged before and it was evicted, then its
3955 * last_dir_index_offset is (u64)-1, so we don't the value of the last index
3956 * key offset. If that's the case, search for it and update the inode. This
3957 * is to avoid lookups in the log tree every time we try to insert a dir index
3958 * key from a leaf changed in the current transaction, and to allow us to always
3959 * do batch insertions of dir index keys.
3961 static int update_last_dir_index_offset(struct btrfs_inode *inode,
3962 struct btrfs_path *path,
3963 const struct btrfs_log_ctx *ctx)
3965 const u64 ino = btrfs_ino(inode);
3966 struct btrfs_key key;
3969 lockdep_assert_held(&inode->log_mutex);
3971 if (inode->last_dir_index_offset != (u64)-1)
3974 if (!ctx->logged_before) {
3975 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
3980 key.type = BTRFS_DIR_INDEX_KEY;
3981 key.offset = (u64)-1;
3983 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3985 * An error happened or we actually have an index key with an offset
3986 * value of (u64)-1. Bail out, we're done.
3992 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
3995 * No dir index items, bail out and leave last_dir_index_offset with
3996 * the value right before the first valid index value.
3998 if (path->slots[0] == 0)
4002 * btrfs_search_slot() left us at one slot beyond the slot with the last
4003 * index key, or beyond the last key of the directory that is not an
4004 * index key. If we have an index key before, set last_dir_index_offset
4005 * to its offset value, otherwise leave it with a value right before the
4006 * first valid index value, as it means we have an empty directory.
4008 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
4009 if (key.objectid == ino && key.type == BTRFS_DIR_INDEX_KEY)
4010 inode->last_dir_index_offset = key.offset;
4013 btrfs_release_path(path);
4019 * logging directories is very similar to logging inodes, We find all the items
4020 * from the current transaction and write them to the log.
4022 * The recovery code scans the directory in the subvolume, and if it finds a
4023 * key in the range logged that is not present in the log tree, then it means
4024 * that dir entry was unlinked during the transaction.
4026 * In order for that scan to work, we must include one key smaller than
4027 * the smallest logged by this transaction and one key larger than the largest
4028 * key logged by this transaction.
4030 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
4031 struct btrfs_inode *inode,
4032 struct btrfs_path *path,
4033 struct btrfs_path *dst_path,
4034 struct btrfs_log_ctx *ctx)
4040 ret = update_last_dir_index_offset(inode, path, ctx);
4044 min_key = BTRFS_DIR_START_INDEX;
4046 ctx->last_dir_item_offset = inode->last_dir_index_offset;
4049 ret = log_dir_items(trans, inode, path, dst_path,
4050 ctx, min_key, &max_key);
4053 if (max_key == (u64)-1)
4055 min_key = max_key + 1;
4058 inode->last_dir_index_offset = ctx->last_dir_item_offset;
4064 * a helper function to drop items from the log before we relog an
4065 * inode. max_key_type indicates the highest item type to remove.
4066 * This cannot be run for file data extents because it does not
4067 * free the extents they point to.
4069 static int drop_inode_items(struct btrfs_trans_handle *trans,
4070 struct btrfs_root *log,
4071 struct btrfs_path *path,
4072 struct btrfs_inode *inode,
4076 struct btrfs_key key;
4077 struct btrfs_key found_key;
4080 key.objectid = btrfs_ino(inode);
4081 key.type = max_key_type;
4082 key.offset = (u64)-1;
4085 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
4086 BUG_ON(ret == 0); /* Logic error */
4090 if (path->slots[0] == 0)
4094 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4097 if (found_key.objectid != key.objectid)
4100 found_key.offset = 0;
4102 ret = btrfs_bin_search(path->nodes[0], &found_key, &start_slot);
4106 ret = btrfs_del_items(trans, log, path, start_slot,
4107 path->slots[0] - start_slot + 1);
4109 * If start slot isn't 0 then we don't need to re-search, we've
4110 * found the last guy with the objectid in this tree.
4112 if (ret || start_slot != 0)
4114 btrfs_release_path(path);
4116 btrfs_release_path(path);
4122 static int truncate_inode_items(struct btrfs_trans_handle *trans,
4123 struct btrfs_root *log_root,
4124 struct btrfs_inode *inode,
4125 u64 new_size, u32 min_type)
4127 struct btrfs_truncate_control control = {
4128 .new_size = new_size,
4129 .ino = btrfs_ino(inode),
4130 .min_type = min_type,
4131 .skip_ref_updates = true,
4134 return btrfs_truncate_inode_items(trans, log_root, &control);
4137 static void fill_inode_item(struct btrfs_trans_handle *trans,
4138 struct extent_buffer *leaf,
4139 struct btrfs_inode_item *item,
4140 struct inode *inode, int log_inode_only,
4143 struct btrfs_map_token token;
4146 btrfs_init_map_token(&token, leaf);
4148 if (log_inode_only) {
4149 /* set the generation to zero so the recover code
4150 * can tell the difference between an logging
4151 * just to say 'this inode exists' and a logging
4152 * to say 'update this inode with these values'
4154 btrfs_set_token_inode_generation(&token, item, 0);
4155 btrfs_set_token_inode_size(&token, item, logged_isize);
4157 btrfs_set_token_inode_generation(&token, item,
4158 BTRFS_I(inode)->generation);
4159 btrfs_set_token_inode_size(&token, item, inode->i_size);
4162 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4163 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4164 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4165 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4167 btrfs_set_token_timespec_sec(&token, &item->atime,
4168 inode->i_atime.tv_sec);
4169 btrfs_set_token_timespec_nsec(&token, &item->atime,
4170 inode->i_atime.tv_nsec);
4172 btrfs_set_token_timespec_sec(&token, &item->mtime,
4173 inode->i_mtime.tv_sec);
4174 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4175 inode->i_mtime.tv_nsec);
4177 btrfs_set_token_timespec_sec(&token, &item->ctime,
4178 inode->i_ctime.tv_sec);
4179 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4180 inode->i_ctime.tv_nsec);
4183 * We do not need to set the nbytes field, in fact during a fast fsync
4184 * its value may not even be correct, since a fast fsync does not wait
4185 * for ordered extent completion, which is where we update nbytes, it
4186 * only waits for writeback to complete. During log replay as we find
4187 * file extent items and replay them, we adjust the nbytes field of the
4188 * inode item in subvolume tree as needed (see overwrite_item()).
4191 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4192 btrfs_set_token_inode_transid(&token, item, trans->transid);
4193 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4194 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4195 BTRFS_I(inode)->ro_flags);
4196 btrfs_set_token_inode_flags(&token, item, flags);
4197 btrfs_set_token_inode_block_group(&token, item, 0);
4200 static int log_inode_item(struct btrfs_trans_handle *trans,
4201 struct btrfs_root *log, struct btrfs_path *path,
4202 struct btrfs_inode *inode, bool inode_item_dropped)
4204 struct btrfs_inode_item *inode_item;
4208 * If we are doing a fast fsync and the inode was logged before in the
4209 * current transaction, then we know the inode was previously logged and
4210 * it exists in the log tree. For performance reasons, in this case use
4211 * btrfs_search_slot() directly with ins_len set to 0 so that we never
4212 * attempt a write lock on the leaf's parent, which adds unnecessary lock
4213 * contention in case there are concurrent fsyncs for other inodes of the
4214 * same subvolume. Using btrfs_insert_empty_item() when the inode item
4215 * already exists can also result in unnecessarily splitting a leaf.
4217 if (!inode_item_dropped && inode->logged_trans == trans->transid) {
4218 ret = btrfs_search_slot(trans, log, &inode->location, path, 0, 1);
4224 * This means it is the first fsync in the current transaction,
4225 * so the inode item is not in the log and we need to insert it.
4226 * We can never get -EEXIST because we are only called for a fast
4227 * fsync and in case an inode eviction happens after the inode was
4228 * logged before in the current transaction, when we load again
4229 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
4230 * flags and set ->logged_trans to 0.
4232 ret = btrfs_insert_empty_item(trans, log, path, &inode->location,
4233 sizeof(*inode_item));
4234 ASSERT(ret != -EEXIST);
4238 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4239 struct btrfs_inode_item);
4240 fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
4242 btrfs_release_path(path);
4246 static int log_csums(struct btrfs_trans_handle *trans,
4247 struct btrfs_inode *inode,
4248 struct btrfs_root *log_root,
4249 struct btrfs_ordered_sum *sums)
4251 const u64 lock_end = sums->bytenr + sums->len - 1;
4252 struct extent_state *cached_state = NULL;
4256 * If this inode was not used for reflink operations in the current
4257 * transaction with new extents, then do the fast path, no need to
4258 * worry about logging checksum items with overlapping ranges.
4260 if (inode->last_reflink_trans < trans->transid)
4261 return btrfs_csum_file_blocks(trans, log_root, sums);
4264 * Serialize logging for checksums. This is to avoid racing with the
4265 * same checksum being logged by another task that is logging another
4266 * file which happens to refer to the same extent as well. Such races
4267 * can leave checksum items in the log with overlapping ranges.
4269 ret = lock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4274 * Due to extent cloning, we might have logged a csum item that covers a
4275 * subrange of a cloned extent, and later we can end up logging a csum
4276 * item for a larger subrange of the same extent or the entire range.
4277 * This would leave csum items in the log tree that cover the same range
4278 * and break the searches for checksums in the log tree, resulting in
4279 * some checksums missing in the fs/subvolume tree. So just delete (or
4280 * trim and adjust) any existing csum items in the log for this range.
4282 ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
4284 ret = btrfs_csum_file_blocks(trans, log_root, sums);
4286 unlock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4292 static noinline int copy_items(struct btrfs_trans_handle *trans,
4293 struct btrfs_inode *inode,
4294 struct btrfs_path *dst_path,
4295 struct btrfs_path *src_path,
4296 int start_slot, int nr, int inode_only,
4299 struct btrfs_root *log = inode->root->log_root;
4300 struct btrfs_file_extent_item *extent;
4301 struct extent_buffer *src;
4303 struct btrfs_key *ins_keys;
4305 struct btrfs_item_batch batch;
4309 const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
4310 const u64 i_size = i_size_read(&inode->vfs_inode);
4313 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4314 * use the clone. This is because otherwise we would be changing the log
4315 * tree, to insert items from the subvolume tree or insert csum items,
4316 * while holding a read lock on a leaf from the subvolume tree, which
4317 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4319 * 1) Modifying the log tree triggers an extent buffer allocation while
4320 * holding a write lock on a parent extent buffer from the log tree.
4321 * Allocating the pages for an extent buffer, or the extent buffer
4322 * struct, can trigger inode eviction and finally the inode eviction
4323 * will trigger a release/remove of a delayed node, which requires
4324 * taking the delayed node's mutex;
4326 * 2) Allocating a metadata extent for a log tree can trigger the async
4327 * reclaim thread and make us wait for it to release enough space and
4328 * unblock our reservation ticket. The reclaim thread can start
4329 * flushing delayed items, and that in turn results in the need to
4330 * lock delayed node mutexes and in the need to write lock extent
4331 * buffers of a subvolume tree - all this while holding a write lock
4332 * on the parent extent buffer in the log tree.
4334 * So one task in scenario 1) running in parallel with another task in
4335 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4336 * node mutex while having a read lock on a leaf from the subvolume,
4337 * while the other is holding the delayed node's mutex and wants to
4338 * write lock the same subvolume leaf for flushing delayed items.
4340 src = btrfs_clone_extent_buffer(src_path->nodes[0]);
4344 i = src_path->slots[0];
4345 btrfs_release_path(src_path);
4346 src_path->nodes[0] = src;
4347 src_path->slots[0] = i;
4349 ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
4350 nr * sizeof(u32), GFP_NOFS);
4354 ins_sizes = (u32 *)ins_data;
4355 ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4356 batch.keys = ins_keys;
4357 batch.data_sizes = ins_sizes;
4358 batch.total_data_size = 0;
4362 for (i = 0; i < nr; i++) {
4363 const int src_slot = start_slot + i;
4364 struct btrfs_root *csum_root;
4365 struct btrfs_ordered_sum *sums;
4366 struct btrfs_ordered_sum *sums_next;
4367 LIST_HEAD(ordered_sums);
4371 u64 extent_num_bytes;
4374 btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
4376 if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
4379 extent = btrfs_item_ptr(src, src_slot,
4380 struct btrfs_file_extent_item);
4382 is_old_extent = (btrfs_file_extent_generation(src, extent) <
4386 * Don't copy extents from past generations. That would make us
4387 * log a lot more metadata for common cases like doing only a
4388 * few random writes into a file and then fsync it for the first
4389 * time or after the full sync flag is set on the inode. We can
4390 * get leaves full of extent items, most of which are from past
4391 * generations, so we can skip them - as long as the inode has
4392 * not been the target of a reflink operation in this transaction,
4393 * as in that case it might have had file extent items with old
4394 * generations copied into it. We also must always log prealloc
4395 * extents that start at or beyond eof, otherwise we would lose
4396 * them on log replay.
4398 if (is_old_extent &&
4399 ins_keys[dst_index].offset < i_size &&
4400 inode->last_reflink_trans < trans->transid)
4406 /* Only regular extents have checksums. */
4407 if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
4411 * If it's an extent created in a past transaction, then its
4412 * checksums are already accessible from the committed csum tree,
4413 * no need to log them.
4418 disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
4419 /* If it's an explicit hole, there are no checksums. */
4420 if (disk_bytenr == 0)
4423 disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
4425 if (btrfs_file_extent_compression(src, extent)) {
4427 extent_num_bytes = disk_num_bytes;
4429 extent_offset = btrfs_file_extent_offset(src, extent);
4430 extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
4433 csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
4434 disk_bytenr += extent_offset;
4435 ret = btrfs_lookup_csums_range(csum_root, disk_bytenr,
4436 disk_bytenr + extent_num_bytes - 1,
4437 &ordered_sums, 0, false);
4441 list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
4443 ret = log_csums(trans, inode, log, sums);
4444 list_del(&sums->list);
4451 ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
4452 batch.total_data_size += ins_sizes[dst_index];
4458 * We have a leaf full of old extent items that don't need to be logged,
4459 * so we don't need to do anything.
4464 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4469 for (i = 0; i < nr; i++) {
4470 const int src_slot = start_slot + i;
4471 const int dst_slot = dst_path->slots[0] + dst_index;
4472 struct btrfs_key key;
4473 unsigned long src_offset;
4474 unsigned long dst_offset;
4477 * We're done, all the remaining items in the source leaf
4478 * correspond to old file extent items.
4480 if (dst_index >= batch.nr)
4483 btrfs_item_key_to_cpu(src, &key, src_slot);
4485 if (key.type != BTRFS_EXTENT_DATA_KEY)
4488 extent = btrfs_item_ptr(src, src_slot,
4489 struct btrfs_file_extent_item);
4491 /* See the comment in the previous loop, same logic. */
4492 if (btrfs_file_extent_generation(src, extent) < trans->transid &&
4493 key.offset < i_size &&
4494 inode->last_reflink_trans < trans->transid)
4498 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
4499 src_offset = btrfs_item_ptr_offset(src, src_slot);
4501 if (key.type == BTRFS_INODE_ITEM_KEY) {
4502 struct btrfs_inode_item *inode_item;
4504 inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
4505 struct btrfs_inode_item);
4506 fill_inode_item(trans, dst_path->nodes[0], inode_item,
4508 inode_only == LOG_INODE_EXISTS,
4511 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4512 src_offset, ins_sizes[dst_index]);
4518 btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4519 btrfs_release_path(dst_path);
4526 static int extent_cmp(void *priv, const struct list_head *a,
4527 const struct list_head *b)
4529 const struct extent_map *em1, *em2;
4531 em1 = list_entry(a, struct extent_map, list);
4532 em2 = list_entry(b, struct extent_map, list);
4534 if (em1->start < em2->start)
4536 else if (em1->start > em2->start)
4541 static int log_extent_csums(struct btrfs_trans_handle *trans,
4542 struct btrfs_inode *inode,
4543 struct btrfs_root *log_root,
4544 const struct extent_map *em,
4545 struct btrfs_log_ctx *ctx)
4547 struct btrfs_ordered_extent *ordered;
4548 struct btrfs_root *csum_root;
4551 u64 mod_start = em->mod_start;
4552 u64 mod_len = em->mod_len;
4553 LIST_HEAD(ordered_sums);
4556 if (inode->flags & BTRFS_INODE_NODATASUM ||
4557 test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
4558 em->block_start == EXTENT_MAP_HOLE)
4561 list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
4562 const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
4563 const u64 mod_end = mod_start + mod_len;
4564 struct btrfs_ordered_sum *sums;
4569 if (ordered_end <= mod_start)
4571 if (mod_end <= ordered->file_offset)
4575 * We are going to copy all the csums on this ordered extent, so
4576 * go ahead and adjust mod_start and mod_len in case this ordered
4577 * extent has already been logged.
4579 if (ordered->file_offset > mod_start) {
4580 if (ordered_end >= mod_end)
4581 mod_len = ordered->file_offset - mod_start;
4583 * If we have this case
4585 * |--------- logged extent ---------|
4586 * |----- ordered extent ----|
4588 * Just don't mess with mod_start and mod_len, we'll
4589 * just end up logging more csums than we need and it
4593 if (ordered_end < mod_end) {
4594 mod_len = mod_end - ordered_end;
4595 mod_start = ordered_end;
4602 * To keep us from looping for the above case of an ordered
4603 * extent that falls inside of the logged extent.
4605 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
4608 list_for_each_entry(sums, &ordered->list, list) {
4609 ret = log_csums(trans, inode, log_root, sums);
4615 /* We're done, found all csums in the ordered extents. */
4619 /* If we're compressed we have to save the entire range of csums. */
4620 if (em->compress_type) {
4622 csum_len = max(em->block_len, em->orig_block_len);
4624 csum_offset = mod_start - em->start;
4628 /* block start is already adjusted for the file extent offset. */
4629 csum_root = btrfs_csum_root(trans->fs_info, em->block_start);
4630 ret = btrfs_lookup_csums_range(csum_root,
4631 em->block_start + csum_offset,
4632 em->block_start + csum_offset +
4633 csum_len - 1, &ordered_sums, 0, false);
4637 while (!list_empty(&ordered_sums)) {
4638 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4639 struct btrfs_ordered_sum,
4642 ret = log_csums(trans, inode, log_root, sums);
4643 list_del(&sums->list);
4650 static int log_one_extent(struct btrfs_trans_handle *trans,
4651 struct btrfs_inode *inode,
4652 const struct extent_map *em,
4653 struct btrfs_path *path,
4654 struct btrfs_log_ctx *ctx)
4656 struct btrfs_drop_extents_args drop_args = { 0 };
4657 struct btrfs_root *log = inode->root->log_root;
4658 struct btrfs_file_extent_item fi = { 0 };
4659 struct extent_buffer *leaf;
4660 struct btrfs_key key;
4661 u64 extent_offset = em->start - em->orig_start;
4665 btrfs_set_stack_file_extent_generation(&fi, trans->transid);
4666 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4667 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
4669 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
4671 block_len = max(em->block_len, em->orig_block_len);
4672 if (em->compress_type != BTRFS_COMPRESS_NONE) {
4673 btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start);
4674 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4675 } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4676 btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start -
4678 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4681 btrfs_set_stack_file_extent_offset(&fi, extent_offset);
4682 btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
4683 btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
4684 btrfs_set_stack_file_extent_compression(&fi, em->compress_type);
4686 ret = log_extent_csums(trans, inode, log, em, ctx);
4691 * If this is the first time we are logging the inode in the current
4692 * transaction, we can avoid btrfs_drop_extents(), which is expensive
4693 * because it does a deletion search, which always acquires write locks
4694 * for extent buffers at levels 2, 1 and 0. This not only wastes time
4695 * but also adds significant contention in a log tree, since log trees
4696 * are small, with a root at level 2 or 3 at most, due to their short
4699 if (ctx->logged_before) {
4700 drop_args.path = path;
4701 drop_args.start = em->start;
4702 drop_args.end = em->start + em->len;
4703 drop_args.replace_extent = true;
4704 drop_args.extent_item_size = sizeof(fi);
4705 ret = btrfs_drop_extents(trans, log, inode, &drop_args);
4710 if (!drop_args.extent_inserted) {
4711 key.objectid = btrfs_ino(inode);
4712 key.type = BTRFS_EXTENT_DATA_KEY;
4713 key.offset = em->start;
4715 ret = btrfs_insert_empty_item(trans, log, path, &key,
4720 leaf = path->nodes[0];
4721 write_extent_buffer(leaf, &fi,
4722 btrfs_item_ptr_offset(leaf, path->slots[0]),
4724 btrfs_mark_buffer_dirty(leaf);
4726 btrfs_release_path(path);
4732 * Log all prealloc extents beyond the inode's i_size to make sure we do not
4733 * lose them after doing a full/fast fsync and replaying the log. We scan the
4734 * subvolume's root instead of iterating the inode's extent map tree because
4735 * otherwise we can log incorrect extent items based on extent map conversion.
4736 * That can happen due to the fact that extent maps are merged when they
4737 * are not in the extent map tree's list of modified extents.
4739 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4740 struct btrfs_inode *inode,
4741 struct btrfs_path *path)
4743 struct btrfs_root *root = inode->root;
4744 struct btrfs_key key;
4745 const u64 i_size = i_size_read(&inode->vfs_inode);
4746 const u64 ino = btrfs_ino(inode);
4747 struct btrfs_path *dst_path = NULL;
4748 bool dropped_extents = false;
4749 u64 truncate_offset = i_size;
4750 struct extent_buffer *leaf;
4756 if (!(inode->flags & BTRFS_INODE_PREALLOC))
4760 key.type = BTRFS_EXTENT_DATA_KEY;
4761 key.offset = i_size;
4762 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4767 * We must check if there is a prealloc extent that starts before the
4768 * i_size and crosses the i_size boundary. This is to ensure later we
4769 * truncate down to the end of that extent and not to the i_size, as
4770 * otherwise we end up losing part of the prealloc extent after a log
4771 * replay and with an implicit hole if there is another prealloc extent
4772 * that starts at an offset beyond i_size.
4774 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4779 struct btrfs_file_extent_item *ei;
4781 leaf = path->nodes[0];
4782 slot = path->slots[0];
4783 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4785 if (btrfs_file_extent_type(leaf, ei) ==
4786 BTRFS_FILE_EXTENT_PREALLOC) {
4789 btrfs_item_key_to_cpu(leaf, &key, slot);
4790 extent_end = key.offset +
4791 btrfs_file_extent_num_bytes(leaf, ei);
4793 if (extent_end > i_size)
4794 truncate_offset = extent_end;
4801 leaf = path->nodes[0];
4802 slot = path->slots[0];
4804 if (slot >= btrfs_header_nritems(leaf)) {
4806 ret = copy_items(trans, inode, dst_path, path,
4807 start_slot, ins_nr, 1, 0);
4812 ret = btrfs_next_leaf(root, path);
4822 btrfs_item_key_to_cpu(leaf, &key, slot);
4823 if (key.objectid > ino)
4825 if (WARN_ON_ONCE(key.objectid < ino) ||
4826 key.type < BTRFS_EXTENT_DATA_KEY ||
4827 key.offset < i_size) {
4831 if (!dropped_extents) {
4833 * Avoid logging extent items logged in past fsync calls
4834 * and leading to duplicate keys in the log tree.
4836 ret = truncate_inode_items(trans, root->log_root, inode,
4838 BTRFS_EXTENT_DATA_KEY);
4841 dropped_extents = true;
4848 dst_path = btrfs_alloc_path();
4856 ret = copy_items(trans, inode, dst_path, path,
4857 start_slot, ins_nr, 1, 0);
4859 btrfs_release_path(path);
4860 btrfs_free_path(dst_path);
4864 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4865 struct btrfs_inode *inode,
4866 struct btrfs_path *path,
4867 struct btrfs_log_ctx *ctx)
4869 struct btrfs_ordered_extent *ordered;
4870 struct btrfs_ordered_extent *tmp;
4871 struct extent_map *em, *n;
4872 struct list_head extents;
4873 struct extent_map_tree *tree = &inode->extent_tree;
4877 INIT_LIST_HEAD(&extents);
4879 write_lock(&tree->lock);
4881 list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4882 list_del_init(&em->list);
4884 * Just an arbitrary number, this can be really CPU intensive
4885 * once we start getting a lot of extents, and really once we
4886 * have a bunch of extents we just want to commit since it will
4889 if (++num > 32768) {
4890 list_del_init(&tree->modified_extents);
4895 if (em->generation < trans->transid)
4898 /* We log prealloc extents beyond eof later. */
4899 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
4900 em->start >= i_size_read(&inode->vfs_inode))
4903 /* Need a ref to keep it from getting evicted from cache */
4904 refcount_inc(&em->refs);
4905 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
4906 list_add_tail(&em->list, &extents);
4910 list_sort(NULL, &extents, extent_cmp);
4912 while (!list_empty(&extents)) {
4913 em = list_entry(extents.next, struct extent_map, list);
4915 list_del_init(&em->list);
4918 * If we had an error we just need to delete everybody from our
4922 clear_em_logging(tree, em);
4923 free_extent_map(em);
4927 write_unlock(&tree->lock);
4929 ret = log_one_extent(trans, inode, em, path, ctx);
4930 write_lock(&tree->lock);
4931 clear_em_logging(tree, em);
4932 free_extent_map(em);
4934 WARN_ON(!list_empty(&extents));
4935 write_unlock(&tree->lock);
4938 ret = btrfs_log_prealloc_extents(trans, inode, path);
4943 * We have logged all extents successfully, now make sure the commit of
4944 * the current transaction waits for the ordered extents to complete
4945 * before it commits and wipes out the log trees, otherwise we would
4946 * lose data if an ordered extents completes after the transaction
4947 * commits and a power failure happens after the transaction commit.
4949 list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
4950 list_del_init(&ordered->log_list);
4951 set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
4953 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4954 spin_lock_irq(&inode->ordered_tree.lock);
4955 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4956 set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
4957 atomic_inc(&trans->transaction->pending_ordered);
4959 spin_unlock_irq(&inode->ordered_tree.lock);
4961 btrfs_put_ordered_extent(ordered);
4967 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
4968 struct btrfs_path *path, u64 *size_ret)
4970 struct btrfs_key key;
4973 key.objectid = btrfs_ino(inode);
4974 key.type = BTRFS_INODE_ITEM_KEY;
4977 ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4980 } else if (ret > 0) {
4983 struct btrfs_inode_item *item;
4985 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4986 struct btrfs_inode_item);
4987 *size_ret = btrfs_inode_size(path->nodes[0], item);
4989 * If the in-memory inode's i_size is smaller then the inode
4990 * size stored in the btree, return the inode's i_size, so
4991 * that we get a correct inode size after replaying the log
4992 * when before a power failure we had a shrinking truncate
4993 * followed by addition of a new name (rename / new hard link).
4994 * Otherwise return the inode size from the btree, to avoid
4995 * data loss when replaying a log due to previously doing a
4996 * write that expands the inode's size and logging a new name
4997 * immediately after.
4999 if (*size_ret > inode->vfs_inode.i_size)
5000 *size_ret = inode->vfs_inode.i_size;
5003 btrfs_release_path(path);
5008 * At the moment we always log all xattrs. This is to figure out at log replay
5009 * time which xattrs must have their deletion replayed. If a xattr is missing
5010 * in the log tree and exists in the fs/subvol tree, we delete it. This is
5011 * because if a xattr is deleted, the inode is fsynced and a power failure
5012 * happens, causing the log to be replayed the next time the fs is mounted,
5013 * we want the xattr to not exist anymore (same behaviour as other filesystems
5014 * with a journal, ext3/4, xfs, f2fs, etc).
5016 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
5017 struct btrfs_inode *inode,
5018 struct btrfs_path *path,
5019 struct btrfs_path *dst_path)
5021 struct btrfs_root *root = inode->root;
5023 struct btrfs_key key;
5024 const u64 ino = btrfs_ino(inode);
5027 bool found_xattrs = false;
5029 if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5033 key.type = BTRFS_XATTR_ITEM_KEY;
5036 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5041 int slot = path->slots[0];
5042 struct extent_buffer *leaf = path->nodes[0];
5043 int nritems = btrfs_header_nritems(leaf);
5045 if (slot >= nritems) {
5047 ret = copy_items(trans, inode, dst_path, path,
5048 start_slot, ins_nr, 1, 0);
5053 ret = btrfs_next_leaf(root, path);
5061 btrfs_item_key_to_cpu(leaf, &key, slot);
5062 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
5069 found_xattrs = true;
5073 ret = copy_items(trans, inode, dst_path, path,
5074 start_slot, ins_nr, 1, 0);
5080 set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5086 * When using the NO_HOLES feature if we punched a hole that causes the
5087 * deletion of entire leafs or all the extent items of the first leaf (the one
5088 * that contains the inode item and references) we may end up not processing
5089 * any extents, because there are no leafs with a generation matching the
5090 * current transaction that have extent items for our inode. So we need to find
5091 * if any holes exist and then log them. We also need to log holes after any
5092 * truncate operation that changes the inode's size.
5094 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5095 struct btrfs_inode *inode,
5096 struct btrfs_path *path)
5098 struct btrfs_root *root = inode->root;
5099 struct btrfs_fs_info *fs_info = root->fs_info;
5100 struct btrfs_key key;
5101 const u64 ino = btrfs_ino(inode);
5102 const u64 i_size = i_size_read(&inode->vfs_inode);
5103 u64 prev_extent_end = 0;
5106 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5110 key.type = BTRFS_EXTENT_DATA_KEY;
5113 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5118 struct extent_buffer *leaf = path->nodes[0];
5120 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5121 ret = btrfs_next_leaf(root, path);
5128 leaf = path->nodes[0];
5131 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5132 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
5135 /* We have a hole, log it. */
5136 if (prev_extent_end < key.offset) {
5137 const u64 hole_len = key.offset - prev_extent_end;
5140 * Release the path to avoid deadlocks with other code
5141 * paths that search the root while holding locks on
5142 * leafs from the log root.
5144 btrfs_release_path(path);
5145 ret = btrfs_insert_hole_extent(trans, root->log_root,
5146 ino, prev_extent_end,
5152 * Search for the same key again in the root. Since it's
5153 * an extent item and we are holding the inode lock, the
5154 * key must still exist. If it doesn't just emit warning
5155 * and return an error to fall back to a transaction
5158 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5161 if (WARN_ON(ret > 0))
5163 leaf = path->nodes[0];
5166 prev_extent_end = btrfs_file_extent_end(path);
5171 if (prev_extent_end < i_size) {
5174 btrfs_release_path(path);
5175 hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5176 ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5177 prev_extent_end, hole_len);
5186 * When we are logging a new inode X, check if it doesn't have a reference that
5187 * matches the reference from some other inode Y created in a past transaction
5188 * and that was renamed in the current transaction. If we don't do this, then at
5189 * log replay time we can lose inode Y (and all its files if it's a directory):
5192 * echo "hello world" > /mnt/x/foobar
5195 * mkdir /mnt/x # or touch /mnt/x
5196 * xfs_io -c fsync /mnt/x
5198 * mount fs, trigger log replay
5200 * After the log replay procedure, we would lose the first directory and all its
5201 * files (file foobar).
5202 * For the case where inode Y is not a directory we simply end up losing it:
5204 * echo "123" > /mnt/foo
5206 * mv /mnt/foo /mnt/bar
5207 * echo "abc" > /mnt/foo
5208 * xfs_io -c fsync /mnt/foo
5211 * We also need this for cases where a snapshot entry is replaced by some other
5212 * entry (file or directory) otherwise we end up with an unreplayable log due to
5213 * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
5214 * if it were a regular entry:
5217 * btrfs subvolume snapshot /mnt /mnt/x/snap
5218 * btrfs subvolume delete /mnt/x/snap
5221 * fsync /mnt/x or fsync some new file inside it
5224 * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
5225 * the same transaction.
5227 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
5229 const struct btrfs_key *key,
5230 struct btrfs_inode *inode,
5231 u64 *other_ino, u64 *other_parent)
5234 struct btrfs_path *search_path;
5237 u32 item_size = btrfs_item_size(eb, slot);
5239 unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
5241 search_path = btrfs_alloc_path();
5244 search_path->search_commit_root = 1;
5245 search_path->skip_locking = 1;
5247 while (cur_offset < item_size) {
5251 unsigned long name_ptr;
5252 struct btrfs_dir_item *di;
5253 struct fscrypt_str name_str;
5255 if (key->type == BTRFS_INODE_REF_KEY) {
5256 struct btrfs_inode_ref *iref;
5258 iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
5259 parent = key->offset;
5260 this_name_len = btrfs_inode_ref_name_len(eb, iref);
5261 name_ptr = (unsigned long)(iref + 1);
5262 this_len = sizeof(*iref) + this_name_len;
5264 struct btrfs_inode_extref *extref;
5266 extref = (struct btrfs_inode_extref *)(ptr +
5268 parent = btrfs_inode_extref_parent(eb, extref);
5269 this_name_len = btrfs_inode_extref_name_len(eb, extref);
5270 name_ptr = (unsigned long)&extref->name;
5271 this_len = sizeof(*extref) + this_name_len;
5274 if (this_name_len > name_len) {
5277 new_name = krealloc(name, this_name_len, GFP_NOFS);
5282 name_len = this_name_len;
5286 read_extent_buffer(eb, name, name_ptr, this_name_len);
5288 name_str.name = name;
5289 name_str.len = this_name_len;
5290 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5291 parent, &name_str, 0);
5292 if (di && !IS_ERR(di)) {
5293 struct btrfs_key di_key;
5295 btrfs_dir_item_key_to_cpu(search_path->nodes[0],
5297 if (di_key.type == BTRFS_INODE_ITEM_KEY) {
5298 if (di_key.objectid != key->objectid) {
5300 *other_ino = di_key.objectid;
5301 *other_parent = parent;
5309 } else if (IS_ERR(di)) {
5313 btrfs_release_path(search_path);
5315 cur_offset += this_len;
5319 btrfs_free_path(search_path);
5325 * Check if we need to log an inode. This is used in contexts where while
5326 * logging an inode we need to log another inode (either that it exists or in
5327 * full mode). This is used instead of btrfs_inode_in_log() because the later
5328 * requires the inode to be in the log and have the log transaction committed,
5329 * while here we do not care if the log transaction was already committed - our
5330 * caller will commit the log later - and we want to avoid logging an inode
5331 * multiple times when multiple tasks have joined the same log transaction.
5333 static bool need_log_inode(const struct btrfs_trans_handle *trans,
5334 const struct btrfs_inode *inode)
5337 * If a directory was not modified, no dentries added or removed, we can
5338 * and should avoid logging it.
5340 if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5344 * If this inode does not have new/updated/deleted xattrs since the last
5345 * time it was logged and is flagged as logged in the current transaction,
5346 * we can skip logging it. As for new/deleted names, those are updated in
5347 * the log by link/unlink/rename operations.
5348 * In case the inode was logged and then evicted and reloaded, its
5349 * logged_trans will be 0, in which case we have to fully log it since
5350 * logged_trans is a transient field, not persisted.
5352 if (inode->logged_trans == trans->transid &&
5353 !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5359 struct btrfs_dir_list {
5361 struct list_head list;
5365 * Log the inodes of the new dentries of a directory.
5366 * See process_dir_items_leaf() for details about why it is needed.
5367 * This is a recursive operation - if an existing dentry corresponds to a
5368 * directory, that directory's new entries are logged too (same behaviour as
5369 * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5370 * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5371 * complains about the following circular lock dependency / possible deadlock:
5375 * lock(&type->i_mutex_dir_key#3/2);
5376 * lock(sb_internal#2);
5377 * lock(&type->i_mutex_dir_key#3/2);
5378 * lock(&sb->s_type->i_mutex_key#14);
5380 * Where sb_internal is the lock (a counter that works as a lock) acquired by
5381 * sb_start_intwrite() in btrfs_start_transaction().
5382 * Not acquiring the VFS lock of the inodes is still safe because:
5384 * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5385 * that while logging the inode new references (names) are added or removed
5386 * from the inode, leaving the logged inode item with a link count that does
5387 * not match the number of logged inode reference items. This is fine because
5388 * at log replay time we compute the real number of links and correct the
5389 * link count in the inode item (see replay_one_buffer() and
5390 * link_to_fixup_dir());
5392 * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5393 * while logging the inode's items new index items (key type
5394 * BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5395 * has a size that doesn't match the sum of the lengths of all the logged
5396 * names - this is ok, not a problem, because at log replay time we set the
5397 * directory's i_size to the correct value (see replay_one_name() and
5398 * do_overwrite_item()).
5400 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5401 struct btrfs_inode *start_inode,
5402 struct btrfs_log_ctx *ctx)
5404 struct btrfs_root *root = start_inode->root;
5405 struct btrfs_fs_info *fs_info = root->fs_info;
5406 struct btrfs_path *path;
5407 LIST_HEAD(dir_list);
5408 struct btrfs_dir_list *dir_elem;
5409 u64 ino = btrfs_ino(start_inode);
5413 * If we are logging a new name, as part of a link or rename operation,
5414 * don't bother logging new dentries, as we just want to log the names
5415 * of an inode and that any new parents exist.
5417 if (ctx->logging_new_name)
5420 path = btrfs_alloc_path();
5425 struct extent_buffer *leaf;
5426 struct btrfs_key min_key;
5427 bool continue_curr_inode = true;
5431 min_key.objectid = ino;
5432 min_key.type = BTRFS_DIR_INDEX_KEY;
5435 btrfs_release_path(path);
5436 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
5439 } else if (ret > 0) {
5444 leaf = path->nodes[0];
5445 nritems = btrfs_header_nritems(leaf);
5446 for (i = path->slots[0]; i < nritems; i++) {
5447 struct btrfs_dir_item *di;
5448 struct btrfs_key di_key;
5449 struct inode *di_inode;
5450 int log_mode = LOG_INODE_EXISTS;
5453 btrfs_item_key_to_cpu(leaf, &min_key, i);
5454 if (min_key.objectid != ino ||
5455 min_key.type != BTRFS_DIR_INDEX_KEY) {
5456 continue_curr_inode = false;
5460 di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5461 type = btrfs_dir_ftype(leaf, di);
5462 if (btrfs_dir_transid(leaf, di) < trans->transid)
5464 btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5465 if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5468 btrfs_release_path(path);
5469 di_inode = btrfs_iget(fs_info->sb, di_key.objectid, root);
5470 if (IS_ERR(di_inode)) {
5471 ret = PTR_ERR(di_inode);
5475 if (!need_log_inode(trans, BTRFS_I(di_inode))) {
5476 btrfs_add_delayed_iput(BTRFS_I(di_inode));
5480 ctx->log_new_dentries = false;
5481 if (type == BTRFS_FT_DIR)
5482 log_mode = LOG_INODE_ALL;
5483 ret = btrfs_log_inode(trans, BTRFS_I(di_inode),
5485 btrfs_add_delayed_iput(BTRFS_I(di_inode));
5488 if (ctx->log_new_dentries) {
5489 dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5494 dir_elem->ino = di_key.objectid;
5495 list_add_tail(&dir_elem->list, &dir_list);
5500 if (continue_curr_inode && min_key.offset < (u64)-1) {
5506 if (list_empty(&dir_list))
5509 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
5510 ino = dir_elem->ino;
5511 list_del(&dir_elem->list);
5515 btrfs_free_path(path);
5517 struct btrfs_dir_list *next;
5519 list_for_each_entry_safe(dir_elem, next, &dir_list, list)
5526 struct btrfs_ino_list {
5529 struct list_head list;
5532 static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
5534 struct btrfs_ino_list *curr;
5535 struct btrfs_ino_list *next;
5537 list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
5538 list_del(&curr->list);
5543 static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
5544 struct btrfs_path *path)
5546 struct btrfs_key key;
5550 key.type = BTRFS_INODE_ITEM_KEY;
5553 path->search_commit_root = 1;
5554 path->skip_locking = 1;
5556 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5557 if (WARN_ON_ONCE(ret > 0)) {
5559 * We have previously found the inode through the commit root
5560 * so this should not happen. If it does, just error out and
5561 * fallback to a transaction commit.
5564 } else if (ret == 0) {
5565 struct btrfs_inode_item *item;
5567 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5568 struct btrfs_inode_item);
5569 if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
5573 btrfs_release_path(path);
5574 path->search_commit_root = 0;
5575 path->skip_locking = 0;
5580 static int add_conflicting_inode(struct btrfs_trans_handle *trans,
5581 struct btrfs_root *root,
5582 struct btrfs_path *path,
5583 u64 ino, u64 parent,
5584 struct btrfs_log_ctx *ctx)
5586 struct btrfs_ino_list *ino_elem;
5587 struct inode *inode;
5590 * It's rare to have a lot of conflicting inodes, in practice it is not
5591 * common to have more than 1 or 2. We don't want to collect too many,
5592 * as we could end up logging too many inodes (even if only in
5593 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
5596 if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES)
5597 return BTRFS_LOG_FORCE_COMMIT;
5599 inode = btrfs_iget(root->fs_info->sb, ino, root);
5601 * If the other inode that had a conflicting dir entry was deleted in
5602 * the current transaction then we either:
5604 * 1) Log the parent directory (later after adding it to the list) if
5605 * the inode is a directory. This is because it may be a deleted
5606 * subvolume/snapshot or it may be a regular directory that had
5607 * deleted subvolumes/snapshots (or subdirectories that had them),
5608 * and at the moment we can't deal with dropping subvolumes/snapshots
5609 * during log replay. So we just log the parent, which will result in
5610 * a fallback to a transaction commit if we are dealing with those
5611 * cases (last_unlink_trans will match the current transaction);
5613 * 2) Do nothing if it's not a directory. During log replay we simply
5614 * unlink the conflicting dentry from the parent directory and then
5615 * add the dentry for our inode. Like this we can avoid logging the
5616 * parent directory (and maybe fallback to a transaction commit in
5617 * case it has a last_unlink_trans == trans->transid, due to moving
5618 * some inode from it to some other directory).
5620 if (IS_ERR(inode)) {
5621 int ret = PTR_ERR(inode);
5626 ret = conflicting_inode_is_dir(root, ino, path);
5627 /* Not a directory or we got an error. */
5631 /* Conflicting inode is a directory, so we'll log its parent. */
5632 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5635 ino_elem->ino = ino;
5636 ino_elem->parent = parent;
5637 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5638 ctx->num_conflict_inodes++;
5644 * If the inode was already logged skip it - otherwise we can hit an
5645 * infinite loop. Example:
5647 * From the commit root (previous transaction) we have the following
5650 * inode 257 a directory
5651 * inode 258 with references "zz" and "zz_link" on inode 257
5652 * inode 259 with reference "a" on inode 257
5654 * And in the current (uncommitted) transaction we have:
5656 * inode 257 a directory, unchanged
5657 * inode 258 with references "a" and "a2" on inode 257
5658 * inode 259 with reference "zz_link" on inode 257
5659 * inode 261 with reference "zz" on inode 257
5661 * When logging inode 261 the following infinite loop could
5662 * happen if we don't skip already logged inodes:
5664 * - we detect inode 258 as a conflicting inode, with inode 261
5665 * on reference "zz", and log it;
5667 * - we detect inode 259 as a conflicting inode, with inode 258
5668 * on reference "a", and log it;
5670 * - we detect inode 258 as a conflicting inode, with inode 259
5671 * on reference "zz_link", and log it - again! After this we
5672 * repeat the above steps forever.
5674 * Here we can use need_log_inode() because we only need to log the
5675 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
5676 * so that the log ends up with the new name and without the old name.
5678 if (!need_log_inode(trans, BTRFS_I(inode))) {
5679 btrfs_add_delayed_iput(BTRFS_I(inode));
5683 btrfs_add_delayed_iput(BTRFS_I(inode));
5685 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5688 ino_elem->ino = ino;
5689 ino_elem->parent = parent;
5690 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5691 ctx->num_conflict_inodes++;
5696 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
5697 struct btrfs_root *root,
5698 struct btrfs_log_ctx *ctx)
5700 struct btrfs_fs_info *fs_info = root->fs_info;
5704 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
5705 * otherwise we could have unbounded recursion of btrfs_log_inode()
5706 * calls. This check guarantees we can have only 1 level of recursion.
5708 if (ctx->logging_conflict_inodes)
5711 ctx->logging_conflict_inodes = true;
5714 * New conflicting inodes may be found and added to the list while we
5715 * are logging a conflicting inode, so keep iterating while the list is
5718 while (!list_empty(&ctx->conflict_inodes)) {
5719 struct btrfs_ino_list *curr;
5720 struct inode *inode;
5724 curr = list_first_entry(&ctx->conflict_inodes,
5725 struct btrfs_ino_list, list);
5727 parent = curr->parent;
5728 list_del(&curr->list);
5731 inode = btrfs_iget(fs_info->sb, ino, root);
5733 * If the other inode that had a conflicting dir entry was
5734 * deleted in the current transaction, we need to log its parent
5735 * directory. See the comment at add_conflicting_inode().
5737 if (IS_ERR(inode)) {
5738 ret = PTR_ERR(inode);
5742 inode = btrfs_iget(fs_info->sb, parent, root);
5743 if (IS_ERR(inode)) {
5744 ret = PTR_ERR(inode);
5749 * Always log the directory, we cannot make this
5750 * conditional on need_log_inode() because the directory
5751 * might have been logged in LOG_INODE_EXISTS mode or
5752 * the dir index of the conflicting inode is not in a
5753 * dir index key range logged for the directory. So we
5754 * must make sure the deletion is recorded.
5756 ret = btrfs_log_inode(trans, BTRFS_I(inode),
5757 LOG_INODE_ALL, ctx);
5758 btrfs_add_delayed_iput(BTRFS_I(inode));
5765 * Here we can use need_log_inode() because we only need to log
5766 * the inode in LOG_INODE_EXISTS mode and rename operations
5767 * update the log, so that the log ends up with the new name and
5768 * without the old name.
5770 * We did this check at add_conflicting_inode(), but here we do
5771 * it again because if some other task logged the inode after
5772 * that, we can avoid doing it again.
5774 if (!need_log_inode(trans, BTRFS_I(inode))) {
5775 btrfs_add_delayed_iput(BTRFS_I(inode));
5780 * We are safe logging the other inode without acquiring its
5781 * lock as long as we log with the LOG_INODE_EXISTS mode. We
5782 * are safe against concurrent renames of the other inode as
5783 * well because during a rename we pin the log and update the
5784 * log with the new name before we unpin it.
5786 ret = btrfs_log_inode(trans, BTRFS_I(inode), LOG_INODE_EXISTS, ctx);
5787 btrfs_add_delayed_iput(BTRFS_I(inode));
5792 ctx->logging_conflict_inodes = false;
5794 free_conflicting_inodes(ctx);
5799 static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
5800 struct btrfs_inode *inode,
5801 struct btrfs_key *min_key,
5802 const struct btrfs_key *max_key,
5803 struct btrfs_path *path,
5804 struct btrfs_path *dst_path,
5805 const u64 logged_isize,
5806 const int inode_only,
5807 struct btrfs_log_ctx *ctx,
5808 bool *need_log_inode_item)
5810 const u64 i_size = i_size_read(&inode->vfs_inode);
5811 struct btrfs_root *root = inode->root;
5812 int ins_start_slot = 0;
5817 ret = btrfs_search_forward(root, min_key, path, trans->transid);
5825 /* Note, ins_nr might be > 0 here, cleanup outside the loop */
5826 if (min_key->objectid != max_key->objectid)
5828 if (min_key->type > max_key->type)
5831 if (min_key->type == BTRFS_INODE_ITEM_KEY) {
5832 *need_log_inode_item = false;
5833 } else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
5834 min_key->offset >= i_size) {
5836 * Extents at and beyond eof are logged with
5837 * btrfs_log_prealloc_extents().
5838 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
5839 * and no keys greater than that, so bail out.
5842 } else if ((min_key->type == BTRFS_INODE_REF_KEY ||
5843 min_key->type == BTRFS_INODE_EXTREF_KEY) &&
5844 (inode->generation == trans->transid ||
5845 ctx->logging_conflict_inodes)) {
5847 u64 other_parent = 0;
5849 ret = btrfs_check_ref_name_override(path->nodes[0],
5850 path->slots[0], min_key, inode,
5851 &other_ino, &other_parent);
5854 } else if (ret > 0 &&
5855 other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5860 ins_start_slot = path->slots[0];
5862 ret = copy_items(trans, inode, dst_path, path,
5863 ins_start_slot, ins_nr,
5864 inode_only, logged_isize);
5869 btrfs_release_path(path);
5870 ret = add_conflicting_inode(trans, root, path,
5877 } else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
5878 /* Skip xattrs, logged later with btrfs_log_all_xattrs() */
5881 ret = copy_items(trans, inode, dst_path, path,
5883 ins_nr, inode_only, logged_isize);
5890 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5893 } else if (!ins_nr) {
5894 ins_start_slot = path->slots[0];
5899 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5900 ins_nr, inode_only, logged_isize);
5904 ins_start_slot = path->slots[0];
5907 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
5908 btrfs_item_key_to_cpu(path->nodes[0], min_key,
5913 ret = copy_items(trans, inode, dst_path, path,
5914 ins_start_slot, ins_nr, inode_only,
5920 btrfs_release_path(path);
5922 if (min_key->offset < (u64)-1) {
5924 } else if (min_key->type < max_key->type) {
5926 min_key->offset = 0;
5932 * We may process many leaves full of items for our inode, so
5933 * avoid monopolizing a cpu for too long by rescheduling while
5934 * not holding locks on any tree.
5939 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5940 ins_nr, inode_only, logged_isize);
5945 if (inode_only == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
5947 * Release the path because otherwise we might attempt to double
5948 * lock the same leaf with btrfs_log_prealloc_extents() below.
5950 btrfs_release_path(path);
5951 ret = btrfs_log_prealloc_extents(trans, inode, dst_path);
5957 static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
5958 struct btrfs_root *log,
5959 struct btrfs_path *path,
5960 const struct btrfs_item_batch *batch,
5961 const struct btrfs_delayed_item *first_item)
5963 const struct btrfs_delayed_item *curr = first_item;
5966 ret = btrfs_insert_empty_items(trans, log, path, batch);
5970 for (int i = 0; i < batch->nr; i++) {
5973 data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
5974 write_extent_buffer(path->nodes[0], &curr->data,
5975 (unsigned long)data_ptr, curr->data_len);
5976 curr = list_next_entry(curr, log_list);
5980 btrfs_release_path(path);
5985 static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
5986 struct btrfs_inode *inode,
5987 struct btrfs_path *path,
5988 const struct list_head *delayed_ins_list,
5989 struct btrfs_log_ctx *ctx)
5991 /* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
5992 const int max_batch_size = 195;
5993 const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
5994 const u64 ino = btrfs_ino(inode);
5995 struct btrfs_root *log = inode->root->log_root;
5996 struct btrfs_item_batch batch = {
5998 .total_data_size = 0,
6000 const struct btrfs_delayed_item *first = NULL;
6001 const struct btrfs_delayed_item *curr;
6003 struct btrfs_key *ins_keys;
6005 u64 curr_batch_size = 0;
6009 /* We are adding dir index items to the log tree. */
6010 lockdep_assert_held(&inode->log_mutex);
6013 * We collect delayed items before copying index keys from the subvolume
6014 * to the log tree. However just after we collected them, they may have
6015 * been flushed (all of them or just some of them), and therefore we
6016 * could have copied them from the subvolume tree to the log tree.
6017 * So find the first delayed item that was not yet logged (they are
6018 * sorted by index number).
6020 list_for_each_entry(curr, delayed_ins_list, log_list) {
6021 if (curr->index > inode->last_dir_index_offset) {
6027 /* Empty list or all delayed items were already logged. */
6031 ins_data = kmalloc(max_batch_size * sizeof(u32) +
6032 max_batch_size * sizeof(struct btrfs_key), GFP_NOFS);
6035 ins_sizes = (u32 *)ins_data;
6036 batch.data_sizes = ins_sizes;
6037 ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
6038 batch.keys = ins_keys;
6041 while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
6042 const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
6044 if (curr_batch_size + curr_size > leaf_data_size ||
6045 batch.nr == max_batch_size) {
6046 ret = insert_delayed_items_batch(trans, log, path,
6052 batch.total_data_size = 0;
6053 curr_batch_size = 0;
6057 ins_sizes[batch_idx] = curr->data_len;
6058 ins_keys[batch_idx].objectid = ino;
6059 ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
6060 ins_keys[batch_idx].offset = curr->index;
6061 curr_batch_size += curr_size;
6062 batch.total_data_size += curr->data_len;
6065 curr = list_next_entry(curr, log_list);
6068 ASSERT(batch.nr >= 1);
6069 ret = insert_delayed_items_batch(trans, log, path, &batch, first);
6071 curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
6073 inode->last_dir_index_offset = curr->index;
6080 static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
6081 struct btrfs_inode *inode,
6082 struct btrfs_path *path,
6083 const struct list_head *delayed_del_list,
6084 struct btrfs_log_ctx *ctx)
6086 const u64 ino = btrfs_ino(inode);
6087 const struct btrfs_delayed_item *curr;
6089 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6092 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6093 u64 first_dir_index = curr->index;
6095 const struct btrfs_delayed_item *next;
6099 * Find a range of consecutive dir index items to delete. Like
6100 * this we log a single dir range item spanning several contiguous
6101 * dir items instead of logging one range item per dir index item.
6103 next = list_next_entry(curr, log_list);
6104 while (!list_entry_is_head(next, delayed_del_list, log_list)) {
6105 if (next->index != curr->index + 1)
6108 next = list_next_entry(next, log_list);
6111 last_dir_index = curr->index;
6112 ASSERT(last_dir_index >= first_dir_index);
6114 ret = insert_dir_log_key(trans, inode->root->log_root, path,
6115 ino, first_dir_index, last_dir_index);
6118 curr = list_next_entry(curr, log_list);
6124 static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
6125 struct btrfs_inode *inode,
6126 struct btrfs_path *path,
6127 struct btrfs_log_ctx *ctx,
6128 const struct list_head *delayed_del_list,
6129 const struct btrfs_delayed_item *first,
6130 const struct btrfs_delayed_item **last_ret)
6132 const struct btrfs_delayed_item *next;
6133 struct extent_buffer *leaf = path->nodes[0];
6134 const int last_slot = btrfs_header_nritems(leaf) - 1;
6135 int slot = path->slots[0] + 1;
6136 const u64 ino = btrfs_ino(inode);
6138 next = list_next_entry(first, log_list);
6140 while (slot < last_slot &&
6141 !list_entry_is_head(next, delayed_del_list, log_list)) {
6142 struct btrfs_key key;
6144 btrfs_item_key_to_cpu(leaf, &key, slot);
6145 if (key.objectid != ino ||
6146 key.type != BTRFS_DIR_INDEX_KEY ||
6147 key.offset != next->index)
6152 next = list_next_entry(next, log_list);
6155 return btrfs_del_items(trans, inode->root->log_root, path,
6156 path->slots[0], slot - path->slots[0]);
6159 static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
6160 struct btrfs_inode *inode,
6161 struct btrfs_path *path,
6162 const struct list_head *delayed_del_list,
6163 struct btrfs_log_ctx *ctx)
6165 struct btrfs_root *log = inode->root->log_root;
6166 const struct btrfs_delayed_item *curr;
6167 u64 last_range_start;
6168 u64 last_range_end = 0;
6169 struct btrfs_key key;
6171 key.objectid = btrfs_ino(inode);
6172 key.type = BTRFS_DIR_INDEX_KEY;
6173 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6176 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6177 const struct btrfs_delayed_item *last = curr;
6178 u64 first_dir_index = curr->index;
6180 bool deleted_items = false;
6183 key.offset = curr->index;
6184 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
6187 } else if (ret == 0) {
6188 ret = batch_delete_dir_index_items(trans, inode, path, ctx,
6189 delayed_del_list, curr,
6193 deleted_items = true;
6196 btrfs_release_path(path);
6199 * If we deleted items from the leaf, it means we have a range
6200 * item logging their range, so no need to add one or update an
6201 * existing one. Otherwise we have to log a dir range item.
6206 last_dir_index = last->index;
6207 ASSERT(last_dir_index >= first_dir_index);
6209 * If this range starts right after where the previous one ends,
6210 * then we want to reuse the previous range item and change its
6211 * end offset to the end of this range. This is just to minimize
6212 * leaf space usage, by avoiding adding a new range item.
6214 if (last_range_end != 0 && first_dir_index == last_range_end + 1)
6215 first_dir_index = last_range_start;
6217 ret = insert_dir_log_key(trans, log, path, key.objectid,
6218 first_dir_index, last_dir_index);
6222 last_range_start = first_dir_index;
6223 last_range_end = last_dir_index;
6225 curr = list_next_entry(last, log_list);
6231 static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
6232 struct btrfs_inode *inode,
6233 struct btrfs_path *path,
6234 const struct list_head *delayed_del_list,
6235 struct btrfs_log_ctx *ctx)
6238 * We are deleting dir index items from the log tree or adding range
6241 lockdep_assert_held(&inode->log_mutex);
6243 if (list_empty(delayed_del_list))
6246 if (ctx->logged_before)
6247 return log_delayed_deletions_incremental(trans, inode, path,
6248 delayed_del_list, ctx);
6250 return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
6255 * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
6256 * items instead of the subvolume tree.
6258 static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
6259 struct btrfs_inode *inode,
6260 const struct list_head *delayed_ins_list,
6261 struct btrfs_log_ctx *ctx)
6263 const bool orig_log_new_dentries = ctx->log_new_dentries;
6264 struct btrfs_fs_info *fs_info = trans->fs_info;
6265 struct btrfs_delayed_item *item;
6269 * No need for the log mutex, plus to avoid potential deadlocks or
6270 * lockdep annotations due to nesting of delayed inode mutexes and log
6273 lockdep_assert_not_held(&inode->log_mutex);
6275 ASSERT(!ctx->logging_new_delayed_dentries);
6276 ctx->logging_new_delayed_dentries = true;
6278 list_for_each_entry(item, delayed_ins_list, log_list) {
6279 struct btrfs_dir_item *dir_item;
6280 struct inode *di_inode;
6281 struct btrfs_key key;
6282 int log_mode = LOG_INODE_EXISTS;
6284 dir_item = (struct btrfs_dir_item *)item->data;
6285 btrfs_disk_key_to_cpu(&key, &dir_item->location);
6287 if (key.type == BTRFS_ROOT_ITEM_KEY)
6290 di_inode = btrfs_iget(fs_info->sb, key.objectid, inode->root);
6291 if (IS_ERR(di_inode)) {
6292 ret = PTR_ERR(di_inode);
6296 if (!need_log_inode(trans, BTRFS_I(di_inode))) {
6297 btrfs_add_delayed_iput(BTRFS_I(di_inode));
6301 if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
6302 log_mode = LOG_INODE_ALL;
6304 ctx->log_new_dentries = false;
6305 ret = btrfs_log_inode(trans, BTRFS_I(di_inode), log_mode, ctx);
6307 if (!ret && ctx->log_new_dentries)
6308 ret = log_new_dir_dentries(trans, BTRFS_I(di_inode), ctx);
6310 btrfs_add_delayed_iput(BTRFS_I(di_inode));
6316 ctx->log_new_dentries = orig_log_new_dentries;
6317 ctx->logging_new_delayed_dentries = false;
6322 /* log a single inode in the tree log.
6323 * At least one parent directory for this inode must exist in the tree
6324 * or be logged already.
6326 * Any items from this inode changed by the current transaction are copied
6327 * to the log tree. An extra reference is taken on any extents in this
6328 * file, allowing us to avoid a whole pile of corner cases around logging
6329 * blocks that have been removed from the tree.
6331 * See LOG_INODE_ALL and related defines for a description of what inode_only
6334 * This handles both files and directories.
6336 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
6337 struct btrfs_inode *inode,
6339 struct btrfs_log_ctx *ctx)
6341 struct btrfs_path *path;
6342 struct btrfs_path *dst_path;
6343 struct btrfs_key min_key;
6344 struct btrfs_key max_key;
6345 struct btrfs_root *log = inode->root->log_root;
6347 bool fast_search = false;
6348 u64 ino = btrfs_ino(inode);
6349 struct extent_map_tree *em_tree = &inode->extent_tree;
6350 u64 logged_isize = 0;
6351 bool need_log_inode_item = true;
6352 bool xattrs_logged = false;
6353 bool inode_item_dropped = true;
6354 bool full_dir_logging = false;
6355 LIST_HEAD(delayed_ins_list);
6356 LIST_HEAD(delayed_del_list);
6358 path = btrfs_alloc_path();
6361 dst_path = btrfs_alloc_path();
6363 btrfs_free_path(path);
6367 min_key.objectid = ino;
6368 min_key.type = BTRFS_INODE_ITEM_KEY;
6371 max_key.objectid = ino;
6374 /* today the code can only do partial logging of directories */
6375 if (S_ISDIR(inode->vfs_inode.i_mode) ||
6376 (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6377 &inode->runtime_flags) &&
6378 inode_only >= LOG_INODE_EXISTS))
6379 max_key.type = BTRFS_XATTR_ITEM_KEY;
6381 max_key.type = (u8)-1;
6382 max_key.offset = (u64)-1;
6384 if (S_ISDIR(inode->vfs_inode.i_mode) && inode_only == LOG_INODE_ALL)
6385 full_dir_logging = true;
6388 * If we are logging a directory while we are logging dentries of the
6389 * delayed items of some other inode, then we need to flush the delayed
6390 * items of this directory and not log the delayed items directly. This
6391 * is to prevent more than one level of recursion into btrfs_log_inode()
6392 * by having something like this:
6394 * $ mkdir -p a/b/c/d/e/f/g/h/...
6395 * $ xfs_io -c "fsync" a
6397 * Where all directories in the path did not exist before and are
6398 * created in the current transaction.
6399 * So in such a case we directly log the delayed items of the main
6400 * directory ("a") without flushing them first, while for each of its
6401 * subdirectories we flush their delayed items before logging them.
6402 * This prevents a potential unbounded recursion like this:
6405 * log_new_delayed_dentries()
6407 * log_new_delayed_dentries()
6409 * log_new_delayed_dentries()
6412 * We have thresholds for the maximum number of delayed items to have in
6413 * memory, and once they are hit, the items are flushed asynchronously.
6414 * However the limit is quite high, so lets prevent deep levels of
6415 * recursion to happen by limiting the maximum depth to be 1.
6417 if (full_dir_logging && ctx->logging_new_delayed_dentries) {
6418 ret = btrfs_commit_inode_delayed_items(trans, inode);
6423 mutex_lock(&inode->log_mutex);
6426 * For symlinks, we must always log their content, which is stored in an
6427 * inline extent, otherwise we could end up with an empty symlink after
6428 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
6429 * one attempts to create an empty symlink).
6430 * We don't need to worry about flushing delalloc, because when we create
6431 * the inline extent when the symlink is created (we never have delalloc
6434 if (S_ISLNK(inode->vfs_inode.i_mode))
6435 inode_only = LOG_INODE_ALL;
6438 * Before logging the inode item, cache the value returned by
6439 * inode_logged(), because after that we have the need to figure out if
6440 * the inode was previously logged in this transaction.
6442 ret = inode_logged(trans, inode, path);
6445 ctx->logged_before = (ret == 1);
6449 * This is for cases where logging a directory could result in losing a
6450 * a file after replaying the log. For example, if we move a file from a
6451 * directory A to a directory B, then fsync directory A, we have no way
6452 * to known the file was moved from A to B, so logging just A would
6453 * result in losing the file after a log replay.
6455 if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
6456 btrfs_set_log_full_commit(trans);
6457 ret = BTRFS_LOG_FORCE_COMMIT;
6462 * a brute force approach to making sure we get the most uptodate
6463 * copies of everything.
6465 if (S_ISDIR(inode->vfs_inode.i_mode)) {
6466 clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
6467 if (ctx->logged_before)
6468 ret = drop_inode_items(trans, log, path, inode,
6469 BTRFS_XATTR_ITEM_KEY);
6471 if (inode_only == LOG_INODE_EXISTS && ctx->logged_before) {
6473 * Make sure the new inode item we write to the log has
6474 * the same isize as the current one (if it exists).
6475 * This is necessary to prevent data loss after log
6476 * replay, and also to prevent doing a wrong expanding
6477 * truncate - for e.g. create file, write 4K into offset
6478 * 0, fsync, write 4K into offset 4096, add hard link,
6479 * fsync some other file (to sync log), power fail - if
6480 * we use the inode's current i_size, after log replay
6481 * we get a 8Kb file, with the last 4Kb extent as a hole
6482 * (zeroes), as if an expanding truncate happened,
6483 * instead of getting a file of 4Kb only.
6485 ret = logged_inode_size(log, inode, path, &logged_isize);
6489 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6490 &inode->runtime_flags)) {
6491 if (inode_only == LOG_INODE_EXISTS) {
6492 max_key.type = BTRFS_XATTR_ITEM_KEY;
6493 if (ctx->logged_before)
6494 ret = drop_inode_items(trans, log, path,
6495 inode, max_key.type);
6497 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6498 &inode->runtime_flags);
6499 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6500 &inode->runtime_flags);
6501 if (ctx->logged_before)
6502 ret = truncate_inode_items(trans, log,
6505 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6506 &inode->runtime_flags) ||
6507 inode_only == LOG_INODE_EXISTS) {
6508 if (inode_only == LOG_INODE_ALL)
6510 max_key.type = BTRFS_XATTR_ITEM_KEY;
6511 if (ctx->logged_before)
6512 ret = drop_inode_items(trans, log, path, inode,
6515 if (inode_only == LOG_INODE_ALL)
6517 inode_item_dropped = false;
6526 * If we are logging a directory in full mode, collect the delayed items
6527 * before iterating the subvolume tree, so that we don't miss any new
6528 * dir index items in case they get flushed while or right after we are
6529 * iterating the subvolume tree.
6531 if (full_dir_logging && !ctx->logging_new_delayed_dentries)
6532 btrfs_log_get_delayed_items(inode, &delayed_ins_list,
6535 ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
6536 path, dst_path, logged_isize,
6538 &need_log_inode_item);
6542 btrfs_release_path(path);
6543 btrfs_release_path(dst_path);
6544 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
6547 xattrs_logged = true;
6548 if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
6549 btrfs_release_path(path);
6550 btrfs_release_path(dst_path);
6551 ret = btrfs_log_holes(trans, inode, path);
6556 btrfs_release_path(path);
6557 btrfs_release_path(dst_path);
6558 if (need_log_inode_item) {
6559 ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
6563 * If we are doing a fast fsync and the inode was logged before
6564 * in this transaction, we don't need to log the xattrs because
6565 * they were logged before. If xattrs were added, changed or
6566 * deleted since the last time we logged the inode, then we have
6567 * already logged them because the inode had the runtime flag
6568 * BTRFS_INODE_COPY_EVERYTHING set.
6570 if (!xattrs_logged && inode->logged_trans < trans->transid) {
6571 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
6574 btrfs_release_path(path);
6578 ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
6581 } else if (inode_only == LOG_INODE_ALL) {
6582 struct extent_map *em, *n;
6584 write_lock(&em_tree->lock);
6585 list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
6586 list_del_init(&em->list);
6587 write_unlock(&em_tree->lock);
6590 if (full_dir_logging) {
6591 ret = log_directory_changes(trans, inode, path, dst_path, ctx);
6594 ret = log_delayed_insertion_items(trans, inode, path,
6595 &delayed_ins_list, ctx);
6598 ret = log_delayed_deletion_items(trans, inode, path,
6599 &delayed_del_list, ctx);
6604 spin_lock(&inode->lock);
6605 inode->logged_trans = trans->transid;
6607 * Don't update last_log_commit if we logged that an inode exists.
6608 * We do this for three reasons:
6610 * 1) We might have had buffered writes to this inode that were
6611 * flushed and had their ordered extents completed in this
6612 * transaction, but we did not previously log the inode with
6613 * LOG_INODE_ALL. Later the inode was evicted and after that
6614 * it was loaded again and this LOG_INODE_EXISTS log operation
6615 * happened. We must make sure that if an explicit fsync against
6616 * the inode is performed later, it logs the new extents, an
6617 * updated inode item, etc, and syncs the log. The same logic
6618 * applies to direct IO writes instead of buffered writes.
6620 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
6621 * is logged with an i_size of 0 or whatever value was logged
6622 * before. If later the i_size of the inode is increased by a
6623 * truncate operation, the log is synced through an fsync of
6624 * some other inode and then finally an explicit fsync against
6625 * this inode is made, we must make sure this fsync logs the
6626 * inode with the new i_size, the hole between old i_size and
6627 * the new i_size, and syncs the log.
6629 * 3) If we are logging that an ancestor inode exists as part of
6630 * logging a new name from a link or rename operation, don't update
6631 * its last_log_commit - otherwise if an explicit fsync is made
6632 * against an ancestor, the fsync considers the inode in the log
6633 * and doesn't sync the log, resulting in the ancestor missing after
6634 * a power failure unless the log was synced as part of an fsync
6635 * against any other unrelated inode.
6637 if (inode_only != LOG_INODE_EXISTS)
6638 inode->last_log_commit = inode->last_sub_trans;
6639 spin_unlock(&inode->lock);
6642 * Reset the last_reflink_trans so that the next fsync does not need to
6643 * go through the slower path when logging extents and their checksums.
6645 if (inode_only == LOG_INODE_ALL)
6646 inode->last_reflink_trans = 0;
6649 mutex_unlock(&inode->log_mutex);
6651 btrfs_free_path(path);
6652 btrfs_free_path(dst_path);
6655 free_conflicting_inodes(ctx);
6657 ret = log_conflicting_inodes(trans, inode->root, ctx);
6659 if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
6661 ret = log_new_delayed_dentries(trans, inode,
6662 &delayed_ins_list, ctx);
6664 btrfs_log_put_delayed_items(inode, &delayed_ins_list,
6671 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
6672 struct btrfs_inode *inode,
6673 struct btrfs_log_ctx *ctx)
6675 struct btrfs_fs_info *fs_info = trans->fs_info;
6677 struct btrfs_path *path;
6678 struct btrfs_key key;
6679 struct btrfs_root *root = inode->root;
6680 const u64 ino = btrfs_ino(inode);
6682 path = btrfs_alloc_path();
6685 path->skip_locking = 1;
6686 path->search_commit_root = 1;
6689 key.type = BTRFS_INODE_REF_KEY;
6691 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6696 struct extent_buffer *leaf = path->nodes[0];
6697 int slot = path->slots[0];
6702 if (slot >= btrfs_header_nritems(leaf)) {
6703 ret = btrfs_next_leaf(root, path);
6711 btrfs_item_key_to_cpu(leaf, &key, slot);
6712 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
6713 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
6716 item_size = btrfs_item_size(leaf, slot);
6717 ptr = btrfs_item_ptr_offset(leaf, slot);
6718 while (cur_offset < item_size) {
6719 struct btrfs_key inode_key;
6720 struct inode *dir_inode;
6722 inode_key.type = BTRFS_INODE_ITEM_KEY;
6723 inode_key.offset = 0;
6725 if (key.type == BTRFS_INODE_EXTREF_KEY) {
6726 struct btrfs_inode_extref *extref;
6728 extref = (struct btrfs_inode_extref *)
6730 inode_key.objectid = btrfs_inode_extref_parent(
6732 cur_offset += sizeof(*extref);
6733 cur_offset += btrfs_inode_extref_name_len(leaf,
6736 inode_key.objectid = key.offset;
6737 cur_offset = item_size;
6740 dir_inode = btrfs_iget(fs_info->sb, inode_key.objectid,
6743 * If the parent inode was deleted, return an error to
6744 * fallback to a transaction commit. This is to prevent
6745 * getting an inode that was moved from one parent A to
6746 * a parent B, got its former parent A deleted and then
6747 * it got fsync'ed, from existing at both parents after
6748 * a log replay (and the old parent still existing).
6755 * mv /mnt/B/bar /mnt/A/bar
6756 * mv -T /mnt/A /mnt/B
6760 * If we ignore the old parent B which got deleted,
6761 * after a log replay we would have file bar linked
6762 * at both parents and the old parent B would still
6765 if (IS_ERR(dir_inode)) {
6766 ret = PTR_ERR(dir_inode);
6770 if (!need_log_inode(trans, BTRFS_I(dir_inode))) {
6771 btrfs_add_delayed_iput(BTRFS_I(dir_inode));
6775 ctx->log_new_dentries = false;
6776 ret = btrfs_log_inode(trans, BTRFS_I(dir_inode),
6777 LOG_INODE_ALL, ctx);
6778 if (!ret && ctx->log_new_dentries)
6779 ret = log_new_dir_dentries(trans,
6780 BTRFS_I(dir_inode), ctx);
6781 btrfs_add_delayed_iput(BTRFS_I(dir_inode));
6789 btrfs_free_path(path);
6793 static int log_new_ancestors(struct btrfs_trans_handle *trans,
6794 struct btrfs_root *root,
6795 struct btrfs_path *path,
6796 struct btrfs_log_ctx *ctx)
6798 struct btrfs_key found_key;
6800 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
6803 struct btrfs_fs_info *fs_info = root->fs_info;
6804 struct extent_buffer *leaf = path->nodes[0];
6805 int slot = path->slots[0];
6806 struct btrfs_key search_key;
6807 struct inode *inode;
6811 btrfs_release_path(path);
6813 ino = found_key.offset;
6815 search_key.objectid = found_key.offset;
6816 search_key.type = BTRFS_INODE_ITEM_KEY;
6817 search_key.offset = 0;
6818 inode = btrfs_iget(fs_info->sb, ino, root);
6820 return PTR_ERR(inode);
6822 if (BTRFS_I(inode)->generation >= trans->transid &&
6823 need_log_inode(trans, BTRFS_I(inode)))
6824 ret = btrfs_log_inode(trans, BTRFS_I(inode),
6825 LOG_INODE_EXISTS, ctx);
6826 btrfs_add_delayed_iput(BTRFS_I(inode));
6830 if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
6833 search_key.type = BTRFS_INODE_REF_KEY;
6834 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6838 leaf = path->nodes[0];
6839 slot = path->slots[0];
6840 if (slot >= btrfs_header_nritems(leaf)) {
6841 ret = btrfs_next_leaf(root, path);
6846 leaf = path->nodes[0];
6847 slot = path->slots[0];
6850 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6851 if (found_key.objectid != search_key.objectid ||
6852 found_key.type != BTRFS_INODE_REF_KEY)
6858 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
6859 struct btrfs_inode *inode,
6860 struct dentry *parent,
6861 struct btrfs_log_ctx *ctx)
6863 struct btrfs_root *root = inode->root;
6864 struct dentry *old_parent = NULL;
6865 struct super_block *sb = inode->vfs_inode.i_sb;
6869 if (!parent || d_really_is_negative(parent) ||
6873 inode = BTRFS_I(d_inode(parent));
6874 if (root != inode->root)
6877 if (inode->generation >= trans->transid &&
6878 need_log_inode(trans, inode)) {
6879 ret = btrfs_log_inode(trans, inode,
6880 LOG_INODE_EXISTS, ctx);
6884 if (IS_ROOT(parent))
6887 parent = dget_parent(parent);
6889 old_parent = parent;
6896 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
6897 struct btrfs_inode *inode,
6898 struct dentry *parent,
6899 struct btrfs_log_ctx *ctx)
6901 struct btrfs_root *root = inode->root;
6902 const u64 ino = btrfs_ino(inode);
6903 struct btrfs_path *path;
6904 struct btrfs_key search_key;
6908 * For a single hard link case, go through a fast path that does not
6909 * need to iterate the fs/subvolume tree.
6911 if (inode->vfs_inode.i_nlink < 2)
6912 return log_new_ancestors_fast(trans, inode, parent, ctx);
6914 path = btrfs_alloc_path();
6918 search_key.objectid = ino;
6919 search_key.type = BTRFS_INODE_REF_KEY;
6920 search_key.offset = 0;
6922 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6929 struct extent_buffer *leaf = path->nodes[0];
6930 int slot = path->slots[0];
6931 struct btrfs_key found_key;
6933 if (slot >= btrfs_header_nritems(leaf)) {
6934 ret = btrfs_next_leaf(root, path);
6942 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6943 if (found_key.objectid != ino ||
6944 found_key.type > BTRFS_INODE_EXTREF_KEY)
6948 * Don't deal with extended references because they are rare
6949 * cases and too complex to deal with (we would need to keep
6950 * track of which subitem we are processing for each item in
6951 * this loop, etc). So just return some error to fallback to
6952 * a transaction commit.
6954 if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
6960 * Logging ancestors needs to do more searches on the fs/subvol
6961 * tree, so it releases the path as needed to avoid deadlocks.
6962 * Keep track of the last inode ref key and resume from that key
6963 * after logging all new ancestors for the current hard link.
6965 memcpy(&search_key, &found_key, sizeof(search_key));
6967 ret = log_new_ancestors(trans, root, path, ctx);
6970 btrfs_release_path(path);
6975 btrfs_free_path(path);
6980 * helper function around btrfs_log_inode to make sure newly created
6981 * parent directories also end up in the log. A minimal inode and backref
6982 * only logging is done of any parent directories that are older than
6983 * the last committed transaction
6985 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
6986 struct btrfs_inode *inode,
6987 struct dentry *parent,
6989 struct btrfs_log_ctx *ctx)
6991 struct btrfs_root *root = inode->root;
6992 struct btrfs_fs_info *fs_info = root->fs_info;
6994 bool log_dentries = false;
6996 if (btrfs_test_opt(fs_info, NOTREELOG)) {
6997 ret = BTRFS_LOG_FORCE_COMMIT;
7001 if (btrfs_root_refs(&root->root_item) == 0) {
7002 ret = BTRFS_LOG_FORCE_COMMIT;
7007 * Skip already logged inodes or inodes corresponding to tmpfiles
7008 * (since logging them is pointless, a link count of 0 means they
7009 * will never be accessible).
7011 if ((btrfs_inode_in_log(inode, trans->transid) &&
7012 list_empty(&ctx->ordered_extents)) ||
7013 inode->vfs_inode.i_nlink == 0) {
7014 ret = BTRFS_NO_LOG_SYNC;
7018 ret = start_log_trans(trans, root, ctx);
7022 ret = btrfs_log_inode(trans, inode, inode_only, ctx);
7027 * for regular files, if its inode is already on disk, we don't
7028 * have to worry about the parents at all. This is because
7029 * we can use the last_unlink_trans field to record renames
7030 * and other fun in this file.
7032 if (S_ISREG(inode->vfs_inode.i_mode) &&
7033 inode->generation < trans->transid &&
7034 inode->last_unlink_trans < trans->transid) {
7039 if (S_ISDIR(inode->vfs_inode.i_mode) && ctx->log_new_dentries)
7040 log_dentries = true;
7043 * On unlink we must make sure all our current and old parent directory
7044 * inodes are fully logged. This is to prevent leaving dangling
7045 * directory index entries in directories that were our parents but are
7046 * not anymore. Not doing this results in old parent directory being
7047 * impossible to delete after log replay (rmdir will always fail with
7048 * error -ENOTEMPTY).
7054 * ln testdir/foo testdir/bar
7056 * unlink testdir/bar
7057 * xfs_io -c fsync testdir/foo
7059 * mount fs, triggers log replay
7061 * If we don't log the parent directory (testdir), after log replay the
7062 * directory still has an entry pointing to the file inode using the bar
7063 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
7064 * the file inode has a link count of 1.
7070 * ln foo testdir/foo2
7071 * ln foo testdir/foo3
7073 * unlink testdir/foo3
7074 * xfs_io -c fsync foo
7076 * mount fs, triggers log replay
7078 * Similar as the first example, after log replay the parent directory
7079 * testdir still has an entry pointing to the inode file with name foo3
7080 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
7081 * and has a link count of 2.
7083 if (inode->last_unlink_trans >= trans->transid) {
7084 ret = btrfs_log_all_parents(trans, inode, ctx);
7089 ret = log_all_new_ancestors(trans, inode, parent, ctx);
7094 ret = log_new_dir_dentries(trans, inode, ctx);
7099 btrfs_set_log_full_commit(trans);
7100 ret = BTRFS_LOG_FORCE_COMMIT;
7104 btrfs_remove_log_ctx(root, ctx);
7105 btrfs_end_log_trans(root);
7111 * it is not safe to log dentry if the chunk root has added new
7112 * chunks. This returns 0 if the dentry was logged, and 1 otherwise.
7113 * If this returns 1, you must commit the transaction to safely get your
7116 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7117 struct dentry *dentry,
7118 struct btrfs_log_ctx *ctx)
7120 struct dentry *parent = dget_parent(dentry);
7123 ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
7124 LOG_INODE_ALL, ctx);
7131 * should be called during mount to recover any replay any log trees
7134 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7137 struct btrfs_path *path;
7138 struct btrfs_trans_handle *trans;
7139 struct btrfs_key key;
7140 struct btrfs_key found_key;
7141 struct btrfs_root *log;
7142 struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7143 struct walk_control wc = {
7144 .process_func = process_one_buffer,
7145 .stage = LOG_WALK_PIN_ONLY,
7148 path = btrfs_alloc_path();
7152 set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7154 trans = btrfs_start_transaction(fs_info->tree_root, 0);
7155 if (IS_ERR(trans)) {
7156 ret = PTR_ERR(trans);
7163 ret = walk_log_tree(trans, log_root_tree, &wc);
7165 btrfs_abort_transaction(trans, ret);
7170 key.objectid = BTRFS_TREE_LOG_OBJECTID;
7171 key.offset = (u64)-1;
7172 key.type = BTRFS_ROOT_ITEM_KEY;
7175 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
7178 btrfs_abort_transaction(trans, ret);
7182 if (path->slots[0] == 0)
7186 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7188 btrfs_release_path(path);
7189 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7192 log = btrfs_read_tree_root(log_root_tree, &found_key);
7195 btrfs_abort_transaction(trans, ret);
7199 wc.replay_dest = btrfs_get_fs_root(fs_info, found_key.offset,
7201 if (IS_ERR(wc.replay_dest)) {
7202 ret = PTR_ERR(wc.replay_dest);
7205 * We didn't find the subvol, likely because it was
7206 * deleted. This is ok, simply skip this log and go to
7209 * We need to exclude the root because we can't have
7210 * other log replays overwriting this log as we'll read
7211 * it back in a few more times. This will keep our
7212 * block from being modified, and we'll just bail for
7213 * each subsequent pass.
7216 ret = btrfs_pin_extent_for_log_replay(trans,
7219 btrfs_put_root(log);
7223 btrfs_abort_transaction(trans, ret);
7227 wc.replay_dest->log_root = log;
7228 ret = btrfs_record_root_in_trans(trans, wc.replay_dest);
7230 /* The loop needs to continue due to the root refs */
7231 btrfs_abort_transaction(trans, ret);
7233 ret = walk_log_tree(trans, log, &wc);
7235 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7236 ret = fixup_inode_link_counts(trans, wc.replay_dest,
7239 btrfs_abort_transaction(trans, ret);
7242 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7243 struct btrfs_root *root = wc.replay_dest;
7245 btrfs_release_path(path);
7248 * We have just replayed everything, and the highest
7249 * objectid of fs roots probably has changed in case
7250 * some inode_item's got replayed.
7252 * root->objectid_mutex is not acquired as log replay
7253 * could only happen during mount.
7255 ret = btrfs_init_root_free_objectid(root);
7257 btrfs_abort_transaction(trans, ret);
7260 wc.replay_dest->log_root = NULL;
7261 btrfs_put_root(wc.replay_dest);
7262 btrfs_put_root(log);
7267 if (found_key.offset == 0)
7269 key.offset = found_key.offset - 1;
7271 btrfs_release_path(path);
7273 /* step one is to pin it all, step two is to replay just inodes */
7276 wc.process_func = replay_one_buffer;
7277 wc.stage = LOG_WALK_REPLAY_INODES;
7280 /* step three is to replay everything */
7281 if (wc.stage < LOG_WALK_REPLAY_ALL) {
7286 btrfs_free_path(path);
7288 /* step 4: commit the transaction, which also unpins the blocks */
7289 ret = btrfs_commit_transaction(trans);
7293 log_root_tree->log_root = NULL;
7294 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7295 btrfs_put_root(log_root_tree);
7300 btrfs_end_transaction(wc.trans);
7301 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7302 btrfs_free_path(path);
7307 * there are some corner cases where we want to force a full
7308 * commit instead of allowing a directory to be logged.
7310 * They revolve around files there were unlinked from the directory, and
7311 * this function updates the parent directory so that a full commit is
7312 * properly done if it is fsync'd later after the unlinks are done.
7314 * Must be called before the unlink operations (updates to the subvolume tree,
7315 * inodes, etc) are done.
7317 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
7318 struct btrfs_inode *dir, struct btrfs_inode *inode,
7322 * when we're logging a file, if it hasn't been renamed
7323 * or unlinked, and its inode is fully committed on disk,
7324 * we don't have to worry about walking up the directory chain
7325 * to log its parents.
7327 * So, we use the last_unlink_trans field to put this transid
7328 * into the file. When the file is logged we check it and
7329 * don't log the parents if the file is fully on disk.
7331 mutex_lock(&inode->log_mutex);
7332 inode->last_unlink_trans = trans->transid;
7333 mutex_unlock(&inode->log_mutex);
7336 * if this directory was already logged any new
7337 * names for this file/dir will get recorded
7339 if (dir->logged_trans == trans->transid)
7343 * if the inode we're about to unlink was logged,
7344 * the log will be properly updated for any new names
7346 if (inode->logged_trans == trans->transid)
7350 * when renaming files across directories, if the directory
7351 * there we're unlinking from gets fsync'd later on, there's
7352 * no way to find the destination directory later and fsync it
7353 * properly. So, we have to be conservative and force commits
7354 * so the new name gets discovered.
7359 /* we can safely do the unlink without any special recording */
7363 mutex_lock(&dir->log_mutex);
7364 dir->last_unlink_trans = trans->transid;
7365 mutex_unlock(&dir->log_mutex);
7369 * Make sure that if someone attempts to fsync the parent directory of a deleted
7370 * snapshot, it ends up triggering a transaction commit. This is to guarantee
7371 * that after replaying the log tree of the parent directory's root we will not
7372 * see the snapshot anymore and at log replay time we will not see any log tree
7373 * corresponding to the deleted snapshot's root, which could lead to replaying
7374 * it after replaying the log tree of the parent directory (which would replay
7375 * the snapshot delete operation).
7377 * Must be called before the actual snapshot destroy operation (updates to the
7378 * parent root and tree of tree roots trees, etc) are done.
7380 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
7381 struct btrfs_inode *dir)
7383 mutex_lock(&dir->log_mutex);
7384 dir->last_unlink_trans = trans->transid;
7385 mutex_unlock(&dir->log_mutex);
7389 * Update the log after adding a new name for an inode.
7391 * @trans: Transaction handle.
7392 * @old_dentry: The dentry associated with the old name and the old
7394 * @old_dir: The inode of the previous parent directory for the case
7395 * of a rename. For a link operation, it must be NULL.
7396 * @old_dir_index: The index number associated with the old name, meaningful
7397 * only for rename operations (when @old_dir is not NULL).
7398 * Ignored for link operations.
7399 * @parent: The dentry associated with the directory under which the
7400 * new name is located.
7402 * Call this after adding a new name for an inode, as a result of a link or
7403 * rename operation, and it will properly update the log to reflect the new name.
7405 void btrfs_log_new_name(struct btrfs_trans_handle *trans,
7406 struct dentry *old_dentry, struct btrfs_inode *old_dir,
7407 u64 old_dir_index, struct dentry *parent)
7409 struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
7410 struct btrfs_root *root = inode->root;
7411 struct btrfs_log_ctx ctx;
7412 bool log_pinned = false;
7416 * this will force the logging code to walk the dentry chain
7419 if (!S_ISDIR(inode->vfs_inode.i_mode))
7420 inode->last_unlink_trans = trans->transid;
7423 * if this inode hasn't been logged and directory we're renaming it
7424 * from hasn't been logged, we don't need to log it
7426 ret = inode_logged(trans, inode, NULL);
7429 } else if (ret == 0) {
7433 * If the inode was not logged and we are doing a rename (old_dir is not
7434 * NULL), check if old_dir was logged - if it was not we can return and
7437 ret = inode_logged(trans, old_dir, NULL);
7446 * If we are doing a rename (old_dir is not NULL) from a directory that
7447 * was previously logged, make sure that on log replay we get the old
7448 * dir entry deleted. This is needed because we will also log the new
7449 * name of the renamed inode, so we need to make sure that after log
7450 * replay we don't end up with both the new and old dir entries existing.
7452 if (old_dir && old_dir->logged_trans == trans->transid) {
7453 struct btrfs_root *log = old_dir->root->log_root;
7454 struct btrfs_path *path;
7455 struct fscrypt_name fname;
7457 ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
7459 ret = fscrypt_setup_filename(&old_dir->vfs_inode,
7460 &old_dentry->d_name, 0, &fname);
7464 * We have two inodes to update in the log, the old directory and
7465 * the inode that got renamed, so we must pin the log to prevent
7466 * anyone from syncing the log until we have updated both inodes
7469 ret = join_running_log_trans(root);
7471 * At least one of the inodes was logged before, so this should
7472 * not fail, but if it does, it's not serious, just bail out and
7473 * mark the log for a full commit.
7475 if (WARN_ON_ONCE(ret < 0))
7479 path = btrfs_alloc_path();
7482 fscrypt_free_filename(&fname);
7487 * Other concurrent task might be logging the old directory,
7488 * as it can be triggered when logging other inode that had or
7489 * still has a dentry in the old directory. We lock the old
7490 * directory's log_mutex to ensure the deletion of the old
7491 * name is persisted, because during directory logging we
7492 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
7493 * the old name's dir index item is in the delayed items, so
7494 * it could be missed by an in progress directory logging.
7496 mutex_lock(&old_dir->log_mutex);
7497 ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
7498 &fname.disk_name, old_dir_index);
7501 * The dentry does not exist in the log, so record its
7504 btrfs_release_path(path);
7505 ret = insert_dir_log_key(trans, log, path,
7507 old_dir_index, old_dir_index);
7509 mutex_unlock(&old_dir->log_mutex);
7511 btrfs_free_path(path);
7512 fscrypt_free_filename(&fname);
7517 btrfs_init_log_ctx(&ctx, &inode->vfs_inode);
7518 ctx.logging_new_name = true;
7520 * We don't care about the return value. If we fail to log the new name
7521 * then we know the next attempt to sync the log will fallback to a full
7522 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
7523 * we don't need to worry about getting a log committed that has an
7524 * inconsistent state after a rename operation.
7526 btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
7527 ASSERT(list_empty(&ctx.conflict_inodes));
7530 * If an error happened mark the log for a full commit because it's not
7531 * consistent and up to date or we couldn't find out if one of the
7532 * inodes was logged before in this transaction. Do it before unpinning
7533 * the log, to avoid any races with someone else trying to commit it.
7536 btrfs_set_log_full_commit(trans);
7538 btrfs_end_log_trans(root);