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>
17 #include "compression.h"
19 #include "block-group.h"
20 #include "space-info.h"
21 #include "inode-item.h"
23 #include "accessors.h"
24 #include "extent-tree.h"
25 #include "root-tree.h"
27 #include "file-item.h"
30 #include "tree-checker.h"
32 #define MAX_CONFLICT_INODES 10
34 /* magic values for the inode_only field in btrfs_log_inode:
36 * LOG_INODE_ALL means to log everything
37 * LOG_INODE_EXISTS means to log just enough to recreate the inode
46 * directory trouble cases
48 * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
49 * log, we must force a full commit before doing an fsync of the directory
50 * where the unlink was done.
51 * ---> record transid of last unlink/rename per directory
55 * rename foo/some_dir foo2/some_dir
57 * fsync foo/some_dir/some_file
59 * The fsync above will unlink the original some_dir without recording
60 * it in its new location (foo2). After a crash, some_dir will be gone
61 * unless the fsync of some_file forces a full commit
63 * 2) we must log any new names for any file or dir that is in the fsync
64 * log. ---> check inode while renaming/linking.
66 * 2a) we must log any new names for any file or dir during rename
67 * when the directory they are being removed from was logged.
68 * ---> check inode and old parent dir during rename
70 * 2a is actually the more important variant. With the extra logging
71 * a crash might unlink the old name without recreating the new one
73 * 3) after a crash, we must go through any directories with a link count
74 * of zero and redo the rm -rf
81 * The directory f1 was fully removed from the FS, but fsync was never
82 * called on f1, only its parent dir. After a crash the rm -rf must
83 * be replayed. This must be able to recurse down the entire
84 * directory tree. The inode link count fixup code takes care of the
89 * stages for the tree walking. The first
90 * stage (0) is to only pin down the blocks we find
91 * the second stage (1) is to make sure that all the inodes
92 * we find in the log are created in the subvolume.
94 * The last stage is to deal with directories and links and extents
95 * and all the other fun semantics
99 LOG_WALK_REPLAY_INODES,
100 LOG_WALK_REPLAY_DIR_INDEX,
104 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
105 struct btrfs_inode *inode,
107 struct btrfs_log_ctx *ctx);
108 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
109 struct btrfs_root *root,
110 struct btrfs_path *path, u64 objectid);
111 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
112 struct btrfs_root *root,
113 struct btrfs_root *log,
114 struct btrfs_path *path,
115 u64 dirid, int del_all);
116 static void wait_log_commit(struct btrfs_root *root, int transid);
119 * tree logging is a special write ahead log used to make sure that
120 * fsyncs and O_SYNCs can happen without doing full tree commits.
122 * Full tree commits are expensive because they require commonly
123 * modified blocks to be recowed, creating many dirty pages in the
124 * extent tree an 4x-6x higher write load than ext3.
126 * Instead of doing a tree commit on every fsync, we use the
127 * key ranges and transaction ids to find items for a given file or directory
128 * that have changed in this transaction. Those items are copied into
129 * a special tree (one per subvolume root), that tree is written to disk
130 * and then the fsync is considered complete.
132 * After a crash, items are copied out of the log-tree back into the
133 * subvolume tree. Any file data extents found are recorded in the extent
134 * allocation tree, and the log-tree freed.
136 * The log tree is read three times, once to pin down all the extents it is
137 * using in ram and once, once to create all the inodes logged in the tree
138 * and once to do all the other items.
141 static struct btrfs_inode *btrfs_iget_logging(u64 objectid, struct btrfs_root *root)
143 unsigned int nofs_flag;
144 struct btrfs_inode *inode;
146 /* Only meant to be called for subvolume roots and not for log roots. */
147 ASSERT(is_fstree(btrfs_root_id(root)));
150 * We're holding a transaction handle whether we are logging or
151 * replaying a log tree, so we must make sure NOFS semantics apply
152 * because btrfs_alloc_inode() may be triggered and it uses GFP_KERNEL
153 * to allocate an inode, which can recurse back into the filesystem and
154 * attempt a transaction commit, resulting in a deadlock.
156 nofs_flag = memalloc_nofs_save();
157 inode = btrfs_iget(objectid, root);
158 memalloc_nofs_restore(nofs_flag);
164 * start a sub transaction and setup the log tree
165 * this increments the log tree writer count to make the people
166 * syncing the tree wait for us to finish
168 static int start_log_trans(struct btrfs_trans_handle *trans,
169 struct btrfs_root *root,
170 struct btrfs_log_ctx *ctx)
172 struct btrfs_fs_info *fs_info = root->fs_info;
173 struct btrfs_root *tree_root = fs_info->tree_root;
174 const bool zoned = btrfs_is_zoned(fs_info);
176 bool created = false;
179 * First check if the log root tree was already created. If not, create
180 * it before locking the root's log_mutex, just to keep lockdep happy.
182 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
183 mutex_lock(&tree_root->log_mutex);
184 if (!fs_info->log_root_tree) {
185 ret = btrfs_init_log_root_tree(trans, fs_info);
187 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
191 mutex_unlock(&tree_root->log_mutex);
196 mutex_lock(&root->log_mutex);
199 if (root->log_root) {
200 int index = (root->log_transid + 1) % 2;
202 if (btrfs_need_log_full_commit(trans)) {
203 ret = BTRFS_LOG_FORCE_COMMIT;
207 if (zoned && atomic_read(&root->log_commit[index])) {
208 wait_log_commit(root, root->log_transid - 1);
212 if (!root->log_start_pid) {
213 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
214 root->log_start_pid = current->pid;
215 } else if (root->log_start_pid != current->pid) {
216 set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
220 * This means fs_info->log_root_tree was already created
221 * for some other FS trees. Do the full commit not to mix
222 * nodes from multiple log transactions to do sequential
225 if (zoned && !created) {
226 ret = BTRFS_LOG_FORCE_COMMIT;
230 ret = btrfs_add_log_tree(trans, root);
234 set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
235 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
236 root->log_start_pid = current->pid;
239 atomic_inc(&root->log_writers);
240 if (!ctx->logging_new_name) {
241 int index = root->log_transid % 2;
242 list_add_tail(&ctx->list, &root->log_ctxs[index]);
243 ctx->log_transid = root->log_transid;
247 mutex_unlock(&root->log_mutex);
252 * returns 0 if there was a log transaction running and we were able
253 * to join, or returns -ENOENT if there were not transactions
256 static int join_running_log_trans(struct btrfs_root *root)
258 const bool zoned = btrfs_is_zoned(root->fs_info);
261 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
264 mutex_lock(&root->log_mutex);
266 if (root->log_root) {
267 int index = (root->log_transid + 1) % 2;
270 if (zoned && atomic_read(&root->log_commit[index])) {
271 wait_log_commit(root, root->log_transid - 1);
274 atomic_inc(&root->log_writers);
276 mutex_unlock(&root->log_mutex);
281 * This either makes the current running log transaction wait
282 * until you call btrfs_end_log_trans() or it makes any future
283 * log transactions wait until you call btrfs_end_log_trans()
285 void btrfs_pin_log_trans(struct btrfs_root *root)
287 atomic_inc(&root->log_writers);
291 * indicate we're done making changes to the log tree
292 * and wake up anyone waiting to do a sync
294 void btrfs_end_log_trans(struct btrfs_root *root)
296 if (atomic_dec_and_test(&root->log_writers)) {
297 /* atomic_dec_and_test implies a barrier */
298 cond_wake_up_nomb(&root->log_writer_wait);
303 * the walk control struct is used to pass state down the chain when
304 * processing the log tree. The stage field tells us which part
305 * of the log tree processing we are currently doing. The others
306 * are state fields used for that specific part
308 struct walk_control {
309 /* should we free the extent on disk when done? This is used
310 * at transaction commit time while freeing a log tree
314 /* pin only walk, we record which extents on disk belong to the
319 /* what stage of the replay code we're currently in */
323 * Ignore any items from the inode currently being processed. Needs
324 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
325 * the LOG_WALK_REPLAY_INODES stage.
327 bool ignore_cur_inode;
329 /* the root we are currently replaying */
330 struct btrfs_root *replay_dest;
332 /* the trans handle for the current replay */
333 struct btrfs_trans_handle *trans;
335 /* the function that gets used to process blocks we find in the
336 * tree. Note the extent_buffer might not be up to date when it is
337 * passed in, and it must be checked or read if you need the data
340 int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
341 struct walk_control *wc, u64 gen, int level);
345 * process_func used to pin down extents, write them or wait on them
347 static int process_one_buffer(struct btrfs_root *log,
348 struct extent_buffer *eb,
349 struct walk_control *wc, u64 gen, int level)
351 struct btrfs_fs_info *fs_info = log->fs_info;
355 * If this fs is mixed then we need to be able to process the leaves to
356 * pin down any logged extents, so we have to read the block.
358 if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
359 struct btrfs_tree_parent_check check = {
364 ret = btrfs_read_extent_buffer(eb, &check);
370 ret = btrfs_pin_extent_for_log_replay(wc->trans, eb);
374 if (btrfs_buffer_uptodate(eb, gen, 0) &&
375 btrfs_header_level(eb) == 0)
376 ret = btrfs_exclude_logged_extents(eb);
382 * Item overwrite used by log replay. The given eb, slot and key all refer to
383 * the source data we are copying out.
385 * The given root is for the tree we are copying into, and path is a scratch
386 * path for use in this function (it should be released on entry and will be
389 * If the key is already in the destination tree the existing item is
390 * overwritten. If the existing item isn't big enough, it is extended.
391 * If it is too large, it is truncated.
393 * If the key isn't in the destination yet, a new item is inserted.
395 static int overwrite_item(struct btrfs_trans_handle *trans,
396 struct btrfs_root *root,
397 struct btrfs_path *path,
398 struct extent_buffer *eb, int slot,
399 struct btrfs_key *key)
403 u64 saved_i_size = 0;
404 int save_old_i_size = 0;
405 unsigned long src_ptr;
406 unsigned long dst_ptr;
407 struct extent_buffer *dst_eb;
409 bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
412 * This is only used during log replay, so the root is always from a
413 * fs/subvolume tree. In case we ever need to support a log root, then
414 * we'll have to clone the leaf in the path, release the path and use
415 * the leaf before writing into the log tree. See the comments at
416 * copy_items() for more details.
418 ASSERT(btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID);
420 item_size = btrfs_item_size(eb, slot);
421 src_ptr = btrfs_item_ptr_offset(eb, slot);
423 /* Look for the key in the destination tree. */
424 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
428 dst_eb = path->nodes[0];
429 dst_slot = path->slots[0];
433 const u32 dst_size = btrfs_item_size(dst_eb, dst_slot);
435 if (dst_size != item_size)
438 if (item_size == 0) {
439 btrfs_release_path(path);
442 src_copy = kmalloc(item_size, GFP_NOFS);
444 btrfs_release_path(path);
448 read_extent_buffer(eb, src_copy, src_ptr, item_size);
449 dst_ptr = btrfs_item_ptr_offset(dst_eb, dst_slot);
450 ret = memcmp_extent_buffer(dst_eb, src_copy, dst_ptr, item_size);
454 * they have the same contents, just return, this saves
455 * us from cowing blocks in the destination tree and doing
456 * extra writes that may not have been done by a previous
460 btrfs_release_path(path);
465 * We need to load the old nbytes into the inode so when we
466 * replay the extents we've logged we get the right nbytes.
469 struct btrfs_inode_item *item;
473 item = btrfs_item_ptr(dst_eb, dst_slot,
474 struct btrfs_inode_item);
475 nbytes = btrfs_inode_nbytes(dst_eb, item);
476 item = btrfs_item_ptr(eb, slot,
477 struct btrfs_inode_item);
478 btrfs_set_inode_nbytes(eb, item, nbytes);
481 * If this is a directory we need to reset the i_size to
482 * 0 so that we can set it up properly when replaying
483 * the rest of the items in this log.
485 mode = btrfs_inode_mode(eb, item);
487 btrfs_set_inode_size(eb, item, 0);
489 } else if (inode_item) {
490 struct btrfs_inode_item *item;
494 * New inode, set nbytes to 0 so that the nbytes comes out
495 * properly when we replay the extents.
497 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
498 btrfs_set_inode_nbytes(eb, item, 0);
501 * If this is a directory we need to reset the i_size to 0 so
502 * that we can set it up properly when replaying the rest of
503 * the items in this log.
505 mode = btrfs_inode_mode(eb, item);
507 btrfs_set_inode_size(eb, item, 0);
510 btrfs_release_path(path);
511 /* try to insert the key into the destination tree */
512 path->skip_release_on_error = 1;
513 ret = btrfs_insert_empty_item(trans, root, path,
515 path->skip_release_on_error = 0;
517 dst_eb = path->nodes[0];
518 dst_slot = path->slots[0];
520 /* make sure any existing item is the correct size */
521 if (ret == -EEXIST || ret == -EOVERFLOW) {
522 const u32 found_size = btrfs_item_size(dst_eb, dst_slot);
524 if (found_size > item_size)
525 btrfs_truncate_item(trans, path, item_size, 1);
526 else if (found_size < item_size)
527 btrfs_extend_item(trans, path, item_size - found_size);
531 dst_ptr = btrfs_item_ptr_offset(dst_eb, dst_slot);
533 /* don't overwrite an existing inode if the generation number
534 * was logged as zero. This is done when the tree logging code
535 * is just logging an inode to make sure it exists after recovery.
537 * Also, don't overwrite i_size on directories during replay.
538 * log replay inserts and removes directory items based on the
539 * state of the tree found in the subvolume, and i_size is modified
542 if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
543 struct btrfs_inode_item *src_item;
544 struct btrfs_inode_item *dst_item;
546 src_item = (struct btrfs_inode_item *)src_ptr;
547 dst_item = (struct btrfs_inode_item *)dst_ptr;
549 if (btrfs_inode_generation(eb, src_item) == 0) {
550 const u64 ino_size = btrfs_inode_size(eb, src_item);
553 * For regular files an ino_size == 0 is used only when
554 * logging that an inode exists, as part of a directory
555 * fsync, and the inode wasn't fsynced before. In this
556 * case don't set the size of the inode in the fs/subvol
557 * tree, otherwise we would be throwing valid data away.
559 if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
560 S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
562 btrfs_set_inode_size(dst_eb, dst_item, ino_size);
566 if (S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
567 S_ISDIR(btrfs_inode_mode(dst_eb, dst_item))) {
569 saved_i_size = btrfs_inode_size(dst_eb, dst_item);
573 copy_extent_buffer(dst_eb, eb, dst_ptr, src_ptr, item_size);
575 if (save_old_i_size) {
576 struct btrfs_inode_item *dst_item;
578 dst_item = (struct btrfs_inode_item *)dst_ptr;
579 btrfs_set_inode_size(dst_eb, dst_item, saved_i_size);
582 /* make sure the generation is filled in */
583 if (key->type == BTRFS_INODE_ITEM_KEY) {
584 struct btrfs_inode_item *dst_item;
586 dst_item = (struct btrfs_inode_item *)dst_ptr;
587 if (btrfs_inode_generation(dst_eb, dst_item) == 0)
588 btrfs_set_inode_generation(dst_eb, dst_item, trans->transid);
591 btrfs_release_path(path);
595 static int read_alloc_one_name(struct extent_buffer *eb, void *start, int len,
596 struct fscrypt_str *name)
600 buf = kmalloc(len, GFP_NOFS);
604 read_extent_buffer(eb, buf, (unsigned long)start, len);
610 /* replays a single extent in 'eb' at 'slot' with 'key' into the
611 * subvolume 'root'. path is released on entry and should be released
614 * extents in the log tree have not been allocated out of the extent
615 * tree yet. So, this completes the allocation, taking a reference
616 * as required if the extent already exists or creating a new extent
617 * if it isn't in the extent allocation tree yet.
619 * The extent is inserted into the file, dropping any existing extents
620 * from the file that overlap the new one.
622 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
623 struct btrfs_root *root,
624 struct btrfs_path *path,
625 struct extent_buffer *eb, int slot,
626 struct btrfs_key *key)
628 struct btrfs_drop_extents_args drop_args = { 0 };
629 struct btrfs_fs_info *fs_info = root->fs_info;
632 u64 start = key->offset;
634 struct btrfs_file_extent_item *item;
635 struct btrfs_inode *inode = NULL;
639 item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
640 found_type = btrfs_file_extent_type(eb, item);
642 if (found_type == BTRFS_FILE_EXTENT_REG ||
643 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
644 nbytes = btrfs_file_extent_num_bytes(eb, item);
645 extent_end = start + nbytes;
648 * We don't add to the inodes nbytes if we are prealloc or a
651 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
653 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
654 size = btrfs_file_extent_ram_bytes(eb, item);
655 nbytes = btrfs_file_extent_ram_bytes(eb, item);
656 extent_end = ALIGN(start + size,
657 fs_info->sectorsize);
660 "unexpected extent type=%d root=%llu inode=%llu offset=%llu",
661 found_type, btrfs_root_id(root), key->objectid, key->offset);
665 inode = btrfs_iget_logging(key->objectid, root);
667 return PTR_ERR(inode);
670 * first check to see if we already have this extent in the
671 * file. This must be done before the btrfs_drop_extents run
672 * so we don't try to drop this extent.
674 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode), start, 0);
677 (found_type == BTRFS_FILE_EXTENT_REG ||
678 found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
679 struct btrfs_file_extent_item existing;
682 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
683 read_extent_buffer(path->nodes[0], &existing, ptr, sizeof(existing));
686 * we already have a pointer to this exact extent,
687 * we don't have to do anything
689 if (memcmp_extent_buffer(eb, &existing, (unsigned long)item,
690 sizeof(existing)) == 0) {
691 btrfs_release_path(path);
695 btrfs_release_path(path);
697 /* drop any overlapping extents */
698 drop_args.start = start;
699 drop_args.end = extent_end;
700 drop_args.drop_cache = true;
701 ret = btrfs_drop_extents(trans, root, inode, &drop_args);
705 if (found_type == BTRFS_FILE_EXTENT_REG ||
706 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
708 unsigned long dest_offset;
709 struct btrfs_key ins;
711 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
712 btrfs_fs_incompat(fs_info, NO_HOLES))
715 ret = btrfs_insert_empty_item(trans, root, path, key,
719 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
721 copy_extent_buffer(path->nodes[0], eb, dest_offset,
722 (unsigned long)item, sizeof(*item));
724 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
725 ins.type = BTRFS_EXTENT_ITEM_KEY;
726 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
727 offset = key->offset - btrfs_file_extent_offset(eb, item);
730 * Manually record dirty extent, as here we did a shallow
731 * file extent item copy and skip normal backref update,
732 * but modifying extent tree all by ourselves.
733 * So need to manually record dirty extent for qgroup,
734 * as the owner of the file extent changed from log tree
735 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
737 ret = btrfs_qgroup_trace_extent(trans,
738 btrfs_file_extent_disk_bytenr(eb, item),
739 btrfs_file_extent_disk_num_bytes(eb, item));
743 if (ins.objectid > 0) {
746 LIST_HEAD(ordered_sums);
749 * is this extent already allocated in the extent
750 * allocation tree? If so, just add a reference
752 ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
756 } else if (ret == 0) {
757 struct btrfs_ref ref = {
758 .action = BTRFS_ADD_DELAYED_REF,
759 .bytenr = ins.objectid,
760 .num_bytes = ins.offset,
761 .owning_root = btrfs_root_id(root),
762 .ref_root = btrfs_root_id(root),
764 btrfs_init_data_ref(&ref, key->objectid, offset,
766 ret = btrfs_inc_extent_ref(trans, &ref);
771 * insert the extent pointer in the extent
774 ret = btrfs_alloc_logged_file_extent(trans,
776 key->objectid, offset, &ins);
780 btrfs_release_path(path);
782 if (btrfs_file_extent_compression(eb, item)) {
783 csum_start = ins.objectid;
784 csum_end = csum_start + ins.offset;
786 csum_start = ins.objectid +
787 btrfs_file_extent_offset(eb, item);
788 csum_end = csum_start +
789 btrfs_file_extent_num_bytes(eb, item);
792 ret = btrfs_lookup_csums_list(root->log_root,
793 csum_start, csum_end - 1,
794 &ordered_sums, false);
799 * Now delete all existing cums in the csum root that
800 * cover our range. We do this because we can have an
801 * extent that is completely referenced by one file
802 * extent item and partially referenced by another
803 * file extent item (like after using the clone or
804 * extent_same ioctls). In this case if we end up doing
805 * the replay of the one that partially references the
806 * extent first, and we do not do the csum deletion
807 * below, we can get 2 csum items in the csum tree that
808 * overlap each other. For example, imagine our log has
809 * the two following file extent items:
811 * key (257 EXTENT_DATA 409600)
812 * extent data disk byte 12845056 nr 102400
813 * extent data offset 20480 nr 20480 ram 102400
815 * key (257 EXTENT_DATA 819200)
816 * extent data disk byte 12845056 nr 102400
817 * extent data offset 0 nr 102400 ram 102400
819 * Where the second one fully references the 100K extent
820 * that starts at disk byte 12845056, and the log tree
821 * has a single csum item that covers the entire range
824 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
826 * After the first file extent item is replayed, the
827 * csum tree gets the following csum item:
829 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
831 * Which covers the 20K sub-range starting at offset 20K
832 * of our extent. Now when we replay the second file
833 * extent item, if we do not delete existing csum items
834 * that cover any of its blocks, we end up getting two
835 * csum items in our csum tree that overlap each other:
837 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
838 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
840 * Which is a problem, because after this anyone trying
841 * to lookup up for the checksum of any block of our
842 * extent starting at an offset of 40K or higher, will
843 * end up looking at the second csum item only, which
844 * does not contain the checksum for any block starting
845 * at offset 40K or higher of our extent.
847 while (!list_empty(&ordered_sums)) {
848 struct btrfs_ordered_sum *sums;
849 struct btrfs_root *csum_root;
851 sums = list_first_entry(&ordered_sums,
852 struct btrfs_ordered_sum,
854 csum_root = btrfs_csum_root(fs_info,
857 ret = btrfs_del_csums(trans, csum_root,
861 ret = btrfs_csum_file_blocks(trans,
864 list_del(&sums->list);
870 btrfs_release_path(path);
872 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
873 /* inline extents are easy, we just overwrite them */
874 ret = overwrite_item(trans, root, path, eb, slot, key);
879 ret = btrfs_inode_set_file_extent_range(inode, start, extent_end - start);
884 btrfs_update_inode_bytes(inode, nbytes, drop_args.bytes_found);
885 ret = btrfs_update_inode(trans, inode);
887 iput(&inode->vfs_inode);
891 static int unlink_inode_for_log_replay(struct btrfs_trans_handle *trans,
892 struct btrfs_inode *dir,
893 struct btrfs_inode *inode,
894 const struct fscrypt_str *name)
898 ret = btrfs_unlink_inode(trans, dir, inode, name);
902 * Whenever we need to check if a name exists or not, we check the
903 * fs/subvolume tree. So after an unlink we must run delayed items, so
904 * that future checks for a name during log replay see that the name
905 * does not exists anymore.
907 return btrfs_run_delayed_items(trans);
911 * when cleaning up conflicts between the directory names in the
912 * subvolume, directory names in the log and directory names in the
913 * inode back references, we may have to unlink inodes from directories.
915 * This is a helper function to do the unlink of a specific directory
918 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
919 struct btrfs_path *path,
920 struct btrfs_inode *dir,
921 struct btrfs_dir_item *di)
923 struct btrfs_root *root = dir->root;
924 struct btrfs_inode *inode;
925 struct fscrypt_str name;
926 struct extent_buffer *leaf;
927 struct btrfs_key location;
930 leaf = path->nodes[0];
932 btrfs_dir_item_key_to_cpu(leaf, di, &location);
933 ret = read_alloc_one_name(leaf, di + 1, btrfs_dir_name_len(leaf, di), &name);
937 btrfs_release_path(path);
939 inode = btrfs_iget_logging(location.objectid, root);
941 ret = PTR_ERR(inode);
946 ret = link_to_fixup_dir(trans, root, path, location.objectid);
950 ret = unlink_inode_for_log_replay(trans, dir, inode, &name);
954 iput(&inode->vfs_inode);
959 * See if a given name and sequence number found in an inode back reference are
960 * already in a directory and correctly point to this inode.
962 * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
965 static noinline int inode_in_dir(struct btrfs_root *root,
966 struct btrfs_path *path,
967 u64 dirid, u64 objectid, u64 index,
968 struct fscrypt_str *name)
970 struct btrfs_dir_item *di;
971 struct btrfs_key location;
974 di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
980 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
981 if (location.objectid != objectid)
987 btrfs_release_path(path);
988 di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, 0);
993 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
994 if (location.objectid == objectid)
998 btrfs_release_path(path);
1003 * helper function to check a log tree for a named back reference in
1004 * an inode. This is used to decide if a back reference that is
1005 * found in the subvolume conflicts with what we find in the log.
1007 * inode backreferences may have multiple refs in a single item,
1008 * during replay we process one reference at a time, and we don't
1009 * want to delete valid links to a file from the subvolume if that
1010 * link is also in the log.
1012 static noinline int backref_in_log(struct btrfs_root *log,
1013 struct btrfs_key *key,
1015 const struct fscrypt_str *name)
1017 struct btrfs_path *path;
1020 path = btrfs_alloc_path();
1024 ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1027 } else if (ret == 1) {
1032 if (key->type == BTRFS_INODE_EXTREF_KEY)
1033 ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
1035 ref_objectid, name);
1037 ret = !!btrfs_find_name_in_backref(path->nodes[0],
1038 path->slots[0], name);
1040 btrfs_free_path(path);
1044 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
1045 struct btrfs_root *root,
1046 struct btrfs_path *path,
1047 struct btrfs_root *log_root,
1048 struct btrfs_inode *dir,
1049 struct btrfs_inode *inode,
1050 u64 inode_objectid, u64 parent_objectid,
1051 u64 ref_index, struct fscrypt_str *name)
1054 struct extent_buffer *leaf;
1055 struct btrfs_dir_item *di;
1056 struct btrfs_key search_key;
1057 struct btrfs_inode_extref *extref;
1060 /* Search old style refs */
1061 search_key.objectid = inode_objectid;
1062 search_key.type = BTRFS_INODE_REF_KEY;
1063 search_key.offset = parent_objectid;
1064 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1067 } else if (ret == 0) {
1068 struct btrfs_inode_ref *victim_ref;
1070 unsigned long ptr_end;
1072 leaf = path->nodes[0];
1074 /* are we trying to overwrite a back ref for the root directory
1075 * if so, just jump out, we're done
1077 if (search_key.objectid == search_key.offset)
1080 /* check all the names in this back reference to see
1081 * if they are in the log. if so, we allow them to stay
1082 * otherwise they must be unlinked as a conflict
1084 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1085 ptr_end = ptr + btrfs_item_size(leaf, path->slots[0]);
1086 while (ptr < ptr_end) {
1087 struct fscrypt_str victim_name;
1089 victim_ref = (struct btrfs_inode_ref *)ptr;
1090 ret = read_alloc_one_name(leaf, (victim_ref + 1),
1091 btrfs_inode_ref_name_len(leaf, victim_ref),
1096 ret = backref_in_log(log_root, &search_key,
1097 parent_objectid, &victim_name);
1099 kfree(victim_name.name);
1102 inc_nlink(&inode->vfs_inode);
1103 btrfs_release_path(path);
1105 ret = unlink_inode_for_log_replay(trans, dir, inode,
1107 kfree(victim_name.name);
1112 kfree(victim_name.name);
1114 ptr = (unsigned long)(victim_ref + 1) + victim_name.len;
1117 btrfs_release_path(path);
1119 /* Same search but for extended refs */
1120 extref = btrfs_lookup_inode_extref(NULL, root, path, name,
1121 inode_objectid, parent_objectid, 0,
1123 if (IS_ERR(extref)) {
1124 return PTR_ERR(extref);
1125 } else if (extref) {
1129 struct btrfs_inode *victim_parent;
1131 leaf = path->nodes[0];
1133 item_size = btrfs_item_size(leaf, path->slots[0]);
1134 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1136 while (cur_offset < item_size) {
1137 struct fscrypt_str victim_name;
1139 extref = (struct btrfs_inode_extref *)(base + cur_offset);
1140 victim_name.len = btrfs_inode_extref_name_len(leaf, extref);
1142 if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1145 ret = read_alloc_one_name(leaf, &extref->name,
1146 victim_name.len, &victim_name);
1150 search_key.objectid = inode_objectid;
1151 search_key.type = BTRFS_INODE_EXTREF_KEY;
1152 search_key.offset = btrfs_extref_hash(parent_objectid,
1155 ret = backref_in_log(log_root, &search_key,
1156 parent_objectid, &victim_name);
1158 kfree(victim_name.name);
1161 victim_parent = btrfs_iget_logging(parent_objectid, root);
1162 if (IS_ERR(victim_parent)) {
1163 ret = PTR_ERR(victim_parent);
1165 inc_nlink(&inode->vfs_inode);
1166 btrfs_release_path(path);
1168 ret = unlink_inode_for_log_replay(trans,
1170 inode, &victim_name);
1171 iput(&victim_parent->vfs_inode);
1173 kfree(victim_name.name);
1178 kfree(victim_name.name);
1180 cur_offset += victim_name.len + sizeof(*extref);
1183 btrfs_release_path(path);
1185 /* look for a conflicting sequence number */
1186 di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1187 ref_index, name, 0);
1191 ret = drop_one_dir_item(trans, path, dir, di);
1195 btrfs_release_path(path);
1197 /* look for a conflicting name */
1198 di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir), name, 0);
1202 ret = drop_one_dir_item(trans, path, dir, di);
1206 btrfs_release_path(path);
1211 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1212 struct fscrypt_str *name, u64 *index,
1213 u64 *parent_objectid)
1215 struct btrfs_inode_extref *extref;
1218 extref = (struct btrfs_inode_extref *)ref_ptr;
1220 ret = read_alloc_one_name(eb, &extref->name,
1221 btrfs_inode_extref_name_len(eb, extref), name);
1226 *index = btrfs_inode_extref_index(eb, extref);
1227 if (parent_objectid)
1228 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1233 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1234 struct fscrypt_str *name, u64 *index)
1236 struct btrfs_inode_ref *ref;
1239 ref = (struct btrfs_inode_ref *)ref_ptr;
1241 ret = read_alloc_one_name(eb, ref + 1, btrfs_inode_ref_name_len(eb, ref),
1247 *index = btrfs_inode_ref_index(eb, ref);
1253 * Take an inode reference item from the log tree and iterate all names from the
1254 * inode reference item in the subvolume tree with the same key (if it exists).
1255 * For any name that is not in the inode reference item from the log tree, do a
1256 * proper unlink of that name (that is, remove its entry from the inode
1257 * reference item and both dir index keys).
1259 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1260 struct btrfs_root *root,
1261 struct btrfs_path *path,
1262 struct btrfs_inode *inode,
1263 struct extent_buffer *log_eb,
1265 struct btrfs_key *key)
1268 unsigned long ref_ptr;
1269 unsigned long ref_end;
1270 struct extent_buffer *eb;
1273 btrfs_release_path(path);
1274 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1282 eb = path->nodes[0];
1283 ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1284 ref_end = ref_ptr + btrfs_item_size(eb, path->slots[0]);
1285 while (ref_ptr < ref_end) {
1286 struct fscrypt_str name;
1289 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1290 ret = extref_get_fields(eb, ref_ptr, &name,
1293 parent_id = key->offset;
1294 ret = ref_get_fields(eb, ref_ptr, &name, NULL);
1299 if (key->type == BTRFS_INODE_EXTREF_KEY)
1300 ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
1303 ret = !!btrfs_find_name_in_backref(log_eb, log_slot, &name);
1306 struct btrfs_inode *dir;
1308 btrfs_release_path(path);
1309 dir = btrfs_iget_logging(parent_id, root);
1315 ret = unlink_inode_for_log_replay(trans, dir, inode, &name);
1317 iput(&dir->vfs_inode);
1324 ref_ptr += name.len;
1325 if (key->type == BTRFS_INODE_EXTREF_KEY)
1326 ref_ptr += sizeof(struct btrfs_inode_extref);
1328 ref_ptr += sizeof(struct btrfs_inode_ref);
1332 btrfs_release_path(path);
1337 * replay one inode back reference item found in the log tree.
1338 * eb, slot and key refer to the buffer and key found in the log tree.
1339 * root is the destination we are replaying into, and path is for temp
1340 * use by this function. (it should be released on return).
1342 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1343 struct btrfs_root *root,
1344 struct btrfs_root *log,
1345 struct btrfs_path *path,
1346 struct extent_buffer *eb, int slot,
1347 struct btrfs_key *key)
1349 struct btrfs_inode *dir = NULL;
1350 struct btrfs_inode *inode = NULL;
1351 unsigned long ref_ptr;
1352 unsigned long ref_end;
1353 struct fscrypt_str name = { 0 };
1355 int log_ref_ver = 0;
1356 u64 parent_objectid;
1359 int ref_struct_size;
1361 ref_ptr = btrfs_item_ptr_offset(eb, slot);
1362 ref_end = ref_ptr + btrfs_item_size(eb, slot);
1364 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1365 struct btrfs_inode_extref *r;
1367 ref_struct_size = sizeof(struct btrfs_inode_extref);
1369 r = (struct btrfs_inode_extref *)ref_ptr;
1370 parent_objectid = btrfs_inode_extref_parent(eb, r);
1372 ref_struct_size = sizeof(struct btrfs_inode_ref);
1373 parent_objectid = key->offset;
1375 inode_objectid = key->objectid;
1378 * it is possible that we didn't log all the parent directories
1379 * for a given inode. If we don't find the dir, just don't
1380 * copy the back ref in. The link count fixup code will take
1383 dir = btrfs_iget_logging(parent_objectid, root);
1390 inode = btrfs_iget_logging(inode_objectid, root);
1391 if (IS_ERR(inode)) {
1392 ret = PTR_ERR(inode);
1397 while (ref_ptr < ref_end) {
1399 ret = extref_get_fields(eb, ref_ptr, &name,
1400 &ref_index, &parent_objectid);
1402 * parent object can change from one array
1406 dir = btrfs_iget_logging(parent_objectid, root);
1414 ret = ref_get_fields(eb, ref_ptr, &name, &ref_index);
1419 ret = inode_in_dir(root, path, btrfs_ino(dir), btrfs_ino(inode),
1423 } else if (ret == 0) {
1425 * look for a conflicting back reference in the
1426 * metadata. if we find one we have to unlink that name
1427 * of the file before we add our new link. Later on, we
1428 * overwrite any existing back reference, and we don't
1429 * want to create dangling pointers in the directory.
1431 ret = __add_inode_ref(trans, root, path, log, dir, inode,
1432 inode_objectid, parent_objectid,
1440 /* insert our name */
1441 ret = btrfs_add_link(trans, dir, inode, &name, 0, ref_index);
1445 ret = btrfs_update_inode(trans, inode);
1449 /* Else, ret == 1, we already have a perfect match, we're done. */
1451 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + name.len;
1455 iput(&dir->vfs_inode);
1461 * Before we overwrite the inode reference item in the subvolume tree
1462 * with the item from the log tree, we must unlink all names from the
1463 * parent directory that are in the subvolume's tree inode reference
1464 * item, otherwise we end up with an inconsistent subvolume tree where
1465 * dir index entries exist for a name but there is no inode reference
1466 * item with the same name.
1468 ret = unlink_old_inode_refs(trans, root, path, inode, eb, slot, key);
1472 /* finally write the back reference in the inode */
1473 ret = overwrite_item(trans, root, path, eb, slot, key);
1475 btrfs_release_path(path);
1478 iput(&dir->vfs_inode);
1480 iput(&inode->vfs_inode);
1484 static int count_inode_extrefs(struct btrfs_inode *inode, struct btrfs_path *path)
1488 unsigned int nlink = 0;
1491 u64 inode_objectid = btrfs_ino(inode);
1494 struct btrfs_inode_extref *extref;
1495 struct extent_buffer *leaf;
1498 ret = btrfs_find_one_extref(inode->root, inode_objectid, offset,
1499 path, &extref, &offset);
1503 leaf = path->nodes[0];
1504 item_size = btrfs_item_size(leaf, path->slots[0]);
1505 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1508 while (cur_offset < item_size) {
1509 extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1510 name_len = btrfs_inode_extref_name_len(leaf, extref);
1514 cur_offset += name_len + sizeof(*extref);
1518 btrfs_release_path(path);
1520 btrfs_release_path(path);
1522 if (ret < 0 && ret != -ENOENT)
1527 static int count_inode_refs(struct btrfs_inode *inode, struct btrfs_path *path)
1530 struct btrfs_key key;
1531 unsigned int nlink = 0;
1533 unsigned long ptr_end;
1535 u64 ino = btrfs_ino(inode);
1538 key.type = BTRFS_INODE_REF_KEY;
1539 key.offset = (u64)-1;
1542 ret = btrfs_search_slot(NULL, inode->root, &key, path, 0, 0);
1546 if (path->slots[0] == 0)
1551 btrfs_item_key_to_cpu(path->nodes[0], &key,
1553 if (key.objectid != ino ||
1554 key.type != BTRFS_INODE_REF_KEY)
1556 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1557 ptr_end = ptr + btrfs_item_size(path->nodes[0],
1559 while (ptr < ptr_end) {
1560 struct btrfs_inode_ref *ref;
1562 ref = (struct btrfs_inode_ref *)ptr;
1563 name_len = btrfs_inode_ref_name_len(path->nodes[0],
1565 ptr = (unsigned long)(ref + 1) + name_len;
1569 if (key.offset == 0)
1571 if (path->slots[0] > 0) {
1576 btrfs_release_path(path);
1578 btrfs_release_path(path);
1584 * There are a few corners where the link count of the file can't
1585 * be properly maintained during replay. So, instead of adding
1586 * lots of complexity to the log code, we just scan the backrefs
1587 * for any file that has been through replay.
1589 * The scan will update the link count on the inode to reflect the
1590 * number of back refs found. If it goes down to zero, the iput
1591 * will free the inode.
1593 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1594 struct btrfs_inode *inode)
1596 struct btrfs_root *root = inode->root;
1597 struct btrfs_path *path;
1600 const u64 ino = btrfs_ino(inode);
1602 path = btrfs_alloc_path();
1606 ret = count_inode_refs(inode, path);
1612 ret = count_inode_extrefs(inode, path);
1620 if (nlink != inode->vfs_inode.i_nlink) {
1621 set_nlink(&inode->vfs_inode, nlink);
1622 ret = btrfs_update_inode(trans, inode);
1626 if (S_ISDIR(inode->vfs_inode.i_mode))
1627 inode->index_cnt = (u64)-1;
1629 if (inode->vfs_inode.i_nlink == 0) {
1630 if (S_ISDIR(inode->vfs_inode.i_mode)) {
1631 ret = replay_dir_deletes(trans, root, NULL, path,
1636 ret = btrfs_insert_orphan_item(trans, root, ino);
1642 btrfs_free_path(path);
1646 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1647 struct btrfs_root *root,
1648 struct btrfs_path *path)
1651 struct btrfs_key key;
1653 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1654 key.type = BTRFS_ORPHAN_ITEM_KEY;
1655 key.offset = (u64)-1;
1657 struct btrfs_inode *inode;
1659 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1665 if (path->slots[0] == 0)
1670 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1671 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1672 key.type != BTRFS_ORPHAN_ITEM_KEY)
1675 ret = btrfs_del_item(trans, root, path);
1679 btrfs_release_path(path);
1680 inode = btrfs_iget_logging(key.offset, root);
1681 if (IS_ERR(inode)) {
1682 ret = PTR_ERR(inode);
1686 ret = fixup_inode_link_count(trans, inode);
1687 iput(&inode->vfs_inode);
1692 * fixup on a directory may create new entries,
1693 * make sure we always look for the highset possible
1696 key.offset = (u64)-1;
1698 btrfs_release_path(path);
1704 * record a given inode in the fixup dir so we can check its link
1705 * count when replay is done. The link count is incremented here
1706 * so the inode won't go away until we check it
1708 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1709 struct btrfs_root *root,
1710 struct btrfs_path *path,
1713 struct btrfs_key key;
1715 struct btrfs_inode *inode;
1716 struct inode *vfs_inode;
1718 inode = btrfs_iget_logging(objectid, root);
1720 return PTR_ERR(inode);
1722 vfs_inode = &inode->vfs_inode;
1723 key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1724 key.type = BTRFS_ORPHAN_ITEM_KEY;
1725 key.offset = objectid;
1727 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1729 btrfs_release_path(path);
1731 if (!vfs_inode->i_nlink)
1732 set_nlink(vfs_inode, 1);
1734 inc_nlink(vfs_inode);
1735 ret = btrfs_update_inode(trans, inode);
1736 } else if (ret == -EEXIST) {
1745 * when replaying the log for a directory, we only insert names
1746 * for inodes that actually exist. This means an fsync on a directory
1747 * does not implicitly fsync all the new files in it
1749 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1750 struct btrfs_root *root,
1751 u64 dirid, u64 index,
1752 const struct fscrypt_str *name,
1753 struct btrfs_key *location)
1755 struct btrfs_inode *inode;
1756 struct btrfs_inode *dir;
1759 inode = btrfs_iget_logging(location->objectid, root);
1761 return PTR_ERR(inode);
1763 dir = btrfs_iget_logging(dirid, root);
1765 iput(&inode->vfs_inode);
1766 return PTR_ERR(dir);
1769 ret = btrfs_add_link(trans, dir, inode, name, 1, index);
1771 /* FIXME, put inode into FIXUP list */
1773 iput(&inode->vfs_inode);
1774 iput(&dir->vfs_inode);
1778 static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
1779 struct btrfs_inode *dir,
1780 struct btrfs_path *path,
1781 struct btrfs_dir_item *dst_di,
1782 const struct btrfs_key *log_key,
1786 struct btrfs_key found_key;
1788 btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1789 /* The existing dentry points to the same inode, don't delete it. */
1790 if (found_key.objectid == log_key->objectid &&
1791 found_key.type == log_key->type &&
1792 found_key.offset == log_key->offset &&
1793 btrfs_dir_flags(path->nodes[0], dst_di) == log_flags)
1797 * Don't drop the conflicting directory entry if the inode for the new
1798 * entry doesn't exist.
1803 return drop_one_dir_item(trans, path, dir, dst_di);
1807 * take a single entry in a log directory item and replay it into
1810 * if a conflicting item exists in the subdirectory already,
1811 * the inode it points to is unlinked and put into the link count
1814 * If a name from the log points to a file or directory that does
1815 * not exist in the FS, it is skipped. fsyncs on directories
1816 * do not force down inodes inside that directory, just changes to the
1817 * names or unlinks in a directory.
1819 * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1820 * non-existing inode) and 1 if the name was replayed.
1822 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1823 struct btrfs_root *root,
1824 struct btrfs_path *path,
1825 struct extent_buffer *eb,
1826 struct btrfs_dir_item *di,
1827 struct btrfs_key *key)
1829 struct fscrypt_str name = { 0 };
1830 struct btrfs_dir_item *dir_dst_di;
1831 struct btrfs_dir_item *index_dst_di;
1832 bool dir_dst_matches = false;
1833 bool index_dst_matches = false;
1834 struct btrfs_key log_key;
1835 struct btrfs_key search_key;
1836 struct btrfs_inode *dir;
1840 bool update_size = true;
1841 bool name_added = false;
1843 dir = btrfs_iget_logging(key->objectid, root);
1845 return PTR_ERR(dir);
1847 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
1851 log_flags = btrfs_dir_flags(eb, di);
1852 btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1853 ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1854 btrfs_release_path(path);
1857 exists = (ret == 0);
1860 dir_dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1862 if (IS_ERR(dir_dst_di)) {
1863 ret = PTR_ERR(dir_dst_di);
1865 } else if (dir_dst_di) {
1866 ret = delete_conflicting_dir_entry(trans, dir, path, dir_dst_di,
1867 &log_key, log_flags, exists);
1870 dir_dst_matches = (ret == 1);
1873 btrfs_release_path(path);
1875 index_dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1876 key->objectid, key->offset,
1878 if (IS_ERR(index_dst_di)) {
1879 ret = PTR_ERR(index_dst_di);
1881 } else if (index_dst_di) {
1882 ret = delete_conflicting_dir_entry(trans, dir, path, index_dst_di,
1883 &log_key, log_flags, exists);
1886 index_dst_matches = (ret == 1);
1889 btrfs_release_path(path);
1891 if (dir_dst_matches && index_dst_matches) {
1893 update_size = false;
1898 * Check if the inode reference exists in the log for the given name,
1899 * inode and parent inode
1901 search_key.objectid = log_key.objectid;
1902 search_key.type = BTRFS_INODE_REF_KEY;
1903 search_key.offset = key->objectid;
1904 ret = backref_in_log(root->log_root, &search_key, 0, &name);
1908 /* The dentry will be added later. */
1910 update_size = false;
1914 search_key.objectid = log_key.objectid;
1915 search_key.type = BTRFS_INODE_EXTREF_KEY;
1916 search_key.offset = key->objectid;
1917 ret = backref_in_log(root->log_root, &search_key, key->objectid, &name);
1921 /* The dentry will be added later. */
1923 update_size = false;
1926 btrfs_release_path(path);
1927 ret = insert_one_name(trans, root, key->objectid, key->offset,
1929 if (ret && ret != -ENOENT && ret != -EEXIST)
1933 update_size = false;
1937 if (!ret && update_size) {
1938 btrfs_i_size_write(dir, dir->vfs_inode.i_size + name.len * 2);
1939 ret = btrfs_update_inode(trans, dir);
1942 iput(&dir->vfs_inode);
1943 if (!ret && name_added)
1948 /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
1949 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1950 struct btrfs_root *root,
1951 struct btrfs_path *path,
1952 struct extent_buffer *eb, int slot,
1953 struct btrfs_key *key)
1956 struct btrfs_dir_item *di;
1958 /* We only log dir index keys, which only contain a single dir item. */
1959 ASSERT(key->type == BTRFS_DIR_INDEX_KEY);
1961 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1962 ret = replay_one_name(trans, root, path, eb, di, key);
1967 * If this entry refers to a non-directory (directories can not have a
1968 * link count > 1) and it was added in the transaction that was not
1969 * committed, make sure we fixup the link count of the inode the entry
1970 * points to. Otherwise something like the following would result in a
1971 * directory pointing to an inode with a wrong link that does not account
1972 * for this dir entry:
1979 * ln testdir/bar testdir/bar_link
1980 * ln testdir/foo testdir/foo_link
1981 * xfs_io -c "fsync" testdir/bar
1985 * mount fs, log replay happens
1987 * File foo would remain with a link count of 1 when it has two entries
1988 * pointing to it in the directory testdir. This would make it impossible
1989 * to ever delete the parent directory has it would result in stale
1990 * dentries that can never be deleted.
1992 if (ret == 1 && btrfs_dir_ftype(eb, di) != BTRFS_FT_DIR) {
1993 struct btrfs_path *fixup_path;
1994 struct btrfs_key di_key;
1996 fixup_path = btrfs_alloc_path();
2000 btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2001 ret = link_to_fixup_dir(trans, root, fixup_path, di_key.objectid);
2002 btrfs_free_path(fixup_path);
2009 * directory replay has two parts. There are the standard directory
2010 * items in the log copied from the subvolume, and range items
2011 * created in the log while the subvolume was logged.
2013 * The range items tell us which parts of the key space the log
2014 * is authoritative for. During replay, if a key in the subvolume
2015 * directory is in a logged range item, but not actually in the log
2016 * that means it was deleted from the directory before the fsync
2017 * and should be removed.
2019 static noinline int find_dir_range(struct btrfs_root *root,
2020 struct btrfs_path *path,
2022 u64 *start_ret, u64 *end_ret)
2024 struct btrfs_key key;
2026 struct btrfs_dir_log_item *item;
2030 if (*start_ret == (u64)-1)
2033 key.objectid = dirid;
2034 key.type = BTRFS_DIR_LOG_INDEX_KEY;
2035 key.offset = *start_ret;
2037 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2041 if (path->slots[0] == 0)
2046 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2048 if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2052 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2053 struct btrfs_dir_log_item);
2054 found_end = btrfs_dir_log_end(path->nodes[0], item);
2056 if (*start_ret >= key.offset && *start_ret <= found_end) {
2058 *start_ret = key.offset;
2059 *end_ret = found_end;
2064 /* check the next slot in the tree to see if it is a valid item */
2065 nritems = btrfs_header_nritems(path->nodes[0]);
2067 if (path->slots[0] >= nritems) {
2068 ret = btrfs_next_leaf(root, path);
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);
2082 *start_ret = key.offset;
2083 *end_ret = found_end;
2086 btrfs_release_path(path);
2091 * this looks for a given directory item in the log. If the directory
2092 * item is not in the log, the item is removed and the inode it points
2095 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2096 struct btrfs_root *log,
2097 struct btrfs_path *path,
2098 struct btrfs_path *log_path,
2099 struct btrfs_inode *dir,
2100 struct btrfs_key *dir_key)
2102 struct btrfs_root *root = dir->root;
2104 struct extent_buffer *eb;
2106 struct btrfs_dir_item *di;
2107 struct fscrypt_str name = { 0 };
2108 struct btrfs_inode *inode = NULL;
2109 struct btrfs_key location;
2112 * Currently we only log dir index keys. Even if we replay a log created
2113 * by an older kernel that logged both dir index and dir item keys, all
2114 * we need to do is process the dir index keys, we (and our caller) can
2115 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2117 ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY);
2119 eb = path->nodes[0];
2120 slot = path->slots[0];
2121 di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2122 ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
2127 struct btrfs_dir_item *log_di;
2129 log_di = btrfs_lookup_dir_index_item(trans, log, log_path,
2131 dir_key->offset, &name, 0);
2132 if (IS_ERR(log_di)) {
2133 ret = PTR_ERR(log_di);
2135 } else if (log_di) {
2136 /* The dentry exists in the log, we have nothing to do. */
2142 btrfs_dir_item_key_to_cpu(eb, di, &location);
2143 btrfs_release_path(path);
2144 btrfs_release_path(log_path);
2145 inode = btrfs_iget_logging(location.objectid, root);
2146 if (IS_ERR(inode)) {
2147 ret = PTR_ERR(inode);
2152 ret = link_to_fixup_dir(trans, root, path, location.objectid);
2156 inc_nlink(&inode->vfs_inode);
2157 ret = unlink_inode_for_log_replay(trans, dir, inode, &name);
2159 * Unlike dir item keys, dir index keys can only have one name (entry) in
2160 * them, as there are no key collisions since each key has a unique offset
2161 * (an index number), so we're done.
2164 btrfs_release_path(path);
2165 btrfs_release_path(log_path);
2168 iput(&inode->vfs_inode);
2172 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2173 struct btrfs_root *root,
2174 struct btrfs_root *log,
2175 struct btrfs_path *path,
2178 struct btrfs_key search_key;
2179 struct btrfs_path *log_path;
2184 log_path = btrfs_alloc_path();
2188 search_key.objectid = ino;
2189 search_key.type = BTRFS_XATTR_ITEM_KEY;
2190 search_key.offset = 0;
2192 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2196 nritems = btrfs_header_nritems(path->nodes[0]);
2197 for (i = path->slots[0]; i < nritems; i++) {
2198 struct btrfs_key key;
2199 struct btrfs_dir_item *di;
2200 struct btrfs_dir_item *log_di;
2204 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2205 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2210 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2211 total_size = btrfs_item_size(path->nodes[0], i);
2213 while (cur < total_size) {
2214 u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2215 u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2216 u32 this_len = sizeof(*di) + name_len + data_len;
2219 name = kmalloc(name_len, GFP_NOFS);
2224 read_extent_buffer(path->nodes[0], name,
2225 (unsigned long)(di + 1), name_len);
2227 log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2229 btrfs_release_path(log_path);
2231 /* Doesn't exist in log tree, so delete it. */
2232 btrfs_release_path(path);
2233 di = btrfs_lookup_xattr(trans, root, path, ino,
2234 name, name_len, -1);
2241 ret = btrfs_delete_one_dir_name(trans, root,
2245 btrfs_release_path(path);
2250 if (IS_ERR(log_di)) {
2251 ret = PTR_ERR(log_di);
2255 di = (struct btrfs_dir_item *)((char *)di + this_len);
2258 ret = btrfs_next_leaf(root, path);
2264 btrfs_free_path(log_path);
2265 btrfs_release_path(path);
2271 * deletion replay happens before we copy any new directory items
2272 * out of the log or out of backreferences from inodes. It
2273 * scans the log to find ranges of keys that log is authoritative for,
2274 * and then scans the directory to find items in those ranges that are
2275 * not present in the log.
2277 * Anything we don't find in the log is unlinked and removed from the
2280 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2281 struct btrfs_root *root,
2282 struct btrfs_root *log,
2283 struct btrfs_path *path,
2284 u64 dirid, int del_all)
2289 struct btrfs_key dir_key;
2290 struct btrfs_key found_key;
2291 struct btrfs_path *log_path;
2292 struct btrfs_inode *dir;
2294 dir_key.objectid = dirid;
2295 dir_key.type = BTRFS_DIR_INDEX_KEY;
2296 log_path = btrfs_alloc_path();
2300 dir = btrfs_iget_logging(dirid, root);
2302 * It isn't an error if the inode isn't there, that can happen because
2303 * we replay the deletes before we copy in the inode item from the log.
2306 btrfs_free_path(log_path);
2317 range_end = (u64)-1;
2319 ret = find_dir_range(log, path, dirid,
2320 &range_start, &range_end);
2327 dir_key.offset = range_start;
2330 ret = btrfs_search_slot(NULL, root, &dir_key, path,
2335 nritems = btrfs_header_nritems(path->nodes[0]);
2336 if (path->slots[0] >= nritems) {
2337 ret = btrfs_next_leaf(root, path);
2343 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2345 if (found_key.objectid != dirid ||
2346 found_key.type != dir_key.type) {
2351 if (found_key.offset > range_end)
2354 ret = check_item_in_log(trans, log, path,
2359 if (found_key.offset == (u64)-1)
2361 dir_key.offset = found_key.offset + 1;
2363 btrfs_release_path(path);
2364 if (range_end == (u64)-1)
2366 range_start = range_end + 1;
2370 btrfs_release_path(path);
2371 btrfs_free_path(log_path);
2372 iput(&dir->vfs_inode);
2377 * the process_func used to replay items from the log tree. This
2378 * gets called in two different stages. The first stage just looks
2379 * for inodes and makes sure they are all copied into the subvolume.
2381 * The second stage copies all the other item types from the log into
2382 * the subvolume. The two stage approach is slower, but gets rid of
2383 * lots of complexity around inodes referencing other inodes that exist
2384 * only in the log (references come from either directory items or inode
2387 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2388 struct walk_control *wc, u64 gen, int level)
2391 struct btrfs_tree_parent_check check = {
2395 struct btrfs_path *path;
2396 struct btrfs_root *root = wc->replay_dest;
2397 struct btrfs_key key;
2401 ret = btrfs_read_extent_buffer(eb, &check);
2405 level = btrfs_header_level(eb);
2410 path = btrfs_alloc_path();
2414 nritems = btrfs_header_nritems(eb);
2415 for (i = 0; i < nritems; i++) {
2416 btrfs_item_key_to_cpu(eb, &key, i);
2418 /* inode keys are done during the first stage */
2419 if (key.type == BTRFS_INODE_ITEM_KEY &&
2420 wc->stage == LOG_WALK_REPLAY_INODES) {
2421 struct btrfs_inode_item *inode_item;
2424 inode_item = btrfs_item_ptr(eb, i,
2425 struct btrfs_inode_item);
2427 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2428 * and never got linked before the fsync, skip it, as
2429 * replaying it is pointless since it would be deleted
2430 * later. We skip logging tmpfiles, but it's always
2431 * possible we are replaying a log created with a kernel
2432 * that used to log tmpfiles.
2434 if (btrfs_inode_nlink(eb, inode_item) == 0) {
2435 wc->ignore_cur_inode = true;
2438 wc->ignore_cur_inode = false;
2440 ret = replay_xattr_deletes(wc->trans, root, log,
2441 path, key.objectid);
2444 mode = btrfs_inode_mode(eb, inode_item);
2445 if (S_ISDIR(mode)) {
2446 ret = replay_dir_deletes(wc->trans,
2447 root, log, path, key.objectid, 0);
2451 ret = overwrite_item(wc->trans, root, path,
2457 * Before replaying extents, truncate the inode to its
2458 * size. We need to do it now and not after log replay
2459 * because before an fsync we can have prealloc extents
2460 * added beyond the inode's i_size. If we did it after,
2461 * through orphan cleanup for example, we would drop
2462 * those prealloc extents just after replaying them.
2464 if (S_ISREG(mode)) {
2465 struct btrfs_drop_extents_args drop_args = { 0 };
2466 struct btrfs_inode *inode;
2469 inode = btrfs_iget_logging(key.objectid, root);
2470 if (IS_ERR(inode)) {
2471 ret = PTR_ERR(inode);
2474 from = ALIGN(i_size_read(&inode->vfs_inode),
2475 root->fs_info->sectorsize);
2476 drop_args.start = from;
2477 drop_args.end = (u64)-1;
2478 drop_args.drop_cache = true;
2479 ret = btrfs_drop_extents(wc->trans, root, inode,
2482 inode_sub_bytes(&inode->vfs_inode,
2483 drop_args.bytes_found);
2484 /* Update the inode's nbytes. */
2485 ret = btrfs_update_inode(wc->trans, inode);
2487 iput(&inode->vfs_inode);
2492 ret = link_to_fixup_dir(wc->trans, root,
2493 path, key.objectid);
2498 if (wc->ignore_cur_inode)
2501 if (key.type == BTRFS_DIR_INDEX_KEY &&
2502 wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2503 ret = replay_one_dir_item(wc->trans, root, path,
2509 if (wc->stage < LOG_WALK_REPLAY_ALL)
2512 /* these keys are simply copied */
2513 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2514 ret = overwrite_item(wc->trans, root, path,
2518 } else if (key.type == BTRFS_INODE_REF_KEY ||
2519 key.type == BTRFS_INODE_EXTREF_KEY) {
2520 ret = add_inode_ref(wc->trans, root, log, path,
2522 if (ret && ret != -ENOENT)
2525 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2526 ret = replay_one_extent(wc->trans, root, path,
2532 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2533 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2534 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2535 * older kernel with such keys, ignore them.
2538 btrfs_free_path(path);
2543 * Correctly adjust the reserved bytes occupied by a log tree extent buffer
2545 static void unaccount_log_buffer(struct btrfs_fs_info *fs_info, u64 start)
2547 struct btrfs_block_group *cache;
2549 cache = btrfs_lookup_block_group(fs_info, start);
2551 btrfs_err(fs_info, "unable to find block group for %llu", start);
2555 spin_lock(&cache->space_info->lock);
2556 spin_lock(&cache->lock);
2557 cache->reserved -= fs_info->nodesize;
2558 cache->space_info->bytes_reserved -= fs_info->nodesize;
2559 spin_unlock(&cache->lock);
2560 spin_unlock(&cache->space_info->lock);
2562 btrfs_put_block_group(cache);
2565 static int clean_log_buffer(struct btrfs_trans_handle *trans,
2566 struct extent_buffer *eb)
2570 btrfs_tree_lock(eb);
2571 btrfs_clear_buffer_dirty(trans, eb);
2572 wait_on_extent_buffer_writeback(eb);
2573 btrfs_tree_unlock(eb);
2576 ret = btrfs_pin_reserved_extent(trans, eb);
2580 unaccount_log_buffer(eb->fs_info, eb->start);
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;
2598 while (*level > 0) {
2599 struct btrfs_tree_parent_check check = { 0 };
2601 cur = path->nodes[*level];
2603 WARN_ON(btrfs_header_level(cur) != *level);
2605 if (path->slots[*level] >=
2606 btrfs_header_nritems(cur))
2609 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2610 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2611 check.transid = ptr_gen;
2612 check.level = *level - 1;
2613 check.has_first_key = true;
2614 btrfs_node_key_to_cpu(cur, &check.first_key, path->slots[*level]);
2616 next = btrfs_find_create_tree_block(fs_info, bytenr,
2617 btrfs_header_owner(cur),
2620 return PTR_ERR(next);
2623 ret = wc->process_func(root, next, wc, ptr_gen,
2626 free_extent_buffer(next);
2630 path->slots[*level]++;
2632 ret = btrfs_read_extent_buffer(next, &check);
2634 free_extent_buffer(next);
2638 ret = clean_log_buffer(trans, next);
2640 free_extent_buffer(next);
2644 free_extent_buffer(next);
2647 ret = btrfs_read_extent_buffer(next, &check);
2649 free_extent_buffer(next);
2653 if (path->nodes[*level-1])
2654 free_extent_buffer(path->nodes[*level-1]);
2655 path->nodes[*level-1] = next;
2656 *level = btrfs_header_level(next);
2657 path->slots[*level] = 0;
2660 path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2666 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2667 struct btrfs_root *root,
2668 struct btrfs_path *path, int *level,
2669 struct walk_control *wc)
2675 for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2676 slot = path->slots[i];
2677 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2680 WARN_ON(*level == 0);
2683 ret = wc->process_func(root, path->nodes[*level], wc,
2684 btrfs_header_generation(path->nodes[*level]),
2690 ret = clean_log_buffer(trans, path->nodes[*level]);
2694 free_extent_buffer(path->nodes[*level]);
2695 path->nodes[*level] = NULL;
2703 * drop the reference count on the tree rooted at 'snap'. This traverses
2704 * the tree freeing any blocks that have a ref count of zero after being
2707 static int walk_log_tree(struct btrfs_trans_handle *trans,
2708 struct btrfs_root *log, struct walk_control *wc)
2713 struct btrfs_path *path;
2716 path = btrfs_alloc_path();
2720 level = btrfs_header_level(log->node);
2722 path->nodes[level] = log->node;
2723 atomic_inc(&log->node->refs);
2724 path->slots[level] = 0;
2727 wret = walk_down_log_tree(trans, log, path, &level, wc);
2735 wret = walk_up_log_tree(trans, log, path, &level, wc);
2744 /* was the root node processed? if not, catch it here */
2745 if (path->nodes[orig_level]) {
2746 ret = wc->process_func(log, path->nodes[orig_level], wc,
2747 btrfs_header_generation(path->nodes[orig_level]),
2752 ret = clean_log_buffer(trans, path->nodes[orig_level]);
2756 btrfs_free_path(path);
2761 * helper function to update the item for a given subvolumes log root
2762 * in the tree of log roots
2764 static int update_log_root(struct btrfs_trans_handle *trans,
2765 struct btrfs_root *log,
2766 struct btrfs_root_item *root_item)
2768 struct btrfs_fs_info *fs_info = log->fs_info;
2771 if (log->log_transid == 1) {
2772 /* insert root item on the first sync */
2773 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2774 &log->root_key, root_item);
2776 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2777 &log->root_key, root_item);
2782 static void wait_log_commit(struct btrfs_root *root, int transid)
2785 int index = transid % 2;
2788 * we only allow two pending log transactions at a time,
2789 * so we know that if ours is more than 2 older than the
2790 * current transaction, we're done
2793 prepare_to_wait(&root->log_commit_wait[index],
2794 &wait, TASK_UNINTERRUPTIBLE);
2796 if (!(root->log_transid_committed < transid &&
2797 atomic_read(&root->log_commit[index])))
2800 mutex_unlock(&root->log_mutex);
2802 mutex_lock(&root->log_mutex);
2804 finish_wait(&root->log_commit_wait[index], &wait);
2807 static void wait_for_writer(struct btrfs_root *root)
2812 prepare_to_wait(&root->log_writer_wait, &wait,
2813 TASK_UNINTERRUPTIBLE);
2814 if (!atomic_read(&root->log_writers))
2817 mutex_unlock(&root->log_mutex);
2819 mutex_lock(&root->log_mutex);
2821 finish_wait(&root->log_writer_wait, &wait);
2824 void btrfs_init_log_ctx(struct btrfs_log_ctx *ctx, struct btrfs_inode *inode)
2827 ctx->log_transid = 0;
2828 ctx->log_new_dentries = false;
2829 ctx->logging_new_name = false;
2830 ctx->logging_new_delayed_dentries = false;
2831 ctx->logged_before = false;
2833 INIT_LIST_HEAD(&ctx->list);
2834 INIT_LIST_HEAD(&ctx->ordered_extents);
2835 INIT_LIST_HEAD(&ctx->conflict_inodes);
2836 ctx->num_conflict_inodes = 0;
2837 ctx->logging_conflict_inodes = false;
2838 ctx->scratch_eb = NULL;
2841 void btrfs_init_log_ctx_scratch_eb(struct btrfs_log_ctx *ctx)
2843 struct btrfs_inode *inode = ctx->inode;
2845 if (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) &&
2846 !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
2850 * Don't care about allocation failure. This is just for optimization,
2851 * if we fail to allocate here, we will try again later if needed.
2853 ctx->scratch_eb = alloc_dummy_extent_buffer(inode->root->fs_info, 0);
2856 void btrfs_release_log_ctx_extents(struct btrfs_log_ctx *ctx)
2858 struct btrfs_ordered_extent *ordered;
2859 struct btrfs_ordered_extent *tmp;
2861 btrfs_assert_inode_locked(ctx->inode);
2863 list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
2864 list_del_init(&ordered->log_list);
2865 btrfs_put_ordered_extent(ordered);
2870 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2871 struct btrfs_log_ctx *ctx)
2873 mutex_lock(&root->log_mutex);
2874 list_del_init(&ctx->list);
2875 mutex_unlock(&root->log_mutex);
2879 * Invoked in log mutex context, or be sure there is no other task which
2880 * can access the list.
2882 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2883 int index, int error)
2885 struct btrfs_log_ctx *ctx;
2886 struct btrfs_log_ctx *safe;
2888 list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2889 list_del_init(&ctx->list);
2890 ctx->log_ret = error;
2895 * Sends a given tree log down to the disk and updates the super blocks to
2896 * record it. When this call is done, you know that any inodes previously
2897 * logged are safely on disk only if it returns 0.
2899 * Any other return value means you need to call btrfs_commit_transaction.
2900 * Some of the edge cases for fsyncing directories that have had unlinks
2901 * or renames done in the past mean that sometimes the only safe
2902 * fsync is to commit the whole FS. When btrfs_sync_log returns -EAGAIN,
2903 * that has happened.
2905 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2906 struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2912 struct btrfs_fs_info *fs_info = root->fs_info;
2913 struct btrfs_root *log = root->log_root;
2914 struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2915 struct btrfs_root_item new_root_item;
2916 int log_transid = 0;
2917 struct btrfs_log_ctx root_log_ctx;
2918 struct blk_plug plug;
2922 mutex_lock(&root->log_mutex);
2923 log_transid = ctx->log_transid;
2924 if (root->log_transid_committed >= log_transid) {
2925 mutex_unlock(&root->log_mutex);
2926 return ctx->log_ret;
2929 index1 = log_transid % 2;
2930 if (atomic_read(&root->log_commit[index1])) {
2931 wait_log_commit(root, log_transid);
2932 mutex_unlock(&root->log_mutex);
2933 return ctx->log_ret;
2935 ASSERT(log_transid == root->log_transid);
2936 atomic_set(&root->log_commit[index1], 1);
2938 /* wait for previous tree log sync to complete */
2939 if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2940 wait_log_commit(root, log_transid - 1);
2943 int batch = atomic_read(&root->log_batch);
2944 /* when we're on an ssd, just kick the log commit out */
2945 if (!btrfs_test_opt(fs_info, SSD) &&
2946 test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
2947 mutex_unlock(&root->log_mutex);
2948 schedule_timeout_uninterruptible(1);
2949 mutex_lock(&root->log_mutex);
2951 wait_for_writer(root);
2952 if (batch == atomic_read(&root->log_batch))
2956 /* bail out if we need to do a full commit */
2957 if (btrfs_need_log_full_commit(trans)) {
2958 ret = BTRFS_LOG_FORCE_COMMIT;
2959 mutex_unlock(&root->log_mutex);
2963 if (log_transid % 2 == 0)
2964 mark = EXTENT_DIRTY;
2968 /* we start IO on all the marked extents here, but we don't actually
2969 * wait for them until later.
2971 blk_start_plug(&plug);
2972 ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2974 * -EAGAIN happens when someone, e.g., a concurrent transaction
2975 * commit, writes a dirty extent in this tree-log commit. This
2976 * concurrent write will create a hole writing out the extents,
2977 * and we cannot proceed on a zoned filesystem, requiring
2978 * sequential writing. While we can bail out to a full commit
2979 * here, but we can continue hoping the concurrent writing fills
2982 if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
2985 blk_finish_plug(&plug);
2986 btrfs_set_log_full_commit(trans);
2987 mutex_unlock(&root->log_mutex);
2992 * We _must_ update under the root->log_mutex in order to make sure we
2993 * have a consistent view of the log root we are trying to commit at
2996 * We _must_ copy this into a local copy, because we are not holding the
2997 * log_root_tree->log_mutex yet. This is important because when we
2998 * commit the log_root_tree we must have a consistent view of the
2999 * log_root_tree when we update the super block to point at the
3000 * log_root_tree bytenr. If we update the log_root_tree here we'll race
3001 * with the commit and possibly point at the new block which we may not
3004 btrfs_set_root_node(&log->root_item, log->node);
3005 memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3007 btrfs_set_root_log_transid(root, root->log_transid + 1);
3008 log->log_transid = root->log_transid;
3009 root->log_start_pid = 0;
3011 * IO has been started, blocks of the log tree have WRITTEN flag set
3012 * in their headers. new modifications of the log will be written to
3013 * new positions. so it's safe to allow log writers to go in.
3015 mutex_unlock(&root->log_mutex);
3017 if (btrfs_is_zoned(fs_info)) {
3018 mutex_lock(&fs_info->tree_root->log_mutex);
3019 if (!log_root_tree->node) {
3020 ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
3022 mutex_unlock(&fs_info->tree_root->log_mutex);
3023 blk_finish_plug(&plug);
3027 mutex_unlock(&fs_info->tree_root->log_mutex);
3030 btrfs_init_log_ctx(&root_log_ctx, NULL);
3032 mutex_lock(&log_root_tree->log_mutex);
3034 index2 = log_root_tree->log_transid % 2;
3035 list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3036 root_log_ctx.log_transid = log_root_tree->log_transid;
3039 * Now we are safe to update the log_root_tree because we're under the
3040 * log_mutex, and we're a current writer so we're holding the commit
3041 * open until we drop the log_mutex.
3043 ret = update_log_root(trans, log, &new_root_item);
3045 list_del_init(&root_log_ctx.list);
3046 blk_finish_plug(&plug);
3047 btrfs_set_log_full_commit(trans);
3050 "failed to update log for root %llu ret %d",
3051 btrfs_root_id(root), ret);
3052 btrfs_wait_tree_log_extents(log, mark);
3053 mutex_unlock(&log_root_tree->log_mutex);
3057 if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3058 blk_finish_plug(&plug);
3059 list_del_init(&root_log_ctx.list);
3060 mutex_unlock(&log_root_tree->log_mutex);
3061 ret = root_log_ctx.log_ret;
3065 if (atomic_read(&log_root_tree->log_commit[index2])) {
3066 blk_finish_plug(&plug);
3067 ret = btrfs_wait_tree_log_extents(log, mark);
3068 wait_log_commit(log_root_tree,
3069 root_log_ctx.log_transid);
3070 mutex_unlock(&log_root_tree->log_mutex);
3072 ret = root_log_ctx.log_ret;
3075 ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
3076 atomic_set(&log_root_tree->log_commit[index2], 1);
3078 if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3079 wait_log_commit(log_root_tree,
3080 root_log_ctx.log_transid - 1);
3084 * now that we've moved on to the tree of log tree roots,
3085 * check the full commit flag again
3087 if (btrfs_need_log_full_commit(trans)) {
3088 blk_finish_plug(&plug);
3089 btrfs_wait_tree_log_extents(log, mark);
3090 mutex_unlock(&log_root_tree->log_mutex);
3091 ret = BTRFS_LOG_FORCE_COMMIT;
3092 goto out_wake_log_root;
3095 ret = btrfs_write_marked_extents(fs_info,
3096 &log_root_tree->dirty_log_pages,
3097 EXTENT_DIRTY | EXTENT_NEW);
3098 blk_finish_plug(&plug);
3100 * As described above, -EAGAIN indicates a hole in the extents. We
3101 * cannot wait for these write outs since the waiting cause a
3102 * deadlock. Bail out to the full commit instead.
3104 if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3105 btrfs_set_log_full_commit(trans);
3106 btrfs_wait_tree_log_extents(log, mark);
3107 mutex_unlock(&log_root_tree->log_mutex);
3108 goto out_wake_log_root;
3110 btrfs_set_log_full_commit(trans);
3111 mutex_unlock(&log_root_tree->log_mutex);
3112 goto out_wake_log_root;
3114 ret = btrfs_wait_tree_log_extents(log, mark);
3116 ret = btrfs_wait_tree_log_extents(log_root_tree,
3117 EXTENT_NEW | EXTENT_DIRTY);
3119 btrfs_set_log_full_commit(trans);
3120 mutex_unlock(&log_root_tree->log_mutex);
3121 goto out_wake_log_root;
3124 log_root_start = log_root_tree->node->start;
3125 log_root_level = btrfs_header_level(log_root_tree->node);
3126 log_root_tree->log_transid++;
3127 mutex_unlock(&log_root_tree->log_mutex);
3130 * Here we are guaranteed that nobody is going to write the superblock
3131 * for the current transaction before us and that neither we do write
3132 * our superblock before the previous transaction finishes its commit
3133 * and writes its superblock, because:
3135 * 1) We are holding a handle on the current transaction, so no body
3136 * can commit it until we release the handle;
3138 * 2) Before writing our superblock we acquire the tree_log_mutex, so
3139 * if the previous transaction is still committing, and hasn't yet
3140 * written its superblock, we wait for it to do it, because a
3141 * transaction commit acquires the tree_log_mutex when the commit
3142 * begins and releases it only after writing its superblock.
3144 mutex_lock(&fs_info->tree_log_mutex);
3147 * The previous transaction writeout phase could have failed, and thus
3148 * marked the fs in an error state. We must not commit here, as we
3149 * could have updated our generation in the super_for_commit and
3150 * writing the super here would result in transid mismatches. If there
3151 * is an error here just bail.
3153 if (BTRFS_FS_ERROR(fs_info)) {
3155 btrfs_set_log_full_commit(trans);
3156 btrfs_abort_transaction(trans, ret);
3157 mutex_unlock(&fs_info->tree_log_mutex);
3158 goto out_wake_log_root;
3161 btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
3162 btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3163 ret = write_all_supers(fs_info, 1);
3164 mutex_unlock(&fs_info->tree_log_mutex);
3166 btrfs_set_log_full_commit(trans);
3167 btrfs_abort_transaction(trans, ret);
3168 goto out_wake_log_root;
3172 * We know there can only be one task here, since we have not yet set
3173 * root->log_commit[index1] to 0 and any task attempting to sync the
3174 * log must wait for the previous log transaction to commit if it's
3175 * still in progress or wait for the current log transaction commit if
3176 * someone else already started it. We use <= and not < because the
3177 * first log transaction has an ID of 0.
3179 ASSERT(btrfs_get_root_last_log_commit(root) <= log_transid);
3180 btrfs_set_root_last_log_commit(root, log_transid);
3183 mutex_lock(&log_root_tree->log_mutex);
3184 btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3186 log_root_tree->log_transid_committed++;
3187 atomic_set(&log_root_tree->log_commit[index2], 0);
3188 mutex_unlock(&log_root_tree->log_mutex);
3191 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3192 * all the updates above are seen by the woken threads. It might not be
3193 * necessary, but proving that seems to be hard.
3195 cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3197 mutex_lock(&root->log_mutex);
3198 btrfs_remove_all_log_ctxs(root, index1, ret);
3199 root->log_transid_committed++;
3200 atomic_set(&root->log_commit[index1], 0);
3201 mutex_unlock(&root->log_mutex);
3204 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3205 * all the updates above are seen by the woken threads. It might not be
3206 * necessary, but proving that seems to be hard.
3208 cond_wake_up(&root->log_commit_wait[index1]);
3212 static void free_log_tree(struct btrfs_trans_handle *trans,
3213 struct btrfs_root *log)
3216 struct walk_control wc = {
3218 .process_func = process_one_buffer
3222 ret = walk_log_tree(trans, log, &wc);
3225 * We weren't able to traverse the entire log tree, the
3226 * typical scenario is getting an -EIO when reading an
3227 * extent buffer of the tree, due to a previous writeback
3230 set_bit(BTRFS_FS_STATE_LOG_CLEANUP_ERROR,
3231 &log->fs_info->fs_state);
3234 * Some extent buffers of the log tree may still be dirty
3235 * and not yet written back to storage, because we may
3236 * have updates to a log tree without syncing a log tree,
3237 * such as during rename and link operations. So flush
3238 * them out and wait for their writeback to complete, so
3239 * that we properly cleanup their state and pages.
3241 btrfs_write_marked_extents(log->fs_info,
3242 &log->dirty_log_pages,
3243 EXTENT_DIRTY | EXTENT_NEW);
3244 btrfs_wait_tree_log_extents(log,
3245 EXTENT_DIRTY | EXTENT_NEW);
3248 btrfs_abort_transaction(trans, ret);
3250 btrfs_handle_fs_error(log->fs_info, ret, NULL);
3254 btrfs_extent_io_tree_release(&log->dirty_log_pages);
3255 btrfs_extent_io_tree_release(&log->log_csum_range);
3257 btrfs_put_root(log);
3261 * free all the extents used by the tree log. This should be called
3262 * at commit time of the full transaction
3264 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3266 if (root->log_root) {
3267 free_log_tree(trans, root->log_root);
3268 root->log_root = NULL;
3269 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
3274 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3275 struct btrfs_fs_info *fs_info)
3277 if (fs_info->log_root_tree) {
3278 free_log_tree(trans, fs_info->log_root_tree);
3279 fs_info->log_root_tree = NULL;
3280 clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
3286 * Check if an inode was logged in the current transaction. This correctly deals
3287 * with the case where the inode was logged but has a logged_trans of 0, which
3288 * happens if the inode is evicted and loaded again, as logged_trans is an in
3289 * memory only field (not persisted).
3291 * Returns 1 if the inode was logged before in the transaction, 0 if it was not,
3294 static int inode_logged(const struct btrfs_trans_handle *trans,
3295 struct btrfs_inode *inode,
3296 struct btrfs_path *path_in)
3298 struct btrfs_path *path = path_in;
3299 struct btrfs_key key;
3302 if (inode->logged_trans == trans->transid)
3306 * If logged_trans is not 0, then we know the inode logged was not logged
3307 * in this transaction, so we can return false right away.
3309 if (inode->logged_trans > 0)
3313 * If no log tree was created for this root in this transaction, then
3314 * the inode can not have been logged in this transaction. In that case
3315 * set logged_trans to anything greater than 0 and less than the current
3316 * transaction's ID, to avoid the search below in a future call in case
3317 * a log tree gets created after this.
3319 if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state)) {
3320 inode->logged_trans = trans->transid - 1;
3325 * We have a log tree and the inode's logged_trans is 0. We can't tell
3326 * for sure if the inode was logged before in this transaction by looking
3327 * only at logged_trans. We could be pessimistic and assume it was, but
3328 * that can lead to unnecessarily logging an inode during rename and link
3329 * operations, and then further updating the log in followup rename and
3330 * link operations, specially if it's a directory, which adds latency
3331 * visible to applications doing a series of rename or link operations.
3333 * A logged_trans of 0 here can mean several things:
3335 * 1) The inode was never logged since the filesystem was mounted, and may
3336 * or may have not been evicted and loaded again;
3338 * 2) The inode was logged in a previous transaction, then evicted and
3339 * then loaded again;
3341 * 3) The inode was logged in the current transaction, then evicted and
3342 * then loaded again.
3344 * For cases 1) and 2) we don't want to return true, but we need to detect
3345 * case 3) and return true. So we do a search in the log root for the inode
3348 key.objectid = btrfs_ino(inode);
3349 key.type = BTRFS_INODE_ITEM_KEY;
3353 path = btrfs_alloc_path();
3358 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3361 btrfs_release_path(path);
3363 btrfs_free_path(path);
3366 * Logging an inode always results in logging its inode item. So if we
3367 * did not find the item we know the inode was not logged for sure.
3371 } else if (ret > 0) {
3373 * Set logged_trans to a value greater than 0 and less then the
3374 * current transaction to avoid doing the search in future calls.
3376 inode->logged_trans = trans->transid - 1;
3381 * The inode was previously logged and then evicted, set logged_trans to
3382 * the current transacion's ID, to avoid future tree searches as long as
3383 * the inode is not evicted again.
3385 inode->logged_trans = trans->transid;
3388 * If it's a directory, then we must set last_dir_index_offset to the
3389 * maximum possible value, so that the next attempt to log the inode does
3390 * not skip checking if dir index keys found in modified subvolume tree
3391 * leaves have been logged before, otherwise it would result in attempts
3392 * to insert duplicate dir index keys in the log tree. This must be done
3393 * because last_dir_index_offset is an in-memory only field, not persisted
3394 * in the inode item or any other on-disk structure, so its value is lost
3395 * once the inode is evicted.
3397 if (S_ISDIR(inode->vfs_inode.i_mode))
3398 inode->last_dir_index_offset = (u64)-1;
3404 * Delete a directory entry from the log if it exists.
3406 * Returns < 0 on error
3407 * 1 if the entry does not exists
3408 * 0 if the entry existed and was successfully deleted
3410 static int del_logged_dentry(struct btrfs_trans_handle *trans,
3411 struct btrfs_root *log,
3412 struct btrfs_path *path,
3414 const struct fscrypt_str *name,
3417 struct btrfs_dir_item *di;
3420 * We only log dir index items of a directory, so we don't need to look
3421 * for dir item keys.
3423 di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3431 * We do not need to update the size field of the directory's
3432 * inode item because on log replay we update the field to reflect
3433 * all existing entries in the directory (see overwrite_item()).
3435 return btrfs_delete_one_dir_name(trans, log, path, di);
3439 * If both a file and directory are logged, and unlinks or renames are
3440 * mixed in, we have a few interesting corners:
3442 * create file X in dir Y
3443 * link file X to X.link in dir Y
3445 * unlink file X but leave X.link
3448 * After a crash we would expect only X.link to exist. But file X
3449 * didn't get fsync'd again so the log has back refs for X and X.link.
3451 * We solve this by removing directory entries and inode backrefs from the
3452 * log when a file that was logged in the current transaction is
3453 * unlinked. Any later fsync will include the updated log entries, and
3454 * we'll be able to reconstruct the proper directory items from backrefs.
3456 * This optimizations allows us to avoid relogging the entire inode
3457 * or the entire directory.
3459 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3460 struct btrfs_root *root,
3461 const struct fscrypt_str *name,
3462 struct btrfs_inode *dir, u64 index)
3464 struct btrfs_path *path;
3467 ret = inode_logged(trans, dir, NULL);
3471 btrfs_set_log_full_commit(trans);
3475 ret = join_running_log_trans(root);
3479 mutex_lock(&dir->log_mutex);
3481 path = btrfs_alloc_path();
3487 ret = del_logged_dentry(trans, root->log_root, path, btrfs_ino(dir),
3489 btrfs_free_path(path);
3491 mutex_unlock(&dir->log_mutex);
3493 btrfs_set_log_full_commit(trans);
3494 btrfs_end_log_trans(root);
3497 /* see comments for btrfs_del_dir_entries_in_log */
3498 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3499 struct btrfs_root *root,
3500 const struct fscrypt_str *name,
3501 struct btrfs_inode *inode, u64 dirid)
3503 struct btrfs_root *log;
3507 ret = inode_logged(trans, inode, NULL);
3511 btrfs_set_log_full_commit(trans);
3515 ret = join_running_log_trans(root);
3518 log = root->log_root;
3519 mutex_lock(&inode->log_mutex);
3521 ret = btrfs_del_inode_ref(trans, log, name, btrfs_ino(inode),
3523 mutex_unlock(&inode->log_mutex);
3524 if (ret < 0 && ret != -ENOENT)
3525 btrfs_set_log_full_commit(trans);
3526 btrfs_end_log_trans(root);
3530 * creates a range item in the log for 'dirid'. first_offset and
3531 * last_offset tell us which parts of the key space the log should
3532 * be considered authoritative for.
3534 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3535 struct btrfs_root *log,
3536 struct btrfs_path *path,
3538 u64 first_offset, u64 last_offset)
3541 struct btrfs_key key;
3542 struct btrfs_dir_log_item *item;
3544 key.objectid = dirid;
3545 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3546 key.offset = first_offset;
3547 ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3549 * -EEXIST is fine and can happen sporadically when we are logging a
3550 * directory and have concurrent insertions in the subvolume's tree for
3551 * items from other inodes and that result in pushing off some dir items
3552 * from one leaf to another in order to accommodate for the new items.
3553 * This results in logging the same dir index range key.
3555 if (ret && ret != -EEXIST)
3558 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3559 struct btrfs_dir_log_item);
3560 if (ret == -EEXIST) {
3561 const u64 curr_end = btrfs_dir_log_end(path->nodes[0], item);
3564 * btrfs_del_dir_entries_in_log() might have been called during
3565 * an unlink between the initial insertion of this key and the
3566 * current update, or we might be logging a single entry deletion
3567 * during a rename, so set the new last_offset to the max value.
3569 last_offset = max(last_offset, curr_end);
3571 btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3572 btrfs_release_path(path);
3576 static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
3577 struct btrfs_inode *inode,
3578 struct extent_buffer *src,
3579 struct btrfs_path *dst_path,
3583 struct btrfs_root *log = inode->root->log_root;
3584 char *ins_data = NULL;
3585 struct btrfs_item_batch batch;
3586 struct extent_buffer *dst;
3587 unsigned long src_offset;
3588 unsigned long dst_offset;
3590 struct btrfs_key key;
3599 btrfs_item_key_to_cpu(src, &key, start_slot);
3600 item_size = btrfs_item_size(src, start_slot);
3602 batch.data_sizes = &item_size;
3603 batch.total_data_size = item_size;
3605 struct btrfs_key *ins_keys;
3608 ins_data = kmalloc(count * sizeof(u32) +
3609 count * sizeof(struct btrfs_key), GFP_NOFS);
3613 ins_sizes = (u32 *)ins_data;
3614 ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
3615 batch.keys = ins_keys;
3616 batch.data_sizes = ins_sizes;
3617 batch.total_data_size = 0;
3619 for (i = 0; i < count; i++) {
3620 const int slot = start_slot + i;
3622 btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
3623 ins_sizes[i] = btrfs_item_size(src, slot);
3624 batch.total_data_size += ins_sizes[i];
3628 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
3632 dst = dst_path->nodes[0];
3634 * Copy all the items in bulk, in a single copy operation. Item data is
3635 * organized such that it's placed at the end of a leaf and from right
3636 * to left. For example, the data for the second item ends at an offset
3637 * that matches the offset where the data for the first item starts, the
3638 * data for the third item ends at an offset that matches the offset
3639 * where the data of the second items starts, and so on.
3640 * Therefore our source and destination start offsets for copy match the
3641 * offsets of the last items (highest slots).
3643 dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
3644 src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
3645 copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
3646 btrfs_release_path(dst_path);
3648 last_index = batch.keys[count - 1].offset;
3649 ASSERT(last_index > inode->last_dir_index_offset);
3652 * If for some unexpected reason the last item's index is not greater
3653 * than the last index we logged, warn and force a transaction commit.
3655 if (WARN_ON(last_index <= inode->last_dir_index_offset))
3656 ret = BTRFS_LOG_FORCE_COMMIT;
3658 inode->last_dir_index_offset = last_index;
3660 if (btrfs_get_first_dir_index_to_log(inode) == 0)
3661 btrfs_set_first_dir_index_to_log(inode, batch.keys[0].offset);
3668 static int clone_leaf(struct btrfs_path *path, struct btrfs_log_ctx *ctx)
3670 const int slot = path->slots[0];
3672 if (ctx->scratch_eb) {
3673 copy_extent_buffer_full(ctx->scratch_eb, path->nodes[0]);
3675 ctx->scratch_eb = btrfs_clone_extent_buffer(path->nodes[0]);
3676 if (!ctx->scratch_eb)
3680 btrfs_release_path(path);
3681 path->nodes[0] = ctx->scratch_eb;
3682 path->slots[0] = slot;
3684 * Add extra ref to scratch eb so that it is not freed when callers
3685 * release the path, so we can reuse it later if needed.
3687 atomic_inc(&ctx->scratch_eb->refs);
3692 static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
3693 struct btrfs_inode *inode,
3694 struct btrfs_path *path,
3695 struct btrfs_path *dst_path,
3696 struct btrfs_log_ctx *ctx,
3697 u64 *last_old_dentry_offset)
3699 struct btrfs_root *log = inode->root->log_root;
3700 struct extent_buffer *src;
3701 const int nritems = btrfs_header_nritems(path->nodes[0]);
3702 const u64 ino = btrfs_ino(inode);
3703 bool last_found = false;
3704 int batch_start = 0;
3709 * We need to clone the leaf, release the read lock on it, and use the
3710 * clone before modifying the log tree. See the comment at copy_items()
3711 * about why we need to do this.
3713 ret = clone_leaf(path, ctx);
3717 src = path->nodes[0];
3719 for (int i = path->slots[0]; i < nritems; i++) {
3720 struct btrfs_dir_item *di;
3721 struct btrfs_key key;
3724 btrfs_item_key_to_cpu(src, &key, i);
3726 if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
3731 di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3734 * Skip ranges of items that consist only of dir item keys created
3735 * in past transactions. However if we find a gap, we must log a
3736 * dir index range item for that gap, so that index keys in that
3737 * gap are deleted during log replay.
3739 if (btrfs_dir_transid(src, di) < trans->transid) {
3740 if (key.offset > *last_old_dentry_offset + 1) {
3741 ret = insert_dir_log_key(trans, log, dst_path,
3742 ino, *last_old_dentry_offset + 1,
3748 *last_old_dentry_offset = key.offset;
3752 /* If we logged this dir index item before, we can skip it. */
3753 if (key.offset <= inode->last_dir_index_offset)
3757 * We must make sure that when we log a directory entry, the
3758 * corresponding inode, after log replay, has a matching link
3759 * count. For example:
3765 * xfs_io -c "fsync" mydir
3767 * <mount fs and log replay>
3769 * Would result in a fsync log that when replayed, our file inode
3770 * would have a link count of 1, but we get two directory entries
3771 * pointing to the same inode. After removing one of the names,
3772 * it would not be possible to remove the other name, which
3773 * resulted always in stale file handle errors, and would not be
3774 * possible to rmdir the parent directory, since its i_size could
3775 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
3776 * resulting in -ENOTEMPTY errors.
3778 if (!ctx->log_new_dentries) {
3779 struct btrfs_key di_key;
3781 btrfs_dir_item_key_to_cpu(src, di, &di_key);
3782 if (di_key.type != BTRFS_ROOT_ITEM_KEY)
3783 ctx->log_new_dentries = true;
3786 if (batch_size == 0)
3791 if (batch_size > 0) {
3794 ret = flush_dir_items_batch(trans, inode, src, dst_path,
3795 batch_start, batch_size);
3800 return last_found ? 1 : 0;
3804 * log all the items included in the current transaction for a given
3805 * directory. This also creates the range items in the log tree required
3806 * to replay anything deleted before the fsync
3808 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3809 struct btrfs_inode *inode,
3810 struct btrfs_path *path,
3811 struct btrfs_path *dst_path,
3812 struct btrfs_log_ctx *ctx,
3813 u64 min_offset, u64 *last_offset_ret)
3815 struct btrfs_key min_key;
3816 struct btrfs_root *root = inode->root;
3817 struct btrfs_root *log = root->log_root;
3819 u64 last_old_dentry_offset = min_offset - 1;
3820 u64 last_offset = (u64)-1;
3821 u64 ino = btrfs_ino(inode);
3823 min_key.objectid = ino;
3824 min_key.type = BTRFS_DIR_INDEX_KEY;
3825 min_key.offset = min_offset;
3827 ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3830 * we didn't find anything from this transaction, see if there
3831 * is anything at all
3833 if (ret != 0 || min_key.objectid != ino ||
3834 min_key.type != BTRFS_DIR_INDEX_KEY) {
3835 min_key.objectid = ino;
3836 min_key.type = BTRFS_DIR_INDEX_KEY;
3837 min_key.offset = (u64)-1;
3838 btrfs_release_path(path);
3839 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3841 btrfs_release_path(path);
3844 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3846 /* if ret == 0 there are items for this type,
3847 * create a range to tell us the last key of this type.
3848 * otherwise, there are no items in this directory after
3849 * *min_offset, and we create a range to indicate that.
3852 struct btrfs_key tmp;
3854 btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3856 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3857 last_old_dentry_offset = tmp.offset;
3858 } else if (ret > 0) {
3865 /* go backward to find any previous key */
3866 ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3868 struct btrfs_key tmp;
3870 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3872 * The dir index key before the first one we found that needs to
3873 * be logged might be in a previous leaf, and there might be a
3874 * gap between these keys, meaning that we had deletions that
3875 * happened. So the key range item we log (key type
3876 * BTRFS_DIR_LOG_INDEX_KEY) must cover a range that starts at the
3877 * previous key's offset plus 1, so that those deletes are replayed.
3879 if (tmp.type == BTRFS_DIR_INDEX_KEY)
3880 last_old_dentry_offset = tmp.offset;
3881 } else if (ret < 0) {
3885 btrfs_release_path(path);
3888 * Find the first key from this transaction again or the one we were at
3889 * in the loop below in case we had to reschedule. We may be logging the
3890 * directory without holding its VFS lock, which happen when logging new
3891 * dentries (through log_new_dir_dentries()) or in some cases when we
3892 * need to log the parent directory of an inode. This means a dir index
3893 * key might be deleted from the inode's root, and therefore we may not
3894 * find it anymore. If we can't find it, just move to the next key. We
3895 * can not bail out and ignore, because if we do that we will simply
3896 * not log dir index keys that come after the one that was just deleted
3897 * and we can end up logging a dir index range that ends at (u64)-1
3898 * (@last_offset is initialized to that), resulting in removing dir
3899 * entries we should not remove at log replay time.
3902 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3904 ret = btrfs_next_item(root, path);
3906 /* There are no more keys in the inode's root. */
3915 * we have a block from this transaction, log every item in it
3916 * from our directory
3919 ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx,
3920 &last_old_dentry_offset);
3926 path->slots[0] = btrfs_header_nritems(path->nodes[0]);
3929 * look ahead to the next item and see if it is also
3930 * from this directory and from this transaction
3932 ret = btrfs_next_leaf(root, path);
3935 last_offset = (u64)-1;
3940 btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
3941 if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
3942 last_offset = (u64)-1;
3945 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3947 * The next leaf was not changed in the current transaction
3948 * and has at least one dir index key.
3949 * We check for the next key because there might have been
3950 * one or more deletions between the last key we logged and
3951 * that next key. So the key range item we log (key type
3952 * BTRFS_DIR_LOG_INDEX_KEY) must end at the next key's
3953 * offset minus 1, so that those deletes are replayed.
3955 last_offset = min_key.offset - 1;
3958 if (need_resched()) {
3959 btrfs_release_path(path);
3965 btrfs_release_path(path);
3966 btrfs_release_path(dst_path);
3969 *last_offset_ret = last_offset;
3971 * In case the leaf was changed in the current transaction but
3972 * all its dir items are from a past transaction, the last item
3973 * in the leaf is a dir item and there's no gap between that last
3974 * dir item and the first one on the next leaf (which did not
3975 * change in the current transaction), then we don't need to log
3976 * a range, last_old_dentry_offset is == to last_offset.
3978 ASSERT(last_old_dentry_offset <= last_offset);
3979 if (last_old_dentry_offset < last_offset)
3980 ret = insert_dir_log_key(trans, log, path, ino,
3981 last_old_dentry_offset + 1,
3989 * If the inode was logged before and it was evicted, then its
3990 * last_dir_index_offset is (u64)-1, so we don't the value of the last index
3991 * key offset. If that's the case, search for it and update the inode. This
3992 * is to avoid lookups in the log tree every time we try to insert a dir index
3993 * key from a leaf changed in the current transaction, and to allow us to always
3994 * do batch insertions of dir index keys.
3996 static int update_last_dir_index_offset(struct btrfs_inode *inode,
3997 struct btrfs_path *path,
3998 const struct btrfs_log_ctx *ctx)
4000 const u64 ino = btrfs_ino(inode);
4001 struct btrfs_key key;
4004 lockdep_assert_held(&inode->log_mutex);
4006 if (inode->last_dir_index_offset != (u64)-1)
4009 if (!ctx->logged_before) {
4010 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
4015 key.type = BTRFS_DIR_INDEX_KEY;
4016 key.offset = (u64)-1;
4018 ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
4020 * An error happened or we actually have an index key with an offset
4021 * value of (u64)-1. Bail out, we're done.
4027 inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
4030 * No dir index items, bail out and leave last_dir_index_offset with
4031 * the value right before the first valid index value.
4033 if (path->slots[0] == 0)
4037 * btrfs_search_slot() left us at one slot beyond the slot with the last
4038 * index key, or beyond the last key of the directory that is not an
4039 * index key. If we have an index key before, set last_dir_index_offset
4040 * to its offset value, otherwise leave it with a value right before the
4041 * first valid index value, as it means we have an empty directory.
4043 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
4044 if (key.objectid == ino && key.type == BTRFS_DIR_INDEX_KEY)
4045 inode->last_dir_index_offset = key.offset;
4048 btrfs_release_path(path);
4054 * logging directories is very similar to logging inodes, We find all the items
4055 * from the current transaction and write them to the log.
4057 * The recovery code scans the directory in the subvolume, and if it finds a
4058 * key in the range logged that is not present in the log tree, then it means
4059 * that dir entry was unlinked during the transaction.
4061 * In order for that scan to work, we must include one key smaller than
4062 * the smallest logged by this transaction and one key larger than the largest
4063 * key logged by this transaction.
4065 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
4066 struct btrfs_inode *inode,
4067 struct btrfs_path *path,
4068 struct btrfs_path *dst_path,
4069 struct btrfs_log_ctx *ctx)
4075 ret = update_last_dir_index_offset(inode, path, ctx);
4079 min_key = BTRFS_DIR_START_INDEX;
4083 ret = log_dir_items(trans, inode, path, dst_path,
4084 ctx, min_key, &max_key);
4087 if (max_key == (u64)-1)
4089 min_key = max_key + 1;
4096 * a helper function to drop items from the log before we relog an
4097 * inode. max_key_type indicates the highest item type to remove.
4098 * This cannot be run for file data extents because it does not
4099 * free the extents they point to.
4101 static int drop_inode_items(struct btrfs_trans_handle *trans,
4102 struct btrfs_root *log,
4103 struct btrfs_path *path,
4104 struct btrfs_inode *inode,
4108 struct btrfs_key key;
4109 struct btrfs_key found_key;
4112 key.objectid = btrfs_ino(inode);
4113 key.type = max_key_type;
4114 key.offset = (u64)-1;
4117 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
4120 } else if (ret > 0) {
4121 if (path->slots[0] == 0)
4126 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4129 if (found_key.objectid != key.objectid)
4132 found_key.offset = 0;
4134 ret = btrfs_bin_search(path->nodes[0], 0, &found_key, &start_slot);
4138 ret = btrfs_del_items(trans, log, path, start_slot,
4139 path->slots[0] - start_slot + 1);
4141 * If start slot isn't 0 then we don't need to re-search, we've
4142 * found the last guy with the objectid in this tree.
4144 if (ret || start_slot != 0)
4146 btrfs_release_path(path);
4148 btrfs_release_path(path);
4154 static int truncate_inode_items(struct btrfs_trans_handle *trans,
4155 struct btrfs_root *log_root,
4156 struct btrfs_inode *inode,
4157 u64 new_size, u32 min_type)
4159 struct btrfs_truncate_control control = {
4160 .new_size = new_size,
4161 .ino = btrfs_ino(inode),
4162 .min_type = min_type,
4163 .skip_ref_updates = true,
4166 return btrfs_truncate_inode_items(trans, log_root, &control);
4169 static void fill_inode_item(struct btrfs_trans_handle *trans,
4170 struct extent_buffer *leaf,
4171 struct btrfs_inode_item *item,
4172 struct inode *inode, int log_inode_only,
4175 struct btrfs_map_token token;
4178 btrfs_init_map_token(&token, leaf);
4180 if (log_inode_only) {
4181 /* set the generation to zero so the recover code
4182 * can tell the difference between an logging
4183 * just to say 'this inode exists' and a logging
4184 * to say 'update this inode with these values'
4186 btrfs_set_token_inode_generation(&token, item, 0);
4187 btrfs_set_token_inode_size(&token, item, logged_isize);
4189 btrfs_set_token_inode_generation(&token, item,
4190 BTRFS_I(inode)->generation);
4191 btrfs_set_token_inode_size(&token, item, inode->i_size);
4194 btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4195 btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4196 btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4197 btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4199 btrfs_set_token_timespec_sec(&token, &item->atime,
4200 inode_get_atime_sec(inode));
4201 btrfs_set_token_timespec_nsec(&token, &item->atime,
4202 inode_get_atime_nsec(inode));
4204 btrfs_set_token_timespec_sec(&token, &item->mtime,
4205 inode_get_mtime_sec(inode));
4206 btrfs_set_token_timespec_nsec(&token, &item->mtime,
4207 inode_get_mtime_nsec(inode));
4209 btrfs_set_token_timespec_sec(&token, &item->ctime,
4210 inode_get_ctime_sec(inode));
4211 btrfs_set_token_timespec_nsec(&token, &item->ctime,
4212 inode_get_ctime_nsec(inode));
4215 * We do not need to set the nbytes field, in fact during a fast fsync
4216 * its value may not even be correct, since a fast fsync does not wait
4217 * for ordered extent completion, which is where we update nbytes, it
4218 * only waits for writeback to complete. During log replay as we find
4219 * file extent items and replay them, we adjust the nbytes field of the
4220 * inode item in subvolume tree as needed (see overwrite_item()).
4223 btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4224 btrfs_set_token_inode_transid(&token, item, trans->transid);
4225 btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4226 flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4227 BTRFS_I(inode)->ro_flags);
4228 btrfs_set_token_inode_flags(&token, item, flags);
4229 btrfs_set_token_inode_block_group(&token, item, 0);
4232 static int log_inode_item(struct btrfs_trans_handle *trans,
4233 struct btrfs_root *log, struct btrfs_path *path,
4234 struct btrfs_inode *inode, bool inode_item_dropped)
4236 struct btrfs_inode_item *inode_item;
4237 struct btrfs_key key;
4240 btrfs_get_inode_key(inode, &key);
4242 * If we are doing a fast fsync and the inode was logged before in the
4243 * current transaction, then we know the inode was previously logged and
4244 * it exists in the log tree. For performance reasons, in this case use
4245 * btrfs_search_slot() directly with ins_len set to 0 so that we never
4246 * attempt a write lock on the leaf's parent, which adds unnecessary lock
4247 * contention in case there are concurrent fsyncs for other inodes of the
4248 * same subvolume. Using btrfs_insert_empty_item() when the inode item
4249 * already exists can also result in unnecessarily splitting a leaf.
4251 if (!inode_item_dropped && inode->logged_trans == trans->transid) {
4252 ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
4258 * This means it is the first fsync in the current transaction,
4259 * so the inode item is not in the log and we need to insert it.
4260 * We can never get -EEXIST because we are only called for a fast
4261 * fsync and in case an inode eviction happens after the inode was
4262 * logged before in the current transaction, when we load again
4263 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
4264 * flags and set ->logged_trans to 0.
4266 ret = btrfs_insert_empty_item(trans, log, path, &key,
4267 sizeof(*inode_item));
4268 ASSERT(ret != -EEXIST);
4272 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4273 struct btrfs_inode_item);
4274 fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
4276 btrfs_release_path(path);
4280 static int log_csums(struct btrfs_trans_handle *trans,
4281 struct btrfs_inode *inode,
4282 struct btrfs_root *log_root,
4283 struct btrfs_ordered_sum *sums)
4285 const u64 lock_end = sums->logical + sums->len - 1;
4286 struct extent_state *cached_state = NULL;
4290 * If this inode was not used for reflink operations in the current
4291 * transaction with new extents, then do the fast path, no need to
4292 * worry about logging checksum items with overlapping ranges.
4294 if (inode->last_reflink_trans < trans->transid)
4295 return btrfs_csum_file_blocks(trans, log_root, sums);
4298 * Serialize logging for checksums. This is to avoid racing with the
4299 * same checksum being logged by another task that is logging another
4300 * file which happens to refer to the same extent as well. Such races
4301 * can leave checksum items in the log with overlapping ranges.
4303 ret = btrfs_lock_extent(&log_root->log_csum_range, sums->logical, lock_end,
4308 * Due to extent cloning, we might have logged a csum item that covers a
4309 * subrange of a cloned extent, and later we can end up logging a csum
4310 * item for a larger subrange of the same extent or the entire range.
4311 * This would leave csum items in the log tree that cover the same range
4312 * and break the searches for checksums in the log tree, resulting in
4313 * some checksums missing in the fs/subvolume tree. So just delete (or
4314 * trim and adjust) any existing csum items in the log for this range.
4316 ret = btrfs_del_csums(trans, log_root, sums->logical, sums->len);
4318 ret = btrfs_csum_file_blocks(trans, log_root, sums);
4320 btrfs_unlock_extent(&log_root->log_csum_range, sums->logical, lock_end,
4326 static noinline int copy_items(struct btrfs_trans_handle *trans,
4327 struct btrfs_inode *inode,
4328 struct btrfs_path *dst_path,
4329 struct btrfs_path *src_path,
4330 int start_slot, int nr, int inode_only,
4331 u64 logged_isize, struct btrfs_log_ctx *ctx)
4333 struct btrfs_root *log = inode->root->log_root;
4334 struct btrfs_file_extent_item *extent;
4335 struct extent_buffer *src;
4337 struct btrfs_key *ins_keys;
4339 struct btrfs_item_batch batch;
4342 const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
4343 const u64 i_size = i_size_read(&inode->vfs_inode);
4346 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4347 * use the clone. This is because otherwise we would be changing the log
4348 * tree, to insert items from the subvolume tree or insert csum items,
4349 * while holding a read lock on a leaf from the subvolume tree, which
4350 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4352 * 1) Modifying the log tree triggers an extent buffer allocation while
4353 * holding a write lock on a parent extent buffer from the log tree.
4354 * Allocating the pages for an extent buffer, or the extent buffer
4355 * struct, can trigger inode eviction and finally the inode eviction
4356 * will trigger a release/remove of a delayed node, which requires
4357 * taking the delayed node's mutex;
4359 * 2) Allocating a metadata extent for a log tree can trigger the async
4360 * reclaim thread and make us wait for it to release enough space and
4361 * unblock our reservation ticket. The reclaim thread can start
4362 * flushing delayed items, and that in turn results in the need to
4363 * lock delayed node mutexes and in the need to write lock extent
4364 * buffers of a subvolume tree - all this while holding a write lock
4365 * on the parent extent buffer in the log tree.
4367 * So one task in scenario 1) running in parallel with another task in
4368 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4369 * node mutex while having a read lock on a leaf from the subvolume,
4370 * while the other is holding the delayed node's mutex and wants to
4371 * write lock the same subvolume leaf for flushing delayed items.
4373 ret = clone_leaf(src_path, ctx);
4377 src = src_path->nodes[0];
4379 ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
4380 nr * sizeof(u32), GFP_NOFS);
4384 ins_sizes = (u32 *)ins_data;
4385 ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4386 batch.keys = ins_keys;
4387 batch.data_sizes = ins_sizes;
4388 batch.total_data_size = 0;
4392 for (int i = 0; i < nr; i++) {
4393 const int src_slot = start_slot + i;
4394 struct btrfs_root *csum_root;
4395 struct btrfs_ordered_sum *sums;
4396 struct btrfs_ordered_sum *sums_next;
4397 LIST_HEAD(ordered_sums);
4401 u64 extent_num_bytes;
4404 btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
4406 if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
4409 extent = btrfs_item_ptr(src, src_slot,
4410 struct btrfs_file_extent_item);
4412 is_old_extent = (btrfs_file_extent_generation(src, extent) <
4416 * Don't copy extents from past generations. That would make us
4417 * log a lot more metadata for common cases like doing only a
4418 * few random writes into a file and then fsync it for the first
4419 * time or after the full sync flag is set on the inode. We can
4420 * get leaves full of extent items, most of which are from past
4421 * generations, so we can skip them - as long as the inode has
4422 * not been the target of a reflink operation in this transaction,
4423 * as in that case it might have had file extent items with old
4424 * generations copied into it. We also must always log prealloc
4425 * extents that start at or beyond eof, otherwise we would lose
4426 * them on log replay.
4428 if (is_old_extent &&
4429 ins_keys[dst_index].offset < i_size &&
4430 inode->last_reflink_trans < trans->transid)
4436 /* Only regular extents have checksums. */
4437 if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
4441 * If it's an extent created in a past transaction, then its
4442 * checksums are already accessible from the committed csum tree,
4443 * no need to log them.
4448 disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
4449 /* If it's an explicit hole, there are no checksums. */
4450 if (disk_bytenr == 0)
4453 disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
4455 if (btrfs_file_extent_compression(src, extent)) {
4457 extent_num_bytes = disk_num_bytes;
4459 extent_offset = btrfs_file_extent_offset(src, extent);
4460 extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
4463 csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
4464 disk_bytenr += extent_offset;
4465 ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
4466 disk_bytenr + extent_num_bytes - 1,
4467 &ordered_sums, false);
4472 list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
4474 ret = log_csums(trans, inode, log, sums);
4475 list_del(&sums->list);
4482 ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
4483 batch.total_data_size += ins_sizes[dst_index];
4489 * We have a leaf full of old extent items that don't need to be logged,
4490 * so we don't need to do anything.
4495 ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4500 for (int i = 0; i < nr; i++) {
4501 const int src_slot = start_slot + i;
4502 const int dst_slot = dst_path->slots[0] + dst_index;
4503 struct btrfs_key key;
4504 unsigned long src_offset;
4505 unsigned long dst_offset;
4508 * We're done, all the remaining items in the source leaf
4509 * correspond to old file extent items.
4511 if (dst_index >= batch.nr)
4514 btrfs_item_key_to_cpu(src, &key, src_slot);
4516 if (key.type != BTRFS_EXTENT_DATA_KEY)
4519 extent = btrfs_item_ptr(src, src_slot,
4520 struct btrfs_file_extent_item);
4522 /* See the comment in the previous loop, same logic. */
4523 if (btrfs_file_extent_generation(src, extent) < trans->transid &&
4524 key.offset < i_size &&
4525 inode->last_reflink_trans < trans->transid)
4529 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
4530 src_offset = btrfs_item_ptr_offset(src, src_slot);
4532 if (key.type == BTRFS_INODE_ITEM_KEY) {
4533 struct btrfs_inode_item *inode_item;
4535 inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
4536 struct btrfs_inode_item);
4537 fill_inode_item(trans, dst_path->nodes[0], inode_item,
4539 inode_only == LOG_INODE_EXISTS,
4542 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4543 src_offset, ins_sizes[dst_index]);
4549 btrfs_release_path(dst_path);
4556 static int extent_cmp(void *priv, const struct list_head *a,
4557 const struct list_head *b)
4559 const struct extent_map *em1, *em2;
4561 em1 = list_entry(a, struct extent_map, list);
4562 em2 = list_entry(b, struct extent_map, list);
4564 if (em1->start < em2->start)
4566 else if (em1->start > em2->start)
4571 static int log_extent_csums(struct btrfs_trans_handle *trans,
4572 struct btrfs_inode *inode,
4573 struct btrfs_root *log_root,
4574 const struct extent_map *em,
4575 struct btrfs_log_ctx *ctx)
4577 struct btrfs_ordered_extent *ordered;
4578 struct btrfs_root *csum_root;
4582 u64 mod_start = em->start;
4583 u64 mod_len = em->len;
4584 LIST_HEAD(ordered_sums);
4587 if (inode->flags & BTRFS_INODE_NODATASUM ||
4588 (em->flags & EXTENT_FLAG_PREALLOC) ||
4589 em->disk_bytenr == EXTENT_MAP_HOLE)
4592 list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
4593 const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
4594 const u64 mod_end = mod_start + mod_len;
4595 struct btrfs_ordered_sum *sums;
4600 if (ordered_end <= mod_start)
4602 if (mod_end <= ordered->file_offset)
4606 * We are going to copy all the csums on this ordered extent, so
4607 * go ahead and adjust mod_start and mod_len in case this ordered
4608 * extent has already been logged.
4610 if (ordered->file_offset > mod_start) {
4611 if (ordered_end >= mod_end)
4612 mod_len = ordered->file_offset - mod_start;
4614 * If we have this case
4616 * |--------- logged extent ---------|
4617 * |----- ordered extent ----|
4619 * Just don't mess with mod_start and mod_len, we'll
4620 * just end up logging more csums than we need and it
4624 if (ordered_end < mod_end) {
4625 mod_len = mod_end - ordered_end;
4626 mod_start = ordered_end;
4633 * To keep us from looping for the above case of an ordered
4634 * extent that falls inside of the logged extent.
4636 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
4639 list_for_each_entry(sums, &ordered->list, list) {
4640 ret = log_csums(trans, inode, log_root, sums);
4646 /* We're done, found all csums in the ordered extents. */
4650 /* If we're compressed we have to save the entire range of csums. */
4651 if (btrfs_extent_map_is_compressed(em)) {
4653 csum_len = em->disk_num_bytes;
4655 csum_offset = mod_start - em->start;
4659 /* block start is already adjusted for the file extent offset. */
4660 block_start = btrfs_extent_map_block_start(em);
4661 csum_root = btrfs_csum_root(trans->fs_info, block_start);
4662 ret = btrfs_lookup_csums_list(csum_root, block_start + csum_offset,
4663 block_start + csum_offset + csum_len - 1,
4664 &ordered_sums, false);
4669 while (!list_empty(&ordered_sums)) {
4670 struct btrfs_ordered_sum *sums = list_first_entry(&ordered_sums,
4671 struct btrfs_ordered_sum,
4674 ret = log_csums(trans, inode, log_root, sums);
4675 list_del(&sums->list);
4682 static int log_one_extent(struct btrfs_trans_handle *trans,
4683 struct btrfs_inode *inode,
4684 const struct extent_map *em,
4685 struct btrfs_path *path,
4686 struct btrfs_log_ctx *ctx)
4688 struct btrfs_drop_extents_args drop_args = { 0 };
4689 struct btrfs_root *log = inode->root->log_root;
4690 struct btrfs_file_extent_item fi = { 0 };
4691 struct extent_buffer *leaf;
4692 struct btrfs_key key;
4693 enum btrfs_compression_type compress_type;
4694 u64 extent_offset = em->offset;
4695 u64 block_start = btrfs_extent_map_block_start(em);
4699 btrfs_set_stack_file_extent_generation(&fi, trans->transid);
4700 if (em->flags & EXTENT_FLAG_PREALLOC)
4701 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
4703 btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
4705 block_len = em->disk_num_bytes;
4706 compress_type = btrfs_extent_map_compression(em);
4707 if (compress_type != BTRFS_COMPRESS_NONE) {
4708 btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
4709 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4710 } else if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) {
4711 btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start - extent_offset);
4712 btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4715 btrfs_set_stack_file_extent_offset(&fi, extent_offset);
4716 btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
4717 btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
4718 btrfs_set_stack_file_extent_compression(&fi, compress_type);
4720 ret = log_extent_csums(trans, inode, log, em, ctx);
4725 * If this is the first time we are logging the inode in the current
4726 * transaction, we can avoid btrfs_drop_extents(), which is expensive
4727 * because it does a deletion search, which always acquires write locks
4728 * for extent buffers at levels 2, 1 and 0. This not only wastes time
4729 * but also adds significant contention in a log tree, since log trees
4730 * are small, with a root at level 2 or 3 at most, due to their short
4733 if (ctx->logged_before) {
4734 drop_args.path = path;
4735 drop_args.start = em->start;
4736 drop_args.end = em->start + em->len;
4737 drop_args.replace_extent = true;
4738 drop_args.extent_item_size = sizeof(fi);
4739 ret = btrfs_drop_extents(trans, log, inode, &drop_args);
4744 if (!drop_args.extent_inserted) {
4745 key.objectid = btrfs_ino(inode);
4746 key.type = BTRFS_EXTENT_DATA_KEY;
4747 key.offset = em->start;
4749 ret = btrfs_insert_empty_item(trans, log, path, &key,
4754 leaf = path->nodes[0];
4755 write_extent_buffer(leaf, &fi,
4756 btrfs_item_ptr_offset(leaf, path->slots[0]),
4759 btrfs_release_path(path);
4765 * Log all prealloc extents beyond the inode's i_size to make sure we do not
4766 * lose them after doing a full/fast fsync and replaying the log. We scan the
4767 * subvolume's root instead of iterating the inode's extent map tree because
4768 * otherwise we can log incorrect extent items based on extent map conversion.
4769 * That can happen due to the fact that extent maps are merged when they
4770 * are not in the extent map tree's list of modified extents.
4772 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4773 struct btrfs_inode *inode,
4774 struct btrfs_path *path,
4775 struct btrfs_log_ctx *ctx)
4777 struct btrfs_root *root = inode->root;
4778 struct btrfs_key key;
4779 const u64 i_size = i_size_read(&inode->vfs_inode);
4780 const u64 ino = btrfs_ino(inode);
4781 struct btrfs_path *dst_path = NULL;
4782 bool dropped_extents = false;
4783 u64 truncate_offset = i_size;
4784 struct extent_buffer *leaf;
4790 if (!(inode->flags & BTRFS_INODE_PREALLOC))
4794 key.type = BTRFS_EXTENT_DATA_KEY;
4795 key.offset = i_size;
4796 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4801 * We must check if there is a prealloc extent that starts before the
4802 * i_size and crosses the i_size boundary. This is to ensure later we
4803 * truncate down to the end of that extent and not to the i_size, as
4804 * otherwise we end up losing part of the prealloc extent after a log
4805 * replay and with an implicit hole if there is another prealloc extent
4806 * that starts at an offset beyond i_size.
4808 ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4813 struct btrfs_file_extent_item *ei;
4815 leaf = path->nodes[0];
4816 slot = path->slots[0];
4817 ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4819 if (btrfs_file_extent_type(leaf, ei) ==
4820 BTRFS_FILE_EXTENT_PREALLOC) {
4823 btrfs_item_key_to_cpu(leaf, &key, slot);
4824 extent_end = key.offset +
4825 btrfs_file_extent_num_bytes(leaf, ei);
4827 if (extent_end > i_size)
4828 truncate_offset = extent_end;
4835 leaf = path->nodes[0];
4836 slot = path->slots[0];
4838 if (slot >= btrfs_header_nritems(leaf)) {
4840 ret = copy_items(trans, inode, dst_path, path,
4841 start_slot, ins_nr, 1, 0, ctx);
4846 ret = btrfs_next_leaf(root, path);
4856 btrfs_item_key_to_cpu(leaf, &key, slot);
4857 if (key.objectid > ino)
4859 if (WARN_ON_ONCE(key.objectid < ino) ||
4860 key.type < BTRFS_EXTENT_DATA_KEY ||
4861 key.offset < i_size) {
4866 * Avoid overlapping items in the log tree. The first time we
4867 * get here, get rid of everything from a past fsync. After
4868 * that, if the current extent starts before the end of the last
4869 * extent we copied, truncate the last one. This can happen if
4870 * an ordered extent completion modifies the subvolume tree
4871 * while btrfs_next_leaf() has the tree unlocked.
4873 if (!dropped_extents || key.offset < truncate_offset) {
4874 ret = truncate_inode_items(trans, root->log_root, inode,
4875 min(key.offset, truncate_offset),
4876 BTRFS_EXTENT_DATA_KEY);
4879 dropped_extents = true;
4881 truncate_offset = btrfs_file_extent_end(path);
4887 dst_path = btrfs_alloc_path();
4895 ret = copy_items(trans, inode, dst_path, path,
4896 start_slot, ins_nr, 1, 0, ctx);
4898 btrfs_release_path(path);
4899 btrfs_free_path(dst_path);
4903 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4904 struct btrfs_inode *inode,
4905 struct btrfs_path *path,
4906 struct btrfs_log_ctx *ctx)
4908 struct btrfs_ordered_extent *ordered;
4909 struct btrfs_ordered_extent *tmp;
4910 struct extent_map *em, *n;
4912 struct extent_map_tree *tree = &inode->extent_tree;
4916 write_lock(&tree->lock);
4918 list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4919 list_del_init(&em->list);
4921 * Just an arbitrary number, this can be really CPU intensive
4922 * once we start getting a lot of extents, and really once we
4923 * have a bunch of extents we just want to commit since it will
4926 if (++num > 32768) {
4927 list_del_init(&tree->modified_extents);
4932 if (em->generation < trans->transid)
4935 /* We log prealloc extents beyond eof later. */
4936 if ((em->flags & EXTENT_FLAG_PREALLOC) &&
4937 em->start >= i_size_read(&inode->vfs_inode))
4940 /* Need a ref to keep it from getting evicted from cache */
4941 refcount_inc(&em->refs);
4942 em->flags |= EXTENT_FLAG_LOGGING;
4943 list_add_tail(&em->list, &extents);
4947 list_sort(NULL, &extents, extent_cmp);
4949 while (!list_empty(&extents)) {
4950 em = list_first_entry(&extents, struct extent_map, list);
4952 list_del_init(&em->list);
4955 * If we had an error we just need to delete everybody from our
4959 btrfs_clear_em_logging(inode, em);
4960 btrfs_free_extent_map(em);
4964 write_unlock(&tree->lock);
4966 ret = log_one_extent(trans, inode, em, path, ctx);
4967 write_lock(&tree->lock);
4968 btrfs_clear_em_logging(inode, em);
4969 btrfs_free_extent_map(em);
4971 WARN_ON(!list_empty(&extents));
4972 write_unlock(&tree->lock);
4975 ret = btrfs_log_prealloc_extents(trans, inode, path, ctx);
4980 * We have logged all extents successfully, now make sure the commit of
4981 * the current transaction waits for the ordered extents to complete
4982 * before it commits and wipes out the log trees, otherwise we would
4983 * lose data if an ordered extents completes after the transaction
4984 * commits and a power failure happens after the transaction commit.
4986 list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
4987 list_del_init(&ordered->log_list);
4988 set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
4990 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4991 spin_lock_irq(&inode->ordered_tree_lock);
4992 if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
4993 set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
4994 atomic_inc(&trans->transaction->pending_ordered);
4996 spin_unlock_irq(&inode->ordered_tree_lock);
4998 btrfs_put_ordered_extent(ordered);
5004 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
5005 struct btrfs_path *path, u64 *size_ret)
5007 struct btrfs_key key;
5010 key.objectid = btrfs_ino(inode);
5011 key.type = BTRFS_INODE_ITEM_KEY;
5014 ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
5017 } else if (ret > 0) {
5020 struct btrfs_inode_item *item;
5022 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5023 struct btrfs_inode_item);
5024 *size_ret = btrfs_inode_size(path->nodes[0], item);
5026 * If the in-memory inode's i_size is smaller then the inode
5027 * size stored in the btree, return the inode's i_size, so
5028 * that we get a correct inode size after replaying the log
5029 * when before a power failure we had a shrinking truncate
5030 * followed by addition of a new name (rename / new hard link).
5031 * Otherwise return the inode size from the btree, to avoid
5032 * data loss when replaying a log due to previously doing a
5033 * write that expands the inode's size and logging a new name
5034 * immediately after.
5036 if (*size_ret > inode->vfs_inode.i_size)
5037 *size_ret = inode->vfs_inode.i_size;
5040 btrfs_release_path(path);
5045 * At the moment we always log all xattrs. This is to figure out at log replay
5046 * time which xattrs must have their deletion replayed. If a xattr is missing
5047 * in the log tree and exists in the fs/subvol tree, we delete it. This is
5048 * because if a xattr is deleted, the inode is fsynced and a power failure
5049 * happens, causing the log to be replayed the next time the fs is mounted,
5050 * we want the xattr to not exist anymore (same behaviour as other filesystems
5051 * with a journal, ext3/4, xfs, f2fs, etc).
5053 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
5054 struct btrfs_inode *inode,
5055 struct btrfs_path *path,
5056 struct btrfs_path *dst_path,
5057 struct btrfs_log_ctx *ctx)
5059 struct btrfs_root *root = inode->root;
5061 struct btrfs_key key;
5062 const u64 ino = btrfs_ino(inode);
5065 bool found_xattrs = false;
5067 if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5071 key.type = BTRFS_XATTR_ITEM_KEY;
5074 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5079 int slot = path->slots[0];
5080 struct extent_buffer *leaf = path->nodes[0];
5081 int nritems = btrfs_header_nritems(leaf);
5083 if (slot >= nritems) {
5085 ret = copy_items(trans, inode, dst_path, path,
5086 start_slot, ins_nr, 1, 0, ctx);
5091 ret = btrfs_next_leaf(root, path);
5099 btrfs_item_key_to_cpu(leaf, &key, slot);
5100 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
5107 found_xattrs = true;
5111 ret = copy_items(trans, inode, dst_path, path,
5112 start_slot, ins_nr, 1, 0, ctx);
5118 set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5124 * When using the NO_HOLES feature if we punched a hole that causes the
5125 * deletion of entire leafs or all the extent items of the first leaf (the one
5126 * that contains the inode item and references) we may end up not processing
5127 * any extents, because there are no leafs with a generation matching the
5128 * current transaction that have extent items for our inode. So we need to find
5129 * if any holes exist and then log them. We also need to log holes after any
5130 * truncate operation that changes the inode's size.
5132 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5133 struct btrfs_inode *inode,
5134 struct btrfs_path *path)
5136 struct btrfs_root *root = inode->root;
5137 struct btrfs_fs_info *fs_info = root->fs_info;
5138 struct btrfs_key key;
5139 const u64 ino = btrfs_ino(inode);
5140 const u64 i_size = i_size_read(&inode->vfs_inode);
5141 u64 prev_extent_end = 0;
5144 if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5148 key.type = BTRFS_EXTENT_DATA_KEY;
5151 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5156 struct extent_buffer *leaf = path->nodes[0];
5158 if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5159 ret = btrfs_next_leaf(root, path);
5166 leaf = path->nodes[0];
5169 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5170 if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
5173 /* We have a hole, log it. */
5174 if (prev_extent_end < key.offset) {
5175 const u64 hole_len = key.offset - prev_extent_end;
5178 * Release the path to avoid deadlocks with other code
5179 * paths that search the root while holding locks on
5180 * leafs from the log root.
5182 btrfs_release_path(path);
5183 ret = btrfs_insert_hole_extent(trans, root->log_root,
5184 ino, prev_extent_end,
5190 * Search for the same key again in the root. Since it's
5191 * an extent item and we are holding the inode lock, the
5192 * key must still exist. If it doesn't just emit warning
5193 * and return an error to fall back to a transaction
5196 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5199 if (WARN_ON(ret > 0))
5201 leaf = path->nodes[0];
5204 prev_extent_end = btrfs_file_extent_end(path);
5209 if (prev_extent_end < i_size) {
5212 btrfs_release_path(path);
5213 hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5214 ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5215 prev_extent_end, hole_len);
5224 * When we are logging a new inode X, check if it doesn't have a reference that
5225 * matches the reference from some other inode Y created in a past transaction
5226 * and that was renamed in the current transaction. If we don't do this, then at
5227 * log replay time we can lose inode Y (and all its files if it's a directory):
5230 * echo "hello world" > /mnt/x/foobar
5233 * mkdir /mnt/x # or touch /mnt/x
5234 * xfs_io -c fsync /mnt/x
5236 * mount fs, trigger log replay
5238 * After the log replay procedure, we would lose the first directory and all its
5239 * files (file foobar).
5240 * For the case where inode Y is not a directory we simply end up losing it:
5242 * echo "123" > /mnt/foo
5244 * mv /mnt/foo /mnt/bar
5245 * echo "abc" > /mnt/foo
5246 * xfs_io -c fsync /mnt/foo
5249 * We also need this for cases where a snapshot entry is replaced by some other
5250 * entry (file or directory) otherwise we end up with an unreplayable log due to
5251 * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
5252 * if it were a regular entry:
5255 * btrfs subvolume snapshot /mnt /mnt/x/snap
5256 * btrfs subvolume delete /mnt/x/snap
5259 * fsync /mnt/x or fsync some new file inside it
5262 * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
5263 * the same transaction.
5265 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
5267 const struct btrfs_key *key,
5268 struct btrfs_inode *inode,
5269 u64 *other_ino, u64 *other_parent)
5272 struct btrfs_path *search_path;
5275 u32 item_size = btrfs_item_size(eb, slot);
5277 unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
5279 search_path = btrfs_alloc_path();
5282 search_path->search_commit_root = 1;
5283 search_path->skip_locking = 1;
5285 while (cur_offset < item_size) {
5289 unsigned long name_ptr;
5290 struct btrfs_dir_item *di;
5291 struct fscrypt_str name_str;
5293 if (key->type == BTRFS_INODE_REF_KEY) {
5294 struct btrfs_inode_ref *iref;
5296 iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
5297 parent = key->offset;
5298 this_name_len = btrfs_inode_ref_name_len(eb, iref);
5299 name_ptr = (unsigned long)(iref + 1);
5300 this_len = sizeof(*iref) + this_name_len;
5302 struct btrfs_inode_extref *extref;
5304 extref = (struct btrfs_inode_extref *)(ptr +
5306 parent = btrfs_inode_extref_parent(eb, extref);
5307 this_name_len = btrfs_inode_extref_name_len(eb, extref);
5308 name_ptr = (unsigned long)&extref->name;
5309 this_len = sizeof(*extref) + this_name_len;
5312 if (this_name_len > name_len) {
5315 new_name = krealloc(name, this_name_len, GFP_NOFS);
5320 name_len = this_name_len;
5324 read_extent_buffer(eb, name, name_ptr, this_name_len);
5326 name_str.name = name;
5327 name_str.len = this_name_len;
5328 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5329 parent, &name_str, 0);
5330 if (di && !IS_ERR(di)) {
5331 struct btrfs_key di_key;
5333 btrfs_dir_item_key_to_cpu(search_path->nodes[0],
5335 if (di_key.type == BTRFS_INODE_ITEM_KEY) {
5336 if (di_key.objectid != key->objectid) {
5338 *other_ino = di_key.objectid;
5339 *other_parent = parent;
5347 } else if (IS_ERR(di)) {
5351 btrfs_release_path(search_path);
5353 cur_offset += this_len;
5357 btrfs_free_path(search_path);
5363 * Check if we need to log an inode. This is used in contexts where while
5364 * logging an inode we need to log another inode (either that it exists or in
5365 * full mode). This is used instead of btrfs_inode_in_log() because the later
5366 * requires the inode to be in the log and have the log transaction committed,
5367 * while here we do not care if the log transaction was already committed - our
5368 * caller will commit the log later - and we want to avoid logging an inode
5369 * multiple times when multiple tasks have joined the same log transaction.
5371 static bool need_log_inode(const struct btrfs_trans_handle *trans,
5372 struct btrfs_inode *inode)
5375 * If a directory was not modified, no dentries added or removed, we can
5376 * and should avoid logging it.
5378 if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5382 * If this inode does not have new/updated/deleted xattrs since the last
5383 * time it was logged and is flagged as logged in the current transaction,
5384 * we can skip logging it. As for new/deleted names, those are updated in
5385 * the log by link/unlink/rename operations.
5386 * In case the inode was logged and then evicted and reloaded, its
5387 * logged_trans will be 0, in which case we have to fully log it since
5388 * logged_trans is a transient field, not persisted.
5390 if (inode_logged(trans, inode, NULL) == 1 &&
5391 !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5397 struct btrfs_dir_list {
5399 struct list_head list;
5403 * Log the inodes of the new dentries of a directory.
5404 * See process_dir_items_leaf() for details about why it is needed.
5405 * This is a recursive operation - if an existing dentry corresponds to a
5406 * directory, that directory's new entries are logged too (same behaviour as
5407 * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5408 * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5409 * complains about the following circular lock dependency / possible deadlock:
5413 * lock(&type->i_mutex_dir_key#3/2);
5414 * lock(sb_internal#2);
5415 * lock(&type->i_mutex_dir_key#3/2);
5416 * lock(&sb->s_type->i_mutex_key#14);
5418 * Where sb_internal is the lock (a counter that works as a lock) acquired by
5419 * sb_start_intwrite() in btrfs_start_transaction().
5420 * Not acquiring the VFS lock of the inodes is still safe because:
5422 * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5423 * that while logging the inode new references (names) are added or removed
5424 * from the inode, leaving the logged inode item with a link count that does
5425 * not match the number of logged inode reference items. This is fine because
5426 * at log replay time we compute the real number of links and correct the
5427 * link count in the inode item (see replay_one_buffer() and
5428 * link_to_fixup_dir());
5430 * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5431 * while logging the inode's items new index items (key type
5432 * BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5433 * has a size that doesn't match the sum of the lengths of all the logged
5434 * names - this is ok, not a problem, because at log replay time we set the
5435 * directory's i_size to the correct value (see replay_one_name() and
5436 * overwrite_item()).
5438 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5439 struct btrfs_inode *start_inode,
5440 struct btrfs_log_ctx *ctx)
5442 struct btrfs_root *root = start_inode->root;
5443 struct btrfs_path *path;
5444 LIST_HEAD(dir_list);
5445 struct btrfs_dir_list *dir_elem;
5446 u64 ino = btrfs_ino(start_inode);
5447 struct btrfs_inode *curr_inode = start_inode;
5451 * If we are logging a new name, as part of a link or rename operation,
5452 * don't bother logging new dentries, as we just want to log the names
5453 * of an inode and that any new parents exist.
5455 if (ctx->logging_new_name)
5458 path = btrfs_alloc_path();
5462 /* Pairs with btrfs_add_delayed_iput below. */
5463 ihold(&curr_inode->vfs_inode);
5466 struct btrfs_key key;
5467 struct btrfs_key found_key;
5469 bool continue_curr_inode = true;
5473 key.type = BTRFS_DIR_INDEX_KEY;
5474 key.offset = btrfs_get_first_dir_index_to_log(curr_inode);
5475 next_index = key.offset;
5477 btrfs_for_each_slot(root->log_root, &key, &found_key, path, iter_ret) {
5478 struct extent_buffer *leaf = path->nodes[0];
5479 struct btrfs_dir_item *di;
5480 struct btrfs_key di_key;
5481 struct btrfs_inode *di_inode;
5482 int log_mode = LOG_INODE_EXISTS;
5485 if (found_key.objectid != ino ||
5486 found_key.type != BTRFS_DIR_INDEX_KEY) {
5487 continue_curr_inode = false;
5491 next_index = found_key.offset + 1;
5493 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
5494 type = btrfs_dir_ftype(leaf, di);
5495 if (btrfs_dir_transid(leaf, di) < trans->transid)
5497 btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5498 if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5501 btrfs_release_path(path);
5502 di_inode = btrfs_iget_logging(di_key.objectid, root);
5503 if (IS_ERR(di_inode)) {
5504 ret = PTR_ERR(di_inode);
5508 if (!need_log_inode(trans, di_inode)) {
5509 btrfs_add_delayed_iput(di_inode);
5513 ctx->log_new_dentries = false;
5514 if (type == BTRFS_FT_DIR)
5515 log_mode = LOG_INODE_ALL;
5516 ret = btrfs_log_inode(trans, di_inode, log_mode, ctx);
5517 btrfs_add_delayed_iput(di_inode);
5520 if (ctx->log_new_dentries) {
5521 dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5526 dir_elem->ino = di_key.objectid;
5527 list_add_tail(&dir_elem->list, &dir_list);
5532 btrfs_release_path(path);
5537 } else if (iter_ret > 0) {
5538 continue_curr_inode = false;
5543 if (continue_curr_inode && key.offset < (u64)-1) {
5548 btrfs_set_first_dir_index_to_log(curr_inode, next_index);
5550 if (list_empty(&dir_list))
5553 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
5554 ino = dir_elem->ino;
5555 list_del(&dir_elem->list);
5558 btrfs_add_delayed_iput(curr_inode);
5560 curr_inode = btrfs_iget_logging(ino, root);
5561 if (IS_ERR(curr_inode)) {
5562 ret = PTR_ERR(curr_inode);
5568 btrfs_free_path(path);
5570 btrfs_add_delayed_iput(curr_inode);
5573 struct btrfs_dir_list *next;
5575 list_for_each_entry_safe(dir_elem, next, &dir_list, list)
5582 struct btrfs_ino_list {
5585 struct list_head list;
5588 static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
5590 struct btrfs_ino_list *curr;
5591 struct btrfs_ino_list *next;
5593 list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
5594 list_del(&curr->list);
5599 static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
5600 struct btrfs_path *path)
5602 struct btrfs_key key;
5606 key.type = BTRFS_INODE_ITEM_KEY;
5609 path->search_commit_root = 1;
5610 path->skip_locking = 1;
5612 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5613 if (WARN_ON_ONCE(ret > 0)) {
5615 * We have previously found the inode through the commit root
5616 * so this should not happen. If it does, just error out and
5617 * fallback to a transaction commit.
5620 } else if (ret == 0) {
5621 struct btrfs_inode_item *item;
5623 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5624 struct btrfs_inode_item);
5625 if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
5629 btrfs_release_path(path);
5630 path->search_commit_root = 0;
5631 path->skip_locking = 0;
5636 static int add_conflicting_inode(struct btrfs_trans_handle *trans,
5637 struct btrfs_root *root,
5638 struct btrfs_path *path,
5639 u64 ino, u64 parent,
5640 struct btrfs_log_ctx *ctx)
5642 struct btrfs_ino_list *ino_elem;
5643 struct btrfs_inode *inode;
5646 * It's rare to have a lot of conflicting inodes, in practice it is not
5647 * common to have more than 1 or 2. We don't want to collect too many,
5648 * as we could end up logging too many inodes (even if only in
5649 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
5652 if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES)
5653 return BTRFS_LOG_FORCE_COMMIT;
5655 inode = btrfs_iget_logging(ino, root);
5657 * If the other inode that had a conflicting dir entry was deleted in
5658 * the current transaction then we either:
5660 * 1) Log the parent directory (later after adding it to the list) if
5661 * the inode is a directory. This is because it may be a deleted
5662 * subvolume/snapshot or it may be a regular directory that had
5663 * deleted subvolumes/snapshots (or subdirectories that had them),
5664 * and at the moment we can't deal with dropping subvolumes/snapshots
5665 * during log replay. So we just log the parent, which will result in
5666 * a fallback to a transaction commit if we are dealing with those
5667 * cases (last_unlink_trans will match the current transaction);
5669 * 2) Do nothing if it's not a directory. During log replay we simply
5670 * unlink the conflicting dentry from the parent directory and then
5671 * add the dentry for our inode. Like this we can avoid logging the
5672 * parent directory (and maybe fallback to a transaction commit in
5673 * case it has a last_unlink_trans == trans->transid, due to moving
5674 * some inode from it to some other directory).
5676 if (IS_ERR(inode)) {
5677 int ret = PTR_ERR(inode);
5682 ret = conflicting_inode_is_dir(root, ino, path);
5683 /* Not a directory or we got an error. */
5687 /* Conflicting inode is a directory, so we'll log its parent. */
5688 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5691 ino_elem->ino = ino;
5692 ino_elem->parent = parent;
5693 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5694 ctx->num_conflict_inodes++;
5700 * If the inode was already logged skip it - otherwise we can hit an
5701 * infinite loop. Example:
5703 * From the commit root (previous transaction) we have the following
5706 * inode 257 a directory
5707 * inode 258 with references "zz" and "zz_link" on inode 257
5708 * inode 259 with reference "a" on inode 257
5710 * And in the current (uncommitted) transaction we have:
5712 * inode 257 a directory, unchanged
5713 * inode 258 with references "a" and "a2" on inode 257
5714 * inode 259 with reference "zz_link" on inode 257
5715 * inode 261 with reference "zz" on inode 257
5717 * When logging inode 261 the following infinite loop could
5718 * happen if we don't skip already logged inodes:
5720 * - we detect inode 258 as a conflicting inode, with inode 261
5721 * on reference "zz", and log it;
5723 * - we detect inode 259 as a conflicting inode, with inode 258
5724 * on reference "a", and log it;
5726 * - we detect inode 258 as a conflicting inode, with inode 259
5727 * on reference "zz_link", and log it - again! After this we
5728 * repeat the above steps forever.
5730 * Here we can use need_log_inode() because we only need to log the
5731 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
5732 * so that the log ends up with the new name and without the old name.
5734 if (!need_log_inode(trans, inode)) {
5735 btrfs_add_delayed_iput(inode);
5739 btrfs_add_delayed_iput(inode);
5741 ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5744 ino_elem->ino = ino;
5745 ino_elem->parent = parent;
5746 list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5747 ctx->num_conflict_inodes++;
5752 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
5753 struct btrfs_root *root,
5754 struct btrfs_log_ctx *ctx)
5759 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
5760 * otherwise we could have unbounded recursion of btrfs_log_inode()
5761 * calls. This check guarantees we can have only 1 level of recursion.
5763 if (ctx->logging_conflict_inodes)
5766 ctx->logging_conflict_inodes = true;
5769 * New conflicting inodes may be found and added to the list while we
5770 * are logging a conflicting inode, so keep iterating while the list is
5773 while (!list_empty(&ctx->conflict_inodes)) {
5774 struct btrfs_ino_list *curr;
5775 struct btrfs_inode *inode;
5779 curr = list_first_entry(&ctx->conflict_inodes,
5780 struct btrfs_ino_list, list);
5782 parent = curr->parent;
5783 list_del(&curr->list);
5786 inode = btrfs_iget_logging(ino, root);
5788 * If the other inode that had a conflicting dir entry was
5789 * deleted in the current transaction, we need to log its parent
5790 * directory. See the comment at add_conflicting_inode().
5792 if (IS_ERR(inode)) {
5793 ret = PTR_ERR(inode);
5797 inode = btrfs_iget_logging(parent, root);
5798 if (IS_ERR(inode)) {
5799 ret = PTR_ERR(inode);
5804 * Always log the directory, we cannot make this
5805 * conditional on need_log_inode() because the directory
5806 * might have been logged in LOG_INODE_EXISTS mode or
5807 * the dir index of the conflicting inode is not in a
5808 * dir index key range logged for the directory. So we
5809 * must make sure the deletion is recorded.
5811 ret = btrfs_log_inode(trans, inode, LOG_INODE_ALL, ctx);
5812 btrfs_add_delayed_iput(inode);
5819 * Here we can use need_log_inode() because we only need to log
5820 * the inode in LOG_INODE_EXISTS mode and rename operations
5821 * update the log, so that the log ends up with the new name and
5822 * without the old name.
5824 * We did this check at add_conflicting_inode(), but here we do
5825 * it again because if some other task logged the inode after
5826 * that, we can avoid doing it again.
5828 if (!need_log_inode(trans, inode)) {
5829 btrfs_add_delayed_iput(inode);
5834 * We are safe logging the other inode without acquiring its
5835 * lock as long as we log with the LOG_INODE_EXISTS mode. We
5836 * are safe against concurrent renames of the other inode as
5837 * well because during a rename we pin the log and update the
5838 * log with the new name before we unpin it.
5840 ret = btrfs_log_inode(trans, inode, LOG_INODE_EXISTS, ctx);
5841 btrfs_add_delayed_iput(inode);
5846 ctx->logging_conflict_inodes = false;
5848 free_conflicting_inodes(ctx);
5853 static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
5854 struct btrfs_inode *inode,
5855 struct btrfs_key *min_key,
5856 const struct btrfs_key *max_key,
5857 struct btrfs_path *path,
5858 struct btrfs_path *dst_path,
5859 const u64 logged_isize,
5860 const int inode_only,
5861 struct btrfs_log_ctx *ctx,
5862 bool *need_log_inode_item)
5864 const u64 i_size = i_size_read(&inode->vfs_inode);
5865 struct btrfs_root *root = inode->root;
5866 int ins_start_slot = 0;
5871 ret = btrfs_search_forward(root, min_key, path, trans->transid);
5879 /* Note, ins_nr might be > 0 here, cleanup outside the loop */
5880 if (min_key->objectid != max_key->objectid)
5882 if (min_key->type > max_key->type)
5885 if (min_key->type == BTRFS_INODE_ITEM_KEY) {
5886 *need_log_inode_item = false;
5887 } else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
5888 min_key->offset >= i_size) {
5890 * Extents at and beyond eof are logged with
5891 * btrfs_log_prealloc_extents().
5892 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
5893 * and no keys greater than that, so bail out.
5896 } else if ((min_key->type == BTRFS_INODE_REF_KEY ||
5897 min_key->type == BTRFS_INODE_EXTREF_KEY) &&
5898 (inode->generation == trans->transid ||
5899 ctx->logging_conflict_inodes)) {
5901 u64 other_parent = 0;
5903 ret = btrfs_check_ref_name_override(path->nodes[0],
5904 path->slots[0], min_key, inode,
5905 &other_ino, &other_parent);
5908 } else if (ret > 0 &&
5909 other_ino != btrfs_ino(ctx->inode)) {
5914 ins_start_slot = path->slots[0];
5916 ret = copy_items(trans, inode, dst_path, path,
5917 ins_start_slot, ins_nr,
5918 inode_only, logged_isize, ctx);
5923 btrfs_release_path(path);
5924 ret = add_conflicting_inode(trans, root, path,
5931 } else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
5932 /* Skip xattrs, logged later with btrfs_log_all_xattrs() */
5935 ret = copy_items(trans, inode, dst_path, path,
5937 ins_nr, inode_only, logged_isize, ctx);
5944 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5947 } else if (!ins_nr) {
5948 ins_start_slot = path->slots[0];
5953 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5954 ins_nr, inode_only, logged_isize, ctx);
5958 ins_start_slot = path->slots[0];
5961 if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
5962 btrfs_item_key_to_cpu(path->nodes[0], min_key,
5967 ret = copy_items(trans, inode, dst_path, path,
5968 ins_start_slot, ins_nr, inode_only,
5974 btrfs_release_path(path);
5976 if (min_key->offset < (u64)-1) {
5978 } else if (min_key->type < max_key->type) {
5980 min_key->offset = 0;
5986 * We may process many leaves full of items for our inode, so
5987 * avoid monopolizing a cpu for too long by rescheduling while
5988 * not holding locks on any tree.
5993 ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5994 ins_nr, inode_only, logged_isize, ctx);
5999 if (inode_only == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
6001 * Release the path because otherwise we might attempt to double
6002 * lock the same leaf with btrfs_log_prealloc_extents() below.
6004 btrfs_release_path(path);
6005 ret = btrfs_log_prealloc_extents(trans, inode, dst_path, ctx);
6011 static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
6012 struct btrfs_root *log,
6013 struct btrfs_path *path,
6014 const struct btrfs_item_batch *batch,
6015 const struct btrfs_delayed_item *first_item)
6017 const struct btrfs_delayed_item *curr = first_item;
6020 ret = btrfs_insert_empty_items(trans, log, path, batch);
6024 for (int i = 0; i < batch->nr; i++) {
6027 data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
6028 write_extent_buffer(path->nodes[0], &curr->data,
6029 (unsigned long)data_ptr, curr->data_len);
6030 curr = list_next_entry(curr, log_list);
6034 btrfs_release_path(path);
6039 static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
6040 struct btrfs_inode *inode,
6041 struct btrfs_path *path,
6042 const struct list_head *delayed_ins_list,
6043 struct btrfs_log_ctx *ctx)
6045 /* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
6046 const int max_batch_size = 195;
6047 const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
6048 const u64 ino = btrfs_ino(inode);
6049 struct btrfs_root *log = inode->root->log_root;
6050 struct btrfs_item_batch batch = {
6052 .total_data_size = 0,
6054 const struct btrfs_delayed_item *first = NULL;
6055 const struct btrfs_delayed_item *curr;
6057 struct btrfs_key *ins_keys;
6059 u64 curr_batch_size = 0;
6063 /* We are adding dir index items to the log tree. */
6064 lockdep_assert_held(&inode->log_mutex);
6067 * We collect delayed items before copying index keys from the subvolume
6068 * to the log tree. However just after we collected them, they may have
6069 * been flushed (all of them or just some of them), and therefore we
6070 * could have copied them from the subvolume tree to the log tree.
6071 * So find the first delayed item that was not yet logged (they are
6072 * sorted by index number).
6074 list_for_each_entry(curr, delayed_ins_list, log_list) {
6075 if (curr->index > inode->last_dir_index_offset) {
6081 /* Empty list or all delayed items were already logged. */
6085 ins_data = kmalloc(max_batch_size * sizeof(u32) +
6086 max_batch_size * sizeof(struct btrfs_key), GFP_NOFS);
6089 ins_sizes = (u32 *)ins_data;
6090 batch.data_sizes = ins_sizes;
6091 ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
6092 batch.keys = ins_keys;
6095 while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
6096 const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
6098 if (curr_batch_size + curr_size > leaf_data_size ||
6099 batch.nr == max_batch_size) {
6100 ret = insert_delayed_items_batch(trans, log, path,
6106 batch.total_data_size = 0;
6107 curr_batch_size = 0;
6111 ins_sizes[batch_idx] = curr->data_len;
6112 ins_keys[batch_idx].objectid = ino;
6113 ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
6114 ins_keys[batch_idx].offset = curr->index;
6115 curr_batch_size += curr_size;
6116 batch.total_data_size += curr->data_len;
6119 curr = list_next_entry(curr, log_list);
6122 ASSERT(batch.nr >= 1);
6123 ret = insert_delayed_items_batch(trans, log, path, &batch, first);
6125 curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
6127 inode->last_dir_index_offset = curr->index;
6134 static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
6135 struct btrfs_inode *inode,
6136 struct btrfs_path *path,
6137 const struct list_head *delayed_del_list,
6138 struct btrfs_log_ctx *ctx)
6140 const u64 ino = btrfs_ino(inode);
6141 const struct btrfs_delayed_item *curr;
6143 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6146 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6147 u64 first_dir_index = curr->index;
6149 const struct btrfs_delayed_item *next;
6153 * Find a range of consecutive dir index items to delete. Like
6154 * this we log a single dir range item spanning several contiguous
6155 * dir items instead of logging one range item per dir index item.
6157 next = list_next_entry(curr, log_list);
6158 while (!list_entry_is_head(next, delayed_del_list, log_list)) {
6159 if (next->index != curr->index + 1)
6162 next = list_next_entry(next, log_list);
6165 last_dir_index = curr->index;
6166 ASSERT(last_dir_index >= first_dir_index);
6168 ret = insert_dir_log_key(trans, inode->root->log_root, path,
6169 ino, first_dir_index, last_dir_index);
6172 curr = list_next_entry(curr, log_list);
6178 static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
6179 struct btrfs_inode *inode,
6180 struct btrfs_path *path,
6181 const struct list_head *delayed_del_list,
6182 const struct btrfs_delayed_item *first,
6183 const struct btrfs_delayed_item **last_ret)
6185 const struct btrfs_delayed_item *next;
6186 struct extent_buffer *leaf = path->nodes[0];
6187 const int last_slot = btrfs_header_nritems(leaf) - 1;
6188 int slot = path->slots[0] + 1;
6189 const u64 ino = btrfs_ino(inode);
6191 next = list_next_entry(first, log_list);
6193 while (slot < last_slot &&
6194 !list_entry_is_head(next, delayed_del_list, log_list)) {
6195 struct btrfs_key key;
6197 btrfs_item_key_to_cpu(leaf, &key, slot);
6198 if (key.objectid != ino ||
6199 key.type != BTRFS_DIR_INDEX_KEY ||
6200 key.offset != next->index)
6205 next = list_next_entry(next, log_list);
6208 return btrfs_del_items(trans, inode->root->log_root, path,
6209 path->slots[0], slot - path->slots[0]);
6212 static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
6213 struct btrfs_inode *inode,
6214 struct btrfs_path *path,
6215 const struct list_head *delayed_del_list,
6216 struct btrfs_log_ctx *ctx)
6218 struct btrfs_root *log = inode->root->log_root;
6219 const struct btrfs_delayed_item *curr;
6220 u64 last_range_start = 0;
6221 u64 last_range_end = 0;
6222 struct btrfs_key key;
6224 key.objectid = btrfs_ino(inode);
6225 key.type = BTRFS_DIR_INDEX_KEY;
6226 curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6229 while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6230 const struct btrfs_delayed_item *last = curr;
6231 u64 first_dir_index = curr->index;
6233 bool deleted_items = false;
6236 key.offset = curr->index;
6237 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
6240 } else if (ret == 0) {
6241 ret = batch_delete_dir_index_items(trans, inode, path,
6242 delayed_del_list, curr,
6246 deleted_items = true;
6249 btrfs_release_path(path);
6252 * If we deleted items from the leaf, it means we have a range
6253 * item logging their range, so no need to add one or update an
6254 * existing one. Otherwise we have to log a dir range item.
6259 last_dir_index = last->index;
6260 ASSERT(last_dir_index >= first_dir_index);
6262 * If this range starts right after where the previous one ends,
6263 * then we want to reuse the previous range item and change its
6264 * end offset to the end of this range. This is just to minimize
6265 * leaf space usage, by avoiding adding a new range item.
6267 if (last_range_end != 0 && first_dir_index == last_range_end + 1)
6268 first_dir_index = last_range_start;
6270 ret = insert_dir_log_key(trans, log, path, key.objectid,
6271 first_dir_index, last_dir_index);
6275 last_range_start = first_dir_index;
6276 last_range_end = last_dir_index;
6278 curr = list_next_entry(last, log_list);
6284 static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
6285 struct btrfs_inode *inode,
6286 struct btrfs_path *path,
6287 const struct list_head *delayed_del_list,
6288 struct btrfs_log_ctx *ctx)
6291 * We are deleting dir index items from the log tree or adding range
6294 lockdep_assert_held(&inode->log_mutex);
6296 if (list_empty(delayed_del_list))
6299 if (ctx->logged_before)
6300 return log_delayed_deletions_incremental(trans, inode, path,
6301 delayed_del_list, ctx);
6303 return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
6308 * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
6309 * items instead of the subvolume tree.
6311 static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
6312 struct btrfs_inode *inode,
6313 const struct list_head *delayed_ins_list,
6314 struct btrfs_log_ctx *ctx)
6316 const bool orig_log_new_dentries = ctx->log_new_dentries;
6317 struct btrfs_delayed_item *item;
6321 * No need for the log mutex, plus to avoid potential deadlocks or
6322 * lockdep annotations due to nesting of delayed inode mutexes and log
6325 lockdep_assert_not_held(&inode->log_mutex);
6327 ASSERT(!ctx->logging_new_delayed_dentries);
6328 ctx->logging_new_delayed_dentries = true;
6330 list_for_each_entry(item, delayed_ins_list, log_list) {
6331 struct btrfs_dir_item *dir_item;
6332 struct btrfs_inode *di_inode;
6333 struct btrfs_key key;
6334 int log_mode = LOG_INODE_EXISTS;
6336 dir_item = (struct btrfs_dir_item *)item->data;
6337 btrfs_disk_key_to_cpu(&key, &dir_item->location);
6339 if (key.type == BTRFS_ROOT_ITEM_KEY)
6342 di_inode = btrfs_iget_logging(key.objectid, inode->root);
6343 if (IS_ERR(di_inode)) {
6344 ret = PTR_ERR(di_inode);
6348 if (!need_log_inode(trans, di_inode)) {
6349 btrfs_add_delayed_iput(di_inode);
6353 if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
6354 log_mode = LOG_INODE_ALL;
6356 ctx->log_new_dentries = false;
6357 ret = btrfs_log_inode(trans, di_inode, log_mode, ctx);
6359 if (!ret && ctx->log_new_dentries)
6360 ret = log_new_dir_dentries(trans, di_inode, ctx);
6362 btrfs_add_delayed_iput(di_inode);
6368 ctx->log_new_dentries = orig_log_new_dentries;
6369 ctx->logging_new_delayed_dentries = false;
6374 /* log a single inode in the tree log.
6375 * At least one parent directory for this inode must exist in the tree
6376 * or be logged already.
6378 * Any items from this inode changed by the current transaction are copied
6379 * to the log tree. An extra reference is taken on any extents in this
6380 * file, allowing us to avoid a whole pile of corner cases around logging
6381 * blocks that have been removed from the tree.
6383 * See LOG_INODE_ALL and related defines for a description of what inode_only
6386 * This handles both files and directories.
6388 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
6389 struct btrfs_inode *inode,
6391 struct btrfs_log_ctx *ctx)
6393 struct btrfs_path *path;
6394 struct btrfs_path *dst_path;
6395 struct btrfs_key min_key;
6396 struct btrfs_key max_key;
6397 struct btrfs_root *log = inode->root->log_root;
6399 bool fast_search = false;
6400 u64 ino = btrfs_ino(inode);
6401 struct extent_map_tree *em_tree = &inode->extent_tree;
6402 u64 logged_isize = 0;
6403 bool need_log_inode_item = true;
6404 bool xattrs_logged = false;
6405 bool inode_item_dropped = true;
6406 bool full_dir_logging = false;
6407 LIST_HEAD(delayed_ins_list);
6408 LIST_HEAD(delayed_del_list);
6410 path = btrfs_alloc_path();
6413 dst_path = btrfs_alloc_path();
6415 btrfs_free_path(path);
6419 min_key.objectid = ino;
6420 min_key.type = BTRFS_INODE_ITEM_KEY;
6423 max_key.objectid = ino;
6426 /* today the code can only do partial logging of directories */
6427 if (S_ISDIR(inode->vfs_inode.i_mode) ||
6428 (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6429 &inode->runtime_flags) &&
6430 inode_only >= LOG_INODE_EXISTS))
6431 max_key.type = BTRFS_XATTR_ITEM_KEY;
6433 max_key.type = (u8)-1;
6434 max_key.offset = (u64)-1;
6436 if (S_ISDIR(inode->vfs_inode.i_mode) && inode_only == LOG_INODE_ALL)
6437 full_dir_logging = true;
6440 * If we are logging a directory while we are logging dentries of the
6441 * delayed items of some other inode, then we need to flush the delayed
6442 * items of this directory and not log the delayed items directly. This
6443 * is to prevent more than one level of recursion into btrfs_log_inode()
6444 * by having something like this:
6446 * $ mkdir -p a/b/c/d/e/f/g/h/...
6447 * $ xfs_io -c "fsync" a
6449 * Where all directories in the path did not exist before and are
6450 * created in the current transaction.
6451 * So in such a case we directly log the delayed items of the main
6452 * directory ("a") without flushing them first, while for each of its
6453 * subdirectories we flush their delayed items before logging them.
6454 * This prevents a potential unbounded recursion like this:
6457 * log_new_delayed_dentries()
6459 * log_new_delayed_dentries()
6461 * log_new_delayed_dentries()
6464 * We have thresholds for the maximum number of delayed items to have in
6465 * memory, and once they are hit, the items are flushed asynchronously.
6466 * However the limit is quite high, so lets prevent deep levels of
6467 * recursion to happen by limiting the maximum depth to be 1.
6469 if (full_dir_logging && ctx->logging_new_delayed_dentries) {
6470 ret = btrfs_commit_inode_delayed_items(trans, inode);
6475 mutex_lock(&inode->log_mutex);
6478 * For symlinks, we must always log their content, which is stored in an
6479 * inline extent, otherwise we could end up with an empty symlink after
6480 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
6481 * one attempts to create an empty symlink).
6482 * We don't need to worry about flushing delalloc, because when we create
6483 * the inline extent when the symlink is created (we never have delalloc
6486 if (S_ISLNK(inode->vfs_inode.i_mode))
6487 inode_only = LOG_INODE_ALL;
6490 * Before logging the inode item, cache the value returned by
6491 * inode_logged(), because after that we have the need to figure out if
6492 * the inode was previously logged in this transaction.
6494 ret = inode_logged(trans, inode, path);
6497 ctx->logged_before = (ret == 1);
6501 * This is for cases where logging a directory could result in losing a
6502 * a file after replaying the log. For example, if we move a file from a
6503 * directory A to a directory B, then fsync directory A, we have no way
6504 * to known the file was moved from A to B, so logging just A would
6505 * result in losing the file after a log replay.
6507 if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
6508 ret = BTRFS_LOG_FORCE_COMMIT;
6513 * a brute force approach to making sure we get the most uptodate
6514 * copies of everything.
6516 if (S_ISDIR(inode->vfs_inode.i_mode)) {
6517 clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
6518 if (ctx->logged_before)
6519 ret = drop_inode_items(trans, log, path, inode,
6520 BTRFS_XATTR_ITEM_KEY);
6522 if (inode_only == LOG_INODE_EXISTS && ctx->logged_before) {
6524 * Make sure the new inode item we write to the log has
6525 * the same isize as the current one (if it exists).
6526 * This is necessary to prevent data loss after log
6527 * replay, and also to prevent doing a wrong expanding
6528 * truncate - for e.g. create file, write 4K into offset
6529 * 0, fsync, write 4K into offset 4096, add hard link,
6530 * fsync some other file (to sync log), power fail - if
6531 * we use the inode's current i_size, after log replay
6532 * we get a 8Kb file, with the last 4Kb extent as a hole
6533 * (zeroes), as if an expanding truncate happened,
6534 * instead of getting a file of 4Kb only.
6536 ret = logged_inode_size(log, inode, path, &logged_isize);
6540 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6541 &inode->runtime_flags)) {
6542 if (inode_only == LOG_INODE_EXISTS) {
6543 max_key.type = BTRFS_XATTR_ITEM_KEY;
6544 if (ctx->logged_before)
6545 ret = drop_inode_items(trans, log, path,
6546 inode, max_key.type);
6548 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6549 &inode->runtime_flags);
6550 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6551 &inode->runtime_flags);
6552 if (ctx->logged_before)
6553 ret = truncate_inode_items(trans, log,
6556 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6557 &inode->runtime_flags) ||
6558 inode_only == LOG_INODE_EXISTS) {
6559 if (inode_only == LOG_INODE_ALL)
6561 max_key.type = BTRFS_XATTR_ITEM_KEY;
6562 if (ctx->logged_before)
6563 ret = drop_inode_items(trans, log, path, inode,
6566 if (inode_only == LOG_INODE_ALL)
6568 inode_item_dropped = false;
6577 * If we are logging a directory in full mode, collect the delayed items
6578 * before iterating the subvolume tree, so that we don't miss any new
6579 * dir index items in case they get flushed while or right after we are
6580 * iterating the subvolume tree.
6582 if (full_dir_logging && !ctx->logging_new_delayed_dentries)
6583 btrfs_log_get_delayed_items(inode, &delayed_ins_list,
6587 * If we are fsyncing a file with 0 hard links, then commit the delayed
6588 * inode because the last inode ref (or extref) item may still be in the
6589 * subvolume tree and if we log it the file will still exist after a log
6590 * replay. So commit the delayed inode to delete that last ref and we
6593 if (inode->vfs_inode.i_nlink == 0) {
6594 ret = btrfs_commit_inode_delayed_inode(inode);
6599 ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
6600 path, dst_path, logged_isize,
6602 &need_log_inode_item);
6606 btrfs_release_path(path);
6607 btrfs_release_path(dst_path);
6608 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path, ctx);
6611 xattrs_logged = true;
6612 if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
6613 btrfs_release_path(path);
6614 btrfs_release_path(dst_path);
6615 ret = btrfs_log_holes(trans, inode, path);
6620 btrfs_release_path(path);
6621 btrfs_release_path(dst_path);
6622 if (need_log_inode_item) {
6623 ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
6627 * If we are doing a fast fsync and the inode was logged before
6628 * in this transaction, we don't need to log the xattrs because
6629 * they were logged before. If xattrs were added, changed or
6630 * deleted since the last time we logged the inode, then we have
6631 * already logged them because the inode had the runtime flag
6632 * BTRFS_INODE_COPY_EVERYTHING set.
6634 if (!xattrs_logged && inode->logged_trans < trans->transid) {
6635 ret = btrfs_log_all_xattrs(trans, inode, path, dst_path, ctx);
6638 btrfs_release_path(path);
6642 ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
6645 } else if (inode_only == LOG_INODE_ALL) {
6646 struct extent_map *em, *n;
6648 write_lock(&em_tree->lock);
6649 list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
6650 list_del_init(&em->list);
6651 write_unlock(&em_tree->lock);
6654 if (full_dir_logging) {
6655 ret = log_directory_changes(trans, inode, path, dst_path, ctx);
6658 ret = log_delayed_insertion_items(trans, inode, path,
6659 &delayed_ins_list, ctx);
6662 ret = log_delayed_deletion_items(trans, inode, path,
6663 &delayed_del_list, ctx);
6668 spin_lock(&inode->lock);
6669 inode->logged_trans = trans->transid;
6671 * Don't update last_log_commit if we logged that an inode exists.
6672 * We do this for three reasons:
6674 * 1) We might have had buffered writes to this inode that were
6675 * flushed and had their ordered extents completed in this
6676 * transaction, but we did not previously log the inode with
6677 * LOG_INODE_ALL. Later the inode was evicted and after that
6678 * it was loaded again and this LOG_INODE_EXISTS log operation
6679 * happened. We must make sure that if an explicit fsync against
6680 * the inode is performed later, it logs the new extents, an
6681 * updated inode item, etc, and syncs the log. The same logic
6682 * applies to direct IO writes instead of buffered writes.
6684 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
6685 * is logged with an i_size of 0 or whatever value was logged
6686 * before. If later the i_size of the inode is increased by a
6687 * truncate operation, the log is synced through an fsync of
6688 * some other inode and then finally an explicit fsync against
6689 * this inode is made, we must make sure this fsync logs the
6690 * inode with the new i_size, the hole between old i_size and
6691 * the new i_size, and syncs the log.
6693 * 3) If we are logging that an ancestor inode exists as part of
6694 * logging a new name from a link or rename operation, don't update
6695 * its last_log_commit - otherwise if an explicit fsync is made
6696 * against an ancestor, the fsync considers the inode in the log
6697 * and doesn't sync the log, resulting in the ancestor missing after
6698 * a power failure unless the log was synced as part of an fsync
6699 * against any other unrelated inode.
6701 if (inode_only != LOG_INODE_EXISTS)
6702 inode->last_log_commit = inode->last_sub_trans;
6703 spin_unlock(&inode->lock);
6706 * Reset the last_reflink_trans so that the next fsync does not need to
6707 * go through the slower path when logging extents and their checksums.
6709 if (inode_only == LOG_INODE_ALL)
6710 inode->last_reflink_trans = 0;
6713 mutex_unlock(&inode->log_mutex);
6715 btrfs_free_path(path);
6716 btrfs_free_path(dst_path);
6719 free_conflicting_inodes(ctx);
6721 ret = log_conflicting_inodes(trans, inode->root, ctx);
6723 if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
6725 ret = log_new_delayed_dentries(trans, inode,
6726 &delayed_ins_list, ctx);
6728 btrfs_log_put_delayed_items(inode, &delayed_ins_list,
6735 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
6736 struct btrfs_inode *inode,
6737 struct btrfs_log_ctx *ctx)
6740 struct btrfs_path *path;
6741 struct btrfs_key key;
6742 struct btrfs_root *root = inode->root;
6743 const u64 ino = btrfs_ino(inode);
6745 path = btrfs_alloc_path();
6748 path->skip_locking = 1;
6749 path->search_commit_root = 1;
6752 key.type = BTRFS_INODE_REF_KEY;
6754 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6759 struct extent_buffer *leaf = path->nodes[0];
6760 int slot = path->slots[0];
6765 if (slot >= btrfs_header_nritems(leaf)) {
6766 ret = btrfs_next_leaf(root, path);
6774 btrfs_item_key_to_cpu(leaf, &key, slot);
6775 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
6776 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
6779 item_size = btrfs_item_size(leaf, slot);
6780 ptr = btrfs_item_ptr_offset(leaf, slot);
6781 while (cur_offset < item_size) {
6782 struct btrfs_key inode_key;
6783 struct btrfs_inode *dir_inode;
6785 inode_key.type = BTRFS_INODE_ITEM_KEY;
6786 inode_key.offset = 0;
6788 if (key.type == BTRFS_INODE_EXTREF_KEY) {
6789 struct btrfs_inode_extref *extref;
6791 extref = (struct btrfs_inode_extref *)
6793 inode_key.objectid = btrfs_inode_extref_parent(
6795 cur_offset += sizeof(*extref);
6796 cur_offset += btrfs_inode_extref_name_len(leaf,
6799 inode_key.objectid = key.offset;
6800 cur_offset = item_size;
6803 dir_inode = btrfs_iget_logging(inode_key.objectid, root);
6805 * If the parent inode was deleted, return an error to
6806 * fallback to a transaction commit. This is to prevent
6807 * getting an inode that was moved from one parent A to
6808 * a parent B, got its former parent A deleted and then
6809 * it got fsync'ed, from existing at both parents after
6810 * a log replay (and the old parent still existing).
6817 * mv /mnt/B/bar /mnt/A/bar
6818 * mv -T /mnt/A /mnt/B
6822 * If we ignore the old parent B which got deleted,
6823 * after a log replay we would have file bar linked
6824 * at both parents and the old parent B would still
6827 if (IS_ERR(dir_inode)) {
6828 ret = PTR_ERR(dir_inode);
6832 if (!need_log_inode(trans, dir_inode)) {
6833 btrfs_add_delayed_iput(dir_inode);
6837 ctx->log_new_dentries = false;
6838 ret = btrfs_log_inode(trans, dir_inode, LOG_INODE_ALL, ctx);
6839 if (!ret && ctx->log_new_dentries)
6840 ret = log_new_dir_dentries(trans, dir_inode, ctx);
6841 btrfs_add_delayed_iput(dir_inode);
6849 btrfs_free_path(path);
6853 static int log_new_ancestors(struct btrfs_trans_handle *trans,
6854 struct btrfs_root *root,
6855 struct btrfs_path *path,
6856 struct btrfs_log_ctx *ctx)
6858 struct btrfs_key found_key;
6860 btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
6863 struct extent_buffer *leaf;
6865 struct btrfs_key search_key;
6866 struct btrfs_inode *inode;
6870 btrfs_release_path(path);
6872 ino = found_key.offset;
6874 search_key.objectid = found_key.offset;
6875 search_key.type = BTRFS_INODE_ITEM_KEY;
6876 search_key.offset = 0;
6877 inode = btrfs_iget_logging(ino, root);
6879 return PTR_ERR(inode);
6881 if (inode->generation >= trans->transid &&
6882 need_log_inode(trans, inode))
6883 ret = btrfs_log_inode(trans, inode, LOG_INODE_EXISTS, ctx);
6884 btrfs_add_delayed_iput(inode);
6888 if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
6891 search_key.type = BTRFS_INODE_REF_KEY;
6892 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6896 leaf = path->nodes[0];
6897 slot = path->slots[0];
6898 if (slot >= btrfs_header_nritems(leaf)) {
6899 ret = btrfs_next_leaf(root, path);
6904 leaf = path->nodes[0];
6905 slot = path->slots[0];
6908 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6909 if (found_key.objectid != search_key.objectid ||
6910 found_key.type != BTRFS_INODE_REF_KEY)
6916 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
6917 struct btrfs_inode *inode,
6918 struct dentry *parent,
6919 struct btrfs_log_ctx *ctx)
6921 struct btrfs_root *root = inode->root;
6922 struct dentry *old_parent = NULL;
6923 struct super_block *sb = inode->vfs_inode.i_sb;
6927 if (!parent || d_really_is_negative(parent) ||
6931 inode = BTRFS_I(d_inode(parent));
6932 if (root != inode->root)
6935 if (inode->generation >= trans->transid &&
6936 need_log_inode(trans, inode)) {
6937 ret = btrfs_log_inode(trans, inode,
6938 LOG_INODE_EXISTS, ctx);
6942 if (IS_ROOT(parent))
6945 parent = dget_parent(parent);
6947 old_parent = parent;
6954 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
6955 struct btrfs_inode *inode,
6956 struct dentry *parent,
6957 struct btrfs_log_ctx *ctx)
6959 struct btrfs_root *root = inode->root;
6960 const u64 ino = btrfs_ino(inode);
6961 struct btrfs_path *path;
6962 struct btrfs_key search_key;
6966 * For a single hard link case, go through a fast path that does not
6967 * need to iterate the fs/subvolume tree.
6969 if (inode->vfs_inode.i_nlink < 2)
6970 return log_new_ancestors_fast(trans, inode, parent, ctx);
6972 path = btrfs_alloc_path();
6976 search_key.objectid = ino;
6977 search_key.type = BTRFS_INODE_REF_KEY;
6978 search_key.offset = 0;
6980 ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6987 struct extent_buffer *leaf = path->nodes[0];
6988 int slot = path->slots[0];
6989 struct btrfs_key found_key;
6991 if (slot >= btrfs_header_nritems(leaf)) {
6992 ret = btrfs_next_leaf(root, path);
7000 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7001 if (found_key.objectid != ino ||
7002 found_key.type > BTRFS_INODE_EXTREF_KEY)
7006 * Don't deal with extended references because they are rare
7007 * cases and too complex to deal with (we would need to keep
7008 * track of which subitem we are processing for each item in
7009 * this loop, etc). So just return some error to fallback to
7010 * a transaction commit.
7012 if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
7018 * Logging ancestors needs to do more searches on the fs/subvol
7019 * tree, so it releases the path as needed to avoid deadlocks.
7020 * Keep track of the last inode ref key and resume from that key
7021 * after logging all new ancestors for the current hard link.
7023 memcpy(&search_key, &found_key, sizeof(search_key));
7025 ret = log_new_ancestors(trans, root, path, ctx);
7028 btrfs_release_path(path);
7033 btrfs_free_path(path);
7038 * helper function around btrfs_log_inode to make sure newly created
7039 * parent directories also end up in the log. A minimal inode and backref
7040 * only logging is done of any parent directories that are older than
7041 * the last committed transaction
7043 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
7044 struct btrfs_inode *inode,
7045 struct dentry *parent,
7047 struct btrfs_log_ctx *ctx)
7049 struct btrfs_root *root = inode->root;
7050 struct btrfs_fs_info *fs_info = root->fs_info;
7054 if (btrfs_test_opt(fs_info, NOTREELOG))
7055 return BTRFS_LOG_FORCE_COMMIT;
7057 if (btrfs_root_refs(&root->root_item) == 0)
7058 return BTRFS_LOG_FORCE_COMMIT;
7061 * If we're logging an inode from a subvolume created in the current
7062 * transaction we must force a commit since the root is not persisted.
7064 if (btrfs_root_generation(&root->root_item) == trans->transid)
7065 return BTRFS_LOG_FORCE_COMMIT;
7067 /* Skip already logged inodes and without new extents. */
7068 if (btrfs_inode_in_log(inode, trans->transid) &&
7069 list_empty(&ctx->ordered_extents))
7070 return BTRFS_NO_LOG_SYNC;
7072 ret = start_log_trans(trans, root, ctx);
7076 ret = btrfs_log_inode(trans, inode, inode_only, ctx);
7081 * for regular files, if its inode is already on disk, we don't
7082 * have to worry about the parents at all. This is because
7083 * we can use the last_unlink_trans field to record renames
7084 * and other fun in this file.
7086 if (S_ISREG(inode->vfs_inode.i_mode) &&
7087 inode->generation < trans->transid &&
7088 inode->last_unlink_trans < trans->transid) {
7094 * Track if we need to log dentries because ctx->log_new_dentries can
7095 * be modified in the call chains below.
7097 log_dentries = ctx->log_new_dentries;
7100 * On unlink we must make sure all our current and old parent directory
7101 * inodes are fully logged. This is to prevent leaving dangling
7102 * directory index entries in directories that were our parents but are
7103 * not anymore. Not doing this results in old parent directory being
7104 * impossible to delete after log replay (rmdir will always fail with
7105 * error -ENOTEMPTY).
7111 * ln testdir/foo testdir/bar
7113 * unlink testdir/bar
7114 * xfs_io -c fsync testdir/foo
7116 * mount fs, triggers log replay
7118 * If we don't log the parent directory (testdir), after log replay the
7119 * directory still has an entry pointing to the file inode using the bar
7120 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
7121 * the file inode has a link count of 1.
7127 * ln foo testdir/foo2
7128 * ln foo testdir/foo3
7130 * unlink testdir/foo3
7131 * xfs_io -c fsync foo
7133 * mount fs, triggers log replay
7135 * Similar as the first example, after log replay the parent directory
7136 * testdir still has an entry pointing to the inode file with name foo3
7137 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
7138 * and has a link count of 2.
7140 if (inode->last_unlink_trans >= trans->transid) {
7141 ret = btrfs_log_all_parents(trans, inode, ctx);
7146 ret = log_all_new_ancestors(trans, inode, parent, ctx);
7151 ret = log_new_dir_dentries(trans, inode, ctx);
7154 btrfs_set_log_full_commit(trans);
7155 ret = BTRFS_LOG_FORCE_COMMIT;
7159 btrfs_remove_log_ctx(root, ctx);
7160 btrfs_end_log_trans(root);
7166 * it is not safe to log dentry if the chunk root has added new
7167 * chunks. This returns 0 if the dentry was logged, and 1 otherwise.
7168 * If this returns 1, you must commit the transaction to safely get your
7171 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7172 struct dentry *dentry,
7173 struct btrfs_log_ctx *ctx)
7175 struct dentry *parent = dget_parent(dentry);
7178 ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
7179 LOG_INODE_ALL, ctx);
7186 * should be called during mount to recover any replay any log trees
7189 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7192 struct btrfs_path *path;
7193 struct btrfs_trans_handle *trans;
7194 struct btrfs_key key;
7195 struct btrfs_key found_key;
7196 struct btrfs_root *log;
7197 struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7198 struct walk_control wc = {
7199 .process_func = process_one_buffer,
7200 .stage = LOG_WALK_PIN_ONLY,
7203 path = btrfs_alloc_path();
7207 set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7209 trans = btrfs_start_transaction(fs_info->tree_root, 0);
7210 if (IS_ERR(trans)) {
7211 ret = PTR_ERR(trans);
7218 ret = walk_log_tree(trans, log_root_tree, &wc);
7220 btrfs_abort_transaction(trans, ret);
7225 key.objectid = BTRFS_TREE_LOG_OBJECTID;
7226 key.type = BTRFS_ROOT_ITEM_KEY;
7227 key.offset = (u64)-1;
7230 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
7233 btrfs_abort_transaction(trans, ret);
7237 if (path->slots[0] == 0)
7241 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7243 btrfs_release_path(path);
7244 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7247 log = btrfs_read_tree_root(log_root_tree, &found_key);
7250 btrfs_abort_transaction(trans, ret);
7254 wc.replay_dest = btrfs_get_fs_root(fs_info, found_key.offset,
7256 if (IS_ERR(wc.replay_dest)) {
7257 ret = PTR_ERR(wc.replay_dest);
7260 * We didn't find the subvol, likely because it was
7261 * deleted. This is ok, simply skip this log and go to
7264 * We need to exclude the root because we can't have
7265 * other log replays overwriting this log as we'll read
7266 * it back in a few more times. This will keep our
7267 * block from being modified, and we'll just bail for
7268 * each subsequent pass.
7271 ret = btrfs_pin_extent_for_log_replay(trans, log->node);
7272 btrfs_put_root(log);
7276 btrfs_abort_transaction(trans, ret);
7280 wc.replay_dest->log_root = log;
7281 ret = btrfs_record_root_in_trans(trans, wc.replay_dest);
7283 /* The loop needs to continue due to the root refs */
7284 btrfs_abort_transaction(trans, ret);
7286 ret = walk_log_tree(trans, log, &wc);
7288 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7289 ret = fixup_inode_link_counts(trans, wc.replay_dest,
7292 btrfs_abort_transaction(trans, ret);
7295 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7296 struct btrfs_root *root = wc.replay_dest;
7298 btrfs_release_path(path);
7301 * We have just replayed everything, and the highest
7302 * objectid of fs roots probably has changed in case
7303 * some inode_item's got replayed.
7305 * root->objectid_mutex is not acquired as log replay
7306 * could only happen during mount.
7308 ret = btrfs_init_root_free_objectid(root);
7310 btrfs_abort_transaction(trans, ret);
7313 wc.replay_dest->log_root = NULL;
7314 btrfs_put_root(wc.replay_dest);
7315 btrfs_put_root(log);
7320 if (found_key.offset == 0)
7322 key.offset = found_key.offset - 1;
7324 btrfs_release_path(path);
7326 /* step one is to pin it all, step two is to replay just inodes */
7329 wc.process_func = replay_one_buffer;
7330 wc.stage = LOG_WALK_REPLAY_INODES;
7333 /* step three is to replay everything */
7334 if (wc.stage < LOG_WALK_REPLAY_ALL) {
7339 btrfs_free_path(path);
7341 /* step 4: commit the transaction, which also unpins the blocks */
7342 ret = btrfs_commit_transaction(trans);
7346 log_root_tree->log_root = NULL;
7347 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7348 btrfs_put_root(log_root_tree);
7353 btrfs_end_transaction(wc.trans);
7354 clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7355 btrfs_free_path(path);
7360 * there are some corner cases where we want to force a full
7361 * commit instead of allowing a directory to be logged.
7363 * They revolve around files there were unlinked from the directory, and
7364 * this function updates the parent directory so that a full commit is
7365 * properly done if it is fsync'd later after the unlinks are done.
7367 * Must be called before the unlink operations (updates to the subvolume tree,
7368 * inodes, etc) are done.
7370 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
7371 struct btrfs_inode *dir, struct btrfs_inode *inode,
7375 * when we're logging a file, if it hasn't been renamed
7376 * or unlinked, and its inode is fully committed on disk,
7377 * we don't have to worry about walking up the directory chain
7378 * to log its parents.
7380 * So, we use the last_unlink_trans field to put this transid
7381 * into the file. When the file is logged we check it and
7382 * don't log the parents if the file is fully on disk.
7384 mutex_lock(&inode->log_mutex);
7385 inode->last_unlink_trans = trans->transid;
7386 mutex_unlock(&inode->log_mutex);
7392 * If this directory was already logged, any new names will be logged
7393 * with btrfs_log_new_name() and old names will be deleted from the log
7394 * tree with btrfs_del_dir_entries_in_log() or with
7395 * btrfs_del_inode_ref_in_log().
7397 if (inode_logged(trans, dir, NULL) == 1)
7401 * If the inode we're about to unlink was logged before, the log will be
7402 * properly updated with the new name with btrfs_log_new_name() and the
7403 * old name removed with btrfs_del_dir_entries_in_log() or with
7404 * btrfs_del_inode_ref_in_log().
7406 if (inode_logged(trans, inode, NULL) == 1)
7410 * when renaming files across directories, if the directory
7411 * there we're unlinking from gets fsync'd later on, there's
7412 * no way to find the destination directory later and fsync it
7413 * properly. So, we have to be conservative and force commits
7414 * so the new name gets discovered.
7416 mutex_lock(&dir->log_mutex);
7417 dir->last_unlink_trans = trans->transid;
7418 mutex_unlock(&dir->log_mutex);
7422 * Make sure that if someone attempts to fsync the parent directory of a deleted
7423 * snapshot, it ends up triggering a transaction commit. This is to guarantee
7424 * that after replaying the log tree of the parent directory's root we will not
7425 * see the snapshot anymore and at log replay time we will not see any log tree
7426 * corresponding to the deleted snapshot's root, which could lead to replaying
7427 * it after replaying the log tree of the parent directory (which would replay
7428 * the snapshot delete operation).
7430 * Must be called before the actual snapshot destroy operation (updates to the
7431 * parent root and tree of tree roots trees, etc) are done.
7433 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
7434 struct btrfs_inode *dir)
7436 mutex_lock(&dir->log_mutex);
7437 dir->last_unlink_trans = trans->transid;
7438 mutex_unlock(&dir->log_mutex);
7442 * Call this when creating a subvolume in a directory.
7443 * Because we don't commit a transaction when creating a subvolume, we can't
7444 * allow the directory pointing to the subvolume to be logged with an entry that
7445 * points to an unpersisted root if we are still in the transaction used to
7446 * create the subvolume, so make any attempt to log the directory to result in a
7448 * Also we don't need to worry with renames, since btrfs_rename() marks the log
7449 * for full commit when renaming a subvolume.
7451 * Must be called before creating the subvolume entry in its parent directory.
7453 void btrfs_record_new_subvolume(const struct btrfs_trans_handle *trans,
7454 struct btrfs_inode *dir)
7456 mutex_lock(&dir->log_mutex);
7457 dir->last_unlink_trans = trans->transid;
7458 mutex_unlock(&dir->log_mutex);
7462 * Update the log after adding a new name for an inode.
7464 * @trans: Transaction handle.
7465 * @old_dentry: The dentry associated with the old name and the old
7467 * @old_dir: The inode of the previous parent directory for the case
7468 * of a rename. For a link operation, it must be NULL.
7469 * @old_dir_index: The index number associated with the old name, meaningful
7470 * only for rename operations (when @old_dir is not NULL).
7471 * Ignored for link operations.
7472 * @parent: The dentry associated with the directory under which the
7473 * new name is located.
7475 * Call this after adding a new name for an inode, as a result of a link or
7476 * rename operation, and it will properly update the log to reflect the new name.
7478 void btrfs_log_new_name(struct btrfs_trans_handle *trans,
7479 struct dentry *old_dentry, struct btrfs_inode *old_dir,
7480 u64 old_dir_index, struct dentry *parent)
7482 struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
7483 struct btrfs_root *root = inode->root;
7484 struct btrfs_log_ctx ctx;
7485 bool log_pinned = false;
7489 * this will force the logging code to walk the dentry chain
7492 if (!S_ISDIR(inode->vfs_inode.i_mode))
7493 inode->last_unlink_trans = trans->transid;
7496 * if this inode hasn't been logged and directory we're renaming it
7497 * from hasn't been logged, we don't need to log it
7499 ret = inode_logged(trans, inode, NULL);
7502 } else if (ret == 0) {
7506 * If the inode was not logged and we are doing a rename (old_dir is not
7507 * NULL), check if old_dir was logged - if it was not we can return and
7510 ret = inode_logged(trans, old_dir, NULL);
7519 * If we are doing a rename (old_dir is not NULL) from a directory that
7520 * was previously logged, make sure that on log replay we get the old
7521 * dir entry deleted. This is needed because we will also log the new
7522 * name of the renamed inode, so we need to make sure that after log
7523 * replay we don't end up with both the new and old dir entries existing.
7525 if (old_dir && old_dir->logged_trans == trans->transid) {
7526 struct btrfs_root *log = old_dir->root->log_root;
7527 struct btrfs_path *path;
7528 struct fscrypt_name fname;
7530 ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
7532 ret = fscrypt_setup_filename(&old_dir->vfs_inode,
7533 &old_dentry->d_name, 0, &fname);
7537 * We have two inodes to update in the log, the old directory and
7538 * the inode that got renamed, so we must pin the log to prevent
7539 * anyone from syncing the log until we have updated both inodes
7542 ret = join_running_log_trans(root);
7544 * At least one of the inodes was logged before, so this should
7545 * not fail, but if it does, it's not serious, just bail out and
7546 * mark the log for a full commit.
7548 if (WARN_ON_ONCE(ret < 0)) {
7549 fscrypt_free_filename(&fname);
7555 path = btrfs_alloc_path();
7558 fscrypt_free_filename(&fname);
7563 * Other concurrent task might be logging the old directory,
7564 * as it can be triggered when logging other inode that had or
7565 * still has a dentry in the old directory. We lock the old
7566 * directory's log_mutex to ensure the deletion of the old
7567 * name is persisted, because during directory logging we
7568 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
7569 * the old name's dir index item is in the delayed items, so
7570 * it could be missed by an in progress directory logging.
7572 mutex_lock(&old_dir->log_mutex);
7573 ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
7574 &fname.disk_name, old_dir_index);
7577 * The dentry does not exist in the log, so record its
7580 btrfs_release_path(path);
7581 ret = insert_dir_log_key(trans, log, path,
7583 old_dir_index, old_dir_index);
7585 mutex_unlock(&old_dir->log_mutex);
7587 btrfs_free_path(path);
7588 fscrypt_free_filename(&fname);
7593 btrfs_init_log_ctx(&ctx, inode);
7594 ctx.logging_new_name = true;
7595 btrfs_init_log_ctx_scratch_eb(&ctx);
7597 * We don't care about the return value. If we fail to log the new name
7598 * then we know the next attempt to sync the log will fallback to a full
7599 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
7600 * we don't need to worry about getting a log committed that has an
7601 * inconsistent state after a rename operation.
7603 btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
7604 free_extent_buffer(ctx.scratch_eb);
7605 ASSERT(list_empty(&ctx.conflict_inodes));
7608 * If an error happened mark the log for a full commit because it's not
7609 * consistent and up to date or we couldn't find out if one of the
7610 * inodes was logged before in this transaction. Do it before unpinning
7611 * the log, to avoid any races with someone else trying to commit it.
7614 btrfs_set_log_full_commit(trans);
7616 btrfs_end_log_trans(root);