xref: /openbmc/linux/fs/btrfs/tree-log.c (revision bf1f4fd3fadb8dd4337ad46d63eb6ebcce3366f5)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
2e02119d5SChris Mason /*
3e02119d5SChris Mason  * Copyright (C) 2008 Oracle.  All rights reserved.
4e02119d5SChris Mason  */
5e02119d5SChris Mason 
6e02119d5SChris Mason #include <linux/sched.h>
75a0e3ad6STejun Heo #include <linux/slab.h>
8c6adc9ccSMiao Xie #include <linux/blkdev.h>
95dc562c5SJosef Bacik #include <linux/list_sort.h>
10c7f88c4eSJeff Layton #include <linux/iversion.h>
11602cbe91SDavid Sterba #include "misc.h"
129678c543SNikolay Borisov #include "ctree.h"
13995946ddSMiao Xie #include "tree-log.h"
14e02119d5SChris Mason #include "disk-io.h"
15e02119d5SChris Mason #include "locking.h"
16e02119d5SChris Mason #include "print-tree.h"
17f186373fSMark Fasheh #include "backref.h"
18ebb8765bSAnand Jain #include "compression.h"
19df2c95f3SQu Wenruo #include "qgroup.h"
206787bb9fSNikolay Borisov #include "block-group.h"
216787bb9fSNikolay Borisov #include "space-info.h"
22d3575156SNaohiro Aota #include "zoned.h"
2326c2c454SJosef Bacik #include "inode-item.h"
24c7f13d42SJosef Bacik #include "fs.h"
25ad1ac501SJosef Bacik #include "accessors.h"
26a0231804SJosef Bacik #include "extent-tree.h"
2745c40c8fSJosef Bacik #include "root-tree.h"
28f2b39277SJosef Bacik #include "dir-item.h"
297c8ede16SJosef Bacik #include "file-item.h"
30af142b6fSJosef Bacik #include "file.h"
31aa5d3003SJosef Bacik #include "orphan.h"
32103c1972SChristoph Hellwig #include "tree-checker.h"
33e02119d5SChris Mason 
34e09d94c9SFilipe Manana #define MAX_CONFLICT_INODES 10
35e09d94c9SFilipe Manana 
36e02119d5SChris Mason /* magic values for the inode_only field in btrfs_log_inode:
37e02119d5SChris Mason  *
38e02119d5SChris Mason  * LOG_INODE_ALL means to log everything
39e02119d5SChris Mason  * LOG_INODE_EXISTS means to log just enough to recreate the inode
40e02119d5SChris Mason  * during log replay
41e02119d5SChris Mason  */
42e13976cfSDavid Sterba enum {
43e13976cfSDavid Sterba 	LOG_INODE_ALL,
44e13976cfSDavid Sterba 	LOG_INODE_EXISTS,
45e13976cfSDavid Sterba };
46e02119d5SChris Mason 
47e02119d5SChris Mason /*
4812fcfd22SChris Mason  * directory trouble cases
4912fcfd22SChris Mason  *
5012fcfd22SChris Mason  * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
5112fcfd22SChris Mason  * log, we must force a full commit before doing an fsync of the directory
5212fcfd22SChris Mason  * where the unlink was done.
5312fcfd22SChris Mason  * ---> record transid of last unlink/rename per directory
5412fcfd22SChris Mason  *
5512fcfd22SChris Mason  * mkdir foo/some_dir
5612fcfd22SChris Mason  * normal commit
5712fcfd22SChris Mason  * rename foo/some_dir foo2/some_dir
5812fcfd22SChris Mason  * mkdir foo/some_dir
5912fcfd22SChris Mason  * fsync foo/some_dir/some_file
6012fcfd22SChris Mason  *
6112fcfd22SChris Mason  * The fsync above will unlink the original some_dir without recording
6212fcfd22SChris Mason  * it in its new location (foo2).  After a crash, some_dir will be gone
6312fcfd22SChris Mason  * unless the fsync of some_file forces a full commit
6412fcfd22SChris Mason  *
6512fcfd22SChris Mason  * 2) we must log any new names for any file or dir that is in the fsync
6612fcfd22SChris Mason  * log. ---> check inode while renaming/linking.
6712fcfd22SChris Mason  *
6812fcfd22SChris Mason  * 2a) we must log any new names for any file or dir during rename
6912fcfd22SChris Mason  * when the directory they are being removed from was logged.
7012fcfd22SChris Mason  * ---> check inode and old parent dir during rename
7112fcfd22SChris Mason  *
7212fcfd22SChris Mason  *  2a is actually the more important variant.  With the extra logging
7312fcfd22SChris Mason  *  a crash might unlink the old name without recreating the new one
7412fcfd22SChris Mason  *
7512fcfd22SChris Mason  * 3) after a crash, we must go through any directories with a link count
7612fcfd22SChris Mason  * of zero and redo the rm -rf
7712fcfd22SChris Mason  *
7812fcfd22SChris Mason  * mkdir f1/foo
7912fcfd22SChris Mason  * normal commit
8012fcfd22SChris Mason  * rm -rf f1/foo
8112fcfd22SChris Mason  * fsync(f1)
8212fcfd22SChris Mason  *
8312fcfd22SChris Mason  * The directory f1 was fully removed from the FS, but fsync was never
8412fcfd22SChris Mason  * called on f1, only its parent dir.  After a crash the rm -rf must
8512fcfd22SChris Mason  * be replayed.  This must be able to recurse down the entire
8612fcfd22SChris Mason  * directory tree.  The inode link count fixup code takes care of the
8712fcfd22SChris Mason  * ugly details.
8812fcfd22SChris Mason  */
8912fcfd22SChris Mason 
9012fcfd22SChris Mason /*
91e02119d5SChris Mason  * stages for the tree walking.  The first
92e02119d5SChris Mason  * stage (0) is to only pin down the blocks we find
93e02119d5SChris Mason  * the second stage (1) is to make sure that all the inodes
94e02119d5SChris Mason  * we find in the log are created in the subvolume.
95e02119d5SChris Mason  *
96e02119d5SChris Mason  * The last stage is to deal with directories and links and extents
97e02119d5SChris Mason  * and all the other fun semantics
98e02119d5SChris Mason  */
99e13976cfSDavid Sterba enum {
100e13976cfSDavid Sterba 	LOG_WALK_PIN_ONLY,
101e13976cfSDavid Sterba 	LOG_WALK_REPLAY_INODES,
102e13976cfSDavid Sterba 	LOG_WALK_REPLAY_DIR_INDEX,
103e13976cfSDavid Sterba 	LOG_WALK_REPLAY_ALL,
104e13976cfSDavid Sterba };
105e02119d5SChris Mason 
10612fcfd22SChris Mason static int btrfs_log_inode(struct btrfs_trans_handle *trans,
10790d04510SFilipe Manana 			   struct btrfs_inode *inode,
10849dae1bcSFilipe Manana 			   int inode_only,
1098407f553SFilipe Manana 			   struct btrfs_log_ctx *ctx);
110ec051c0fSYan Zheng static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
111ec051c0fSYan Zheng 			     struct btrfs_root *root,
112ec051c0fSYan Zheng 			     struct btrfs_path *path, u64 objectid);
11312fcfd22SChris Mason static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
11412fcfd22SChris Mason 				       struct btrfs_root *root,
11512fcfd22SChris Mason 				       struct btrfs_root *log,
11612fcfd22SChris Mason 				       struct btrfs_path *path,
11712fcfd22SChris Mason 				       u64 dirid, int del_all);
118fa1a0f42SNaohiro Aota static void wait_log_commit(struct btrfs_root *root, int transid);
119e02119d5SChris Mason 
120e02119d5SChris Mason /*
121e02119d5SChris Mason  * tree logging is a special write ahead log used to make sure that
122e02119d5SChris Mason  * fsyncs and O_SYNCs can happen without doing full tree commits.
123e02119d5SChris Mason  *
124e02119d5SChris Mason  * Full tree commits are expensive because they require commonly
125e02119d5SChris Mason  * modified blocks to be recowed, creating many dirty pages in the
126e02119d5SChris Mason  * extent tree an 4x-6x higher write load than ext3.
127e02119d5SChris Mason  *
128e02119d5SChris Mason  * Instead of doing a tree commit on every fsync, we use the
129e02119d5SChris Mason  * key ranges and transaction ids to find items for a given file or directory
130e02119d5SChris Mason  * that have changed in this transaction.  Those items are copied into
131e02119d5SChris Mason  * a special tree (one per subvolume root), that tree is written to disk
132e02119d5SChris Mason  * and then the fsync is considered complete.
133e02119d5SChris Mason  *
134e02119d5SChris Mason  * After a crash, items are copied out of the log-tree back into the
135e02119d5SChris Mason  * subvolume tree.  Any file data extents found are recorded in the extent
136e02119d5SChris Mason  * allocation tree, and the log-tree freed.
137e02119d5SChris Mason  *
138e02119d5SChris Mason  * The log tree is read three times, once to pin down all the extents it is
139e02119d5SChris Mason  * using in ram and once, once to create all the inodes logged in the tree
140e02119d5SChris Mason  * and once to do all the other items.
141e02119d5SChris Mason  */
142e02119d5SChris Mason 
143e02119d5SChris Mason /*
144e02119d5SChris Mason  * start a sub transaction and setup the log tree
145e02119d5SChris Mason  * this increments the log tree writer count to make the people
146e02119d5SChris Mason  * syncing the tree wait for us to finish
147e02119d5SChris Mason  */
148e02119d5SChris Mason static int start_log_trans(struct btrfs_trans_handle *trans,
1498b050d35SMiao Xie 			   struct btrfs_root *root,
1508b050d35SMiao Xie 			   struct btrfs_log_ctx *ctx)
151e02119d5SChris Mason {
1520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
15347876f7cSFilipe Manana 	struct btrfs_root *tree_root = fs_info->tree_root;
154fa1a0f42SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
15534eb2a52SZhaolei 	int ret = 0;
156fa1a0f42SNaohiro Aota 	bool created = false;
1577237f183SYan Zheng 
15847876f7cSFilipe Manana 	/*
15947876f7cSFilipe Manana 	 * First check if the log root tree was already created. If not, create
16047876f7cSFilipe Manana 	 * it before locking the root's log_mutex, just to keep lockdep happy.
16147876f7cSFilipe Manana 	 */
16247876f7cSFilipe Manana 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
16347876f7cSFilipe Manana 		mutex_lock(&tree_root->log_mutex);
16447876f7cSFilipe Manana 		if (!fs_info->log_root_tree) {
16547876f7cSFilipe Manana 			ret = btrfs_init_log_root_tree(trans, fs_info);
166fa1a0f42SNaohiro Aota 			if (!ret) {
16747876f7cSFilipe Manana 				set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
168fa1a0f42SNaohiro Aota 				created = true;
169fa1a0f42SNaohiro Aota 			}
17047876f7cSFilipe Manana 		}
17147876f7cSFilipe Manana 		mutex_unlock(&tree_root->log_mutex);
17247876f7cSFilipe Manana 		if (ret)
17347876f7cSFilipe Manana 			return ret;
17447876f7cSFilipe Manana 	}
17547876f7cSFilipe Manana 
1767237f183SYan Zheng 	mutex_lock(&root->log_mutex);
17734eb2a52SZhaolei 
178fa1a0f42SNaohiro Aota again:
1797237f183SYan Zheng 	if (root->log_root) {
180fa1a0f42SNaohiro Aota 		int index = (root->log_transid + 1) % 2;
181fa1a0f42SNaohiro Aota 
1824884b8e8SDavid Sterba 		if (btrfs_need_log_full_commit(trans)) {
183f31f09f6SJosef Bacik 			ret = BTRFS_LOG_FORCE_COMMIT;
18450471a38SMiao Xie 			goto out;
18550471a38SMiao Xie 		}
18634eb2a52SZhaolei 
187fa1a0f42SNaohiro Aota 		if (zoned && atomic_read(&root->log_commit[index])) {
188fa1a0f42SNaohiro Aota 			wait_log_commit(root, root->log_transid - 1);
189fa1a0f42SNaohiro Aota 			goto again;
190fa1a0f42SNaohiro Aota 		}
191fa1a0f42SNaohiro Aota 
192ff782e0aSJosef Bacik 		if (!root->log_start_pid) {
19327cdeb70SMiao Xie 			clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
19434eb2a52SZhaolei 			root->log_start_pid = current->pid;
195ff782e0aSJosef Bacik 		} else if (root->log_start_pid != current->pid) {
19627cdeb70SMiao Xie 			set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
197ff782e0aSJosef Bacik 		}
19834eb2a52SZhaolei 	} else {
199fa1a0f42SNaohiro Aota 		/*
200fa1a0f42SNaohiro Aota 		 * This means fs_info->log_root_tree was already created
201fa1a0f42SNaohiro Aota 		 * for some other FS trees. Do the full commit not to mix
202fa1a0f42SNaohiro Aota 		 * nodes from multiple log transactions to do sequential
203fa1a0f42SNaohiro Aota 		 * writing.
204fa1a0f42SNaohiro Aota 		 */
205fa1a0f42SNaohiro Aota 		if (zoned && !created) {
206f31f09f6SJosef Bacik 			ret = BTRFS_LOG_FORCE_COMMIT;
207fa1a0f42SNaohiro Aota 			goto out;
208fa1a0f42SNaohiro Aota 		}
209fa1a0f42SNaohiro Aota 
210e02119d5SChris Mason 		ret = btrfs_add_log_tree(trans, root);
2114a500fd1SYan, Zheng 		if (ret)
212e87ac136SMiao Xie 			goto out;
21334eb2a52SZhaolei 
214e7a79811SFilipe Manana 		set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
21527cdeb70SMiao Xie 		clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
216e87ac136SMiao Xie 		root->log_start_pid = current->pid;
21734eb2a52SZhaolei 	}
21834eb2a52SZhaolei 
2197237f183SYan Zheng 	atomic_inc(&root->log_writers);
220289cffcbSFilipe Manana 	if (!ctx->logging_new_name) {
22134eb2a52SZhaolei 		int index = root->log_transid % 2;
2228b050d35SMiao Xie 		list_add_tail(&ctx->list, &root->log_ctxs[index]);
223d1433debSMiao Xie 		ctx->log_transid = root->log_transid;
2248b050d35SMiao Xie 	}
22534eb2a52SZhaolei 
226e87ac136SMiao Xie out:
2277237f183SYan Zheng 	mutex_unlock(&root->log_mutex);
228e87ac136SMiao Xie 	return ret;
229e02119d5SChris Mason }
230e02119d5SChris Mason 
231e02119d5SChris Mason /*
232e02119d5SChris Mason  * returns 0 if there was a log transaction running and we were able
233e02119d5SChris Mason  * to join, or returns -ENOENT if there were not transactions
234e02119d5SChris Mason  * in progress
235e02119d5SChris Mason  */
236e02119d5SChris Mason static int join_running_log_trans(struct btrfs_root *root)
237e02119d5SChris Mason {
238fa1a0f42SNaohiro Aota 	const bool zoned = btrfs_is_zoned(root->fs_info);
239e02119d5SChris Mason 	int ret = -ENOENT;
240e02119d5SChris Mason 
241e7a79811SFilipe Manana 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
242e7a79811SFilipe Manana 		return ret;
243e7a79811SFilipe Manana 
2447237f183SYan Zheng 	mutex_lock(&root->log_mutex);
245fa1a0f42SNaohiro Aota again:
246e02119d5SChris Mason 	if (root->log_root) {
247fa1a0f42SNaohiro Aota 		int index = (root->log_transid + 1) % 2;
248fa1a0f42SNaohiro Aota 
249e02119d5SChris Mason 		ret = 0;
250fa1a0f42SNaohiro Aota 		if (zoned && atomic_read(&root->log_commit[index])) {
251fa1a0f42SNaohiro Aota 			wait_log_commit(root, root->log_transid - 1);
252fa1a0f42SNaohiro Aota 			goto again;
253fa1a0f42SNaohiro Aota 		}
2547237f183SYan Zheng 		atomic_inc(&root->log_writers);
255e02119d5SChris Mason 	}
2567237f183SYan Zheng 	mutex_unlock(&root->log_mutex);
257e02119d5SChris Mason 	return ret;
258e02119d5SChris Mason }
259e02119d5SChris Mason 
260e02119d5SChris Mason /*
26112fcfd22SChris Mason  * This either makes the current running log transaction wait
26212fcfd22SChris Mason  * until you call btrfs_end_log_trans() or it makes any future
26312fcfd22SChris Mason  * log transactions wait until you call btrfs_end_log_trans()
26412fcfd22SChris Mason  */
26545128b08Szhong jiang void btrfs_pin_log_trans(struct btrfs_root *root)
26612fcfd22SChris Mason {
26712fcfd22SChris Mason 	atomic_inc(&root->log_writers);
26812fcfd22SChris Mason }
26912fcfd22SChris Mason 
27012fcfd22SChris Mason /*
271e02119d5SChris Mason  * indicate we're done making changes to the log tree
272e02119d5SChris Mason  * and wake up anyone waiting to do a sync
273e02119d5SChris Mason  */
274143bede5SJeff Mahoney void btrfs_end_log_trans(struct btrfs_root *root)
275e02119d5SChris Mason {
2767237f183SYan Zheng 	if (atomic_dec_and_test(&root->log_writers)) {
277093258e6SDavid Sterba 		/* atomic_dec_and_test implies a barrier */
278093258e6SDavid Sterba 		cond_wake_up_nomb(&root->log_writer_wait);
2797237f183SYan Zheng 	}
280e02119d5SChris Mason }
281e02119d5SChris Mason 
282e02119d5SChris Mason /*
283e02119d5SChris Mason  * the walk control struct is used to pass state down the chain when
284e02119d5SChris Mason  * processing the log tree.  The stage field tells us which part
285e02119d5SChris Mason  * of the log tree processing we are currently doing.  The others
286e02119d5SChris Mason  * are state fields used for that specific part
287e02119d5SChris Mason  */
288e02119d5SChris Mason struct walk_control {
289e02119d5SChris Mason 	/* should we free the extent on disk when done?  This is used
290e02119d5SChris Mason 	 * at transaction commit time while freeing a log tree
291e02119d5SChris Mason 	 */
292e02119d5SChris Mason 	int free;
293e02119d5SChris Mason 
294e02119d5SChris Mason 	/* pin only walk, we record which extents on disk belong to the
295e02119d5SChris Mason 	 * log trees
296e02119d5SChris Mason 	 */
297e02119d5SChris Mason 	int pin;
298e02119d5SChris Mason 
299e02119d5SChris Mason 	/* what stage of the replay code we're currently in */
300e02119d5SChris Mason 	int stage;
301e02119d5SChris Mason 
302f2d72f42SFilipe Manana 	/*
303f2d72f42SFilipe Manana 	 * Ignore any items from the inode currently being processed. Needs
304f2d72f42SFilipe Manana 	 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
305f2d72f42SFilipe Manana 	 * the LOG_WALK_REPLAY_INODES stage.
306f2d72f42SFilipe Manana 	 */
307f2d72f42SFilipe Manana 	bool ignore_cur_inode;
308f2d72f42SFilipe Manana 
309e02119d5SChris Mason 	/* the root we are currently replaying */
310e02119d5SChris Mason 	struct btrfs_root *replay_dest;
311e02119d5SChris Mason 
312e02119d5SChris Mason 	/* the trans handle for the current replay */
313e02119d5SChris Mason 	struct btrfs_trans_handle *trans;
314e02119d5SChris Mason 
315e02119d5SChris Mason 	/* the function that gets used to process blocks we find in the
316e02119d5SChris Mason 	 * tree.  Note the extent_buffer might not be up to date when it is
317e02119d5SChris Mason 	 * passed in, and it must be checked or read if you need the data
318e02119d5SChris Mason 	 * inside it
319e02119d5SChris Mason 	 */
320e02119d5SChris Mason 	int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
321581c1760SQu Wenruo 			    struct walk_control *wc, u64 gen, int level);
322e02119d5SChris Mason };
323e02119d5SChris Mason 
324e02119d5SChris Mason /*
325e02119d5SChris Mason  * process_func used to pin down extents, write them or wait on them
326e02119d5SChris Mason  */
327e02119d5SChris Mason static int process_one_buffer(struct btrfs_root *log,
328e02119d5SChris Mason 			      struct extent_buffer *eb,
329581c1760SQu Wenruo 			      struct walk_control *wc, u64 gen, int level)
330e02119d5SChris Mason {
3310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = log->fs_info;
332b50c6e25SJosef Bacik 	int ret = 0;
333b50c6e25SJosef Bacik 
3348c2a1a30SJosef Bacik 	/*
3358c2a1a30SJosef Bacik 	 * If this fs is mixed then we need to be able to process the leaves to
3368c2a1a30SJosef Bacik 	 * pin down any logged extents, so we have to read the block.
3378c2a1a30SJosef Bacik 	 */
3380b246afaSJeff Mahoney 	if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
339789d6a3aSQu Wenruo 		struct btrfs_tree_parent_check check = {
340789d6a3aSQu Wenruo 			.level = level,
341789d6a3aSQu Wenruo 			.transid = gen
342789d6a3aSQu Wenruo 		};
343789d6a3aSQu Wenruo 
344789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(eb, &check);
3458c2a1a30SJosef Bacik 		if (ret)
3468c2a1a30SJosef Bacik 			return ret;
3478c2a1a30SJosef Bacik 	}
3488c2a1a30SJosef Bacik 
349c816d705SFilipe Manana 	if (wc->pin) {
3509fce5704SNikolay Borisov 		ret = btrfs_pin_extent_for_log_replay(wc->trans, eb->start,
3512ff7e61eSJeff Mahoney 						      eb->len);
352c816d705SFilipe Manana 		if (ret)
353c816d705SFilipe Manana 			return ret;
354e02119d5SChris Mason 
355c816d705SFilipe Manana 		if (btrfs_buffer_uptodate(eb, gen, 0) &&
356c816d705SFilipe Manana 		    btrfs_header_level(eb) == 0)
357bcdc428cSDavid Sterba 			ret = btrfs_exclude_logged_extents(eb);
358e02119d5SChris Mason 	}
359b50c6e25SJosef Bacik 	return ret;
360e02119d5SChris Mason }
361e02119d5SChris Mason 
3623a8d1db3SFilipe Manana /*
3633a8d1db3SFilipe Manana  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
3643a8d1db3SFilipe Manana  * to the src data we are copying out.
3653a8d1db3SFilipe Manana  *
3663a8d1db3SFilipe Manana  * root is the tree we are copying into, and path is a scratch
3673a8d1db3SFilipe Manana  * path for use in this function (it should be released on entry and
3683a8d1db3SFilipe Manana  * will be released on exit).
3693a8d1db3SFilipe Manana  *
3703a8d1db3SFilipe Manana  * If the key is already in the destination tree the existing item is
3713a8d1db3SFilipe Manana  * overwritten.  If the existing item isn't big enough, it is extended.
3723a8d1db3SFilipe Manana  * If it is too large, it is truncated.
3733a8d1db3SFilipe Manana  *
3743a8d1db3SFilipe Manana  * If the key isn't in the destination yet, a new item is inserted.
3753a8d1db3SFilipe Manana  */
3763a8d1db3SFilipe Manana static int overwrite_item(struct btrfs_trans_handle *trans,
377e02119d5SChris Mason 			  struct btrfs_root *root,
378e02119d5SChris Mason 			  struct btrfs_path *path,
379e02119d5SChris Mason 			  struct extent_buffer *eb, int slot,
380e02119d5SChris Mason 			  struct btrfs_key *key)
381e02119d5SChris Mason {
382e02119d5SChris Mason 	int ret;
383e02119d5SChris Mason 	u32 item_size;
384e02119d5SChris Mason 	u64 saved_i_size = 0;
385e02119d5SChris Mason 	int save_old_i_size = 0;
386e02119d5SChris Mason 	unsigned long src_ptr;
387e02119d5SChris Mason 	unsigned long dst_ptr;
3884bc4bee4SJosef Bacik 	bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
389e02119d5SChris Mason 
3903eb42344SFilipe Manana 	/*
3913eb42344SFilipe Manana 	 * This is only used during log replay, so the root is always from a
3923eb42344SFilipe Manana 	 * fs/subvolume tree. In case we ever need to support a log root, then
3933eb42344SFilipe Manana 	 * we'll have to clone the leaf in the path, release the path and use
3943eb42344SFilipe Manana 	 * the leaf before writing into the log tree. See the comments at
3953eb42344SFilipe Manana 	 * copy_items() for more details.
3963eb42344SFilipe Manana 	 */
3973eb42344SFilipe Manana 	ASSERT(root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID);
398e02119d5SChris Mason 
3993212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, slot);
400e02119d5SChris Mason 	src_ptr = btrfs_item_ptr_offset(eb, slot);
401e02119d5SChris Mason 
4023a8d1db3SFilipe Manana 	/* Look for the key in the destination tree. */
4033a8d1db3SFilipe Manana 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
4043a8d1db3SFilipe Manana 	if (ret < 0)
4053a8d1db3SFilipe Manana 		return ret;
4064bc4bee4SJosef Bacik 
407e02119d5SChris Mason 	if (ret == 0) {
408e02119d5SChris Mason 		char *src_copy;
409e02119d5SChris Mason 		char *dst_copy;
4103212fa14SJosef Bacik 		u32 dst_size = btrfs_item_size(path->nodes[0],
411e02119d5SChris Mason 						  path->slots[0]);
412e02119d5SChris Mason 		if (dst_size != item_size)
413e02119d5SChris Mason 			goto insert;
414e02119d5SChris Mason 
415e02119d5SChris Mason 		if (item_size == 0) {
416b3b4aa74SDavid Sterba 			btrfs_release_path(path);
417e02119d5SChris Mason 			return 0;
418e02119d5SChris Mason 		}
419e02119d5SChris Mason 		dst_copy = kmalloc(item_size, GFP_NOFS);
420e02119d5SChris Mason 		src_copy = kmalloc(item_size, GFP_NOFS);
4212a29edc6Sliubo 		if (!dst_copy || !src_copy) {
422b3b4aa74SDavid Sterba 			btrfs_release_path(path);
4232a29edc6Sliubo 			kfree(dst_copy);
4242a29edc6Sliubo 			kfree(src_copy);
4252a29edc6Sliubo 			return -ENOMEM;
4262a29edc6Sliubo 		}
427e02119d5SChris Mason 
428e02119d5SChris Mason 		read_extent_buffer(eb, src_copy, src_ptr, item_size);
429e02119d5SChris Mason 
430e02119d5SChris Mason 		dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
431e02119d5SChris Mason 		read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
432e02119d5SChris Mason 				   item_size);
433e02119d5SChris Mason 		ret = memcmp(dst_copy, src_copy, item_size);
434e02119d5SChris Mason 
435e02119d5SChris Mason 		kfree(dst_copy);
436e02119d5SChris Mason 		kfree(src_copy);
437e02119d5SChris Mason 		/*
438e02119d5SChris Mason 		 * they have the same contents, just return, this saves
439e02119d5SChris Mason 		 * us from cowing blocks in the destination tree and doing
440e02119d5SChris Mason 		 * extra writes that may not have been done by a previous
441e02119d5SChris Mason 		 * sync
442e02119d5SChris Mason 		 */
443e02119d5SChris Mason 		if (ret == 0) {
444b3b4aa74SDavid Sterba 			btrfs_release_path(path);
445e02119d5SChris Mason 			return 0;
446e02119d5SChris Mason 		}
447e02119d5SChris Mason 
4484bc4bee4SJosef Bacik 		/*
4494bc4bee4SJosef Bacik 		 * We need to load the old nbytes into the inode so when we
4504bc4bee4SJosef Bacik 		 * replay the extents we've logged we get the right nbytes.
4514bc4bee4SJosef Bacik 		 */
4524bc4bee4SJosef Bacik 		if (inode_item) {
4534bc4bee4SJosef Bacik 			struct btrfs_inode_item *item;
4544bc4bee4SJosef Bacik 			u64 nbytes;
455d555438bSJosef Bacik 			u32 mode;
4564bc4bee4SJosef Bacik 
4574bc4bee4SJosef Bacik 			item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4584bc4bee4SJosef Bacik 					      struct btrfs_inode_item);
4594bc4bee4SJosef Bacik 			nbytes = btrfs_inode_nbytes(path->nodes[0], item);
4604bc4bee4SJosef Bacik 			item = btrfs_item_ptr(eb, slot,
4614bc4bee4SJosef Bacik 					      struct btrfs_inode_item);
4624bc4bee4SJosef Bacik 			btrfs_set_inode_nbytes(eb, item, nbytes);
463d555438bSJosef Bacik 
464d555438bSJosef Bacik 			/*
465d555438bSJosef Bacik 			 * If this is a directory we need to reset the i_size to
466d555438bSJosef Bacik 			 * 0 so that we can set it up properly when replaying
467d555438bSJosef Bacik 			 * the rest of the items in this log.
468d555438bSJosef Bacik 			 */
469d555438bSJosef Bacik 			mode = btrfs_inode_mode(eb, item);
470d555438bSJosef Bacik 			if (S_ISDIR(mode))
471d555438bSJosef Bacik 				btrfs_set_inode_size(eb, item, 0);
4724bc4bee4SJosef Bacik 		}
4734bc4bee4SJosef Bacik 	} else if (inode_item) {
4744bc4bee4SJosef Bacik 		struct btrfs_inode_item *item;
475d555438bSJosef Bacik 		u32 mode;
4764bc4bee4SJosef Bacik 
4774bc4bee4SJosef Bacik 		/*
4784bc4bee4SJosef Bacik 		 * New inode, set nbytes to 0 so that the nbytes comes out
4794bc4bee4SJosef Bacik 		 * properly when we replay the extents.
4804bc4bee4SJosef Bacik 		 */
4814bc4bee4SJosef Bacik 		item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
4824bc4bee4SJosef Bacik 		btrfs_set_inode_nbytes(eb, item, 0);
483d555438bSJosef Bacik 
484d555438bSJosef Bacik 		/*
485d555438bSJosef Bacik 		 * If this is a directory we need to reset the i_size to 0 so
486d555438bSJosef Bacik 		 * that we can set it up properly when replaying the rest of
487d555438bSJosef Bacik 		 * the items in this log.
488d555438bSJosef Bacik 		 */
489d555438bSJosef Bacik 		mode = btrfs_inode_mode(eb, item);
490d555438bSJosef Bacik 		if (S_ISDIR(mode))
491d555438bSJosef Bacik 			btrfs_set_inode_size(eb, item, 0);
492e02119d5SChris Mason 	}
493e02119d5SChris Mason insert:
494b3b4aa74SDavid Sterba 	btrfs_release_path(path);
495e02119d5SChris Mason 	/* try to insert the key into the destination tree */
496df8d116fSFilipe Manana 	path->skip_release_on_error = 1;
497e02119d5SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path,
498e02119d5SChris Mason 				      key, item_size);
499df8d116fSFilipe Manana 	path->skip_release_on_error = 0;
500e02119d5SChris Mason 
501e02119d5SChris Mason 	/* make sure any existing item is the correct size */
502df8d116fSFilipe Manana 	if (ret == -EEXIST || ret == -EOVERFLOW) {
503e02119d5SChris Mason 		u32 found_size;
5043212fa14SJosef Bacik 		found_size = btrfs_item_size(path->nodes[0],
505e02119d5SChris Mason 						path->slots[0]);
506143bede5SJeff Mahoney 		if (found_size > item_size)
50778ac4f9eSDavid Sterba 			btrfs_truncate_item(path, item_size, 1);
508143bede5SJeff Mahoney 		else if (found_size < item_size)
509c71dd880SDavid Sterba 			btrfs_extend_item(path, item_size - found_size);
510e02119d5SChris Mason 	} else if (ret) {
5114a500fd1SYan, Zheng 		return ret;
512e02119d5SChris Mason 	}
513e02119d5SChris Mason 	dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
514e02119d5SChris Mason 					path->slots[0]);
515e02119d5SChris Mason 
516e02119d5SChris Mason 	/* don't overwrite an existing inode if the generation number
517e02119d5SChris Mason 	 * was logged as zero.  This is done when the tree logging code
518e02119d5SChris Mason 	 * is just logging an inode to make sure it exists after recovery.
519e02119d5SChris Mason 	 *
520e02119d5SChris Mason 	 * Also, don't overwrite i_size on directories during replay.
521e02119d5SChris Mason 	 * log replay inserts and removes directory items based on the
522e02119d5SChris Mason 	 * state of the tree found in the subvolume, and i_size is modified
523e02119d5SChris Mason 	 * as it goes
524e02119d5SChris Mason 	 */
525e02119d5SChris Mason 	if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
526e02119d5SChris Mason 		struct btrfs_inode_item *src_item;
527e02119d5SChris Mason 		struct btrfs_inode_item *dst_item;
528e02119d5SChris Mason 
529e02119d5SChris Mason 		src_item = (struct btrfs_inode_item *)src_ptr;
530e02119d5SChris Mason 		dst_item = (struct btrfs_inode_item *)dst_ptr;
531e02119d5SChris Mason 
5321a4bcf47SFilipe Manana 		if (btrfs_inode_generation(eb, src_item) == 0) {
5331a4bcf47SFilipe Manana 			struct extent_buffer *dst_eb = path->nodes[0];
5342f2ff0eeSFilipe Manana 			const u64 ino_size = btrfs_inode_size(eb, src_item);
5351a4bcf47SFilipe Manana 
5362f2ff0eeSFilipe Manana 			/*
5372f2ff0eeSFilipe Manana 			 * For regular files an ino_size == 0 is used only when
5382f2ff0eeSFilipe Manana 			 * logging that an inode exists, as part of a directory
5392f2ff0eeSFilipe Manana 			 * fsync, and the inode wasn't fsynced before. In this
5402f2ff0eeSFilipe Manana 			 * case don't set the size of the inode in the fs/subvol
5412f2ff0eeSFilipe Manana 			 * tree, otherwise we would be throwing valid data away.
5422f2ff0eeSFilipe Manana 			 */
5431a4bcf47SFilipe Manana 			if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
5442f2ff0eeSFilipe Manana 			    S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
54560d48e2eSDavid Sterba 			    ino_size != 0)
54660d48e2eSDavid Sterba 				btrfs_set_inode_size(dst_eb, dst_item, ino_size);
547e02119d5SChris Mason 			goto no_copy;
5481a4bcf47SFilipe Manana 		}
549e02119d5SChris Mason 
5503eb42344SFilipe Manana 		if (S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
551e02119d5SChris Mason 		    S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
552e02119d5SChris Mason 			save_old_i_size = 1;
553e02119d5SChris Mason 			saved_i_size = btrfs_inode_size(path->nodes[0],
554e02119d5SChris Mason 							dst_item);
555e02119d5SChris Mason 		}
556e02119d5SChris Mason 	}
557e02119d5SChris Mason 
558e02119d5SChris Mason 	copy_extent_buffer(path->nodes[0], eb, dst_ptr,
559e02119d5SChris Mason 			   src_ptr, item_size);
560e02119d5SChris Mason 
561e02119d5SChris Mason 	if (save_old_i_size) {
562e02119d5SChris Mason 		struct btrfs_inode_item *dst_item;
563e02119d5SChris Mason 		dst_item = (struct btrfs_inode_item *)dst_ptr;
564e02119d5SChris Mason 		btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
565e02119d5SChris Mason 	}
566e02119d5SChris Mason 
567e02119d5SChris Mason 	/* make sure the generation is filled in */
568e02119d5SChris Mason 	if (key->type == BTRFS_INODE_ITEM_KEY) {
569e02119d5SChris Mason 		struct btrfs_inode_item *dst_item;
570e02119d5SChris Mason 		dst_item = (struct btrfs_inode_item *)dst_ptr;
571e02119d5SChris Mason 		if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
572e02119d5SChris Mason 			btrfs_set_inode_generation(path->nodes[0], dst_item,
573e02119d5SChris Mason 						   trans->transid);
574e02119d5SChris Mason 		}
575e02119d5SChris Mason 	}
576e02119d5SChris Mason no_copy:
577e02119d5SChris Mason 	btrfs_mark_buffer_dirty(path->nodes[0]);
578b3b4aa74SDavid Sterba 	btrfs_release_path(path);
579e02119d5SChris Mason 	return 0;
580e02119d5SChris Mason }
581e02119d5SChris Mason 
582e43eec81SSweet Tea Dorminy static int read_alloc_one_name(struct extent_buffer *eb, void *start, int len,
5836db75318SSweet Tea Dorminy 			       struct fscrypt_str *name)
584e43eec81SSweet Tea Dorminy {
585e43eec81SSweet Tea Dorminy 	char *buf;
586e43eec81SSweet Tea Dorminy 
587e43eec81SSweet Tea Dorminy 	buf = kmalloc(len, GFP_NOFS);
588e43eec81SSweet Tea Dorminy 	if (!buf)
589e43eec81SSweet Tea Dorminy 		return -ENOMEM;
590e43eec81SSweet Tea Dorminy 
591e43eec81SSweet Tea Dorminy 	read_extent_buffer(eb, buf, (unsigned long)start, len);
592e43eec81SSweet Tea Dorminy 	name->name = buf;
593e43eec81SSweet Tea Dorminy 	name->len = len;
594e43eec81SSweet Tea Dorminy 	return 0;
595e43eec81SSweet Tea Dorminy }
596e43eec81SSweet Tea Dorminy 
597086dcbfaSFilipe Manana /*
598e02119d5SChris Mason  * simple helper to read an inode off the disk from a given root
599e02119d5SChris Mason  * This can only be called for subvolume roots and not for the log
600e02119d5SChris Mason  */
601e02119d5SChris Mason static noinline struct inode *read_one_inode(struct btrfs_root *root,
602e02119d5SChris Mason 					     u64 objectid)
603e02119d5SChris Mason {
604e02119d5SChris Mason 	struct inode *inode;
605e02119d5SChris Mason 
6060202e83fSDavid Sterba 	inode = btrfs_iget(root->fs_info->sb, objectid, root);
6072e19f1f9SAl Viro 	if (IS_ERR(inode))
6085d4f98a2SYan Zheng 		inode = NULL;
609e02119d5SChris Mason 	return inode;
610e02119d5SChris Mason }
611e02119d5SChris Mason 
612e02119d5SChris Mason /* replays a single extent in 'eb' at 'slot' with 'key' into the
613e02119d5SChris Mason  * subvolume 'root'.  path is released on entry and should be released
614e02119d5SChris Mason  * on exit.
615e02119d5SChris Mason  *
616e02119d5SChris Mason  * extents in the log tree have not been allocated out of the extent
617e02119d5SChris Mason  * tree yet.  So, this completes the allocation, taking a reference
618e02119d5SChris Mason  * as required if the extent already exists or creating a new extent
619e02119d5SChris Mason  * if it isn't in the extent allocation tree yet.
620e02119d5SChris Mason  *
621e02119d5SChris Mason  * The extent is inserted into the file, dropping any existing extents
622e02119d5SChris Mason  * from the file that overlap the new one.
623e02119d5SChris Mason  */
624e02119d5SChris Mason static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
625e02119d5SChris Mason 				      struct btrfs_root *root,
626e02119d5SChris Mason 				      struct btrfs_path *path,
627e02119d5SChris Mason 				      struct extent_buffer *eb, int slot,
628e02119d5SChris Mason 				      struct btrfs_key *key)
629e02119d5SChris Mason {
6305893dfb9SFilipe Manana 	struct btrfs_drop_extents_args drop_args = { 0 };
6310b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
632e02119d5SChris Mason 	int found_type;
633e02119d5SChris Mason 	u64 extent_end;
634e02119d5SChris Mason 	u64 start = key->offset;
6354bc4bee4SJosef Bacik 	u64 nbytes = 0;
636e02119d5SChris Mason 	struct btrfs_file_extent_item *item;
637e02119d5SChris Mason 	struct inode *inode = NULL;
638e02119d5SChris Mason 	unsigned long size;
639e02119d5SChris Mason 	int ret = 0;
640e02119d5SChris Mason 
641e02119d5SChris Mason 	item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
642e02119d5SChris Mason 	found_type = btrfs_file_extent_type(eb, item);
643e02119d5SChris Mason 
644d899e052SYan Zheng 	if (found_type == BTRFS_FILE_EXTENT_REG ||
6454bc4bee4SJosef Bacik 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6464bc4bee4SJosef Bacik 		nbytes = btrfs_file_extent_num_bytes(eb, item);
6474bc4bee4SJosef Bacik 		extent_end = start + nbytes;
6484bc4bee4SJosef Bacik 
6494bc4bee4SJosef Bacik 		/*
6504bc4bee4SJosef Bacik 		 * We don't add to the inodes nbytes if we are prealloc or a
6514bc4bee4SJosef Bacik 		 * hole.
6524bc4bee4SJosef Bacik 		 */
6534bc4bee4SJosef Bacik 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6544bc4bee4SJosef Bacik 			nbytes = 0;
6554bc4bee4SJosef Bacik 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
656e41ca589SQu Wenruo 		size = btrfs_file_extent_ram_bytes(eb, item);
6574bc4bee4SJosef Bacik 		nbytes = btrfs_file_extent_ram_bytes(eb, item);
658da17066cSJeff Mahoney 		extent_end = ALIGN(start + size,
6590b246afaSJeff Mahoney 				   fs_info->sectorsize);
660e02119d5SChris Mason 	} else {
661e02119d5SChris Mason 		ret = 0;
662e02119d5SChris Mason 		goto out;
663e02119d5SChris Mason 	}
664e02119d5SChris Mason 
665e02119d5SChris Mason 	inode = read_one_inode(root, key->objectid);
666e02119d5SChris Mason 	if (!inode) {
667e02119d5SChris Mason 		ret = -EIO;
668e02119d5SChris Mason 		goto out;
669e02119d5SChris Mason 	}
670e02119d5SChris Mason 
671e02119d5SChris Mason 	/*
672e02119d5SChris Mason 	 * first check to see if we already have this extent in the
673e02119d5SChris Mason 	 * file.  This must be done before the btrfs_drop_extents run
674e02119d5SChris Mason 	 * so we don't try to drop this extent.
675e02119d5SChris Mason 	 */
676f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(trans, root, path,
677f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(inode)), start, 0);
678e02119d5SChris Mason 
679d899e052SYan Zheng 	if (ret == 0 &&
680d899e052SYan Zheng 	    (found_type == BTRFS_FILE_EXTENT_REG ||
681d899e052SYan Zheng 	     found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
682e02119d5SChris Mason 		struct btrfs_file_extent_item cmp1;
683e02119d5SChris Mason 		struct btrfs_file_extent_item cmp2;
684e02119d5SChris Mason 		struct btrfs_file_extent_item *existing;
685e02119d5SChris Mason 		struct extent_buffer *leaf;
686e02119d5SChris Mason 
687e02119d5SChris Mason 		leaf = path->nodes[0];
688e02119d5SChris Mason 		existing = btrfs_item_ptr(leaf, path->slots[0],
689e02119d5SChris Mason 					  struct btrfs_file_extent_item);
690e02119d5SChris Mason 
691e02119d5SChris Mason 		read_extent_buffer(eb, &cmp1, (unsigned long)item,
692e02119d5SChris Mason 				   sizeof(cmp1));
693e02119d5SChris Mason 		read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
694e02119d5SChris Mason 				   sizeof(cmp2));
695e02119d5SChris Mason 
696e02119d5SChris Mason 		/*
697e02119d5SChris Mason 		 * we already have a pointer to this exact extent,
698e02119d5SChris Mason 		 * we don't have to do anything
699e02119d5SChris Mason 		 */
700e02119d5SChris Mason 		if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
701b3b4aa74SDavid Sterba 			btrfs_release_path(path);
702e02119d5SChris Mason 			goto out;
703e02119d5SChris Mason 		}
704e02119d5SChris Mason 	}
705b3b4aa74SDavid Sterba 	btrfs_release_path(path);
706e02119d5SChris Mason 
707e02119d5SChris Mason 	/* drop any overlapping extents */
7085893dfb9SFilipe Manana 	drop_args.start = start;
7095893dfb9SFilipe Manana 	drop_args.end = extent_end;
7105893dfb9SFilipe Manana 	drop_args.drop_cache = true;
7115893dfb9SFilipe Manana 	ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
7123650860bSJosef Bacik 	if (ret)
7133650860bSJosef Bacik 		goto out;
714e02119d5SChris Mason 
71507d400a6SYan Zheng 	if (found_type == BTRFS_FILE_EXTENT_REG ||
71607d400a6SYan Zheng 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7175d4f98a2SYan Zheng 		u64 offset;
71807d400a6SYan Zheng 		unsigned long dest_offset;
71907d400a6SYan Zheng 		struct btrfs_key ins;
72007d400a6SYan Zheng 
7213168021cSFilipe Manana 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
7223168021cSFilipe Manana 		    btrfs_fs_incompat(fs_info, NO_HOLES))
7233168021cSFilipe Manana 			goto update_inode;
7243168021cSFilipe Manana 
72507d400a6SYan Zheng 		ret = btrfs_insert_empty_item(trans, root, path, key,
72607d400a6SYan Zheng 					      sizeof(*item));
7273650860bSJosef Bacik 		if (ret)
7283650860bSJosef Bacik 			goto out;
72907d400a6SYan Zheng 		dest_offset = btrfs_item_ptr_offset(path->nodes[0],
73007d400a6SYan Zheng 						    path->slots[0]);
73107d400a6SYan Zheng 		copy_extent_buffer(path->nodes[0], eb, dest_offset,
73207d400a6SYan Zheng 				(unsigned long)item,  sizeof(*item));
73307d400a6SYan Zheng 
73407d400a6SYan Zheng 		ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
73507d400a6SYan Zheng 		ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
73607d400a6SYan Zheng 		ins.type = BTRFS_EXTENT_ITEM_KEY;
7375d4f98a2SYan Zheng 		offset = key->offset - btrfs_file_extent_offset(eb, item);
73807d400a6SYan Zheng 
739df2c95f3SQu Wenruo 		/*
740df2c95f3SQu Wenruo 		 * Manually record dirty extent, as here we did a shallow
741df2c95f3SQu Wenruo 		 * file extent item copy and skip normal backref update,
742df2c95f3SQu Wenruo 		 * but modifying extent tree all by ourselves.
743df2c95f3SQu Wenruo 		 * So need to manually record dirty extent for qgroup,
744df2c95f3SQu Wenruo 		 * as the owner of the file extent changed from log tree
745df2c95f3SQu Wenruo 		 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
746df2c95f3SQu Wenruo 		 */
747a95f3aafSLu Fengqi 		ret = btrfs_qgroup_trace_extent(trans,
748df2c95f3SQu Wenruo 				btrfs_file_extent_disk_bytenr(eb, item),
749e2896e79SDavid Sterba 				btrfs_file_extent_disk_num_bytes(eb, item));
750df2c95f3SQu Wenruo 		if (ret < 0)
751df2c95f3SQu Wenruo 			goto out;
752df2c95f3SQu Wenruo 
75307d400a6SYan Zheng 		if (ins.objectid > 0) {
75482fa113fSQu Wenruo 			struct btrfs_ref ref = { 0 };
75507d400a6SYan Zheng 			u64 csum_start;
75607d400a6SYan Zheng 			u64 csum_end;
75707d400a6SYan Zheng 			LIST_HEAD(ordered_sums);
75882fa113fSQu Wenruo 
75907d400a6SYan Zheng 			/*
76007d400a6SYan Zheng 			 * is this extent already allocated in the extent
76107d400a6SYan Zheng 			 * allocation tree?  If so, just add a reference
76207d400a6SYan Zheng 			 */
7632ff7e61eSJeff Mahoney 			ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
76407d400a6SYan Zheng 						ins.offset);
7653736127aSMarcos Paulo de Souza 			if (ret < 0) {
7663736127aSMarcos Paulo de Souza 				goto out;
7673736127aSMarcos Paulo de Souza 			} else if (ret == 0) {
76882fa113fSQu Wenruo 				btrfs_init_generic_ref(&ref,
76982fa113fSQu Wenruo 						BTRFS_ADD_DELAYED_REF,
77082fa113fSQu Wenruo 						ins.objectid, ins.offset, 0);
77182fa113fSQu Wenruo 				btrfs_init_data_ref(&ref,
77282fa113fSQu Wenruo 						root->root_key.objectid,
773f42c5da6SNikolay Borisov 						key->objectid, offset, 0, false);
77482fa113fSQu Wenruo 				ret = btrfs_inc_extent_ref(trans, &ref);
775b50c6e25SJosef Bacik 				if (ret)
776b50c6e25SJosef Bacik 					goto out;
77707d400a6SYan Zheng 			} else {
77807d400a6SYan Zheng 				/*
77907d400a6SYan Zheng 				 * insert the extent pointer in the extent
78007d400a6SYan Zheng 				 * allocation tree
78107d400a6SYan Zheng 				 */
7825d4f98a2SYan Zheng 				ret = btrfs_alloc_logged_file_extent(trans,
7832ff7e61eSJeff Mahoney 						root->root_key.objectid,
7845d4f98a2SYan Zheng 						key->objectid, offset, &ins);
785b50c6e25SJosef Bacik 				if (ret)
786b50c6e25SJosef Bacik 					goto out;
78707d400a6SYan Zheng 			}
788b3b4aa74SDavid Sterba 			btrfs_release_path(path);
78907d400a6SYan Zheng 
79007d400a6SYan Zheng 			if (btrfs_file_extent_compression(eb, item)) {
79107d400a6SYan Zheng 				csum_start = ins.objectid;
79207d400a6SYan Zheng 				csum_end = csum_start + ins.offset;
79307d400a6SYan Zheng 			} else {
79407d400a6SYan Zheng 				csum_start = ins.objectid +
79507d400a6SYan Zheng 					btrfs_file_extent_offset(eb, item);
79607d400a6SYan Zheng 				csum_end = csum_start +
79707d400a6SYan Zheng 					btrfs_file_extent_num_bytes(eb, item);
79807d400a6SYan Zheng 			}
79907d400a6SYan Zheng 
80097e38239SQu Wenruo 			ret = btrfs_lookup_csums_list(root->log_root,
80107d400a6SYan Zheng 						csum_start, csum_end - 1,
80226ce9114SJosef Bacik 						&ordered_sums, 0, false);
8033650860bSJosef Bacik 			if (ret)
8043650860bSJosef Bacik 				goto out;
805b84b8390SFilipe Manana 			/*
806b84b8390SFilipe Manana 			 * Now delete all existing cums in the csum root that
807b84b8390SFilipe Manana 			 * cover our range. We do this because we can have an
808b84b8390SFilipe Manana 			 * extent that is completely referenced by one file
809b84b8390SFilipe Manana 			 * extent item and partially referenced by another
810b84b8390SFilipe Manana 			 * file extent item (like after using the clone or
811b84b8390SFilipe Manana 			 * extent_same ioctls). In this case if we end up doing
812b84b8390SFilipe Manana 			 * the replay of the one that partially references the
813b84b8390SFilipe Manana 			 * extent first, and we do not do the csum deletion
814b84b8390SFilipe Manana 			 * below, we can get 2 csum items in the csum tree that
815b84b8390SFilipe Manana 			 * overlap each other. For example, imagine our log has
816b84b8390SFilipe Manana 			 * the two following file extent items:
817b84b8390SFilipe Manana 			 *
818b84b8390SFilipe Manana 			 * key (257 EXTENT_DATA 409600)
819b84b8390SFilipe Manana 			 *     extent data disk byte 12845056 nr 102400
820b84b8390SFilipe Manana 			 *     extent data offset 20480 nr 20480 ram 102400
821b84b8390SFilipe Manana 			 *
822b84b8390SFilipe Manana 			 * key (257 EXTENT_DATA 819200)
823b84b8390SFilipe Manana 			 *     extent data disk byte 12845056 nr 102400
824b84b8390SFilipe Manana 			 *     extent data offset 0 nr 102400 ram 102400
825b84b8390SFilipe Manana 			 *
826b84b8390SFilipe Manana 			 * Where the second one fully references the 100K extent
827b84b8390SFilipe Manana 			 * that starts at disk byte 12845056, and the log tree
828b84b8390SFilipe Manana 			 * has a single csum item that covers the entire range
829b84b8390SFilipe Manana 			 * of the extent:
830b84b8390SFilipe Manana 			 *
831b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
832b84b8390SFilipe Manana 			 *
833b84b8390SFilipe Manana 			 * After the first file extent item is replayed, the
834b84b8390SFilipe Manana 			 * csum tree gets the following csum item:
835b84b8390SFilipe Manana 			 *
836b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
837b84b8390SFilipe Manana 			 *
838b84b8390SFilipe Manana 			 * Which covers the 20K sub-range starting at offset 20K
839b84b8390SFilipe Manana 			 * of our extent. Now when we replay the second file
840b84b8390SFilipe Manana 			 * extent item, if we do not delete existing csum items
841b84b8390SFilipe Manana 			 * that cover any of its blocks, we end up getting two
842b84b8390SFilipe Manana 			 * csum items in our csum tree that overlap each other:
843b84b8390SFilipe Manana 			 *
844b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
845b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
846b84b8390SFilipe Manana 			 *
847b84b8390SFilipe Manana 			 * Which is a problem, because after this anyone trying
848b84b8390SFilipe Manana 			 * to lookup up for the checksum of any block of our
849b84b8390SFilipe Manana 			 * extent starting at an offset of 40K or higher, will
850b84b8390SFilipe Manana 			 * end up looking at the second csum item only, which
851b84b8390SFilipe Manana 			 * does not contain the checksum for any block starting
852b84b8390SFilipe Manana 			 * at offset 40K or higher of our extent.
853b84b8390SFilipe Manana 			 */
85407d400a6SYan Zheng 			while (!list_empty(&ordered_sums)) {
85507d400a6SYan Zheng 				struct btrfs_ordered_sum *sums;
856fc28b25eSJosef Bacik 				struct btrfs_root *csum_root;
857fc28b25eSJosef Bacik 
85807d400a6SYan Zheng 				sums = list_entry(ordered_sums.next,
85907d400a6SYan Zheng 						struct btrfs_ordered_sum,
86007d400a6SYan Zheng 						list);
861fc28b25eSJosef Bacik 				csum_root = btrfs_csum_root(fs_info,
862fc28b25eSJosef Bacik 							    sums->bytenr);
8633650860bSJosef Bacik 				if (!ret)
864fc28b25eSJosef Bacik 					ret = btrfs_del_csums(trans, csum_root,
865b84b8390SFilipe Manana 							      sums->bytenr,
866b84b8390SFilipe Manana 							      sums->len);
867b84b8390SFilipe Manana 				if (!ret)
86807d400a6SYan Zheng 					ret = btrfs_csum_file_blocks(trans,
869fc28b25eSJosef Bacik 								     csum_root,
870fc28b25eSJosef Bacik 								     sums);
87107d400a6SYan Zheng 				list_del(&sums->list);
87207d400a6SYan Zheng 				kfree(sums);
87307d400a6SYan Zheng 			}
8743650860bSJosef Bacik 			if (ret)
8753650860bSJosef Bacik 				goto out;
87607d400a6SYan Zheng 		} else {
877b3b4aa74SDavid Sterba 			btrfs_release_path(path);
87807d400a6SYan Zheng 		}
87907d400a6SYan Zheng 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
88007d400a6SYan Zheng 		/* inline extents are easy, we just overwrite them */
881e02119d5SChris Mason 		ret = overwrite_item(trans, root, path, eb, slot, key);
8823650860bSJosef Bacik 		if (ret)
8833650860bSJosef Bacik 			goto out;
88407d400a6SYan Zheng 	}
885e02119d5SChris Mason 
8869ddc959eSJosef Bacik 	ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start,
8879ddc959eSJosef Bacik 						extent_end - start);
8889ddc959eSJosef Bacik 	if (ret)
8899ddc959eSJosef Bacik 		goto out;
8909ddc959eSJosef Bacik 
8913168021cSFilipe Manana update_inode:
8922766ff61SFilipe Manana 	btrfs_update_inode_bytes(BTRFS_I(inode), nbytes, drop_args.bytes_found);
8939a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
894e02119d5SChris Mason out:
895e02119d5SChris Mason 	iput(inode);
896e02119d5SChris Mason 	return ret;
897e02119d5SChris Mason }
898e02119d5SChris Mason 
899313ab753SFilipe Manana static int unlink_inode_for_log_replay(struct btrfs_trans_handle *trans,
900313ab753SFilipe Manana 				       struct btrfs_inode *dir,
901313ab753SFilipe Manana 				       struct btrfs_inode *inode,
9026db75318SSweet Tea Dorminy 				       const struct fscrypt_str *name)
903313ab753SFilipe Manana {
904313ab753SFilipe Manana 	int ret;
905313ab753SFilipe Manana 
906e43eec81SSweet Tea Dorminy 	ret = btrfs_unlink_inode(trans, dir, inode, name);
907313ab753SFilipe Manana 	if (ret)
908313ab753SFilipe Manana 		return ret;
909313ab753SFilipe Manana 	/*
910313ab753SFilipe Manana 	 * Whenever we need to check if a name exists or not, we check the
911313ab753SFilipe Manana 	 * fs/subvolume tree. So after an unlink we must run delayed items, so
912313ab753SFilipe Manana 	 * that future checks for a name during log replay see that the name
913313ab753SFilipe Manana 	 * does not exists anymore.
914313ab753SFilipe Manana 	 */
915313ab753SFilipe Manana 	return btrfs_run_delayed_items(trans);
916313ab753SFilipe Manana }
917313ab753SFilipe Manana 
918e02119d5SChris Mason /*
919e02119d5SChris Mason  * when cleaning up conflicts between the directory names in the
920e02119d5SChris Mason  * subvolume, directory names in the log and directory names in the
921e02119d5SChris Mason  * inode back references, we may have to unlink inodes from directories.
922e02119d5SChris Mason  *
923e02119d5SChris Mason  * This is a helper function to do the unlink of a specific directory
924e02119d5SChris Mason  * item
925e02119d5SChris Mason  */
926e02119d5SChris Mason static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
927e02119d5SChris Mason 				      struct btrfs_path *path,
928207e7d92SNikolay Borisov 				      struct btrfs_inode *dir,
929e02119d5SChris Mason 				      struct btrfs_dir_item *di)
930e02119d5SChris Mason {
9319798ba24SFilipe Manana 	struct btrfs_root *root = dir->root;
932e02119d5SChris Mason 	struct inode *inode;
9336db75318SSweet Tea Dorminy 	struct fscrypt_str name;
934e02119d5SChris Mason 	struct extent_buffer *leaf;
935e02119d5SChris Mason 	struct btrfs_key location;
936e02119d5SChris Mason 	int ret;
937e02119d5SChris Mason 
938e02119d5SChris Mason 	leaf = path->nodes[0];
939e02119d5SChris Mason 
940e02119d5SChris Mason 	btrfs_dir_item_key_to_cpu(leaf, di, &location);
941e43eec81SSweet Tea Dorminy 	ret = read_alloc_one_name(leaf, di + 1, btrfs_dir_name_len(leaf, di), &name);
942e43eec81SSweet Tea Dorminy 	if (ret)
9432a29edc6Sliubo 		return -ENOMEM;
9442a29edc6Sliubo 
945b3b4aa74SDavid Sterba 	btrfs_release_path(path);
946e02119d5SChris Mason 
947e02119d5SChris Mason 	inode = read_one_inode(root, location.objectid);
948c00e9493STsutomu Itoh 	if (!inode) {
9493650860bSJosef Bacik 		ret = -EIO;
9503650860bSJosef Bacik 		goto out;
951c00e9493STsutomu Itoh 	}
952e02119d5SChris Mason 
953ec051c0fSYan Zheng 	ret = link_to_fixup_dir(trans, root, path, location.objectid);
9543650860bSJosef Bacik 	if (ret)
9553650860bSJosef Bacik 		goto out;
95612fcfd22SChris Mason 
957e43eec81SSweet Tea Dorminy 	ret = unlink_inode_for_log_replay(trans, dir, BTRFS_I(inode), &name);
9583650860bSJosef Bacik out:
959e43eec81SSweet Tea Dorminy 	kfree(name.name);
9603650860bSJosef Bacik 	iput(inode);
961e02119d5SChris Mason 	return ret;
962e02119d5SChris Mason }
963e02119d5SChris Mason 
964e02119d5SChris Mason /*
96577a5b9e3SFilipe Manana  * See if a given name and sequence number found in an inode back reference are
96677a5b9e3SFilipe Manana  * already in a directory and correctly point to this inode.
96777a5b9e3SFilipe Manana  *
96877a5b9e3SFilipe Manana  * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
96977a5b9e3SFilipe Manana  * exists.
970e02119d5SChris Mason  */
971e02119d5SChris Mason static noinline int inode_in_dir(struct btrfs_root *root,
972e02119d5SChris Mason 				 struct btrfs_path *path,
973e02119d5SChris Mason 				 u64 dirid, u64 objectid, u64 index,
9746db75318SSweet Tea Dorminy 				 struct fscrypt_str *name)
975e02119d5SChris Mason {
976e02119d5SChris Mason 	struct btrfs_dir_item *di;
977e02119d5SChris Mason 	struct btrfs_key location;
97877a5b9e3SFilipe Manana 	int ret = 0;
979e02119d5SChris Mason 
980e02119d5SChris Mason 	di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
981e43eec81SSweet Tea Dorminy 					 index, name, 0);
98277a5b9e3SFilipe Manana 	if (IS_ERR(di)) {
98377a5b9e3SFilipe Manana 		ret = PTR_ERR(di);
98477a5b9e3SFilipe Manana 		goto out;
98577a5b9e3SFilipe Manana 	} else if (di) {
986e02119d5SChris Mason 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
987e02119d5SChris Mason 		if (location.objectid != objectid)
988e02119d5SChris Mason 			goto out;
98977a5b9e3SFilipe Manana 	} else {
990e02119d5SChris Mason 		goto out;
99177a5b9e3SFilipe Manana 	}
992e02119d5SChris Mason 
99377a5b9e3SFilipe Manana 	btrfs_release_path(path);
994e43eec81SSweet Tea Dorminy 	di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, 0);
99577a5b9e3SFilipe Manana 	if (IS_ERR(di)) {
99677a5b9e3SFilipe Manana 		ret = PTR_ERR(di);
99777a5b9e3SFilipe Manana 		goto out;
99877a5b9e3SFilipe Manana 	} else if (di) {
999e02119d5SChris Mason 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
100077a5b9e3SFilipe Manana 		if (location.objectid == objectid)
100177a5b9e3SFilipe Manana 			ret = 1;
100277a5b9e3SFilipe Manana 	}
1003e02119d5SChris Mason out:
1004b3b4aa74SDavid Sterba 	btrfs_release_path(path);
100577a5b9e3SFilipe Manana 	return ret;
1006e02119d5SChris Mason }
1007e02119d5SChris Mason 
1008e02119d5SChris Mason /*
1009e02119d5SChris Mason  * helper function to check a log tree for a named back reference in
1010e02119d5SChris Mason  * an inode.  This is used to decide if a back reference that is
1011e02119d5SChris Mason  * found in the subvolume conflicts with what we find in the log.
1012e02119d5SChris Mason  *
1013e02119d5SChris Mason  * inode backreferences may have multiple refs in a single item,
1014e02119d5SChris Mason  * during replay we process one reference at a time, and we don't
1015e02119d5SChris Mason  * want to delete valid links to a file from the subvolume if that
1016e02119d5SChris Mason  * link is also in the log.
1017e02119d5SChris Mason  */
1018e02119d5SChris Mason static noinline int backref_in_log(struct btrfs_root *log,
1019e02119d5SChris Mason 				   struct btrfs_key *key,
1020f186373fSMark Fasheh 				   u64 ref_objectid,
10216db75318SSweet Tea Dorminy 				   const struct fscrypt_str *name)
1022e02119d5SChris Mason {
1023e02119d5SChris Mason 	struct btrfs_path *path;
1024e02119d5SChris Mason 	int ret;
1025e02119d5SChris Mason 
1026e02119d5SChris Mason 	path = btrfs_alloc_path();
10272a29edc6Sliubo 	if (!path)
10282a29edc6Sliubo 		return -ENOMEM;
10292a29edc6Sliubo 
1030e02119d5SChris Mason 	ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1031d3316c82SNikolay Borisov 	if (ret < 0) {
1032d3316c82SNikolay Borisov 		goto out;
1033d3316c82SNikolay Borisov 	} else if (ret == 1) {
103489cbf5f6SNikolay Borisov 		ret = 0;
1035e02119d5SChris Mason 		goto out;
103689cbf5f6SNikolay Borisov 	}
1037e02119d5SChris Mason 
103889cbf5f6SNikolay Borisov 	if (key->type == BTRFS_INODE_EXTREF_KEY)
103989cbf5f6SNikolay Borisov 		ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
10401f250e92SFilipe Manana 						       path->slots[0],
1041e43eec81SSweet Tea Dorminy 						       ref_objectid, name);
104289cbf5f6SNikolay Borisov 	else
104389cbf5f6SNikolay Borisov 		ret = !!btrfs_find_name_in_backref(path->nodes[0],
1044e43eec81SSweet Tea Dorminy 						   path->slots[0], name);
1045e02119d5SChris Mason out:
1046e02119d5SChris Mason 	btrfs_free_path(path);
104789cbf5f6SNikolay Borisov 	return ret;
1048e02119d5SChris Mason }
1049e02119d5SChris Mason 
10505a1d7843SJan Schmidt static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
10515a1d7843SJan Schmidt 				  struct btrfs_root *root,
10525a1d7843SJan Schmidt 				  struct btrfs_path *path,
10535a1d7843SJan Schmidt 				  struct btrfs_root *log_root,
105494c91a1fSNikolay Borisov 				  struct btrfs_inode *dir,
105594c91a1fSNikolay Borisov 				  struct btrfs_inode *inode,
1056f186373fSMark Fasheh 				  u64 inode_objectid, u64 parent_objectid,
10576db75318SSweet Tea Dorminy 				  u64 ref_index, struct fscrypt_str *name)
10585a1d7843SJan Schmidt {
10595a1d7843SJan Schmidt 	int ret;
1060f186373fSMark Fasheh 	struct extent_buffer *leaf;
1061f186373fSMark Fasheh 	struct btrfs_dir_item *di;
1062f186373fSMark Fasheh 	struct btrfs_key search_key;
1063f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
1064f186373fSMark Fasheh 
1065f186373fSMark Fasheh again:
1066f186373fSMark Fasheh 	/* Search old style refs */
1067f186373fSMark Fasheh 	search_key.objectid = inode_objectid;
1068f186373fSMark Fasheh 	search_key.type = BTRFS_INODE_REF_KEY;
1069f186373fSMark Fasheh 	search_key.offset = parent_objectid;
1070f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1071f186373fSMark Fasheh 	if (ret == 0) {
10725a1d7843SJan Schmidt 		struct btrfs_inode_ref *victim_ref;
10735a1d7843SJan Schmidt 		unsigned long ptr;
10745a1d7843SJan Schmidt 		unsigned long ptr_end;
1075f186373fSMark Fasheh 
1076f186373fSMark Fasheh 		leaf = path->nodes[0];
10775a1d7843SJan Schmidt 
10785a1d7843SJan Schmidt 		/* are we trying to overwrite a back ref for the root directory
10795a1d7843SJan Schmidt 		 * if so, just jump out, we're done
10805a1d7843SJan Schmidt 		 */
1081f186373fSMark Fasheh 		if (search_key.objectid == search_key.offset)
10825a1d7843SJan Schmidt 			return 1;
10835a1d7843SJan Schmidt 
10845a1d7843SJan Schmidt 		/* check all the names in this back reference to see
10855a1d7843SJan Schmidt 		 * if they are in the log.  if so, we allow them to stay
10865a1d7843SJan Schmidt 		 * otherwise they must be unlinked as a conflict
10875a1d7843SJan Schmidt 		 */
10885a1d7843SJan Schmidt 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
10893212fa14SJosef Bacik 		ptr_end = ptr + btrfs_item_size(leaf, path->slots[0]);
10905a1d7843SJan Schmidt 		while (ptr < ptr_end) {
10916db75318SSweet Tea Dorminy 			struct fscrypt_str victim_name;
10925a1d7843SJan Schmidt 
1093e43eec81SSweet Tea Dorminy 			victim_ref = (struct btrfs_inode_ref *)ptr;
1094e43eec81SSweet Tea Dorminy 			ret = read_alloc_one_name(leaf, (victim_ref + 1),
1095e43eec81SSweet Tea Dorminy 				 btrfs_inode_ref_name_len(leaf, victim_ref),
1096e43eec81SSweet Tea Dorminy 				 &victim_name);
1097e43eec81SSweet Tea Dorminy 			if (ret)
1098e43eec81SSweet Tea Dorminy 				return ret;
10995a1d7843SJan Schmidt 
1100d3316c82SNikolay Borisov 			ret = backref_in_log(log_root, &search_key,
1101e43eec81SSweet Tea Dorminy 					     parent_objectid, &victim_name);
1102d3316c82SNikolay Borisov 			if (ret < 0) {
1103e43eec81SSweet Tea Dorminy 				kfree(victim_name.name);
1104d3316c82SNikolay Borisov 				return ret;
1105d3316c82SNikolay Borisov 			} else if (!ret) {
110694c91a1fSNikolay Borisov 				inc_nlink(&inode->vfs_inode);
11075a1d7843SJan Schmidt 				btrfs_release_path(path);
11085a1d7843SJan Schmidt 
1109313ab753SFilipe Manana 				ret = unlink_inode_for_log_replay(trans, dir, inode,
1110e43eec81SSweet Tea Dorminy 						&victim_name);
1111e43eec81SSweet Tea Dorminy 				kfree(victim_name.name);
11123650860bSJosef Bacik 				if (ret)
11133650860bSJosef Bacik 					return ret;
1114f186373fSMark Fasheh 				goto again;
11155a1d7843SJan Schmidt 			}
1116e43eec81SSweet Tea Dorminy 			kfree(victim_name.name);
1117f186373fSMark Fasheh 
1118e43eec81SSweet Tea Dorminy 			ptr = (unsigned long)(victim_ref + 1) + victim_name.len;
11195a1d7843SJan Schmidt 		}
11205a1d7843SJan Schmidt 	}
11215a1d7843SJan Schmidt 	btrfs_release_path(path);
11225a1d7843SJan Schmidt 
1123f186373fSMark Fasheh 	/* Same search but for extended refs */
1124e43eec81SSweet Tea Dorminy 	extref = btrfs_lookup_inode_extref(NULL, root, path, name,
1125f186373fSMark Fasheh 					   inode_objectid, parent_objectid, 0,
1126f186373fSMark Fasheh 					   0);
11277a6b75b7SFilipe Manana 	if (IS_ERR(extref)) {
11287a6b75b7SFilipe Manana 		return PTR_ERR(extref);
11297a6b75b7SFilipe Manana 	} else if (extref) {
1130f186373fSMark Fasheh 		u32 item_size;
1131f186373fSMark Fasheh 		u32 cur_offset = 0;
1132f186373fSMark Fasheh 		unsigned long base;
1133f186373fSMark Fasheh 		struct inode *victim_parent;
1134f186373fSMark Fasheh 
1135f186373fSMark Fasheh 		leaf = path->nodes[0];
1136f186373fSMark Fasheh 
11373212fa14SJosef Bacik 		item_size = btrfs_item_size(leaf, path->slots[0]);
1138f186373fSMark Fasheh 		base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1139f186373fSMark Fasheh 
1140f186373fSMark Fasheh 		while (cur_offset < item_size) {
11416db75318SSweet Tea Dorminy 			struct fscrypt_str victim_name;
1142f186373fSMark Fasheh 
1143e43eec81SSweet Tea Dorminy 			extref = (struct btrfs_inode_extref *)(base + cur_offset);
1144f186373fSMark Fasheh 
1145f186373fSMark Fasheh 			if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1146f186373fSMark Fasheh 				goto next;
1147f186373fSMark Fasheh 
1148e43eec81SSweet Tea Dorminy 			ret = read_alloc_one_name(leaf, &extref->name,
1149e43eec81SSweet Tea Dorminy 				 btrfs_inode_extref_name_len(leaf, extref),
1150e43eec81SSweet Tea Dorminy 				 &victim_name);
1151e43eec81SSweet Tea Dorminy 			if (ret)
1152e43eec81SSweet Tea Dorminy 				return ret;
1153f186373fSMark Fasheh 
1154f186373fSMark Fasheh 			search_key.objectid = inode_objectid;
1155f186373fSMark Fasheh 			search_key.type = BTRFS_INODE_EXTREF_KEY;
1156f186373fSMark Fasheh 			search_key.offset = btrfs_extref_hash(parent_objectid,
1157e43eec81SSweet Tea Dorminy 							      victim_name.name,
1158e43eec81SSweet Tea Dorminy 							      victim_name.len);
1159d3316c82SNikolay Borisov 			ret = backref_in_log(log_root, &search_key,
1160e43eec81SSweet Tea Dorminy 					     parent_objectid, &victim_name);
1161d3316c82SNikolay Borisov 			if (ret < 0) {
1162e43eec81SSweet Tea Dorminy 				kfree(victim_name.name);
1163d3316c82SNikolay Borisov 				return ret;
1164d3316c82SNikolay Borisov 			} else if (!ret) {
1165f186373fSMark Fasheh 				ret = -ENOENT;
1166f186373fSMark Fasheh 				victim_parent = read_one_inode(root,
1167f186373fSMark Fasheh 						parent_objectid);
1168f186373fSMark Fasheh 				if (victim_parent) {
116994c91a1fSNikolay Borisov 					inc_nlink(&inode->vfs_inode);
1170f186373fSMark Fasheh 					btrfs_release_path(path);
1171f186373fSMark Fasheh 
1172313ab753SFilipe Manana 					ret = unlink_inode_for_log_replay(trans,
11734ec5934eSNikolay Borisov 							BTRFS_I(victim_parent),
1174e43eec81SSweet Tea Dorminy 							inode, &victim_name);
1175f186373fSMark Fasheh 				}
1176f186373fSMark Fasheh 				iput(victim_parent);
1177e43eec81SSweet Tea Dorminy 				kfree(victim_name.name);
11783650860bSJosef Bacik 				if (ret)
11793650860bSJosef Bacik 					return ret;
1180f186373fSMark Fasheh 				goto again;
1181f186373fSMark Fasheh 			}
1182e43eec81SSweet Tea Dorminy 			kfree(victim_name.name);
1183f186373fSMark Fasheh next:
1184e43eec81SSweet Tea Dorminy 			cur_offset += victim_name.len + sizeof(*extref);
1185f186373fSMark Fasheh 		}
1186f186373fSMark Fasheh 	}
1187f186373fSMark Fasheh 	btrfs_release_path(path);
1188f186373fSMark Fasheh 
11895a1d7843SJan Schmidt 	/* look for a conflicting sequence number */
119094c91a1fSNikolay Borisov 	di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1191e43eec81SSweet Tea Dorminy 					 ref_index, name, 0);
119252db7779SFilipe Manana 	if (IS_ERR(di)) {
119352db7779SFilipe Manana 		return PTR_ERR(di);
119452db7779SFilipe Manana 	} else if (di) {
11959798ba24SFilipe Manana 		ret = drop_one_dir_item(trans, path, dir, di);
11963650860bSJosef Bacik 		if (ret)
11973650860bSJosef Bacik 			return ret;
11985a1d7843SJan Schmidt 	}
11995a1d7843SJan Schmidt 	btrfs_release_path(path);
12005a1d7843SJan Schmidt 
120152042d8eSAndrea Gelmini 	/* look for a conflicting name */
1202e43eec81SSweet Tea Dorminy 	di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir), name, 0);
120352db7779SFilipe Manana 	if (IS_ERR(di)) {
120452db7779SFilipe Manana 		return PTR_ERR(di);
120552db7779SFilipe Manana 	} else if (di) {
12069798ba24SFilipe Manana 		ret = drop_one_dir_item(trans, path, dir, di);
12073650860bSJosef Bacik 		if (ret)
12083650860bSJosef Bacik 			return ret;
12095a1d7843SJan Schmidt 	}
12105a1d7843SJan Schmidt 	btrfs_release_path(path);
12115a1d7843SJan Schmidt 
12125a1d7843SJan Schmidt 	return 0;
12135a1d7843SJan Schmidt }
1214e02119d5SChris Mason 
1215bae15d95SQu Wenruo static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
12166db75318SSweet Tea Dorminy 			     struct fscrypt_str *name, u64 *index,
1217bae15d95SQu Wenruo 			     u64 *parent_objectid)
1218f186373fSMark Fasheh {
1219f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
1220e43eec81SSweet Tea Dorminy 	int ret;
1221f186373fSMark Fasheh 
1222f186373fSMark Fasheh 	extref = (struct btrfs_inode_extref *)ref_ptr;
1223f186373fSMark Fasheh 
1224e43eec81SSweet Tea Dorminy 	ret = read_alloc_one_name(eb, &extref->name,
1225e43eec81SSweet Tea Dorminy 				  btrfs_inode_extref_name_len(eb, extref), name);
1226e43eec81SSweet Tea Dorminy 	if (ret)
1227e43eec81SSweet Tea Dorminy 		return ret;
1228f186373fSMark Fasheh 
12291f250e92SFilipe Manana 	if (index)
1230f186373fSMark Fasheh 		*index = btrfs_inode_extref_index(eb, extref);
1231f186373fSMark Fasheh 	if (parent_objectid)
1232f186373fSMark Fasheh 		*parent_objectid = btrfs_inode_extref_parent(eb, extref);
1233f186373fSMark Fasheh 
1234f186373fSMark Fasheh 	return 0;
1235f186373fSMark Fasheh }
1236f186373fSMark Fasheh 
1237bae15d95SQu Wenruo static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
12386db75318SSweet Tea Dorminy 			  struct fscrypt_str *name, u64 *index)
1239f186373fSMark Fasheh {
1240f186373fSMark Fasheh 	struct btrfs_inode_ref *ref;
1241e43eec81SSweet Tea Dorminy 	int ret;
1242f186373fSMark Fasheh 
1243f186373fSMark Fasheh 	ref = (struct btrfs_inode_ref *)ref_ptr;
1244f186373fSMark Fasheh 
1245e43eec81SSweet Tea Dorminy 	ret = read_alloc_one_name(eb, ref + 1, btrfs_inode_ref_name_len(eb, ref),
1246e43eec81SSweet Tea Dorminy 				  name);
1247e43eec81SSweet Tea Dorminy 	if (ret)
1248e43eec81SSweet Tea Dorminy 		return ret;
1249f186373fSMark Fasheh 
12501f250e92SFilipe Manana 	if (index)
1251f186373fSMark Fasheh 		*index = btrfs_inode_ref_index(eb, ref);
1252f186373fSMark Fasheh 
1253f186373fSMark Fasheh 	return 0;
1254f186373fSMark Fasheh }
1255f186373fSMark Fasheh 
1256e02119d5SChris Mason /*
12571f250e92SFilipe Manana  * Take an inode reference item from the log tree and iterate all names from the
12581f250e92SFilipe Manana  * inode reference item in the subvolume tree with the same key (if it exists).
12591f250e92SFilipe Manana  * For any name that is not in the inode reference item from the log tree, do a
12601f250e92SFilipe Manana  * proper unlink of that name (that is, remove its entry from the inode
12611f250e92SFilipe Manana  * reference item and both dir index keys).
12621f250e92SFilipe Manana  */
12631f250e92SFilipe Manana static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
12641f250e92SFilipe Manana 				 struct btrfs_root *root,
12651f250e92SFilipe Manana 				 struct btrfs_path *path,
12661f250e92SFilipe Manana 				 struct btrfs_inode *inode,
12671f250e92SFilipe Manana 				 struct extent_buffer *log_eb,
12681f250e92SFilipe Manana 				 int log_slot,
12691f250e92SFilipe Manana 				 struct btrfs_key *key)
12701f250e92SFilipe Manana {
12711f250e92SFilipe Manana 	int ret;
12721f250e92SFilipe Manana 	unsigned long ref_ptr;
12731f250e92SFilipe Manana 	unsigned long ref_end;
12741f250e92SFilipe Manana 	struct extent_buffer *eb;
12751f250e92SFilipe Manana 
12761f250e92SFilipe Manana again:
12771f250e92SFilipe Manana 	btrfs_release_path(path);
12781f250e92SFilipe Manana 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
12791f250e92SFilipe Manana 	if (ret > 0) {
12801f250e92SFilipe Manana 		ret = 0;
12811f250e92SFilipe Manana 		goto out;
12821f250e92SFilipe Manana 	}
12831f250e92SFilipe Manana 	if (ret < 0)
12841f250e92SFilipe Manana 		goto out;
12851f250e92SFilipe Manana 
12861f250e92SFilipe Manana 	eb = path->nodes[0];
12871f250e92SFilipe Manana 	ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
12883212fa14SJosef Bacik 	ref_end = ref_ptr + btrfs_item_size(eb, path->slots[0]);
12891f250e92SFilipe Manana 	while (ref_ptr < ref_end) {
12906db75318SSweet Tea Dorminy 		struct fscrypt_str name;
12911f250e92SFilipe Manana 		u64 parent_id;
12921f250e92SFilipe Manana 
12931f250e92SFilipe Manana 		if (key->type == BTRFS_INODE_EXTREF_KEY) {
1294e43eec81SSweet Tea Dorminy 			ret = extref_get_fields(eb, ref_ptr, &name,
12951f250e92SFilipe Manana 						NULL, &parent_id);
12961f250e92SFilipe Manana 		} else {
12971f250e92SFilipe Manana 			parent_id = key->offset;
1298e43eec81SSweet Tea Dorminy 			ret = ref_get_fields(eb, ref_ptr, &name, NULL);
12991f250e92SFilipe Manana 		}
13001f250e92SFilipe Manana 		if (ret)
13011f250e92SFilipe Manana 			goto out;
13021f250e92SFilipe Manana 
13031f250e92SFilipe Manana 		if (key->type == BTRFS_INODE_EXTREF_KEY)
13046ff49c6aSNikolay Borisov 			ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
1305e43eec81SSweet Tea Dorminy 							       parent_id, &name);
13061f250e92SFilipe Manana 		else
1307e43eec81SSweet Tea Dorminy 			ret = !!btrfs_find_name_in_backref(log_eb, log_slot, &name);
13081f250e92SFilipe Manana 
13091f250e92SFilipe Manana 		if (!ret) {
13101f250e92SFilipe Manana 			struct inode *dir;
13111f250e92SFilipe Manana 
13121f250e92SFilipe Manana 			btrfs_release_path(path);
13131f250e92SFilipe Manana 			dir = read_one_inode(root, parent_id);
13141f250e92SFilipe Manana 			if (!dir) {
13151f250e92SFilipe Manana 				ret = -ENOENT;
1316e43eec81SSweet Tea Dorminy 				kfree(name.name);
13171f250e92SFilipe Manana 				goto out;
13181f250e92SFilipe Manana 			}
1319313ab753SFilipe Manana 			ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir),
1320e43eec81SSweet Tea Dorminy 						 inode, &name);
1321e43eec81SSweet Tea Dorminy 			kfree(name.name);
13221f250e92SFilipe Manana 			iput(dir);
13231f250e92SFilipe Manana 			if (ret)
13241f250e92SFilipe Manana 				goto out;
13251f250e92SFilipe Manana 			goto again;
13261f250e92SFilipe Manana 		}
13271f250e92SFilipe Manana 
1328e43eec81SSweet Tea Dorminy 		kfree(name.name);
1329e43eec81SSweet Tea Dorminy 		ref_ptr += name.len;
13301f250e92SFilipe Manana 		if (key->type == BTRFS_INODE_EXTREF_KEY)
13311f250e92SFilipe Manana 			ref_ptr += sizeof(struct btrfs_inode_extref);
13321f250e92SFilipe Manana 		else
13331f250e92SFilipe Manana 			ref_ptr += sizeof(struct btrfs_inode_ref);
13341f250e92SFilipe Manana 	}
13351f250e92SFilipe Manana 	ret = 0;
13361f250e92SFilipe Manana  out:
13371f250e92SFilipe Manana 	btrfs_release_path(path);
13381f250e92SFilipe Manana 	return ret;
13391f250e92SFilipe Manana }
13401f250e92SFilipe Manana 
13411f250e92SFilipe Manana /*
1342e02119d5SChris Mason  * replay one inode back reference item found in the log tree.
1343e02119d5SChris Mason  * eb, slot and key refer to the buffer and key found in the log tree.
1344e02119d5SChris Mason  * root is the destination we are replaying into, and path is for temp
1345e02119d5SChris Mason  * use by this function.  (it should be released on return).
1346e02119d5SChris Mason  */
1347e02119d5SChris Mason static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1348e02119d5SChris Mason 				  struct btrfs_root *root,
1349e02119d5SChris Mason 				  struct btrfs_root *log,
1350e02119d5SChris Mason 				  struct btrfs_path *path,
1351e02119d5SChris Mason 				  struct extent_buffer *eb, int slot,
1352e02119d5SChris Mason 				  struct btrfs_key *key)
1353e02119d5SChris Mason {
135403b2f08bSGeyslan G. Bem 	struct inode *dir = NULL;
135503b2f08bSGeyslan G. Bem 	struct inode *inode = NULL;
1356e02119d5SChris Mason 	unsigned long ref_ptr;
1357e02119d5SChris Mason 	unsigned long ref_end;
13586db75318SSweet Tea Dorminy 	struct fscrypt_str name;
135934f3e4f2Sliubo 	int ret;
1360f186373fSMark Fasheh 	int log_ref_ver = 0;
1361f186373fSMark Fasheh 	u64 parent_objectid;
1362f186373fSMark Fasheh 	u64 inode_objectid;
1363f46dbe3dSChris Mason 	u64 ref_index = 0;
1364f186373fSMark Fasheh 	int ref_struct_size;
1365f186373fSMark Fasheh 
1366f186373fSMark Fasheh 	ref_ptr = btrfs_item_ptr_offset(eb, slot);
13673212fa14SJosef Bacik 	ref_end = ref_ptr + btrfs_item_size(eb, slot);
1368f186373fSMark Fasheh 
1369f186373fSMark Fasheh 	if (key->type == BTRFS_INODE_EXTREF_KEY) {
1370f186373fSMark Fasheh 		struct btrfs_inode_extref *r;
1371f186373fSMark Fasheh 
1372f186373fSMark Fasheh 		ref_struct_size = sizeof(struct btrfs_inode_extref);
1373f186373fSMark Fasheh 		log_ref_ver = 1;
1374f186373fSMark Fasheh 		r = (struct btrfs_inode_extref *)ref_ptr;
1375f186373fSMark Fasheh 		parent_objectid = btrfs_inode_extref_parent(eb, r);
1376f186373fSMark Fasheh 	} else {
1377f186373fSMark Fasheh 		ref_struct_size = sizeof(struct btrfs_inode_ref);
1378f186373fSMark Fasheh 		parent_objectid = key->offset;
1379f186373fSMark Fasheh 	}
1380f186373fSMark Fasheh 	inode_objectid = key->objectid;
1381e02119d5SChris Mason 
1382e02119d5SChris Mason 	/*
1383e02119d5SChris Mason 	 * it is possible that we didn't log all the parent directories
1384e02119d5SChris Mason 	 * for a given inode.  If we don't find the dir, just don't
1385e02119d5SChris Mason 	 * copy the back ref in.  The link count fixup code will take
1386e02119d5SChris Mason 	 * care of the rest
1387e02119d5SChris Mason 	 */
1388f186373fSMark Fasheh 	dir = read_one_inode(root, parent_objectid);
138903b2f08bSGeyslan G. Bem 	if (!dir) {
139003b2f08bSGeyslan G. Bem 		ret = -ENOENT;
139103b2f08bSGeyslan G. Bem 		goto out;
139203b2f08bSGeyslan G. Bem 	}
1393e02119d5SChris Mason 
1394f186373fSMark Fasheh 	inode = read_one_inode(root, inode_objectid);
1395c00e9493STsutomu Itoh 	if (!inode) {
139603b2f08bSGeyslan G. Bem 		ret = -EIO;
139703b2f08bSGeyslan G. Bem 		goto out;
1398c00e9493STsutomu Itoh 	}
1399e02119d5SChris Mason 
14005a1d7843SJan Schmidt 	while (ref_ptr < ref_end) {
1401f186373fSMark Fasheh 		if (log_ref_ver) {
1402e43eec81SSweet Tea Dorminy 			ret = extref_get_fields(eb, ref_ptr, &name,
1403bae15d95SQu Wenruo 						&ref_index, &parent_objectid);
1404f186373fSMark Fasheh 			/*
1405f186373fSMark Fasheh 			 * parent object can change from one array
1406f186373fSMark Fasheh 			 * item to another.
1407f186373fSMark Fasheh 			 */
1408f186373fSMark Fasheh 			if (!dir)
1409f186373fSMark Fasheh 				dir = read_one_inode(root, parent_objectid);
141003b2f08bSGeyslan G. Bem 			if (!dir) {
141103b2f08bSGeyslan G. Bem 				ret = -ENOENT;
141203b2f08bSGeyslan G. Bem 				goto out;
141303b2f08bSGeyslan G. Bem 			}
1414f186373fSMark Fasheh 		} else {
1415e43eec81SSweet Tea Dorminy 			ret = ref_get_fields(eb, ref_ptr, &name, &ref_index);
1416f186373fSMark Fasheh 		}
1417f186373fSMark Fasheh 		if (ret)
141803b2f08bSGeyslan G. Bem 			goto out;
1419e02119d5SChris Mason 
142077a5b9e3SFilipe Manana 		ret = inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1421e43eec81SSweet Tea Dorminy 				   btrfs_ino(BTRFS_I(inode)), ref_index, &name);
142277a5b9e3SFilipe Manana 		if (ret < 0) {
142377a5b9e3SFilipe Manana 			goto out;
142477a5b9e3SFilipe Manana 		} else if (ret == 0) {
14255a1d7843SJan Schmidt 			/*
14265a1d7843SJan Schmidt 			 * look for a conflicting back reference in the
14275a1d7843SJan Schmidt 			 * metadata. if we find one we have to unlink that name
14285a1d7843SJan Schmidt 			 * of the file before we add our new link.  Later on, we
14295a1d7843SJan Schmidt 			 * overwrite any existing back reference, and we don't
14305a1d7843SJan Schmidt 			 * want to create dangling pointers in the directory.
14315a1d7843SJan Schmidt 			 */
14325a1d7843SJan Schmidt 			ret = __add_inode_ref(trans, root, path, log,
14337059c658SFilipe Manana 					      BTRFS_I(dir), BTRFS_I(inode),
14347059c658SFilipe Manana 					      inode_objectid, parent_objectid,
1435e43eec81SSweet Tea Dorminy 					      ref_index, &name);
143603b2f08bSGeyslan G. Bem 			if (ret) {
143703b2f08bSGeyslan G. Bem 				if (ret == 1)
14383650860bSJosef Bacik 					ret = 0;
1439e02119d5SChris Mason 				goto out;
14403650860bSJosef Bacik 			}
14410d836392SFilipe Manana 
1442e02119d5SChris Mason 			/* insert our name */
14437059c658SFilipe Manana 			ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
1444e43eec81SSweet Tea Dorminy 					     &name, 0, ref_index);
14453650860bSJosef Bacik 			if (ret)
14463650860bSJosef Bacik 				goto out;
1447e02119d5SChris Mason 
1448f96d4474SJosef Bacik 			ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1449f96d4474SJosef Bacik 			if (ret)
1450f96d4474SJosef Bacik 				goto out;
14515a1d7843SJan Schmidt 		}
145277a5b9e3SFilipe Manana 		/* Else, ret == 1, we already have a perfect match, we're done. */
1453e02119d5SChris Mason 
1454e43eec81SSweet Tea Dorminy 		ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + name.len;
1455e43eec81SSweet Tea Dorminy 		kfree(name.name);
1456e43eec81SSweet Tea Dorminy 		name.name = NULL;
1457f186373fSMark Fasheh 		if (log_ref_ver) {
1458f186373fSMark Fasheh 			iput(dir);
1459f186373fSMark Fasheh 			dir = NULL;
1460f186373fSMark Fasheh 		}
14615a1d7843SJan Schmidt 	}
1462e02119d5SChris Mason 
14631f250e92SFilipe Manana 	/*
14641f250e92SFilipe Manana 	 * Before we overwrite the inode reference item in the subvolume tree
14651f250e92SFilipe Manana 	 * with the item from the log tree, we must unlink all names from the
14661f250e92SFilipe Manana 	 * parent directory that are in the subvolume's tree inode reference
14671f250e92SFilipe Manana 	 * item, otherwise we end up with an inconsistent subvolume tree where
14681f250e92SFilipe Manana 	 * dir index entries exist for a name but there is no inode reference
14691f250e92SFilipe Manana 	 * item with the same name.
14701f250e92SFilipe Manana 	 */
14711f250e92SFilipe Manana 	ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
14721f250e92SFilipe Manana 				    key);
14731f250e92SFilipe Manana 	if (ret)
14741f250e92SFilipe Manana 		goto out;
14751f250e92SFilipe Manana 
1476e02119d5SChris Mason 	/* finally write the back reference in the inode */
1477e02119d5SChris Mason 	ret = overwrite_item(trans, root, path, eb, slot, key);
14785a1d7843SJan Schmidt out:
1479b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1480e43eec81SSweet Tea Dorminy 	kfree(name.name);
1481e02119d5SChris Mason 	iput(dir);
1482e02119d5SChris Mason 	iput(inode);
14833650860bSJosef Bacik 	return ret;
1484e02119d5SChris Mason }
1485e02119d5SChris Mason 
1486f186373fSMark Fasheh static int count_inode_extrefs(struct btrfs_root *root,
148736283658SNikolay Borisov 		struct btrfs_inode *inode, struct btrfs_path *path)
1488e02119d5SChris Mason {
1489f186373fSMark Fasheh 	int ret = 0;
1490f186373fSMark Fasheh 	int name_len;
1491f186373fSMark Fasheh 	unsigned int nlink = 0;
1492f186373fSMark Fasheh 	u32 item_size;
1493f186373fSMark Fasheh 	u32 cur_offset = 0;
149436283658SNikolay Borisov 	u64 inode_objectid = btrfs_ino(inode);
1495f186373fSMark Fasheh 	u64 offset = 0;
1496f186373fSMark Fasheh 	unsigned long ptr;
1497f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
1498f186373fSMark Fasheh 	struct extent_buffer *leaf;
1499f186373fSMark Fasheh 
1500f186373fSMark Fasheh 	while (1) {
1501f186373fSMark Fasheh 		ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1502f186373fSMark Fasheh 					    &extref, &offset);
1503f186373fSMark Fasheh 		if (ret)
1504f186373fSMark Fasheh 			break;
1505f186373fSMark Fasheh 
1506f186373fSMark Fasheh 		leaf = path->nodes[0];
15073212fa14SJosef Bacik 		item_size = btrfs_item_size(leaf, path->slots[0]);
1508f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
15092c2c452bSFilipe Manana 		cur_offset = 0;
1510f186373fSMark Fasheh 
1511f186373fSMark Fasheh 		while (cur_offset < item_size) {
1512f186373fSMark Fasheh 			extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1513f186373fSMark Fasheh 			name_len = btrfs_inode_extref_name_len(leaf, extref);
1514f186373fSMark Fasheh 
1515f186373fSMark Fasheh 			nlink++;
1516f186373fSMark Fasheh 
1517f186373fSMark Fasheh 			cur_offset += name_len + sizeof(*extref);
1518f186373fSMark Fasheh 		}
1519f186373fSMark Fasheh 
1520f186373fSMark Fasheh 		offset++;
1521f186373fSMark Fasheh 		btrfs_release_path(path);
1522f186373fSMark Fasheh 	}
1523f186373fSMark Fasheh 	btrfs_release_path(path);
1524f186373fSMark Fasheh 
15252c2c452bSFilipe Manana 	if (ret < 0 && ret != -ENOENT)
1526f186373fSMark Fasheh 		return ret;
1527f186373fSMark Fasheh 	return nlink;
1528f186373fSMark Fasheh }
1529f186373fSMark Fasheh 
1530f186373fSMark Fasheh static int count_inode_refs(struct btrfs_root *root,
1531f329e319SNikolay Borisov 			struct btrfs_inode *inode, struct btrfs_path *path)
1532f186373fSMark Fasheh {
1533e02119d5SChris Mason 	int ret;
1534e02119d5SChris Mason 	struct btrfs_key key;
1535f186373fSMark Fasheh 	unsigned int nlink = 0;
1536e02119d5SChris Mason 	unsigned long ptr;
1537e02119d5SChris Mason 	unsigned long ptr_end;
1538e02119d5SChris Mason 	int name_len;
1539f329e319SNikolay Borisov 	u64 ino = btrfs_ino(inode);
1540e02119d5SChris Mason 
154133345d01SLi Zefan 	key.objectid = ino;
1542e02119d5SChris Mason 	key.type = BTRFS_INODE_REF_KEY;
1543e02119d5SChris Mason 	key.offset = (u64)-1;
1544e02119d5SChris Mason 
1545e02119d5SChris Mason 	while (1) {
1546e02119d5SChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1547e02119d5SChris Mason 		if (ret < 0)
1548e02119d5SChris Mason 			break;
1549e02119d5SChris Mason 		if (ret > 0) {
1550e02119d5SChris Mason 			if (path->slots[0] == 0)
1551e02119d5SChris Mason 				break;
1552e02119d5SChris Mason 			path->slots[0]--;
1553e02119d5SChris Mason 		}
1554e93ae26fSFilipe David Borba Manana process_slot:
1555e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &key,
1556e02119d5SChris Mason 				      path->slots[0]);
155733345d01SLi Zefan 		if (key.objectid != ino ||
1558e02119d5SChris Mason 		    key.type != BTRFS_INODE_REF_KEY)
1559e02119d5SChris Mason 			break;
1560e02119d5SChris Mason 		ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
15613212fa14SJosef Bacik 		ptr_end = ptr + btrfs_item_size(path->nodes[0],
1562e02119d5SChris Mason 						   path->slots[0]);
1563e02119d5SChris Mason 		while (ptr < ptr_end) {
1564e02119d5SChris Mason 			struct btrfs_inode_ref *ref;
1565e02119d5SChris Mason 
1566e02119d5SChris Mason 			ref = (struct btrfs_inode_ref *)ptr;
1567e02119d5SChris Mason 			name_len = btrfs_inode_ref_name_len(path->nodes[0],
1568e02119d5SChris Mason 							    ref);
1569e02119d5SChris Mason 			ptr = (unsigned long)(ref + 1) + name_len;
1570e02119d5SChris Mason 			nlink++;
1571e02119d5SChris Mason 		}
1572e02119d5SChris Mason 
1573e02119d5SChris Mason 		if (key.offset == 0)
1574e02119d5SChris Mason 			break;
1575e93ae26fSFilipe David Borba Manana 		if (path->slots[0] > 0) {
1576e93ae26fSFilipe David Borba Manana 			path->slots[0]--;
1577e93ae26fSFilipe David Borba Manana 			goto process_slot;
1578e93ae26fSFilipe David Borba Manana 		}
1579e02119d5SChris Mason 		key.offset--;
1580b3b4aa74SDavid Sterba 		btrfs_release_path(path);
1581e02119d5SChris Mason 	}
1582b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1583f186373fSMark Fasheh 
1584f186373fSMark Fasheh 	return nlink;
1585f186373fSMark Fasheh }
1586f186373fSMark Fasheh 
1587f186373fSMark Fasheh /*
1588f186373fSMark Fasheh  * There are a few corners where the link count of the file can't
1589f186373fSMark Fasheh  * be properly maintained during replay.  So, instead of adding
1590f186373fSMark Fasheh  * lots of complexity to the log code, we just scan the backrefs
1591f186373fSMark Fasheh  * for any file that has been through replay.
1592f186373fSMark Fasheh  *
1593f186373fSMark Fasheh  * The scan will update the link count on the inode to reflect the
1594f186373fSMark Fasheh  * number of back refs found.  If it goes down to zero, the iput
1595f186373fSMark Fasheh  * will free the inode.
1596f186373fSMark Fasheh  */
1597f186373fSMark Fasheh static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1598f186373fSMark Fasheh 					   struct btrfs_root *root,
1599f186373fSMark Fasheh 					   struct inode *inode)
1600f186373fSMark Fasheh {
1601f186373fSMark Fasheh 	struct btrfs_path *path;
1602f186373fSMark Fasheh 	int ret;
1603f186373fSMark Fasheh 	u64 nlink = 0;
16044a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
1605f186373fSMark Fasheh 
1606f186373fSMark Fasheh 	path = btrfs_alloc_path();
1607f186373fSMark Fasheh 	if (!path)
1608f186373fSMark Fasheh 		return -ENOMEM;
1609f186373fSMark Fasheh 
1610f329e319SNikolay Borisov 	ret = count_inode_refs(root, BTRFS_I(inode), path);
1611f186373fSMark Fasheh 	if (ret < 0)
1612f186373fSMark Fasheh 		goto out;
1613f186373fSMark Fasheh 
1614f186373fSMark Fasheh 	nlink = ret;
1615f186373fSMark Fasheh 
161636283658SNikolay Borisov 	ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1617f186373fSMark Fasheh 	if (ret < 0)
1618f186373fSMark Fasheh 		goto out;
1619f186373fSMark Fasheh 
1620f186373fSMark Fasheh 	nlink += ret;
1621f186373fSMark Fasheh 
1622f186373fSMark Fasheh 	ret = 0;
1623f186373fSMark Fasheh 
1624e02119d5SChris Mason 	if (nlink != inode->i_nlink) {
1625bfe86848SMiklos Szeredi 		set_nlink(inode, nlink);
1626f96d4474SJosef Bacik 		ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1627f96d4474SJosef Bacik 		if (ret)
1628f96d4474SJosef Bacik 			goto out;
1629e02119d5SChris Mason 	}
16308d5bf1cbSChris Mason 	BTRFS_I(inode)->index_cnt = (u64)-1;
1631e02119d5SChris Mason 
1632c71bf099SYan, Zheng 	if (inode->i_nlink == 0) {
1633c71bf099SYan, Zheng 		if (S_ISDIR(inode->i_mode)) {
163412fcfd22SChris Mason 			ret = replay_dir_deletes(trans, root, NULL, path,
163533345d01SLi Zefan 						 ino, 1);
16363650860bSJosef Bacik 			if (ret)
16373650860bSJosef Bacik 				goto out;
163812fcfd22SChris Mason 		}
1639ecdcf3c2SNikolay Borisov 		ret = btrfs_insert_orphan_item(trans, root, ino);
1640ecdcf3c2SNikolay Borisov 		if (ret == -EEXIST)
1641ecdcf3c2SNikolay Borisov 			ret = 0;
1642c71bf099SYan, Zheng 	}
164312fcfd22SChris Mason 
1644f186373fSMark Fasheh out:
1645f186373fSMark Fasheh 	btrfs_free_path(path);
1646f186373fSMark Fasheh 	return ret;
1647e02119d5SChris Mason }
1648e02119d5SChris Mason 
1649e02119d5SChris Mason static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1650e02119d5SChris Mason 					    struct btrfs_root *root,
1651e02119d5SChris Mason 					    struct btrfs_path *path)
1652e02119d5SChris Mason {
1653e02119d5SChris Mason 	int ret;
1654e02119d5SChris Mason 	struct btrfs_key key;
1655e02119d5SChris Mason 	struct inode *inode;
1656e02119d5SChris Mason 
1657e02119d5SChris Mason 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1658e02119d5SChris Mason 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1659e02119d5SChris Mason 	key.offset = (u64)-1;
1660e02119d5SChris Mason 	while (1) {
1661e02119d5SChris Mason 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1662e02119d5SChris Mason 		if (ret < 0)
1663e02119d5SChris Mason 			break;
1664e02119d5SChris Mason 
1665e02119d5SChris Mason 		if (ret == 1) {
1666011b28acSJosef Bacik 			ret = 0;
1667e02119d5SChris Mason 			if (path->slots[0] == 0)
1668e02119d5SChris Mason 				break;
1669e02119d5SChris Mason 			path->slots[0]--;
1670e02119d5SChris Mason 		}
1671e02119d5SChris Mason 
1672e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1673e02119d5SChris Mason 		if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1674e02119d5SChris Mason 		    key.type != BTRFS_ORPHAN_ITEM_KEY)
1675e02119d5SChris Mason 			break;
1676e02119d5SChris Mason 
1677e02119d5SChris Mason 		ret = btrfs_del_item(trans, root, path);
167865a246c5STsutomu Itoh 		if (ret)
1679011b28acSJosef Bacik 			break;
1680e02119d5SChris Mason 
1681b3b4aa74SDavid Sterba 		btrfs_release_path(path);
1682e02119d5SChris Mason 		inode = read_one_inode(root, key.offset);
1683011b28acSJosef Bacik 		if (!inode) {
1684011b28acSJosef Bacik 			ret = -EIO;
1685011b28acSJosef Bacik 			break;
1686011b28acSJosef Bacik 		}
1687e02119d5SChris Mason 
1688e02119d5SChris Mason 		ret = fixup_inode_link_count(trans, root, inode);
1689e02119d5SChris Mason 		iput(inode);
16903650860bSJosef Bacik 		if (ret)
1691011b28acSJosef Bacik 			break;
1692e02119d5SChris Mason 
169312fcfd22SChris Mason 		/*
169412fcfd22SChris Mason 		 * fixup on a directory may create new entries,
169512fcfd22SChris Mason 		 * make sure we always look for the highset possible
169612fcfd22SChris Mason 		 * offset
169712fcfd22SChris Mason 		 */
169812fcfd22SChris Mason 		key.offset = (u64)-1;
1699e02119d5SChris Mason 	}
1700b3b4aa74SDavid Sterba 	btrfs_release_path(path);
170165a246c5STsutomu Itoh 	return ret;
1702e02119d5SChris Mason }
1703e02119d5SChris Mason 
1704e02119d5SChris Mason 
1705e02119d5SChris Mason /*
1706e02119d5SChris Mason  * record a given inode in the fixup dir so we can check its link
1707e02119d5SChris Mason  * count when replay is done.  The link count is incremented here
1708e02119d5SChris Mason  * so the inode won't go away until we check it
1709e02119d5SChris Mason  */
1710e02119d5SChris Mason static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1711e02119d5SChris Mason 				      struct btrfs_root *root,
1712e02119d5SChris Mason 				      struct btrfs_path *path,
1713e02119d5SChris Mason 				      u64 objectid)
1714e02119d5SChris Mason {
1715e02119d5SChris Mason 	struct btrfs_key key;
1716e02119d5SChris Mason 	int ret = 0;
1717e02119d5SChris Mason 	struct inode *inode;
1718e02119d5SChris Mason 
1719e02119d5SChris Mason 	inode = read_one_inode(root, objectid);
1720c00e9493STsutomu Itoh 	if (!inode)
1721c00e9493STsutomu Itoh 		return -EIO;
1722e02119d5SChris Mason 
1723e02119d5SChris Mason 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1724962a298fSDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1725e02119d5SChris Mason 	key.offset = objectid;
1726e02119d5SChris Mason 
1727e02119d5SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1728e02119d5SChris Mason 
1729b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1730e02119d5SChris Mason 	if (ret == 0) {
17319bf7a489SJosef Bacik 		if (!inode->i_nlink)
17329bf7a489SJosef Bacik 			set_nlink(inode, 1);
17339bf7a489SJosef Bacik 		else
17348b558c5fSZach Brown 			inc_nlink(inode);
17359a56fcd1SNikolay Borisov 		ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1736e02119d5SChris Mason 	} else if (ret == -EEXIST) {
1737e02119d5SChris Mason 		ret = 0;
1738e02119d5SChris Mason 	}
1739e02119d5SChris Mason 	iput(inode);
1740e02119d5SChris Mason 
1741e02119d5SChris Mason 	return ret;
1742e02119d5SChris Mason }
1743e02119d5SChris Mason 
1744e02119d5SChris Mason /*
1745e02119d5SChris Mason  * when replaying the log for a directory, we only insert names
1746e02119d5SChris Mason  * for inodes that actually exist.  This means an fsync on a directory
1747e02119d5SChris Mason  * does not implicitly fsync all the new files in it
1748e02119d5SChris Mason  */
1749e02119d5SChris Mason static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1750e02119d5SChris Mason 				    struct btrfs_root *root,
1751e02119d5SChris Mason 				    u64 dirid, u64 index,
17526db75318SSweet Tea Dorminy 				    const struct fscrypt_str *name,
1753e02119d5SChris Mason 				    struct btrfs_key *location)
1754e02119d5SChris Mason {
1755e02119d5SChris Mason 	struct inode *inode;
1756e02119d5SChris Mason 	struct inode *dir;
1757e02119d5SChris Mason 	int ret;
1758e02119d5SChris Mason 
1759e02119d5SChris Mason 	inode = read_one_inode(root, location->objectid);
1760e02119d5SChris Mason 	if (!inode)
1761e02119d5SChris Mason 		return -ENOENT;
1762e02119d5SChris Mason 
1763e02119d5SChris Mason 	dir = read_one_inode(root, dirid);
1764e02119d5SChris Mason 	if (!dir) {
1765e02119d5SChris Mason 		iput(inode);
1766e02119d5SChris Mason 		return -EIO;
1767e02119d5SChris Mason 	}
1768d555438bSJosef Bacik 
1769db0a669fSNikolay Borisov 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1770e43eec81SSweet Tea Dorminy 			     1, index);
1771e02119d5SChris Mason 
1772e02119d5SChris Mason 	/* FIXME, put inode into FIXUP list */
1773e02119d5SChris Mason 
1774e02119d5SChris Mason 	iput(inode);
1775e02119d5SChris Mason 	iput(dir);
1776e02119d5SChris Mason 	return ret;
1777e02119d5SChris Mason }
1778e02119d5SChris Mason 
1779339d0354SFilipe Manana static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
1780339d0354SFilipe Manana 					struct btrfs_inode *dir,
1781339d0354SFilipe Manana 					struct btrfs_path *path,
1782339d0354SFilipe Manana 					struct btrfs_dir_item *dst_di,
1783339d0354SFilipe Manana 					const struct btrfs_key *log_key,
178494a48aefSOmar Sandoval 					u8 log_flags,
1785339d0354SFilipe Manana 					bool exists)
1786339d0354SFilipe Manana {
1787339d0354SFilipe Manana 	struct btrfs_key found_key;
1788339d0354SFilipe Manana 
1789339d0354SFilipe Manana 	btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1790339d0354SFilipe Manana 	/* The existing dentry points to the same inode, don't delete it. */
1791339d0354SFilipe Manana 	if (found_key.objectid == log_key->objectid &&
1792339d0354SFilipe Manana 	    found_key.type == log_key->type &&
1793339d0354SFilipe Manana 	    found_key.offset == log_key->offset &&
179494a48aefSOmar Sandoval 	    btrfs_dir_flags(path->nodes[0], dst_di) == log_flags)
1795339d0354SFilipe Manana 		return 1;
1796339d0354SFilipe Manana 
1797339d0354SFilipe Manana 	/*
1798339d0354SFilipe Manana 	 * Don't drop the conflicting directory entry if the inode for the new
1799339d0354SFilipe Manana 	 * entry doesn't exist.
1800339d0354SFilipe Manana 	 */
1801339d0354SFilipe Manana 	if (!exists)
1802339d0354SFilipe Manana 		return 0;
1803339d0354SFilipe Manana 
1804339d0354SFilipe Manana 	return drop_one_dir_item(trans, path, dir, dst_di);
1805339d0354SFilipe Manana }
1806339d0354SFilipe Manana 
1807e02119d5SChris Mason /*
1808e02119d5SChris Mason  * take a single entry in a log directory item and replay it into
1809e02119d5SChris Mason  * the subvolume.
1810e02119d5SChris Mason  *
1811e02119d5SChris Mason  * if a conflicting item exists in the subdirectory already,
1812e02119d5SChris Mason  * the inode it points to is unlinked and put into the link count
1813e02119d5SChris Mason  * fix up tree.
1814e02119d5SChris Mason  *
1815e02119d5SChris Mason  * If a name from the log points to a file or directory that does
1816e02119d5SChris Mason  * not exist in the FS, it is skipped.  fsyncs on directories
1817e02119d5SChris Mason  * do not force down inodes inside that directory, just changes to the
1818e02119d5SChris Mason  * names or unlinks in a directory.
1819bb53eda9SFilipe Manana  *
1820bb53eda9SFilipe Manana  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1821bb53eda9SFilipe Manana  * non-existing inode) and 1 if the name was replayed.
1822e02119d5SChris Mason  */
1823e02119d5SChris Mason static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1824e02119d5SChris Mason 				    struct btrfs_root *root,
1825e02119d5SChris Mason 				    struct btrfs_path *path,
1826e02119d5SChris Mason 				    struct extent_buffer *eb,
1827e02119d5SChris Mason 				    struct btrfs_dir_item *di,
1828e02119d5SChris Mason 				    struct btrfs_key *key)
1829e02119d5SChris Mason {
18306db75318SSweet Tea Dorminy 	struct fscrypt_str name;
1831339d0354SFilipe Manana 	struct btrfs_dir_item *dir_dst_di;
1832339d0354SFilipe Manana 	struct btrfs_dir_item *index_dst_di;
1833339d0354SFilipe Manana 	bool dir_dst_matches = false;
1834339d0354SFilipe Manana 	bool index_dst_matches = false;
1835e02119d5SChris Mason 	struct btrfs_key log_key;
1836339d0354SFilipe Manana 	struct btrfs_key search_key;
1837e02119d5SChris Mason 	struct inode *dir;
183894a48aefSOmar Sandoval 	u8 log_flags;
1839cfd31269SFilipe Manana 	bool exists;
1840cfd31269SFilipe Manana 	int ret;
1841339d0354SFilipe Manana 	bool update_size = true;
1842bb53eda9SFilipe Manana 	bool name_added = false;
1843e02119d5SChris Mason 
1844e02119d5SChris Mason 	dir = read_one_inode(root, key->objectid);
1845c00e9493STsutomu Itoh 	if (!dir)
1846c00e9493STsutomu Itoh 		return -EIO;
1847e02119d5SChris Mason 
1848e43eec81SSweet Tea Dorminy 	ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
1849e43eec81SSweet Tea Dorminy 	if (ret)
18502bac325eSFilipe David Borba Manana 		goto out;
18512a29edc6Sliubo 
185294a48aefSOmar Sandoval 	log_flags = btrfs_dir_flags(eb, di);
1853e02119d5SChris Mason 	btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1854cfd31269SFilipe Manana 	ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1855b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1856cfd31269SFilipe Manana 	if (ret < 0)
1857cfd31269SFilipe Manana 		goto out;
1858cfd31269SFilipe Manana 	exists = (ret == 0);
1859cfd31269SFilipe Manana 	ret = 0;
18604bef0848SChris Mason 
1861339d0354SFilipe Manana 	dir_dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1862e43eec81SSweet Tea Dorminy 					   &name, 1);
1863339d0354SFilipe Manana 	if (IS_ERR(dir_dst_di)) {
1864339d0354SFilipe Manana 		ret = PTR_ERR(dir_dst_di);
18653650860bSJosef Bacik 		goto out;
1866339d0354SFilipe Manana 	} else if (dir_dst_di) {
1867339d0354SFilipe Manana 		ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
186894a48aefSOmar Sandoval 						   dir_dst_di, &log_key,
186994a48aefSOmar Sandoval 						   log_flags, exists);
1870339d0354SFilipe Manana 		if (ret < 0)
1871339d0354SFilipe Manana 			goto out;
1872339d0354SFilipe Manana 		dir_dst_matches = (ret == 1);
1873e02119d5SChris Mason 	}
1874e15ac641SFilipe Manana 
1875339d0354SFilipe Manana 	btrfs_release_path(path);
1876339d0354SFilipe Manana 
1877339d0354SFilipe Manana 	index_dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1878339d0354SFilipe Manana 						   key->objectid, key->offset,
1879e43eec81SSweet Tea Dorminy 						   &name, 1);
1880339d0354SFilipe Manana 	if (IS_ERR(index_dst_di)) {
1881339d0354SFilipe Manana 		ret = PTR_ERR(index_dst_di);
1882e15ac641SFilipe Manana 		goto out;
1883339d0354SFilipe Manana 	} else if (index_dst_di) {
1884339d0354SFilipe Manana 		ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
1885339d0354SFilipe Manana 						   index_dst_di, &log_key,
188694a48aefSOmar Sandoval 						   log_flags, exists);
1887339d0354SFilipe Manana 		if (ret < 0)
1888e02119d5SChris Mason 			goto out;
1889339d0354SFilipe Manana 		index_dst_matches = (ret == 1);
1890e02119d5SChris Mason 	}
1891e02119d5SChris Mason 
1892339d0354SFilipe Manana 	btrfs_release_path(path);
1893339d0354SFilipe Manana 
1894339d0354SFilipe Manana 	if (dir_dst_matches && index_dst_matches) {
1895339d0354SFilipe Manana 		ret = 0;
1896a2cc11dbSFilipe Manana 		update_size = false;
1897e02119d5SChris Mason 		goto out;
1898e02119d5SChris Mason 	}
1899e02119d5SChris Mason 
1900e02119d5SChris Mason 	/*
1901725af92aSNikolay Borisov 	 * Check if the inode reference exists in the log for the given name,
1902725af92aSNikolay Borisov 	 * inode and parent inode
1903725af92aSNikolay Borisov 	 */
1904339d0354SFilipe Manana 	search_key.objectid = log_key.objectid;
1905339d0354SFilipe Manana 	search_key.type = BTRFS_INODE_REF_KEY;
1906339d0354SFilipe Manana 	search_key.offset = key->objectid;
1907e43eec81SSweet Tea Dorminy 	ret = backref_in_log(root->log_root, &search_key, 0, &name);
1908725af92aSNikolay Borisov 	if (ret < 0) {
1909725af92aSNikolay Borisov 	        goto out;
1910725af92aSNikolay Borisov 	} else if (ret) {
1911725af92aSNikolay Borisov 	        /* The dentry will be added later. */
1912725af92aSNikolay Borisov 	        ret = 0;
1913725af92aSNikolay Borisov 	        update_size = false;
1914725af92aSNikolay Borisov 	        goto out;
1915725af92aSNikolay Borisov 	}
1916725af92aSNikolay Borisov 
1917339d0354SFilipe Manana 	search_key.objectid = log_key.objectid;
1918339d0354SFilipe Manana 	search_key.type = BTRFS_INODE_EXTREF_KEY;
1919339d0354SFilipe Manana 	search_key.offset = key->objectid;
1920e43eec81SSweet Tea Dorminy 	ret = backref_in_log(root->log_root, &search_key, key->objectid, &name);
1921725af92aSNikolay Borisov 	if (ret < 0) {
1922725af92aSNikolay Borisov 		goto out;
1923725af92aSNikolay Borisov 	} else if (ret) {
1924df8d116fSFilipe Manana 		/* The dentry will be added later. */
1925df8d116fSFilipe Manana 		ret = 0;
1926df8d116fSFilipe Manana 		update_size = false;
1927df8d116fSFilipe Manana 		goto out;
1928df8d116fSFilipe Manana 	}
1929b3b4aa74SDavid Sterba 	btrfs_release_path(path);
193060d53eb3SZhaolei 	ret = insert_one_name(trans, root, key->objectid, key->offset,
1931e43eec81SSweet Tea Dorminy 			      &name, &log_key);
1932df8d116fSFilipe Manana 	if (ret && ret != -ENOENT && ret != -EEXIST)
19333650860bSJosef Bacik 		goto out;
1934bb53eda9SFilipe Manana 	if (!ret)
1935bb53eda9SFilipe Manana 		name_added = true;
1936d555438bSJosef Bacik 	update_size = false;
19373650860bSJosef Bacik 	ret = 0;
1938339d0354SFilipe Manana 
1939339d0354SFilipe Manana out:
1940339d0354SFilipe Manana 	if (!ret && update_size) {
1941e43eec81SSweet Tea Dorminy 		btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name.len * 2);
1942339d0354SFilipe Manana 		ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
1943339d0354SFilipe Manana 	}
1944e43eec81SSweet Tea Dorminy 	kfree(name.name);
1945339d0354SFilipe Manana 	iput(dir);
1946339d0354SFilipe Manana 	if (!ret && name_added)
1947339d0354SFilipe Manana 		ret = 1;
1948339d0354SFilipe Manana 	return ret;
1949e02119d5SChris Mason }
1950e02119d5SChris Mason 
1951339d0354SFilipe Manana /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
1952e02119d5SChris Mason static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1953e02119d5SChris Mason 					struct btrfs_root *root,
1954e02119d5SChris Mason 					struct btrfs_path *path,
1955e02119d5SChris Mason 					struct extent_buffer *eb, int slot,
1956e02119d5SChris Mason 					struct btrfs_key *key)
1957e02119d5SChris Mason {
1958339d0354SFilipe Manana 	int ret;
1959e02119d5SChris Mason 	struct btrfs_dir_item *di;
1960e02119d5SChris Mason 
1961339d0354SFilipe Manana 	/* We only log dir index keys, which only contain a single dir item. */
1962339d0354SFilipe Manana 	ASSERT(key->type == BTRFS_DIR_INDEX_KEY);
1963339d0354SFilipe Manana 
1964339d0354SFilipe Manana 	di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
1965e02119d5SChris Mason 	ret = replay_one_name(trans, root, path, eb, di, key);
1966bb53eda9SFilipe Manana 	if (ret < 0)
1967339d0354SFilipe Manana 		return ret;
1968bb53eda9SFilipe Manana 
1969bb53eda9SFilipe Manana 	/*
1970339d0354SFilipe Manana 	 * If this entry refers to a non-directory (directories can not have a
1971339d0354SFilipe Manana 	 * link count > 1) and it was added in the transaction that was not
1972339d0354SFilipe Manana 	 * committed, make sure we fixup the link count of the inode the entry
1973339d0354SFilipe Manana 	 * points to. Otherwise something like the following would result in a
1974339d0354SFilipe Manana 	 * directory pointing to an inode with a wrong link that does not account
1975339d0354SFilipe Manana 	 * for this dir entry:
1976bb53eda9SFilipe Manana 	 *
1977bb53eda9SFilipe Manana 	 * mkdir testdir
1978bb53eda9SFilipe Manana 	 * touch testdir/foo
1979bb53eda9SFilipe Manana 	 * touch testdir/bar
1980bb53eda9SFilipe Manana 	 * sync
1981bb53eda9SFilipe Manana 	 *
1982bb53eda9SFilipe Manana 	 * ln testdir/bar testdir/bar_link
1983bb53eda9SFilipe Manana 	 * ln testdir/foo testdir/foo_link
1984bb53eda9SFilipe Manana 	 * xfs_io -c "fsync" testdir/bar
1985bb53eda9SFilipe Manana 	 *
1986bb53eda9SFilipe Manana 	 * <power failure>
1987bb53eda9SFilipe Manana 	 *
1988bb53eda9SFilipe Manana 	 * mount fs, log replay happens
1989bb53eda9SFilipe Manana 	 *
1990339d0354SFilipe Manana 	 * File foo would remain with a link count of 1 when it has two entries
1991339d0354SFilipe Manana 	 * pointing to it in the directory testdir. This would make it impossible
1992339d0354SFilipe Manana 	 * to ever delete the parent directory has it would result in stale
1993339d0354SFilipe Manana 	 * dentries that can never be deleted.
1994bb53eda9SFilipe Manana 	 */
199594a48aefSOmar Sandoval 	if (ret == 1 && btrfs_dir_ftype(eb, di) != BTRFS_FT_DIR) {
1996339d0354SFilipe Manana 		struct btrfs_path *fixup_path;
1997bb53eda9SFilipe Manana 		struct btrfs_key di_key;
1998bb53eda9SFilipe Manana 
1999bb53eda9SFilipe Manana 		fixup_path = btrfs_alloc_path();
2000339d0354SFilipe Manana 		if (!fixup_path)
2001339d0354SFilipe Manana 			return -ENOMEM;
2002bb53eda9SFilipe Manana 
2003bb53eda9SFilipe Manana 		btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2004339d0354SFilipe Manana 		ret = link_to_fixup_dir(trans, root, fixup_path, di_key.objectid);
2005bb53eda9SFilipe Manana 		btrfs_free_path(fixup_path);
2006339d0354SFilipe Manana 	}
2007339d0354SFilipe Manana 
2008bb53eda9SFilipe Manana 	return ret;
2009e02119d5SChris Mason }
2010e02119d5SChris Mason 
2011e02119d5SChris Mason /*
2012e02119d5SChris Mason  * directory replay has two parts.  There are the standard directory
2013e02119d5SChris Mason  * items in the log copied from the subvolume, and range items
2014e02119d5SChris Mason  * created in the log while the subvolume was logged.
2015e02119d5SChris Mason  *
2016e02119d5SChris Mason  * The range items tell us which parts of the key space the log
2017e02119d5SChris Mason  * is authoritative for.  During replay, if a key in the subvolume
2018e02119d5SChris Mason  * directory is in a logged range item, but not actually in the log
2019e02119d5SChris Mason  * that means it was deleted from the directory before the fsync
2020e02119d5SChris Mason  * and should be removed.
2021e02119d5SChris Mason  */
2022e02119d5SChris Mason static noinline int find_dir_range(struct btrfs_root *root,
2023e02119d5SChris Mason 				   struct btrfs_path *path,
2024ccae4a19SFilipe Manana 				   u64 dirid,
2025e02119d5SChris Mason 				   u64 *start_ret, u64 *end_ret)
2026e02119d5SChris Mason {
2027e02119d5SChris Mason 	struct btrfs_key key;
2028e02119d5SChris Mason 	u64 found_end;
2029e02119d5SChris Mason 	struct btrfs_dir_log_item *item;
2030e02119d5SChris Mason 	int ret;
2031e02119d5SChris Mason 	int nritems;
2032e02119d5SChris Mason 
2033e02119d5SChris Mason 	if (*start_ret == (u64)-1)
2034e02119d5SChris Mason 		return 1;
2035e02119d5SChris Mason 
2036e02119d5SChris Mason 	key.objectid = dirid;
2037ccae4a19SFilipe Manana 	key.type = BTRFS_DIR_LOG_INDEX_KEY;
2038e02119d5SChris Mason 	key.offset = *start_ret;
2039e02119d5SChris Mason 
2040e02119d5SChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2041e02119d5SChris Mason 	if (ret < 0)
2042e02119d5SChris Mason 		goto out;
2043e02119d5SChris Mason 	if (ret > 0) {
2044e02119d5SChris Mason 		if (path->slots[0] == 0)
2045e02119d5SChris Mason 			goto out;
2046e02119d5SChris Mason 		path->slots[0]--;
2047e02119d5SChris Mason 	}
2048e02119d5SChris Mason 	if (ret != 0)
2049e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2050e02119d5SChris Mason 
2051ccae4a19SFilipe Manana 	if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2052e02119d5SChris Mason 		ret = 1;
2053e02119d5SChris Mason 		goto next;
2054e02119d5SChris Mason 	}
2055e02119d5SChris Mason 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2056e02119d5SChris Mason 			      struct btrfs_dir_log_item);
2057e02119d5SChris Mason 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2058e02119d5SChris Mason 
2059e02119d5SChris Mason 	if (*start_ret >= key.offset && *start_ret <= found_end) {
2060e02119d5SChris Mason 		ret = 0;
2061e02119d5SChris Mason 		*start_ret = key.offset;
2062e02119d5SChris Mason 		*end_ret = found_end;
2063e02119d5SChris Mason 		goto out;
2064e02119d5SChris Mason 	}
2065e02119d5SChris Mason 	ret = 1;
2066e02119d5SChris Mason next:
2067e02119d5SChris Mason 	/* check the next slot in the tree to see if it is a valid item */
2068e02119d5SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
20692a7bf53fSRobbie Ko 	path->slots[0]++;
2070e02119d5SChris Mason 	if (path->slots[0] >= nritems) {
2071e02119d5SChris Mason 		ret = btrfs_next_leaf(root, path);
2072e02119d5SChris Mason 		if (ret)
2073e02119d5SChris Mason 			goto out;
2074e02119d5SChris Mason 	}
2075e02119d5SChris Mason 
2076e02119d5SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2077e02119d5SChris Mason 
2078ccae4a19SFilipe Manana 	if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2079e02119d5SChris Mason 		ret = 1;
2080e02119d5SChris Mason 		goto out;
2081e02119d5SChris Mason 	}
2082e02119d5SChris Mason 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2083e02119d5SChris Mason 			      struct btrfs_dir_log_item);
2084e02119d5SChris Mason 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2085e02119d5SChris Mason 	*start_ret = key.offset;
2086e02119d5SChris Mason 	*end_ret = found_end;
2087e02119d5SChris Mason 	ret = 0;
2088e02119d5SChris Mason out:
2089b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2090e02119d5SChris Mason 	return ret;
2091e02119d5SChris Mason }
2092e02119d5SChris Mason 
2093e02119d5SChris Mason /*
2094e02119d5SChris Mason  * this looks for a given directory item in the log.  If the directory
2095e02119d5SChris Mason  * item is not in the log, the item is removed and the inode it points
2096e02119d5SChris Mason  * to is unlinked
2097e02119d5SChris Mason  */
2098e02119d5SChris Mason static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2099e02119d5SChris Mason 				      struct btrfs_root *log,
2100e02119d5SChris Mason 				      struct btrfs_path *path,
2101e02119d5SChris Mason 				      struct btrfs_path *log_path,
2102e02119d5SChris Mason 				      struct inode *dir,
2103e02119d5SChris Mason 				      struct btrfs_key *dir_key)
2104e02119d5SChris Mason {
2105d1ed82f3SFilipe Manana 	struct btrfs_root *root = BTRFS_I(dir)->root;
2106e02119d5SChris Mason 	int ret;
2107e02119d5SChris Mason 	struct extent_buffer *eb;
2108e02119d5SChris Mason 	int slot;
2109e02119d5SChris Mason 	struct btrfs_dir_item *di;
21106db75318SSweet Tea Dorminy 	struct fscrypt_str name;
2111ccae4a19SFilipe Manana 	struct inode *inode = NULL;
2112e02119d5SChris Mason 	struct btrfs_key location;
2113e02119d5SChris Mason 
2114ccae4a19SFilipe Manana 	/*
2115143823cfSDavid Sterba 	 * Currently we only log dir index keys. Even if we replay a log created
2116ccae4a19SFilipe Manana 	 * by an older kernel that logged both dir index and dir item keys, all
2117ccae4a19SFilipe Manana 	 * we need to do is process the dir index keys, we (and our caller) can
2118ccae4a19SFilipe Manana 	 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2119ccae4a19SFilipe Manana 	 */
2120ccae4a19SFilipe Manana 	ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY);
2121ccae4a19SFilipe Manana 
2122e02119d5SChris Mason 	eb = path->nodes[0];
2123e02119d5SChris Mason 	slot = path->slots[0];
2124ccae4a19SFilipe Manana 	di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2125e43eec81SSweet Tea Dorminy 	ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
2126e43eec81SSweet Tea Dorminy 	if (ret)
2127e02119d5SChris Mason 		goto out;
2128ccae4a19SFilipe Manana 
2129ccae4a19SFilipe Manana 	if (log) {
2130ccae4a19SFilipe Manana 		struct btrfs_dir_item *log_di;
2131ccae4a19SFilipe Manana 
2132ccae4a19SFilipe Manana 		log_di = btrfs_lookup_dir_index_item(trans, log, log_path,
2133e02119d5SChris Mason 						     dir_key->objectid,
2134e43eec81SSweet Tea Dorminy 						     dir_key->offset, &name, 0);
2135ccae4a19SFilipe Manana 		if (IS_ERR(log_di)) {
2136ccae4a19SFilipe Manana 			ret = PTR_ERR(log_di);
2137ccae4a19SFilipe Manana 			goto out;
2138ccae4a19SFilipe Manana 		} else if (log_di) {
2139ccae4a19SFilipe Manana 			/* The dentry exists in the log, we have nothing to do. */
2140ccae4a19SFilipe Manana 			ret = 0;
2141ccae4a19SFilipe Manana 			goto out;
2142e02119d5SChris Mason 		}
2143ccae4a19SFilipe Manana 	}
2144ccae4a19SFilipe Manana 
2145e02119d5SChris Mason 	btrfs_dir_item_key_to_cpu(eb, di, &location);
2146b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2147b3b4aa74SDavid Sterba 	btrfs_release_path(log_path);
2148e02119d5SChris Mason 	inode = read_one_inode(root, location.objectid);
2149c00e9493STsutomu Itoh 	if (!inode) {
2150ccae4a19SFilipe Manana 		ret = -EIO;
21513650860bSJosef Bacik 		goto out;
21523650860bSJosef Bacik 	}
21533650860bSJosef Bacik 
2154ccae4a19SFilipe Manana 	ret = link_to_fixup_dir(trans, root, path, location.objectid);
21553650860bSJosef Bacik 	if (ret)
21563650860bSJosef Bacik 		goto out;
2157e02119d5SChris Mason 
2158ccae4a19SFilipe Manana 	inc_nlink(inode);
2159313ab753SFilipe Manana 	ret = unlink_inode_for_log_replay(trans, BTRFS_I(dir), BTRFS_I(inode),
2160e43eec81SSweet Tea Dorminy 					  &name);
2161ccae4a19SFilipe Manana 	/*
2162ccae4a19SFilipe Manana 	 * Unlike dir item keys, dir index keys can only have one name (entry) in
2163ccae4a19SFilipe Manana 	 * them, as there are no key collisions since each key has a unique offset
2164ccae4a19SFilipe Manana 	 * (an index number), so we're done.
2165ccae4a19SFilipe Manana 	 */
2166e02119d5SChris Mason out:
2167b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2168b3b4aa74SDavid Sterba 	btrfs_release_path(log_path);
2169e43eec81SSweet Tea Dorminy 	kfree(name.name);
2170ccae4a19SFilipe Manana 	iput(inode);
2171e02119d5SChris Mason 	return ret;
2172e02119d5SChris Mason }
2173e02119d5SChris Mason 
21744f764e51SFilipe Manana static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
21754f764e51SFilipe Manana 			      struct btrfs_root *root,
21764f764e51SFilipe Manana 			      struct btrfs_root *log,
21774f764e51SFilipe Manana 			      struct btrfs_path *path,
21784f764e51SFilipe Manana 			      const u64 ino)
21794f764e51SFilipe Manana {
21804f764e51SFilipe Manana 	struct btrfs_key search_key;
21814f764e51SFilipe Manana 	struct btrfs_path *log_path;
21824f764e51SFilipe Manana 	int i;
21834f764e51SFilipe Manana 	int nritems;
21844f764e51SFilipe Manana 	int ret;
21854f764e51SFilipe Manana 
21864f764e51SFilipe Manana 	log_path = btrfs_alloc_path();
21874f764e51SFilipe Manana 	if (!log_path)
21884f764e51SFilipe Manana 		return -ENOMEM;
21894f764e51SFilipe Manana 
21904f764e51SFilipe Manana 	search_key.objectid = ino;
21914f764e51SFilipe Manana 	search_key.type = BTRFS_XATTR_ITEM_KEY;
21924f764e51SFilipe Manana 	search_key.offset = 0;
21934f764e51SFilipe Manana again:
21944f764e51SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
21954f764e51SFilipe Manana 	if (ret < 0)
21964f764e51SFilipe Manana 		goto out;
21974f764e51SFilipe Manana process_leaf:
21984f764e51SFilipe Manana 	nritems = btrfs_header_nritems(path->nodes[0]);
21994f764e51SFilipe Manana 	for (i = path->slots[0]; i < nritems; i++) {
22004f764e51SFilipe Manana 		struct btrfs_key key;
22014f764e51SFilipe Manana 		struct btrfs_dir_item *di;
22024f764e51SFilipe Manana 		struct btrfs_dir_item *log_di;
22034f764e51SFilipe Manana 		u32 total_size;
22044f764e51SFilipe Manana 		u32 cur;
22054f764e51SFilipe Manana 
22064f764e51SFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, i);
22074f764e51SFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
22084f764e51SFilipe Manana 			ret = 0;
22094f764e51SFilipe Manana 			goto out;
22104f764e51SFilipe Manana 		}
22114f764e51SFilipe Manana 
22124f764e51SFilipe Manana 		di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
22133212fa14SJosef Bacik 		total_size = btrfs_item_size(path->nodes[0], i);
22144f764e51SFilipe Manana 		cur = 0;
22154f764e51SFilipe Manana 		while (cur < total_size) {
22164f764e51SFilipe Manana 			u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
22174f764e51SFilipe Manana 			u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
22184f764e51SFilipe Manana 			u32 this_len = sizeof(*di) + name_len + data_len;
22194f764e51SFilipe Manana 			char *name;
22204f764e51SFilipe Manana 
22214f764e51SFilipe Manana 			name = kmalloc(name_len, GFP_NOFS);
22224f764e51SFilipe Manana 			if (!name) {
22234f764e51SFilipe Manana 				ret = -ENOMEM;
22244f764e51SFilipe Manana 				goto out;
22254f764e51SFilipe Manana 			}
22264f764e51SFilipe Manana 			read_extent_buffer(path->nodes[0], name,
22274f764e51SFilipe Manana 					   (unsigned long)(di + 1), name_len);
22284f764e51SFilipe Manana 
22294f764e51SFilipe Manana 			log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
22304f764e51SFilipe Manana 						    name, name_len, 0);
22314f764e51SFilipe Manana 			btrfs_release_path(log_path);
22324f764e51SFilipe Manana 			if (!log_di) {
22334f764e51SFilipe Manana 				/* Doesn't exist in log tree, so delete it. */
22344f764e51SFilipe Manana 				btrfs_release_path(path);
22354f764e51SFilipe Manana 				di = btrfs_lookup_xattr(trans, root, path, ino,
22364f764e51SFilipe Manana 							name, name_len, -1);
22374f764e51SFilipe Manana 				kfree(name);
22384f764e51SFilipe Manana 				if (IS_ERR(di)) {
22394f764e51SFilipe Manana 					ret = PTR_ERR(di);
22404f764e51SFilipe Manana 					goto out;
22414f764e51SFilipe Manana 				}
22424f764e51SFilipe Manana 				ASSERT(di);
22434f764e51SFilipe Manana 				ret = btrfs_delete_one_dir_name(trans, root,
22444f764e51SFilipe Manana 								path, di);
22454f764e51SFilipe Manana 				if (ret)
22464f764e51SFilipe Manana 					goto out;
22474f764e51SFilipe Manana 				btrfs_release_path(path);
22484f764e51SFilipe Manana 				search_key = key;
22494f764e51SFilipe Manana 				goto again;
22504f764e51SFilipe Manana 			}
22514f764e51SFilipe Manana 			kfree(name);
22524f764e51SFilipe Manana 			if (IS_ERR(log_di)) {
22534f764e51SFilipe Manana 				ret = PTR_ERR(log_di);
22544f764e51SFilipe Manana 				goto out;
22554f764e51SFilipe Manana 			}
22564f764e51SFilipe Manana 			cur += this_len;
22574f764e51SFilipe Manana 			di = (struct btrfs_dir_item *)((char *)di + this_len);
22584f764e51SFilipe Manana 		}
22594f764e51SFilipe Manana 	}
22604f764e51SFilipe Manana 	ret = btrfs_next_leaf(root, path);
22614f764e51SFilipe Manana 	if (ret > 0)
22624f764e51SFilipe Manana 		ret = 0;
22634f764e51SFilipe Manana 	else if (ret == 0)
22644f764e51SFilipe Manana 		goto process_leaf;
22654f764e51SFilipe Manana out:
22664f764e51SFilipe Manana 	btrfs_free_path(log_path);
22674f764e51SFilipe Manana 	btrfs_release_path(path);
22684f764e51SFilipe Manana 	return ret;
22694f764e51SFilipe Manana }
22704f764e51SFilipe Manana 
22714f764e51SFilipe Manana 
2272e02119d5SChris Mason /*
2273e02119d5SChris Mason  * deletion replay happens before we copy any new directory items
2274e02119d5SChris Mason  * out of the log or out of backreferences from inodes.  It
2275e02119d5SChris Mason  * scans the log to find ranges of keys that log is authoritative for,
2276e02119d5SChris Mason  * and then scans the directory to find items in those ranges that are
2277e02119d5SChris Mason  * not present in the log.
2278e02119d5SChris Mason  *
2279e02119d5SChris Mason  * Anything we don't find in the log is unlinked and removed from the
2280e02119d5SChris Mason  * directory.
2281e02119d5SChris Mason  */
2282e02119d5SChris Mason static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2283e02119d5SChris Mason 				       struct btrfs_root *root,
2284e02119d5SChris Mason 				       struct btrfs_root *log,
2285e02119d5SChris Mason 				       struct btrfs_path *path,
228612fcfd22SChris Mason 				       u64 dirid, int del_all)
2287e02119d5SChris Mason {
2288e02119d5SChris Mason 	u64 range_start;
2289e02119d5SChris Mason 	u64 range_end;
2290e02119d5SChris Mason 	int ret = 0;
2291e02119d5SChris Mason 	struct btrfs_key dir_key;
2292e02119d5SChris Mason 	struct btrfs_key found_key;
2293e02119d5SChris Mason 	struct btrfs_path *log_path;
2294e02119d5SChris Mason 	struct inode *dir;
2295e02119d5SChris Mason 
2296e02119d5SChris Mason 	dir_key.objectid = dirid;
2297ccae4a19SFilipe Manana 	dir_key.type = BTRFS_DIR_INDEX_KEY;
2298e02119d5SChris Mason 	log_path = btrfs_alloc_path();
2299e02119d5SChris Mason 	if (!log_path)
2300e02119d5SChris Mason 		return -ENOMEM;
2301e02119d5SChris Mason 
2302e02119d5SChris Mason 	dir = read_one_inode(root, dirid);
2303e02119d5SChris Mason 	/* it isn't an error if the inode isn't there, that can happen
2304e02119d5SChris Mason 	 * because we replay the deletes before we copy in the inode item
2305e02119d5SChris Mason 	 * from the log
2306e02119d5SChris Mason 	 */
2307e02119d5SChris Mason 	if (!dir) {
2308e02119d5SChris Mason 		btrfs_free_path(log_path);
2309e02119d5SChris Mason 		return 0;
2310e02119d5SChris Mason 	}
2311ccae4a19SFilipe Manana 
2312e02119d5SChris Mason 	range_start = 0;
2313e02119d5SChris Mason 	range_end = 0;
2314e02119d5SChris Mason 	while (1) {
231512fcfd22SChris Mason 		if (del_all)
231612fcfd22SChris Mason 			range_end = (u64)-1;
231712fcfd22SChris Mason 		else {
2318ccae4a19SFilipe Manana 			ret = find_dir_range(log, path, dirid,
2319e02119d5SChris Mason 					     &range_start, &range_end);
232010adb115SFilipe Manana 			if (ret < 0)
232110adb115SFilipe Manana 				goto out;
232210adb115SFilipe Manana 			else if (ret > 0)
2323e02119d5SChris Mason 				break;
232412fcfd22SChris Mason 		}
2325e02119d5SChris Mason 
2326e02119d5SChris Mason 		dir_key.offset = range_start;
2327e02119d5SChris Mason 		while (1) {
2328e02119d5SChris Mason 			int nritems;
2329e02119d5SChris Mason 			ret = btrfs_search_slot(NULL, root, &dir_key, path,
2330e02119d5SChris Mason 						0, 0);
2331e02119d5SChris Mason 			if (ret < 0)
2332e02119d5SChris Mason 				goto out;
2333e02119d5SChris Mason 
2334e02119d5SChris Mason 			nritems = btrfs_header_nritems(path->nodes[0]);
2335e02119d5SChris Mason 			if (path->slots[0] >= nritems) {
2336e02119d5SChris Mason 				ret = btrfs_next_leaf(root, path);
2337b98def7cSLiu Bo 				if (ret == 1)
2338e02119d5SChris Mason 					break;
2339b98def7cSLiu Bo 				else if (ret < 0)
2340b98def7cSLiu Bo 					goto out;
2341e02119d5SChris Mason 			}
2342e02119d5SChris Mason 			btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2343e02119d5SChris Mason 					      path->slots[0]);
2344e02119d5SChris Mason 			if (found_key.objectid != dirid ||
2345ccae4a19SFilipe Manana 			    found_key.type != dir_key.type) {
2346ccae4a19SFilipe Manana 				ret = 0;
2347ccae4a19SFilipe Manana 				goto out;
2348ccae4a19SFilipe Manana 			}
2349e02119d5SChris Mason 
2350e02119d5SChris Mason 			if (found_key.offset > range_end)
2351e02119d5SChris Mason 				break;
2352e02119d5SChris Mason 
2353d1ed82f3SFilipe Manana 			ret = check_item_in_log(trans, log, path,
235412fcfd22SChris Mason 						log_path, dir,
235512fcfd22SChris Mason 						&found_key);
23563650860bSJosef Bacik 			if (ret)
23573650860bSJosef Bacik 				goto out;
2358e02119d5SChris Mason 			if (found_key.offset == (u64)-1)
2359e02119d5SChris Mason 				break;
2360e02119d5SChris Mason 			dir_key.offset = found_key.offset + 1;
2361e02119d5SChris Mason 		}
2362b3b4aa74SDavid Sterba 		btrfs_release_path(path);
2363e02119d5SChris Mason 		if (range_end == (u64)-1)
2364e02119d5SChris Mason 			break;
2365e02119d5SChris Mason 		range_start = range_end + 1;
2366e02119d5SChris Mason 	}
2367e02119d5SChris Mason 	ret = 0;
2368e02119d5SChris Mason out:
2369b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2370e02119d5SChris Mason 	btrfs_free_path(log_path);
2371e02119d5SChris Mason 	iput(dir);
2372e02119d5SChris Mason 	return ret;
2373e02119d5SChris Mason }
2374e02119d5SChris Mason 
2375e02119d5SChris Mason /*
2376e02119d5SChris Mason  * the process_func used to replay items from the log tree.  This
2377e02119d5SChris Mason  * gets called in two different stages.  The first stage just looks
2378e02119d5SChris Mason  * for inodes and makes sure they are all copied into the subvolume.
2379e02119d5SChris Mason  *
2380e02119d5SChris Mason  * The second stage copies all the other item types from the log into
2381e02119d5SChris Mason  * the subvolume.  The two stage approach is slower, but gets rid of
2382e02119d5SChris Mason  * lots of complexity around inodes referencing other inodes that exist
2383e02119d5SChris Mason  * only in the log (references come from either directory items or inode
2384e02119d5SChris Mason  * back refs).
2385e02119d5SChris Mason  */
2386e02119d5SChris Mason static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2387581c1760SQu Wenruo 			     struct walk_control *wc, u64 gen, int level)
2388e02119d5SChris Mason {
2389e02119d5SChris Mason 	int nritems;
2390789d6a3aSQu Wenruo 	struct btrfs_tree_parent_check check = {
2391789d6a3aSQu Wenruo 		.transid = gen,
2392789d6a3aSQu Wenruo 		.level = level
2393789d6a3aSQu Wenruo 	};
2394e02119d5SChris Mason 	struct btrfs_path *path;
2395e02119d5SChris Mason 	struct btrfs_root *root = wc->replay_dest;
2396e02119d5SChris Mason 	struct btrfs_key key;
2397e02119d5SChris Mason 	int i;
2398e02119d5SChris Mason 	int ret;
2399e02119d5SChris Mason 
2400789d6a3aSQu Wenruo 	ret = btrfs_read_extent_buffer(eb, &check);
2401018642a1STsutomu Itoh 	if (ret)
2402018642a1STsutomu Itoh 		return ret;
2403e02119d5SChris Mason 
2404e02119d5SChris Mason 	level = btrfs_header_level(eb);
2405e02119d5SChris Mason 
2406e02119d5SChris Mason 	if (level != 0)
2407e02119d5SChris Mason 		return 0;
2408e02119d5SChris Mason 
2409e02119d5SChris Mason 	path = btrfs_alloc_path();
24101e5063d0SMark Fasheh 	if (!path)
24111e5063d0SMark Fasheh 		return -ENOMEM;
2412e02119d5SChris Mason 
2413e02119d5SChris Mason 	nritems = btrfs_header_nritems(eb);
2414e02119d5SChris Mason 	for (i = 0; i < nritems; i++) {
2415e02119d5SChris Mason 		btrfs_item_key_to_cpu(eb, &key, i);
2416e02119d5SChris Mason 
2417e02119d5SChris Mason 		/* inode keys are done during the first stage */
2418e02119d5SChris Mason 		if (key.type == BTRFS_INODE_ITEM_KEY &&
2419e02119d5SChris Mason 		    wc->stage == LOG_WALK_REPLAY_INODES) {
2420e02119d5SChris Mason 			struct btrfs_inode_item *inode_item;
2421e02119d5SChris Mason 			u32 mode;
2422e02119d5SChris Mason 
2423e02119d5SChris Mason 			inode_item = btrfs_item_ptr(eb, i,
2424e02119d5SChris Mason 					    struct btrfs_inode_item);
2425f2d72f42SFilipe Manana 			/*
2426f2d72f42SFilipe Manana 			 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2427f2d72f42SFilipe Manana 			 * and never got linked before the fsync, skip it, as
2428f2d72f42SFilipe Manana 			 * replaying it is pointless since it would be deleted
2429f2d72f42SFilipe Manana 			 * later. We skip logging tmpfiles, but it's always
2430f2d72f42SFilipe Manana 			 * possible we are replaying a log created with a kernel
2431f2d72f42SFilipe Manana 			 * that used to log tmpfiles.
2432f2d72f42SFilipe Manana 			 */
2433f2d72f42SFilipe Manana 			if (btrfs_inode_nlink(eb, inode_item) == 0) {
2434f2d72f42SFilipe Manana 				wc->ignore_cur_inode = true;
2435f2d72f42SFilipe Manana 				continue;
2436f2d72f42SFilipe Manana 			} else {
2437f2d72f42SFilipe Manana 				wc->ignore_cur_inode = false;
2438f2d72f42SFilipe Manana 			}
24394f764e51SFilipe Manana 			ret = replay_xattr_deletes(wc->trans, root, log,
24404f764e51SFilipe Manana 						   path, key.objectid);
24414f764e51SFilipe Manana 			if (ret)
24424f764e51SFilipe Manana 				break;
2443e02119d5SChris Mason 			mode = btrfs_inode_mode(eb, inode_item);
2444e02119d5SChris Mason 			if (S_ISDIR(mode)) {
2445e02119d5SChris Mason 				ret = replay_dir_deletes(wc->trans,
244612fcfd22SChris Mason 					 root, log, path, key.objectid, 0);
2447b50c6e25SJosef Bacik 				if (ret)
2448b50c6e25SJosef Bacik 					break;
2449e02119d5SChris Mason 			}
2450e02119d5SChris Mason 			ret = overwrite_item(wc->trans, root, path,
2451e02119d5SChris Mason 					     eb, i, &key);
2452b50c6e25SJosef Bacik 			if (ret)
2453b50c6e25SJosef Bacik 				break;
2454e02119d5SChris Mason 
2455471d557aSFilipe Manana 			/*
2456471d557aSFilipe Manana 			 * Before replaying extents, truncate the inode to its
2457471d557aSFilipe Manana 			 * size. We need to do it now and not after log replay
2458471d557aSFilipe Manana 			 * because before an fsync we can have prealloc extents
2459471d557aSFilipe Manana 			 * added beyond the inode's i_size. If we did it after,
2460471d557aSFilipe Manana 			 * through orphan cleanup for example, we would drop
2461471d557aSFilipe Manana 			 * those prealloc extents just after replaying them.
2462e02119d5SChris Mason 			 */
2463e02119d5SChris Mason 			if (S_ISREG(mode)) {
24645893dfb9SFilipe Manana 				struct btrfs_drop_extents_args drop_args = { 0 };
2465471d557aSFilipe Manana 				struct inode *inode;
2466471d557aSFilipe Manana 				u64 from;
2467471d557aSFilipe Manana 
2468471d557aSFilipe Manana 				inode = read_one_inode(root, key.objectid);
2469471d557aSFilipe Manana 				if (!inode) {
2470471d557aSFilipe Manana 					ret = -EIO;
2471471d557aSFilipe Manana 					break;
2472471d557aSFilipe Manana 				}
2473471d557aSFilipe Manana 				from = ALIGN(i_size_read(inode),
2474471d557aSFilipe Manana 					     root->fs_info->sectorsize);
24755893dfb9SFilipe Manana 				drop_args.start = from;
24765893dfb9SFilipe Manana 				drop_args.end = (u64)-1;
24775893dfb9SFilipe Manana 				drop_args.drop_cache = true;
24785893dfb9SFilipe Manana 				ret = btrfs_drop_extents(wc->trans, root,
24795893dfb9SFilipe Manana 							 BTRFS_I(inode),
24805893dfb9SFilipe Manana 							 &drop_args);
2481471d557aSFilipe Manana 				if (!ret) {
24822766ff61SFilipe Manana 					inode_sub_bytes(inode,
24832766ff61SFilipe Manana 							drop_args.bytes_found);
2484f2d72f42SFilipe Manana 					/* Update the inode's nbytes. */
2485471d557aSFilipe Manana 					ret = btrfs_update_inode(wc->trans,
24869a56fcd1SNikolay Borisov 							root, BTRFS_I(inode));
2487471d557aSFilipe Manana 				}
2488471d557aSFilipe Manana 				iput(inode);
2489b50c6e25SJosef Bacik 				if (ret)
2490b50c6e25SJosef Bacik 					break;
2491c71bf099SYan, Zheng 			}
2492a74ac322SChris Mason 
2493e02119d5SChris Mason 			ret = link_to_fixup_dir(wc->trans, root,
2494e02119d5SChris Mason 						path, key.objectid);
2495b50c6e25SJosef Bacik 			if (ret)
2496b50c6e25SJosef Bacik 				break;
2497e02119d5SChris Mason 		}
2498dd8e7217SJosef Bacik 
2499f2d72f42SFilipe Manana 		if (wc->ignore_cur_inode)
2500f2d72f42SFilipe Manana 			continue;
2501f2d72f42SFilipe Manana 
2502dd8e7217SJosef Bacik 		if (key.type == BTRFS_DIR_INDEX_KEY &&
2503dd8e7217SJosef Bacik 		    wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2504dd8e7217SJosef Bacik 			ret = replay_one_dir_item(wc->trans, root, path,
2505dd8e7217SJosef Bacik 						  eb, i, &key);
2506dd8e7217SJosef Bacik 			if (ret)
2507dd8e7217SJosef Bacik 				break;
2508dd8e7217SJosef Bacik 		}
2509dd8e7217SJosef Bacik 
2510e02119d5SChris Mason 		if (wc->stage < LOG_WALK_REPLAY_ALL)
2511e02119d5SChris Mason 			continue;
2512e02119d5SChris Mason 
2513e02119d5SChris Mason 		/* these keys are simply copied */
2514e02119d5SChris Mason 		if (key.type == BTRFS_XATTR_ITEM_KEY) {
2515e02119d5SChris Mason 			ret = overwrite_item(wc->trans, root, path,
2516e02119d5SChris Mason 					     eb, i, &key);
2517b50c6e25SJosef Bacik 			if (ret)
2518b50c6e25SJosef Bacik 				break;
25192da1c669SLiu Bo 		} else if (key.type == BTRFS_INODE_REF_KEY ||
25202da1c669SLiu Bo 			   key.type == BTRFS_INODE_EXTREF_KEY) {
2521f186373fSMark Fasheh 			ret = add_inode_ref(wc->trans, root, log, path,
2522f186373fSMark Fasheh 					    eb, i, &key);
2523b50c6e25SJosef Bacik 			if (ret && ret != -ENOENT)
2524b50c6e25SJosef Bacik 				break;
2525b50c6e25SJosef Bacik 			ret = 0;
2526e02119d5SChris Mason 		} else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2527e02119d5SChris Mason 			ret = replay_one_extent(wc->trans, root, path,
2528e02119d5SChris Mason 						eb, i, &key);
2529b50c6e25SJosef Bacik 			if (ret)
2530b50c6e25SJosef Bacik 				break;
2531e02119d5SChris Mason 		}
2532339d0354SFilipe Manana 		/*
2533339d0354SFilipe Manana 		 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2534339d0354SFilipe Manana 		 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2535339d0354SFilipe Manana 		 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2536339d0354SFilipe Manana 		 * older kernel with such keys, ignore them.
2537339d0354SFilipe Manana 		 */
2538e02119d5SChris Mason 	}
2539e02119d5SChris Mason 	btrfs_free_path(path);
2540b50c6e25SJosef Bacik 	return ret;
2541e02119d5SChris Mason }
2542e02119d5SChris Mason 
25436787bb9fSNikolay Borisov /*
25446787bb9fSNikolay Borisov  * Correctly adjust the reserved bytes occupied by a log tree extent buffer
25456787bb9fSNikolay Borisov  */
25466787bb9fSNikolay Borisov static void unaccount_log_buffer(struct btrfs_fs_info *fs_info, u64 start)
25476787bb9fSNikolay Borisov {
25486787bb9fSNikolay Borisov 	struct btrfs_block_group *cache;
25496787bb9fSNikolay Borisov 
25506787bb9fSNikolay Borisov 	cache = btrfs_lookup_block_group(fs_info, start);
25516787bb9fSNikolay Borisov 	if (!cache) {
25526787bb9fSNikolay Borisov 		btrfs_err(fs_info, "unable to find block group for %llu", start);
25536787bb9fSNikolay Borisov 		return;
25546787bb9fSNikolay Borisov 	}
25556787bb9fSNikolay Borisov 
25566787bb9fSNikolay Borisov 	spin_lock(&cache->space_info->lock);
25576787bb9fSNikolay Borisov 	spin_lock(&cache->lock);
25586787bb9fSNikolay Borisov 	cache->reserved -= fs_info->nodesize;
25596787bb9fSNikolay Borisov 	cache->space_info->bytes_reserved -= fs_info->nodesize;
25606787bb9fSNikolay Borisov 	spin_unlock(&cache->lock);
25616787bb9fSNikolay Borisov 	spin_unlock(&cache->space_info->lock);
25626787bb9fSNikolay Borisov 
25636787bb9fSNikolay Borisov 	btrfs_put_block_group(cache);
25646787bb9fSNikolay Borisov }
25656787bb9fSNikolay Borisov 
2566e6b430f8SChristoph Hellwig static int clean_log_buffer(struct btrfs_trans_handle *trans,
2567e6b430f8SChristoph Hellwig 			    struct extent_buffer *eb)
2568e6b430f8SChristoph Hellwig {
2569e6b430f8SChristoph Hellwig 	int ret;
2570e6b430f8SChristoph Hellwig 
2571e6b430f8SChristoph Hellwig 	btrfs_tree_lock(eb);
2572e6b430f8SChristoph Hellwig 	btrfs_clear_buffer_dirty(trans, eb);
2573e6b430f8SChristoph Hellwig 	wait_on_extent_buffer_writeback(eb);
2574e6b430f8SChristoph Hellwig 	btrfs_tree_unlock(eb);
2575e6b430f8SChristoph Hellwig 
2576e6b430f8SChristoph Hellwig 	if (trans) {
2577e6b430f8SChristoph Hellwig 		ret = btrfs_pin_reserved_extent(trans, eb->start, eb->len);
2578e6b430f8SChristoph Hellwig 		if (ret)
2579e6b430f8SChristoph Hellwig 			return ret;
2580e6b430f8SChristoph Hellwig 		btrfs_redirty_list_add(trans->transaction, eb);
2581e6b430f8SChristoph Hellwig 	} else {
2582e6b430f8SChristoph Hellwig 		unaccount_log_buffer(eb->fs_info, eb->start);
2583e6b430f8SChristoph Hellwig 	}
2584e6b430f8SChristoph Hellwig 
2585e6b430f8SChristoph Hellwig 	return 0;
2586e6b430f8SChristoph Hellwig }
2587e6b430f8SChristoph Hellwig 
2588d397712bSChris Mason static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2589e02119d5SChris Mason 				   struct btrfs_root *root,
2590e02119d5SChris Mason 				   struct btrfs_path *path, int *level,
2591e02119d5SChris Mason 				   struct walk_control *wc)
2592e02119d5SChris Mason {
25930b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2594e02119d5SChris Mason 	u64 bytenr;
2595e02119d5SChris Mason 	u64 ptr_gen;
2596e02119d5SChris Mason 	struct extent_buffer *next;
2597e02119d5SChris Mason 	struct extent_buffer *cur;
2598e02119d5SChris Mason 	int ret = 0;
2599e02119d5SChris Mason 
2600e02119d5SChris Mason 	while (*level > 0) {
2601789d6a3aSQu Wenruo 		struct btrfs_tree_parent_check check = { 0 };
2602581c1760SQu Wenruo 
2603e02119d5SChris Mason 		cur = path->nodes[*level];
2604e02119d5SChris Mason 
2605fae7f21cSDulshani Gunawardhana 		WARN_ON(btrfs_header_level(cur) != *level);
2606e02119d5SChris Mason 
2607e02119d5SChris Mason 		if (path->slots[*level] >=
2608e02119d5SChris Mason 		    btrfs_header_nritems(cur))
2609e02119d5SChris Mason 			break;
2610e02119d5SChris Mason 
2611e02119d5SChris Mason 		bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2612e02119d5SChris Mason 		ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2613789d6a3aSQu Wenruo 		check.transid = ptr_gen;
2614789d6a3aSQu Wenruo 		check.level = *level - 1;
2615789d6a3aSQu Wenruo 		check.has_first_key = true;
2616789d6a3aSQu Wenruo 		btrfs_node_key_to_cpu(cur, &check.first_key, path->slots[*level]);
2617e02119d5SChris Mason 
26183fbaf258SJosef Bacik 		next = btrfs_find_create_tree_block(fs_info, bytenr,
26193fbaf258SJosef Bacik 						    btrfs_header_owner(cur),
26203fbaf258SJosef Bacik 						    *level - 1);
2621c871b0f2SLiu Bo 		if (IS_ERR(next))
2622c871b0f2SLiu Bo 			return PTR_ERR(next);
2623e02119d5SChris Mason 
26244a500fd1SYan, Zheng 		if (*level == 1) {
2625581c1760SQu Wenruo 			ret = wc->process_func(root, next, wc, ptr_gen,
2626581c1760SQu Wenruo 					       *level - 1);
2627b50c6e25SJosef Bacik 			if (ret) {
2628b50c6e25SJosef Bacik 				free_extent_buffer(next);
26291e5063d0SMark Fasheh 				return ret;
2630b50c6e25SJosef Bacik 			}
2631e02119d5SChris Mason 
2632e02119d5SChris Mason 			path->slots[*level]++;
2633e02119d5SChris Mason 			if (wc->free) {
2634789d6a3aSQu Wenruo 				ret = btrfs_read_extent_buffer(next, &check);
2635018642a1STsutomu Itoh 				if (ret) {
2636018642a1STsutomu Itoh 					free_extent_buffer(next);
2637018642a1STsutomu Itoh 					return ret;
2638018642a1STsutomu Itoh 				}
2639e02119d5SChris Mason 
2640e6b430f8SChristoph Hellwig 				ret = clean_log_buffer(trans, next);
26413650860bSJosef Bacik 				if (ret) {
26423650860bSJosef Bacik 					free_extent_buffer(next);
26433650860bSJosef Bacik 					return ret;
26443650860bSJosef Bacik 				}
2645e02119d5SChris Mason 			}
2646e02119d5SChris Mason 			free_extent_buffer(next);
2647e02119d5SChris Mason 			continue;
2648e02119d5SChris Mason 		}
2649789d6a3aSQu Wenruo 		ret = btrfs_read_extent_buffer(next, &check);
2650018642a1STsutomu Itoh 		if (ret) {
2651018642a1STsutomu Itoh 			free_extent_buffer(next);
2652018642a1STsutomu Itoh 			return ret;
2653018642a1STsutomu Itoh 		}
2654e02119d5SChris Mason 
2655e02119d5SChris Mason 		if (path->nodes[*level-1])
2656e02119d5SChris Mason 			free_extent_buffer(path->nodes[*level-1]);
2657e02119d5SChris Mason 		path->nodes[*level-1] = next;
2658e02119d5SChris Mason 		*level = btrfs_header_level(next);
2659e02119d5SChris Mason 		path->slots[*level] = 0;
2660e02119d5SChris Mason 		cond_resched();
2661e02119d5SChris Mason 	}
26624a500fd1SYan, Zheng 	path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2663e02119d5SChris Mason 
2664e02119d5SChris Mason 	cond_resched();
2665e02119d5SChris Mason 	return 0;
2666e02119d5SChris Mason }
2667e02119d5SChris Mason 
2668d397712bSChris Mason static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2669e02119d5SChris Mason 				 struct btrfs_root *root,
2670e02119d5SChris Mason 				 struct btrfs_path *path, int *level,
2671e02119d5SChris Mason 				 struct walk_control *wc)
2672e02119d5SChris Mason {
2673e02119d5SChris Mason 	int i;
2674e02119d5SChris Mason 	int slot;
2675e02119d5SChris Mason 	int ret;
2676e02119d5SChris Mason 
2677e02119d5SChris Mason 	for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2678e02119d5SChris Mason 		slot = path->slots[i];
26794a500fd1SYan, Zheng 		if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2680e02119d5SChris Mason 			path->slots[i]++;
2681e02119d5SChris Mason 			*level = i;
2682e02119d5SChris Mason 			WARN_ON(*level == 0);
2683e02119d5SChris Mason 			return 0;
2684e02119d5SChris Mason 		} else {
26851e5063d0SMark Fasheh 			ret = wc->process_func(root, path->nodes[*level], wc,
2686581c1760SQu Wenruo 				 btrfs_header_generation(path->nodes[*level]),
2687581c1760SQu Wenruo 				 *level);
26881e5063d0SMark Fasheh 			if (ret)
26891e5063d0SMark Fasheh 				return ret;
26901e5063d0SMark Fasheh 
2691e02119d5SChris Mason 			if (wc->free) {
2692e6b430f8SChristoph Hellwig 				ret = clean_log_buffer(trans, path->nodes[*level]);
26933650860bSJosef Bacik 				if (ret)
26943650860bSJosef Bacik 					return ret;
2695e02119d5SChris Mason 			}
2696e02119d5SChris Mason 			free_extent_buffer(path->nodes[*level]);
2697e02119d5SChris Mason 			path->nodes[*level] = NULL;
2698e02119d5SChris Mason 			*level = i + 1;
2699e02119d5SChris Mason 		}
2700e02119d5SChris Mason 	}
2701e02119d5SChris Mason 	return 1;
2702e02119d5SChris Mason }
2703e02119d5SChris Mason 
2704e02119d5SChris Mason /*
2705e02119d5SChris Mason  * drop the reference count on the tree rooted at 'snap'.  This traverses
2706e02119d5SChris Mason  * the tree freeing any blocks that have a ref count of zero after being
2707e02119d5SChris Mason  * decremented.
2708e02119d5SChris Mason  */
2709e02119d5SChris Mason static int walk_log_tree(struct btrfs_trans_handle *trans,
2710e02119d5SChris Mason 			 struct btrfs_root *log, struct walk_control *wc)
2711e02119d5SChris Mason {
2712e02119d5SChris Mason 	int ret = 0;
2713e02119d5SChris Mason 	int wret;
2714e02119d5SChris Mason 	int level;
2715e02119d5SChris Mason 	struct btrfs_path *path;
2716e02119d5SChris Mason 	int orig_level;
2717e02119d5SChris Mason 
2718e02119d5SChris Mason 	path = btrfs_alloc_path();
2719db5b493aSTsutomu Itoh 	if (!path)
2720db5b493aSTsutomu Itoh 		return -ENOMEM;
2721e02119d5SChris Mason 
2722e02119d5SChris Mason 	level = btrfs_header_level(log->node);
2723e02119d5SChris Mason 	orig_level = level;
2724e02119d5SChris Mason 	path->nodes[level] = log->node;
272567439dadSDavid Sterba 	atomic_inc(&log->node->refs);
2726e02119d5SChris Mason 	path->slots[level] = 0;
2727e02119d5SChris Mason 
2728e02119d5SChris Mason 	while (1) {
2729e02119d5SChris Mason 		wret = walk_down_log_tree(trans, log, path, &level, wc);
2730e02119d5SChris Mason 		if (wret > 0)
2731e02119d5SChris Mason 			break;
273279787eaaSJeff Mahoney 		if (wret < 0) {
2733e02119d5SChris Mason 			ret = wret;
273479787eaaSJeff Mahoney 			goto out;
273579787eaaSJeff Mahoney 		}
2736e02119d5SChris Mason 
2737e02119d5SChris Mason 		wret = walk_up_log_tree(trans, log, path, &level, wc);
2738e02119d5SChris Mason 		if (wret > 0)
2739e02119d5SChris Mason 			break;
274079787eaaSJeff Mahoney 		if (wret < 0) {
2741e02119d5SChris Mason 			ret = wret;
274279787eaaSJeff Mahoney 			goto out;
274379787eaaSJeff Mahoney 		}
2744e02119d5SChris Mason 	}
2745e02119d5SChris Mason 
2746e02119d5SChris Mason 	/* was the root node processed? if not, catch it here */
2747e02119d5SChris Mason 	if (path->nodes[orig_level]) {
274879787eaaSJeff Mahoney 		ret = wc->process_func(log, path->nodes[orig_level], wc,
2749581c1760SQu Wenruo 			 btrfs_header_generation(path->nodes[orig_level]),
2750581c1760SQu Wenruo 			 orig_level);
275179787eaaSJeff Mahoney 		if (ret)
275279787eaaSJeff Mahoney 			goto out;
2753e6b430f8SChristoph Hellwig 		if (wc->free)
2754e6b430f8SChristoph Hellwig 			ret = clean_log_buffer(trans, path->nodes[orig_level]);
2755e02119d5SChris Mason 	}
2756e02119d5SChris Mason 
275779787eaaSJeff Mahoney out:
2758e02119d5SChris Mason 	btrfs_free_path(path);
2759e02119d5SChris Mason 	return ret;
2760e02119d5SChris Mason }
2761e02119d5SChris Mason 
27627237f183SYan Zheng /*
27637237f183SYan Zheng  * helper function to update the item for a given subvolumes log root
27647237f183SYan Zheng  * in the tree of log roots
27657237f183SYan Zheng  */
27667237f183SYan Zheng static int update_log_root(struct btrfs_trans_handle *trans,
27674203e968SJosef Bacik 			   struct btrfs_root *log,
27684203e968SJosef Bacik 			   struct btrfs_root_item *root_item)
27697237f183SYan Zheng {
27700b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = log->fs_info;
27717237f183SYan Zheng 	int ret;
27727237f183SYan Zheng 
27737237f183SYan Zheng 	if (log->log_transid == 1) {
27747237f183SYan Zheng 		/* insert root item on the first sync */
27750b246afaSJeff Mahoney 		ret = btrfs_insert_root(trans, fs_info->log_root_tree,
27764203e968SJosef Bacik 				&log->root_key, root_item);
27777237f183SYan Zheng 	} else {
27780b246afaSJeff Mahoney 		ret = btrfs_update_root(trans, fs_info->log_root_tree,
27794203e968SJosef Bacik 				&log->root_key, root_item);
27807237f183SYan Zheng 	}
27817237f183SYan Zheng 	return ret;
27827237f183SYan Zheng }
27837237f183SYan Zheng 
278460d53eb3SZhaolei static void wait_log_commit(struct btrfs_root *root, int transid)
2785e02119d5SChris Mason {
2786e02119d5SChris Mason 	DEFINE_WAIT(wait);
27877237f183SYan Zheng 	int index = transid % 2;
2788e02119d5SChris Mason 
27897237f183SYan Zheng 	/*
27907237f183SYan Zheng 	 * we only allow two pending log transactions at a time,
27917237f183SYan Zheng 	 * so we know that if ours is more than 2 older than the
27927237f183SYan Zheng 	 * current transaction, we're done
27937237f183SYan Zheng 	 */
279449e83f57SLiu Bo 	for (;;) {
27957237f183SYan Zheng 		prepare_to_wait(&root->log_commit_wait[index],
27967237f183SYan Zheng 				&wait, TASK_UNINTERRUPTIBLE);
279749e83f57SLiu Bo 
279849e83f57SLiu Bo 		if (!(root->log_transid_committed < transid &&
279949e83f57SLiu Bo 		      atomic_read(&root->log_commit[index])))
280049e83f57SLiu Bo 			break;
280149e83f57SLiu Bo 
28027237f183SYan Zheng 		mutex_unlock(&root->log_mutex);
2803e02119d5SChris Mason 		schedule();
28047237f183SYan Zheng 		mutex_lock(&root->log_mutex);
280549e83f57SLiu Bo 	}
280649e83f57SLiu Bo 	finish_wait(&root->log_commit_wait[index], &wait);
28077237f183SYan Zheng }
28087237f183SYan Zheng 
280960d53eb3SZhaolei static void wait_for_writer(struct btrfs_root *root)
28107237f183SYan Zheng {
28117237f183SYan Zheng 	DEFINE_WAIT(wait);
28128b050d35SMiao Xie 
281349e83f57SLiu Bo 	for (;;) {
281449e83f57SLiu Bo 		prepare_to_wait(&root->log_writer_wait, &wait,
281549e83f57SLiu Bo 				TASK_UNINTERRUPTIBLE);
281649e83f57SLiu Bo 		if (!atomic_read(&root->log_writers))
281749e83f57SLiu Bo 			break;
281849e83f57SLiu Bo 
28197237f183SYan Zheng 		mutex_unlock(&root->log_mutex);
28207237f183SYan Zheng 		schedule();
2821575849ecSFilipe Manana 		mutex_lock(&root->log_mutex);
28227237f183SYan Zheng 	}
282349e83f57SLiu Bo 	finish_wait(&root->log_writer_wait, &wait);
2824e02119d5SChris Mason }
2825e02119d5SChris Mason 
28268b050d35SMiao Xie static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
28278b050d35SMiao Xie 					struct btrfs_log_ctx *ctx)
28288b050d35SMiao Xie {
28298b050d35SMiao Xie 	mutex_lock(&root->log_mutex);
28308b050d35SMiao Xie 	list_del_init(&ctx->list);
28318b050d35SMiao Xie 	mutex_unlock(&root->log_mutex);
28328b050d35SMiao Xie }
28338b050d35SMiao Xie 
28348b050d35SMiao Xie /*
28358b050d35SMiao Xie  * Invoked in log mutex context, or be sure there is no other task which
28368b050d35SMiao Xie  * can access the list.
28378b050d35SMiao Xie  */
28388b050d35SMiao Xie static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
28398b050d35SMiao Xie 					     int index, int error)
28408b050d35SMiao Xie {
28418b050d35SMiao Xie 	struct btrfs_log_ctx *ctx;
2842570dd450SChris Mason 	struct btrfs_log_ctx *safe;
28438b050d35SMiao Xie 
2844570dd450SChris Mason 	list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2845570dd450SChris Mason 		list_del_init(&ctx->list);
28468b050d35SMiao Xie 		ctx->log_ret = error;
2847570dd450SChris Mason 	}
28488b050d35SMiao Xie }
28498b050d35SMiao Xie 
2850e02119d5SChris Mason /*
2851e02119d5SChris Mason  * btrfs_sync_log does sends a given tree log down to the disk and
2852e02119d5SChris Mason  * updates the super blocks to record it.  When this call is done,
285312fcfd22SChris Mason  * you know that any inodes previously logged are safely on disk only
285412fcfd22SChris Mason  * if it returns 0.
285512fcfd22SChris Mason  *
285612fcfd22SChris Mason  * Any other return value means you need to call btrfs_commit_transaction.
285712fcfd22SChris Mason  * Some of the edge cases for fsyncing directories that have had unlinks
285812fcfd22SChris Mason  * or renames done in the past mean that sometimes the only safe
285912fcfd22SChris Mason  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
286012fcfd22SChris Mason  * that has happened.
2861e02119d5SChris Mason  */
2862e02119d5SChris Mason int btrfs_sync_log(struct btrfs_trans_handle *trans,
28638b050d35SMiao Xie 		   struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2864e02119d5SChris Mason {
28657237f183SYan Zheng 	int index1;
28667237f183SYan Zheng 	int index2;
28678cef4e16SYan, Zheng 	int mark;
2868e02119d5SChris Mason 	int ret;
28690b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2870e02119d5SChris Mason 	struct btrfs_root *log = root->log_root;
28710b246afaSJeff Mahoney 	struct btrfs_root *log_root_tree = fs_info->log_root_tree;
28724203e968SJosef Bacik 	struct btrfs_root_item new_root_item;
2873bb14a59bSMiao Xie 	int log_transid = 0;
28748b050d35SMiao Xie 	struct btrfs_log_ctx root_log_ctx;
2875c6adc9ccSMiao Xie 	struct blk_plug plug;
287647876f7cSFilipe Manana 	u64 log_root_start;
287747876f7cSFilipe Manana 	u64 log_root_level;
2878e02119d5SChris Mason 
28797237f183SYan Zheng 	mutex_lock(&root->log_mutex);
2880d1433debSMiao Xie 	log_transid = ctx->log_transid;
2881d1433debSMiao Xie 	if (root->log_transid_committed >= log_transid) {
28827237f183SYan Zheng 		mutex_unlock(&root->log_mutex);
28838b050d35SMiao Xie 		return ctx->log_ret;
2884e02119d5SChris Mason 	}
2885d1433debSMiao Xie 
2886d1433debSMiao Xie 	index1 = log_transid % 2;
2887d1433debSMiao Xie 	if (atomic_read(&root->log_commit[index1])) {
288860d53eb3SZhaolei 		wait_log_commit(root, log_transid);
2889d1433debSMiao Xie 		mutex_unlock(&root->log_mutex);
2890d1433debSMiao Xie 		return ctx->log_ret;
2891d1433debSMiao Xie 	}
2892d1433debSMiao Xie 	ASSERT(log_transid == root->log_transid);
28937237f183SYan Zheng 	atomic_set(&root->log_commit[index1], 1);
28947237f183SYan Zheng 
28957237f183SYan Zheng 	/* wait for previous tree log sync to complete */
28967237f183SYan Zheng 	if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
289760d53eb3SZhaolei 		wait_log_commit(root, log_transid - 1);
289848cab2e0SMiao Xie 
289986df7eb9SYan, Zheng 	while (1) {
29002ecb7923SMiao Xie 		int batch = atomic_read(&root->log_batch);
2901cd354ad6SChris Mason 		/* when we're on an ssd, just kick the log commit out */
29020b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, SSD) &&
290327cdeb70SMiao Xie 		    test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
29047237f183SYan Zheng 			mutex_unlock(&root->log_mutex);
2905e02119d5SChris Mason 			schedule_timeout_uninterruptible(1);
29067237f183SYan Zheng 			mutex_lock(&root->log_mutex);
290786df7eb9SYan, Zheng 		}
290860d53eb3SZhaolei 		wait_for_writer(root);
29092ecb7923SMiao Xie 		if (batch == atomic_read(&root->log_batch))
2910e02119d5SChris Mason 			break;
2911e02119d5SChris Mason 	}
2912d0c803c4SChris Mason 
291312fcfd22SChris Mason 	/* bail out if we need to do a full commit */
29144884b8e8SDavid Sterba 	if (btrfs_need_log_full_commit(trans)) {
2915f31f09f6SJosef Bacik 		ret = BTRFS_LOG_FORCE_COMMIT;
291612fcfd22SChris Mason 		mutex_unlock(&root->log_mutex);
291712fcfd22SChris Mason 		goto out;
291812fcfd22SChris Mason 	}
291912fcfd22SChris Mason 
29208cef4e16SYan, Zheng 	if (log_transid % 2 == 0)
29218cef4e16SYan, Zheng 		mark = EXTENT_DIRTY;
29228cef4e16SYan, Zheng 	else
29238cef4e16SYan, Zheng 		mark = EXTENT_NEW;
29248cef4e16SYan, Zheng 
2925690587d1SChris Mason 	/* we start IO on  all the marked extents here, but we don't actually
2926690587d1SChris Mason 	 * wait for them until later.
2927690587d1SChris Mason 	 */
2928c6adc9ccSMiao Xie 	blk_start_plug(&plug);
29292ff7e61eSJeff Mahoney 	ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2930b528f467SNaohiro Aota 	/*
2931b528f467SNaohiro Aota 	 * -EAGAIN happens when someone, e.g., a concurrent transaction
2932b528f467SNaohiro Aota 	 *  commit, writes a dirty extent in this tree-log commit. This
2933b528f467SNaohiro Aota 	 *  concurrent write will create a hole writing out the extents,
2934b528f467SNaohiro Aota 	 *  and we cannot proceed on a zoned filesystem, requiring
2935b528f467SNaohiro Aota 	 *  sequential writing. While we can bail out to a full commit
2936b528f467SNaohiro Aota 	 *  here, but we can continue hoping the concurrent writing fills
2937b528f467SNaohiro Aota 	 *  the hole.
2938b528f467SNaohiro Aota 	 */
2939b528f467SNaohiro Aota 	if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
2940b528f467SNaohiro Aota 		ret = 0;
294179787eaaSJeff Mahoney 	if (ret) {
2942c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
294390787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
294479787eaaSJeff Mahoney 		mutex_unlock(&root->log_mutex);
294579787eaaSJeff Mahoney 		goto out;
294679787eaaSJeff Mahoney 	}
29477237f183SYan Zheng 
29484203e968SJosef Bacik 	/*
29494203e968SJosef Bacik 	 * We _must_ update under the root->log_mutex in order to make sure we
29504203e968SJosef Bacik 	 * have a consistent view of the log root we are trying to commit at
29514203e968SJosef Bacik 	 * this moment.
29524203e968SJosef Bacik 	 *
29534203e968SJosef Bacik 	 * We _must_ copy this into a local copy, because we are not holding the
29544203e968SJosef Bacik 	 * log_root_tree->log_mutex yet.  This is important because when we
29554203e968SJosef Bacik 	 * commit the log_root_tree we must have a consistent view of the
29564203e968SJosef Bacik 	 * log_root_tree when we update the super block to point at the
29574203e968SJosef Bacik 	 * log_root_tree bytenr.  If we update the log_root_tree here we'll race
29584203e968SJosef Bacik 	 * with the commit and possibly point at the new block which we may not
29594203e968SJosef Bacik 	 * have written out.
29604203e968SJosef Bacik 	 */
29615d4f98a2SYan Zheng 	btrfs_set_root_node(&log->root_item, log->node);
29624203e968SJosef Bacik 	memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
29637237f183SYan Zheng 
29647237f183SYan Zheng 	root->log_transid++;
29657237f183SYan Zheng 	log->log_transid = root->log_transid;
2966ff782e0aSJosef Bacik 	root->log_start_pid = 0;
29677237f183SYan Zheng 	/*
29688cef4e16SYan, Zheng 	 * IO has been started, blocks of the log tree have WRITTEN flag set
29698cef4e16SYan, Zheng 	 * in their headers. new modifications of the log will be written to
29708cef4e16SYan, Zheng 	 * new positions. so it's safe to allow log writers to go in.
29717237f183SYan Zheng 	 */
29727237f183SYan Zheng 	mutex_unlock(&root->log_mutex);
29737237f183SYan Zheng 
29743ddebf27SNaohiro Aota 	if (btrfs_is_zoned(fs_info)) {
2975e75f9fd1SNaohiro Aota 		mutex_lock(&fs_info->tree_root->log_mutex);
29763ddebf27SNaohiro Aota 		if (!log_root_tree->node) {
29773ddebf27SNaohiro Aota 			ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
29783ddebf27SNaohiro Aota 			if (ret) {
2979ea32af47SFilipe Manana 				mutex_unlock(&fs_info->tree_root->log_mutex);
298050ff5788SFilipe Manana 				blk_finish_plug(&plug);
29813ddebf27SNaohiro Aota 				goto out;
29823ddebf27SNaohiro Aota 			}
29833ddebf27SNaohiro Aota 		}
2984e75f9fd1SNaohiro Aota 		mutex_unlock(&fs_info->tree_root->log_mutex);
29853ddebf27SNaohiro Aota 	}
29863ddebf27SNaohiro Aota 
2987e75f9fd1SNaohiro Aota 	btrfs_init_log_ctx(&root_log_ctx, NULL);
2988e75f9fd1SNaohiro Aota 
2989e75f9fd1SNaohiro Aota 	mutex_lock(&log_root_tree->log_mutex);
2990e75f9fd1SNaohiro Aota 
2991e3d3b415SFilipe Manana 	index2 = log_root_tree->log_transid % 2;
2992e3d3b415SFilipe Manana 	list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
2993e3d3b415SFilipe Manana 	root_log_ctx.log_transid = log_root_tree->log_transid;
2994e3d3b415SFilipe Manana 
29954203e968SJosef Bacik 	/*
29964203e968SJosef Bacik 	 * Now we are safe to update the log_root_tree because we're under the
29974203e968SJosef Bacik 	 * log_mutex, and we're a current writer so we're holding the commit
29984203e968SJosef Bacik 	 * open until we drop the log_mutex.
29994203e968SJosef Bacik 	 */
30004203e968SJosef Bacik 	ret = update_log_root(trans, log, &new_root_item);
30014a500fd1SYan, Zheng 	if (ret) {
3002d1433debSMiao Xie 		if (!list_empty(&root_log_ctx.list))
3003d1433debSMiao Xie 			list_del_init(&root_log_ctx.list);
3004d1433debSMiao Xie 
3005c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
300690787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
300709e44868SFilipe Manana 		if (ret != -ENOSPC)
300809e44868SFilipe Manana 			btrfs_err(fs_info,
300909e44868SFilipe Manana 				  "failed to update log for root %llu ret %d",
301009e44868SFilipe Manana 				  root->root_key.objectid, ret);
3011bf89d38fSJeff Mahoney 		btrfs_wait_tree_log_extents(log, mark);
30124a500fd1SYan, Zheng 		mutex_unlock(&log_root_tree->log_mutex);
30134a500fd1SYan, Zheng 		goto out;
30144a500fd1SYan, Zheng 	}
30154a500fd1SYan, Zheng 
3016d1433debSMiao Xie 	if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
30173da5ab56SForrest Liu 		blk_finish_plug(&plug);
3018cbd60aa7SChris Mason 		list_del_init(&root_log_ctx.list);
3019d1433debSMiao Xie 		mutex_unlock(&log_root_tree->log_mutex);
3020d1433debSMiao Xie 		ret = root_log_ctx.log_ret;
3021d1433debSMiao Xie 		goto out;
3022d1433debSMiao Xie 	}
30238b050d35SMiao Xie 
3024d1433debSMiao Xie 	index2 = root_log_ctx.log_transid % 2;
30257237f183SYan Zheng 	if (atomic_read(&log_root_tree->log_commit[index2])) {
3026c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
3027bf89d38fSJeff Mahoney 		ret = btrfs_wait_tree_log_extents(log, mark);
302860d53eb3SZhaolei 		wait_log_commit(log_root_tree,
3029d1433debSMiao Xie 				root_log_ctx.log_transid);
30307237f183SYan Zheng 		mutex_unlock(&log_root_tree->log_mutex);
30315ab5e44aSFilipe Manana 		if (!ret)
30328b050d35SMiao Xie 			ret = root_log_ctx.log_ret;
30337237f183SYan Zheng 		goto out;
30347237f183SYan Zheng 	}
3035d1433debSMiao Xie 	ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
30367237f183SYan Zheng 	atomic_set(&log_root_tree->log_commit[index2], 1);
30377237f183SYan Zheng 
303812fcfd22SChris Mason 	if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
303960d53eb3SZhaolei 		wait_log_commit(log_root_tree,
3040d1433debSMiao Xie 				root_log_ctx.log_transid - 1);
304112fcfd22SChris Mason 	}
30427237f183SYan Zheng 
304312fcfd22SChris Mason 	/*
304412fcfd22SChris Mason 	 * now that we've moved on to the tree of log tree roots,
304512fcfd22SChris Mason 	 * check the full commit flag again
304612fcfd22SChris Mason 	 */
30474884b8e8SDavid Sterba 	if (btrfs_need_log_full_commit(trans)) {
3048c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
3049bf89d38fSJeff Mahoney 		btrfs_wait_tree_log_extents(log, mark);
305012fcfd22SChris Mason 		mutex_unlock(&log_root_tree->log_mutex);
3051f31f09f6SJosef Bacik 		ret = BTRFS_LOG_FORCE_COMMIT;
305212fcfd22SChris Mason 		goto out_wake_log_root;
305312fcfd22SChris Mason 	}
30547237f183SYan Zheng 
30552ff7e61eSJeff Mahoney 	ret = btrfs_write_marked_extents(fs_info,
30568cef4e16SYan, Zheng 					 &log_root_tree->dirty_log_pages,
30578cef4e16SYan, Zheng 					 EXTENT_DIRTY | EXTENT_NEW);
3058c6adc9ccSMiao Xie 	blk_finish_plug(&plug);
3059b528f467SNaohiro Aota 	/*
3060b528f467SNaohiro Aota 	 * As described above, -EAGAIN indicates a hole in the extents. We
3061b528f467SNaohiro Aota 	 * cannot wait for these write outs since the waiting cause a
3062b528f467SNaohiro Aota 	 * deadlock. Bail out to the full commit instead.
3063b528f467SNaohiro Aota 	 */
3064b528f467SNaohiro Aota 	if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3065b528f467SNaohiro Aota 		btrfs_set_log_full_commit(trans);
3066b528f467SNaohiro Aota 		btrfs_wait_tree_log_extents(log, mark);
3067b528f467SNaohiro Aota 		mutex_unlock(&log_root_tree->log_mutex);
3068b528f467SNaohiro Aota 		goto out_wake_log_root;
3069b528f467SNaohiro Aota 	} else if (ret) {
307090787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
307179787eaaSJeff Mahoney 		mutex_unlock(&log_root_tree->log_mutex);
307279787eaaSJeff Mahoney 		goto out_wake_log_root;
307379787eaaSJeff Mahoney 	}
3074bf89d38fSJeff Mahoney 	ret = btrfs_wait_tree_log_extents(log, mark);
30755ab5e44aSFilipe Manana 	if (!ret)
3076bf89d38fSJeff Mahoney 		ret = btrfs_wait_tree_log_extents(log_root_tree,
3077c6adc9ccSMiao Xie 						  EXTENT_NEW | EXTENT_DIRTY);
30785ab5e44aSFilipe Manana 	if (ret) {
307990787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
30805ab5e44aSFilipe Manana 		mutex_unlock(&log_root_tree->log_mutex);
30815ab5e44aSFilipe Manana 		goto out_wake_log_root;
30825ab5e44aSFilipe Manana 	}
3083e02119d5SChris Mason 
308447876f7cSFilipe Manana 	log_root_start = log_root_tree->node->start;
308547876f7cSFilipe Manana 	log_root_level = btrfs_header_level(log_root_tree->node);
30867237f183SYan Zheng 	log_root_tree->log_transid++;
30877237f183SYan Zheng 	mutex_unlock(&log_root_tree->log_mutex);
30887237f183SYan Zheng 
30897237f183SYan Zheng 	/*
309047876f7cSFilipe Manana 	 * Here we are guaranteed that nobody is going to write the superblock
309147876f7cSFilipe Manana 	 * for the current transaction before us and that neither we do write
309247876f7cSFilipe Manana 	 * our superblock before the previous transaction finishes its commit
309347876f7cSFilipe Manana 	 * and writes its superblock, because:
309447876f7cSFilipe Manana 	 *
309547876f7cSFilipe Manana 	 * 1) We are holding a handle on the current transaction, so no body
309647876f7cSFilipe Manana 	 *    can commit it until we release the handle;
309747876f7cSFilipe Manana 	 *
309847876f7cSFilipe Manana 	 * 2) Before writing our superblock we acquire the tree_log_mutex, so
309947876f7cSFilipe Manana 	 *    if the previous transaction is still committing, and hasn't yet
310047876f7cSFilipe Manana 	 *    written its superblock, we wait for it to do it, because a
310147876f7cSFilipe Manana 	 *    transaction commit acquires the tree_log_mutex when the commit
310247876f7cSFilipe Manana 	 *    begins and releases it only after writing its superblock.
31037237f183SYan Zheng 	 */
310447876f7cSFilipe Manana 	mutex_lock(&fs_info->tree_log_mutex);
3105165ea85fSJosef Bacik 
3106165ea85fSJosef Bacik 	/*
3107165ea85fSJosef Bacik 	 * The previous transaction writeout phase could have failed, and thus
3108165ea85fSJosef Bacik 	 * marked the fs in an error state.  We must not commit here, as we
3109165ea85fSJosef Bacik 	 * could have updated our generation in the super_for_commit and
3110165ea85fSJosef Bacik 	 * writing the super here would result in transid mismatches.  If there
3111165ea85fSJosef Bacik 	 * is an error here just bail.
3112165ea85fSJosef Bacik 	 */
311384961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
3114165ea85fSJosef Bacik 		ret = -EIO;
3115165ea85fSJosef Bacik 		btrfs_set_log_full_commit(trans);
3116165ea85fSJosef Bacik 		btrfs_abort_transaction(trans, ret);
3117165ea85fSJosef Bacik 		mutex_unlock(&fs_info->tree_log_mutex);
3118165ea85fSJosef Bacik 		goto out_wake_log_root;
3119165ea85fSJosef Bacik 	}
3120165ea85fSJosef Bacik 
312147876f7cSFilipe Manana 	btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
312247876f7cSFilipe Manana 	btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3123eece6a9cSDavid Sterba 	ret = write_all_supers(fs_info, 1);
312447876f7cSFilipe Manana 	mutex_unlock(&fs_info->tree_log_mutex);
31255af3e8ccSStefan Behrens 	if (ret) {
312690787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
312766642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
31285af3e8ccSStefan Behrens 		goto out_wake_log_root;
31295af3e8ccSStefan Behrens 	}
31307237f183SYan Zheng 
3131e1a6d264SFilipe Manana 	/*
3132e1a6d264SFilipe Manana 	 * We know there can only be one task here, since we have not yet set
3133e1a6d264SFilipe Manana 	 * root->log_commit[index1] to 0 and any task attempting to sync the
3134e1a6d264SFilipe Manana 	 * log must wait for the previous log transaction to commit if it's
3135e1a6d264SFilipe Manana 	 * still in progress or wait for the current log transaction commit if
3136e1a6d264SFilipe Manana 	 * someone else already started it. We use <= and not < because the
3137e1a6d264SFilipe Manana 	 * first log transaction has an ID of 0.
3138e1a6d264SFilipe Manana 	 */
3139e1a6d264SFilipe Manana 	ASSERT(root->last_log_commit <= log_transid);
3140257c62e1SChris Mason 	root->last_log_commit = log_transid;
3141257c62e1SChris Mason 
314212fcfd22SChris Mason out_wake_log_root:
3143570dd450SChris Mason 	mutex_lock(&log_root_tree->log_mutex);
31448b050d35SMiao Xie 	btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
31458b050d35SMiao Xie 
3146d1433debSMiao Xie 	log_root_tree->log_transid_committed++;
31477237f183SYan Zheng 	atomic_set(&log_root_tree->log_commit[index2], 0);
3148d1433debSMiao Xie 	mutex_unlock(&log_root_tree->log_mutex);
3149d1433debSMiao Xie 
315033a9eca7SDavid Sterba 	/*
3151093258e6SDavid Sterba 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3152093258e6SDavid Sterba 	 * all the updates above are seen by the woken threads. It might not be
3153093258e6SDavid Sterba 	 * necessary, but proving that seems to be hard.
315433a9eca7SDavid Sterba 	 */
3155093258e6SDavid Sterba 	cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3156e02119d5SChris Mason out:
3157d1433debSMiao Xie 	mutex_lock(&root->log_mutex);
3158570dd450SChris Mason 	btrfs_remove_all_log_ctxs(root, index1, ret);
3159d1433debSMiao Xie 	root->log_transid_committed++;
31607237f183SYan Zheng 	atomic_set(&root->log_commit[index1], 0);
3161d1433debSMiao Xie 	mutex_unlock(&root->log_mutex);
31628b050d35SMiao Xie 
316333a9eca7SDavid Sterba 	/*
3164093258e6SDavid Sterba 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3165093258e6SDavid Sterba 	 * all the updates above are seen by the woken threads. It might not be
3166093258e6SDavid Sterba 	 * necessary, but proving that seems to be hard.
316733a9eca7SDavid Sterba 	 */
3168093258e6SDavid Sterba 	cond_wake_up(&root->log_commit_wait[index1]);
3169b31eabd8SChris Mason 	return ret;
3170e02119d5SChris Mason }
3171e02119d5SChris Mason 
31724a500fd1SYan, Zheng static void free_log_tree(struct btrfs_trans_handle *trans,
31734a500fd1SYan, Zheng 			  struct btrfs_root *log)
3174e02119d5SChris Mason {
3175e02119d5SChris Mason 	int ret;
3176e02119d5SChris Mason 	struct walk_control wc = {
3177e02119d5SChris Mason 		.free = 1,
3178e02119d5SChris Mason 		.process_func = process_one_buffer
3179e02119d5SChris Mason 	};
3180e02119d5SChris Mason 
31813ddebf27SNaohiro Aota 	if (log->node) {
3182e02119d5SChris Mason 		ret = walk_log_tree(trans, log, &wc);
3183374b0e2dSJeff Mahoney 		if (ret) {
318440cdc509SFilipe Manana 			/*
318540cdc509SFilipe Manana 			 * We weren't able to traverse the entire log tree, the
318640cdc509SFilipe Manana 			 * typical scenario is getting an -EIO when reading an
318740cdc509SFilipe Manana 			 * extent buffer of the tree, due to a previous writeback
318840cdc509SFilipe Manana 			 * failure of it.
318940cdc509SFilipe Manana 			 */
319040cdc509SFilipe Manana 			set_bit(BTRFS_FS_STATE_LOG_CLEANUP_ERROR,
319140cdc509SFilipe Manana 				&log->fs_info->fs_state);
319240cdc509SFilipe Manana 
319340cdc509SFilipe Manana 			/*
319440cdc509SFilipe Manana 			 * Some extent buffers of the log tree may still be dirty
319540cdc509SFilipe Manana 			 * and not yet written back to storage, because we may
319640cdc509SFilipe Manana 			 * have updates to a log tree without syncing a log tree,
319740cdc509SFilipe Manana 			 * such as during rename and link operations. So flush
319840cdc509SFilipe Manana 			 * them out and wait for their writeback to complete, so
319940cdc509SFilipe Manana 			 * that we properly cleanup their state and pages.
320040cdc509SFilipe Manana 			 */
320140cdc509SFilipe Manana 			btrfs_write_marked_extents(log->fs_info,
320240cdc509SFilipe Manana 						   &log->dirty_log_pages,
320340cdc509SFilipe Manana 						   EXTENT_DIRTY | EXTENT_NEW);
320440cdc509SFilipe Manana 			btrfs_wait_tree_log_extents(log,
320540cdc509SFilipe Manana 						    EXTENT_DIRTY | EXTENT_NEW);
320640cdc509SFilipe Manana 
3207374b0e2dSJeff Mahoney 			if (trans)
320866642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
3209374b0e2dSJeff Mahoney 			else
3210374b0e2dSJeff Mahoney 				btrfs_handle_fs_error(log->fs_info, ret, NULL);
3211374b0e2dSJeff Mahoney 		}
32123ddebf27SNaohiro Aota 	}
3213e02119d5SChris Mason 
321459b0713aSFilipe Manana 	clear_extent_bits(&log->dirty_log_pages, 0, (u64)-1,
321555237a5fSLiu Bo 			  EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3216e289f03eSFilipe Manana 	extent_io_tree_release(&log->log_csum_range);
3217d3575156SNaohiro Aota 
321800246528SJosef Bacik 	btrfs_put_root(log);
32194a500fd1SYan, Zheng }
32204a500fd1SYan, Zheng 
32214a500fd1SYan, Zheng /*
32224a500fd1SYan, Zheng  * free all the extents used by the tree log.  This should be called
32234a500fd1SYan, Zheng  * at commit time of the full transaction
32244a500fd1SYan, Zheng  */
32254a500fd1SYan, Zheng int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
32264a500fd1SYan, Zheng {
32274a500fd1SYan, Zheng 	if (root->log_root) {
32284a500fd1SYan, Zheng 		free_log_tree(trans, root->log_root);
32294a500fd1SYan, Zheng 		root->log_root = NULL;
3230e7a79811SFilipe Manana 		clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
32314a500fd1SYan, Zheng 	}
32324a500fd1SYan, Zheng 	return 0;
32334a500fd1SYan, Zheng }
32344a500fd1SYan, Zheng 
32354a500fd1SYan, Zheng int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
32364a500fd1SYan, Zheng 			     struct btrfs_fs_info *fs_info)
32374a500fd1SYan, Zheng {
32384a500fd1SYan, Zheng 	if (fs_info->log_root_tree) {
32394a500fd1SYan, Zheng 		free_log_tree(trans, fs_info->log_root_tree);
32404a500fd1SYan, Zheng 		fs_info->log_root_tree = NULL;
324147876f7cSFilipe Manana 		clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
32424a500fd1SYan, Zheng 	}
3243e02119d5SChris Mason 	return 0;
3244e02119d5SChris Mason }
3245e02119d5SChris Mason 
3246e02119d5SChris Mason /*
32470f8ce498SFilipe Manana  * Check if an inode was logged in the current transaction. This correctly deals
32480f8ce498SFilipe Manana  * with the case where the inode was logged but has a logged_trans of 0, which
32490f8ce498SFilipe Manana  * happens if the inode is evicted and loaded again, as logged_trans is an in
32500f8ce498SFilipe Manana  * memory only field (not persisted).
32510f8ce498SFilipe Manana  *
32520f8ce498SFilipe Manana  * Returns 1 if the inode was logged before in the transaction, 0 if it was not,
32530f8ce498SFilipe Manana  * and < 0 on error.
3254803f0f64SFilipe Manana  */
3255*bf1f4fd3SFilipe Manana static int inode_logged(const struct btrfs_trans_handle *trans,
32560f8ce498SFilipe Manana 			struct btrfs_inode *inode,
32570f8ce498SFilipe Manana 			struct btrfs_path *path_in)
3258803f0f64SFilipe Manana {
32590f8ce498SFilipe Manana 	struct btrfs_path *path = path_in;
32600f8ce498SFilipe Manana 	struct btrfs_key key;
32610f8ce498SFilipe Manana 	int ret;
3262803f0f64SFilipe Manana 
32630f8ce498SFilipe Manana 	if (inode->logged_trans == trans->transid)
32640f8ce498SFilipe Manana 		return 1;
32651e0860f3SFilipe Manana 
32666e8e777dSFilipe Manana 	/*
32670f8ce498SFilipe Manana 	 * If logged_trans is not 0, then we know the inode logged was not logged
32680f8ce498SFilipe Manana 	 * in this transaction, so we can return false right away.
32696e8e777dSFilipe Manana 	 */
32700f8ce498SFilipe Manana 	if (inode->logged_trans > 0)
32710f8ce498SFilipe Manana 		return 0;
3272803f0f64SFilipe Manana 
32730f8ce498SFilipe Manana 	/*
32740f8ce498SFilipe Manana 	 * If no log tree was created for this root in this transaction, then
32750f8ce498SFilipe Manana 	 * the inode can not have been logged in this transaction. In that case
32760f8ce498SFilipe Manana 	 * set logged_trans to anything greater than 0 and less than the current
32770f8ce498SFilipe Manana 	 * transaction's ID, to avoid the search below in a future call in case
32780f8ce498SFilipe Manana 	 * a log tree gets created after this.
32790f8ce498SFilipe Manana 	 */
32800f8ce498SFilipe Manana 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state)) {
32810f8ce498SFilipe Manana 		inode->logged_trans = trans->transid - 1;
32820f8ce498SFilipe Manana 		return 0;
32830f8ce498SFilipe Manana 	}
32840f8ce498SFilipe Manana 
32850f8ce498SFilipe Manana 	/*
32860f8ce498SFilipe Manana 	 * We have a log tree and the inode's logged_trans is 0. We can't tell
32870f8ce498SFilipe Manana 	 * for sure if the inode was logged before in this transaction by looking
32880f8ce498SFilipe Manana 	 * only at logged_trans. We could be pessimistic and assume it was, but
32890f8ce498SFilipe Manana 	 * that can lead to unnecessarily logging an inode during rename and link
32900f8ce498SFilipe Manana 	 * operations, and then further updating the log in followup rename and
32910f8ce498SFilipe Manana 	 * link operations, specially if it's a directory, which adds latency
32920f8ce498SFilipe Manana 	 * visible to applications doing a series of rename or link operations.
32930f8ce498SFilipe Manana 	 *
32940f8ce498SFilipe Manana 	 * A logged_trans of 0 here can mean several things:
32950f8ce498SFilipe Manana 	 *
32960f8ce498SFilipe Manana 	 * 1) The inode was never logged since the filesystem was mounted, and may
32970f8ce498SFilipe Manana 	 *    or may have not been evicted and loaded again;
32980f8ce498SFilipe Manana 	 *
32990f8ce498SFilipe Manana 	 * 2) The inode was logged in a previous transaction, then evicted and
33000f8ce498SFilipe Manana 	 *    then loaded again;
33010f8ce498SFilipe Manana 	 *
33020f8ce498SFilipe Manana 	 * 3) The inode was logged in the current transaction, then evicted and
33030f8ce498SFilipe Manana 	 *    then loaded again.
33040f8ce498SFilipe Manana 	 *
33050f8ce498SFilipe Manana 	 * For cases 1) and 2) we don't want to return true, but we need to detect
33060f8ce498SFilipe Manana 	 * case 3) and return true. So we do a search in the log root for the inode
33070f8ce498SFilipe Manana 	 * item.
33080f8ce498SFilipe Manana 	 */
33090f8ce498SFilipe Manana 	key.objectid = btrfs_ino(inode);
33100f8ce498SFilipe Manana 	key.type = BTRFS_INODE_ITEM_KEY;
33110f8ce498SFilipe Manana 	key.offset = 0;
33120f8ce498SFilipe Manana 
33130f8ce498SFilipe Manana 	if (!path) {
33140f8ce498SFilipe Manana 		path = btrfs_alloc_path();
33150f8ce498SFilipe Manana 		if (!path)
33160f8ce498SFilipe Manana 			return -ENOMEM;
33170f8ce498SFilipe Manana 	}
33180f8ce498SFilipe Manana 
33190f8ce498SFilipe Manana 	ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
33200f8ce498SFilipe Manana 
33210f8ce498SFilipe Manana 	if (path_in)
33220f8ce498SFilipe Manana 		btrfs_release_path(path);
33230f8ce498SFilipe Manana 	else
33240f8ce498SFilipe Manana 		btrfs_free_path(path);
33250f8ce498SFilipe Manana 
33260f8ce498SFilipe Manana 	/*
33270f8ce498SFilipe Manana 	 * Logging an inode always results in logging its inode item. So if we
33280f8ce498SFilipe Manana 	 * did not find the item we know the inode was not logged for sure.
33290f8ce498SFilipe Manana 	 */
33300f8ce498SFilipe Manana 	if (ret < 0) {
33310f8ce498SFilipe Manana 		return ret;
33320f8ce498SFilipe Manana 	} else if (ret > 0) {
33330f8ce498SFilipe Manana 		/*
33340f8ce498SFilipe Manana 		 * Set logged_trans to a value greater than 0 and less then the
33350f8ce498SFilipe Manana 		 * current transaction to avoid doing the search in future calls.
33360f8ce498SFilipe Manana 		 */
33370f8ce498SFilipe Manana 		inode->logged_trans = trans->transid - 1;
33380f8ce498SFilipe Manana 		return 0;
33390f8ce498SFilipe Manana 	}
33400f8ce498SFilipe Manana 
33410f8ce498SFilipe Manana 	/*
33420f8ce498SFilipe Manana 	 * The inode was previously logged and then evicted, set logged_trans to
33430f8ce498SFilipe Manana 	 * the current transacion's ID, to avoid future tree searches as long as
33440f8ce498SFilipe Manana 	 * the inode is not evicted again.
33450f8ce498SFilipe Manana 	 */
33460f8ce498SFilipe Manana 	inode->logged_trans = trans->transid;
33470f8ce498SFilipe Manana 
33480f8ce498SFilipe Manana 	/*
33490f8ce498SFilipe Manana 	 * If it's a directory, then we must set last_dir_index_offset to the
33500f8ce498SFilipe Manana 	 * maximum possible value, so that the next attempt to log the inode does
33510f8ce498SFilipe Manana 	 * not skip checking if dir index keys found in modified subvolume tree
33520f8ce498SFilipe Manana 	 * leaves have been logged before, otherwise it would result in attempts
33530f8ce498SFilipe Manana 	 * to insert duplicate dir index keys in the log tree. This must be done
33540f8ce498SFilipe Manana 	 * because last_dir_index_offset is an in-memory only field, not persisted
33550f8ce498SFilipe Manana 	 * in the inode item or any other on-disk structure, so its value is lost
33560f8ce498SFilipe Manana 	 * once the inode is evicted.
33570f8ce498SFilipe Manana 	 */
33580f8ce498SFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode))
33590f8ce498SFilipe Manana 		inode->last_dir_index_offset = (u64)-1;
33600f8ce498SFilipe Manana 
33610f8ce498SFilipe Manana 	return 1;
3362803f0f64SFilipe Manana }
3363803f0f64SFilipe Manana 
3364803f0f64SFilipe Manana /*
3365839061feSFilipe Manana  * Delete a directory entry from the log if it exists.
3366839061feSFilipe Manana  *
3367839061feSFilipe Manana  * Returns < 0 on error
3368839061feSFilipe Manana  *           1 if the entry does not exists
3369839061feSFilipe Manana  *           0 if the entry existed and was successfully deleted
3370839061feSFilipe Manana  */
3371839061feSFilipe Manana static int del_logged_dentry(struct btrfs_trans_handle *trans,
3372839061feSFilipe Manana 			     struct btrfs_root *log,
3373839061feSFilipe Manana 			     struct btrfs_path *path,
3374839061feSFilipe Manana 			     u64 dir_ino,
33756db75318SSweet Tea Dorminy 			     const struct fscrypt_str *name,
3376839061feSFilipe Manana 			     u64 index)
3377839061feSFilipe Manana {
3378839061feSFilipe Manana 	struct btrfs_dir_item *di;
3379839061feSFilipe Manana 
3380839061feSFilipe Manana 	/*
3381839061feSFilipe Manana 	 * We only log dir index items of a directory, so we don't need to look
3382839061feSFilipe Manana 	 * for dir item keys.
3383839061feSFilipe Manana 	 */
3384839061feSFilipe Manana 	di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3385e43eec81SSweet Tea Dorminy 					 index, name, -1);
3386839061feSFilipe Manana 	if (IS_ERR(di))
3387839061feSFilipe Manana 		return PTR_ERR(di);
3388839061feSFilipe Manana 	else if (!di)
3389839061feSFilipe Manana 		return 1;
3390839061feSFilipe Manana 
3391839061feSFilipe Manana 	/*
3392839061feSFilipe Manana 	 * We do not need to update the size field of the directory's
3393839061feSFilipe Manana 	 * inode item because on log replay we update the field to reflect
3394839061feSFilipe Manana 	 * all existing entries in the directory (see overwrite_item()).
3395839061feSFilipe Manana 	 */
3396839061feSFilipe Manana 	return btrfs_delete_one_dir_name(trans, log, path, di);
3397839061feSFilipe Manana }
3398839061feSFilipe Manana 
3399839061feSFilipe Manana /*
3400e02119d5SChris Mason  * If both a file and directory are logged, and unlinks or renames are
3401e02119d5SChris Mason  * mixed in, we have a few interesting corners:
3402e02119d5SChris Mason  *
3403e02119d5SChris Mason  * create file X in dir Y
3404e02119d5SChris Mason  * link file X to X.link in dir Y
3405e02119d5SChris Mason  * fsync file X
3406e02119d5SChris Mason  * unlink file X but leave X.link
3407e02119d5SChris Mason  * fsync dir Y
3408e02119d5SChris Mason  *
3409e02119d5SChris Mason  * After a crash we would expect only X.link to exist.  But file X
3410e02119d5SChris Mason  * didn't get fsync'd again so the log has back refs for X and X.link.
3411e02119d5SChris Mason  *
3412e02119d5SChris Mason  * We solve this by removing directory entries and inode backrefs from the
3413e02119d5SChris Mason  * log when a file that was logged in the current transaction is
3414e02119d5SChris Mason  * unlinked.  Any later fsync will include the updated log entries, and
3415e02119d5SChris Mason  * we'll be able to reconstruct the proper directory items from backrefs.
3416e02119d5SChris Mason  *
3417e02119d5SChris Mason  * This optimizations allows us to avoid relogging the entire inode
3418e02119d5SChris Mason  * or the entire directory.
3419e02119d5SChris Mason  */
34209a35fc95SJosef Bacik void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3421e02119d5SChris Mason 				  struct btrfs_root *root,
34226db75318SSweet Tea Dorminy 				  const struct fscrypt_str *name,
342349f34d1fSNikolay Borisov 				  struct btrfs_inode *dir, u64 index)
3424e02119d5SChris Mason {
3425e02119d5SChris Mason 	struct btrfs_path *path;
3426e02119d5SChris Mason 	int ret;
3427e02119d5SChris Mason 
34280f8ce498SFilipe Manana 	ret = inode_logged(trans, dir, NULL);
34290f8ce498SFilipe Manana 	if (ret == 0)
34309a35fc95SJosef Bacik 		return;
34310f8ce498SFilipe Manana 	else if (ret < 0) {
34320f8ce498SFilipe Manana 		btrfs_set_log_full_commit(trans);
34330f8ce498SFilipe Manana 		return;
34340f8ce498SFilipe Manana 	}
34353a5f1d45SChris Mason 
3436e02119d5SChris Mason 	ret = join_running_log_trans(root);
3437e02119d5SChris Mason 	if (ret)
34389a35fc95SJosef Bacik 		return;
3439e02119d5SChris Mason 
344049f34d1fSNikolay Borisov 	mutex_lock(&dir->log_mutex);
3441e02119d5SChris Mason 
3442e02119d5SChris Mason 	path = btrfs_alloc_path();
3443a62f44a5STsutomu Itoh 	if (!path) {
3444839061feSFilipe Manana 		ret = -ENOMEM;
3445a62f44a5STsutomu Itoh 		goto out_unlock;
3446a62f44a5STsutomu Itoh 	}
34472a29edc6Sliubo 
3448839061feSFilipe Manana 	ret = del_logged_dentry(trans, root->log_root, path, btrfs_ino(dir),
3449e43eec81SSweet Tea Dorminy 				name, index);
3450e02119d5SChris Mason 	btrfs_free_path(path);
3451a62f44a5STsutomu Itoh out_unlock:
345249f34d1fSNikolay Borisov 	mutex_unlock(&dir->log_mutex);
3453839061feSFilipe Manana 	if (ret < 0)
345490787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
345512fcfd22SChris Mason 	btrfs_end_log_trans(root);
3456e02119d5SChris Mason }
3457e02119d5SChris Mason 
3458e02119d5SChris Mason /* see comments for btrfs_del_dir_entries_in_log */
34599a35fc95SJosef Bacik void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3460e02119d5SChris Mason 				struct btrfs_root *root,
34616db75318SSweet Tea Dorminy 				const struct fscrypt_str *name,
3462a491abb2SNikolay Borisov 				struct btrfs_inode *inode, u64 dirid)
3463e02119d5SChris Mason {
3464e02119d5SChris Mason 	struct btrfs_root *log;
3465e02119d5SChris Mason 	u64 index;
3466e02119d5SChris Mason 	int ret;
3467e02119d5SChris Mason 
34680f8ce498SFilipe Manana 	ret = inode_logged(trans, inode, NULL);
34690f8ce498SFilipe Manana 	if (ret == 0)
34709a35fc95SJosef Bacik 		return;
34710f8ce498SFilipe Manana 	else if (ret < 0) {
34720f8ce498SFilipe Manana 		btrfs_set_log_full_commit(trans);
34730f8ce498SFilipe Manana 		return;
34740f8ce498SFilipe Manana 	}
34753a5f1d45SChris Mason 
3476e02119d5SChris Mason 	ret = join_running_log_trans(root);
3477e02119d5SChris Mason 	if (ret)
34789a35fc95SJosef Bacik 		return;
3479e02119d5SChris Mason 	log = root->log_root;
3480a491abb2SNikolay Borisov 	mutex_lock(&inode->log_mutex);
3481e02119d5SChris Mason 
3482e43eec81SSweet Tea Dorminy 	ret = btrfs_del_inode_ref(trans, log, name, btrfs_ino(inode),
3483e02119d5SChris Mason 				  dirid, &index);
3484a491abb2SNikolay Borisov 	mutex_unlock(&inode->log_mutex);
34859a35fc95SJosef Bacik 	if (ret < 0 && ret != -ENOENT)
348690787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
348712fcfd22SChris Mason 	btrfs_end_log_trans(root);
3488e02119d5SChris Mason }
3489e02119d5SChris Mason 
3490e02119d5SChris Mason /*
3491e02119d5SChris Mason  * creates a range item in the log for 'dirid'.  first_offset and
3492e02119d5SChris Mason  * last_offset tell us which parts of the key space the log should
3493e02119d5SChris Mason  * be considered authoritative for.
3494e02119d5SChris Mason  */
3495e02119d5SChris Mason static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3496e02119d5SChris Mason 				       struct btrfs_root *log,
3497e02119d5SChris Mason 				       struct btrfs_path *path,
3498339d0354SFilipe Manana 				       u64 dirid,
3499e02119d5SChris Mason 				       u64 first_offset, u64 last_offset)
3500e02119d5SChris Mason {
3501e02119d5SChris Mason 	int ret;
3502e02119d5SChris Mason 	struct btrfs_key key;
3503e02119d5SChris Mason 	struct btrfs_dir_log_item *item;
3504e02119d5SChris Mason 
3505e02119d5SChris Mason 	key.objectid = dirid;
3506e02119d5SChris Mason 	key.offset = first_offset;
3507e02119d5SChris Mason 	key.type = BTRFS_DIR_LOG_INDEX_KEY;
3508e02119d5SChris Mason 	ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3509750ee454SFilipe Manana 	/*
3510750ee454SFilipe Manana 	 * -EEXIST is fine and can happen sporadically when we are logging a
3511750ee454SFilipe Manana 	 * directory and have concurrent insertions in the subvolume's tree for
3512750ee454SFilipe Manana 	 * items from other inodes and that result in pushing off some dir items
3513750ee454SFilipe Manana 	 * from one leaf to another in order to accommodate for the new items.
3514750ee454SFilipe Manana 	 * This results in logging the same dir index range key.
3515750ee454SFilipe Manana 	 */
3516750ee454SFilipe Manana 	if (ret && ret != -EEXIST)
35174a500fd1SYan, Zheng 		return ret;
3518e02119d5SChris Mason 
3519e02119d5SChris Mason 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3520e02119d5SChris Mason 			      struct btrfs_dir_log_item);
3521750ee454SFilipe Manana 	if (ret == -EEXIST) {
3522750ee454SFilipe Manana 		const u64 curr_end = btrfs_dir_log_end(path->nodes[0], item);
3523750ee454SFilipe Manana 
3524750ee454SFilipe Manana 		/*
3525750ee454SFilipe Manana 		 * btrfs_del_dir_entries_in_log() might have been called during
3526750ee454SFilipe Manana 		 * an unlink between the initial insertion of this key and the
3527750ee454SFilipe Manana 		 * current update, or we might be logging a single entry deletion
3528750ee454SFilipe Manana 		 * during a rename, so set the new last_offset to the max value.
3529750ee454SFilipe Manana 		 */
3530750ee454SFilipe Manana 		last_offset = max(last_offset, curr_end);
3531750ee454SFilipe Manana 	}
3532e02119d5SChris Mason 	btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3533e02119d5SChris Mason 	btrfs_mark_buffer_dirty(path->nodes[0]);
3534b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3535e02119d5SChris Mason 	return 0;
3536e02119d5SChris Mason }
3537e02119d5SChris Mason 
3538086dcbfaSFilipe Manana static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
35396afaed53SFilipe Manana 				 struct btrfs_inode *inode,
3540086dcbfaSFilipe Manana 				 struct extent_buffer *src,
3541086dcbfaSFilipe Manana 				 struct btrfs_path *dst_path,
3542086dcbfaSFilipe Manana 				 int start_slot,
3543086dcbfaSFilipe Manana 				 int count)
3544086dcbfaSFilipe Manana {
35456afaed53SFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
3546086dcbfaSFilipe Manana 	char *ins_data = NULL;
3547b7ef5f3aSFilipe Manana 	struct btrfs_item_batch batch;
3548086dcbfaSFilipe Manana 	struct extent_buffer *dst;
3549da1b811fSFilipe Manana 	unsigned long src_offset;
3550da1b811fSFilipe Manana 	unsigned long dst_offset;
35516afaed53SFilipe Manana 	u64 last_index;
3552086dcbfaSFilipe Manana 	struct btrfs_key key;
3553086dcbfaSFilipe Manana 	u32 item_size;
3554086dcbfaSFilipe Manana 	int ret;
3555086dcbfaSFilipe Manana 	int i;
3556086dcbfaSFilipe Manana 
3557086dcbfaSFilipe Manana 	ASSERT(count > 0);
3558b7ef5f3aSFilipe Manana 	batch.nr = count;
3559086dcbfaSFilipe Manana 
3560086dcbfaSFilipe Manana 	if (count == 1) {
3561086dcbfaSFilipe Manana 		btrfs_item_key_to_cpu(src, &key, start_slot);
35623212fa14SJosef Bacik 		item_size = btrfs_item_size(src, start_slot);
3563b7ef5f3aSFilipe Manana 		batch.keys = &key;
3564b7ef5f3aSFilipe Manana 		batch.data_sizes = &item_size;
3565b7ef5f3aSFilipe Manana 		batch.total_data_size = item_size;
3566086dcbfaSFilipe Manana 	} else {
3567b7ef5f3aSFilipe Manana 		struct btrfs_key *ins_keys;
3568b7ef5f3aSFilipe Manana 		u32 *ins_sizes;
3569b7ef5f3aSFilipe Manana 
3570086dcbfaSFilipe Manana 		ins_data = kmalloc(count * sizeof(u32) +
3571086dcbfaSFilipe Manana 				   count * sizeof(struct btrfs_key), GFP_NOFS);
3572086dcbfaSFilipe Manana 		if (!ins_data)
3573086dcbfaSFilipe Manana 			return -ENOMEM;
3574086dcbfaSFilipe Manana 
3575086dcbfaSFilipe Manana 		ins_sizes = (u32 *)ins_data;
3576086dcbfaSFilipe Manana 		ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
3577b7ef5f3aSFilipe Manana 		batch.keys = ins_keys;
3578b7ef5f3aSFilipe Manana 		batch.data_sizes = ins_sizes;
3579b7ef5f3aSFilipe Manana 		batch.total_data_size = 0;
3580086dcbfaSFilipe Manana 
3581086dcbfaSFilipe Manana 		for (i = 0; i < count; i++) {
3582086dcbfaSFilipe Manana 			const int slot = start_slot + i;
3583086dcbfaSFilipe Manana 
3584086dcbfaSFilipe Manana 			btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
35853212fa14SJosef Bacik 			ins_sizes[i] = btrfs_item_size(src, slot);
3586b7ef5f3aSFilipe Manana 			batch.total_data_size += ins_sizes[i];
3587086dcbfaSFilipe Manana 		}
3588086dcbfaSFilipe Manana 	}
3589086dcbfaSFilipe Manana 
3590b7ef5f3aSFilipe Manana 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
3591086dcbfaSFilipe Manana 	if (ret)
3592086dcbfaSFilipe Manana 		goto out;
3593086dcbfaSFilipe Manana 
3594086dcbfaSFilipe Manana 	dst = dst_path->nodes[0];
3595da1b811fSFilipe Manana 	/*
3596da1b811fSFilipe Manana 	 * Copy all the items in bulk, in a single copy operation. Item data is
3597da1b811fSFilipe Manana 	 * organized such that it's placed at the end of a leaf and from right
3598da1b811fSFilipe Manana 	 * to left. For example, the data for the second item ends at an offset
3599da1b811fSFilipe Manana 	 * that matches the offset where the data for the first item starts, the
3600da1b811fSFilipe Manana 	 * data for the third item ends at an offset that matches the offset
3601da1b811fSFilipe Manana 	 * where the data of the second items starts, and so on.
3602da1b811fSFilipe Manana 	 * Therefore our source and destination start offsets for copy match the
3603da1b811fSFilipe Manana 	 * offsets of the last items (highest slots).
3604da1b811fSFilipe Manana 	 */
3605da1b811fSFilipe Manana 	dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
3606da1b811fSFilipe Manana 	src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
3607da1b811fSFilipe Manana 	copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
3608086dcbfaSFilipe Manana 	btrfs_release_path(dst_path);
36096afaed53SFilipe Manana 
36106afaed53SFilipe Manana 	last_index = batch.keys[count - 1].offset;
36116afaed53SFilipe Manana 	ASSERT(last_index > inode->last_dir_index_offset);
36126afaed53SFilipe Manana 
36136afaed53SFilipe Manana 	/*
36146afaed53SFilipe Manana 	 * If for some unexpected reason the last item's index is not greater
36155cce1780SFilipe Manana 	 * than the last index we logged, warn and force a transaction commit.
36166afaed53SFilipe Manana 	 */
36176afaed53SFilipe Manana 	if (WARN_ON(last_index <= inode->last_dir_index_offset))
36185cce1780SFilipe Manana 		ret = BTRFS_LOG_FORCE_COMMIT;
36196afaed53SFilipe Manana 	else
36206afaed53SFilipe Manana 		inode->last_dir_index_offset = last_index;
3621fa4b8cb1SFilipe Manana 
3622fa4b8cb1SFilipe Manana 	if (btrfs_get_first_dir_index_to_log(inode) == 0)
3623fa4b8cb1SFilipe Manana 		btrfs_set_first_dir_index_to_log(inode, batch.keys[0].offset);
3624086dcbfaSFilipe Manana out:
3625086dcbfaSFilipe Manana 	kfree(ins_data);
3626086dcbfaSFilipe Manana 
3627086dcbfaSFilipe Manana 	return ret;
3628086dcbfaSFilipe Manana }
3629086dcbfaSFilipe Manana 
3630eb10d85eSFilipe Manana static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
3631eb10d85eSFilipe Manana 				  struct btrfs_inode *inode,
3632eb10d85eSFilipe Manana 				  struct btrfs_path *path,
3633eb10d85eSFilipe Manana 				  struct btrfs_path *dst_path,
3634732d591aSFilipe Manana 				  struct btrfs_log_ctx *ctx,
3635732d591aSFilipe Manana 				  u64 *last_old_dentry_offset)
3636eb10d85eSFilipe Manana {
3637eb10d85eSFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
3638796787c9SFilipe Manana 	struct extent_buffer *src;
3639796787c9SFilipe Manana 	const int nritems = btrfs_header_nritems(path->nodes[0]);
3640eb10d85eSFilipe Manana 	const u64 ino = btrfs_ino(inode);
3641086dcbfaSFilipe Manana 	bool last_found = false;
3642086dcbfaSFilipe Manana 	int batch_start = 0;
3643086dcbfaSFilipe Manana 	int batch_size = 0;
3644eb10d85eSFilipe Manana 	int i;
3645eb10d85eSFilipe Manana 
3646796787c9SFilipe Manana 	/*
3647796787c9SFilipe Manana 	 * We need to clone the leaf, release the read lock on it, and use the
3648796787c9SFilipe Manana 	 * clone before modifying the log tree. See the comment at copy_items()
3649796787c9SFilipe Manana 	 * about why we need to do this.
3650796787c9SFilipe Manana 	 */
3651796787c9SFilipe Manana 	src = btrfs_clone_extent_buffer(path->nodes[0]);
3652796787c9SFilipe Manana 	if (!src)
3653796787c9SFilipe Manana 		return -ENOMEM;
3654796787c9SFilipe Manana 
3655796787c9SFilipe Manana 	i = path->slots[0];
3656796787c9SFilipe Manana 	btrfs_release_path(path);
3657796787c9SFilipe Manana 	path->nodes[0] = src;
3658796787c9SFilipe Manana 	path->slots[0] = i;
3659796787c9SFilipe Manana 
3660796787c9SFilipe Manana 	for (; i < nritems; i++) {
3661732d591aSFilipe Manana 		struct btrfs_dir_item *di;
3662eb10d85eSFilipe Manana 		struct btrfs_key key;
3663eb10d85eSFilipe Manana 		int ret;
3664eb10d85eSFilipe Manana 
3665eb10d85eSFilipe Manana 		btrfs_item_key_to_cpu(src, &key, i);
3666eb10d85eSFilipe Manana 
3667339d0354SFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
3668086dcbfaSFilipe Manana 			last_found = true;
3669086dcbfaSFilipe Manana 			break;
3670086dcbfaSFilipe Manana 		}
3671eb10d85eSFilipe Manana 
3672732d591aSFilipe Manana 		di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3673732d591aSFilipe Manana 
3674732d591aSFilipe Manana 		/*
3675732d591aSFilipe Manana 		 * Skip ranges of items that consist only of dir item keys created
3676732d591aSFilipe Manana 		 * in past transactions. However if we find a gap, we must log a
3677732d591aSFilipe Manana 		 * dir index range item for that gap, so that index keys in that
3678732d591aSFilipe Manana 		 * gap are deleted during log replay.
3679732d591aSFilipe Manana 		 */
3680732d591aSFilipe Manana 		if (btrfs_dir_transid(src, di) < trans->transid) {
3681732d591aSFilipe Manana 			if (key.offset > *last_old_dentry_offset + 1) {
3682732d591aSFilipe Manana 				ret = insert_dir_log_key(trans, log, dst_path,
3683732d591aSFilipe Manana 						 ino, *last_old_dentry_offset + 1,
3684732d591aSFilipe Manana 						 key.offset - 1);
3685732d591aSFilipe Manana 				if (ret < 0)
3686732d591aSFilipe Manana 					return ret;
3687732d591aSFilipe Manana 			}
3688732d591aSFilipe Manana 
3689732d591aSFilipe Manana 			*last_old_dentry_offset = key.offset;
3690732d591aSFilipe Manana 			continue;
3691732d591aSFilipe Manana 		}
3692193df624SFilipe Manana 
3693193df624SFilipe Manana 		/* If we logged this dir index item before, we can skip it. */
3694193df624SFilipe Manana 		if (key.offset <= inode->last_dir_index_offset)
3695193df624SFilipe Manana 			continue;
3696193df624SFilipe Manana 
3697eb10d85eSFilipe Manana 		/*
3698eb10d85eSFilipe Manana 		 * We must make sure that when we log a directory entry, the
3699eb10d85eSFilipe Manana 		 * corresponding inode, after log replay, has a matching link
3700eb10d85eSFilipe Manana 		 * count. For example:
3701eb10d85eSFilipe Manana 		 *
3702eb10d85eSFilipe Manana 		 * touch foo
3703eb10d85eSFilipe Manana 		 * mkdir mydir
3704eb10d85eSFilipe Manana 		 * sync
3705eb10d85eSFilipe Manana 		 * ln foo mydir/bar
3706eb10d85eSFilipe Manana 		 * xfs_io -c "fsync" mydir
3707eb10d85eSFilipe Manana 		 * <crash>
3708eb10d85eSFilipe Manana 		 * <mount fs and log replay>
3709eb10d85eSFilipe Manana 		 *
3710eb10d85eSFilipe Manana 		 * Would result in a fsync log that when replayed, our file inode
3711eb10d85eSFilipe Manana 		 * would have a link count of 1, but we get two directory entries
3712eb10d85eSFilipe Manana 		 * pointing to the same inode. After removing one of the names,
3713eb10d85eSFilipe Manana 		 * it would not be possible to remove the other name, which
3714eb10d85eSFilipe Manana 		 * resulted always in stale file handle errors, and would not be
3715eb10d85eSFilipe Manana 		 * possible to rmdir the parent directory, since its i_size could
3716eb10d85eSFilipe Manana 		 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
3717eb10d85eSFilipe Manana 		 * resulting in -ENOTEMPTY errors.
3718eb10d85eSFilipe Manana 		 */
3719086dcbfaSFilipe Manana 		if (!ctx->log_new_dentries) {
3720086dcbfaSFilipe Manana 			struct btrfs_key di_key;
3721086dcbfaSFilipe Manana 
3722086dcbfaSFilipe Manana 			btrfs_dir_item_key_to_cpu(src, di, &di_key);
3723732d591aSFilipe Manana 			if (di_key.type != BTRFS_ROOT_ITEM_KEY)
3724eb10d85eSFilipe Manana 				ctx->log_new_dentries = true;
3725eb10d85eSFilipe Manana 		}
3726eb10d85eSFilipe Manana 
3727086dcbfaSFilipe Manana 		if (batch_size == 0)
3728086dcbfaSFilipe Manana 			batch_start = i;
3729086dcbfaSFilipe Manana 		batch_size++;
3730086dcbfaSFilipe Manana 	}
3731086dcbfaSFilipe Manana 
3732086dcbfaSFilipe Manana 	if (batch_size > 0) {
3733086dcbfaSFilipe Manana 		int ret;
3734086dcbfaSFilipe Manana 
37356afaed53SFilipe Manana 		ret = flush_dir_items_batch(trans, inode, src, dst_path,
3736086dcbfaSFilipe Manana 					    batch_start, batch_size);
3737086dcbfaSFilipe Manana 		if (ret < 0)
3738086dcbfaSFilipe Manana 			return ret;
3739086dcbfaSFilipe Manana 	}
3740086dcbfaSFilipe Manana 
3741086dcbfaSFilipe Manana 	return last_found ? 1 : 0;
3742eb10d85eSFilipe Manana }
3743eb10d85eSFilipe Manana 
3744e02119d5SChris Mason /*
3745e02119d5SChris Mason  * log all the items included in the current transaction for a given
3746e02119d5SChris Mason  * directory.  This also creates the range items in the log tree required
3747e02119d5SChris Mason  * to replay anything deleted before the fsync
3748e02119d5SChris Mason  */
3749e02119d5SChris Mason static noinline int log_dir_items(struct btrfs_trans_handle *trans,
375090d04510SFilipe Manana 			  struct btrfs_inode *inode,
3751e02119d5SChris Mason 			  struct btrfs_path *path,
3752339d0354SFilipe Manana 			  struct btrfs_path *dst_path,
37532f2ff0eeSFilipe Manana 			  struct btrfs_log_ctx *ctx,
3754e02119d5SChris Mason 			  u64 min_offset, u64 *last_offset_ret)
3755e02119d5SChris Mason {
3756e02119d5SChris Mason 	struct btrfs_key min_key;
375790d04510SFilipe Manana 	struct btrfs_root *root = inode->root;
3758e02119d5SChris Mason 	struct btrfs_root *log = root->log_root;
3759e02119d5SChris Mason 	int ret;
3760732d591aSFilipe Manana 	u64 last_old_dentry_offset = min_offset - 1;
3761e02119d5SChris Mason 	u64 last_offset = (u64)-1;
3762684a5773SNikolay Borisov 	u64 ino = btrfs_ino(inode);
3763e02119d5SChris Mason 
376433345d01SLi Zefan 	min_key.objectid = ino;
3765339d0354SFilipe Manana 	min_key.type = BTRFS_DIR_INDEX_KEY;
3766e02119d5SChris Mason 	min_key.offset = min_offset;
3767e02119d5SChris Mason 
37686174d3cbSFilipe David Borba Manana 	ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3769e02119d5SChris Mason 
3770e02119d5SChris Mason 	/*
3771e02119d5SChris Mason 	 * we didn't find anything from this transaction, see if there
3772e02119d5SChris Mason 	 * is anything at all
3773e02119d5SChris Mason 	 */
3774339d0354SFilipe Manana 	if (ret != 0 || min_key.objectid != ino ||
3775339d0354SFilipe Manana 	    min_key.type != BTRFS_DIR_INDEX_KEY) {
377633345d01SLi Zefan 		min_key.objectid = ino;
3777339d0354SFilipe Manana 		min_key.type = BTRFS_DIR_INDEX_KEY;
3778e02119d5SChris Mason 		min_key.offset = (u64)-1;
3779b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3780e02119d5SChris Mason 		ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3781e02119d5SChris Mason 		if (ret < 0) {
3782b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3783e02119d5SChris Mason 			return ret;
3784e02119d5SChris Mason 		}
3785339d0354SFilipe Manana 		ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3786e02119d5SChris Mason 
3787e02119d5SChris Mason 		/* if ret == 0 there are items for this type,
3788e02119d5SChris Mason 		 * create a range to tell us the last key of this type.
3789e02119d5SChris Mason 		 * otherwise, there are no items in this directory after
3790e02119d5SChris Mason 		 * *min_offset, and we create a range to indicate that.
3791e02119d5SChris Mason 		 */
3792e02119d5SChris Mason 		if (ret == 0) {
3793e02119d5SChris Mason 			struct btrfs_key tmp;
3794732d591aSFilipe Manana 
3795e02119d5SChris Mason 			btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3796e02119d5SChris Mason 					      path->slots[0]);
3797339d0354SFilipe Manana 			if (tmp.type == BTRFS_DIR_INDEX_KEY)
3798732d591aSFilipe Manana 				last_old_dentry_offset = tmp.offset;
3799235e1c7bSFilipe Manana 		} else if (ret > 0) {
3800235e1c7bSFilipe Manana 			ret = 0;
3801e02119d5SChris Mason 		}
38026d3d970bSFilipe Manana 
3803e02119d5SChris Mason 		goto done;
3804e02119d5SChris Mason 	}
3805e02119d5SChris Mason 
3806e02119d5SChris Mason 	/* go backward to find any previous key */
3807339d0354SFilipe Manana 	ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3808e02119d5SChris Mason 	if (ret == 0) {
3809e02119d5SChris Mason 		struct btrfs_key tmp;
3810a450a4afSFilipe Manana 
3811e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3812a450a4afSFilipe Manana 		/*
3813a450a4afSFilipe Manana 		 * The dir index key before the first one we found that needs to
3814a450a4afSFilipe Manana 		 * be logged might be in a previous leaf, and there might be a
3815a450a4afSFilipe Manana 		 * gap between these keys, meaning that we had deletions that
3816a450a4afSFilipe Manana 		 * happened. So the key range item we log (key type
3817a450a4afSFilipe Manana 		 * BTRFS_DIR_LOG_INDEX_KEY) must cover a range that starts at the
3818a450a4afSFilipe Manana 		 * previous key's offset plus 1, so that those deletes are replayed.
3819a450a4afSFilipe Manana 		 */
3820a450a4afSFilipe Manana 		if (tmp.type == BTRFS_DIR_INDEX_KEY)
3821732d591aSFilipe Manana 			last_old_dentry_offset = tmp.offset;
38226d3d970bSFilipe Manana 	} else if (ret < 0) {
38236d3d970bSFilipe Manana 		goto done;
3824e02119d5SChris Mason 	}
38256d3d970bSFilipe Manana 
3826b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3827e02119d5SChris Mason 
38282cc83342SJosef Bacik 	/*
38298bb6898dSFilipe Manana 	 * Find the first key from this transaction again or the one we were at
38308bb6898dSFilipe Manana 	 * in the loop below in case we had to reschedule. We may be logging the
38318bb6898dSFilipe Manana 	 * directory without holding its VFS lock, which happen when logging new
38328bb6898dSFilipe Manana 	 * dentries (through log_new_dir_dentries()) or in some cases when we
38338bb6898dSFilipe Manana 	 * need to log the parent directory of an inode. This means a dir index
38348bb6898dSFilipe Manana 	 * key might be deleted from the inode's root, and therefore we may not
38358bb6898dSFilipe Manana 	 * find it anymore. If we can't find it, just move to the next key. We
38368bb6898dSFilipe Manana 	 * can not bail out and ignore, because if we do that we will simply
38378bb6898dSFilipe Manana 	 * not log dir index keys that come after the one that was just deleted
38388bb6898dSFilipe Manana 	 * and we can end up logging a dir index range that ends at (u64)-1
38398bb6898dSFilipe Manana 	 * (@last_offset is initialized to that), resulting in removing dir
38408bb6898dSFilipe Manana 	 * entries we should not remove at log replay time.
38412cc83342SJosef Bacik 	 */
3842bb56f02fSFilipe Manana search:
3843e02119d5SChris Mason 	ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3844235e1c7bSFilipe Manana 	if (ret > 0) {
38458bb6898dSFilipe Manana 		ret = btrfs_next_item(root, path);
3846235e1c7bSFilipe Manana 		if (ret > 0) {
3847235e1c7bSFilipe Manana 			/* There are no more keys in the inode's root. */
3848235e1c7bSFilipe Manana 			ret = 0;
3849235e1c7bSFilipe Manana 			goto done;
3850235e1c7bSFilipe Manana 		}
3851235e1c7bSFilipe Manana 	}
38526d3d970bSFilipe Manana 	if (ret < 0)
3853e02119d5SChris Mason 		goto done;
3854e02119d5SChris Mason 
3855e02119d5SChris Mason 	/*
3856e02119d5SChris Mason 	 * we have a block from this transaction, log every item in it
3857e02119d5SChris Mason 	 * from our directory
3858e02119d5SChris Mason 	 */
3859e02119d5SChris Mason 	while (1) {
3860732d591aSFilipe Manana 		ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx,
3861732d591aSFilipe Manana 					     &last_old_dentry_offset);
3862eb10d85eSFilipe Manana 		if (ret != 0) {
3863235e1c7bSFilipe Manana 			if (ret > 0)
3864235e1c7bSFilipe Manana 				ret = 0;
38654a500fd1SYan, Zheng 			goto done;
38664a500fd1SYan, Zheng 		}
3867eb10d85eSFilipe Manana 		path->slots[0] = btrfs_header_nritems(path->nodes[0]);
3868e02119d5SChris Mason 
3869e02119d5SChris Mason 		/*
3870e02119d5SChris Mason 		 * look ahead to the next item and see if it is also
3871e02119d5SChris Mason 		 * from this directory and from this transaction
3872e02119d5SChris Mason 		 */
3873e02119d5SChris Mason 		ret = btrfs_next_leaf(root, path);
387480c0b421SLiu Bo 		if (ret) {
3875235e1c7bSFilipe Manana 			if (ret == 1) {
3876e02119d5SChris Mason 				last_offset = (u64)-1;
3877235e1c7bSFilipe Manana 				ret = 0;
3878235e1c7bSFilipe Manana 			}
3879e02119d5SChris Mason 			goto done;
3880e02119d5SChris Mason 		}
3881eb10d85eSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
3882339d0354SFilipe Manana 		if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
3883e02119d5SChris Mason 			last_offset = (u64)-1;
3884e02119d5SChris Mason 			goto done;
3885e02119d5SChris Mason 		}
3886e02119d5SChris Mason 		if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3887a450a4afSFilipe Manana 			/*
3888a450a4afSFilipe Manana 			 * The next leaf was not changed in the current transaction
3889a450a4afSFilipe Manana 			 * and has at least one dir index key.
3890a450a4afSFilipe Manana 			 * We check for the next key because there might have been
3891a450a4afSFilipe Manana 			 * one or more deletions between the last key we logged and
3892a450a4afSFilipe Manana 			 * that next key. So the key range item we log (key type
3893a450a4afSFilipe Manana 			 * BTRFS_DIR_LOG_INDEX_KEY) must end at the next key's
3894a450a4afSFilipe Manana 			 * offset minus 1, so that those deletes are replayed.
3895a450a4afSFilipe Manana 			 */
3896a450a4afSFilipe Manana 			last_offset = min_key.offset - 1;
3897e02119d5SChris Mason 			goto done;
3898e02119d5SChris Mason 		}
3899eb10d85eSFilipe Manana 		if (need_resched()) {
3900eb10d85eSFilipe Manana 			btrfs_release_path(path);
3901eb10d85eSFilipe Manana 			cond_resched();
3902eb10d85eSFilipe Manana 			goto search;
3903eb10d85eSFilipe Manana 		}
3904e02119d5SChris Mason 	}
3905e02119d5SChris Mason done:
3906b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3907b3b4aa74SDavid Sterba 	btrfs_release_path(dst_path);
3908e02119d5SChris Mason 
3909235e1c7bSFilipe Manana 	if (ret == 0) {
39104a500fd1SYan, Zheng 		*last_offset_ret = last_offset;
39114a500fd1SYan, Zheng 		/*
3912732d591aSFilipe Manana 		 * In case the leaf was changed in the current transaction but
3913732d591aSFilipe Manana 		 * all its dir items are from a past transaction, the last item
3914732d591aSFilipe Manana 		 * in the leaf is a dir item and there's no gap between that last
3915732d591aSFilipe Manana 		 * dir item and the first one on the next leaf (which did not
3916732d591aSFilipe Manana 		 * change in the current transaction), then we don't need to log
3917732d591aSFilipe Manana 		 * a range, last_old_dentry_offset is == to last_offset.
39184a500fd1SYan, Zheng 		 */
3919732d591aSFilipe Manana 		ASSERT(last_old_dentry_offset <= last_offset);
3920235e1c7bSFilipe Manana 		if (last_old_dentry_offset < last_offset)
3921732d591aSFilipe Manana 			ret = insert_dir_log_key(trans, log, path, ino,
3922732d591aSFilipe Manana 						 last_old_dentry_offset + 1,
3923339d0354SFilipe Manana 						 last_offset);
39244a500fd1SYan, Zheng 	}
3925235e1c7bSFilipe Manana 
3926235e1c7bSFilipe Manana 	return ret;
3927e02119d5SChris Mason }
3928e02119d5SChris Mason 
3929e02119d5SChris Mason /*
3930193df624SFilipe Manana  * If the inode was logged before and it was evicted, then its
3931193df624SFilipe Manana  * last_dir_index_offset is (u64)-1, so we don't the value of the last index
3932193df624SFilipe Manana  * key offset. If that's the case, search for it and update the inode. This
3933193df624SFilipe Manana  * is to avoid lookups in the log tree every time we try to insert a dir index
3934193df624SFilipe Manana  * key from a leaf changed in the current transaction, and to allow us to always
3935193df624SFilipe Manana  * do batch insertions of dir index keys.
3936193df624SFilipe Manana  */
3937193df624SFilipe Manana static int update_last_dir_index_offset(struct btrfs_inode *inode,
3938193df624SFilipe Manana 					struct btrfs_path *path,
3939193df624SFilipe Manana 					const struct btrfs_log_ctx *ctx)
3940193df624SFilipe Manana {
3941193df624SFilipe Manana 	const u64 ino = btrfs_ino(inode);
3942193df624SFilipe Manana 	struct btrfs_key key;
3943193df624SFilipe Manana 	int ret;
3944193df624SFilipe Manana 
3945193df624SFilipe Manana 	lockdep_assert_held(&inode->log_mutex);
3946193df624SFilipe Manana 
3947193df624SFilipe Manana 	if (inode->last_dir_index_offset != (u64)-1)
3948193df624SFilipe Manana 		return 0;
3949193df624SFilipe Manana 
3950193df624SFilipe Manana 	if (!ctx->logged_before) {
3951193df624SFilipe Manana 		inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
3952193df624SFilipe Manana 		return 0;
3953193df624SFilipe Manana 	}
3954193df624SFilipe Manana 
3955193df624SFilipe Manana 	key.objectid = ino;
3956193df624SFilipe Manana 	key.type = BTRFS_DIR_INDEX_KEY;
3957193df624SFilipe Manana 	key.offset = (u64)-1;
3958193df624SFilipe Manana 
3959193df624SFilipe Manana 	ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3960193df624SFilipe Manana 	/*
3961193df624SFilipe Manana 	 * An error happened or we actually have an index key with an offset
3962193df624SFilipe Manana 	 * value of (u64)-1. Bail out, we're done.
3963193df624SFilipe Manana 	 */
3964193df624SFilipe Manana 	if (ret <= 0)
3965193df624SFilipe Manana 		goto out;
3966193df624SFilipe Manana 
3967193df624SFilipe Manana 	ret = 0;
3968193df624SFilipe Manana 	inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
3969193df624SFilipe Manana 
3970193df624SFilipe Manana 	/*
3971193df624SFilipe Manana 	 * No dir index items, bail out and leave last_dir_index_offset with
3972193df624SFilipe Manana 	 * the value right before the first valid index value.
3973193df624SFilipe Manana 	 */
3974193df624SFilipe Manana 	if (path->slots[0] == 0)
3975193df624SFilipe Manana 		goto out;
3976193df624SFilipe Manana 
3977193df624SFilipe Manana 	/*
3978193df624SFilipe Manana 	 * btrfs_search_slot() left us at one slot beyond the slot with the last
3979193df624SFilipe Manana 	 * index key, or beyond the last key of the directory that is not an
3980193df624SFilipe Manana 	 * index key. If we have an index key before, set last_dir_index_offset
3981193df624SFilipe Manana 	 * to its offset value, otherwise leave it with a value right before the
3982193df624SFilipe Manana 	 * first valid index value, as it means we have an empty directory.
3983193df624SFilipe Manana 	 */
3984193df624SFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3985193df624SFilipe Manana 	if (key.objectid == ino && key.type == BTRFS_DIR_INDEX_KEY)
3986193df624SFilipe Manana 		inode->last_dir_index_offset = key.offset;
3987193df624SFilipe Manana 
3988193df624SFilipe Manana out:
3989193df624SFilipe Manana 	btrfs_release_path(path);
3990193df624SFilipe Manana 
3991193df624SFilipe Manana 	return ret;
3992193df624SFilipe Manana }
3993193df624SFilipe Manana 
3994193df624SFilipe Manana /*
3995e02119d5SChris Mason  * logging directories is very similar to logging inodes, We find all the items
3996e02119d5SChris Mason  * from the current transaction and write them to the log.
3997e02119d5SChris Mason  *
3998e02119d5SChris Mason  * The recovery code scans the directory in the subvolume, and if it finds a
3999e02119d5SChris Mason  * key in the range logged that is not present in the log tree, then it means
4000e02119d5SChris Mason  * that dir entry was unlinked during the transaction.
4001e02119d5SChris Mason  *
4002e02119d5SChris Mason  * In order for that scan to work, we must include one key smaller than
4003e02119d5SChris Mason  * the smallest logged by this transaction and one key larger than the largest
4004e02119d5SChris Mason  * key logged by this transaction.
4005e02119d5SChris Mason  */
4006e02119d5SChris Mason static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
400790d04510SFilipe Manana 			  struct btrfs_inode *inode,
4008e02119d5SChris Mason 			  struct btrfs_path *path,
40092f2ff0eeSFilipe Manana 			  struct btrfs_path *dst_path,
40102f2ff0eeSFilipe Manana 			  struct btrfs_log_ctx *ctx)
4011e02119d5SChris Mason {
4012e02119d5SChris Mason 	u64 min_key;
4013e02119d5SChris Mason 	u64 max_key;
4014e02119d5SChris Mason 	int ret;
4015e02119d5SChris Mason 
4016193df624SFilipe Manana 	ret = update_last_dir_index_offset(inode, path, ctx);
4017193df624SFilipe Manana 	if (ret)
4018193df624SFilipe Manana 		return ret;
4019193df624SFilipe Manana 
4020732d591aSFilipe Manana 	min_key = BTRFS_DIR_START_INDEX;
4021e02119d5SChris Mason 	max_key = 0;
4022dc287224SFilipe Manana 
4023e02119d5SChris Mason 	while (1) {
4024339d0354SFilipe Manana 		ret = log_dir_items(trans, inode, path, dst_path,
4025dbf39ea4SNikolay Borisov 				ctx, min_key, &max_key);
40264a500fd1SYan, Zheng 		if (ret)
40274a500fd1SYan, Zheng 			return ret;
4028e02119d5SChris Mason 		if (max_key == (u64)-1)
4029e02119d5SChris Mason 			break;
4030e02119d5SChris Mason 		min_key = max_key + 1;
4031e02119d5SChris Mason 	}
4032e02119d5SChris Mason 
4033e02119d5SChris Mason 	return 0;
4034e02119d5SChris Mason }
4035e02119d5SChris Mason 
4036e02119d5SChris Mason /*
4037e02119d5SChris Mason  * a helper function to drop items from the log before we relog an
4038e02119d5SChris Mason  * inode.  max_key_type indicates the highest item type to remove.
4039e02119d5SChris Mason  * This cannot be run for file data extents because it does not
4040e02119d5SChris Mason  * free the extents they point to.
4041e02119d5SChris Mason  */
404288e221cdSFilipe Manana static int drop_inode_items(struct btrfs_trans_handle *trans,
4043e02119d5SChris Mason 				  struct btrfs_root *log,
4044e02119d5SChris Mason 				  struct btrfs_path *path,
404588e221cdSFilipe Manana 				  struct btrfs_inode *inode,
404688e221cdSFilipe Manana 				  int max_key_type)
4047e02119d5SChris Mason {
4048e02119d5SChris Mason 	int ret;
4049e02119d5SChris Mason 	struct btrfs_key key;
4050e02119d5SChris Mason 	struct btrfs_key found_key;
405118ec90d6SJosef Bacik 	int start_slot;
4052e02119d5SChris Mason 
405388e221cdSFilipe Manana 	key.objectid = btrfs_ino(inode);
4054e02119d5SChris Mason 	key.type = max_key_type;
4055e02119d5SChris Mason 	key.offset = (u64)-1;
4056e02119d5SChris Mason 
4057e02119d5SChris Mason 	while (1) {
4058e02119d5SChris Mason 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
40593650860bSJosef Bacik 		BUG_ON(ret == 0); /* Logic error */
40604a500fd1SYan, Zheng 		if (ret < 0)
4061e02119d5SChris Mason 			break;
4062e02119d5SChris Mason 
4063e02119d5SChris Mason 		if (path->slots[0] == 0)
4064e02119d5SChris Mason 			break;
4065e02119d5SChris Mason 
4066e02119d5SChris Mason 		path->slots[0]--;
4067e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4068e02119d5SChris Mason 				      path->slots[0]);
4069e02119d5SChris Mason 
407088e221cdSFilipe Manana 		if (found_key.objectid != key.objectid)
4071e02119d5SChris Mason 			break;
4072e02119d5SChris Mason 
407318ec90d6SJosef Bacik 		found_key.offset = 0;
407418ec90d6SJosef Bacik 		found_key.type = 0;
4075fdf8d595SAnand Jain 		ret = btrfs_bin_search(path->nodes[0], 0, &found_key, &start_slot);
4076cbca7d59SFilipe Manana 		if (ret < 0)
4077cbca7d59SFilipe Manana 			break;
407818ec90d6SJosef Bacik 
407918ec90d6SJosef Bacik 		ret = btrfs_del_items(trans, log, path, start_slot,
408018ec90d6SJosef Bacik 				      path->slots[0] - start_slot + 1);
408118ec90d6SJosef Bacik 		/*
408218ec90d6SJosef Bacik 		 * If start slot isn't 0 then we don't need to re-search, we've
408318ec90d6SJosef Bacik 		 * found the last guy with the objectid in this tree.
408418ec90d6SJosef Bacik 		 */
408518ec90d6SJosef Bacik 		if (ret || start_slot != 0)
408665a246c5STsutomu Itoh 			break;
4087b3b4aa74SDavid Sterba 		btrfs_release_path(path);
4088e02119d5SChris Mason 	}
4089b3b4aa74SDavid Sterba 	btrfs_release_path(path);
40905bdbeb21SJosef Bacik 	if (ret > 0)
40915bdbeb21SJosef Bacik 		ret = 0;
40924a500fd1SYan, Zheng 	return ret;
4093e02119d5SChris Mason }
4094e02119d5SChris Mason 
40958a2b3da1SFilipe Manana static int truncate_inode_items(struct btrfs_trans_handle *trans,
40968a2b3da1SFilipe Manana 				struct btrfs_root *log_root,
40978a2b3da1SFilipe Manana 				struct btrfs_inode *inode,
40988a2b3da1SFilipe Manana 				u64 new_size, u32 min_type)
40998a2b3da1SFilipe Manana {
4100d9ac19c3SJosef Bacik 	struct btrfs_truncate_control control = {
4101d9ac19c3SJosef Bacik 		.new_size = new_size,
4102487e81d2SJosef Bacik 		.ino = btrfs_ino(inode),
4103d9ac19c3SJosef Bacik 		.min_type = min_type,
41045caa490eSJosef Bacik 		.skip_ref_updates = true,
4105d9ac19c3SJosef Bacik 	};
41068a2b3da1SFilipe Manana 
41078697b8f8SJosef Bacik 	return btrfs_truncate_inode_items(trans, log_root, &control);
41088a2b3da1SFilipe Manana }
41098a2b3da1SFilipe Manana 
411094edf4aeSJosef Bacik static void fill_inode_item(struct btrfs_trans_handle *trans,
411194edf4aeSJosef Bacik 			    struct extent_buffer *leaf,
411294edf4aeSJosef Bacik 			    struct btrfs_inode_item *item,
41131a4bcf47SFilipe Manana 			    struct inode *inode, int log_inode_only,
41141a4bcf47SFilipe Manana 			    u64 logged_isize)
411594edf4aeSJosef Bacik {
41160b1c6ccaSJosef Bacik 	struct btrfs_map_token token;
411777eea05eSBoris Burkov 	u64 flags;
411894edf4aeSJosef Bacik 
4119c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
412094edf4aeSJosef Bacik 
412194edf4aeSJosef Bacik 	if (log_inode_only) {
412294edf4aeSJosef Bacik 		/* set the generation to zero so the recover code
412394edf4aeSJosef Bacik 		 * can tell the difference between an logging
412494edf4aeSJosef Bacik 		 * just to say 'this inode exists' and a logging
412594edf4aeSJosef Bacik 		 * to say 'update this inode with these values'
412694edf4aeSJosef Bacik 		 */
4127cc4c13d5SDavid Sterba 		btrfs_set_token_inode_generation(&token, item, 0);
4128cc4c13d5SDavid Sterba 		btrfs_set_token_inode_size(&token, item, logged_isize);
412994edf4aeSJosef Bacik 	} else {
4130cc4c13d5SDavid Sterba 		btrfs_set_token_inode_generation(&token, item,
4131cc4c13d5SDavid Sterba 						 BTRFS_I(inode)->generation);
4132cc4c13d5SDavid Sterba 		btrfs_set_token_inode_size(&token, item, inode->i_size);
413394edf4aeSJosef Bacik 	}
413494edf4aeSJosef Bacik 
4135cc4c13d5SDavid Sterba 	btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4136cc4c13d5SDavid Sterba 	btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4137cc4c13d5SDavid Sterba 	btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4138cc4c13d5SDavid Sterba 	btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
41390b1c6ccaSJosef Bacik 
4140cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_sec(&token, &item->atime,
4141cc4c13d5SDavid Sterba 				     inode->i_atime.tv_sec);
4142cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_nsec(&token, &item->atime,
4143cc4c13d5SDavid Sterba 				      inode->i_atime.tv_nsec);
41440b1c6ccaSJosef Bacik 
4145cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_sec(&token, &item->mtime,
4146cc4c13d5SDavid Sterba 				     inode->i_mtime.tv_sec);
4147cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_nsec(&token, &item->mtime,
4148cc4c13d5SDavid Sterba 				      inode->i_mtime.tv_nsec);
41490b1c6ccaSJosef Bacik 
4150cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_sec(&token, &item->ctime,
4151cc4c13d5SDavid Sterba 				     inode->i_ctime.tv_sec);
4152cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_nsec(&token, &item->ctime,
4153cc4c13d5SDavid Sterba 				      inode->i_ctime.tv_nsec);
41540b1c6ccaSJosef Bacik 
4155e593e54eSFilipe Manana 	/*
4156e593e54eSFilipe Manana 	 * We do not need to set the nbytes field, in fact during a fast fsync
4157e593e54eSFilipe Manana 	 * its value may not even be correct, since a fast fsync does not wait
4158e593e54eSFilipe Manana 	 * for ordered extent completion, which is where we update nbytes, it
4159e593e54eSFilipe Manana 	 * only waits for writeback to complete. During log replay as we find
4160e593e54eSFilipe Manana 	 * file extent items and replay them, we adjust the nbytes field of the
4161e593e54eSFilipe Manana 	 * inode item in subvolume tree as needed (see overwrite_item()).
4162e593e54eSFilipe Manana 	 */
41630b1c6ccaSJosef Bacik 
4164cc4c13d5SDavid Sterba 	btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4165cc4c13d5SDavid Sterba 	btrfs_set_token_inode_transid(&token, item, trans->transid);
4166cc4c13d5SDavid Sterba 	btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
416777eea05eSBoris Burkov 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
416877eea05eSBoris Burkov 					  BTRFS_I(inode)->ro_flags);
416977eea05eSBoris Burkov 	btrfs_set_token_inode_flags(&token, item, flags);
4170cc4c13d5SDavid Sterba 	btrfs_set_token_inode_block_group(&token, item, 0);
417194edf4aeSJosef Bacik }
417294edf4aeSJosef Bacik 
4173a95249b3SJosef Bacik static int log_inode_item(struct btrfs_trans_handle *trans,
4174a95249b3SJosef Bacik 			  struct btrfs_root *log, struct btrfs_path *path,
41752ac691d8SFilipe Manana 			  struct btrfs_inode *inode, bool inode_item_dropped)
4176a95249b3SJosef Bacik {
4177a95249b3SJosef Bacik 	struct btrfs_inode_item *inode_item;
4178a95249b3SJosef Bacik 	int ret;
4179a95249b3SJosef Bacik 
41802ac691d8SFilipe Manana 	/*
41812ac691d8SFilipe Manana 	 * If we are doing a fast fsync and the inode was logged before in the
41822ac691d8SFilipe Manana 	 * current transaction, then we know the inode was previously logged and
41832ac691d8SFilipe Manana 	 * it exists in the log tree. For performance reasons, in this case use
41842ac691d8SFilipe Manana 	 * btrfs_search_slot() directly with ins_len set to 0 so that we never
41852ac691d8SFilipe Manana 	 * attempt a write lock on the leaf's parent, which adds unnecessary lock
41862ac691d8SFilipe Manana 	 * contention in case there are concurrent fsyncs for other inodes of the
41872ac691d8SFilipe Manana 	 * same subvolume. Using btrfs_insert_empty_item() when the inode item
41882ac691d8SFilipe Manana 	 * already exists can also result in unnecessarily splitting a leaf.
41892ac691d8SFilipe Manana 	 */
41902ac691d8SFilipe Manana 	if (!inode_item_dropped && inode->logged_trans == trans->transid) {
41912ac691d8SFilipe Manana 		ret = btrfs_search_slot(trans, log, &inode->location, path, 0, 1);
41922ac691d8SFilipe Manana 		ASSERT(ret <= 0);
41932ac691d8SFilipe Manana 		if (ret > 0)
41942ac691d8SFilipe Manana 			ret = -ENOENT;
41952ac691d8SFilipe Manana 	} else {
41962ac691d8SFilipe Manana 		/*
41972ac691d8SFilipe Manana 		 * This means it is the first fsync in the current transaction,
41982ac691d8SFilipe Manana 		 * so the inode item is not in the log and we need to insert it.
41992ac691d8SFilipe Manana 		 * We can never get -EEXIST because we are only called for a fast
42002ac691d8SFilipe Manana 		 * fsync and in case an inode eviction happens after the inode was
42012ac691d8SFilipe Manana 		 * logged before in the current transaction, when we load again
42022ac691d8SFilipe Manana 		 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
42032ac691d8SFilipe Manana 		 * flags and set ->logged_trans to 0.
42042ac691d8SFilipe Manana 		 */
42052ac691d8SFilipe Manana 		ret = btrfs_insert_empty_item(trans, log, path, &inode->location,
42062ac691d8SFilipe Manana 					      sizeof(*inode_item));
42072ac691d8SFilipe Manana 		ASSERT(ret != -EEXIST);
42082ac691d8SFilipe Manana 	}
42092ac691d8SFilipe Manana 	if (ret)
4210a95249b3SJosef Bacik 		return ret;
4211a95249b3SJosef Bacik 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4212a95249b3SJosef Bacik 				    struct btrfs_inode_item);
42136d889a3bSNikolay Borisov 	fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
42146d889a3bSNikolay Borisov 			0, 0);
4215a95249b3SJosef Bacik 	btrfs_release_path(path);
4216a95249b3SJosef Bacik 	return 0;
4217a95249b3SJosef Bacik }
4218a95249b3SJosef Bacik 
421940e046acSFilipe Manana static int log_csums(struct btrfs_trans_handle *trans,
42203ebac17cSFilipe Manana 		     struct btrfs_inode *inode,
422140e046acSFilipe Manana 		     struct btrfs_root *log_root,
422240e046acSFilipe Manana 		     struct btrfs_ordered_sum *sums)
422340e046acSFilipe Manana {
4224e289f03eSFilipe Manana 	const u64 lock_end = sums->bytenr + sums->len - 1;
4225e289f03eSFilipe Manana 	struct extent_state *cached_state = NULL;
422640e046acSFilipe Manana 	int ret;
422740e046acSFilipe Manana 
422840e046acSFilipe Manana 	/*
42293ebac17cSFilipe Manana 	 * If this inode was not used for reflink operations in the current
42303ebac17cSFilipe Manana 	 * transaction with new extents, then do the fast path, no need to
42313ebac17cSFilipe Manana 	 * worry about logging checksum items with overlapping ranges.
42323ebac17cSFilipe Manana 	 */
42333ebac17cSFilipe Manana 	if (inode->last_reflink_trans < trans->transid)
42343ebac17cSFilipe Manana 		return btrfs_csum_file_blocks(trans, log_root, sums);
42353ebac17cSFilipe Manana 
42363ebac17cSFilipe Manana 	/*
4237e289f03eSFilipe Manana 	 * Serialize logging for checksums. This is to avoid racing with the
4238e289f03eSFilipe Manana 	 * same checksum being logged by another task that is logging another
4239e289f03eSFilipe Manana 	 * file which happens to refer to the same extent as well. Such races
4240e289f03eSFilipe Manana 	 * can leave checksum items in the log with overlapping ranges.
4241e289f03eSFilipe Manana 	 */
4242570eb97bSJosef Bacik 	ret = lock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4243570eb97bSJosef Bacik 			  &cached_state);
4244e289f03eSFilipe Manana 	if (ret)
4245e289f03eSFilipe Manana 		return ret;
4246e289f03eSFilipe Manana 	/*
424740e046acSFilipe Manana 	 * Due to extent cloning, we might have logged a csum item that covers a
424840e046acSFilipe Manana 	 * subrange of a cloned extent, and later we can end up logging a csum
424940e046acSFilipe Manana 	 * item for a larger subrange of the same extent or the entire range.
425040e046acSFilipe Manana 	 * This would leave csum items in the log tree that cover the same range
425140e046acSFilipe Manana 	 * and break the searches for checksums in the log tree, resulting in
425240e046acSFilipe Manana 	 * some checksums missing in the fs/subvolume tree. So just delete (or
425340e046acSFilipe Manana 	 * trim and adjust) any existing csum items in the log for this range.
425440e046acSFilipe Manana 	 */
425540e046acSFilipe Manana 	ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
4256e289f03eSFilipe Manana 	if (!ret)
4257e289f03eSFilipe Manana 		ret = btrfs_csum_file_blocks(trans, log_root, sums);
425840e046acSFilipe Manana 
4259570eb97bSJosef Bacik 	unlock_extent(&log_root->log_csum_range, sums->bytenr, lock_end,
4260e289f03eSFilipe Manana 		      &cached_state);
4261e289f03eSFilipe Manana 
4262e289f03eSFilipe Manana 	return ret;
426340e046acSFilipe Manana }
426440e046acSFilipe Manana 
426531ff1cd2SChris Mason static noinline int copy_items(struct btrfs_trans_handle *trans,
426644d70e19SNikolay Borisov 			       struct btrfs_inode *inode,
426731ff1cd2SChris Mason 			       struct btrfs_path *dst_path,
42680e56315cSFilipe Manana 			       struct btrfs_path *src_path,
42691a4bcf47SFilipe Manana 			       int start_slot, int nr, int inode_only,
42701a4bcf47SFilipe Manana 			       u64 logged_isize)
427131ff1cd2SChris Mason {
427244d70e19SNikolay Borisov 	struct btrfs_root *log = inode->root->log_root;
427331ff1cd2SChris Mason 	struct btrfs_file_extent_item *extent;
4274796787c9SFilipe Manana 	struct extent_buffer *src;
42757f30c072SFilipe Manana 	int ret = 0;
427631ff1cd2SChris Mason 	struct btrfs_key *ins_keys;
427731ff1cd2SChris Mason 	u32 *ins_sizes;
4278b7ef5f3aSFilipe Manana 	struct btrfs_item_batch batch;
427931ff1cd2SChris Mason 	char *ins_data;
428031ff1cd2SChris Mason 	int i;
42817f30c072SFilipe Manana 	int dst_index;
42827f30c072SFilipe Manana 	const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
42837f30c072SFilipe Manana 	const u64 i_size = i_size_read(&inode->vfs_inode);
4284d20f7043SChris Mason 
4285796787c9SFilipe Manana 	/*
4286796787c9SFilipe Manana 	 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4287796787c9SFilipe Manana 	 * use the clone. This is because otherwise we would be changing the log
4288796787c9SFilipe Manana 	 * tree, to insert items from the subvolume tree or insert csum items,
4289796787c9SFilipe Manana 	 * while holding a read lock on a leaf from the subvolume tree, which
4290796787c9SFilipe Manana 	 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4291796787c9SFilipe Manana 	 *
4292796787c9SFilipe Manana 	 * 1) Modifying the log tree triggers an extent buffer allocation while
4293796787c9SFilipe Manana 	 *    holding a write lock on a parent extent buffer from the log tree.
4294796787c9SFilipe Manana 	 *    Allocating the pages for an extent buffer, or the extent buffer
4295796787c9SFilipe Manana 	 *    struct, can trigger inode eviction and finally the inode eviction
4296796787c9SFilipe Manana 	 *    will trigger a release/remove of a delayed node, which requires
4297796787c9SFilipe Manana 	 *    taking the delayed node's mutex;
4298796787c9SFilipe Manana 	 *
4299796787c9SFilipe Manana 	 * 2) Allocating a metadata extent for a log tree can trigger the async
4300796787c9SFilipe Manana 	 *    reclaim thread and make us wait for it to release enough space and
4301796787c9SFilipe Manana 	 *    unblock our reservation ticket. The reclaim thread can start
4302796787c9SFilipe Manana 	 *    flushing delayed items, and that in turn results in the need to
4303796787c9SFilipe Manana 	 *    lock delayed node mutexes and in the need to write lock extent
4304796787c9SFilipe Manana 	 *    buffers of a subvolume tree - all this while holding a write lock
4305796787c9SFilipe Manana 	 *    on the parent extent buffer in the log tree.
4306796787c9SFilipe Manana 	 *
4307796787c9SFilipe Manana 	 * So one task in scenario 1) running in parallel with another task in
4308796787c9SFilipe Manana 	 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4309796787c9SFilipe Manana 	 * node mutex while having a read lock on a leaf from the subvolume,
4310796787c9SFilipe Manana 	 * while the other is holding the delayed node's mutex and wants to
4311796787c9SFilipe Manana 	 * write lock the same subvolume leaf for flushing delayed items.
4312796787c9SFilipe Manana 	 */
4313796787c9SFilipe Manana 	src = btrfs_clone_extent_buffer(src_path->nodes[0]);
4314796787c9SFilipe Manana 	if (!src)
4315796787c9SFilipe Manana 		return -ENOMEM;
4316796787c9SFilipe Manana 
4317796787c9SFilipe Manana 	i = src_path->slots[0];
4318796787c9SFilipe Manana 	btrfs_release_path(src_path);
4319796787c9SFilipe Manana 	src_path->nodes[0] = src;
4320796787c9SFilipe Manana 	src_path->slots[0] = i;
4321796787c9SFilipe Manana 
432231ff1cd2SChris Mason 	ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
432331ff1cd2SChris Mason 			   nr * sizeof(u32), GFP_NOFS);
43242a29edc6Sliubo 	if (!ins_data)
43252a29edc6Sliubo 		return -ENOMEM;
43262a29edc6Sliubo 
432731ff1cd2SChris Mason 	ins_sizes = (u32 *)ins_data;
432831ff1cd2SChris Mason 	ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4329b7ef5f3aSFilipe Manana 	batch.keys = ins_keys;
4330b7ef5f3aSFilipe Manana 	batch.data_sizes = ins_sizes;
4331b7ef5f3aSFilipe Manana 	batch.total_data_size = 0;
43327f30c072SFilipe Manana 	batch.nr = 0;
433331ff1cd2SChris Mason 
43347f30c072SFilipe Manana 	dst_index = 0;
433531ff1cd2SChris Mason 	for (i = 0; i < nr; i++) {
43367f30c072SFilipe Manana 		const int src_slot = start_slot + i;
43377f30c072SFilipe Manana 		struct btrfs_root *csum_root;
43385b7ce5e2SFilipe Manana 		struct btrfs_ordered_sum *sums;
43395b7ce5e2SFilipe Manana 		struct btrfs_ordered_sum *sums_next;
43405b7ce5e2SFilipe Manana 		LIST_HEAD(ordered_sums);
43417f30c072SFilipe Manana 		u64 disk_bytenr;
43427f30c072SFilipe Manana 		u64 disk_num_bytes;
43437f30c072SFilipe Manana 		u64 extent_offset;
43447f30c072SFilipe Manana 		u64 extent_num_bytes;
43457f30c072SFilipe Manana 		bool is_old_extent;
43467f30c072SFilipe Manana 
43477f30c072SFilipe Manana 		btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
43487f30c072SFilipe Manana 
43497f30c072SFilipe Manana 		if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
43507f30c072SFilipe Manana 			goto add_to_batch;
43517f30c072SFilipe Manana 
43527f30c072SFilipe Manana 		extent = btrfs_item_ptr(src, src_slot,
43537f30c072SFilipe Manana 					struct btrfs_file_extent_item);
43547f30c072SFilipe Manana 
43557f30c072SFilipe Manana 		is_old_extent = (btrfs_file_extent_generation(src, extent) <
43567f30c072SFilipe Manana 				 trans->transid);
43577f30c072SFilipe Manana 
43587f30c072SFilipe Manana 		/*
43597f30c072SFilipe Manana 		 * Don't copy extents from past generations. That would make us
43607f30c072SFilipe Manana 		 * log a lot more metadata for common cases like doing only a
43617f30c072SFilipe Manana 		 * few random writes into a file and then fsync it for the first
43627f30c072SFilipe Manana 		 * time or after the full sync flag is set on the inode. We can
43637f30c072SFilipe Manana 		 * get leaves full of extent items, most of which are from past
43647f30c072SFilipe Manana 		 * generations, so we can skip them - as long as the inode has
43657f30c072SFilipe Manana 		 * not been the target of a reflink operation in this transaction,
43667f30c072SFilipe Manana 		 * as in that case it might have had file extent items with old
43677f30c072SFilipe Manana 		 * generations copied into it. We also must always log prealloc
43687f30c072SFilipe Manana 		 * extents that start at or beyond eof, otherwise we would lose
43697f30c072SFilipe Manana 		 * them on log replay.
43707f30c072SFilipe Manana 		 */
43717f30c072SFilipe Manana 		if (is_old_extent &&
43727f30c072SFilipe Manana 		    ins_keys[dst_index].offset < i_size &&
43737f30c072SFilipe Manana 		    inode->last_reflink_trans < trans->transid)
43747f30c072SFilipe Manana 			continue;
43757f30c072SFilipe Manana 
43767f30c072SFilipe Manana 		if (skip_csum)
43777f30c072SFilipe Manana 			goto add_to_batch;
43787f30c072SFilipe Manana 
43797f30c072SFilipe Manana 		/* Only regular extents have checksums. */
43807f30c072SFilipe Manana 		if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
43817f30c072SFilipe Manana 			goto add_to_batch;
43827f30c072SFilipe Manana 
43837f30c072SFilipe Manana 		/*
43847f30c072SFilipe Manana 		 * If it's an extent created in a past transaction, then its
43857f30c072SFilipe Manana 		 * checksums are already accessible from the committed csum tree,
43867f30c072SFilipe Manana 		 * no need to log them.
43877f30c072SFilipe Manana 		 */
43887f30c072SFilipe Manana 		if (is_old_extent)
43897f30c072SFilipe Manana 			goto add_to_batch;
43907f30c072SFilipe Manana 
43917f30c072SFilipe Manana 		disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
43927f30c072SFilipe Manana 		/* If it's an explicit hole, there are no checksums. */
43937f30c072SFilipe Manana 		if (disk_bytenr == 0)
43947f30c072SFilipe Manana 			goto add_to_batch;
43957f30c072SFilipe Manana 
43967f30c072SFilipe Manana 		disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
43977f30c072SFilipe Manana 
43987f30c072SFilipe Manana 		if (btrfs_file_extent_compression(src, extent)) {
43997f30c072SFilipe Manana 			extent_offset = 0;
44007f30c072SFilipe Manana 			extent_num_bytes = disk_num_bytes;
44017f30c072SFilipe Manana 		} else {
44027f30c072SFilipe Manana 			extent_offset = btrfs_file_extent_offset(src, extent);
44037f30c072SFilipe Manana 			extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
440431ff1cd2SChris Mason 		}
44057f30c072SFilipe Manana 
44067f30c072SFilipe Manana 		csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
44077f30c072SFilipe Manana 		disk_bytenr += extent_offset;
440897e38239SQu Wenruo 		ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
44097f30c072SFilipe Manana 					      disk_bytenr + extent_num_bytes - 1,
441026ce9114SJosef Bacik 					      &ordered_sums, 0, false);
44117f30c072SFilipe Manana 		if (ret)
44127f30c072SFilipe Manana 			goto out;
44137f30c072SFilipe Manana 
44145b7ce5e2SFilipe Manana 		list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
44155b7ce5e2SFilipe Manana 			if (!ret)
44165b7ce5e2SFilipe Manana 				ret = log_csums(trans, inode, log, sums);
44175b7ce5e2SFilipe Manana 			list_del(&sums->list);
44185b7ce5e2SFilipe Manana 			kfree(sums);
44195b7ce5e2SFilipe Manana 		}
44205b7ce5e2SFilipe Manana 		if (ret)
44215b7ce5e2SFilipe Manana 			goto out;
44225b7ce5e2SFilipe Manana 
44237f30c072SFilipe Manana add_to_batch:
44247f30c072SFilipe Manana 		ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
44257f30c072SFilipe Manana 		batch.total_data_size += ins_sizes[dst_index];
44267f30c072SFilipe Manana 		batch.nr++;
44277f30c072SFilipe Manana 		dst_index++;
44287f30c072SFilipe Manana 	}
44297f30c072SFilipe Manana 
44307f30c072SFilipe Manana 	/*
44317f30c072SFilipe Manana 	 * We have a leaf full of old extent items that don't need to be logged,
44327f30c072SFilipe Manana 	 * so we don't need to do anything.
44337f30c072SFilipe Manana 	 */
44347f30c072SFilipe Manana 	if (batch.nr == 0)
44357f30c072SFilipe Manana 		goto out;
44367f30c072SFilipe Manana 
4437b7ef5f3aSFilipe Manana 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
44387f30c072SFilipe Manana 	if (ret)
44397f30c072SFilipe Manana 		goto out;
444031ff1cd2SChris Mason 
44417f30c072SFilipe Manana 	dst_index = 0;
44427f30c072SFilipe Manana 	for (i = 0; i < nr; i++) {
44437f30c072SFilipe Manana 		const int src_slot = start_slot + i;
44447f30c072SFilipe Manana 		const int dst_slot = dst_path->slots[0] + dst_index;
44457f30c072SFilipe Manana 		struct btrfs_key key;
44467f30c072SFilipe Manana 		unsigned long src_offset;
44477f30c072SFilipe Manana 		unsigned long dst_offset;
444831ff1cd2SChris Mason 
44497f30c072SFilipe Manana 		/*
44507f30c072SFilipe Manana 		 * We're done, all the remaining items in the source leaf
44517f30c072SFilipe Manana 		 * correspond to old file extent items.
44527f30c072SFilipe Manana 		 */
44537f30c072SFilipe Manana 		if (dst_index >= batch.nr)
44547f30c072SFilipe Manana 			break;
445531ff1cd2SChris Mason 
44567f30c072SFilipe Manana 		btrfs_item_key_to_cpu(src, &key, src_slot);
44577f30c072SFilipe Manana 
44587f30c072SFilipe Manana 		if (key.type != BTRFS_EXTENT_DATA_KEY)
44597f30c072SFilipe Manana 			goto copy_item;
44607f30c072SFilipe Manana 
44617f30c072SFilipe Manana 		extent = btrfs_item_ptr(src, src_slot,
44627f30c072SFilipe Manana 					struct btrfs_file_extent_item);
44637f30c072SFilipe Manana 
44647f30c072SFilipe Manana 		/* See the comment in the previous loop, same logic. */
44657f30c072SFilipe Manana 		if (btrfs_file_extent_generation(src, extent) < trans->transid &&
44667f30c072SFilipe Manana 		    key.offset < i_size &&
44677f30c072SFilipe Manana 		    inode->last_reflink_trans < trans->transid)
44687f30c072SFilipe Manana 			continue;
44697f30c072SFilipe Manana 
44707f30c072SFilipe Manana copy_item:
44717f30c072SFilipe Manana 		dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
44727f30c072SFilipe Manana 		src_offset = btrfs_item_ptr_offset(src, src_slot);
44737f30c072SFilipe Manana 
44747f30c072SFilipe Manana 		if (key.type == BTRFS_INODE_ITEM_KEY) {
44757f30c072SFilipe Manana 			struct btrfs_inode_item *inode_item;
44767f30c072SFilipe Manana 
44777f30c072SFilipe Manana 			inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
447831ff1cd2SChris Mason 						    struct btrfs_inode_item);
447994edf4aeSJosef Bacik 			fill_inode_item(trans, dst_path->nodes[0], inode_item,
4480f85b7379SDavid Sterba 					&inode->vfs_inode,
4481f85b7379SDavid Sterba 					inode_only == LOG_INODE_EXISTS,
44821a4bcf47SFilipe Manana 					logged_isize);
448394edf4aeSJosef Bacik 		} else {
448494edf4aeSJosef Bacik 			copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
44857f30c072SFilipe Manana 					   src_offset, ins_sizes[dst_index]);
448631ff1cd2SChris Mason 		}
448794edf4aeSJosef Bacik 
44887f30c072SFilipe Manana 		dst_index++;
448931ff1cd2SChris Mason 	}
449031ff1cd2SChris Mason 
449131ff1cd2SChris Mason 	btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4492b3b4aa74SDavid Sterba 	btrfs_release_path(dst_path);
44937f30c072SFilipe Manana out:
449431ff1cd2SChris Mason 	kfree(ins_data);
4495d20f7043SChris Mason 
44964a500fd1SYan, Zheng 	return ret;
449731ff1cd2SChris Mason }
449831ff1cd2SChris Mason 
44994f0f586bSSami Tolvanen static int extent_cmp(void *priv, const struct list_head *a,
45004f0f586bSSami Tolvanen 		      const struct list_head *b)
45015dc562c5SJosef Bacik {
4502214cc184SDavid Sterba 	const struct extent_map *em1, *em2;
45035dc562c5SJosef Bacik 
45045dc562c5SJosef Bacik 	em1 = list_entry(a, struct extent_map, list);
45055dc562c5SJosef Bacik 	em2 = list_entry(b, struct extent_map, list);
45065dc562c5SJosef Bacik 
45075dc562c5SJosef Bacik 	if (em1->start < em2->start)
45085dc562c5SJosef Bacik 		return -1;
45095dc562c5SJosef Bacik 	else if (em1->start > em2->start)
45105dc562c5SJosef Bacik 		return 1;
45115dc562c5SJosef Bacik 	return 0;
45125dc562c5SJosef Bacik }
45135dc562c5SJosef Bacik 
4514e7175a69SJosef Bacik static int log_extent_csums(struct btrfs_trans_handle *trans,
4515e7175a69SJosef Bacik 			    struct btrfs_inode *inode,
4516a9ecb653SNikolay Borisov 			    struct btrfs_root *log_root,
451748778179SFilipe Manana 			    const struct extent_map *em,
451848778179SFilipe Manana 			    struct btrfs_log_ctx *ctx)
45195dc562c5SJosef Bacik {
452048778179SFilipe Manana 	struct btrfs_ordered_extent *ordered;
4521fc28b25eSJosef Bacik 	struct btrfs_root *csum_root;
45222ab28f32SJosef Bacik 	u64 csum_offset;
45232ab28f32SJosef Bacik 	u64 csum_len;
452448778179SFilipe Manana 	u64 mod_start = em->mod_start;
452548778179SFilipe Manana 	u64 mod_len = em->mod_len;
45268407f553SFilipe Manana 	LIST_HEAD(ordered_sums);
45278407f553SFilipe Manana 	int ret = 0;
452809a2a8f9SJosef Bacik 
4529e7175a69SJosef Bacik 	if (inode->flags & BTRFS_INODE_NODATASUM ||
4530e7175a69SJosef Bacik 	    test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
45318407f553SFilipe Manana 	    em->block_start == EXTENT_MAP_HOLE)
453270c8a91cSJosef Bacik 		return 0;
453370c8a91cSJosef Bacik 
453448778179SFilipe Manana 	list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
453548778179SFilipe Manana 		const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
453648778179SFilipe Manana 		const u64 mod_end = mod_start + mod_len;
453748778179SFilipe Manana 		struct btrfs_ordered_sum *sums;
453848778179SFilipe Manana 
453948778179SFilipe Manana 		if (mod_len == 0)
454048778179SFilipe Manana 			break;
454148778179SFilipe Manana 
454248778179SFilipe Manana 		if (ordered_end <= mod_start)
454348778179SFilipe Manana 			continue;
454448778179SFilipe Manana 		if (mod_end <= ordered->file_offset)
454548778179SFilipe Manana 			break;
454648778179SFilipe Manana 
454748778179SFilipe Manana 		/*
454848778179SFilipe Manana 		 * We are going to copy all the csums on this ordered extent, so
454948778179SFilipe Manana 		 * go ahead and adjust mod_start and mod_len in case this ordered
455048778179SFilipe Manana 		 * extent has already been logged.
455148778179SFilipe Manana 		 */
455248778179SFilipe Manana 		if (ordered->file_offset > mod_start) {
455348778179SFilipe Manana 			if (ordered_end >= mod_end)
455448778179SFilipe Manana 				mod_len = ordered->file_offset - mod_start;
455548778179SFilipe Manana 			/*
455648778179SFilipe Manana 			 * If we have this case
455748778179SFilipe Manana 			 *
455848778179SFilipe Manana 			 * |--------- logged extent ---------|
455948778179SFilipe Manana 			 *       |----- ordered extent ----|
456048778179SFilipe Manana 			 *
456148778179SFilipe Manana 			 * Just don't mess with mod_start and mod_len, we'll
456248778179SFilipe Manana 			 * just end up logging more csums than we need and it
456348778179SFilipe Manana 			 * will be ok.
456448778179SFilipe Manana 			 */
456548778179SFilipe Manana 		} else {
456648778179SFilipe Manana 			if (ordered_end < mod_end) {
456748778179SFilipe Manana 				mod_len = mod_end - ordered_end;
456848778179SFilipe Manana 				mod_start = ordered_end;
456948778179SFilipe Manana 			} else {
457048778179SFilipe Manana 				mod_len = 0;
457148778179SFilipe Manana 			}
457248778179SFilipe Manana 		}
457348778179SFilipe Manana 
457448778179SFilipe Manana 		/*
457548778179SFilipe Manana 		 * To keep us from looping for the above case of an ordered
457648778179SFilipe Manana 		 * extent that falls inside of the logged extent.
457748778179SFilipe Manana 		 */
457848778179SFilipe Manana 		if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
457948778179SFilipe Manana 			continue;
458048778179SFilipe Manana 
458148778179SFilipe Manana 		list_for_each_entry(sums, &ordered->list, list) {
458248778179SFilipe Manana 			ret = log_csums(trans, inode, log_root, sums);
458348778179SFilipe Manana 			if (ret)
458448778179SFilipe Manana 				return ret;
458548778179SFilipe Manana 		}
458648778179SFilipe Manana 	}
458748778179SFilipe Manana 
458848778179SFilipe Manana 	/* We're done, found all csums in the ordered extents. */
458948778179SFilipe Manana 	if (mod_len == 0)
459048778179SFilipe Manana 		return 0;
459148778179SFilipe Manana 
4592e7175a69SJosef Bacik 	/* If we're compressed we have to save the entire range of csums. */
4593488111aaSFilipe David Borba Manana 	if (em->compress_type) {
4594488111aaSFilipe David Borba Manana 		csum_offset = 0;
45958407f553SFilipe Manana 		csum_len = max(em->block_len, em->orig_block_len);
4596488111aaSFilipe David Borba Manana 	} else {
459748778179SFilipe Manana 		csum_offset = mod_start - em->start;
459848778179SFilipe Manana 		csum_len = mod_len;
4599488111aaSFilipe David Borba Manana 	}
46002ab28f32SJosef Bacik 
460170c8a91cSJosef Bacik 	/* block start is already adjusted for the file extent offset. */
4602fc28b25eSJosef Bacik 	csum_root = btrfs_csum_root(trans->fs_info, em->block_start);
460397e38239SQu Wenruo 	ret = btrfs_lookup_csums_list(csum_root, em->block_start + csum_offset,
460470c8a91cSJosef Bacik 				      em->block_start + csum_offset +
460526ce9114SJosef Bacik 				      csum_len - 1, &ordered_sums, 0, false);
46065dc562c5SJosef Bacik 	if (ret)
46075dc562c5SJosef Bacik 		return ret;
460870c8a91cSJosef Bacik 
460970c8a91cSJosef Bacik 	while (!list_empty(&ordered_sums)) {
461070c8a91cSJosef Bacik 		struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
461170c8a91cSJosef Bacik 						   struct btrfs_ordered_sum,
461270c8a91cSJosef Bacik 						   list);
461370c8a91cSJosef Bacik 		if (!ret)
46143ebac17cSFilipe Manana 			ret = log_csums(trans, inode, log_root, sums);
461570c8a91cSJosef Bacik 		list_del(&sums->list);
461670c8a91cSJosef Bacik 		kfree(sums);
46175dc562c5SJosef Bacik 	}
46185dc562c5SJosef Bacik 
461970c8a91cSJosef Bacik 	return ret;
46205dc562c5SJosef Bacik }
46215dc562c5SJosef Bacik 
46228407f553SFilipe Manana static int log_one_extent(struct btrfs_trans_handle *trans,
462390d04510SFilipe Manana 			  struct btrfs_inode *inode,
46248407f553SFilipe Manana 			  const struct extent_map *em,
46258407f553SFilipe Manana 			  struct btrfs_path *path,
46268407f553SFilipe Manana 			  struct btrfs_log_ctx *ctx)
46278407f553SFilipe Manana {
46285893dfb9SFilipe Manana 	struct btrfs_drop_extents_args drop_args = { 0 };
462990d04510SFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
4630e1f53ed8SFilipe Manana 	struct btrfs_file_extent_item fi = { 0 };
46318407f553SFilipe Manana 	struct extent_buffer *leaf;
46328407f553SFilipe Manana 	struct btrfs_key key;
46338407f553SFilipe Manana 	u64 extent_offset = em->start - em->orig_start;
46348407f553SFilipe Manana 	u64 block_len;
46358407f553SFilipe Manana 	int ret;
46368407f553SFilipe Manana 
4637e1f53ed8SFilipe Manana 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
4638e1f53ed8SFilipe Manana 	if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4639e1f53ed8SFilipe Manana 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
4640e1f53ed8SFilipe Manana 	else
4641e1f53ed8SFilipe Manana 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
4642e1f53ed8SFilipe Manana 
4643e1f53ed8SFilipe Manana 	block_len = max(em->block_len, em->orig_block_len);
4644e1f53ed8SFilipe Manana 	if (em->compress_type != BTRFS_COMPRESS_NONE) {
4645e1f53ed8SFilipe Manana 		btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start);
4646e1f53ed8SFilipe Manana 		btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4647e1f53ed8SFilipe Manana 	} else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4648e1f53ed8SFilipe Manana 		btrfs_set_stack_file_extent_disk_bytenr(&fi, em->block_start -
4649e1f53ed8SFilipe Manana 							extent_offset);
4650e1f53ed8SFilipe Manana 		btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
4651e1f53ed8SFilipe Manana 	}
4652e1f53ed8SFilipe Manana 
4653e1f53ed8SFilipe Manana 	btrfs_set_stack_file_extent_offset(&fi, extent_offset);
4654e1f53ed8SFilipe Manana 	btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
4655e1f53ed8SFilipe Manana 	btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
4656e1f53ed8SFilipe Manana 	btrfs_set_stack_file_extent_compression(&fi, em->compress_type);
4657e1f53ed8SFilipe Manana 
465848778179SFilipe Manana 	ret = log_extent_csums(trans, inode, log, em, ctx);
46598407f553SFilipe Manana 	if (ret)
46608407f553SFilipe Manana 		return ret;
46618407f553SFilipe Manana 
46625328b2a7SFilipe Manana 	/*
46635328b2a7SFilipe Manana 	 * If this is the first time we are logging the inode in the current
46645328b2a7SFilipe Manana 	 * transaction, we can avoid btrfs_drop_extents(), which is expensive
46655328b2a7SFilipe Manana 	 * because it does a deletion search, which always acquires write locks
46665328b2a7SFilipe Manana 	 * for extent buffers at levels 2, 1 and 0. This not only wastes time
46675328b2a7SFilipe Manana 	 * but also adds significant contention in a log tree, since log trees
46685328b2a7SFilipe Manana 	 * are small, with a root at level 2 or 3 at most, due to their short
46695328b2a7SFilipe Manana 	 * life span.
46705328b2a7SFilipe Manana 	 */
46710f8ce498SFilipe Manana 	if (ctx->logged_before) {
46725893dfb9SFilipe Manana 		drop_args.path = path;
46735893dfb9SFilipe Manana 		drop_args.start = em->start;
46745893dfb9SFilipe Manana 		drop_args.end = em->start + em->len;
46755893dfb9SFilipe Manana 		drop_args.replace_extent = true;
4676e1f53ed8SFilipe Manana 		drop_args.extent_item_size = sizeof(fi);
46775893dfb9SFilipe Manana 		ret = btrfs_drop_extents(trans, log, inode, &drop_args);
46788407f553SFilipe Manana 		if (ret)
46798407f553SFilipe Manana 			return ret;
46805328b2a7SFilipe Manana 	}
46818407f553SFilipe Manana 
46825893dfb9SFilipe Manana 	if (!drop_args.extent_inserted) {
46839d122629SNikolay Borisov 		key.objectid = btrfs_ino(inode);
46848407f553SFilipe Manana 		key.type = BTRFS_EXTENT_DATA_KEY;
46858407f553SFilipe Manana 		key.offset = em->start;
46868407f553SFilipe Manana 
46878407f553SFilipe Manana 		ret = btrfs_insert_empty_item(trans, log, path, &key,
4688e1f53ed8SFilipe Manana 					      sizeof(fi));
46898407f553SFilipe Manana 		if (ret)
46908407f553SFilipe Manana 			return ret;
46918407f553SFilipe Manana 	}
46928407f553SFilipe Manana 	leaf = path->nodes[0];
4693e1f53ed8SFilipe Manana 	write_extent_buffer(leaf, &fi,
4694e1f53ed8SFilipe Manana 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
4695e1f53ed8SFilipe Manana 			    sizeof(fi));
46968407f553SFilipe Manana 	btrfs_mark_buffer_dirty(leaf);
46978407f553SFilipe Manana 
46988407f553SFilipe Manana 	btrfs_release_path(path);
46998407f553SFilipe Manana 
47008407f553SFilipe Manana 	return ret;
47018407f553SFilipe Manana }
47028407f553SFilipe Manana 
470331d11b83SFilipe Manana /*
470431d11b83SFilipe Manana  * Log all prealloc extents beyond the inode's i_size to make sure we do not
4705d9947887SFilipe Manana  * lose them after doing a full/fast fsync and replaying the log. We scan the
470631d11b83SFilipe Manana  * subvolume's root instead of iterating the inode's extent map tree because
470731d11b83SFilipe Manana  * otherwise we can log incorrect extent items based on extent map conversion.
470831d11b83SFilipe Manana  * That can happen due to the fact that extent maps are merged when they
470931d11b83SFilipe Manana  * are not in the extent map tree's list of modified extents.
471031d11b83SFilipe Manana  */
471131d11b83SFilipe Manana static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
471231d11b83SFilipe Manana 				      struct btrfs_inode *inode,
471331d11b83SFilipe Manana 				      struct btrfs_path *path)
471431d11b83SFilipe Manana {
471531d11b83SFilipe Manana 	struct btrfs_root *root = inode->root;
471631d11b83SFilipe Manana 	struct btrfs_key key;
471731d11b83SFilipe Manana 	const u64 i_size = i_size_read(&inode->vfs_inode);
471831d11b83SFilipe Manana 	const u64 ino = btrfs_ino(inode);
471931d11b83SFilipe Manana 	struct btrfs_path *dst_path = NULL;
47200e56315cSFilipe Manana 	bool dropped_extents = false;
4721f135cea3SFilipe Manana 	u64 truncate_offset = i_size;
4722f135cea3SFilipe Manana 	struct extent_buffer *leaf;
4723f135cea3SFilipe Manana 	int slot;
472431d11b83SFilipe Manana 	int ins_nr = 0;
472531d11b83SFilipe Manana 	int start_slot;
472631d11b83SFilipe Manana 	int ret;
472731d11b83SFilipe Manana 
472831d11b83SFilipe Manana 	if (!(inode->flags & BTRFS_INODE_PREALLOC))
472931d11b83SFilipe Manana 		return 0;
473031d11b83SFilipe Manana 
473131d11b83SFilipe Manana 	key.objectid = ino;
473231d11b83SFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
473331d11b83SFilipe Manana 	key.offset = i_size;
473431d11b83SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
473531d11b83SFilipe Manana 	if (ret < 0)
473631d11b83SFilipe Manana 		goto out;
473731d11b83SFilipe Manana 
4738f135cea3SFilipe Manana 	/*
4739f135cea3SFilipe Manana 	 * We must check if there is a prealloc extent that starts before the
4740f135cea3SFilipe Manana 	 * i_size and crosses the i_size boundary. This is to ensure later we
4741f135cea3SFilipe Manana 	 * truncate down to the end of that extent and not to the i_size, as
4742f135cea3SFilipe Manana 	 * otherwise we end up losing part of the prealloc extent after a log
4743f135cea3SFilipe Manana 	 * replay and with an implicit hole if there is another prealloc extent
4744f135cea3SFilipe Manana 	 * that starts at an offset beyond i_size.
4745f135cea3SFilipe Manana 	 */
4746f135cea3SFilipe Manana 	ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4747f135cea3SFilipe Manana 	if (ret < 0)
4748f135cea3SFilipe Manana 		goto out;
4749f135cea3SFilipe Manana 
4750f135cea3SFilipe Manana 	if (ret == 0) {
4751f135cea3SFilipe Manana 		struct btrfs_file_extent_item *ei;
4752f135cea3SFilipe Manana 
4753f135cea3SFilipe Manana 		leaf = path->nodes[0];
4754f135cea3SFilipe Manana 		slot = path->slots[0];
4755f135cea3SFilipe Manana 		ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4756f135cea3SFilipe Manana 
4757f135cea3SFilipe Manana 		if (btrfs_file_extent_type(leaf, ei) ==
4758f135cea3SFilipe Manana 		    BTRFS_FILE_EXTENT_PREALLOC) {
4759f135cea3SFilipe Manana 			u64 extent_end;
4760f135cea3SFilipe Manana 
4761f135cea3SFilipe Manana 			btrfs_item_key_to_cpu(leaf, &key, slot);
4762f135cea3SFilipe Manana 			extent_end = key.offset +
4763f135cea3SFilipe Manana 				btrfs_file_extent_num_bytes(leaf, ei);
4764f135cea3SFilipe Manana 
4765f135cea3SFilipe Manana 			if (extent_end > i_size)
4766f135cea3SFilipe Manana 				truncate_offset = extent_end;
4767f135cea3SFilipe Manana 		}
4768f135cea3SFilipe Manana 	} else {
4769f135cea3SFilipe Manana 		ret = 0;
4770f135cea3SFilipe Manana 	}
4771f135cea3SFilipe Manana 
477231d11b83SFilipe Manana 	while (true) {
4773f135cea3SFilipe Manana 		leaf = path->nodes[0];
4774f135cea3SFilipe Manana 		slot = path->slots[0];
477531d11b83SFilipe Manana 
477631d11b83SFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
477731d11b83SFilipe Manana 			if (ins_nr > 0) {
477831d11b83SFilipe Manana 				ret = copy_items(trans, inode, dst_path, path,
47790e56315cSFilipe Manana 						 start_slot, ins_nr, 1, 0);
478031d11b83SFilipe Manana 				if (ret < 0)
478131d11b83SFilipe Manana 					goto out;
478231d11b83SFilipe Manana 				ins_nr = 0;
478331d11b83SFilipe Manana 			}
478431d11b83SFilipe Manana 			ret = btrfs_next_leaf(root, path);
478531d11b83SFilipe Manana 			if (ret < 0)
478631d11b83SFilipe Manana 				goto out;
478731d11b83SFilipe Manana 			if (ret > 0) {
478831d11b83SFilipe Manana 				ret = 0;
478931d11b83SFilipe Manana 				break;
479031d11b83SFilipe Manana 			}
479131d11b83SFilipe Manana 			continue;
479231d11b83SFilipe Manana 		}
479331d11b83SFilipe Manana 
479431d11b83SFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
479531d11b83SFilipe Manana 		if (key.objectid > ino)
479631d11b83SFilipe Manana 			break;
479731d11b83SFilipe Manana 		if (WARN_ON_ONCE(key.objectid < ino) ||
479831d11b83SFilipe Manana 		    key.type < BTRFS_EXTENT_DATA_KEY ||
479931d11b83SFilipe Manana 		    key.offset < i_size) {
480031d11b83SFilipe Manana 			path->slots[0]++;
480131d11b83SFilipe Manana 			continue;
480231d11b83SFilipe Manana 		}
48030e56315cSFilipe Manana 		if (!dropped_extents) {
480431d11b83SFilipe Manana 			/*
480531d11b83SFilipe Manana 			 * Avoid logging extent items logged in past fsync calls
480631d11b83SFilipe Manana 			 * and leading to duplicate keys in the log tree.
480731d11b83SFilipe Manana 			 */
48088a2b3da1SFilipe Manana 			ret = truncate_inode_items(trans, root->log_root, inode,
48098a2b3da1SFilipe Manana 						   truncate_offset,
48108a2b3da1SFilipe Manana 						   BTRFS_EXTENT_DATA_KEY);
481131d11b83SFilipe Manana 			if (ret)
481231d11b83SFilipe Manana 				goto out;
48130e56315cSFilipe Manana 			dropped_extents = true;
481431d11b83SFilipe Manana 		}
481531d11b83SFilipe Manana 		if (ins_nr == 0)
481631d11b83SFilipe Manana 			start_slot = slot;
481731d11b83SFilipe Manana 		ins_nr++;
481831d11b83SFilipe Manana 		path->slots[0]++;
481931d11b83SFilipe Manana 		if (!dst_path) {
482031d11b83SFilipe Manana 			dst_path = btrfs_alloc_path();
482131d11b83SFilipe Manana 			if (!dst_path) {
482231d11b83SFilipe Manana 				ret = -ENOMEM;
482331d11b83SFilipe Manana 				goto out;
482431d11b83SFilipe Manana 			}
482531d11b83SFilipe Manana 		}
482631d11b83SFilipe Manana 	}
48270bc2d3c0SFilipe Manana 	if (ins_nr > 0)
48280e56315cSFilipe Manana 		ret = copy_items(trans, inode, dst_path, path,
482931d11b83SFilipe Manana 				 start_slot, ins_nr, 1, 0);
483031d11b83SFilipe Manana out:
483131d11b83SFilipe Manana 	btrfs_release_path(path);
483231d11b83SFilipe Manana 	btrfs_free_path(dst_path);
483331d11b83SFilipe Manana 	return ret;
483431d11b83SFilipe Manana }
483531d11b83SFilipe Manana 
48365dc562c5SJosef Bacik static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
48379d122629SNikolay Borisov 				     struct btrfs_inode *inode,
4838827463c4SMiao Xie 				     struct btrfs_path *path,
483948778179SFilipe Manana 				     struct btrfs_log_ctx *ctx)
48405dc562c5SJosef Bacik {
484148778179SFilipe Manana 	struct btrfs_ordered_extent *ordered;
484248778179SFilipe Manana 	struct btrfs_ordered_extent *tmp;
48435dc562c5SJosef Bacik 	struct extent_map *em, *n;
48445dc562c5SJosef Bacik 	struct list_head extents;
48459d122629SNikolay Borisov 	struct extent_map_tree *tree = &inode->extent_tree;
48465dc562c5SJosef Bacik 	int ret = 0;
48472ab28f32SJosef Bacik 	int num = 0;
48485dc562c5SJosef Bacik 
48495dc562c5SJosef Bacik 	INIT_LIST_HEAD(&extents);
48505dc562c5SJosef Bacik 
48515dc562c5SJosef Bacik 	write_lock(&tree->lock);
48525dc562c5SJosef Bacik 
48535dc562c5SJosef Bacik 	list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
48545dc562c5SJosef Bacik 		list_del_init(&em->list);
48552ab28f32SJosef Bacik 		/*
48562ab28f32SJosef Bacik 		 * Just an arbitrary number, this can be really CPU intensive
48572ab28f32SJosef Bacik 		 * once we start getting a lot of extents, and really once we
48582ab28f32SJosef Bacik 		 * have a bunch of extents we just want to commit since it will
48592ab28f32SJosef Bacik 		 * be faster.
48602ab28f32SJosef Bacik 		 */
48612ab28f32SJosef Bacik 		if (++num > 32768) {
48622ab28f32SJosef Bacik 			list_del_init(&tree->modified_extents);
48632ab28f32SJosef Bacik 			ret = -EFBIG;
48642ab28f32SJosef Bacik 			goto process;
48652ab28f32SJosef Bacik 		}
48662ab28f32SJosef Bacik 
48675f96bfb7SFilipe Manana 		if (em->generation < trans->transid)
48685dc562c5SJosef Bacik 			continue;
48698c6c5928SJosef Bacik 
487031d11b83SFilipe Manana 		/* We log prealloc extents beyond eof later. */
487131d11b83SFilipe Manana 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
487231d11b83SFilipe Manana 		    em->start >= i_size_read(&inode->vfs_inode))
487331d11b83SFilipe Manana 			continue;
487431d11b83SFilipe Manana 
4875ff44c6e3SJosef Bacik 		/* Need a ref to keep it from getting evicted from cache */
4876490b54d6SElena Reshetova 		refcount_inc(&em->refs);
4877ff44c6e3SJosef Bacik 		set_bit(EXTENT_FLAG_LOGGING, &em->flags);
48785dc562c5SJosef Bacik 		list_add_tail(&em->list, &extents);
48792ab28f32SJosef Bacik 		num++;
48805dc562c5SJosef Bacik 	}
48815dc562c5SJosef Bacik 
48825dc562c5SJosef Bacik 	list_sort(NULL, &extents, extent_cmp);
48832ab28f32SJosef Bacik process:
48845dc562c5SJosef Bacik 	while (!list_empty(&extents)) {
48855dc562c5SJosef Bacik 		em = list_entry(extents.next, struct extent_map, list);
48865dc562c5SJosef Bacik 
48875dc562c5SJosef Bacik 		list_del_init(&em->list);
48885dc562c5SJosef Bacik 
48895dc562c5SJosef Bacik 		/*
48905dc562c5SJosef Bacik 		 * If we had an error we just need to delete everybody from our
48915dc562c5SJosef Bacik 		 * private list.
48925dc562c5SJosef Bacik 		 */
4893ff44c6e3SJosef Bacik 		if (ret) {
4894201a9038SJosef Bacik 			clear_em_logging(tree, em);
4895ff44c6e3SJosef Bacik 			free_extent_map(em);
48965dc562c5SJosef Bacik 			continue;
4897ff44c6e3SJosef Bacik 		}
4898ff44c6e3SJosef Bacik 
4899ff44c6e3SJosef Bacik 		write_unlock(&tree->lock);
49005dc562c5SJosef Bacik 
490190d04510SFilipe Manana 		ret = log_one_extent(trans, inode, em, path, ctx);
4902ff44c6e3SJosef Bacik 		write_lock(&tree->lock);
4903201a9038SJosef Bacik 		clear_em_logging(tree, em);
4904201a9038SJosef Bacik 		free_extent_map(em);
49055dc562c5SJosef Bacik 	}
4906ff44c6e3SJosef Bacik 	WARN_ON(!list_empty(&extents));
4907ff44c6e3SJosef Bacik 	write_unlock(&tree->lock);
49085dc562c5SJosef Bacik 
490931d11b83SFilipe Manana 	if (!ret)
491031d11b83SFilipe Manana 		ret = btrfs_log_prealloc_extents(trans, inode, path);
491148778179SFilipe Manana 	if (ret)
49125dc562c5SJosef Bacik 		return ret;
491348778179SFilipe Manana 
491448778179SFilipe Manana 	/*
491548778179SFilipe Manana 	 * We have logged all extents successfully, now make sure the commit of
491648778179SFilipe Manana 	 * the current transaction waits for the ordered extents to complete
491748778179SFilipe Manana 	 * before it commits and wipes out the log trees, otherwise we would
491848778179SFilipe Manana 	 * lose data if an ordered extents completes after the transaction
491948778179SFilipe Manana 	 * commits and a power failure happens after the transaction commit.
492048778179SFilipe Manana 	 */
492148778179SFilipe Manana 	list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
492248778179SFilipe Manana 		list_del_init(&ordered->log_list);
492348778179SFilipe Manana 		set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
492448778179SFilipe Manana 
492548778179SFilipe Manana 		if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
492648778179SFilipe Manana 			spin_lock_irq(&inode->ordered_tree.lock);
492748778179SFilipe Manana 			if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
492848778179SFilipe Manana 				set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
492948778179SFilipe Manana 				atomic_inc(&trans->transaction->pending_ordered);
493048778179SFilipe Manana 			}
493148778179SFilipe Manana 			spin_unlock_irq(&inode->ordered_tree.lock);
493248778179SFilipe Manana 		}
493348778179SFilipe Manana 		btrfs_put_ordered_extent(ordered);
493448778179SFilipe Manana 	}
493548778179SFilipe Manana 
493648778179SFilipe Manana 	return 0;
49375dc562c5SJosef Bacik }
49385dc562c5SJosef Bacik 
4939481b01c0SNikolay Borisov static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
49401a4bcf47SFilipe Manana 			     struct btrfs_path *path, u64 *size_ret)
49411a4bcf47SFilipe Manana {
49421a4bcf47SFilipe Manana 	struct btrfs_key key;
49431a4bcf47SFilipe Manana 	int ret;
49441a4bcf47SFilipe Manana 
4945481b01c0SNikolay Borisov 	key.objectid = btrfs_ino(inode);
49461a4bcf47SFilipe Manana 	key.type = BTRFS_INODE_ITEM_KEY;
49471a4bcf47SFilipe Manana 	key.offset = 0;
49481a4bcf47SFilipe Manana 
49491a4bcf47SFilipe Manana 	ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
49501a4bcf47SFilipe Manana 	if (ret < 0) {
49511a4bcf47SFilipe Manana 		return ret;
49521a4bcf47SFilipe Manana 	} else if (ret > 0) {
49532f2ff0eeSFilipe Manana 		*size_ret = 0;
49541a4bcf47SFilipe Manana 	} else {
49551a4bcf47SFilipe Manana 		struct btrfs_inode_item *item;
49561a4bcf47SFilipe Manana 
49571a4bcf47SFilipe Manana 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
49581a4bcf47SFilipe Manana 				      struct btrfs_inode_item);
49591a4bcf47SFilipe Manana 		*size_ret = btrfs_inode_size(path->nodes[0], item);
4960bf504110SFilipe Manana 		/*
4961bf504110SFilipe Manana 		 * If the in-memory inode's i_size is smaller then the inode
4962bf504110SFilipe Manana 		 * size stored in the btree, return the inode's i_size, so
4963bf504110SFilipe Manana 		 * that we get a correct inode size after replaying the log
4964bf504110SFilipe Manana 		 * when before a power failure we had a shrinking truncate
4965bf504110SFilipe Manana 		 * followed by addition of a new name (rename / new hard link).
4966bf504110SFilipe Manana 		 * Otherwise return the inode size from the btree, to avoid
4967bf504110SFilipe Manana 		 * data loss when replaying a log due to previously doing a
4968bf504110SFilipe Manana 		 * write that expands the inode's size and logging a new name
4969bf504110SFilipe Manana 		 * immediately after.
4970bf504110SFilipe Manana 		 */
4971bf504110SFilipe Manana 		if (*size_ret > inode->vfs_inode.i_size)
4972bf504110SFilipe Manana 			*size_ret = inode->vfs_inode.i_size;
49731a4bcf47SFilipe Manana 	}
49741a4bcf47SFilipe Manana 
49751a4bcf47SFilipe Manana 	btrfs_release_path(path);
49761a4bcf47SFilipe Manana 	return 0;
49771a4bcf47SFilipe Manana }
49781a4bcf47SFilipe Manana 
497936283bf7SFilipe Manana /*
498036283bf7SFilipe Manana  * At the moment we always log all xattrs. This is to figure out at log replay
498136283bf7SFilipe Manana  * time which xattrs must have their deletion replayed. If a xattr is missing
498236283bf7SFilipe Manana  * in the log tree and exists in the fs/subvol tree, we delete it. This is
498336283bf7SFilipe Manana  * because if a xattr is deleted, the inode is fsynced and a power failure
498436283bf7SFilipe Manana  * happens, causing the log to be replayed the next time the fs is mounted,
498536283bf7SFilipe Manana  * we want the xattr to not exist anymore (same behaviour as other filesystems
498636283bf7SFilipe Manana  * with a journal, ext3/4, xfs, f2fs, etc).
498736283bf7SFilipe Manana  */
498836283bf7SFilipe Manana static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
49891a93c36aSNikolay Borisov 				struct btrfs_inode *inode,
499036283bf7SFilipe Manana 				struct btrfs_path *path,
499136283bf7SFilipe Manana 				struct btrfs_path *dst_path)
499236283bf7SFilipe Manana {
499390d04510SFilipe Manana 	struct btrfs_root *root = inode->root;
499436283bf7SFilipe Manana 	int ret;
499536283bf7SFilipe Manana 	struct btrfs_key key;
49961a93c36aSNikolay Borisov 	const u64 ino = btrfs_ino(inode);
499736283bf7SFilipe Manana 	int ins_nr = 0;
499836283bf7SFilipe Manana 	int start_slot = 0;
4999f2f121abSFilipe Manana 	bool found_xattrs = false;
5000f2f121abSFilipe Manana 
5001f2f121abSFilipe Manana 	if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5002f2f121abSFilipe Manana 		return 0;
500336283bf7SFilipe Manana 
500436283bf7SFilipe Manana 	key.objectid = ino;
500536283bf7SFilipe Manana 	key.type = BTRFS_XATTR_ITEM_KEY;
500636283bf7SFilipe Manana 	key.offset = 0;
500736283bf7SFilipe Manana 
500836283bf7SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
500936283bf7SFilipe Manana 	if (ret < 0)
501036283bf7SFilipe Manana 		return ret;
501136283bf7SFilipe Manana 
501236283bf7SFilipe Manana 	while (true) {
501336283bf7SFilipe Manana 		int slot = path->slots[0];
501436283bf7SFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
501536283bf7SFilipe Manana 		int nritems = btrfs_header_nritems(leaf);
501636283bf7SFilipe Manana 
501736283bf7SFilipe Manana 		if (slot >= nritems) {
501836283bf7SFilipe Manana 			if (ins_nr > 0) {
50191a93c36aSNikolay Borisov 				ret = copy_items(trans, inode, dst_path, path,
50200e56315cSFilipe Manana 						 start_slot, ins_nr, 1, 0);
502136283bf7SFilipe Manana 				if (ret < 0)
502236283bf7SFilipe Manana 					return ret;
502336283bf7SFilipe Manana 				ins_nr = 0;
502436283bf7SFilipe Manana 			}
502536283bf7SFilipe Manana 			ret = btrfs_next_leaf(root, path);
502636283bf7SFilipe Manana 			if (ret < 0)
502736283bf7SFilipe Manana 				return ret;
502836283bf7SFilipe Manana 			else if (ret > 0)
502936283bf7SFilipe Manana 				break;
503036283bf7SFilipe Manana 			continue;
503136283bf7SFilipe Manana 		}
503236283bf7SFilipe Manana 
503336283bf7SFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
503436283bf7SFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
503536283bf7SFilipe Manana 			break;
503636283bf7SFilipe Manana 
503736283bf7SFilipe Manana 		if (ins_nr == 0)
503836283bf7SFilipe Manana 			start_slot = slot;
503936283bf7SFilipe Manana 		ins_nr++;
504036283bf7SFilipe Manana 		path->slots[0]++;
5041f2f121abSFilipe Manana 		found_xattrs = true;
504236283bf7SFilipe Manana 		cond_resched();
504336283bf7SFilipe Manana 	}
504436283bf7SFilipe Manana 	if (ins_nr > 0) {
50451a93c36aSNikolay Borisov 		ret = copy_items(trans, inode, dst_path, path,
50460e56315cSFilipe Manana 				 start_slot, ins_nr, 1, 0);
504736283bf7SFilipe Manana 		if (ret < 0)
504836283bf7SFilipe Manana 			return ret;
504936283bf7SFilipe Manana 	}
505036283bf7SFilipe Manana 
5051f2f121abSFilipe Manana 	if (!found_xattrs)
5052f2f121abSFilipe Manana 		set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5053f2f121abSFilipe Manana 
505436283bf7SFilipe Manana 	return 0;
505536283bf7SFilipe Manana }
505636283bf7SFilipe Manana 
5057a89ca6f2SFilipe Manana /*
50580e56315cSFilipe Manana  * When using the NO_HOLES feature if we punched a hole that causes the
50590e56315cSFilipe Manana  * deletion of entire leafs or all the extent items of the first leaf (the one
50600e56315cSFilipe Manana  * that contains the inode item and references) we may end up not processing
50610e56315cSFilipe Manana  * any extents, because there are no leafs with a generation matching the
50620e56315cSFilipe Manana  * current transaction that have extent items for our inode. So we need to find
50630e56315cSFilipe Manana  * if any holes exist and then log them. We also need to log holes after any
50640e56315cSFilipe Manana  * truncate operation that changes the inode's size.
5065a89ca6f2SFilipe Manana  */
50660e56315cSFilipe Manana static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5067a0308dd7SNikolay Borisov 			   struct btrfs_inode *inode,
50687af59743SFilipe Manana 			   struct btrfs_path *path)
5069a89ca6f2SFilipe Manana {
507090d04510SFilipe Manana 	struct btrfs_root *root = inode->root;
50710b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
5072a89ca6f2SFilipe Manana 	struct btrfs_key key;
5073a0308dd7SNikolay Borisov 	const u64 ino = btrfs_ino(inode);
5074a0308dd7SNikolay Borisov 	const u64 i_size = i_size_read(&inode->vfs_inode);
50757af59743SFilipe Manana 	u64 prev_extent_end = 0;
50760e56315cSFilipe Manana 	int ret;
5077a89ca6f2SFilipe Manana 
50780e56315cSFilipe Manana 	if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5079a89ca6f2SFilipe Manana 		return 0;
5080a89ca6f2SFilipe Manana 
5081a89ca6f2SFilipe Manana 	key.objectid = ino;
5082a89ca6f2SFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
50837af59743SFilipe Manana 	key.offset = 0;
5084a89ca6f2SFilipe Manana 
5085a89ca6f2SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5086a89ca6f2SFilipe Manana 	if (ret < 0)
5087a89ca6f2SFilipe Manana 		return ret;
5088a89ca6f2SFilipe Manana 
50890e56315cSFilipe Manana 	while (true) {
50900e56315cSFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
5091a89ca6f2SFilipe Manana 
50920e56315cSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
50930e56315cSFilipe Manana 			ret = btrfs_next_leaf(root, path);
50940e56315cSFilipe Manana 			if (ret < 0)
50950e56315cSFilipe Manana 				return ret;
50960e56315cSFilipe Manana 			if (ret > 0) {
50970e56315cSFilipe Manana 				ret = 0;
50980e56315cSFilipe Manana 				break;
50990e56315cSFilipe Manana 			}
51000e56315cSFilipe Manana 			leaf = path->nodes[0];
51010e56315cSFilipe Manana 		}
51020e56315cSFilipe Manana 
51030e56315cSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
51040e56315cSFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
51050e56315cSFilipe Manana 			break;
51060e56315cSFilipe Manana 
51070e56315cSFilipe Manana 		/* We have a hole, log it. */
51080e56315cSFilipe Manana 		if (prev_extent_end < key.offset) {
51097af59743SFilipe Manana 			const u64 hole_len = key.offset - prev_extent_end;
51100e56315cSFilipe Manana 
5111a89ca6f2SFilipe Manana 			/*
51120e56315cSFilipe Manana 			 * Release the path to avoid deadlocks with other code
51130e56315cSFilipe Manana 			 * paths that search the root while holding locks on
51140e56315cSFilipe Manana 			 * leafs from the log root.
5115a89ca6f2SFilipe Manana 			 */
51160e56315cSFilipe Manana 			btrfs_release_path(path);
5117d1f68ba0SOmar Sandoval 			ret = btrfs_insert_hole_extent(trans, root->log_root,
5118d1f68ba0SOmar Sandoval 						       ino, prev_extent_end,
5119d1f68ba0SOmar Sandoval 						       hole_len);
51200e56315cSFilipe Manana 			if (ret < 0)
51210e56315cSFilipe Manana 				return ret;
51220e56315cSFilipe Manana 
51230e56315cSFilipe Manana 			/*
51240e56315cSFilipe Manana 			 * Search for the same key again in the root. Since it's
51250e56315cSFilipe Manana 			 * an extent item and we are holding the inode lock, the
51260e56315cSFilipe Manana 			 * key must still exist. If it doesn't just emit warning
51270e56315cSFilipe Manana 			 * and return an error to fall back to a transaction
51280e56315cSFilipe Manana 			 * commit.
51290e56315cSFilipe Manana 			 */
51300e56315cSFilipe Manana 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
51310e56315cSFilipe Manana 			if (ret < 0)
51320e56315cSFilipe Manana 				return ret;
51330e56315cSFilipe Manana 			if (WARN_ON(ret > 0))
51340e56315cSFilipe Manana 				return -ENOENT;
51350e56315cSFilipe Manana 			leaf = path->nodes[0];
51360e56315cSFilipe Manana 		}
5137a89ca6f2SFilipe Manana 
51387af59743SFilipe Manana 		prev_extent_end = btrfs_file_extent_end(path);
51390e56315cSFilipe Manana 		path->slots[0]++;
51400e56315cSFilipe Manana 		cond_resched();
51410e56315cSFilipe Manana 	}
51420e56315cSFilipe Manana 
51437af59743SFilipe Manana 	if (prev_extent_end < i_size) {
51440e56315cSFilipe Manana 		u64 hole_len;
51450e56315cSFilipe Manana 
5146a89ca6f2SFilipe Manana 		btrfs_release_path(path);
51477af59743SFilipe Manana 		hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5148d1f68ba0SOmar Sandoval 		ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5149d1f68ba0SOmar Sandoval 					       prev_extent_end, hole_len);
51500e56315cSFilipe Manana 		if (ret < 0)
5151a89ca6f2SFilipe Manana 			return ret;
5152a89ca6f2SFilipe Manana 	}
5153a89ca6f2SFilipe Manana 
51540e56315cSFilipe Manana 	return 0;
51550e56315cSFilipe Manana }
51560e56315cSFilipe Manana 
515756f23fdbSFilipe Manana /*
515856f23fdbSFilipe Manana  * When we are logging a new inode X, check if it doesn't have a reference that
515956f23fdbSFilipe Manana  * matches the reference from some other inode Y created in a past transaction
516056f23fdbSFilipe Manana  * and that was renamed in the current transaction. If we don't do this, then at
516156f23fdbSFilipe Manana  * log replay time we can lose inode Y (and all its files if it's a directory):
516256f23fdbSFilipe Manana  *
516356f23fdbSFilipe Manana  * mkdir /mnt/x
516456f23fdbSFilipe Manana  * echo "hello world" > /mnt/x/foobar
516556f23fdbSFilipe Manana  * sync
516656f23fdbSFilipe Manana  * mv /mnt/x /mnt/y
516756f23fdbSFilipe Manana  * mkdir /mnt/x                 # or touch /mnt/x
516856f23fdbSFilipe Manana  * xfs_io -c fsync /mnt/x
516956f23fdbSFilipe Manana  * <power fail>
517056f23fdbSFilipe Manana  * mount fs, trigger log replay
517156f23fdbSFilipe Manana  *
517256f23fdbSFilipe Manana  * After the log replay procedure, we would lose the first directory and all its
517356f23fdbSFilipe Manana  * files (file foobar).
517456f23fdbSFilipe Manana  * For the case where inode Y is not a directory we simply end up losing it:
517556f23fdbSFilipe Manana  *
517656f23fdbSFilipe Manana  * echo "123" > /mnt/foo
517756f23fdbSFilipe Manana  * sync
517856f23fdbSFilipe Manana  * mv /mnt/foo /mnt/bar
517956f23fdbSFilipe Manana  * echo "abc" > /mnt/foo
518056f23fdbSFilipe Manana  * xfs_io -c fsync /mnt/foo
518156f23fdbSFilipe Manana  * <power fail>
518256f23fdbSFilipe Manana  *
518356f23fdbSFilipe Manana  * We also need this for cases where a snapshot entry is replaced by some other
518456f23fdbSFilipe Manana  * entry (file or directory) otherwise we end up with an unreplayable log due to
518556f23fdbSFilipe Manana  * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
518656f23fdbSFilipe Manana  * if it were a regular entry:
518756f23fdbSFilipe Manana  *
518856f23fdbSFilipe Manana  * mkdir /mnt/x
518956f23fdbSFilipe Manana  * btrfs subvolume snapshot /mnt /mnt/x/snap
519056f23fdbSFilipe Manana  * btrfs subvolume delete /mnt/x/snap
519156f23fdbSFilipe Manana  * rmdir /mnt/x
519256f23fdbSFilipe Manana  * mkdir /mnt/x
519356f23fdbSFilipe Manana  * fsync /mnt/x or fsync some new file inside it
519456f23fdbSFilipe Manana  * <power fail>
519556f23fdbSFilipe Manana  *
519656f23fdbSFilipe Manana  * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
519756f23fdbSFilipe Manana  * the same transaction.
519856f23fdbSFilipe Manana  */
519956f23fdbSFilipe Manana static int btrfs_check_ref_name_override(struct extent_buffer *eb,
520056f23fdbSFilipe Manana 					 const int slot,
520156f23fdbSFilipe Manana 					 const struct btrfs_key *key,
52024791c8f1SNikolay Borisov 					 struct btrfs_inode *inode,
5203a3baaf0dSFilipe Manana 					 u64 *other_ino, u64 *other_parent)
520456f23fdbSFilipe Manana {
520556f23fdbSFilipe Manana 	int ret;
520656f23fdbSFilipe Manana 	struct btrfs_path *search_path;
520756f23fdbSFilipe Manana 	char *name = NULL;
520856f23fdbSFilipe Manana 	u32 name_len = 0;
52093212fa14SJosef Bacik 	u32 item_size = btrfs_item_size(eb, slot);
521056f23fdbSFilipe Manana 	u32 cur_offset = 0;
521156f23fdbSFilipe Manana 	unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
521256f23fdbSFilipe Manana 
521356f23fdbSFilipe Manana 	search_path = btrfs_alloc_path();
521456f23fdbSFilipe Manana 	if (!search_path)
521556f23fdbSFilipe Manana 		return -ENOMEM;
521656f23fdbSFilipe Manana 	search_path->search_commit_root = 1;
521756f23fdbSFilipe Manana 	search_path->skip_locking = 1;
521856f23fdbSFilipe Manana 
521956f23fdbSFilipe Manana 	while (cur_offset < item_size) {
522056f23fdbSFilipe Manana 		u64 parent;
522156f23fdbSFilipe Manana 		u32 this_name_len;
522256f23fdbSFilipe Manana 		u32 this_len;
522356f23fdbSFilipe Manana 		unsigned long name_ptr;
522456f23fdbSFilipe Manana 		struct btrfs_dir_item *di;
52256db75318SSweet Tea Dorminy 		struct fscrypt_str name_str;
522656f23fdbSFilipe Manana 
522756f23fdbSFilipe Manana 		if (key->type == BTRFS_INODE_REF_KEY) {
522856f23fdbSFilipe Manana 			struct btrfs_inode_ref *iref;
522956f23fdbSFilipe Manana 
523056f23fdbSFilipe Manana 			iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
523156f23fdbSFilipe Manana 			parent = key->offset;
523256f23fdbSFilipe Manana 			this_name_len = btrfs_inode_ref_name_len(eb, iref);
523356f23fdbSFilipe Manana 			name_ptr = (unsigned long)(iref + 1);
523456f23fdbSFilipe Manana 			this_len = sizeof(*iref) + this_name_len;
523556f23fdbSFilipe Manana 		} else {
523656f23fdbSFilipe Manana 			struct btrfs_inode_extref *extref;
523756f23fdbSFilipe Manana 
523856f23fdbSFilipe Manana 			extref = (struct btrfs_inode_extref *)(ptr +
523956f23fdbSFilipe Manana 							       cur_offset);
524056f23fdbSFilipe Manana 			parent = btrfs_inode_extref_parent(eb, extref);
524156f23fdbSFilipe Manana 			this_name_len = btrfs_inode_extref_name_len(eb, extref);
524256f23fdbSFilipe Manana 			name_ptr = (unsigned long)&extref->name;
524356f23fdbSFilipe Manana 			this_len = sizeof(*extref) + this_name_len;
524456f23fdbSFilipe Manana 		}
524556f23fdbSFilipe Manana 
524656f23fdbSFilipe Manana 		if (this_name_len > name_len) {
524756f23fdbSFilipe Manana 			char *new_name;
524856f23fdbSFilipe Manana 
524956f23fdbSFilipe Manana 			new_name = krealloc(name, this_name_len, GFP_NOFS);
525056f23fdbSFilipe Manana 			if (!new_name) {
525156f23fdbSFilipe Manana 				ret = -ENOMEM;
525256f23fdbSFilipe Manana 				goto out;
525356f23fdbSFilipe Manana 			}
525456f23fdbSFilipe Manana 			name_len = this_name_len;
525556f23fdbSFilipe Manana 			name = new_name;
525656f23fdbSFilipe Manana 		}
525756f23fdbSFilipe Manana 
525856f23fdbSFilipe Manana 		read_extent_buffer(eb, name, name_ptr, this_name_len);
5259e43eec81SSweet Tea Dorminy 
5260e43eec81SSweet Tea Dorminy 		name_str.name = name;
5261e43eec81SSweet Tea Dorminy 		name_str.len = this_name_len;
52624791c8f1SNikolay Borisov 		di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5263e43eec81SSweet Tea Dorminy 				parent, &name_str, 0);
526456f23fdbSFilipe Manana 		if (di && !IS_ERR(di)) {
526544f714daSFilipe Manana 			struct btrfs_key di_key;
526644f714daSFilipe Manana 
526744f714daSFilipe Manana 			btrfs_dir_item_key_to_cpu(search_path->nodes[0],
526844f714daSFilipe Manana 						  di, &di_key);
526944f714daSFilipe Manana 			if (di_key.type == BTRFS_INODE_ITEM_KEY) {
52706b5fc433SFilipe Manana 				if (di_key.objectid != key->objectid) {
527156f23fdbSFilipe Manana 					ret = 1;
527244f714daSFilipe Manana 					*other_ino = di_key.objectid;
5273a3baaf0dSFilipe Manana 					*other_parent = parent;
527444f714daSFilipe Manana 				} else {
52756b5fc433SFilipe Manana 					ret = 0;
52766b5fc433SFilipe Manana 				}
52776b5fc433SFilipe Manana 			} else {
527844f714daSFilipe Manana 				ret = -EAGAIN;
527944f714daSFilipe Manana 			}
528056f23fdbSFilipe Manana 			goto out;
528156f23fdbSFilipe Manana 		} else if (IS_ERR(di)) {
528256f23fdbSFilipe Manana 			ret = PTR_ERR(di);
528356f23fdbSFilipe Manana 			goto out;
528456f23fdbSFilipe Manana 		}
528556f23fdbSFilipe Manana 		btrfs_release_path(search_path);
528656f23fdbSFilipe Manana 
528756f23fdbSFilipe Manana 		cur_offset += this_len;
528856f23fdbSFilipe Manana 	}
528956f23fdbSFilipe Manana 	ret = 0;
529056f23fdbSFilipe Manana out:
529156f23fdbSFilipe Manana 	btrfs_free_path(search_path);
529256f23fdbSFilipe Manana 	kfree(name);
529356f23fdbSFilipe Manana 	return ret;
529456f23fdbSFilipe Manana }
529556f23fdbSFilipe Manana 
5296a3751024SFilipe Manana /*
5297a3751024SFilipe Manana  * Check if we need to log an inode. This is used in contexts where while
5298a3751024SFilipe Manana  * logging an inode we need to log another inode (either that it exists or in
5299a3751024SFilipe Manana  * full mode). This is used instead of btrfs_inode_in_log() because the later
5300a3751024SFilipe Manana  * requires the inode to be in the log and have the log transaction committed,
5301a3751024SFilipe Manana  * while here we do not care if the log transaction was already committed - our
5302a3751024SFilipe Manana  * caller will commit the log later - and we want to avoid logging an inode
5303a3751024SFilipe Manana  * multiple times when multiple tasks have joined the same log transaction.
5304a3751024SFilipe Manana  */
5305a3751024SFilipe Manana static bool need_log_inode(const struct btrfs_trans_handle *trans,
5306*bf1f4fd3SFilipe Manana 			   struct btrfs_inode *inode)
5307a3751024SFilipe Manana {
5308a3751024SFilipe Manana 	/*
5309a3751024SFilipe Manana 	 * If a directory was not modified, no dentries added or removed, we can
5310a3751024SFilipe Manana 	 * and should avoid logging it.
5311a3751024SFilipe Manana 	 */
5312a3751024SFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5313a3751024SFilipe Manana 		return false;
5314a3751024SFilipe Manana 
5315a3751024SFilipe Manana 	/*
5316a3751024SFilipe Manana 	 * If this inode does not have new/updated/deleted xattrs since the last
5317a3751024SFilipe Manana 	 * time it was logged and is flagged as logged in the current transaction,
5318a3751024SFilipe Manana 	 * we can skip logging it. As for new/deleted names, those are updated in
5319a3751024SFilipe Manana 	 * the log by link/unlink/rename operations.
5320a3751024SFilipe Manana 	 * In case the inode was logged and then evicted and reloaded, its
5321a3751024SFilipe Manana 	 * logged_trans will be 0, in which case we have to fully log it since
5322a3751024SFilipe Manana 	 * logged_trans is a transient field, not persisted.
5323a3751024SFilipe Manana 	 */
5324*bf1f4fd3SFilipe Manana 	if (inode_logged(trans, inode, NULL) == 1 &&
5325a3751024SFilipe Manana 	    !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5326a3751024SFilipe Manana 		return false;
5327a3751024SFilipe Manana 
5328a3751024SFilipe Manana 	return true;
5329a3751024SFilipe Manana }
5330a3751024SFilipe Manana 
5331f6d86dbeSFilipe Manana struct btrfs_dir_list {
5332f6d86dbeSFilipe Manana 	u64 ino;
5333f6d86dbeSFilipe Manana 	struct list_head list;
5334f6d86dbeSFilipe Manana };
5335f6d86dbeSFilipe Manana 
5336f6d86dbeSFilipe Manana /*
5337f6d86dbeSFilipe Manana  * Log the inodes of the new dentries of a directory.
5338f6d86dbeSFilipe Manana  * See process_dir_items_leaf() for details about why it is needed.
5339f6d86dbeSFilipe Manana  * This is a recursive operation - if an existing dentry corresponds to a
5340f6d86dbeSFilipe Manana  * directory, that directory's new entries are logged too (same behaviour as
5341f6d86dbeSFilipe Manana  * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5342f6d86dbeSFilipe Manana  * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5343f6d86dbeSFilipe Manana  * complains about the following circular lock dependency / possible deadlock:
5344f6d86dbeSFilipe Manana  *
5345f6d86dbeSFilipe Manana  *        CPU0                                        CPU1
5346f6d86dbeSFilipe Manana  *        ----                                        ----
5347f6d86dbeSFilipe Manana  * lock(&type->i_mutex_dir_key#3/2);
5348f6d86dbeSFilipe Manana  *                                            lock(sb_internal#2);
5349f6d86dbeSFilipe Manana  *                                            lock(&type->i_mutex_dir_key#3/2);
5350f6d86dbeSFilipe Manana  * lock(&sb->s_type->i_mutex_key#14);
5351f6d86dbeSFilipe Manana  *
5352f6d86dbeSFilipe Manana  * Where sb_internal is the lock (a counter that works as a lock) acquired by
5353f6d86dbeSFilipe Manana  * sb_start_intwrite() in btrfs_start_transaction().
5354f6d86dbeSFilipe Manana  * Not acquiring the VFS lock of the inodes is still safe because:
5355f6d86dbeSFilipe Manana  *
5356f6d86dbeSFilipe Manana  * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5357f6d86dbeSFilipe Manana  *    that while logging the inode new references (names) are added or removed
5358f6d86dbeSFilipe Manana  *    from the inode, leaving the logged inode item with a link count that does
5359f6d86dbeSFilipe Manana  *    not match the number of logged inode reference items. This is fine because
5360f6d86dbeSFilipe Manana  *    at log replay time we compute the real number of links and correct the
5361f6d86dbeSFilipe Manana  *    link count in the inode item (see replay_one_buffer() and
5362f6d86dbeSFilipe Manana  *    link_to_fixup_dir());
5363f6d86dbeSFilipe Manana  *
5364f6d86dbeSFilipe Manana  * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5365f6d86dbeSFilipe Manana  *    while logging the inode's items new index items (key type
5366f6d86dbeSFilipe Manana  *    BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5367f6d86dbeSFilipe Manana  *    has a size that doesn't match the sum of the lengths of all the logged
5368f6d86dbeSFilipe Manana  *    names - this is ok, not a problem, because at log replay time we set the
5369f6d86dbeSFilipe Manana  *    directory's i_size to the correct value (see replay_one_name() and
53703a8d1db3SFilipe Manana  *    overwrite_item()).
5371f6d86dbeSFilipe Manana  */
5372f6d86dbeSFilipe Manana static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5373f6d86dbeSFilipe Manana 				struct btrfs_inode *start_inode,
5374f6d86dbeSFilipe Manana 				struct btrfs_log_ctx *ctx)
5375f6d86dbeSFilipe Manana {
5376f6d86dbeSFilipe Manana 	struct btrfs_root *root = start_inode->root;
5377f6d86dbeSFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
5378f6d86dbeSFilipe Manana 	struct btrfs_path *path;
5379f6d86dbeSFilipe Manana 	LIST_HEAD(dir_list);
5380f6d86dbeSFilipe Manana 	struct btrfs_dir_list *dir_elem;
5381f6d86dbeSFilipe Manana 	u64 ino = btrfs_ino(start_inode);
5382fa4b8cb1SFilipe Manana 	struct btrfs_inode *curr_inode = start_inode;
5383f6d86dbeSFilipe Manana 	int ret = 0;
5384f6d86dbeSFilipe Manana 
5385f6d86dbeSFilipe Manana 	/*
5386f6d86dbeSFilipe Manana 	 * If we are logging a new name, as part of a link or rename operation,
5387f6d86dbeSFilipe Manana 	 * don't bother logging new dentries, as we just want to log the names
5388f6d86dbeSFilipe Manana 	 * of an inode and that any new parents exist.
5389f6d86dbeSFilipe Manana 	 */
5390f6d86dbeSFilipe Manana 	if (ctx->logging_new_name)
5391f6d86dbeSFilipe Manana 		return 0;
5392f6d86dbeSFilipe Manana 
5393f6d86dbeSFilipe Manana 	path = btrfs_alloc_path();
5394f6d86dbeSFilipe Manana 	if (!path)
5395f6d86dbeSFilipe Manana 		return -ENOMEM;
5396f6d86dbeSFilipe Manana 
5397fa4b8cb1SFilipe Manana 	/* Pairs with btrfs_add_delayed_iput below. */
5398fa4b8cb1SFilipe Manana 	ihold(&curr_inode->vfs_inode);
5399fa4b8cb1SFilipe Manana 
5400f6d86dbeSFilipe Manana 	while (true) {
5401fa4b8cb1SFilipe Manana 		struct inode *vfs_inode;
54025d3e4f1dSFilipe Manana 		struct btrfs_key key;
54035d3e4f1dSFilipe Manana 		struct btrfs_key found_key;
5404fa4b8cb1SFilipe Manana 		u64 next_index;
5405f6d86dbeSFilipe Manana 		bool continue_curr_inode = true;
54065d3e4f1dSFilipe Manana 		int iter_ret;
5407f6d86dbeSFilipe Manana 
54085d3e4f1dSFilipe Manana 		key.objectid = ino;
54095d3e4f1dSFilipe Manana 		key.type = BTRFS_DIR_INDEX_KEY;
54105d3e4f1dSFilipe Manana 		key.offset = btrfs_get_first_dir_index_to_log(curr_inode);
54115d3e4f1dSFilipe Manana 		next_index = key.offset;
5412f6d86dbeSFilipe Manana again:
54135d3e4f1dSFilipe Manana 		btrfs_for_each_slot(root->log_root, &key, &found_key, path, iter_ret) {
54145d3e4f1dSFilipe Manana 			struct extent_buffer *leaf = path->nodes[0];
5415f6d86dbeSFilipe Manana 			struct btrfs_dir_item *di;
5416f6d86dbeSFilipe Manana 			struct btrfs_key di_key;
5417f6d86dbeSFilipe Manana 			struct inode *di_inode;
5418f6d86dbeSFilipe Manana 			int log_mode = LOG_INODE_EXISTS;
5419f6d86dbeSFilipe Manana 			int type;
5420f6d86dbeSFilipe Manana 
54215d3e4f1dSFilipe Manana 			if (found_key.objectid != ino ||
54225d3e4f1dSFilipe Manana 			    found_key.type != BTRFS_DIR_INDEX_KEY) {
5423f6d86dbeSFilipe Manana 				continue_curr_inode = false;
5424f6d86dbeSFilipe Manana 				break;
5425f6d86dbeSFilipe Manana 			}
5426f6d86dbeSFilipe Manana 
54275d3e4f1dSFilipe Manana 			next_index = found_key.offset + 1;
5428fa4b8cb1SFilipe Manana 
54295d3e4f1dSFilipe Manana 			di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
543094a48aefSOmar Sandoval 			type = btrfs_dir_ftype(leaf, di);
5431f6d86dbeSFilipe Manana 			if (btrfs_dir_transid(leaf, di) < trans->transid)
5432f6d86dbeSFilipe Manana 				continue;
5433f6d86dbeSFilipe Manana 			btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5434f6d86dbeSFilipe Manana 			if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5435f6d86dbeSFilipe Manana 				continue;
5436f6d86dbeSFilipe Manana 
5437f6d86dbeSFilipe Manana 			btrfs_release_path(path);
5438f6d86dbeSFilipe Manana 			di_inode = btrfs_iget(fs_info->sb, di_key.objectid, root);
5439f6d86dbeSFilipe Manana 			if (IS_ERR(di_inode)) {
5440f6d86dbeSFilipe Manana 				ret = PTR_ERR(di_inode);
5441f6d86dbeSFilipe Manana 				goto out;
5442f6d86dbeSFilipe Manana 			}
5443f6d86dbeSFilipe Manana 
5444f6d86dbeSFilipe Manana 			if (!need_log_inode(trans, BTRFS_I(di_inode))) {
5445e55cf7caSDavid Sterba 				btrfs_add_delayed_iput(BTRFS_I(di_inode));
5446f6d86dbeSFilipe Manana 				break;
5447f6d86dbeSFilipe Manana 			}
5448f6d86dbeSFilipe Manana 
5449f6d86dbeSFilipe Manana 			ctx->log_new_dentries = false;
5450f6d86dbeSFilipe Manana 			if (type == BTRFS_FT_DIR)
5451f6d86dbeSFilipe Manana 				log_mode = LOG_INODE_ALL;
5452f6d86dbeSFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(di_inode),
5453f6d86dbeSFilipe Manana 					      log_mode, ctx);
5454e55cf7caSDavid Sterba 			btrfs_add_delayed_iput(BTRFS_I(di_inode));
5455f6d86dbeSFilipe Manana 			if (ret)
5456f6d86dbeSFilipe Manana 				goto out;
5457f6d86dbeSFilipe Manana 			if (ctx->log_new_dentries) {
5458f6d86dbeSFilipe Manana 				dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5459f6d86dbeSFilipe Manana 				if (!dir_elem) {
5460f6d86dbeSFilipe Manana 					ret = -ENOMEM;
5461f6d86dbeSFilipe Manana 					goto out;
5462f6d86dbeSFilipe Manana 				}
5463f6d86dbeSFilipe Manana 				dir_elem->ino = di_key.objectid;
5464f6d86dbeSFilipe Manana 				list_add_tail(&dir_elem->list, &dir_list);
5465f6d86dbeSFilipe Manana 			}
5466f6d86dbeSFilipe Manana 			break;
5467f6d86dbeSFilipe Manana 		}
5468f6d86dbeSFilipe Manana 
5469fa4b8cb1SFilipe Manana 		btrfs_release_path(path);
5470fa4b8cb1SFilipe Manana 
54715d3e4f1dSFilipe Manana 		if (iter_ret < 0) {
54725d3e4f1dSFilipe Manana 			ret = iter_ret;
54735d3e4f1dSFilipe Manana 			goto out;
54745d3e4f1dSFilipe Manana 		} else if (iter_ret > 0) {
54755d3e4f1dSFilipe Manana 			continue_curr_inode = false;
54765d3e4f1dSFilipe Manana 		} else {
54775d3e4f1dSFilipe Manana 			key = found_key;
54785d3e4f1dSFilipe Manana 		}
54795d3e4f1dSFilipe Manana 
54805d3e4f1dSFilipe Manana 		if (continue_curr_inode && key.offset < (u64)-1) {
54815d3e4f1dSFilipe Manana 			key.offset++;
5482f6d86dbeSFilipe Manana 			goto again;
5483f6d86dbeSFilipe Manana 		}
5484f6d86dbeSFilipe Manana 
5485fa4b8cb1SFilipe Manana 		btrfs_set_first_dir_index_to_log(curr_inode, next_index);
5486fa4b8cb1SFilipe Manana 
5487f6d86dbeSFilipe Manana 		if (list_empty(&dir_list))
5488f6d86dbeSFilipe Manana 			break;
5489f6d86dbeSFilipe Manana 
5490f6d86dbeSFilipe Manana 		dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
5491f6d86dbeSFilipe Manana 		ino = dir_elem->ino;
5492f6d86dbeSFilipe Manana 		list_del(&dir_elem->list);
5493f6d86dbeSFilipe Manana 		kfree(dir_elem);
5494fa4b8cb1SFilipe Manana 
5495fa4b8cb1SFilipe Manana 		btrfs_add_delayed_iput(curr_inode);
5496fa4b8cb1SFilipe Manana 		curr_inode = NULL;
5497fa4b8cb1SFilipe Manana 
5498fa4b8cb1SFilipe Manana 		vfs_inode = btrfs_iget(fs_info->sb, ino, root);
5499fa4b8cb1SFilipe Manana 		if (IS_ERR(vfs_inode)) {
5500fa4b8cb1SFilipe Manana 			ret = PTR_ERR(vfs_inode);
5501fa4b8cb1SFilipe Manana 			break;
5502fa4b8cb1SFilipe Manana 		}
5503fa4b8cb1SFilipe Manana 		curr_inode = BTRFS_I(vfs_inode);
5504f6d86dbeSFilipe Manana 	}
5505f6d86dbeSFilipe Manana out:
5506f6d86dbeSFilipe Manana 	btrfs_free_path(path);
5507fa4b8cb1SFilipe Manana 	if (curr_inode)
5508fa4b8cb1SFilipe Manana 		btrfs_add_delayed_iput(curr_inode);
5509fa4b8cb1SFilipe Manana 
5510f6d86dbeSFilipe Manana 	if (ret) {
5511f6d86dbeSFilipe Manana 		struct btrfs_dir_list *next;
5512f6d86dbeSFilipe Manana 
5513f6d86dbeSFilipe Manana 		list_for_each_entry_safe(dir_elem, next, &dir_list, list)
5514f6d86dbeSFilipe Manana 			kfree(dir_elem);
5515f6d86dbeSFilipe Manana 	}
5516f6d86dbeSFilipe Manana 
5517f6d86dbeSFilipe Manana 	return ret;
5518f6d86dbeSFilipe Manana }
5519f6d86dbeSFilipe Manana 
55206b5fc433SFilipe Manana struct btrfs_ino_list {
55216b5fc433SFilipe Manana 	u64 ino;
5522a3baaf0dSFilipe Manana 	u64 parent;
55236b5fc433SFilipe Manana 	struct list_head list;
55246b5fc433SFilipe Manana };
55256b5fc433SFilipe Manana 
5526e09d94c9SFilipe Manana static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
5527e09d94c9SFilipe Manana {
5528e09d94c9SFilipe Manana 	struct btrfs_ino_list *curr;
5529e09d94c9SFilipe Manana 	struct btrfs_ino_list *next;
5530e09d94c9SFilipe Manana 
5531e09d94c9SFilipe Manana 	list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
5532e09d94c9SFilipe Manana 		list_del(&curr->list);
5533e09d94c9SFilipe Manana 		kfree(curr);
5534e09d94c9SFilipe Manana 	}
5535e09d94c9SFilipe Manana }
5536e09d94c9SFilipe Manana 
55375557a069SFilipe Manana static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
55385557a069SFilipe Manana 				    struct btrfs_path *path)
55395557a069SFilipe Manana {
55405557a069SFilipe Manana 	struct btrfs_key key;
55415557a069SFilipe Manana 	int ret;
55425557a069SFilipe Manana 
55435557a069SFilipe Manana 	key.objectid = ino;
55445557a069SFilipe Manana 	key.type = BTRFS_INODE_ITEM_KEY;
55455557a069SFilipe Manana 	key.offset = 0;
55465557a069SFilipe Manana 
55475557a069SFilipe Manana 	path->search_commit_root = 1;
55485557a069SFilipe Manana 	path->skip_locking = 1;
55495557a069SFilipe Manana 
55505557a069SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
55515557a069SFilipe Manana 	if (WARN_ON_ONCE(ret > 0)) {
55525557a069SFilipe Manana 		/*
55535557a069SFilipe Manana 		 * We have previously found the inode through the commit root
55545557a069SFilipe Manana 		 * so this should not happen. If it does, just error out and
55555557a069SFilipe Manana 		 * fallback to a transaction commit.
55565557a069SFilipe Manana 		 */
55575557a069SFilipe Manana 		ret = -ENOENT;
55585557a069SFilipe Manana 	} else if (ret == 0) {
55595557a069SFilipe Manana 		struct btrfs_inode_item *item;
55605557a069SFilipe Manana 
55615557a069SFilipe Manana 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
55625557a069SFilipe Manana 				      struct btrfs_inode_item);
55635557a069SFilipe Manana 		if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
55645557a069SFilipe Manana 			ret = 1;
55655557a069SFilipe Manana 	}
55665557a069SFilipe Manana 
55675557a069SFilipe Manana 	btrfs_release_path(path);
55685557a069SFilipe Manana 	path->search_commit_root = 0;
55695557a069SFilipe Manana 	path->skip_locking = 0;
55705557a069SFilipe Manana 
55715557a069SFilipe Manana 	return ret;
55725557a069SFilipe Manana }
55735557a069SFilipe Manana 
5574e09d94c9SFilipe Manana static int add_conflicting_inode(struct btrfs_trans_handle *trans,
55756b5fc433SFilipe Manana 				 struct btrfs_root *root,
55765557a069SFilipe Manana 				 struct btrfs_path *path,
5577e09d94c9SFilipe Manana 				 u64 ino, u64 parent,
5578e09d94c9SFilipe Manana 				 struct btrfs_log_ctx *ctx)
55796b5fc433SFilipe Manana {
55806b5fc433SFilipe Manana 	struct btrfs_ino_list *ino_elem;
5581e09d94c9SFilipe Manana 	struct inode *inode;
5582e09d94c9SFilipe Manana 
5583e09d94c9SFilipe Manana 	/*
5584e09d94c9SFilipe Manana 	 * It's rare to have a lot of conflicting inodes, in practice it is not
5585e09d94c9SFilipe Manana 	 * common to have more than 1 or 2. We don't want to collect too many,
5586e09d94c9SFilipe Manana 	 * as we could end up logging too many inodes (even if only in
5587e09d94c9SFilipe Manana 	 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
5588e09d94c9SFilipe Manana 	 * commits.
5589e09d94c9SFilipe Manana 	 */
55905cce1780SFilipe Manana 	if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES)
5591e09d94c9SFilipe Manana 		return BTRFS_LOG_FORCE_COMMIT;
5592e09d94c9SFilipe Manana 
5593e09d94c9SFilipe Manana 	inode = btrfs_iget(root->fs_info->sb, ino, root);
5594e09d94c9SFilipe Manana 	/*
5595e09d94c9SFilipe Manana 	 * If the other inode that had a conflicting dir entry was deleted in
55965557a069SFilipe Manana 	 * the current transaction then we either:
55975557a069SFilipe Manana 	 *
55985557a069SFilipe Manana 	 * 1) Log the parent directory (later after adding it to the list) if
55995557a069SFilipe Manana 	 *    the inode is a directory. This is because it may be a deleted
56005557a069SFilipe Manana 	 *    subvolume/snapshot or it may be a regular directory that had
56015557a069SFilipe Manana 	 *    deleted subvolumes/snapshots (or subdirectories that had them),
56025557a069SFilipe Manana 	 *    and at the moment we can't deal with dropping subvolumes/snapshots
56035557a069SFilipe Manana 	 *    during log replay. So we just log the parent, which will result in
56045557a069SFilipe Manana 	 *    a fallback to a transaction commit if we are dealing with those
56055557a069SFilipe Manana 	 *    cases (last_unlink_trans will match the current transaction);
56065557a069SFilipe Manana 	 *
56075557a069SFilipe Manana 	 * 2) Do nothing if it's not a directory. During log replay we simply
56085557a069SFilipe Manana 	 *    unlink the conflicting dentry from the parent directory and then
56095557a069SFilipe Manana 	 *    add the dentry for our inode. Like this we can avoid logging the
56105557a069SFilipe Manana 	 *    parent directory (and maybe fallback to a transaction commit in
56115557a069SFilipe Manana 	 *    case it has a last_unlink_trans == trans->transid, due to moving
56125557a069SFilipe Manana 	 *    some inode from it to some other directory).
5613e09d94c9SFilipe Manana 	 */
5614e09d94c9SFilipe Manana 	if (IS_ERR(inode)) {
5615e09d94c9SFilipe Manana 		int ret = PTR_ERR(inode);
5616e09d94c9SFilipe Manana 
5617e09d94c9SFilipe Manana 		if (ret != -ENOENT)
5618e09d94c9SFilipe Manana 			return ret;
56196b5fc433SFilipe Manana 
56205557a069SFilipe Manana 		ret = conflicting_inode_is_dir(root, ino, path);
56215557a069SFilipe Manana 		/* Not a directory or we got an error. */
56225557a069SFilipe Manana 		if (ret <= 0)
56235557a069SFilipe Manana 			return ret;
56245557a069SFilipe Manana 
56255557a069SFilipe Manana 		/* Conflicting inode is a directory, so we'll log its parent. */
56266b5fc433SFilipe Manana 		ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
56276b5fc433SFilipe Manana 		if (!ino_elem)
56286b5fc433SFilipe Manana 			return -ENOMEM;
56296b5fc433SFilipe Manana 		ino_elem->ino = ino;
5630a3baaf0dSFilipe Manana 		ino_elem->parent = parent;
5631e09d94c9SFilipe Manana 		list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5632e09d94c9SFilipe Manana 		ctx->num_conflict_inodes++;
56336b5fc433SFilipe Manana 
5634e09d94c9SFilipe Manana 		return 0;
5635e09d94c9SFilipe Manana 	}
56366b5fc433SFilipe Manana 
56376b5fc433SFilipe Manana 	/*
5638e09d94c9SFilipe Manana 	 * If the inode was already logged skip it - otherwise we can hit an
5639e09d94c9SFilipe Manana 	 * infinite loop. Example:
5640b5e4ff9dSFilipe Manana 	 *
5641e09d94c9SFilipe Manana 	 * From the commit root (previous transaction) we have the following
5642e09d94c9SFilipe Manana 	 * inodes:
5643b5e4ff9dSFilipe Manana 	 *
5644b5e4ff9dSFilipe Manana 	 * inode 257 a directory
5645b5e4ff9dSFilipe Manana 	 * inode 258 with references "zz" and "zz_link" on inode 257
5646b5e4ff9dSFilipe Manana 	 * inode 259 with reference "a" on inode 257
5647b5e4ff9dSFilipe Manana 	 *
5648b5e4ff9dSFilipe Manana 	 * And in the current (uncommitted) transaction we have:
5649b5e4ff9dSFilipe Manana 	 *
5650b5e4ff9dSFilipe Manana 	 * inode 257 a directory, unchanged
5651b5e4ff9dSFilipe Manana 	 * inode 258 with references "a" and "a2" on inode 257
5652b5e4ff9dSFilipe Manana 	 * inode 259 with reference "zz_link" on inode 257
5653b5e4ff9dSFilipe Manana 	 * inode 261 with reference "zz" on inode 257
5654b5e4ff9dSFilipe Manana 	 *
5655b5e4ff9dSFilipe Manana 	 * When logging inode 261 the following infinite loop could
5656b5e4ff9dSFilipe Manana 	 * happen if we don't skip already logged inodes:
5657b5e4ff9dSFilipe Manana 	 *
5658b5e4ff9dSFilipe Manana 	 * - we detect inode 258 as a conflicting inode, with inode 261
5659b5e4ff9dSFilipe Manana 	 *   on reference "zz", and log it;
5660b5e4ff9dSFilipe Manana 	 *
5661b5e4ff9dSFilipe Manana 	 * - we detect inode 259 as a conflicting inode, with inode 258
5662b5e4ff9dSFilipe Manana 	 *   on reference "a", and log it;
5663b5e4ff9dSFilipe Manana 	 *
5664b5e4ff9dSFilipe Manana 	 * - we detect inode 258 as a conflicting inode, with inode 259
5665b5e4ff9dSFilipe Manana 	 *   on reference "zz_link", and log it - again! After this we
5666b5e4ff9dSFilipe Manana 	 *   repeat the above steps forever.
5667e09d94c9SFilipe Manana 	 *
5668e09d94c9SFilipe Manana 	 * Here we can use need_log_inode() because we only need to log the
5669e09d94c9SFilipe Manana 	 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
5670e09d94c9SFilipe Manana 	 * so that the log ends up with the new name and without the old name.
5671b5e4ff9dSFilipe Manana 	 */
5672e09d94c9SFilipe Manana 	if (!need_log_inode(trans, BTRFS_I(inode))) {
5673e55cf7caSDavid Sterba 		btrfs_add_delayed_iput(BTRFS_I(inode));
5674e09d94c9SFilipe Manana 		return 0;
5675e09d94c9SFilipe Manana 	}
5676e09d94c9SFilipe Manana 
5677e55cf7caSDavid Sterba 	btrfs_add_delayed_iput(BTRFS_I(inode));
5678e09d94c9SFilipe Manana 
5679e09d94c9SFilipe Manana 	ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
5680e09d94c9SFilipe Manana 	if (!ino_elem)
5681e09d94c9SFilipe Manana 		return -ENOMEM;
5682e09d94c9SFilipe Manana 	ino_elem->ino = ino;
5683e09d94c9SFilipe Manana 	ino_elem->parent = parent;
5684e09d94c9SFilipe Manana 	list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
5685e09d94c9SFilipe Manana 	ctx->num_conflict_inodes++;
5686e09d94c9SFilipe Manana 
5687e09d94c9SFilipe Manana 	return 0;
5688e09d94c9SFilipe Manana }
5689e09d94c9SFilipe Manana 
5690e09d94c9SFilipe Manana static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
5691e09d94c9SFilipe Manana 				  struct btrfs_root *root,
5692e09d94c9SFilipe Manana 				  struct btrfs_log_ctx *ctx)
5693e09d94c9SFilipe Manana {
5694e09d94c9SFilipe Manana 	struct btrfs_fs_info *fs_info = root->fs_info;
5695e09d94c9SFilipe Manana 	int ret = 0;
5696e09d94c9SFilipe Manana 
5697b5e4ff9dSFilipe Manana 	/*
5698e09d94c9SFilipe Manana 	 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
5699e09d94c9SFilipe Manana 	 * otherwise we could have unbounded recursion of btrfs_log_inode()
5700e09d94c9SFilipe Manana 	 * calls. This check guarantees we can have only 1 level of recursion.
5701b5e4ff9dSFilipe Manana 	 */
5702e09d94c9SFilipe Manana 	if (ctx->logging_conflict_inodes)
5703e09d94c9SFilipe Manana 		return 0;
5704e09d94c9SFilipe Manana 
5705e09d94c9SFilipe Manana 	ctx->logging_conflict_inodes = true;
5706e09d94c9SFilipe Manana 
5707e09d94c9SFilipe Manana 	/*
5708e09d94c9SFilipe Manana 	 * New conflicting inodes may be found and added to the list while we
5709e09d94c9SFilipe Manana 	 * are logging a conflicting inode, so keep iterating while the list is
5710e09d94c9SFilipe Manana 	 * not empty.
5711e09d94c9SFilipe Manana 	 */
5712e09d94c9SFilipe Manana 	while (!list_empty(&ctx->conflict_inodes)) {
5713e09d94c9SFilipe Manana 		struct btrfs_ino_list *curr;
5714e09d94c9SFilipe Manana 		struct inode *inode;
5715e09d94c9SFilipe Manana 		u64 ino;
5716e09d94c9SFilipe Manana 		u64 parent;
5717e09d94c9SFilipe Manana 
5718e09d94c9SFilipe Manana 		curr = list_first_entry(&ctx->conflict_inodes,
5719e09d94c9SFilipe Manana 					struct btrfs_ino_list, list);
5720e09d94c9SFilipe Manana 		ino = curr->ino;
5721e09d94c9SFilipe Manana 		parent = curr->parent;
5722e09d94c9SFilipe Manana 		list_del(&curr->list);
5723e09d94c9SFilipe Manana 		kfree(curr);
5724e09d94c9SFilipe Manana 
5725e09d94c9SFilipe Manana 		inode = btrfs_iget(fs_info->sb, ino, root);
5726e09d94c9SFilipe Manana 		/*
5727e09d94c9SFilipe Manana 		 * If the other inode that had a conflicting dir entry was
5728e09d94c9SFilipe Manana 		 * deleted in the current transaction, we need to log its parent
5729e09d94c9SFilipe Manana 		 * directory. See the comment at add_conflicting_inode().
5730e09d94c9SFilipe Manana 		 */
5731e09d94c9SFilipe Manana 		if (IS_ERR(inode)) {
5732e09d94c9SFilipe Manana 			ret = PTR_ERR(inode);
5733e09d94c9SFilipe Manana 			if (ret != -ENOENT)
5734e09d94c9SFilipe Manana 				break;
5735e09d94c9SFilipe Manana 
5736e09d94c9SFilipe Manana 			inode = btrfs_iget(fs_info->sb, parent, root);
5737e09d94c9SFilipe Manana 			if (IS_ERR(inode)) {
5738e09d94c9SFilipe Manana 				ret = PTR_ERR(inode);
5739e09d94c9SFilipe Manana 				break;
5740e09d94c9SFilipe Manana 			}
5741e09d94c9SFilipe Manana 
5742e09d94c9SFilipe Manana 			/*
5743e09d94c9SFilipe Manana 			 * Always log the directory, we cannot make this
5744e09d94c9SFilipe Manana 			 * conditional on need_log_inode() because the directory
5745e09d94c9SFilipe Manana 			 * might have been logged in LOG_INODE_EXISTS mode or
5746e09d94c9SFilipe Manana 			 * the dir index of the conflicting inode is not in a
5747e09d94c9SFilipe Manana 			 * dir index key range logged for the directory. So we
5748e09d94c9SFilipe Manana 			 * must make sure the deletion is recorded.
5749e09d94c9SFilipe Manana 			 */
5750e09d94c9SFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(inode),
5751e09d94c9SFilipe Manana 					      LOG_INODE_ALL, ctx);
5752e55cf7caSDavid Sterba 			btrfs_add_delayed_iput(BTRFS_I(inode));
5753e09d94c9SFilipe Manana 			if (ret)
5754e09d94c9SFilipe Manana 				break;
5755e09d94c9SFilipe Manana 			continue;
5756e09d94c9SFilipe Manana 		}
5757e09d94c9SFilipe Manana 
5758e09d94c9SFilipe Manana 		/*
5759e09d94c9SFilipe Manana 		 * Here we can use need_log_inode() because we only need to log
5760e09d94c9SFilipe Manana 		 * the inode in LOG_INODE_EXISTS mode and rename operations
5761e09d94c9SFilipe Manana 		 * update the log, so that the log ends up with the new name and
5762e09d94c9SFilipe Manana 		 * without the old name.
5763e09d94c9SFilipe Manana 		 *
5764e09d94c9SFilipe Manana 		 * We did this check at add_conflicting_inode(), but here we do
5765e09d94c9SFilipe Manana 		 * it again because if some other task logged the inode after
5766e09d94c9SFilipe Manana 		 * that, we can avoid doing it again.
5767e09d94c9SFilipe Manana 		 */
5768e09d94c9SFilipe Manana 		if (!need_log_inode(trans, BTRFS_I(inode))) {
5769e55cf7caSDavid Sterba 			btrfs_add_delayed_iput(BTRFS_I(inode));
5770b5e4ff9dSFilipe Manana 			continue;
5771b5e4ff9dSFilipe Manana 		}
5772e09d94c9SFilipe Manana 
5773b5e4ff9dSFilipe Manana 		/*
57746b5fc433SFilipe Manana 		 * We are safe logging the other inode without acquiring its
57756b5fc433SFilipe Manana 		 * lock as long as we log with the LOG_INODE_EXISTS mode. We
57766b5fc433SFilipe Manana 		 * are safe against concurrent renames of the other inode as
57776b5fc433SFilipe Manana 		 * well because during a rename we pin the log and update the
57786b5fc433SFilipe Manana 		 * log with the new name before we unpin it.
57796b5fc433SFilipe Manana 		 */
5780e09d94c9SFilipe Manana 		ret = btrfs_log_inode(trans, BTRFS_I(inode), LOG_INODE_EXISTS, ctx);
5781e55cf7caSDavid Sterba 		btrfs_add_delayed_iput(BTRFS_I(inode));
5782e09d94c9SFilipe Manana 		if (ret)
57836b5fc433SFilipe Manana 			break;
57846b5fc433SFilipe Manana 	}
57856b5fc433SFilipe Manana 
5786e09d94c9SFilipe Manana 	ctx->logging_conflict_inodes = false;
5787e09d94c9SFilipe Manana 	if (ret)
5788e09d94c9SFilipe Manana 		free_conflicting_inodes(ctx);
57896b5fc433SFilipe Manana 
57906b5fc433SFilipe Manana 	return ret;
57916b5fc433SFilipe Manana }
57926b5fc433SFilipe Manana 
5793da447009SFilipe Manana static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
5794da447009SFilipe Manana 				   struct btrfs_inode *inode,
5795da447009SFilipe Manana 				   struct btrfs_key *min_key,
5796da447009SFilipe Manana 				   const struct btrfs_key *max_key,
5797da447009SFilipe Manana 				   struct btrfs_path *path,
5798da447009SFilipe Manana 				   struct btrfs_path *dst_path,
5799da447009SFilipe Manana 				   const u64 logged_isize,
5800da447009SFilipe Manana 				   const int inode_only,
5801da447009SFilipe Manana 				   struct btrfs_log_ctx *ctx,
5802da447009SFilipe Manana 				   bool *need_log_inode_item)
5803da447009SFilipe Manana {
5804d9947887SFilipe Manana 	const u64 i_size = i_size_read(&inode->vfs_inode);
5805da447009SFilipe Manana 	struct btrfs_root *root = inode->root;
5806da447009SFilipe Manana 	int ins_start_slot = 0;
5807da447009SFilipe Manana 	int ins_nr = 0;
5808da447009SFilipe Manana 	int ret;
5809da447009SFilipe Manana 
5810da447009SFilipe Manana 	while (1) {
5811da447009SFilipe Manana 		ret = btrfs_search_forward(root, min_key, path, trans->transid);
5812da447009SFilipe Manana 		if (ret < 0)
5813da447009SFilipe Manana 			return ret;
5814da447009SFilipe Manana 		if (ret > 0) {
5815da447009SFilipe Manana 			ret = 0;
5816da447009SFilipe Manana 			break;
5817da447009SFilipe Manana 		}
5818da447009SFilipe Manana again:
5819da447009SFilipe Manana 		/* Note, ins_nr might be > 0 here, cleanup outside the loop */
5820da447009SFilipe Manana 		if (min_key->objectid != max_key->objectid)
5821da447009SFilipe Manana 			break;
5822da447009SFilipe Manana 		if (min_key->type > max_key->type)
5823da447009SFilipe Manana 			break;
5824da447009SFilipe Manana 
5825d9947887SFilipe Manana 		if (min_key->type == BTRFS_INODE_ITEM_KEY) {
5826da447009SFilipe Manana 			*need_log_inode_item = false;
5827d9947887SFilipe Manana 		} else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
5828d9947887SFilipe Manana 			   min_key->offset >= i_size) {
5829d9947887SFilipe Manana 			/*
5830d9947887SFilipe Manana 			 * Extents at and beyond eof are logged with
5831d9947887SFilipe Manana 			 * btrfs_log_prealloc_extents().
5832d9947887SFilipe Manana 			 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
5833d9947887SFilipe Manana 			 * and no keys greater than that, so bail out.
5834d9947887SFilipe Manana 			 */
5835d9947887SFilipe Manana 			break;
5836d9947887SFilipe Manana 		} else if ((min_key->type == BTRFS_INODE_REF_KEY ||
5837da447009SFilipe Manana 			    min_key->type == BTRFS_INODE_EXTREF_KEY) &&
5838e09d94c9SFilipe Manana 			   (inode->generation == trans->transid ||
5839e09d94c9SFilipe Manana 			    ctx->logging_conflict_inodes)) {
5840da447009SFilipe Manana 			u64 other_ino = 0;
5841da447009SFilipe Manana 			u64 other_parent = 0;
5842da447009SFilipe Manana 
5843da447009SFilipe Manana 			ret = btrfs_check_ref_name_override(path->nodes[0],
5844da447009SFilipe Manana 					path->slots[0], min_key, inode,
5845da447009SFilipe Manana 					&other_ino, &other_parent);
5846da447009SFilipe Manana 			if (ret < 0) {
5847da447009SFilipe Manana 				return ret;
5848289cffcbSFilipe Manana 			} else if (ret > 0 &&
5849da447009SFilipe Manana 				   other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5850da447009SFilipe Manana 				if (ins_nr > 0) {
5851da447009SFilipe Manana 					ins_nr++;
5852da447009SFilipe Manana 				} else {
5853da447009SFilipe Manana 					ins_nr = 1;
5854da447009SFilipe Manana 					ins_start_slot = path->slots[0];
5855da447009SFilipe Manana 				}
5856da447009SFilipe Manana 				ret = copy_items(trans, inode, dst_path, path,
5857da447009SFilipe Manana 						 ins_start_slot, ins_nr,
5858da447009SFilipe Manana 						 inode_only, logged_isize);
5859da447009SFilipe Manana 				if (ret < 0)
5860da447009SFilipe Manana 					return ret;
5861da447009SFilipe Manana 				ins_nr = 0;
5862da447009SFilipe Manana 
5863e09d94c9SFilipe Manana 				btrfs_release_path(path);
58645557a069SFilipe Manana 				ret = add_conflicting_inode(trans, root, path,
5865e09d94c9SFilipe Manana 							    other_ino,
5866e09d94c9SFilipe Manana 							    other_parent, ctx);
5867da447009SFilipe Manana 				if (ret)
5868da447009SFilipe Manana 					return ret;
5869da447009SFilipe Manana 				goto next_key;
5870da447009SFilipe Manana 			}
5871d9947887SFilipe Manana 		} else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
5872d9947887SFilipe Manana 			/* Skip xattrs, logged later with btrfs_log_all_xattrs() */
5873da447009SFilipe Manana 			if (ins_nr == 0)
5874da447009SFilipe Manana 				goto next_slot;
5875da447009SFilipe Manana 			ret = copy_items(trans, inode, dst_path, path,
5876da447009SFilipe Manana 					 ins_start_slot,
5877da447009SFilipe Manana 					 ins_nr, inode_only, logged_isize);
5878da447009SFilipe Manana 			if (ret < 0)
5879da447009SFilipe Manana 				return ret;
5880da447009SFilipe Manana 			ins_nr = 0;
5881da447009SFilipe Manana 			goto next_slot;
5882da447009SFilipe Manana 		}
5883da447009SFilipe Manana 
5884da447009SFilipe Manana 		if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5885da447009SFilipe Manana 			ins_nr++;
5886da447009SFilipe Manana 			goto next_slot;
5887da447009SFilipe Manana 		} else if (!ins_nr) {
5888da447009SFilipe Manana 			ins_start_slot = path->slots[0];
5889da447009SFilipe Manana 			ins_nr = 1;
5890da447009SFilipe Manana 			goto next_slot;
5891da447009SFilipe Manana 		}
5892da447009SFilipe Manana 
5893da447009SFilipe Manana 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5894da447009SFilipe Manana 				 ins_nr, inode_only, logged_isize);
5895da447009SFilipe Manana 		if (ret < 0)
5896da447009SFilipe Manana 			return ret;
5897da447009SFilipe Manana 		ins_nr = 1;
5898da447009SFilipe Manana 		ins_start_slot = path->slots[0];
5899da447009SFilipe Manana next_slot:
5900da447009SFilipe Manana 		path->slots[0]++;
5901da447009SFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
5902da447009SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], min_key,
5903da447009SFilipe Manana 					      path->slots[0]);
5904da447009SFilipe Manana 			goto again;
5905da447009SFilipe Manana 		}
5906da447009SFilipe Manana 		if (ins_nr) {
5907da447009SFilipe Manana 			ret = copy_items(trans, inode, dst_path, path,
5908da447009SFilipe Manana 					 ins_start_slot, ins_nr, inode_only,
5909da447009SFilipe Manana 					 logged_isize);
5910da447009SFilipe Manana 			if (ret < 0)
5911da447009SFilipe Manana 				return ret;
5912da447009SFilipe Manana 			ins_nr = 0;
5913da447009SFilipe Manana 		}
5914da447009SFilipe Manana 		btrfs_release_path(path);
5915da447009SFilipe Manana next_key:
5916da447009SFilipe Manana 		if (min_key->offset < (u64)-1) {
5917da447009SFilipe Manana 			min_key->offset++;
5918da447009SFilipe Manana 		} else if (min_key->type < max_key->type) {
5919da447009SFilipe Manana 			min_key->type++;
5920da447009SFilipe Manana 			min_key->offset = 0;
5921da447009SFilipe Manana 		} else {
5922da447009SFilipe Manana 			break;
5923da447009SFilipe Manana 		}
592496acb375SFilipe Manana 
592596acb375SFilipe Manana 		/*
592696acb375SFilipe Manana 		 * We may process many leaves full of items for our inode, so
592796acb375SFilipe Manana 		 * avoid monopolizing a cpu for too long by rescheduling while
592896acb375SFilipe Manana 		 * not holding locks on any tree.
592996acb375SFilipe Manana 		 */
593096acb375SFilipe Manana 		cond_resched();
5931da447009SFilipe Manana 	}
5932d9947887SFilipe Manana 	if (ins_nr) {
5933da447009SFilipe Manana 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5934da447009SFilipe Manana 				 ins_nr, inode_only, logged_isize);
5935d9947887SFilipe Manana 		if (ret)
5936d9947887SFilipe Manana 			return ret;
5937d9947887SFilipe Manana 	}
5938d9947887SFilipe Manana 
5939d9947887SFilipe Manana 	if (inode_only == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
5940d9947887SFilipe Manana 		/*
5941d9947887SFilipe Manana 		 * Release the path because otherwise we might attempt to double
5942d9947887SFilipe Manana 		 * lock the same leaf with btrfs_log_prealloc_extents() below.
5943d9947887SFilipe Manana 		 */
5944d9947887SFilipe Manana 		btrfs_release_path(path);
5945d9947887SFilipe Manana 		ret = btrfs_log_prealloc_extents(trans, inode, dst_path);
5946d9947887SFilipe Manana 	}
5947da447009SFilipe Manana 
5948da447009SFilipe Manana 	return ret;
5949da447009SFilipe Manana }
5950da447009SFilipe Manana 
595130b80f3cSFilipe Manana static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
595230b80f3cSFilipe Manana 				      struct btrfs_root *log,
595330b80f3cSFilipe Manana 				      struct btrfs_path *path,
595430b80f3cSFilipe Manana 				      const struct btrfs_item_batch *batch,
595530b80f3cSFilipe Manana 				      const struct btrfs_delayed_item *first_item)
595630b80f3cSFilipe Manana {
595730b80f3cSFilipe Manana 	const struct btrfs_delayed_item *curr = first_item;
595830b80f3cSFilipe Manana 	int ret;
595930b80f3cSFilipe Manana 
596030b80f3cSFilipe Manana 	ret = btrfs_insert_empty_items(trans, log, path, batch);
596130b80f3cSFilipe Manana 	if (ret)
596230b80f3cSFilipe Manana 		return ret;
596330b80f3cSFilipe Manana 
596430b80f3cSFilipe Manana 	for (int i = 0; i < batch->nr; i++) {
596530b80f3cSFilipe Manana 		char *data_ptr;
596630b80f3cSFilipe Manana 
596730b80f3cSFilipe Manana 		data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
596830b80f3cSFilipe Manana 		write_extent_buffer(path->nodes[0], &curr->data,
596930b80f3cSFilipe Manana 				    (unsigned long)data_ptr, curr->data_len);
597030b80f3cSFilipe Manana 		curr = list_next_entry(curr, log_list);
597130b80f3cSFilipe Manana 		path->slots[0]++;
597230b80f3cSFilipe Manana 	}
597330b80f3cSFilipe Manana 
597430b80f3cSFilipe Manana 	btrfs_release_path(path);
597530b80f3cSFilipe Manana 
597630b80f3cSFilipe Manana 	return 0;
597730b80f3cSFilipe Manana }
597830b80f3cSFilipe Manana 
597930b80f3cSFilipe Manana static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
598030b80f3cSFilipe Manana 				       struct btrfs_inode *inode,
598130b80f3cSFilipe Manana 				       struct btrfs_path *path,
598230b80f3cSFilipe Manana 				       const struct list_head *delayed_ins_list,
598330b80f3cSFilipe Manana 				       struct btrfs_log_ctx *ctx)
598430b80f3cSFilipe Manana {
598530b80f3cSFilipe Manana 	/* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
598630b80f3cSFilipe Manana 	const int max_batch_size = 195;
598730b80f3cSFilipe Manana 	const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
598830b80f3cSFilipe Manana 	const u64 ino = btrfs_ino(inode);
598930b80f3cSFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
599030b80f3cSFilipe Manana 	struct btrfs_item_batch batch = {
599130b80f3cSFilipe Manana 		.nr = 0,
599230b80f3cSFilipe Manana 		.total_data_size = 0,
599330b80f3cSFilipe Manana 	};
599430b80f3cSFilipe Manana 	const struct btrfs_delayed_item *first = NULL;
599530b80f3cSFilipe Manana 	const struct btrfs_delayed_item *curr;
599630b80f3cSFilipe Manana 	char *ins_data;
599730b80f3cSFilipe Manana 	struct btrfs_key *ins_keys;
599830b80f3cSFilipe Manana 	u32 *ins_sizes;
599930b80f3cSFilipe Manana 	u64 curr_batch_size = 0;
600030b80f3cSFilipe Manana 	int batch_idx = 0;
600130b80f3cSFilipe Manana 	int ret;
600230b80f3cSFilipe Manana 
600330b80f3cSFilipe Manana 	/* We are adding dir index items to the log tree. */
600430b80f3cSFilipe Manana 	lockdep_assert_held(&inode->log_mutex);
600530b80f3cSFilipe Manana 
600630b80f3cSFilipe Manana 	/*
600730b80f3cSFilipe Manana 	 * We collect delayed items before copying index keys from the subvolume
600830b80f3cSFilipe Manana 	 * to the log tree. However just after we collected them, they may have
600930b80f3cSFilipe Manana 	 * been flushed (all of them or just some of them), and therefore we
601030b80f3cSFilipe Manana 	 * could have copied them from the subvolume tree to the log tree.
601130b80f3cSFilipe Manana 	 * So find the first delayed item that was not yet logged (they are
601230b80f3cSFilipe Manana 	 * sorted by index number).
601330b80f3cSFilipe Manana 	 */
601430b80f3cSFilipe Manana 	list_for_each_entry(curr, delayed_ins_list, log_list) {
601530b80f3cSFilipe Manana 		if (curr->index > inode->last_dir_index_offset) {
601630b80f3cSFilipe Manana 			first = curr;
601730b80f3cSFilipe Manana 			break;
601830b80f3cSFilipe Manana 		}
601930b80f3cSFilipe Manana 	}
602030b80f3cSFilipe Manana 
602130b80f3cSFilipe Manana 	/* Empty list or all delayed items were already logged. */
602230b80f3cSFilipe Manana 	if (!first)
602330b80f3cSFilipe Manana 		return 0;
602430b80f3cSFilipe Manana 
602530b80f3cSFilipe Manana 	ins_data = kmalloc(max_batch_size * sizeof(u32) +
602630b80f3cSFilipe Manana 			   max_batch_size * sizeof(struct btrfs_key), GFP_NOFS);
602730b80f3cSFilipe Manana 	if (!ins_data)
602830b80f3cSFilipe Manana 		return -ENOMEM;
602930b80f3cSFilipe Manana 	ins_sizes = (u32 *)ins_data;
603030b80f3cSFilipe Manana 	batch.data_sizes = ins_sizes;
603130b80f3cSFilipe Manana 	ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
603230b80f3cSFilipe Manana 	batch.keys = ins_keys;
603330b80f3cSFilipe Manana 
603430b80f3cSFilipe Manana 	curr = first;
603530b80f3cSFilipe Manana 	while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
603630b80f3cSFilipe Manana 		const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
603730b80f3cSFilipe Manana 
603830b80f3cSFilipe Manana 		if (curr_batch_size + curr_size > leaf_data_size ||
603930b80f3cSFilipe Manana 		    batch.nr == max_batch_size) {
604030b80f3cSFilipe Manana 			ret = insert_delayed_items_batch(trans, log, path,
604130b80f3cSFilipe Manana 							 &batch, first);
604230b80f3cSFilipe Manana 			if (ret)
604330b80f3cSFilipe Manana 				goto out;
604430b80f3cSFilipe Manana 			batch_idx = 0;
604530b80f3cSFilipe Manana 			batch.nr = 0;
604630b80f3cSFilipe Manana 			batch.total_data_size = 0;
604730b80f3cSFilipe Manana 			curr_batch_size = 0;
604830b80f3cSFilipe Manana 			first = curr;
604930b80f3cSFilipe Manana 		}
605030b80f3cSFilipe Manana 
605130b80f3cSFilipe Manana 		ins_sizes[batch_idx] = curr->data_len;
605230b80f3cSFilipe Manana 		ins_keys[batch_idx].objectid = ino;
605330b80f3cSFilipe Manana 		ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
605430b80f3cSFilipe Manana 		ins_keys[batch_idx].offset = curr->index;
605530b80f3cSFilipe Manana 		curr_batch_size += curr_size;
605630b80f3cSFilipe Manana 		batch.total_data_size += curr->data_len;
605730b80f3cSFilipe Manana 		batch.nr++;
605830b80f3cSFilipe Manana 		batch_idx++;
605930b80f3cSFilipe Manana 		curr = list_next_entry(curr, log_list);
606030b80f3cSFilipe Manana 	}
606130b80f3cSFilipe Manana 
606230b80f3cSFilipe Manana 	ASSERT(batch.nr >= 1);
606330b80f3cSFilipe Manana 	ret = insert_delayed_items_batch(trans, log, path, &batch, first);
606430b80f3cSFilipe Manana 
606530b80f3cSFilipe Manana 	curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
606630b80f3cSFilipe Manana 			       log_list);
606730b80f3cSFilipe Manana 	inode->last_dir_index_offset = curr->index;
606830b80f3cSFilipe Manana out:
606930b80f3cSFilipe Manana 	kfree(ins_data);
607030b80f3cSFilipe Manana 
607130b80f3cSFilipe Manana 	return ret;
607230b80f3cSFilipe Manana }
607330b80f3cSFilipe Manana 
607430b80f3cSFilipe Manana static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
607530b80f3cSFilipe Manana 				      struct btrfs_inode *inode,
607630b80f3cSFilipe Manana 				      struct btrfs_path *path,
607730b80f3cSFilipe Manana 				      const struct list_head *delayed_del_list,
607830b80f3cSFilipe Manana 				      struct btrfs_log_ctx *ctx)
607930b80f3cSFilipe Manana {
608030b80f3cSFilipe Manana 	const u64 ino = btrfs_ino(inode);
608130b80f3cSFilipe Manana 	const struct btrfs_delayed_item *curr;
608230b80f3cSFilipe Manana 
608330b80f3cSFilipe Manana 	curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
608430b80f3cSFilipe Manana 				log_list);
608530b80f3cSFilipe Manana 
608630b80f3cSFilipe Manana 	while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
608730b80f3cSFilipe Manana 		u64 first_dir_index = curr->index;
608830b80f3cSFilipe Manana 		u64 last_dir_index;
608930b80f3cSFilipe Manana 		const struct btrfs_delayed_item *next;
609030b80f3cSFilipe Manana 		int ret;
609130b80f3cSFilipe Manana 
609230b80f3cSFilipe Manana 		/*
609330b80f3cSFilipe Manana 		 * Find a range of consecutive dir index items to delete. Like
609430b80f3cSFilipe Manana 		 * this we log a single dir range item spanning several contiguous
609530b80f3cSFilipe Manana 		 * dir items instead of logging one range item per dir index item.
609630b80f3cSFilipe Manana 		 */
609730b80f3cSFilipe Manana 		next = list_next_entry(curr, log_list);
609830b80f3cSFilipe Manana 		while (!list_entry_is_head(next, delayed_del_list, log_list)) {
609930b80f3cSFilipe Manana 			if (next->index != curr->index + 1)
610030b80f3cSFilipe Manana 				break;
610130b80f3cSFilipe Manana 			curr = next;
610230b80f3cSFilipe Manana 			next = list_next_entry(next, log_list);
610330b80f3cSFilipe Manana 		}
610430b80f3cSFilipe Manana 
610530b80f3cSFilipe Manana 		last_dir_index = curr->index;
610630b80f3cSFilipe Manana 		ASSERT(last_dir_index >= first_dir_index);
610730b80f3cSFilipe Manana 
610830b80f3cSFilipe Manana 		ret = insert_dir_log_key(trans, inode->root->log_root, path,
610930b80f3cSFilipe Manana 					 ino, first_dir_index, last_dir_index);
611030b80f3cSFilipe Manana 		if (ret)
611130b80f3cSFilipe Manana 			return ret;
611230b80f3cSFilipe Manana 		curr = list_next_entry(curr, log_list);
611330b80f3cSFilipe Manana 	}
611430b80f3cSFilipe Manana 
611530b80f3cSFilipe Manana 	return 0;
611630b80f3cSFilipe Manana }
611730b80f3cSFilipe Manana 
611830b80f3cSFilipe Manana static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
611930b80f3cSFilipe Manana 					struct btrfs_inode *inode,
612030b80f3cSFilipe Manana 					struct btrfs_path *path,
612130b80f3cSFilipe Manana 					struct btrfs_log_ctx *ctx,
612230b80f3cSFilipe Manana 					const struct list_head *delayed_del_list,
612330b80f3cSFilipe Manana 					const struct btrfs_delayed_item *first,
612430b80f3cSFilipe Manana 					const struct btrfs_delayed_item **last_ret)
612530b80f3cSFilipe Manana {
612630b80f3cSFilipe Manana 	const struct btrfs_delayed_item *next;
612730b80f3cSFilipe Manana 	struct extent_buffer *leaf = path->nodes[0];
612830b80f3cSFilipe Manana 	const int last_slot = btrfs_header_nritems(leaf) - 1;
612930b80f3cSFilipe Manana 	int slot = path->slots[0] + 1;
613030b80f3cSFilipe Manana 	const u64 ino = btrfs_ino(inode);
613130b80f3cSFilipe Manana 
613230b80f3cSFilipe Manana 	next = list_next_entry(first, log_list);
613330b80f3cSFilipe Manana 
613430b80f3cSFilipe Manana 	while (slot < last_slot &&
613530b80f3cSFilipe Manana 	       !list_entry_is_head(next, delayed_del_list, log_list)) {
613630b80f3cSFilipe Manana 		struct btrfs_key key;
613730b80f3cSFilipe Manana 
613830b80f3cSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
613930b80f3cSFilipe Manana 		if (key.objectid != ino ||
614030b80f3cSFilipe Manana 		    key.type != BTRFS_DIR_INDEX_KEY ||
614130b80f3cSFilipe Manana 		    key.offset != next->index)
614230b80f3cSFilipe Manana 			break;
614330b80f3cSFilipe Manana 
614430b80f3cSFilipe Manana 		slot++;
614530b80f3cSFilipe Manana 		*last_ret = next;
614630b80f3cSFilipe Manana 		next = list_next_entry(next, log_list);
614730b80f3cSFilipe Manana 	}
614830b80f3cSFilipe Manana 
614930b80f3cSFilipe Manana 	return btrfs_del_items(trans, inode->root->log_root, path,
615030b80f3cSFilipe Manana 			       path->slots[0], slot - path->slots[0]);
615130b80f3cSFilipe Manana }
615230b80f3cSFilipe Manana 
615330b80f3cSFilipe Manana static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
615430b80f3cSFilipe Manana 					     struct btrfs_inode *inode,
615530b80f3cSFilipe Manana 					     struct btrfs_path *path,
615630b80f3cSFilipe Manana 					     const struct list_head *delayed_del_list,
615730b80f3cSFilipe Manana 					     struct btrfs_log_ctx *ctx)
615830b80f3cSFilipe Manana {
615930b80f3cSFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
616030b80f3cSFilipe Manana 	const struct btrfs_delayed_item *curr;
61618fd9f423SShida Zhang 	u64 last_range_start = 0;
616230b80f3cSFilipe Manana 	u64 last_range_end = 0;
616330b80f3cSFilipe Manana 	struct btrfs_key key;
616430b80f3cSFilipe Manana 
616530b80f3cSFilipe Manana 	key.objectid = btrfs_ino(inode);
616630b80f3cSFilipe Manana 	key.type = BTRFS_DIR_INDEX_KEY;
616730b80f3cSFilipe Manana 	curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
616830b80f3cSFilipe Manana 				log_list);
616930b80f3cSFilipe Manana 
617030b80f3cSFilipe Manana 	while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
617130b80f3cSFilipe Manana 		const struct btrfs_delayed_item *last = curr;
617230b80f3cSFilipe Manana 		u64 first_dir_index = curr->index;
617330b80f3cSFilipe Manana 		u64 last_dir_index;
617430b80f3cSFilipe Manana 		bool deleted_items = false;
617530b80f3cSFilipe Manana 		int ret;
617630b80f3cSFilipe Manana 
617730b80f3cSFilipe Manana 		key.offset = curr->index;
617830b80f3cSFilipe Manana 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
617930b80f3cSFilipe Manana 		if (ret < 0) {
618030b80f3cSFilipe Manana 			return ret;
618130b80f3cSFilipe Manana 		} else if (ret == 0) {
618230b80f3cSFilipe Manana 			ret = batch_delete_dir_index_items(trans, inode, path, ctx,
618330b80f3cSFilipe Manana 							   delayed_del_list, curr,
618430b80f3cSFilipe Manana 							   &last);
618530b80f3cSFilipe Manana 			if (ret)
618630b80f3cSFilipe Manana 				return ret;
618730b80f3cSFilipe Manana 			deleted_items = true;
618830b80f3cSFilipe Manana 		}
618930b80f3cSFilipe Manana 
619030b80f3cSFilipe Manana 		btrfs_release_path(path);
619130b80f3cSFilipe Manana 
619230b80f3cSFilipe Manana 		/*
619330b80f3cSFilipe Manana 		 * If we deleted items from the leaf, it means we have a range
619430b80f3cSFilipe Manana 		 * item logging their range, so no need to add one or update an
619530b80f3cSFilipe Manana 		 * existing one. Otherwise we have to log a dir range item.
619630b80f3cSFilipe Manana 		 */
619730b80f3cSFilipe Manana 		if (deleted_items)
619830b80f3cSFilipe Manana 			goto next_batch;
619930b80f3cSFilipe Manana 
620030b80f3cSFilipe Manana 		last_dir_index = last->index;
620130b80f3cSFilipe Manana 		ASSERT(last_dir_index >= first_dir_index);
620230b80f3cSFilipe Manana 		/*
620330b80f3cSFilipe Manana 		 * If this range starts right after where the previous one ends,
620430b80f3cSFilipe Manana 		 * then we want to reuse the previous range item and change its
620530b80f3cSFilipe Manana 		 * end offset to the end of this range. This is just to minimize
620630b80f3cSFilipe Manana 		 * leaf space usage, by avoiding adding a new range item.
620730b80f3cSFilipe Manana 		 */
620830b80f3cSFilipe Manana 		if (last_range_end != 0 && first_dir_index == last_range_end + 1)
620930b80f3cSFilipe Manana 			first_dir_index = last_range_start;
621030b80f3cSFilipe Manana 
621130b80f3cSFilipe Manana 		ret = insert_dir_log_key(trans, log, path, key.objectid,
621230b80f3cSFilipe Manana 					 first_dir_index, last_dir_index);
621330b80f3cSFilipe Manana 		if (ret)
621430b80f3cSFilipe Manana 			return ret;
621530b80f3cSFilipe Manana 
621630b80f3cSFilipe Manana 		last_range_start = first_dir_index;
621730b80f3cSFilipe Manana 		last_range_end = last_dir_index;
621830b80f3cSFilipe Manana next_batch:
621930b80f3cSFilipe Manana 		curr = list_next_entry(last, log_list);
622030b80f3cSFilipe Manana 	}
622130b80f3cSFilipe Manana 
622230b80f3cSFilipe Manana 	return 0;
622330b80f3cSFilipe Manana }
622430b80f3cSFilipe Manana 
622530b80f3cSFilipe Manana static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
622630b80f3cSFilipe Manana 				      struct btrfs_inode *inode,
622730b80f3cSFilipe Manana 				      struct btrfs_path *path,
622830b80f3cSFilipe Manana 				      const struct list_head *delayed_del_list,
622930b80f3cSFilipe Manana 				      struct btrfs_log_ctx *ctx)
623030b80f3cSFilipe Manana {
623130b80f3cSFilipe Manana 	/*
623230b80f3cSFilipe Manana 	 * We are deleting dir index items from the log tree or adding range
623330b80f3cSFilipe Manana 	 * items to it.
623430b80f3cSFilipe Manana 	 */
623530b80f3cSFilipe Manana 	lockdep_assert_held(&inode->log_mutex);
623630b80f3cSFilipe Manana 
623730b80f3cSFilipe Manana 	if (list_empty(delayed_del_list))
623830b80f3cSFilipe Manana 		return 0;
623930b80f3cSFilipe Manana 
624030b80f3cSFilipe Manana 	if (ctx->logged_before)
624130b80f3cSFilipe Manana 		return log_delayed_deletions_incremental(trans, inode, path,
624230b80f3cSFilipe Manana 							 delayed_del_list, ctx);
624330b80f3cSFilipe Manana 
624430b80f3cSFilipe Manana 	return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
624530b80f3cSFilipe Manana 					  ctx);
624630b80f3cSFilipe Manana }
624730b80f3cSFilipe Manana 
624830b80f3cSFilipe Manana /*
624930b80f3cSFilipe Manana  * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
625030b80f3cSFilipe Manana  * items instead of the subvolume tree.
625130b80f3cSFilipe Manana  */
625230b80f3cSFilipe Manana static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
625330b80f3cSFilipe Manana 				    struct btrfs_inode *inode,
625430b80f3cSFilipe Manana 				    const struct list_head *delayed_ins_list,
625530b80f3cSFilipe Manana 				    struct btrfs_log_ctx *ctx)
625630b80f3cSFilipe Manana {
625730b80f3cSFilipe Manana 	const bool orig_log_new_dentries = ctx->log_new_dentries;
625830b80f3cSFilipe Manana 	struct btrfs_fs_info *fs_info = trans->fs_info;
625930b80f3cSFilipe Manana 	struct btrfs_delayed_item *item;
626030b80f3cSFilipe Manana 	int ret = 0;
626130b80f3cSFilipe Manana 
626230b80f3cSFilipe Manana 	/*
626330b80f3cSFilipe Manana 	 * No need for the log mutex, plus to avoid potential deadlocks or
626430b80f3cSFilipe Manana 	 * lockdep annotations due to nesting of delayed inode mutexes and log
626530b80f3cSFilipe Manana 	 * mutexes.
626630b80f3cSFilipe Manana 	 */
626730b80f3cSFilipe Manana 	lockdep_assert_not_held(&inode->log_mutex);
626830b80f3cSFilipe Manana 
626930b80f3cSFilipe Manana 	ASSERT(!ctx->logging_new_delayed_dentries);
627030b80f3cSFilipe Manana 	ctx->logging_new_delayed_dentries = true;
627130b80f3cSFilipe Manana 
627230b80f3cSFilipe Manana 	list_for_each_entry(item, delayed_ins_list, log_list) {
627330b80f3cSFilipe Manana 		struct btrfs_dir_item *dir_item;
627430b80f3cSFilipe Manana 		struct inode *di_inode;
627530b80f3cSFilipe Manana 		struct btrfs_key key;
627630b80f3cSFilipe Manana 		int log_mode = LOG_INODE_EXISTS;
627730b80f3cSFilipe Manana 
627830b80f3cSFilipe Manana 		dir_item = (struct btrfs_dir_item *)item->data;
627930b80f3cSFilipe Manana 		btrfs_disk_key_to_cpu(&key, &dir_item->location);
628030b80f3cSFilipe Manana 
628130b80f3cSFilipe Manana 		if (key.type == BTRFS_ROOT_ITEM_KEY)
628230b80f3cSFilipe Manana 			continue;
628330b80f3cSFilipe Manana 
628430b80f3cSFilipe Manana 		di_inode = btrfs_iget(fs_info->sb, key.objectid, inode->root);
628530b80f3cSFilipe Manana 		if (IS_ERR(di_inode)) {
628630b80f3cSFilipe Manana 			ret = PTR_ERR(di_inode);
628730b80f3cSFilipe Manana 			break;
628830b80f3cSFilipe Manana 		}
628930b80f3cSFilipe Manana 
629030b80f3cSFilipe Manana 		if (!need_log_inode(trans, BTRFS_I(di_inode))) {
6291e55cf7caSDavid Sterba 			btrfs_add_delayed_iput(BTRFS_I(di_inode));
629230b80f3cSFilipe Manana 			continue;
629330b80f3cSFilipe Manana 		}
629430b80f3cSFilipe Manana 
629594a48aefSOmar Sandoval 		if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
629630b80f3cSFilipe Manana 			log_mode = LOG_INODE_ALL;
629730b80f3cSFilipe Manana 
629830b80f3cSFilipe Manana 		ctx->log_new_dentries = false;
629930b80f3cSFilipe Manana 		ret = btrfs_log_inode(trans, BTRFS_I(di_inode), log_mode, ctx);
630030b80f3cSFilipe Manana 
630130b80f3cSFilipe Manana 		if (!ret && ctx->log_new_dentries)
630230b80f3cSFilipe Manana 			ret = log_new_dir_dentries(trans, BTRFS_I(di_inode), ctx);
630330b80f3cSFilipe Manana 
6304e55cf7caSDavid Sterba 		btrfs_add_delayed_iput(BTRFS_I(di_inode));
630530b80f3cSFilipe Manana 
630630b80f3cSFilipe Manana 		if (ret)
630730b80f3cSFilipe Manana 			break;
630830b80f3cSFilipe Manana 	}
630930b80f3cSFilipe Manana 
631030b80f3cSFilipe Manana 	ctx->log_new_dentries = orig_log_new_dentries;
631130b80f3cSFilipe Manana 	ctx->logging_new_delayed_dentries = false;
631230b80f3cSFilipe Manana 
631330b80f3cSFilipe Manana 	return ret;
631430b80f3cSFilipe Manana }
631530b80f3cSFilipe Manana 
6316e02119d5SChris Mason /* log a single inode in the tree log.
6317e02119d5SChris Mason  * At least one parent directory for this inode must exist in the tree
6318e02119d5SChris Mason  * or be logged already.
6319e02119d5SChris Mason  *
6320e02119d5SChris Mason  * Any items from this inode changed by the current transaction are copied
6321e02119d5SChris Mason  * to the log tree.  An extra reference is taken on any extents in this
6322e02119d5SChris Mason  * file, allowing us to avoid a whole pile of corner cases around logging
6323e02119d5SChris Mason  * blocks that have been removed from the tree.
6324e02119d5SChris Mason  *
6325e02119d5SChris Mason  * See LOG_INODE_ALL and related defines for a description of what inode_only
6326e02119d5SChris Mason  * does.
6327e02119d5SChris Mason  *
6328e02119d5SChris Mason  * This handles both files and directories.
6329e02119d5SChris Mason  */
633012fcfd22SChris Mason static int btrfs_log_inode(struct btrfs_trans_handle *trans,
633190d04510SFilipe Manana 			   struct btrfs_inode *inode,
633249dae1bcSFilipe Manana 			   int inode_only,
63338407f553SFilipe Manana 			   struct btrfs_log_ctx *ctx)
6334e02119d5SChris Mason {
6335e02119d5SChris Mason 	struct btrfs_path *path;
6336e02119d5SChris Mason 	struct btrfs_path *dst_path;
6337e02119d5SChris Mason 	struct btrfs_key min_key;
6338e02119d5SChris Mason 	struct btrfs_key max_key;
633990d04510SFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
634065faced5SFilipe Manana 	int ret;
63415dc562c5SJosef Bacik 	bool fast_search = false;
6342a59108a7SNikolay Borisov 	u64 ino = btrfs_ino(inode);
6343a59108a7SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
63441a4bcf47SFilipe Manana 	u64 logged_isize = 0;
6345e4545de5SFilipe Manana 	bool need_log_inode_item = true;
63469a8fca62SFilipe Manana 	bool xattrs_logged = false;
63472ac691d8SFilipe Manana 	bool inode_item_dropped = true;
634830b80f3cSFilipe Manana 	bool full_dir_logging = false;
634930b80f3cSFilipe Manana 	LIST_HEAD(delayed_ins_list);
635030b80f3cSFilipe Manana 	LIST_HEAD(delayed_del_list);
6351e02119d5SChris Mason 
6352e02119d5SChris Mason 	path = btrfs_alloc_path();
63535df67083STsutomu Itoh 	if (!path)
63545df67083STsutomu Itoh 		return -ENOMEM;
6355e02119d5SChris Mason 	dst_path = btrfs_alloc_path();
63565df67083STsutomu Itoh 	if (!dst_path) {
63575df67083STsutomu Itoh 		btrfs_free_path(path);
63585df67083STsutomu Itoh 		return -ENOMEM;
63595df67083STsutomu Itoh 	}
6360e02119d5SChris Mason 
636133345d01SLi Zefan 	min_key.objectid = ino;
6362e02119d5SChris Mason 	min_key.type = BTRFS_INODE_ITEM_KEY;
6363e02119d5SChris Mason 	min_key.offset = 0;
6364e02119d5SChris Mason 
636533345d01SLi Zefan 	max_key.objectid = ino;
636612fcfd22SChris Mason 
636712fcfd22SChris Mason 
63685dc562c5SJosef Bacik 	/* today the code can only do partial logging of directories */
6369a59108a7SNikolay Borisov 	if (S_ISDIR(inode->vfs_inode.i_mode) ||
63705269b67eSMiao Xie 	    (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6371a59108a7SNikolay Borisov 		       &inode->runtime_flags) &&
6372781feef7SLiu Bo 	     inode_only >= LOG_INODE_EXISTS))
6373e02119d5SChris Mason 		max_key.type = BTRFS_XATTR_ITEM_KEY;
6374e02119d5SChris Mason 	else
6375e02119d5SChris Mason 		max_key.type = (u8)-1;
6376e02119d5SChris Mason 	max_key.offset = (u64)-1;
6377e02119d5SChris Mason 
637830b80f3cSFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode) && inode_only == LOG_INODE_ALL)
637930b80f3cSFilipe Manana 		full_dir_logging = true;
638030b80f3cSFilipe Manana 
63812c2c452bSFilipe Manana 	/*
638230b80f3cSFilipe Manana 	 * If we are logging a directory while we are logging dentries of the
638330b80f3cSFilipe Manana 	 * delayed items of some other inode, then we need to flush the delayed
638430b80f3cSFilipe Manana 	 * items of this directory and not log the delayed items directly. This
638530b80f3cSFilipe Manana 	 * is to prevent more than one level of recursion into btrfs_log_inode()
638630b80f3cSFilipe Manana 	 * by having something like this:
638730b80f3cSFilipe Manana 	 *
638830b80f3cSFilipe Manana 	 *     $ mkdir -p a/b/c/d/e/f/g/h/...
638930b80f3cSFilipe Manana 	 *     $ xfs_io -c "fsync" a
639030b80f3cSFilipe Manana 	 *
639130b80f3cSFilipe Manana 	 * Where all directories in the path did not exist before and are
639230b80f3cSFilipe Manana 	 * created in the current transaction.
639330b80f3cSFilipe Manana 	 * So in such a case we directly log the delayed items of the main
639430b80f3cSFilipe Manana 	 * directory ("a") without flushing them first, while for each of its
639530b80f3cSFilipe Manana 	 * subdirectories we flush their delayed items before logging them.
639630b80f3cSFilipe Manana 	 * This prevents a potential unbounded recursion like this:
639730b80f3cSFilipe Manana 	 *
639830b80f3cSFilipe Manana 	 * btrfs_log_inode()
639930b80f3cSFilipe Manana 	 *   log_new_delayed_dentries()
640030b80f3cSFilipe Manana 	 *      btrfs_log_inode()
640130b80f3cSFilipe Manana 	 *        log_new_delayed_dentries()
640230b80f3cSFilipe Manana 	 *          btrfs_log_inode()
640330b80f3cSFilipe Manana 	 *            log_new_delayed_dentries()
640430b80f3cSFilipe Manana 	 *              (...)
640530b80f3cSFilipe Manana 	 *
640630b80f3cSFilipe Manana 	 * We have thresholds for the maximum number of delayed items to have in
640730b80f3cSFilipe Manana 	 * memory, and once they are hit, the items are flushed asynchronously.
640830b80f3cSFilipe Manana 	 * However the limit is quite high, so lets prevent deep levels of
640930b80f3cSFilipe Manana 	 * recursion to happen by limiting the maximum depth to be 1.
64102c2c452bSFilipe Manana 	 */
641130b80f3cSFilipe Manana 	if (full_dir_logging && ctx->logging_new_delayed_dentries) {
641265faced5SFilipe Manana 		ret = btrfs_commit_inode_delayed_items(trans, inode);
641365faced5SFilipe Manana 		if (ret)
6414f6df27ddSFilipe Manana 			goto out;
641516cdcec7SMiao Xie 	}
641616cdcec7SMiao Xie 
6417a59108a7SNikolay Borisov 	mutex_lock(&inode->log_mutex);
6418e02119d5SChris Mason 
64195e33a2bdSFilipe Manana 	/*
6420d0e64a98SFilipe Manana 	 * For symlinks, we must always log their content, which is stored in an
6421d0e64a98SFilipe Manana 	 * inline extent, otherwise we could end up with an empty symlink after
6422d0e64a98SFilipe Manana 	 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
6423d0e64a98SFilipe Manana 	 * one attempts to create an empty symlink).
6424d0e64a98SFilipe Manana 	 * We don't need to worry about flushing delalloc, because when we create
6425d0e64a98SFilipe Manana 	 * the inline extent when the symlink is created (we never have delalloc
6426d0e64a98SFilipe Manana 	 * for symlinks).
6427d0e64a98SFilipe Manana 	 */
6428d0e64a98SFilipe Manana 	if (S_ISLNK(inode->vfs_inode.i_mode))
6429d0e64a98SFilipe Manana 		inode_only = LOG_INODE_ALL;
6430d0e64a98SFilipe Manana 
6431d0e64a98SFilipe Manana 	/*
64320f8ce498SFilipe Manana 	 * Before logging the inode item, cache the value returned by
64330f8ce498SFilipe Manana 	 * inode_logged(), because after that we have the need to figure out if
64340f8ce498SFilipe Manana 	 * the inode was previously logged in this transaction.
64350f8ce498SFilipe Manana 	 */
64360f8ce498SFilipe Manana 	ret = inode_logged(trans, inode, path);
643765faced5SFilipe Manana 	if (ret < 0)
64380f8ce498SFilipe Manana 		goto out_unlock;
64390f8ce498SFilipe Manana 	ctx->logged_before = (ret == 1);
644065faced5SFilipe Manana 	ret = 0;
64410f8ce498SFilipe Manana 
64420f8ce498SFilipe Manana 	/*
644364d6b281SFilipe Manana 	 * This is for cases where logging a directory could result in losing a
644464d6b281SFilipe Manana 	 * a file after replaying the log. For example, if we move a file from a
644564d6b281SFilipe Manana 	 * directory A to a directory B, then fsync directory A, we have no way
644664d6b281SFilipe Manana 	 * to known the file was moved from A to B, so logging just A would
644764d6b281SFilipe Manana 	 * result in losing the file after a log replay.
644864d6b281SFilipe Manana 	 */
644930b80f3cSFilipe Manana 	if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
6450f31f09f6SJosef Bacik 		ret = BTRFS_LOG_FORCE_COMMIT;
645164d6b281SFilipe Manana 		goto out_unlock;
645264d6b281SFilipe Manana 	}
645364d6b281SFilipe Manana 
645464d6b281SFilipe Manana 	/*
6455e02119d5SChris Mason 	 * a brute force approach to making sure we get the most uptodate
6456e02119d5SChris Mason 	 * copies of everything.
6457e02119d5SChris Mason 	 */
6458a59108a7SNikolay Borisov 	if (S_ISDIR(inode->vfs_inode.i_mode)) {
6459ab12313aSFilipe Manana 		clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
64600f8ce498SFilipe Manana 		if (ctx->logged_before)
64610f8ce498SFilipe Manana 			ret = drop_inode_items(trans, log, path, inode,
646204fc7d51SFilipe Manana 					       BTRFS_XATTR_ITEM_KEY);
6463e02119d5SChris Mason 	} else {
64640f8ce498SFilipe Manana 		if (inode_only == LOG_INODE_EXISTS && ctx->logged_before) {
64651a4bcf47SFilipe Manana 			/*
64661a4bcf47SFilipe Manana 			 * Make sure the new inode item we write to the log has
64671a4bcf47SFilipe Manana 			 * the same isize as the current one (if it exists).
64681a4bcf47SFilipe Manana 			 * This is necessary to prevent data loss after log
64691a4bcf47SFilipe Manana 			 * replay, and also to prevent doing a wrong expanding
64701a4bcf47SFilipe Manana 			 * truncate - for e.g. create file, write 4K into offset
64711a4bcf47SFilipe Manana 			 * 0, fsync, write 4K into offset 4096, add hard link,
64721a4bcf47SFilipe Manana 			 * fsync some other file (to sync log), power fail - if
64731a4bcf47SFilipe Manana 			 * we use the inode's current i_size, after log replay
64741a4bcf47SFilipe Manana 			 * we get a 8Kb file, with the last 4Kb extent as a hole
64751a4bcf47SFilipe Manana 			 * (zeroes), as if an expanding truncate happened,
64761a4bcf47SFilipe Manana 			 * instead of getting a file of 4Kb only.
64771a4bcf47SFilipe Manana 			 */
647865faced5SFilipe Manana 			ret = logged_inode_size(log, inode, path, &logged_isize);
647965faced5SFilipe Manana 			if (ret)
64801a4bcf47SFilipe Manana 				goto out_unlock;
64811a4bcf47SFilipe Manana 		}
6482a742994aSFilipe Manana 		if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6483a59108a7SNikolay Borisov 			     &inode->runtime_flags)) {
6484a742994aSFilipe Manana 			if (inode_only == LOG_INODE_EXISTS) {
64854f764e51SFilipe Manana 				max_key.type = BTRFS_XATTR_ITEM_KEY;
64860f8ce498SFilipe Manana 				if (ctx->logged_before)
64870f8ce498SFilipe Manana 					ret = drop_inode_items(trans, log, path,
64880f8ce498SFilipe Manana 							       inode, max_key.type);
6489a742994aSFilipe Manana 			} else {
6490a742994aSFilipe Manana 				clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6491a59108a7SNikolay Borisov 					  &inode->runtime_flags);
6492e9976151SJosef Bacik 				clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6493a59108a7SNikolay Borisov 					  &inode->runtime_flags);
64940f8ce498SFilipe Manana 				if (ctx->logged_before)
64954934a815SFilipe Manana 					ret = truncate_inode_items(trans, log,
64964934a815SFilipe Manana 								   inode, 0, 0);
6497a742994aSFilipe Manana 			}
64984f764e51SFilipe Manana 		} else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
6499a59108a7SNikolay Borisov 					      &inode->runtime_flags) ||
65006cfab851SJosef Bacik 			   inode_only == LOG_INODE_EXISTS) {
65014f764e51SFilipe Manana 			if (inode_only == LOG_INODE_ALL)
6502a95249b3SJosef Bacik 				fast_search = true;
6503a95249b3SJosef Bacik 			max_key.type = BTRFS_XATTR_ITEM_KEY;
65040f8ce498SFilipe Manana 			if (ctx->logged_before)
650588e221cdSFilipe Manana 				ret = drop_inode_items(trans, log, path, inode,
6506a95249b3SJosef Bacik 						       max_key.type);
65075dc562c5SJosef Bacik 		} else {
6508183f37faSLiu Bo 			if (inode_only == LOG_INODE_ALL)
65095dc562c5SJosef Bacik 				fast_search = true;
65102ac691d8SFilipe Manana 			inode_item_dropped = false;
6511a95249b3SJosef Bacik 			goto log_extents;
6512a95249b3SJosef Bacik 		}
6513a95249b3SJosef Bacik 
6514e02119d5SChris Mason 	}
651565faced5SFilipe Manana 	if (ret)
65164a500fd1SYan, Zheng 		goto out_unlock;
6517e02119d5SChris Mason 
651830b80f3cSFilipe Manana 	/*
651930b80f3cSFilipe Manana 	 * If we are logging a directory in full mode, collect the delayed items
652030b80f3cSFilipe Manana 	 * before iterating the subvolume tree, so that we don't miss any new
652130b80f3cSFilipe Manana 	 * dir index items in case they get flushed while or right after we are
652230b80f3cSFilipe Manana 	 * iterating the subvolume tree.
652330b80f3cSFilipe Manana 	 */
652430b80f3cSFilipe Manana 	if (full_dir_logging && !ctx->logging_new_delayed_dentries)
652530b80f3cSFilipe Manana 		btrfs_log_get_delayed_items(inode, &delayed_ins_list,
652630b80f3cSFilipe Manana 					    &delayed_del_list);
652730b80f3cSFilipe Manana 
652865faced5SFilipe Manana 	ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
6529da447009SFilipe Manana 				      path, dst_path, logged_isize,
6530e09d94c9SFilipe Manana 				      inode_only, ctx,
65317af59743SFilipe Manana 				      &need_log_inode_item);
653265faced5SFilipe Manana 	if (ret)
653344f714daSFilipe Manana 		goto out_unlock;
65345dc562c5SJosef Bacik 
653536283bf7SFilipe Manana 	btrfs_release_path(path);
653636283bf7SFilipe Manana 	btrfs_release_path(dst_path);
653765faced5SFilipe Manana 	ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
653865faced5SFilipe Manana 	if (ret)
653936283bf7SFilipe Manana 		goto out_unlock;
65409a8fca62SFilipe Manana 	xattrs_logged = true;
6541a89ca6f2SFilipe Manana 	if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
6542a89ca6f2SFilipe Manana 		btrfs_release_path(path);
6543a89ca6f2SFilipe Manana 		btrfs_release_path(dst_path);
654465faced5SFilipe Manana 		ret = btrfs_log_holes(trans, inode, path);
654565faced5SFilipe Manana 		if (ret)
6546a89ca6f2SFilipe Manana 			goto out_unlock;
6547a89ca6f2SFilipe Manana 	}
6548a95249b3SJosef Bacik log_extents:
6549f3b15ccdSJosef Bacik 	btrfs_release_path(path);
65505dc562c5SJosef Bacik 	btrfs_release_path(dst_path);
6551e4545de5SFilipe Manana 	if (need_log_inode_item) {
655265faced5SFilipe Manana 		ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
655365faced5SFilipe Manana 		if (ret)
6554e4545de5SFilipe Manana 			goto out_unlock;
6555b590b839SFilipe Manana 		/*
6556b590b839SFilipe Manana 		 * If we are doing a fast fsync and the inode was logged before
6557b590b839SFilipe Manana 		 * in this transaction, we don't need to log the xattrs because
6558b590b839SFilipe Manana 		 * they were logged before. If xattrs were added, changed or
6559b590b839SFilipe Manana 		 * deleted since the last time we logged the inode, then we have
6560b590b839SFilipe Manana 		 * already logged them because the inode had the runtime flag
6561b590b839SFilipe Manana 		 * BTRFS_INODE_COPY_EVERYTHING set.
6562b590b839SFilipe Manana 		 */
6563b590b839SFilipe Manana 		if (!xattrs_logged && inode->logged_trans < trans->transid) {
656465faced5SFilipe Manana 			ret = btrfs_log_all_xattrs(trans, inode, path, dst_path);
656565faced5SFilipe Manana 			if (ret)
6566b590b839SFilipe Manana 				goto out_unlock;
6567b590b839SFilipe Manana 			btrfs_release_path(path);
6568b590b839SFilipe Manana 		}
6569e4545de5SFilipe Manana 	}
6570f3b15ccdSJosef Bacik 	if (fast_search) {
657190d04510SFilipe Manana 		ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
657265faced5SFilipe Manana 		if (ret)
65735dc562c5SJosef Bacik 			goto out_unlock;
6574d006a048SJosef Bacik 	} else if (inode_only == LOG_INODE_ALL) {
657506d3d22bSLiu Bo 		struct extent_map *em, *n;
657606d3d22bSLiu Bo 
657749dae1bcSFilipe Manana 		write_lock(&em_tree->lock);
657848778179SFilipe Manana 		list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
657906d3d22bSLiu Bo 			list_del_init(&em->list);
658049dae1bcSFilipe Manana 		write_unlock(&em_tree->lock);
65815dc562c5SJosef Bacik 	}
65825dc562c5SJosef Bacik 
658330b80f3cSFilipe Manana 	if (full_dir_logging) {
658490d04510SFilipe Manana 		ret = log_directory_changes(trans, inode, path, dst_path, ctx);
658565faced5SFilipe Manana 		if (ret)
65864a500fd1SYan, Zheng 			goto out_unlock;
658730b80f3cSFilipe Manana 		ret = log_delayed_insertion_items(trans, inode, path,
658830b80f3cSFilipe Manana 						  &delayed_ins_list, ctx);
658930b80f3cSFilipe Manana 		if (ret)
659030b80f3cSFilipe Manana 			goto out_unlock;
659130b80f3cSFilipe Manana 		ret = log_delayed_deletion_items(trans, inode, path,
659230b80f3cSFilipe Manana 						 &delayed_del_list, ctx);
659330b80f3cSFilipe Manana 		if (ret)
659430b80f3cSFilipe Manana 			goto out_unlock;
65954a500fd1SYan, Zheng 	}
659649dae1bcSFilipe Manana 
6597a59108a7SNikolay Borisov 	spin_lock(&inode->lock);
6598a59108a7SNikolay Borisov 	inode->logged_trans = trans->transid;
659975b463d2SFilipe Manana 	/*
66009acc8103SFilipe Manana 	 * Don't update last_log_commit if we logged that an inode exists.
6601130341beSFilipe Manana 	 * We do this for three reasons:
66029acc8103SFilipe Manana 	 *
66039acc8103SFilipe Manana 	 * 1) We might have had buffered writes to this inode that were
66049acc8103SFilipe Manana 	 *    flushed and had their ordered extents completed in this
66059acc8103SFilipe Manana 	 *    transaction, but we did not previously log the inode with
66069acc8103SFilipe Manana 	 *    LOG_INODE_ALL. Later the inode was evicted and after that
66079acc8103SFilipe Manana 	 *    it was loaded again and this LOG_INODE_EXISTS log operation
66089acc8103SFilipe Manana 	 *    happened. We must make sure that if an explicit fsync against
66099acc8103SFilipe Manana 	 *    the inode is performed later, it logs the new extents, an
66109acc8103SFilipe Manana 	 *    updated inode item, etc, and syncs the log. The same logic
66119acc8103SFilipe Manana 	 *    applies to direct IO writes instead of buffered writes.
66129acc8103SFilipe Manana 	 *
66139acc8103SFilipe Manana 	 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
66149acc8103SFilipe Manana 	 *    is logged with an i_size of 0 or whatever value was logged
66159acc8103SFilipe Manana 	 *    before. If later the i_size of the inode is increased by a
66169acc8103SFilipe Manana 	 *    truncate operation, the log is synced through an fsync of
66179acc8103SFilipe Manana 	 *    some other inode and then finally an explicit fsync against
66189acc8103SFilipe Manana 	 *    this inode is made, we must make sure this fsync logs the
66199acc8103SFilipe Manana 	 *    inode with the new i_size, the hole between old i_size and
66209acc8103SFilipe Manana 	 *    the new i_size, and syncs the log.
6621130341beSFilipe Manana 	 *
6622130341beSFilipe Manana 	 * 3) If we are logging that an ancestor inode exists as part of
6623130341beSFilipe Manana 	 *    logging a new name from a link or rename operation, don't update
6624130341beSFilipe Manana 	 *    its last_log_commit - otherwise if an explicit fsync is made
6625130341beSFilipe Manana 	 *    against an ancestor, the fsync considers the inode in the log
6626130341beSFilipe Manana 	 *    and doesn't sync the log, resulting in the ancestor missing after
6627130341beSFilipe Manana 	 *    a power failure unless the log was synced as part of an fsync
6628130341beSFilipe Manana 	 *    against any other unrelated inode.
662975b463d2SFilipe Manana 	 */
66309acc8103SFilipe Manana 	if (inode_only != LOG_INODE_EXISTS)
6631a59108a7SNikolay Borisov 		inode->last_log_commit = inode->last_sub_trans;
6632a59108a7SNikolay Borisov 	spin_unlock(&inode->lock);
663323e3337fSFilipe Manana 
663423e3337fSFilipe Manana 	/*
663523e3337fSFilipe Manana 	 * Reset the last_reflink_trans so that the next fsync does not need to
663623e3337fSFilipe Manana 	 * go through the slower path when logging extents and their checksums.
663723e3337fSFilipe Manana 	 */
663823e3337fSFilipe Manana 	if (inode_only == LOG_INODE_ALL)
663923e3337fSFilipe Manana 		inode->last_reflink_trans = 0;
664023e3337fSFilipe Manana 
66414a500fd1SYan, Zheng out_unlock:
6642a59108a7SNikolay Borisov 	mutex_unlock(&inode->log_mutex);
6643f6df27ddSFilipe Manana out:
6644e02119d5SChris Mason 	btrfs_free_path(path);
6645e02119d5SChris Mason 	btrfs_free_path(dst_path);
66460f8ce498SFilipe Manana 
6647e09d94c9SFilipe Manana 	if (ret)
6648e09d94c9SFilipe Manana 		free_conflicting_inodes(ctx);
6649e09d94c9SFilipe Manana 	else
6650e09d94c9SFilipe Manana 		ret = log_conflicting_inodes(trans, inode->root, ctx);
66510f8ce498SFilipe Manana 
665230b80f3cSFilipe Manana 	if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
665330b80f3cSFilipe Manana 		if (!ret)
665430b80f3cSFilipe Manana 			ret = log_new_delayed_dentries(trans, inode,
665530b80f3cSFilipe Manana 						       &delayed_ins_list, ctx);
665630b80f3cSFilipe Manana 
665730b80f3cSFilipe Manana 		btrfs_log_put_delayed_items(inode, &delayed_ins_list,
665830b80f3cSFilipe Manana 					    &delayed_del_list);
665930b80f3cSFilipe Manana 	}
666030b80f3cSFilipe Manana 
666165faced5SFilipe Manana 	return ret;
6662e02119d5SChris Mason }
6663e02119d5SChris Mason 
666418aa0922SFilipe Manana static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
6665d0a0b78dSNikolay Borisov 				 struct btrfs_inode *inode,
666618aa0922SFilipe Manana 				 struct btrfs_log_ctx *ctx)
666718aa0922SFilipe Manana {
66683ffbd68cSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
666918aa0922SFilipe Manana 	int ret;
667018aa0922SFilipe Manana 	struct btrfs_path *path;
667118aa0922SFilipe Manana 	struct btrfs_key key;
6672d0a0b78dSNikolay Borisov 	struct btrfs_root *root = inode->root;
6673d0a0b78dSNikolay Borisov 	const u64 ino = btrfs_ino(inode);
667418aa0922SFilipe Manana 
667518aa0922SFilipe Manana 	path = btrfs_alloc_path();
667618aa0922SFilipe Manana 	if (!path)
667718aa0922SFilipe Manana 		return -ENOMEM;
667818aa0922SFilipe Manana 	path->skip_locking = 1;
667918aa0922SFilipe Manana 	path->search_commit_root = 1;
668018aa0922SFilipe Manana 
668118aa0922SFilipe Manana 	key.objectid = ino;
668218aa0922SFilipe Manana 	key.type = BTRFS_INODE_REF_KEY;
668318aa0922SFilipe Manana 	key.offset = 0;
668418aa0922SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
668518aa0922SFilipe Manana 	if (ret < 0)
668618aa0922SFilipe Manana 		goto out;
668718aa0922SFilipe Manana 
668818aa0922SFilipe Manana 	while (true) {
668918aa0922SFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
669018aa0922SFilipe Manana 		int slot = path->slots[0];
669118aa0922SFilipe Manana 		u32 cur_offset = 0;
669218aa0922SFilipe Manana 		u32 item_size;
669318aa0922SFilipe Manana 		unsigned long ptr;
669418aa0922SFilipe Manana 
669518aa0922SFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
669618aa0922SFilipe Manana 			ret = btrfs_next_leaf(root, path);
669718aa0922SFilipe Manana 			if (ret < 0)
669818aa0922SFilipe Manana 				goto out;
669918aa0922SFilipe Manana 			else if (ret > 0)
670018aa0922SFilipe Manana 				break;
670118aa0922SFilipe Manana 			continue;
670218aa0922SFilipe Manana 		}
670318aa0922SFilipe Manana 
670418aa0922SFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
670518aa0922SFilipe Manana 		/* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
670618aa0922SFilipe Manana 		if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
670718aa0922SFilipe Manana 			break;
670818aa0922SFilipe Manana 
67093212fa14SJosef Bacik 		item_size = btrfs_item_size(leaf, slot);
671018aa0922SFilipe Manana 		ptr = btrfs_item_ptr_offset(leaf, slot);
671118aa0922SFilipe Manana 		while (cur_offset < item_size) {
671218aa0922SFilipe Manana 			struct btrfs_key inode_key;
671318aa0922SFilipe Manana 			struct inode *dir_inode;
671418aa0922SFilipe Manana 
671518aa0922SFilipe Manana 			inode_key.type = BTRFS_INODE_ITEM_KEY;
671618aa0922SFilipe Manana 			inode_key.offset = 0;
671718aa0922SFilipe Manana 
671818aa0922SFilipe Manana 			if (key.type == BTRFS_INODE_EXTREF_KEY) {
671918aa0922SFilipe Manana 				struct btrfs_inode_extref *extref;
672018aa0922SFilipe Manana 
672118aa0922SFilipe Manana 				extref = (struct btrfs_inode_extref *)
672218aa0922SFilipe Manana 					(ptr + cur_offset);
672318aa0922SFilipe Manana 				inode_key.objectid = btrfs_inode_extref_parent(
672418aa0922SFilipe Manana 					leaf, extref);
672518aa0922SFilipe Manana 				cur_offset += sizeof(*extref);
672618aa0922SFilipe Manana 				cur_offset += btrfs_inode_extref_name_len(leaf,
672718aa0922SFilipe Manana 					extref);
672818aa0922SFilipe Manana 			} else {
672918aa0922SFilipe Manana 				inode_key.objectid = key.offset;
673018aa0922SFilipe Manana 				cur_offset = item_size;
673118aa0922SFilipe Manana 			}
673218aa0922SFilipe Manana 
67330202e83fSDavid Sterba 			dir_inode = btrfs_iget(fs_info->sb, inode_key.objectid,
67340202e83fSDavid Sterba 					       root);
67350f375eedSFilipe Manana 			/*
67360f375eedSFilipe Manana 			 * If the parent inode was deleted, return an error to
67370f375eedSFilipe Manana 			 * fallback to a transaction commit. This is to prevent
67380f375eedSFilipe Manana 			 * getting an inode that was moved from one parent A to
67390f375eedSFilipe Manana 			 * a parent B, got its former parent A deleted and then
67400f375eedSFilipe Manana 			 * it got fsync'ed, from existing at both parents after
67410f375eedSFilipe Manana 			 * a log replay (and the old parent still existing).
67420f375eedSFilipe Manana 			 * Example:
67430f375eedSFilipe Manana 			 *
67440f375eedSFilipe Manana 			 * mkdir /mnt/A
67450f375eedSFilipe Manana 			 * mkdir /mnt/B
67460f375eedSFilipe Manana 			 * touch /mnt/B/bar
67470f375eedSFilipe Manana 			 * sync
67480f375eedSFilipe Manana 			 * mv /mnt/B/bar /mnt/A/bar
67490f375eedSFilipe Manana 			 * mv -T /mnt/A /mnt/B
67500f375eedSFilipe Manana 			 * fsync /mnt/B/bar
67510f375eedSFilipe Manana 			 * <power fail>
67520f375eedSFilipe Manana 			 *
67530f375eedSFilipe Manana 			 * If we ignore the old parent B which got deleted,
67540f375eedSFilipe Manana 			 * after a log replay we would have file bar linked
67550f375eedSFilipe Manana 			 * at both parents and the old parent B would still
67560f375eedSFilipe Manana 			 * exist.
67570f375eedSFilipe Manana 			 */
67580f375eedSFilipe Manana 			if (IS_ERR(dir_inode)) {
67590f375eedSFilipe Manana 				ret = PTR_ERR(dir_inode);
67600f375eedSFilipe Manana 				goto out;
67610f375eedSFilipe Manana 			}
676218aa0922SFilipe Manana 
67633e6a86a1SFilipe Manana 			if (!need_log_inode(trans, BTRFS_I(dir_inode))) {
6764e55cf7caSDavid Sterba 				btrfs_add_delayed_iput(BTRFS_I(dir_inode));
67653e6a86a1SFilipe Manana 				continue;
67663e6a86a1SFilipe Manana 			}
67673e6a86a1SFilipe Manana 
6768657ed1aaSFilipe Manana 			ctx->log_new_dentries = false;
676990d04510SFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(dir_inode),
677048778179SFilipe Manana 					      LOG_INODE_ALL, ctx);
6771289cffcbSFilipe Manana 			if (!ret && ctx->log_new_dentries)
67728786a6d7SFilipe Manana 				ret = log_new_dir_dentries(trans,
677351cc0d32SNikolay Borisov 						   BTRFS_I(dir_inode), ctx);
6774e55cf7caSDavid Sterba 			btrfs_add_delayed_iput(BTRFS_I(dir_inode));
677518aa0922SFilipe Manana 			if (ret)
677618aa0922SFilipe Manana 				goto out;
677718aa0922SFilipe Manana 		}
677818aa0922SFilipe Manana 		path->slots[0]++;
677918aa0922SFilipe Manana 	}
678018aa0922SFilipe Manana 	ret = 0;
678118aa0922SFilipe Manana out:
678218aa0922SFilipe Manana 	btrfs_free_path(path);
678318aa0922SFilipe Manana 	return ret;
678418aa0922SFilipe Manana }
678518aa0922SFilipe Manana 
6786b8aa330dSFilipe Manana static int log_new_ancestors(struct btrfs_trans_handle *trans,
6787b8aa330dSFilipe Manana 			     struct btrfs_root *root,
6788b8aa330dSFilipe Manana 			     struct btrfs_path *path,
6789b8aa330dSFilipe Manana 			     struct btrfs_log_ctx *ctx)
6790b8aa330dSFilipe Manana {
6791b8aa330dSFilipe Manana 	struct btrfs_key found_key;
6792b8aa330dSFilipe Manana 
6793b8aa330dSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
6794b8aa330dSFilipe Manana 
6795b8aa330dSFilipe Manana 	while (true) {
6796b8aa330dSFilipe Manana 		struct btrfs_fs_info *fs_info = root->fs_info;
6797b8aa330dSFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
6798b8aa330dSFilipe Manana 		int slot = path->slots[0];
6799b8aa330dSFilipe Manana 		struct btrfs_key search_key;
6800b8aa330dSFilipe Manana 		struct inode *inode;
68010202e83fSDavid Sterba 		u64 ino;
6802b8aa330dSFilipe Manana 		int ret = 0;
6803b8aa330dSFilipe Manana 
6804b8aa330dSFilipe Manana 		btrfs_release_path(path);
6805b8aa330dSFilipe Manana 
68060202e83fSDavid Sterba 		ino = found_key.offset;
68070202e83fSDavid Sterba 
6808b8aa330dSFilipe Manana 		search_key.objectid = found_key.offset;
6809b8aa330dSFilipe Manana 		search_key.type = BTRFS_INODE_ITEM_KEY;
6810b8aa330dSFilipe Manana 		search_key.offset = 0;
68110202e83fSDavid Sterba 		inode = btrfs_iget(fs_info->sb, ino, root);
6812b8aa330dSFilipe Manana 		if (IS_ERR(inode))
6813b8aa330dSFilipe Manana 			return PTR_ERR(inode);
6814b8aa330dSFilipe Manana 
6815ab12313aSFilipe Manana 		if (BTRFS_I(inode)->generation >= trans->transid &&
6816ab12313aSFilipe Manana 		    need_log_inode(trans, BTRFS_I(inode)))
681790d04510SFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(inode),
681848778179SFilipe Manana 					      LOG_INODE_EXISTS, ctx);
6819e55cf7caSDavid Sterba 		btrfs_add_delayed_iput(BTRFS_I(inode));
6820b8aa330dSFilipe Manana 		if (ret)
6821b8aa330dSFilipe Manana 			return ret;
6822b8aa330dSFilipe Manana 
6823b8aa330dSFilipe Manana 		if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
6824b8aa330dSFilipe Manana 			break;
6825b8aa330dSFilipe Manana 
6826b8aa330dSFilipe Manana 		search_key.type = BTRFS_INODE_REF_KEY;
6827b8aa330dSFilipe Manana 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6828b8aa330dSFilipe Manana 		if (ret < 0)
6829b8aa330dSFilipe Manana 			return ret;
6830b8aa330dSFilipe Manana 
6831b8aa330dSFilipe Manana 		leaf = path->nodes[0];
6832b8aa330dSFilipe Manana 		slot = path->slots[0];
6833b8aa330dSFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
6834b8aa330dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
6835b8aa330dSFilipe Manana 			if (ret < 0)
6836b8aa330dSFilipe Manana 				return ret;
6837b8aa330dSFilipe Manana 			else if (ret > 0)
6838b8aa330dSFilipe Manana 				return -ENOENT;
6839b8aa330dSFilipe Manana 			leaf = path->nodes[0];
6840b8aa330dSFilipe Manana 			slot = path->slots[0];
6841b8aa330dSFilipe Manana 		}
6842b8aa330dSFilipe Manana 
6843b8aa330dSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
6844b8aa330dSFilipe Manana 		if (found_key.objectid != search_key.objectid ||
6845b8aa330dSFilipe Manana 		    found_key.type != BTRFS_INODE_REF_KEY)
6846b8aa330dSFilipe Manana 			return -ENOENT;
6847b8aa330dSFilipe Manana 	}
6848b8aa330dSFilipe Manana 	return 0;
6849b8aa330dSFilipe Manana }
6850b8aa330dSFilipe Manana 
6851b8aa330dSFilipe Manana static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
6852b8aa330dSFilipe Manana 				  struct btrfs_inode *inode,
6853b8aa330dSFilipe Manana 				  struct dentry *parent,
6854b8aa330dSFilipe Manana 				  struct btrfs_log_ctx *ctx)
6855b8aa330dSFilipe Manana {
6856b8aa330dSFilipe Manana 	struct btrfs_root *root = inode->root;
6857b8aa330dSFilipe Manana 	struct dentry *old_parent = NULL;
6858b8aa330dSFilipe Manana 	struct super_block *sb = inode->vfs_inode.i_sb;
6859b8aa330dSFilipe Manana 	int ret = 0;
6860b8aa330dSFilipe Manana 
6861b8aa330dSFilipe Manana 	while (true) {
6862b8aa330dSFilipe Manana 		if (!parent || d_really_is_negative(parent) ||
6863b8aa330dSFilipe Manana 		    sb != parent->d_sb)
6864b8aa330dSFilipe Manana 			break;
6865b8aa330dSFilipe Manana 
6866b8aa330dSFilipe Manana 		inode = BTRFS_I(d_inode(parent));
6867b8aa330dSFilipe Manana 		if (root != inode->root)
6868b8aa330dSFilipe Manana 			break;
6869b8aa330dSFilipe Manana 
6870ab12313aSFilipe Manana 		if (inode->generation >= trans->transid &&
6871ab12313aSFilipe Manana 		    need_log_inode(trans, inode)) {
687290d04510SFilipe Manana 			ret = btrfs_log_inode(trans, inode,
687348778179SFilipe Manana 					      LOG_INODE_EXISTS, ctx);
6874b8aa330dSFilipe Manana 			if (ret)
6875b8aa330dSFilipe Manana 				break;
6876b8aa330dSFilipe Manana 		}
6877b8aa330dSFilipe Manana 		if (IS_ROOT(parent))
6878b8aa330dSFilipe Manana 			break;
6879b8aa330dSFilipe Manana 
6880b8aa330dSFilipe Manana 		parent = dget_parent(parent);
6881b8aa330dSFilipe Manana 		dput(old_parent);
6882b8aa330dSFilipe Manana 		old_parent = parent;
6883b8aa330dSFilipe Manana 	}
6884b8aa330dSFilipe Manana 	dput(old_parent);
6885b8aa330dSFilipe Manana 
6886b8aa330dSFilipe Manana 	return ret;
6887b8aa330dSFilipe Manana }
6888b8aa330dSFilipe Manana 
6889b8aa330dSFilipe Manana static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
6890b8aa330dSFilipe Manana 				 struct btrfs_inode *inode,
6891b8aa330dSFilipe Manana 				 struct dentry *parent,
6892b8aa330dSFilipe Manana 				 struct btrfs_log_ctx *ctx)
6893b8aa330dSFilipe Manana {
6894b8aa330dSFilipe Manana 	struct btrfs_root *root = inode->root;
6895b8aa330dSFilipe Manana 	const u64 ino = btrfs_ino(inode);
6896b8aa330dSFilipe Manana 	struct btrfs_path *path;
6897b8aa330dSFilipe Manana 	struct btrfs_key search_key;
6898b8aa330dSFilipe Manana 	int ret;
6899b8aa330dSFilipe Manana 
6900b8aa330dSFilipe Manana 	/*
6901b8aa330dSFilipe Manana 	 * For a single hard link case, go through a fast path that does not
6902b8aa330dSFilipe Manana 	 * need to iterate the fs/subvolume tree.
6903b8aa330dSFilipe Manana 	 */
6904b8aa330dSFilipe Manana 	if (inode->vfs_inode.i_nlink < 2)
6905b8aa330dSFilipe Manana 		return log_new_ancestors_fast(trans, inode, parent, ctx);
6906b8aa330dSFilipe Manana 
6907b8aa330dSFilipe Manana 	path = btrfs_alloc_path();
6908b8aa330dSFilipe Manana 	if (!path)
6909b8aa330dSFilipe Manana 		return -ENOMEM;
6910b8aa330dSFilipe Manana 
6911b8aa330dSFilipe Manana 	search_key.objectid = ino;
6912b8aa330dSFilipe Manana 	search_key.type = BTRFS_INODE_REF_KEY;
6913b8aa330dSFilipe Manana 	search_key.offset = 0;
6914b8aa330dSFilipe Manana again:
6915b8aa330dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6916b8aa330dSFilipe Manana 	if (ret < 0)
6917b8aa330dSFilipe Manana 		goto out;
6918b8aa330dSFilipe Manana 	if (ret == 0)
6919b8aa330dSFilipe Manana 		path->slots[0]++;
6920b8aa330dSFilipe Manana 
6921b8aa330dSFilipe Manana 	while (true) {
6922b8aa330dSFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
6923b8aa330dSFilipe Manana 		int slot = path->slots[0];
6924b8aa330dSFilipe Manana 		struct btrfs_key found_key;
6925b8aa330dSFilipe Manana 
6926b8aa330dSFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
6927b8aa330dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
6928b8aa330dSFilipe Manana 			if (ret < 0)
6929b8aa330dSFilipe Manana 				goto out;
6930b8aa330dSFilipe Manana 			else if (ret > 0)
6931b8aa330dSFilipe Manana 				break;
6932b8aa330dSFilipe Manana 			continue;
6933b8aa330dSFilipe Manana 		}
6934b8aa330dSFilipe Manana 
6935b8aa330dSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
6936b8aa330dSFilipe Manana 		if (found_key.objectid != ino ||
6937b8aa330dSFilipe Manana 		    found_key.type > BTRFS_INODE_EXTREF_KEY)
6938b8aa330dSFilipe Manana 			break;
6939b8aa330dSFilipe Manana 
6940b8aa330dSFilipe Manana 		/*
6941b8aa330dSFilipe Manana 		 * Don't deal with extended references because they are rare
6942b8aa330dSFilipe Manana 		 * cases and too complex to deal with (we would need to keep
6943b8aa330dSFilipe Manana 		 * track of which subitem we are processing for each item in
6944b8aa330dSFilipe Manana 		 * this loop, etc). So just return some error to fallback to
6945b8aa330dSFilipe Manana 		 * a transaction commit.
6946b8aa330dSFilipe Manana 		 */
6947b8aa330dSFilipe Manana 		if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
6948b8aa330dSFilipe Manana 			ret = -EMLINK;
6949b8aa330dSFilipe Manana 			goto out;
6950b8aa330dSFilipe Manana 		}
6951b8aa330dSFilipe Manana 
6952b8aa330dSFilipe Manana 		/*
6953b8aa330dSFilipe Manana 		 * Logging ancestors needs to do more searches on the fs/subvol
6954b8aa330dSFilipe Manana 		 * tree, so it releases the path as needed to avoid deadlocks.
6955b8aa330dSFilipe Manana 		 * Keep track of the last inode ref key and resume from that key
6956b8aa330dSFilipe Manana 		 * after logging all new ancestors for the current hard link.
6957b8aa330dSFilipe Manana 		 */
6958b8aa330dSFilipe Manana 		memcpy(&search_key, &found_key, sizeof(search_key));
6959b8aa330dSFilipe Manana 
6960b8aa330dSFilipe Manana 		ret = log_new_ancestors(trans, root, path, ctx);
6961b8aa330dSFilipe Manana 		if (ret)
6962b8aa330dSFilipe Manana 			goto out;
6963b8aa330dSFilipe Manana 		btrfs_release_path(path);
6964b8aa330dSFilipe Manana 		goto again;
6965b8aa330dSFilipe Manana 	}
6966b8aa330dSFilipe Manana 	ret = 0;
6967b8aa330dSFilipe Manana out:
6968b8aa330dSFilipe Manana 	btrfs_free_path(path);
6969b8aa330dSFilipe Manana 	return ret;
6970b8aa330dSFilipe Manana }
6971b8aa330dSFilipe Manana 
6972e02119d5SChris Mason /*
6973e02119d5SChris Mason  * helper function around btrfs_log_inode to make sure newly created
6974e02119d5SChris Mason  * parent directories also end up in the log.  A minimal inode and backref
6975e02119d5SChris Mason  * only logging is done of any parent directories that are older than
6976e02119d5SChris Mason  * the last committed transaction
6977e02119d5SChris Mason  */
697848a3b636SEric Sandeen static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
697919df27a9SNikolay Borisov 				  struct btrfs_inode *inode,
698049dae1bcSFilipe Manana 				  struct dentry *parent,
698141a1eadaSEdmund Nadolski 				  int inode_only,
69828b050d35SMiao Xie 				  struct btrfs_log_ctx *ctx)
6983e02119d5SChris Mason {
6984f882274bSNikolay Borisov 	struct btrfs_root *root = inode->root;
69850b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
698612fcfd22SChris Mason 	int ret = 0;
69872f2ff0eeSFilipe Manana 	bool log_dentries = false;
698812fcfd22SChris Mason 
69890b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, NOTREELOG)) {
6990f31f09f6SJosef Bacik 		ret = BTRFS_LOG_FORCE_COMMIT;
69913a5e1404SSage Weil 		goto end_no_trans;
69923a5e1404SSage Weil 	}
69933a5e1404SSage Weil 
6994f882274bSNikolay Borisov 	if (btrfs_root_refs(&root->root_item) == 0) {
6995f31f09f6SJosef Bacik 		ret = BTRFS_LOG_FORCE_COMMIT;
699676dda93cSYan, Zheng 		goto end_no_trans;
699776dda93cSYan, Zheng 	}
699876dda93cSYan, Zheng 
6999f2d72f42SFilipe Manana 	/*
7000f2d72f42SFilipe Manana 	 * Skip already logged inodes or inodes corresponding to tmpfiles
7001f2d72f42SFilipe Manana 	 * (since logging them is pointless, a link count of 0 means they
7002f2d72f42SFilipe Manana 	 * will never be accessible).
7003f2d72f42SFilipe Manana 	 */
7004626e9f41SFilipe Manana 	if ((btrfs_inode_in_log(inode, trans->transid) &&
7005626e9f41SFilipe Manana 	     list_empty(&ctx->ordered_extents)) ||
7006f2d72f42SFilipe Manana 	    inode->vfs_inode.i_nlink == 0) {
7007257c62e1SChris Mason 		ret = BTRFS_NO_LOG_SYNC;
7008257c62e1SChris Mason 		goto end_no_trans;
7009257c62e1SChris Mason 	}
7010257c62e1SChris Mason 
70118b050d35SMiao Xie 	ret = start_log_trans(trans, root, ctx);
70124a500fd1SYan, Zheng 	if (ret)
7013e87ac136SMiao Xie 		goto end_no_trans;
701412fcfd22SChris Mason 
701590d04510SFilipe Manana 	ret = btrfs_log_inode(trans, inode, inode_only, ctx);
70164a500fd1SYan, Zheng 	if (ret)
70174a500fd1SYan, Zheng 		goto end_trans;
7018e02119d5SChris Mason 
7019af4176b4SChris Mason 	/*
7020af4176b4SChris Mason 	 * for regular files, if its inode is already on disk, we don't
7021af4176b4SChris Mason 	 * have to worry about the parents at all.  This is because
7022af4176b4SChris Mason 	 * we can use the last_unlink_trans field to record renames
7023af4176b4SChris Mason 	 * and other fun in this file.
7024af4176b4SChris Mason 	 */
702519df27a9SNikolay Borisov 	if (S_ISREG(inode->vfs_inode.i_mode) &&
702647d3db41SFilipe Manana 	    inode->generation < trans->transid &&
702747d3db41SFilipe Manana 	    inode->last_unlink_trans < trans->transid) {
70284a500fd1SYan, Zheng 		ret = 0;
70294a500fd1SYan, Zheng 		goto end_trans;
70304a500fd1SYan, Zheng 	}
7031af4176b4SChris Mason 
7032289cffcbSFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode) && ctx->log_new_dentries)
70332f2ff0eeSFilipe Manana 		log_dentries = true;
70342f2ff0eeSFilipe Manana 
703518aa0922SFilipe Manana 	/*
703601327610SNicholas D Steeves 	 * On unlink we must make sure all our current and old parent directory
703718aa0922SFilipe Manana 	 * inodes are fully logged. This is to prevent leaving dangling
703818aa0922SFilipe Manana 	 * directory index entries in directories that were our parents but are
703918aa0922SFilipe Manana 	 * not anymore. Not doing this results in old parent directory being
704018aa0922SFilipe Manana 	 * impossible to delete after log replay (rmdir will always fail with
704118aa0922SFilipe Manana 	 * error -ENOTEMPTY).
704218aa0922SFilipe Manana 	 *
704318aa0922SFilipe Manana 	 * Example 1:
704418aa0922SFilipe Manana 	 *
704518aa0922SFilipe Manana 	 * mkdir testdir
704618aa0922SFilipe Manana 	 * touch testdir/foo
704718aa0922SFilipe Manana 	 * ln testdir/foo testdir/bar
704818aa0922SFilipe Manana 	 * sync
704918aa0922SFilipe Manana 	 * unlink testdir/bar
705018aa0922SFilipe Manana 	 * xfs_io -c fsync testdir/foo
705118aa0922SFilipe Manana 	 * <power failure>
705218aa0922SFilipe Manana 	 * mount fs, triggers log replay
705318aa0922SFilipe Manana 	 *
705418aa0922SFilipe Manana 	 * If we don't log the parent directory (testdir), after log replay the
705518aa0922SFilipe Manana 	 * directory still has an entry pointing to the file inode using the bar
705618aa0922SFilipe Manana 	 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
705718aa0922SFilipe Manana 	 * the file inode has a link count of 1.
705818aa0922SFilipe Manana 	 *
705918aa0922SFilipe Manana 	 * Example 2:
706018aa0922SFilipe Manana 	 *
706118aa0922SFilipe Manana 	 * mkdir testdir
706218aa0922SFilipe Manana 	 * touch foo
706318aa0922SFilipe Manana 	 * ln foo testdir/foo2
706418aa0922SFilipe Manana 	 * ln foo testdir/foo3
706518aa0922SFilipe Manana 	 * sync
706618aa0922SFilipe Manana 	 * unlink testdir/foo3
706718aa0922SFilipe Manana 	 * xfs_io -c fsync foo
706818aa0922SFilipe Manana 	 * <power failure>
706918aa0922SFilipe Manana 	 * mount fs, triggers log replay
707018aa0922SFilipe Manana 	 *
707118aa0922SFilipe Manana 	 * Similar as the first example, after log replay the parent directory
707218aa0922SFilipe Manana 	 * testdir still has an entry pointing to the inode file with name foo3
707318aa0922SFilipe Manana 	 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
707418aa0922SFilipe Manana 	 * and has a link count of 2.
707518aa0922SFilipe Manana 	 */
707647d3db41SFilipe Manana 	if (inode->last_unlink_trans >= trans->transid) {
7077b8aa330dSFilipe Manana 		ret = btrfs_log_all_parents(trans, inode, ctx);
707818aa0922SFilipe Manana 		if (ret)
707918aa0922SFilipe Manana 			goto end_trans;
708018aa0922SFilipe Manana 	}
708118aa0922SFilipe Manana 
7082b8aa330dSFilipe Manana 	ret = log_all_new_ancestors(trans, inode, parent, ctx);
70834a500fd1SYan, Zheng 	if (ret)
70844a500fd1SYan, Zheng 		goto end_trans;
708512fcfd22SChris Mason 
70862f2ff0eeSFilipe Manana 	if (log_dentries)
70878786a6d7SFilipe Manana 		ret = log_new_dir_dentries(trans, inode, ctx);
70882f2ff0eeSFilipe Manana 	else
708912fcfd22SChris Mason 		ret = 0;
70904a500fd1SYan, Zheng end_trans:
70914a500fd1SYan, Zheng 	if (ret < 0) {
709290787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
7093f31f09f6SJosef Bacik 		ret = BTRFS_LOG_FORCE_COMMIT;
70944a500fd1SYan, Zheng 	}
70958b050d35SMiao Xie 
70968b050d35SMiao Xie 	if (ret)
70978b050d35SMiao Xie 		btrfs_remove_log_ctx(root, ctx);
709812fcfd22SChris Mason 	btrfs_end_log_trans(root);
709912fcfd22SChris Mason end_no_trans:
710012fcfd22SChris Mason 	return ret;
7101e02119d5SChris Mason }
7102e02119d5SChris Mason 
7103e02119d5SChris Mason /*
7104e02119d5SChris Mason  * it is not safe to log dentry if the chunk root has added new
7105e02119d5SChris Mason  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
7106e02119d5SChris Mason  * If this returns 1, you must commit the transaction to safely get your
7107e02119d5SChris Mason  * data on disk.
7108e02119d5SChris Mason  */
7109e02119d5SChris Mason int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7110e5b84f7aSNikolay Borisov 			  struct dentry *dentry,
71118b050d35SMiao Xie 			  struct btrfs_log_ctx *ctx)
7112e02119d5SChris Mason {
71136a912213SJosef Bacik 	struct dentry *parent = dget_parent(dentry);
71146a912213SJosef Bacik 	int ret;
71156a912213SJosef Bacik 
7116f882274bSNikolay Borisov 	ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
711748778179SFilipe Manana 				     LOG_INODE_ALL, ctx);
71186a912213SJosef Bacik 	dput(parent);
71196a912213SJosef Bacik 
71206a912213SJosef Bacik 	return ret;
7121e02119d5SChris Mason }
7122e02119d5SChris Mason 
7123e02119d5SChris Mason /*
7124e02119d5SChris Mason  * should be called during mount to recover any replay any log trees
7125e02119d5SChris Mason  * from the FS
7126e02119d5SChris Mason  */
7127e02119d5SChris Mason int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7128e02119d5SChris Mason {
7129e02119d5SChris Mason 	int ret;
7130e02119d5SChris Mason 	struct btrfs_path *path;
7131e02119d5SChris Mason 	struct btrfs_trans_handle *trans;
7132e02119d5SChris Mason 	struct btrfs_key key;
7133e02119d5SChris Mason 	struct btrfs_key found_key;
7134e02119d5SChris Mason 	struct btrfs_root *log;
7135e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7136e02119d5SChris Mason 	struct walk_control wc = {
7137e02119d5SChris Mason 		.process_func = process_one_buffer,
7138430a6626SDavid Sterba 		.stage = LOG_WALK_PIN_ONLY,
7139e02119d5SChris Mason 	};
7140e02119d5SChris Mason 
7141e02119d5SChris Mason 	path = btrfs_alloc_path();
7142db5b493aSTsutomu Itoh 	if (!path)
7143db5b493aSTsutomu Itoh 		return -ENOMEM;
7144db5b493aSTsutomu Itoh 
7145afcdd129SJosef Bacik 	set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7146e02119d5SChris Mason 
71474a500fd1SYan, Zheng 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
714879787eaaSJeff Mahoney 	if (IS_ERR(trans)) {
714979787eaaSJeff Mahoney 		ret = PTR_ERR(trans);
715079787eaaSJeff Mahoney 		goto error;
715179787eaaSJeff Mahoney 	}
7152e02119d5SChris Mason 
7153e02119d5SChris Mason 	wc.trans = trans;
7154e02119d5SChris Mason 	wc.pin = 1;
7155e02119d5SChris Mason 
7156db5b493aSTsutomu Itoh 	ret = walk_log_tree(trans, log_root_tree, &wc);
715779787eaaSJeff Mahoney 	if (ret) {
7158ba51e2a1SJosef Bacik 		btrfs_abort_transaction(trans, ret);
715979787eaaSJeff Mahoney 		goto error;
716079787eaaSJeff Mahoney 	}
7161e02119d5SChris Mason 
7162e02119d5SChris Mason again:
7163e02119d5SChris Mason 	key.objectid = BTRFS_TREE_LOG_OBJECTID;
7164e02119d5SChris Mason 	key.offset = (u64)-1;
7165962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
7166e02119d5SChris Mason 
7167e02119d5SChris Mason 	while (1) {
7168e02119d5SChris Mason 		ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
716979787eaaSJeff Mahoney 
717079787eaaSJeff Mahoney 		if (ret < 0) {
7171ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
717279787eaaSJeff Mahoney 			goto error;
717379787eaaSJeff Mahoney 		}
7174e02119d5SChris Mason 		if (ret > 0) {
7175e02119d5SChris Mason 			if (path->slots[0] == 0)
7176e02119d5SChris Mason 				break;
7177e02119d5SChris Mason 			path->slots[0]--;
7178e02119d5SChris Mason 		}
7179e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7180e02119d5SChris Mason 				      path->slots[0]);
7181b3b4aa74SDavid Sterba 		btrfs_release_path(path);
7182e02119d5SChris Mason 		if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7183e02119d5SChris Mason 			break;
7184e02119d5SChris Mason 
718562a2c73eSJosef Bacik 		log = btrfs_read_tree_root(log_root_tree, &found_key);
718679787eaaSJeff Mahoney 		if (IS_ERR(log)) {
718779787eaaSJeff Mahoney 			ret = PTR_ERR(log);
7188ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
718979787eaaSJeff Mahoney 			goto error;
719079787eaaSJeff Mahoney 		}
7191e02119d5SChris Mason 
719256e9357aSDavid Sterba 		wc.replay_dest = btrfs_get_fs_root(fs_info, found_key.offset,
719356e9357aSDavid Sterba 						   true);
719479787eaaSJeff Mahoney 		if (IS_ERR(wc.replay_dest)) {
719579787eaaSJeff Mahoney 			ret = PTR_ERR(wc.replay_dest);
71969bc574deSJosef Bacik 
71979bc574deSJosef Bacik 			/*
71989bc574deSJosef Bacik 			 * We didn't find the subvol, likely because it was
71999bc574deSJosef Bacik 			 * deleted.  This is ok, simply skip this log and go to
72009bc574deSJosef Bacik 			 * the next one.
72019bc574deSJosef Bacik 			 *
72029bc574deSJosef Bacik 			 * We need to exclude the root because we can't have
72039bc574deSJosef Bacik 			 * other log replays overwriting this log as we'll read
72049bc574deSJosef Bacik 			 * it back in a few more times.  This will keep our
72059bc574deSJosef Bacik 			 * block from being modified, and we'll just bail for
72069bc574deSJosef Bacik 			 * each subsequent pass.
72079bc574deSJosef Bacik 			 */
72089bc574deSJosef Bacik 			if (ret == -ENOENT)
72099fce5704SNikolay Borisov 				ret = btrfs_pin_extent_for_log_replay(trans,
72109bc574deSJosef Bacik 							log->node->start,
72119bc574deSJosef Bacik 							log->node->len);
721200246528SJosef Bacik 			btrfs_put_root(log);
72139bc574deSJosef Bacik 
72149bc574deSJosef Bacik 			if (!ret)
72159bc574deSJosef Bacik 				goto next;
7216ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
721779787eaaSJeff Mahoney 			goto error;
721879787eaaSJeff Mahoney 		}
7219e02119d5SChris Mason 
722007d400a6SYan Zheng 		wc.replay_dest->log_root = log;
72212002ae11SJosef Bacik 		ret = btrfs_record_root_in_trans(trans, wc.replay_dest);
72222002ae11SJosef Bacik 		if (ret)
72232002ae11SJosef Bacik 			/* The loop needs to continue due to the root refs */
7224ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
72252002ae11SJosef Bacik 		else
7226e02119d5SChris Mason 			ret = walk_log_tree(trans, log, &wc);
7227e02119d5SChris Mason 
7228b50c6e25SJosef Bacik 		if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7229e02119d5SChris Mason 			ret = fixup_inode_link_counts(trans, wc.replay_dest,
7230e02119d5SChris Mason 						      path);
7231ba51e2a1SJosef Bacik 			if (ret)
7232ba51e2a1SJosef Bacik 				btrfs_abort_transaction(trans, ret);
7233e02119d5SChris Mason 		}
7234e02119d5SChris Mason 
7235900c9981SLiu Bo 		if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
7236900c9981SLiu Bo 			struct btrfs_root *root = wc.replay_dest;
7237900c9981SLiu Bo 
7238900c9981SLiu Bo 			btrfs_release_path(path);
7239900c9981SLiu Bo 
7240900c9981SLiu Bo 			/*
7241900c9981SLiu Bo 			 * We have just replayed everything, and the highest
7242900c9981SLiu Bo 			 * objectid of fs roots probably has changed in case
7243900c9981SLiu Bo 			 * some inode_item's got replayed.
7244900c9981SLiu Bo 			 *
7245900c9981SLiu Bo 			 * root->objectid_mutex is not acquired as log replay
7246900c9981SLiu Bo 			 * could only happen during mount.
7247900c9981SLiu Bo 			 */
7248453e4873SNikolay Borisov 			ret = btrfs_init_root_free_objectid(root);
7249ba51e2a1SJosef Bacik 			if (ret)
7250ba51e2a1SJosef Bacik 				btrfs_abort_transaction(trans, ret);
7251900c9981SLiu Bo 		}
7252900c9981SLiu Bo 
725307d400a6SYan Zheng 		wc.replay_dest->log_root = NULL;
725400246528SJosef Bacik 		btrfs_put_root(wc.replay_dest);
725500246528SJosef Bacik 		btrfs_put_root(log);
7256e02119d5SChris Mason 
7257b50c6e25SJosef Bacik 		if (ret)
7258b50c6e25SJosef Bacik 			goto error;
72599bc574deSJosef Bacik next:
7260e02119d5SChris Mason 		if (found_key.offset == 0)
7261e02119d5SChris Mason 			break;
72629bc574deSJosef Bacik 		key.offset = found_key.offset - 1;
7263e02119d5SChris Mason 	}
7264b3b4aa74SDavid Sterba 	btrfs_release_path(path);
7265e02119d5SChris Mason 
7266e02119d5SChris Mason 	/* step one is to pin it all, step two is to replay just inodes */
7267e02119d5SChris Mason 	if (wc.pin) {
7268e02119d5SChris Mason 		wc.pin = 0;
7269e02119d5SChris Mason 		wc.process_func = replay_one_buffer;
7270e02119d5SChris Mason 		wc.stage = LOG_WALK_REPLAY_INODES;
7271e02119d5SChris Mason 		goto again;
7272e02119d5SChris Mason 	}
7273e02119d5SChris Mason 	/* step three is to replay everything */
7274e02119d5SChris Mason 	if (wc.stage < LOG_WALK_REPLAY_ALL) {
7275e02119d5SChris Mason 		wc.stage++;
7276e02119d5SChris Mason 		goto again;
7277e02119d5SChris Mason 	}
7278e02119d5SChris Mason 
7279e02119d5SChris Mason 	btrfs_free_path(path);
7280e02119d5SChris Mason 
7281abefa55aSJosef Bacik 	/* step 4: commit the transaction, which also unpins the blocks */
72823a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
7283abefa55aSJosef Bacik 	if (ret)
7284abefa55aSJosef Bacik 		return ret;
7285abefa55aSJosef Bacik 
7286e02119d5SChris Mason 	log_root_tree->log_root = NULL;
7287afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
728800246528SJosef Bacik 	btrfs_put_root(log_root_tree);
728979787eaaSJeff Mahoney 
7290abefa55aSJosef Bacik 	return 0;
729179787eaaSJeff Mahoney error:
7292b50c6e25SJosef Bacik 	if (wc.trans)
72933a45bb20SJeff Mahoney 		btrfs_end_transaction(wc.trans);
72941aeb6b56SDavid Sterba 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
729579787eaaSJeff Mahoney 	btrfs_free_path(path);
729679787eaaSJeff Mahoney 	return ret;
7297e02119d5SChris Mason }
729812fcfd22SChris Mason 
729912fcfd22SChris Mason /*
730012fcfd22SChris Mason  * there are some corner cases where we want to force a full
730112fcfd22SChris Mason  * commit instead of allowing a directory to be logged.
730212fcfd22SChris Mason  *
730312fcfd22SChris Mason  * They revolve around files there were unlinked from the directory, and
730412fcfd22SChris Mason  * this function updates the parent directory so that a full commit is
730512fcfd22SChris Mason  * properly done if it is fsync'd later after the unlinks are done.
73062be63d5cSFilipe Manana  *
73072be63d5cSFilipe Manana  * Must be called before the unlink operations (updates to the subvolume tree,
73082be63d5cSFilipe Manana  * inodes, etc) are done.
730912fcfd22SChris Mason  */
731012fcfd22SChris Mason void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
73114176bdbfSNikolay Borisov 			     struct btrfs_inode *dir, struct btrfs_inode *inode,
731212fcfd22SChris Mason 			     int for_rename)
731312fcfd22SChris Mason {
731412fcfd22SChris Mason 	/*
7315af4176b4SChris Mason 	 * when we're logging a file, if it hasn't been renamed
7316af4176b4SChris Mason 	 * or unlinked, and its inode is fully committed on disk,
7317af4176b4SChris Mason 	 * we don't have to worry about walking up the directory chain
7318af4176b4SChris Mason 	 * to log its parents.
7319af4176b4SChris Mason 	 *
7320af4176b4SChris Mason 	 * So, we use the last_unlink_trans field to put this transid
7321af4176b4SChris Mason 	 * into the file.  When the file is logged we check it and
7322af4176b4SChris Mason 	 * don't log the parents if the file is fully on disk.
7323af4176b4SChris Mason 	 */
73244176bdbfSNikolay Borisov 	mutex_lock(&inode->log_mutex);
73254176bdbfSNikolay Borisov 	inode->last_unlink_trans = trans->transid;
73264176bdbfSNikolay Borisov 	mutex_unlock(&inode->log_mutex);
7327af4176b4SChris Mason 
7328af4176b4SChris Mason 	/*
732912fcfd22SChris Mason 	 * if this directory was already logged any new
733012fcfd22SChris Mason 	 * names for this file/dir will get recorded
733112fcfd22SChris Mason 	 */
73324176bdbfSNikolay Borisov 	if (dir->logged_trans == trans->transid)
733312fcfd22SChris Mason 		return;
733412fcfd22SChris Mason 
733512fcfd22SChris Mason 	/*
733612fcfd22SChris Mason 	 * if the inode we're about to unlink was logged,
733712fcfd22SChris Mason 	 * the log will be properly updated for any new names
733812fcfd22SChris Mason 	 */
73394176bdbfSNikolay Borisov 	if (inode->logged_trans == trans->transid)
734012fcfd22SChris Mason 		return;
734112fcfd22SChris Mason 
734212fcfd22SChris Mason 	/*
734312fcfd22SChris Mason 	 * when renaming files across directories, if the directory
734412fcfd22SChris Mason 	 * there we're unlinking from gets fsync'd later on, there's
734512fcfd22SChris Mason 	 * no way to find the destination directory later and fsync it
734612fcfd22SChris Mason 	 * properly.  So, we have to be conservative and force commits
734712fcfd22SChris Mason 	 * so the new name gets discovered.
734812fcfd22SChris Mason 	 */
734912fcfd22SChris Mason 	if (for_rename)
735012fcfd22SChris Mason 		goto record;
735112fcfd22SChris Mason 
735212fcfd22SChris Mason 	/* we can safely do the unlink without any special recording */
735312fcfd22SChris Mason 	return;
735412fcfd22SChris Mason 
735512fcfd22SChris Mason record:
73564176bdbfSNikolay Borisov 	mutex_lock(&dir->log_mutex);
73574176bdbfSNikolay Borisov 	dir->last_unlink_trans = trans->transid;
73584176bdbfSNikolay Borisov 	mutex_unlock(&dir->log_mutex);
735912fcfd22SChris Mason }
736012fcfd22SChris Mason 
736112fcfd22SChris Mason /*
73621ec9a1aeSFilipe Manana  * Make sure that if someone attempts to fsync the parent directory of a deleted
73631ec9a1aeSFilipe Manana  * snapshot, it ends up triggering a transaction commit. This is to guarantee
73641ec9a1aeSFilipe Manana  * that after replaying the log tree of the parent directory's root we will not
73651ec9a1aeSFilipe Manana  * see the snapshot anymore and at log replay time we will not see any log tree
73661ec9a1aeSFilipe Manana  * corresponding to the deleted snapshot's root, which could lead to replaying
73671ec9a1aeSFilipe Manana  * it after replaying the log tree of the parent directory (which would replay
73681ec9a1aeSFilipe Manana  * the snapshot delete operation).
73692be63d5cSFilipe Manana  *
73702be63d5cSFilipe Manana  * Must be called before the actual snapshot destroy operation (updates to the
73712be63d5cSFilipe Manana  * parent root and tree of tree roots trees, etc) are done.
73721ec9a1aeSFilipe Manana  */
73731ec9a1aeSFilipe Manana void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
737443663557SNikolay Borisov 				   struct btrfs_inode *dir)
73751ec9a1aeSFilipe Manana {
737643663557SNikolay Borisov 	mutex_lock(&dir->log_mutex);
737743663557SNikolay Borisov 	dir->last_unlink_trans = trans->transid;
737843663557SNikolay Borisov 	mutex_unlock(&dir->log_mutex);
73791ec9a1aeSFilipe Manana }
73801ec9a1aeSFilipe Manana 
738143dd529aSDavid Sterba /*
7382d5f5bd54SFilipe Manana  * Update the log after adding a new name for an inode.
7383d5f5bd54SFilipe Manana  *
7384d5f5bd54SFilipe Manana  * @trans:              Transaction handle.
7385d5f5bd54SFilipe Manana  * @old_dentry:         The dentry associated with the old name and the old
7386d5f5bd54SFilipe Manana  *                      parent directory.
7387d5f5bd54SFilipe Manana  * @old_dir:            The inode of the previous parent directory for the case
7388d5f5bd54SFilipe Manana  *                      of a rename. For a link operation, it must be NULL.
738988d2beecSFilipe Manana  * @old_dir_index:      The index number associated with the old name, meaningful
739088d2beecSFilipe Manana  *                      only for rename operations (when @old_dir is not NULL).
739188d2beecSFilipe Manana  *                      Ignored for link operations.
7392d5f5bd54SFilipe Manana  * @parent:             The dentry associated with the directory under which the
7393d5f5bd54SFilipe Manana  *                      new name is located.
7394d5f5bd54SFilipe Manana  *
7395d5f5bd54SFilipe Manana  * Call this after adding a new name for an inode, as a result of a link or
7396d5f5bd54SFilipe Manana  * rename operation, and it will properly update the log to reflect the new name.
739712fcfd22SChris Mason  */
739875b463d2SFilipe Manana void btrfs_log_new_name(struct btrfs_trans_handle *trans,
7399d5f5bd54SFilipe Manana 			struct dentry *old_dentry, struct btrfs_inode *old_dir,
740088d2beecSFilipe Manana 			u64 old_dir_index, struct dentry *parent)
740112fcfd22SChris Mason {
7402d5f5bd54SFilipe Manana 	struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
7403259c4b96SFilipe Manana 	struct btrfs_root *root = inode->root;
740475b463d2SFilipe Manana 	struct btrfs_log_ctx ctx;
7405259c4b96SFilipe Manana 	bool log_pinned = false;
74060f8ce498SFilipe Manana 	int ret;
740712fcfd22SChris Mason 
740812fcfd22SChris Mason 	/*
7409af4176b4SChris Mason 	 * this will force the logging code to walk the dentry chain
7410af4176b4SChris Mason 	 * up for the file
7411af4176b4SChris Mason 	 */
74129a6509c4SFilipe Manana 	if (!S_ISDIR(inode->vfs_inode.i_mode))
74139ca5fbfbSNikolay Borisov 		inode->last_unlink_trans = trans->transid;
7414af4176b4SChris Mason 
7415af4176b4SChris Mason 	/*
741612fcfd22SChris Mason 	 * if this inode hasn't been logged and directory we're renaming it
741712fcfd22SChris Mason 	 * from hasn't been logged, we don't need to log it
741812fcfd22SChris Mason 	 */
74190f8ce498SFilipe Manana 	ret = inode_logged(trans, inode, NULL);
74200f8ce498SFilipe Manana 	if (ret < 0) {
74210f8ce498SFilipe Manana 		goto out;
74220f8ce498SFilipe Manana 	} else if (ret == 0) {
74230f8ce498SFilipe Manana 		if (!old_dir)
742475b463d2SFilipe Manana 			return;
74250f8ce498SFilipe Manana 		/*
74260f8ce498SFilipe Manana 		 * If the inode was not logged and we are doing a rename (old_dir is not
74270f8ce498SFilipe Manana 		 * NULL), check if old_dir was logged - if it was not we can return and
74280f8ce498SFilipe Manana 		 * do nothing.
74290f8ce498SFilipe Manana 		 */
74300f8ce498SFilipe Manana 		ret = inode_logged(trans, old_dir, NULL);
74310f8ce498SFilipe Manana 		if (ret < 0)
74320f8ce498SFilipe Manana 			goto out;
74330f8ce498SFilipe Manana 		else if (ret == 0)
74340f8ce498SFilipe Manana 			return;
74350f8ce498SFilipe Manana 	}
74360f8ce498SFilipe Manana 	ret = 0;
743712fcfd22SChris Mason 
743854a40fc3SFilipe Manana 	/*
743954a40fc3SFilipe Manana 	 * If we are doing a rename (old_dir is not NULL) from a directory that
744088d2beecSFilipe Manana 	 * was previously logged, make sure that on log replay we get the old
744188d2beecSFilipe Manana 	 * dir entry deleted. This is needed because we will also log the new
744288d2beecSFilipe Manana 	 * name of the renamed inode, so we need to make sure that after log
744388d2beecSFilipe Manana 	 * replay we don't end up with both the new and old dir entries existing.
744454a40fc3SFilipe Manana 	 */
744588d2beecSFilipe Manana 	if (old_dir && old_dir->logged_trans == trans->transid) {
744688d2beecSFilipe Manana 		struct btrfs_root *log = old_dir->root->log_root;
744788d2beecSFilipe Manana 		struct btrfs_path *path;
7448ab3c5c18SSweet Tea Dorminy 		struct fscrypt_name fname;
744988d2beecSFilipe Manana 
745088d2beecSFilipe Manana 		ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX);
745188d2beecSFilipe Manana 
7452ab3c5c18SSweet Tea Dorminy 		ret = fscrypt_setup_filename(&old_dir->vfs_inode,
7453ab3c5c18SSweet Tea Dorminy 					     &old_dentry->d_name, 0, &fname);
7454ab3c5c18SSweet Tea Dorminy 		if (ret)
7455ab3c5c18SSweet Tea Dorminy 			goto out;
7456259c4b96SFilipe Manana 		/*
7457259c4b96SFilipe Manana 		 * We have two inodes to update in the log, the old directory and
7458259c4b96SFilipe Manana 		 * the inode that got renamed, so we must pin the log to prevent
7459259c4b96SFilipe Manana 		 * anyone from syncing the log until we have updated both inodes
7460259c4b96SFilipe Manana 		 * in the log.
7461259c4b96SFilipe Manana 		 */
7462723df2bcSFilipe Manana 		ret = join_running_log_trans(root);
7463723df2bcSFilipe Manana 		/*
7464723df2bcSFilipe Manana 		 * At least one of the inodes was logged before, so this should
7465723df2bcSFilipe Manana 		 * not fail, but if it does, it's not serious, just bail out and
7466723df2bcSFilipe Manana 		 * mark the log for a full commit.
7467723df2bcSFilipe Manana 		 */
7468fee4c199SFilipe Manana 		if (WARN_ON_ONCE(ret < 0)) {
7469fee4c199SFilipe Manana 			fscrypt_free_filename(&fname);
7470723df2bcSFilipe Manana 			goto out;
7471fee4c199SFilipe Manana 		}
7472fee4c199SFilipe Manana 
7473259c4b96SFilipe Manana 		log_pinned = true;
7474259c4b96SFilipe Manana 
747588d2beecSFilipe Manana 		path = btrfs_alloc_path();
747688d2beecSFilipe Manana 		if (!path) {
7477259c4b96SFilipe Manana 			ret = -ENOMEM;
7478ab3c5c18SSweet Tea Dorminy 			fscrypt_free_filename(&fname);
7479259c4b96SFilipe Manana 			goto out;
748088d2beecSFilipe Manana 		}
748188d2beecSFilipe Manana 
748288d2beecSFilipe Manana 		/*
748388d2beecSFilipe Manana 		 * Other concurrent task might be logging the old directory,
748488d2beecSFilipe Manana 		 * as it can be triggered when logging other inode that had or
7485750ee454SFilipe Manana 		 * still has a dentry in the old directory. We lock the old
7486750ee454SFilipe Manana 		 * directory's log_mutex to ensure the deletion of the old
7487750ee454SFilipe Manana 		 * name is persisted, because during directory logging we
7488750ee454SFilipe Manana 		 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
7489750ee454SFilipe Manana 		 * the old name's dir index item is in the delayed items, so
7490750ee454SFilipe Manana 		 * it could be missed by an in progress directory logging.
749188d2beecSFilipe Manana 		 */
749288d2beecSFilipe Manana 		mutex_lock(&old_dir->log_mutex);
749388d2beecSFilipe Manana 		ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
74946db75318SSweet Tea Dorminy 					&fname.disk_name, old_dir_index);
749588d2beecSFilipe Manana 		if (ret > 0) {
749688d2beecSFilipe Manana 			/*
749788d2beecSFilipe Manana 			 * The dentry does not exist in the log, so record its
749888d2beecSFilipe Manana 			 * deletion.
749988d2beecSFilipe Manana 			 */
750088d2beecSFilipe Manana 			btrfs_release_path(path);
750188d2beecSFilipe Manana 			ret = insert_dir_log_key(trans, log, path,
750288d2beecSFilipe Manana 						 btrfs_ino(old_dir),
750388d2beecSFilipe Manana 						 old_dir_index, old_dir_index);
750488d2beecSFilipe Manana 		}
750588d2beecSFilipe Manana 		mutex_unlock(&old_dir->log_mutex);
750688d2beecSFilipe Manana 
750788d2beecSFilipe Manana 		btrfs_free_path(path);
7508ab3c5c18SSweet Tea Dorminy 		fscrypt_free_filename(&fname);
7509259c4b96SFilipe Manana 		if (ret < 0)
7510259c4b96SFilipe Manana 			goto out;
751188d2beecSFilipe Manana 	}
751254a40fc3SFilipe Manana 
751375b463d2SFilipe Manana 	btrfs_init_log_ctx(&ctx, &inode->vfs_inode);
751475b463d2SFilipe Manana 	ctx.logging_new_name = true;
751575b463d2SFilipe Manana 	/*
751675b463d2SFilipe Manana 	 * We don't care about the return value. If we fail to log the new name
751775b463d2SFilipe Manana 	 * then we know the next attempt to sync the log will fallback to a full
751875b463d2SFilipe Manana 	 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
751975b463d2SFilipe Manana 	 * we don't need to worry about getting a log committed that has an
752075b463d2SFilipe Manana 	 * inconsistent state after a rename operation.
752175b463d2SFilipe Manana 	 */
752248778179SFilipe Manana 	btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
7523e09d94c9SFilipe Manana 	ASSERT(list_empty(&ctx.conflict_inodes));
7524259c4b96SFilipe Manana out:
7525259c4b96SFilipe Manana 	/*
75260f8ce498SFilipe Manana 	 * If an error happened mark the log for a full commit because it's not
75270f8ce498SFilipe Manana 	 * consistent and up to date or we couldn't find out if one of the
75280f8ce498SFilipe Manana 	 * inodes was logged before in this transaction. Do it before unpinning
75290f8ce498SFilipe Manana 	 * the log, to avoid any races with someone else trying to commit it.
7530259c4b96SFilipe Manana 	 */
7531259c4b96SFilipe Manana 	if (ret < 0)
7532259c4b96SFilipe Manana 		btrfs_set_log_full_commit(trans);
75330f8ce498SFilipe Manana 	if (log_pinned)
7534259c4b96SFilipe Manana 		btrfs_end_log_trans(root);
7535259c4b96SFilipe Manana }
753612fcfd22SChris Mason 
7537