xref: /openbmc/linux/fs/btrfs/tree-log.c (revision 5caa490ed8f07488e47378999bd4ad451bf8858b)
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"
24e02119d5SChris Mason 
25e02119d5SChris Mason /* magic values for the inode_only field in btrfs_log_inode:
26e02119d5SChris Mason  *
27e02119d5SChris Mason  * LOG_INODE_ALL means to log everything
28e02119d5SChris Mason  * LOG_INODE_EXISTS means to log just enough to recreate the inode
29e02119d5SChris Mason  * during log replay
30e02119d5SChris Mason  */
31e13976cfSDavid Sterba enum {
32e13976cfSDavid Sterba 	LOG_INODE_ALL,
33e13976cfSDavid Sterba 	LOG_INODE_EXISTS,
34e13976cfSDavid Sterba 	LOG_OTHER_INODE,
35e13976cfSDavid Sterba 	LOG_OTHER_INODE_ALL,
36e13976cfSDavid Sterba };
37e02119d5SChris Mason 
38e02119d5SChris Mason /*
3912fcfd22SChris Mason  * directory trouble cases
4012fcfd22SChris Mason  *
4112fcfd22SChris Mason  * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
4212fcfd22SChris Mason  * log, we must force a full commit before doing an fsync of the directory
4312fcfd22SChris Mason  * where the unlink was done.
4412fcfd22SChris Mason  * ---> record transid of last unlink/rename per directory
4512fcfd22SChris Mason  *
4612fcfd22SChris Mason  * mkdir foo/some_dir
4712fcfd22SChris Mason  * normal commit
4812fcfd22SChris Mason  * rename foo/some_dir foo2/some_dir
4912fcfd22SChris Mason  * mkdir foo/some_dir
5012fcfd22SChris Mason  * fsync foo/some_dir/some_file
5112fcfd22SChris Mason  *
5212fcfd22SChris Mason  * The fsync above will unlink the original some_dir without recording
5312fcfd22SChris Mason  * it in its new location (foo2).  After a crash, some_dir will be gone
5412fcfd22SChris Mason  * unless the fsync of some_file forces a full commit
5512fcfd22SChris Mason  *
5612fcfd22SChris Mason  * 2) we must log any new names for any file or dir that is in the fsync
5712fcfd22SChris Mason  * log. ---> check inode while renaming/linking.
5812fcfd22SChris Mason  *
5912fcfd22SChris Mason  * 2a) we must log any new names for any file or dir during rename
6012fcfd22SChris Mason  * when the directory they are being removed from was logged.
6112fcfd22SChris Mason  * ---> check inode and old parent dir during rename
6212fcfd22SChris Mason  *
6312fcfd22SChris Mason  *  2a is actually the more important variant.  With the extra logging
6412fcfd22SChris Mason  *  a crash might unlink the old name without recreating the new one
6512fcfd22SChris Mason  *
6612fcfd22SChris Mason  * 3) after a crash, we must go through any directories with a link count
6712fcfd22SChris Mason  * of zero and redo the rm -rf
6812fcfd22SChris Mason  *
6912fcfd22SChris Mason  * mkdir f1/foo
7012fcfd22SChris Mason  * normal commit
7112fcfd22SChris Mason  * rm -rf f1/foo
7212fcfd22SChris Mason  * fsync(f1)
7312fcfd22SChris Mason  *
7412fcfd22SChris Mason  * The directory f1 was fully removed from the FS, but fsync was never
7512fcfd22SChris Mason  * called on f1, only its parent dir.  After a crash the rm -rf must
7612fcfd22SChris Mason  * be replayed.  This must be able to recurse down the entire
7712fcfd22SChris Mason  * directory tree.  The inode link count fixup code takes care of the
7812fcfd22SChris Mason  * ugly details.
7912fcfd22SChris Mason  */
8012fcfd22SChris Mason 
8112fcfd22SChris Mason /*
82e02119d5SChris Mason  * stages for the tree walking.  The first
83e02119d5SChris Mason  * stage (0) is to only pin down the blocks we find
84e02119d5SChris Mason  * the second stage (1) is to make sure that all the inodes
85e02119d5SChris Mason  * we find in the log are created in the subvolume.
86e02119d5SChris Mason  *
87e02119d5SChris Mason  * The last stage is to deal with directories and links and extents
88e02119d5SChris Mason  * and all the other fun semantics
89e02119d5SChris Mason  */
90e13976cfSDavid Sterba enum {
91e13976cfSDavid Sterba 	LOG_WALK_PIN_ONLY,
92e13976cfSDavid Sterba 	LOG_WALK_REPLAY_INODES,
93e13976cfSDavid Sterba 	LOG_WALK_REPLAY_DIR_INDEX,
94e13976cfSDavid Sterba 	LOG_WALK_REPLAY_ALL,
95e13976cfSDavid Sterba };
96e02119d5SChris Mason 
9712fcfd22SChris Mason static int btrfs_log_inode(struct btrfs_trans_handle *trans,
9890d04510SFilipe Manana 			   struct btrfs_inode *inode,
9949dae1bcSFilipe Manana 			   int inode_only,
1008407f553SFilipe Manana 			   struct btrfs_log_ctx *ctx);
101ec051c0fSYan Zheng static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
102ec051c0fSYan Zheng 			     struct btrfs_root *root,
103ec051c0fSYan Zheng 			     struct btrfs_path *path, u64 objectid);
10412fcfd22SChris Mason static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
10512fcfd22SChris Mason 				       struct btrfs_root *root,
10612fcfd22SChris Mason 				       struct btrfs_root *log,
10712fcfd22SChris Mason 				       struct btrfs_path *path,
10812fcfd22SChris Mason 				       u64 dirid, int del_all);
109fa1a0f42SNaohiro Aota static void wait_log_commit(struct btrfs_root *root, int transid);
110e02119d5SChris Mason 
111e02119d5SChris Mason /*
112e02119d5SChris Mason  * tree logging is a special write ahead log used to make sure that
113e02119d5SChris Mason  * fsyncs and O_SYNCs can happen without doing full tree commits.
114e02119d5SChris Mason  *
115e02119d5SChris Mason  * Full tree commits are expensive because they require commonly
116e02119d5SChris Mason  * modified blocks to be recowed, creating many dirty pages in the
117e02119d5SChris Mason  * extent tree an 4x-6x higher write load than ext3.
118e02119d5SChris Mason  *
119e02119d5SChris Mason  * Instead of doing a tree commit on every fsync, we use the
120e02119d5SChris Mason  * key ranges and transaction ids to find items for a given file or directory
121e02119d5SChris Mason  * that have changed in this transaction.  Those items are copied into
122e02119d5SChris Mason  * a special tree (one per subvolume root), that tree is written to disk
123e02119d5SChris Mason  * and then the fsync is considered complete.
124e02119d5SChris Mason  *
125e02119d5SChris Mason  * After a crash, items are copied out of the log-tree back into the
126e02119d5SChris Mason  * subvolume tree.  Any file data extents found are recorded in the extent
127e02119d5SChris Mason  * allocation tree, and the log-tree freed.
128e02119d5SChris Mason  *
129e02119d5SChris Mason  * The log tree is read three times, once to pin down all the extents it is
130e02119d5SChris Mason  * using in ram and once, once to create all the inodes logged in the tree
131e02119d5SChris Mason  * and once to do all the other items.
132e02119d5SChris Mason  */
133e02119d5SChris Mason 
134e02119d5SChris Mason /*
135e02119d5SChris Mason  * start a sub transaction and setup the log tree
136e02119d5SChris Mason  * this increments the log tree writer count to make the people
137e02119d5SChris Mason  * syncing the tree wait for us to finish
138e02119d5SChris Mason  */
139e02119d5SChris Mason static int start_log_trans(struct btrfs_trans_handle *trans,
1408b050d35SMiao Xie 			   struct btrfs_root *root,
1418b050d35SMiao Xie 			   struct btrfs_log_ctx *ctx)
142e02119d5SChris Mason {
1430b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
14447876f7cSFilipe Manana 	struct btrfs_root *tree_root = fs_info->tree_root;
145fa1a0f42SNaohiro Aota 	const bool zoned = btrfs_is_zoned(fs_info);
14634eb2a52SZhaolei 	int ret = 0;
147fa1a0f42SNaohiro Aota 	bool created = false;
1487237f183SYan Zheng 
14947876f7cSFilipe Manana 	/*
15047876f7cSFilipe Manana 	 * First check if the log root tree was already created. If not, create
15147876f7cSFilipe Manana 	 * it before locking the root's log_mutex, just to keep lockdep happy.
15247876f7cSFilipe Manana 	 */
15347876f7cSFilipe Manana 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
15447876f7cSFilipe Manana 		mutex_lock(&tree_root->log_mutex);
15547876f7cSFilipe Manana 		if (!fs_info->log_root_tree) {
15647876f7cSFilipe Manana 			ret = btrfs_init_log_root_tree(trans, fs_info);
157fa1a0f42SNaohiro Aota 			if (!ret) {
15847876f7cSFilipe Manana 				set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
159fa1a0f42SNaohiro Aota 				created = true;
160fa1a0f42SNaohiro Aota 			}
16147876f7cSFilipe Manana 		}
16247876f7cSFilipe Manana 		mutex_unlock(&tree_root->log_mutex);
16347876f7cSFilipe Manana 		if (ret)
16447876f7cSFilipe Manana 			return ret;
16547876f7cSFilipe Manana 	}
16647876f7cSFilipe Manana 
1677237f183SYan Zheng 	mutex_lock(&root->log_mutex);
16834eb2a52SZhaolei 
169fa1a0f42SNaohiro Aota again:
1707237f183SYan Zheng 	if (root->log_root) {
171fa1a0f42SNaohiro Aota 		int index = (root->log_transid + 1) % 2;
172fa1a0f42SNaohiro Aota 
1734884b8e8SDavid Sterba 		if (btrfs_need_log_full_commit(trans)) {
17450471a38SMiao Xie 			ret = -EAGAIN;
17550471a38SMiao Xie 			goto out;
17650471a38SMiao Xie 		}
17734eb2a52SZhaolei 
178fa1a0f42SNaohiro Aota 		if (zoned && atomic_read(&root->log_commit[index])) {
179fa1a0f42SNaohiro Aota 			wait_log_commit(root, root->log_transid - 1);
180fa1a0f42SNaohiro Aota 			goto again;
181fa1a0f42SNaohiro Aota 		}
182fa1a0f42SNaohiro Aota 
183ff782e0aSJosef Bacik 		if (!root->log_start_pid) {
18427cdeb70SMiao Xie 			clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
18534eb2a52SZhaolei 			root->log_start_pid = current->pid;
186ff782e0aSJosef Bacik 		} else if (root->log_start_pid != current->pid) {
18727cdeb70SMiao Xie 			set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
188ff782e0aSJosef Bacik 		}
18934eb2a52SZhaolei 	} else {
190fa1a0f42SNaohiro Aota 		/*
191fa1a0f42SNaohiro Aota 		 * This means fs_info->log_root_tree was already created
192fa1a0f42SNaohiro Aota 		 * for some other FS trees. Do the full commit not to mix
193fa1a0f42SNaohiro Aota 		 * nodes from multiple log transactions to do sequential
194fa1a0f42SNaohiro Aota 		 * writing.
195fa1a0f42SNaohiro Aota 		 */
196fa1a0f42SNaohiro Aota 		if (zoned && !created) {
197fa1a0f42SNaohiro Aota 			ret = -EAGAIN;
198fa1a0f42SNaohiro Aota 			goto out;
199fa1a0f42SNaohiro Aota 		}
200fa1a0f42SNaohiro Aota 
201e02119d5SChris Mason 		ret = btrfs_add_log_tree(trans, root);
2024a500fd1SYan, Zheng 		if (ret)
203e87ac136SMiao Xie 			goto out;
20434eb2a52SZhaolei 
205e7a79811SFilipe Manana 		set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
20627cdeb70SMiao Xie 		clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
207e87ac136SMiao Xie 		root->log_start_pid = current->pid;
20834eb2a52SZhaolei 	}
20934eb2a52SZhaolei 
2107237f183SYan Zheng 	atomic_inc(&root->log_writers);
211289cffcbSFilipe Manana 	if (!ctx->logging_new_name) {
21234eb2a52SZhaolei 		int index = root->log_transid % 2;
2138b050d35SMiao Xie 		list_add_tail(&ctx->list, &root->log_ctxs[index]);
214d1433debSMiao Xie 		ctx->log_transid = root->log_transid;
2158b050d35SMiao Xie 	}
21634eb2a52SZhaolei 
217e87ac136SMiao Xie out:
2187237f183SYan Zheng 	mutex_unlock(&root->log_mutex);
219e87ac136SMiao Xie 	return ret;
220e02119d5SChris Mason }
221e02119d5SChris Mason 
222e02119d5SChris Mason /*
223e02119d5SChris Mason  * returns 0 if there was a log transaction running and we were able
224e02119d5SChris Mason  * to join, or returns -ENOENT if there were not transactions
225e02119d5SChris Mason  * in progress
226e02119d5SChris Mason  */
227e02119d5SChris Mason static int join_running_log_trans(struct btrfs_root *root)
228e02119d5SChris Mason {
229fa1a0f42SNaohiro Aota 	const bool zoned = btrfs_is_zoned(root->fs_info);
230e02119d5SChris Mason 	int ret = -ENOENT;
231e02119d5SChris Mason 
232e7a79811SFilipe Manana 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
233e7a79811SFilipe Manana 		return ret;
234e7a79811SFilipe Manana 
2357237f183SYan Zheng 	mutex_lock(&root->log_mutex);
236fa1a0f42SNaohiro Aota again:
237e02119d5SChris Mason 	if (root->log_root) {
238fa1a0f42SNaohiro Aota 		int index = (root->log_transid + 1) % 2;
239fa1a0f42SNaohiro Aota 
240e02119d5SChris Mason 		ret = 0;
241fa1a0f42SNaohiro Aota 		if (zoned && atomic_read(&root->log_commit[index])) {
242fa1a0f42SNaohiro Aota 			wait_log_commit(root, root->log_transid - 1);
243fa1a0f42SNaohiro Aota 			goto again;
244fa1a0f42SNaohiro Aota 		}
2457237f183SYan Zheng 		atomic_inc(&root->log_writers);
246e02119d5SChris Mason 	}
2477237f183SYan Zheng 	mutex_unlock(&root->log_mutex);
248e02119d5SChris Mason 	return ret;
249e02119d5SChris Mason }
250e02119d5SChris Mason 
251e02119d5SChris Mason /*
25212fcfd22SChris Mason  * This either makes the current running log transaction wait
25312fcfd22SChris Mason  * until you call btrfs_end_log_trans() or it makes any future
25412fcfd22SChris Mason  * log transactions wait until you call btrfs_end_log_trans()
25512fcfd22SChris Mason  */
25645128b08Szhong jiang void btrfs_pin_log_trans(struct btrfs_root *root)
25712fcfd22SChris Mason {
25812fcfd22SChris Mason 	atomic_inc(&root->log_writers);
25912fcfd22SChris Mason }
26012fcfd22SChris Mason 
26112fcfd22SChris Mason /*
262e02119d5SChris Mason  * indicate we're done making changes to the log tree
263e02119d5SChris Mason  * and wake up anyone waiting to do a sync
264e02119d5SChris Mason  */
265143bede5SJeff Mahoney void btrfs_end_log_trans(struct btrfs_root *root)
266e02119d5SChris Mason {
2677237f183SYan Zheng 	if (atomic_dec_and_test(&root->log_writers)) {
268093258e6SDavid Sterba 		/* atomic_dec_and_test implies a barrier */
269093258e6SDavid Sterba 		cond_wake_up_nomb(&root->log_writer_wait);
2707237f183SYan Zheng 	}
271e02119d5SChris Mason }
272e02119d5SChris Mason 
273247462a5SDavid Sterba static int btrfs_write_tree_block(struct extent_buffer *buf)
274247462a5SDavid Sterba {
275247462a5SDavid Sterba 	return filemap_fdatawrite_range(buf->pages[0]->mapping, buf->start,
276247462a5SDavid Sterba 					buf->start + buf->len - 1);
277247462a5SDavid Sterba }
278247462a5SDavid Sterba 
279247462a5SDavid Sterba static void btrfs_wait_tree_block_writeback(struct extent_buffer *buf)
280247462a5SDavid Sterba {
281247462a5SDavid Sterba 	filemap_fdatawait_range(buf->pages[0]->mapping,
282247462a5SDavid Sterba 			        buf->start, buf->start + buf->len - 1);
283247462a5SDavid Sterba }
284e02119d5SChris Mason 
285e02119d5SChris Mason /*
286e02119d5SChris Mason  * the walk control struct is used to pass state down the chain when
287e02119d5SChris Mason  * processing the log tree.  The stage field tells us which part
288e02119d5SChris Mason  * of the log tree processing we are currently doing.  The others
289e02119d5SChris Mason  * are state fields used for that specific part
290e02119d5SChris Mason  */
291e02119d5SChris Mason struct walk_control {
292e02119d5SChris Mason 	/* should we free the extent on disk when done?  This is used
293e02119d5SChris Mason 	 * at transaction commit time while freeing a log tree
294e02119d5SChris Mason 	 */
295e02119d5SChris Mason 	int free;
296e02119d5SChris Mason 
297e02119d5SChris Mason 	/* should we write out the extent buffer?  This is used
298e02119d5SChris Mason 	 * while flushing the log tree to disk during a sync
299e02119d5SChris Mason 	 */
300e02119d5SChris Mason 	int write;
301e02119d5SChris Mason 
302e02119d5SChris Mason 	/* should we wait for the extent buffer io to finish?  Also used
303e02119d5SChris Mason 	 * while flushing the log tree to disk for a sync
304e02119d5SChris Mason 	 */
305e02119d5SChris Mason 	int wait;
306e02119d5SChris Mason 
307e02119d5SChris Mason 	/* pin only walk, we record which extents on disk belong to the
308e02119d5SChris Mason 	 * log trees
309e02119d5SChris Mason 	 */
310e02119d5SChris Mason 	int pin;
311e02119d5SChris Mason 
312e02119d5SChris Mason 	/* what stage of the replay code we're currently in */
313e02119d5SChris Mason 	int stage;
314e02119d5SChris Mason 
315f2d72f42SFilipe Manana 	/*
316f2d72f42SFilipe Manana 	 * Ignore any items from the inode currently being processed. Needs
317f2d72f42SFilipe Manana 	 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
318f2d72f42SFilipe Manana 	 * the LOG_WALK_REPLAY_INODES stage.
319f2d72f42SFilipe Manana 	 */
320f2d72f42SFilipe Manana 	bool ignore_cur_inode;
321f2d72f42SFilipe Manana 
322e02119d5SChris Mason 	/* the root we are currently replaying */
323e02119d5SChris Mason 	struct btrfs_root *replay_dest;
324e02119d5SChris Mason 
325e02119d5SChris Mason 	/* the trans handle for the current replay */
326e02119d5SChris Mason 	struct btrfs_trans_handle *trans;
327e02119d5SChris Mason 
328e02119d5SChris Mason 	/* the function that gets used to process blocks we find in the
329e02119d5SChris Mason 	 * tree.  Note the extent_buffer might not be up to date when it is
330e02119d5SChris Mason 	 * passed in, and it must be checked or read if you need the data
331e02119d5SChris Mason 	 * inside it
332e02119d5SChris Mason 	 */
333e02119d5SChris Mason 	int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
334581c1760SQu Wenruo 			    struct walk_control *wc, u64 gen, int level);
335e02119d5SChris Mason };
336e02119d5SChris Mason 
337e02119d5SChris Mason /*
338e02119d5SChris Mason  * process_func used to pin down extents, write them or wait on them
339e02119d5SChris Mason  */
340e02119d5SChris Mason static int process_one_buffer(struct btrfs_root *log,
341e02119d5SChris Mason 			      struct extent_buffer *eb,
342581c1760SQu Wenruo 			      struct walk_control *wc, u64 gen, int level)
343e02119d5SChris Mason {
3440b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = log->fs_info;
345b50c6e25SJosef Bacik 	int ret = 0;
346b50c6e25SJosef Bacik 
3478c2a1a30SJosef Bacik 	/*
3488c2a1a30SJosef Bacik 	 * If this fs is mixed then we need to be able to process the leaves to
3498c2a1a30SJosef Bacik 	 * pin down any logged extents, so we have to read the block.
3508c2a1a30SJosef Bacik 	 */
3510b246afaSJeff Mahoney 	if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
352581c1760SQu Wenruo 		ret = btrfs_read_buffer(eb, gen, level, NULL);
3538c2a1a30SJosef Bacik 		if (ret)
3548c2a1a30SJosef Bacik 			return ret;
3558c2a1a30SJosef Bacik 	}
3568c2a1a30SJosef Bacik 
35704018de5SJosef Bacik 	if (wc->pin)
3589fce5704SNikolay Borisov 		ret = btrfs_pin_extent_for_log_replay(wc->trans, eb->start,
3592ff7e61eSJeff Mahoney 						      eb->len);
360e02119d5SChris Mason 
361b50c6e25SJosef Bacik 	if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
3628c2a1a30SJosef Bacik 		if (wc->pin && btrfs_header_level(eb) == 0)
363bcdc428cSDavid Sterba 			ret = btrfs_exclude_logged_extents(eb);
364e02119d5SChris Mason 		if (wc->write)
365e02119d5SChris Mason 			btrfs_write_tree_block(eb);
366e02119d5SChris Mason 		if (wc->wait)
367e02119d5SChris Mason 			btrfs_wait_tree_block_writeback(eb);
368e02119d5SChris Mason 	}
369b50c6e25SJosef Bacik 	return ret;
370e02119d5SChris Mason }
371e02119d5SChris Mason 
372086dcbfaSFilipe Manana static int do_overwrite_item(struct btrfs_trans_handle *trans,
373e02119d5SChris Mason 			     struct btrfs_root *root,
374e02119d5SChris Mason 			     struct btrfs_path *path,
375e02119d5SChris Mason 			     struct extent_buffer *eb, int slot,
376e02119d5SChris Mason 			     struct btrfs_key *key)
377e02119d5SChris Mason {
378e02119d5SChris Mason 	int ret;
379e02119d5SChris Mason 	u32 item_size;
380e02119d5SChris Mason 	u64 saved_i_size = 0;
381e02119d5SChris Mason 	int save_old_i_size = 0;
382e02119d5SChris Mason 	unsigned long src_ptr;
383e02119d5SChris Mason 	unsigned long dst_ptr;
384e02119d5SChris Mason 	int overwrite_root = 0;
3854bc4bee4SJosef Bacik 	bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
386e02119d5SChris Mason 
387e02119d5SChris Mason 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
388e02119d5SChris Mason 		overwrite_root = 1;
389e02119d5SChris Mason 
3903212fa14SJosef Bacik 	item_size = btrfs_item_size(eb, slot);
391e02119d5SChris Mason 	src_ptr = btrfs_item_ptr_offset(eb, slot);
392e02119d5SChris Mason 
393086dcbfaSFilipe Manana 	/* Our caller must have done a search for the key for us. */
394086dcbfaSFilipe Manana 	ASSERT(path->nodes[0] != NULL);
395086dcbfaSFilipe Manana 
396086dcbfaSFilipe Manana 	/*
397086dcbfaSFilipe Manana 	 * And the slot must point to the exact key or the slot where the key
398086dcbfaSFilipe Manana 	 * should be at (the first item with a key greater than 'key')
399086dcbfaSFilipe Manana 	 */
400086dcbfaSFilipe Manana 	if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
401086dcbfaSFilipe Manana 		struct btrfs_key found_key;
402086dcbfaSFilipe Manana 
403086dcbfaSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
404086dcbfaSFilipe Manana 		ret = btrfs_comp_cpu_keys(&found_key, key);
405086dcbfaSFilipe Manana 		ASSERT(ret >= 0);
406086dcbfaSFilipe Manana 	} else {
407086dcbfaSFilipe Manana 		ret = 1;
408086dcbfaSFilipe Manana 	}
4094bc4bee4SJosef Bacik 
410e02119d5SChris Mason 	if (ret == 0) {
411e02119d5SChris Mason 		char *src_copy;
412e02119d5SChris Mason 		char *dst_copy;
4133212fa14SJosef Bacik 		u32 dst_size = btrfs_item_size(path->nodes[0],
414e02119d5SChris Mason 						  path->slots[0]);
415e02119d5SChris Mason 		if (dst_size != item_size)
416e02119d5SChris Mason 			goto insert;
417e02119d5SChris Mason 
418e02119d5SChris Mason 		if (item_size == 0) {
419b3b4aa74SDavid Sterba 			btrfs_release_path(path);
420e02119d5SChris Mason 			return 0;
421e02119d5SChris Mason 		}
422e02119d5SChris Mason 		dst_copy = kmalloc(item_size, GFP_NOFS);
423e02119d5SChris Mason 		src_copy = kmalloc(item_size, GFP_NOFS);
4242a29edc6Sliubo 		if (!dst_copy || !src_copy) {
425b3b4aa74SDavid Sterba 			btrfs_release_path(path);
4262a29edc6Sliubo 			kfree(dst_copy);
4272a29edc6Sliubo 			kfree(src_copy);
4282a29edc6Sliubo 			return -ENOMEM;
4292a29edc6Sliubo 		}
430e02119d5SChris Mason 
431e02119d5SChris Mason 		read_extent_buffer(eb, src_copy, src_ptr, item_size);
432e02119d5SChris Mason 
433e02119d5SChris Mason 		dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
434e02119d5SChris Mason 		read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
435e02119d5SChris Mason 				   item_size);
436e02119d5SChris Mason 		ret = memcmp(dst_copy, src_copy, item_size);
437e02119d5SChris Mason 
438e02119d5SChris Mason 		kfree(dst_copy);
439e02119d5SChris Mason 		kfree(src_copy);
440e02119d5SChris Mason 		/*
441e02119d5SChris Mason 		 * they have the same contents, just return, this saves
442e02119d5SChris Mason 		 * us from cowing blocks in the destination tree and doing
443e02119d5SChris Mason 		 * extra writes that may not have been done by a previous
444e02119d5SChris Mason 		 * sync
445e02119d5SChris Mason 		 */
446e02119d5SChris Mason 		if (ret == 0) {
447b3b4aa74SDavid Sterba 			btrfs_release_path(path);
448e02119d5SChris Mason 			return 0;
449e02119d5SChris Mason 		}
450e02119d5SChris Mason 
4514bc4bee4SJosef Bacik 		/*
4524bc4bee4SJosef Bacik 		 * We need to load the old nbytes into the inode so when we
4534bc4bee4SJosef Bacik 		 * replay the extents we've logged we get the right nbytes.
4544bc4bee4SJosef Bacik 		 */
4554bc4bee4SJosef Bacik 		if (inode_item) {
4564bc4bee4SJosef Bacik 			struct btrfs_inode_item *item;
4574bc4bee4SJosef Bacik 			u64 nbytes;
458d555438bSJosef Bacik 			u32 mode;
4594bc4bee4SJosef Bacik 
4604bc4bee4SJosef Bacik 			item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4614bc4bee4SJosef Bacik 					      struct btrfs_inode_item);
4624bc4bee4SJosef Bacik 			nbytes = btrfs_inode_nbytes(path->nodes[0], item);
4634bc4bee4SJosef Bacik 			item = btrfs_item_ptr(eb, slot,
4644bc4bee4SJosef Bacik 					      struct btrfs_inode_item);
4654bc4bee4SJosef Bacik 			btrfs_set_inode_nbytes(eb, item, nbytes);
466d555438bSJosef Bacik 
467d555438bSJosef Bacik 			/*
468d555438bSJosef Bacik 			 * If this is a directory we need to reset the i_size to
469d555438bSJosef Bacik 			 * 0 so that we can set it up properly when replaying
470d555438bSJosef Bacik 			 * the rest of the items in this log.
471d555438bSJosef Bacik 			 */
472d555438bSJosef Bacik 			mode = btrfs_inode_mode(eb, item);
473d555438bSJosef Bacik 			if (S_ISDIR(mode))
474d555438bSJosef Bacik 				btrfs_set_inode_size(eb, item, 0);
4754bc4bee4SJosef Bacik 		}
4764bc4bee4SJosef Bacik 	} else if (inode_item) {
4774bc4bee4SJosef Bacik 		struct btrfs_inode_item *item;
478d555438bSJosef Bacik 		u32 mode;
4794bc4bee4SJosef Bacik 
4804bc4bee4SJosef Bacik 		/*
4814bc4bee4SJosef Bacik 		 * New inode, set nbytes to 0 so that the nbytes comes out
4824bc4bee4SJosef Bacik 		 * properly when we replay the extents.
4834bc4bee4SJosef Bacik 		 */
4844bc4bee4SJosef Bacik 		item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
4854bc4bee4SJosef Bacik 		btrfs_set_inode_nbytes(eb, item, 0);
486d555438bSJosef Bacik 
487d555438bSJosef Bacik 		/*
488d555438bSJosef Bacik 		 * If this is a directory we need to reset the i_size to 0 so
489d555438bSJosef Bacik 		 * that we can set it up properly when replaying the rest of
490d555438bSJosef Bacik 		 * the items in this log.
491d555438bSJosef Bacik 		 */
492d555438bSJosef Bacik 		mode = btrfs_inode_mode(eb, item);
493d555438bSJosef Bacik 		if (S_ISDIR(mode))
494d555438bSJosef Bacik 			btrfs_set_inode_size(eb, item, 0);
495e02119d5SChris Mason 	}
496e02119d5SChris Mason insert:
497b3b4aa74SDavid Sterba 	btrfs_release_path(path);
498e02119d5SChris Mason 	/* try to insert the key into the destination tree */
499df8d116fSFilipe Manana 	path->skip_release_on_error = 1;
500e02119d5SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path,
501e02119d5SChris Mason 				      key, item_size);
502df8d116fSFilipe Manana 	path->skip_release_on_error = 0;
503e02119d5SChris Mason 
504e02119d5SChris Mason 	/* make sure any existing item is the correct size */
505df8d116fSFilipe Manana 	if (ret == -EEXIST || ret == -EOVERFLOW) {
506e02119d5SChris Mason 		u32 found_size;
5073212fa14SJosef Bacik 		found_size = btrfs_item_size(path->nodes[0],
508e02119d5SChris Mason 						path->slots[0]);
509143bede5SJeff Mahoney 		if (found_size > item_size)
51078ac4f9eSDavid Sterba 			btrfs_truncate_item(path, item_size, 1);
511143bede5SJeff Mahoney 		else if (found_size < item_size)
512c71dd880SDavid Sterba 			btrfs_extend_item(path, item_size - found_size);
513e02119d5SChris Mason 	} else if (ret) {
5144a500fd1SYan, Zheng 		return ret;
515e02119d5SChris Mason 	}
516e02119d5SChris Mason 	dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
517e02119d5SChris Mason 					path->slots[0]);
518e02119d5SChris Mason 
519e02119d5SChris Mason 	/* don't overwrite an existing inode if the generation number
520e02119d5SChris Mason 	 * was logged as zero.  This is done when the tree logging code
521e02119d5SChris Mason 	 * is just logging an inode to make sure it exists after recovery.
522e02119d5SChris Mason 	 *
523e02119d5SChris Mason 	 * Also, don't overwrite i_size on directories during replay.
524e02119d5SChris Mason 	 * log replay inserts and removes directory items based on the
525e02119d5SChris Mason 	 * state of the tree found in the subvolume, and i_size is modified
526e02119d5SChris Mason 	 * as it goes
527e02119d5SChris Mason 	 */
528e02119d5SChris Mason 	if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
529e02119d5SChris Mason 		struct btrfs_inode_item *src_item;
530e02119d5SChris Mason 		struct btrfs_inode_item *dst_item;
531e02119d5SChris Mason 
532e02119d5SChris Mason 		src_item = (struct btrfs_inode_item *)src_ptr;
533e02119d5SChris Mason 		dst_item = (struct btrfs_inode_item *)dst_ptr;
534e02119d5SChris Mason 
5351a4bcf47SFilipe Manana 		if (btrfs_inode_generation(eb, src_item) == 0) {
5361a4bcf47SFilipe Manana 			struct extent_buffer *dst_eb = path->nodes[0];
5372f2ff0eeSFilipe Manana 			const u64 ino_size = btrfs_inode_size(eb, src_item);
5381a4bcf47SFilipe Manana 
5392f2ff0eeSFilipe Manana 			/*
5402f2ff0eeSFilipe Manana 			 * For regular files an ino_size == 0 is used only when
5412f2ff0eeSFilipe Manana 			 * logging that an inode exists, as part of a directory
5422f2ff0eeSFilipe Manana 			 * fsync, and the inode wasn't fsynced before. In this
5432f2ff0eeSFilipe Manana 			 * case don't set the size of the inode in the fs/subvol
5442f2ff0eeSFilipe Manana 			 * tree, otherwise we would be throwing valid data away.
5452f2ff0eeSFilipe Manana 			 */
5461a4bcf47SFilipe Manana 			if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
5472f2ff0eeSFilipe Manana 			    S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
54860d48e2eSDavid Sterba 			    ino_size != 0)
54960d48e2eSDavid Sterba 				btrfs_set_inode_size(dst_eb, dst_item, ino_size);
550e02119d5SChris Mason 			goto no_copy;
5511a4bcf47SFilipe Manana 		}
552e02119d5SChris Mason 
553e02119d5SChris Mason 		if (overwrite_root &&
554e02119d5SChris Mason 		    S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
555e02119d5SChris Mason 		    S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
556e02119d5SChris Mason 			save_old_i_size = 1;
557e02119d5SChris Mason 			saved_i_size = btrfs_inode_size(path->nodes[0],
558e02119d5SChris Mason 							dst_item);
559e02119d5SChris Mason 		}
560e02119d5SChris Mason 	}
561e02119d5SChris Mason 
562e02119d5SChris Mason 	copy_extent_buffer(path->nodes[0], eb, dst_ptr,
563e02119d5SChris Mason 			   src_ptr, item_size);
564e02119d5SChris Mason 
565e02119d5SChris Mason 	if (save_old_i_size) {
566e02119d5SChris Mason 		struct btrfs_inode_item *dst_item;
567e02119d5SChris Mason 		dst_item = (struct btrfs_inode_item *)dst_ptr;
568e02119d5SChris Mason 		btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
569e02119d5SChris Mason 	}
570e02119d5SChris Mason 
571e02119d5SChris Mason 	/* make sure the generation is filled in */
572e02119d5SChris Mason 	if (key->type == BTRFS_INODE_ITEM_KEY) {
573e02119d5SChris Mason 		struct btrfs_inode_item *dst_item;
574e02119d5SChris Mason 		dst_item = (struct btrfs_inode_item *)dst_ptr;
575e02119d5SChris Mason 		if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
576e02119d5SChris Mason 			btrfs_set_inode_generation(path->nodes[0], dst_item,
577e02119d5SChris Mason 						   trans->transid);
578e02119d5SChris Mason 		}
579e02119d5SChris Mason 	}
580e02119d5SChris Mason no_copy:
581e02119d5SChris Mason 	btrfs_mark_buffer_dirty(path->nodes[0]);
582b3b4aa74SDavid Sterba 	btrfs_release_path(path);
583e02119d5SChris Mason 	return 0;
584e02119d5SChris Mason }
585e02119d5SChris Mason 
586e02119d5SChris Mason /*
587086dcbfaSFilipe Manana  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
588086dcbfaSFilipe Manana  * to the src data we are copying out.
589086dcbfaSFilipe Manana  *
590086dcbfaSFilipe Manana  * root is the tree we are copying into, and path is a scratch
591086dcbfaSFilipe Manana  * path for use in this function (it should be released on entry and
592086dcbfaSFilipe Manana  * will be released on exit).
593086dcbfaSFilipe Manana  *
594086dcbfaSFilipe Manana  * If the key is already in the destination tree the existing item is
595086dcbfaSFilipe Manana  * overwritten.  If the existing item isn't big enough, it is extended.
596086dcbfaSFilipe Manana  * If it is too large, it is truncated.
597086dcbfaSFilipe Manana  *
598086dcbfaSFilipe Manana  * If the key isn't in the destination yet, a new item is inserted.
599086dcbfaSFilipe Manana  */
600086dcbfaSFilipe Manana static int overwrite_item(struct btrfs_trans_handle *trans,
601086dcbfaSFilipe Manana 			  struct btrfs_root *root,
602086dcbfaSFilipe Manana 			  struct btrfs_path *path,
603086dcbfaSFilipe Manana 			  struct extent_buffer *eb, int slot,
604086dcbfaSFilipe Manana 			  struct btrfs_key *key)
605086dcbfaSFilipe Manana {
606086dcbfaSFilipe Manana 	int ret;
607086dcbfaSFilipe Manana 
608086dcbfaSFilipe Manana 	/* Look for the key in the destination tree. */
609086dcbfaSFilipe Manana 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
610086dcbfaSFilipe Manana 	if (ret < 0)
611086dcbfaSFilipe Manana 		return ret;
612086dcbfaSFilipe Manana 
613086dcbfaSFilipe Manana 	return do_overwrite_item(trans, root, path, eb, slot, key);
614086dcbfaSFilipe Manana }
615086dcbfaSFilipe Manana 
616086dcbfaSFilipe Manana /*
617e02119d5SChris Mason  * simple helper to read an inode off the disk from a given root
618e02119d5SChris Mason  * This can only be called for subvolume roots and not for the log
619e02119d5SChris Mason  */
620e02119d5SChris Mason static noinline struct inode *read_one_inode(struct btrfs_root *root,
621e02119d5SChris Mason 					     u64 objectid)
622e02119d5SChris Mason {
623e02119d5SChris Mason 	struct inode *inode;
624e02119d5SChris Mason 
6250202e83fSDavid Sterba 	inode = btrfs_iget(root->fs_info->sb, objectid, root);
6262e19f1f9SAl Viro 	if (IS_ERR(inode))
6275d4f98a2SYan Zheng 		inode = NULL;
628e02119d5SChris Mason 	return inode;
629e02119d5SChris Mason }
630e02119d5SChris Mason 
631e02119d5SChris Mason /* replays a single extent in 'eb' at 'slot' with 'key' into the
632e02119d5SChris Mason  * subvolume 'root'.  path is released on entry and should be released
633e02119d5SChris Mason  * on exit.
634e02119d5SChris Mason  *
635e02119d5SChris Mason  * extents in the log tree have not been allocated out of the extent
636e02119d5SChris Mason  * tree yet.  So, this completes the allocation, taking a reference
637e02119d5SChris Mason  * as required if the extent already exists or creating a new extent
638e02119d5SChris Mason  * if it isn't in the extent allocation tree yet.
639e02119d5SChris Mason  *
640e02119d5SChris Mason  * The extent is inserted into the file, dropping any existing extents
641e02119d5SChris Mason  * from the file that overlap the new one.
642e02119d5SChris Mason  */
643e02119d5SChris Mason static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
644e02119d5SChris Mason 				      struct btrfs_root *root,
645e02119d5SChris Mason 				      struct btrfs_path *path,
646e02119d5SChris Mason 				      struct extent_buffer *eb, int slot,
647e02119d5SChris Mason 				      struct btrfs_key *key)
648e02119d5SChris Mason {
6495893dfb9SFilipe Manana 	struct btrfs_drop_extents_args drop_args = { 0 };
6500b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
651e02119d5SChris Mason 	int found_type;
652e02119d5SChris Mason 	u64 extent_end;
653e02119d5SChris Mason 	u64 start = key->offset;
6544bc4bee4SJosef Bacik 	u64 nbytes = 0;
655e02119d5SChris Mason 	struct btrfs_file_extent_item *item;
656e02119d5SChris Mason 	struct inode *inode = NULL;
657e02119d5SChris Mason 	unsigned long size;
658e02119d5SChris Mason 	int ret = 0;
659e02119d5SChris Mason 
660e02119d5SChris Mason 	item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
661e02119d5SChris Mason 	found_type = btrfs_file_extent_type(eb, item);
662e02119d5SChris Mason 
663d899e052SYan Zheng 	if (found_type == BTRFS_FILE_EXTENT_REG ||
6644bc4bee4SJosef Bacik 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6654bc4bee4SJosef Bacik 		nbytes = btrfs_file_extent_num_bytes(eb, item);
6664bc4bee4SJosef Bacik 		extent_end = start + nbytes;
6674bc4bee4SJosef Bacik 
6684bc4bee4SJosef Bacik 		/*
6694bc4bee4SJosef Bacik 		 * We don't add to the inodes nbytes if we are prealloc or a
6704bc4bee4SJosef Bacik 		 * hole.
6714bc4bee4SJosef Bacik 		 */
6724bc4bee4SJosef Bacik 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6734bc4bee4SJosef Bacik 			nbytes = 0;
6744bc4bee4SJosef Bacik 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
675e41ca589SQu Wenruo 		size = btrfs_file_extent_ram_bytes(eb, item);
6764bc4bee4SJosef Bacik 		nbytes = btrfs_file_extent_ram_bytes(eb, item);
677da17066cSJeff Mahoney 		extent_end = ALIGN(start + size,
6780b246afaSJeff Mahoney 				   fs_info->sectorsize);
679e02119d5SChris Mason 	} else {
680e02119d5SChris Mason 		ret = 0;
681e02119d5SChris Mason 		goto out;
682e02119d5SChris Mason 	}
683e02119d5SChris Mason 
684e02119d5SChris Mason 	inode = read_one_inode(root, key->objectid);
685e02119d5SChris Mason 	if (!inode) {
686e02119d5SChris Mason 		ret = -EIO;
687e02119d5SChris Mason 		goto out;
688e02119d5SChris Mason 	}
689e02119d5SChris Mason 
690e02119d5SChris Mason 	/*
691e02119d5SChris Mason 	 * first check to see if we already have this extent in the
692e02119d5SChris Mason 	 * file.  This must be done before the btrfs_drop_extents run
693e02119d5SChris Mason 	 * so we don't try to drop this extent.
694e02119d5SChris Mason 	 */
695f85b7379SDavid Sterba 	ret = btrfs_lookup_file_extent(trans, root, path,
696f85b7379SDavid Sterba 			btrfs_ino(BTRFS_I(inode)), start, 0);
697e02119d5SChris Mason 
698d899e052SYan Zheng 	if (ret == 0 &&
699d899e052SYan Zheng 	    (found_type == BTRFS_FILE_EXTENT_REG ||
700d899e052SYan Zheng 	     found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
701e02119d5SChris Mason 		struct btrfs_file_extent_item cmp1;
702e02119d5SChris Mason 		struct btrfs_file_extent_item cmp2;
703e02119d5SChris Mason 		struct btrfs_file_extent_item *existing;
704e02119d5SChris Mason 		struct extent_buffer *leaf;
705e02119d5SChris Mason 
706e02119d5SChris Mason 		leaf = path->nodes[0];
707e02119d5SChris Mason 		existing = btrfs_item_ptr(leaf, path->slots[0],
708e02119d5SChris Mason 					  struct btrfs_file_extent_item);
709e02119d5SChris Mason 
710e02119d5SChris Mason 		read_extent_buffer(eb, &cmp1, (unsigned long)item,
711e02119d5SChris Mason 				   sizeof(cmp1));
712e02119d5SChris Mason 		read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
713e02119d5SChris Mason 				   sizeof(cmp2));
714e02119d5SChris Mason 
715e02119d5SChris Mason 		/*
716e02119d5SChris Mason 		 * we already have a pointer to this exact extent,
717e02119d5SChris Mason 		 * we don't have to do anything
718e02119d5SChris Mason 		 */
719e02119d5SChris Mason 		if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
720b3b4aa74SDavid Sterba 			btrfs_release_path(path);
721e02119d5SChris Mason 			goto out;
722e02119d5SChris Mason 		}
723e02119d5SChris Mason 	}
724b3b4aa74SDavid Sterba 	btrfs_release_path(path);
725e02119d5SChris Mason 
726e02119d5SChris Mason 	/* drop any overlapping extents */
7275893dfb9SFilipe Manana 	drop_args.start = start;
7285893dfb9SFilipe Manana 	drop_args.end = extent_end;
7295893dfb9SFilipe Manana 	drop_args.drop_cache = true;
7305893dfb9SFilipe Manana 	ret = btrfs_drop_extents(trans, root, BTRFS_I(inode), &drop_args);
7313650860bSJosef Bacik 	if (ret)
7323650860bSJosef Bacik 		goto out;
733e02119d5SChris Mason 
73407d400a6SYan Zheng 	if (found_type == BTRFS_FILE_EXTENT_REG ||
73507d400a6SYan Zheng 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7365d4f98a2SYan Zheng 		u64 offset;
73707d400a6SYan Zheng 		unsigned long dest_offset;
73807d400a6SYan Zheng 		struct btrfs_key ins;
73907d400a6SYan Zheng 
7403168021cSFilipe Manana 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
7413168021cSFilipe Manana 		    btrfs_fs_incompat(fs_info, NO_HOLES))
7423168021cSFilipe Manana 			goto update_inode;
7433168021cSFilipe Manana 
74407d400a6SYan Zheng 		ret = btrfs_insert_empty_item(trans, root, path, key,
74507d400a6SYan Zheng 					      sizeof(*item));
7463650860bSJosef Bacik 		if (ret)
7473650860bSJosef Bacik 			goto out;
74807d400a6SYan Zheng 		dest_offset = btrfs_item_ptr_offset(path->nodes[0],
74907d400a6SYan Zheng 						    path->slots[0]);
75007d400a6SYan Zheng 		copy_extent_buffer(path->nodes[0], eb, dest_offset,
75107d400a6SYan Zheng 				(unsigned long)item,  sizeof(*item));
75207d400a6SYan Zheng 
75307d400a6SYan Zheng 		ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
75407d400a6SYan Zheng 		ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
75507d400a6SYan Zheng 		ins.type = BTRFS_EXTENT_ITEM_KEY;
7565d4f98a2SYan Zheng 		offset = key->offset - btrfs_file_extent_offset(eb, item);
75707d400a6SYan Zheng 
758df2c95f3SQu Wenruo 		/*
759df2c95f3SQu Wenruo 		 * Manually record dirty extent, as here we did a shallow
760df2c95f3SQu Wenruo 		 * file extent item copy and skip normal backref update,
761df2c95f3SQu Wenruo 		 * but modifying extent tree all by ourselves.
762df2c95f3SQu Wenruo 		 * So need to manually record dirty extent for qgroup,
763df2c95f3SQu Wenruo 		 * as the owner of the file extent changed from log tree
764df2c95f3SQu Wenruo 		 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
765df2c95f3SQu Wenruo 		 */
766a95f3aafSLu Fengqi 		ret = btrfs_qgroup_trace_extent(trans,
767df2c95f3SQu Wenruo 				btrfs_file_extent_disk_bytenr(eb, item),
768df2c95f3SQu Wenruo 				btrfs_file_extent_disk_num_bytes(eb, item),
769df2c95f3SQu Wenruo 				GFP_NOFS);
770df2c95f3SQu Wenruo 		if (ret < 0)
771df2c95f3SQu Wenruo 			goto out;
772df2c95f3SQu Wenruo 
77307d400a6SYan Zheng 		if (ins.objectid > 0) {
77482fa113fSQu Wenruo 			struct btrfs_ref ref = { 0 };
77507d400a6SYan Zheng 			u64 csum_start;
77607d400a6SYan Zheng 			u64 csum_end;
77707d400a6SYan Zheng 			LIST_HEAD(ordered_sums);
77882fa113fSQu Wenruo 
77907d400a6SYan Zheng 			/*
78007d400a6SYan Zheng 			 * is this extent already allocated in the extent
78107d400a6SYan Zheng 			 * allocation tree?  If so, just add a reference
78207d400a6SYan Zheng 			 */
7832ff7e61eSJeff Mahoney 			ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
78407d400a6SYan Zheng 						ins.offset);
7853736127aSMarcos Paulo de Souza 			if (ret < 0) {
7863736127aSMarcos Paulo de Souza 				goto out;
7873736127aSMarcos Paulo de Souza 			} else if (ret == 0) {
78882fa113fSQu Wenruo 				btrfs_init_generic_ref(&ref,
78982fa113fSQu Wenruo 						BTRFS_ADD_DELAYED_REF,
79082fa113fSQu Wenruo 						ins.objectid, ins.offset, 0);
79182fa113fSQu Wenruo 				btrfs_init_data_ref(&ref,
79282fa113fSQu Wenruo 						root->root_key.objectid,
793f42c5da6SNikolay Borisov 						key->objectid, offset, 0, false);
79482fa113fSQu Wenruo 				ret = btrfs_inc_extent_ref(trans, &ref);
795b50c6e25SJosef Bacik 				if (ret)
796b50c6e25SJosef Bacik 					goto out;
79707d400a6SYan Zheng 			} else {
79807d400a6SYan Zheng 				/*
79907d400a6SYan Zheng 				 * insert the extent pointer in the extent
80007d400a6SYan Zheng 				 * allocation tree
80107d400a6SYan Zheng 				 */
8025d4f98a2SYan Zheng 				ret = btrfs_alloc_logged_file_extent(trans,
8032ff7e61eSJeff Mahoney 						root->root_key.objectid,
8045d4f98a2SYan Zheng 						key->objectid, offset, &ins);
805b50c6e25SJosef Bacik 				if (ret)
806b50c6e25SJosef Bacik 					goto out;
80707d400a6SYan Zheng 			}
808b3b4aa74SDavid Sterba 			btrfs_release_path(path);
80907d400a6SYan Zheng 
81007d400a6SYan Zheng 			if (btrfs_file_extent_compression(eb, item)) {
81107d400a6SYan Zheng 				csum_start = ins.objectid;
81207d400a6SYan Zheng 				csum_end = csum_start + ins.offset;
81307d400a6SYan Zheng 			} else {
81407d400a6SYan Zheng 				csum_start = ins.objectid +
81507d400a6SYan Zheng 					btrfs_file_extent_offset(eb, item);
81607d400a6SYan Zheng 				csum_end = csum_start +
81707d400a6SYan Zheng 					btrfs_file_extent_num_bytes(eb, item);
81807d400a6SYan Zheng 			}
81907d400a6SYan Zheng 
82007d400a6SYan Zheng 			ret = btrfs_lookup_csums_range(root->log_root,
82107d400a6SYan Zheng 						csum_start, csum_end - 1,
822a2de733cSArne Jansen 						&ordered_sums, 0);
8233650860bSJosef Bacik 			if (ret)
8243650860bSJosef Bacik 				goto out;
825b84b8390SFilipe Manana 			/*
826b84b8390SFilipe Manana 			 * Now delete all existing cums in the csum root that
827b84b8390SFilipe Manana 			 * cover our range. We do this because we can have an
828b84b8390SFilipe Manana 			 * extent that is completely referenced by one file
829b84b8390SFilipe Manana 			 * extent item and partially referenced by another
830b84b8390SFilipe Manana 			 * file extent item (like after using the clone or
831b84b8390SFilipe Manana 			 * extent_same ioctls). In this case if we end up doing
832b84b8390SFilipe Manana 			 * the replay of the one that partially references the
833b84b8390SFilipe Manana 			 * extent first, and we do not do the csum deletion
834b84b8390SFilipe Manana 			 * below, we can get 2 csum items in the csum tree that
835b84b8390SFilipe Manana 			 * overlap each other. For example, imagine our log has
836b84b8390SFilipe Manana 			 * the two following file extent items:
837b84b8390SFilipe Manana 			 *
838b84b8390SFilipe Manana 			 * key (257 EXTENT_DATA 409600)
839b84b8390SFilipe Manana 			 *     extent data disk byte 12845056 nr 102400
840b84b8390SFilipe Manana 			 *     extent data offset 20480 nr 20480 ram 102400
841b84b8390SFilipe Manana 			 *
842b84b8390SFilipe Manana 			 * key (257 EXTENT_DATA 819200)
843b84b8390SFilipe Manana 			 *     extent data disk byte 12845056 nr 102400
844b84b8390SFilipe Manana 			 *     extent data offset 0 nr 102400 ram 102400
845b84b8390SFilipe Manana 			 *
846b84b8390SFilipe Manana 			 * Where the second one fully references the 100K extent
847b84b8390SFilipe Manana 			 * that starts at disk byte 12845056, and the log tree
848b84b8390SFilipe Manana 			 * has a single csum item that covers the entire range
849b84b8390SFilipe Manana 			 * of the extent:
850b84b8390SFilipe Manana 			 *
851b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
852b84b8390SFilipe Manana 			 *
853b84b8390SFilipe Manana 			 * After the first file extent item is replayed, the
854b84b8390SFilipe Manana 			 * csum tree gets the following csum item:
855b84b8390SFilipe Manana 			 *
856b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
857b84b8390SFilipe Manana 			 *
858b84b8390SFilipe Manana 			 * Which covers the 20K sub-range starting at offset 20K
859b84b8390SFilipe Manana 			 * of our extent. Now when we replay the second file
860b84b8390SFilipe Manana 			 * extent item, if we do not delete existing csum items
861b84b8390SFilipe Manana 			 * that cover any of its blocks, we end up getting two
862b84b8390SFilipe Manana 			 * csum items in our csum tree that overlap each other:
863b84b8390SFilipe Manana 			 *
864b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
865b84b8390SFilipe Manana 			 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
866b84b8390SFilipe Manana 			 *
867b84b8390SFilipe Manana 			 * Which is a problem, because after this anyone trying
868b84b8390SFilipe Manana 			 * to lookup up for the checksum of any block of our
869b84b8390SFilipe Manana 			 * extent starting at an offset of 40K or higher, will
870b84b8390SFilipe Manana 			 * end up looking at the second csum item only, which
871b84b8390SFilipe Manana 			 * does not contain the checksum for any block starting
872b84b8390SFilipe Manana 			 * at offset 40K or higher of our extent.
873b84b8390SFilipe Manana 			 */
87407d400a6SYan Zheng 			while (!list_empty(&ordered_sums)) {
87507d400a6SYan Zheng 				struct btrfs_ordered_sum *sums;
876fc28b25eSJosef Bacik 				struct btrfs_root *csum_root;
877fc28b25eSJosef Bacik 
87807d400a6SYan Zheng 				sums = list_entry(ordered_sums.next,
87907d400a6SYan Zheng 						struct btrfs_ordered_sum,
88007d400a6SYan Zheng 						list);
881fc28b25eSJosef Bacik 				csum_root = btrfs_csum_root(fs_info,
882fc28b25eSJosef Bacik 							    sums->bytenr);
8833650860bSJosef Bacik 				if (!ret)
884fc28b25eSJosef Bacik 					ret = btrfs_del_csums(trans, csum_root,
885b84b8390SFilipe Manana 							      sums->bytenr,
886b84b8390SFilipe Manana 							      sums->len);
887b84b8390SFilipe Manana 				if (!ret)
88807d400a6SYan Zheng 					ret = btrfs_csum_file_blocks(trans,
889fc28b25eSJosef Bacik 								     csum_root,
890fc28b25eSJosef Bacik 								     sums);
89107d400a6SYan Zheng 				list_del(&sums->list);
89207d400a6SYan Zheng 				kfree(sums);
89307d400a6SYan Zheng 			}
8943650860bSJosef Bacik 			if (ret)
8953650860bSJosef Bacik 				goto out;
89607d400a6SYan Zheng 		} else {
897b3b4aa74SDavid Sterba 			btrfs_release_path(path);
89807d400a6SYan Zheng 		}
89907d400a6SYan Zheng 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
90007d400a6SYan Zheng 		/* inline extents are easy, we just overwrite them */
901e02119d5SChris Mason 		ret = overwrite_item(trans, root, path, eb, slot, key);
9023650860bSJosef Bacik 		if (ret)
9033650860bSJosef Bacik 			goto out;
90407d400a6SYan Zheng 	}
905e02119d5SChris Mason 
9069ddc959eSJosef Bacik 	ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode), start,
9079ddc959eSJosef Bacik 						extent_end - start);
9089ddc959eSJosef Bacik 	if (ret)
9099ddc959eSJosef Bacik 		goto out;
9109ddc959eSJosef Bacik 
9113168021cSFilipe Manana update_inode:
9122766ff61SFilipe Manana 	btrfs_update_inode_bytes(BTRFS_I(inode), nbytes, drop_args.bytes_found);
9139a56fcd1SNikolay Borisov 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
914e02119d5SChris Mason out:
915e02119d5SChris Mason 	if (inode)
916e02119d5SChris Mason 		iput(inode);
917e02119d5SChris Mason 	return ret;
918e02119d5SChris Mason }
919e02119d5SChris Mason 
920e02119d5SChris Mason /*
921e02119d5SChris Mason  * when cleaning up conflicts between the directory names in the
922e02119d5SChris Mason  * subvolume, directory names in the log and directory names in the
923e02119d5SChris Mason  * inode back references, we may have to unlink inodes from directories.
924e02119d5SChris Mason  *
925e02119d5SChris Mason  * This is a helper function to do the unlink of a specific directory
926e02119d5SChris Mason  * item
927e02119d5SChris Mason  */
928e02119d5SChris Mason static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
929e02119d5SChris Mason 				      struct btrfs_path *path,
930207e7d92SNikolay Borisov 				      struct btrfs_inode *dir,
931e02119d5SChris Mason 				      struct btrfs_dir_item *di)
932e02119d5SChris Mason {
9339798ba24SFilipe Manana 	struct btrfs_root *root = dir->root;
934e02119d5SChris Mason 	struct inode *inode;
935e02119d5SChris Mason 	char *name;
936e02119d5SChris Mason 	int name_len;
937e02119d5SChris Mason 	struct extent_buffer *leaf;
938e02119d5SChris Mason 	struct btrfs_key location;
939e02119d5SChris Mason 	int ret;
940e02119d5SChris Mason 
941e02119d5SChris Mason 	leaf = path->nodes[0];
942e02119d5SChris Mason 
943e02119d5SChris Mason 	btrfs_dir_item_key_to_cpu(leaf, di, &location);
944e02119d5SChris Mason 	name_len = btrfs_dir_name_len(leaf, di);
945e02119d5SChris Mason 	name = kmalloc(name_len, GFP_NOFS);
9462a29edc6Sliubo 	if (!name)
9472a29edc6Sliubo 		return -ENOMEM;
9482a29edc6Sliubo 
949e02119d5SChris Mason 	read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
950b3b4aa74SDavid Sterba 	btrfs_release_path(path);
951e02119d5SChris Mason 
952e02119d5SChris Mason 	inode = read_one_inode(root, location.objectid);
953c00e9493STsutomu Itoh 	if (!inode) {
9543650860bSJosef Bacik 		ret = -EIO;
9553650860bSJosef Bacik 		goto out;
956c00e9493STsutomu Itoh 	}
957e02119d5SChris Mason 
958ec051c0fSYan Zheng 	ret = link_to_fixup_dir(trans, root, path, location.objectid);
9593650860bSJosef Bacik 	if (ret)
9603650860bSJosef Bacik 		goto out;
96112fcfd22SChris Mason 
9624467af88SFilipe Manana 	ret = btrfs_unlink_inode(trans, dir, BTRFS_I(inode), name,
963207e7d92SNikolay Borisov 			name_len);
9643650860bSJosef Bacik 	if (ret)
9653650860bSJosef Bacik 		goto out;
966ada9af21SFilipe David Borba Manana 	else
967e5c304e6SNikolay Borisov 		ret = btrfs_run_delayed_items(trans);
9683650860bSJosef Bacik out:
9693650860bSJosef Bacik 	kfree(name);
9703650860bSJosef Bacik 	iput(inode);
971e02119d5SChris Mason 	return ret;
972e02119d5SChris Mason }
973e02119d5SChris Mason 
974e02119d5SChris Mason /*
97577a5b9e3SFilipe Manana  * See if a given name and sequence number found in an inode back reference are
97677a5b9e3SFilipe Manana  * already in a directory and correctly point to this inode.
97777a5b9e3SFilipe Manana  *
97877a5b9e3SFilipe Manana  * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
97977a5b9e3SFilipe Manana  * exists.
980e02119d5SChris Mason  */
981e02119d5SChris Mason static noinline int inode_in_dir(struct btrfs_root *root,
982e02119d5SChris Mason 				 struct btrfs_path *path,
983e02119d5SChris Mason 				 u64 dirid, u64 objectid, u64 index,
984e02119d5SChris Mason 				 const char *name, int name_len)
985e02119d5SChris Mason {
986e02119d5SChris Mason 	struct btrfs_dir_item *di;
987e02119d5SChris Mason 	struct btrfs_key location;
98877a5b9e3SFilipe Manana 	int ret = 0;
989e02119d5SChris Mason 
990e02119d5SChris Mason 	di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
991e02119d5SChris Mason 					 index, name, name_len, 0);
99277a5b9e3SFilipe Manana 	if (IS_ERR(di)) {
99377a5b9e3SFilipe Manana 		ret = PTR_ERR(di);
99477a5b9e3SFilipe Manana 		goto out;
99577a5b9e3SFilipe Manana 	} else if (di) {
996e02119d5SChris Mason 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
997e02119d5SChris Mason 		if (location.objectid != objectid)
998e02119d5SChris Mason 			goto out;
99977a5b9e3SFilipe Manana 	} else {
1000e02119d5SChris Mason 		goto out;
100177a5b9e3SFilipe Manana 	}
1002e02119d5SChris Mason 
100377a5b9e3SFilipe Manana 	btrfs_release_path(path);
1004e02119d5SChris Mason 	di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
100577a5b9e3SFilipe Manana 	if (IS_ERR(di)) {
100677a5b9e3SFilipe Manana 		ret = PTR_ERR(di);
100777a5b9e3SFilipe Manana 		goto out;
100877a5b9e3SFilipe Manana 	} else if (di) {
1009e02119d5SChris Mason 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
101077a5b9e3SFilipe Manana 		if (location.objectid == objectid)
101177a5b9e3SFilipe Manana 			ret = 1;
101277a5b9e3SFilipe Manana 	}
1013e02119d5SChris Mason out:
1014b3b4aa74SDavid Sterba 	btrfs_release_path(path);
101577a5b9e3SFilipe Manana 	return ret;
1016e02119d5SChris Mason }
1017e02119d5SChris Mason 
1018e02119d5SChris Mason /*
1019e02119d5SChris Mason  * helper function to check a log tree for a named back reference in
1020e02119d5SChris Mason  * an inode.  This is used to decide if a back reference that is
1021e02119d5SChris Mason  * found in the subvolume conflicts with what we find in the log.
1022e02119d5SChris Mason  *
1023e02119d5SChris Mason  * inode backreferences may have multiple refs in a single item,
1024e02119d5SChris Mason  * during replay we process one reference at a time, and we don't
1025e02119d5SChris Mason  * want to delete valid links to a file from the subvolume if that
1026e02119d5SChris Mason  * link is also in the log.
1027e02119d5SChris Mason  */
1028e02119d5SChris Mason static noinline int backref_in_log(struct btrfs_root *log,
1029e02119d5SChris Mason 				   struct btrfs_key *key,
1030f186373fSMark Fasheh 				   u64 ref_objectid,
1031df8d116fSFilipe Manana 				   const char *name, int namelen)
1032e02119d5SChris Mason {
1033e02119d5SChris Mason 	struct btrfs_path *path;
1034e02119d5SChris Mason 	int ret;
1035e02119d5SChris Mason 
1036e02119d5SChris Mason 	path = btrfs_alloc_path();
10372a29edc6Sliubo 	if (!path)
10382a29edc6Sliubo 		return -ENOMEM;
10392a29edc6Sliubo 
1040e02119d5SChris Mason 	ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1041d3316c82SNikolay Borisov 	if (ret < 0) {
1042d3316c82SNikolay Borisov 		goto out;
1043d3316c82SNikolay Borisov 	} else if (ret == 1) {
104489cbf5f6SNikolay Borisov 		ret = 0;
1045e02119d5SChris Mason 		goto out;
104689cbf5f6SNikolay Borisov 	}
1047e02119d5SChris Mason 
104889cbf5f6SNikolay Borisov 	if (key->type == BTRFS_INODE_EXTREF_KEY)
104989cbf5f6SNikolay Borisov 		ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
10501f250e92SFilipe Manana 						       path->slots[0],
10511f250e92SFilipe Manana 						       ref_objectid,
105289cbf5f6SNikolay Borisov 						       name, namelen);
105389cbf5f6SNikolay Borisov 	else
105489cbf5f6SNikolay Borisov 		ret = !!btrfs_find_name_in_backref(path->nodes[0],
105589cbf5f6SNikolay Borisov 						   path->slots[0],
105689cbf5f6SNikolay Borisov 						   name, namelen);
1057e02119d5SChris Mason out:
1058e02119d5SChris Mason 	btrfs_free_path(path);
105989cbf5f6SNikolay Borisov 	return ret;
1060e02119d5SChris Mason }
1061e02119d5SChris Mason 
10625a1d7843SJan Schmidt static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
10635a1d7843SJan Schmidt 				  struct btrfs_root *root,
10645a1d7843SJan Schmidt 				  struct btrfs_path *path,
10655a1d7843SJan Schmidt 				  struct btrfs_root *log_root,
106694c91a1fSNikolay Borisov 				  struct btrfs_inode *dir,
106794c91a1fSNikolay Borisov 				  struct btrfs_inode *inode,
1068f186373fSMark Fasheh 				  u64 inode_objectid, u64 parent_objectid,
1069f186373fSMark Fasheh 				  u64 ref_index, char *name, int namelen,
1070f186373fSMark Fasheh 				  int *search_done)
10715a1d7843SJan Schmidt {
10725a1d7843SJan Schmidt 	int ret;
10735a1d7843SJan Schmidt 	char *victim_name;
10745a1d7843SJan Schmidt 	int victim_name_len;
1075f186373fSMark Fasheh 	struct extent_buffer *leaf;
1076f186373fSMark Fasheh 	struct btrfs_dir_item *di;
1077f186373fSMark Fasheh 	struct btrfs_key search_key;
1078f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
1079f186373fSMark Fasheh 
1080f186373fSMark Fasheh again:
1081f186373fSMark Fasheh 	/* Search old style refs */
1082f186373fSMark Fasheh 	search_key.objectid = inode_objectid;
1083f186373fSMark Fasheh 	search_key.type = BTRFS_INODE_REF_KEY;
1084f186373fSMark Fasheh 	search_key.offset = parent_objectid;
1085f186373fSMark Fasheh 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1086f186373fSMark Fasheh 	if (ret == 0) {
10875a1d7843SJan Schmidt 		struct btrfs_inode_ref *victim_ref;
10885a1d7843SJan Schmidt 		unsigned long ptr;
10895a1d7843SJan Schmidt 		unsigned long ptr_end;
1090f186373fSMark Fasheh 
1091f186373fSMark Fasheh 		leaf = path->nodes[0];
10925a1d7843SJan Schmidt 
10935a1d7843SJan Schmidt 		/* are we trying to overwrite a back ref for the root directory
10945a1d7843SJan Schmidt 		 * if so, just jump out, we're done
10955a1d7843SJan Schmidt 		 */
1096f186373fSMark Fasheh 		if (search_key.objectid == search_key.offset)
10975a1d7843SJan Schmidt 			return 1;
10985a1d7843SJan Schmidt 
10995a1d7843SJan Schmidt 		/* check all the names in this back reference to see
11005a1d7843SJan Schmidt 		 * if they are in the log.  if so, we allow them to stay
11015a1d7843SJan Schmidt 		 * otherwise they must be unlinked as a conflict
11025a1d7843SJan Schmidt 		 */
11035a1d7843SJan Schmidt 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
11043212fa14SJosef Bacik 		ptr_end = ptr + btrfs_item_size(leaf, path->slots[0]);
11055a1d7843SJan Schmidt 		while (ptr < ptr_end) {
11065a1d7843SJan Schmidt 			victim_ref = (struct btrfs_inode_ref *)ptr;
11075a1d7843SJan Schmidt 			victim_name_len = btrfs_inode_ref_name_len(leaf,
11085a1d7843SJan Schmidt 								   victim_ref);
11095a1d7843SJan Schmidt 			victim_name = kmalloc(victim_name_len, GFP_NOFS);
11103650860bSJosef Bacik 			if (!victim_name)
11113650860bSJosef Bacik 				return -ENOMEM;
11125a1d7843SJan Schmidt 
11135a1d7843SJan Schmidt 			read_extent_buffer(leaf, victim_name,
11145a1d7843SJan Schmidt 					   (unsigned long)(victim_ref + 1),
11155a1d7843SJan Schmidt 					   victim_name_len);
11165a1d7843SJan Schmidt 
1117d3316c82SNikolay Borisov 			ret = backref_in_log(log_root, &search_key,
1118d3316c82SNikolay Borisov 					     parent_objectid, victim_name,
1119d3316c82SNikolay Borisov 					     victim_name_len);
1120d3316c82SNikolay Borisov 			if (ret < 0) {
1121d3316c82SNikolay Borisov 				kfree(victim_name);
1122d3316c82SNikolay Borisov 				return ret;
1123d3316c82SNikolay Borisov 			} else if (!ret) {
112494c91a1fSNikolay Borisov 				inc_nlink(&inode->vfs_inode);
11255a1d7843SJan Schmidt 				btrfs_release_path(path);
11265a1d7843SJan Schmidt 
11274467af88SFilipe Manana 				ret = btrfs_unlink_inode(trans, dir, inode,
11284ec5934eSNikolay Borisov 						victim_name, victim_name_len);
1129f186373fSMark Fasheh 				kfree(victim_name);
11303650860bSJosef Bacik 				if (ret)
11313650860bSJosef Bacik 					return ret;
1132e5c304e6SNikolay Borisov 				ret = btrfs_run_delayed_items(trans);
1133ada9af21SFilipe David Borba Manana 				if (ret)
1134ada9af21SFilipe David Borba Manana 					return ret;
1135f186373fSMark Fasheh 				*search_done = 1;
1136f186373fSMark Fasheh 				goto again;
11375a1d7843SJan Schmidt 			}
11385a1d7843SJan Schmidt 			kfree(victim_name);
1139f186373fSMark Fasheh 
11405a1d7843SJan Schmidt 			ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
11415a1d7843SJan Schmidt 		}
11425a1d7843SJan Schmidt 
11435a1d7843SJan Schmidt 		/*
11445a1d7843SJan Schmidt 		 * NOTE: we have searched root tree and checked the
1145bb7ab3b9SAdam Buchbinder 		 * corresponding ref, it does not need to check again.
11465a1d7843SJan Schmidt 		 */
11475a1d7843SJan Schmidt 		*search_done = 1;
11485a1d7843SJan Schmidt 	}
11495a1d7843SJan Schmidt 	btrfs_release_path(path);
11505a1d7843SJan Schmidt 
1151f186373fSMark Fasheh 	/* Same search but for extended refs */
1152f186373fSMark Fasheh 	extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
1153f186373fSMark Fasheh 					   inode_objectid, parent_objectid, 0,
1154f186373fSMark Fasheh 					   0);
1155f186373fSMark Fasheh 	if (!IS_ERR_OR_NULL(extref)) {
1156f186373fSMark Fasheh 		u32 item_size;
1157f186373fSMark Fasheh 		u32 cur_offset = 0;
1158f186373fSMark Fasheh 		unsigned long base;
1159f186373fSMark Fasheh 		struct inode *victim_parent;
1160f186373fSMark Fasheh 
1161f186373fSMark Fasheh 		leaf = path->nodes[0];
1162f186373fSMark Fasheh 
11633212fa14SJosef Bacik 		item_size = btrfs_item_size(leaf, path->slots[0]);
1164f186373fSMark Fasheh 		base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1165f186373fSMark Fasheh 
1166f186373fSMark Fasheh 		while (cur_offset < item_size) {
1167dd9ef135SQuentin Casasnovas 			extref = (struct btrfs_inode_extref *)(base + cur_offset);
1168f186373fSMark Fasheh 
1169f186373fSMark Fasheh 			victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
1170f186373fSMark Fasheh 
1171f186373fSMark Fasheh 			if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1172f186373fSMark Fasheh 				goto next;
1173f186373fSMark Fasheh 
1174f186373fSMark Fasheh 			victim_name = kmalloc(victim_name_len, GFP_NOFS);
11753650860bSJosef Bacik 			if (!victim_name)
11763650860bSJosef Bacik 				return -ENOMEM;
1177f186373fSMark Fasheh 			read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1178f186373fSMark Fasheh 					   victim_name_len);
1179f186373fSMark Fasheh 
1180f186373fSMark Fasheh 			search_key.objectid = inode_objectid;
1181f186373fSMark Fasheh 			search_key.type = BTRFS_INODE_EXTREF_KEY;
1182f186373fSMark Fasheh 			search_key.offset = btrfs_extref_hash(parent_objectid,
1183f186373fSMark Fasheh 							      victim_name,
1184f186373fSMark Fasheh 							      victim_name_len);
1185d3316c82SNikolay Borisov 			ret = backref_in_log(log_root, &search_key,
1186f186373fSMark Fasheh 					     parent_objectid, victim_name,
1187d3316c82SNikolay Borisov 					     victim_name_len);
1188d3316c82SNikolay Borisov 			if (ret < 0) {
1189f35838a6SJianglei Nie 				kfree(victim_name);
1190d3316c82SNikolay Borisov 				return ret;
1191d3316c82SNikolay Borisov 			} else if (!ret) {
1192f186373fSMark Fasheh 				ret = -ENOENT;
1193f186373fSMark Fasheh 				victim_parent = read_one_inode(root,
1194f186373fSMark Fasheh 						parent_objectid);
1195f186373fSMark Fasheh 				if (victim_parent) {
119694c91a1fSNikolay Borisov 					inc_nlink(&inode->vfs_inode);
1197f186373fSMark Fasheh 					btrfs_release_path(path);
1198f186373fSMark Fasheh 
11994467af88SFilipe Manana 					ret = btrfs_unlink_inode(trans,
12004ec5934eSNikolay Borisov 							BTRFS_I(victim_parent),
120194c91a1fSNikolay Borisov 							inode,
1202f186373fSMark Fasheh 							victim_name,
1203f186373fSMark Fasheh 							victim_name_len);
1204ada9af21SFilipe David Borba Manana 					if (!ret)
1205ada9af21SFilipe David Borba Manana 						ret = btrfs_run_delayed_items(
1206e5c304e6SNikolay Borisov 								  trans);
1207f186373fSMark Fasheh 				}
1208f186373fSMark Fasheh 				iput(victim_parent);
1209f186373fSMark Fasheh 				kfree(victim_name);
12103650860bSJosef Bacik 				if (ret)
12113650860bSJosef Bacik 					return ret;
1212f186373fSMark Fasheh 				*search_done = 1;
1213f186373fSMark Fasheh 				goto again;
1214f186373fSMark Fasheh 			}
1215f186373fSMark Fasheh 			kfree(victim_name);
1216f186373fSMark Fasheh next:
1217f186373fSMark Fasheh 			cur_offset += victim_name_len + sizeof(*extref);
1218f186373fSMark Fasheh 		}
1219f186373fSMark Fasheh 		*search_done = 1;
1220f186373fSMark Fasheh 	}
1221f186373fSMark Fasheh 	btrfs_release_path(path);
1222f186373fSMark Fasheh 
12235a1d7843SJan Schmidt 	/* look for a conflicting sequence number */
122494c91a1fSNikolay Borisov 	di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1225f186373fSMark Fasheh 					 ref_index, name, namelen, 0);
122652db7779SFilipe Manana 	if (IS_ERR(di)) {
122752db7779SFilipe Manana 		return PTR_ERR(di);
122852db7779SFilipe Manana 	} else if (di) {
12299798ba24SFilipe Manana 		ret = drop_one_dir_item(trans, path, dir, di);
12303650860bSJosef Bacik 		if (ret)
12313650860bSJosef Bacik 			return ret;
12325a1d7843SJan Schmidt 	}
12335a1d7843SJan Schmidt 	btrfs_release_path(path);
12345a1d7843SJan Schmidt 
123552042d8eSAndrea Gelmini 	/* look for a conflicting name */
123694c91a1fSNikolay Borisov 	di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
12375a1d7843SJan Schmidt 				   name, namelen, 0);
123852db7779SFilipe Manana 	if (IS_ERR(di)) {
123952db7779SFilipe Manana 		return PTR_ERR(di);
124052db7779SFilipe Manana 	} else if (di) {
12419798ba24SFilipe Manana 		ret = drop_one_dir_item(trans, path, dir, di);
12423650860bSJosef Bacik 		if (ret)
12433650860bSJosef Bacik 			return ret;
12445a1d7843SJan Schmidt 	}
12455a1d7843SJan Schmidt 	btrfs_release_path(path);
12465a1d7843SJan Schmidt 
12475a1d7843SJan Schmidt 	return 0;
12485a1d7843SJan Schmidt }
1249e02119d5SChris Mason 
1250bae15d95SQu Wenruo static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1251bae15d95SQu Wenruo 			     u32 *namelen, char **name, u64 *index,
1252bae15d95SQu Wenruo 			     u64 *parent_objectid)
1253f186373fSMark Fasheh {
1254f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
1255f186373fSMark Fasheh 
1256f186373fSMark Fasheh 	extref = (struct btrfs_inode_extref *)ref_ptr;
1257f186373fSMark Fasheh 
1258f186373fSMark Fasheh 	*namelen = btrfs_inode_extref_name_len(eb, extref);
1259f186373fSMark Fasheh 	*name = kmalloc(*namelen, GFP_NOFS);
1260f186373fSMark Fasheh 	if (*name == NULL)
1261f186373fSMark Fasheh 		return -ENOMEM;
1262f186373fSMark Fasheh 
1263f186373fSMark Fasheh 	read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1264f186373fSMark Fasheh 			   *namelen);
1265f186373fSMark Fasheh 
12661f250e92SFilipe Manana 	if (index)
1267f186373fSMark Fasheh 		*index = btrfs_inode_extref_index(eb, extref);
1268f186373fSMark Fasheh 	if (parent_objectid)
1269f186373fSMark Fasheh 		*parent_objectid = btrfs_inode_extref_parent(eb, extref);
1270f186373fSMark Fasheh 
1271f186373fSMark Fasheh 	return 0;
1272f186373fSMark Fasheh }
1273f186373fSMark Fasheh 
1274bae15d95SQu Wenruo static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1275bae15d95SQu Wenruo 			  u32 *namelen, char **name, u64 *index)
1276f186373fSMark Fasheh {
1277f186373fSMark Fasheh 	struct btrfs_inode_ref *ref;
1278f186373fSMark Fasheh 
1279f186373fSMark Fasheh 	ref = (struct btrfs_inode_ref *)ref_ptr;
1280f186373fSMark Fasheh 
1281f186373fSMark Fasheh 	*namelen = btrfs_inode_ref_name_len(eb, ref);
1282f186373fSMark Fasheh 	*name = kmalloc(*namelen, GFP_NOFS);
1283f186373fSMark Fasheh 	if (*name == NULL)
1284f186373fSMark Fasheh 		return -ENOMEM;
1285f186373fSMark Fasheh 
1286f186373fSMark Fasheh 	read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1287f186373fSMark Fasheh 
12881f250e92SFilipe Manana 	if (index)
1289f186373fSMark Fasheh 		*index = btrfs_inode_ref_index(eb, ref);
1290f186373fSMark Fasheh 
1291f186373fSMark Fasheh 	return 0;
1292f186373fSMark Fasheh }
1293f186373fSMark Fasheh 
1294e02119d5SChris Mason /*
12951f250e92SFilipe Manana  * Take an inode reference item from the log tree and iterate all names from the
12961f250e92SFilipe Manana  * inode reference item in the subvolume tree with the same key (if it exists).
12971f250e92SFilipe Manana  * For any name that is not in the inode reference item from the log tree, do a
12981f250e92SFilipe Manana  * proper unlink of that name (that is, remove its entry from the inode
12991f250e92SFilipe Manana  * reference item and both dir index keys).
13001f250e92SFilipe Manana  */
13011f250e92SFilipe Manana static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
13021f250e92SFilipe Manana 				 struct btrfs_root *root,
13031f250e92SFilipe Manana 				 struct btrfs_path *path,
13041f250e92SFilipe Manana 				 struct btrfs_inode *inode,
13051f250e92SFilipe Manana 				 struct extent_buffer *log_eb,
13061f250e92SFilipe Manana 				 int log_slot,
13071f250e92SFilipe Manana 				 struct btrfs_key *key)
13081f250e92SFilipe Manana {
13091f250e92SFilipe Manana 	int ret;
13101f250e92SFilipe Manana 	unsigned long ref_ptr;
13111f250e92SFilipe Manana 	unsigned long ref_end;
13121f250e92SFilipe Manana 	struct extent_buffer *eb;
13131f250e92SFilipe Manana 
13141f250e92SFilipe Manana again:
13151f250e92SFilipe Manana 	btrfs_release_path(path);
13161f250e92SFilipe Manana 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
13171f250e92SFilipe Manana 	if (ret > 0) {
13181f250e92SFilipe Manana 		ret = 0;
13191f250e92SFilipe Manana 		goto out;
13201f250e92SFilipe Manana 	}
13211f250e92SFilipe Manana 	if (ret < 0)
13221f250e92SFilipe Manana 		goto out;
13231f250e92SFilipe Manana 
13241f250e92SFilipe Manana 	eb = path->nodes[0];
13251f250e92SFilipe Manana 	ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
13263212fa14SJosef Bacik 	ref_end = ref_ptr + btrfs_item_size(eb, path->slots[0]);
13271f250e92SFilipe Manana 	while (ref_ptr < ref_end) {
13281f250e92SFilipe Manana 		char *name = NULL;
13291f250e92SFilipe Manana 		int namelen;
13301f250e92SFilipe Manana 		u64 parent_id;
13311f250e92SFilipe Manana 
13321f250e92SFilipe Manana 		if (key->type == BTRFS_INODE_EXTREF_KEY) {
13331f250e92SFilipe Manana 			ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
13341f250e92SFilipe Manana 						NULL, &parent_id);
13351f250e92SFilipe Manana 		} else {
13361f250e92SFilipe Manana 			parent_id = key->offset;
13371f250e92SFilipe Manana 			ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
13381f250e92SFilipe Manana 					     NULL);
13391f250e92SFilipe Manana 		}
13401f250e92SFilipe Manana 		if (ret)
13411f250e92SFilipe Manana 			goto out;
13421f250e92SFilipe Manana 
13431f250e92SFilipe Manana 		if (key->type == BTRFS_INODE_EXTREF_KEY)
13446ff49c6aSNikolay Borisov 			ret = !!btrfs_find_name_in_ext_backref(log_eb, log_slot,
13451f250e92SFilipe Manana 							       parent_id, name,
13466ff49c6aSNikolay Borisov 							       namelen);
13471f250e92SFilipe Manana 		else
13489bb8407fSNikolay Borisov 			ret = !!btrfs_find_name_in_backref(log_eb, log_slot,
13499bb8407fSNikolay Borisov 							   name, namelen);
13501f250e92SFilipe Manana 
13511f250e92SFilipe Manana 		if (!ret) {
13521f250e92SFilipe Manana 			struct inode *dir;
13531f250e92SFilipe Manana 
13541f250e92SFilipe Manana 			btrfs_release_path(path);
13551f250e92SFilipe Manana 			dir = read_one_inode(root, parent_id);
13561f250e92SFilipe Manana 			if (!dir) {
13571f250e92SFilipe Manana 				ret = -ENOENT;
13581f250e92SFilipe Manana 				kfree(name);
13591f250e92SFilipe Manana 				goto out;
13601f250e92SFilipe Manana 			}
13614467af88SFilipe Manana 			ret = btrfs_unlink_inode(trans, BTRFS_I(dir),
13621f250e92SFilipe Manana 						 inode, name, namelen);
13631f250e92SFilipe Manana 			kfree(name);
13641f250e92SFilipe Manana 			iput(dir);
13651f250e92SFilipe Manana 			if (ret)
13661f250e92SFilipe Manana 				goto out;
13671f250e92SFilipe Manana 			goto again;
13681f250e92SFilipe Manana 		}
13691f250e92SFilipe Manana 
13701f250e92SFilipe Manana 		kfree(name);
13711f250e92SFilipe Manana 		ref_ptr += namelen;
13721f250e92SFilipe Manana 		if (key->type == BTRFS_INODE_EXTREF_KEY)
13731f250e92SFilipe Manana 			ref_ptr += sizeof(struct btrfs_inode_extref);
13741f250e92SFilipe Manana 		else
13751f250e92SFilipe Manana 			ref_ptr += sizeof(struct btrfs_inode_ref);
13761f250e92SFilipe Manana 	}
13771f250e92SFilipe Manana 	ret = 0;
13781f250e92SFilipe Manana  out:
13791f250e92SFilipe Manana 	btrfs_release_path(path);
13801f250e92SFilipe Manana 	return ret;
13811f250e92SFilipe Manana }
13821f250e92SFilipe Manana 
13830d836392SFilipe Manana static int btrfs_inode_ref_exists(struct inode *inode, struct inode *dir,
13840d836392SFilipe Manana 				  const u8 ref_type, const char *name,
13850d836392SFilipe Manana 				  const int namelen)
13860d836392SFilipe Manana {
13870d836392SFilipe Manana 	struct btrfs_key key;
13880d836392SFilipe Manana 	struct btrfs_path *path;
13890d836392SFilipe Manana 	const u64 parent_id = btrfs_ino(BTRFS_I(dir));
13900d836392SFilipe Manana 	int ret;
13910d836392SFilipe Manana 
13920d836392SFilipe Manana 	path = btrfs_alloc_path();
13930d836392SFilipe Manana 	if (!path)
13940d836392SFilipe Manana 		return -ENOMEM;
13950d836392SFilipe Manana 
13960d836392SFilipe Manana 	key.objectid = btrfs_ino(BTRFS_I(inode));
13970d836392SFilipe Manana 	key.type = ref_type;
13980d836392SFilipe Manana 	if (key.type == BTRFS_INODE_REF_KEY)
13990d836392SFilipe Manana 		key.offset = parent_id;
14000d836392SFilipe Manana 	else
14010d836392SFilipe Manana 		key.offset = btrfs_extref_hash(parent_id, name, namelen);
14020d836392SFilipe Manana 
14030d836392SFilipe Manana 	ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
14040d836392SFilipe Manana 	if (ret < 0)
14050d836392SFilipe Manana 		goto out;
14060d836392SFilipe Manana 	if (ret > 0) {
14070d836392SFilipe Manana 		ret = 0;
14080d836392SFilipe Manana 		goto out;
14090d836392SFilipe Manana 	}
14100d836392SFilipe Manana 	if (key.type == BTRFS_INODE_EXTREF_KEY)
14116ff49c6aSNikolay Borisov 		ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
14126ff49c6aSNikolay Borisov 				path->slots[0], parent_id, name, namelen);
14130d836392SFilipe Manana 	else
14149bb8407fSNikolay Borisov 		ret = !!btrfs_find_name_in_backref(path->nodes[0], path->slots[0],
14159bb8407fSNikolay Borisov 						   name, namelen);
14160d836392SFilipe Manana 
14170d836392SFilipe Manana out:
14180d836392SFilipe Manana 	btrfs_free_path(path);
14190d836392SFilipe Manana 	return ret;
14200d836392SFilipe Manana }
14210d836392SFilipe Manana 
14226d9cc072SFilipe Manana static int add_link(struct btrfs_trans_handle *trans,
14236b5fc433SFilipe Manana 		    struct inode *dir, struct inode *inode, const char *name,
14246b5fc433SFilipe Manana 		    int namelen, u64 ref_index)
14256b5fc433SFilipe Manana {
14266d9cc072SFilipe Manana 	struct btrfs_root *root = BTRFS_I(dir)->root;
14276b5fc433SFilipe Manana 	struct btrfs_dir_item *dir_item;
14286b5fc433SFilipe Manana 	struct btrfs_key key;
14296b5fc433SFilipe Manana 	struct btrfs_path *path;
14306b5fc433SFilipe Manana 	struct inode *other_inode = NULL;
14316b5fc433SFilipe Manana 	int ret;
14326b5fc433SFilipe Manana 
14336b5fc433SFilipe Manana 	path = btrfs_alloc_path();
14346b5fc433SFilipe Manana 	if (!path)
14356b5fc433SFilipe Manana 		return -ENOMEM;
14366b5fc433SFilipe Manana 
14376b5fc433SFilipe Manana 	dir_item = btrfs_lookup_dir_item(NULL, root, path,
14386b5fc433SFilipe Manana 					 btrfs_ino(BTRFS_I(dir)),
14396b5fc433SFilipe Manana 					 name, namelen, 0);
14406b5fc433SFilipe Manana 	if (!dir_item) {
14416b5fc433SFilipe Manana 		btrfs_release_path(path);
14426b5fc433SFilipe Manana 		goto add_link;
14436b5fc433SFilipe Manana 	} else if (IS_ERR(dir_item)) {
14446b5fc433SFilipe Manana 		ret = PTR_ERR(dir_item);
14456b5fc433SFilipe Manana 		goto out;
14466b5fc433SFilipe Manana 	}
14476b5fc433SFilipe Manana 
14486b5fc433SFilipe Manana 	/*
14496b5fc433SFilipe Manana 	 * Our inode's dentry collides with the dentry of another inode which is
14506b5fc433SFilipe Manana 	 * in the log but not yet processed since it has a higher inode number.
14516b5fc433SFilipe Manana 	 * So delete that other dentry.
14526b5fc433SFilipe Manana 	 */
14536b5fc433SFilipe Manana 	btrfs_dir_item_key_to_cpu(path->nodes[0], dir_item, &key);
14546b5fc433SFilipe Manana 	btrfs_release_path(path);
14556b5fc433SFilipe Manana 	other_inode = read_one_inode(root, key.objectid);
14566b5fc433SFilipe Manana 	if (!other_inode) {
14576b5fc433SFilipe Manana 		ret = -ENOENT;
14586b5fc433SFilipe Manana 		goto out;
14596b5fc433SFilipe Manana 	}
14604467af88SFilipe Manana 	ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(other_inode),
14616b5fc433SFilipe Manana 				 name, namelen);
14626b5fc433SFilipe Manana 	if (ret)
14636b5fc433SFilipe Manana 		goto out;
14646b5fc433SFilipe Manana 	/*
14656b5fc433SFilipe Manana 	 * If we dropped the link count to 0, bump it so that later the iput()
14666b5fc433SFilipe Manana 	 * on the inode will not free it. We will fixup the link count later.
14676b5fc433SFilipe Manana 	 */
14686b5fc433SFilipe Manana 	if (other_inode->i_nlink == 0)
14696b5fc433SFilipe Manana 		inc_nlink(other_inode);
14706b5fc433SFilipe Manana 
14716b5fc433SFilipe Manana 	ret = btrfs_run_delayed_items(trans);
14726b5fc433SFilipe Manana 	if (ret)
14736b5fc433SFilipe Manana 		goto out;
14746b5fc433SFilipe Manana add_link:
14756b5fc433SFilipe Manana 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
14766b5fc433SFilipe Manana 			     name, namelen, 0, ref_index);
14776b5fc433SFilipe Manana out:
14786b5fc433SFilipe Manana 	iput(other_inode);
14796b5fc433SFilipe Manana 	btrfs_free_path(path);
14806b5fc433SFilipe Manana 
14816b5fc433SFilipe Manana 	return ret;
14826b5fc433SFilipe Manana }
14836b5fc433SFilipe Manana 
14841f250e92SFilipe Manana /*
1485e02119d5SChris Mason  * replay one inode back reference item found in the log tree.
1486e02119d5SChris Mason  * eb, slot and key refer to the buffer and key found in the log tree.
1487e02119d5SChris Mason  * root is the destination we are replaying into, and path is for temp
1488e02119d5SChris Mason  * use by this function.  (it should be released on return).
1489e02119d5SChris Mason  */
1490e02119d5SChris Mason static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1491e02119d5SChris Mason 				  struct btrfs_root *root,
1492e02119d5SChris Mason 				  struct btrfs_root *log,
1493e02119d5SChris Mason 				  struct btrfs_path *path,
1494e02119d5SChris Mason 				  struct extent_buffer *eb, int slot,
1495e02119d5SChris Mason 				  struct btrfs_key *key)
1496e02119d5SChris Mason {
149703b2f08bSGeyslan G. Bem 	struct inode *dir = NULL;
149803b2f08bSGeyslan G. Bem 	struct inode *inode = NULL;
1499e02119d5SChris Mason 	unsigned long ref_ptr;
1500e02119d5SChris Mason 	unsigned long ref_end;
150103b2f08bSGeyslan G. Bem 	char *name = NULL;
150234f3e4f2Sliubo 	int namelen;
150334f3e4f2Sliubo 	int ret;
1504c622ae60Sliubo 	int search_done = 0;
1505f186373fSMark Fasheh 	int log_ref_ver = 0;
1506f186373fSMark Fasheh 	u64 parent_objectid;
1507f186373fSMark Fasheh 	u64 inode_objectid;
1508f46dbe3dSChris Mason 	u64 ref_index = 0;
1509f186373fSMark Fasheh 	int ref_struct_size;
1510f186373fSMark Fasheh 
1511f186373fSMark Fasheh 	ref_ptr = btrfs_item_ptr_offset(eb, slot);
15123212fa14SJosef Bacik 	ref_end = ref_ptr + btrfs_item_size(eb, slot);
1513f186373fSMark Fasheh 
1514f186373fSMark Fasheh 	if (key->type == BTRFS_INODE_EXTREF_KEY) {
1515f186373fSMark Fasheh 		struct btrfs_inode_extref *r;
1516f186373fSMark Fasheh 
1517f186373fSMark Fasheh 		ref_struct_size = sizeof(struct btrfs_inode_extref);
1518f186373fSMark Fasheh 		log_ref_ver = 1;
1519f186373fSMark Fasheh 		r = (struct btrfs_inode_extref *)ref_ptr;
1520f186373fSMark Fasheh 		parent_objectid = btrfs_inode_extref_parent(eb, r);
1521f186373fSMark Fasheh 	} else {
1522f186373fSMark Fasheh 		ref_struct_size = sizeof(struct btrfs_inode_ref);
1523f186373fSMark Fasheh 		parent_objectid = key->offset;
1524f186373fSMark Fasheh 	}
1525f186373fSMark Fasheh 	inode_objectid = key->objectid;
1526e02119d5SChris Mason 
1527e02119d5SChris Mason 	/*
1528e02119d5SChris Mason 	 * it is possible that we didn't log all the parent directories
1529e02119d5SChris Mason 	 * for a given inode.  If we don't find the dir, just don't
1530e02119d5SChris Mason 	 * copy the back ref in.  The link count fixup code will take
1531e02119d5SChris Mason 	 * care of the rest
1532e02119d5SChris Mason 	 */
1533f186373fSMark Fasheh 	dir = read_one_inode(root, parent_objectid);
153403b2f08bSGeyslan G. Bem 	if (!dir) {
153503b2f08bSGeyslan G. Bem 		ret = -ENOENT;
153603b2f08bSGeyslan G. Bem 		goto out;
153703b2f08bSGeyslan G. Bem 	}
1538e02119d5SChris Mason 
1539f186373fSMark Fasheh 	inode = read_one_inode(root, inode_objectid);
1540c00e9493STsutomu Itoh 	if (!inode) {
154103b2f08bSGeyslan G. Bem 		ret = -EIO;
154203b2f08bSGeyslan G. Bem 		goto out;
1543c00e9493STsutomu Itoh 	}
1544e02119d5SChris Mason 
15455a1d7843SJan Schmidt 	while (ref_ptr < ref_end) {
1546f186373fSMark Fasheh 		if (log_ref_ver) {
1547bae15d95SQu Wenruo 			ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1548bae15d95SQu Wenruo 						&ref_index, &parent_objectid);
1549f186373fSMark Fasheh 			/*
1550f186373fSMark Fasheh 			 * parent object can change from one array
1551f186373fSMark Fasheh 			 * item to another.
1552f186373fSMark Fasheh 			 */
1553f186373fSMark Fasheh 			if (!dir)
1554f186373fSMark Fasheh 				dir = read_one_inode(root, parent_objectid);
155503b2f08bSGeyslan G. Bem 			if (!dir) {
155603b2f08bSGeyslan G. Bem 				ret = -ENOENT;
155703b2f08bSGeyslan G. Bem 				goto out;
155803b2f08bSGeyslan G. Bem 			}
1559f186373fSMark Fasheh 		} else {
1560bae15d95SQu Wenruo 			ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1561bae15d95SQu Wenruo 					     &ref_index);
1562f186373fSMark Fasheh 		}
1563f186373fSMark Fasheh 		if (ret)
156403b2f08bSGeyslan G. Bem 			goto out;
1565e02119d5SChris Mason 
156677a5b9e3SFilipe Manana 		ret = inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1567f85b7379SDavid Sterba 				   btrfs_ino(BTRFS_I(inode)), ref_index,
156877a5b9e3SFilipe Manana 				   name, namelen);
156977a5b9e3SFilipe Manana 		if (ret < 0) {
157077a5b9e3SFilipe Manana 			goto out;
157177a5b9e3SFilipe Manana 		} else if (ret == 0) {
15725a1d7843SJan Schmidt 			/*
15735a1d7843SJan Schmidt 			 * look for a conflicting back reference in the
15745a1d7843SJan Schmidt 			 * metadata. if we find one we have to unlink that name
15755a1d7843SJan Schmidt 			 * of the file before we add our new link.  Later on, we
15765a1d7843SJan Schmidt 			 * overwrite any existing back reference, and we don't
15775a1d7843SJan Schmidt 			 * want to create dangling pointers in the directory.
15785a1d7843SJan Schmidt 			 */
15795a1d7843SJan Schmidt 
15805a1d7843SJan Schmidt 			if (!search_done) {
15815a1d7843SJan Schmidt 				ret = __add_inode_ref(trans, root, path, log,
158294c91a1fSNikolay Borisov 						      BTRFS_I(dir),
1583d75eefdfSDavid Sterba 						      BTRFS_I(inode),
1584f186373fSMark Fasheh 						      inode_objectid,
1585f186373fSMark Fasheh 						      parent_objectid,
1586f186373fSMark Fasheh 						      ref_index, name, namelen,
15875a1d7843SJan Schmidt 						      &search_done);
158803b2f08bSGeyslan G. Bem 				if (ret) {
158903b2f08bSGeyslan G. Bem 					if (ret == 1)
15903650860bSJosef Bacik 						ret = 0;
1591e02119d5SChris Mason 					goto out;
15923650860bSJosef Bacik 				}
159334f3e4f2Sliubo 			}
159434f3e4f2Sliubo 
15950d836392SFilipe Manana 			/*
15960d836392SFilipe Manana 			 * If a reference item already exists for this inode
15970d836392SFilipe Manana 			 * with the same parent and name, but different index,
15980d836392SFilipe Manana 			 * drop it and the corresponding directory index entries
15990d836392SFilipe Manana 			 * from the parent before adding the new reference item
16000d836392SFilipe Manana 			 * and dir index entries, otherwise we would fail with
16010d836392SFilipe Manana 			 * -EEXIST returned from btrfs_add_link() below.
16020d836392SFilipe Manana 			 */
16030d836392SFilipe Manana 			ret = btrfs_inode_ref_exists(inode, dir, key->type,
16040d836392SFilipe Manana 						     name, namelen);
16050d836392SFilipe Manana 			if (ret > 0) {
16064467af88SFilipe Manana 				ret = btrfs_unlink_inode(trans,
16070d836392SFilipe Manana 							 BTRFS_I(dir),
16080d836392SFilipe Manana 							 BTRFS_I(inode),
16090d836392SFilipe Manana 							 name, namelen);
16100d836392SFilipe Manana 				/*
16110d836392SFilipe Manana 				 * If we dropped the link count to 0, bump it so
16120d836392SFilipe Manana 				 * that later the iput() on the inode will not
16130d836392SFilipe Manana 				 * free it. We will fixup the link count later.
16140d836392SFilipe Manana 				 */
16150d836392SFilipe Manana 				if (!ret && inode->i_nlink == 0)
16160d836392SFilipe Manana 					inc_nlink(inode);
16170d836392SFilipe Manana 			}
16180d836392SFilipe Manana 			if (ret < 0)
16190d836392SFilipe Manana 				goto out;
16200d836392SFilipe Manana 
1621e02119d5SChris Mason 			/* insert our name */
16226d9cc072SFilipe Manana 			ret = add_link(trans, dir, inode, name, namelen,
16236b5fc433SFilipe Manana 				       ref_index);
16243650860bSJosef Bacik 			if (ret)
16253650860bSJosef Bacik 				goto out;
1626e02119d5SChris Mason 
1627f96d4474SJosef Bacik 			ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1628f96d4474SJosef Bacik 			if (ret)
1629f96d4474SJosef Bacik 				goto out;
16305a1d7843SJan Schmidt 		}
163177a5b9e3SFilipe Manana 		/* Else, ret == 1, we already have a perfect match, we're done. */
1632e02119d5SChris Mason 
1633f186373fSMark Fasheh 		ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1634e02119d5SChris Mason 		kfree(name);
163503b2f08bSGeyslan G. Bem 		name = NULL;
1636f186373fSMark Fasheh 		if (log_ref_ver) {
1637f186373fSMark Fasheh 			iput(dir);
1638f186373fSMark Fasheh 			dir = NULL;
1639f186373fSMark Fasheh 		}
16405a1d7843SJan Schmidt 	}
1641e02119d5SChris Mason 
16421f250e92SFilipe Manana 	/*
16431f250e92SFilipe Manana 	 * Before we overwrite the inode reference item in the subvolume tree
16441f250e92SFilipe Manana 	 * with the item from the log tree, we must unlink all names from the
16451f250e92SFilipe Manana 	 * parent directory that are in the subvolume's tree inode reference
16461f250e92SFilipe Manana 	 * item, otherwise we end up with an inconsistent subvolume tree where
16471f250e92SFilipe Manana 	 * dir index entries exist for a name but there is no inode reference
16481f250e92SFilipe Manana 	 * item with the same name.
16491f250e92SFilipe Manana 	 */
16501f250e92SFilipe Manana 	ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
16511f250e92SFilipe Manana 				    key);
16521f250e92SFilipe Manana 	if (ret)
16531f250e92SFilipe Manana 		goto out;
16541f250e92SFilipe Manana 
1655e02119d5SChris Mason 	/* finally write the back reference in the inode */
1656e02119d5SChris Mason 	ret = overwrite_item(trans, root, path, eb, slot, key);
16575a1d7843SJan Schmidt out:
1658b3b4aa74SDavid Sterba 	btrfs_release_path(path);
165903b2f08bSGeyslan G. Bem 	kfree(name);
1660e02119d5SChris Mason 	iput(dir);
1661e02119d5SChris Mason 	iput(inode);
16623650860bSJosef Bacik 	return ret;
1663e02119d5SChris Mason }
1664e02119d5SChris Mason 
1665f186373fSMark Fasheh static int count_inode_extrefs(struct btrfs_root *root,
166636283658SNikolay Borisov 		struct btrfs_inode *inode, struct btrfs_path *path)
1667e02119d5SChris Mason {
1668f186373fSMark Fasheh 	int ret = 0;
1669f186373fSMark Fasheh 	int name_len;
1670f186373fSMark Fasheh 	unsigned int nlink = 0;
1671f186373fSMark Fasheh 	u32 item_size;
1672f186373fSMark Fasheh 	u32 cur_offset = 0;
167336283658SNikolay Borisov 	u64 inode_objectid = btrfs_ino(inode);
1674f186373fSMark Fasheh 	u64 offset = 0;
1675f186373fSMark Fasheh 	unsigned long ptr;
1676f186373fSMark Fasheh 	struct btrfs_inode_extref *extref;
1677f186373fSMark Fasheh 	struct extent_buffer *leaf;
1678f186373fSMark Fasheh 
1679f186373fSMark Fasheh 	while (1) {
1680f186373fSMark Fasheh 		ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1681f186373fSMark Fasheh 					    &extref, &offset);
1682f186373fSMark Fasheh 		if (ret)
1683f186373fSMark Fasheh 			break;
1684f186373fSMark Fasheh 
1685f186373fSMark Fasheh 		leaf = path->nodes[0];
16863212fa14SJosef Bacik 		item_size = btrfs_item_size(leaf, path->slots[0]);
1687f186373fSMark Fasheh 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
16882c2c452bSFilipe Manana 		cur_offset = 0;
1689f186373fSMark Fasheh 
1690f186373fSMark Fasheh 		while (cur_offset < item_size) {
1691f186373fSMark Fasheh 			extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1692f186373fSMark Fasheh 			name_len = btrfs_inode_extref_name_len(leaf, extref);
1693f186373fSMark Fasheh 
1694f186373fSMark Fasheh 			nlink++;
1695f186373fSMark Fasheh 
1696f186373fSMark Fasheh 			cur_offset += name_len + sizeof(*extref);
1697f186373fSMark Fasheh 		}
1698f186373fSMark Fasheh 
1699f186373fSMark Fasheh 		offset++;
1700f186373fSMark Fasheh 		btrfs_release_path(path);
1701f186373fSMark Fasheh 	}
1702f186373fSMark Fasheh 	btrfs_release_path(path);
1703f186373fSMark Fasheh 
17042c2c452bSFilipe Manana 	if (ret < 0 && ret != -ENOENT)
1705f186373fSMark Fasheh 		return ret;
1706f186373fSMark Fasheh 	return nlink;
1707f186373fSMark Fasheh }
1708f186373fSMark Fasheh 
1709f186373fSMark Fasheh static int count_inode_refs(struct btrfs_root *root,
1710f329e319SNikolay Borisov 			struct btrfs_inode *inode, struct btrfs_path *path)
1711f186373fSMark Fasheh {
1712e02119d5SChris Mason 	int ret;
1713e02119d5SChris Mason 	struct btrfs_key key;
1714f186373fSMark Fasheh 	unsigned int nlink = 0;
1715e02119d5SChris Mason 	unsigned long ptr;
1716e02119d5SChris Mason 	unsigned long ptr_end;
1717e02119d5SChris Mason 	int name_len;
1718f329e319SNikolay Borisov 	u64 ino = btrfs_ino(inode);
1719e02119d5SChris Mason 
172033345d01SLi Zefan 	key.objectid = ino;
1721e02119d5SChris Mason 	key.type = BTRFS_INODE_REF_KEY;
1722e02119d5SChris Mason 	key.offset = (u64)-1;
1723e02119d5SChris Mason 
1724e02119d5SChris Mason 	while (1) {
1725e02119d5SChris Mason 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1726e02119d5SChris Mason 		if (ret < 0)
1727e02119d5SChris Mason 			break;
1728e02119d5SChris Mason 		if (ret > 0) {
1729e02119d5SChris Mason 			if (path->slots[0] == 0)
1730e02119d5SChris Mason 				break;
1731e02119d5SChris Mason 			path->slots[0]--;
1732e02119d5SChris Mason 		}
1733e93ae26fSFilipe David Borba Manana process_slot:
1734e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &key,
1735e02119d5SChris Mason 				      path->slots[0]);
173633345d01SLi Zefan 		if (key.objectid != ino ||
1737e02119d5SChris Mason 		    key.type != BTRFS_INODE_REF_KEY)
1738e02119d5SChris Mason 			break;
1739e02119d5SChris Mason 		ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
17403212fa14SJosef Bacik 		ptr_end = ptr + btrfs_item_size(path->nodes[0],
1741e02119d5SChris Mason 						   path->slots[0]);
1742e02119d5SChris Mason 		while (ptr < ptr_end) {
1743e02119d5SChris Mason 			struct btrfs_inode_ref *ref;
1744e02119d5SChris Mason 
1745e02119d5SChris Mason 			ref = (struct btrfs_inode_ref *)ptr;
1746e02119d5SChris Mason 			name_len = btrfs_inode_ref_name_len(path->nodes[0],
1747e02119d5SChris Mason 							    ref);
1748e02119d5SChris Mason 			ptr = (unsigned long)(ref + 1) + name_len;
1749e02119d5SChris Mason 			nlink++;
1750e02119d5SChris Mason 		}
1751e02119d5SChris Mason 
1752e02119d5SChris Mason 		if (key.offset == 0)
1753e02119d5SChris Mason 			break;
1754e93ae26fSFilipe David Borba Manana 		if (path->slots[0] > 0) {
1755e93ae26fSFilipe David Borba Manana 			path->slots[0]--;
1756e93ae26fSFilipe David Borba Manana 			goto process_slot;
1757e93ae26fSFilipe David Borba Manana 		}
1758e02119d5SChris Mason 		key.offset--;
1759b3b4aa74SDavid Sterba 		btrfs_release_path(path);
1760e02119d5SChris Mason 	}
1761b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1762f186373fSMark Fasheh 
1763f186373fSMark Fasheh 	return nlink;
1764f186373fSMark Fasheh }
1765f186373fSMark Fasheh 
1766f186373fSMark Fasheh /*
1767f186373fSMark Fasheh  * There are a few corners where the link count of the file can't
1768f186373fSMark Fasheh  * be properly maintained during replay.  So, instead of adding
1769f186373fSMark Fasheh  * lots of complexity to the log code, we just scan the backrefs
1770f186373fSMark Fasheh  * for any file that has been through replay.
1771f186373fSMark Fasheh  *
1772f186373fSMark Fasheh  * The scan will update the link count on the inode to reflect the
1773f186373fSMark Fasheh  * number of back refs found.  If it goes down to zero, the iput
1774f186373fSMark Fasheh  * will free the inode.
1775f186373fSMark Fasheh  */
1776f186373fSMark Fasheh static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1777f186373fSMark Fasheh 					   struct btrfs_root *root,
1778f186373fSMark Fasheh 					   struct inode *inode)
1779f186373fSMark Fasheh {
1780f186373fSMark Fasheh 	struct btrfs_path *path;
1781f186373fSMark Fasheh 	int ret;
1782f186373fSMark Fasheh 	u64 nlink = 0;
17834a0cc7caSNikolay Borisov 	u64 ino = btrfs_ino(BTRFS_I(inode));
1784f186373fSMark Fasheh 
1785f186373fSMark Fasheh 	path = btrfs_alloc_path();
1786f186373fSMark Fasheh 	if (!path)
1787f186373fSMark Fasheh 		return -ENOMEM;
1788f186373fSMark Fasheh 
1789f329e319SNikolay Borisov 	ret = count_inode_refs(root, BTRFS_I(inode), path);
1790f186373fSMark Fasheh 	if (ret < 0)
1791f186373fSMark Fasheh 		goto out;
1792f186373fSMark Fasheh 
1793f186373fSMark Fasheh 	nlink = ret;
1794f186373fSMark Fasheh 
179536283658SNikolay Borisov 	ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1796f186373fSMark Fasheh 	if (ret < 0)
1797f186373fSMark Fasheh 		goto out;
1798f186373fSMark Fasheh 
1799f186373fSMark Fasheh 	nlink += ret;
1800f186373fSMark Fasheh 
1801f186373fSMark Fasheh 	ret = 0;
1802f186373fSMark Fasheh 
1803e02119d5SChris Mason 	if (nlink != inode->i_nlink) {
1804bfe86848SMiklos Szeredi 		set_nlink(inode, nlink);
1805f96d4474SJosef Bacik 		ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1806f96d4474SJosef Bacik 		if (ret)
1807f96d4474SJosef Bacik 			goto out;
1808e02119d5SChris Mason 	}
18098d5bf1cbSChris Mason 	BTRFS_I(inode)->index_cnt = (u64)-1;
1810e02119d5SChris Mason 
1811c71bf099SYan, Zheng 	if (inode->i_nlink == 0) {
1812c71bf099SYan, Zheng 		if (S_ISDIR(inode->i_mode)) {
181312fcfd22SChris Mason 			ret = replay_dir_deletes(trans, root, NULL, path,
181433345d01SLi Zefan 						 ino, 1);
18153650860bSJosef Bacik 			if (ret)
18163650860bSJosef Bacik 				goto out;
181712fcfd22SChris Mason 		}
1818ecdcf3c2SNikolay Borisov 		ret = btrfs_insert_orphan_item(trans, root, ino);
1819ecdcf3c2SNikolay Borisov 		if (ret == -EEXIST)
1820ecdcf3c2SNikolay Borisov 			ret = 0;
1821c71bf099SYan, Zheng 	}
182212fcfd22SChris Mason 
1823f186373fSMark Fasheh out:
1824f186373fSMark Fasheh 	btrfs_free_path(path);
1825f186373fSMark Fasheh 	return ret;
1826e02119d5SChris Mason }
1827e02119d5SChris Mason 
1828e02119d5SChris Mason static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1829e02119d5SChris Mason 					    struct btrfs_root *root,
1830e02119d5SChris Mason 					    struct btrfs_path *path)
1831e02119d5SChris Mason {
1832e02119d5SChris Mason 	int ret;
1833e02119d5SChris Mason 	struct btrfs_key key;
1834e02119d5SChris Mason 	struct inode *inode;
1835e02119d5SChris Mason 
1836e02119d5SChris Mason 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1837e02119d5SChris Mason 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1838e02119d5SChris Mason 	key.offset = (u64)-1;
1839e02119d5SChris Mason 	while (1) {
1840e02119d5SChris Mason 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1841e02119d5SChris Mason 		if (ret < 0)
1842e02119d5SChris Mason 			break;
1843e02119d5SChris Mason 
1844e02119d5SChris Mason 		if (ret == 1) {
1845011b28acSJosef Bacik 			ret = 0;
1846e02119d5SChris Mason 			if (path->slots[0] == 0)
1847e02119d5SChris Mason 				break;
1848e02119d5SChris Mason 			path->slots[0]--;
1849e02119d5SChris Mason 		}
1850e02119d5SChris Mason 
1851e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1852e02119d5SChris Mason 		if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1853e02119d5SChris Mason 		    key.type != BTRFS_ORPHAN_ITEM_KEY)
1854e02119d5SChris Mason 			break;
1855e02119d5SChris Mason 
1856e02119d5SChris Mason 		ret = btrfs_del_item(trans, root, path);
185765a246c5STsutomu Itoh 		if (ret)
1858011b28acSJosef Bacik 			break;
1859e02119d5SChris Mason 
1860b3b4aa74SDavid Sterba 		btrfs_release_path(path);
1861e02119d5SChris Mason 		inode = read_one_inode(root, key.offset);
1862011b28acSJosef Bacik 		if (!inode) {
1863011b28acSJosef Bacik 			ret = -EIO;
1864011b28acSJosef Bacik 			break;
1865011b28acSJosef Bacik 		}
1866e02119d5SChris Mason 
1867e02119d5SChris Mason 		ret = fixup_inode_link_count(trans, root, inode);
1868e02119d5SChris Mason 		iput(inode);
18693650860bSJosef Bacik 		if (ret)
1870011b28acSJosef Bacik 			break;
1871e02119d5SChris Mason 
187212fcfd22SChris Mason 		/*
187312fcfd22SChris Mason 		 * fixup on a directory may create new entries,
187412fcfd22SChris Mason 		 * make sure we always look for the highset possible
187512fcfd22SChris Mason 		 * offset
187612fcfd22SChris Mason 		 */
187712fcfd22SChris Mason 		key.offset = (u64)-1;
1878e02119d5SChris Mason 	}
1879b3b4aa74SDavid Sterba 	btrfs_release_path(path);
188065a246c5STsutomu Itoh 	return ret;
1881e02119d5SChris Mason }
1882e02119d5SChris Mason 
1883e02119d5SChris Mason 
1884e02119d5SChris Mason /*
1885e02119d5SChris Mason  * record a given inode in the fixup dir so we can check its link
1886e02119d5SChris Mason  * count when replay is done.  The link count is incremented here
1887e02119d5SChris Mason  * so the inode won't go away until we check it
1888e02119d5SChris Mason  */
1889e02119d5SChris Mason static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1890e02119d5SChris Mason 				      struct btrfs_root *root,
1891e02119d5SChris Mason 				      struct btrfs_path *path,
1892e02119d5SChris Mason 				      u64 objectid)
1893e02119d5SChris Mason {
1894e02119d5SChris Mason 	struct btrfs_key key;
1895e02119d5SChris Mason 	int ret = 0;
1896e02119d5SChris Mason 	struct inode *inode;
1897e02119d5SChris Mason 
1898e02119d5SChris Mason 	inode = read_one_inode(root, objectid);
1899c00e9493STsutomu Itoh 	if (!inode)
1900c00e9493STsutomu Itoh 		return -EIO;
1901e02119d5SChris Mason 
1902e02119d5SChris Mason 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1903962a298fSDavid Sterba 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1904e02119d5SChris Mason 	key.offset = objectid;
1905e02119d5SChris Mason 
1906e02119d5SChris Mason 	ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1907e02119d5SChris Mason 
1908b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1909e02119d5SChris Mason 	if (ret == 0) {
19109bf7a489SJosef Bacik 		if (!inode->i_nlink)
19119bf7a489SJosef Bacik 			set_nlink(inode, 1);
19129bf7a489SJosef Bacik 		else
19138b558c5fSZach Brown 			inc_nlink(inode);
19149a56fcd1SNikolay Borisov 		ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1915e02119d5SChris Mason 	} else if (ret == -EEXIST) {
1916e02119d5SChris Mason 		ret = 0;
1917e02119d5SChris Mason 	}
1918e02119d5SChris Mason 	iput(inode);
1919e02119d5SChris Mason 
1920e02119d5SChris Mason 	return ret;
1921e02119d5SChris Mason }
1922e02119d5SChris Mason 
1923e02119d5SChris Mason /*
1924e02119d5SChris Mason  * when replaying the log for a directory, we only insert names
1925e02119d5SChris Mason  * for inodes that actually exist.  This means an fsync on a directory
1926e02119d5SChris Mason  * does not implicitly fsync all the new files in it
1927e02119d5SChris Mason  */
1928e02119d5SChris Mason static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1929e02119d5SChris Mason 				    struct btrfs_root *root,
1930e02119d5SChris Mason 				    u64 dirid, u64 index,
193160d53eb3SZhaolei 				    char *name, int name_len,
1932e02119d5SChris Mason 				    struct btrfs_key *location)
1933e02119d5SChris Mason {
1934e02119d5SChris Mason 	struct inode *inode;
1935e02119d5SChris Mason 	struct inode *dir;
1936e02119d5SChris Mason 	int ret;
1937e02119d5SChris Mason 
1938e02119d5SChris Mason 	inode = read_one_inode(root, location->objectid);
1939e02119d5SChris Mason 	if (!inode)
1940e02119d5SChris Mason 		return -ENOENT;
1941e02119d5SChris Mason 
1942e02119d5SChris Mason 	dir = read_one_inode(root, dirid);
1943e02119d5SChris Mason 	if (!dir) {
1944e02119d5SChris Mason 		iput(inode);
1945e02119d5SChris Mason 		return -EIO;
1946e02119d5SChris Mason 	}
1947d555438bSJosef Bacik 
1948db0a669fSNikolay Borisov 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1949db0a669fSNikolay Borisov 			name_len, 1, index);
1950e02119d5SChris Mason 
1951e02119d5SChris Mason 	/* FIXME, put inode into FIXUP list */
1952e02119d5SChris Mason 
1953e02119d5SChris Mason 	iput(inode);
1954e02119d5SChris Mason 	iput(dir);
1955e02119d5SChris Mason 	return ret;
1956e02119d5SChris Mason }
1957e02119d5SChris Mason 
1958339d0354SFilipe Manana static int delete_conflicting_dir_entry(struct btrfs_trans_handle *trans,
1959339d0354SFilipe Manana 					struct btrfs_inode *dir,
1960339d0354SFilipe Manana 					struct btrfs_path *path,
1961339d0354SFilipe Manana 					struct btrfs_dir_item *dst_di,
1962339d0354SFilipe Manana 					const struct btrfs_key *log_key,
1963339d0354SFilipe Manana 					u8 log_type,
1964339d0354SFilipe Manana 					bool exists)
1965339d0354SFilipe Manana {
1966339d0354SFilipe Manana 	struct btrfs_key found_key;
1967339d0354SFilipe Manana 
1968339d0354SFilipe Manana 	btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1969339d0354SFilipe Manana 	/* The existing dentry points to the same inode, don't delete it. */
1970339d0354SFilipe Manana 	if (found_key.objectid == log_key->objectid &&
1971339d0354SFilipe Manana 	    found_key.type == log_key->type &&
1972339d0354SFilipe Manana 	    found_key.offset == log_key->offset &&
1973339d0354SFilipe Manana 	    btrfs_dir_type(path->nodes[0], dst_di) == log_type)
1974339d0354SFilipe Manana 		return 1;
1975339d0354SFilipe Manana 
1976339d0354SFilipe Manana 	/*
1977339d0354SFilipe Manana 	 * Don't drop the conflicting directory entry if the inode for the new
1978339d0354SFilipe Manana 	 * entry doesn't exist.
1979339d0354SFilipe Manana 	 */
1980339d0354SFilipe Manana 	if (!exists)
1981339d0354SFilipe Manana 		return 0;
1982339d0354SFilipe Manana 
1983339d0354SFilipe Manana 	return drop_one_dir_item(trans, path, dir, dst_di);
1984339d0354SFilipe Manana }
1985339d0354SFilipe Manana 
1986e02119d5SChris Mason /*
1987e02119d5SChris Mason  * take a single entry in a log directory item and replay it into
1988e02119d5SChris Mason  * the subvolume.
1989e02119d5SChris Mason  *
1990e02119d5SChris Mason  * if a conflicting item exists in the subdirectory already,
1991e02119d5SChris Mason  * the inode it points to is unlinked and put into the link count
1992e02119d5SChris Mason  * fix up tree.
1993e02119d5SChris Mason  *
1994e02119d5SChris Mason  * If a name from the log points to a file or directory that does
1995e02119d5SChris Mason  * not exist in the FS, it is skipped.  fsyncs on directories
1996e02119d5SChris Mason  * do not force down inodes inside that directory, just changes to the
1997e02119d5SChris Mason  * names or unlinks in a directory.
1998bb53eda9SFilipe Manana  *
1999bb53eda9SFilipe Manana  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
2000bb53eda9SFilipe Manana  * non-existing inode) and 1 if the name was replayed.
2001e02119d5SChris Mason  */
2002e02119d5SChris Mason static noinline int replay_one_name(struct btrfs_trans_handle *trans,
2003e02119d5SChris Mason 				    struct btrfs_root *root,
2004e02119d5SChris Mason 				    struct btrfs_path *path,
2005e02119d5SChris Mason 				    struct extent_buffer *eb,
2006e02119d5SChris Mason 				    struct btrfs_dir_item *di,
2007e02119d5SChris Mason 				    struct btrfs_key *key)
2008e02119d5SChris Mason {
2009e02119d5SChris Mason 	char *name;
2010e02119d5SChris Mason 	int name_len;
2011339d0354SFilipe Manana 	struct btrfs_dir_item *dir_dst_di;
2012339d0354SFilipe Manana 	struct btrfs_dir_item *index_dst_di;
2013339d0354SFilipe Manana 	bool dir_dst_matches = false;
2014339d0354SFilipe Manana 	bool index_dst_matches = false;
2015e02119d5SChris Mason 	struct btrfs_key log_key;
2016339d0354SFilipe Manana 	struct btrfs_key search_key;
2017e02119d5SChris Mason 	struct inode *dir;
2018e02119d5SChris Mason 	u8 log_type;
2019cfd31269SFilipe Manana 	bool exists;
2020cfd31269SFilipe Manana 	int ret;
2021339d0354SFilipe Manana 	bool update_size = true;
2022bb53eda9SFilipe Manana 	bool name_added = false;
2023e02119d5SChris Mason 
2024e02119d5SChris Mason 	dir = read_one_inode(root, key->objectid);
2025c00e9493STsutomu Itoh 	if (!dir)
2026c00e9493STsutomu Itoh 		return -EIO;
2027e02119d5SChris Mason 
2028e02119d5SChris Mason 	name_len = btrfs_dir_name_len(eb, di);
2029e02119d5SChris Mason 	name = kmalloc(name_len, GFP_NOFS);
20302bac325eSFilipe David Borba Manana 	if (!name) {
20312bac325eSFilipe David Borba Manana 		ret = -ENOMEM;
20322bac325eSFilipe David Borba Manana 		goto out;
20332bac325eSFilipe David Borba Manana 	}
20342a29edc6Sliubo 
2035e02119d5SChris Mason 	log_type = btrfs_dir_type(eb, di);
2036e02119d5SChris Mason 	read_extent_buffer(eb, name, (unsigned long)(di + 1),
2037e02119d5SChris Mason 		   name_len);
2038e02119d5SChris Mason 
2039e02119d5SChris Mason 	btrfs_dir_item_key_to_cpu(eb, di, &log_key);
2040cfd31269SFilipe Manana 	ret = btrfs_lookup_inode(trans, root, path, &log_key, 0);
2041b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2042cfd31269SFilipe Manana 	if (ret < 0)
2043cfd31269SFilipe Manana 		goto out;
2044cfd31269SFilipe Manana 	exists = (ret == 0);
2045cfd31269SFilipe Manana 	ret = 0;
20464bef0848SChris Mason 
2047339d0354SFilipe Manana 	dir_dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
2048e02119d5SChris Mason 					   name, name_len, 1);
2049339d0354SFilipe Manana 	if (IS_ERR(dir_dst_di)) {
2050339d0354SFilipe Manana 		ret = PTR_ERR(dir_dst_di);
20513650860bSJosef Bacik 		goto out;
2052339d0354SFilipe Manana 	} else if (dir_dst_di) {
2053339d0354SFilipe Manana 		ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
2054339d0354SFilipe Manana 						   dir_dst_di, &log_key, log_type,
2055339d0354SFilipe Manana 						   exists);
2056339d0354SFilipe Manana 		if (ret < 0)
2057339d0354SFilipe Manana 			goto out;
2058339d0354SFilipe Manana 		dir_dst_matches = (ret == 1);
2059e02119d5SChris Mason 	}
2060e15ac641SFilipe Manana 
2061339d0354SFilipe Manana 	btrfs_release_path(path);
2062339d0354SFilipe Manana 
2063339d0354SFilipe Manana 	index_dst_di = btrfs_lookup_dir_index_item(trans, root, path,
2064339d0354SFilipe Manana 						   key->objectid, key->offset,
2065339d0354SFilipe Manana 						   name, name_len, 1);
2066339d0354SFilipe Manana 	if (IS_ERR(index_dst_di)) {
2067339d0354SFilipe Manana 		ret = PTR_ERR(index_dst_di);
2068e15ac641SFilipe Manana 		goto out;
2069339d0354SFilipe Manana 	} else if (index_dst_di) {
2070339d0354SFilipe Manana 		ret = delete_conflicting_dir_entry(trans, BTRFS_I(dir), path,
2071339d0354SFilipe Manana 						   index_dst_di, &log_key,
2072339d0354SFilipe Manana 						   log_type, exists);
2073339d0354SFilipe Manana 		if (ret < 0)
2074e02119d5SChris Mason 			goto out;
2075339d0354SFilipe Manana 		index_dst_matches = (ret == 1);
2076e02119d5SChris Mason 	}
2077e02119d5SChris Mason 
2078339d0354SFilipe Manana 	btrfs_release_path(path);
2079339d0354SFilipe Manana 
2080339d0354SFilipe Manana 	if (dir_dst_matches && index_dst_matches) {
2081339d0354SFilipe Manana 		ret = 0;
2082a2cc11dbSFilipe Manana 		update_size = false;
2083e02119d5SChris Mason 		goto out;
2084e02119d5SChris Mason 	}
2085e02119d5SChris Mason 
2086e02119d5SChris Mason 	/*
2087725af92aSNikolay Borisov 	 * Check if the inode reference exists in the log for the given name,
2088725af92aSNikolay Borisov 	 * inode and parent inode
2089725af92aSNikolay Borisov 	 */
2090339d0354SFilipe Manana 	search_key.objectid = log_key.objectid;
2091339d0354SFilipe Manana 	search_key.type = BTRFS_INODE_REF_KEY;
2092339d0354SFilipe Manana 	search_key.offset = key->objectid;
2093339d0354SFilipe Manana 	ret = backref_in_log(root->log_root, &search_key, 0, name, name_len);
2094725af92aSNikolay Borisov 	if (ret < 0) {
2095725af92aSNikolay Borisov 	        goto out;
2096725af92aSNikolay Borisov 	} else if (ret) {
2097725af92aSNikolay Borisov 	        /* The dentry will be added later. */
2098725af92aSNikolay Borisov 	        ret = 0;
2099725af92aSNikolay Borisov 	        update_size = false;
2100725af92aSNikolay Borisov 	        goto out;
2101725af92aSNikolay Borisov 	}
2102725af92aSNikolay Borisov 
2103339d0354SFilipe Manana 	search_key.objectid = log_key.objectid;
2104339d0354SFilipe Manana 	search_key.type = BTRFS_INODE_EXTREF_KEY;
2105339d0354SFilipe Manana 	search_key.offset = key->objectid;
2106339d0354SFilipe Manana 	ret = backref_in_log(root->log_root, &search_key, key->objectid, name,
2107725af92aSNikolay Borisov 			     name_len);
2108725af92aSNikolay Borisov 	if (ret < 0) {
2109725af92aSNikolay Borisov 		goto out;
2110725af92aSNikolay Borisov 	} else if (ret) {
2111df8d116fSFilipe Manana 		/* The dentry will be added later. */
2112df8d116fSFilipe Manana 		ret = 0;
2113df8d116fSFilipe Manana 		update_size = false;
2114df8d116fSFilipe Manana 		goto out;
2115df8d116fSFilipe Manana 	}
2116b3b4aa74SDavid Sterba 	btrfs_release_path(path);
211760d53eb3SZhaolei 	ret = insert_one_name(trans, root, key->objectid, key->offset,
211860d53eb3SZhaolei 			      name, name_len, &log_key);
2119df8d116fSFilipe Manana 	if (ret && ret != -ENOENT && ret != -EEXIST)
21203650860bSJosef Bacik 		goto out;
2121bb53eda9SFilipe Manana 	if (!ret)
2122bb53eda9SFilipe Manana 		name_added = true;
2123d555438bSJosef Bacik 	update_size = false;
21243650860bSJosef Bacik 	ret = 0;
2125339d0354SFilipe Manana 
2126339d0354SFilipe Manana out:
2127339d0354SFilipe Manana 	if (!ret && update_size) {
2128339d0354SFilipe Manana 		btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
2129339d0354SFilipe Manana 		ret = btrfs_update_inode(trans, root, BTRFS_I(dir));
2130339d0354SFilipe Manana 	}
2131339d0354SFilipe Manana 	kfree(name);
2132339d0354SFilipe Manana 	iput(dir);
2133339d0354SFilipe Manana 	if (!ret && name_added)
2134339d0354SFilipe Manana 		ret = 1;
2135339d0354SFilipe Manana 	return ret;
2136e02119d5SChris Mason }
2137e02119d5SChris Mason 
2138339d0354SFilipe Manana /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
2139e02119d5SChris Mason static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
2140e02119d5SChris Mason 					struct btrfs_root *root,
2141e02119d5SChris Mason 					struct btrfs_path *path,
2142e02119d5SChris Mason 					struct extent_buffer *eb, int slot,
2143e02119d5SChris Mason 					struct btrfs_key *key)
2144e02119d5SChris Mason {
2145339d0354SFilipe Manana 	int ret;
2146e02119d5SChris Mason 	struct btrfs_dir_item *di;
2147e02119d5SChris Mason 
2148339d0354SFilipe Manana 	/* We only log dir index keys, which only contain a single dir item. */
2149339d0354SFilipe Manana 	ASSERT(key->type == BTRFS_DIR_INDEX_KEY);
2150339d0354SFilipe Manana 
2151339d0354SFilipe Manana 	di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2152e02119d5SChris Mason 	ret = replay_one_name(trans, root, path, eb, di, key);
2153bb53eda9SFilipe Manana 	if (ret < 0)
2154339d0354SFilipe Manana 		return ret;
2155bb53eda9SFilipe Manana 
2156bb53eda9SFilipe Manana 	/*
2157339d0354SFilipe Manana 	 * If this entry refers to a non-directory (directories can not have a
2158339d0354SFilipe Manana 	 * link count > 1) and it was added in the transaction that was not
2159339d0354SFilipe Manana 	 * committed, make sure we fixup the link count of the inode the entry
2160339d0354SFilipe Manana 	 * points to. Otherwise something like the following would result in a
2161339d0354SFilipe Manana 	 * directory pointing to an inode with a wrong link that does not account
2162339d0354SFilipe Manana 	 * for this dir entry:
2163bb53eda9SFilipe Manana 	 *
2164bb53eda9SFilipe Manana 	 * mkdir testdir
2165bb53eda9SFilipe Manana 	 * touch testdir/foo
2166bb53eda9SFilipe Manana 	 * touch testdir/bar
2167bb53eda9SFilipe Manana 	 * sync
2168bb53eda9SFilipe Manana 	 *
2169bb53eda9SFilipe Manana 	 * ln testdir/bar testdir/bar_link
2170bb53eda9SFilipe Manana 	 * ln testdir/foo testdir/foo_link
2171bb53eda9SFilipe Manana 	 * xfs_io -c "fsync" testdir/bar
2172bb53eda9SFilipe Manana 	 *
2173bb53eda9SFilipe Manana 	 * <power failure>
2174bb53eda9SFilipe Manana 	 *
2175bb53eda9SFilipe Manana 	 * mount fs, log replay happens
2176bb53eda9SFilipe Manana 	 *
2177339d0354SFilipe Manana 	 * File foo would remain with a link count of 1 when it has two entries
2178339d0354SFilipe Manana 	 * pointing to it in the directory testdir. This would make it impossible
2179339d0354SFilipe Manana 	 * to ever delete the parent directory has it would result in stale
2180339d0354SFilipe Manana 	 * dentries that can never be deleted.
2181bb53eda9SFilipe Manana 	 */
2182bb53eda9SFilipe Manana 	if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
2183339d0354SFilipe Manana 		struct btrfs_path *fixup_path;
2184bb53eda9SFilipe Manana 		struct btrfs_key di_key;
2185bb53eda9SFilipe Manana 
2186bb53eda9SFilipe Manana 		fixup_path = btrfs_alloc_path();
2187339d0354SFilipe Manana 		if (!fixup_path)
2188339d0354SFilipe Manana 			return -ENOMEM;
2189bb53eda9SFilipe Manana 
2190bb53eda9SFilipe Manana 		btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2191339d0354SFilipe Manana 		ret = link_to_fixup_dir(trans, root, fixup_path, di_key.objectid);
2192bb53eda9SFilipe Manana 		btrfs_free_path(fixup_path);
2193339d0354SFilipe Manana 	}
2194339d0354SFilipe Manana 
2195bb53eda9SFilipe Manana 	return ret;
2196e02119d5SChris Mason }
2197e02119d5SChris Mason 
2198e02119d5SChris Mason /*
2199e02119d5SChris Mason  * directory replay has two parts.  There are the standard directory
2200e02119d5SChris Mason  * items in the log copied from the subvolume, and range items
2201e02119d5SChris Mason  * created in the log while the subvolume was logged.
2202e02119d5SChris Mason  *
2203e02119d5SChris Mason  * The range items tell us which parts of the key space the log
2204e02119d5SChris Mason  * is authoritative for.  During replay, if a key in the subvolume
2205e02119d5SChris Mason  * directory is in a logged range item, but not actually in the log
2206e02119d5SChris Mason  * that means it was deleted from the directory before the fsync
2207e02119d5SChris Mason  * and should be removed.
2208e02119d5SChris Mason  */
2209e02119d5SChris Mason static noinline int find_dir_range(struct btrfs_root *root,
2210e02119d5SChris Mason 				   struct btrfs_path *path,
2211ccae4a19SFilipe Manana 				   u64 dirid,
2212e02119d5SChris Mason 				   u64 *start_ret, u64 *end_ret)
2213e02119d5SChris Mason {
2214e02119d5SChris Mason 	struct btrfs_key key;
2215e02119d5SChris Mason 	u64 found_end;
2216e02119d5SChris Mason 	struct btrfs_dir_log_item *item;
2217e02119d5SChris Mason 	int ret;
2218e02119d5SChris Mason 	int nritems;
2219e02119d5SChris Mason 
2220e02119d5SChris Mason 	if (*start_ret == (u64)-1)
2221e02119d5SChris Mason 		return 1;
2222e02119d5SChris Mason 
2223e02119d5SChris Mason 	key.objectid = dirid;
2224ccae4a19SFilipe Manana 	key.type = BTRFS_DIR_LOG_INDEX_KEY;
2225e02119d5SChris Mason 	key.offset = *start_ret;
2226e02119d5SChris Mason 
2227e02119d5SChris Mason 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2228e02119d5SChris Mason 	if (ret < 0)
2229e02119d5SChris Mason 		goto out;
2230e02119d5SChris Mason 	if (ret > 0) {
2231e02119d5SChris Mason 		if (path->slots[0] == 0)
2232e02119d5SChris Mason 			goto out;
2233e02119d5SChris Mason 		path->slots[0]--;
2234e02119d5SChris Mason 	}
2235e02119d5SChris Mason 	if (ret != 0)
2236e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2237e02119d5SChris Mason 
2238ccae4a19SFilipe Manana 	if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2239e02119d5SChris Mason 		ret = 1;
2240e02119d5SChris Mason 		goto next;
2241e02119d5SChris Mason 	}
2242e02119d5SChris Mason 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2243e02119d5SChris Mason 			      struct btrfs_dir_log_item);
2244e02119d5SChris Mason 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2245e02119d5SChris Mason 
2246e02119d5SChris Mason 	if (*start_ret >= key.offset && *start_ret <= found_end) {
2247e02119d5SChris Mason 		ret = 0;
2248e02119d5SChris Mason 		*start_ret = key.offset;
2249e02119d5SChris Mason 		*end_ret = found_end;
2250e02119d5SChris Mason 		goto out;
2251e02119d5SChris Mason 	}
2252e02119d5SChris Mason 	ret = 1;
2253e02119d5SChris Mason next:
2254e02119d5SChris Mason 	/* check the next slot in the tree to see if it is a valid item */
2255e02119d5SChris Mason 	nritems = btrfs_header_nritems(path->nodes[0]);
22562a7bf53fSRobbie Ko 	path->slots[0]++;
2257e02119d5SChris Mason 	if (path->slots[0] >= nritems) {
2258e02119d5SChris Mason 		ret = btrfs_next_leaf(root, path);
2259e02119d5SChris Mason 		if (ret)
2260e02119d5SChris Mason 			goto out;
2261e02119d5SChris Mason 	}
2262e02119d5SChris Mason 
2263e02119d5SChris Mason 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2264e02119d5SChris Mason 
2265ccae4a19SFilipe Manana 	if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2266e02119d5SChris Mason 		ret = 1;
2267e02119d5SChris Mason 		goto out;
2268e02119d5SChris Mason 	}
2269e02119d5SChris Mason 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2270e02119d5SChris Mason 			      struct btrfs_dir_log_item);
2271e02119d5SChris Mason 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2272e02119d5SChris Mason 	*start_ret = key.offset;
2273e02119d5SChris Mason 	*end_ret = found_end;
2274e02119d5SChris Mason 	ret = 0;
2275e02119d5SChris Mason out:
2276b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2277e02119d5SChris Mason 	return ret;
2278e02119d5SChris Mason }
2279e02119d5SChris Mason 
2280e02119d5SChris Mason /*
2281e02119d5SChris Mason  * this looks for a given directory item in the log.  If the directory
2282e02119d5SChris Mason  * item is not in the log, the item is removed and the inode it points
2283e02119d5SChris Mason  * to is unlinked
2284e02119d5SChris Mason  */
2285e02119d5SChris Mason static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2286e02119d5SChris Mason 				      struct btrfs_root *log,
2287e02119d5SChris Mason 				      struct btrfs_path *path,
2288e02119d5SChris Mason 				      struct btrfs_path *log_path,
2289e02119d5SChris Mason 				      struct inode *dir,
2290e02119d5SChris Mason 				      struct btrfs_key *dir_key)
2291e02119d5SChris Mason {
2292d1ed82f3SFilipe Manana 	struct btrfs_root *root = BTRFS_I(dir)->root;
2293e02119d5SChris Mason 	int ret;
2294e02119d5SChris Mason 	struct extent_buffer *eb;
2295e02119d5SChris Mason 	int slot;
2296e02119d5SChris Mason 	struct btrfs_dir_item *di;
2297e02119d5SChris Mason 	int name_len;
2298e02119d5SChris Mason 	char *name;
2299ccae4a19SFilipe Manana 	struct inode *inode = NULL;
2300e02119d5SChris Mason 	struct btrfs_key location;
2301e02119d5SChris Mason 
2302ccae4a19SFilipe Manana 	/*
2303ccae4a19SFilipe Manana 	 * Currenly we only log dir index keys. Even if we replay a log created
2304ccae4a19SFilipe Manana 	 * by an older kernel that logged both dir index and dir item keys, all
2305ccae4a19SFilipe Manana 	 * we need to do is process the dir index keys, we (and our caller) can
2306ccae4a19SFilipe Manana 	 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2307ccae4a19SFilipe Manana 	 */
2308ccae4a19SFilipe Manana 	ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY);
2309ccae4a19SFilipe Manana 
2310e02119d5SChris Mason 	eb = path->nodes[0];
2311e02119d5SChris Mason 	slot = path->slots[0];
2312ccae4a19SFilipe Manana 	di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2313e02119d5SChris Mason 	name_len = btrfs_dir_name_len(eb, di);
2314e02119d5SChris Mason 	name = kmalloc(name_len, GFP_NOFS);
2315e02119d5SChris Mason 	if (!name) {
2316e02119d5SChris Mason 		ret = -ENOMEM;
2317e02119d5SChris Mason 		goto out;
2318e02119d5SChris Mason 	}
2319ccae4a19SFilipe Manana 
2320ccae4a19SFilipe Manana 	read_extent_buffer(eb, name, (unsigned long)(di + 1), name_len);
2321ccae4a19SFilipe Manana 
2322ccae4a19SFilipe Manana 	if (log) {
2323ccae4a19SFilipe Manana 		struct btrfs_dir_item *log_di;
2324ccae4a19SFilipe Manana 
2325ccae4a19SFilipe Manana 		log_di = btrfs_lookup_dir_index_item(trans, log, log_path,
2326e02119d5SChris Mason 						     dir_key->objectid,
2327e02119d5SChris Mason 						     dir_key->offset,
2328e02119d5SChris Mason 						     name, name_len, 0);
2329ccae4a19SFilipe Manana 		if (IS_ERR(log_di)) {
2330ccae4a19SFilipe Manana 			ret = PTR_ERR(log_di);
2331ccae4a19SFilipe Manana 			goto out;
2332ccae4a19SFilipe Manana 		} else if (log_di) {
2333ccae4a19SFilipe Manana 			/* The dentry exists in the log, we have nothing to do. */
2334ccae4a19SFilipe Manana 			ret = 0;
2335ccae4a19SFilipe Manana 			goto out;
2336e02119d5SChris Mason 		}
2337ccae4a19SFilipe Manana 	}
2338ccae4a19SFilipe Manana 
2339e02119d5SChris Mason 	btrfs_dir_item_key_to_cpu(eb, di, &location);
2340b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2341b3b4aa74SDavid Sterba 	btrfs_release_path(log_path);
2342e02119d5SChris Mason 	inode = read_one_inode(root, location.objectid);
2343c00e9493STsutomu Itoh 	if (!inode) {
2344ccae4a19SFilipe Manana 		ret = -EIO;
23453650860bSJosef Bacik 		goto out;
23463650860bSJosef Bacik 	}
23473650860bSJosef Bacik 
2348ccae4a19SFilipe Manana 	ret = link_to_fixup_dir(trans, root, path, location.objectid);
23493650860bSJosef Bacik 	if (ret)
23503650860bSJosef Bacik 		goto out;
2351e02119d5SChris Mason 
2352ccae4a19SFilipe Manana 	inc_nlink(inode);
2353ccae4a19SFilipe Manana 	ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(inode), name,
2354ccae4a19SFilipe Manana 				 name_len);
2355ccae4a19SFilipe Manana 	if (ret)
2356e02119d5SChris Mason 		goto out;
2357e02119d5SChris Mason 
2358ccae4a19SFilipe Manana 	ret = btrfs_run_delayed_items(trans);
2359ccae4a19SFilipe Manana 	if (ret)
2360ccae4a19SFilipe Manana 		goto out;
2361ccae4a19SFilipe Manana 
2362ccae4a19SFilipe Manana 	/*
2363ccae4a19SFilipe Manana 	 * Unlike dir item keys, dir index keys can only have one name (entry) in
2364ccae4a19SFilipe Manana 	 * them, as there are no key collisions since each key has a unique offset
2365ccae4a19SFilipe Manana 	 * (an index number), so we're done.
2366ccae4a19SFilipe Manana 	 */
2367e02119d5SChris Mason out:
2368b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2369b3b4aa74SDavid Sterba 	btrfs_release_path(log_path);
2370ccae4a19SFilipe Manana 	kfree(name);
2371ccae4a19SFilipe Manana 	iput(inode);
2372e02119d5SChris Mason 	return ret;
2373e02119d5SChris Mason }
2374e02119d5SChris Mason 
23754f764e51SFilipe Manana static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
23764f764e51SFilipe Manana 			      struct btrfs_root *root,
23774f764e51SFilipe Manana 			      struct btrfs_root *log,
23784f764e51SFilipe Manana 			      struct btrfs_path *path,
23794f764e51SFilipe Manana 			      const u64 ino)
23804f764e51SFilipe Manana {
23814f764e51SFilipe Manana 	struct btrfs_key search_key;
23824f764e51SFilipe Manana 	struct btrfs_path *log_path;
23834f764e51SFilipe Manana 	int i;
23844f764e51SFilipe Manana 	int nritems;
23854f764e51SFilipe Manana 	int ret;
23864f764e51SFilipe Manana 
23874f764e51SFilipe Manana 	log_path = btrfs_alloc_path();
23884f764e51SFilipe Manana 	if (!log_path)
23894f764e51SFilipe Manana 		return -ENOMEM;
23904f764e51SFilipe Manana 
23914f764e51SFilipe Manana 	search_key.objectid = ino;
23924f764e51SFilipe Manana 	search_key.type = BTRFS_XATTR_ITEM_KEY;
23934f764e51SFilipe Manana 	search_key.offset = 0;
23944f764e51SFilipe Manana again:
23954f764e51SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
23964f764e51SFilipe Manana 	if (ret < 0)
23974f764e51SFilipe Manana 		goto out;
23984f764e51SFilipe Manana process_leaf:
23994f764e51SFilipe Manana 	nritems = btrfs_header_nritems(path->nodes[0]);
24004f764e51SFilipe Manana 	for (i = path->slots[0]; i < nritems; i++) {
24014f764e51SFilipe Manana 		struct btrfs_key key;
24024f764e51SFilipe Manana 		struct btrfs_dir_item *di;
24034f764e51SFilipe Manana 		struct btrfs_dir_item *log_di;
24044f764e51SFilipe Manana 		u32 total_size;
24054f764e51SFilipe Manana 		u32 cur;
24064f764e51SFilipe Manana 
24074f764e51SFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &key, i);
24084f764e51SFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
24094f764e51SFilipe Manana 			ret = 0;
24104f764e51SFilipe Manana 			goto out;
24114f764e51SFilipe Manana 		}
24124f764e51SFilipe Manana 
24134f764e51SFilipe Manana 		di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
24143212fa14SJosef Bacik 		total_size = btrfs_item_size(path->nodes[0], i);
24154f764e51SFilipe Manana 		cur = 0;
24164f764e51SFilipe Manana 		while (cur < total_size) {
24174f764e51SFilipe Manana 			u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
24184f764e51SFilipe Manana 			u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
24194f764e51SFilipe Manana 			u32 this_len = sizeof(*di) + name_len + data_len;
24204f764e51SFilipe Manana 			char *name;
24214f764e51SFilipe Manana 
24224f764e51SFilipe Manana 			name = kmalloc(name_len, GFP_NOFS);
24234f764e51SFilipe Manana 			if (!name) {
24244f764e51SFilipe Manana 				ret = -ENOMEM;
24254f764e51SFilipe Manana 				goto out;
24264f764e51SFilipe Manana 			}
24274f764e51SFilipe Manana 			read_extent_buffer(path->nodes[0], name,
24284f764e51SFilipe Manana 					   (unsigned long)(di + 1), name_len);
24294f764e51SFilipe Manana 
24304f764e51SFilipe Manana 			log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
24314f764e51SFilipe Manana 						    name, name_len, 0);
24324f764e51SFilipe Manana 			btrfs_release_path(log_path);
24334f764e51SFilipe Manana 			if (!log_di) {
24344f764e51SFilipe Manana 				/* Doesn't exist in log tree, so delete it. */
24354f764e51SFilipe Manana 				btrfs_release_path(path);
24364f764e51SFilipe Manana 				di = btrfs_lookup_xattr(trans, root, path, ino,
24374f764e51SFilipe Manana 							name, name_len, -1);
24384f764e51SFilipe Manana 				kfree(name);
24394f764e51SFilipe Manana 				if (IS_ERR(di)) {
24404f764e51SFilipe Manana 					ret = PTR_ERR(di);
24414f764e51SFilipe Manana 					goto out;
24424f764e51SFilipe Manana 				}
24434f764e51SFilipe Manana 				ASSERT(di);
24444f764e51SFilipe Manana 				ret = btrfs_delete_one_dir_name(trans, root,
24454f764e51SFilipe Manana 								path, di);
24464f764e51SFilipe Manana 				if (ret)
24474f764e51SFilipe Manana 					goto out;
24484f764e51SFilipe Manana 				btrfs_release_path(path);
24494f764e51SFilipe Manana 				search_key = key;
24504f764e51SFilipe Manana 				goto again;
24514f764e51SFilipe Manana 			}
24524f764e51SFilipe Manana 			kfree(name);
24534f764e51SFilipe Manana 			if (IS_ERR(log_di)) {
24544f764e51SFilipe Manana 				ret = PTR_ERR(log_di);
24554f764e51SFilipe Manana 				goto out;
24564f764e51SFilipe Manana 			}
24574f764e51SFilipe Manana 			cur += this_len;
24584f764e51SFilipe Manana 			di = (struct btrfs_dir_item *)((char *)di + this_len);
24594f764e51SFilipe Manana 		}
24604f764e51SFilipe Manana 	}
24614f764e51SFilipe Manana 	ret = btrfs_next_leaf(root, path);
24624f764e51SFilipe Manana 	if (ret > 0)
24634f764e51SFilipe Manana 		ret = 0;
24644f764e51SFilipe Manana 	else if (ret == 0)
24654f764e51SFilipe Manana 		goto process_leaf;
24664f764e51SFilipe Manana out:
24674f764e51SFilipe Manana 	btrfs_free_path(log_path);
24684f764e51SFilipe Manana 	btrfs_release_path(path);
24694f764e51SFilipe Manana 	return ret;
24704f764e51SFilipe Manana }
24714f764e51SFilipe Manana 
24724f764e51SFilipe Manana 
2473e02119d5SChris Mason /*
2474e02119d5SChris Mason  * deletion replay happens before we copy any new directory items
2475e02119d5SChris Mason  * out of the log or out of backreferences from inodes.  It
2476e02119d5SChris Mason  * scans the log to find ranges of keys that log is authoritative for,
2477e02119d5SChris Mason  * and then scans the directory to find items in those ranges that are
2478e02119d5SChris Mason  * not present in the log.
2479e02119d5SChris Mason  *
2480e02119d5SChris Mason  * Anything we don't find in the log is unlinked and removed from the
2481e02119d5SChris Mason  * directory.
2482e02119d5SChris Mason  */
2483e02119d5SChris Mason static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2484e02119d5SChris Mason 				       struct btrfs_root *root,
2485e02119d5SChris Mason 				       struct btrfs_root *log,
2486e02119d5SChris Mason 				       struct btrfs_path *path,
248712fcfd22SChris Mason 				       u64 dirid, int del_all)
2488e02119d5SChris Mason {
2489e02119d5SChris Mason 	u64 range_start;
2490e02119d5SChris Mason 	u64 range_end;
2491e02119d5SChris Mason 	int ret = 0;
2492e02119d5SChris Mason 	struct btrfs_key dir_key;
2493e02119d5SChris Mason 	struct btrfs_key found_key;
2494e02119d5SChris Mason 	struct btrfs_path *log_path;
2495e02119d5SChris Mason 	struct inode *dir;
2496e02119d5SChris Mason 
2497e02119d5SChris Mason 	dir_key.objectid = dirid;
2498ccae4a19SFilipe Manana 	dir_key.type = BTRFS_DIR_INDEX_KEY;
2499e02119d5SChris Mason 	log_path = btrfs_alloc_path();
2500e02119d5SChris Mason 	if (!log_path)
2501e02119d5SChris Mason 		return -ENOMEM;
2502e02119d5SChris Mason 
2503e02119d5SChris Mason 	dir = read_one_inode(root, dirid);
2504e02119d5SChris Mason 	/* it isn't an error if the inode isn't there, that can happen
2505e02119d5SChris Mason 	 * because we replay the deletes before we copy in the inode item
2506e02119d5SChris Mason 	 * from the log
2507e02119d5SChris Mason 	 */
2508e02119d5SChris Mason 	if (!dir) {
2509e02119d5SChris Mason 		btrfs_free_path(log_path);
2510e02119d5SChris Mason 		return 0;
2511e02119d5SChris Mason 	}
2512ccae4a19SFilipe Manana 
2513e02119d5SChris Mason 	range_start = 0;
2514e02119d5SChris Mason 	range_end = 0;
2515e02119d5SChris Mason 	while (1) {
251612fcfd22SChris Mason 		if (del_all)
251712fcfd22SChris Mason 			range_end = (u64)-1;
251812fcfd22SChris Mason 		else {
2519ccae4a19SFilipe Manana 			ret = find_dir_range(log, path, dirid,
2520e02119d5SChris Mason 					     &range_start, &range_end);
252110adb115SFilipe Manana 			if (ret < 0)
252210adb115SFilipe Manana 				goto out;
252310adb115SFilipe Manana 			else if (ret > 0)
2524e02119d5SChris Mason 				break;
252512fcfd22SChris Mason 		}
2526e02119d5SChris Mason 
2527e02119d5SChris Mason 		dir_key.offset = range_start;
2528e02119d5SChris Mason 		while (1) {
2529e02119d5SChris Mason 			int nritems;
2530e02119d5SChris Mason 			ret = btrfs_search_slot(NULL, root, &dir_key, path,
2531e02119d5SChris Mason 						0, 0);
2532e02119d5SChris Mason 			if (ret < 0)
2533e02119d5SChris Mason 				goto out;
2534e02119d5SChris Mason 
2535e02119d5SChris Mason 			nritems = btrfs_header_nritems(path->nodes[0]);
2536e02119d5SChris Mason 			if (path->slots[0] >= nritems) {
2537e02119d5SChris Mason 				ret = btrfs_next_leaf(root, path);
2538b98def7cSLiu Bo 				if (ret == 1)
2539e02119d5SChris Mason 					break;
2540b98def7cSLiu Bo 				else if (ret < 0)
2541b98def7cSLiu Bo 					goto out;
2542e02119d5SChris Mason 			}
2543e02119d5SChris Mason 			btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2544e02119d5SChris Mason 					      path->slots[0]);
2545e02119d5SChris Mason 			if (found_key.objectid != dirid ||
2546ccae4a19SFilipe Manana 			    found_key.type != dir_key.type) {
2547ccae4a19SFilipe Manana 				ret = 0;
2548ccae4a19SFilipe Manana 				goto out;
2549ccae4a19SFilipe Manana 			}
2550e02119d5SChris Mason 
2551e02119d5SChris Mason 			if (found_key.offset > range_end)
2552e02119d5SChris Mason 				break;
2553e02119d5SChris Mason 
2554d1ed82f3SFilipe Manana 			ret = check_item_in_log(trans, log, path,
255512fcfd22SChris Mason 						log_path, dir,
255612fcfd22SChris Mason 						&found_key);
25573650860bSJosef Bacik 			if (ret)
25583650860bSJosef Bacik 				goto out;
2559e02119d5SChris Mason 			if (found_key.offset == (u64)-1)
2560e02119d5SChris Mason 				break;
2561e02119d5SChris Mason 			dir_key.offset = found_key.offset + 1;
2562e02119d5SChris Mason 		}
2563b3b4aa74SDavid Sterba 		btrfs_release_path(path);
2564e02119d5SChris Mason 		if (range_end == (u64)-1)
2565e02119d5SChris Mason 			break;
2566e02119d5SChris Mason 		range_start = range_end + 1;
2567e02119d5SChris Mason 	}
2568e02119d5SChris Mason 	ret = 0;
2569e02119d5SChris Mason out:
2570b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2571e02119d5SChris Mason 	btrfs_free_path(log_path);
2572e02119d5SChris Mason 	iput(dir);
2573e02119d5SChris Mason 	return ret;
2574e02119d5SChris Mason }
2575e02119d5SChris Mason 
2576e02119d5SChris Mason /*
2577e02119d5SChris Mason  * the process_func used to replay items from the log tree.  This
2578e02119d5SChris Mason  * gets called in two different stages.  The first stage just looks
2579e02119d5SChris Mason  * for inodes and makes sure they are all copied into the subvolume.
2580e02119d5SChris Mason  *
2581e02119d5SChris Mason  * The second stage copies all the other item types from the log into
2582e02119d5SChris Mason  * the subvolume.  The two stage approach is slower, but gets rid of
2583e02119d5SChris Mason  * lots of complexity around inodes referencing other inodes that exist
2584e02119d5SChris Mason  * only in the log (references come from either directory items or inode
2585e02119d5SChris Mason  * back refs).
2586e02119d5SChris Mason  */
2587e02119d5SChris Mason static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2588581c1760SQu Wenruo 			     struct walk_control *wc, u64 gen, int level)
2589e02119d5SChris Mason {
2590e02119d5SChris Mason 	int nritems;
2591e02119d5SChris Mason 	struct btrfs_path *path;
2592e02119d5SChris Mason 	struct btrfs_root *root = wc->replay_dest;
2593e02119d5SChris Mason 	struct btrfs_key key;
2594e02119d5SChris Mason 	int i;
2595e02119d5SChris Mason 	int ret;
2596e02119d5SChris Mason 
2597581c1760SQu Wenruo 	ret = btrfs_read_buffer(eb, gen, level, NULL);
2598018642a1STsutomu Itoh 	if (ret)
2599018642a1STsutomu Itoh 		return ret;
2600e02119d5SChris Mason 
2601e02119d5SChris Mason 	level = btrfs_header_level(eb);
2602e02119d5SChris Mason 
2603e02119d5SChris Mason 	if (level != 0)
2604e02119d5SChris Mason 		return 0;
2605e02119d5SChris Mason 
2606e02119d5SChris Mason 	path = btrfs_alloc_path();
26071e5063d0SMark Fasheh 	if (!path)
26081e5063d0SMark Fasheh 		return -ENOMEM;
2609e02119d5SChris Mason 
2610e02119d5SChris Mason 	nritems = btrfs_header_nritems(eb);
2611e02119d5SChris Mason 	for (i = 0; i < nritems; i++) {
2612e02119d5SChris Mason 		btrfs_item_key_to_cpu(eb, &key, i);
2613e02119d5SChris Mason 
2614e02119d5SChris Mason 		/* inode keys are done during the first stage */
2615e02119d5SChris Mason 		if (key.type == BTRFS_INODE_ITEM_KEY &&
2616e02119d5SChris Mason 		    wc->stage == LOG_WALK_REPLAY_INODES) {
2617e02119d5SChris Mason 			struct btrfs_inode_item *inode_item;
2618e02119d5SChris Mason 			u32 mode;
2619e02119d5SChris Mason 
2620e02119d5SChris Mason 			inode_item = btrfs_item_ptr(eb, i,
2621e02119d5SChris Mason 					    struct btrfs_inode_item);
2622f2d72f42SFilipe Manana 			/*
2623f2d72f42SFilipe Manana 			 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2624f2d72f42SFilipe Manana 			 * and never got linked before the fsync, skip it, as
2625f2d72f42SFilipe Manana 			 * replaying it is pointless since it would be deleted
2626f2d72f42SFilipe Manana 			 * later. We skip logging tmpfiles, but it's always
2627f2d72f42SFilipe Manana 			 * possible we are replaying a log created with a kernel
2628f2d72f42SFilipe Manana 			 * that used to log tmpfiles.
2629f2d72f42SFilipe Manana 			 */
2630f2d72f42SFilipe Manana 			if (btrfs_inode_nlink(eb, inode_item) == 0) {
2631f2d72f42SFilipe Manana 				wc->ignore_cur_inode = true;
2632f2d72f42SFilipe Manana 				continue;
2633f2d72f42SFilipe Manana 			} else {
2634f2d72f42SFilipe Manana 				wc->ignore_cur_inode = false;
2635f2d72f42SFilipe Manana 			}
26364f764e51SFilipe Manana 			ret = replay_xattr_deletes(wc->trans, root, log,
26374f764e51SFilipe Manana 						   path, key.objectid);
26384f764e51SFilipe Manana 			if (ret)
26394f764e51SFilipe Manana 				break;
2640e02119d5SChris Mason 			mode = btrfs_inode_mode(eb, inode_item);
2641e02119d5SChris Mason 			if (S_ISDIR(mode)) {
2642e02119d5SChris Mason 				ret = replay_dir_deletes(wc->trans,
264312fcfd22SChris Mason 					 root, log, path, key.objectid, 0);
2644b50c6e25SJosef Bacik 				if (ret)
2645b50c6e25SJosef Bacik 					break;
2646e02119d5SChris Mason 			}
2647e02119d5SChris Mason 			ret = overwrite_item(wc->trans, root, path,
2648e02119d5SChris Mason 					     eb, i, &key);
2649b50c6e25SJosef Bacik 			if (ret)
2650b50c6e25SJosef Bacik 				break;
2651e02119d5SChris Mason 
2652471d557aSFilipe Manana 			/*
2653471d557aSFilipe Manana 			 * Before replaying extents, truncate the inode to its
2654471d557aSFilipe Manana 			 * size. We need to do it now and not after log replay
2655471d557aSFilipe Manana 			 * because before an fsync we can have prealloc extents
2656471d557aSFilipe Manana 			 * added beyond the inode's i_size. If we did it after,
2657471d557aSFilipe Manana 			 * through orphan cleanup for example, we would drop
2658471d557aSFilipe Manana 			 * those prealloc extents just after replaying them.
2659e02119d5SChris Mason 			 */
2660e02119d5SChris Mason 			if (S_ISREG(mode)) {
26615893dfb9SFilipe Manana 				struct btrfs_drop_extents_args drop_args = { 0 };
2662471d557aSFilipe Manana 				struct inode *inode;
2663471d557aSFilipe Manana 				u64 from;
2664471d557aSFilipe Manana 
2665471d557aSFilipe Manana 				inode = read_one_inode(root, key.objectid);
2666471d557aSFilipe Manana 				if (!inode) {
2667471d557aSFilipe Manana 					ret = -EIO;
2668471d557aSFilipe Manana 					break;
2669471d557aSFilipe Manana 				}
2670471d557aSFilipe Manana 				from = ALIGN(i_size_read(inode),
2671471d557aSFilipe Manana 					     root->fs_info->sectorsize);
26725893dfb9SFilipe Manana 				drop_args.start = from;
26735893dfb9SFilipe Manana 				drop_args.end = (u64)-1;
26745893dfb9SFilipe Manana 				drop_args.drop_cache = true;
26755893dfb9SFilipe Manana 				ret = btrfs_drop_extents(wc->trans, root,
26765893dfb9SFilipe Manana 							 BTRFS_I(inode),
26775893dfb9SFilipe Manana 							 &drop_args);
2678471d557aSFilipe Manana 				if (!ret) {
26792766ff61SFilipe Manana 					inode_sub_bytes(inode,
26802766ff61SFilipe Manana 							drop_args.bytes_found);
2681f2d72f42SFilipe Manana 					/* Update the inode's nbytes. */
2682471d557aSFilipe Manana 					ret = btrfs_update_inode(wc->trans,
26839a56fcd1SNikolay Borisov 							root, BTRFS_I(inode));
2684471d557aSFilipe Manana 				}
2685471d557aSFilipe Manana 				iput(inode);
2686b50c6e25SJosef Bacik 				if (ret)
2687b50c6e25SJosef Bacik 					break;
2688c71bf099SYan, Zheng 			}
2689a74ac322SChris Mason 
2690e02119d5SChris Mason 			ret = link_to_fixup_dir(wc->trans, root,
2691e02119d5SChris Mason 						path, key.objectid);
2692b50c6e25SJosef Bacik 			if (ret)
2693b50c6e25SJosef Bacik 				break;
2694e02119d5SChris Mason 		}
2695dd8e7217SJosef Bacik 
2696f2d72f42SFilipe Manana 		if (wc->ignore_cur_inode)
2697f2d72f42SFilipe Manana 			continue;
2698f2d72f42SFilipe Manana 
2699dd8e7217SJosef Bacik 		if (key.type == BTRFS_DIR_INDEX_KEY &&
2700dd8e7217SJosef Bacik 		    wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2701dd8e7217SJosef Bacik 			ret = replay_one_dir_item(wc->trans, root, path,
2702dd8e7217SJosef Bacik 						  eb, i, &key);
2703dd8e7217SJosef Bacik 			if (ret)
2704dd8e7217SJosef Bacik 				break;
2705dd8e7217SJosef Bacik 		}
2706dd8e7217SJosef Bacik 
2707e02119d5SChris Mason 		if (wc->stage < LOG_WALK_REPLAY_ALL)
2708e02119d5SChris Mason 			continue;
2709e02119d5SChris Mason 
2710e02119d5SChris Mason 		/* these keys are simply copied */
2711e02119d5SChris Mason 		if (key.type == BTRFS_XATTR_ITEM_KEY) {
2712e02119d5SChris Mason 			ret = overwrite_item(wc->trans, root, path,
2713e02119d5SChris Mason 					     eb, i, &key);
2714b50c6e25SJosef Bacik 			if (ret)
2715b50c6e25SJosef Bacik 				break;
27162da1c669SLiu Bo 		} else if (key.type == BTRFS_INODE_REF_KEY ||
27172da1c669SLiu Bo 			   key.type == BTRFS_INODE_EXTREF_KEY) {
2718f186373fSMark Fasheh 			ret = add_inode_ref(wc->trans, root, log, path,
2719f186373fSMark Fasheh 					    eb, i, &key);
2720b50c6e25SJosef Bacik 			if (ret && ret != -ENOENT)
2721b50c6e25SJosef Bacik 				break;
2722b50c6e25SJosef Bacik 			ret = 0;
2723e02119d5SChris Mason 		} else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2724e02119d5SChris Mason 			ret = replay_one_extent(wc->trans, root, path,
2725e02119d5SChris Mason 						eb, i, &key);
2726b50c6e25SJosef Bacik 			if (ret)
2727b50c6e25SJosef Bacik 				break;
2728e02119d5SChris Mason 		}
2729339d0354SFilipe Manana 		/*
2730339d0354SFilipe Manana 		 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2731339d0354SFilipe Manana 		 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2732339d0354SFilipe Manana 		 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2733339d0354SFilipe Manana 		 * older kernel with such keys, ignore them.
2734339d0354SFilipe Manana 		 */
2735e02119d5SChris Mason 	}
2736e02119d5SChris Mason 	btrfs_free_path(path);
2737b50c6e25SJosef Bacik 	return ret;
2738e02119d5SChris Mason }
2739e02119d5SChris Mason 
27406787bb9fSNikolay Borisov /*
27416787bb9fSNikolay Borisov  * Correctly adjust the reserved bytes occupied by a log tree extent buffer
27426787bb9fSNikolay Borisov  */
27436787bb9fSNikolay Borisov static void unaccount_log_buffer(struct btrfs_fs_info *fs_info, u64 start)
27446787bb9fSNikolay Borisov {
27456787bb9fSNikolay Borisov 	struct btrfs_block_group *cache;
27466787bb9fSNikolay Borisov 
27476787bb9fSNikolay Borisov 	cache = btrfs_lookup_block_group(fs_info, start);
27486787bb9fSNikolay Borisov 	if (!cache) {
27496787bb9fSNikolay Borisov 		btrfs_err(fs_info, "unable to find block group for %llu", start);
27506787bb9fSNikolay Borisov 		return;
27516787bb9fSNikolay Borisov 	}
27526787bb9fSNikolay Borisov 
27536787bb9fSNikolay Borisov 	spin_lock(&cache->space_info->lock);
27546787bb9fSNikolay Borisov 	spin_lock(&cache->lock);
27556787bb9fSNikolay Borisov 	cache->reserved -= fs_info->nodesize;
27566787bb9fSNikolay Borisov 	cache->space_info->bytes_reserved -= fs_info->nodesize;
27576787bb9fSNikolay Borisov 	spin_unlock(&cache->lock);
27586787bb9fSNikolay Borisov 	spin_unlock(&cache->space_info->lock);
27596787bb9fSNikolay Borisov 
27606787bb9fSNikolay Borisov 	btrfs_put_block_group(cache);
27616787bb9fSNikolay Borisov }
27626787bb9fSNikolay Borisov 
2763d397712bSChris Mason static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2764e02119d5SChris Mason 				   struct btrfs_root *root,
2765e02119d5SChris Mason 				   struct btrfs_path *path, int *level,
2766e02119d5SChris Mason 				   struct walk_control *wc)
2767e02119d5SChris Mason {
27680b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2769e02119d5SChris Mason 	u64 bytenr;
2770e02119d5SChris Mason 	u64 ptr_gen;
2771e02119d5SChris Mason 	struct extent_buffer *next;
2772e02119d5SChris Mason 	struct extent_buffer *cur;
2773e02119d5SChris Mason 	u32 blocksize;
2774e02119d5SChris Mason 	int ret = 0;
2775e02119d5SChris Mason 
2776e02119d5SChris Mason 	while (*level > 0) {
2777581c1760SQu Wenruo 		struct btrfs_key first_key;
2778581c1760SQu Wenruo 
2779e02119d5SChris Mason 		cur = path->nodes[*level];
2780e02119d5SChris Mason 
2781fae7f21cSDulshani Gunawardhana 		WARN_ON(btrfs_header_level(cur) != *level);
2782e02119d5SChris Mason 
2783e02119d5SChris Mason 		if (path->slots[*level] >=
2784e02119d5SChris Mason 		    btrfs_header_nritems(cur))
2785e02119d5SChris Mason 			break;
2786e02119d5SChris Mason 
2787e02119d5SChris Mason 		bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2788e02119d5SChris Mason 		ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2789581c1760SQu Wenruo 		btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
27900b246afaSJeff Mahoney 		blocksize = fs_info->nodesize;
2791e02119d5SChris Mason 
27923fbaf258SJosef Bacik 		next = btrfs_find_create_tree_block(fs_info, bytenr,
27933fbaf258SJosef Bacik 						    btrfs_header_owner(cur),
27943fbaf258SJosef Bacik 						    *level - 1);
2795c871b0f2SLiu Bo 		if (IS_ERR(next))
2796c871b0f2SLiu Bo 			return PTR_ERR(next);
2797e02119d5SChris Mason 
27984a500fd1SYan, Zheng 		if (*level == 1) {
2799581c1760SQu Wenruo 			ret = wc->process_func(root, next, wc, ptr_gen,
2800581c1760SQu Wenruo 					       *level - 1);
2801b50c6e25SJosef Bacik 			if (ret) {
2802b50c6e25SJosef Bacik 				free_extent_buffer(next);
28031e5063d0SMark Fasheh 				return ret;
2804b50c6e25SJosef Bacik 			}
2805e02119d5SChris Mason 
2806e02119d5SChris Mason 			path->slots[*level]++;
2807e02119d5SChris Mason 			if (wc->free) {
2808581c1760SQu Wenruo 				ret = btrfs_read_buffer(next, ptr_gen,
2809581c1760SQu Wenruo 							*level - 1, &first_key);
2810018642a1STsutomu Itoh 				if (ret) {
2811018642a1STsutomu Itoh 					free_extent_buffer(next);
2812018642a1STsutomu Itoh 					return ret;
2813018642a1STsutomu Itoh 				}
2814e02119d5SChris Mason 
2815681ae509SJosef Bacik 				if (trans) {
2816e02119d5SChris Mason 					btrfs_tree_lock(next);
28176a884d7dSDavid Sterba 					btrfs_clean_tree_block(next);
2818e02119d5SChris Mason 					btrfs_wait_tree_block_writeback(next);
2819e02119d5SChris Mason 					btrfs_tree_unlock(next);
28207bfc1007SNikolay Borisov 					ret = btrfs_pin_reserved_extent(trans,
2821a0fbf736SNikolay Borisov 							bytenr, blocksize);
28223650860bSJosef Bacik 					if (ret) {
28233650860bSJosef Bacik 						free_extent_buffer(next);
28243650860bSJosef Bacik 						return ret;
28253650860bSJosef Bacik 					}
2826d3575156SNaohiro Aota 					btrfs_redirty_list_add(
2827d3575156SNaohiro Aota 						trans->transaction, next);
282810e958d5SNikolay Borisov 				} else {
282910e958d5SNikolay Borisov 					if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
283010e958d5SNikolay Borisov 						clear_extent_buffer_dirty(next);
283110e958d5SNikolay Borisov 					unaccount_log_buffer(fs_info, bytenr);
283210e958d5SNikolay Borisov 				}
2833e02119d5SChris Mason 			}
2834e02119d5SChris Mason 			free_extent_buffer(next);
2835e02119d5SChris Mason 			continue;
2836e02119d5SChris Mason 		}
2837581c1760SQu Wenruo 		ret = btrfs_read_buffer(next, ptr_gen, *level - 1, &first_key);
2838018642a1STsutomu Itoh 		if (ret) {
2839018642a1STsutomu Itoh 			free_extent_buffer(next);
2840018642a1STsutomu Itoh 			return ret;
2841018642a1STsutomu Itoh 		}
2842e02119d5SChris Mason 
2843e02119d5SChris Mason 		if (path->nodes[*level-1])
2844e02119d5SChris Mason 			free_extent_buffer(path->nodes[*level-1]);
2845e02119d5SChris Mason 		path->nodes[*level-1] = next;
2846e02119d5SChris Mason 		*level = btrfs_header_level(next);
2847e02119d5SChris Mason 		path->slots[*level] = 0;
2848e02119d5SChris Mason 		cond_resched();
2849e02119d5SChris Mason 	}
28504a500fd1SYan, Zheng 	path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2851e02119d5SChris Mason 
2852e02119d5SChris Mason 	cond_resched();
2853e02119d5SChris Mason 	return 0;
2854e02119d5SChris Mason }
2855e02119d5SChris Mason 
2856d397712bSChris Mason static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2857e02119d5SChris Mason 				 struct btrfs_root *root,
2858e02119d5SChris Mason 				 struct btrfs_path *path, int *level,
2859e02119d5SChris Mason 				 struct walk_control *wc)
2860e02119d5SChris Mason {
28610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
2862e02119d5SChris Mason 	int i;
2863e02119d5SChris Mason 	int slot;
2864e02119d5SChris Mason 	int ret;
2865e02119d5SChris Mason 
2866e02119d5SChris Mason 	for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2867e02119d5SChris Mason 		slot = path->slots[i];
28684a500fd1SYan, Zheng 		if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2869e02119d5SChris Mason 			path->slots[i]++;
2870e02119d5SChris Mason 			*level = i;
2871e02119d5SChris Mason 			WARN_ON(*level == 0);
2872e02119d5SChris Mason 			return 0;
2873e02119d5SChris Mason 		} else {
28741e5063d0SMark Fasheh 			ret = wc->process_func(root, path->nodes[*level], wc,
2875581c1760SQu Wenruo 				 btrfs_header_generation(path->nodes[*level]),
2876581c1760SQu Wenruo 				 *level);
28771e5063d0SMark Fasheh 			if (ret)
28781e5063d0SMark Fasheh 				return ret;
28791e5063d0SMark Fasheh 
2880e02119d5SChris Mason 			if (wc->free) {
2881e02119d5SChris Mason 				struct extent_buffer *next;
2882e02119d5SChris Mason 
2883e02119d5SChris Mason 				next = path->nodes[*level];
2884e02119d5SChris Mason 
2885681ae509SJosef Bacik 				if (trans) {
2886e02119d5SChris Mason 					btrfs_tree_lock(next);
28876a884d7dSDavid Sterba 					btrfs_clean_tree_block(next);
2888e02119d5SChris Mason 					btrfs_wait_tree_block_writeback(next);
2889e02119d5SChris Mason 					btrfs_tree_unlock(next);
28907bfc1007SNikolay Borisov 					ret = btrfs_pin_reserved_extent(trans,
2891e02119d5SChris Mason 						     path->nodes[*level]->start,
2892d00aff00SChris Mason 						     path->nodes[*level]->len);
28933650860bSJosef Bacik 					if (ret)
28943650860bSJosef Bacik 						return ret;
289584c25448SNaohiro Aota 					btrfs_redirty_list_add(trans->transaction,
289684c25448SNaohiro Aota 							       next);
289710e958d5SNikolay Borisov 				} else {
289810e958d5SNikolay Borisov 					if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
289910e958d5SNikolay Borisov 						clear_extent_buffer_dirty(next);
290010e958d5SNikolay Borisov 
290110e958d5SNikolay Borisov 					unaccount_log_buffer(fs_info,
290210e958d5SNikolay Borisov 						path->nodes[*level]->start);
290310e958d5SNikolay Borisov 				}
2904e02119d5SChris Mason 			}
2905e02119d5SChris Mason 			free_extent_buffer(path->nodes[*level]);
2906e02119d5SChris Mason 			path->nodes[*level] = NULL;
2907e02119d5SChris Mason 			*level = i + 1;
2908e02119d5SChris Mason 		}
2909e02119d5SChris Mason 	}
2910e02119d5SChris Mason 	return 1;
2911e02119d5SChris Mason }
2912e02119d5SChris Mason 
2913e02119d5SChris Mason /*
2914e02119d5SChris Mason  * drop the reference count on the tree rooted at 'snap'.  This traverses
2915e02119d5SChris Mason  * the tree freeing any blocks that have a ref count of zero after being
2916e02119d5SChris Mason  * decremented.
2917e02119d5SChris Mason  */
2918e02119d5SChris Mason static int walk_log_tree(struct btrfs_trans_handle *trans,
2919e02119d5SChris Mason 			 struct btrfs_root *log, struct walk_control *wc)
2920e02119d5SChris Mason {
29212ff7e61eSJeff Mahoney 	struct btrfs_fs_info *fs_info = log->fs_info;
2922e02119d5SChris Mason 	int ret = 0;
2923e02119d5SChris Mason 	int wret;
2924e02119d5SChris Mason 	int level;
2925e02119d5SChris Mason 	struct btrfs_path *path;
2926e02119d5SChris Mason 	int orig_level;
2927e02119d5SChris Mason 
2928e02119d5SChris Mason 	path = btrfs_alloc_path();
2929db5b493aSTsutomu Itoh 	if (!path)
2930db5b493aSTsutomu Itoh 		return -ENOMEM;
2931e02119d5SChris Mason 
2932e02119d5SChris Mason 	level = btrfs_header_level(log->node);
2933e02119d5SChris Mason 	orig_level = level;
2934e02119d5SChris Mason 	path->nodes[level] = log->node;
293567439dadSDavid Sterba 	atomic_inc(&log->node->refs);
2936e02119d5SChris Mason 	path->slots[level] = 0;
2937e02119d5SChris Mason 
2938e02119d5SChris Mason 	while (1) {
2939e02119d5SChris Mason 		wret = walk_down_log_tree(trans, log, path, &level, wc);
2940e02119d5SChris Mason 		if (wret > 0)
2941e02119d5SChris Mason 			break;
294279787eaaSJeff Mahoney 		if (wret < 0) {
2943e02119d5SChris Mason 			ret = wret;
294479787eaaSJeff Mahoney 			goto out;
294579787eaaSJeff Mahoney 		}
2946e02119d5SChris Mason 
2947e02119d5SChris Mason 		wret = walk_up_log_tree(trans, log, path, &level, wc);
2948e02119d5SChris Mason 		if (wret > 0)
2949e02119d5SChris Mason 			break;
295079787eaaSJeff Mahoney 		if (wret < 0) {
2951e02119d5SChris Mason 			ret = wret;
295279787eaaSJeff Mahoney 			goto out;
295379787eaaSJeff Mahoney 		}
2954e02119d5SChris Mason 	}
2955e02119d5SChris Mason 
2956e02119d5SChris Mason 	/* was the root node processed? if not, catch it here */
2957e02119d5SChris Mason 	if (path->nodes[orig_level]) {
295879787eaaSJeff Mahoney 		ret = wc->process_func(log, path->nodes[orig_level], wc,
2959581c1760SQu Wenruo 			 btrfs_header_generation(path->nodes[orig_level]),
2960581c1760SQu Wenruo 			 orig_level);
296179787eaaSJeff Mahoney 		if (ret)
296279787eaaSJeff Mahoney 			goto out;
2963e02119d5SChris Mason 		if (wc->free) {
2964e02119d5SChris Mason 			struct extent_buffer *next;
2965e02119d5SChris Mason 
2966e02119d5SChris Mason 			next = path->nodes[orig_level];
2967e02119d5SChris Mason 
2968681ae509SJosef Bacik 			if (trans) {
2969e02119d5SChris Mason 				btrfs_tree_lock(next);
29706a884d7dSDavid Sterba 				btrfs_clean_tree_block(next);
2971e02119d5SChris Mason 				btrfs_wait_tree_block_writeback(next);
2972e02119d5SChris Mason 				btrfs_tree_unlock(next);
29737bfc1007SNikolay Borisov 				ret = btrfs_pin_reserved_extent(trans,
297410e958d5SNikolay Borisov 						next->start, next->len);
297510e958d5SNikolay Borisov 				if (ret)
297610e958d5SNikolay Borisov 					goto out;
297784c25448SNaohiro Aota 				btrfs_redirty_list_add(trans->transaction, next);
29781846430cSLiu Bo 			} else {
29791846430cSLiu Bo 				if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
29801846430cSLiu Bo 					clear_extent_buffer_dirty(next);
298110e958d5SNikolay Borisov 				unaccount_log_buffer(fs_info, next->start);
2982681ae509SJosef Bacik 			}
2983e02119d5SChris Mason 		}
2984e02119d5SChris Mason 	}
2985e02119d5SChris Mason 
298679787eaaSJeff Mahoney out:
2987e02119d5SChris Mason 	btrfs_free_path(path);
2988e02119d5SChris Mason 	return ret;
2989e02119d5SChris Mason }
2990e02119d5SChris Mason 
29917237f183SYan Zheng /*
29927237f183SYan Zheng  * helper function to update the item for a given subvolumes log root
29937237f183SYan Zheng  * in the tree of log roots
29947237f183SYan Zheng  */
29957237f183SYan Zheng static int update_log_root(struct btrfs_trans_handle *trans,
29964203e968SJosef Bacik 			   struct btrfs_root *log,
29974203e968SJosef Bacik 			   struct btrfs_root_item *root_item)
29987237f183SYan Zheng {
29990b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = log->fs_info;
30007237f183SYan Zheng 	int ret;
30017237f183SYan Zheng 
30027237f183SYan Zheng 	if (log->log_transid == 1) {
30037237f183SYan Zheng 		/* insert root item on the first sync */
30040b246afaSJeff Mahoney 		ret = btrfs_insert_root(trans, fs_info->log_root_tree,
30054203e968SJosef Bacik 				&log->root_key, root_item);
30067237f183SYan Zheng 	} else {
30070b246afaSJeff Mahoney 		ret = btrfs_update_root(trans, fs_info->log_root_tree,
30084203e968SJosef Bacik 				&log->root_key, root_item);
30097237f183SYan Zheng 	}
30107237f183SYan Zheng 	return ret;
30117237f183SYan Zheng }
30127237f183SYan Zheng 
301360d53eb3SZhaolei static void wait_log_commit(struct btrfs_root *root, int transid)
3014e02119d5SChris Mason {
3015e02119d5SChris Mason 	DEFINE_WAIT(wait);
30167237f183SYan Zheng 	int index = transid % 2;
3017e02119d5SChris Mason 
30187237f183SYan Zheng 	/*
30197237f183SYan Zheng 	 * we only allow two pending log transactions at a time,
30207237f183SYan Zheng 	 * so we know that if ours is more than 2 older than the
30217237f183SYan Zheng 	 * current transaction, we're done
30227237f183SYan Zheng 	 */
302349e83f57SLiu Bo 	for (;;) {
30247237f183SYan Zheng 		prepare_to_wait(&root->log_commit_wait[index],
30257237f183SYan Zheng 				&wait, TASK_UNINTERRUPTIBLE);
302649e83f57SLiu Bo 
302749e83f57SLiu Bo 		if (!(root->log_transid_committed < transid &&
302849e83f57SLiu Bo 		      atomic_read(&root->log_commit[index])))
302949e83f57SLiu Bo 			break;
303049e83f57SLiu Bo 
30317237f183SYan Zheng 		mutex_unlock(&root->log_mutex);
3032e02119d5SChris Mason 		schedule();
30337237f183SYan Zheng 		mutex_lock(&root->log_mutex);
303449e83f57SLiu Bo 	}
303549e83f57SLiu Bo 	finish_wait(&root->log_commit_wait[index], &wait);
30367237f183SYan Zheng }
30377237f183SYan Zheng 
303860d53eb3SZhaolei static void wait_for_writer(struct btrfs_root *root)
30397237f183SYan Zheng {
30407237f183SYan Zheng 	DEFINE_WAIT(wait);
30418b050d35SMiao Xie 
304249e83f57SLiu Bo 	for (;;) {
304349e83f57SLiu Bo 		prepare_to_wait(&root->log_writer_wait, &wait,
304449e83f57SLiu Bo 				TASK_UNINTERRUPTIBLE);
304549e83f57SLiu Bo 		if (!atomic_read(&root->log_writers))
304649e83f57SLiu Bo 			break;
304749e83f57SLiu Bo 
30487237f183SYan Zheng 		mutex_unlock(&root->log_mutex);
30497237f183SYan Zheng 		schedule();
3050575849ecSFilipe Manana 		mutex_lock(&root->log_mutex);
30517237f183SYan Zheng 	}
305249e83f57SLiu Bo 	finish_wait(&root->log_writer_wait, &wait);
3053e02119d5SChris Mason }
3054e02119d5SChris Mason 
30558b050d35SMiao Xie static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
30568b050d35SMiao Xie 					struct btrfs_log_ctx *ctx)
30578b050d35SMiao Xie {
30588b050d35SMiao Xie 	mutex_lock(&root->log_mutex);
30598b050d35SMiao Xie 	list_del_init(&ctx->list);
30608b050d35SMiao Xie 	mutex_unlock(&root->log_mutex);
30618b050d35SMiao Xie }
30628b050d35SMiao Xie 
30638b050d35SMiao Xie /*
30648b050d35SMiao Xie  * Invoked in log mutex context, or be sure there is no other task which
30658b050d35SMiao Xie  * can access the list.
30668b050d35SMiao Xie  */
30678b050d35SMiao Xie static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
30688b050d35SMiao Xie 					     int index, int error)
30698b050d35SMiao Xie {
30708b050d35SMiao Xie 	struct btrfs_log_ctx *ctx;
3071570dd450SChris Mason 	struct btrfs_log_ctx *safe;
30728b050d35SMiao Xie 
3073570dd450SChris Mason 	list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
3074570dd450SChris Mason 		list_del_init(&ctx->list);
30758b050d35SMiao Xie 		ctx->log_ret = error;
3076570dd450SChris Mason 	}
30778b050d35SMiao Xie }
30788b050d35SMiao Xie 
3079e02119d5SChris Mason /*
3080e02119d5SChris Mason  * btrfs_sync_log does sends a given tree log down to the disk and
3081e02119d5SChris Mason  * updates the super blocks to record it.  When this call is done,
308212fcfd22SChris Mason  * you know that any inodes previously logged are safely on disk only
308312fcfd22SChris Mason  * if it returns 0.
308412fcfd22SChris Mason  *
308512fcfd22SChris Mason  * Any other return value means you need to call btrfs_commit_transaction.
308612fcfd22SChris Mason  * Some of the edge cases for fsyncing directories that have had unlinks
308712fcfd22SChris Mason  * or renames done in the past mean that sometimes the only safe
308812fcfd22SChris Mason  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
308912fcfd22SChris Mason  * that has happened.
3090e02119d5SChris Mason  */
3091e02119d5SChris Mason int btrfs_sync_log(struct btrfs_trans_handle *trans,
30928b050d35SMiao Xie 		   struct btrfs_root *root, struct btrfs_log_ctx *ctx)
3093e02119d5SChris Mason {
30947237f183SYan Zheng 	int index1;
30957237f183SYan Zheng 	int index2;
30968cef4e16SYan, Zheng 	int mark;
3097e02119d5SChris Mason 	int ret;
30980b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
3099e02119d5SChris Mason 	struct btrfs_root *log = root->log_root;
31000b246afaSJeff Mahoney 	struct btrfs_root *log_root_tree = fs_info->log_root_tree;
31014203e968SJosef Bacik 	struct btrfs_root_item new_root_item;
3102bb14a59bSMiao Xie 	int log_transid = 0;
31038b050d35SMiao Xie 	struct btrfs_log_ctx root_log_ctx;
3104c6adc9ccSMiao Xie 	struct blk_plug plug;
310547876f7cSFilipe Manana 	u64 log_root_start;
310647876f7cSFilipe Manana 	u64 log_root_level;
3107e02119d5SChris Mason 
31087237f183SYan Zheng 	mutex_lock(&root->log_mutex);
3109d1433debSMiao Xie 	log_transid = ctx->log_transid;
3110d1433debSMiao Xie 	if (root->log_transid_committed >= log_transid) {
31117237f183SYan Zheng 		mutex_unlock(&root->log_mutex);
31128b050d35SMiao Xie 		return ctx->log_ret;
3113e02119d5SChris Mason 	}
3114d1433debSMiao Xie 
3115d1433debSMiao Xie 	index1 = log_transid % 2;
3116d1433debSMiao Xie 	if (atomic_read(&root->log_commit[index1])) {
311760d53eb3SZhaolei 		wait_log_commit(root, log_transid);
3118d1433debSMiao Xie 		mutex_unlock(&root->log_mutex);
3119d1433debSMiao Xie 		return ctx->log_ret;
3120d1433debSMiao Xie 	}
3121d1433debSMiao Xie 	ASSERT(log_transid == root->log_transid);
31227237f183SYan Zheng 	atomic_set(&root->log_commit[index1], 1);
31237237f183SYan Zheng 
31247237f183SYan Zheng 	/* wait for previous tree log sync to complete */
31257237f183SYan Zheng 	if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
312660d53eb3SZhaolei 		wait_log_commit(root, log_transid - 1);
312748cab2e0SMiao Xie 
312886df7eb9SYan, Zheng 	while (1) {
31292ecb7923SMiao Xie 		int batch = atomic_read(&root->log_batch);
3130cd354ad6SChris Mason 		/* when we're on an ssd, just kick the log commit out */
31310b246afaSJeff Mahoney 		if (!btrfs_test_opt(fs_info, SSD) &&
313227cdeb70SMiao Xie 		    test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
31337237f183SYan Zheng 			mutex_unlock(&root->log_mutex);
3134e02119d5SChris Mason 			schedule_timeout_uninterruptible(1);
31357237f183SYan Zheng 			mutex_lock(&root->log_mutex);
313686df7eb9SYan, Zheng 		}
313760d53eb3SZhaolei 		wait_for_writer(root);
31382ecb7923SMiao Xie 		if (batch == atomic_read(&root->log_batch))
3139e02119d5SChris Mason 			break;
3140e02119d5SChris Mason 	}
3141d0c803c4SChris Mason 
314212fcfd22SChris Mason 	/* bail out if we need to do a full commit */
31434884b8e8SDavid Sterba 	if (btrfs_need_log_full_commit(trans)) {
314412fcfd22SChris Mason 		ret = -EAGAIN;
314512fcfd22SChris Mason 		mutex_unlock(&root->log_mutex);
314612fcfd22SChris Mason 		goto out;
314712fcfd22SChris Mason 	}
314812fcfd22SChris Mason 
31498cef4e16SYan, Zheng 	if (log_transid % 2 == 0)
31508cef4e16SYan, Zheng 		mark = EXTENT_DIRTY;
31518cef4e16SYan, Zheng 	else
31528cef4e16SYan, Zheng 		mark = EXTENT_NEW;
31538cef4e16SYan, Zheng 
3154690587d1SChris Mason 	/* we start IO on  all the marked extents here, but we don't actually
3155690587d1SChris Mason 	 * wait for them until later.
3156690587d1SChris Mason 	 */
3157c6adc9ccSMiao Xie 	blk_start_plug(&plug);
31582ff7e61eSJeff Mahoney 	ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
3159b528f467SNaohiro Aota 	/*
3160b528f467SNaohiro Aota 	 * -EAGAIN happens when someone, e.g., a concurrent transaction
3161b528f467SNaohiro Aota 	 *  commit, writes a dirty extent in this tree-log commit. This
3162b528f467SNaohiro Aota 	 *  concurrent write will create a hole writing out the extents,
3163b528f467SNaohiro Aota 	 *  and we cannot proceed on a zoned filesystem, requiring
3164b528f467SNaohiro Aota 	 *  sequential writing. While we can bail out to a full commit
3165b528f467SNaohiro Aota 	 *  here, but we can continue hoping the concurrent writing fills
3166b528f467SNaohiro Aota 	 *  the hole.
3167b528f467SNaohiro Aota 	 */
3168b528f467SNaohiro Aota 	if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
3169b528f467SNaohiro Aota 		ret = 0;
317079787eaaSJeff Mahoney 	if (ret) {
3171c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
317266642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
317390787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
317479787eaaSJeff Mahoney 		mutex_unlock(&root->log_mutex);
317579787eaaSJeff Mahoney 		goto out;
317679787eaaSJeff Mahoney 	}
31777237f183SYan Zheng 
31784203e968SJosef Bacik 	/*
31794203e968SJosef Bacik 	 * We _must_ update under the root->log_mutex in order to make sure we
31804203e968SJosef Bacik 	 * have a consistent view of the log root we are trying to commit at
31814203e968SJosef Bacik 	 * this moment.
31824203e968SJosef Bacik 	 *
31834203e968SJosef Bacik 	 * We _must_ copy this into a local copy, because we are not holding the
31844203e968SJosef Bacik 	 * log_root_tree->log_mutex yet.  This is important because when we
31854203e968SJosef Bacik 	 * commit the log_root_tree we must have a consistent view of the
31864203e968SJosef Bacik 	 * log_root_tree when we update the super block to point at the
31874203e968SJosef Bacik 	 * log_root_tree bytenr.  If we update the log_root_tree here we'll race
31884203e968SJosef Bacik 	 * with the commit and possibly point at the new block which we may not
31894203e968SJosef Bacik 	 * have written out.
31904203e968SJosef Bacik 	 */
31915d4f98a2SYan Zheng 	btrfs_set_root_node(&log->root_item, log->node);
31924203e968SJosef Bacik 	memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
31937237f183SYan Zheng 
31947237f183SYan Zheng 	root->log_transid++;
31957237f183SYan Zheng 	log->log_transid = root->log_transid;
3196ff782e0aSJosef Bacik 	root->log_start_pid = 0;
31977237f183SYan Zheng 	/*
31988cef4e16SYan, Zheng 	 * IO has been started, blocks of the log tree have WRITTEN flag set
31998cef4e16SYan, Zheng 	 * in their headers. new modifications of the log will be written to
32008cef4e16SYan, Zheng 	 * new positions. so it's safe to allow log writers to go in.
32017237f183SYan Zheng 	 */
32027237f183SYan Zheng 	mutex_unlock(&root->log_mutex);
32037237f183SYan Zheng 
32043ddebf27SNaohiro Aota 	if (btrfs_is_zoned(fs_info)) {
3205e75f9fd1SNaohiro Aota 		mutex_lock(&fs_info->tree_root->log_mutex);
32063ddebf27SNaohiro Aota 		if (!log_root_tree->node) {
32073ddebf27SNaohiro Aota 			ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
32083ddebf27SNaohiro Aota 			if (ret) {
3209ea32af47SFilipe Manana 				mutex_unlock(&fs_info->tree_root->log_mutex);
32103ddebf27SNaohiro Aota 				goto out;
32113ddebf27SNaohiro Aota 			}
32123ddebf27SNaohiro Aota 		}
3213e75f9fd1SNaohiro Aota 		mutex_unlock(&fs_info->tree_root->log_mutex);
32143ddebf27SNaohiro Aota 	}
32153ddebf27SNaohiro Aota 
3216e75f9fd1SNaohiro Aota 	btrfs_init_log_ctx(&root_log_ctx, NULL);
3217e75f9fd1SNaohiro Aota 
3218e75f9fd1SNaohiro Aota 	mutex_lock(&log_root_tree->log_mutex);
3219e75f9fd1SNaohiro Aota 
3220e3d3b415SFilipe Manana 	index2 = log_root_tree->log_transid % 2;
3221e3d3b415SFilipe Manana 	list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3222e3d3b415SFilipe Manana 	root_log_ctx.log_transid = log_root_tree->log_transid;
3223e3d3b415SFilipe Manana 
32244203e968SJosef Bacik 	/*
32254203e968SJosef Bacik 	 * Now we are safe to update the log_root_tree because we're under the
32264203e968SJosef Bacik 	 * log_mutex, and we're a current writer so we're holding the commit
32274203e968SJosef Bacik 	 * open until we drop the log_mutex.
32284203e968SJosef Bacik 	 */
32294203e968SJosef Bacik 	ret = update_log_root(trans, log, &new_root_item);
32304a500fd1SYan, Zheng 	if (ret) {
3231d1433debSMiao Xie 		if (!list_empty(&root_log_ctx.list))
3232d1433debSMiao Xie 			list_del_init(&root_log_ctx.list);
3233d1433debSMiao Xie 
3234c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
323590787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
3236995946ddSMiao Xie 
323779787eaaSJeff Mahoney 		if (ret != -ENOSPC) {
323866642832SJeff Mahoney 			btrfs_abort_transaction(trans, ret);
323979787eaaSJeff Mahoney 			mutex_unlock(&log_root_tree->log_mutex);
324079787eaaSJeff Mahoney 			goto out;
324179787eaaSJeff Mahoney 		}
3242bf89d38fSJeff Mahoney 		btrfs_wait_tree_log_extents(log, mark);
32434a500fd1SYan, Zheng 		mutex_unlock(&log_root_tree->log_mutex);
32444a500fd1SYan, Zheng 		ret = -EAGAIN;
32454a500fd1SYan, Zheng 		goto out;
32464a500fd1SYan, Zheng 	}
32474a500fd1SYan, Zheng 
3248d1433debSMiao Xie 	if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
32493da5ab56SForrest Liu 		blk_finish_plug(&plug);
3250cbd60aa7SChris Mason 		list_del_init(&root_log_ctx.list);
3251d1433debSMiao Xie 		mutex_unlock(&log_root_tree->log_mutex);
3252d1433debSMiao Xie 		ret = root_log_ctx.log_ret;
3253d1433debSMiao Xie 		goto out;
3254d1433debSMiao Xie 	}
32558b050d35SMiao Xie 
3256d1433debSMiao Xie 	index2 = root_log_ctx.log_transid % 2;
32577237f183SYan Zheng 	if (atomic_read(&log_root_tree->log_commit[index2])) {
3258c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
3259bf89d38fSJeff Mahoney 		ret = btrfs_wait_tree_log_extents(log, mark);
326060d53eb3SZhaolei 		wait_log_commit(log_root_tree,
3261d1433debSMiao Xie 				root_log_ctx.log_transid);
32627237f183SYan Zheng 		mutex_unlock(&log_root_tree->log_mutex);
32635ab5e44aSFilipe Manana 		if (!ret)
32648b050d35SMiao Xie 			ret = root_log_ctx.log_ret;
32657237f183SYan Zheng 		goto out;
32667237f183SYan Zheng 	}
3267d1433debSMiao Xie 	ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
32687237f183SYan Zheng 	atomic_set(&log_root_tree->log_commit[index2], 1);
32697237f183SYan Zheng 
327012fcfd22SChris Mason 	if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
327160d53eb3SZhaolei 		wait_log_commit(log_root_tree,
3272d1433debSMiao Xie 				root_log_ctx.log_transid - 1);
327312fcfd22SChris Mason 	}
32747237f183SYan Zheng 
327512fcfd22SChris Mason 	/*
327612fcfd22SChris Mason 	 * now that we've moved on to the tree of log tree roots,
327712fcfd22SChris Mason 	 * check the full commit flag again
327812fcfd22SChris Mason 	 */
32794884b8e8SDavid Sterba 	if (btrfs_need_log_full_commit(trans)) {
3280c6adc9ccSMiao Xie 		blk_finish_plug(&plug);
3281bf89d38fSJeff Mahoney 		btrfs_wait_tree_log_extents(log, mark);
328212fcfd22SChris Mason 		mutex_unlock(&log_root_tree->log_mutex);
328312fcfd22SChris Mason 		ret = -EAGAIN;
328412fcfd22SChris Mason 		goto out_wake_log_root;
328512fcfd22SChris Mason 	}
32867237f183SYan Zheng 
32872ff7e61eSJeff Mahoney 	ret = btrfs_write_marked_extents(fs_info,
32888cef4e16SYan, Zheng 					 &log_root_tree->dirty_log_pages,
32898cef4e16SYan, Zheng 					 EXTENT_DIRTY | EXTENT_NEW);
3290c6adc9ccSMiao Xie 	blk_finish_plug(&plug);
3291b528f467SNaohiro Aota 	/*
3292b528f467SNaohiro Aota 	 * As described above, -EAGAIN indicates a hole in the extents. We
3293b528f467SNaohiro Aota 	 * cannot wait for these write outs since the waiting cause a
3294b528f467SNaohiro Aota 	 * deadlock. Bail out to the full commit instead.
3295b528f467SNaohiro Aota 	 */
3296b528f467SNaohiro Aota 	if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3297b528f467SNaohiro Aota 		btrfs_set_log_full_commit(trans);
3298b528f467SNaohiro Aota 		btrfs_wait_tree_log_extents(log, mark);
3299b528f467SNaohiro Aota 		mutex_unlock(&log_root_tree->log_mutex);
3300b528f467SNaohiro Aota 		goto out_wake_log_root;
3301b528f467SNaohiro Aota 	} else if (ret) {
330290787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
330366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
330479787eaaSJeff Mahoney 		mutex_unlock(&log_root_tree->log_mutex);
330579787eaaSJeff Mahoney 		goto out_wake_log_root;
330679787eaaSJeff Mahoney 	}
3307bf89d38fSJeff Mahoney 	ret = btrfs_wait_tree_log_extents(log, mark);
33085ab5e44aSFilipe Manana 	if (!ret)
3309bf89d38fSJeff Mahoney 		ret = btrfs_wait_tree_log_extents(log_root_tree,
3310c6adc9ccSMiao Xie 						  EXTENT_NEW | EXTENT_DIRTY);
33115ab5e44aSFilipe Manana 	if (ret) {
331290787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
33135ab5e44aSFilipe Manana 		mutex_unlock(&log_root_tree->log_mutex);
33145ab5e44aSFilipe Manana 		goto out_wake_log_root;
33155ab5e44aSFilipe Manana 	}
3316e02119d5SChris Mason 
331747876f7cSFilipe Manana 	log_root_start = log_root_tree->node->start;
331847876f7cSFilipe Manana 	log_root_level = btrfs_header_level(log_root_tree->node);
33197237f183SYan Zheng 	log_root_tree->log_transid++;
33207237f183SYan Zheng 	mutex_unlock(&log_root_tree->log_mutex);
33217237f183SYan Zheng 
33227237f183SYan Zheng 	/*
332347876f7cSFilipe Manana 	 * Here we are guaranteed that nobody is going to write the superblock
332447876f7cSFilipe Manana 	 * for the current transaction before us and that neither we do write
332547876f7cSFilipe Manana 	 * our superblock before the previous transaction finishes its commit
332647876f7cSFilipe Manana 	 * and writes its superblock, because:
332747876f7cSFilipe Manana 	 *
332847876f7cSFilipe Manana 	 * 1) We are holding a handle on the current transaction, so no body
332947876f7cSFilipe Manana 	 *    can commit it until we release the handle;
333047876f7cSFilipe Manana 	 *
333147876f7cSFilipe Manana 	 * 2) Before writing our superblock we acquire the tree_log_mutex, so
333247876f7cSFilipe Manana 	 *    if the previous transaction is still committing, and hasn't yet
333347876f7cSFilipe Manana 	 *    written its superblock, we wait for it to do it, because a
333447876f7cSFilipe Manana 	 *    transaction commit acquires the tree_log_mutex when the commit
333547876f7cSFilipe Manana 	 *    begins and releases it only after writing its superblock.
33367237f183SYan Zheng 	 */
333747876f7cSFilipe Manana 	mutex_lock(&fs_info->tree_log_mutex);
3338165ea85fSJosef Bacik 
3339165ea85fSJosef Bacik 	/*
3340165ea85fSJosef Bacik 	 * The previous transaction writeout phase could have failed, and thus
3341165ea85fSJosef Bacik 	 * marked the fs in an error state.  We must not commit here, as we
3342165ea85fSJosef Bacik 	 * could have updated our generation in the super_for_commit and
3343165ea85fSJosef Bacik 	 * writing the super here would result in transid mismatches.  If there
3344165ea85fSJosef Bacik 	 * is an error here just bail.
3345165ea85fSJosef Bacik 	 */
334684961539SJosef Bacik 	if (BTRFS_FS_ERROR(fs_info)) {
3347165ea85fSJosef Bacik 		ret = -EIO;
3348165ea85fSJosef Bacik 		btrfs_set_log_full_commit(trans);
3349165ea85fSJosef Bacik 		btrfs_abort_transaction(trans, ret);
3350165ea85fSJosef Bacik 		mutex_unlock(&fs_info->tree_log_mutex);
3351165ea85fSJosef Bacik 		goto out_wake_log_root;
3352165ea85fSJosef Bacik 	}
3353165ea85fSJosef Bacik 
335447876f7cSFilipe Manana 	btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
335547876f7cSFilipe Manana 	btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3356eece6a9cSDavid Sterba 	ret = write_all_supers(fs_info, 1);
335747876f7cSFilipe Manana 	mutex_unlock(&fs_info->tree_log_mutex);
33585af3e8ccSStefan Behrens 	if (ret) {
335990787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
336066642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
33615af3e8ccSStefan Behrens 		goto out_wake_log_root;
33625af3e8ccSStefan Behrens 	}
33637237f183SYan Zheng 
3364e1a6d264SFilipe Manana 	/*
3365e1a6d264SFilipe Manana 	 * We know there can only be one task here, since we have not yet set
3366e1a6d264SFilipe Manana 	 * root->log_commit[index1] to 0 and any task attempting to sync the
3367e1a6d264SFilipe Manana 	 * log must wait for the previous log transaction to commit if it's
3368e1a6d264SFilipe Manana 	 * still in progress or wait for the current log transaction commit if
3369e1a6d264SFilipe Manana 	 * someone else already started it. We use <= and not < because the
3370e1a6d264SFilipe Manana 	 * first log transaction has an ID of 0.
3371e1a6d264SFilipe Manana 	 */
3372e1a6d264SFilipe Manana 	ASSERT(root->last_log_commit <= log_transid);
3373257c62e1SChris Mason 	root->last_log_commit = log_transid;
3374257c62e1SChris Mason 
337512fcfd22SChris Mason out_wake_log_root:
3376570dd450SChris Mason 	mutex_lock(&log_root_tree->log_mutex);
33778b050d35SMiao Xie 	btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
33788b050d35SMiao Xie 
3379d1433debSMiao Xie 	log_root_tree->log_transid_committed++;
33807237f183SYan Zheng 	atomic_set(&log_root_tree->log_commit[index2], 0);
3381d1433debSMiao Xie 	mutex_unlock(&log_root_tree->log_mutex);
3382d1433debSMiao Xie 
338333a9eca7SDavid Sterba 	/*
3384093258e6SDavid Sterba 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3385093258e6SDavid Sterba 	 * all the updates above are seen by the woken threads. It might not be
3386093258e6SDavid Sterba 	 * necessary, but proving that seems to be hard.
338733a9eca7SDavid Sterba 	 */
3388093258e6SDavid Sterba 	cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3389e02119d5SChris Mason out:
3390d1433debSMiao Xie 	mutex_lock(&root->log_mutex);
3391570dd450SChris Mason 	btrfs_remove_all_log_ctxs(root, index1, ret);
3392d1433debSMiao Xie 	root->log_transid_committed++;
33937237f183SYan Zheng 	atomic_set(&root->log_commit[index1], 0);
3394d1433debSMiao Xie 	mutex_unlock(&root->log_mutex);
33958b050d35SMiao Xie 
339633a9eca7SDavid Sterba 	/*
3397093258e6SDavid Sterba 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3398093258e6SDavid Sterba 	 * all the updates above are seen by the woken threads. It might not be
3399093258e6SDavid Sterba 	 * necessary, but proving that seems to be hard.
340033a9eca7SDavid Sterba 	 */
3401093258e6SDavid Sterba 	cond_wake_up(&root->log_commit_wait[index1]);
3402b31eabd8SChris Mason 	return ret;
3403e02119d5SChris Mason }
3404e02119d5SChris Mason 
34054a500fd1SYan, Zheng static void free_log_tree(struct btrfs_trans_handle *trans,
34064a500fd1SYan, Zheng 			  struct btrfs_root *log)
3407e02119d5SChris Mason {
3408e02119d5SChris Mason 	int ret;
3409e02119d5SChris Mason 	struct walk_control wc = {
3410e02119d5SChris Mason 		.free = 1,
3411e02119d5SChris Mason 		.process_func = process_one_buffer
3412e02119d5SChris Mason 	};
3413e02119d5SChris Mason 
34143ddebf27SNaohiro Aota 	if (log->node) {
3415e02119d5SChris Mason 		ret = walk_log_tree(trans, log, &wc);
3416374b0e2dSJeff Mahoney 		if (ret) {
3417374b0e2dSJeff Mahoney 			if (trans)
341866642832SJeff Mahoney 				btrfs_abort_transaction(trans, ret);
3419374b0e2dSJeff Mahoney 			else
3420374b0e2dSJeff Mahoney 				btrfs_handle_fs_error(log->fs_info, ret, NULL);
3421374b0e2dSJeff Mahoney 		}
34223ddebf27SNaohiro Aota 	}
3423e02119d5SChris Mason 
342459b0713aSFilipe Manana 	clear_extent_bits(&log->dirty_log_pages, 0, (u64)-1,
342555237a5fSLiu Bo 			  EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3426e289f03eSFilipe Manana 	extent_io_tree_release(&log->log_csum_range);
3427d3575156SNaohiro Aota 
342800246528SJosef Bacik 	btrfs_put_root(log);
34294a500fd1SYan, Zheng }
34304a500fd1SYan, Zheng 
34314a500fd1SYan, Zheng /*
34324a500fd1SYan, Zheng  * free all the extents used by the tree log.  This should be called
34334a500fd1SYan, Zheng  * at commit time of the full transaction
34344a500fd1SYan, Zheng  */
34354a500fd1SYan, Zheng int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
34364a500fd1SYan, Zheng {
34374a500fd1SYan, Zheng 	if (root->log_root) {
34384a500fd1SYan, Zheng 		free_log_tree(trans, root->log_root);
34394a500fd1SYan, Zheng 		root->log_root = NULL;
3440e7a79811SFilipe Manana 		clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
34414a500fd1SYan, Zheng 	}
34424a500fd1SYan, Zheng 	return 0;
34434a500fd1SYan, Zheng }
34444a500fd1SYan, Zheng 
34454a500fd1SYan, Zheng int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
34464a500fd1SYan, Zheng 			     struct btrfs_fs_info *fs_info)
34474a500fd1SYan, Zheng {
34484a500fd1SYan, Zheng 	if (fs_info->log_root_tree) {
34494a500fd1SYan, Zheng 		free_log_tree(trans, fs_info->log_root_tree);
34504a500fd1SYan, Zheng 		fs_info->log_root_tree = NULL;
345147876f7cSFilipe Manana 		clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
34524a500fd1SYan, Zheng 	}
3453e02119d5SChris Mason 	return 0;
3454e02119d5SChris Mason }
3455e02119d5SChris Mason 
3456e02119d5SChris Mason /*
34576e8e777dSFilipe Manana  * Check if an inode was logged in the current transaction. This may often
34586e8e777dSFilipe Manana  * return some false positives, because logged_trans is an in memory only field,
34596e8e777dSFilipe Manana  * not persisted anywhere. This is meant to be used in contexts where a false
34606e8e777dSFilipe Manana  * positive has no functional consequences.
3461803f0f64SFilipe Manana  */
3462803f0f64SFilipe Manana static bool inode_logged(struct btrfs_trans_handle *trans,
3463803f0f64SFilipe Manana 			 struct btrfs_inode *inode)
3464803f0f64SFilipe Manana {
3465803f0f64SFilipe Manana 	if (inode->logged_trans == trans->transid)
3466803f0f64SFilipe Manana 		return true;
3467803f0f64SFilipe Manana 
34681e0860f3SFilipe Manana 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state))
34691e0860f3SFilipe Manana 		return false;
34701e0860f3SFilipe Manana 
34716e8e777dSFilipe Manana 	/*
34726e8e777dSFilipe Manana 	 * The inode's logged_trans is always 0 when we load it (because it is
34736e8e777dSFilipe Manana 	 * not persisted in the inode item or elsewhere). So if it is 0, the
3474d135a533SFilipe Manana 	 * inode was last modified in the current transaction then the inode may
3475d135a533SFilipe Manana 	 * have been logged before in the current transaction, then evicted and
3476d135a533SFilipe Manana 	 * loaded again in the current transaction - or may have never been logged
3477d135a533SFilipe Manana 	 * in the current transaction, but since we can not be sure, we have to
3478d135a533SFilipe Manana 	 * assume it was, otherwise our callers can leave an inconsistent log.
34796e8e777dSFilipe Manana 	 */
34806e8e777dSFilipe Manana 	if (inode->logged_trans == 0 &&
34816e8e777dSFilipe Manana 	    inode->last_trans == trans->transid &&
3482803f0f64SFilipe Manana 	    !test_bit(BTRFS_FS_LOG_RECOVERING, &trans->fs_info->flags))
3483803f0f64SFilipe Manana 		return true;
3484803f0f64SFilipe Manana 
3485803f0f64SFilipe Manana 	return false;
3486803f0f64SFilipe Manana }
3487803f0f64SFilipe Manana 
3488803f0f64SFilipe Manana /*
3489e02119d5SChris Mason  * If both a file and directory are logged, and unlinks or renames are
3490e02119d5SChris Mason  * mixed in, we have a few interesting corners:
3491e02119d5SChris Mason  *
3492e02119d5SChris Mason  * create file X in dir Y
3493e02119d5SChris Mason  * link file X to X.link in dir Y
3494e02119d5SChris Mason  * fsync file X
3495e02119d5SChris Mason  * unlink file X but leave X.link
3496e02119d5SChris Mason  * fsync dir Y
3497e02119d5SChris Mason  *
3498e02119d5SChris Mason  * After a crash we would expect only X.link to exist.  But file X
3499e02119d5SChris Mason  * didn't get fsync'd again so the log has back refs for X and X.link.
3500e02119d5SChris Mason  *
3501e02119d5SChris Mason  * We solve this by removing directory entries and inode backrefs from the
3502e02119d5SChris Mason  * log when a file that was logged in the current transaction is
3503e02119d5SChris Mason  * unlinked.  Any later fsync will include the updated log entries, and
3504e02119d5SChris Mason  * we'll be able to reconstruct the proper directory items from backrefs.
3505e02119d5SChris Mason  *
3506e02119d5SChris Mason  * This optimizations allows us to avoid relogging the entire inode
3507e02119d5SChris Mason  * or the entire directory.
3508e02119d5SChris Mason  */
35099a35fc95SJosef Bacik void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3510e02119d5SChris Mason 				  struct btrfs_root *root,
3511e02119d5SChris Mason 				  const char *name, int name_len,
351249f34d1fSNikolay Borisov 				  struct btrfs_inode *dir, u64 index)
3513e02119d5SChris Mason {
3514e02119d5SChris Mason 	struct btrfs_root *log;
3515e02119d5SChris Mason 	struct btrfs_dir_item *di;
3516e02119d5SChris Mason 	struct btrfs_path *path;
3517e02119d5SChris Mason 	int ret;
35184a500fd1SYan, Zheng 	int err = 0;
351949f34d1fSNikolay Borisov 	u64 dir_ino = btrfs_ino(dir);
3520e02119d5SChris Mason 
3521803f0f64SFilipe Manana 	if (!inode_logged(trans, dir))
35229a35fc95SJosef Bacik 		return;
35233a5f1d45SChris Mason 
3524e02119d5SChris Mason 	ret = join_running_log_trans(root);
3525e02119d5SChris Mason 	if (ret)
35269a35fc95SJosef Bacik 		return;
3527e02119d5SChris Mason 
352849f34d1fSNikolay Borisov 	mutex_lock(&dir->log_mutex);
3529e02119d5SChris Mason 
3530e02119d5SChris Mason 	log = root->log_root;
3531e02119d5SChris Mason 	path = btrfs_alloc_path();
3532a62f44a5STsutomu Itoh 	if (!path) {
3533a62f44a5STsutomu Itoh 		err = -ENOMEM;
3534a62f44a5STsutomu Itoh 		goto out_unlock;
3535a62f44a5STsutomu Itoh 	}
35362a29edc6Sliubo 
3537339d0354SFilipe Manana 	/*
3538339d0354SFilipe Manana 	 * We only log dir index items of a directory, so we don't need to look
3539339d0354SFilipe Manana 	 * for dir item keys.
3540339d0354SFilipe Manana 	 */
354133345d01SLi Zefan 	di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3542e02119d5SChris Mason 					 index, name, name_len, -1);
35434a500fd1SYan, Zheng 	if (IS_ERR(di)) {
35444a500fd1SYan, Zheng 		err = PTR_ERR(di);
35454a500fd1SYan, Zheng 		goto fail;
35464a500fd1SYan, Zheng 	}
35474a500fd1SYan, Zheng 	if (di) {
3548e02119d5SChris Mason 		ret = btrfs_delete_one_dir_name(trans, log, path, di);
35493650860bSJosef Bacik 		if (ret) {
35503650860bSJosef Bacik 			err = ret;
35513650860bSJosef Bacik 			goto fail;
35523650860bSJosef Bacik 		}
3553e02119d5SChris Mason 	}
3554e02119d5SChris Mason 
3555ddffcf6fSFilipe Manana 	/*
3556ddffcf6fSFilipe Manana 	 * We do not need to update the size field of the directory's inode item
3557ddffcf6fSFilipe Manana 	 * because on log replay we update the field to reflect all existing
3558ddffcf6fSFilipe Manana 	 * entries in the directory (see overwrite_item()).
3559e02119d5SChris Mason 	 */
35604a500fd1SYan, Zheng fail:
3561e02119d5SChris Mason 	btrfs_free_path(path);
3562a62f44a5STsutomu Itoh out_unlock:
356349f34d1fSNikolay Borisov 	mutex_unlock(&dir->log_mutex);
35649a35fc95SJosef Bacik 	if (err < 0)
356590787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
356612fcfd22SChris Mason 	btrfs_end_log_trans(root);
3567e02119d5SChris Mason }
3568e02119d5SChris Mason 
3569e02119d5SChris Mason /* see comments for btrfs_del_dir_entries_in_log */
35709a35fc95SJosef Bacik void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3571e02119d5SChris Mason 				struct btrfs_root *root,
3572e02119d5SChris Mason 				const char *name, int name_len,
3573a491abb2SNikolay Borisov 				struct btrfs_inode *inode, u64 dirid)
3574e02119d5SChris Mason {
3575e02119d5SChris Mason 	struct btrfs_root *log;
3576e02119d5SChris Mason 	u64 index;
3577e02119d5SChris Mason 	int ret;
3578e02119d5SChris Mason 
3579803f0f64SFilipe Manana 	if (!inode_logged(trans, inode))
35809a35fc95SJosef Bacik 		return;
35813a5f1d45SChris Mason 
3582e02119d5SChris Mason 	ret = join_running_log_trans(root);
3583e02119d5SChris Mason 	if (ret)
35849a35fc95SJosef Bacik 		return;
3585e02119d5SChris Mason 	log = root->log_root;
3586a491abb2SNikolay Borisov 	mutex_lock(&inode->log_mutex);
3587e02119d5SChris Mason 
3588a491abb2SNikolay Borisov 	ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
3589e02119d5SChris Mason 				  dirid, &index);
3590a491abb2SNikolay Borisov 	mutex_unlock(&inode->log_mutex);
35919a35fc95SJosef Bacik 	if (ret < 0 && ret != -ENOENT)
359290787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
359312fcfd22SChris Mason 	btrfs_end_log_trans(root);
3594e02119d5SChris Mason }
3595e02119d5SChris Mason 
3596e02119d5SChris Mason /*
3597e02119d5SChris Mason  * creates a range item in the log for 'dirid'.  first_offset and
3598e02119d5SChris Mason  * last_offset tell us which parts of the key space the log should
3599e02119d5SChris Mason  * be considered authoritative for.
3600e02119d5SChris Mason  */
3601e02119d5SChris Mason static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3602e02119d5SChris Mason 				       struct btrfs_root *log,
3603e02119d5SChris Mason 				       struct btrfs_path *path,
3604339d0354SFilipe Manana 				       u64 dirid,
3605e02119d5SChris Mason 				       u64 first_offset, u64 last_offset)
3606e02119d5SChris Mason {
3607e02119d5SChris Mason 	int ret;
3608e02119d5SChris Mason 	struct btrfs_key key;
3609e02119d5SChris Mason 	struct btrfs_dir_log_item *item;
3610e02119d5SChris Mason 
3611e02119d5SChris Mason 	key.objectid = dirid;
3612e02119d5SChris Mason 	key.offset = first_offset;
3613e02119d5SChris Mason 	key.type = BTRFS_DIR_LOG_INDEX_KEY;
3614e02119d5SChris Mason 	ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
36154a500fd1SYan, Zheng 	if (ret)
36164a500fd1SYan, Zheng 		return ret;
3617e02119d5SChris Mason 
3618e02119d5SChris Mason 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3619e02119d5SChris Mason 			      struct btrfs_dir_log_item);
3620e02119d5SChris Mason 	btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3621e02119d5SChris Mason 	btrfs_mark_buffer_dirty(path->nodes[0]);
3622b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3623e02119d5SChris Mason 	return 0;
3624e02119d5SChris Mason }
3625e02119d5SChris Mason 
3626086dcbfaSFilipe Manana static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
3627086dcbfaSFilipe Manana 				 struct btrfs_root *log,
3628086dcbfaSFilipe Manana 				 struct extent_buffer *src,
3629086dcbfaSFilipe Manana 				 struct btrfs_path *dst_path,
3630086dcbfaSFilipe Manana 				 int start_slot,
3631086dcbfaSFilipe Manana 				 int count)
3632086dcbfaSFilipe Manana {
3633086dcbfaSFilipe Manana 	char *ins_data = NULL;
3634b7ef5f3aSFilipe Manana 	struct btrfs_item_batch batch;
3635086dcbfaSFilipe Manana 	struct extent_buffer *dst;
3636da1b811fSFilipe Manana 	unsigned long src_offset;
3637da1b811fSFilipe Manana 	unsigned long dst_offset;
3638086dcbfaSFilipe Manana 	struct btrfs_key key;
3639086dcbfaSFilipe Manana 	u32 item_size;
3640086dcbfaSFilipe Manana 	int ret;
3641086dcbfaSFilipe Manana 	int i;
3642086dcbfaSFilipe Manana 
3643086dcbfaSFilipe Manana 	ASSERT(count > 0);
3644b7ef5f3aSFilipe Manana 	batch.nr = count;
3645086dcbfaSFilipe Manana 
3646086dcbfaSFilipe Manana 	if (count == 1) {
3647086dcbfaSFilipe Manana 		btrfs_item_key_to_cpu(src, &key, start_slot);
36483212fa14SJosef Bacik 		item_size = btrfs_item_size(src, start_slot);
3649b7ef5f3aSFilipe Manana 		batch.keys = &key;
3650b7ef5f3aSFilipe Manana 		batch.data_sizes = &item_size;
3651b7ef5f3aSFilipe Manana 		batch.total_data_size = item_size;
3652086dcbfaSFilipe Manana 	} else {
3653b7ef5f3aSFilipe Manana 		struct btrfs_key *ins_keys;
3654b7ef5f3aSFilipe Manana 		u32 *ins_sizes;
3655b7ef5f3aSFilipe Manana 
3656086dcbfaSFilipe Manana 		ins_data = kmalloc(count * sizeof(u32) +
3657086dcbfaSFilipe Manana 				   count * sizeof(struct btrfs_key), GFP_NOFS);
3658086dcbfaSFilipe Manana 		if (!ins_data)
3659086dcbfaSFilipe Manana 			return -ENOMEM;
3660086dcbfaSFilipe Manana 
3661086dcbfaSFilipe Manana 		ins_sizes = (u32 *)ins_data;
3662086dcbfaSFilipe Manana 		ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
3663b7ef5f3aSFilipe Manana 		batch.keys = ins_keys;
3664b7ef5f3aSFilipe Manana 		batch.data_sizes = ins_sizes;
3665b7ef5f3aSFilipe Manana 		batch.total_data_size = 0;
3666086dcbfaSFilipe Manana 
3667086dcbfaSFilipe Manana 		for (i = 0; i < count; i++) {
3668086dcbfaSFilipe Manana 			const int slot = start_slot + i;
3669086dcbfaSFilipe Manana 
3670086dcbfaSFilipe Manana 			btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
36713212fa14SJosef Bacik 			ins_sizes[i] = btrfs_item_size(src, slot);
3672b7ef5f3aSFilipe Manana 			batch.total_data_size += ins_sizes[i];
3673086dcbfaSFilipe Manana 		}
3674086dcbfaSFilipe Manana 	}
3675086dcbfaSFilipe Manana 
3676b7ef5f3aSFilipe Manana 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
3677086dcbfaSFilipe Manana 	if (ret)
3678086dcbfaSFilipe Manana 		goto out;
3679086dcbfaSFilipe Manana 
3680086dcbfaSFilipe Manana 	dst = dst_path->nodes[0];
3681da1b811fSFilipe Manana 	/*
3682da1b811fSFilipe Manana 	 * Copy all the items in bulk, in a single copy operation. Item data is
3683da1b811fSFilipe Manana 	 * organized such that it's placed at the end of a leaf and from right
3684da1b811fSFilipe Manana 	 * to left. For example, the data for the second item ends at an offset
3685da1b811fSFilipe Manana 	 * that matches the offset where the data for the first item starts, the
3686da1b811fSFilipe Manana 	 * data for the third item ends at an offset that matches the offset
3687da1b811fSFilipe Manana 	 * where the data of the second items starts, and so on.
3688da1b811fSFilipe Manana 	 * Therefore our source and destination start offsets for copy match the
3689da1b811fSFilipe Manana 	 * offsets of the last items (highest slots).
3690da1b811fSFilipe Manana 	 */
3691da1b811fSFilipe Manana 	dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
3692da1b811fSFilipe Manana 	src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
3693da1b811fSFilipe Manana 	copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
3694086dcbfaSFilipe Manana 	btrfs_release_path(dst_path);
3695086dcbfaSFilipe Manana out:
3696086dcbfaSFilipe Manana 	kfree(ins_data);
3697086dcbfaSFilipe Manana 
3698086dcbfaSFilipe Manana 	return ret;
3699086dcbfaSFilipe Manana }
3700086dcbfaSFilipe Manana 
3701eb10d85eSFilipe Manana static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
3702eb10d85eSFilipe Manana 				  struct btrfs_inode *inode,
3703eb10d85eSFilipe Manana 				  struct btrfs_path *path,
3704eb10d85eSFilipe Manana 				  struct btrfs_path *dst_path,
3705eb10d85eSFilipe Manana 				  struct btrfs_log_ctx *ctx)
3706eb10d85eSFilipe Manana {
3707eb10d85eSFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
3708eb10d85eSFilipe Manana 	struct extent_buffer *src = path->nodes[0];
3709eb10d85eSFilipe Manana 	const int nritems = btrfs_header_nritems(src);
3710eb10d85eSFilipe Manana 	const u64 ino = btrfs_ino(inode);
3711086dcbfaSFilipe Manana 	const bool inode_logged_before = inode_logged(trans, inode);
3712086dcbfaSFilipe Manana 	bool last_found = false;
3713086dcbfaSFilipe Manana 	int batch_start = 0;
3714086dcbfaSFilipe Manana 	int batch_size = 0;
3715eb10d85eSFilipe Manana 	int i;
3716eb10d85eSFilipe Manana 
3717eb10d85eSFilipe Manana 	for (i = path->slots[0]; i < nritems; i++) {
3718eb10d85eSFilipe Manana 		struct btrfs_key key;
3719eb10d85eSFilipe Manana 		int ret;
3720eb10d85eSFilipe Manana 
3721eb10d85eSFilipe Manana 		btrfs_item_key_to_cpu(src, &key, i);
3722eb10d85eSFilipe Manana 
3723339d0354SFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
3724086dcbfaSFilipe Manana 			last_found = true;
3725086dcbfaSFilipe Manana 			break;
3726086dcbfaSFilipe Manana 		}
3727eb10d85eSFilipe Manana 
3728dc287224SFilipe Manana 		ctx->last_dir_item_offset = key.offset;
3729eb10d85eSFilipe Manana 		/*
3730eb10d85eSFilipe Manana 		 * We must make sure that when we log a directory entry, the
3731eb10d85eSFilipe Manana 		 * corresponding inode, after log replay, has a matching link
3732eb10d85eSFilipe Manana 		 * count. For example:
3733eb10d85eSFilipe Manana 		 *
3734eb10d85eSFilipe Manana 		 * touch foo
3735eb10d85eSFilipe Manana 		 * mkdir mydir
3736eb10d85eSFilipe Manana 		 * sync
3737eb10d85eSFilipe Manana 		 * ln foo mydir/bar
3738eb10d85eSFilipe Manana 		 * xfs_io -c "fsync" mydir
3739eb10d85eSFilipe Manana 		 * <crash>
3740eb10d85eSFilipe Manana 		 * <mount fs and log replay>
3741eb10d85eSFilipe Manana 		 *
3742eb10d85eSFilipe Manana 		 * Would result in a fsync log that when replayed, our file inode
3743eb10d85eSFilipe Manana 		 * would have a link count of 1, but we get two directory entries
3744eb10d85eSFilipe Manana 		 * pointing to the same inode. After removing one of the names,
3745eb10d85eSFilipe Manana 		 * it would not be possible to remove the other name, which
3746eb10d85eSFilipe Manana 		 * resulted always in stale file handle errors, and would not be
3747eb10d85eSFilipe Manana 		 * possible to rmdir the parent directory, since its i_size could
3748eb10d85eSFilipe Manana 		 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
3749eb10d85eSFilipe Manana 		 * resulting in -ENOTEMPTY errors.
3750eb10d85eSFilipe Manana 		 */
3751086dcbfaSFilipe Manana 		if (!ctx->log_new_dentries) {
3752086dcbfaSFilipe Manana 			struct btrfs_dir_item *di;
3753086dcbfaSFilipe Manana 			struct btrfs_key di_key;
3754086dcbfaSFilipe Manana 
3755eb10d85eSFilipe Manana 			di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3756086dcbfaSFilipe Manana 			btrfs_dir_item_key_to_cpu(src, di, &di_key);
3757eb10d85eSFilipe Manana 			if ((btrfs_dir_transid(src, di) == trans->transid ||
3758eb10d85eSFilipe Manana 			     btrfs_dir_type(src, di) == BTRFS_FT_DIR) &&
3759086dcbfaSFilipe Manana 			    di_key.type != BTRFS_ROOT_ITEM_KEY)
3760eb10d85eSFilipe Manana 				ctx->log_new_dentries = true;
3761eb10d85eSFilipe Manana 		}
3762eb10d85eSFilipe Manana 
3763086dcbfaSFilipe Manana 		if (!inode_logged_before)
3764086dcbfaSFilipe Manana 			goto add_to_batch;
3765dc287224SFilipe Manana 
3766dc287224SFilipe Manana 		/*
3767dc287224SFilipe Manana 		 * If we were logged before and have logged dir items, we can skip
3768dc287224SFilipe Manana 		 * checking if any item with a key offset larger than the last one
3769dc287224SFilipe Manana 		 * we logged is in the log tree, saving time and avoiding adding
3770dc287224SFilipe Manana 		 * contention on the log tree.
3771dc287224SFilipe Manana 		 */
3772339d0354SFilipe Manana 		if (key.offset > inode->last_dir_index_offset)
3773dc287224SFilipe Manana 			goto add_to_batch;
3774086dcbfaSFilipe Manana 		/*
3775086dcbfaSFilipe Manana 		 * Check if the key was already logged before. If not we can add
3776086dcbfaSFilipe Manana 		 * it to a batch for bulk insertion.
3777086dcbfaSFilipe Manana 		 */
3778086dcbfaSFilipe Manana 		ret = btrfs_search_slot(NULL, log, &key, dst_path, 0, 0);
3779086dcbfaSFilipe Manana 		if (ret < 0) {
3780086dcbfaSFilipe Manana 			return ret;
3781086dcbfaSFilipe Manana 		} else if (ret > 0) {
3782086dcbfaSFilipe Manana 			btrfs_release_path(dst_path);
3783086dcbfaSFilipe Manana 			goto add_to_batch;
3784086dcbfaSFilipe Manana 		}
3785086dcbfaSFilipe Manana 
3786086dcbfaSFilipe Manana 		/*
3787086dcbfaSFilipe Manana 		 * Item exists in the log. Overwrite the item in the log if it
3788086dcbfaSFilipe Manana 		 * has different content or do nothing if it has exactly the same
3789086dcbfaSFilipe Manana 		 * content. And then flush the current batch if any - do it after
3790086dcbfaSFilipe Manana 		 * overwriting the current item, or we would deadlock otherwise,
3791086dcbfaSFilipe Manana 		 * since we are holding a path for the existing item.
3792086dcbfaSFilipe Manana 		 */
3793086dcbfaSFilipe Manana 		ret = do_overwrite_item(trans, log, dst_path, src, i, &key);
3794086dcbfaSFilipe Manana 		if (ret < 0)
3795086dcbfaSFilipe Manana 			return ret;
3796086dcbfaSFilipe Manana 
3797086dcbfaSFilipe Manana 		if (batch_size > 0) {
3798086dcbfaSFilipe Manana 			ret = flush_dir_items_batch(trans, log, src, dst_path,
3799086dcbfaSFilipe Manana 						    batch_start, batch_size);
3800086dcbfaSFilipe Manana 			if (ret < 0)
3801086dcbfaSFilipe Manana 				return ret;
3802086dcbfaSFilipe Manana 			batch_size = 0;
3803086dcbfaSFilipe Manana 		}
3804086dcbfaSFilipe Manana 		continue;
3805086dcbfaSFilipe Manana add_to_batch:
3806086dcbfaSFilipe Manana 		if (batch_size == 0)
3807086dcbfaSFilipe Manana 			batch_start = i;
3808086dcbfaSFilipe Manana 		batch_size++;
3809086dcbfaSFilipe Manana 	}
3810086dcbfaSFilipe Manana 
3811086dcbfaSFilipe Manana 	if (batch_size > 0) {
3812086dcbfaSFilipe Manana 		int ret;
3813086dcbfaSFilipe Manana 
3814086dcbfaSFilipe Manana 		ret = flush_dir_items_batch(trans, log, src, dst_path,
3815086dcbfaSFilipe Manana 					    batch_start, batch_size);
3816086dcbfaSFilipe Manana 		if (ret < 0)
3817086dcbfaSFilipe Manana 			return ret;
3818086dcbfaSFilipe Manana 	}
3819086dcbfaSFilipe Manana 
3820086dcbfaSFilipe Manana 	return last_found ? 1 : 0;
3821eb10d85eSFilipe Manana }
3822eb10d85eSFilipe Manana 
3823e02119d5SChris Mason /*
3824e02119d5SChris Mason  * log all the items included in the current transaction for a given
3825e02119d5SChris Mason  * directory.  This also creates the range items in the log tree required
3826e02119d5SChris Mason  * to replay anything deleted before the fsync
3827e02119d5SChris Mason  */
3828e02119d5SChris Mason static noinline int log_dir_items(struct btrfs_trans_handle *trans,
382990d04510SFilipe Manana 			  struct btrfs_inode *inode,
3830e02119d5SChris Mason 			  struct btrfs_path *path,
3831339d0354SFilipe Manana 			  struct btrfs_path *dst_path,
38322f2ff0eeSFilipe Manana 			  struct btrfs_log_ctx *ctx,
3833e02119d5SChris Mason 			  u64 min_offset, u64 *last_offset_ret)
3834e02119d5SChris Mason {
3835e02119d5SChris Mason 	struct btrfs_key min_key;
383690d04510SFilipe Manana 	struct btrfs_root *root = inode->root;
3837e02119d5SChris Mason 	struct btrfs_root *log = root->log_root;
38384a500fd1SYan, Zheng 	int err = 0;
3839e02119d5SChris Mason 	int ret;
3840e02119d5SChris Mason 	u64 first_offset = min_offset;
3841e02119d5SChris Mason 	u64 last_offset = (u64)-1;
3842684a5773SNikolay Borisov 	u64 ino = btrfs_ino(inode);
3843e02119d5SChris Mason 
384433345d01SLi Zefan 	min_key.objectid = ino;
3845339d0354SFilipe Manana 	min_key.type = BTRFS_DIR_INDEX_KEY;
3846e02119d5SChris Mason 	min_key.offset = min_offset;
3847e02119d5SChris Mason 
38486174d3cbSFilipe David Borba Manana 	ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3849e02119d5SChris Mason 
3850e02119d5SChris Mason 	/*
3851e02119d5SChris Mason 	 * we didn't find anything from this transaction, see if there
3852e02119d5SChris Mason 	 * is anything at all
3853e02119d5SChris Mason 	 */
3854339d0354SFilipe Manana 	if (ret != 0 || min_key.objectid != ino ||
3855339d0354SFilipe Manana 	    min_key.type != BTRFS_DIR_INDEX_KEY) {
385633345d01SLi Zefan 		min_key.objectid = ino;
3857339d0354SFilipe Manana 		min_key.type = BTRFS_DIR_INDEX_KEY;
3858e02119d5SChris Mason 		min_key.offset = (u64)-1;
3859b3b4aa74SDavid Sterba 		btrfs_release_path(path);
3860e02119d5SChris Mason 		ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3861e02119d5SChris Mason 		if (ret < 0) {
3862b3b4aa74SDavid Sterba 			btrfs_release_path(path);
3863e02119d5SChris Mason 			return ret;
3864e02119d5SChris Mason 		}
3865339d0354SFilipe Manana 		ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3866e02119d5SChris Mason 
3867e02119d5SChris Mason 		/* if ret == 0 there are items for this type,
3868e02119d5SChris Mason 		 * create a range to tell us the last key of this type.
3869e02119d5SChris Mason 		 * otherwise, there are no items in this directory after
3870e02119d5SChris Mason 		 * *min_offset, and we create a range to indicate that.
3871e02119d5SChris Mason 		 */
3872e02119d5SChris Mason 		if (ret == 0) {
3873e02119d5SChris Mason 			struct btrfs_key tmp;
3874e02119d5SChris Mason 			btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3875e02119d5SChris Mason 					      path->slots[0]);
3876339d0354SFilipe Manana 			if (tmp.type == BTRFS_DIR_INDEX_KEY)
3877e02119d5SChris Mason 				first_offset = max(min_offset, tmp.offset) + 1;
3878e02119d5SChris Mason 		}
3879e02119d5SChris Mason 		goto done;
3880e02119d5SChris Mason 	}
3881e02119d5SChris Mason 
3882e02119d5SChris Mason 	/* go backward to find any previous key */
3883339d0354SFilipe Manana 	ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
3884e02119d5SChris Mason 	if (ret == 0) {
3885e02119d5SChris Mason 		struct btrfs_key tmp;
3886e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3887339d0354SFilipe Manana 		if (tmp.type == BTRFS_DIR_INDEX_KEY) {
3888e02119d5SChris Mason 			first_offset = tmp.offset;
3889e02119d5SChris Mason 			ret = overwrite_item(trans, log, dst_path,
3890e02119d5SChris Mason 					     path->nodes[0], path->slots[0],
3891e02119d5SChris Mason 					     &tmp);
38924a500fd1SYan, Zheng 			if (ret) {
38934a500fd1SYan, Zheng 				err = ret;
38944a500fd1SYan, Zheng 				goto done;
38954a500fd1SYan, Zheng 			}
3896e02119d5SChris Mason 		}
3897e02119d5SChris Mason 	}
3898b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3899e02119d5SChris Mason 
39002cc83342SJosef Bacik 	/*
39012cc83342SJosef Bacik 	 * Find the first key from this transaction again.  See the note for
39022cc83342SJosef Bacik 	 * log_new_dir_dentries, if we're logging a directory recursively we
39032cc83342SJosef Bacik 	 * won't be holding its i_mutex, which means we can modify the directory
39042cc83342SJosef Bacik 	 * while we're logging it.  If we remove an entry between our first
39052cc83342SJosef Bacik 	 * search and this search we'll not find the key again and can just
39062cc83342SJosef Bacik 	 * bail.
39072cc83342SJosef Bacik 	 */
3908bb56f02fSFilipe Manana search:
3909e02119d5SChris Mason 	ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
39102cc83342SJosef Bacik 	if (ret != 0)
3911e02119d5SChris Mason 		goto done;
3912e02119d5SChris Mason 
3913e02119d5SChris Mason 	/*
3914e02119d5SChris Mason 	 * we have a block from this transaction, log every item in it
3915e02119d5SChris Mason 	 * from our directory
3916e02119d5SChris Mason 	 */
3917e02119d5SChris Mason 	while (1) {
3918339d0354SFilipe Manana 		ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx);
3919eb10d85eSFilipe Manana 		if (ret != 0) {
3920eb10d85eSFilipe Manana 			if (ret < 0)
39214a500fd1SYan, Zheng 				err = ret;
39224a500fd1SYan, Zheng 			goto done;
39234a500fd1SYan, Zheng 		}
3924eb10d85eSFilipe Manana 		path->slots[0] = btrfs_header_nritems(path->nodes[0]);
3925e02119d5SChris Mason 
3926e02119d5SChris Mason 		/*
3927e02119d5SChris Mason 		 * look ahead to the next item and see if it is also
3928e02119d5SChris Mason 		 * from this directory and from this transaction
3929e02119d5SChris Mason 		 */
3930e02119d5SChris Mason 		ret = btrfs_next_leaf(root, path);
393180c0b421SLiu Bo 		if (ret) {
393280c0b421SLiu Bo 			if (ret == 1)
3933e02119d5SChris Mason 				last_offset = (u64)-1;
393480c0b421SLiu Bo 			else
393580c0b421SLiu Bo 				err = ret;
3936e02119d5SChris Mason 			goto done;
3937e02119d5SChris Mason 		}
3938eb10d85eSFilipe Manana 		btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
3939339d0354SFilipe Manana 		if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
3940e02119d5SChris Mason 			last_offset = (u64)-1;
3941e02119d5SChris Mason 			goto done;
3942e02119d5SChris Mason 		}
3943e02119d5SChris Mason 		if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
39441b2e5e5cSFilipe Manana 			ctx->last_dir_item_offset = min_key.offset;
3945e02119d5SChris Mason 			ret = overwrite_item(trans, log, dst_path,
3946e02119d5SChris Mason 					     path->nodes[0], path->slots[0],
3947eb10d85eSFilipe Manana 					     &min_key);
39484a500fd1SYan, Zheng 			if (ret)
39494a500fd1SYan, Zheng 				err = ret;
39504a500fd1SYan, Zheng 			else
3951eb10d85eSFilipe Manana 				last_offset = min_key.offset;
3952e02119d5SChris Mason 			goto done;
3953e02119d5SChris Mason 		}
3954eb10d85eSFilipe Manana 		if (need_resched()) {
3955eb10d85eSFilipe Manana 			btrfs_release_path(path);
3956eb10d85eSFilipe Manana 			cond_resched();
3957eb10d85eSFilipe Manana 			goto search;
3958eb10d85eSFilipe Manana 		}
3959e02119d5SChris Mason 	}
3960e02119d5SChris Mason done:
3961b3b4aa74SDavid Sterba 	btrfs_release_path(path);
3962b3b4aa74SDavid Sterba 	btrfs_release_path(dst_path);
3963e02119d5SChris Mason 
39644a500fd1SYan, Zheng 	if (err == 0) {
39654a500fd1SYan, Zheng 		*last_offset_ret = last_offset;
39664a500fd1SYan, Zheng 		/*
39674a500fd1SYan, Zheng 		 * insert the log range keys to indicate where the log
39684a500fd1SYan, Zheng 		 * is valid
39694a500fd1SYan, Zheng 		 */
3970339d0354SFilipe Manana 		ret = insert_dir_log_key(trans, log, path, ino, first_offset,
3971339d0354SFilipe Manana 					 last_offset);
39724a500fd1SYan, Zheng 		if (ret)
39734a500fd1SYan, Zheng 			err = ret;
39744a500fd1SYan, Zheng 	}
39754a500fd1SYan, Zheng 	return err;
3976e02119d5SChris Mason }
3977e02119d5SChris Mason 
3978e02119d5SChris Mason /*
3979e02119d5SChris Mason  * logging directories is very similar to logging inodes, We find all the items
3980e02119d5SChris Mason  * from the current transaction and write them to the log.
3981e02119d5SChris Mason  *
3982e02119d5SChris Mason  * The recovery code scans the directory in the subvolume, and if it finds a
3983e02119d5SChris Mason  * key in the range logged that is not present in the log tree, then it means
3984e02119d5SChris Mason  * that dir entry was unlinked during the transaction.
3985e02119d5SChris Mason  *
3986e02119d5SChris Mason  * In order for that scan to work, we must include one key smaller than
3987e02119d5SChris Mason  * the smallest logged by this transaction and one key larger than the largest
3988e02119d5SChris Mason  * key logged by this transaction.
3989e02119d5SChris Mason  */
3990e02119d5SChris Mason static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
399190d04510SFilipe Manana 			  struct btrfs_inode *inode,
3992e02119d5SChris Mason 			  struct btrfs_path *path,
39932f2ff0eeSFilipe Manana 			  struct btrfs_path *dst_path,
39942f2ff0eeSFilipe Manana 			  struct btrfs_log_ctx *ctx)
3995e02119d5SChris Mason {
3996e02119d5SChris Mason 	u64 min_key;
3997e02119d5SChris Mason 	u64 max_key;
3998e02119d5SChris Mason 	int ret;
3999e02119d5SChris Mason 
4000dc287224SFilipe Manana 	/*
4001dc287224SFilipe Manana 	 * If this is the first time we are being logged in the current
4002dc287224SFilipe Manana 	 * transaction, or we were logged before but the inode was evicted and
4003339d0354SFilipe Manana 	 * reloaded later, in which case its logged_trans is 0, reset the value
4004339d0354SFilipe Manana 	 * of the last logged key offset. Note that we don't use the helper
4005dc287224SFilipe Manana 	 * function inode_logged() here - that is because the function returns
4006dc287224SFilipe Manana 	 * true after an inode eviction, assuming the worst case as it can not
4007dc287224SFilipe Manana 	 * know for sure if the inode was logged before. So we can not skip key
4008dc287224SFilipe Manana 	 * searches in the case the inode was evicted, because it may not have
4009dc287224SFilipe Manana 	 * been logged in this transaction and may have been logged in a past
4010339d0354SFilipe Manana 	 * transaction, so we need to reset the last dir index offset to (u64)-1.
4011dc287224SFilipe Manana 	 */
4012339d0354SFilipe Manana 	if (inode->logged_trans != trans->transid)
4013dc287224SFilipe Manana 		inode->last_dir_index_offset = (u64)-1;
4014339d0354SFilipe Manana 
4015e02119d5SChris Mason 	min_key = 0;
4016e02119d5SChris Mason 	max_key = 0;
4017dc287224SFilipe Manana 	ctx->last_dir_item_offset = inode->last_dir_index_offset;
4018dc287224SFilipe Manana 
4019e02119d5SChris Mason 	while (1) {
4020339d0354SFilipe Manana 		ret = log_dir_items(trans, inode, path, dst_path,
4021dbf39ea4SNikolay Borisov 				ctx, min_key, &max_key);
40224a500fd1SYan, Zheng 		if (ret)
40234a500fd1SYan, Zheng 			return ret;
4024e02119d5SChris Mason 		if (max_key == (u64)-1)
4025e02119d5SChris Mason 			break;
4026e02119d5SChris Mason 		min_key = max_key + 1;
4027e02119d5SChris Mason 	}
4028e02119d5SChris Mason 
4029dc287224SFilipe Manana 	inode->last_dir_index_offset = ctx->last_dir_item_offset;
4030339d0354SFilipe Manana 
4031e02119d5SChris Mason 	return 0;
4032e02119d5SChris Mason }
4033e02119d5SChris Mason 
4034e02119d5SChris Mason /*
4035e02119d5SChris Mason  * a helper function to drop items from the log before we relog an
4036e02119d5SChris Mason  * inode.  max_key_type indicates the highest item type to remove.
4037e02119d5SChris Mason  * This cannot be run for file data extents because it does not
4038e02119d5SChris Mason  * free the extents they point to.
4039e02119d5SChris Mason  */
404088e221cdSFilipe Manana static int drop_inode_items(struct btrfs_trans_handle *trans,
4041e02119d5SChris Mason 				  struct btrfs_root *log,
4042e02119d5SChris Mason 				  struct btrfs_path *path,
404388e221cdSFilipe Manana 				  struct btrfs_inode *inode,
404488e221cdSFilipe Manana 				  int max_key_type)
4045e02119d5SChris Mason {
4046e02119d5SChris Mason 	int ret;
4047e02119d5SChris Mason 	struct btrfs_key key;
4048e02119d5SChris Mason 	struct btrfs_key found_key;
404918ec90d6SJosef Bacik 	int start_slot;
4050e02119d5SChris Mason 
405188e221cdSFilipe Manana 	if (!inode_logged(trans, inode))
405288e221cdSFilipe Manana 		return 0;
405388e221cdSFilipe Manana 
405488e221cdSFilipe Manana 	key.objectid = btrfs_ino(inode);
4055e02119d5SChris Mason 	key.type = max_key_type;
4056e02119d5SChris Mason 	key.offset = (u64)-1;
4057e02119d5SChris Mason 
4058e02119d5SChris Mason 	while (1) {
4059e02119d5SChris Mason 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
40603650860bSJosef Bacik 		BUG_ON(ret == 0); /* Logic error */
40614a500fd1SYan, Zheng 		if (ret < 0)
4062e02119d5SChris Mason 			break;
4063e02119d5SChris Mason 
4064e02119d5SChris Mason 		if (path->slots[0] == 0)
4065e02119d5SChris Mason 			break;
4066e02119d5SChris Mason 
4067e02119d5SChris Mason 		path->slots[0]--;
4068e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4069e02119d5SChris Mason 				      path->slots[0]);
4070e02119d5SChris Mason 
407188e221cdSFilipe Manana 		if (found_key.objectid != key.objectid)
4072e02119d5SChris Mason 			break;
4073e02119d5SChris Mason 
407418ec90d6SJosef Bacik 		found_key.offset = 0;
407518ec90d6SJosef Bacik 		found_key.type = 0;
4076e3b83361SQu Wenruo 		ret = btrfs_bin_search(path->nodes[0], &found_key, &start_slot);
4077cbca7d59SFilipe Manana 		if (ret < 0)
4078cbca7d59SFilipe Manana 			break;
407918ec90d6SJosef Bacik 
408018ec90d6SJosef Bacik 		ret = btrfs_del_items(trans, log, path, start_slot,
408118ec90d6SJosef Bacik 				      path->slots[0] - start_slot + 1);
408218ec90d6SJosef Bacik 		/*
408318ec90d6SJosef Bacik 		 * If start slot isn't 0 then we don't need to re-search, we've
408418ec90d6SJosef Bacik 		 * found the last guy with the objectid in this tree.
408518ec90d6SJosef Bacik 		 */
408618ec90d6SJosef Bacik 		if (ret || start_slot != 0)
408765a246c5STsutomu Itoh 			break;
4088b3b4aa74SDavid Sterba 		btrfs_release_path(path);
4089e02119d5SChris Mason 	}
4090b3b4aa74SDavid Sterba 	btrfs_release_path(path);
40915bdbeb21SJosef Bacik 	if (ret > 0)
40925bdbeb21SJosef Bacik 		ret = 0;
40934a500fd1SYan, Zheng 	return ret;
4094e02119d5SChris Mason }
4095e02119d5SChris Mason 
40968a2b3da1SFilipe Manana static int truncate_inode_items(struct btrfs_trans_handle *trans,
40978a2b3da1SFilipe Manana 				struct btrfs_root *log_root,
40988a2b3da1SFilipe Manana 				struct btrfs_inode *inode,
40998a2b3da1SFilipe Manana 				u64 new_size, u32 min_type)
41008a2b3da1SFilipe Manana {
4101d9ac19c3SJosef Bacik 	struct btrfs_truncate_control control = {
4102d9ac19c3SJosef Bacik 		.new_size = new_size,
4103d9ac19c3SJosef Bacik 		.min_type = min_type,
4104*5caa490eSJosef Bacik 		.skip_ref_updates = true,
4105d9ac19c3SJosef Bacik 	};
41068a2b3da1SFilipe Manana 	int ret;
41078a2b3da1SFilipe Manana 
41088a2b3da1SFilipe Manana 	do {
41098a2b3da1SFilipe Manana 		ret = btrfs_truncate_inode_items(trans, log_root, inode,
4110d9ac19c3SJosef Bacik 						 &control);
41118a2b3da1SFilipe Manana 	} while (ret == -EAGAIN);
41128a2b3da1SFilipe Manana 
41138a2b3da1SFilipe Manana 	return ret;
41148a2b3da1SFilipe Manana }
41158a2b3da1SFilipe Manana 
411694edf4aeSJosef Bacik static void fill_inode_item(struct btrfs_trans_handle *trans,
411794edf4aeSJosef Bacik 			    struct extent_buffer *leaf,
411894edf4aeSJosef Bacik 			    struct btrfs_inode_item *item,
41191a4bcf47SFilipe Manana 			    struct inode *inode, int log_inode_only,
41201a4bcf47SFilipe Manana 			    u64 logged_isize)
412194edf4aeSJosef Bacik {
41220b1c6ccaSJosef Bacik 	struct btrfs_map_token token;
412377eea05eSBoris Burkov 	u64 flags;
412494edf4aeSJosef Bacik 
4125c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
412694edf4aeSJosef Bacik 
412794edf4aeSJosef Bacik 	if (log_inode_only) {
412894edf4aeSJosef Bacik 		/* set the generation to zero so the recover code
412994edf4aeSJosef Bacik 		 * can tell the difference between an logging
413094edf4aeSJosef Bacik 		 * just to say 'this inode exists' and a logging
413194edf4aeSJosef Bacik 		 * to say 'update this inode with these values'
413294edf4aeSJosef Bacik 		 */
4133cc4c13d5SDavid Sterba 		btrfs_set_token_inode_generation(&token, item, 0);
4134cc4c13d5SDavid Sterba 		btrfs_set_token_inode_size(&token, item, logged_isize);
413594edf4aeSJosef Bacik 	} else {
4136cc4c13d5SDavid Sterba 		btrfs_set_token_inode_generation(&token, item,
4137cc4c13d5SDavid Sterba 						 BTRFS_I(inode)->generation);
4138cc4c13d5SDavid Sterba 		btrfs_set_token_inode_size(&token, item, inode->i_size);
413994edf4aeSJosef Bacik 	}
414094edf4aeSJosef Bacik 
4141cc4c13d5SDavid Sterba 	btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4142cc4c13d5SDavid Sterba 	btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4143cc4c13d5SDavid Sterba 	btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4144cc4c13d5SDavid Sterba 	btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
41450b1c6ccaSJosef Bacik 
4146cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_sec(&token, &item->atime,
4147cc4c13d5SDavid Sterba 				     inode->i_atime.tv_sec);
4148cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_nsec(&token, &item->atime,
4149cc4c13d5SDavid Sterba 				      inode->i_atime.tv_nsec);
41500b1c6ccaSJosef Bacik 
4151cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_sec(&token, &item->mtime,
4152cc4c13d5SDavid Sterba 				     inode->i_mtime.tv_sec);
4153cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_nsec(&token, &item->mtime,
4154cc4c13d5SDavid Sterba 				      inode->i_mtime.tv_nsec);
41550b1c6ccaSJosef Bacik 
4156cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_sec(&token, &item->ctime,
4157cc4c13d5SDavid Sterba 				     inode->i_ctime.tv_sec);
4158cc4c13d5SDavid Sterba 	btrfs_set_token_timespec_nsec(&token, &item->ctime,
4159cc4c13d5SDavid Sterba 				      inode->i_ctime.tv_nsec);
41600b1c6ccaSJosef Bacik 
4161e593e54eSFilipe Manana 	/*
4162e593e54eSFilipe Manana 	 * We do not need to set the nbytes field, in fact during a fast fsync
4163e593e54eSFilipe Manana 	 * its value may not even be correct, since a fast fsync does not wait
4164e593e54eSFilipe Manana 	 * for ordered extent completion, which is where we update nbytes, it
4165e593e54eSFilipe Manana 	 * only waits for writeback to complete. During log replay as we find
4166e593e54eSFilipe Manana 	 * file extent items and replay them, we adjust the nbytes field of the
4167e593e54eSFilipe Manana 	 * inode item in subvolume tree as needed (see overwrite_item()).
4168e593e54eSFilipe Manana 	 */
41690b1c6ccaSJosef Bacik 
4170cc4c13d5SDavid Sterba 	btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4171cc4c13d5SDavid Sterba 	btrfs_set_token_inode_transid(&token, item, trans->transid);
4172cc4c13d5SDavid Sterba 	btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
417377eea05eSBoris Burkov 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
417477eea05eSBoris Burkov 					  BTRFS_I(inode)->ro_flags);
417577eea05eSBoris Burkov 	btrfs_set_token_inode_flags(&token, item, flags);
4176cc4c13d5SDavid Sterba 	btrfs_set_token_inode_block_group(&token, item, 0);
417794edf4aeSJosef Bacik }
417894edf4aeSJosef Bacik 
4179a95249b3SJosef Bacik static int log_inode_item(struct btrfs_trans_handle *trans,
4180a95249b3SJosef Bacik 			  struct btrfs_root *log, struct btrfs_path *path,
41812ac691d8SFilipe Manana 			  struct btrfs_inode *inode, bool inode_item_dropped)
4182a95249b3SJosef Bacik {
4183a95249b3SJosef Bacik 	struct btrfs_inode_item *inode_item;
4184a95249b3SJosef Bacik 	int ret;
4185a95249b3SJosef Bacik 
41862ac691d8SFilipe Manana 	/*
41872ac691d8SFilipe Manana 	 * If we are doing a fast fsync and the inode was logged before in the
41882ac691d8SFilipe Manana 	 * current transaction, then we know the inode was previously logged and
41892ac691d8SFilipe Manana 	 * it exists in the log tree. For performance reasons, in this case use
41902ac691d8SFilipe Manana 	 * btrfs_search_slot() directly with ins_len set to 0 so that we never
41912ac691d8SFilipe Manana 	 * attempt a write lock on the leaf's parent, which adds unnecessary lock
41922ac691d8SFilipe Manana 	 * contention in case there are concurrent fsyncs for other inodes of the
41932ac691d8SFilipe Manana 	 * same subvolume. Using btrfs_insert_empty_item() when the inode item
41942ac691d8SFilipe Manana 	 * already exists can also result in unnecessarily splitting a leaf.
41952ac691d8SFilipe Manana 	 */
41962ac691d8SFilipe Manana 	if (!inode_item_dropped && inode->logged_trans == trans->transid) {
41972ac691d8SFilipe Manana 		ret = btrfs_search_slot(trans, log, &inode->location, path, 0, 1);
41982ac691d8SFilipe Manana 		ASSERT(ret <= 0);
41992ac691d8SFilipe Manana 		if (ret > 0)
42002ac691d8SFilipe Manana 			ret = -ENOENT;
42012ac691d8SFilipe Manana 	} else {
42022ac691d8SFilipe Manana 		/*
42032ac691d8SFilipe Manana 		 * This means it is the first fsync in the current transaction,
42042ac691d8SFilipe Manana 		 * so the inode item is not in the log and we need to insert it.
42052ac691d8SFilipe Manana 		 * We can never get -EEXIST because we are only called for a fast
42062ac691d8SFilipe Manana 		 * fsync and in case an inode eviction happens after the inode was
42072ac691d8SFilipe Manana 		 * logged before in the current transaction, when we load again
42082ac691d8SFilipe Manana 		 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
42092ac691d8SFilipe Manana 		 * flags and set ->logged_trans to 0.
42102ac691d8SFilipe Manana 		 */
42112ac691d8SFilipe Manana 		ret = btrfs_insert_empty_item(trans, log, path, &inode->location,
42122ac691d8SFilipe Manana 					      sizeof(*inode_item));
42132ac691d8SFilipe Manana 		ASSERT(ret != -EEXIST);
42142ac691d8SFilipe Manana 	}
42152ac691d8SFilipe Manana 	if (ret)
4216a95249b3SJosef Bacik 		return ret;
4217a95249b3SJosef Bacik 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4218a95249b3SJosef Bacik 				    struct btrfs_inode_item);
42196d889a3bSNikolay Borisov 	fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
42206d889a3bSNikolay Borisov 			0, 0);
4221a95249b3SJosef Bacik 	btrfs_release_path(path);
4222a95249b3SJosef Bacik 	return 0;
4223a95249b3SJosef Bacik }
4224a95249b3SJosef Bacik 
422540e046acSFilipe Manana static int log_csums(struct btrfs_trans_handle *trans,
42263ebac17cSFilipe Manana 		     struct btrfs_inode *inode,
422740e046acSFilipe Manana 		     struct btrfs_root *log_root,
422840e046acSFilipe Manana 		     struct btrfs_ordered_sum *sums)
422940e046acSFilipe Manana {
4230e289f03eSFilipe Manana 	const u64 lock_end = sums->bytenr + sums->len - 1;
4231e289f03eSFilipe Manana 	struct extent_state *cached_state = NULL;
423240e046acSFilipe Manana 	int ret;
423340e046acSFilipe Manana 
423440e046acSFilipe Manana 	/*
42353ebac17cSFilipe Manana 	 * If this inode was not used for reflink operations in the current
42363ebac17cSFilipe Manana 	 * transaction with new extents, then do the fast path, no need to
42373ebac17cSFilipe Manana 	 * worry about logging checksum items with overlapping ranges.
42383ebac17cSFilipe Manana 	 */
42393ebac17cSFilipe Manana 	if (inode->last_reflink_trans < trans->transid)
42403ebac17cSFilipe Manana 		return btrfs_csum_file_blocks(trans, log_root, sums);
42413ebac17cSFilipe Manana 
42423ebac17cSFilipe Manana 	/*
4243e289f03eSFilipe Manana 	 * Serialize logging for checksums. This is to avoid racing with the
4244e289f03eSFilipe Manana 	 * same checksum being logged by another task that is logging another
4245e289f03eSFilipe Manana 	 * file which happens to refer to the same extent as well. Such races
4246e289f03eSFilipe Manana 	 * can leave checksum items in the log with overlapping ranges.
4247e289f03eSFilipe Manana 	 */
4248e289f03eSFilipe Manana 	ret = lock_extent_bits(&log_root->log_csum_range, sums->bytenr,
4249e289f03eSFilipe Manana 			       lock_end, &cached_state);
4250e289f03eSFilipe Manana 	if (ret)
4251e289f03eSFilipe Manana 		return ret;
4252e289f03eSFilipe Manana 	/*
425340e046acSFilipe Manana 	 * Due to extent cloning, we might have logged a csum item that covers a
425440e046acSFilipe Manana 	 * subrange of a cloned extent, and later we can end up logging a csum
425540e046acSFilipe Manana 	 * item for a larger subrange of the same extent or the entire range.
425640e046acSFilipe Manana 	 * This would leave csum items in the log tree that cover the same range
425740e046acSFilipe Manana 	 * and break the searches for checksums in the log tree, resulting in
425840e046acSFilipe Manana 	 * some checksums missing in the fs/subvolume tree. So just delete (or
425940e046acSFilipe Manana 	 * trim and adjust) any existing csum items in the log for this range.
426040e046acSFilipe Manana 	 */
426140e046acSFilipe Manana 	ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
4262e289f03eSFilipe Manana 	if (!ret)
4263e289f03eSFilipe Manana 		ret = btrfs_csum_file_blocks(trans, log_root, sums);
426440e046acSFilipe Manana 
4265e289f03eSFilipe Manana 	unlock_extent_cached(&log_root->log_csum_range, sums->bytenr, lock_end,
4266e289f03eSFilipe Manana 			     &cached_state);
4267e289f03eSFilipe Manana 
4268e289f03eSFilipe Manana 	return ret;
426940e046acSFilipe Manana }
427040e046acSFilipe Manana 
427131ff1cd2SChris Mason static noinline int copy_items(struct btrfs_trans_handle *trans,
427244d70e19SNikolay Borisov 			       struct btrfs_inode *inode,
427331ff1cd2SChris Mason 			       struct btrfs_path *dst_path,
42740e56315cSFilipe Manana 			       struct btrfs_path *src_path,
42751a4bcf47SFilipe Manana 			       int start_slot, int nr, int inode_only,
42761a4bcf47SFilipe Manana 			       u64 logged_isize)
427731ff1cd2SChris Mason {
42783ffbd68cSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
427931ff1cd2SChris Mason 	unsigned long src_offset;
428031ff1cd2SChris Mason 	unsigned long dst_offset;
428144d70e19SNikolay Borisov 	struct btrfs_root *log = inode->root->log_root;
428231ff1cd2SChris Mason 	struct btrfs_file_extent_item *extent;
428331ff1cd2SChris Mason 	struct btrfs_inode_item *inode_item;
428416e7549fSJosef Bacik 	struct extent_buffer *src = src_path->nodes[0];
428531ff1cd2SChris Mason 	int ret;
428631ff1cd2SChris Mason 	struct btrfs_key *ins_keys;
428731ff1cd2SChris Mason 	u32 *ins_sizes;
4288b7ef5f3aSFilipe Manana 	struct btrfs_item_batch batch;
428931ff1cd2SChris Mason 	char *ins_data;
429031ff1cd2SChris Mason 	int i;
4291d20f7043SChris Mason 	struct list_head ordered_sums;
429244d70e19SNikolay Borisov 	int skip_csum = inode->flags & BTRFS_INODE_NODATASUM;
4293d20f7043SChris Mason 
4294d20f7043SChris Mason 	INIT_LIST_HEAD(&ordered_sums);
429531ff1cd2SChris Mason 
429631ff1cd2SChris Mason 	ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
429731ff1cd2SChris Mason 			   nr * sizeof(u32), GFP_NOFS);
42982a29edc6Sliubo 	if (!ins_data)
42992a29edc6Sliubo 		return -ENOMEM;
43002a29edc6Sliubo 
430131ff1cd2SChris Mason 	ins_sizes = (u32 *)ins_data;
430231ff1cd2SChris Mason 	ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4303b7ef5f3aSFilipe Manana 	batch.keys = ins_keys;
4304b7ef5f3aSFilipe Manana 	batch.data_sizes = ins_sizes;
4305b7ef5f3aSFilipe Manana 	batch.total_data_size = 0;
4306b7ef5f3aSFilipe Manana 	batch.nr = nr;
430731ff1cd2SChris Mason 
430831ff1cd2SChris Mason 	for (i = 0; i < nr; i++) {
43093212fa14SJosef Bacik 		ins_sizes[i] = btrfs_item_size(src, i + start_slot);
4310b7ef5f3aSFilipe Manana 		batch.total_data_size += ins_sizes[i];
431131ff1cd2SChris Mason 		btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
431231ff1cd2SChris Mason 	}
4313b7ef5f3aSFilipe Manana 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
43144a500fd1SYan, Zheng 	if (ret) {
43154a500fd1SYan, Zheng 		kfree(ins_data);
43164a500fd1SYan, Zheng 		return ret;
43174a500fd1SYan, Zheng 	}
431831ff1cd2SChris Mason 
43195d4f98a2SYan Zheng 	for (i = 0; i < nr; i++, dst_path->slots[0]++) {
432031ff1cd2SChris Mason 		dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
432131ff1cd2SChris Mason 						   dst_path->slots[0]);
432231ff1cd2SChris Mason 
432331ff1cd2SChris Mason 		src_offset = btrfs_item_ptr_offset(src, start_slot + i);
432431ff1cd2SChris Mason 
432594edf4aeSJosef Bacik 		if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
432631ff1cd2SChris Mason 			inode_item = btrfs_item_ptr(dst_path->nodes[0],
432731ff1cd2SChris Mason 						    dst_path->slots[0],
432831ff1cd2SChris Mason 						    struct btrfs_inode_item);
432994edf4aeSJosef Bacik 			fill_inode_item(trans, dst_path->nodes[0], inode_item,
4330f85b7379SDavid Sterba 					&inode->vfs_inode,
4331f85b7379SDavid Sterba 					inode_only == LOG_INODE_EXISTS,
43321a4bcf47SFilipe Manana 					logged_isize);
433394edf4aeSJosef Bacik 		} else {
433494edf4aeSJosef Bacik 			copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
433594edf4aeSJosef Bacik 					   src_offset, ins_sizes[i]);
433631ff1cd2SChris Mason 		}
433794edf4aeSJosef Bacik 
433831ff1cd2SChris Mason 		/* take a reference on file data extents so that truncates
433931ff1cd2SChris Mason 		 * or deletes of this inode don't have to relog the inode
434031ff1cd2SChris Mason 		 * again
434131ff1cd2SChris Mason 		 */
4342962a298fSDavid Sterba 		if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY &&
4343d2794405SLiu Bo 		    !skip_csum) {
434431ff1cd2SChris Mason 			int found_type;
434531ff1cd2SChris Mason 			extent = btrfs_item_ptr(src, start_slot + i,
434631ff1cd2SChris Mason 						struct btrfs_file_extent_item);
434731ff1cd2SChris Mason 
43488e531cdfSliubo 			if (btrfs_file_extent_generation(src, extent) < trans->transid)
43498e531cdfSliubo 				continue;
43508e531cdfSliubo 
435131ff1cd2SChris Mason 			found_type = btrfs_file_extent_type(src, extent);
43526f1fed77SJosef Bacik 			if (found_type == BTRFS_FILE_EXTENT_REG) {
4353fc28b25eSJosef Bacik 				struct btrfs_root *csum_root;
43545d4f98a2SYan Zheng 				u64 ds, dl, cs, cl;
43555d4f98a2SYan Zheng 				ds = btrfs_file_extent_disk_bytenr(src,
435631ff1cd2SChris Mason 								extent);
43575d4f98a2SYan Zheng 				/* ds == 0 is a hole */
43585d4f98a2SYan Zheng 				if (ds == 0)
43595d4f98a2SYan Zheng 					continue;
43605d4f98a2SYan Zheng 
43615d4f98a2SYan Zheng 				dl = btrfs_file_extent_disk_num_bytes(src,
436231ff1cd2SChris Mason 								extent);
43635d4f98a2SYan Zheng 				cs = btrfs_file_extent_offset(src, extent);
43645d4f98a2SYan Zheng 				cl = btrfs_file_extent_num_bytes(src,
4365a419aef8SJoe Perches 								extent);
4366580afd76SChris Mason 				if (btrfs_file_extent_compression(src,
4367580afd76SChris Mason 								  extent)) {
4368580afd76SChris Mason 					cs = 0;
4369580afd76SChris Mason 					cl = dl;
4370580afd76SChris Mason 				}
43715d4f98a2SYan Zheng 
4372fc28b25eSJosef Bacik 				csum_root = btrfs_csum_root(fs_info, ds);
4373fc28b25eSJosef Bacik 				ret = btrfs_lookup_csums_range(csum_root,
437407d400a6SYan Zheng 						ds + cs, ds + cs + cl - 1,
4375a2de733cSArne Jansen 						&ordered_sums, 0);
43764f26433eSFilipe Manana 				if (ret)
43774f26433eSFilipe Manana 					break;
437831ff1cd2SChris Mason 			}
437931ff1cd2SChris Mason 		}
438031ff1cd2SChris Mason 	}
438131ff1cd2SChris Mason 
438231ff1cd2SChris Mason 	btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4383b3b4aa74SDavid Sterba 	btrfs_release_path(dst_path);
438431ff1cd2SChris Mason 	kfree(ins_data);
4385d20f7043SChris Mason 
4386d20f7043SChris Mason 	/*
4387d20f7043SChris Mason 	 * we have to do this after the loop above to avoid changing the
4388d20f7043SChris Mason 	 * log tree while trying to change the log tree.
4389d20f7043SChris Mason 	 */
4390d20f7043SChris Mason 	while (!list_empty(&ordered_sums)) {
4391d20f7043SChris Mason 		struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4392d20f7043SChris Mason 						   struct btrfs_ordered_sum,
4393d20f7043SChris Mason 						   list);
43944a500fd1SYan, Zheng 		if (!ret)
43953ebac17cSFilipe Manana 			ret = log_csums(trans, inode, log, sums);
4396d20f7043SChris Mason 		list_del(&sums->list);
4397d20f7043SChris Mason 		kfree(sums);
4398d20f7043SChris Mason 	}
439916e7549fSJosef Bacik 
44004a500fd1SYan, Zheng 	return ret;
440131ff1cd2SChris Mason }
440231ff1cd2SChris Mason 
44034f0f586bSSami Tolvanen static int extent_cmp(void *priv, const struct list_head *a,
44044f0f586bSSami Tolvanen 		      const struct list_head *b)
44055dc562c5SJosef Bacik {
4406214cc184SDavid Sterba 	const struct extent_map *em1, *em2;
44075dc562c5SJosef Bacik 
44085dc562c5SJosef Bacik 	em1 = list_entry(a, struct extent_map, list);
44095dc562c5SJosef Bacik 	em2 = list_entry(b, struct extent_map, list);
44105dc562c5SJosef Bacik 
44115dc562c5SJosef Bacik 	if (em1->start < em2->start)
44125dc562c5SJosef Bacik 		return -1;
44135dc562c5SJosef Bacik 	else if (em1->start > em2->start)
44145dc562c5SJosef Bacik 		return 1;
44155dc562c5SJosef Bacik 	return 0;
44165dc562c5SJosef Bacik }
44175dc562c5SJosef Bacik 
4418e7175a69SJosef Bacik static int log_extent_csums(struct btrfs_trans_handle *trans,
4419e7175a69SJosef Bacik 			    struct btrfs_inode *inode,
4420a9ecb653SNikolay Borisov 			    struct btrfs_root *log_root,
442148778179SFilipe Manana 			    const struct extent_map *em,
442248778179SFilipe Manana 			    struct btrfs_log_ctx *ctx)
44235dc562c5SJosef Bacik {
442448778179SFilipe Manana 	struct btrfs_ordered_extent *ordered;
4425fc28b25eSJosef Bacik 	struct btrfs_root *csum_root;
44262ab28f32SJosef Bacik 	u64 csum_offset;
44272ab28f32SJosef Bacik 	u64 csum_len;
442848778179SFilipe Manana 	u64 mod_start = em->mod_start;
442948778179SFilipe Manana 	u64 mod_len = em->mod_len;
44308407f553SFilipe Manana 	LIST_HEAD(ordered_sums);
44318407f553SFilipe Manana 	int ret = 0;
443209a2a8f9SJosef Bacik 
4433e7175a69SJosef Bacik 	if (inode->flags & BTRFS_INODE_NODATASUM ||
4434e7175a69SJosef Bacik 	    test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
44358407f553SFilipe Manana 	    em->block_start == EXTENT_MAP_HOLE)
443670c8a91cSJosef Bacik 		return 0;
443770c8a91cSJosef Bacik 
443848778179SFilipe Manana 	list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
443948778179SFilipe Manana 		const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
444048778179SFilipe Manana 		const u64 mod_end = mod_start + mod_len;
444148778179SFilipe Manana 		struct btrfs_ordered_sum *sums;
444248778179SFilipe Manana 
444348778179SFilipe Manana 		if (mod_len == 0)
444448778179SFilipe Manana 			break;
444548778179SFilipe Manana 
444648778179SFilipe Manana 		if (ordered_end <= mod_start)
444748778179SFilipe Manana 			continue;
444848778179SFilipe Manana 		if (mod_end <= ordered->file_offset)
444948778179SFilipe Manana 			break;
445048778179SFilipe Manana 
445148778179SFilipe Manana 		/*
445248778179SFilipe Manana 		 * We are going to copy all the csums on this ordered extent, so
445348778179SFilipe Manana 		 * go ahead and adjust mod_start and mod_len in case this ordered
445448778179SFilipe Manana 		 * extent has already been logged.
445548778179SFilipe Manana 		 */
445648778179SFilipe Manana 		if (ordered->file_offset > mod_start) {
445748778179SFilipe Manana 			if (ordered_end >= mod_end)
445848778179SFilipe Manana 				mod_len = ordered->file_offset - mod_start;
445948778179SFilipe Manana 			/*
446048778179SFilipe Manana 			 * If we have this case
446148778179SFilipe Manana 			 *
446248778179SFilipe Manana 			 * |--------- logged extent ---------|
446348778179SFilipe Manana 			 *       |----- ordered extent ----|
446448778179SFilipe Manana 			 *
446548778179SFilipe Manana 			 * Just don't mess with mod_start and mod_len, we'll
446648778179SFilipe Manana 			 * just end up logging more csums than we need and it
446748778179SFilipe Manana 			 * will be ok.
446848778179SFilipe Manana 			 */
446948778179SFilipe Manana 		} else {
447048778179SFilipe Manana 			if (ordered_end < mod_end) {
447148778179SFilipe Manana 				mod_len = mod_end - ordered_end;
447248778179SFilipe Manana 				mod_start = ordered_end;
447348778179SFilipe Manana 			} else {
447448778179SFilipe Manana 				mod_len = 0;
447548778179SFilipe Manana 			}
447648778179SFilipe Manana 		}
447748778179SFilipe Manana 
447848778179SFilipe Manana 		/*
447948778179SFilipe Manana 		 * To keep us from looping for the above case of an ordered
448048778179SFilipe Manana 		 * extent that falls inside of the logged extent.
448148778179SFilipe Manana 		 */
448248778179SFilipe Manana 		if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
448348778179SFilipe Manana 			continue;
448448778179SFilipe Manana 
448548778179SFilipe Manana 		list_for_each_entry(sums, &ordered->list, list) {
448648778179SFilipe Manana 			ret = log_csums(trans, inode, log_root, sums);
448748778179SFilipe Manana 			if (ret)
448848778179SFilipe Manana 				return ret;
448948778179SFilipe Manana 		}
449048778179SFilipe Manana 	}
449148778179SFilipe Manana 
449248778179SFilipe Manana 	/* We're done, found all csums in the ordered extents. */
449348778179SFilipe Manana 	if (mod_len == 0)
449448778179SFilipe Manana 		return 0;
449548778179SFilipe Manana 
4496e7175a69SJosef Bacik 	/* If we're compressed we have to save the entire range of csums. */
4497488111aaSFilipe David Borba Manana 	if (em->compress_type) {
4498488111aaSFilipe David Borba Manana 		csum_offset = 0;
44998407f553SFilipe Manana 		csum_len = max(em->block_len, em->orig_block_len);
4500488111aaSFilipe David Borba Manana 	} else {
450148778179SFilipe Manana 		csum_offset = mod_start - em->start;
450248778179SFilipe Manana 		csum_len = mod_len;
4503488111aaSFilipe David Borba Manana 	}
45042ab28f32SJosef Bacik 
450570c8a91cSJosef Bacik 	/* block start is already adjusted for the file extent offset. */
4506fc28b25eSJosef Bacik 	csum_root = btrfs_csum_root(trans->fs_info, em->block_start);
4507fc28b25eSJosef Bacik 	ret = btrfs_lookup_csums_range(csum_root,
450870c8a91cSJosef Bacik 				       em->block_start + csum_offset,
450970c8a91cSJosef Bacik 				       em->block_start + csum_offset +
451070c8a91cSJosef Bacik 				       csum_len - 1, &ordered_sums, 0);
45115dc562c5SJosef Bacik 	if (ret)
45125dc562c5SJosef Bacik 		return ret;
451370c8a91cSJosef Bacik 
451470c8a91cSJosef Bacik 	while (!list_empty(&ordered_sums)) {
451570c8a91cSJosef Bacik 		struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
451670c8a91cSJosef Bacik 						   struct btrfs_ordered_sum,
451770c8a91cSJosef Bacik 						   list);
451870c8a91cSJosef Bacik 		if (!ret)
45193ebac17cSFilipe Manana 			ret = log_csums(trans, inode, log_root, sums);
452070c8a91cSJosef Bacik 		list_del(&sums->list);
452170c8a91cSJosef Bacik 		kfree(sums);
45225dc562c5SJosef Bacik 	}
45235dc562c5SJosef Bacik 
452470c8a91cSJosef Bacik 	return ret;
45255dc562c5SJosef Bacik }
45265dc562c5SJosef Bacik 
45278407f553SFilipe Manana static int log_one_extent(struct btrfs_trans_handle *trans,
452890d04510SFilipe Manana 			  struct btrfs_inode *inode,
45298407f553SFilipe Manana 			  const struct extent_map *em,
45308407f553SFilipe Manana 			  struct btrfs_path *path,
45318407f553SFilipe Manana 			  struct btrfs_log_ctx *ctx)
45328407f553SFilipe Manana {
45335893dfb9SFilipe Manana 	struct btrfs_drop_extents_args drop_args = { 0 };
453490d04510SFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
45358407f553SFilipe Manana 	struct btrfs_file_extent_item *fi;
45368407f553SFilipe Manana 	struct extent_buffer *leaf;
45378407f553SFilipe Manana 	struct btrfs_map_token token;
45388407f553SFilipe Manana 	struct btrfs_key key;
45398407f553SFilipe Manana 	u64 extent_offset = em->start - em->orig_start;
45408407f553SFilipe Manana 	u64 block_len;
45418407f553SFilipe Manana 	int ret;
45428407f553SFilipe Manana 
454348778179SFilipe Manana 	ret = log_extent_csums(trans, inode, log, em, ctx);
45448407f553SFilipe Manana 	if (ret)
45458407f553SFilipe Manana 		return ret;
45468407f553SFilipe Manana 
45475328b2a7SFilipe Manana 	/*
45485328b2a7SFilipe Manana 	 * If this is the first time we are logging the inode in the current
45495328b2a7SFilipe Manana 	 * transaction, we can avoid btrfs_drop_extents(), which is expensive
45505328b2a7SFilipe Manana 	 * because it does a deletion search, which always acquires write locks
45515328b2a7SFilipe Manana 	 * for extent buffers at levels 2, 1 and 0. This not only wastes time
45525328b2a7SFilipe Manana 	 * but also adds significant contention in a log tree, since log trees
45535328b2a7SFilipe Manana 	 * are small, with a root at level 2 or 3 at most, due to their short
45545328b2a7SFilipe Manana 	 * life span.
45555328b2a7SFilipe Manana 	 */
45565328b2a7SFilipe Manana 	if (inode_logged(trans, inode)) {
45575893dfb9SFilipe Manana 		drop_args.path = path;
45585893dfb9SFilipe Manana 		drop_args.start = em->start;
45595893dfb9SFilipe Manana 		drop_args.end = em->start + em->len;
45605893dfb9SFilipe Manana 		drop_args.replace_extent = true;
45615893dfb9SFilipe Manana 		drop_args.extent_item_size = sizeof(*fi);
45625893dfb9SFilipe Manana 		ret = btrfs_drop_extents(trans, log, inode, &drop_args);
45638407f553SFilipe Manana 		if (ret)
45648407f553SFilipe Manana 			return ret;
45655328b2a7SFilipe Manana 	}
45668407f553SFilipe Manana 
45675893dfb9SFilipe Manana 	if (!drop_args.extent_inserted) {
45689d122629SNikolay Borisov 		key.objectid = btrfs_ino(inode);
45698407f553SFilipe Manana 		key.type = BTRFS_EXTENT_DATA_KEY;
45708407f553SFilipe Manana 		key.offset = em->start;
45718407f553SFilipe Manana 
45728407f553SFilipe Manana 		ret = btrfs_insert_empty_item(trans, log, path, &key,
45738407f553SFilipe Manana 					      sizeof(*fi));
45748407f553SFilipe Manana 		if (ret)
45758407f553SFilipe Manana 			return ret;
45768407f553SFilipe Manana 	}
45778407f553SFilipe Manana 	leaf = path->nodes[0];
4578c82f823cSDavid Sterba 	btrfs_init_map_token(&token, leaf);
45798407f553SFilipe Manana 	fi = btrfs_item_ptr(leaf, path->slots[0],
45808407f553SFilipe Manana 			    struct btrfs_file_extent_item);
45818407f553SFilipe Manana 
4582cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_generation(&token, fi, trans->transid);
45838407f553SFilipe Manana 	if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4584cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_type(&token, fi,
4585cc4c13d5SDavid Sterba 						 BTRFS_FILE_EXTENT_PREALLOC);
45868407f553SFilipe Manana 	else
4587cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_type(&token, fi,
4588cc4c13d5SDavid Sterba 						 BTRFS_FILE_EXTENT_REG);
45898407f553SFilipe Manana 
45908407f553SFilipe Manana 	block_len = max(em->block_len, em->orig_block_len);
45918407f553SFilipe Manana 	if (em->compress_type != BTRFS_COMPRESS_NONE) {
4592cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_disk_bytenr(&token, fi,
4593cc4c13d5SDavid Sterba 							em->block_start);
4594cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_disk_num_bytes(&token, fi, block_len);
45958407f553SFilipe Manana 	} else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4596cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_disk_bytenr(&token, fi,
45978407f553SFilipe Manana 							em->block_start -
4598cc4c13d5SDavid Sterba 							extent_offset);
4599cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_disk_num_bytes(&token, fi, block_len);
46008407f553SFilipe Manana 	} else {
4601cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_disk_bytenr(&token, fi, 0);
4602cc4c13d5SDavid Sterba 		btrfs_set_token_file_extent_disk_num_bytes(&token, fi, 0);
46038407f553SFilipe Manana 	}
46048407f553SFilipe Manana 
4605cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_offset(&token, fi, extent_offset);
4606cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_num_bytes(&token, fi, em->len);
4607cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_ram_bytes(&token, fi, em->ram_bytes);
4608cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_compression(&token, fi, em->compress_type);
4609cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_encryption(&token, fi, 0);
4610cc4c13d5SDavid Sterba 	btrfs_set_token_file_extent_other_encoding(&token, fi, 0);
46118407f553SFilipe Manana 	btrfs_mark_buffer_dirty(leaf);
46128407f553SFilipe Manana 
46138407f553SFilipe Manana 	btrfs_release_path(path);
46148407f553SFilipe Manana 
46158407f553SFilipe Manana 	return ret;
46168407f553SFilipe Manana }
46178407f553SFilipe Manana 
461831d11b83SFilipe Manana /*
461931d11b83SFilipe Manana  * Log all prealloc extents beyond the inode's i_size to make sure we do not
462031d11b83SFilipe Manana  * lose them after doing a fast fsync and replaying the log. We scan the
462131d11b83SFilipe Manana  * subvolume's root instead of iterating the inode's extent map tree because
462231d11b83SFilipe Manana  * otherwise we can log incorrect extent items based on extent map conversion.
462331d11b83SFilipe Manana  * That can happen due to the fact that extent maps are merged when they
462431d11b83SFilipe Manana  * are not in the extent map tree's list of modified extents.
462531d11b83SFilipe Manana  */
462631d11b83SFilipe Manana static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
462731d11b83SFilipe Manana 				      struct btrfs_inode *inode,
462831d11b83SFilipe Manana 				      struct btrfs_path *path)
462931d11b83SFilipe Manana {
463031d11b83SFilipe Manana 	struct btrfs_root *root = inode->root;
463131d11b83SFilipe Manana 	struct btrfs_key key;
463231d11b83SFilipe Manana 	const u64 i_size = i_size_read(&inode->vfs_inode);
463331d11b83SFilipe Manana 	const u64 ino = btrfs_ino(inode);
463431d11b83SFilipe Manana 	struct btrfs_path *dst_path = NULL;
46350e56315cSFilipe Manana 	bool dropped_extents = false;
4636f135cea3SFilipe Manana 	u64 truncate_offset = i_size;
4637f135cea3SFilipe Manana 	struct extent_buffer *leaf;
4638f135cea3SFilipe Manana 	int slot;
463931d11b83SFilipe Manana 	int ins_nr = 0;
464031d11b83SFilipe Manana 	int start_slot;
464131d11b83SFilipe Manana 	int ret;
464231d11b83SFilipe Manana 
464331d11b83SFilipe Manana 	if (!(inode->flags & BTRFS_INODE_PREALLOC))
464431d11b83SFilipe Manana 		return 0;
464531d11b83SFilipe Manana 
464631d11b83SFilipe Manana 	key.objectid = ino;
464731d11b83SFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
464831d11b83SFilipe Manana 	key.offset = i_size;
464931d11b83SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
465031d11b83SFilipe Manana 	if (ret < 0)
465131d11b83SFilipe Manana 		goto out;
465231d11b83SFilipe Manana 
4653f135cea3SFilipe Manana 	/*
4654f135cea3SFilipe Manana 	 * We must check if there is a prealloc extent that starts before the
4655f135cea3SFilipe Manana 	 * i_size and crosses the i_size boundary. This is to ensure later we
4656f135cea3SFilipe Manana 	 * truncate down to the end of that extent and not to the i_size, as
4657f135cea3SFilipe Manana 	 * otherwise we end up losing part of the prealloc extent after a log
4658f135cea3SFilipe Manana 	 * replay and with an implicit hole if there is another prealloc extent
4659f135cea3SFilipe Manana 	 * that starts at an offset beyond i_size.
4660f135cea3SFilipe Manana 	 */
4661f135cea3SFilipe Manana 	ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4662f135cea3SFilipe Manana 	if (ret < 0)
4663f135cea3SFilipe Manana 		goto out;
4664f135cea3SFilipe Manana 
4665f135cea3SFilipe Manana 	if (ret == 0) {
4666f135cea3SFilipe Manana 		struct btrfs_file_extent_item *ei;
4667f135cea3SFilipe Manana 
4668f135cea3SFilipe Manana 		leaf = path->nodes[0];
4669f135cea3SFilipe Manana 		slot = path->slots[0];
4670f135cea3SFilipe Manana 		ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4671f135cea3SFilipe Manana 
4672f135cea3SFilipe Manana 		if (btrfs_file_extent_type(leaf, ei) ==
4673f135cea3SFilipe Manana 		    BTRFS_FILE_EXTENT_PREALLOC) {
4674f135cea3SFilipe Manana 			u64 extent_end;
4675f135cea3SFilipe Manana 
4676f135cea3SFilipe Manana 			btrfs_item_key_to_cpu(leaf, &key, slot);
4677f135cea3SFilipe Manana 			extent_end = key.offset +
4678f135cea3SFilipe Manana 				btrfs_file_extent_num_bytes(leaf, ei);
4679f135cea3SFilipe Manana 
4680f135cea3SFilipe Manana 			if (extent_end > i_size)
4681f135cea3SFilipe Manana 				truncate_offset = extent_end;
4682f135cea3SFilipe Manana 		}
4683f135cea3SFilipe Manana 	} else {
4684f135cea3SFilipe Manana 		ret = 0;
4685f135cea3SFilipe Manana 	}
4686f135cea3SFilipe Manana 
468731d11b83SFilipe Manana 	while (true) {
4688f135cea3SFilipe Manana 		leaf = path->nodes[0];
4689f135cea3SFilipe Manana 		slot = path->slots[0];
469031d11b83SFilipe Manana 
469131d11b83SFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
469231d11b83SFilipe Manana 			if (ins_nr > 0) {
469331d11b83SFilipe Manana 				ret = copy_items(trans, inode, dst_path, path,
46940e56315cSFilipe Manana 						 start_slot, ins_nr, 1, 0);
469531d11b83SFilipe Manana 				if (ret < 0)
469631d11b83SFilipe Manana 					goto out;
469731d11b83SFilipe Manana 				ins_nr = 0;
469831d11b83SFilipe Manana 			}
469931d11b83SFilipe Manana 			ret = btrfs_next_leaf(root, path);
470031d11b83SFilipe Manana 			if (ret < 0)
470131d11b83SFilipe Manana 				goto out;
470231d11b83SFilipe Manana 			if (ret > 0) {
470331d11b83SFilipe Manana 				ret = 0;
470431d11b83SFilipe Manana 				break;
470531d11b83SFilipe Manana 			}
470631d11b83SFilipe Manana 			continue;
470731d11b83SFilipe Manana 		}
470831d11b83SFilipe Manana 
470931d11b83SFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
471031d11b83SFilipe Manana 		if (key.objectid > ino)
471131d11b83SFilipe Manana 			break;
471231d11b83SFilipe Manana 		if (WARN_ON_ONCE(key.objectid < ino) ||
471331d11b83SFilipe Manana 		    key.type < BTRFS_EXTENT_DATA_KEY ||
471431d11b83SFilipe Manana 		    key.offset < i_size) {
471531d11b83SFilipe Manana 			path->slots[0]++;
471631d11b83SFilipe Manana 			continue;
471731d11b83SFilipe Manana 		}
47180e56315cSFilipe Manana 		if (!dropped_extents) {
471931d11b83SFilipe Manana 			/*
472031d11b83SFilipe Manana 			 * Avoid logging extent items logged in past fsync calls
472131d11b83SFilipe Manana 			 * and leading to duplicate keys in the log tree.
472231d11b83SFilipe Manana 			 */
47238a2b3da1SFilipe Manana 			ret = truncate_inode_items(trans, root->log_root, inode,
47248a2b3da1SFilipe Manana 						   truncate_offset,
47258a2b3da1SFilipe Manana 						   BTRFS_EXTENT_DATA_KEY);
472631d11b83SFilipe Manana 			if (ret)
472731d11b83SFilipe Manana 				goto out;
47280e56315cSFilipe Manana 			dropped_extents = true;
472931d11b83SFilipe Manana 		}
473031d11b83SFilipe Manana 		if (ins_nr == 0)
473131d11b83SFilipe Manana 			start_slot = slot;
473231d11b83SFilipe Manana 		ins_nr++;
473331d11b83SFilipe Manana 		path->slots[0]++;
473431d11b83SFilipe Manana 		if (!dst_path) {
473531d11b83SFilipe Manana 			dst_path = btrfs_alloc_path();
473631d11b83SFilipe Manana 			if (!dst_path) {
473731d11b83SFilipe Manana 				ret = -ENOMEM;
473831d11b83SFilipe Manana 				goto out;
473931d11b83SFilipe Manana 			}
474031d11b83SFilipe Manana 		}
474131d11b83SFilipe Manana 	}
47420bc2d3c0SFilipe Manana 	if (ins_nr > 0)
47430e56315cSFilipe Manana 		ret = copy_items(trans, inode, dst_path, path,
474431d11b83SFilipe Manana 				 start_slot, ins_nr, 1, 0);
474531d11b83SFilipe Manana out:
474631d11b83SFilipe Manana 	btrfs_release_path(path);
474731d11b83SFilipe Manana 	btrfs_free_path(dst_path);
474831d11b83SFilipe Manana 	return ret;
474931d11b83SFilipe Manana }
475031d11b83SFilipe Manana 
47515dc562c5SJosef Bacik static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
47529d122629SNikolay Borisov 				     struct btrfs_inode *inode,
4753827463c4SMiao Xie 				     struct btrfs_path *path,
475448778179SFilipe Manana 				     struct btrfs_log_ctx *ctx)
47555dc562c5SJosef Bacik {
475648778179SFilipe Manana 	struct btrfs_ordered_extent *ordered;
475748778179SFilipe Manana 	struct btrfs_ordered_extent *tmp;
47585dc562c5SJosef Bacik 	struct extent_map *em, *n;
47595dc562c5SJosef Bacik 	struct list_head extents;
47609d122629SNikolay Borisov 	struct extent_map_tree *tree = &inode->extent_tree;
47615dc562c5SJosef Bacik 	int ret = 0;
47622ab28f32SJosef Bacik 	int num = 0;
47635dc562c5SJosef Bacik 
47645dc562c5SJosef Bacik 	INIT_LIST_HEAD(&extents);
47655dc562c5SJosef Bacik 
47665dc562c5SJosef Bacik 	write_lock(&tree->lock);
47675dc562c5SJosef Bacik 
47685dc562c5SJosef Bacik 	list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
47695dc562c5SJosef Bacik 		list_del_init(&em->list);
47702ab28f32SJosef Bacik 		/*
47712ab28f32SJosef Bacik 		 * Just an arbitrary number, this can be really CPU intensive
47722ab28f32SJosef Bacik 		 * once we start getting a lot of extents, and really once we
47732ab28f32SJosef Bacik 		 * have a bunch of extents we just want to commit since it will
47742ab28f32SJosef Bacik 		 * be faster.
47752ab28f32SJosef Bacik 		 */
47762ab28f32SJosef Bacik 		if (++num > 32768) {
47772ab28f32SJosef Bacik 			list_del_init(&tree->modified_extents);
47782ab28f32SJosef Bacik 			ret = -EFBIG;
47792ab28f32SJosef Bacik 			goto process;
47802ab28f32SJosef Bacik 		}
47812ab28f32SJosef Bacik 
47825f96bfb7SFilipe Manana 		if (em->generation < trans->transid)
47835dc562c5SJosef Bacik 			continue;
47848c6c5928SJosef Bacik 
478531d11b83SFilipe Manana 		/* We log prealloc extents beyond eof later. */
478631d11b83SFilipe Manana 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
478731d11b83SFilipe Manana 		    em->start >= i_size_read(&inode->vfs_inode))
478831d11b83SFilipe Manana 			continue;
478931d11b83SFilipe Manana 
4790ff44c6e3SJosef Bacik 		/* Need a ref to keep it from getting evicted from cache */
4791490b54d6SElena Reshetova 		refcount_inc(&em->refs);
4792ff44c6e3SJosef Bacik 		set_bit(EXTENT_FLAG_LOGGING, &em->flags);
47935dc562c5SJosef Bacik 		list_add_tail(&em->list, &extents);
47942ab28f32SJosef Bacik 		num++;
47955dc562c5SJosef Bacik 	}
47965dc562c5SJosef Bacik 
47975dc562c5SJosef Bacik 	list_sort(NULL, &extents, extent_cmp);
47982ab28f32SJosef Bacik process:
47995dc562c5SJosef Bacik 	while (!list_empty(&extents)) {
48005dc562c5SJosef Bacik 		em = list_entry(extents.next, struct extent_map, list);
48015dc562c5SJosef Bacik 
48025dc562c5SJosef Bacik 		list_del_init(&em->list);
48035dc562c5SJosef Bacik 
48045dc562c5SJosef Bacik 		/*
48055dc562c5SJosef Bacik 		 * If we had an error we just need to delete everybody from our
48065dc562c5SJosef Bacik 		 * private list.
48075dc562c5SJosef Bacik 		 */
4808ff44c6e3SJosef Bacik 		if (ret) {
4809201a9038SJosef Bacik 			clear_em_logging(tree, em);
4810ff44c6e3SJosef Bacik 			free_extent_map(em);
48115dc562c5SJosef Bacik 			continue;
4812ff44c6e3SJosef Bacik 		}
4813ff44c6e3SJosef Bacik 
4814ff44c6e3SJosef Bacik 		write_unlock(&tree->lock);
48155dc562c5SJosef Bacik 
481690d04510SFilipe Manana 		ret = log_one_extent(trans, inode, em, path, ctx);
4817ff44c6e3SJosef Bacik 		write_lock(&tree->lock);
4818201a9038SJosef Bacik 		clear_em_logging(tree, em);
4819201a9038SJosef Bacik 		free_extent_map(em);
48205dc562c5SJosef Bacik 	}
4821ff44c6e3SJosef Bacik 	WARN_ON(!list_empty(&extents));
4822ff44c6e3SJosef Bacik 	write_unlock(&tree->lock);
48235dc562c5SJosef Bacik 
48245dc562c5SJosef Bacik 	btrfs_release_path(path);
482531d11b83SFilipe Manana 	if (!ret)
482631d11b83SFilipe Manana 		ret = btrfs_log_prealloc_extents(trans, inode, path);
482748778179SFilipe Manana 	if (ret)
48285dc562c5SJosef Bacik 		return ret;
482948778179SFilipe Manana 
483048778179SFilipe Manana 	/*
483148778179SFilipe Manana 	 * We have logged all extents successfully, now make sure the commit of
483248778179SFilipe Manana 	 * the current transaction waits for the ordered extents to complete
483348778179SFilipe Manana 	 * before it commits and wipes out the log trees, otherwise we would
483448778179SFilipe Manana 	 * lose data if an ordered extents completes after the transaction
483548778179SFilipe Manana 	 * commits and a power failure happens after the transaction commit.
483648778179SFilipe Manana 	 */
483748778179SFilipe Manana 	list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
483848778179SFilipe Manana 		list_del_init(&ordered->log_list);
483948778179SFilipe Manana 		set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
484048778179SFilipe Manana 
484148778179SFilipe Manana 		if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
484248778179SFilipe Manana 			spin_lock_irq(&inode->ordered_tree.lock);
484348778179SFilipe Manana 			if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
484448778179SFilipe Manana 				set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
484548778179SFilipe Manana 				atomic_inc(&trans->transaction->pending_ordered);
484648778179SFilipe Manana 			}
484748778179SFilipe Manana 			spin_unlock_irq(&inode->ordered_tree.lock);
484848778179SFilipe Manana 		}
484948778179SFilipe Manana 		btrfs_put_ordered_extent(ordered);
485048778179SFilipe Manana 	}
485148778179SFilipe Manana 
485248778179SFilipe Manana 	return 0;
48535dc562c5SJosef Bacik }
48545dc562c5SJosef Bacik 
4855481b01c0SNikolay Borisov static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
48561a4bcf47SFilipe Manana 			     struct btrfs_path *path, u64 *size_ret)
48571a4bcf47SFilipe Manana {
48581a4bcf47SFilipe Manana 	struct btrfs_key key;
48591a4bcf47SFilipe Manana 	int ret;
48601a4bcf47SFilipe Manana 
4861481b01c0SNikolay Borisov 	key.objectid = btrfs_ino(inode);
48621a4bcf47SFilipe Manana 	key.type = BTRFS_INODE_ITEM_KEY;
48631a4bcf47SFilipe Manana 	key.offset = 0;
48641a4bcf47SFilipe Manana 
48651a4bcf47SFilipe Manana 	ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
48661a4bcf47SFilipe Manana 	if (ret < 0) {
48671a4bcf47SFilipe Manana 		return ret;
48681a4bcf47SFilipe Manana 	} else if (ret > 0) {
48692f2ff0eeSFilipe Manana 		*size_ret = 0;
48701a4bcf47SFilipe Manana 	} else {
48711a4bcf47SFilipe Manana 		struct btrfs_inode_item *item;
48721a4bcf47SFilipe Manana 
48731a4bcf47SFilipe Manana 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
48741a4bcf47SFilipe Manana 				      struct btrfs_inode_item);
48751a4bcf47SFilipe Manana 		*size_ret = btrfs_inode_size(path->nodes[0], item);
4876bf504110SFilipe Manana 		/*
4877bf504110SFilipe Manana 		 * If the in-memory inode's i_size is smaller then the inode
4878bf504110SFilipe Manana 		 * size stored in the btree, return the inode's i_size, so
4879bf504110SFilipe Manana 		 * that we get a correct inode size after replaying the log
4880bf504110SFilipe Manana 		 * when before a power failure we had a shrinking truncate
4881bf504110SFilipe Manana 		 * followed by addition of a new name (rename / new hard link).
4882bf504110SFilipe Manana 		 * Otherwise return the inode size from the btree, to avoid
4883bf504110SFilipe Manana 		 * data loss when replaying a log due to previously doing a
4884bf504110SFilipe Manana 		 * write that expands the inode's size and logging a new name
4885bf504110SFilipe Manana 		 * immediately after.
4886bf504110SFilipe Manana 		 */
4887bf504110SFilipe Manana 		if (*size_ret > inode->vfs_inode.i_size)
4888bf504110SFilipe Manana 			*size_ret = inode->vfs_inode.i_size;
48891a4bcf47SFilipe Manana 	}
48901a4bcf47SFilipe Manana 
48911a4bcf47SFilipe Manana 	btrfs_release_path(path);
48921a4bcf47SFilipe Manana 	return 0;
48931a4bcf47SFilipe Manana }
48941a4bcf47SFilipe Manana 
489536283bf7SFilipe Manana /*
489636283bf7SFilipe Manana  * At the moment we always log all xattrs. This is to figure out at log replay
489736283bf7SFilipe Manana  * time which xattrs must have their deletion replayed. If a xattr is missing
489836283bf7SFilipe Manana  * in the log tree and exists in the fs/subvol tree, we delete it. This is
489936283bf7SFilipe Manana  * because if a xattr is deleted, the inode is fsynced and a power failure
490036283bf7SFilipe Manana  * happens, causing the log to be replayed the next time the fs is mounted,
490136283bf7SFilipe Manana  * we want the xattr to not exist anymore (same behaviour as other filesystems
490236283bf7SFilipe Manana  * with a journal, ext3/4, xfs, f2fs, etc).
490336283bf7SFilipe Manana  */
490436283bf7SFilipe Manana static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
49051a93c36aSNikolay Borisov 				struct btrfs_inode *inode,
490636283bf7SFilipe Manana 				struct btrfs_path *path,
490736283bf7SFilipe Manana 				struct btrfs_path *dst_path)
490836283bf7SFilipe Manana {
490990d04510SFilipe Manana 	struct btrfs_root *root = inode->root;
491036283bf7SFilipe Manana 	int ret;
491136283bf7SFilipe Manana 	struct btrfs_key key;
49121a93c36aSNikolay Borisov 	const u64 ino = btrfs_ino(inode);
491336283bf7SFilipe Manana 	int ins_nr = 0;
491436283bf7SFilipe Manana 	int start_slot = 0;
4915f2f121abSFilipe Manana 	bool found_xattrs = false;
4916f2f121abSFilipe Manana 
4917f2f121abSFilipe Manana 	if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
4918f2f121abSFilipe Manana 		return 0;
491936283bf7SFilipe Manana 
492036283bf7SFilipe Manana 	key.objectid = ino;
492136283bf7SFilipe Manana 	key.type = BTRFS_XATTR_ITEM_KEY;
492236283bf7SFilipe Manana 	key.offset = 0;
492336283bf7SFilipe Manana 
492436283bf7SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
492536283bf7SFilipe Manana 	if (ret < 0)
492636283bf7SFilipe Manana 		return ret;
492736283bf7SFilipe Manana 
492836283bf7SFilipe Manana 	while (true) {
492936283bf7SFilipe Manana 		int slot = path->slots[0];
493036283bf7SFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
493136283bf7SFilipe Manana 		int nritems = btrfs_header_nritems(leaf);
493236283bf7SFilipe Manana 
493336283bf7SFilipe Manana 		if (slot >= nritems) {
493436283bf7SFilipe Manana 			if (ins_nr > 0) {
49351a93c36aSNikolay Borisov 				ret = copy_items(trans, inode, dst_path, path,
49360e56315cSFilipe Manana 						 start_slot, ins_nr, 1, 0);
493736283bf7SFilipe Manana 				if (ret < 0)
493836283bf7SFilipe Manana 					return ret;
493936283bf7SFilipe Manana 				ins_nr = 0;
494036283bf7SFilipe Manana 			}
494136283bf7SFilipe Manana 			ret = btrfs_next_leaf(root, path);
494236283bf7SFilipe Manana 			if (ret < 0)
494336283bf7SFilipe Manana 				return ret;
494436283bf7SFilipe Manana 			else if (ret > 0)
494536283bf7SFilipe Manana 				break;
494636283bf7SFilipe Manana 			continue;
494736283bf7SFilipe Manana 		}
494836283bf7SFilipe Manana 
494936283bf7SFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
495036283bf7SFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
495136283bf7SFilipe Manana 			break;
495236283bf7SFilipe Manana 
495336283bf7SFilipe Manana 		if (ins_nr == 0)
495436283bf7SFilipe Manana 			start_slot = slot;
495536283bf7SFilipe Manana 		ins_nr++;
495636283bf7SFilipe Manana 		path->slots[0]++;
4957f2f121abSFilipe Manana 		found_xattrs = true;
495836283bf7SFilipe Manana 		cond_resched();
495936283bf7SFilipe Manana 	}
496036283bf7SFilipe Manana 	if (ins_nr > 0) {
49611a93c36aSNikolay Borisov 		ret = copy_items(trans, inode, dst_path, path,
49620e56315cSFilipe Manana 				 start_slot, ins_nr, 1, 0);
496336283bf7SFilipe Manana 		if (ret < 0)
496436283bf7SFilipe Manana 			return ret;
496536283bf7SFilipe Manana 	}
496636283bf7SFilipe Manana 
4967f2f121abSFilipe Manana 	if (!found_xattrs)
4968f2f121abSFilipe Manana 		set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
4969f2f121abSFilipe Manana 
497036283bf7SFilipe Manana 	return 0;
497136283bf7SFilipe Manana }
497236283bf7SFilipe Manana 
4973a89ca6f2SFilipe Manana /*
49740e56315cSFilipe Manana  * When using the NO_HOLES feature if we punched a hole that causes the
49750e56315cSFilipe Manana  * deletion of entire leafs or all the extent items of the first leaf (the one
49760e56315cSFilipe Manana  * that contains the inode item and references) we may end up not processing
49770e56315cSFilipe Manana  * any extents, because there are no leafs with a generation matching the
49780e56315cSFilipe Manana  * current transaction that have extent items for our inode. So we need to find
49790e56315cSFilipe Manana  * if any holes exist and then log them. We also need to log holes after any
49800e56315cSFilipe Manana  * truncate operation that changes the inode's size.
4981a89ca6f2SFilipe Manana  */
49820e56315cSFilipe Manana static int btrfs_log_holes(struct btrfs_trans_handle *trans,
4983a0308dd7SNikolay Borisov 			   struct btrfs_inode *inode,
49847af59743SFilipe Manana 			   struct btrfs_path *path)
4985a89ca6f2SFilipe Manana {
498690d04510SFilipe Manana 	struct btrfs_root *root = inode->root;
49870b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
4988a89ca6f2SFilipe Manana 	struct btrfs_key key;
4989a0308dd7SNikolay Borisov 	const u64 ino = btrfs_ino(inode);
4990a0308dd7SNikolay Borisov 	const u64 i_size = i_size_read(&inode->vfs_inode);
49917af59743SFilipe Manana 	u64 prev_extent_end = 0;
49920e56315cSFilipe Manana 	int ret;
4993a89ca6f2SFilipe Manana 
49940e56315cSFilipe Manana 	if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
4995a89ca6f2SFilipe Manana 		return 0;
4996a89ca6f2SFilipe Manana 
4997a89ca6f2SFilipe Manana 	key.objectid = ino;
4998a89ca6f2SFilipe Manana 	key.type = BTRFS_EXTENT_DATA_KEY;
49997af59743SFilipe Manana 	key.offset = 0;
5000a89ca6f2SFilipe Manana 
5001a89ca6f2SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5002a89ca6f2SFilipe Manana 	if (ret < 0)
5003a89ca6f2SFilipe Manana 		return ret;
5004a89ca6f2SFilipe Manana 
50050e56315cSFilipe Manana 	while (true) {
50060e56315cSFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
5007a89ca6f2SFilipe Manana 
50080e56315cSFilipe Manana 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
50090e56315cSFilipe Manana 			ret = btrfs_next_leaf(root, path);
50100e56315cSFilipe Manana 			if (ret < 0)
50110e56315cSFilipe Manana 				return ret;
50120e56315cSFilipe Manana 			if (ret > 0) {
50130e56315cSFilipe Manana 				ret = 0;
50140e56315cSFilipe Manana 				break;
50150e56315cSFilipe Manana 			}
50160e56315cSFilipe Manana 			leaf = path->nodes[0];
50170e56315cSFilipe Manana 		}
50180e56315cSFilipe Manana 
50190e56315cSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
50200e56315cSFilipe Manana 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
50210e56315cSFilipe Manana 			break;
50220e56315cSFilipe Manana 
50230e56315cSFilipe Manana 		/* We have a hole, log it. */
50240e56315cSFilipe Manana 		if (prev_extent_end < key.offset) {
50257af59743SFilipe Manana 			const u64 hole_len = key.offset - prev_extent_end;
50260e56315cSFilipe Manana 
5027a89ca6f2SFilipe Manana 			/*
50280e56315cSFilipe Manana 			 * Release the path to avoid deadlocks with other code
50290e56315cSFilipe Manana 			 * paths that search the root while holding locks on
50300e56315cSFilipe Manana 			 * leafs from the log root.
5031a89ca6f2SFilipe Manana 			 */
50320e56315cSFilipe Manana 			btrfs_release_path(path);
50330e56315cSFilipe Manana 			ret = btrfs_insert_file_extent(trans, root->log_root,
50340e56315cSFilipe Manana 						       ino, prev_extent_end, 0,
50350e56315cSFilipe Manana 						       0, hole_len, 0, hole_len,
50360e56315cSFilipe Manana 						       0, 0, 0);
50370e56315cSFilipe Manana 			if (ret < 0)
50380e56315cSFilipe Manana 				return ret;
50390e56315cSFilipe Manana 
50400e56315cSFilipe Manana 			/*
50410e56315cSFilipe Manana 			 * Search for the same key again in the root. Since it's
50420e56315cSFilipe Manana 			 * an extent item and we are holding the inode lock, the
50430e56315cSFilipe Manana 			 * key must still exist. If it doesn't just emit warning
50440e56315cSFilipe Manana 			 * and return an error to fall back to a transaction
50450e56315cSFilipe Manana 			 * commit.
50460e56315cSFilipe Manana 			 */
50470e56315cSFilipe Manana 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
50480e56315cSFilipe Manana 			if (ret < 0)
50490e56315cSFilipe Manana 				return ret;
50500e56315cSFilipe Manana 			if (WARN_ON(ret > 0))
50510e56315cSFilipe Manana 				return -ENOENT;
50520e56315cSFilipe Manana 			leaf = path->nodes[0];
50530e56315cSFilipe Manana 		}
5054a89ca6f2SFilipe Manana 
50557af59743SFilipe Manana 		prev_extent_end = btrfs_file_extent_end(path);
50560e56315cSFilipe Manana 		path->slots[0]++;
50570e56315cSFilipe Manana 		cond_resched();
50580e56315cSFilipe Manana 	}
50590e56315cSFilipe Manana 
50607af59743SFilipe Manana 	if (prev_extent_end < i_size) {
50610e56315cSFilipe Manana 		u64 hole_len;
50620e56315cSFilipe Manana 
5063a89ca6f2SFilipe Manana 		btrfs_release_path(path);
50647af59743SFilipe Manana 		hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
50650e56315cSFilipe Manana 		ret = btrfs_insert_file_extent(trans, root->log_root,
50660e56315cSFilipe Manana 					       ino, prev_extent_end, 0, 0,
50670e56315cSFilipe Manana 					       hole_len, 0, hole_len,
50680e56315cSFilipe Manana 					       0, 0, 0);
50690e56315cSFilipe Manana 		if (ret < 0)
5070a89ca6f2SFilipe Manana 			return ret;
5071a89ca6f2SFilipe Manana 	}
5072a89ca6f2SFilipe Manana 
50730e56315cSFilipe Manana 	return 0;
50740e56315cSFilipe Manana }
50750e56315cSFilipe Manana 
507656f23fdbSFilipe Manana /*
507756f23fdbSFilipe Manana  * When we are logging a new inode X, check if it doesn't have a reference that
507856f23fdbSFilipe Manana  * matches the reference from some other inode Y created in a past transaction
507956f23fdbSFilipe Manana  * and that was renamed in the current transaction. If we don't do this, then at
508056f23fdbSFilipe Manana  * log replay time we can lose inode Y (and all its files if it's a directory):
508156f23fdbSFilipe Manana  *
508256f23fdbSFilipe Manana  * mkdir /mnt/x
508356f23fdbSFilipe Manana  * echo "hello world" > /mnt/x/foobar
508456f23fdbSFilipe Manana  * sync
508556f23fdbSFilipe Manana  * mv /mnt/x /mnt/y
508656f23fdbSFilipe Manana  * mkdir /mnt/x                 # or touch /mnt/x
508756f23fdbSFilipe Manana  * xfs_io -c fsync /mnt/x
508856f23fdbSFilipe Manana  * <power fail>
508956f23fdbSFilipe Manana  * mount fs, trigger log replay
509056f23fdbSFilipe Manana  *
509156f23fdbSFilipe Manana  * After the log replay procedure, we would lose the first directory and all its
509256f23fdbSFilipe Manana  * files (file foobar).
509356f23fdbSFilipe Manana  * For the case where inode Y is not a directory we simply end up losing it:
509456f23fdbSFilipe Manana  *
509556f23fdbSFilipe Manana  * echo "123" > /mnt/foo
509656f23fdbSFilipe Manana  * sync
509756f23fdbSFilipe Manana  * mv /mnt/foo /mnt/bar
509856f23fdbSFilipe Manana  * echo "abc" > /mnt/foo
509956f23fdbSFilipe Manana  * xfs_io -c fsync /mnt/foo
510056f23fdbSFilipe Manana  * <power fail>
510156f23fdbSFilipe Manana  *
510256f23fdbSFilipe Manana  * We also need this for cases where a snapshot entry is replaced by some other
510356f23fdbSFilipe Manana  * entry (file or directory) otherwise we end up with an unreplayable log due to
510456f23fdbSFilipe Manana  * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
510556f23fdbSFilipe Manana  * if it were a regular entry:
510656f23fdbSFilipe Manana  *
510756f23fdbSFilipe Manana  * mkdir /mnt/x
510856f23fdbSFilipe Manana  * btrfs subvolume snapshot /mnt /mnt/x/snap
510956f23fdbSFilipe Manana  * btrfs subvolume delete /mnt/x/snap
511056f23fdbSFilipe Manana  * rmdir /mnt/x
511156f23fdbSFilipe Manana  * mkdir /mnt/x
511256f23fdbSFilipe Manana  * fsync /mnt/x or fsync some new file inside it
511356f23fdbSFilipe Manana  * <power fail>
511456f23fdbSFilipe Manana  *
511556f23fdbSFilipe Manana  * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
511656f23fdbSFilipe Manana  * the same transaction.
511756f23fdbSFilipe Manana  */
511856f23fdbSFilipe Manana static int btrfs_check_ref_name_override(struct extent_buffer *eb,
511956f23fdbSFilipe Manana 					 const int slot,
512056f23fdbSFilipe Manana 					 const struct btrfs_key *key,
51214791c8f1SNikolay Borisov 					 struct btrfs_inode *inode,
5122a3baaf0dSFilipe Manana 					 u64 *other_ino, u64 *other_parent)
512356f23fdbSFilipe Manana {
512456f23fdbSFilipe Manana 	int ret;
512556f23fdbSFilipe Manana 	struct btrfs_path *search_path;
512656f23fdbSFilipe Manana 	char *name = NULL;
512756f23fdbSFilipe Manana 	u32 name_len = 0;
51283212fa14SJosef Bacik 	u32 item_size = btrfs_item_size(eb, slot);
512956f23fdbSFilipe Manana 	u32 cur_offset = 0;
513056f23fdbSFilipe Manana 	unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
513156f23fdbSFilipe Manana 
513256f23fdbSFilipe Manana 	search_path = btrfs_alloc_path();
513356f23fdbSFilipe Manana 	if (!search_path)
513456f23fdbSFilipe Manana 		return -ENOMEM;
513556f23fdbSFilipe Manana 	search_path->search_commit_root = 1;
513656f23fdbSFilipe Manana 	search_path->skip_locking = 1;
513756f23fdbSFilipe Manana 
513856f23fdbSFilipe Manana 	while (cur_offset < item_size) {
513956f23fdbSFilipe Manana 		u64 parent;
514056f23fdbSFilipe Manana 		u32 this_name_len;
514156f23fdbSFilipe Manana 		u32 this_len;
514256f23fdbSFilipe Manana 		unsigned long name_ptr;
514356f23fdbSFilipe Manana 		struct btrfs_dir_item *di;
514456f23fdbSFilipe Manana 
514556f23fdbSFilipe Manana 		if (key->type == BTRFS_INODE_REF_KEY) {
514656f23fdbSFilipe Manana 			struct btrfs_inode_ref *iref;
514756f23fdbSFilipe Manana 
514856f23fdbSFilipe Manana 			iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
514956f23fdbSFilipe Manana 			parent = key->offset;
515056f23fdbSFilipe Manana 			this_name_len = btrfs_inode_ref_name_len(eb, iref);
515156f23fdbSFilipe Manana 			name_ptr = (unsigned long)(iref + 1);
515256f23fdbSFilipe Manana 			this_len = sizeof(*iref) + this_name_len;
515356f23fdbSFilipe Manana 		} else {
515456f23fdbSFilipe Manana 			struct btrfs_inode_extref *extref;
515556f23fdbSFilipe Manana 
515656f23fdbSFilipe Manana 			extref = (struct btrfs_inode_extref *)(ptr +
515756f23fdbSFilipe Manana 							       cur_offset);
515856f23fdbSFilipe Manana 			parent = btrfs_inode_extref_parent(eb, extref);
515956f23fdbSFilipe Manana 			this_name_len = btrfs_inode_extref_name_len(eb, extref);
516056f23fdbSFilipe Manana 			name_ptr = (unsigned long)&extref->name;
516156f23fdbSFilipe Manana 			this_len = sizeof(*extref) + this_name_len;
516256f23fdbSFilipe Manana 		}
516356f23fdbSFilipe Manana 
516456f23fdbSFilipe Manana 		if (this_name_len > name_len) {
516556f23fdbSFilipe Manana 			char *new_name;
516656f23fdbSFilipe Manana 
516756f23fdbSFilipe Manana 			new_name = krealloc(name, this_name_len, GFP_NOFS);
516856f23fdbSFilipe Manana 			if (!new_name) {
516956f23fdbSFilipe Manana 				ret = -ENOMEM;
517056f23fdbSFilipe Manana 				goto out;
517156f23fdbSFilipe Manana 			}
517256f23fdbSFilipe Manana 			name_len = this_name_len;
517356f23fdbSFilipe Manana 			name = new_name;
517456f23fdbSFilipe Manana 		}
517556f23fdbSFilipe Manana 
517656f23fdbSFilipe Manana 		read_extent_buffer(eb, name, name_ptr, this_name_len);
51774791c8f1SNikolay Borisov 		di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
51784791c8f1SNikolay Borisov 				parent, name, this_name_len, 0);
517956f23fdbSFilipe Manana 		if (di && !IS_ERR(di)) {
518044f714daSFilipe Manana 			struct btrfs_key di_key;
518144f714daSFilipe Manana 
518244f714daSFilipe Manana 			btrfs_dir_item_key_to_cpu(search_path->nodes[0],
518344f714daSFilipe Manana 						  di, &di_key);
518444f714daSFilipe Manana 			if (di_key.type == BTRFS_INODE_ITEM_KEY) {
51856b5fc433SFilipe Manana 				if (di_key.objectid != key->objectid) {
518656f23fdbSFilipe Manana 					ret = 1;
518744f714daSFilipe Manana 					*other_ino = di_key.objectid;
5188a3baaf0dSFilipe Manana 					*other_parent = parent;
518944f714daSFilipe Manana 				} else {
51906b5fc433SFilipe Manana 					ret = 0;
51916b5fc433SFilipe Manana 				}
51926b5fc433SFilipe Manana 			} else {
519344f714daSFilipe Manana 				ret = -EAGAIN;
519444f714daSFilipe Manana 			}
519556f23fdbSFilipe Manana 			goto out;
519656f23fdbSFilipe Manana 		} else if (IS_ERR(di)) {
519756f23fdbSFilipe Manana 			ret = PTR_ERR(di);
519856f23fdbSFilipe Manana 			goto out;
519956f23fdbSFilipe Manana 		}
520056f23fdbSFilipe Manana 		btrfs_release_path(search_path);
520156f23fdbSFilipe Manana 
520256f23fdbSFilipe Manana 		cur_offset += this_len;
520356f23fdbSFilipe Manana 	}
520456f23fdbSFilipe Manana 	ret = 0;
520556f23fdbSFilipe Manana out:
520656f23fdbSFilipe Manana 	btrfs_free_path(search_path);
520756f23fdbSFilipe Manana 	kfree(name);
520856f23fdbSFilipe Manana 	return ret;
520956f23fdbSFilipe Manana }
521056f23fdbSFilipe Manana 
52116b5fc433SFilipe Manana struct btrfs_ino_list {
52126b5fc433SFilipe Manana 	u64 ino;
5213a3baaf0dSFilipe Manana 	u64 parent;
52146b5fc433SFilipe Manana 	struct list_head list;
52156b5fc433SFilipe Manana };
52166b5fc433SFilipe Manana 
52176b5fc433SFilipe Manana static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
52186b5fc433SFilipe Manana 				  struct btrfs_root *root,
52196b5fc433SFilipe Manana 				  struct btrfs_path *path,
52206b5fc433SFilipe Manana 				  struct btrfs_log_ctx *ctx,
5221a3baaf0dSFilipe Manana 				  u64 ino, u64 parent)
52226b5fc433SFilipe Manana {
52236b5fc433SFilipe Manana 	struct btrfs_ino_list *ino_elem;
52246b5fc433SFilipe Manana 	LIST_HEAD(inode_list);
52256b5fc433SFilipe Manana 	int ret = 0;
52266b5fc433SFilipe Manana 
52276b5fc433SFilipe Manana 	ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
52286b5fc433SFilipe Manana 	if (!ino_elem)
52296b5fc433SFilipe Manana 		return -ENOMEM;
52306b5fc433SFilipe Manana 	ino_elem->ino = ino;
5231a3baaf0dSFilipe Manana 	ino_elem->parent = parent;
52326b5fc433SFilipe Manana 	list_add_tail(&ino_elem->list, &inode_list);
52336b5fc433SFilipe Manana 
52346b5fc433SFilipe Manana 	while (!list_empty(&inode_list)) {
52356b5fc433SFilipe Manana 		struct btrfs_fs_info *fs_info = root->fs_info;
52366b5fc433SFilipe Manana 		struct btrfs_key key;
52376b5fc433SFilipe Manana 		struct inode *inode;
52386b5fc433SFilipe Manana 
52396b5fc433SFilipe Manana 		ino_elem = list_first_entry(&inode_list, struct btrfs_ino_list,
52406b5fc433SFilipe Manana 					    list);
52416b5fc433SFilipe Manana 		ino = ino_elem->ino;
5242a3baaf0dSFilipe Manana 		parent = ino_elem->parent;
52436b5fc433SFilipe Manana 		list_del(&ino_elem->list);
52446b5fc433SFilipe Manana 		kfree(ino_elem);
52456b5fc433SFilipe Manana 		if (ret)
52466b5fc433SFilipe Manana 			continue;
52476b5fc433SFilipe Manana 
52486b5fc433SFilipe Manana 		btrfs_release_path(path);
52496b5fc433SFilipe Manana 
52500202e83fSDavid Sterba 		inode = btrfs_iget(fs_info->sb, ino, root);
52516b5fc433SFilipe Manana 		/*
52526b5fc433SFilipe Manana 		 * If the other inode that had a conflicting dir entry was
5253a3baaf0dSFilipe Manana 		 * deleted in the current transaction, we need to log its parent
5254a3baaf0dSFilipe Manana 		 * directory.
52556b5fc433SFilipe Manana 		 */
52566b5fc433SFilipe Manana 		if (IS_ERR(inode)) {
52576b5fc433SFilipe Manana 			ret = PTR_ERR(inode);
5258a3baaf0dSFilipe Manana 			if (ret == -ENOENT) {
52590202e83fSDavid Sterba 				inode = btrfs_iget(fs_info->sb, parent, root);
5260a3baaf0dSFilipe Manana 				if (IS_ERR(inode)) {
5261a3baaf0dSFilipe Manana 					ret = PTR_ERR(inode);
5262a3baaf0dSFilipe Manana 				} else {
526390d04510SFilipe Manana 					ret = btrfs_log_inode(trans,
5264a3baaf0dSFilipe Manana 						      BTRFS_I(inode),
5265a3baaf0dSFilipe Manana 						      LOG_OTHER_INODE_ALL,
526648778179SFilipe Manana 						      ctx);
5267410f954cSFilipe Manana 					btrfs_add_delayed_iput(inode);
5268a3baaf0dSFilipe Manana 				}
5269a3baaf0dSFilipe Manana 			}
52706b5fc433SFilipe Manana 			continue;
52716b5fc433SFilipe Manana 		}
52726b5fc433SFilipe Manana 		/*
5273b5e4ff9dSFilipe Manana 		 * If the inode was already logged skip it - otherwise we can
5274b5e4ff9dSFilipe Manana 		 * hit an infinite loop. Example:
5275b5e4ff9dSFilipe Manana 		 *
5276b5e4ff9dSFilipe Manana 		 * From the commit root (previous transaction) we have the
5277b5e4ff9dSFilipe Manana 		 * following inodes:
5278b5e4ff9dSFilipe Manana 		 *
5279b5e4ff9dSFilipe Manana 		 * inode 257 a directory
5280b5e4ff9dSFilipe Manana 		 * inode 258 with references "zz" and "zz_link" on inode 257
5281b5e4ff9dSFilipe Manana 		 * inode 259 with reference "a" on inode 257
5282b5e4ff9dSFilipe Manana 		 *
5283b5e4ff9dSFilipe Manana 		 * And in the current (uncommitted) transaction we have:
5284b5e4ff9dSFilipe Manana 		 *
5285b5e4ff9dSFilipe Manana 		 * inode 257 a directory, unchanged
5286b5e4ff9dSFilipe Manana 		 * inode 258 with references "a" and "a2" on inode 257
5287b5e4ff9dSFilipe Manana 		 * inode 259 with reference "zz_link" on inode 257
5288b5e4ff9dSFilipe Manana 		 * inode 261 with reference "zz" on inode 257
5289b5e4ff9dSFilipe Manana 		 *
5290b5e4ff9dSFilipe Manana 		 * When logging inode 261 the following infinite loop could
5291b5e4ff9dSFilipe Manana 		 * happen if we don't skip already logged inodes:
5292b5e4ff9dSFilipe Manana 		 *
5293b5e4ff9dSFilipe Manana 		 * - we detect inode 258 as a conflicting inode, with inode 261
5294b5e4ff9dSFilipe Manana 		 *   on reference "zz", and log it;
5295b5e4ff9dSFilipe Manana 		 *
5296b5e4ff9dSFilipe Manana 		 * - we detect inode 259 as a conflicting inode, with inode 258
5297b5e4ff9dSFilipe Manana 		 *   on reference "a", and log it;
5298b5e4ff9dSFilipe Manana 		 *
5299b5e4ff9dSFilipe Manana 		 * - we detect inode 258 as a conflicting inode, with inode 259
5300b5e4ff9dSFilipe Manana 		 *   on reference "zz_link", and log it - again! After this we
5301b5e4ff9dSFilipe Manana 		 *   repeat the above steps forever.
5302b5e4ff9dSFilipe Manana 		 */
5303b5e4ff9dSFilipe Manana 		spin_lock(&BTRFS_I(inode)->lock);
5304b5e4ff9dSFilipe Manana 		/*
5305b5e4ff9dSFilipe Manana 		 * Check the inode's logged_trans only instead of
5306b5e4ff9dSFilipe Manana 		 * btrfs_inode_in_log(). This is because the last_log_commit of
53071f295373SFilipe Manana 		 * the inode is not updated when we only log that it exists (see
53081f295373SFilipe Manana 		 * btrfs_log_inode()).
5309b5e4ff9dSFilipe Manana 		 */
5310b5e4ff9dSFilipe Manana 		if (BTRFS_I(inode)->logged_trans == trans->transid) {
5311b5e4ff9dSFilipe Manana 			spin_unlock(&BTRFS_I(inode)->lock);
5312b5e4ff9dSFilipe Manana 			btrfs_add_delayed_iput(inode);
5313b5e4ff9dSFilipe Manana 			continue;
5314b5e4ff9dSFilipe Manana 		}
5315b5e4ff9dSFilipe Manana 		spin_unlock(&BTRFS_I(inode)->lock);
5316b5e4ff9dSFilipe Manana 		/*
53176b5fc433SFilipe Manana 		 * We are safe logging the other inode without acquiring its
53186b5fc433SFilipe Manana 		 * lock as long as we log with the LOG_INODE_EXISTS mode. We
53196b5fc433SFilipe Manana 		 * are safe against concurrent renames of the other inode as
53206b5fc433SFilipe Manana 		 * well because during a rename we pin the log and update the
53216b5fc433SFilipe Manana 		 * log with the new name before we unpin it.
53226b5fc433SFilipe Manana 		 */
532390d04510SFilipe Manana 		ret = btrfs_log_inode(trans, BTRFS_I(inode), LOG_OTHER_INODE, ctx);
53246b5fc433SFilipe Manana 		if (ret) {
5325410f954cSFilipe Manana 			btrfs_add_delayed_iput(inode);
53266b5fc433SFilipe Manana 			continue;
53276b5fc433SFilipe Manana 		}
53286b5fc433SFilipe Manana 
53296b5fc433SFilipe Manana 		key.objectid = ino;
53306b5fc433SFilipe Manana 		key.type = BTRFS_INODE_REF_KEY;
53316b5fc433SFilipe Manana 		key.offset = 0;
53326b5fc433SFilipe Manana 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
53336b5fc433SFilipe Manana 		if (ret < 0) {
5334410f954cSFilipe Manana 			btrfs_add_delayed_iput(inode);
53356b5fc433SFilipe Manana 			continue;
53366b5fc433SFilipe Manana 		}
53376b5fc433SFilipe Manana 
53386b5fc433SFilipe Manana 		while (true) {
53396b5fc433SFilipe Manana 			struct extent_buffer *leaf = path->nodes[0];
53406b5fc433SFilipe Manana 			int slot = path->slots[0];
53416b5fc433SFilipe Manana 			u64 other_ino = 0;
5342a3baaf0dSFilipe Manana 			u64 other_parent = 0;
53436b5fc433SFilipe Manana 
53446b5fc433SFilipe Manana 			if (slot >= btrfs_header_nritems(leaf)) {
53456b5fc433SFilipe Manana 				ret = btrfs_next_leaf(root, path);
53466b5fc433SFilipe Manana 				if (ret < 0) {
53476b5fc433SFilipe Manana 					break;
53486b5fc433SFilipe Manana 				} else if (ret > 0) {
53496b5fc433SFilipe Manana 					ret = 0;
53506b5fc433SFilipe Manana 					break;
53516b5fc433SFilipe Manana 				}
53526b5fc433SFilipe Manana 				continue;
53536b5fc433SFilipe Manana 			}
53546b5fc433SFilipe Manana 
53556b5fc433SFilipe Manana 			btrfs_item_key_to_cpu(leaf, &key, slot);
53566b5fc433SFilipe Manana 			if (key.objectid != ino ||
53576b5fc433SFilipe Manana 			    (key.type != BTRFS_INODE_REF_KEY &&
53586b5fc433SFilipe Manana 			     key.type != BTRFS_INODE_EXTREF_KEY)) {
53596b5fc433SFilipe Manana 				ret = 0;
53606b5fc433SFilipe Manana 				break;
53616b5fc433SFilipe Manana 			}
53626b5fc433SFilipe Manana 
53636b5fc433SFilipe Manana 			ret = btrfs_check_ref_name_override(leaf, slot, &key,
5364a3baaf0dSFilipe Manana 					BTRFS_I(inode), &other_ino,
5365a3baaf0dSFilipe Manana 					&other_parent);
53666b5fc433SFilipe Manana 			if (ret < 0)
53676b5fc433SFilipe Manana 				break;
53686b5fc433SFilipe Manana 			if (ret > 0) {
53696b5fc433SFilipe Manana 				ino_elem = kmalloc(sizeof(*ino_elem), GFP_NOFS);
53706b5fc433SFilipe Manana 				if (!ino_elem) {
53716b5fc433SFilipe Manana 					ret = -ENOMEM;
53726b5fc433SFilipe Manana 					break;
53736b5fc433SFilipe Manana 				}
53746b5fc433SFilipe Manana 				ino_elem->ino = other_ino;
5375a3baaf0dSFilipe Manana 				ino_elem->parent = other_parent;
53766b5fc433SFilipe Manana 				list_add_tail(&ino_elem->list, &inode_list);
53776b5fc433SFilipe Manana 				ret = 0;
53786b5fc433SFilipe Manana 			}
53796b5fc433SFilipe Manana 			path->slots[0]++;
53806b5fc433SFilipe Manana 		}
5381410f954cSFilipe Manana 		btrfs_add_delayed_iput(inode);
53826b5fc433SFilipe Manana 	}
53836b5fc433SFilipe Manana 
53846b5fc433SFilipe Manana 	return ret;
53856b5fc433SFilipe Manana }
53866b5fc433SFilipe Manana 
5387da447009SFilipe Manana static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
5388da447009SFilipe Manana 				   struct btrfs_inode *inode,
5389da447009SFilipe Manana 				   struct btrfs_key *min_key,
5390da447009SFilipe Manana 				   const struct btrfs_key *max_key,
5391da447009SFilipe Manana 				   struct btrfs_path *path,
5392da447009SFilipe Manana 				   struct btrfs_path *dst_path,
5393da447009SFilipe Manana 				   const u64 logged_isize,
5394da447009SFilipe Manana 				   const bool recursive_logging,
5395da447009SFilipe Manana 				   const int inode_only,
5396da447009SFilipe Manana 				   struct btrfs_log_ctx *ctx,
5397da447009SFilipe Manana 				   bool *need_log_inode_item)
5398da447009SFilipe Manana {
5399da447009SFilipe Manana 	struct btrfs_root *root = inode->root;
5400da447009SFilipe Manana 	int ins_start_slot = 0;
5401da447009SFilipe Manana 	int ins_nr = 0;
5402da447009SFilipe Manana 	int ret;
5403da447009SFilipe Manana 
5404da447009SFilipe Manana 	while (1) {
5405da447009SFilipe Manana 		ret = btrfs_search_forward(root, min_key, path, trans->transid);
5406da447009SFilipe Manana 		if (ret < 0)
5407da447009SFilipe Manana 			return ret;
5408da447009SFilipe Manana 		if (ret > 0) {
5409da447009SFilipe Manana 			ret = 0;
5410da447009SFilipe Manana 			break;
5411da447009SFilipe Manana 		}
5412da447009SFilipe Manana again:
5413da447009SFilipe Manana 		/* Note, ins_nr might be > 0 here, cleanup outside the loop */
5414da447009SFilipe Manana 		if (min_key->objectid != max_key->objectid)
5415da447009SFilipe Manana 			break;
5416da447009SFilipe Manana 		if (min_key->type > max_key->type)
5417da447009SFilipe Manana 			break;
5418da447009SFilipe Manana 
5419da447009SFilipe Manana 		if (min_key->type == BTRFS_INODE_ITEM_KEY)
5420da447009SFilipe Manana 			*need_log_inode_item = false;
5421da447009SFilipe Manana 
5422da447009SFilipe Manana 		if ((min_key->type == BTRFS_INODE_REF_KEY ||
5423da447009SFilipe Manana 		     min_key->type == BTRFS_INODE_EXTREF_KEY) &&
5424da447009SFilipe Manana 		    inode->generation == trans->transid &&
5425da447009SFilipe Manana 		    !recursive_logging) {
5426da447009SFilipe Manana 			u64 other_ino = 0;
5427da447009SFilipe Manana 			u64 other_parent = 0;
5428da447009SFilipe Manana 
5429da447009SFilipe Manana 			ret = btrfs_check_ref_name_override(path->nodes[0],
5430da447009SFilipe Manana 					path->slots[0], min_key, inode,
5431da447009SFilipe Manana 					&other_ino, &other_parent);
5432da447009SFilipe Manana 			if (ret < 0) {
5433da447009SFilipe Manana 				return ret;
5434289cffcbSFilipe Manana 			} else if (ret > 0 &&
5435da447009SFilipe Manana 				   other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5436da447009SFilipe Manana 				if (ins_nr > 0) {
5437da447009SFilipe Manana 					ins_nr++;
5438da447009SFilipe Manana 				} else {
5439da447009SFilipe Manana 					ins_nr = 1;
5440da447009SFilipe Manana 					ins_start_slot = path->slots[0];
5441da447009SFilipe Manana 				}
5442da447009SFilipe Manana 				ret = copy_items(trans, inode, dst_path, path,
5443da447009SFilipe Manana 						 ins_start_slot, ins_nr,
5444da447009SFilipe Manana 						 inode_only, logged_isize);
5445da447009SFilipe Manana 				if (ret < 0)
5446da447009SFilipe Manana 					return ret;
5447da447009SFilipe Manana 				ins_nr = 0;
5448da447009SFilipe Manana 
5449da447009SFilipe Manana 				ret = log_conflicting_inodes(trans, root, path,
5450da447009SFilipe Manana 						ctx, other_ino, other_parent);
5451da447009SFilipe Manana 				if (ret)
5452da447009SFilipe Manana 					return ret;
5453da447009SFilipe Manana 				btrfs_release_path(path);
5454da447009SFilipe Manana 				goto next_key;
5455da447009SFilipe Manana 			}
5456da447009SFilipe Manana 		}
5457da447009SFilipe Manana 
5458da447009SFilipe Manana 		/* Skip xattrs, we log them later with btrfs_log_all_xattrs() */
5459da447009SFilipe Manana 		if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
5460da447009SFilipe Manana 			if (ins_nr == 0)
5461da447009SFilipe Manana 				goto next_slot;
5462da447009SFilipe Manana 			ret = copy_items(trans, inode, dst_path, path,
5463da447009SFilipe Manana 					 ins_start_slot,
5464da447009SFilipe Manana 					 ins_nr, inode_only, logged_isize);
5465da447009SFilipe Manana 			if (ret < 0)
5466da447009SFilipe Manana 				return ret;
5467da447009SFilipe Manana 			ins_nr = 0;
5468da447009SFilipe Manana 			goto next_slot;
5469da447009SFilipe Manana 		}
5470da447009SFilipe Manana 
5471da447009SFilipe Manana 		if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5472da447009SFilipe Manana 			ins_nr++;
5473da447009SFilipe Manana 			goto next_slot;
5474da447009SFilipe Manana 		} else if (!ins_nr) {
5475da447009SFilipe Manana 			ins_start_slot = path->slots[0];
5476da447009SFilipe Manana 			ins_nr = 1;
5477da447009SFilipe Manana 			goto next_slot;
5478da447009SFilipe Manana 		}
5479da447009SFilipe Manana 
5480da447009SFilipe Manana 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5481da447009SFilipe Manana 				 ins_nr, inode_only, logged_isize);
5482da447009SFilipe Manana 		if (ret < 0)
5483da447009SFilipe Manana 			return ret;
5484da447009SFilipe Manana 		ins_nr = 1;
5485da447009SFilipe Manana 		ins_start_slot = path->slots[0];
5486da447009SFilipe Manana next_slot:
5487da447009SFilipe Manana 		path->slots[0]++;
5488da447009SFilipe Manana 		if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
5489da447009SFilipe Manana 			btrfs_item_key_to_cpu(path->nodes[0], min_key,
5490da447009SFilipe Manana 					      path->slots[0]);
5491da447009SFilipe Manana 			goto again;
5492da447009SFilipe Manana 		}
5493da447009SFilipe Manana 		if (ins_nr) {
5494da447009SFilipe Manana 			ret = copy_items(trans, inode, dst_path, path,
5495da447009SFilipe Manana 					 ins_start_slot, ins_nr, inode_only,
5496da447009SFilipe Manana 					 logged_isize);
5497da447009SFilipe Manana 			if (ret < 0)
5498da447009SFilipe Manana 				return ret;
5499da447009SFilipe Manana 			ins_nr = 0;
5500da447009SFilipe Manana 		}
5501da447009SFilipe Manana 		btrfs_release_path(path);
5502da447009SFilipe Manana next_key:
5503da447009SFilipe Manana 		if (min_key->offset < (u64)-1) {
5504da447009SFilipe Manana 			min_key->offset++;
5505da447009SFilipe Manana 		} else if (min_key->type < max_key->type) {
5506da447009SFilipe Manana 			min_key->type++;
5507da447009SFilipe Manana 			min_key->offset = 0;
5508da447009SFilipe Manana 		} else {
5509da447009SFilipe Manana 			break;
5510da447009SFilipe Manana 		}
5511da447009SFilipe Manana 	}
5512da447009SFilipe Manana 	if (ins_nr)
5513da447009SFilipe Manana 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
5514da447009SFilipe Manana 				 ins_nr, inode_only, logged_isize);
5515da447009SFilipe Manana 
5516da447009SFilipe Manana 	return ret;
5517da447009SFilipe Manana }
5518da447009SFilipe Manana 
5519e02119d5SChris Mason /* log a single inode in the tree log.
5520e02119d5SChris Mason  * At least one parent directory for this inode must exist in the tree
5521e02119d5SChris Mason  * or be logged already.
5522e02119d5SChris Mason  *
5523e02119d5SChris Mason  * Any items from this inode changed by the current transaction are copied
5524e02119d5SChris Mason  * to the log tree.  An extra reference is taken on any extents in this
5525e02119d5SChris Mason  * file, allowing us to avoid a whole pile of corner cases around logging
5526e02119d5SChris Mason  * blocks that have been removed from the tree.
5527e02119d5SChris Mason  *
5528e02119d5SChris Mason  * See LOG_INODE_ALL and related defines for a description of what inode_only
5529e02119d5SChris Mason  * does.
5530e02119d5SChris Mason  *
5531e02119d5SChris Mason  * This handles both files and directories.
5532e02119d5SChris Mason  */
553312fcfd22SChris Mason static int btrfs_log_inode(struct btrfs_trans_handle *trans,
553490d04510SFilipe Manana 			   struct btrfs_inode *inode,
553549dae1bcSFilipe Manana 			   int inode_only,
55368407f553SFilipe Manana 			   struct btrfs_log_ctx *ctx)
5537e02119d5SChris Mason {
5538e02119d5SChris Mason 	struct btrfs_path *path;
5539e02119d5SChris Mason 	struct btrfs_path *dst_path;
5540e02119d5SChris Mason 	struct btrfs_key min_key;
5541e02119d5SChris Mason 	struct btrfs_key max_key;
554290d04510SFilipe Manana 	struct btrfs_root *log = inode->root->log_root;
55434a500fd1SYan, Zheng 	int err = 0;
55448c8648ddSFilipe Manana 	int ret = 0;
55455dc562c5SJosef Bacik 	bool fast_search = false;
5546a59108a7SNikolay Borisov 	u64 ino = btrfs_ino(inode);
5547a59108a7SNikolay Borisov 	struct extent_map_tree *em_tree = &inode->extent_tree;
55481a4bcf47SFilipe Manana 	u64 logged_isize = 0;
5549e4545de5SFilipe Manana 	bool need_log_inode_item = true;
55509a8fca62SFilipe Manana 	bool xattrs_logged = false;
5551a3baaf0dSFilipe Manana 	bool recursive_logging = false;
55522ac691d8SFilipe Manana 	bool inode_item_dropped = true;
5553e02119d5SChris Mason 
5554e02119d5SChris Mason 	path = btrfs_alloc_path();
55555df67083STsutomu Itoh 	if (!path)
55565df67083STsutomu Itoh 		return -ENOMEM;
5557e02119d5SChris Mason 	dst_path = btrfs_alloc_path();
55585df67083STsutomu Itoh 	if (!dst_path) {
55595df67083STsutomu Itoh 		btrfs_free_path(path);
55605df67083STsutomu Itoh 		return -ENOMEM;
55615df67083STsutomu Itoh 	}
5562e02119d5SChris Mason 
556333345d01SLi Zefan 	min_key.objectid = ino;
5564e02119d5SChris Mason 	min_key.type = BTRFS_INODE_ITEM_KEY;
5565e02119d5SChris Mason 	min_key.offset = 0;
5566e02119d5SChris Mason 
556733345d01SLi Zefan 	max_key.objectid = ino;
556812fcfd22SChris Mason 
556912fcfd22SChris Mason 
55705dc562c5SJosef Bacik 	/* today the code can only do partial logging of directories */
5571a59108a7SNikolay Borisov 	if (S_ISDIR(inode->vfs_inode.i_mode) ||
55725269b67eSMiao Xie 	    (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5573a59108a7SNikolay Borisov 		       &inode->runtime_flags) &&
5574781feef7SLiu Bo 	     inode_only >= LOG_INODE_EXISTS))
5575e02119d5SChris Mason 		max_key.type = BTRFS_XATTR_ITEM_KEY;
5576e02119d5SChris Mason 	else
5577e02119d5SChris Mason 		max_key.type = (u8)-1;
5578e02119d5SChris Mason 	max_key.offset = (u64)-1;
5579e02119d5SChris Mason 
55802c2c452bSFilipe Manana 	/*
55815aa7d1a7SFilipe Manana 	 * Only run delayed items if we are a directory. We want to make sure
55825aa7d1a7SFilipe Manana 	 * all directory indexes hit the fs/subvolume tree so we can find them
55835aa7d1a7SFilipe Manana 	 * and figure out which index ranges have to be logged.
55842c2c452bSFilipe Manana 	 */
5585f6df27ddSFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode)) {
5586f6df27ddSFilipe Manana 		err = btrfs_commit_inode_delayed_items(trans, inode);
5587f6df27ddSFilipe Manana 		if (err)
5588f6df27ddSFilipe Manana 			goto out;
558916cdcec7SMiao Xie 	}
559016cdcec7SMiao Xie 
5591a3baaf0dSFilipe Manana 	if (inode_only == LOG_OTHER_INODE || inode_only == LOG_OTHER_INODE_ALL) {
5592a3baaf0dSFilipe Manana 		recursive_logging = true;
5593a3baaf0dSFilipe Manana 		if (inode_only == LOG_OTHER_INODE)
5594781feef7SLiu Bo 			inode_only = LOG_INODE_EXISTS;
5595a3baaf0dSFilipe Manana 		else
5596a3baaf0dSFilipe Manana 			inode_only = LOG_INODE_ALL;
5597a59108a7SNikolay Borisov 		mutex_lock_nested(&inode->log_mutex, SINGLE_DEPTH_NESTING);
5598781feef7SLiu Bo 	} else {
5599a59108a7SNikolay Borisov 		mutex_lock(&inode->log_mutex);
5600781feef7SLiu Bo 	}
5601e02119d5SChris Mason 
56025e33a2bdSFilipe Manana 	/*
560364d6b281SFilipe Manana 	 * This is for cases where logging a directory could result in losing a
560464d6b281SFilipe Manana 	 * a file after replaying the log. For example, if we move a file from a
560564d6b281SFilipe Manana 	 * directory A to a directory B, then fsync directory A, we have no way
560664d6b281SFilipe Manana 	 * to known the file was moved from A to B, so logging just A would
560764d6b281SFilipe Manana 	 * result in losing the file after a log replay.
560864d6b281SFilipe Manana 	 */
560964d6b281SFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode) &&
561064d6b281SFilipe Manana 	    inode_only == LOG_INODE_ALL &&
561164d6b281SFilipe Manana 	    inode->last_unlink_trans >= trans->transid) {
561264d6b281SFilipe Manana 		btrfs_set_log_full_commit(trans);
561364d6b281SFilipe Manana 		err = 1;
561464d6b281SFilipe Manana 		goto out_unlock;
561564d6b281SFilipe Manana 	}
561664d6b281SFilipe Manana 
561764d6b281SFilipe Manana 	/*
5618e02119d5SChris Mason 	 * a brute force approach to making sure we get the most uptodate
5619e02119d5SChris Mason 	 * copies of everything.
5620e02119d5SChris Mason 	 */
5621a59108a7SNikolay Borisov 	if (S_ISDIR(inode->vfs_inode.i_mode)) {
5622e02119d5SChris Mason 		int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
5623e02119d5SChris Mason 
5624ab12313aSFilipe Manana 		clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
56254f764e51SFilipe Manana 		if (inode_only == LOG_INODE_EXISTS)
56264f764e51SFilipe Manana 			max_key_type = BTRFS_XATTR_ITEM_KEY;
562788e221cdSFilipe Manana 		ret = drop_inode_items(trans, log, path, inode, max_key_type);
5628e02119d5SChris Mason 	} else {
5629a5c733a4SFilipe Manana 		if (inode_only == LOG_INODE_EXISTS && inode_logged(trans, inode)) {
56301a4bcf47SFilipe Manana 			/*
56311a4bcf47SFilipe Manana 			 * Make sure the new inode item we write to the log has
56321a4bcf47SFilipe Manana 			 * the same isize as the current one (if it exists).
56331a4bcf47SFilipe Manana 			 * This is necessary to prevent data loss after log
56341a4bcf47SFilipe Manana 			 * replay, and also to prevent doing a wrong expanding
56351a4bcf47SFilipe Manana 			 * truncate - for e.g. create file, write 4K into offset
56361a4bcf47SFilipe Manana 			 * 0, fsync, write 4K into offset 4096, add hard link,
56371a4bcf47SFilipe Manana 			 * fsync some other file (to sync log), power fail - if
56381a4bcf47SFilipe Manana 			 * we use the inode's current i_size, after log replay
56391a4bcf47SFilipe Manana 			 * we get a 8Kb file, with the last 4Kb extent as a hole
56401a4bcf47SFilipe Manana 			 * (zeroes), as if an expanding truncate happened,
56411a4bcf47SFilipe Manana 			 * instead of getting a file of 4Kb only.
56421a4bcf47SFilipe Manana 			 */
5643a59108a7SNikolay Borisov 			err = logged_inode_size(log, inode, path, &logged_isize);
56441a4bcf47SFilipe Manana 			if (err)
56451a4bcf47SFilipe Manana 				goto out_unlock;
56461a4bcf47SFilipe Manana 		}
5647a742994aSFilipe Manana 		if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5648a59108a7SNikolay Borisov 			     &inode->runtime_flags)) {
5649a742994aSFilipe Manana 			if (inode_only == LOG_INODE_EXISTS) {
56504f764e51SFilipe Manana 				max_key.type = BTRFS_XATTR_ITEM_KEY;
565188e221cdSFilipe Manana 				ret = drop_inode_items(trans, log, path, inode,
5652a742994aSFilipe Manana 						       max_key.type);
5653a742994aSFilipe Manana 			} else {
5654a742994aSFilipe Manana 				clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5655a59108a7SNikolay Borisov 					  &inode->runtime_flags);
5656e9976151SJosef Bacik 				clear_bit(BTRFS_INODE_COPY_EVERYTHING,
5657a59108a7SNikolay Borisov 					  &inode->runtime_flags);
56584934a815SFilipe Manana 				if (inode_logged(trans, inode))
56594934a815SFilipe Manana 					ret = truncate_inode_items(trans, log,
56604934a815SFilipe Manana 								   inode, 0, 0);
5661a742994aSFilipe Manana 			}
56624f764e51SFilipe Manana 		} else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
5663a59108a7SNikolay Borisov 					      &inode->runtime_flags) ||
56646cfab851SJosef Bacik 			   inode_only == LOG_INODE_EXISTS) {
56654f764e51SFilipe Manana 			if (inode_only == LOG_INODE_ALL)
5666a95249b3SJosef Bacik 				fast_search = true;
5667a95249b3SJosef Bacik 			max_key.type = BTRFS_XATTR_ITEM_KEY;
566888e221cdSFilipe Manana 			ret = drop_inode_items(trans, log, path, inode,
5669a95249b3SJosef Bacik 					       max_key.type);
56705dc562c5SJosef Bacik 		} else {
5671183f37faSLiu Bo 			if (inode_only == LOG_INODE_ALL)
56725dc562c5SJosef Bacik 				fast_search = true;
56732ac691d8SFilipe Manana 			inode_item_dropped = false;
5674a95249b3SJosef Bacik 			goto log_extents;
5675a95249b3SJosef Bacik 		}
5676a95249b3SJosef Bacik 
5677e02119d5SChris Mason 	}
56784a500fd1SYan, Zheng 	if (ret) {
56794a500fd1SYan, Zheng 		err = ret;
56804a500fd1SYan, Zheng 		goto out_unlock;
56814a500fd1SYan, Zheng 	}
5682e02119d5SChris Mason 
5683da447009SFilipe Manana 	err = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
5684da447009SFilipe Manana 				      path, dst_path, logged_isize,
56857af59743SFilipe Manana 				      recursive_logging, inode_only, ctx,
56867af59743SFilipe Manana 				      &need_log_inode_item);
568744f714daSFilipe Manana 	if (err)
568844f714daSFilipe Manana 		goto out_unlock;
56895dc562c5SJosef Bacik 
569036283bf7SFilipe Manana 	btrfs_release_path(path);
569136283bf7SFilipe Manana 	btrfs_release_path(dst_path);
569290d04510SFilipe Manana 	err = btrfs_log_all_xattrs(trans, inode, path, dst_path);
569336283bf7SFilipe Manana 	if (err)
569436283bf7SFilipe Manana 		goto out_unlock;
56959a8fca62SFilipe Manana 	xattrs_logged = true;
5696a89ca6f2SFilipe Manana 	if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
5697a89ca6f2SFilipe Manana 		btrfs_release_path(path);
5698a89ca6f2SFilipe Manana 		btrfs_release_path(dst_path);
569990d04510SFilipe Manana 		err = btrfs_log_holes(trans, inode, path);
5700a89ca6f2SFilipe Manana 		if (err)
5701a89ca6f2SFilipe Manana 			goto out_unlock;
5702a89ca6f2SFilipe Manana 	}
5703a95249b3SJosef Bacik log_extents:
5704f3b15ccdSJosef Bacik 	btrfs_release_path(path);
57055dc562c5SJosef Bacik 	btrfs_release_path(dst_path);
5706e4545de5SFilipe Manana 	if (need_log_inode_item) {
57072ac691d8SFilipe Manana 		err = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
5708e4545de5SFilipe Manana 		if (err)
5709e4545de5SFilipe Manana 			goto out_unlock;
5710b590b839SFilipe Manana 		/*
5711b590b839SFilipe Manana 		 * If we are doing a fast fsync and the inode was logged before
5712b590b839SFilipe Manana 		 * in this transaction, we don't need to log the xattrs because
5713b590b839SFilipe Manana 		 * they were logged before. If xattrs were added, changed or
5714b590b839SFilipe Manana 		 * deleted since the last time we logged the inode, then we have
5715b590b839SFilipe Manana 		 * already logged them because the inode had the runtime flag
5716b590b839SFilipe Manana 		 * BTRFS_INODE_COPY_EVERYTHING set.
5717b590b839SFilipe Manana 		 */
5718b590b839SFilipe Manana 		if (!xattrs_logged && inode->logged_trans < trans->transid) {
571990d04510SFilipe Manana 			err = btrfs_log_all_xattrs(trans, inode, path, dst_path);
5720b590b839SFilipe Manana 			if (err)
5721b590b839SFilipe Manana 				goto out_unlock;
5722b590b839SFilipe Manana 			btrfs_release_path(path);
5723b590b839SFilipe Manana 		}
5724e4545de5SFilipe Manana 	}
5725f3b15ccdSJosef Bacik 	if (fast_search) {
572690d04510SFilipe Manana 		ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
57275dc562c5SJosef Bacik 		if (ret) {
57285dc562c5SJosef Bacik 			err = ret;
57295dc562c5SJosef Bacik 			goto out_unlock;
57305dc562c5SJosef Bacik 		}
5731d006a048SJosef Bacik 	} else if (inode_only == LOG_INODE_ALL) {
573206d3d22bSLiu Bo 		struct extent_map *em, *n;
573306d3d22bSLiu Bo 
573449dae1bcSFilipe Manana 		write_lock(&em_tree->lock);
573548778179SFilipe Manana 		list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
573606d3d22bSLiu Bo 			list_del_init(&em->list);
573749dae1bcSFilipe Manana 		write_unlock(&em_tree->lock);
57385dc562c5SJosef Bacik 	}
57395dc562c5SJosef Bacik 
5740a59108a7SNikolay Borisov 	if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->vfs_inode.i_mode)) {
574190d04510SFilipe Manana 		ret = log_directory_changes(trans, inode, path, dst_path, ctx);
57424a500fd1SYan, Zheng 		if (ret) {
57434a500fd1SYan, Zheng 			err = ret;
57444a500fd1SYan, Zheng 			goto out_unlock;
57454a500fd1SYan, Zheng 		}
5746e02119d5SChris Mason 	}
574749dae1bcSFilipe Manana 
5748a59108a7SNikolay Borisov 	spin_lock(&inode->lock);
5749a59108a7SNikolay Borisov 	inode->logged_trans = trans->transid;
575075b463d2SFilipe Manana 	/*
57519acc8103SFilipe Manana 	 * Don't update last_log_commit if we logged that an inode exists.
5752130341beSFilipe Manana 	 * We do this for three reasons:
57539acc8103SFilipe Manana 	 *
57549acc8103SFilipe Manana 	 * 1) We might have had buffered writes to this inode that were
57559acc8103SFilipe Manana 	 *    flushed and had their ordered extents completed in this
57569acc8103SFilipe Manana 	 *    transaction, but we did not previously log the inode with
57579acc8103SFilipe Manana 	 *    LOG_INODE_ALL. Later the inode was evicted and after that
57589acc8103SFilipe Manana 	 *    it was loaded again and this LOG_INODE_EXISTS log operation
57599acc8103SFilipe Manana 	 *    happened. We must make sure that if an explicit fsync against
57609acc8103SFilipe Manana 	 *    the inode is performed later, it logs the new extents, an
57619acc8103SFilipe Manana 	 *    updated inode item, etc, and syncs the log. The same logic
57629acc8103SFilipe Manana 	 *    applies to direct IO writes instead of buffered writes.
57639acc8103SFilipe Manana 	 *
57649acc8103SFilipe Manana 	 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
57659acc8103SFilipe Manana 	 *    is logged with an i_size of 0 or whatever value was logged
57669acc8103SFilipe Manana 	 *    before. If later the i_size of the inode is increased by a
57679acc8103SFilipe Manana 	 *    truncate operation, the log is synced through an fsync of
57689acc8103SFilipe Manana 	 *    some other inode and then finally an explicit fsync against
57699acc8103SFilipe Manana 	 *    this inode is made, we must make sure this fsync logs the
57709acc8103SFilipe Manana 	 *    inode with the new i_size, the hole between old i_size and
57719acc8103SFilipe Manana 	 *    the new i_size, and syncs the log.
5772130341beSFilipe Manana 	 *
5773130341beSFilipe Manana 	 * 3) If we are logging that an ancestor inode exists as part of
5774130341beSFilipe Manana 	 *    logging a new name from a link or rename operation, don't update
5775130341beSFilipe Manana 	 *    its last_log_commit - otherwise if an explicit fsync is made
5776130341beSFilipe Manana 	 *    against an ancestor, the fsync considers the inode in the log
5777130341beSFilipe Manana 	 *    and doesn't sync the log, resulting in the ancestor missing after
5778130341beSFilipe Manana 	 *    a power failure unless the log was synced as part of an fsync
5779130341beSFilipe Manana 	 *    against any other unrelated inode.
578075b463d2SFilipe Manana 	 */
57819acc8103SFilipe Manana 	if (inode_only != LOG_INODE_EXISTS)
5782a59108a7SNikolay Borisov 		inode->last_log_commit = inode->last_sub_trans;
5783a59108a7SNikolay Borisov 	spin_unlock(&inode->lock);
57844a500fd1SYan, Zheng out_unlock:
5785a59108a7SNikolay Borisov 	mutex_unlock(&inode->log_mutex);
5786f6df27ddSFilipe Manana out:
5787e02119d5SChris Mason 	btrfs_free_path(path);
5788e02119d5SChris Mason 	btrfs_free_path(dst_path);
57894a500fd1SYan, Zheng 	return err;
5790e02119d5SChris Mason }
5791e02119d5SChris Mason 
579212fcfd22SChris Mason /*
5793ab12313aSFilipe Manana  * Check if we need to log an inode. This is used in contexts where while
5794ab12313aSFilipe Manana  * logging an inode we need to log another inode (either that it exists or in
5795ab12313aSFilipe Manana  * full mode). This is used instead of btrfs_inode_in_log() because the later
5796ab12313aSFilipe Manana  * requires the inode to be in the log and have the log transaction committed,
5797ab12313aSFilipe Manana  * while here we do not care if the log transaction was already committed - our
5798ab12313aSFilipe Manana  * caller will commit the log later - and we want to avoid logging an inode
5799ab12313aSFilipe Manana  * multiple times when multiple tasks have joined the same log transaction.
5800ab12313aSFilipe Manana  */
5801ab12313aSFilipe Manana static bool need_log_inode(struct btrfs_trans_handle *trans,
5802ab12313aSFilipe Manana 			   struct btrfs_inode *inode)
5803ab12313aSFilipe Manana {
5804ab12313aSFilipe Manana 	/*
58058be2ba2eSFilipe Manana 	 * If a directory was not modified, no dentries added or removed, we can
58068be2ba2eSFilipe Manana 	 * and should avoid logging it.
58078be2ba2eSFilipe Manana 	 */
58088be2ba2eSFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
58098be2ba2eSFilipe Manana 		return false;
58108be2ba2eSFilipe Manana 
58118be2ba2eSFilipe Manana 	/*
5812ab12313aSFilipe Manana 	 * If this inode does not have new/updated/deleted xattrs since the last
5813ab12313aSFilipe Manana 	 * time it was logged and is flagged as logged in the current transaction,
5814ab12313aSFilipe Manana 	 * we can skip logging it. As for new/deleted names, those are updated in
5815ab12313aSFilipe Manana 	 * the log by link/unlink/rename operations.
5816ab12313aSFilipe Manana 	 * In case the inode was logged and then evicted and reloaded, its
5817ab12313aSFilipe Manana 	 * logged_trans will be 0, in which case we have to fully log it since
5818ab12313aSFilipe Manana 	 * logged_trans is a transient field, not persisted.
5819ab12313aSFilipe Manana 	 */
5820ab12313aSFilipe Manana 	if (inode->logged_trans == trans->transid &&
5821ab12313aSFilipe Manana 	    !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5822ab12313aSFilipe Manana 		return false;
5823ab12313aSFilipe Manana 
5824ab12313aSFilipe Manana 	return true;
5825ab12313aSFilipe Manana }
5826ab12313aSFilipe Manana 
58272f2ff0eeSFilipe Manana struct btrfs_dir_list {
58282f2ff0eeSFilipe Manana 	u64 ino;
58292f2ff0eeSFilipe Manana 	struct list_head list;
58302f2ff0eeSFilipe Manana };
58312f2ff0eeSFilipe Manana 
58322f2ff0eeSFilipe Manana /*
58332f2ff0eeSFilipe Manana  * Log the inodes of the new dentries of a directory. See log_dir_items() for
58342f2ff0eeSFilipe Manana  * details about the why it is needed.
58352f2ff0eeSFilipe Manana  * This is a recursive operation - if an existing dentry corresponds to a
58362f2ff0eeSFilipe Manana  * directory, that directory's new entries are logged too (same behaviour as
58372f2ff0eeSFilipe Manana  * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
58382f2ff0eeSFilipe Manana  * the dentries point to we do not lock their i_mutex, otherwise lockdep
58392f2ff0eeSFilipe Manana  * complains about the following circular lock dependency / possible deadlock:
58402f2ff0eeSFilipe Manana  *
58412f2ff0eeSFilipe Manana  *        CPU0                                        CPU1
58422f2ff0eeSFilipe Manana  *        ----                                        ----
58432f2ff0eeSFilipe Manana  * lock(&type->i_mutex_dir_key#3/2);
58442f2ff0eeSFilipe Manana  *                                            lock(sb_internal#2);
58452f2ff0eeSFilipe Manana  *                                            lock(&type->i_mutex_dir_key#3/2);
58462f2ff0eeSFilipe Manana  * lock(&sb->s_type->i_mutex_key#14);
58472f2ff0eeSFilipe Manana  *
58482f2ff0eeSFilipe Manana  * Where sb_internal is the lock (a counter that works as a lock) acquired by
58492f2ff0eeSFilipe Manana  * sb_start_intwrite() in btrfs_start_transaction().
58502f2ff0eeSFilipe Manana  * Not locking i_mutex of the inodes is still safe because:
58512f2ff0eeSFilipe Manana  *
58522f2ff0eeSFilipe Manana  * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
58532f2ff0eeSFilipe Manana  *    that while logging the inode new references (names) are added or removed
58542f2ff0eeSFilipe Manana  *    from the inode, leaving the logged inode item with a link count that does
58552f2ff0eeSFilipe Manana  *    not match the number of logged inode reference items. This is fine because
58562f2ff0eeSFilipe Manana  *    at log replay time we compute the real number of links and correct the
58572f2ff0eeSFilipe Manana  *    link count in the inode item (see replay_one_buffer() and
58582f2ff0eeSFilipe Manana  *    link_to_fixup_dir());
58592f2ff0eeSFilipe Manana  *
58602f2ff0eeSFilipe Manana  * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5861339d0354SFilipe Manana  *    while logging the inode's items new index items (key type
5862339d0354SFilipe Manana  *    BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
58632f2ff0eeSFilipe Manana  *    has a size that doesn't match the sum of the lengths of all the logged
5864339d0354SFilipe Manana  *    names - this is ok, not a problem, because at log replay time we set the
5865339d0354SFilipe Manana  *    directory's i_size to the correct value (see replay_one_name() and
5866339d0354SFilipe Manana  *    do_overwrite_item()).
58672f2ff0eeSFilipe Manana  */
58682f2ff0eeSFilipe Manana static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
58692f2ff0eeSFilipe Manana 				struct btrfs_root *root,
587051cc0d32SNikolay Borisov 				struct btrfs_inode *start_inode,
58712f2ff0eeSFilipe Manana 				struct btrfs_log_ctx *ctx)
58722f2ff0eeSFilipe Manana {
58730b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
58742f2ff0eeSFilipe Manana 	struct btrfs_root *log = root->log_root;
58752f2ff0eeSFilipe Manana 	struct btrfs_path *path;
58762f2ff0eeSFilipe Manana 	LIST_HEAD(dir_list);
58772f2ff0eeSFilipe Manana 	struct btrfs_dir_list *dir_elem;
58782f2ff0eeSFilipe Manana 	int ret = 0;
58792f2ff0eeSFilipe Manana 
5880c48792c6SFilipe Manana 	/*
5881c48792c6SFilipe Manana 	 * If we are logging a new name, as part of a link or rename operation,
5882c48792c6SFilipe Manana 	 * don't bother logging new dentries, as we just want to log the names
5883c48792c6SFilipe Manana 	 * of an inode and that any new parents exist.
5884c48792c6SFilipe Manana 	 */
5885c48792c6SFilipe Manana 	if (ctx->logging_new_name)
5886c48792c6SFilipe Manana 		return 0;
5887c48792c6SFilipe Manana 
58882f2ff0eeSFilipe Manana 	path = btrfs_alloc_path();
58892f2ff0eeSFilipe Manana 	if (!path)
58902f2ff0eeSFilipe Manana 		return -ENOMEM;
58912f2ff0eeSFilipe Manana 
58922f2ff0eeSFilipe Manana 	dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
58932f2ff0eeSFilipe Manana 	if (!dir_elem) {
58942f2ff0eeSFilipe Manana 		btrfs_free_path(path);
58952f2ff0eeSFilipe Manana 		return -ENOMEM;
58962f2ff0eeSFilipe Manana 	}
589751cc0d32SNikolay Borisov 	dir_elem->ino = btrfs_ino(start_inode);
58982f2ff0eeSFilipe Manana 	list_add_tail(&dir_elem->list, &dir_list);
58992f2ff0eeSFilipe Manana 
59002f2ff0eeSFilipe Manana 	while (!list_empty(&dir_list)) {
59012f2ff0eeSFilipe Manana 		struct extent_buffer *leaf;
59022f2ff0eeSFilipe Manana 		struct btrfs_key min_key;
59032f2ff0eeSFilipe Manana 		int nritems;
59042f2ff0eeSFilipe Manana 		int i;
59052f2ff0eeSFilipe Manana 
59062f2ff0eeSFilipe Manana 		dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list,
59072f2ff0eeSFilipe Manana 					    list);
59082f2ff0eeSFilipe Manana 		if (ret)
59092f2ff0eeSFilipe Manana 			goto next_dir_inode;
59102f2ff0eeSFilipe Manana 
59112f2ff0eeSFilipe Manana 		min_key.objectid = dir_elem->ino;
5912339d0354SFilipe Manana 		min_key.type = BTRFS_DIR_INDEX_KEY;
59132f2ff0eeSFilipe Manana 		min_key.offset = 0;
59142f2ff0eeSFilipe Manana again:
59152f2ff0eeSFilipe Manana 		btrfs_release_path(path);
59162f2ff0eeSFilipe Manana 		ret = btrfs_search_forward(log, &min_key, path, trans->transid);
59172f2ff0eeSFilipe Manana 		if (ret < 0) {
59182f2ff0eeSFilipe Manana 			goto next_dir_inode;
59192f2ff0eeSFilipe Manana 		} else if (ret > 0) {
59202f2ff0eeSFilipe Manana 			ret = 0;
59212f2ff0eeSFilipe Manana 			goto next_dir_inode;
59222f2ff0eeSFilipe Manana 		}
59232f2ff0eeSFilipe Manana 
59242f2ff0eeSFilipe Manana process_leaf:
59252f2ff0eeSFilipe Manana 		leaf = path->nodes[0];
59262f2ff0eeSFilipe Manana 		nritems = btrfs_header_nritems(leaf);
59272f2ff0eeSFilipe Manana 		for (i = path->slots[0]; i < nritems; i++) {
59282f2ff0eeSFilipe Manana 			struct btrfs_dir_item *di;
59292f2ff0eeSFilipe Manana 			struct btrfs_key di_key;
59302f2ff0eeSFilipe Manana 			struct inode *di_inode;
59312f2ff0eeSFilipe Manana 			struct btrfs_dir_list *new_dir_elem;
59322f2ff0eeSFilipe Manana 			int log_mode = LOG_INODE_EXISTS;
59332f2ff0eeSFilipe Manana 			int type;
59342f2ff0eeSFilipe Manana 
59352f2ff0eeSFilipe Manana 			btrfs_item_key_to_cpu(leaf, &min_key, i);
59362f2ff0eeSFilipe Manana 			if (min_key.objectid != dir_elem->ino ||
5937339d0354SFilipe Manana 			    min_key.type != BTRFS_DIR_INDEX_KEY)
59382f2ff0eeSFilipe Manana 				goto next_dir_inode;
59392f2ff0eeSFilipe Manana 
59402f2ff0eeSFilipe Manana 			di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
59412f2ff0eeSFilipe Manana 			type = btrfs_dir_type(leaf, di);
59422f2ff0eeSFilipe Manana 			if (btrfs_dir_transid(leaf, di) < trans->transid &&
59432f2ff0eeSFilipe Manana 			    type != BTRFS_FT_DIR)
59442f2ff0eeSFilipe Manana 				continue;
59452f2ff0eeSFilipe Manana 			btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
59462f2ff0eeSFilipe Manana 			if (di_key.type == BTRFS_ROOT_ITEM_KEY)
59472f2ff0eeSFilipe Manana 				continue;
59482f2ff0eeSFilipe Manana 
5949ec125cfbSRobbie Ko 			btrfs_release_path(path);
59500202e83fSDavid Sterba 			di_inode = btrfs_iget(fs_info->sb, di_key.objectid, root);
59512f2ff0eeSFilipe Manana 			if (IS_ERR(di_inode)) {
59522f2ff0eeSFilipe Manana 				ret = PTR_ERR(di_inode);
59532f2ff0eeSFilipe Manana 				goto next_dir_inode;
59542f2ff0eeSFilipe Manana 			}
59552f2ff0eeSFilipe Manana 
59560e44cb3fSFilipe Manana 			if (!need_log_inode(trans, BTRFS_I(di_inode))) {
5957410f954cSFilipe Manana 				btrfs_add_delayed_iput(di_inode);
5958ec125cfbSRobbie Ko 				break;
59592f2ff0eeSFilipe Manana 			}
59602f2ff0eeSFilipe Manana 
59612f2ff0eeSFilipe Manana 			ctx->log_new_dentries = false;
59623f9749f6SFilipe Manana 			if (type == BTRFS_FT_DIR || type == BTRFS_FT_SYMLINK)
59632f2ff0eeSFilipe Manana 				log_mode = LOG_INODE_ALL;
596490d04510SFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(di_inode),
596548778179SFilipe Manana 					      log_mode, ctx);
5966410f954cSFilipe Manana 			btrfs_add_delayed_iput(di_inode);
59672f2ff0eeSFilipe Manana 			if (ret)
59682f2ff0eeSFilipe Manana 				goto next_dir_inode;
59692f2ff0eeSFilipe Manana 			if (ctx->log_new_dentries) {
59702f2ff0eeSFilipe Manana 				new_dir_elem = kmalloc(sizeof(*new_dir_elem),
59712f2ff0eeSFilipe Manana 						       GFP_NOFS);
59722f2ff0eeSFilipe Manana 				if (!new_dir_elem) {
59732f2ff0eeSFilipe Manana 					ret = -ENOMEM;
59742f2ff0eeSFilipe Manana 					goto next_dir_inode;
59752f2ff0eeSFilipe Manana 				}
59762f2ff0eeSFilipe Manana 				new_dir_elem->ino = di_key.objectid;
59772f2ff0eeSFilipe Manana 				list_add_tail(&new_dir_elem->list, &dir_list);
59782f2ff0eeSFilipe Manana 			}
59792f2ff0eeSFilipe Manana 			break;
59802f2ff0eeSFilipe Manana 		}
59812f2ff0eeSFilipe Manana 		if (i == nritems) {
59822f2ff0eeSFilipe Manana 			ret = btrfs_next_leaf(log, path);
59832f2ff0eeSFilipe Manana 			if (ret < 0) {
59842f2ff0eeSFilipe Manana 				goto next_dir_inode;
59852f2ff0eeSFilipe Manana 			} else if (ret > 0) {
59862f2ff0eeSFilipe Manana 				ret = 0;
59872f2ff0eeSFilipe Manana 				goto next_dir_inode;
59882f2ff0eeSFilipe Manana 			}
59892f2ff0eeSFilipe Manana 			goto process_leaf;
59902f2ff0eeSFilipe Manana 		}
59912f2ff0eeSFilipe Manana 		if (min_key.offset < (u64)-1) {
59922f2ff0eeSFilipe Manana 			min_key.offset++;
59932f2ff0eeSFilipe Manana 			goto again;
59942f2ff0eeSFilipe Manana 		}
59952f2ff0eeSFilipe Manana next_dir_inode:
59962f2ff0eeSFilipe Manana 		list_del(&dir_elem->list);
59972f2ff0eeSFilipe Manana 		kfree(dir_elem);
59982f2ff0eeSFilipe Manana 	}
59992f2ff0eeSFilipe Manana 
60002f2ff0eeSFilipe Manana 	btrfs_free_path(path);
60012f2ff0eeSFilipe Manana 	return ret;
60022f2ff0eeSFilipe Manana }
60032f2ff0eeSFilipe Manana 
600418aa0922SFilipe Manana static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
6005d0a0b78dSNikolay Borisov 				 struct btrfs_inode *inode,
600618aa0922SFilipe Manana 				 struct btrfs_log_ctx *ctx)
600718aa0922SFilipe Manana {
60083ffbd68cSDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
600918aa0922SFilipe Manana 	int ret;
601018aa0922SFilipe Manana 	struct btrfs_path *path;
601118aa0922SFilipe Manana 	struct btrfs_key key;
6012d0a0b78dSNikolay Borisov 	struct btrfs_root *root = inode->root;
6013d0a0b78dSNikolay Borisov 	const u64 ino = btrfs_ino(inode);
601418aa0922SFilipe Manana 
601518aa0922SFilipe Manana 	path = btrfs_alloc_path();
601618aa0922SFilipe Manana 	if (!path)
601718aa0922SFilipe Manana 		return -ENOMEM;
601818aa0922SFilipe Manana 	path->skip_locking = 1;
601918aa0922SFilipe Manana 	path->search_commit_root = 1;
602018aa0922SFilipe Manana 
602118aa0922SFilipe Manana 	key.objectid = ino;
602218aa0922SFilipe Manana 	key.type = BTRFS_INODE_REF_KEY;
602318aa0922SFilipe Manana 	key.offset = 0;
602418aa0922SFilipe Manana 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
602518aa0922SFilipe Manana 	if (ret < 0)
602618aa0922SFilipe Manana 		goto out;
602718aa0922SFilipe Manana 
602818aa0922SFilipe Manana 	while (true) {
602918aa0922SFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
603018aa0922SFilipe Manana 		int slot = path->slots[0];
603118aa0922SFilipe Manana 		u32 cur_offset = 0;
603218aa0922SFilipe Manana 		u32 item_size;
603318aa0922SFilipe Manana 		unsigned long ptr;
603418aa0922SFilipe Manana 
603518aa0922SFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
603618aa0922SFilipe Manana 			ret = btrfs_next_leaf(root, path);
603718aa0922SFilipe Manana 			if (ret < 0)
603818aa0922SFilipe Manana 				goto out;
603918aa0922SFilipe Manana 			else if (ret > 0)
604018aa0922SFilipe Manana 				break;
604118aa0922SFilipe Manana 			continue;
604218aa0922SFilipe Manana 		}
604318aa0922SFilipe Manana 
604418aa0922SFilipe Manana 		btrfs_item_key_to_cpu(leaf, &key, slot);
604518aa0922SFilipe Manana 		/* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
604618aa0922SFilipe Manana 		if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
604718aa0922SFilipe Manana 			break;
604818aa0922SFilipe Manana 
60493212fa14SJosef Bacik 		item_size = btrfs_item_size(leaf, slot);
605018aa0922SFilipe Manana 		ptr = btrfs_item_ptr_offset(leaf, slot);
605118aa0922SFilipe Manana 		while (cur_offset < item_size) {
605218aa0922SFilipe Manana 			struct btrfs_key inode_key;
605318aa0922SFilipe Manana 			struct inode *dir_inode;
605418aa0922SFilipe Manana 
605518aa0922SFilipe Manana 			inode_key.type = BTRFS_INODE_ITEM_KEY;
605618aa0922SFilipe Manana 			inode_key.offset = 0;
605718aa0922SFilipe Manana 
605818aa0922SFilipe Manana 			if (key.type == BTRFS_INODE_EXTREF_KEY) {
605918aa0922SFilipe Manana 				struct btrfs_inode_extref *extref;
606018aa0922SFilipe Manana 
606118aa0922SFilipe Manana 				extref = (struct btrfs_inode_extref *)
606218aa0922SFilipe Manana 					(ptr + cur_offset);
606318aa0922SFilipe Manana 				inode_key.objectid = btrfs_inode_extref_parent(
606418aa0922SFilipe Manana 					leaf, extref);
606518aa0922SFilipe Manana 				cur_offset += sizeof(*extref);
606618aa0922SFilipe Manana 				cur_offset += btrfs_inode_extref_name_len(leaf,
606718aa0922SFilipe Manana 					extref);
606818aa0922SFilipe Manana 			} else {
606918aa0922SFilipe Manana 				inode_key.objectid = key.offset;
607018aa0922SFilipe Manana 				cur_offset = item_size;
607118aa0922SFilipe Manana 			}
607218aa0922SFilipe Manana 
60730202e83fSDavid Sterba 			dir_inode = btrfs_iget(fs_info->sb, inode_key.objectid,
60740202e83fSDavid Sterba 					       root);
60750f375eedSFilipe Manana 			/*
60760f375eedSFilipe Manana 			 * If the parent inode was deleted, return an error to
60770f375eedSFilipe Manana 			 * fallback to a transaction commit. This is to prevent
60780f375eedSFilipe Manana 			 * getting an inode that was moved from one parent A to
60790f375eedSFilipe Manana 			 * a parent B, got its former parent A deleted and then
60800f375eedSFilipe Manana 			 * it got fsync'ed, from existing at both parents after
60810f375eedSFilipe Manana 			 * a log replay (and the old parent still existing).
60820f375eedSFilipe Manana 			 * Example:
60830f375eedSFilipe Manana 			 *
60840f375eedSFilipe Manana 			 * mkdir /mnt/A
60850f375eedSFilipe Manana 			 * mkdir /mnt/B
60860f375eedSFilipe Manana 			 * touch /mnt/B/bar
60870f375eedSFilipe Manana 			 * sync
60880f375eedSFilipe Manana 			 * mv /mnt/B/bar /mnt/A/bar
60890f375eedSFilipe Manana 			 * mv -T /mnt/A /mnt/B
60900f375eedSFilipe Manana 			 * fsync /mnt/B/bar
60910f375eedSFilipe Manana 			 * <power fail>
60920f375eedSFilipe Manana 			 *
60930f375eedSFilipe Manana 			 * If we ignore the old parent B which got deleted,
60940f375eedSFilipe Manana 			 * after a log replay we would have file bar linked
60950f375eedSFilipe Manana 			 * at both parents and the old parent B would still
60960f375eedSFilipe Manana 			 * exist.
60970f375eedSFilipe Manana 			 */
60980f375eedSFilipe Manana 			if (IS_ERR(dir_inode)) {
60990f375eedSFilipe Manana 				ret = PTR_ERR(dir_inode);
61000f375eedSFilipe Manana 				goto out;
61010f375eedSFilipe Manana 			}
610218aa0922SFilipe Manana 
61033e6a86a1SFilipe Manana 			if (!need_log_inode(trans, BTRFS_I(dir_inode))) {
61043e6a86a1SFilipe Manana 				btrfs_add_delayed_iput(dir_inode);
61053e6a86a1SFilipe Manana 				continue;
61063e6a86a1SFilipe Manana 			}
61073e6a86a1SFilipe Manana 
6108657ed1aaSFilipe Manana 			ctx->log_new_dentries = false;
610990d04510SFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(dir_inode),
611048778179SFilipe Manana 					      LOG_INODE_ALL, ctx);
6111289cffcbSFilipe Manana 			if (!ret && ctx->log_new_dentries)
6112657ed1aaSFilipe Manana 				ret = log_new_dir_dentries(trans, root,
611351cc0d32SNikolay Borisov 						   BTRFS_I(dir_inode), ctx);
6114410f954cSFilipe Manana 			btrfs_add_delayed_iput(dir_inode);
611518aa0922SFilipe Manana 			if (ret)
611618aa0922SFilipe Manana 				goto out;
611718aa0922SFilipe Manana 		}
611818aa0922SFilipe Manana 		path->slots[0]++;
611918aa0922SFilipe Manana 	}
612018aa0922SFilipe Manana 	ret = 0;
612118aa0922SFilipe Manana out:
612218aa0922SFilipe Manana 	btrfs_free_path(path);
612318aa0922SFilipe Manana 	return ret;
612418aa0922SFilipe Manana }
612518aa0922SFilipe Manana 
6126b8aa330dSFilipe Manana static int log_new_ancestors(struct btrfs_trans_handle *trans,
6127b8aa330dSFilipe Manana 			     struct btrfs_root *root,
6128b8aa330dSFilipe Manana 			     struct btrfs_path *path,
6129b8aa330dSFilipe Manana 			     struct btrfs_log_ctx *ctx)
6130b8aa330dSFilipe Manana {
6131b8aa330dSFilipe Manana 	struct btrfs_key found_key;
6132b8aa330dSFilipe Manana 
6133b8aa330dSFilipe Manana 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
6134b8aa330dSFilipe Manana 
6135b8aa330dSFilipe Manana 	while (true) {
6136b8aa330dSFilipe Manana 		struct btrfs_fs_info *fs_info = root->fs_info;
6137b8aa330dSFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
6138b8aa330dSFilipe Manana 		int slot = path->slots[0];
6139b8aa330dSFilipe Manana 		struct btrfs_key search_key;
6140b8aa330dSFilipe Manana 		struct inode *inode;
61410202e83fSDavid Sterba 		u64 ino;
6142b8aa330dSFilipe Manana 		int ret = 0;
6143b8aa330dSFilipe Manana 
6144b8aa330dSFilipe Manana 		btrfs_release_path(path);
6145b8aa330dSFilipe Manana 
61460202e83fSDavid Sterba 		ino = found_key.offset;
61470202e83fSDavid Sterba 
6148b8aa330dSFilipe Manana 		search_key.objectid = found_key.offset;
6149b8aa330dSFilipe Manana 		search_key.type = BTRFS_INODE_ITEM_KEY;
6150b8aa330dSFilipe Manana 		search_key.offset = 0;
61510202e83fSDavid Sterba 		inode = btrfs_iget(fs_info->sb, ino, root);
6152b8aa330dSFilipe Manana 		if (IS_ERR(inode))
6153b8aa330dSFilipe Manana 			return PTR_ERR(inode);
6154b8aa330dSFilipe Manana 
6155ab12313aSFilipe Manana 		if (BTRFS_I(inode)->generation >= trans->transid &&
6156ab12313aSFilipe Manana 		    need_log_inode(trans, BTRFS_I(inode)))
615790d04510SFilipe Manana 			ret = btrfs_log_inode(trans, BTRFS_I(inode),
615848778179SFilipe Manana 					      LOG_INODE_EXISTS, ctx);
6159410f954cSFilipe Manana 		btrfs_add_delayed_iput(inode);
6160b8aa330dSFilipe Manana 		if (ret)
6161b8aa330dSFilipe Manana 			return ret;
6162b8aa330dSFilipe Manana 
6163b8aa330dSFilipe Manana 		if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
6164b8aa330dSFilipe Manana 			break;
6165b8aa330dSFilipe Manana 
6166b8aa330dSFilipe Manana 		search_key.type = BTRFS_INODE_REF_KEY;
6167b8aa330dSFilipe Manana 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6168b8aa330dSFilipe Manana 		if (ret < 0)
6169b8aa330dSFilipe Manana 			return ret;
6170b8aa330dSFilipe Manana 
6171b8aa330dSFilipe Manana 		leaf = path->nodes[0];
6172b8aa330dSFilipe Manana 		slot = path->slots[0];
6173b8aa330dSFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
6174b8aa330dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
6175b8aa330dSFilipe Manana 			if (ret < 0)
6176b8aa330dSFilipe Manana 				return ret;
6177b8aa330dSFilipe Manana 			else if (ret > 0)
6178b8aa330dSFilipe Manana 				return -ENOENT;
6179b8aa330dSFilipe Manana 			leaf = path->nodes[0];
6180b8aa330dSFilipe Manana 			slot = path->slots[0];
6181b8aa330dSFilipe Manana 		}
6182b8aa330dSFilipe Manana 
6183b8aa330dSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
6184b8aa330dSFilipe Manana 		if (found_key.objectid != search_key.objectid ||
6185b8aa330dSFilipe Manana 		    found_key.type != BTRFS_INODE_REF_KEY)
6186b8aa330dSFilipe Manana 			return -ENOENT;
6187b8aa330dSFilipe Manana 	}
6188b8aa330dSFilipe Manana 	return 0;
6189b8aa330dSFilipe Manana }
6190b8aa330dSFilipe Manana 
6191b8aa330dSFilipe Manana static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
6192b8aa330dSFilipe Manana 				  struct btrfs_inode *inode,
6193b8aa330dSFilipe Manana 				  struct dentry *parent,
6194b8aa330dSFilipe Manana 				  struct btrfs_log_ctx *ctx)
6195b8aa330dSFilipe Manana {
6196b8aa330dSFilipe Manana 	struct btrfs_root *root = inode->root;
6197b8aa330dSFilipe Manana 	struct dentry *old_parent = NULL;
6198b8aa330dSFilipe Manana 	struct super_block *sb = inode->vfs_inode.i_sb;
6199b8aa330dSFilipe Manana 	int ret = 0;
6200b8aa330dSFilipe Manana 
6201b8aa330dSFilipe Manana 	while (true) {
6202b8aa330dSFilipe Manana 		if (!parent || d_really_is_negative(parent) ||
6203b8aa330dSFilipe Manana 		    sb != parent->d_sb)
6204b8aa330dSFilipe Manana 			break;
6205b8aa330dSFilipe Manana 
6206b8aa330dSFilipe Manana 		inode = BTRFS_I(d_inode(parent));
6207b8aa330dSFilipe Manana 		if (root != inode->root)
6208b8aa330dSFilipe Manana 			break;
6209b8aa330dSFilipe Manana 
6210ab12313aSFilipe Manana 		if (inode->generation >= trans->transid &&
6211ab12313aSFilipe Manana 		    need_log_inode(trans, inode)) {
621290d04510SFilipe Manana 			ret = btrfs_log_inode(trans, inode,
621348778179SFilipe Manana 					      LOG_INODE_EXISTS, ctx);
6214b8aa330dSFilipe Manana 			if (ret)
6215b8aa330dSFilipe Manana 				break;
6216b8aa330dSFilipe Manana 		}
6217b8aa330dSFilipe Manana 		if (IS_ROOT(parent))
6218b8aa330dSFilipe Manana 			break;
6219b8aa330dSFilipe Manana 
6220b8aa330dSFilipe Manana 		parent = dget_parent(parent);
6221b8aa330dSFilipe Manana 		dput(old_parent);
6222b8aa330dSFilipe Manana 		old_parent = parent;
6223b8aa330dSFilipe Manana 	}
6224b8aa330dSFilipe Manana 	dput(old_parent);
6225b8aa330dSFilipe Manana 
6226b8aa330dSFilipe Manana 	return ret;
6227b8aa330dSFilipe Manana }
6228b8aa330dSFilipe Manana 
6229b8aa330dSFilipe Manana static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
6230b8aa330dSFilipe Manana 				 struct btrfs_inode *inode,
6231b8aa330dSFilipe Manana 				 struct dentry *parent,
6232b8aa330dSFilipe Manana 				 struct btrfs_log_ctx *ctx)
6233b8aa330dSFilipe Manana {
6234b8aa330dSFilipe Manana 	struct btrfs_root *root = inode->root;
6235b8aa330dSFilipe Manana 	const u64 ino = btrfs_ino(inode);
6236b8aa330dSFilipe Manana 	struct btrfs_path *path;
6237b8aa330dSFilipe Manana 	struct btrfs_key search_key;
6238b8aa330dSFilipe Manana 	int ret;
6239b8aa330dSFilipe Manana 
6240b8aa330dSFilipe Manana 	/*
6241b8aa330dSFilipe Manana 	 * For a single hard link case, go through a fast path that does not
6242b8aa330dSFilipe Manana 	 * need to iterate the fs/subvolume tree.
6243b8aa330dSFilipe Manana 	 */
6244b8aa330dSFilipe Manana 	if (inode->vfs_inode.i_nlink < 2)
6245b8aa330dSFilipe Manana 		return log_new_ancestors_fast(trans, inode, parent, ctx);
6246b8aa330dSFilipe Manana 
6247b8aa330dSFilipe Manana 	path = btrfs_alloc_path();
6248b8aa330dSFilipe Manana 	if (!path)
6249b8aa330dSFilipe Manana 		return -ENOMEM;
6250b8aa330dSFilipe Manana 
6251b8aa330dSFilipe Manana 	search_key.objectid = ino;
6252b8aa330dSFilipe Manana 	search_key.type = BTRFS_INODE_REF_KEY;
6253b8aa330dSFilipe Manana 	search_key.offset = 0;
6254b8aa330dSFilipe Manana again:
6255b8aa330dSFilipe Manana 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
6256b8aa330dSFilipe Manana 	if (ret < 0)
6257b8aa330dSFilipe Manana 		goto out;
6258b8aa330dSFilipe Manana 	if (ret == 0)
6259b8aa330dSFilipe Manana 		path->slots[0]++;
6260b8aa330dSFilipe Manana 
6261b8aa330dSFilipe Manana 	while (true) {
6262b8aa330dSFilipe Manana 		struct extent_buffer *leaf = path->nodes[0];
6263b8aa330dSFilipe Manana 		int slot = path->slots[0];
6264b8aa330dSFilipe Manana 		struct btrfs_key found_key;
6265b8aa330dSFilipe Manana 
6266b8aa330dSFilipe Manana 		if (slot >= btrfs_header_nritems(leaf)) {
6267b8aa330dSFilipe Manana 			ret = btrfs_next_leaf(root, path);
6268b8aa330dSFilipe Manana 			if (ret < 0)
6269b8aa330dSFilipe Manana 				goto out;
6270b8aa330dSFilipe Manana 			else if (ret > 0)
6271b8aa330dSFilipe Manana 				break;
6272b8aa330dSFilipe Manana 			continue;
6273b8aa330dSFilipe Manana 		}
6274b8aa330dSFilipe Manana 
6275b8aa330dSFilipe Manana 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
6276b8aa330dSFilipe Manana 		if (found_key.objectid != ino ||
6277b8aa330dSFilipe Manana 		    found_key.type > BTRFS_INODE_EXTREF_KEY)
6278b8aa330dSFilipe Manana 			break;
6279b8aa330dSFilipe Manana 
6280b8aa330dSFilipe Manana 		/*
6281b8aa330dSFilipe Manana 		 * Don't deal with extended references because they are rare
6282b8aa330dSFilipe Manana 		 * cases and too complex to deal with (we would need to keep
6283b8aa330dSFilipe Manana 		 * track of which subitem we are processing for each item in
6284b8aa330dSFilipe Manana 		 * this loop, etc). So just return some error to fallback to
6285b8aa330dSFilipe Manana 		 * a transaction commit.
6286b8aa330dSFilipe Manana 		 */
6287b8aa330dSFilipe Manana 		if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
6288b8aa330dSFilipe Manana 			ret = -EMLINK;
6289b8aa330dSFilipe Manana 			goto out;
6290b8aa330dSFilipe Manana 		}
6291b8aa330dSFilipe Manana 
6292b8aa330dSFilipe Manana 		/*
6293b8aa330dSFilipe Manana 		 * Logging ancestors needs to do more searches on the fs/subvol
6294b8aa330dSFilipe Manana 		 * tree, so it releases the path as needed to avoid deadlocks.
6295b8aa330dSFilipe Manana 		 * Keep track of the last inode ref key and resume from that key
6296b8aa330dSFilipe Manana 		 * after logging all new ancestors for the current hard link.
6297b8aa330dSFilipe Manana 		 */
6298b8aa330dSFilipe Manana 		memcpy(&search_key, &found_key, sizeof(search_key));
6299b8aa330dSFilipe Manana 
6300b8aa330dSFilipe Manana 		ret = log_new_ancestors(trans, root, path, ctx);
6301b8aa330dSFilipe Manana 		if (ret)
6302b8aa330dSFilipe Manana 			goto out;
6303b8aa330dSFilipe Manana 		btrfs_release_path(path);
6304b8aa330dSFilipe Manana 		goto again;
6305b8aa330dSFilipe Manana 	}
6306b8aa330dSFilipe Manana 	ret = 0;
6307b8aa330dSFilipe Manana out:
6308b8aa330dSFilipe Manana 	btrfs_free_path(path);
6309b8aa330dSFilipe Manana 	return ret;
6310b8aa330dSFilipe Manana }
6311b8aa330dSFilipe Manana 
6312e02119d5SChris Mason /*
6313e02119d5SChris Mason  * helper function around btrfs_log_inode to make sure newly created
6314e02119d5SChris Mason  * parent directories also end up in the log.  A minimal inode and backref
6315e02119d5SChris Mason  * only logging is done of any parent directories that are older than
6316e02119d5SChris Mason  * the last committed transaction
6317e02119d5SChris Mason  */
631848a3b636SEric Sandeen static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
631919df27a9SNikolay Borisov 				  struct btrfs_inode *inode,
632049dae1bcSFilipe Manana 				  struct dentry *parent,
632141a1eadaSEdmund Nadolski 				  int inode_only,
63228b050d35SMiao Xie 				  struct btrfs_log_ctx *ctx)
6323e02119d5SChris Mason {
6324f882274bSNikolay Borisov 	struct btrfs_root *root = inode->root;
63250b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
632612fcfd22SChris Mason 	int ret = 0;
63272f2ff0eeSFilipe Manana 	bool log_dentries = false;
632812fcfd22SChris Mason 
63290b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, NOTREELOG)) {
63303a5e1404SSage Weil 		ret = 1;
63313a5e1404SSage Weil 		goto end_no_trans;
63323a5e1404SSage Weil 	}
63333a5e1404SSage Weil 
6334f882274bSNikolay Borisov 	if (btrfs_root_refs(&root->root_item) == 0) {
633576dda93cSYan, Zheng 		ret = 1;
633676dda93cSYan, Zheng 		goto end_no_trans;
633776dda93cSYan, Zheng 	}
633876dda93cSYan, Zheng 
6339f2d72f42SFilipe Manana 	/*
6340f2d72f42SFilipe Manana 	 * Skip already logged inodes or inodes corresponding to tmpfiles
6341f2d72f42SFilipe Manana 	 * (since logging them is pointless, a link count of 0 means they
6342f2d72f42SFilipe Manana 	 * will never be accessible).
6343f2d72f42SFilipe Manana 	 */
6344626e9f41SFilipe Manana 	if ((btrfs_inode_in_log(inode, trans->transid) &&
6345626e9f41SFilipe Manana 	     list_empty(&ctx->ordered_extents)) ||
6346f2d72f42SFilipe Manana 	    inode->vfs_inode.i_nlink == 0) {
6347257c62e1SChris Mason 		ret = BTRFS_NO_LOG_SYNC;
6348257c62e1SChris Mason 		goto end_no_trans;
6349257c62e1SChris Mason 	}
6350257c62e1SChris Mason 
63518b050d35SMiao Xie 	ret = start_log_trans(trans, root, ctx);
63524a500fd1SYan, Zheng 	if (ret)
6353e87ac136SMiao Xie 		goto end_no_trans;
635412fcfd22SChris Mason 
635590d04510SFilipe Manana 	ret = btrfs_log_inode(trans, inode, inode_only, ctx);
63564a500fd1SYan, Zheng 	if (ret)
63574a500fd1SYan, Zheng 		goto end_trans;
6358e02119d5SChris Mason 
6359af4176b4SChris Mason 	/*
6360af4176b4SChris Mason 	 * for regular files, if its inode is already on disk, we don't
6361af4176b4SChris Mason 	 * have to worry about the parents at all.  This is because
6362af4176b4SChris Mason 	 * we can use the last_unlink_trans field to record renames
6363af4176b4SChris Mason 	 * and other fun in this file.
6364af4176b4SChris Mason 	 */
636519df27a9SNikolay Borisov 	if (S_ISREG(inode->vfs_inode.i_mode) &&
636647d3db41SFilipe Manana 	    inode->generation < trans->transid &&
636747d3db41SFilipe Manana 	    inode->last_unlink_trans < trans->transid) {
63684a500fd1SYan, Zheng 		ret = 0;
63694a500fd1SYan, Zheng 		goto end_trans;
63704a500fd1SYan, Zheng 	}
6371af4176b4SChris Mason 
6372289cffcbSFilipe Manana 	if (S_ISDIR(inode->vfs_inode.i_mode) && ctx->log_new_dentries)
63732f2ff0eeSFilipe Manana 		log_dentries = true;
63742f2ff0eeSFilipe Manana 
637518aa0922SFilipe Manana 	/*
637601327610SNicholas D Steeves 	 * On unlink we must make sure all our current and old parent directory
637718aa0922SFilipe Manana 	 * inodes are fully logged. This is to prevent leaving dangling
637818aa0922SFilipe Manana 	 * directory index entries in directories that were our parents but are
637918aa0922SFilipe Manana 	 * not anymore. Not doing this results in old parent directory being
638018aa0922SFilipe Manana 	 * impossible to delete after log replay (rmdir will always fail with
638118aa0922SFilipe Manana 	 * error -ENOTEMPTY).
638218aa0922SFilipe Manana 	 *
638318aa0922SFilipe Manana 	 * Example 1:
638418aa0922SFilipe Manana 	 *
638518aa0922SFilipe Manana 	 * mkdir testdir
638618aa0922SFilipe Manana 	 * touch testdir/foo
638718aa0922SFilipe Manana 	 * ln testdir/foo testdir/bar
638818aa0922SFilipe Manana 	 * sync
638918aa0922SFilipe Manana 	 * unlink testdir/bar
639018aa0922SFilipe Manana 	 * xfs_io -c fsync testdir/foo
639118aa0922SFilipe Manana 	 * <power failure>
639218aa0922SFilipe Manana 	 * mount fs, triggers log replay
639318aa0922SFilipe Manana 	 *
639418aa0922SFilipe Manana 	 * If we don't log the parent directory (testdir), after log replay the
639518aa0922SFilipe Manana 	 * directory still has an entry pointing to the file inode using the bar
639618aa0922SFilipe Manana 	 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
639718aa0922SFilipe Manana 	 * the file inode has a link count of 1.
639818aa0922SFilipe Manana 	 *
639918aa0922SFilipe Manana 	 * Example 2:
640018aa0922SFilipe Manana 	 *
640118aa0922SFilipe Manana 	 * mkdir testdir
640218aa0922SFilipe Manana 	 * touch foo
640318aa0922SFilipe Manana 	 * ln foo testdir/foo2
640418aa0922SFilipe Manana 	 * ln foo testdir/foo3
640518aa0922SFilipe Manana 	 * sync
640618aa0922SFilipe Manana 	 * unlink testdir/foo3
640718aa0922SFilipe Manana 	 * xfs_io -c fsync foo
640818aa0922SFilipe Manana 	 * <power failure>
640918aa0922SFilipe Manana 	 * mount fs, triggers log replay
641018aa0922SFilipe Manana 	 *
641118aa0922SFilipe Manana 	 * Similar as the first example, after log replay the parent directory
641218aa0922SFilipe Manana 	 * testdir still has an entry pointing to the inode file with name foo3
641318aa0922SFilipe Manana 	 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
641418aa0922SFilipe Manana 	 * and has a link count of 2.
641518aa0922SFilipe Manana 	 */
641647d3db41SFilipe Manana 	if (inode->last_unlink_trans >= trans->transid) {
6417b8aa330dSFilipe Manana 		ret = btrfs_log_all_parents(trans, inode, ctx);
641818aa0922SFilipe Manana 		if (ret)
641918aa0922SFilipe Manana 			goto end_trans;
642018aa0922SFilipe Manana 	}
642118aa0922SFilipe Manana 
6422b8aa330dSFilipe Manana 	ret = log_all_new_ancestors(trans, inode, parent, ctx);
64234a500fd1SYan, Zheng 	if (ret)
64244a500fd1SYan, Zheng 		goto end_trans;
642512fcfd22SChris Mason 
64262f2ff0eeSFilipe Manana 	if (log_dentries)
6427b8aa330dSFilipe Manana 		ret = log_new_dir_dentries(trans, root, inode, ctx);
64282f2ff0eeSFilipe Manana 	else
642912fcfd22SChris Mason 		ret = 0;
64304a500fd1SYan, Zheng end_trans:
64314a500fd1SYan, Zheng 	if (ret < 0) {
643290787766SDavid Sterba 		btrfs_set_log_full_commit(trans);
64334a500fd1SYan, Zheng 		ret = 1;
64344a500fd1SYan, Zheng 	}
64358b050d35SMiao Xie 
64368b050d35SMiao Xie 	if (ret)
64378b050d35SMiao Xie 		btrfs_remove_log_ctx(root, ctx);
643812fcfd22SChris Mason 	btrfs_end_log_trans(root);
643912fcfd22SChris Mason end_no_trans:
644012fcfd22SChris Mason 	return ret;
6441e02119d5SChris Mason }
6442e02119d5SChris Mason 
6443e02119d5SChris Mason /*
6444e02119d5SChris Mason  * it is not safe to log dentry if the chunk root has added new
6445e02119d5SChris Mason  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
6446e02119d5SChris Mason  * If this returns 1, you must commit the transaction to safely get your
6447e02119d5SChris Mason  * data on disk.
6448e02119d5SChris Mason  */
6449e02119d5SChris Mason int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
6450e5b84f7aSNikolay Borisov 			  struct dentry *dentry,
64518b050d35SMiao Xie 			  struct btrfs_log_ctx *ctx)
6452e02119d5SChris Mason {
64536a912213SJosef Bacik 	struct dentry *parent = dget_parent(dentry);
64546a912213SJosef Bacik 	int ret;
64556a912213SJosef Bacik 
6456f882274bSNikolay Borisov 	ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
645748778179SFilipe Manana 				     LOG_INODE_ALL, ctx);
64586a912213SJosef Bacik 	dput(parent);
64596a912213SJosef Bacik 
64606a912213SJosef Bacik 	return ret;
6461e02119d5SChris Mason }
6462e02119d5SChris Mason 
6463e02119d5SChris Mason /*
6464e02119d5SChris Mason  * should be called during mount to recover any replay any log trees
6465e02119d5SChris Mason  * from the FS
6466e02119d5SChris Mason  */
6467e02119d5SChris Mason int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
6468e02119d5SChris Mason {
6469e02119d5SChris Mason 	int ret;
6470e02119d5SChris Mason 	struct btrfs_path *path;
6471e02119d5SChris Mason 	struct btrfs_trans_handle *trans;
6472e02119d5SChris Mason 	struct btrfs_key key;
6473e02119d5SChris Mason 	struct btrfs_key found_key;
6474e02119d5SChris Mason 	struct btrfs_root *log;
6475e02119d5SChris Mason 	struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
6476e02119d5SChris Mason 	struct walk_control wc = {
6477e02119d5SChris Mason 		.process_func = process_one_buffer,
6478430a6626SDavid Sterba 		.stage = LOG_WALK_PIN_ONLY,
6479e02119d5SChris Mason 	};
6480e02119d5SChris Mason 
6481e02119d5SChris Mason 	path = btrfs_alloc_path();
6482db5b493aSTsutomu Itoh 	if (!path)
6483db5b493aSTsutomu Itoh 		return -ENOMEM;
6484db5b493aSTsutomu Itoh 
6485afcdd129SJosef Bacik 	set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
6486e02119d5SChris Mason 
64874a500fd1SYan, Zheng 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
648879787eaaSJeff Mahoney 	if (IS_ERR(trans)) {
648979787eaaSJeff Mahoney 		ret = PTR_ERR(trans);
649079787eaaSJeff Mahoney 		goto error;
649179787eaaSJeff Mahoney 	}
6492e02119d5SChris Mason 
6493e02119d5SChris Mason 	wc.trans = trans;
6494e02119d5SChris Mason 	wc.pin = 1;
6495e02119d5SChris Mason 
6496db5b493aSTsutomu Itoh 	ret = walk_log_tree(trans, log_root_tree, &wc);
649779787eaaSJeff Mahoney 	if (ret) {
6498ba51e2a1SJosef Bacik 		btrfs_abort_transaction(trans, ret);
649979787eaaSJeff Mahoney 		goto error;
650079787eaaSJeff Mahoney 	}
6501e02119d5SChris Mason 
6502e02119d5SChris Mason again:
6503e02119d5SChris Mason 	key.objectid = BTRFS_TREE_LOG_OBJECTID;
6504e02119d5SChris Mason 	key.offset = (u64)-1;
6505962a298fSDavid Sterba 	key.type = BTRFS_ROOT_ITEM_KEY;
6506e02119d5SChris Mason 
6507e02119d5SChris Mason 	while (1) {
6508e02119d5SChris Mason 		ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
650979787eaaSJeff Mahoney 
651079787eaaSJeff Mahoney 		if (ret < 0) {
6511ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
651279787eaaSJeff Mahoney 			goto error;
651379787eaaSJeff Mahoney 		}
6514e02119d5SChris Mason 		if (ret > 0) {
6515e02119d5SChris Mason 			if (path->slots[0] == 0)
6516e02119d5SChris Mason 				break;
6517e02119d5SChris Mason 			path->slots[0]--;
6518e02119d5SChris Mason 		}
6519e02119d5SChris Mason 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
6520e02119d5SChris Mason 				      path->slots[0]);
6521b3b4aa74SDavid Sterba 		btrfs_release_path(path);
6522e02119d5SChris Mason 		if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
6523e02119d5SChris Mason 			break;
6524e02119d5SChris Mason 
652562a2c73eSJosef Bacik 		log = btrfs_read_tree_root(log_root_tree, &found_key);
652679787eaaSJeff Mahoney 		if (IS_ERR(log)) {
652779787eaaSJeff Mahoney 			ret = PTR_ERR(log);
6528ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
652979787eaaSJeff Mahoney 			goto error;
653079787eaaSJeff Mahoney 		}
6531e02119d5SChris Mason 
653256e9357aSDavid Sterba 		wc.replay_dest = btrfs_get_fs_root(fs_info, found_key.offset,
653356e9357aSDavid Sterba 						   true);
653479787eaaSJeff Mahoney 		if (IS_ERR(wc.replay_dest)) {
653579787eaaSJeff Mahoney 			ret = PTR_ERR(wc.replay_dest);
65369bc574deSJosef Bacik 
65379bc574deSJosef Bacik 			/*
65389bc574deSJosef Bacik 			 * We didn't find the subvol, likely because it was
65399bc574deSJosef Bacik 			 * deleted.  This is ok, simply skip this log and go to
65409bc574deSJosef Bacik 			 * the next one.
65419bc574deSJosef Bacik 			 *
65429bc574deSJosef Bacik 			 * We need to exclude the root because we can't have
65439bc574deSJosef Bacik 			 * other log replays overwriting this log as we'll read
65449bc574deSJosef Bacik 			 * it back in a few more times.  This will keep our
65459bc574deSJosef Bacik 			 * block from being modified, and we'll just bail for
65469bc574deSJosef Bacik 			 * each subsequent pass.
65479bc574deSJosef Bacik 			 */
65489bc574deSJosef Bacik 			if (ret == -ENOENT)
65499fce5704SNikolay Borisov 				ret = btrfs_pin_extent_for_log_replay(trans,
65509bc574deSJosef Bacik 							log->node->start,
65519bc574deSJosef Bacik 							log->node->len);
655200246528SJosef Bacik 			btrfs_put_root(log);
65539bc574deSJosef Bacik 
65549bc574deSJosef Bacik 			if (!ret)
65559bc574deSJosef Bacik 				goto next;
6556ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
655779787eaaSJeff Mahoney 			goto error;
655879787eaaSJeff Mahoney 		}
6559e02119d5SChris Mason 
656007d400a6SYan Zheng 		wc.replay_dest->log_root = log;
65612002ae11SJosef Bacik 		ret = btrfs_record_root_in_trans(trans, wc.replay_dest);
65622002ae11SJosef Bacik 		if (ret)
65632002ae11SJosef Bacik 			/* The loop needs to continue due to the root refs */
6564ba51e2a1SJosef Bacik 			btrfs_abort_transaction(trans, ret);
65652002ae11SJosef Bacik 		else
6566e02119d5SChris Mason 			ret = walk_log_tree(trans, log, &wc);
6567e02119d5SChris Mason 
6568b50c6e25SJosef Bacik 		if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
6569e02119d5SChris Mason 			ret = fixup_inode_link_counts(trans, wc.replay_dest,
6570e02119d5SChris Mason 						      path);
6571ba51e2a1SJosef Bacik 			if (ret)
6572ba51e2a1SJosef Bacik 				btrfs_abort_transaction(trans, ret);
6573e02119d5SChris Mason 		}
6574e02119d5SChris Mason 
6575900c9981SLiu Bo 		if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
6576900c9981SLiu Bo 			struct btrfs_root *root = wc.replay_dest;
6577900c9981SLiu Bo 
6578900c9981SLiu Bo 			btrfs_release_path(path);
6579900c9981SLiu Bo 
6580900c9981SLiu Bo 			/*
6581900c9981SLiu Bo 			 * We have just replayed everything, and the highest
6582900c9981SLiu Bo 			 * objectid of fs roots probably has changed in case
6583900c9981SLiu Bo 			 * some inode_item's got replayed.
6584900c9981SLiu Bo 			 *
6585900c9981SLiu Bo 			 * root->objectid_mutex is not acquired as log replay
6586900c9981SLiu Bo 			 * could only happen during mount.
6587900c9981SLiu Bo 			 */
6588453e4873SNikolay Borisov 			ret = btrfs_init_root_free_objectid(root);
6589ba51e2a1SJosef Bacik 			if (ret)
6590ba51e2a1SJosef Bacik 				btrfs_abort_transaction(trans, ret);
6591900c9981SLiu Bo 		}
6592900c9981SLiu Bo 
659307d400a6SYan Zheng 		wc.replay_dest->log_root = NULL;
659400246528SJosef Bacik 		btrfs_put_root(wc.replay_dest);
659500246528SJosef Bacik 		btrfs_put_root(log);
6596e02119d5SChris Mason 
6597b50c6e25SJosef Bacik 		if (ret)
6598b50c6e25SJosef Bacik 			goto error;
65999bc574deSJosef Bacik next:
6600e02119d5SChris Mason 		if (found_key.offset == 0)
6601e02119d5SChris Mason 			break;
66029bc574deSJosef Bacik 		key.offset = found_key.offset - 1;
6603e02119d5SChris Mason 	}
6604b3b4aa74SDavid Sterba 	btrfs_release_path(path);
6605e02119d5SChris Mason 
6606e02119d5SChris Mason 	/* step one is to pin it all, step two is to replay just inodes */
6607e02119d5SChris Mason 	if (wc.pin) {
6608e02119d5SChris Mason 		wc.pin = 0;
6609e02119d5SChris Mason 		wc.process_func = replay_one_buffer;
6610e02119d5SChris Mason 		wc.stage = LOG_WALK_REPLAY_INODES;
6611e02119d5SChris Mason 		goto again;
6612e02119d5SChris Mason 	}
6613e02119d5SChris Mason 	/* step three is to replay everything */
6614e02119d5SChris Mason 	if (wc.stage < LOG_WALK_REPLAY_ALL) {
6615e02119d5SChris Mason 		wc.stage++;
6616e02119d5SChris Mason 		goto again;
6617e02119d5SChris Mason 	}
6618e02119d5SChris Mason 
6619e02119d5SChris Mason 	btrfs_free_path(path);
6620e02119d5SChris Mason 
6621abefa55aSJosef Bacik 	/* step 4: commit the transaction, which also unpins the blocks */
66223a45bb20SJeff Mahoney 	ret = btrfs_commit_transaction(trans);
6623abefa55aSJosef Bacik 	if (ret)
6624abefa55aSJosef Bacik 		return ret;
6625abefa55aSJosef Bacik 
6626e02119d5SChris Mason 	log_root_tree->log_root = NULL;
6627afcdd129SJosef Bacik 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
662800246528SJosef Bacik 	btrfs_put_root(log_root_tree);
662979787eaaSJeff Mahoney 
6630abefa55aSJosef Bacik 	return 0;
663179787eaaSJeff Mahoney error:
6632b50c6e25SJosef Bacik 	if (wc.trans)
66333a45bb20SJeff Mahoney 		btrfs_end_transaction(wc.trans);
66341aeb6b56SDavid Sterba 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
663579787eaaSJeff Mahoney 	btrfs_free_path(path);
663679787eaaSJeff Mahoney 	return ret;
6637e02119d5SChris Mason }
663812fcfd22SChris Mason 
663912fcfd22SChris Mason /*
664012fcfd22SChris Mason  * there are some corner cases where we want to force a full
664112fcfd22SChris Mason  * commit instead of allowing a directory to be logged.
664212fcfd22SChris Mason  *
664312fcfd22SChris Mason  * They revolve around files there were unlinked from the directory, and
664412fcfd22SChris Mason  * this function updates the parent directory so that a full commit is
664512fcfd22SChris Mason  * properly done if it is fsync'd later after the unlinks are done.
66462be63d5cSFilipe Manana  *
66472be63d5cSFilipe Manana  * Must be called before the unlink operations (updates to the subvolume tree,
66482be63d5cSFilipe Manana  * inodes, etc) are done.
664912fcfd22SChris Mason  */
665012fcfd22SChris Mason void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
66514176bdbfSNikolay Borisov 			     struct btrfs_inode *dir, struct btrfs_inode *inode,
665212fcfd22SChris Mason 			     int for_rename)
665312fcfd22SChris Mason {
665412fcfd22SChris Mason 	/*
6655af4176b4SChris Mason 	 * when we're logging a file, if it hasn't been renamed
6656af4176b4SChris Mason 	 * or unlinked, and its inode is fully committed on disk,
6657af4176b4SChris Mason 	 * we don't have to worry about walking up the directory chain
6658af4176b4SChris Mason 	 * to log its parents.
6659af4176b4SChris Mason 	 *
6660af4176b4SChris Mason 	 * So, we use the last_unlink_trans field to put this transid
6661af4176b4SChris Mason 	 * into the file.  When the file is logged we check it and
6662af4176b4SChris Mason 	 * don't log the parents if the file is fully on disk.
6663af4176b4SChris Mason 	 */
66644176bdbfSNikolay Borisov 	mutex_lock(&inode->log_mutex);
66654176bdbfSNikolay Borisov 	inode->last_unlink_trans = trans->transid;
66664176bdbfSNikolay Borisov 	mutex_unlock(&inode->log_mutex);
6667af4176b4SChris Mason 
6668af4176b4SChris Mason 	/*
666912fcfd22SChris Mason 	 * if this directory was already logged any new
667012fcfd22SChris Mason 	 * names for this file/dir will get recorded
667112fcfd22SChris Mason 	 */
66724176bdbfSNikolay Borisov 	if (dir->logged_trans == trans->transid)
667312fcfd22SChris Mason 		return;
667412fcfd22SChris Mason 
667512fcfd22SChris Mason 	/*
667612fcfd22SChris Mason 	 * if the inode we're about to unlink was logged,
667712fcfd22SChris Mason 	 * the log will be properly updated for any new names
667812fcfd22SChris Mason 	 */
66794176bdbfSNikolay Borisov 	if (inode->logged_trans == trans->transid)
668012fcfd22SChris Mason 		return;
668112fcfd22SChris Mason 
668212fcfd22SChris Mason 	/*
668312fcfd22SChris Mason 	 * when renaming files across directories, if the directory
668412fcfd22SChris Mason 	 * there we're unlinking from gets fsync'd later on, there's
668512fcfd22SChris Mason 	 * no way to find the destination directory later and fsync it
668612fcfd22SChris Mason 	 * properly.  So, we have to be conservative and force commits
668712fcfd22SChris Mason 	 * so the new name gets discovered.
668812fcfd22SChris Mason 	 */
668912fcfd22SChris Mason 	if (for_rename)
669012fcfd22SChris Mason 		goto record;
669112fcfd22SChris Mason 
669212fcfd22SChris Mason 	/* we can safely do the unlink without any special recording */
669312fcfd22SChris Mason 	return;
669412fcfd22SChris Mason 
669512fcfd22SChris Mason record:
66964176bdbfSNikolay Borisov 	mutex_lock(&dir->log_mutex);
66974176bdbfSNikolay Borisov 	dir->last_unlink_trans = trans->transid;
66984176bdbfSNikolay Borisov 	mutex_unlock(&dir->log_mutex);
669912fcfd22SChris Mason }
670012fcfd22SChris Mason 
670112fcfd22SChris Mason /*
67021ec9a1aeSFilipe Manana  * Make sure that if someone attempts to fsync the parent directory of a deleted
67031ec9a1aeSFilipe Manana  * snapshot, it ends up triggering a transaction commit. This is to guarantee
67041ec9a1aeSFilipe Manana  * that after replaying the log tree of the parent directory's root we will not
67051ec9a1aeSFilipe Manana  * see the snapshot anymore and at log replay time we will not see any log tree
67061ec9a1aeSFilipe Manana  * corresponding to the deleted snapshot's root, which could lead to replaying
67071ec9a1aeSFilipe Manana  * it after replaying the log tree of the parent directory (which would replay
67081ec9a1aeSFilipe Manana  * the snapshot delete operation).
67092be63d5cSFilipe Manana  *
67102be63d5cSFilipe Manana  * Must be called before the actual snapshot destroy operation (updates to the
67112be63d5cSFilipe Manana  * parent root and tree of tree roots trees, etc) are done.
67121ec9a1aeSFilipe Manana  */
67131ec9a1aeSFilipe Manana void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
671443663557SNikolay Borisov 				   struct btrfs_inode *dir)
67151ec9a1aeSFilipe Manana {
671643663557SNikolay Borisov 	mutex_lock(&dir->log_mutex);
671743663557SNikolay Borisov 	dir->last_unlink_trans = trans->transid;
671843663557SNikolay Borisov 	mutex_unlock(&dir->log_mutex);
67191ec9a1aeSFilipe Manana }
67201ec9a1aeSFilipe Manana 
67211ec9a1aeSFilipe Manana /*
672212fcfd22SChris Mason  * Call this after adding a new name for a file and it will properly
672312fcfd22SChris Mason  * update the log to reflect the new name.
672412fcfd22SChris Mason  */
672575b463d2SFilipe Manana void btrfs_log_new_name(struct btrfs_trans_handle *trans,
67269ca5fbfbSNikolay Borisov 			struct btrfs_inode *inode, struct btrfs_inode *old_dir,
672775b463d2SFilipe Manana 			struct dentry *parent)
672812fcfd22SChris Mason {
672975b463d2SFilipe Manana 	struct btrfs_log_ctx ctx;
673012fcfd22SChris Mason 
673112fcfd22SChris Mason 	/*
6732af4176b4SChris Mason 	 * this will force the logging code to walk the dentry chain
6733af4176b4SChris Mason 	 * up for the file
6734af4176b4SChris Mason 	 */
67359a6509c4SFilipe Manana 	if (!S_ISDIR(inode->vfs_inode.i_mode))
67369ca5fbfbSNikolay Borisov 		inode->last_unlink_trans = trans->transid;
6737af4176b4SChris Mason 
6738af4176b4SChris Mason 	/*
673912fcfd22SChris Mason 	 * if this inode hasn't been logged and directory we're renaming it
674012fcfd22SChris Mason 	 * from hasn't been logged, we don't need to log it
674112fcfd22SChris Mason 	 */
6742ecc64fabSFilipe Manana 	if (!inode_logged(trans, inode) &&
6743ecc64fabSFilipe Manana 	    (!old_dir || !inode_logged(trans, old_dir)))
674475b463d2SFilipe Manana 		return;
674512fcfd22SChris Mason 
674654a40fc3SFilipe Manana 	/*
674754a40fc3SFilipe Manana 	 * If we are doing a rename (old_dir is not NULL) from a directory that
674854a40fc3SFilipe Manana 	 * was previously logged, make sure the next log attempt on the directory
674954a40fc3SFilipe Manana 	 * is not skipped and logs the inode again. This is because the log may
675054a40fc3SFilipe Manana 	 * not currently be authoritative for a range including the old
6751339d0354SFilipe Manana 	 * BTRFS_DIR_INDEX_KEY key, so we want to make sure after a log replay we
6752339d0354SFilipe Manana 	 * do not end up with both the new and old dentries around (in case the
6753339d0354SFilipe Manana 	 * inode is a directory we would have a directory with two hard links and
6754339d0354SFilipe Manana 	 * 2 inode references for different parents). The next log attempt of
6755339d0354SFilipe Manana 	 * old_dir will happen at btrfs_log_all_parents(), called through
6756339d0354SFilipe Manana 	 * btrfs_log_inode_parent() below, because we have previously set
6757339d0354SFilipe Manana 	 * inode->last_unlink_trans to the current transaction ID, either here or
6758339d0354SFilipe Manana 	 * at btrfs_record_unlink_dir() in case the inode is a directory.
675954a40fc3SFilipe Manana 	 */
676054a40fc3SFilipe Manana 	if (old_dir)
676154a40fc3SFilipe Manana 		old_dir->logged_trans = 0;
676254a40fc3SFilipe Manana 
676375b463d2SFilipe Manana 	btrfs_init_log_ctx(&ctx, &inode->vfs_inode);
676475b463d2SFilipe Manana 	ctx.logging_new_name = true;
676575b463d2SFilipe Manana 	/*
676675b463d2SFilipe Manana 	 * We don't care about the return value. If we fail to log the new name
676775b463d2SFilipe Manana 	 * then we know the next attempt to sync the log will fallback to a full
676875b463d2SFilipe Manana 	 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
676975b463d2SFilipe Manana 	 * we don't need to worry about getting a log committed that has an
677075b463d2SFilipe Manana 	 * inconsistent state after a rename operation.
677175b463d2SFilipe Manana 	 */
677248778179SFilipe Manana 	btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
677312fcfd22SChris Mason }
677412fcfd22SChris Mason 
6775