xref: /linux/fs/btrfs/tree-log.c (revision 375336c17efa3d1ac62c4ecfde7c107ef3712f72)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2008 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/blkdev.h>
9 #include <linux/list_sort.h>
10 #include <linux/iversion.h>
11 #include "misc.h"
12 #include "ctree.h"
13 #include "tree-log.h"
14 #include "disk-io.h"
15 #include "locking.h"
16 #include "backref.h"
17 #include "compression.h"
18 #include "qgroup.h"
19 #include "block-group.h"
20 #include "space-info.h"
21 #include "inode-item.h"
22 #include "fs.h"
23 #include "accessors.h"
24 #include "extent-tree.h"
25 #include "root-tree.h"
26 #include "dir-item.h"
27 #include "file-item.h"
28 #include "file.h"
29 #include "orphan.h"
30 #include "print-tree.h"
31 #include "tree-checker.h"
32 #include "delayed-inode.h"
33 
34 #define MAX_CONFLICT_INODES 10
35 
36 /*
37  * directory trouble cases
38  *
39  * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
40  * log, we must force a full commit before doing an fsync of the directory
41  * where the unlink was done.
42  * ---> record transid of last unlink/rename per directory
43  *
44  * mkdir foo/some_dir
45  * normal commit
46  * rename foo/some_dir foo2/some_dir
47  * mkdir foo/some_dir
48  * fsync foo/some_dir/some_file
49  *
50  * The fsync above will unlink the original some_dir without recording
51  * it in its new location (foo2).  After a crash, some_dir will be gone
52  * unless the fsync of some_file forces a full commit
53  *
54  * 2) we must log any new names for any file or dir that is in the fsync
55  * log. ---> check inode while renaming/linking.
56  *
57  * 2a) we must log any new names for any file or dir during rename
58  * when the directory they are being removed from was logged.
59  * ---> check inode and old parent dir during rename
60  *
61  *  2a is actually the more important variant.  With the extra logging
62  *  a crash might unlink the old name without recreating the new one
63  *
64  * 3) after a crash, we must go through any directories with a link count
65  * of zero and redo the rm -rf
66  *
67  * mkdir f1/foo
68  * normal commit
69  * rm -rf f1/foo
70  * fsync(f1)
71  *
72  * The directory f1 was fully removed from the FS, but fsync was never
73  * called on f1, only its parent dir.  After a crash the rm -rf must
74  * be replayed.  This must be able to recurse down the entire
75  * directory tree.  The inode link count fixup code takes care of the
76  * ugly details.
77  */
78 
79 /*
80  * stages for the tree walking.  The first
81  * stage (0) is to only pin down the blocks we find
82  * the second stage (1) is to make sure that all the inodes
83  * we find in the log are created in the subvolume.
84  *
85  * The last stage is to deal with directories and links and extents
86  * and all the other fun semantics
87  */
88 enum {
89 	LOG_WALK_PIN_ONLY,
90 	LOG_WALK_REPLAY_INODES,
91 	LOG_WALK_REPLAY_DIR_INDEX,
92 	LOG_WALK_REPLAY_ALL,
93 };
94 
95 /*
96  * The walk control struct is used to pass state down the chain when processing
97  * the log tree. The stage field tells us which part of the log tree processing
98  * we are currently doing.
99  */
100 struct walk_control {
101 	/*
102 	 * Signal that we are freeing the metadata extents of a log tree.
103 	 * This is used at transaction commit time while freeing a log tree.
104 	 */
105 	bool free;
106 
107 	/*
108 	 * Signal that we are pinning the metadata extents of a log tree and the
109 	 * data extents its leaves point to (if using mixed block groups).
110 	 * This happens in the first stage of log replay to ensure that during
111 	 * replay, while we are modifying subvolume trees, we don't overwrite
112 	 * the metadata extents of log trees.
113 	 */
114 	bool pin;
115 
116 	/* What stage of the replay code we're currently in. */
117 	int stage;
118 
119 	/*
120 	 * Ignore any items from the inode currently being processed. Needs
121 	 * to be set every time we find a BTRFS_INODE_ITEM_KEY.
122 	 */
123 	bool ignore_cur_inode;
124 
125 	/*
126 	 * The root we are currently replaying to. This is NULL for the replay
127 	 * stage LOG_WALK_PIN_ONLY.
128 	 */
129 	struct btrfs_root *root;
130 
131 	/* The log tree we are currently processing (not NULL for any stage). */
132 	struct btrfs_root *log;
133 
134 	/* The transaction handle used for replaying all log trees. */
135 	struct btrfs_trans_handle *trans;
136 
137 	/*
138 	 * The function that gets used to process blocks we find in the tree.
139 	 * Note the extent_buffer might not be up to date when it is passed in,
140 	 * and it must be checked or read if you need the data inside it.
141 	 */
142 	int (*process_func)(struct extent_buffer *eb,
143 			    struct walk_control *wc, u64 gen, int level);
144 
145 	/*
146 	 * The following are used only when stage is >= LOG_WALK_REPLAY_INODES
147 	 * and by the replay_one_buffer() callback.
148 	 */
149 
150 	/* The current log leaf being processed. */
151 	struct extent_buffer *log_leaf;
152 	/* The key being processed of the current log leaf. */
153 	struct btrfs_key log_key;
154 	/* The slot being processed of the current log leaf. */
155 	int log_slot;
156 
157 	/* A path used for searches and modifications to subvolume trees. */
158 	struct btrfs_path *subvol_path;
159 };
160 
161 static void do_abort_log_replay(struct walk_control *wc, const char *function,
162 				unsigned int line, int error, const char *fmt, ...)
163 {
164 	struct btrfs_fs_info *fs_info = wc->trans->fs_info;
165 	struct va_format vaf;
166 	va_list args;
167 
168 	/*
169 	 * Do nothing if we already aborted, to avoid dumping leaves again which
170 	 * can be verbose. Further more, only the first call is useful since it
171 	 * is where we have a problem. Note that we do not use the flag
172 	 * BTRFS_FS_STATE_TRANS_ABORTED because log replay calls functions that
173 	 * are outside of tree-log.c that can abort transactions (such as
174 	 * btrfs_add_link() for example), so if that happens we still want to
175 	 * dump all log replay specific information below.
176 	 */
177 	if (test_and_set_bit(BTRFS_FS_STATE_LOG_REPLAY_ABORTED, &fs_info->fs_state))
178 		return;
179 
180 	btrfs_abort_transaction(wc->trans, error);
181 
182 	if (wc->subvol_path && wc->subvol_path->nodes[0]) {
183 		btrfs_crit(fs_info,
184 			   "subvolume (root %llu) leaf currently being processed:",
185 			   btrfs_root_id(wc->root));
186 		btrfs_print_leaf(wc->subvol_path->nodes[0]);
187 	}
188 
189 	if (wc->log_leaf) {
190 		btrfs_crit(fs_info,
191 "log tree (for root %llu) leaf currently being processed (slot %d key " BTRFS_KEY_FMT "):",
192 			   btrfs_root_id(wc->root), wc->log_slot,
193 			   BTRFS_KEY_FMT_VALUE(&wc->log_key));
194 		btrfs_print_leaf(wc->log_leaf);
195 	}
196 
197 	va_start(args, fmt);
198 	vaf.fmt = fmt;
199 	vaf.va = &args;
200 
201 	btrfs_crit(fs_info,
202 	   "log replay failed in %s:%u for root %llu, stage %d, with error %d: %pV",
203 		   function, line, btrfs_root_id(wc->root), wc->stage, error, &vaf);
204 
205 	va_end(args);
206 }
207 
208 /*
209  * Use this for aborting a transaction during log replay while we are down the
210  * call chain of replay_one_buffer(), so that we get a lot more useful
211  * information for debugging issues when compared to a plain call to
212  * btrfs_abort_transaction().
213  */
214 #define btrfs_abort_log_replay(wc, error, fmt, args...) \
215 	do_abort_log_replay((wc), __func__, __LINE__, (error), fmt, ##args)
216 
217 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
218 			   struct btrfs_inode *inode,
219 			   enum btrfs_log_mode log_mode,
220 			   struct btrfs_log_ctx *ctx);
221 static int link_to_fixup_dir(struct walk_control *wc, u64 objectid);
222 static noinline int replay_dir_deletes(struct walk_control *wc,
223 				       u64 dirid, bool del_all);
224 static void wait_log_commit(struct btrfs_root *root, int transid);
225 
226 /*
227  * tree logging is a special write ahead log used to make sure that
228  * fsyncs and O_SYNCs can happen without doing full tree commits.
229  *
230  * Full tree commits are expensive because they require commonly
231  * modified blocks to be recowed, creating many dirty pages in the
232  * extent tree an 4x-6x higher write load than ext3.
233  *
234  * Instead of doing a tree commit on every fsync, we use the
235  * key ranges and transaction ids to find items for a given file or directory
236  * that have changed in this transaction.  Those items are copied into
237  * a special tree (one per subvolume root), that tree is written to disk
238  * and then the fsync is considered complete.
239  *
240  * After a crash, items are copied out of the log-tree back into the
241  * subvolume tree.  Any file data extents found are recorded in the extent
242  * allocation tree, and the log-tree freed.
243  *
244  * The log tree is read three times, once to pin down all the extents it is
245  * using in ram and once, once to create all the inodes logged in the tree
246  * and once to do all the other items.
247  */
248 
249 static struct btrfs_inode *btrfs_iget_logging(u64 objectid, struct btrfs_root *root)
250 {
251 	unsigned int nofs_flag;
252 	struct btrfs_inode *inode;
253 
254 	/* Only meant to be called for subvolume roots and not for log roots. */
255 	ASSERT(btrfs_is_fstree(btrfs_root_id(root)), "root_id=%llu", btrfs_root_id(root));
256 
257 	/*
258 	 * We're holding a transaction handle whether we are logging or
259 	 * replaying a log tree, so we must make sure NOFS semantics apply
260 	 * because btrfs_alloc_inode() may be triggered and it uses GFP_KERNEL
261 	 * to allocate an inode, which can recurse back into the filesystem and
262 	 * attempt a transaction commit, resulting in a deadlock.
263 	 */
264 	nofs_flag = memalloc_nofs_save();
265 	inode = btrfs_iget(objectid, root);
266 	memalloc_nofs_restore(nofs_flag);
267 
268 	return inode;
269 }
270 
271 /*
272  * start a sub transaction and setup the log tree
273  * this increments the log tree writer count to make the people
274  * syncing the tree wait for us to finish
275  */
276 static int start_log_trans(struct btrfs_trans_handle *trans,
277 			   struct btrfs_root *root,
278 			   struct btrfs_log_ctx *ctx)
279 {
280 	struct btrfs_fs_info *fs_info = root->fs_info;
281 	struct btrfs_root *tree_root = fs_info->tree_root;
282 	const bool zoned = btrfs_is_zoned(fs_info);
283 	int ret = 0;
284 	bool created = false;
285 
286 	/*
287 	 * First check if the log root tree was already created. If not, create
288 	 * it before locking the root's log_mutex, just to keep lockdep happy.
289 	 */
290 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state)) {
291 		mutex_lock(&tree_root->log_mutex);
292 		if (!fs_info->log_root_tree) {
293 			ret = btrfs_init_log_root_tree(trans, fs_info);
294 			if (!ret) {
295 				set_bit(BTRFS_ROOT_HAS_LOG_TREE, &tree_root->state);
296 				created = true;
297 			}
298 		}
299 		mutex_unlock(&tree_root->log_mutex);
300 		if (ret)
301 			return ret;
302 	}
303 
304 	mutex_lock(&root->log_mutex);
305 
306 again:
307 	if (root->log_root) {
308 		int index = (root->log_transid + 1) % 2;
309 
310 		if (btrfs_need_log_full_commit(trans)) {
311 			ret = BTRFS_LOG_FORCE_COMMIT;
312 			goto out;
313 		}
314 
315 		if (zoned && atomic_read(&root->log_commit[index])) {
316 			wait_log_commit(root, root->log_transid - 1);
317 			goto again;
318 		}
319 
320 		if (!root->log_start_pid) {
321 			clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
322 			root->log_start_pid = current->pid;
323 		} else if (root->log_start_pid != current->pid) {
324 			set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
325 		}
326 	} else {
327 		/*
328 		 * This means fs_info->log_root_tree was already created
329 		 * for some other FS trees. Do the full commit not to mix
330 		 * nodes from multiple log transactions to do sequential
331 		 * writing.
332 		 */
333 		if (zoned && !created) {
334 			ret = BTRFS_LOG_FORCE_COMMIT;
335 			goto out;
336 		}
337 
338 		ret = btrfs_add_log_tree(trans, root);
339 		if (ret)
340 			goto out;
341 
342 		set_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
343 		clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
344 		root->log_start_pid = current->pid;
345 	}
346 
347 	atomic_inc(&root->log_writers);
348 	if (!ctx->logging_new_name) {
349 		int index = root->log_transid % 2;
350 		list_add_tail(&ctx->list, &root->log_ctxs[index]);
351 		ctx->log_transid = root->log_transid;
352 	}
353 
354 out:
355 	mutex_unlock(&root->log_mutex);
356 	return ret;
357 }
358 
359 /*
360  * returns 0 if there was a log transaction running and we were able
361  * to join, or returns -ENOENT if there were not transactions
362  * in progress
363  */
364 static int join_running_log_trans(struct btrfs_root *root)
365 {
366 	const bool zoned = btrfs_is_zoned(root->fs_info);
367 	int ret = -ENOENT;
368 
369 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state))
370 		return ret;
371 
372 	mutex_lock(&root->log_mutex);
373 again:
374 	if (root->log_root) {
375 		int index = (root->log_transid + 1) % 2;
376 
377 		ret = 0;
378 		if (zoned && atomic_read(&root->log_commit[index])) {
379 			wait_log_commit(root, root->log_transid - 1);
380 			goto again;
381 		}
382 		atomic_inc(&root->log_writers);
383 	}
384 	mutex_unlock(&root->log_mutex);
385 	return ret;
386 }
387 
388 /*
389  * This either makes the current running log transaction wait
390  * until you call btrfs_end_log_trans() or it makes any future
391  * log transactions wait until you call btrfs_end_log_trans()
392  */
393 void btrfs_pin_log_trans(struct btrfs_root *root)
394 {
395 	atomic_inc(&root->log_writers);
396 }
397 
398 /*
399  * indicate we're done making changes to the log tree
400  * and wake up anyone waiting to do a sync
401  */
402 void btrfs_end_log_trans(struct btrfs_root *root)
403 {
404 	if (atomic_dec_and_test(&root->log_writers)) {
405 		/* atomic_dec_and_test implies a barrier */
406 		cond_wake_up_nomb(&root->log_writer_wait);
407 	}
408 }
409 
410 /*
411  * process_func used to pin down extents, write them or wait on them
412  */
413 static int process_one_buffer(struct extent_buffer *eb,
414 			      struct walk_control *wc, u64 gen, int level)
415 {
416 	struct btrfs_root *log = wc->log;
417 	struct btrfs_trans_handle *trans = wc->trans;
418 	struct btrfs_fs_info *fs_info = log->fs_info;
419 	int ret = 0;
420 
421 	/*
422 	 * If this fs is mixed then we need to be able to process the leaves to
423 	 * pin down any logged extents, so we have to read the block.
424 	 */
425 	if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
426 		struct btrfs_tree_parent_check check = {
427 			.level = level,
428 			.transid = gen
429 		};
430 
431 		ret = btrfs_read_extent_buffer(eb, &check);
432 		if (unlikely(ret)) {
433 			if (trans)
434 				btrfs_abort_transaction(trans, ret);
435 			else
436 				btrfs_handle_fs_error(fs_info, ret, NULL);
437 			return ret;
438 		}
439 	}
440 
441 	if (wc->pin) {
442 		ASSERT(trans != NULL);
443 		ret = btrfs_pin_extent_for_log_replay(trans, eb);
444 		if (unlikely(ret)) {
445 			btrfs_abort_transaction(trans, ret);
446 			return ret;
447 		}
448 
449 		if (btrfs_buffer_uptodate(eb, gen, NULL) && level == 0) {
450 			ret = btrfs_exclude_logged_extents(eb);
451 			if (ret)
452 				btrfs_abort_transaction(trans, ret);
453 		}
454 	}
455 	return ret;
456 }
457 
458 /*
459  * Item overwrite used by log replay. The given log tree leaf, slot and key
460  * from the walk_control structure all refer to the source data we are copying
461  * out.
462  *
463  * The given root is for the tree we are copying into, and path is a scratch
464  * path for use in this function (it should be released on entry and will be
465  * released on exit).
466  *
467  * If the key is already in the destination tree the existing item is
468  * overwritten.  If the existing item isn't big enough, it is extended.
469  * If it is too large, it is truncated.
470  *
471  * If the key isn't in the destination yet, a new item is inserted.
472  */
473 static int overwrite_item(struct walk_control *wc)
474 {
475 	struct btrfs_trans_handle *trans = wc->trans;
476 	struct btrfs_root *root = wc->root;
477 	int ret;
478 	u32 item_size;
479 	u64 saved_i_size = 0;
480 	int save_old_i_size = 0;
481 	unsigned long src_ptr;
482 	unsigned long dst_ptr;
483 	struct extent_buffer *dst_eb;
484 	int dst_slot;
485 	const bool is_inode_item = (wc->log_key.type == BTRFS_INODE_ITEM_KEY);
486 
487 	/*
488 	 * This is only used during log replay, so the root is always from a
489 	 * fs/subvolume tree. In case we ever need to support a log root, then
490 	 * we'll have to clone the leaf in the path, release the path and use
491 	 * the leaf before writing into the log tree. See the comments at
492 	 * copy_items() for more details.
493 	 */
494 	ASSERT(btrfs_root_id(root) != BTRFS_TREE_LOG_OBJECTID);
495 
496 	item_size = btrfs_item_size(wc->log_leaf, wc->log_slot);
497 	src_ptr = btrfs_item_ptr_offset(wc->log_leaf, wc->log_slot);
498 
499 	/* Look for the key in the destination tree. */
500 	ret = btrfs_search_slot(NULL, root, &wc->log_key, wc->subvol_path, 0, 0);
501 	if (ret < 0) {
502 		btrfs_abort_log_replay(wc, ret,
503 		"failed to search subvolume tree for key " BTRFS_KEY_FMT " root %llu",
504 				       BTRFS_KEY_FMT_VALUE(&wc->log_key),
505 				       btrfs_root_id(root));
506 		return ret;
507 	}
508 
509 	dst_eb = wc->subvol_path->nodes[0];
510 	dst_slot = wc->subvol_path->slots[0];
511 
512 	if (ret == 0) {
513 		char *src_copy;
514 		const u32 dst_size = btrfs_item_size(dst_eb, dst_slot);
515 
516 		if (dst_size != item_size)
517 			goto insert;
518 
519 		if (item_size == 0) {
520 			btrfs_release_path(wc->subvol_path);
521 			return 0;
522 		}
523 		src_copy = kmalloc(item_size, GFP_NOFS);
524 		if (!src_copy) {
525 			btrfs_abort_log_replay(wc, -ENOMEM,
526 			       "failed to allocate memory for log leaf item");
527 			return -ENOMEM;
528 		}
529 
530 		read_extent_buffer(wc->log_leaf, src_copy, src_ptr, item_size);
531 		dst_ptr = btrfs_item_ptr_offset(dst_eb, dst_slot);
532 		ret = memcmp_extent_buffer(dst_eb, src_copy, dst_ptr, item_size);
533 
534 		kfree(src_copy);
535 		/*
536 		 * they have the same contents, just return, this saves
537 		 * us from cowing blocks in the destination tree and doing
538 		 * extra writes that may not have been done by a previous
539 		 * sync
540 		 */
541 		if (ret == 0) {
542 			btrfs_release_path(wc->subvol_path);
543 			return 0;
544 		}
545 
546 		/*
547 		 * We need to load the old nbytes into the inode so when we
548 		 * replay the extents we've logged we get the right nbytes.
549 		 */
550 		if (is_inode_item) {
551 			struct btrfs_inode_item *item;
552 			u64 nbytes;
553 			u32 mode;
554 
555 			item = btrfs_item_ptr(dst_eb, dst_slot,
556 					      struct btrfs_inode_item);
557 			nbytes = btrfs_inode_nbytes(dst_eb, item);
558 			item = btrfs_item_ptr(wc->log_leaf, wc->log_slot,
559 					      struct btrfs_inode_item);
560 			btrfs_set_inode_nbytes(wc->log_leaf, item, nbytes);
561 
562 			/*
563 			 * If this is a directory we need to reset the i_size to
564 			 * 0 so that we can set it up properly when replaying
565 			 * the rest of the items in this log.
566 			 */
567 			mode = btrfs_inode_mode(wc->log_leaf, item);
568 			if (S_ISDIR(mode))
569 				btrfs_set_inode_size(wc->log_leaf, item, 0);
570 		}
571 	} else if (is_inode_item) {
572 		struct btrfs_inode_item *item;
573 		u32 mode;
574 
575 		/*
576 		 * New inode, set nbytes to 0 so that the nbytes comes out
577 		 * properly when we replay the extents.
578 		 */
579 		item = btrfs_item_ptr(wc->log_leaf, wc->log_slot, struct btrfs_inode_item);
580 		btrfs_set_inode_nbytes(wc->log_leaf, item, 0);
581 
582 		/*
583 		 * If this is a directory we need to reset the i_size to 0 so
584 		 * that we can set it up properly when replaying the rest of
585 		 * the items in this log.
586 		 */
587 		mode = btrfs_inode_mode(wc->log_leaf, item);
588 		if (S_ISDIR(mode))
589 			btrfs_set_inode_size(wc->log_leaf, item, 0);
590 	}
591 insert:
592 	btrfs_release_path(wc->subvol_path);
593 	/* try to insert the key into the destination tree */
594 	wc->subvol_path->skip_release_on_error = true;
595 	ret = btrfs_insert_empty_item(trans, root, wc->subvol_path, &wc->log_key, item_size);
596 	wc->subvol_path->skip_release_on_error = false;
597 
598 	dst_eb = wc->subvol_path->nodes[0];
599 	dst_slot = wc->subvol_path->slots[0];
600 
601 	/* make sure any existing item is the correct size */
602 	if (ret == -EEXIST || ret == -EOVERFLOW) {
603 		const u32 found_size = btrfs_item_size(dst_eb, dst_slot);
604 
605 		if (found_size > item_size)
606 			btrfs_truncate_item(trans, wc->subvol_path, item_size, 1);
607 		else if (found_size < item_size)
608 			btrfs_extend_item(trans, wc->subvol_path, item_size - found_size);
609 	} else if (ret) {
610 		btrfs_abort_log_replay(wc, ret,
611 				       "failed to insert item for key " BTRFS_KEY_FMT,
612 				       BTRFS_KEY_FMT_VALUE(&wc->log_key));
613 		return ret;
614 	}
615 	dst_ptr = btrfs_item_ptr_offset(dst_eb, dst_slot);
616 
617 	/* don't overwrite an existing inode if the generation number
618 	 * was logged as zero.  This is done when the tree logging code
619 	 * is just logging an inode to make sure it exists after recovery.
620 	 *
621 	 * Also, don't overwrite i_size on directories during replay.
622 	 * log replay inserts and removes directory items based on the
623 	 * state of the tree found in the subvolume, and i_size is modified
624 	 * as it goes
625 	 */
626 	if (is_inode_item && ret == -EEXIST) {
627 		struct btrfs_inode_item *src_item;
628 		struct btrfs_inode_item *dst_item;
629 
630 		src_item = (struct btrfs_inode_item *)src_ptr;
631 		dst_item = (struct btrfs_inode_item *)dst_ptr;
632 
633 		if (btrfs_inode_generation(wc->log_leaf, src_item) == 0) {
634 			const u64 ino_size = btrfs_inode_size(wc->log_leaf, src_item);
635 
636 			/*
637 			 * For regular files an ino_size == 0 is used only when
638 			 * logging that an inode exists, as part of a directory
639 			 * fsync, and the inode wasn't fsynced before. In this
640 			 * case don't set the size of the inode in the fs/subvol
641 			 * tree, otherwise we would be throwing valid data away.
642 			 */
643 			if (S_ISREG(btrfs_inode_mode(wc->log_leaf, src_item)) &&
644 			    S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
645 			    ino_size != 0)
646 				btrfs_set_inode_size(dst_eb, dst_item, ino_size);
647 			goto no_copy;
648 		}
649 
650 		if (S_ISDIR(btrfs_inode_mode(wc->log_leaf, src_item)) &&
651 		    S_ISDIR(btrfs_inode_mode(dst_eb, dst_item))) {
652 			save_old_i_size = 1;
653 			saved_i_size = btrfs_inode_size(dst_eb, dst_item);
654 		}
655 	}
656 
657 	copy_extent_buffer(dst_eb, wc->log_leaf, dst_ptr, src_ptr, item_size);
658 
659 	if (save_old_i_size) {
660 		struct btrfs_inode_item *dst_item;
661 
662 		dst_item = (struct btrfs_inode_item *)dst_ptr;
663 		btrfs_set_inode_size(dst_eb, dst_item, saved_i_size);
664 	}
665 
666 	/* make sure the generation is filled in */
667 	if (is_inode_item) {
668 		struct btrfs_inode_item *dst_item;
669 
670 		dst_item = (struct btrfs_inode_item *)dst_ptr;
671 		if (btrfs_inode_generation(dst_eb, dst_item) == 0)
672 			btrfs_set_inode_generation(dst_eb, dst_item, trans->transid);
673 	}
674 no_copy:
675 	btrfs_release_path(wc->subvol_path);
676 	return 0;
677 }
678 
679 static int read_alloc_one_name(struct extent_buffer *eb, void *start, int len,
680 			       struct fscrypt_str *name)
681 {
682 	char *buf;
683 
684 	buf = kmalloc(len, GFP_NOFS);
685 	if (!buf)
686 		return -ENOMEM;
687 
688 	read_extent_buffer(eb, buf, (unsigned long)start, len);
689 	name->name = buf;
690 	name->len = len;
691 	return 0;
692 }
693 
694 /* replays a single extent in 'eb' at 'slot' with 'key' into the
695  * subvolume 'root'.  path is released on entry and should be released
696  * on exit.
697  *
698  * extents in the log tree have not been allocated out of the extent
699  * tree yet.  So, this completes the allocation, taking a reference
700  * as required if the extent already exists or creating a new extent
701  * if it isn't in the extent allocation tree yet.
702  *
703  * The extent is inserted into the file, dropping any existing extents
704  * from the file that overlap the new one.
705  */
706 static noinline int replay_one_extent(struct walk_control *wc)
707 {
708 	struct btrfs_trans_handle *trans = wc->trans;
709 	struct btrfs_root *root = wc->root;
710 	struct btrfs_drop_extents_args drop_args = { 0 };
711 	struct btrfs_fs_info *fs_info = root->fs_info;
712 	int found_type;
713 	u64 extent_end;
714 	const u64 start = wc->log_key.offset;
715 	u64 nbytes = 0;
716 	u64 csum_start;
717 	u64 csum_end;
718 	LIST_HEAD(ordered_sums);
719 	u64 offset;
720 	unsigned long dest_offset;
721 	struct btrfs_key ins;
722 	struct btrfs_file_extent_item *item;
723 	struct btrfs_inode *inode = NULL;
724 	int ret = 0;
725 
726 	item = btrfs_item_ptr(wc->log_leaf, wc->log_slot, struct btrfs_file_extent_item);
727 	found_type = btrfs_file_extent_type(wc->log_leaf, item);
728 
729 	if (found_type == BTRFS_FILE_EXTENT_REG ||
730 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
731 		extent_end = start + btrfs_file_extent_num_bytes(wc->log_leaf, item);
732 		/* Holes don't take up space. */
733 		if (btrfs_file_extent_disk_bytenr(wc->log_leaf, item) != 0)
734 			nbytes = btrfs_file_extent_num_bytes(wc->log_leaf, item);
735 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
736 		nbytes = btrfs_file_extent_ram_bytes(wc->log_leaf, item);
737 		extent_end = ALIGN(start + nbytes, fs_info->sectorsize);
738 	} else {
739 		btrfs_abort_log_replay(wc, -EUCLEAN,
740 		       "unexpected extent type=%d root=%llu inode=%llu offset=%llu",
741 				       found_type, btrfs_root_id(root),
742 				       wc->log_key.objectid, wc->log_key.offset);
743 		return -EUCLEAN;
744 	}
745 
746 	inode = btrfs_iget_logging(wc->log_key.objectid, root);
747 	if (IS_ERR(inode)) {
748 		ret = PTR_ERR(inode);
749 		btrfs_abort_log_replay(wc, ret,
750 				       "failed to get inode %llu for root %llu",
751 				       wc->log_key.objectid, btrfs_root_id(root));
752 		return ret;
753 	}
754 
755 	/*
756 	 * first check to see if we already have this extent in the
757 	 * file.  This must be done before the btrfs_drop_extents run
758 	 * so we don't try to drop this extent.
759 	 */
760 	ret = btrfs_lookup_file_extent(trans, root, wc->subvol_path,
761 				       btrfs_ino(inode), start, 0);
762 
763 	if (ret == 0 &&
764 	    (found_type == BTRFS_FILE_EXTENT_REG ||
765 	     found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
766 		struct extent_buffer *leaf = wc->subvol_path->nodes[0];
767 		struct btrfs_file_extent_item existing;
768 		unsigned long ptr;
769 
770 		ptr = btrfs_item_ptr_offset(leaf, wc->subvol_path->slots[0]);
771 		read_extent_buffer(leaf, &existing, ptr, sizeof(existing));
772 
773 		/*
774 		 * we already have a pointer to this exact extent,
775 		 * we don't have to do anything
776 		 */
777 		if (memcmp_extent_buffer(wc->log_leaf, &existing, (unsigned long)item,
778 					 sizeof(existing)) == 0) {
779 			btrfs_release_path(wc->subvol_path);
780 			goto out;
781 		}
782 	}
783 	btrfs_release_path(wc->subvol_path);
784 
785 	/* drop any overlapping extents */
786 	drop_args.start = start;
787 	drop_args.end = extent_end;
788 	drop_args.drop_cache = true;
789 	drop_args.path = wc->subvol_path;
790 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
791 	if (ret) {
792 		btrfs_abort_log_replay(wc, ret,
793 	       "failed to drop extents for inode %llu range [%llu, %llu) root %llu",
794 				       wc->log_key.objectid, start, extent_end,
795 				       btrfs_root_id(root));
796 		goto out;
797 	}
798 
799 	if (found_type == BTRFS_FILE_EXTENT_INLINE) {
800 		/* inline extents are easy, we just overwrite them */
801 		ret = overwrite_item(wc);
802 		if (ret)
803 			goto out;
804 		goto update_inode;
805 	}
806 
807 	/*
808 	 * If not an inline extent, it can only be a regular or prealloc one.
809 	 * We have checked that above and returned -EUCLEAN if not.
810 	 */
811 
812 	/* A hole and NO_HOLES feature enabled, nothing else to do. */
813 	if (btrfs_file_extent_disk_bytenr(wc->log_leaf, item) == 0 &&
814 	    btrfs_fs_incompat(fs_info, NO_HOLES))
815 		goto update_inode;
816 
817 	ret = btrfs_insert_empty_item(trans, root, wc->subvol_path,
818 				      &wc->log_key, sizeof(*item));
819 	if (ret) {
820 		btrfs_abort_log_replay(wc, ret,
821 		       "failed to insert item with key " BTRFS_KEY_FMT " root %llu",
822 				       BTRFS_KEY_FMT_VALUE(&wc->log_key),
823 				       btrfs_root_id(root));
824 		goto out;
825 	}
826 	dest_offset = btrfs_item_ptr_offset(wc->subvol_path->nodes[0],
827 					    wc->subvol_path->slots[0]);
828 	copy_extent_buffer(wc->subvol_path->nodes[0], wc->log_leaf, dest_offset,
829 			   (unsigned long)item, sizeof(*item));
830 
831 	/*
832 	 * We have an explicit hole and NO_HOLES is not enabled. We have added
833 	 * the hole file extent item to the subvolume tree, so we don't have
834 	 * anything else to do other than update the file extent item range and
835 	 * update the inode item.
836 	 */
837 	if (btrfs_file_extent_disk_bytenr(wc->log_leaf, item) == 0) {
838 		btrfs_release_path(wc->subvol_path);
839 		goto update_inode;
840 	}
841 
842 	ins.objectid = btrfs_file_extent_disk_bytenr(wc->log_leaf, item);
843 	ins.type = BTRFS_EXTENT_ITEM_KEY;
844 	ins.offset = btrfs_file_extent_disk_num_bytes(wc->log_leaf, item);
845 	offset = wc->log_key.offset - btrfs_file_extent_offset(wc->log_leaf, item);
846 
847 	/*
848 	 * Manually record dirty extent, as here we did a shallow file extent
849 	 * item copy and skip normal backref update, but modifying extent tree
850 	 * all by ourselves. So need to manually record dirty extent for qgroup,
851 	 * as the owner of the file extent changed from log tree (doesn't affect
852 	 * qgroup) to fs/file tree (affects qgroup).
853 	 */
854 	ret = btrfs_qgroup_trace_extent(trans, ins.objectid, ins.offset);
855 	if (ret < 0) {
856 		btrfs_abort_log_replay(wc, ret,
857 "failed to trace extent for bytenr %llu disk_num_bytes %llu inode %llu root %llu",
858 				       ins.objectid, ins.offset,
859 				       wc->log_key.objectid, btrfs_root_id(root));
860 		goto out;
861 	}
862 
863 	/*
864 	 * Is this extent already allocated in the extent tree?
865 	 * If so, just add a reference.
866 	 */
867 	ret = btrfs_lookup_data_extent(fs_info, ins.objectid, ins.offset);
868 	if (ret < 0) {
869 		btrfs_abort_log_replay(wc, ret,
870 "failed to lookup data extent for bytenr %llu disk_num_bytes %llu inode %llu root %llu",
871 				       ins.objectid, ins.offset,
872 				       wc->log_key.objectid, btrfs_root_id(root));
873 		goto out;
874 	} else if (ret == 0) {
875 		struct btrfs_ref ref = {
876 			.action = BTRFS_ADD_DELAYED_REF,
877 			.bytenr = ins.objectid,
878 			.num_bytes = ins.offset,
879 			.owning_root = btrfs_root_id(root),
880 			.ref_root = btrfs_root_id(root),
881 		};
882 
883 		btrfs_init_data_ref(&ref, wc->log_key.objectid, offset, 0, false);
884 		ret = btrfs_inc_extent_ref(trans, &ref);
885 		if (ret) {
886 			btrfs_abort_log_replay(wc, ret,
887 "failed to increment data extent for bytenr %llu disk_num_bytes %llu inode %llu root %llu",
888 					       ins.objectid, ins.offset,
889 					       wc->log_key.objectid,
890 					       btrfs_root_id(root));
891 			goto out;
892 		}
893 	} else {
894 		/* Insert the extent pointer in the extent tree. */
895 		ret = btrfs_alloc_logged_file_extent(trans, btrfs_root_id(root),
896 						     wc->log_key.objectid, offset, &ins);
897 		if (ret) {
898 			btrfs_abort_log_replay(wc, ret,
899 "failed to allocate logged data extent for bytenr %llu disk_num_bytes %llu offset %llu inode %llu root %llu",
900 					       ins.objectid, ins.offset, offset,
901 					       wc->log_key.objectid, btrfs_root_id(root));
902 			goto out;
903 		}
904 	}
905 
906 	btrfs_release_path(wc->subvol_path);
907 
908 	if (btrfs_file_extent_compression(wc->log_leaf, item)) {
909 		csum_start = ins.objectid;
910 		csum_end = csum_start + ins.offset;
911 	} else {
912 		csum_start = ins.objectid + btrfs_file_extent_offset(wc->log_leaf, item);
913 		csum_end = csum_start + btrfs_file_extent_num_bytes(wc->log_leaf, item);
914 	}
915 
916 	ret = btrfs_lookup_csums_list(root->log_root, csum_start, csum_end - 1,
917 				      &ordered_sums, false);
918 	if (ret < 0) {
919 		btrfs_abort_log_replay(wc, ret,
920 	       "failed to lookups csums for range [%llu, %llu) inode %llu root %llu",
921 				       csum_start, csum_end, wc->log_key.objectid,
922 				       btrfs_root_id(root));
923 		goto out;
924 	}
925 	ret = 0;
926 	/*
927 	 * Now delete all existing cums in the csum root that cover our range.
928 	 * We do this because we can have an extent that is completely
929 	 * referenced by one file extent item and partially referenced by
930 	 * another file extent item (like after using the clone or extent_same
931 	 * ioctls). In this case if we end up doing the replay of the one that
932 	 * partially references the extent first, and we do not do the csum
933 	 * deletion below, we can get 2 csum items in the csum tree that overlap
934 	 * each other. For example, imagine our log has the two following file
935 	 * extent items:
936 	 *
937 	 * key (257 EXTENT_DATA 409600)
938 	 *     extent data disk byte 12845056 nr 102400
939 	 *     extent data offset 20480 nr 20480 ram 102400
940 	 *
941 	 * key (257 EXTENT_DATA 819200)
942 	 *     extent data disk byte 12845056 nr 102400
943 	 *     extent data offset 0 nr 102400 ram 102400
944 	 *
945 	 * Where the second one fully references the 100K extent that starts at
946 	 * disk byte 12845056, and the log tree has a single csum item that
947 	 * covers the entire range of the extent:
948 	 *
949 	 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
950 	 *
951 	 * After the first file extent item is replayed, the csum tree gets the
952 	 * following csum item:
953 	 *
954 	 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
955 	 *
956 	 * Which covers the 20K sub-range starting at offset 20K of our extent.
957 	 * Now when we replay the second file extent item, if we do not delete
958 	 * existing csum items that cover any of its blocks, we end up getting
959 	 * two csum items in our csum tree that overlap each other:
960 	 *
961 	 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
962 	 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
963 	 *
964 	 * Which is a problem, because after this anyone trying to lookup for
965 	 * the checksum of any block of our extent starting at an offset of 40K
966 	 * or higher, will end up looking at the second csum item only, which
967 	 * does not contain the checksum for any block starting at offset 40K or
968 	 * higher of our extent.
969 	 */
970 	while (!list_empty(&ordered_sums)) {
971 		struct btrfs_ordered_sum *sums;
972 		struct btrfs_root *csum_root;
973 
974 		sums = list_first_entry(&ordered_sums, struct btrfs_ordered_sum, list);
975 		csum_root = btrfs_csum_root(fs_info, sums->logical);
976 		if (unlikely(!csum_root)) {
977 			btrfs_err(fs_info,
978 				  "missing csum root for extent at bytenr %llu",
979 				  sums->logical);
980 			ret = -EUCLEAN;
981 		}
982 
983 		if (!ret) {
984 			ret = btrfs_del_csums(trans, csum_root, sums->logical,
985 					      sums->len);
986 			if (ret)
987 				btrfs_abort_log_replay(wc, ret,
988 	       "failed to delete csums for range [%llu, %llu) inode %llu root %llu",
989 						       sums->logical,
990 						       sums->logical + sums->len,
991 						       wc->log_key.objectid,
992 						       btrfs_root_id(root));
993 		}
994 		if (!ret) {
995 			ret = btrfs_insert_data_csums(trans, csum_root, sums);
996 			if (ret)
997 				btrfs_abort_log_replay(wc, ret,
998 	       "failed to add csums for range [%llu, %llu) inode %llu root %llu",
999 						       sums->logical,
1000 						       sums->logical + sums->len,
1001 						       wc->log_key.objectid,
1002 						       btrfs_root_id(root));
1003 		}
1004 		list_del(&sums->list);
1005 		kfree(sums);
1006 	}
1007 	if (ret)
1008 		goto out;
1009 
1010 update_inode:
1011 	ret = btrfs_inode_set_file_extent_range(inode, start, extent_end - start);
1012 	if (ret) {
1013 		btrfs_abort_log_replay(wc, ret,
1014 	       "failed to set file extent range [%llu, %llu) inode %llu root %llu",
1015 				       start, extent_end, wc->log_key.objectid,
1016 				       btrfs_root_id(root));
1017 		goto out;
1018 	}
1019 
1020 	btrfs_update_inode_bytes(inode, nbytes, drop_args.bytes_found);
1021 	ret = btrfs_update_inode(trans, inode);
1022 	if (ret)
1023 		btrfs_abort_log_replay(wc, ret,
1024 				       "failed to update inode %llu root %llu",
1025 				       wc->log_key.objectid, btrfs_root_id(root));
1026 out:
1027 	iput(&inode->vfs_inode);
1028 	return ret;
1029 }
1030 
1031 static int unlink_inode_for_log_replay(struct walk_control *wc,
1032 				       struct btrfs_inode *dir,
1033 				       struct btrfs_inode *inode,
1034 				       const struct fscrypt_str *name)
1035 {
1036 	struct btrfs_trans_handle *trans = wc->trans;
1037 	int ret;
1038 
1039 	ret = btrfs_unlink_inode(trans, dir, inode, name);
1040 	if (ret) {
1041 		btrfs_abort_log_replay(wc, ret,
1042 	       "failed to unlink inode %llu parent dir %llu name %.*s root %llu",
1043 				       btrfs_ino(inode), btrfs_ino(dir), name->len,
1044 				       name->name, btrfs_root_id(inode->root));
1045 		return ret;
1046 	}
1047 	/*
1048 	 * Whenever we need to check if a name exists or not, we check the
1049 	 * fs/subvolume tree. So after an unlink we must run delayed items, so
1050 	 * that future checks for a name during log replay see that the name
1051 	 * does not exists anymore.
1052 	 */
1053 	ret = btrfs_run_delayed_items(trans);
1054 	if (ret)
1055 		btrfs_abort_log_replay(wc, ret,
1056 "failed to run delayed items current inode %llu parent dir %llu name %.*s root %llu",
1057 				       btrfs_ino(inode), btrfs_ino(dir), name->len,
1058 				       name->name, btrfs_root_id(inode->root));
1059 
1060 	return ret;
1061 }
1062 
1063 /*
1064  * when cleaning up conflicts between the directory names in the
1065  * subvolume, directory names in the log and directory names in the
1066  * inode back references, we may have to unlink inodes from directories.
1067  *
1068  * This is a helper function to do the unlink of a specific directory
1069  * item
1070  */
1071 static noinline int drop_one_dir_item(struct walk_control *wc,
1072 				      struct btrfs_inode *dir,
1073 				      struct btrfs_dir_item *di)
1074 {
1075 	struct btrfs_root *root = dir->root;
1076 	struct btrfs_inode *inode;
1077 	struct fscrypt_str name;
1078 	struct extent_buffer *leaf = wc->subvol_path->nodes[0];
1079 	struct btrfs_key location;
1080 	int ret;
1081 
1082 	btrfs_dir_item_key_to_cpu(leaf, di, &location);
1083 	ret = read_alloc_one_name(leaf, di + 1, btrfs_dir_name_len(leaf, di), &name);
1084 	if (ret) {
1085 		btrfs_abort_log_replay(wc, ret,
1086 				       "failed to allocate name for dir %llu root %llu",
1087 				       btrfs_ino(dir), btrfs_root_id(root));
1088 		return ret;
1089 	}
1090 
1091 	btrfs_release_path(wc->subvol_path);
1092 
1093 	inode = btrfs_iget_logging(location.objectid, root);
1094 	if (IS_ERR(inode)) {
1095 		ret = PTR_ERR(inode);
1096 		btrfs_abort_log_replay(wc, ret,
1097 		       "failed to open inode %llu parent dir %llu name %.*s root %llu",
1098 				       location.objectid, btrfs_ino(dir),
1099 				       name.len, name.name, btrfs_root_id(root));
1100 		inode = NULL;
1101 		goto out;
1102 	}
1103 
1104 	ret = link_to_fixup_dir(wc, location.objectid);
1105 	if (ret)
1106 		goto out;
1107 
1108 	ret = unlink_inode_for_log_replay(wc, dir, inode, &name);
1109 out:
1110 	kfree(name.name);
1111 	if (inode)
1112 		iput(&inode->vfs_inode);
1113 	return ret;
1114 }
1115 
1116 /*
1117  * See if a given name and sequence number found in an inode back reference are
1118  * already in a directory and correctly point to this inode.
1119  *
1120  * Returns: < 0 on error, 0 if the directory entry does not exists and 1 if it
1121  * exists.
1122  */
1123 static noinline int inode_in_dir(struct btrfs_root *root,
1124 				 struct btrfs_path *path,
1125 				 u64 dirid, u64 objectid, u64 index,
1126 				 struct fscrypt_str *name)
1127 {
1128 	struct btrfs_dir_item *di;
1129 	struct btrfs_key location;
1130 	int ret = 0;
1131 
1132 	di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
1133 					 index, name, 0);
1134 	if (IS_ERR(di)) {
1135 		ret = PTR_ERR(di);
1136 		goto out;
1137 	} else if (di) {
1138 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1139 		if (location.objectid != objectid)
1140 			goto out;
1141 	} else {
1142 		goto out;
1143 	}
1144 
1145 	btrfs_release_path(path);
1146 	di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, 0);
1147 	if (IS_ERR(di)) {
1148 		ret = PTR_ERR(di);
1149 		goto out;
1150 	} else if (di) {
1151 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
1152 		if (location.objectid == objectid)
1153 			ret = 1;
1154 	}
1155 out:
1156 	btrfs_release_path(path);
1157 	return ret;
1158 }
1159 
1160 /*
1161  * helper function to check a log tree for a named back reference in
1162  * an inode.  This is used to decide if a back reference that is
1163  * found in the subvolume conflicts with what we find in the log.
1164  *
1165  * inode backreferences may have multiple refs in a single item,
1166  * during replay we process one reference at a time, and we don't
1167  * want to delete valid links to a file from the subvolume if that
1168  * link is also in the log.
1169  */
1170 static noinline int backref_in_log(struct btrfs_root *log,
1171 				   struct btrfs_key *key,
1172 				   u64 ref_objectid,
1173 				   const struct fscrypt_str *name)
1174 {
1175 	BTRFS_PATH_AUTO_FREE(path);
1176 	int ret;
1177 
1178 	path = btrfs_alloc_path();
1179 	if (!path)
1180 		return -ENOMEM;
1181 
1182 	ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
1183 	if (ret < 0)
1184 		return ret;
1185 	if (ret == 1)
1186 		return 0;
1187 
1188 	if (key->type == BTRFS_INODE_EXTREF_KEY)
1189 		ret = !!btrfs_find_name_in_ext_backref(path->nodes[0],
1190 						       path->slots[0],
1191 						       ref_objectid, name);
1192 	else
1193 		ret = !!btrfs_find_name_in_backref(path->nodes[0],
1194 						   path->slots[0], name);
1195 	return ret;
1196 }
1197 
1198 static int unlink_refs_not_in_log(struct walk_control *wc,
1199 				  struct btrfs_key *search_key,
1200 				  struct btrfs_inode *dir,
1201 				  struct btrfs_inode *inode)
1202 {
1203 	struct extent_buffer *leaf = wc->subvol_path->nodes[0];
1204 	unsigned long ptr;
1205 	unsigned long ptr_end;
1206 
1207 	/*
1208 	 * Check all the names in this back reference to see if they are in the
1209 	 * log. If so, we allow them to stay otherwise they must be unlinked as
1210 	 * a conflict.
1211 	 */
1212 	ptr = btrfs_item_ptr_offset(leaf, wc->subvol_path->slots[0]);
1213 	ptr_end = ptr + btrfs_item_size(leaf, wc->subvol_path->slots[0]);
1214 	while (ptr < ptr_end) {
1215 		struct fscrypt_str victim_name;
1216 		struct btrfs_inode_ref *victim_ref;
1217 		int ret;
1218 
1219 		victim_ref = (struct btrfs_inode_ref *)ptr;
1220 		ret = read_alloc_one_name(leaf, (victim_ref + 1),
1221 					  btrfs_inode_ref_name_len(leaf, victim_ref),
1222 					  &victim_name);
1223 		if (ret) {
1224 			btrfs_abort_log_replay(wc, ret,
1225 	       "failed to allocate name for inode %llu parent dir %llu root %llu",
1226 					       btrfs_ino(inode), btrfs_ino(dir),
1227 					       btrfs_root_id(inode->root));
1228 			return ret;
1229 		}
1230 
1231 		ret = backref_in_log(wc->log, search_key, btrfs_ino(dir), &victim_name);
1232 		if (ret) {
1233 			if (ret < 0) {
1234 				btrfs_abort_log_replay(wc, ret,
1235 "failed to check if backref is in log tree for inode %llu parent dir %llu name %.*s root %llu",
1236 						       btrfs_ino(inode), btrfs_ino(dir),
1237 						       victim_name.len, victim_name.name,
1238 						       btrfs_root_id(inode->root));
1239 				kfree(victim_name.name);
1240 				return ret;
1241 			}
1242 			kfree(victim_name.name);
1243 			ptr = (unsigned long)(victim_ref + 1) + victim_name.len;
1244 			continue;
1245 		}
1246 
1247 		inc_nlink(&inode->vfs_inode);
1248 		btrfs_release_path(wc->subvol_path);
1249 
1250 		ret = unlink_inode_for_log_replay(wc, dir, inode, &victim_name);
1251 		kfree(victim_name.name);
1252 		if (ret)
1253 			return ret;
1254 		return -EAGAIN;
1255 	}
1256 
1257 	return 0;
1258 }
1259 
1260 static int unlink_extrefs_not_in_log(struct walk_control *wc,
1261 				     struct btrfs_key *search_key,
1262 				     struct btrfs_inode *dir,
1263 				     struct btrfs_inode *inode)
1264 {
1265 	struct extent_buffer *leaf = wc->subvol_path->nodes[0];
1266 	const unsigned long base = btrfs_item_ptr_offset(leaf, wc->subvol_path->slots[0]);
1267 	const u32 item_size = btrfs_item_size(leaf, wc->subvol_path->slots[0]);
1268 	u32 cur_offset = 0;
1269 
1270 	while (cur_offset < item_size) {
1271 		struct btrfs_root *log_root = wc->log;
1272 		struct btrfs_inode_extref *extref;
1273 		struct fscrypt_str victim_name;
1274 		int ret;
1275 
1276 		extref = (struct btrfs_inode_extref *)(base + cur_offset);
1277 		victim_name.len = btrfs_inode_extref_name_len(leaf, extref);
1278 
1279 		if (btrfs_inode_extref_parent(leaf, extref) != btrfs_ino(dir))
1280 			goto next;
1281 
1282 		ret = read_alloc_one_name(leaf, &extref->name, victim_name.len,
1283 					  &victim_name);
1284 		if (ret) {
1285 			btrfs_abort_log_replay(wc, ret,
1286 	       "failed to allocate name for inode %llu parent dir %llu root %llu",
1287 					       btrfs_ino(inode), btrfs_ino(dir),
1288 					       btrfs_root_id(inode->root));
1289 			return ret;
1290 		}
1291 
1292 		search_key->objectid = btrfs_ino(inode);
1293 		search_key->type = BTRFS_INODE_EXTREF_KEY;
1294 		search_key->offset = btrfs_extref_hash(btrfs_ino(dir),
1295 						       victim_name.name,
1296 						       victim_name.len);
1297 		ret = backref_in_log(log_root, search_key, btrfs_ino(dir), &victim_name);
1298 		if (ret) {
1299 			if (ret < 0) {
1300 				btrfs_abort_log_replay(wc, ret,
1301 "failed to check if backref is in log tree for inode %llu parent dir %llu name %.*s root %llu",
1302 						       btrfs_ino(inode), btrfs_ino(dir),
1303 						       victim_name.len, victim_name.name,
1304 						       btrfs_root_id(inode->root));
1305 				kfree(victim_name.name);
1306 				return ret;
1307 			}
1308 			kfree(victim_name.name);
1309 next:
1310 			cur_offset += victim_name.len + sizeof(*extref);
1311 			continue;
1312 		}
1313 
1314 		inc_nlink(&inode->vfs_inode);
1315 		btrfs_release_path(wc->subvol_path);
1316 
1317 		ret = unlink_inode_for_log_replay(wc, dir, inode, &victim_name);
1318 		kfree(victim_name.name);
1319 		if (ret)
1320 			return ret;
1321 		return -EAGAIN;
1322 	}
1323 
1324 	return 0;
1325 }
1326 
1327 static inline int __add_inode_ref(struct walk_control *wc,
1328 				  struct btrfs_inode *dir,
1329 				  struct btrfs_inode *inode,
1330 				  u64 ref_index, struct fscrypt_str *name)
1331 {
1332 	int ret;
1333 	struct btrfs_trans_handle *trans = wc->trans;
1334 	struct btrfs_root *root = wc->root;
1335 	struct btrfs_dir_item *di;
1336 	struct btrfs_key search_key;
1337 	struct btrfs_inode_extref *extref;
1338 
1339 again:
1340 	/* Search old style refs */
1341 	search_key.objectid = btrfs_ino(inode);
1342 	search_key.type = BTRFS_INODE_REF_KEY;
1343 	search_key.offset = btrfs_ino(dir);
1344 	ret = btrfs_search_slot(NULL, root, &search_key, wc->subvol_path, 0, 0);
1345 	if (ret < 0) {
1346 		btrfs_abort_log_replay(wc, ret,
1347 	       "failed to search subvolume tree for key " BTRFS_KEY_FMT " root %llu",
1348 				       BTRFS_KEY_FMT_VALUE(&search_key),
1349 				       btrfs_root_id(root));
1350 		return ret;
1351 	} else if (ret == 0) {
1352 		/*
1353 		 * Are we trying to overwrite a back ref for the root directory?
1354 		 * If so, we're done.
1355 		 */
1356 		if (search_key.objectid == search_key.offset)
1357 			return 1;
1358 
1359 		ret = unlink_refs_not_in_log(wc, &search_key, dir, inode);
1360 		if (ret == -EAGAIN)
1361 			goto again;
1362 		else if (ret)
1363 			return ret;
1364 	}
1365 	btrfs_release_path(wc->subvol_path);
1366 
1367 	/* Same search but for extended refs */
1368 	extref = btrfs_lookup_inode_extref(root, wc->subvol_path, name,
1369 					   btrfs_ino(inode), btrfs_ino(dir));
1370 	if (IS_ERR(extref)) {
1371 		return PTR_ERR(extref);
1372 	} else if (extref) {
1373 		ret = unlink_extrefs_not_in_log(wc, &search_key, dir, inode);
1374 		if (ret == -EAGAIN)
1375 			goto again;
1376 		else if (ret)
1377 			return ret;
1378 	}
1379 	btrfs_release_path(wc->subvol_path);
1380 
1381 	/* look for a conflicting sequence number */
1382 	di = btrfs_lookup_dir_index_item(trans, root, wc->subvol_path, btrfs_ino(dir),
1383 					 ref_index, name, 0);
1384 	if (IS_ERR(di)) {
1385 		ret = PTR_ERR(di);
1386 		btrfs_abort_log_replay(wc, ret,
1387 "failed to lookup dir index item for dir %llu ref_index %llu name %.*s root %llu",
1388 				       btrfs_ino(dir), ref_index, name->len,
1389 				       name->name, btrfs_root_id(root));
1390 		return ret;
1391 	} else if (di) {
1392 		ret = drop_one_dir_item(wc, dir, di);
1393 		if (ret)
1394 			return ret;
1395 	}
1396 	btrfs_release_path(wc->subvol_path);
1397 
1398 	/* look for a conflicting name */
1399 	di = btrfs_lookup_dir_item(trans, root, wc->subvol_path, btrfs_ino(dir), name, 0);
1400 	if (IS_ERR(di)) {
1401 		ret = PTR_ERR(di);
1402 		btrfs_abort_log_replay(wc, ret,
1403 	"failed to lookup dir item for dir %llu name %.*s root %llu",
1404 				       btrfs_ino(dir), name->len, name->name,
1405 				       btrfs_root_id(root));
1406 		return ret;
1407 	} else if (di) {
1408 		ret = drop_one_dir_item(wc, dir, di);
1409 		if (ret)
1410 			return ret;
1411 	}
1412 	btrfs_release_path(wc->subvol_path);
1413 
1414 	return 0;
1415 }
1416 
1417 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1418 			     struct fscrypt_str *name, u64 *index,
1419 			     u64 *parent_objectid)
1420 {
1421 	struct btrfs_inode_extref *extref;
1422 	int ret;
1423 
1424 	extref = (struct btrfs_inode_extref *)ref_ptr;
1425 
1426 	ret = read_alloc_one_name(eb, &extref->name,
1427 				  btrfs_inode_extref_name_len(eb, extref), name);
1428 	if (ret)
1429 		return ret;
1430 
1431 	if (index)
1432 		*index = btrfs_inode_extref_index(eb, extref);
1433 	if (parent_objectid)
1434 		*parent_objectid = btrfs_inode_extref_parent(eb, extref);
1435 
1436 	return 0;
1437 }
1438 
1439 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1440 			  struct fscrypt_str *name, u64 *index)
1441 {
1442 	struct btrfs_inode_ref *ref;
1443 	int ret;
1444 
1445 	ref = (struct btrfs_inode_ref *)ref_ptr;
1446 
1447 	ret = read_alloc_one_name(eb, ref + 1, btrfs_inode_ref_name_len(eb, ref),
1448 				  name);
1449 	if (ret)
1450 		return ret;
1451 
1452 	if (index)
1453 		*index = btrfs_inode_ref_index(eb, ref);
1454 
1455 	return 0;
1456 }
1457 
1458 /*
1459  * Take an inode reference item from the log tree and iterate all names from the
1460  * inode reference item in the subvolume tree with the same key (if it exists).
1461  * For any name that is not in the inode reference item from the log tree, do a
1462  * proper unlink of that name (that is, remove its entry from the inode
1463  * reference item and both dir index keys).
1464  */
1465 static int unlink_old_inode_refs(struct walk_control *wc, struct btrfs_inode *inode)
1466 {
1467 	struct btrfs_root *root = wc->root;
1468 	int ret;
1469 	unsigned long ref_ptr;
1470 	unsigned long ref_end;
1471 	struct extent_buffer *eb;
1472 
1473 again:
1474 	btrfs_release_path(wc->subvol_path);
1475 	ret = btrfs_search_slot(NULL, root, &wc->log_key, wc->subvol_path, 0, 0);
1476 	if (ret > 0) {
1477 		ret = 0;
1478 		goto out;
1479 	}
1480 	if (ret < 0) {
1481 		btrfs_abort_log_replay(wc, ret,
1482 	       "failed to search subvolume tree for key " BTRFS_KEY_FMT " root %llu",
1483 				       BTRFS_KEY_FMT_VALUE(&wc->log_key),
1484 				       btrfs_root_id(root));
1485 		goto out;
1486 	}
1487 
1488 	eb = wc->subvol_path->nodes[0];
1489 	ref_ptr = btrfs_item_ptr_offset(eb, wc->subvol_path->slots[0]);
1490 	ref_end = ref_ptr + btrfs_item_size(eb, wc->subvol_path->slots[0]);
1491 	while (ref_ptr < ref_end) {
1492 		struct fscrypt_str name;
1493 		u64 parent_id;
1494 
1495 		if (wc->log_key.type == BTRFS_INODE_EXTREF_KEY) {
1496 			ret = extref_get_fields(eb, ref_ptr, &name,
1497 						NULL, &parent_id);
1498 			if (ret) {
1499 				btrfs_abort_log_replay(wc, ret,
1500 			       "failed to get extref details for inode %llu root %llu",
1501 						       btrfs_ino(inode),
1502 						       btrfs_root_id(root));
1503 				goto out;
1504 			}
1505 		} else {
1506 			parent_id = wc->log_key.offset;
1507 			ret = ref_get_fields(eb, ref_ptr, &name, NULL);
1508 			if (ret) {
1509 				btrfs_abort_log_replay(wc, ret,
1510 	       "failed to get ref details for inode %llu parent_id %llu root %llu",
1511 						       btrfs_ino(inode), parent_id,
1512 						       btrfs_root_id(root));
1513 				goto out;
1514 			}
1515 		}
1516 
1517 		if (wc->log_key.type == BTRFS_INODE_EXTREF_KEY)
1518 			ret = !!btrfs_find_name_in_ext_backref(wc->log_leaf, wc->log_slot,
1519 							       parent_id, &name);
1520 		else
1521 			ret = !!btrfs_find_name_in_backref(wc->log_leaf, wc->log_slot,
1522 							   &name);
1523 
1524 		if (!ret) {
1525 			struct btrfs_inode *dir;
1526 
1527 			btrfs_release_path(wc->subvol_path);
1528 			dir = btrfs_iget_logging(parent_id, root);
1529 			if (IS_ERR(dir)) {
1530 				ret = PTR_ERR(dir);
1531 				kfree(name.name);
1532 				btrfs_abort_log_replay(wc, ret,
1533 				       "failed to lookup dir inode %llu root %llu",
1534 						       parent_id, btrfs_root_id(root));
1535 				goto out;
1536 			}
1537 			ret = unlink_inode_for_log_replay(wc, dir, inode, &name);
1538 			kfree(name.name);
1539 			iput(&dir->vfs_inode);
1540 			if (ret)
1541 				goto out;
1542 			goto again;
1543 		}
1544 
1545 		kfree(name.name);
1546 		ref_ptr += name.len;
1547 		if (wc->log_key.type == BTRFS_INODE_EXTREF_KEY)
1548 			ref_ptr += sizeof(struct btrfs_inode_extref);
1549 		else
1550 			ref_ptr += sizeof(struct btrfs_inode_ref);
1551 	}
1552 	ret = 0;
1553  out:
1554 	btrfs_release_path(wc->subvol_path);
1555 	return ret;
1556 }
1557 
1558 /*
1559  * Replay one inode back reference item found in the log tree.
1560  * Path is for temporary use by this function (it should be released on return).
1561  */
1562 static noinline int add_inode_ref(struct walk_control *wc)
1563 {
1564 	struct btrfs_trans_handle *trans = wc->trans;
1565 	struct btrfs_root *root = wc->root;
1566 	struct btrfs_inode *dir = NULL;
1567 	struct btrfs_inode *inode = NULL;
1568 	unsigned long ref_ptr;
1569 	unsigned long ref_end;
1570 	struct fscrypt_str name = { 0 };
1571 	int ret;
1572 	const bool is_extref_item = (wc->log_key.type == BTRFS_INODE_EXTREF_KEY);
1573 	u64 parent_objectid;
1574 	u64 inode_objectid;
1575 	u64 ref_index = 0;
1576 	int ref_struct_size;
1577 
1578 	ref_ptr = btrfs_item_ptr_offset(wc->log_leaf, wc->log_slot);
1579 	ref_end = ref_ptr + btrfs_item_size(wc->log_leaf, wc->log_slot);
1580 
1581 	if (is_extref_item) {
1582 		struct btrfs_inode_extref *r;
1583 
1584 		ref_struct_size = sizeof(struct btrfs_inode_extref);
1585 		r = (struct btrfs_inode_extref *)ref_ptr;
1586 		parent_objectid = btrfs_inode_extref_parent(wc->log_leaf, r);
1587 	} else {
1588 		ref_struct_size = sizeof(struct btrfs_inode_ref);
1589 		parent_objectid = wc->log_key.offset;
1590 	}
1591 	inode_objectid = wc->log_key.objectid;
1592 
1593 	/*
1594 	 * it is possible that we didn't log all the parent directories
1595 	 * for a given inode.  If we don't find the dir, just don't
1596 	 * copy the back ref in.  The link count fixup code will take
1597 	 * care of the rest
1598 	 */
1599 	dir = btrfs_iget_logging(parent_objectid, root);
1600 	if (IS_ERR(dir)) {
1601 		ret = PTR_ERR(dir);
1602 		if (ret == -ENOENT)
1603 			ret = 0;
1604 		else
1605 			btrfs_abort_log_replay(wc, ret,
1606 			       "failed to lookup dir inode %llu root %llu",
1607 					       parent_objectid, btrfs_root_id(root));
1608 		dir = NULL;
1609 		goto out;
1610 	}
1611 
1612 	inode = btrfs_iget_logging(inode_objectid, root);
1613 	if (IS_ERR(inode)) {
1614 		ret = PTR_ERR(inode);
1615 		btrfs_abort_log_replay(wc, ret,
1616 				       "failed to lookup inode %llu root %llu",
1617 				       inode_objectid, btrfs_root_id(root));
1618 		inode = NULL;
1619 		goto out;
1620 	}
1621 
1622 	while (ref_ptr < ref_end) {
1623 		if (is_extref_item) {
1624 			ret = extref_get_fields(wc->log_leaf, ref_ptr, &name,
1625 						&ref_index, &parent_objectid);
1626 			if (ret) {
1627 				btrfs_abort_log_replay(wc, ret,
1628 			       "failed to get extref details for inode %llu root %llu",
1629 						       btrfs_ino(inode),
1630 						       btrfs_root_id(root));
1631 				goto out;
1632 			}
1633 			/*
1634 			 * parent object can change from one array
1635 			 * item to another.
1636 			 */
1637 			if (!dir) {
1638 				dir = btrfs_iget_logging(parent_objectid, root);
1639 				if (IS_ERR(dir)) {
1640 					ret = PTR_ERR(dir);
1641 					dir = NULL;
1642 					/*
1643 					 * A new parent dir may have not been
1644 					 * logged and not exist in the subvolume
1645 					 * tree, see the comment above before
1646 					 * the loop when getting the first
1647 					 * parent dir.
1648 					 */
1649 					if (ret == -ENOENT) {
1650 						/*
1651 						 * The next extref may refer to
1652 						 * another parent dir that
1653 						 * exists, so continue.
1654 						 */
1655 						ret = 0;
1656 						goto next;
1657 					} else {
1658 						btrfs_abort_log_replay(wc, ret,
1659 				       "failed to lookup dir inode %llu root %llu",
1660 								       parent_objectid,
1661 								       btrfs_root_id(root));
1662 					}
1663 					goto out;
1664 				}
1665 			}
1666 		} else {
1667 			ret = ref_get_fields(wc->log_leaf, ref_ptr, &name, &ref_index);
1668 			if (ret) {
1669 				btrfs_abort_log_replay(wc, ret,
1670 	"failed to get ref details for inode %llu parent_objectid %llu root %llu",
1671 						       btrfs_ino(inode),
1672 						       parent_objectid,
1673 						       btrfs_root_id(root));
1674 				goto out;
1675 			}
1676 		}
1677 
1678 		ret = inode_in_dir(root, wc->subvol_path, btrfs_ino(dir),
1679 				   btrfs_ino(inode), ref_index, &name);
1680 		if (ret < 0) {
1681 			btrfs_abort_log_replay(wc, ret,
1682 "failed to check if inode %llu is in dir %llu ref_index %llu name %.*s root %llu",
1683 					       btrfs_ino(inode), btrfs_ino(dir),
1684 					       ref_index, name.len, name.name,
1685 					       btrfs_root_id(root));
1686 			goto out;
1687 		} else if (ret == 0) {
1688 			/*
1689 			 * look for a conflicting back reference in the
1690 			 * metadata. if we find one we have to unlink that name
1691 			 * of the file before we add our new link.  Later on, we
1692 			 * overwrite any existing back reference, and we don't
1693 			 * want to create dangling pointers in the directory.
1694 			 */
1695 			ret = __add_inode_ref(wc, dir, inode, ref_index, &name);
1696 			if (ret) {
1697 				if (ret == 1)
1698 					ret = 0;
1699 				goto out;
1700 			}
1701 
1702 			/* insert our name */
1703 			ret = btrfs_add_link(trans, dir, inode, &name, false, ref_index);
1704 			if (ret) {
1705 				btrfs_abort_log_replay(wc, ret,
1706 "failed to add link for inode %llu in dir %llu ref_index %llu name %.*s root %llu",
1707 						       btrfs_ino(inode),
1708 						       btrfs_ino(dir), ref_index,
1709 						       name.len, name.name,
1710 						       btrfs_root_id(root));
1711 				goto out;
1712 			}
1713 
1714 			ret = btrfs_update_inode(trans, inode);
1715 			if (ret) {
1716 				btrfs_abort_log_replay(wc, ret,
1717 				       "failed to update inode %llu root %llu",
1718 						       btrfs_ino(inode),
1719 						       btrfs_root_id(root));
1720 				goto out;
1721 			}
1722 		}
1723 		/* Else, ret == 1, we already have a perfect match, we're done. */
1724 
1725 next:
1726 		ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + name.len;
1727 		kfree(name.name);
1728 		name.name = NULL;
1729 		if (is_extref_item && dir) {
1730 			iput(&dir->vfs_inode);
1731 			dir = NULL;
1732 		}
1733 	}
1734 
1735 	/*
1736 	 * Before we overwrite the inode reference item in the subvolume tree
1737 	 * with the item from the log tree, we must unlink all names from the
1738 	 * parent directory that are in the subvolume's tree inode reference
1739 	 * item, otherwise we end up with an inconsistent subvolume tree where
1740 	 * dir index entries exist for a name but there is no inode reference
1741 	 * item with the same name.
1742 	 */
1743 	ret = unlink_old_inode_refs(wc, inode);
1744 	if (ret)
1745 		goto out;
1746 
1747 	/* finally write the back reference in the inode */
1748 	ret = overwrite_item(wc);
1749 out:
1750 	btrfs_release_path(wc->subvol_path);
1751 	kfree(name.name);
1752 	if (dir)
1753 		iput(&dir->vfs_inode);
1754 	if (inode)
1755 		iput(&inode->vfs_inode);
1756 	return ret;
1757 }
1758 
1759 static int count_inode_extrefs(struct btrfs_inode *inode, struct btrfs_path *path)
1760 {
1761 	int ret = 0;
1762 	int name_len;
1763 	unsigned int nlink = 0;
1764 	u32 item_size;
1765 	u32 cur_offset = 0;
1766 	u64 inode_objectid = btrfs_ino(inode);
1767 	u64 offset = 0;
1768 	unsigned long ptr;
1769 	struct btrfs_inode_extref *extref;
1770 	struct extent_buffer *leaf;
1771 
1772 	while (1) {
1773 		ret = btrfs_find_one_extref(inode->root, inode_objectid, offset,
1774 					    path, &extref, &offset);
1775 		if (ret)
1776 			break;
1777 
1778 		leaf = path->nodes[0];
1779 		item_size = btrfs_item_size(leaf, path->slots[0]);
1780 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1781 		cur_offset = 0;
1782 
1783 		while (cur_offset < item_size) {
1784 			extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1785 			name_len = btrfs_inode_extref_name_len(leaf, extref);
1786 
1787 			nlink++;
1788 
1789 			cur_offset += name_len + sizeof(*extref);
1790 		}
1791 
1792 		offset++;
1793 		btrfs_release_path(path);
1794 	}
1795 	btrfs_release_path(path);
1796 
1797 	if (ret < 0 && ret != -ENOENT)
1798 		return ret;
1799 	return nlink;
1800 }
1801 
1802 static int count_inode_refs(struct btrfs_inode *inode, struct btrfs_path *path)
1803 {
1804 	int ret;
1805 	struct btrfs_key key;
1806 	unsigned int nlink = 0;
1807 	unsigned long ptr;
1808 	unsigned long ptr_end;
1809 	int name_len;
1810 	u64 ino = btrfs_ino(inode);
1811 
1812 	key.objectid = ino;
1813 	key.type = BTRFS_INODE_REF_KEY;
1814 	key.offset = (u64)-1;
1815 
1816 	while (1) {
1817 		ret = btrfs_search_slot(NULL, inode->root, &key, path, 0, 0);
1818 		if (ret < 0)
1819 			break;
1820 		if (ret > 0) {
1821 			if (path->slots[0] == 0)
1822 				break;
1823 			path->slots[0]--;
1824 		}
1825 process_slot:
1826 		btrfs_item_key_to_cpu(path->nodes[0], &key,
1827 				      path->slots[0]);
1828 		if (key.objectid != ino ||
1829 		    key.type != BTRFS_INODE_REF_KEY)
1830 			break;
1831 		ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1832 		ptr_end = ptr + btrfs_item_size(path->nodes[0],
1833 						   path->slots[0]);
1834 		while (ptr < ptr_end) {
1835 			struct btrfs_inode_ref *ref;
1836 
1837 			ref = (struct btrfs_inode_ref *)ptr;
1838 			name_len = btrfs_inode_ref_name_len(path->nodes[0],
1839 							    ref);
1840 			ptr = (unsigned long)(ref + 1) + name_len;
1841 			nlink++;
1842 		}
1843 
1844 		if (key.offset == 0)
1845 			break;
1846 		if (path->slots[0] > 0) {
1847 			path->slots[0]--;
1848 			goto process_slot;
1849 		}
1850 		key.offset--;
1851 		btrfs_release_path(path);
1852 	}
1853 	btrfs_release_path(path);
1854 
1855 	return nlink;
1856 }
1857 
1858 /*
1859  * There are a few corners where the link count of the file can't
1860  * be properly maintained during replay.  So, instead of adding
1861  * lots of complexity to the log code, we just scan the backrefs
1862  * for any file that has been through replay.
1863  *
1864  * The scan will update the link count on the inode to reflect the
1865  * number of back refs found.  If it goes down to zero, the iput
1866  * will free the inode.
1867  */
1868 static noinline int fixup_inode_link_count(struct walk_control *wc,
1869 					   struct btrfs_inode *inode)
1870 {
1871 	struct btrfs_trans_handle *trans = wc->trans;
1872 	struct btrfs_root *root = inode->root;
1873 	int ret;
1874 	u64 nlink = 0;
1875 	const u64 ino = btrfs_ino(inode);
1876 
1877 	ret = count_inode_refs(inode, wc->subvol_path);
1878 	if (ret < 0)
1879 		goto out;
1880 
1881 	nlink = ret;
1882 
1883 	ret = count_inode_extrefs(inode, wc->subvol_path);
1884 	if (ret < 0)
1885 		goto out;
1886 
1887 	nlink += ret;
1888 
1889 	ret = 0;
1890 
1891 	if (nlink != inode->vfs_inode.i_nlink) {
1892 		set_nlink(&inode->vfs_inode, nlink);
1893 		ret = btrfs_update_inode(trans, inode);
1894 		if (ret)
1895 			goto out;
1896 	}
1897 	if (S_ISDIR(inode->vfs_inode.i_mode))
1898 		inode->index_cnt = (u64)-1;
1899 
1900 	if (inode->vfs_inode.i_nlink == 0) {
1901 		if (S_ISDIR(inode->vfs_inode.i_mode)) {
1902 			ret = replay_dir_deletes(wc, ino, true);
1903 			if (ret)
1904 				goto out;
1905 		}
1906 		ret = btrfs_insert_orphan_item(trans, root, ino);
1907 		if (ret == -EEXIST)
1908 			ret = 0;
1909 	}
1910 
1911 out:
1912 	btrfs_release_path(wc->subvol_path);
1913 	return ret;
1914 }
1915 
1916 static noinline int fixup_inode_link_counts(struct walk_control *wc)
1917 {
1918 	int ret;
1919 	struct btrfs_key key;
1920 
1921 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1922 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1923 	key.offset = (u64)-1;
1924 	while (1) {
1925 		struct btrfs_trans_handle *trans = wc->trans;
1926 		struct btrfs_root *root = wc->root;
1927 		struct btrfs_inode *inode;
1928 
1929 		ret = btrfs_search_slot(trans, root, &key, wc->subvol_path, -1, 1);
1930 		if (ret < 0)
1931 			break;
1932 
1933 		if (ret == 1) {
1934 			ret = 0;
1935 			if (wc->subvol_path->slots[0] == 0)
1936 				break;
1937 			wc->subvol_path->slots[0]--;
1938 		}
1939 
1940 		btrfs_item_key_to_cpu(wc->subvol_path->nodes[0], &key, wc->subvol_path->slots[0]);
1941 		if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1942 		    key.type != BTRFS_ORPHAN_ITEM_KEY)
1943 			break;
1944 
1945 		ret = btrfs_del_item(trans, root, wc->subvol_path);
1946 		if (ret)
1947 			break;
1948 
1949 		btrfs_release_path(wc->subvol_path);
1950 		inode = btrfs_iget_logging(key.offset, root);
1951 		if (IS_ERR(inode)) {
1952 			ret = PTR_ERR(inode);
1953 			break;
1954 		}
1955 
1956 		ret = fixup_inode_link_count(wc, inode);
1957 		iput(&inode->vfs_inode);
1958 		if (ret)
1959 			break;
1960 
1961 		/*
1962 		 * fixup on a directory may create new entries,
1963 		 * make sure we always look for the highest possible
1964 		 * offset
1965 		 */
1966 		key.offset = (u64)-1;
1967 	}
1968 	btrfs_release_path(wc->subvol_path);
1969 	return ret;
1970 }
1971 
1972 
1973 /*
1974  * record a given inode in the fixup dir so we can check its link
1975  * count when replay is done.  The link count is incremented here
1976  * so the inode won't go away until we check it
1977  */
1978 static noinline int link_to_fixup_dir(struct walk_control *wc, u64 objectid)
1979 {
1980 	struct btrfs_trans_handle *trans = wc->trans;
1981 	struct btrfs_root *root = wc->root;
1982 	struct btrfs_key key;
1983 	int ret = 0;
1984 	struct btrfs_inode *inode;
1985 	struct inode *vfs_inode;
1986 
1987 	inode = btrfs_iget_logging(objectid, root);
1988 	if (IS_ERR(inode)) {
1989 		ret = PTR_ERR(inode);
1990 		btrfs_abort_log_replay(wc, ret,
1991 				       "failed to lookup inode %llu root %llu",
1992 				       objectid, btrfs_root_id(root));
1993 		return ret;
1994 	}
1995 
1996 	vfs_inode = &inode->vfs_inode;
1997 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1998 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1999 	key.offset = objectid;
2000 
2001 	ret = btrfs_insert_empty_item(trans, root, wc->subvol_path, &key, 0);
2002 
2003 	btrfs_release_path(wc->subvol_path);
2004 	if (ret == 0) {
2005 		if (!vfs_inode->i_nlink)
2006 			set_nlink(vfs_inode, 1);
2007 		else
2008 			inc_nlink(vfs_inode);
2009 		ret = btrfs_update_inode(trans, inode);
2010 		if (ret)
2011 			btrfs_abort_log_replay(wc, ret,
2012 				       "failed to update inode %llu root %llu",
2013 					       objectid, btrfs_root_id(root));
2014 	} else if (ret == -EEXIST) {
2015 		ret = 0;
2016 	} else {
2017 		btrfs_abort_log_replay(wc, ret,
2018 		       "failed to insert fixup item for inode %llu root %llu",
2019 				       objectid, btrfs_root_id(root));
2020 	}
2021 	iput(vfs_inode);
2022 
2023 	return ret;
2024 }
2025 
2026 /*
2027  * when replaying the log for a directory, we only insert names
2028  * for inodes that actually exist.  This means an fsync on a directory
2029  * does not implicitly fsync all the new files in it
2030  */
2031 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
2032 				    struct btrfs_root *root,
2033 				    u64 dirid, u64 index,
2034 				    const struct fscrypt_str *name,
2035 				    struct btrfs_key *location)
2036 {
2037 	struct btrfs_inode *inode;
2038 	struct btrfs_inode *dir;
2039 	int ret;
2040 
2041 	inode = btrfs_iget_logging(location->objectid, root);
2042 	if (IS_ERR(inode))
2043 		return PTR_ERR(inode);
2044 
2045 	dir = btrfs_iget_logging(dirid, root);
2046 	if (IS_ERR(dir)) {
2047 		iput(&inode->vfs_inode);
2048 		return PTR_ERR(dir);
2049 	}
2050 
2051 	ret = btrfs_add_link(trans, dir, inode, name, true, index);
2052 
2053 	/* FIXME, put inode into FIXUP list */
2054 
2055 	iput(&inode->vfs_inode);
2056 	iput(&dir->vfs_inode);
2057 	return ret;
2058 }
2059 
2060 static int delete_conflicting_dir_entry(struct walk_control *wc,
2061 					struct btrfs_inode *dir,
2062 					struct btrfs_dir_item *dst_di,
2063 					const struct btrfs_key *log_key,
2064 					u8 log_flags,
2065 					bool exists)
2066 {
2067 	struct btrfs_key found_key;
2068 
2069 	btrfs_dir_item_key_to_cpu(wc->subvol_path->nodes[0], dst_di, &found_key);
2070 	/* The existing dentry points to the same inode, don't delete it. */
2071 	if (found_key.objectid == log_key->objectid &&
2072 	    found_key.type == log_key->type &&
2073 	    found_key.offset == log_key->offset &&
2074 	    btrfs_dir_flags(wc->subvol_path->nodes[0], dst_di) == log_flags)
2075 		return 1;
2076 
2077 	/*
2078 	 * Don't drop the conflicting directory entry if the inode for the new
2079 	 * entry doesn't exist.
2080 	 */
2081 	if (!exists)
2082 		return 0;
2083 
2084 	return drop_one_dir_item(wc, dir, dst_di);
2085 }
2086 
2087 /*
2088  * take a single entry in a log directory item and replay it into
2089  * the subvolume.
2090  *
2091  * if a conflicting item exists in the subdirectory already,
2092  * the inode it points to is unlinked and put into the link count
2093  * fix up tree.
2094  *
2095  * If a name from the log points to a file or directory that does
2096  * not exist in the FS, it is skipped.  fsyncs on directories
2097  * do not force down inodes inside that directory, just changes to the
2098  * names or unlinks in a directory.
2099  *
2100  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
2101  * non-existing inode) and 1 if the name was replayed.
2102  */
2103 static noinline int replay_one_name(struct walk_control *wc, struct btrfs_dir_item *di)
2104 {
2105 	struct btrfs_trans_handle *trans = wc->trans;
2106 	struct btrfs_root *root = wc->root;
2107 	struct fscrypt_str name = { 0 };
2108 	struct btrfs_dir_item *dir_dst_di;
2109 	struct btrfs_dir_item *index_dst_di;
2110 	bool dir_dst_matches = false;
2111 	bool index_dst_matches = false;
2112 	struct btrfs_key log_key;
2113 	struct btrfs_key search_key;
2114 	struct btrfs_inode *dir;
2115 	u8 log_flags;
2116 	bool exists;
2117 	int ret;
2118 	bool update_size = true;
2119 	bool name_added = false;
2120 
2121 	dir = btrfs_iget_logging(wc->log_key.objectid, root);
2122 	if (IS_ERR(dir)) {
2123 		ret = PTR_ERR(dir);
2124 		btrfs_abort_log_replay(wc, ret,
2125 				       "failed to lookup dir inode %llu root %llu",
2126 				       wc->log_key.objectid, btrfs_root_id(root));
2127 		return ret;
2128 	}
2129 
2130 	ret = read_alloc_one_name(wc->log_leaf, di + 1,
2131 				  btrfs_dir_name_len(wc->log_leaf, di), &name);
2132 	if (ret) {
2133 		btrfs_abort_log_replay(wc, ret,
2134 			       "failed to allocate name for dir %llu root %llu",
2135 				       btrfs_ino(dir), btrfs_root_id(root));
2136 		goto out;
2137 	}
2138 
2139 	log_flags = btrfs_dir_flags(wc->log_leaf, di);
2140 	btrfs_dir_item_key_to_cpu(wc->log_leaf, di, &log_key);
2141 	ret = btrfs_lookup_inode(trans, root, wc->subvol_path, &log_key, 0);
2142 	btrfs_release_path(wc->subvol_path);
2143 	if (ret < 0) {
2144 		btrfs_abort_log_replay(wc, ret,
2145 				       "failed to lookup inode %llu root %llu",
2146 				       log_key.objectid, btrfs_root_id(root));
2147 		goto out;
2148 	}
2149 	exists = (ret == 0);
2150 	ret = 0;
2151 
2152 	dir_dst_di = btrfs_lookup_dir_item(trans, root, wc->subvol_path,
2153 					   wc->log_key.objectid, &name, 1);
2154 	if (IS_ERR(dir_dst_di)) {
2155 		ret = PTR_ERR(dir_dst_di);
2156 		btrfs_abort_log_replay(wc, ret,
2157 		       "failed to lookup dir item for dir %llu name %.*s root %llu",
2158 				       wc->log_key.objectid, name.len, name.name,
2159 				       btrfs_root_id(root));
2160 		goto out;
2161 	} else if (dir_dst_di) {
2162 		ret = delete_conflicting_dir_entry(wc, dir, dir_dst_di,
2163 						   &log_key, log_flags, exists);
2164 		if (ret < 0) {
2165 			btrfs_abort_log_replay(wc, ret,
2166 	       "failed to delete conflicting entry for dir %llu name %.*s root %llu",
2167 					       btrfs_ino(dir), name.len, name.name,
2168 					       btrfs_root_id(root));
2169 			goto out;
2170 		}
2171 		dir_dst_matches = (ret == 1);
2172 	}
2173 
2174 	btrfs_release_path(wc->subvol_path);
2175 
2176 	index_dst_di = btrfs_lookup_dir_index_item(trans, root, wc->subvol_path,
2177 						   wc->log_key.objectid,
2178 						   wc->log_key.offset, &name, 1);
2179 	if (IS_ERR(index_dst_di)) {
2180 		ret = PTR_ERR(index_dst_di);
2181 		btrfs_abort_log_replay(wc, ret,
2182 	       "failed to lookup dir index item for dir %llu name %.*s root %llu",
2183 				       wc->log_key.objectid, name.len, name.name,
2184 				       btrfs_root_id(root));
2185 		goto out;
2186 	} else if (index_dst_di) {
2187 		ret = delete_conflicting_dir_entry(wc, dir, index_dst_di,
2188 						   &log_key, log_flags, exists);
2189 		if (ret < 0) {
2190 			btrfs_abort_log_replay(wc, ret,
2191 	       "failed to delete conflicting entry for dir %llu name %.*s root %llu",
2192 					       btrfs_ino(dir), name.len, name.name,
2193 					       btrfs_root_id(root));
2194 			goto out;
2195 		}
2196 		index_dst_matches = (ret == 1);
2197 	}
2198 
2199 	btrfs_release_path(wc->subvol_path);
2200 
2201 	if (dir_dst_matches && index_dst_matches) {
2202 		ret = 0;
2203 		update_size = false;
2204 		goto out;
2205 	}
2206 
2207 	/*
2208 	 * Check if the inode reference exists in the log for the given name,
2209 	 * inode and parent inode
2210 	 */
2211 	search_key.objectid = log_key.objectid;
2212 	search_key.type = BTRFS_INODE_REF_KEY;
2213 	search_key.offset = wc->log_key.objectid;
2214 	ret = backref_in_log(root->log_root, &search_key, 0, &name);
2215 	if (ret < 0) {
2216 		btrfs_abort_log_replay(wc, ret,
2217 "failed to check if ref item is logged for inode %llu dir %llu name %.*s root %llu",
2218 				       search_key.objectid, btrfs_ino(dir),
2219 				       name.len, name.name, btrfs_root_id(root));
2220 	        goto out;
2221 	} else if (ret) {
2222 	        /* The dentry will be added later. */
2223 	        ret = 0;
2224 	        update_size = false;
2225 	        goto out;
2226 	}
2227 
2228 	search_key.objectid = log_key.objectid;
2229 	search_key.type = BTRFS_INODE_EXTREF_KEY;
2230 	search_key.offset = btrfs_extref_hash(wc->log_key.objectid, name.name, name.len);
2231 	ret = backref_in_log(root->log_root, &search_key, wc->log_key.objectid, &name);
2232 	if (ret < 0) {
2233 		btrfs_abort_log_replay(wc, ret,
2234 "failed to check if extref item is logged for inode %llu dir %llu name %.*s root %llu",
2235 				       search_key.objectid, btrfs_ino(dir),
2236 				       name.len, name.name, btrfs_root_id(root));
2237 		goto out;
2238 	} else if (ret) {
2239 		/* The dentry will be added later. */
2240 		ret = 0;
2241 		update_size = false;
2242 		goto out;
2243 	}
2244 	ret = insert_one_name(trans, root, wc->log_key.objectid, wc->log_key.offset,
2245 			      &name, &log_key);
2246 	if (ret && ret != -ENOENT && ret != -EEXIST) {
2247 		btrfs_abort_log_replay(wc, ret,
2248 		       "failed to insert name %.*s for inode %llu dir %llu root %llu",
2249 				       name.len, name.name, log_key.objectid,
2250 				       btrfs_ino(dir), btrfs_root_id(root));
2251 		goto out;
2252 	}
2253 	if (!ret)
2254 		name_added = true;
2255 	update_size = false;
2256 	ret = 0;
2257 
2258 out:
2259 	if (!ret && update_size) {
2260 		btrfs_i_size_write(dir, dir->vfs_inode.i_size + name.len * 2);
2261 		ret = btrfs_update_inode(trans, dir);
2262 		if (ret)
2263 			btrfs_abort_log_replay(wc, ret,
2264 				       "failed to update dir inode %llu root %llu",
2265 					       btrfs_ino(dir), btrfs_root_id(root));
2266 	}
2267 	kfree(name.name);
2268 	iput(&dir->vfs_inode);
2269 	if (!ret && name_added)
2270 		ret = 1;
2271 	return ret;
2272 }
2273 
2274 /* Replay one dir item from a BTRFS_DIR_INDEX_KEY key. */
2275 static noinline int replay_one_dir_item(struct walk_control *wc)
2276 {
2277 	int ret;
2278 	struct btrfs_dir_item *di;
2279 
2280 	/* We only log dir index keys, which only contain a single dir item. */
2281 	ASSERT(wc->log_key.type == BTRFS_DIR_INDEX_KEY,
2282 	       "wc->log_key.type=%u", wc->log_key.type);
2283 
2284 	di = btrfs_item_ptr(wc->log_leaf, wc->log_slot, struct btrfs_dir_item);
2285 	ret = replay_one_name(wc, di);
2286 	if (ret < 0)
2287 		return ret;
2288 
2289 	/*
2290 	 * If this entry refers to a non-directory (directories can not have a
2291 	 * link count > 1) and it was added in the transaction that was not
2292 	 * committed, make sure we fixup the link count of the inode the entry
2293 	 * points to. Otherwise something like the following would result in a
2294 	 * directory pointing to an inode with a wrong link that does not account
2295 	 * for this dir entry:
2296 	 *
2297 	 * mkdir testdir
2298 	 * touch testdir/foo
2299 	 * touch testdir/bar
2300 	 * sync
2301 	 *
2302 	 * ln testdir/bar testdir/bar_link
2303 	 * ln testdir/foo testdir/foo_link
2304 	 * xfs_io -c "fsync" testdir/bar
2305 	 *
2306 	 * <power failure>
2307 	 *
2308 	 * mount fs, log replay happens
2309 	 *
2310 	 * File foo would remain with a link count of 1 when it has two entries
2311 	 * pointing to it in the directory testdir. This would make it impossible
2312 	 * to ever delete the parent directory has it would result in stale
2313 	 * dentries that can never be deleted.
2314 	 */
2315 	if (ret == 1 && btrfs_dir_ftype(wc->log_leaf, di) != BTRFS_FT_DIR) {
2316 		struct btrfs_key di_key;
2317 
2318 		btrfs_dir_item_key_to_cpu(wc->log_leaf, di, &di_key);
2319 		ret = link_to_fixup_dir(wc, di_key.objectid);
2320 	}
2321 
2322 	return ret;
2323 }
2324 
2325 /*
2326  * directory replay has two parts.  There are the standard directory
2327  * items in the log copied from the subvolume, and range items
2328  * created in the log while the subvolume was logged.
2329  *
2330  * The range items tell us which parts of the key space the log
2331  * is authoritative for.  During replay, if a key in the subvolume
2332  * directory is in a logged range item, but not actually in the log
2333  * that means it was deleted from the directory before the fsync
2334  * and should be removed.
2335  */
2336 static noinline int find_dir_range(struct btrfs_root *root,
2337 				   struct btrfs_path *path,
2338 				   u64 dirid,
2339 				   u64 *start_ret, u64 *end_ret)
2340 {
2341 	struct btrfs_key key;
2342 	u64 found_end;
2343 	struct btrfs_dir_log_item *item;
2344 	int ret;
2345 	int nritems;
2346 
2347 	if (*start_ret == (u64)-1)
2348 		return 1;
2349 
2350 	key.objectid = dirid;
2351 	key.type = BTRFS_DIR_LOG_INDEX_KEY;
2352 	key.offset = *start_ret;
2353 
2354 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2355 	if (ret < 0)
2356 		goto out;
2357 	if (ret > 0) {
2358 		if (path->slots[0] == 0)
2359 			goto out;
2360 		path->slots[0]--;
2361 	}
2362 	if (ret != 0)
2363 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2364 
2365 	if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2366 		ret = 1;
2367 		goto next;
2368 	}
2369 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2370 			      struct btrfs_dir_log_item);
2371 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2372 
2373 	if (*start_ret >= key.offset && *start_ret <= found_end) {
2374 		ret = 0;
2375 		*start_ret = key.offset;
2376 		*end_ret = found_end;
2377 		goto out;
2378 	}
2379 	ret = 1;
2380 next:
2381 	/* check the next slot in the tree to see if it is a valid item */
2382 	nritems = btrfs_header_nritems(path->nodes[0]);
2383 	path->slots[0]++;
2384 	if (path->slots[0] >= nritems) {
2385 		ret = btrfs_next_leaf(root, path);
2386 		if (ret)
2387 			goto out;
2388 	}
2389 
2390 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2391 
2392 	if (key.type != BTRFS_DIR_LOG_INDEX_KEY || key.objectid != dirid) {
2393 		ret = 1;
2394 		goto out;
2395 	}
2396 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2397 			      struct btrfs_dir_log_item);
2398 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2399 	*start_ret = key.offset;
2400 	*end_ret = found_end;
2401 	ret = 0;
2402 out:
2403 	btrfs_release_path(path);
2404 	return ret;
2405 }
2406 
2407 /*
2408  * this looks for a given directory item in the log.  If the directory
2409  * item is not in the log, the item is removed and the inode it points
2410  * to is unlinked
2411  */
2412 static noinline int check_item_in_log(struct walk_control *wc,
2413 				      struct btrfs_path *log_path,
2414 				      struct btrfs_inode *dir,
2415 				      struct btrfs_key *dir_key,
2416 				      bool force_remove)
2417 {
2418 	struct btrfs_trans_handle *trans = wc->trans;
2419 	struct btrfs_root *root = dir->root;
2420 	int ret;
2421 	struct extent_buffer *eb;
2422 	int slot;
2423 	struct btrfs_dir_item *di;
2424 	struct fscrypt_str name = { 0 };
2425 	struct btrfs_inode *inode = NULL;
2426 	struct btrfs_key location;
2427 
2428 	/*
2429 	 * Currently we only log dir index keys. Even if we replay a log created
2430 	 * by an older kernel that logged both dir index and dir item keys, all
2431 	 * we need to do is process the dir index keys, we (and our caller) can
2432 	 * safely ignore dir item keys (key type BTRFS_DIR_ITEM_KEY).
2433 	 */
2434 	ASSERT(dir_key->type == BTRFS_DIR_INDEX_KEY, "dir_key->type=%u", dir_key->type);
2435 
2436 	eb = wc->subvol_path->nodes[0];
2437 	slot = wc->subvol_path->slots[0];
2438 	di = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
2439 	ret = read_alloc_one_name(eb, di + 1, btrfs_dir_name_len(eb, di), &name);
2440 	if (ret) {
2441 		btrfs_abort_log_replay(wc, ret,
2442 		       "failed to allocate name for dir %llu index %llu root %llu",
2443 				       btrfs_ino(dir), dir_key->offset,
2444 				       btrfs_root_id(root));
2445 		goto out;
2446 	}
2447 
2448 	if (!force_remove) {
2449 		struct btrfs_dir_item *log_di;
2450 
2451 		log_di = btrfs_lookup_dir_index_item(trans, wc->log, log_path,
2452 						     dir_key->objectid,
2453 						     dir_key->offset, &name, 0);
2454 		if (IS_ERR(log_di)) {
2455 			ret = PTR_ERR(log_di);
2456 			btrfs_abort_log_replay(wc, ret,
2457 	"failed to lookup dir index item for dir %llu index %llu name %.*s root %llu",
2458 					       btrfs_ino(dir), dir_key->offset,
2459 					       name.len, name.name,
2460 					       btrfs_root_id(root));
2461 			goto out;
2462 		} else if (log_di) {
2463 			/* The dentry exists in the log, we have nothing to do. */
2464 			ret = 0;
2465 			goto out;
2466 		}
2467 	}
2468 
2469 	btrfs_dir_item_key_to_cpu(eb, di, &location);
2470 	btrfs_release_path(wc->subvol_path);
2471 	btrfs_release_path(log_path);
2472 	inode = btrfs_iget_logging(location.objectid, root);
2473 	if (IS_ERR(inode)) {
2474 		ret = PTR_ERR(inode);
2475 		inode = NULL;
2476 		btrfs_abort_log_replay(wc, ret,
2477 				       "failed to lookup inode %llu root %llu",
2478 				       location.objectid, btrfs_root_id(root));
2479 		goto out;
2480 	}
2481 
2482 	ret = link_to_fixup_dir(wc, location.objectid);
2483 	if (ret)
2484 		goto out;
2485 
2486 	inc_nlink(&inode->vfs_inode);
2487 	ret = unlink_inode_for_log_replay(wc, dir, inode, &name);
2488 	/*
2489 	 * Unlike dir item keys, dir index keys can only have one name (entry) in
2490 	 * them, as there are no key collisions since each key has a unique offset
2491 	 * (an index number), so we're done.
2492 	 */
2493 out:
2494 	btrfs_release_path(wc->subvol_path);
2495 	btrfs_release_path(log_path);
2496 	kfree(name.name);
2497 	if (inode)
2498 		iput(&inode->vfs_inode);
2499 	return ret;
2500 }
2501 
2502 static int replay_xattr_deletes(struct walk_control *wc)
2503 {
2504 	struct btrfs_trans_handle *trans = wc->trans;
2505 	struct btrfs_root *root = wc->root;
2506 	struct btrfs_root *log = wc->log;
2507 	struct btrfs_key search_key;
2508 	BTRFS_PATH_AUTO_FREE(log_path);
2509 	const u64 ino = wc->log_key.objectid;
2510 	int nritems;
2511 	int ret;
2512 
2513 	log_path = btrfs_alloc_path();
2514 	if (!log_path) {
2515 		btrfs_abort_log_replay(wc, -ENOMEM, "failed to allocate path");
2516 		return -ENOMEM;
2517 	}
2518 
2519 	search_key.objectid = ino;
2520 	search_key.type = BTRFS_XATTR_ITEM_KEY;
2521 	search_key.offset = 0;
2522 again:
2523 	ret = btrfs_search_slot(NULL, root, &search_key, wc->subvol_path, 0, 0);
2524 	if (ret < 0) {
2525 		btrfs_abort_log_replay(wc, ret,
2526 			       "failed to search xattrs for inode %llu root %llu",
2527 				       ino, btrfs_root_id(root));
2528 		goto out;
2529 	}
2530 process_leaf:
2531 	nritems = btrfs_header_nritems(wc->subvol_path->nodes[0]);
2532 	for (int i = wc->subvol_path->slots[0]; i < nritems; i++) {
2533 		struct btrfs_key key;
2534 		struct btrfs_dir_item *di;
2535 		struct btrfs_dir_item *log_di;
2536 		u32 total_size;
2537 		u32 cur;
2538 
2539 		btrfs_item_key_to_cpu(wc->subvol_path->nodes[0], &key, i);
2540 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2541 			ret = 0;
2542 			goto out;
2543 		}
2544 
2545 		di = btrfs_item_ptr(wc->subvol_path->nodes[0], i, struct btrfs_dir_item);
2546 		total_size = btrfs_item_size(wc->subvol_path->nodes[0], i);
2547 		cur = 0;
2548 		while (cur < total_size) {
2549 			u16 name_len = btrfs_dir_name_len(wc->subvol_path->nodes[0], di);
2550 			u16 data_len = btrfs_dir_data_len(wc->subvol_path->nodes[0], di);
2551 			u32 this_len = sizeof(*di) + name_len + data_len;
2552 			char *name;
2553 
2554 			name = kmalloc(name_len, GFP_NOFS);
2555 			if (!name) {
2556 				ret = -ENOMEM;
2557 				btrfs_abort_log_replay(wc, ret,
2558 				       "failed to allocate memory for name of length %u",
2559 						       name_len);
2560 				goto out;
2561 			}
2562 			read_extent_buffer(wc->subvol_path->nodes[0], name,
2563 					   (unsigned long)(di + 1), name_len);
2564 
2565 			log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2566 						    name, name_len, 0);
2567 			btrfs_release_path(log_path);
2568 			if (!log_di) {
2569 				/* Doesn't exist in log tree, so delete it. */
2570 				btrfs_release_path(wc->subvol_path);
2571 				di = btrfs_lookup_xattr(trans, root, wc->subvol_path, ino,
2572 							name, name_len, -1);
2573 				if (IS_ERR(di)) {
2574 					ret = PTR_ERR(di);
2575 					btrfs_abort_log_replay(wc, ret,
2576 		       "failed to lookup xattr with name %.*s for inode %llu root %llu",
2577 							       name_len, name, ino,
2578 							       btrfs_root_id(root));
2579 					kfree(name);
2580 					goto out;
2581 				}
2582 				ASSERT(di);
2583 				ret = btrfs_delete_one_dir_name(trans, root,
2584 								wc->subvol_path, di);
2585 				if (ret) {
2586 					btrfs_abort_log_replay(wc, ret,
2587 		       "failed to delete xattr with name %.*s for inode %llu root %llu",
2588 							       name_len, name, ino,
2589 							       btrfs_root_id(root));
2590 					kfree(name);
2591 					goto out;
2592 				}
2593 				btrfs_release_path(wc->subvol_path);
2594 				kfree(name);
2595 				search_key = key;
2596 				goto again;
2597 			}
2598 			if (IS_ERR(log_di)) {
2599 				ret = PTR_ERR(log_di);
2600 				btrfs_abort_log_replay(wc, ret,
2601 	"failed to lookup xattr in log tree with name %.*s for inode %llu root %llu",
2602 						       name_len, name, ino,
2603 						       btrfs_root_id(root));
2604 				kfree(name);
2605 				goto out;
2606 			}
2607 			kfree(name);
2608 			cur += this_len;
2609 			di = (struct btrfs_dir_item *)((char *)di + this_len);
2610 		}
2611 	}
2612 	ret = btrfs_next_leaf(root, wc->subvol_path);
2613 	if (ret > 0)
2614 		ret = 0;
2615 	else if (ret == 0)
2616 		goto process_leaf;
2617 	else
2618 		btrfs_abort_log_replay(wc, ret,
2619 			       "failed to get next leaf in subvolume root %llu",
2620 				       btrfs_root_id(root));
2621 out:
2622 	btrfs_release_path(wc->subvol_path);
2623 	return ret;
2624 }
2625 
2626 
2627 /*
2628  * deletion replay happens before we copy any new directory items
2629  * out of the log or out of backreferences from inodes.  It
2630  * scans the log to find ranges of keys that log is authoritative for,
2631  * and then scans the directory to find items in those ranges that are
2632  * not present in the log.
2633  *
2634  * Anything we don't find in the log is unlinked and removed from the
2635  * directory.
2636  */
2637 static noinline int replay_dir_deletes(struct walk_control *wc,
2638 				       u64 dirid, bool del_all)
2639 {
2640 	struct btrfs_root *root = wc->root;
2641 	struct btrfs_root *log = (del_all ? NULL : wc->log);
2642 	u64 range_start;
2643 	u64 range_end;
2644 	int ret = 0;
2645 	struct btrfs_key dir_key;
2646 	struct btrfs_key found_key;
2647 	BTRFS_PATH_AUTO_FREE(log_path);
2648 	struct btrfs_inode *dir;
2649 
2650 	dir_key.objectid = dirid;
2651 	dir_key.type = BTRFS_DIR_INDEX_KEY;
2652 	log_path = btrfs_alloc_path();
2653 	if (!log_path) {
2654 		btrfs_abort_log_replay(wc, -ENOMEM, "failed to allocate path");
2655 		return -ENOMEM;
2656 	}
2657 
2658 	dir = btrfs_iget_logging(dirid, root);
2659 	/*
2660 	 * It isn't an error if the inode isn't there, that can happen because
2661 	 * we replay the deletes before we copy in the inode item from the log.
2662 	 */
2663 	if (IS_ERR(dir)) {
2664 		ret = PTR_ERR(dir);
2665 		if (ret == -ENOENT)
2666 			ret = 0;
2667 		else
2668 			btrfs_abort_log_replay(wc, ret,
2669 			       "failed to lookup dir inode %llu root %llu",
2670 					       dirid, btrfs_root_id(root));
2671 		return ret;
2672 	}
2673 
2674 	range_start = 0;
2675 	range_end = 0;
2676 	while (1) {
2677 		if (del_all)
2678 			range_end = (u64)-1;
2679 		else {
2680 			ret = find_dir_range(log, wc->subvol_path, dirid,
2681 					     &range_start, &range_end);
2682 			if (ret < 0) {
2683 				btrfs_abort_log_replay(wc, ret,
2684 			       "failed to find range for dir %llu in log tree root %llu",
2685 						       dirid, btrfs_root_id(root));
2686 				goto out;
2687 			} else if (ret > 0) {
2688 				break;
2689 			}
2690 		}
2691 
2692 		dir_key.offset = range_start;
2693 		while (1) {
2694 			int nritems;
2695 			ret = btrfs_search_slot(NULL, root, &dir_key,
2696 						wc->subvol_path, 0, 0);
2697 			if (ret < 0) {
2698 				btrfs_abort_log_replay(wc, ret,
2699 			       "failed to search root %llu for key " BTRFS_KEY_FMT,
2700 						       btrfs_root_id(root),
2701 						       BTRFS_KEY_FMT_VALUE(&dir_key));
2702 				goto out;
2703 			}
2704 
2705 			nritems = btrfs_header_nritems(wc->subvol_path->nodes[0]);
2706 			if (wc->subvol_path->slots[0] >= nritems) {
2707 				ret = btrfs_next_leaf(root, wc->subvol_path);
2708 				if (ret == 1) {
2709 					break;
2710 				} else if (ret < 0) {
2711 					btrfs_abort_log_replay(wc, ret,
2712 				       "failed to get next leaf in subvolume root %llu",
2713 							       btrfs_root_id(root));
2714 					goto out;
2715 				}
2716 			}
2717 			btrfs_item_key_to_cpu(wc->subvol_path->nodes[0], &found_key,
2718 					      wc->subvol_path->slots[0]);
2719 			if (found_key.objectid != dirid ||
2720 			    found_key.type != dir_key.type) {
2721 				ret = 0;
2722 				goto out;
2723 			}
2724 
2725 			if (found_key.offset > range_end)
2726 				break;
2727 
2728 			ret = check_item_in_log(wc, log_path, dir, &found_key, del_all);
2729 			if (ret)
2730 				goto out;
2731 			if (found_key.offset == (u64)-1)
2732 				break;
2733 			dir_key.offset = found_key.offset + 1;
2734 		}
2735 		btrfs_release_path(wc->subvol_path);
2736 		if (range_end == (u64)-1)
2737 			break;
2738 		range_start = range_end + 1;
2739 	}
2740 	ret = 0;
2741 out:
2742 	btrfs_release_path(wc->subvol_path);
2743 	iput(&dir->vfs_inode);
2744 	return ret;
2745 }
2746 
2747 /*
2748  * the process_func used to replay items from the log tree.  This
2749  * gets called in two different stages.  The first stage just looks
2750  * for inodes and makes sure they are all copied into the subvolume.
2751  *
2752  * The second stage copies all the other item types from the log into
2753  * the subvolume.  The two stage approach is slower, but gets rid of
2754  * lots of complexity around inodes referencing other inodes that exist
2755  * only in the log (references come from either directory items or inode
2756  * back refs).
2757  */
2758 static int replay_one_buffer(struct extent_buffer *eb,
2759 			     struct walk_control *wc, u64 gen, int level)
2760 {
2761 	int nritems;
2762 	struct btrfs_tree_parent_check check = {
2763 		.transid = gen,
2764 		.level = level
2765 	};
2766 	struct btrfs_root *root = wc->root;
2767 	struct btrfs_trans_handle *trans = wc->trans;
2768 	int ret;
2769 
2770 	if (level != 0)
2771 		return 0;
2772 
2773 	/*
2774 	 * Set to NULL since it was not yet read and in case we abort log replay
2775 	 * on error, we have no valid log tree leaf to dump.
2776 	 */
2777 	wc->log_leaf = NULL;
2778 	ret = btrfs_read_extent_buffer(eb, &check);
2779 	if (ret) {
2780 		btrfs_abort_log_replay(wc, ret,
2781 		       "failed to read log tree leaf %llu for root %llu",
2782 				       eb->start, btrfs_root_id(root));
2783 		return ret;
2784 	}
2785 
2786 	ASSERT(wc->subvol_path == NULL);
2787 	wc->subvol_path = btrfs_alloc_path();
2788 	if (!wc->subvol_path) {
2789 		btrfs_abort_log_replay(wc, -ENOMEM, "failed to allocate path");
2790 		return -ENOMEM;
2791 	}
2792 
2793 	wc->log_leaf = eb;
2794 
2795 	nritems = btrfs_header_nritems(eb);
2796 	for (wc->log_slot = 0; wc->log_slot < nritems; wc->log_slot++) {
2797 		struct btrfs_inode_item *inode_item = NULL;
2798 
2799 		btrfs_item_key_to_cpu(eb, &wc->log_key, wc->log_slot);
2800 
2801 		if (wc->log_key.type == BTRFS_INODE_ITEM_KEY) {
2802 			inode_item = btrfs_item_ptr(eb, wc->log_slot,
2803 						    struct btrfs_inode_item);
2804 			/*
2805 			 * An inode with no links is either:
2806 			 *
2807 			 * 1) A tmpfile (O_TMPFILE) that got fsync'ed and never
2808 			 *    got linked before the fsync, skip it, as replaying
2809 			 *    it is pointless since it would be deleted later.
2810 			 *    We skip logging tmpfiles, but it's always possible
2811 			 *    we are replaying a log created with a kernel that
2812 			 *    used to log tmpfiles;
2813 			 *
2814 			 * 2) A non-tmpfile which got its last link deleted
2815 			 *    while holding an open fd on it and later got
2816 			 *    fsynced through that fd. We always log the
2817 			 *    parent inodes when inode->last_unlink_trans is
2818 			 *    set to the current transaction, so ignore all the
2819 			 *    inode items for this inode. We will delete the
2820 			 *    inode when processing the parent directory with
2821 			 *    replay_dir_deletes().
2822 			 */
2823 			if (btrfs_inode_nlink(eb, inode_item) == 0) {
2824 				wc->ignore_cur_inode = true;
2825 				continue;
2826 			} else {
2827 				wc->ignore_cur_inode = false;
2828 			}
2829 		}
2830 
2831 		/* Inode keys are done during the first stage. */
2832 		if (wc->log_key.type == BTRFS_INODE_ITEM_KEY &&
2833 		    wc->stage == LOG_WALK_REPLAY_INODES) {
2834 			u32 mode;
2835 
2836 			ret = replay_xattr_deletes(wc);
2837 			if (ret)
2838 				break;
2839 			mode = btrfs_inode_mode(eb, inode_item);
2840 			if (S_ISDIR(mode)) {
2841 				ret = replay_dir_deletes(wc, wc->log_key.objectid, false);
2842 				if (ret)
2843 					break;
2844 			}
2845 			ret = overwrite_item(wc);
2846 			if (ret)
2847 				break;
2848 
2849 			/*
2850 			 * Before replaying extents, truncate the inode to its
2851 			 * size. We need to do it now and not after log replay
2852 			 * because before an fsync we can have prealloc extents
2853 			 * added beyond the inode's i_size. If we did it after,
2854 			 * through orphan cleanup for example, we would drop
2855 			 * those prealloc extents just after replaying them.
2856 			 */
2857 			if (S_ISREG(mode)) {
2858 				struct btrfs_drop_extents_args drop_args = { 0 };
2859 				struct btrfs_inode *inode;
2860 				u64 from;
2861 
2862 				inode = btrfs_iget_logging(wc->log_key.objectid, root);
2863 				if (IS_ERR(inode)) {
2864 					ret = PTR_ERR(inode);
2865 					btrfs_abort_log_replay(wc, ret,
2866 					       "failed to lookup inode %llu root %llu",
2867 							       wc->log_key.objectid,
2868 							       btrfs_root_id(root));
2869 					break;
2870 				}
2871 				from = ALIGN(i_size_read(&inode->vfs_inode),
2872 					     root->fs_info->sectorsize);
2873 				drop_args.start = from;
2874 				drop_args.end = (u64)-1;
2875 				drop_args.drop_cache = true;
2876 				drop_args.path = wc->subvol_path;
2877 				ret = btrfs_drop_extents(trans, root, inode,  &drop_args);
2878 				if (ret) {
2879 					btrfs_abort_log_replay(wc, ret,
2880 		       "failed to drop extents for inode %llu root %llu offset %llu",
2881 							       btrfs_ino(inode),
2882 							       btrfs_root_id(root),
2883 							       from);
2884 				} else {
2885 					inode_sub_bytes(&inode->vfs_inode,
2886 							drop_args.bytes_found);
2887 					/* Update the inode's nbytes. */
2888 					ret = btrfs_update_inode(trans, inode);
2889 					if (ret)
2890 						btrfs_abort_log_replay(wc, ret,
2891 					       "failed to update inode %llu root %llu",
2892 								       btrfs_ino(inode),
2893 								       btrfs_root_id(root));
2894 				}
2895 				iput(&inode->vfs_inode);
2896 				if (ret)
2897 					break;
2898 			}
2899 
2900 			ret = link_to_fixup_dir(wc, wc->log_key.objectid);
2901 			if (ret)
2902 				break;
2903 		}
2904 
2905 		if (wc->ignore_cur_inode)
2906 			continue;
2907 
2908 		if (wc->log_key.type == BTRFS_DIR_INDEX_KEY &&
2909 		    wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2910 			ret = replay_one_dir_item(wc);
2911 			if (ret)
2912 				break;
2913 		}
2914 
2915 		if (wc->stage < LOG_WALK_REPLAY_ALL)
2916 			continue;
2917 
2918 		/* these keys are simply copied */
2919 		if (wc->log_key.type == BTRFS_XATTR_ITEM_KEY) {
2920 			ret = overwrite_item(wc);
2921 			if (ret)
2922 				break;
2923 		} else if (wc->log_key.type == BTRFS_INODE_REF_KEY ||
2924 			   wc->log_key.type == BTRFS_INODE_EXTREF_KEY) {
2925 			ret = add_inode_ref(wc);
2926 			if (ret)
2927 				break;
2928 		} else if (wc->log_key.type == BTRFS_EXTENT_DATA_KEY) {
2929 			ret = replay_one_extent(wc);
2930 			if (ret)
2931 				break;
2932 		}
2933 		/*
2934 		 * We don't log BTRFS_DIR_ITEM_KEY keys anymore, only the
2935 		 * BTRFS_DIR_INDEX_KEY items which we use to derive the
2936 		 * BTRFS_DIR_ITEM_KEY items. If we are replaying a log from an
2937 		 * older kernel with such keys, ignore them.
2938 		 */
2939 	}
2940 	btrfs_free_path(wc->subvol_path);
2941 	wc->subvol_path = NULL;
2942 	return ret;
2943 }
2944 
2945 static int clean_log_buffer(struct btrfs_trans_handle *trans,
2946 			    struct extent_buffer *eb)
2947 {
2948 	struct btrfs_fs_info *fs_info = eb->fs_info;
2949 	struct btrfs_block_group *bg;
2950 
2951 	btrfs_tree_lock(eb);
2952 	btrfs_clear_buffer_dirty(trans, eb);
2953 	wait_on_extent_buffer_writeback(eb);
2954 	btrfs_tree_unlock(eb);
2955 
2956 	if (trans) {
2957 		int ret;
2958 
2959 		ret = btrfs_pin_reserved_extent(trans, eb);
2960 		if (ret)
2961 			btrfs_abort_transaction(trans, ret);
2962 		return ret;
2963 	}
2964 
2965 	bg = btrfs_lookup_block_group(fs_info, eb->start);
2966 	if (!bg) {
2967 		btrfs_err(fs_info, "unable to find block group for %llu", eb->start);
2968 		btrfs_handle_fs_error(fs_info, -ENOENT, NULL);
2969 		return -ENOENT;
2970 	}
2971 
2972 	spin_lock(&bg->space_info->lock);
2973 	spin_lock(&bg->lock);
2974 	bg->reserved -= fs_info->nodesize;
2975 	bg->space_info->bytes_reserved -= fs_info->nodesize;
2976 	spin_unlock(&bg->lock);
2977 	spin_unlock(&bg->space_info->lock);
2978 
2979 	btrfs_put_block_group(bg);
2980 
2981 	return 0;
2982 }
2983 
2984 static noinline int walk_down_log_tree(struct btrfs_path *path, int *level,
2985 				       struct walk_control *wc)
2986 {
2987 	struct btrfs_trans_handle *trans = wc->trans;
2988 	struct btrfs_fs_info *fs_info = wc->log->fs_info;
2989 	u64 bytenr;
2990 	u64 ptr_gen;
2991 	struct extent_buffer *next;
2992 	struct extent_buffer *cur;
2993 	int ret = 0;
2994 
2995 	while (*level > 0) {
2996 		struct btrfs_tree_parent_check check = { 0 };
2997 
2998 		cur = path->nodes[*level];
2999 
3000 		WARN_ON(btrfs_header_level(cur) != *level);
3001 
3002 		if (path->slots[*level] >=
3003 		    btrfs_header_nritems(cur))
3004 			break;
3005 
3006 		bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
3007 		ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
3008 		check.transid = ptr_gen;
3009 		check.level = *level - 1;
3010 		check.has_first_key = true;
3011 		btrfs_node_key_to_cpu(cur, &check.first_key, path->slots[*level]);
3012 
3013 		next = btrfs_find_create_tree_block(fs_info, bytenr,
3014 						    btrfs_header_owner(cur),
3015 						    *level - 1);
3016 		if (IS_ERR(next)) {
3017 			ret = PTR_ERR(next);
3018 			if (trans)
3019 				btrfs_abort_transaction(trans, ret);
3020 			else
3021 				btrfs_handle_fs_error(fs_info, ret, NULL);
3022 			return ret;
3023 		}
3024 
3025 		if (*level == 1) {
3026 			ret = wc->process_func(next, wc, ptr_gen, *level - 1);
3027 			if (ret) {
3028 				free_extent_buffer(next);
3029 				return ret;
3030 			}
3031 
3032 			path->slots[*level]++;
3033 			if (wc->free) {
3034 				ret = btrfs_read_extent_buffer(next, &check);
3035 				if (ret) {
3036 					free_extent_buffer(next);
3037 					if (trans)
3038 						btrfs_abort_transaction(trans, ret);
3039 					else
3040 						btrfs_handle_fs_error(fs_info, ret, NULL);
3041 					return ret;
3042 				}
3043 
3044 				ret = clean_log_buffer(trans, next);
3045 				if (ret) {
3046 					free_extent_buffer(next);
3047 					return ret;
3048 				}
3049 			}
3050 			free_extent_buffer(next);
3051 			continue;
3052 		}
3053 		ret = btrfs_read_extent_buffer(next, &check);
3054 		if (ret) {
3055 			free_extent_buffer(next);
3056 			if (trans)
3057 				btrfs_abort_transaction(trans, ret);
3058 			else
3059 				btrfs_handle_fs_error(fs_info, ret, NULL);
3060 			return ret;
3061 		}
3062 
3063 		if (path->nodes[*level-1])
3064 			free_extent_buffer(path->nodes[*level-1]);
3065 		path->nodes[*level-1] = next;
3066 		*level = btrfs_header_level(next);
3067 		path->slots[*level] = 0;
3068 		cond_resched();
3069 	}
3070 	path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
3071 
3072 	cond_resched();
3073 	return 0;
3074 }
3075 
3076 static noinline int walk_up_log_tree(struct btrfs_path *path, int *level,
3077 				     struct walk_control *wc)
3078 {
3079 	int i;
3080 	int slot;
3081 	int ret;
3082 
3083 	for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
3084 		slot = path->slots[i];
3085 		if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
3086 			path->slots[i]++;
3087 			*level = i;
3088 			WARN_ON(*level == 0);
3089 			return 0;
3090 		} else {
3091 			ret = wc->process_func(path->nodes[*level], wc,
3092 				 btrfs_header_generation(path->nodes[*level]),
3093 				 *level);
3094 			if (ret)
3095 				return ret;
3096 
3097 			if (wc->free) {
3098 				ret = clean_log_buffer(wc->trans, path->nodes[*level]);
3099 				if (ret)
3100 					return ret;
3101 			}
3102 			free_extent_buffer(path->nodes[*level]);
3103 			path->nodes[*level] = NULL;
3104 			*level = i + 1;
3105 		}
3106 	}
3107 	return 1;
3108 }
3109 
3110 /*
3111  * drop the reference count on the tree rooted at 'snap'.  This traverses
3112  * the tree freeing any blocks that have a ref count of zero after being
3113  * decremented.
3114  */
3115 static int walk_log_tree(struct walk_control *wc)
3116 {
3117 	struct btrfs_root *log = wc->log;
3118 	int ret = 0;
3119 	int wret;
3120 	int level;
3121 	BTRFS_PATH_AUTO_FREE(path);
3122 	int orig_level;
3123 
3124 	path = btrfs_alloc_path();
3125 	if (!path)
3126 		return -ENOMEM;
3127 
3128 	level = btrfs_header_level(log->node);
3129 	orig_level = level;
3130 	path->nodes[level] = log->node;
3131 	refcount_inc(&log->node->refs);
3132 	path->slots[level] = 0;
3133 
3134 	while (1) {
3135 		wret = walk_down_log_tree(path, &level, wc);
3136 		if (wret > 0)
3137 			break;
3138 		if (wret < 0)
3139 			return wret;
3140 
3141 		wret = walk_up_log_tree(path, &level, wc);
3142 		if (wret > 0)
3143 			break;
3144 		if (wret < 0)
3145 			return wret;
3146 	}
3147 
3148 	/* was the root node processed? if not, catch it here */
3149 	if (path->nodes[orig_level]) {
3150 		ret = wc->process_func(path->nodes[orig_level], wc,
3151 			 btrfs_header_generation(path->nodes[orig_level]),
3152 			 orig_level);
3153 		if (ret)
3154 			return ret;
3155 		if (wc->free)
3156 			ret = clean_log_buffer(wc->trans, path->nodes[orig_level]);
3157 	}
3158 
3159 	return ret;
3160 }
3161 
3162 /*
3163  * helper function to update the item for a given subvolumes log root
3164  * in the tree of log roots
3165  */
3166 static int update_log_root(struct btrfs_trans_handle *trans,
3167 			   struct btrfs_root *log,
3168 			   struct btrfs_root_item *root_item)
3169 {
3170 	struct btrfs_fs_info *fs_info = log->fs_info;
3171 	int ret;
3172 
3173 	if (log->log_transid == 1) {
3174 		/* insert root item on the first sync */
3175 		ret = btrfs_insert_root(trans, fs_info->log_root_tree,
3176 				&log->root_key, root_item);
3177 	} else {
3178 		ret = btrfs_update_root(trans, fs_info->log_root_tree,
3179 				&log->root_key, root_item);
3180 	}
3181 	return ret;
3182 }
3183 
3184 static void wait_log_commit(struct btrfs_root *root, int transid)
3185 {
3186 	DEFINE_WAIT(wait);
3187 	int index = transid % 2;
3188 
3189 	/*
3190 	 * we only allow two pending log transactions at a time,
3191 	 * so we know that if ours is more than 2 older than the
3192 	 * current transaction, we're done
3193 	 */
3194 	for (;;) {
3195 		prepare_to_wait(&root->log_commit_wait[index],
3196 				&wait, TASK_UNINTERRUPTIBLE);
3197 
3198 		if (!(root->log_transid_committed < transid &&
3199 		      atomic_read(&root->log_commit[index])))
3200 			break;
3201 
3202 		mutex_unlock(&root->log_mutex);
3203 		schedule();
3204 		mutex_lock(&root->log_mutex);
3205 	}
3206 	finish_wait(&root->log_commit_wait[index], &wait);
3207 }
3208 
3209 static void wait_for_writer(struct btrfs_root *root)
3210 {
3211 	DEFINE_WAIT(wait);
3212 
3213 	for (;;) {
3214 		prepare_to_wait(&root->log_writer_wait, &wait,
3215 				TASK_UNINTERRUPTIBLE);
3216 		if (!atomic_read(&root->log_writers))
3217 			break;
3218 
3219 		mutex_unlock(&root->log_mutex);
3220 		schedule();
3221 		mutex_lock(&root->log_mutex);
3222 	}
3223 	finish_wait(&root->log_writer_wait, &wait);
3224 }
3225 
3226 void btrfs_init_log_ctx(struct btrfs_log_ctx *ctx, struct btrfs_inode *inode)
3227 {
3228 	ctx->log_ret = 0;
3229 	ctx->log_transid = 0;
3230 	ctx->log_new_dentries = false;
3231 	ctx->logging_new_name = false;
3232 	ctx->logging_new_delayed_dentries = false;
3233 	ctx->logged_before = false;
3234 	ctx->inode = inode;
3235 	INIT_LIST_HEAD(&ctx->list);
3236 	INIT_LIST_HEAD(&ctx->ordered_extents);
3237 	INIT_LIST_HEAD(&ctx->conflict_inodes);
3238 	ctx->num_conflict_inodes = 0;
3239 	ctx->logging_conflict_inodes = false;
3240 	ctx->scratch_eb = NULL;
3241 }
3242 
3243 void btrfs_init_log_ctx_scratch_eb(struct btrfs_log_ctx *ctx)
3244 {
3245 	struct btrfs_inode *inode = ctx->inode;
3246 
3247 	if (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) &&
3248 	    !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
3249 		return;
3250 
3251 	/*
3252 	 * Don't care about allocation failure. This is just for optimization,
3253 	 * if we fail to allocate here, we will try again later if needed.
3254 	 */
3255 	ctx->scratch_eb = alloc_dummy_extent_buffer(inode->root->fs_info, 0);
3256 }
3257 
3258 void btrfs_release_log_ctx_extents(struct btrfs_log_ctx *ctx)
3259 {
3260 	struct btrfs_ordered_extent *ordered;
3261 	struct btrfs_ordered_extent *tmp;
3262 
3263 	btrfs_assert_inode_locked(ctx->inode);
3264 
3265 	list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
3266 		list_del_init(&ordered->log_list);
3267 		btrfs_put_ordered_extent(ordered);
3268 	}
3269 }
3270 
3271 
3272 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
3273 					struct btrfs_log_ctx *ctx)
3274 {
3275 	mutex_lock(&root->log_mutex);
3276 	list_del_init(&ctx->list);
3277 	mutex_unlock(&root->log_mutex);
3278 }
3279 
3280 /*
3281  * Invoked in log mutex context, or be sure there is no other task which
3282  * can access the list.
3283  */
3284 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
3285 					     int index, int error)
3286 {
3287 	struct btrfs_log_ctx *ctx;
3288 	struct btrfs_log_ctx *safe;
3289 
3290 	list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
3291 		list_del_init(&ctx->list);
3292 		ctx->log_ret = error;
3293 	}
3294 }
3295 
3296 /*
3297  * Sends a given tree log down to the disk and updates the super blocks to
3298  * record it.  When this call is done, you know that any inodes previously
3299  * logged are safely on disk only if it returns 0.
3300  *
3301  * Any other return value means you need to call btrfs_commit_transaction.
3302  * Some of the edge cases for fsyncing directories that have had unlinks
3303  * or renames done in the past mean that sometimes the only safe
3304  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
3305  * that has happened.
3306  */
3307 int btrfs_sync_log(struct btrfs_trans_handle *trans,
3308 		   struct btrfs_root *root, struct btrfs_log_ctx *ctx)
3309 {
3310 	int index1;
3311 	int index2;
3312 	int mark;
3313 	int ret;
3314 	struct btrfs_fs_info *fs_info = root->fs_info;
3315 	struct btrfs_root *log = root->log_root;
3316 	struct btrfs_root *log_root_tree = fs_info->log_root_tree;
3317 	struct btrfs_root_item new_root_item;
3318 	int log_transid = 0;
3319 	struct btrfs_log_ctx root_log_ctx;
3320 	struct blk_plug plug;
3321 	u64 log_root_start;
3322 	u64 log_root_level;
3323 
3324 	mutex_lock(&root->log_mutex);
3325 	trace_btrfs_sync_log_enter(trans, root, ctx);
3326 	log_transid = ctx->log_transid;
3327 	if (root->log_transid_committed >= log_transid) {
3328 		trace_btrfs_sync_log_exit(trans, root, ctx, ctx->log_ret);
3329 		mutex_unlock(&root->log_mutex);
3330 		return ctx->log_ret;
3331 	}
3332 
3333 	index1 = log_transid % 2;
3334 	if (atomic_read(&root->log_commit[index1])) {
3335 		wait_log_commit(root, log_transid);
3336 		trace_btrfs_sync_log_exit(trans, root, ctx, ctx->log_ret);
3337 		mutex_unlock(&root->log_mutex);
3338 		return ctx->log_ret;
3339 	}
3340 	ASSERT(log_transid == root->log_transid,
3341 	       "log_transid=%d root->log_transid=%d", log_transid, root->log_transid);
3342 	atomic_set(&root->log_commit[index1], 1);
3343 
3344 	/* wait for previous tree log sync to complete */
3345 	if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
3346 		wait_log_commit(root, log_transid - 1);
3347 
3348 	while (1) {
3349 		int batch = atomic_read(&root->log_batch);
3350 		/* when we're on an ssd, just kick the log commit out */
3351 		if (!btrfs_test_opt(fs_info, SSD) &&
3352 		    test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
3353 			mutex_unlock(&root->log_mutex);
3354 			schedule_timeout_uninterruptible(1);
3355 			mutex_lock(&root->log_mutex);
3356 		}
3357 		wait_for_writer(root);
3358 		if (batch == atomic_read(&root->log_batch))
3359 			break;
3360 	}
3361 
3362 	/* bail out if we need to do a full commit */
3363 	if (btrfs_need_log_full_commit(trans)) {
3364 		ret = BTRFS_LOG_FORCE_COMMIT;
3365 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3366 		mutex_unlock(&root->log_mutex);
3367 		goto out;
3368 	}
3369 
3370 	if (log_transid % 2 == 0)
3371 		mark = EXTENT_DIRTY_LOG1;
3372 	else
3373 		mark = EXTENT_DIRTY_LOG2;
3374 
3375 	/* we start IO on  all the marked extents here, but we don't actually
3376 	 * wait for them until later.
3377 	 */
3378 	blk_start_plug(&plug);
3379 	ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
3380 	/*
3381 	 * -EAGAIN happens when someone, e.g., a concurrent transaction
3382 	 *  commit, writes a dirty extent in this tree-log commit. This
3383 	 *  concurrent write will create a hole writing out the extents,
3384 	 *  and we cannot proceed on a zoned filesystem, requiring
3385 	 *  sequential writing. While we can bail out to a full commit
3386 	 *  here, but we can continue hoping the concurrent writing fills
3387 	 *  the hole.
3388 	 */
3389 	if (ret == -EAGAIN && btrfs_is_zoned(fs_info))
3390 		ret = 0;
3391 	if (ret) {
3392 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3393 		blk_finish_plug(&plug);
3394 		btrfs_set_log_full_commit(trans);
3395 		mutex_unlock(&root->log_mutex);
3396 		goto out;
3397 	}
3398 
3399 	/*
3400 	 * We _must_ update under the root->log_mutex in order to make sure we
3401 	 * have a consistent view of the log root we are trying to commit at
3402 	 * this moment.
3403 	 *
3404 	 * We _must_ copy this into a local copy, because we are not holding the
3405 	 * log_root_tree->log_mutex yet.  This is important because when we
3406 	 * commit the log_root_tree we must have a consistent view of the
3407 	 * log_root_tree when we update the super block to point at the
3408 	 * log_root_tree bytenr.  If we update the log_root_tree here we'll race
3409 	 * with the commit and possibly point at the new block which we may not
3410 	 * have written out.
3411 	 */
3412 	btrfs_set_root_node(&log->root_item, log->node);
3413 	memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3414 
3415 	btrfs_set_root_log_transid(root, root->log_transid + 1);
3416 	log->log_transid = root->log_transid;
3417 	root->log_start_pid = 0;
3418 	/*
3419 	 * IO has been started, blocks of the log tree have WRITTEN flag set
3420 	 * in their headers. new modifications of the log will be written to
3421 	 * new positions. so it's safe to allow log writers to go in.
3422 	 */
3423 	mutex_unlock(&root->log_mutex);
3424 
3425 	if (btrfs_is_zoned(fs_info)) {
3426 		mutex_lock(&fs_info->tree_root->log_mutex);
3427 		if (!log_root_tree->node) {
3428 			ret = btrfs_alloc_log_tree_node(trans, log_root_tree);
3429 			if (ret) {
3430 				trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3431 				mutex_unlock(&fs_info->tree_root->log_mutex);
3432 				blk_finish_plug(&plug);
3433 				goto out;
3434 			}
3435 		}
3436 		mutex_unlock(&fs_info->tree_root->log_mutex);
3437 	}
3438 
3439 	btrfs_init_log_ctx(&root_log_ctx, NULL);
3440 
3441 	mutex_lock(&log_root_tree->log_mutex);
3442 
3443 	index2 = log_root_tree->log_transid % 2;
3444 	list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3445 	root_log_ctx.log_transid = log_root_tree->log_transid;
3446 
3447 	/*
3448 	 * Now we are safe to update the log_root_tree because we're under the
3449 	 * log_mutex, and we're a current writer so we're holding the commit
3450 	 * open until we drop the log_mutex.
3451 	 */
3452 	ret = update_log_root(trans, log, &new_root_item);
3453 	if (ret) {
3454 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3455 		list_del_init(&root_log_ctx.list);
3456 		blk_finish_plug(&plug);
3457 		btrfs_set_log_full_commit(trans);
3458 		if (ret != -ENOSPC)
3459 			btrfs_err(fs_info,
3460 				  "failed to update log for root %llu ret %d",
3461 				  btrfs_root_id(root), ret);
3462 		btrfs_wait_tree_log_extents(log, mark);
3463 		mutex_unlock(&log_root_tree->log_mutex);
3464 		goto out;
3465 	}
3466 
3467 	if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3468 		blk_finish_plug(&plug);
3469 		list_del_init(&root_log_ctx.list);
3470 		mutex_unlock(&log_root_tree->log_mutex);
3471 		ret = root_log_ctx.log_ret;
3472 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3473 		goto out;
3474 	}
3475 
3476 	if (atomic_read(&log_root_tree->log_commit[index2])) {
3477 		blk_finish_plug(&plug);
3478 		ret = btrfs_wait_tree_log_extents(log, mark);
3479 		wait_log_commit(log_root_tree,
3480 				root_log_ctx.log_transid);
3481 		mutex_unlock(&log_root_tree->log_mutex);
3482 		if (!ret)
3483 			ret = root_log_ctx.log_ret;
3484 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3485 		goto out;
3486 	}
3487 	ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid,
3488 	       "root_log_ctx.log_transid=%d log_root_tree->log_transid=%d",
3489 		root_log_ctx.log_transid, log_root_tree->log_transid);
3490 	atomic_set(&log_root_tree->log_commit[index2], 1);
3491 
3492 	if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3493 		wait_log_commit(log_root_tree,
3494 				root_log_ctx.log_transid - 1);
3495 	}
3496 
3497 	/*
3498 	 * now that we've moved on to the tree of log tree roots,
3499 	 * check the full commit flag again
3500 	 */
3501 	if (btrfs_need_log_full_commit(trans)) {
3502 		blk_finish_plug(&plug);
3503 		btrfs_wait_tree_log_extents(log, mark);
3504 		mutex_unlock(&log_root_tree->log_mutex);
3505 		ret = BTRFS_LOG_FORCE_COMMIT;
3506 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3507 		goto out_wake_log_root;
3508 	}
3509 
3510 	ret = btrfs_write_marked_extents(fs_info,
3511 					 &log_root_tree->dirty_log_pages,
3512 					 EXTENT_DIRTY_LOG1 | EXTENT_DIRTY_LOG2);
3513 	blk_finish_plug(&plug);
3514 	/*
3515 	 * As described above, -EAGAIN indicates a hole in the extents. We
3516 	 * cannot wait for these write outs since the waiting cause a
3517 	 * deadlock. Bail out to the full commit instead.
3518 	 */
3519 	if (ret == -EAGAIN && btrfs_is_zoned(fs_info)) {
3520 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3521 		btrfs_set_log_full_commit(trans);
3522 		btrfs_wait_tree_log_extents(log, mark);
3523 		mutex_unlock(&log_root_tree->log_mutex);
3524 		goto out_wake_log_root;
3525 	} else if (ret) {
3526 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3527 		btrfs_set_log_full_commit(trans);
3528 		mutex_unlock(&log_root_tree->log_mutex);
3529 		goto out_wake_log_root;
3530 	}
3531 	ret = btrfs_wait_tree_log_extents(log, mark);
3532 	if (!ret)
3533 		ret = btrfs_wait_tree_log_extents(log_root_tree,
3534 						  EXTENT_DIRTY_LOG1 | EXTENT_DIRTY_LOG2);
3535 	if (ret) {
3536 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3537 		btrfs_set_log_full_commit(trans);
3538 		mutex_unlock(&log_root_tree->log_mutex);
3539 		goto out_wake_log_root;
3540 	}
3541 
3542 	log_root_start = log_root_tree->node->start;
3543 	log_root_level = btrfs_header_level(log_root_tree->node);
3544 	log_root_tree->log_transid++;
3545 	mutex_unlock(&log_root_tree->log_mutex);
3546 
3547 	/*
3548 	 * Here we are guaranteed that nobody is going to write the superblock
3549 	 * for the current transaction before us and that neither we do write
3550 	 * our superblock before the previous transaction finishes its commit
3551 	 * and writes its superblock, because:
3552 	 *
3553 	 * 1) We are holding a handle on the current transaction, so no body
3554 	 *    can commit it until we release the handle;
3555 	 *
3556 	 * 2) Before writing our superblock we acquire the tree_log_mutex, so
3557 	 *    if the previous transaction is still committing, and hasn't yet
3558 	 *    written its superblock, we wait for it to do it, because a
3559 	 *    transaction commit acquires the tree_log_mutex when the commit
3560 	 *    begins and releases it only after writing its superblock.
3561 	 */
3562 	mutex_lock(&fs_info->tree_log_mutex);
3563 
3564 	/*
3565 	 * The previous transaction writeout phase could have failed, and thus
3566 	 * marked the fs in an error state.  We must not commit here, as we
3567 	 * could have updated our generation in the super_for_commit and
3568 	 * writing the super here would result in transid mismatches.  If there
3569 	 * is an error here just bail.
3570 	 */
3571 	if (unlikely(BTRFS_FS_ERROR(fs_info))) {
3572 		ret = -EIO;
3573 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3574 		btrfs_set_log_full_commit(trans);
3575 		btrfs_abort_transaction(trans, ret);
3576 		mutex_unlock(&fs_info->tree_log_mutex);
3577 		goto out_wake_log_root;
3578 	}
3579 
3580 	btrfs_set_super_log_root(fs_info->super_for_commit, log_root_start);
3581 	btrfs_set_super_log_root_level(fs_info->super_for_commit, log_root_level);
3582 	ret = write_all_supers(trans);
3583 	mutex_unlock(&fs_info->tree_log_mutex);
3584 	if (unlikely(ret)) {
3585 		trace_btrfs_sync_log_exit(trans, root, ctx, ret);
3586 		btrfs_set_log_full_commit(trans);
3587 		btrfs_abort_transaction(trans, ret);
3588 		goto out_wake_log_root;
3589 	}
3590 
3591 	/*
3592 	 * We know there can only be one task here, since we have not yet set
3593 	 * root->log_commit[index1] to 0 and any task attempting to sync the
3594 	 * log must wait for the previous log transaction to commit if it's
3595 	 * still in progress or wait for the current log transaction commit if
3596 	 * someone else already started it. We use <= and not < because the
3597 	 * first log transaction has an ID of 0.
3598 	 */
3599 	ASSERT(btrfs_get_root_last_log_commit(root) <= log_transid,
3600 	       "last_log_commit(root)=%d log_transid=%d",
3601 	       btrfs_get_root_last_log_commit(root), log_transid);
3602 	btrfs_set_root_last_log_commit(root, log_transid);
3603 
3604 out_wake_log_root:
3605 	mutex_lock(&log_root_tree->log_mutex);
3606 	btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3607 
3608 	log_root_tree->log_transid_committed++;
3609 	atomic_set(&log_root_tree->log_commit[index2], 0);
3610 	mutex_unlock(&log_root_tree->log_mutex);
3611 
3612 	/*
3613 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3614 	 * all the updates above are seen by the woken threads. It might not be
3615 	 * necessary, but proving that seems to be hard.
3616 	 */
3617 	cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3618 out:
3619 	mutex_lock(&root->log_mutex);
3620 	btrfs_remove_all_log_ctxs(root, index1, ret);
3621 	root->log_transid_committed++;
3622 	atomic_set(&root->log_commit[index1], 0);
3623 	mutex_unlock(&root->log_mutex);
3624 
3625 	/*
3626 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3627 	 * all the updates above are seen by the woken threads. It might not be
3628 	 * necessary, but proving that seems to be hard.
3629 	 */
3630 	cond_wake_up(&root->log_commit_wait[index1]);
3631 	return ret;
3632 }
3633 
3634 static void free_log_tree(struct btrfs_trans_handle *trans,
3635 			  struct btrfs_root *log)
3636 {
3637 	int ret;
3638 	struct walk_control wc = {
3639 		.free = true,
3640 		.process_func = process_one_buffer,
3641 		.log = log,
3642 		.trans = trans,
3643 	};
3644 
3645 	if (log->node) {
3646 		ret = walk_log_tree(&wc);
3647 		if (ret) {
3648 			/*
3649 			 * We weren't able to traverse the entire log tree, the
3650 			 * typical scenario is getting an -EIO when reading an
3651 			 * extent buffer of the tree, due to a previous writeback
3652 			 * failure of it.
3653 			 */
3654 			set_bit(BTRFS_FS_STATE_LOG_CLEANUP_ERROR,
3655 				&log->fs_info->fs_state);
3656 
3657 			/*
3658 			 * Some extent buffers of the log tree may still be dirty
3659 			 * and not yet written back to storage, because we may
3660 			 * have updates to a log tree without syncing a log tree,
3661 			 * such as during rename and link operations. So flush
3662 			 * them out and wait for their writeback to complete, so
3663 			 * that we properly cleanup their state and pages.
3664 			 */
3665 			btrfs_write_marked_extents(log->fs_info,
3666 						   &log->dirty_log_pages,
3667 						   EXTENT_DIRTY_LOG1 | EXTENT_DIRTY_LOG2);
3668 			btrfs_wait_tree_log_extents(log,
3669 						    EXTENT_DIRTY_LOG1 | EXTENT_DIRTY_LOG2);
3670 
3671 			if (trans)
3672 				btrfs_abort_transaction(trans, ret);
3673 			else
3674 				btrfs_handle_fs_error(log->fs_info, ret, NULL);
3675 		}
3676 	}
3677 
3678 	btrfs_extent_io_tree_release(&log->dirty_log_pages);
3679 	btrfs_extent_io_tree_release(&log->log_csum_range);
3680 
3681 	btrfs_put_root(log);
3682 }
3683 
3684 /*
3685  * free all the extents used by the tree log.  This should be called
3686  * at commit time of the full transaction
3687  */
3688 void btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3689 {
3690 	if (root->log_root) {
3691 		free_log_tree(trans, root->log_root);
3692 		root->log_root = NULL;
3693 		clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &root->state);
3694 	}
3695 }
3696 
3697 void btrfs_free_log_root_tree(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info)
3698 {
3699 	if (fs_info->log_root_tree) {
3700 		free_log_tree(trans, fs_info->log_root_tree);
3701 		fs_info->log_root_tree = NULL;
3702 		clear_bit(BTRFS_ROOT_HAS_LOG_TREE, &fs_info->tree_root->state);
3703 	}
3704 }
3705 
3706 static bool mark_inode_as_not_logged(const struct btrfs_trans_handle *trans,
3707 				     struct btrfs_inode *inode)
3708 {
3709 	bool ret = false;
3710 
3711 	/*
3712 	 * Do this only if ->logged_trans is still 0 to prevent races with
3713 	 * concurrent logging as we may see the inode not logged when
3714 	 * inode_logged() is called but it gets logged after inode_logged() did
3715 	 * not find it in the log tree and we end up setting ->logged_trans to a
3716 	 * value less than trans->transid after the concurrent logging task has
3717 	 * set it to trans->transid. As a consequence, subsequent rename, unlink
3718 	 * and link operations may end up not logging new names and removing old
3719 	 * names from the log.
3720 	 */
3721 	spin_lock(&inode->lock);
3722 	if (inode->logged_trans == 0)
3723 		inode->logged_trans = trans->transid - 1;
3724 	else if (inode->logged_trans == trans->transid)
3725 		ret = true;
3726 	spin_unlock(&inode->lock);
3727 
3728 	return ret;
3729 }
3730 
3731 /*
3732  * Check if an inode was logged in the current transaction. This correctly deals
3733  * with the case where the inode was logged but has a logged_trans of 0, which
3734  * happens if the inode is evicted and loaded again, as logged_trans is an in
3735  * memory only field (not persisted).
3736  *
3737  * Returns 1 if the inode was logged before in the transaction, 0 if it was not,
3738  * and < 0 on error.
3739  */
3740 static int inode_logged(const struct btrfs_trans_handle *trans,
3741 			struct btrfs_inode *inode,
3742 			struct btrfs_path *path_in)
3743 {
3744 	struct btrfs_path *path = path_in;
3745 	struct btrfs_key key;
3746 	int ret;
3747 
3748 	/*
3749 	 * Quick lockless call, since once ->logged_trans is set to the current
3750 	 * transaction, we never set it to a lower value anywhere else.
3751 	 */
3752 	if (data_race(inode->logged_trans) == trans->transid)
3753 		return 1;
3754 
3755 	/*
3756 	 * If logged_trans is not 0 and not trans->transid, then we know the
3757 	 * inode was not logged in this transaction, so we can return false
3758 	 * right away. We take the lock to avoid a race caused by load/store
3759 	 * tearing with a concurrent btrfs_log_inode() call or a concurrent task
3760 	 * in this function further below - an update to trans->transid can be
3761 	 * teared into two 32 bits updates for example, in which case we could
3762 	 * see a positive value that is not trans->transid and assume the inode
3763 	 * was not logged when it was.
3764 	 */
3765 	spin_lock(&inode->lock);
3766 	if (inode->logged_trans == trans->transid) {
3767 		spin_unlock(&inode->lock);
3768 		return 1;
3769 	} else if (inode->logged_trans > 0) {
3770 		spin_unlock(&inode->lock);
3771 		return 0;
3772 	}
3773 	spin_unlock(&inode->lock);
3774 
3775 	/*
3776 	 * If no log tree was created for this root in this transaction, then
3777 	 * the inode can not have been logged in this transaction. In that case
3778 	 * set logged_trans to anything greater than 0 and less than the current
3779 	 * transaction's ID, to avoid the search below in a future call in case
3780 	 * a log tree gets created after this.
3781 	 */
3782 	if (!test_bit(BTRFS_ROOT_HAS_LOG_TREE, &inode->root->state))
3783 		return mark_inode_as_not_logged(trans, inode);
3784 
3785 	/*
3786 	 * We have a log tree and the inode's logged_trans is 0. We can't tell
3787 	 * for sure if the inode was logged before in this transaction by looking
3788 	 * only at logged_trans. We could be pessimistic and assume it was, but
3789 	 * that can lead to unnecessarily logging an inode during rename and link
3790 	 * operations, and then further updating the log in followup rename and
3791 	 * link operations, specially if it's a directory, which adds latency
3792 	 * visible to applications doing a series of rename or link operations.
3793 	 *
3794 	 * A logged_trans of 0 here can mean several things:
3795 	 *
3796 	 * 1) The inode was never logged since the filesystem was mounted, and may
3797 	 *    or may have not been evicted and loaded again;
3798 	 *
3799 	 * 2) The inode was logged in a previous transaction, then evicted and
3800 	 *    then loaded again;
3801 	 *
3802 	 * 3) The inode was logged in the current transaction, then evicted and
3803 	 *    then loaded again.
3804 	 *
3805 	 * For cases 1) and 2) we don't want to return true, but we need to detect
3806 	 * case 3) and return true. So we do a search in the log root for the inode
3807 	 * item.
3808 	 */
3809 	key.objectid = btrfs_ino(inode);
3810 	key.type = BTRFS_INODE_ITEM_KEY;
3811 	key.offset = 0;
3812 
3813 	if (!path) {
3814 		path = btrfs_alloc_path();
3815 		if (!path)
3816 			return -ENOMEM;
3817 	}
3818 
3819 	ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
3820 
3821 	if (path_in)
3822 		btrfs_release_path(path);
3823 	else
3824 		btrfs_free_path(path);
3825 
3826 	/*
3827 	 * Logging an inode always results in logging its inode item. So if we
3828 	 * did not find the item we know the inode was not logged for sure.
3829 	 */
3830 	if (ret < 0) {
3831 		return ret;
3832 	} else if (ret > 0) {
3833 		/*
3834 		 * Set logged_trans to a value greater than 0 and less then the
3835 		 * current transaction to avoid doing the search in future calls.
3836 		 */
3837 		return mark_inode_as_not_logged(trans, inode);
3838 	}
3839 
3840 	/*
3841 	 * The inode was previously logged and then evicted, set logged_trans to
3842 	 * the current transaction's ID, to avoid future tree searches as long as
3843 	 * the inode is not evicted again.
3844 	 */
3845 	spin_lock(&inode->lock);
3846 	inode->logged_trans = trans->transid;
3847 	spin_unlock(&inode->lock);
3848 
3849 	return 1;
3850 }
3851 
3852 /*
3853  * Delete a directory entry from the log if it exists.
3854  *
3855  * Returns < 0 on error
3856  *           1 if the entry does not exists
3857  *           0 if the entry existed and was successfully deleted
3858  */
3859 static int del_logged_dentry(struct btrfs_trans_handle *trans,
3860 			     struct btrfs_root *log,
3861 			     struct btrfs_path *path,
3862 			     u64 dir_ino,
3863 			     const struct fscrypt_str *name,
3864 			     u64 index)
3865 {
3866 	struct btrfs_dir_item *di;
3867 
3868 	/*
3869 	 * We only log dir index items of a directory, so we don't need to look
3870 	 * for dir item keys.
3871 	 */
3872 	di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3873 					 index, name, -1);
3874 	if (IS_ERR(di))
3875 		return PTR_ERR(di);
3876 	else if (!di)
3877 		return 1;
3878 
3879 	/*
3880 	 * We do not need to update the size field of the directory's
3881 	 * inode item because on log replay we update the field to reflect
3882 	 * all existing entries in the directory (see overwrite_item()).
3883 	 */
3884 	return btrfs_del_item(trans, log, path);
3885 }
3886 
3887 /*
3888  * If both a file and directory are logged, and unlinks or renames are
3889  * mixed in, we have a few interesting corners:
3890  *
3891  * create file X in dir Y
3892  * link file X to X.link in dir Y
3893  * fsync file X
3894  * unlink file X but leave X.link
3895  * fsync dir Y
3896  *
3897  * After a crash we would expect only X.link to exist.  But file X
3898  * didn't get fsync'd again so the log has back refs for X and X.link.
3899  *
3900  * We solve this by removing directory entries and inode backrefs from the
3901  * log when a file that was logged in the current transaction is
3902  * unlinked.  Any later fsync will include the updated log entries, and
3903  * we'll be able to reconstruct the proper directory items from backrefs.
3904  *
3905  * This optimizations allows us to avoid relogging the entire inode
3906  * or the entire directory.
3907  */
3908 void btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3909 				  const struct fscrypt_str *name,
3910 				  struct btrfs_inode *dir, u64 index)
3911 {
3912 	struct btrfs_root *root = dir->root;
3913 	BTRFS_PATH_AUTO_FREE(path);
3914 	int ret;
3915 
3916 	ret = inode_logged(trans, dir, NULL);
3917 	if (ret == 0)
3918 		return;
3919 	if (ret < 0) {
3920 		btrfs_set_log_full_commit(trans);
3921 		return;
3922 	}
3923 
3924 	path = btrfs_alloc_path();
3925 	if (!path) {
3926 		btrfs_set_log_full_commit(trans);
3927 		return;
3928 	}
3929 
3930 	ret = join_running_log_trans(root);
3931 	ASSERT(ret == 0, "join_running_log_trans() ret=%d", ret);
3932 	if (WARN_ON(ret))
3933 		return;
3934 
3935 	mutex_lock(&dir->log_mutex);
3936 
3937 	ret = del_logged_dentry(trans, root->log_root, path, btrfs_ino(dir),
3938 				name, index);
3939 	mutex_unlock(&dir->log_mutex);
3940 	if (ret < 0)
3941 		btrfs_set_log_full_commit(trans);
3942 	btrfs_end_log_trans(root);
3943 }
3944 
3945 /* see comments for btrfs_del_dir_entries_in_log */
3946 void btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3947 				const struct fscrypt_str *name,
3948 				struct btrfs_inode *inode,
3949 				struct btrfs_inode *dir)
3950 {
3951 	struct btrfs_root *root = dir->root;
3952 	int ret;
3953 
3954 	ret = inode_logged(trans, inode, NULL);
3955 	if (ret == 0)
3956 		return;
3957 	else if (ret < 0) {
3958 		btrfs_set_log_full_commit(trans);
3959 		return;
3960 	}
3961 
3962 	ret = join_running_log_trans(root);
3963 	ASSERT(ret == 0, "join_running_log_trans() ret=%d", ret);
3964 	if (WARN_ON(ret))
3965 		return;
3966 	mutex_lock(&inode->log_mutex);
3967 
3968 	ret = btrfs_del_inode_ref(trans, root->log_root, name, btrfs_ino(inode),
3969 				  btrfs_ino(dir), NULL);
3970 	mutex_unlock(&inode->log_mutex);
3971 	if (ret < 0 && ret != -ENOENT)
3972 		btrfs_set_log_full_commit(trans);
3973 	btrfs_end_log_trans(root);
3974 }
3975 
3976 /*
3977  * creates a range item in the log for 'dirid'.  first_offset and
3978  * last_offset tell us which parts of the key space the log should
3979  * be considered authoritative for.
3980  */
3981 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3982 				       struct btrfs_root *log,
3983 				       struct btrfs_path *path,
3984 				       u64 dirid,
3985 				       u64 first_offset, u64 last_offset)
3986 {
3987 	int ret;
3988 	struct btrfs_key key;
3989 	struct btrfs_dir_log_item *item;
3990 
3991 	key.objectid = dirid;
3992 	key.type = BTRFS_DIR_LOG_INDEX_KEY;
3993 	key.offset = first_offset;
3994 	ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3995 	/*
3996 	 * -EEXIST is fine and can happen sporadically when we are logging a
3997 	 * directory and have concurrent insertions in the subvolume's tree for
3998 	 * items from other inodes and that result in pushing off some dir items
3999 	 * from one leaf to another in order to accommodate for the new items.
4000 	 * This results in logging the same dir index range key.
4001 	 */
4002 	if (ret && ret != -EEXIST)
4003 		return ret;
4004 
4005 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4006 			      struct btrfs_dir_log_item);
4007 	if (ret == -EEXIST) {
4008 		const u64 curr_end = btrfs_dir_log_end(path->nodes[0], item);
4009 
4010 		/*
4011 		 * btrfs_del_dir_entries_in_log() might have been called during
4012 		 * an unlink between the initial insertion of this key and the
4013 		 * current update, or we might be logging a single entry deletion
4014 		 * during a rename, so set the new last_offset to the max value.
4015 		 */
4016 		last_offset = max(last_offset, curr_end);
4017 	}
4018 	btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
4019 	btrfs_release_path(path);
4020 	return 0;
4021 }
4022 
4023 static int flush_dir_items_batch(struct btrfs_trans_handle *trans,
4024 				 struct btrfs_inode *inode,
4025 				 struct extent_buffer *src,
4026 				 struct btrfs_path *dst_path,
4027 				 int start_slot,
4028 				 int count)
4029 {
4030 	struct btrfs_root *log = inode->root->log_root;
4031 	char AUTO_KFREE(ins_data);
4032 	struct btrfs_item_batch batch;
4033 	struct extent_buffer *dst;
4034 	unsigned long src_offset;
4035 	unsigned long dst_offset;
4036 	u64 last_index;
4037 	struct btrfs_key key;
4038 	u32 item_size;
4039 	int ret;
4040 	int i;
4041 
4042 	ASSERT(count > 0, "count=%d", count);
4043 	batch.nr = count;
4044 
4045 	if (count == 1) {
4046 		btrfs_item_key_to_cpu(src, &key, start_slot);
4047 		item_size = btrfs_item_size(src, start_slot);
4048 		batch.keys = &key;
4049 		batch.data_sizes = &item_size;
4050 		batch.total_data_size = item_size;
4051 	} else {
4052 		struct btrfs_key *ins_keys;
4053 		u32 *ins_sizes;
4054 
4055 		ins_data = kmalloc_array(count, sizeof(u32) + sizeof(struct btrfs_key), GFP_NOFS);
4056 		if (!ins_data)
4057 			return -ENOMEM;
4058 
4059 		ins_sizes = (u32 *)ins_data;
4060 		ins_keys = (struct btrfs_key *)(ins_data + count * sizeof(u32));
4061 		batch.keys = ins_keys;
4062 		batch.data_sizes = ins_sizes;
4063 		batch.total_data_size = 0;
4064 
4065 		for (i = 0; i < count; i++) {
4066 			const int slot = start_slot + i;
4067 
4068 			btrfs_item_key_to_cpu(src, &ins_keys[i], slot);
4069 			ins_sizes[i] = btrfs_item_size(src, slot);
4070 			batch.total_data_size += ins_sizes[i];
4071 		}
4072 	}
4073 
4074 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4075 	if (ret)
4076 		return ret;
4077 
4078 	dst = dst_path->nodes[0];
4079 	/*
4080 	 * Copy all the items in bulk, in a single copy operation. Item data is
4081 	 * organized such that it's placed at the end of a leaf and from right
4082 	 * to left. For example, the data for the second item ends at an offset
4083 	 * that matches the offset where the data for the first item starts, the
4084 	 * data for the third item ends at an offset that matches the offset
4085 	 * where the data of the second items starts, and so on.
4086 	 * Therefore our source and destination start offsets for copy match the
4087 	 * offsets of the last items (highest slots).
4088 	 */
4089 	dst_offset = btrfs_item_ptr_offset(dst, dst_path->slots[0] + count - 1);
4090 	src_offset = btrfs_item_ptr_offset(src, start_slot + count - 1);
4091 	copy_extent_buffer(dst, src, dst_offset, src_offset, batch.total_data_size);
4092 	btrfs_release_path(dst_path);
4093 
4094 	last_index = batch.keys[count - 1].offset;
4095 	ASSERT(last_index > inode->last_dir_index_offset,
4096 	       "last_index=%llu inode->last_dir_index_offset=%llu",
4097 	       last_index, inode->last_dir_index_offset);
4098 
4099 	/*
4100 	 * If for some unexpected reason the last item's index is not greater
4101 	 * than the last index we logged, warn and force a transaction commit.
4102 	 */
4103 	if (WARN_ON(last_index <= inode->last_dir_index_offset))
4104 		ret = BTRFS_LOG_FORCE_COMMIT;
4105 	else
4106 		inode->last_dir_index_offset = last_index;
4107 
4108 	if (btrfs_get_first_dir_index_to_log(inode) == 0)
4109 		btrfs_set_first_dir_index_to_log(inode, batch.keys[0].offset);
4110 
4111 	return ret;
4112 }
4113 
4114 static int clone_leaf(struct btrfs_path *path, struct btrfs_log_ctx *ctx)
4115 {
4116 	const int slot = path->slots[0];
4117 
4118 	if (ctx->scratch_eb) {
4119 		copy_extent_buffer_full(ctx->scratch_eb, path->nodes[0]);
4120 	} else {
4121 		ctx->scratch_eb = btrfs_clone_extent_buffer(path->nodes[0]);
4122 		if (!ctx->scratch_eb)
4123 			return -ENOMEM;
4124 	}
4125 
4126 	btrfs_release_path(path);
4127 	path->nodes[0] = ctx->scratch_eb;
4128 	path->slots[0] = slot;
4129 	/*
4130 	 * Add extra ref to scratch eb so that it is not freed when callers
4131 	 * release the path, so we can reuse it later if needed.
4132 	 */
4133 	refcount_inc(&ctx->scratch_eb->refs);
4134 
4135 	return 0;
4136 }
4137 
4138 static int process_dir_items_leaf(struct btrfs_trans_handle *trans,
4139 				  struct btrfs_inode *inode,
4140 				  struct btrfs_path *path,
4141 				  struct btrfs_path *dst_path,
4142 				  struct btrfs_log_ctx *ctx,
4143 				  u64 *last_old_dentry_offset)
4144 {
4145 	struct btrfs_root *log = inode->root->log_root;
4146 	struct extent_buffer *src;
4147 	const int nritems = btrfs_header_nritems(path->nodes[0]);
4148 	const u64 ino = btrfs_ino(inode);
4149 	bool last_found = false;
4150 	int batch_start = 0;
4151 	int batch_size = 0;
4152 	int ret;
4153 
4154 	/*
4155 	 * We need to clone the leaf, release the read lock on it, and use the
4156 	 * clone before modifying the log tree. See the comment at copy_items()
4157 	 * about why we need to do this.
4158 	 */
4159 	ret = clone_leaf(path, ctx);
4160 	if (ret < 0)
4161 		return ret;
4162 
4163 	src = path->nodes[0];
4164 
4165 	for (int i = path->slots[0]; i < nritems; i++) {
4166 		struct btrfs_dir_item *di;
4167 		struct btrfs_key key;
4168 
4169 		btrfs_item_key_to_cpu(src, &key, i);
4170 
4171 		if (key.objectid != ino || key.type != BTRFS_DIR_INDEX_KEY) {
4172 			last_found = true;
4173 			break;
4174 		}
4175 
4176 		di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
4177 
4178 		/*
4179 		 * Skip ranges of items that consist only of dir item keys created
4180 		 * in past transactions. However if we find a gap, we must log a
4181 		 * dir index range item for that gap, so that index keys in that
4182 		 * gap are deleted during log replay.
4183 		 */
4184 		if (btrfs_dir_transid(src, di) < trans->transid) {
4185 			if (key.offset > *last_old_dentry_offset + 1) {
4186 				ret = insert_dir_log_key(trans, log, dst_path,
4187 						 ino, *last_old_dentry_offset + 1,
4188 						 key.offset - 1);
4189 				if (ret < 0)
4190 					return ret;
4191 			}
4192 
4193 			*last_old_dentry_offset = key.offset;
4194 			continue;
4195 		}
4196 
4197 		/* If we logged this dir index item before, we can skip it. */
4198 		if (key.offset <= inode->last_dir_index_offset)
4199 			continue;
4200 
4201 		/*
4202 		 * We must make sure that when we log a directory entry, the
4203 		 * corresponding inode, after log replay, has a matching link
4204 		 * count. For example:
4205 		 *
4206 		 * touch foo
4207 		 * mkdir mydir
4208 		 * sync
4209 		 * ln foo mydir/bar
4210 		 * xfs_io -c "fsync" mydir
4211 		 * <crash>
4212 		 * <mount fs and log replay>
4213 		 *
4214 		 * Would result in a fsync log that when replayed, our file inode
4215 		 * would have a link count of 1, but we get two directory entries
4216 		 * pointing to the same inode. After removing one of the names,
4217 		 * it would not be possible to remove the other name, which
4218 		 * resulted always in stale file handle errors, and would not be
4219 		 * possible to rmdir the parent directory, since its i_size could
4220 		 * never be decremented to the value BTRFS_EMPTY_DIR_SIZE,
4221 		 * resulting in -ENOTEMPTY errors.
4222 		 */
4223 		if (!ctx->log_new_dentries) {
4224 			struct btrfs_key di_key;
4225 
4226 			btrfs_dir_item_key_to_cpu(src, di, &di_key);
4227 			if (di_key.type != BTRFS_ROOT_ITEM_KEY)
4228 				ctx->log_new_dentries = true;
4229 		}
4230 
4231 		if (batch_size == 0)
4232 			batch_start = i;
4233 		batch_size++;
4234 	}
4235 
4236 	if (batch_size > 0) {
4237 		ret = flush_dir_items_batch(trans, inode, src, dst_path,
4238 					    batch_start, batch_size);
4239 		if (ret < 0)
4240 			return ret;
4241 	}
4242 
4243 	return last_found ? 1 : 0;
4244 }
4245 
4246 /*
4247  * log all the items included in the current transaction for a given
4248  * directory.  This also creates the range items in the log tree required
4249  * to replay anything deleted before the fsync
4250  */
4251 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
4252 			  struct btrfs_inode *inode,
4253 			  struct btrfs_path *path,
4254 			  struct btrfs_path *dst_path,
4255 			  struct btrfs_log_ctx *ctx,
4256 			  u64 min_offset, u64 *last_offset_ret)
4257 {
4258 	struct btrfs_key min_key;
4259 	struct btrfs_root *root = inode->root;
4260 	struct btrfs_root *log = root->log_root;
4261 	int ret;
4262 	u64 last_old_dentry_offset = min_offset - 1;
4263 	u64 last_offset = (u64)-1;
4264 	u64 ino = btrfs_ino(inode);
4265 
4266 	min_key.objectid = ino;
4267 	min_key.type = BTRFS_DIR_INDEX_KEY;
4268 	min_key.offset = min_offset;
4269 
4270 	ret = btrfs_search_forward(root, &min_key, path, trans->transid);
4271 
4272 	/*
4273 	 * we didn't find anything from this transaction, see if there
4274 	 * is anything at all
4275 	 */
4276 	if (ret != 0 || min_key.objectid != ino ||
4277 	    min_key.type != BTRFS_DIR_INDEX_KEY) {
4278 		min_key.objectid = ino;
4279 		min_key.type = BTRFS_DIR_INDEX_KEY;
4280 		min_key.offset = (u64)-1;
4281 		btrfs_release_path(path);
4282 		ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
4283 		if (ret < 0) {
4284 			btrfs_release_path(path);
4285 			return ret;
4286 		}
4287 		ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
4288 
4289 		/* if ret == 0 there are items for this type,
4290 		 * create a range to tell us the last key of this type.
4291 		 * otherwise, there are no items in this directory after
4292 		 * *min_offset, and we create a range to indicate that.
4293 		 */
4294 		if (ret == 0) {
4295 			struct btrfs_key tmp;
4296 
4297 			btrfs_item_key_to_cpu(path->nodes[0], &tmp,
4298 					      path->slots[0]);
4299 			if (tmp.type == BTRFS_DIR_INDEX_KEY)
4300 				last_old_dentry_offset = tmp.offset;
4301 		} else if (ret > 0) {
4302 			ret = 0;
4303 		}
4304 
4305 		goto done;
4306 	}
4307 
4308 	/* go backward to find any previous key */
4309 	ret = btrfs_previous_item(root, path, ino, BTRFS_DIR_INDEX_KEY);
4310 	if (ret == 0) {
4311 		struct btrfs_key tmp;
4312 
4313 		btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
4314 		/*
4315 		 * The dir index key before the first one we found that needs to
4316 		 * be logged might be in a previous leaf, and there might be a
4317 		 * gap between these keys, meaning that we had deletions that
4318 		 * happened. So the key range item we log (key type
4319 		 * BTRFS_DIR_LOG_INDEX_KEY) must cover a range that starts at the
4320 		 * previous key's offset plus 1, so that those deletes are replayed.
4321 		 */
4322 		if (tmp.type == BTRFS_DIR_INDEX_KEY)
4323 			last_old_dentry_offset = tmp.offset;
4324 	} else if (ret < 0) {
4325 		goto done;
4326 	}
4327 
4328 	btrfs_release_path(path);
4329 
4330 	/*
4331 	 * Find the first key from this transaction again or the one we were at
4332 	 * in the loop below in case we had to reschedule. We may be logging the
4333 	 * directory without holding its VFS lock, which happen when logging new
4334 	 * dentries (through log_new_dir_dentries()) or in some cases when we
4335 	 * need to log the parent directory of an inode. This means a dir index
4336 	 * key might be deleted from the inode's root, and therefore we may not
4337 	 * find it anymore. If we can't find it, just move to the next key. We
4338 	 * can not bail out and ignore, because if we do that we will simply
4339 	 * not log dir index keys that come after the one that was just deleted
4340 	 * and we can end up logging a dir index range that ends at (u64)-1
4341 	 * (@last_offset is initialized to that), resulting in removing dir
4342 	 * entries we should not remove at log replay time.
4343 	 */
4344 search:
4345 	ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
4346 	if (ret > 0) {
4347 		ret = btrfs_next_item(root, path);
4348 		if (ret > 0) {
4349 			/* There are no more keys in the inode's root. */
4350 			ret = 0;
4351 			goto done;
4352 		}
4353 	}
4354 	if (ret < 0)
4355 		goto done;
4356 
4357 	/*
4358 	 * we have a block from this transaction, log every item in it
4359 	 * from our directory
4360 	 */
4361 	while (1) {
4362 		ret = process_dir_items_leaf(trans, inode, path, dst_path, ctx,
4363 					     &last_old_dentry_offset);
4364 		if (ret != 0) {
4365 			if (ret > 0)
4366 				ret = 0;
4367 			goto done;
4368 		}
4369 		path->slots[0] = btrfs_header_nritems(path->nodes[0]);
4370 
4371 		/*
4372 		 * look ahead to the next item and see if it is also
4373 		 * from this directory and from this transaction
4374 		 */
4375 		ret = btrfs_next_leaf(root, path);
4376 		if (ret) {
4377 			if (ret == 1) {
4378 				last_offset = (u64)-1;
4379 				ret = 0;
4380 			}
4381 			goto done;
4382 		}
4383 		btrfs_item_key_to_cpu(path->nodes[0], &min_key, path->slots[0]);
4384 		if (min_key.objectid != ino || min_key.type != BTRFS_DIR_INDEX_KEY) {
4385 			last_offset = (u64)-1;
4386 			goto done;
4387 		}
4388 		if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
4389 			/*
4390 			 * The next leaf was not changed in the current transaction
4391 			 * and has at least one dir index key.
4392 			 * We check for the next key because there might have been
4393 			 * one or more deletions between the last key we logged and
4394 			 * that next key. So the key range item we log (key type
4395 			 * BTRFS_DIR_LOG_INDEX_KEY) must end at the next key's
4396 			 * offset minus 1, so that those deletes are replayed.
4397 			 */
4398 			last_offset = min_key.offset - 1;
4399 			goto done;
4400 		}
4401 		if (need_resched()) {
4402 			btrfs_release_path(path);
4403 			cond_resched();
4404 			goto search;
4405 		}
4406 	}
4407 done:
4408 	btrfs_release_path(path);
4409 	btrfs_release_path(dst_path);
4410 
4411 	if (ret == 0) {
4412 		*last_offset_ret = last_offset;
4413 		/*
4414 		 * In case the leaf was changed in the current transaction but
4415 		 * all its dir items are from a past transaction, the last item
4416 		 * in the leaf is a dir item and there's no gap between that last
4417 		 * dir item and the first one on the next leaf (which did not
4418 		 * change in the current transaction), then we don't need to log
4419 		 * a range, last_old_dentry_offset is == to last_offset.
4420 		 */
4421 		ASSERT(last_old_dentry_offset <= last_offset,
4422 		       "last_old_dentry_offset=%llu last_offset=%llu",
4423 		       last_old_dentry_offset, last_offset);
4424 		if (last_old_dentry_offset < last_offset)
4425 			ret = insert_dir_log_key(trans, log, path, ino,
4426 						 last_old_dentry_offset + 1,
4427 						 last_offset);
4428 	}
4429 
4430 	return ret;
4431 }
4432 
4433 /*
4434  * If the inode was logged before and it was evicted, then its
4435  * last_dir_index_offset is 0, so we don't know the value of the last index
4436  * key offset. If that's the case, search for it and update the inode. This
4437  * is to avoid lookups in the log tree every time we try to insert a dir index
4438  * key from a leaf changed in the current transaction, and to allow us to always
4439  * do batch insertions of dir index keys.
4440  */
4441 static int update_last_dir_index_offset(struct btrfs_inode *inode,
4442 					struct btrfs_path *path,
4443 					const struct btrfs_log_ctx *ctx)
4444 {
4445 	const u64 ino = btrfs_ino(inode);
4446 	struct btrfs_key key;
4447 	int ret;
4448 
4449 	lockdep_assert_held(&inode->log_mutex);
4450 
4451 	if (inode->last_dir_index_offset != 0)
4452 		return 0;
4453 
4454 	if (!ctx->logged_before) {
4455 		inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
4456 		return 0;
4457 	}
4458 
4459 	key.objectid = ino;
4460 	key.type = BTRFS_DIR_INDEX_KEY;
4461 	key.offset = (u64)-1;
4462 
4463 	ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
4464 	/*
4465 	 * An error happened or we actually have an index key with an offset
4466 	 * value of (u64)-1. Bail out, we're done.
4467 	 */
4468 	if (ret <= 0)
4469 		goto out;
4470 
4471 	ret = 0;
4472 	inode->last_dir_index_offset = BTRFS_DIR_START_INDEX - 1;
4473 
4474 	/*
4475 	 * No dir index items, bail out and leave last_dir_index_offset with
4476 	 * the value right before the first valid index value.
4477 	 */
4478 	if (path->slots[0] == 0)
4479 		goto out;
4480 
4481 	/*
4482 	 * btrfs_search_slot() left us at one slot beyond the slot with the last
4483 	 * index key, or beyond the last key of the directory that is not an
4484 	 * index key. If we have an index key before, set last_dir_index_offset
4485 	 * to its offset value, otherwise leave it with a value right before the
4486 	 * first valid index value, as it means we have an empty directory.
4487 	 */
4488 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
4489 	if (key.objectid == ino && key.type == BTRFS_DIR_INDEX_KEY)
4490 		inode->last_dir_index_offset = key.offset;
4491 
4492 out:
4493 	btrfs_release_path(path);
4494 
4495 	return ret;
4496 }
4497 
4498 /*
4499  * logging directories is very similar to logging inodes, We find all the items
4500  * from the current transaction and write them to the log.
4501  *
4502  * The recovery code scans the directory in the subvolume, and if it finds a
4503  * key in the range logged that is not present in the log tree, then it means
4504  * that dir entry was unlinked during the transaction.
4505  *
4506  * In order for that scan to work, we must include one key smaller than
4507  * the smallest logged by this transaction and one key larger than the largest
4508  * key logged by this transaction.
4509  */
4510 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
4511 			  struct btrfs_inode *inode,
4512 			  struct btrfs_path *path,
4513 			  struct btrfs_path *dst_path,
4514 			  struct btrfs_log_ctx *ctx)
4515 {
4516 	u64 min_key;
4517 	u64 max_key;
4518 	int ret;
4519 
4520 	ret = update_last_dir_index_offset(inode, path, ctx);
4521 	if (ret)
4522 		return ret;
4523 
4524 	min_key = BTRFS_DIR_START_INDEX;
4525 	max_key = 0;
4526 
4527 	while (1) {
4528 		ret = log_dir_items(trans, inode, path, dst_path,
4529 				ctx, min_key, &max_key);
4530 		if (ret)
4531 			return ret;
4532 		if (max_key == (u64)-1)
4533 			break;
4534 		min_key = max_key + 1;
4535 	}
4536 
4537 	return 0;
4538 }
4539 
4540 /*
4541  * a helper function to drop items from the log before we relog an
4542  * inode.  max_key_type indicates the highest item type to remove.
4543  * This cannot be run for file data extents because it does not
4544  * free the extents they point to.
4545  */
4546 static int drop_inode_items(struct btrfs_trans_handle *trans,
4547 				  struct btrfs_root *log,
4548 				  struct btrfs_path *path,
4549 				  struct btrfs_inode *inode,
4550 				  int max_key_type)
4551 {
4552 	int ret;
4553 	struct btrfs_key key;
4554 	struct btrfs_key found_key;
4555 	int start_slot;
4556 
4557 	key.objectid = btrfs_ino(inode);
4558 	key.type = max_key_type;
4559 	key.offset = (u64)-1;
4560 
4561 	while (1) {
4562 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
4563 		if (ret < 0) {
4564 			break;
4565 		} else if (ret > 0) {
4566 			if (path->slots[0] == 0)
4567 				break;
4568 			path->slots[0]--;
4569 		}
4570 
4571 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4572 				      path->slots[0]);
4573 
4574 		if (found_key.objectid != key.objectid)
4575 			break;
4576 
4577 		found_key.offset = 0;
4578 		found_key.type = 0;
4579 		ret = btrfs_bin_search(path->nodes[0], 0, &found_key, &start_slot);
4580 		if (ret < 0)
4581 			break;
4582 
4583 		ret = btrfs_del_items(trans, log, path, start_slot,
4584 				      path->slots[0] - start_slot + 1);
4585 		/*
4586 		 * If start slot isn't 0 then we don't need to re-search, we've
4587 		 * found the last guy with the objectid in this tree.
4588 		 */
4589 		if (ret || start_slot != 0)
4590 			break;
4591 		btrfs_release_path(path);
4592 	}
4593 	btrfs_release_path(path);
4594 	if (ret > 0)
4595 		ret = 0;
4596 	return ret;
4597 }
4598 
4599 static int truncate_inode_items(struct btrfs_trans_handle *trans,
4600 				struct btrfs_root *log_root,
4601 				struct btrfs_inode *inode,
4602 				u64 new_size, u32 min_type)
4603 {
4604 	struct btrfs_truncate_control control = {
4605 		.new_size = new_size,
4606 		.ino = btrfs_ino(inode),
4607 		.min_type = min_type,
4608 		.skip_ref_updates = true,
4609 	};
4610 
4611 	return btrfs_truncate_inode_items(trans, log_root, &control);
4612 }
4613 
4614 static void fill_inode_item(struct btrfs_trans_handle *trans,
4615 			    struct extent_buffer *leaf,
4616 			    struct btrfs_inode_item *item,
4617 			    struct btrfs_inode *inode, bool log_inode_only,
4618 			    u64 logged_isize)
4619 {
4620 	struct inode *vfs_inode = &inode->vfs_inode;
4621 	u64 gen = inode->generation;
4622 	u64 flags;
4623 
4624 	if (log_inode_only) {
4625 		/*
4626 		 * Set the generation to zero so the recover code can tell the
4627 		 * difference between a logging just to say 'this inode exists'
4628 		 * and a logging to say 'update this inode with these values'.
4629 		 * But only if the inode was not already logged before.
4630 		 * We access ->logged_trans directly since it was already set
4631 		 * up in the call chain by btrfs_log_inode(), and data_race()
4632 		 * to avoid false alerts from KCSAN and since it was set already
4633 		 * and one can set it to 0 since that only happens on eviction
4634 		 * and we are holding a ref on the inode.
4635 		 */
4636 		ASSERT(data_race(inode->logged_trans) > 0);
4637 		if (data_race(inode->logged_trans) < trans->transid)
4638 			gen = 0;
4639 
4640 		btrfs_set_inode_size(leaf, item, logged_isize);
4641 	} else {
4642 		btrfs_set_inode_size(leaf, item, vfs_inode->i_size);
4643 	}
4644 
4645 	btrfs_set_inode_generation(leaf, item, gen);
4646 
4647 	btrfs_set_inode_uid(leaf, item, i_uid_read(vfs_inode));
4648 	btrfs_set_inode_gid(leaf, item, i_gid_read(vfs_inode));
4649 	btrfs_set_inode_mode(leaf, item, vfs_inode->i_mode);
4650 	btrfs_set_inode_nlink(leaf, item, vfs_inode->i_nlink);
4651 
4652 	btrfs_set_timespec_sec(leaf, &item->atime, inode_get_atime_sec(vfs_inode));
4653 	btrfs_set_timespec_nsec(leaf, &item->atime, inode_get_atime_nsec(vfs_inode));
4654 
4655 	btrfs_set_timespec_sec(leaf, &item->mtime, inode_get_mtime_sec(vfs_inode));
4656 	btrfs_set_timespec_nsec(leaf, &item->mtime, inode_get_mtime_nsec(vfs_inode));
4657 
4658 	btrfs_set_timespec_sec(leaf, &item->ctime, inode_get_ctime_sec(vfs_inode));
4659 	btrfs_set_timespec_nsec(leaf, &item->ctime, inode_get_ctime_nsec(vfs_inode));
4660 
4661 	btrfs_set_timespec_sec(leaf, &item->otime, inode->i_otime_sec);
4662 	btrfs_set_timespec_nsec(leaf, &item->otime, inode->i_otime_nsec);
4663 
4664 	/*
4665 	 * We do not need to set the nbytes field, in fact during a fast fsync
4666 	 * its value may not even be correct, since a fast fsync does not wait
4667 	 * for ordered extent completion, which is where we update nbytes, it
4668 	 * only waits for writeback to complete. During log replay as we find
4669 	 * file extent items and replay them, we adjust the nbytes field of the
4670 	 * inode item in subvolume tree as needed (see overwrite_item()).
4671 	 */
4672 
4673 	btrfs_set_inode_sequence(leaf, item, inode_peek_iversion(vfs_inode));
4674 	btrfs_set_inode_transid(leaf, item, trans->transid);
4675 	btrfs_set_inode_rdev(leaf, item, vfs_inode->i_rdev);
4676 	flags = btrfs_inode_combine_flags(inode->flags, inode->ro_flags);
4677 	btrfs_set_inode_flags(leaf, item, flags);
4678 	btrfs_set_inode_block_group(leaf, item, 0);
4679 }
4680 
4681 static int log_inode_item(struct btrfs_trans_handle *trans,
4682 			  struct btrfs_root *log, struct btrfs_path *path,
4683 			  struct btrfs_inode *inode, bool inode_item_dropped)
4684 {
4685 	struct btrfs_inode_item *inode_item;
4686 	struct btrfs_key key;
4687 	int ret;
4688 
4689 	btrfs_get_inode_key(inode, &key);
4690 	/*
4691 	 * If we are doing a fast fsync and the inode was logged before in the
4692 	 * current transaction, then we know the inode was previously logged and
4693 	 * it exists in the log tree. For performance reasons, in this case use
4694 	 * btrfs_search_slot() directly with ins_len set to 0 so that we never
4695 	 * attempt a write lock on the leaf's parent, which adds unnecessary lock
4696 	 * contention in case there are concurrent fsyncs for other inodes of the
4697 	 * same subvolume. Using btrfs_insert_empty_item() when the inode item
4698 	 * already exists can also result in unnecessarily splitting a leaf.
4699 	 */
4700 	if (!inode_item_dropped && inode->logged_trans == trans->transid) {
4701 		ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
4702 		ASSERT(ret <= 0);
4703 		if (ret > 0)
4704 			ret = -ENOENT;
4705 	} else {
4706 		/*
4707 		 * This means it is the first fsync in the current transaction,
4708 		 * so the inode item is not in the log and we need to insert it.
4709 		 * We can never get -EEXIST because we are only called for a fast
4710 		 * fsync and in case an inode eviction happens after the inode was
4711 		 * logged before in the current transaction, when we load again
4712 		 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
4713 		 * flags and set ->logged_trans to 0.
4714 		 */
4715 		ret = btrfs_insert_empty_item(trans, log, path, &key,
4716 					      sizeof(*inode_item));
4717 		ASSERT(ret != -EEXIST);
4718 	}
4719 	if (ret)
4720 		return ret;
4721 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4722 				    struct btrfs_inode_item);
4723 	fill_inode_item(trans, path->nodes[0], inode_item, inode, false, 0);
4724 	btrfs_release_path(path);
4725 	return 0;
4726 }
4727 
4728 static int log_csums(struct btrfs_trans_handle *trans,
4729 		     struct btrfs_inode *inode,
4730 		     struct btrfs_root *log_root,
4731 		     struct btrfs_ordered_sum *sums)
4732 {
4733 	const u64 lock_end = sums->logical + sums->len - 1;
4734 	struct extent_state *cached_state = NULL;
4735 	int ret;
4736 
4737 	/*
4738 	 * If this inode was not used for reflink operations in the current
4739 	 * transaction with new extents, then do the fast path, no need to
4740 	 * worry about logging checksum items with overlapping ranges.
4741 	 */
4742 	if (inode->last_reflink_trans < trans->transid)
4743 		return btrfs_insert_data_csums(trans, log_root, sums);
4744 
4745 	/*
4746 	 * Serialize logging for checksums. This is to avoid racing with the
4747 	 * same checksum being logged by another task that is logging another
4748 	 * file which happens to refer to the same extent as well. Such races
4749 	 * can leave checksum items in the log with overlapping ranges.
4750 	 */
4751 	ret = btrfs_lock_extent(&log_root->log_csum_range, sums->logical, lock_end,
4752 				&cached_state);
4753 	if (ret)
4754 		return ret;
4755 	/*
4756 	 * Due to extent cloning, we might have logged a csum item that covers a
4757 	 * subrange of a cloned extent, and later we can end up logging a csum
4758 	 * item for a larger subrange of the same extent or the entire range.
4759 	 * This would leave csum items in the log tree that cover the same range
4760 	 * and break the searches for checksums in the log tree, resulting in
4761 	 * some checksums missing in the fs/subvolume tree. So just delete (or
4762 	 * trim and adjust) any existing csum items in the log for this range.
4763 	 */
4764 	ret = btrfs_del_csums(trans, log_root, sums->logical, sums->len);
4765 	if (!ret)
4766 		ret = btrfs_insert_data_csums(trans, log_root, sums);
4767 
4768 	btrfs_unlock_extent(&log_root->log_csum_range, sums->logical, lock_end,
4769 			    &cached_state);
4770 
4771 	return ret;
4772 }
4773 
4774 static noinline int copy_items(struct btrfs_trans_handle *trans,
4775 			       struct btrfs_inode *inode,
4776 			       struct btrfs_path *dst_path,
4777 			       struct btrfs_path *src_path,
4778 			       int start_slot, int nr, enum btrfs_log_mode log_mode,
4779 			       u64 logged_isize, struct btrfs_log_ctx *ctx)
4780 {
4781 	struct btrfs_root *log = inode->root->log_root;
4782 	struct btrfs_file_extent_item *extent;
4783 	struct extent_buffer *src;
4784 	int ret;
4785 	struct btrfs_key *ins_keys;
4786 	u32 *ins_sizes;
4787 	struct btrfs_item_batch batch;
4788 	char AUTO_KFREE(ins_data);
4789 	int dst_index;
4790 	const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
4791 	const u64 i_size = i_size_read(&inode->vfs_inode);
4792 
4793 	/*
4794 	 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4795 	 * use the clone. This is because otherwise we would be changing the log
4796 	 * tree, to insert items from the subvolume tree or insert csum items,
4797 	 * while holding a read lock on a leaf from the subvolume tree, which
4798 	 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4799 	 *
4800 	 * 1) Modifying the log tree triggers an extent buffer allocation while
4801 	 *    holding a write lock on a parent extent buffer from the log tree.
4802 	 *    Allocating the pages for an extent buffer, or the extent buffer
4803 	 *    struct, can trigger inode eviction and finally the inode eviction
4804 	 *    will trigger a release/remove of a delayed node, which requires
4805 	 *    taking the delayed node's mutex;
4806 	 *
4807 	 * 2) Allocating a metadata extent for a log tree can trigger the async
4808 	 *    reclaim thread and make us wait for it to release enough space and
4809 	 *    unblock our reservation ticket. The reclaim thread can start
4810 	 *    flushing delayed items, and that in turn results in the need to
4811 	 *    lock delayed node mutexes and in the need to write lock extent
4812 	 *    buffers of a subvolume tree - all this while holding a write lock
4813 	 *    on the parent extent buffer in the log tree.
4814 	 *
4815 	 * So one task in scenario 1) running in parallel with another task in
4816 	 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4817 	 * node mutex while having a read lock on a leaf from the subvolume,
4818 	 * while the other is holding the delayed node's mutex and wants to
4819 	 * write lock the same subvolume leaf for flushing delayed items.
4820 	 */
4821 	ret = clone_leaf(src_path, ctx);
4822 	if (ret < 0)
4823 		return ret;
4824 
4825 	src = src_path->nodes[0];
4826 
4827 	ins_data = kmalloc_array(nr, sizeof(struct btrfs_key) + sizeof(u32), GFP_NOFS);
4828 	if (!ins_data)
4829 		return -ENOMEM;
4830 
4831 	ins_sizes = (u32 *)ins_data;
4832 	ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4833 	batch.keys = ins_keys;
4834 	batch.data_sizes = ins_sizes;
4835 	batch.total_data_size = 0;
4836 	batch.nr = 0;
4837 
4838 	dst_index = 0;
4839 	for (int i = 0; i < nr; i++) {
4840 		const int src_slot = start_slot + i;
4841 		struct btrfs_root *csum_root;
4842 		struct btrfs_ordered_sum *sums;
4843 		struct btrfs_ordered_sum *sums_next;
4844 		LIST_HEAD(ordered_sums);
4845 		u64 disk_bytenr;
4846 		u64 disk_num_bytes;
4847 		u64 extent_offset;
4848 		u64 extent_num_bytes;
4849 		bool is_old_extent;
4850 
4851 		btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
4852 
4853 		if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
4854 			goto add_to_batch;
4855 
4856 		extent = btrfs_item_ptr(src, src_slot,
4857 					struct btrfs_file_extent_item);
4858 
4859 		is_old_extent = (btrfs_file_extent_generation(src, extent) <
4860 				 trans->transid);
4861 
4862 		/*
4863 		 * Don't copy extents from past generations. That would make us
4864 		 * log a lot more metadata for common cases like doing only a
4865 		 * few random writes into a file and then fsync it for the first
4866 		 * time or after the full sync flag is set on the inode. We can
4867 		 * get leaves full of extent items, most of which are from past
4868 		 * generations, so we can skip them - as long as the inode has
4869 		 * not been the target of a reflink operation in this transaction,
4870 		 * as in that case it might have had file extent items with old
4871 		 * generations copied into it. We also must always log prealloc
4872 		 * extents that start at or beyond eof, otherwise we would lose
4873 		 * them on log replay.
4874 		 */
4875 		if (is_old_extent &&
4876 		    ins_keys[dst_index].offset < i_size &&
4877 		    inode->last_reflink_trans < trans->transid)
4878 			continue;
4879 
4880 		if (skip_csum)
4881 			goto add_to_batch;
4882 
4883 		/* Only regular extents have checksums. */
4884 		if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
4885 			goto add_to_batch;
4886 
4887 		/*
4888 		 * If it's an extent created in a past transaction, then its
4889 		 * checksums are already accessible from the committed csum tree,
4890 		 * no need to log them.
4891 		 */
4892 		if (is_old_extent)
4893 			goto add_to_batch;
4894 
4895 		disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
4896 		/* If it's an explicit hole, there are no checksums. */
4897 		if (disk_bytenr == 0)
4898 			goto add_to_batch;
4899 
4900 		disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
4901 
4902 		if (btrfs_file_extent_compression(src, extent)) {
4903 			extent_offset = 0;
4904 			extent_num_bytes = disk_num_bytes;
4905 		} else {
4906 			extent_offset = btrfs_file_extent_offset(src, extent);
4907 			extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
4908 		}
4909 
4910 		csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
4911 		if (unlikely(!csum_root)) {
4912 			btrfs_err(trans->fs_info,
4913 				  "missing csum root for extent at bytenr %llu",
4914 				  disk_bytenr);
4915 			return -EUCLEAN;
4916 		}
4917 
4918 		disk_bytenr += extent_offset;
4919 		ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
4920 					      disk_bytenr + extent_num_bytes - 1,
4921 					      &ordered_sums, false);
4922 		if (ret < 0)
4923 			return ret;
4924 		ret = 0;
4925 
4926 		list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
4927 			if (!ret)
4928 				ret = log_csums(trans, inode, log, sums);
4929 			list_del(&sums->list);
4930 			kfree(sums);
4931 		}
4932 		if (ret)
4933 			return ret;
4934 
4935 add_to_batch:
4936 		ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
4937 		batch.total_data_size += ins_sizes[dst_index];
4938 		batch.nr++;
4939 		dst_index++;
4940 	}
4941 
4942 	/*
4943 	 * We have a leaf full of old extent items that don't need to be logged,
4944 	 * so we don't need to do anything.
4945 	 */
4946 	if (batch.nr == 0)
4947 		return 0;
4948 
4949 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4950 	if (ret)
4951 		return ret;
4952 
4953 	dst_index = 0;
4954 	for (int i = 0; i < nr; i++) {
4955 		const int src_slot = start_slot + i;
4956 		const int dst_slot = dst_path->slots[0] + dst_index;
4957 		struct btrfs_key key;
4958 		unsigned long src_offset;
4959 		unsigned long dst_offset;
4960 
4961 		/*
4962 		 * We're done, all the remaining items in the source leaf
4963 		 * correspond to old file extent items.
4964 		 */
4965 		if (dst_index >= batch.nr)
4966 			break;
4967 
4968 		btrfs_item_key_to_cpu(src, &key, src_slot);
4969 
4970 		if (key.type != BTRFS_EXTENT_DATA_KEY)
4971 			goto copy_item;
4972 
4973 		extent = btrfs_item_ptr(src, src_slot,
4974 					struct btrfs_file_extent_item);
4975 
4976 		/* See the comment in the previous loop, same logic. */
4977 		if (btrfs_file_extent_generation(src, extent) < trans->transid &&
4978 		    key.offset < i_size &&
4979 		    inode->last_reflink_trans < trans->transid)
4980 			continue;
4981 
4982 copy_item:
4983 		dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
4984 		src_offset = btrfs_item_ptr_offset(src, src_slot);
4985 
4986 		if (key.type == BTRFS_INODE_ITEM_KEY) {
4987 			struct btrfs_inode_item *inode_item;
4988 
4989 			inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
4990 						    struct btrfs_inode_item);
4991 			fill_inode_item(trans, dst_path->nodes[0], inode_item,
4992 					inode, log_mode == LOG_INODE_EXISTS,
4993 					logged_isize);
4994 		} else {
4995 			copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4996 					   src_offset, ins_sizes[dst_index]);
4997 		}
4998 
4999 		dst_index++;
5000 	}
5001 
5002 	btrfs_release_path(dst_path);
5003 
5004 	return ret;
5005 }
5006 
5007 static int extent_cmp(void *priv, const struct list_head *a,
5008 		      const struct list_head *b)
5009 {
5010 	const struct extent_map *em1, *em2;
5011 
5012 	em1 = list_entry(a, struct extent_map, list);
5013 	em2 = list_entry(b, struct extent_map, list);
5014 
5015 	if (em1->start < em2->start)
5016 		return -1;
5017 	else if (em1->start > em2->start)
5018 		return 1;
5019 	return 0;
5020 }
5021 
5022 static int log_extent_csums(struct btrfs_trans_handle *trans,
5023 			    struct btrfs_inode *inode,
5024 			    struct btrfs_root *log_root,
5025 			    const struct extent_map *em,
5026 			    struct btrfs_log_ctx *ctx)
5027 {
5028 	struct btrfs_ordered_extent *ordered;
5029 	struct btrfs_root *csum_root;
5030 	u64 block_start;
5031 	u64 csum_offset;
5032 	u64 csum_len;
5033 	u64 mod_start = em->start;
5034 	u64 mod_len = em->len;
5035 	LIST_HEAD(ordered_sums);
5036 	int ret = 0;
5037 
5038 	if (inode->flags & BTRFS_INODE_NODATASUM ||
5039 	    (em->flags & EXTENT_FLAG_PREALLOC) ||
5040 	    em->disk_bytenr == EXTENT_MAP_HOLE)
5041 		return 0;
5042 
5043 	list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
5044 		const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
5045 		const u64 mod_end = mod_start + mod_len;
5046 		struct btrfs_ordered_sum *sums;
5047 
5048 		if (mod_len == 0)
5049 			break;
5050 
5051 		if (ordered_end <= mod_start)
5052 			continue;
5053 		if (mod_end <= ordered->file_offset)
5054 			break;
5055 
5056 		/*
5057 		 * We are going to copy all the csums on this ordered extent, so
5058 		 * go ahead and adjust mod_start and mod_len in case this ordered
5059 		 * extent has already been logged.
5060 		 */
5061 		if (ordered->file_offset > mod_start) {
5062 			if (ordered_end >= mod_end)
5063 				mod_len = ordered->file_offset - mod_start;
5064 			/*
5065 			 * If we have this case
5066 			 *
5067 			 * |--------- logged extent ---------|
5068 			 *       |----- ordered extent ----|
5069 			 *
5070 			 * Just don't mess with mod_start and mod_len, we'll
5071 			 * just end up logging more csums than we need and it
5072 			 * will be ok.
5073 			 */
5074 		} else {
5075 			if (ordered_end < mod_end) {
5076 				mod_len = mod_end - ordered_end;
5077 				mod_start = ordered_end;
5078 			} else {
5079 				mod_len = 0;
5080 			}
5081 		}
5082 
5083 		/*
5084 		 * To keep us from looping for the above case of an ordered
5085 		 * extent that falls inside of the logged extent.
5086 		 */
5087 		if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
5088 			continue;
5089 
5090 		list_for_each_entry(sums, &ordered->csum_list, list) {
5091 			ret = log_csums(trans, inode, log_root, sums);
5092 			if (ret)
5093 				return ret;
5094 		}
5095 	}
5096 
5097 	/* We're done, found all csums in the ordered extents. */
5098 	if (mod_len == 0)
5099 		return 0;
5100 
5101 	/* If we're compressed we have to save the entire range of csums. */
5102 	if (btrfs_extent_map_is_compressed(em)) {
5103 		csum_offset = 0;
5104 		csum_len = em->disk_num_bytes;
5105 	} else {
5106 		csum_offset = mod_start - em->start;
5107 		csum_len = mod_len;
5108 	}
5109 
5110 	/* block start is already adjusted for the file extent offset. */
5111 	block_start = btrfs_extent_map_block_start(em);
5112 	csum_root = btrfs_csum_root(trans->fs_info, block_start);
5113 	if (unlikely(!csum_root)) {
5114 		btrfs_err(trans->fs_info,
5115 			  "missing csum root for extent at bytenr %llu",
5116 			  block_start);
5117 		return -EUCLEAN;
5118 	}
5119 
5120 	ret = btrfs_lookup_csums_list(csum_root, block_start + csum_offset,
5121 				      block_start + csum_offset + csum_len - 1,
5122 				      &ordered_sums, false);
5123 	if (ret < 0)
5124 		return ret;
5125 	ret = 0;
5126 
5127 	while (!list_empty(&ordered_sums)) {
5128 		struct btrfs_ordered_sum *sums = list_first_entry(&ordered_sums,
5129 								  struct btrfs_ordered_sum,
5130 								  list);
5131 		if (!ret)
5132 			ret = log_csums(trans, inode, log_root, sums);
5133 		list_del(&sums->list);
5134 		kfree(sums);
5135 	}
5136 
5137 	return ret;
5138 }
5139 
5140 static int log_one_extent(struct btrfs_trans_handle *trans,
5141 			  struct btrfs_inode *inode,
5142 			  const struct extent_map *em,
5143 			  struct btrfs_path *path,
5144 			  struct btrfs_log_ctx *ctx)
5145 {
5146 	struct btrfs_drop_extents_args drop_args = { 0 };
5147 	struct btrfs_root *log = inode->root->log_root;
5148 	struct btrfs_file_extent_item fi = { 0 };
5149 	struct extent_buffer *leaf;
5150 	struct btrfs_key key;
5151 	enum btrfs_compression_type compress_type;
5152 	u64 extent_offset = em->offset;
5153 	u64 block_start = btrfs_extent_map_block_start(em);
5154 	u64 block_len;
5155 	int ret;
5156 
5157 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
5158 	if (em->flags & EXTENT_FLAG_PREALLOC)
5159 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
5160 	else
5161 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
5162 
5163 	block_len = em->disk_num_bytes;
5164 	compress_type = btrfs_extent_map_compression(em);
5165 	if (compress_type != BTRFS_COMPRESS_NONE) {
5166 		btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
5167 		btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
5168 	} else if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) {
5169 		btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start - extent_offset);
5170 		btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
5171 	}
5172 
5173 	btrfs_set_stack_file_extent_offset(&fi, extent_offset);
5174 	btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
5175 	btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
5176 	btrfs_set_stack_file_extent_compression(&fi, compress_type);
5177 
5178 	ret = log_extent_csums(trans, inode, log, em, ctx);
5179 	if (ret)
5180 		return ret;
5181 
5182 	/*
5183 	 * If this is the first time we are logging the inode in the current
5184 	 * transaction, we can avoid btrfs_drop_extents(), which is expensive
5185 	 * because it does a deletion search, which always acquires write locks
5186 	 * for extent buffers at levels 2, 1 and 0. This not only wastes time
5187 	 * but also adds significant contention in a log tree, since log trees
5188 	 * are small, with a root at level 2 or 3 at most, due to their short
5189 	 * life span.
5190 	 */
5191 	if (ctx->logged_before) {
5192 		drop_args.path = path;
5193 		drop_args.start = em->start;
5194 		drop_args.end = btrfs_extent_map_end(em);
5195 		drop_args.replace_extent = true;
5196 		drop_args.extent_item_size = sizeof(fi);
5197 		ret = btrfs_drop_extents(trans, log, inode, &drop_args);
5198 		if (ret)
5199 			return ret;
5200 	}
5201 
5202 	if (!drop_args.extent_inserted) {
5203 		key.objectid = btrfs_ino(inode);
5204 		key.type = BTRFS_EXTENT_DATA_KEY;
5205 		key.offset = em->start;
5206 
5207 		ret = btrfs_insert_empty_item(trans, log, path, &key,
5208 					      sizeof(fi));
5209 		if (ret)
5210 			return ret;
5211 	}
5212 	leaf = path->nodes[0];
5213 	write_extent_buffer(leaf, &fi,
5214 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
5215 			    sizeof(fi));
5216 
5217 	btrfs_release_path(path);
5218 
5219 	return ret;
5220 }
5221 
5222 /*
5223  * Log all prealloc extents beyond the inode's i_size to make sure we do not
5224  * lose them after doing a full/fast fsync and replaying the log. We scan the
5225  * subvolume's root instead of iterating the inode's extent map tree because
5226  * otherwise we can log incorrect extent items based on extent map conversion.
5227  * That can happen due to the fact that extent maps are merged when they
5228  * are not in the extent map tree's list of modified extents.
5229  */
5230 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
5231 				      struct btrfs_inode *inode,
5232 				      struct btrfs_path *path,
5233 				      struct btrfs_log_ctx *ctx)
5234 {
5235 	struct btrfs_root *root = inode->root;
5236 	struct btrfs_key key;
5237 	const u64 i_size = i_size_read(&inode->vfs_inode);
5238 	const u64 ino = btrfs_ino(inode);
5239 	BTRFS_PATH_AUTO_FREE(dst_path);
5240 	bool dropped_extents = false;
5241 	u64 truncate_offset = i_size;
5242 	struct extent_buffer *leaf;
5243 	int slot;
5244 	int ins_nr = 0;
5245 	int start_slot = 0;
5246 	int ret;
5247 
5248 	if (!(inode->flags & BTRFS_INODE_PREALLOC))
5249 		return 0;
5250 
5251 	key.objectid = ino;
5252 	key.type = BTRFS_EXTENT_DATA_KEY;
5253 	key.offset = i_size;
5254 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5255 	if (ret < 0)
5256 		goto out;
5257 
5258 	/*
5259 	 * We must check if there is a prealloc extent that starts before the
5260 	 * i_size and crosses the i_size boundary. This is to ensure later we
5261 	 * truncate down to the end of that extent and not to the i_size, as
5262 	 * otherwise we end up losing part of the prealloc extent after a log
5263 	 * replay and with an implicit hole if there is another prealloc extent
5264 	 * that starts at an offset beyond i_size.
5265 	 */
5266 	ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
5267 	if (ret < 0)
5268 		goto out;
5269 
5270 	if (ret == 0) {
5271 		struct btrfs_file_extent_item *ei;
5272 
5273 		leaf = path->nodes[0];
5274 		slot = path->slots[0];
5275 		ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5276 
5277 		if (btrfs_file_extent_type(leaf, ei) ==
5278 		    BTRFS_FILE_EXTENT_PREALLOC) {
5279 			u64 extent_end;
5280 
5281 			btrfs_item_key_to_cpu(leaf, &key, slot);
5282 			extent_end = key.offset +
5283 				btrfs_file_extent_num_bytes(leaf, ei);
5284 
5285 			if (extent_end > i_size)
5286 				truncate_offset = extent_end;
5287 		}
5288 	} else {
5289 		ret = 0;
5290 	}
5291 
5292 	while (true) {
5293 		leaf = path->nodes[0];
5294 		slot = path->slots[0];
5295 
5296 		if (slot >= btrfs_header_nritems(leaf)) {
5297 			if (ins_nr > 0) {
5298 				ret = copy_items(trans, inode, dst_path, path,
5299 						 start_slot, ins_nr, 1, 0, ctx);
5300 				if (ret < 0)
5301 					goto out;
5302 				ins_nr = 0;
5303 			}
5304 			ret = btrfs_next_leaf(root, path);
5305 			if (ret < 0)
5306 				goto out;
5307 			if (ret > 0) {
5308 				ret = 0;
5309 				break;
5310 			}
5311 			continue;
5312 		}
5313 
5314 		btrfs_item_key_to_cpu(leaf, &key, slot);
5315 		if (key.objectid > ino)
5316 			break;
5317 		if (WARN_ON_ONCE(key.objectid < ino) ||
5318 		    key.type < BTRFS_EXTENT_DATA_KEY ||
5319 		    key.offset < i_size) {
5320 			path->slots[0]++;
5321 			continue;
5322 		}
5323 		/*
5324 		 * Avoid overlapping items in the log tree. The first time we
5325 		 * get here, get rid of everything from a past fsync. After
5326 		 * that, if the current extent starts before the end of the last
5327 		 * extent we copied, truncate the last one. This can happen if
5328 		 * an ordered extent completion modifies the subvolume tree
5329 		 * while btrfs_next_leaf() has the tree unlocked.
5330 		 */
5331 		if (!dropped_extents || key.offset < truncate_offset) {
5332 			ret = truncate_inode_items(trans, root->log_root, inode,
5333 						   min(key.offset, truncate_offset),
5334 						   BTRFS_EXTENT_DATA_KEY);
5335 			if (ret)
5336 				goto out;
5337 			dropped_extents = true;
5338 		}
5339 		truncate_offset = btrfs_file_extent_end(path);
5340 		if (ins_nr == 0)
5341 			start_slot = slot;
5342 		ins_nr++;
5343 		path->slots[0]++;
5344 		if (!dst_path) {
5345 			dst_path = btrfs_alloc_path();
5346 			if (!dst_path) {
5347 				ret = -ENOMEM;
5348 				goto out;
5349 			}
5350 		}
5351 	}
5352 	if (ins_nr > 0)
5353 		ret = copy_items(trans, inode, dst_path, path,
5354 				 start_slot, ins_nr, 1, 0, ctx);
5355 out:
5356 	btrfs_release_path(path);
5357 	return ret;
5358 }
5359 
5360 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
5361 				     struct btrfs_inode *inode,
5362 				     struct btrfs_path *path,
5363 				     struct btrfs_log_ctx *ctx)
5364 {
5365 	struct btrfs_ordered_extent *ordered;
5366 	struct btrfs_ordered_extent *tmp;
5367 	struct extent_map *em, *n;
5368 	LIST_HEAD(extents);
5369 	struct extent_map_tree *tree = &inode->extent_tree;
5370 	int ret = 0;
5371 	int num = 0;
5372 
5373 	write_lock(&tree->lock);
5374 
5375 	list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
5376 		list_del_init(&em->list);
5377 		/*
5378 		 * Just an arbitrary number, this can be really CPU intensive
5379 		 * once we start getting a lot of extents, and really once we
5380 		 * have a bunch of extents we just want to commit since it will
5381 		 * be faster.
5382 		 */
5383 		if (++num > 32768) {
5384 			list_del_init(&tree->modified_extents);
5385 			ret = -EFBIG;
5386 			goto process;
5387 		}
5388 
5389 		if (em->generation < trans->transid)
5390 			continue;
5391 
5392 		/* We log prealloc extents beyond eof later. */
5393 		if ((em->flags & EXTENT_FLAG_PREALLOC) &&
5394 		    em->start >= i_size_read(&inode->vfs_inode))
5395 			continue;
5396 
5397 		/* Need a ref to keep it from getting evicted from cache */
5398 		refcount_inc(&em->refs);
5399 		em->flags |= EXTENT_FLAG_LOGGING;
5400 		list_add_tail(&em->list, &extents);
5401 		num++;
5402 	}
5403 
5404 	list_sort(NULL, &extents, extent_cmp);
5405 process:
5406 	while (!list_empty(&extents)) {
5407 		em = list_first_entry(&extents, struct extent_map, list);
5408 
5409 		list_del_init(&em->list);
5410 
5411 		/*
5412 		 * If we had an error we just need to delete everybody from our
5413 		 * private list.
5414 		 */
5415 		if (ret) {
5416 			btrfs_clear_em_logging(inode, em);
5417 			btrfs_free_extent_map(em);
5418 			continue;
5419 		}
5420 
5421 		write_unlock(&tree->lock);
5422 
5423 		ret = log_one_extent(trans, inode, em, path, ctx);
5424 		write_lock(&tree->lock);
5425 		btrfs_clear_em_logging(inode, em);
5426 		btrfs_free_extent_map(em);
5427 	}
5428 	WARN_ON(!list_empty(&extents));
5429 	write_unlock(&tree->lock);
5430 
5431 	if (!ret)
5432 		ret = btrfs_log_prealloc_extents(trans, inode, path, ctx);
5433 	if (ret)
5434 		return ret;
5435 
5436 	/*
5437 	 * We have logged all extents successfully, now make sure the commit of
5438 	 * the current transaction waits for the ordered extents to complete
5439 	 * before it commits and wipes out the log trees, otherwise we would
5440 	 * lose data if an ordered extents completes after the transaction
5441 	 * commits and a power failure happens after the transaction commit.
5442 	 */
5443 	list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
5444 		list_del_init(&ordered->log_list);
5445 		set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
5446 
5447 		if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
5448 			spin_lock(&inode->ordered_tree_lock);
5449 			if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
5450 				set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
5451 				atomic_inc(&trans->transaction->pending_ordered);
5452 			}
5453 			spin_unlock(&inode->ordered_tree_lock);
5454 		}
5455 		btrfs_put_ordered_extent(ordered);
5456 	}
5457 
5458 	return 0;
5459 }
5460 
5461 static int get_inode_size_to_log(struct btrfs_trans_handle *trans,
5462 				 struct btrfs_inode *inode,
5463 				 struct btrfs_path *path, u64 *size_ret)
5464 {
5465 	struct btrfs_key key;
5466 	struct btrfs_inode_item *item;
5467 	int ret;
5468 
5469 	key.objectid = btrfs_ino(inode);
5470 	key.type = BTRFS_INODE_ITEM_KEY;
5471 	key.offset = 0;
5472 
5473 	/*
5474 	 * Our caller called inode_logged(), so logged_trans is up to date.
5475 	 * Use data_race() to silence any warning from KCSAN. Once logged_trans
5476 	 * is set, it can only be reset to 0 after inode eviction.
5477 	 */
5478 	if (data_race(inode->logged_trans) == trans->transid) {
5479 		ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
5480 	} else if (inode->generation < trans->transid) {
5481 		path->search_commit_root = true;
5482 		path->skip_locking = true;
5483 		ret = btrfs_search_slot(NULL, inode->root, &key, path, 0, 0);
5484 		path->search_commit_root = false;
5485 		path->skip_locking = false;
5486 
5487 	} else {
5488 		*size_ret = 0;
5489 		return 0;
5490 	}
5491 
5492 	/*
5493 	 * If the inode was logged before or is from a past transaction, then
5494 	 * its inode item must exist in the log root or in the commit root.
5495 	 */
5496 	ASSERT(ret <= 0);
5497 	if (WARN_ON_ONCE(ret > 0))
5498 		ret = -ENOENT;
5499 
5500 	if (ret < 0)
5501 		return ret;
5502 
5503 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5504 			      struct btrfs_inode_item);
5505 	*size_ret = btrfs_inode_size(path->nodes[0], item);
5506 	/*
5507 	 * If the in-memory inode's i_size is smaller then the inode size stored
5508 	 * in the btree, return the inode's i_size, so that we get a correct
5509 	 * inode size after replaying the log when before a power failure we had
5510 	 * a shrinking truncate followed by addition of a new name (rename / new
5511 	 * hard link). Otherwise return the inode size from the btree, to avoid
5512 	 * data loss when replaying a log due to previously doing a write that
5513 	 * expands the inode's size and logging a new name immediately after.
5514 	 */
5515 	if (*size_ret > inode->vfs_inode.i_size)
5516 		*size_ret = inode->vfs_inode.i_size;
5517 
5518 	btrfs_release_path(path);
5519 	return 0;
5520 }
5521 
5522 /*
5523  * At the moment we always log all xattrs. This is to figure out at log replay
5524  * time which xattrs must have their deletion replayed. If a xattr is missing
5525  * in the log tree and exists in the fs/subvol tree, we delete it. This is
5526  * because if a xattr is deleted, the inode is fsynced and a power failure
5527  * happens, causing the log to be replayed the next time the fs is mounted,
5528  * we want the xattr to not exist anymore (same behaviour as other filesystems
5529  * with a journal, ext3/4, xfs, f2fs, etc).
5530  */
5531 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
5532 				struct btrfs_inode *inode,
5533 				struct btrfs_path *path,
5534 				struct btrfs_path *dst_path,
5535 				struct btrfs_log_ctx *ctx)
5536 {
5537 	struct btrfs_root *root = inode->root;
5538 	int ret;
5539 	struct btrfs_key key;
5540 	const u64 ino = btrfs_ino(inode);
5541 	int ins_nr = 0;
5542 	int start_slot = 0;
5543 	bool found_xattrs = false;
5544 
5545 	if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5546 		return 0;
5547 
5548 	key.objectid = ino;
5549 	key.type = BTRFS_XATTR_ITEM_KEY;
5550 	key.offset = 0;
5551 
5552 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5553 	if (ret < 0)
5554 		return ret;
5555 
5556 	while (true) {
5557 		int slot = path->slots[0];
5558 		struct extent_buffer *leaf = path->nodes[0];
5559 		int nritems = btrfs_header_nritems(leaf);
5560 
5561 		if (slot >= nritems) {
5562 			if (ins_nr > 0) {
5563 				ret = copy_items(trans, inode, dst_path, path,
5564 						 start_slot, ins_nr, 1, 0, ctx);
5565 				if (ret < 0)
5566 					return ret;
5567 				ins_nr = 0;
5568 			}
5569 			ret = btrfs_next_leaf(root, path);
5570 			if (ret < 0)
5571 				return ret;
5572 			else if (ret > 0)
5573 				break;
5574 			continue;
5575 		}
5576 
5577 		btrfs_item_key_to_cpu(leaf, &key, slot);
5578 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
5579 			break;
5580 
5581 		if (ins_nr == 0)
5582 			start_slot = slot;
5583 		ins_nr++;
5584 		path->slots[0]++;
5585 		found_xattrs = true;
5586 		cond_resched();
5587 	}
5588 	if (ins_nr > 0) {
5589 		ret = copy_items(trans, inode, dst_path, path,
5590 				 start_slot, ins_nr, 1, 0, ctx);
5591 		if (ret < 0)
5592 			return ret;
5593 	}
5594 
5595 	if (!found_xattrs)
5596 		set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5597 
5598 	return 0;
5599 }
5600 
5601 /*
5602  * When using the NO_HOLES feature if we punched a hole that causes the
5603  * deletion of entire leafs or all the extent items of the first leaf (the one
5604  * that contains the inode item and references) we may end up not processing
5605  * any extents, because there are no leafs with a generation matching the
5606  * current transaction that have extent items for our inode. So we need to find
5607  * if any holes exist and then log them. We also need to log holes after any
5608  * truncate operation that changes the inode's size.
5609  */
5610 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5611 			   struct btrfs_inode *inode,
5612 			   struct btrfs_path *path)
5613 {
5614 	struct btrfs_root *root = inode->root;
5615 	struct btrfs_fs_info *fs_info = root->fs_info;
5616 	struct btrfs_key key;
5617 	const u64 ino = btrfs_ino(inode);
5618 	const u64 i_size = i_size_read(&inode->vfs_inode);
5619 	u64 prev_extent_end = 0;
5620 	int ret;
5621 
5622 	if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5623 		return 0;
5624 
5625 	key.objectid = ino;
5626 	key.type = BTRFS_EXTENT_DATA_KEY;
5627 	key.offset = 0;
5628 
5629 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5630 	if (ret < 0)
5631 		return ret;
5632 
5633 	while (true) {
5634 		struct extent_buffer *leaf = path->nodes[0];
5635 
5636 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5637 			ret = btrfs_next_leaf(root, path);
5638 			if (ret < 0)
5639 				return ret;
5640 			if (ret > 0) {
5641 				ret = 0;
5642 				break;
5643 			}
5644 			leaf = path->nodes[0];
5645 		}
5646 
5647 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5648 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
5649 			break;
5650 
5651 		/* We have a hole, log it. */
5652 		if (prev_extent_end < key.offset) {
5653 			const u64 hole_len = key.offset - prev_extent_end;
5654 
5655 			/*
5656 			 * Release the path to avoid deadlocks with other code
5657 			 * paths that search the root while holding locks on
5658 			 * leafs from the log root.
5659 			 */
5660 			btrfs_release_path(path);
5661 			ret = btrfs_insert_hole_extent(trans, root->log_root,
5662 						       ino, prev_extent_end,
5663 						       hole_len);
5664 			if (ret < 0)
5665 				return ret;
5666 
5667 			/*
5668 			 * Search for the same key again in the root. Since it's
5669 			 * an extent item and we are holding the inode lock, the
5670 			 * key must still exist. If it doesn't just emit warning
5671 			 * and return an error to fall back to a transaction
5672 			 * commit.
5673 			 */
5674 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5675 			if (ret < 0)
5676 				return ret;
5677 			if (WARN_ON(ret > 0))
5678 				return -ENOENT;
5679 			leaf = path->nodes[0];
5680 		}
5681 
5682 		prev_extent_end = btrfs_file_extent_end(path);
5683 		path->slots[0]++;
5684 		cond_resched();
5685 	}
5686 
5687 	if (prev_extent_end < i_size) {
5688 		u64 hole_len;
5689 
5690 		btrfs_release_path(path);
5691 		hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5692 		ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5693 					       prev_extent_end, hole_len);
5694 		if (ret < 0)
5695 			return ret;
5696 	}
5697 
5698 	return 0;
5699 }
5700 
5701 /*
5702  * When we are logging a new inode X, check if it doesn't have a reference that
5703  * matches the reference from some other inode Y created in a past transaction
5704  * and that was renamed in the current transaction. If we don't do this, then at
5705  * log replay time we can lose inode Y (and all its files if it's a directory):
5706  *
5707  * mkdir /mnt/x
5708  * echo "hello world" > /mnt/x/foobar
5709  * sync
5710  * mv /mnt/x /mnt/y
5711  * mkdir /mnt/x                 # or touch /mnt/x
5712  * xfs_io -c fsync /mnt/x
5713  * <power fail>
5714  * mount fs, trigger log replay
5715  *
5716  * After the log replay procedure, we would lose the first directory and all its
5717  * files (file foobar).
5718  * For the case where inode Y is not a directory we simply end up losing it:
5719  *
5720  * echo "123" > /mnt/foo
5721  * sync
5722  * mv /mnt/foo /mnt/bar
5723  * echo "abc" > /mnt/foo
5724  * xfs_io -c fsync /mnt/foo
5725  * <power fail>
5726  *
5727  * We also need this for cases where a snapshot entry is replaced by some other
5728  * entry (file or directory) otherwise we end up with an unreplayable log due to
5729  * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
5730  * if it were a regular entry:
5731  *
5732  * mkdir /mnt/x
5733  * btrfs subvolume snapshot /mnt /mnt/x/snap
5734  * btrfs subvolume delete /mnt/x/snap
5735  * rmdir /mnt/x
5736  * mkdir /mnt/x
5737  * fsync /mnt/x or fsync some new file inside it
5738  * <power fail>
5739  *
5740  * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
5741  * the same transaction.
5742  */
5743 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
5744 					 const int slot,
5745 					 const struct btrfs_key *key,
5746 					 struct btrfs_inode *inode,
5747 					 u64 *other_ino, u64 *other_parent)
5748 {
5749 	BTRFS_PATH_AUTO_FREE(search_path);
5750 	char AUTO_KFREE(name);
5751 	u32 name_len = 0;
5752 	u32 item_size = btrfs_item_size(eb, slot);
5753 	u32 cur_offset = 0;
5754 	unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
5755 
5756 	search_path = btrfs_alloc_path();
5757 	if (!search_path)
5758 		return -ENOMEM;
5759 	search_path->search_commit_root = true;
5760 	search_path->skip_locking = true;
5761 
5762 	while (cur_offset < item_size) {
5763 		u64 parent;
5764 		u32 this_name_len;
5765 		u32 this_len;
5766 		unsigned long name_ptr;
5767 		struct btrfs_dir_item *di;
5768 		struct fscrypt_str name_str;
5769 
5770 		if (key->type == BTRFS_INODE_REF_KEY) {
5771 			struct btrfs_inode_ref *iref;
5772 
5773 			iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
5774 			parent = key->offset;
5775 			this_name_len = btrfs_inode_ref_name_len(eb, iref);
5776 			name_ptr = (unsigned long)(iref + 1);
5777 			this_len = sizeof(*iref) + this_name_len;
5778 		} else {
5779 			struct btrfs_inode_extref *extref;
5780 
5781 			extref = (struct btrfs_inode_extref *)(ptr +
5782 							       cur_offset);
5783 			parent = btrfs_inode_extref_parent(eb, extref);
5784 			this_name_len = btrfs_inode_extref_name_len(eb, extref);
5785 			name_ptr = (unsigned long)&extref->name;
5786 			this_len = sizeof(*extref) + this_name_len;
5787 		}
5788 
5789 		if (this_name_len > name_len) {
5790 			char *new_name;
5791 
5792 			new_name = krealloc(name, this_name_len, GFP_NOFS);
5793 			if (!new_name)
5794 				return -ENOMEM;
5795 			name_len = this_name_len;
5796 			name = new_name;
5797 		}
5798 
5799 		read_extent_buffer(eb, name, name_ptr, this_name_len);
5800 
5801 		name_str.name = name;
5802 		name_str.len = this_name_len;
5803 		di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5804 				parent, &name_str, 0);
5805 		if (!IS_ERR_OR_NULL(di)) {
5806 			struct btrfs_key di_key;
5807 
5808 			btrfs_dir_item_key_to_cpu(search_path->nodes[0],
5809 						  di, &di_key);
5810 			if (di_key.type == BTRFS_INODE_ITEM_KEY) {
5811 				if (di_key.objectid != key->objectid) {
5812 					*other_ino = di_key.objectid;
5813 					*other_parent = parent;
5814 					return 1;
5815 				} else {
5816 					return 0;
5817 				}
5818 			} else {
5819 				return -EAGAIN;
5820 			}
5821 		} else if (IS_ERR(di)) {
5822 			return PTR_ERR(di);
5823 		}
5824 		btrfs_release_path(search_path);
5825 
5826 		cur_offset += this_len;
5827 	}
5828 
5829 	return 0;
5830 }
5831 
5832 /*
5833  * Check if we need to log an inode. This is used in contexts where while
5834  * logging an inode we need to log another inode (either that it exists or in
5835  * full mode). This is used instead of btrfs_inode_in_log() because the later
5836  * requires the inode to be in the log and have the log transaction committed,
5837  * while here we do not care if the log transaction was already committed - our
5838  * caller will commit the log later - and we want to avoid logging an inode
5839  * multiple times when multiple tasks have joined the same log transaction.
5840  */
5841 static bool need_log_inode(const struct btrfs_trans_handle *trans,
5842 			   struct btrfs_inode *inode)
5843 {
5844 	/*
5845 	 * If a directory was not modified, no dentries added or removed, we can
5846 	 * and should avoid logging it.
5847 	 */
5848 	if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5849 		return false;
5850 
5851 	/*
5852 	 * If this inode does not have new/updated/deleted xattrs since the last
5853 	 * time it was logged and is flagged as logged in the current transaction,
5854 	 * we can skip logging it. As for new/deleted names, those are updated in
5855 	 * the log by link/unlink/rename operations.
5856 	 * In case the inode was logged and then evicted and reloaded, its
5857 	 * logged_trans will be 0, in which case we have to fully log it since
5858 	 * logged_trans is a transient field, not persisted.
5859 	 */
5860 	if (inode_logged(trans, inode, NULL) == 1 &&
5861 	    !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5862 		return false;
5863 
5864 	return true;
5865 }
5866 
5867 struct btrfs_dir_list {
5868 	u64 ino;
5869 	struct list_head list;
5870 };
5871 
5872 /*
5873  * Log the inodes of the new dentries of a directory.
5874  * See process_dir_items_leaf() for details about why it is needed.
5875  * This is a recursive operation - if an existing dentry corresponds to a
5876  * directory, that directory's new entries are logged too (same behaviour as
5877  * ext3/4, xfs, f2fs, nilfs2). Note that when logging the inodes
5878  * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5879  * complains about the following circular lock dependency / possible deadlock:
5880  *
5881  *        CPU0                                        CPU1
5882  *        ----                                        ----
5883  * lock(&type->i_mutex_dir_key#3/2);
5884  *                                            lock(sb_internal#2);
5885  *                                            lock(&type->i_mutex_dir_key#3/2);
5886  * lock(&sb->s_type->i_mutex_key#14);
5887  *
5888  * Where sb_internal is the lock (a counter that works as a lock) acquired by
5889  * sb_start_intwrite() in btrfs_start_transaction().
5890  * Not acquiring the VFS lock of the inodes is still safe because:
5891  *
5892  * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5893  *    that while logging the inode new references (names) are added or removed
5894  *    from the inode, leaving the logged inode item with a link count that does
5895  *    not match the number of logged inode reference items. This is fine because
5896  *    at log replay time we compute the real number of links and correct the
5897  *    link count in the inode item (see replay_one_buffer() and
5898  *    link_to_fixup_dir());
5899  *
5900  * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5901  *    while logging the inode's items new index items (key type
5902  *    BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5903  *    has a size that doesn't match the sum of the lengths of all the logged
5904  *    names - this is ok, not a problem, because at log replay time we set the
5905  *    directory's i_size to the correct value (see replay_one_name() and
5906  *    overwrite_item()).
5907  */
5908 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5909 				struct btrfs_inode *start_inode,
5910 				struct btrfs_log_ctx *ctx)
5911 {
5912 	struct btrfs_root *root = start_inode->root;
5913 	struct btrfs_path *path;
5914 	LIST_HEAD(dir_list);
5915 	struct btrfs_dir_list *dir_elem;
5916 	u64 ino = btrfs_ino(start_inode);
5917 	struct btrfs_inode *curr_inode = start_inode;
5918 	int ret = 0;
5919 
5920 	trace_btrfs_log_new_dir_dentries_enter(trans, start_inode);
5921 
5922 	path = btrfs_alloc_path();
5923 	if (!path) {
5924 		ret = -ENOMEM;
5925 		goto out;
5926 	}
5927 
5928 	/* Pairs with btrfs_add_delayed_iput below. */
5929 	ihold(&curr_inode->vfs_inode);
5930 
5931 	while (true) {
5932 		struct btrfs_key key;
5933 		struct btrfs_key found_key;
5934 		u64 next_index;
5935 		bool continue_curr_inode = true;
5936 		int iter_ret;
5937 
5938 		key.objectid = ino;
5939 		key.type = BTRFS_DIR_INDEX_KEY;
5940 		key.offset = btrfs_get_first_dir_index_to_log(curr_inode);
5941 		next_index = key.offset;
5942 again:
5943 		btrfs_for_each_slot(root->log_root, &key, &found_key, path, iter_ret) {
5944 			struct extent_buffer *leaf = path->nodes[0];
5945 			struct btrfs_dir_item *di;
5946 			struct btrfs_key di_key;
5947 			struct btrfs_inode *di_inode;
5948 			int log_mode = LOG_INODE_EXISTS;
5949 			int type;
5950 
5951 			if (found_key.objectid != ino ||
5952 			    found_key.type != BTRFS_DIR_INDEX_KEY) {
5953 				continue_curr_inode = false;
5954 				break;
5955 			}
5956 
5957 			next_index = found_key.offset + 1;
5958 
5959 			di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
5960 			type = btrfs_dir_ftype(leaf, di);
5961 			if (btrfs_dir_transid(leaf, di) < trans->transid)
5962 				continue;
5963 			btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5964 			if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5965 				continue;
5966 
5967 			btrfs_release_path(path);
5968 			di_inode = btrfs_iget_logging(di_key.objectid, root);
5969 			if (IS_ERR(di_inode)) {
5970 				ret = PTR_ERR(di_inode);
5971 				goto out;
5972 			}
5973 
5974 			if (!need_log_inode(trans, di_inode)) {
5975 				btrfs_add_delayed_iput(di_inode);
5976 				break;
5977 			}
5978 
5979 			ctx->log_new_dentries = false;
5980 			if (type == BTRFS_FT_DIR)
5981 				log_mode = LOG_INODE_ALL;
5982 			ret = btrfs_log_inode(trans, di_inode, log_mode, ctx);
5983 			btrfs_add_delayed_iput(di_inode);
5984 			if (ret)
5985 				goto out;
5986 			if (ctx->log_new_dentries) {
5987 				dir_elem = kmalloc_obj(*dir_elem, GFP_NOFS);
5988 				if (!dir_elem) {
5989 					ret = -ENOMEM;
5990 					goto out;
5991 				}
5992 				dir_elem->ino = di_key.objectid;
5993 				list_add_tail(&dir_elem->list, &dir_list);
5994 			}
5995 			break;
5996 		}
5997 
5998 		btrfs_release_path(path);
5999 
6000 		if (iter_ret < 0) {
6001 			ret = iter_ret;
6002 			goto out;
6003 		} else if (iter_ret > 0) {
6004 			continue_curr_inode = false;
6005 		} else {
6006 			key = found_key;
6007 		}
6008 
6009 		if (continue_curr_inode && key.offset < (u64)-1) {
6010 			key.offset++;
6011 			goto again;
6012 		}
6013 
6014 		btrfs_set_first_dir_index_to_log(curr_inode, next_index);
6015 
6016 		if (list_empty(&dir_list))
6017 			break;
6018 
6019 		dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
6020 		ino = dir_elem->ino;
6021 		list_del(&dir_elem->list);
6022 		kfree(dir_elem);
6023 
6024 		btrfs_add_delayed_iput(curr_inode);
6025 
6026 		curr_inode = btrfs_iget_logging(ino, root);
6027 		if (IS_ERR(curr_inode)) {
6028 			ret = PTR_ERR(curr_inode);
6029 			curr_inode = NULL;
6030 			break;
6031 		}
6032 	}
6033 out:
6034 	btrfs_free_path(path);
6035 	if (curr_inode)
6036 		btrfs_add_delayed_iput(curr_inode);
6037 
6038 	if (ret) {
6039 		struct btrfs_dir_list *next;
6040 
6041 		list_for_each_entry_safe(dir_elem, next, &dir_list, list)
6042 			kfree(dir_elem);
6043 	}
6044 
6045 	trace_btrfs_log_new_dir_dentries_exit(trans, start_inode, ret);
6046 
6047 	return ret;
6048 }
6049 
6050 struct btrfs_ino_list {
6051 	u64 ino;
6052 	u64 parent;
6053 	struct list_head list;
6054 };
6055 
6056 static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
6057 {
6058 	struct btrfs_ino_list *curr;
6059 	struct btrfs_ino_list *next;
6060 
6061 	list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
6062 		list_del(&curr->list);
6063 		kfree(curr);
6064 	}
6065 }
6066 
6067 static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
6068 				    struct btrfs_path *path)
6069 {
6070 	struct btrfs_key key;
6071 	int ret;
6072 
6073 	key.objectid = ino;
6074 	key.type = BTRFS_INODE_ITEM_KEY;
6075 	key.offset = 0;
6076 
6077 	path->search_commit_root = true;
6078 	path->skip_locking = true;
6079 
6080 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6081 	if (WARN_ON_ONCE(ret > 0)) {
6082 		/*
6083 		 * We have previously found the inode through the commit root
6084 		 * so this should not happen. If it does, just error out and
6085 		 * fallback to a transaction commit.
6086 		 */
6087 		ret = -ENOENT;
6088 	} else if (ret == 0) {
6089 		struct btrfs_inode_item *item;
6090 
6091 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6092 				      struct btrfs_inode_item);
6093 		if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
6094 			ret = 1;
6095 	}
6096 
6097 	btrfs_release_path(path);
6098 	path->search_commit_root = false;
6099 	path->skip_locking = false;
6100 
6101 	return ret;
6102 }
6103 
6104 static bool can_log_conflicting_inode(const struct btrfs_trans_handle *trans,
6105 				      const struct btrfs_inode *inode)
6106 {
6107 	if (!S_ISDIR(inode->vfs_inode.i_mode))
6108 		return true;
6109 
6110 	if (inode->last_unlink_trans < trans->transid)
6111 		return true;
6112 
6113 	/*
6114 	 * If this is a directory and its unlink_trans is not from a past
6115 	 * transaction then we must fallback to a transaction commit in order
6116 	 * to avoid getting a directory with 2 hard links after log replay.
6117 	 *
6118 	 * This happens if a directory A is renamed, moved from one parent
6119 	 * directory to another one, a new file is created in the old parent
6120 	 * directory with the old name of our directory A, the new file is
6121 	 * fsynced, then we moved the new file to some other parent directory
6122 	 * and fsync again the new file. This results in a log tree where we
6123 	 * logged that directory A existed, with the INODE_REF item for the
6124 	 * new location but without having logged its old parent inode, so
6125 	 * that on log replay we add a new link for the new location but the
6126 	 * old link remains, resulting in a link count of 2.
6127 	 */
6128 	return false;
6129 }
6130 
6131 static int add_conflicting_inode(struct btrfs_trans_handle *trans,
6132 				 struct btrfs_root *root,
6133 				 struct btrfs_path *path,
6134 				 u64 ino, u64 parent,
6135 				 struct btrfs_log_ctx *ctx)
6136 {
6137 	struct btrfs_ino_list *ino_elem;
6138 	struct btrfs_inode *inode;
6139 	int ret = 0;
6140 
6141 	trace_btrfs_add_conflicting_inode_enter(trans, ctx, ino, parent);
6142 
6143 	/*
6144 	 * It's rare to have a lot of conflicting inodes, in practice it is not
6145 	 * common to have more than 1 or 2. We don't want to collect too many,
6146 	 * as we could end up logging too many inodes (even if only in
6147 	 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
6148 	 * commits.
6149 	 */
6150 	if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES) {
6151 		ret = BTRFS_LOG_FORCE_COMMIT;
6152 		goto out;
6153 	}
6154 
6155 	inode = btrfs_iget_logging(ino, root);
6156 	/*
6157 	 * If the other inode that had a conflicting dir entry was deleted in
6158 	 * the current transaction then we either:
6159 	 *
6160 	 * 1) Log the parent directory (later after adding it to the list) if
6161 	 *    the inode is a directory. This is because it may be a deleted
6162 	 *    subvolume/snapshot or it may be a regular directory that had
6163 	 *    deleted subvolumes/snapshots (or subdirectories that had them),
6164 	 *    and at the moment we can't deal with dropping subvolumes/snapshots
6165 	 *    during log replay. So we just log the parent, which will result in
6166 	 *    a fallback to a transaction commit if we are dealing with those
6167 	 *    cases (last_unlink_trans will match the current transaction);
6168 	 *
6169 	 * 2) Do nothing if it's not a directory. During log replay we simply
6170 	 *    unlink the conflicting dentry from the parent directory and then
6171 	 *    add the dentry for our inode. Like this we can avoid logging the
6172 	 *    parent directory (and maybe fallback to a transaction commit in
6173 	 *    case it has a last_unlink_trans == trans->transid, due to moving
6174 	 *    some inode from it to some other directory).
6175 	 */
6176 	if (IS_ERR(inode)) {
6177 		ret = PTR_ERR(inode);
6178 		if (ret != -ENOENT)
6179 			goto out;
6180 
6181 		ret = conflicting_inode_is_dir(root, ino, path);
6182 		/* Not a directory or we got an error. */
6183 		if (ret <= 0)
6184 			goto out;
6185 
6186 		/* Conflicting inode is a directory, so we'll log its parent. */
6187 		ino_elem = kmalloc_obj(*ino_elem, GFP_NOFS);
6188 		if (!ino_elem) {
6189 			ret = -ENOMEM;
6190 			goto out;
6191 		}
6192 		ino_elem->ino = ino;
6193 		ino_elem->parent = parent;
6194 		list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
6195 		ctx->num_conflict_inodes++;
6196 		ret = 0;
6197 		goto out;
6198 	}
6199 
6200 	/*
6201 	 * If the inode was already logged skip it - otherwise we can hit an
6202 	 * infinite loop. Example:
6203 	 *
6204 	 * From the commit root (previous transaction) we have the following
6205 	 * inodes:
6206 	 *
6207 	 * inode 257 a directory
6208 	 * inode 258 with references "zz" and "zz_link" on inode 257
6209 	 * inode 259 with reference "a" on inode 257
6210 	 *
6211 	 * And in the current (uncommitted) transaction we have:
6212 	 *
6213 	 * inode 257 a directory, unchanged
6214 	 * inode 258 with references "a" and "a2" on inode 257
6215 	 * inode 259 with reference "zz_link" on inode 257
6216 	 * inode 261 with reference "zz" on inode 257
6217 	 *
6218 	 * When logging inode 261 the following infinite loop could
6219 	 * happen if we don't skip already logged inodes:
6220 	 *
6221 	 * - we detect inode 258 as a conflicting inode, with inode 261
6222 	 *   on reference "zz", and log it;
6223 	 *
6224 	 * - we detect inode 259 as a conflicting inode, with inode 258
6225 	 *   on reference "a", and log it;
6226 	 *
6227 	 * - we detect inode 258 as a conflicting inode, with inode 259
6228 	 *   on reference "zz_link", and log it - again! After this we
6229 	 *   repeat the above steps forever.
6230 	 *
6231 	 * Here we can use need_log_inode() because we only need to log the
6232 	 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
6233 	 * so that the log ends up with the new name and without the old name.
6234 	 */
6235 	if (!need_log_inode(trans, inode)) {
6236 		btrfs_add_delayed_iput(inode);
6237 		goto out;
6238 	}
6239 
6240 	if (!can_log_conflicting_inode(trans, inode)) {
6241 		btrfs_add_delayed_iput(inode);
6242 		ret = BTRFS_LOG_FORCE_COMMIT;
6243 		goto out;
6244 	}
6245 
6246 	btrfs_add_delayed_iput(inode);
6247 
6248 	ino_elem = kmalloc_obj(*ino_elem, GFP_NOFS);
6249 	if (!ino_elem) {
6250 		ret = -ENOMEM;
6251 		goto out;
6252 	}
6253 	ino_elem->ino = ino;
6254 	ino_elem->parent = parent;
6255 	list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
6256 	ctx->num_conflict_inodes++;
6257 
6258 out:
6259 	trace_btrfs_add_conflicting_inode_exit(trans, ctx, ino, parent, ret);
6260 
6261 	return ret;
6262 }
6263 
6264 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
6265 				  struct btrfs_root *root,
6266 				  struct btrfs_log_ctx *ctx)
6267 {
6268 	const bool orig_log_new_dentries = ctx->log_new_dentries;
6269 	int ret = 0;
6270 
6271 	/*
6272 	 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
6273 	 * otherwise we could have unbounded recursion of btrfs_log_inode()
6274 	 * calls. This check guarantees we can have only 1 level of recursion.
6275 	 */
6276 	if (ctx->logging_conflict_inodes)
6277 		return 0;
6278 
6279 	/*
6280 	 * Avoid any work if no conflicting inodes and emitting the trace event
6281 	 * which only adds noise and it's useless if there are no inodes.
6282 	 */
6283 	if (list_empty(&ctx->conflict_inodes))
6284 		return 0;
6285 
6286 	ctx->logging_conflict_inodes = true;
6287 	trace_btrfs_log_conflicting_inodes_enter(trans, ctx);
6288 
6289 	/*
6290 	 * New conflicting inodes may be found and added to the list while we
6291 	 * are logging a conflicting inode, so keep iterating while the list is
6292 	 * not empty.
6293 	 */
6294 	while (!list_empty(&ctx->conflict_inodes)) {
6295 		struct btrfs_ino_list *curr;
6296 		struct btrfs_inode *inode;
6297 		u64 ino;
6298 		u64 parent;
6299 
6300 		curr = list_first_entry(&ctx->conflict_inodes,
6301 					struct btrfs_ino_list, list);
6302 		ino = curr->ino;
6303 		parent = curr->parent;
6304 		list_del(&curr->list);
6305 		kfree(curr);
6306 
6307 		inode = btrfs_iget_logging(ino, root);
6308 		/*
6309 		 * If the other inode that had a conflicting dir entry was
6310 		 * deleted in the current transaction, we need to log its parent
6311 		 * directory. See the comment at add_conflicting_inode().
6312 		 */
6313 		if (IS_ERR(inode)) {
6314 			ret = PTR_ERR(inode);
6315 			if (ret != -ENOENT)
6316 				break;
6317 
6318 			inode = btrfs_iget_logging(parent, root);
6319 			if (IS_ERR(inode)) {
6320 				ret = PTR_ERR(inode);
6321 				break;
6322 			}
6323 
6324 			if (!can_log_conflicting_inode(trans, inode)) {
6325 				btrfs_add_delayed_iput(inode);
6326 				ret = BTRFS_LOG_FORCE_COMMIT;
6327 				break;
6328 			}
6329 
6330 			/*
6331 			 * Always log the directory, we cannot make this
6332 			 * conditional on need_log_inode() because the directory
6333 			 * might have been logged in LOG_INODE_EXISTS mode or
6334 			 * the dir index of the conflicting inode is not in a
6335 			 * dir index key range logged for the directory. So we
6336 			 * must make sure the deletion is recorded.
6337 			 */
6338 			ctx->log_new_dentries = false;
6339 			ret = btrfs_log_inode(trans, inode, LOG_INODE_ALL, ctx);
6340 			if (!ret && ctx->log_new_dentries)
6341 				ret = log_new_dir_dentries(trans, inode, ctx);
6342 
6343 			btrfs_add_delayed_iput(inode);
6344 			if (ret)
6345 				break;
6346 			continue;
6347 		}
6348 
6349 		/*
6350 		 * Here we can use need_log_inode() because we only need to log
6351 		 * the inode in LOG_INODE_EXISTS mode and rename operations
6352 		 * update the log, so that the log ends up with the new name and
6353 		 * without the old name.
6354 		 *
6355 		 * We did this check at add_conflicting_inode(), but here we do
6356 		 * it again because if some other task logged the inode after
6357 		 * that, we can avoid doing it again.
6358 		 */
6359 		if (!need_log_inode(trans, inode)) {
6360 			btrfs_add_delayed_iput(inode);
6361 			continue;
6362 		}
6363 
6364 		/*
6365 		 * We are safe logging the other inode without acquiring its
6366 		 * lock as long as we log with the LOG_INODE_EXISTS mode. We
6367 		 * are safe against concurrent renames of the other inode as
6368 		 * well because during a rename we pin the log and update the
6369 		 * log with the new name before we unpin it.
6370 		 */
6371 		ret = btrfs_log_inode(trans, inode, LOG_INODE_EXISTS, ctx);
6372 		btrfs_add_delayed_iput(inode);
6373 		if (ret)
6374 			break;
6375 	}
6376 
6377 	ctx->log_new_dentries = orig_log_new_dentries;
6378 	ctx->logging_conflict_inodes = false;
6379 	if (ret)
6380 		free_conflicting_inodes(ctx);
6381 	trace_btrfs_log_conflicting_inodes_exit(trans, ctx, ret);
6382 
6383 	return ret;
6384 }
6385 
6386 static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
6387 				   struct btrfs_inode *inode,
6388 				   struct btrfs_key *min_key,
6389 				   const struct btrfs_key *max_key,
6390 				   struct btrfs_path *path,
6391 				   struct btrfs_path *dst_path,
6392 				   const u64 logged_isize,
6393 				   const enum btrfs_log_mode log_mode,
6394 				   struct btrfs_log_ctx *ctx,
6395 				   bool *need_log_inode_item)
6396 {
6397 	const u64 i_size = i_size_read(&inode->vfs_inode);
6398 	struct btrfs_root *root = inode->root;
6399 	int ins_start_slot = 0;
6400 	int ins_nr = 0;
6401 	int ret;
6402 
6403 	while (1) {
6404 		ret = btrfs_search_forward(root, min_key, path, trans->transid);
6405 		if (ret < 0)
6406 			return ret;
6407 		if (ret > 0) {
6408 			ret = 0;
6409 			break;
6410 		}
6411 again:
6412 		/* Note, ins_nr might be > 0 here, cleanup outside the loop */
6413 		if (min_key->objectid != max_key->objectid)
6414 			break;
6415 		if (min_key->type > max_key->type)
6416 			break;
6417 
6418 		if (min_key->type == BTRFS_INODE_ITEM_KEY) {
6419 			*need_log_inode_item = false;
6420 		} else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
6421 			   min_key->offset >= i_size) {
6422 			/*
6423 			 * Extents at and beyond eof are logged with
6424 			 * btrfs_log_prealloc_extents().
6425 			 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
6426 			 * and no keys greater than that, so bail out.
6427 			 */
6428 			break;
6429 		} else if (min_key->type == BTRFS_INODE_REF_KEY ||
6430 			   min_key->type == BTRFS_INODE_EXTREF_KEY) {
6431 			u64 other_ino = 0;
6432 			u64 other_parent = 0;
6433 
6434 			ret = btrfs_check_ref_name_override(path->nodes[0],
6435 					path->slots[0], min_key, inode,
6436 					&other_ino, &other_parent);
6437 			if (ret < 0) {
6438 				return ret;
6439 			} else if (ret > 0 &&
6440 				   other_ino != btrfs_ino(ctx->inode)) {
6441 				if (ins_nr > 0) {
6442 					ins_nr++;
6443 				} else {
6444 					ins_nr = 1;
6445 					ins_start_slot = path->slots[0];
6446 				}
6447 				ret = copy_items(trans, inode, dst_path, path,
6448 						 ins_start_slot, ins_nr,
6449 						 log_mode, logged_isize, ctx);
6450 				if (ret < 0)
6451 					return ret;
6452 				ins_nr = 0;
6453 
6454 				btrfs_release_path(path);
6455 				ret = add_conflicting_inode(trans, root, path,
6456 							    other_ino,
6457 							    other_parent, ctx);
6458 				if (ret)
6459 					return ret;
6460 				goto next_key;
6461 			}
6462 		} else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
6463 			/* Skip xattrs, logged later with btrfs_log_all_xattrs() */
6464 			if (ins_nr == 0)
6465 				goto next_slot;
6466 			ret = copy_items(trans, inode, dst_path, path,
6467 					 ins_start_slot,
6468 					 ins_nr, log_mode, logged_isize, ctx);
6469 			if (ret < 0)
6470 				return ret;
6471 			ins_nr = 0;
6472 			goto next_slot;
6473 		}
6474 
6475 		if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
6476 			ins_nr++;
6477 			goto next_slot;
6478 		} else if (!ins_nr) {
6479 			ins_start_slot = path->slots[0];
6480 			ins_nr = 1;
6481 			goto next_slot;
6482 		}
6483 
6484 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
6485 				 ins_nr, log_mode, logged_isize, ctx);
6486 		if (ret < 0)
6487 			return ret;
6488 		ins_nr = 1;
6489 		ins_start_slot = path->slots[0];
6490 next_slot:
6491 		path->slots[0]++;
6492 		if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
6493 			btrfs_item_key_to_cpu(path->nodes[0], min_key,
6494 					      path->slots[0]);
6495 			goto again;
6496 		}
6497 		if (ins_nr) {
6498 			ret = copy_items(trans, inode, dst_path, path,
6499 					 ins_start_slot, ins_nr, log_mode,
6500 					 logged_isize, ctx);
6501 			if (ret < 0)
6502 				return ret;
6503 			ins_nr = 0;
6504 		}
6505 		btrfs_release_path(path);
6506 next_key:
6507 		if (min_key->offset < (u64)-1) {
6508 			min_key->offset++;
6509 		} else if (min_key->type < max_key->type) {
6510 			min_key->type++;
6511 			min_key->offset = 0;
6512 		} else {
6513 			break;
6514 		}
6515 
6516 		/*
6517 		 * We may process many leaves full of items for our inode, so
6518 		 * avoid monopolizing a cpu for too long by rescheduling while
6519 		 * not holding locks on any tree.
6520 		 */
6521 		cond_resched();
6522 	}
6523 	if (ins_nr) {
6524 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
6525 				 ins_nr, log_mode, logged_isize, ctx);
6526 		if (ret)
6527 			return ret;
6528 	}
6529 
6530 	if (log_mode == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
6531 		/*
6532 		 * Release the path because otherwise we might attempt to double
6533 		 * lock the same leaf with btrfs_log_prealloc_extents() below.
6534 		 */
6535 		btrfs_release_path(path);
6536 		ret = btrfs_log_prealloc_extents(trans, inode, dst_path, ctx);
6537 	}
6538 
6539 	return ret;
6540 }
6541 
6542 static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
6543 				      struct btrfs_root *log,
6544 				      struct btrfs_path *path,
6545 				      const struct btrfs_item_batch *batch,
6546 				      const struct btrfs_delayed_item *first_item)
6547 {
6548 	const struct btrfs_delayed_item *curr = first_item;
6549 	int ret;
6550 
6551 	ret = btrfs_insert_empty_items(trans, log, path, batch);
6552 	if (ret)
6553 		return ret;
6554 
6555 	for (int i = 0; i < batch->nr; i++) {
6556 		char *data_ptr;
6557 
6558 		data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
6559 		write_extent_buffer(path->nodes[0], &curr->data,
6560 				    (unsigned long)data_ptr, curr->data_len);
6561 		curr = list_next_entry(curr, log_list);
6562 		path->slots[0]++;
6563 	}
6564 
6565 	btrfs_release_path(path);
6566 
6567 	return 0;
6568 }
6569 
6570 static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
6571 				       struct btrfs_inode *inode,
6572 				       struct btrfs_path *path,
6573 				       const struct list_head *delayed_ins_list,
6574 				       struct btrfs_log_ctx *ctx)
6575 {
6576 	/* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
6577 	const int max_batch_size = 195;
6578 	const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
6579 	const u64 ino = btrfs_ino(inode);
6580 	struct btrfs_root *log = inode->root->log_root;
6581 	struct btrfs_item_batch batch = {
6582 		.nr = 0,
6583 		.total_data_size = 0,
6584 	};
6585 	const struct btrfs_delayed_item *first = NULL;
6586 	const struct btrfs_delayed_item *curr;
6587 	char *ins_data;
6588 	struct btrfs_key *ins_keys;
6589 	u32 *ins_sizes;
6590 	u64 curr_batch_size = 0;
6591 	int batch_idx = 0;
6592 	int ret;
6593 
6594 	/* We are adding dir index items to the log tree. */
6595 	lockdep_assert_held(&inode->log_mutex);
6596 
6597 	/*
6598 	 * We collect delayed items before copying index keys from the subvolume
6599 	 * to the log tree. However just after we collected them, they may have
6600 	 * been flushed (all of them or just some of them), and therefore we
6601 	 * could have copied them from the subvolume tree to the log tree.
6602 	 * So find the first delayed item that was not yet logged (they are
6603 	 * sorted by index number).
6604 	 */
6605 	list_for_each_entry(curr, delayed_ins_list, log_list) {
6606 		if (curr->index > inode->last_dir_index_offset) {
6607 			first = curr;
6608 			break;
6609 		}
6610 	}
6611 
6612 	/* Empty list or all delayed items were already logged. */
6613 	if (!first)
6614 		return 0;
6615 
6616 	ins_data = kmalloc_array(max_batch_size, sizeof(u32) + sizeof(struct btrfs_key), GFP_NOFS);
6617 	if (!ins_data)
6618 		return -ENOMEM;
6619 	ins_sizes = (u32 *)ins_data;
6620 	batch.data_sizes = ins_sizes;
6621 	ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
6622 	batch.keys = ins_keys;
6623 
6624 	curr = first;
6625 	while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
6626 		const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
6627 
6628 		if (curr_batch_size + curr_size > leaf_data_size ||
6629 		    batch.nr == max_batch_size) {
6630 			ret = insert_delayed_items_batch(trans, log, path,
6631 							 &batch, first);
6632 			if (ret)
6633 				goto out;
6634 			batch_idx = 0;
6635 			batch.nr = 0;
6636 			batch.total_data_size = 0;
6637 			curr_batch_size = 0;
6638 			first = curr;
6639 		}
6640 
6641 		ins_sizes[batch_idx] = curr->data_len;
6642 		ins_keys[batch_idx].objectid = ino;
6643 		ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
6644 		ins_keys[batch_idx].offset = curr->index;
6645 		curr_batch_size += curr_size;
6646 		batch.total_data_size += curr->data_len;
6647 		batch.nr++;
6648 		batch_idx++;
6649 		curr = list_next_entry(curr, log_list);
6650 	}
6651 
6652 	ASSERT(batch.nr >= 1, "batch.nr=%d", batch.nr);
6653 	ret = insert_delayed_items_batch(trans, log, path, &batch, first);
6654 
6655 	curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
6656 			       log_list);
6657 	inode->last_dir_index_offset = curr->index;
6658 out:
6659 	kfree(ins_data);
6660 
6661 	return ret;
6662 }
6663 
6664 static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
6665 				      struct btrfs_inode *inode,
6666 				      struct btrfs_path *path,
6667 				      const struct list_head *delayed_del_list,
6668 				      struct btrfs_log_ctx *ctx)
6669 {
6670 	const u64 ino = btrfs_ino(inode);
6671 	const struct btrfs_delayed_item *curr;
6672 
6673 	curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6674 				log_list);
6675 
6676 	while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6677 		u64 first_dir_index = curr->index;
6678 		u64 last_dir_index;
6679 		const struct btrfs_delayed_item *next;
6680 		int ret;
6681 
6682 		/*
6683 		 * Find a range of consecutive dir index items to delete. Like
6684 		 * this we log a single dir range item spanning several contiguous
6685 		 * dir items instead of logging one range item per dir index item.
6686 		 */
6687 		next = list_next_entry(curr, log_list);
6688 		while (!list_entry_is_head(next, delayed_del_list, log_list)) {
6689 			if (next->index != curr->index + 1)
6690 				break;
6691 			curr = next;
6692 			next = list_next_entry(next, log_list);
6693 		}
6694 
6695 		last_dir_index = curr->index;
6696 		ASSERT(last_dir_index >= first_dir_index,
6697 		       "last_dir_index=%llu first_dir_index=%llu",
6698 		       last_dir_index, first_dir_index);
6699 
6700 		ret = insert_dir_log_key(trans, inode->root->log_root, path,
6701 					 ino, first_dir_index, last_dir_index);
6702 		if (ret)
6703 			return ret;
6704 		curr = list_next_entry(curr, log_list);
6705 	}
6706 
6707 	return 0;
6708 }
6709 
6710 static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
6711 					struct btrfs_inode *inode,
6712 					struct btrfs_path *path,
6713 					const struct list_head *delayed_del_list,
6714 					const struct btrfs_delayed_item *first,
6715 					const struct btrfs_delayed_item **last_ret)
6716 {
6717 	const struct btrfs_delayed_item *next;
6718 	struct extent_buffer *leaf = path->nodes[0];
6719 	const int last_slot = btrfs_header_nritems(leaf) - 1;
6720 	int slot = path->slots[0] + 1;
6721 	const u64 ino = btrfs_ino(inode);
6722 
6723 	next = list_next_entry(first, log_list);
6724 
6725 	while (slot < last_slot &&
6726 	       !list_entry_is_head(next, delayed_del_list, log_list)) {
6727 		struct btrfs_key key;
6728 
6729 		btrfs_item_key_to_cpu(leaf, &key, slot);
6730 		if (key.objectid != ino ||
6731 		    key.type != BTRFS_DIR_INDEX_KEY ||
6732 		    key.offset != next->index)
6733 			break;
6734 
6735 		slot++;
6736 		*last_ret = next;
6737 		next = list_next_entry(next, log_list);
6738 	}
6739 
6740 	return btrfs_del_items(trans, inode->root->log_root, path,
6741 			       path->slots[0], slot - path->slots[0]);
6742 }
6743 
6744 static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
6745 					     struct btrfs_inode *inode,
6746 					     struct btrfs_path *path,
6747 					     const struct list_head *delayed_del_list,
6748 					     struct btrfs_log_ctx *ctx)
6749 {
6750 	struct btrfs_root *log = inode->root->log_root;
6751 	const struct btrfs_delayed_item *curr;
6752 	u64 last_range_start = 0;
6753 	u64 last_range_end = 0;
6754 	struct btrfs_key key;
6755 
6756 	key.objectid = btrfs_ino(inode);
6757 	key.type = BTRFS_DIR_INDEX_KEY;
6758 	curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6759 				log_list);
6760 
6761 	while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6762 		const struct btrfs_delayed_item *last = curr;
6763 		u64 first_dir_index = curr->index;
6764 		u64 last_dir_index;
6765 		bool deleted_items = false;
6766 		int ret;
6767 
6768 		key.offset = curr->index;
6769 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
6770 		if (ret < 0) {
6771 			return ret;
6772 		} else if (ret == 0) {
6773 			ret = batch_delete_dir_index_items(trans, inode, path,
6774 							   delayed_del_list, curr,
6775 							   &last);
6776 			if (ret)
6777 				return ret;
6778 			deleted_items = true;
6779 		}
6780 
6781 		btrfs_release_path(path);
6782 
6783 		/*
6784 		 * If we deleted items from the leaf, it means we have a range
6785 		 * item logging their range, so no need to add one or update an
6786 		 * existing one. Otherwise we have to log a dir range item.
6787 		 */
6788 		if (deleted_items)
6789 			goto next_batch;
6790 
6791 		last_dir_index = last->index;
6792 		ASSERT(last_dir_index >= first_dir_index,
6793 		       "last_dir_index=%llu first_dir_index=%llu",
6794 		       last_dir_index, first_dir_index);
6795 		/*
6796 		 * If this range starts right after where the previous one ends,
6797 		 * then we want to reuse the previous range item and change its
6798 		 * end offset to the end of this range. This is just to minimize
6799 		 * leaf space usage, by avoiding adding a new range item.
6800 		 */
6801 		if (last_range_end != 0 && first_dir_index == last_range_end + 1)
6802 			first_dir_index = last_range_start;
6803 
6804 		ret = insert_dir_log_key(trans, log, path, key.objectid,
6805 					 first_dir_index, last_dir_index);
6806 		if (ret)
6807 			return ret;
6808 
6809 		last_range_start = first_dir_index;
6810 		last_range_end = last_dir_index;
6811 next_batch:
6812 		curr = list_next_entry(last, log_list);
6813 	}
6814 
6815 	return 0;
6816 }
6817 
6818 static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
6819 				      struct btrfs_inode *inode,
6820 				      struct btrfs_path *path,
6821 				      const struct list_head *delayed_del_list,
6822 				      struct btrfs_log_ctx *ctx)
6823 {
6824 	/*
6825 	 * We are deleting dir index items from the log tree or adding range
6826 	 * items to it.
6827 	 */
6828 	lockdep_assert_held(&inode->log_mutex);
6829 
6830 	if (list_empty(delayed_del_list))
6831 		return 0;
6832 
6833 	if (ctx->logged_before)
6834 		return log_delayed_deletions_incremental(trans, inode, path,
6835 							 delayed_del_list, ctx);
6836 
6837 	return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
6838 					  ctx);
6839 }
6840 
6841 /*
6842  * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
6843  * items instead of the subvolume tree.
6844  */
6845 static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
6846 				    struct btrfs_inode *inode,
6847 				    const struct list_head *delayed_ins_list,
6848 				    struct btrfs_log_ctx *ctx)
6849 {
6850 	const bool orig_log_new_dentries = ctx->log_new_dentries;
6851 	struct btrfs_delayed_item *item;
6852 	int ret = 0;
6853 
6854 	/*
6855 	 * No need for the log mutex, plus to avoid potential deadlocks or
6856 	 * lockdep annotations due to nesting of delayed inode mutexes and log
6857 	 * mutexes.
6858 	 */
6859 	lockdep_assert_not_held(&inode->log_mutex);
6860 
6861 	ASSERT(!ctx->logging_new_delayed_dentries);
6862 
6863 	/*
6864 	 * Return early if empty list, avoid emitting redundant trace events
6865 	 * that generate noise only.
6866 	 */
6867 	if (list_empty(delayed_ins_list))
6868 		return 0;
6869 
6870 	trace_btrfs_log_new_delayed_dentries_enter(trans, inode);
6871 	ctx->logging_new_delayed_dentries = true;
6872 
6873 	list_for_each_entry(item, delayed_ins_list, log_list) {
6874 		struct btrfs_dir_item *dir_item;
6875 		struct btrfs_inode *di_inode;
6876 		struct btrfs_key key;
6877 		int log_mode = LOG_INODE_EXISTS;
6878 
6879 		dir_item = (struct btrfs_dir_item *)item->data;
6880 		btrfs_disk_key_to_cpu(&key, &dir_item->location);
6881 
6882 		if (key.type == BTRFS_ROOT_ITEM_KEY)
6883 			continue;
6884 
6885 		di_inode = btrfs_iget_logging(key.objectid, inode->root);
6886 		if (IS_ERR(di_inode)) {
6887 			ret = PTR_ERR(di_inode);
6888 			break;
6889 		}
6890 
6891 		if (!need_log_inode(trans, di_inode)) {
6892 			btrfs_add_delayed_iput(di_inode);
6893 			continue;
6894 		}
6895 
6896 		if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
6897 			log_mode = LOG_INODE_ALL;
6898 
6899 		ctx->log_new_dentries = false;
6900 		ret = btrfs_log_inode(trans, di_inode, log_mode, ctx);
6901 
6902 		if (!ret && ctx->log_new_dentries)
6903 			ret = log_new_dir_dentries(trans, di_inode, ctx);
6904 
6905 		btrfs_add_delayed_iput(di_inode);
6906 
6907 		if (ret)
6908 			break;
6909 	}
6910 
6911 	ctx->log_new_dentries = orig_log_new_dentries;
6912 	ctx->logging_new_delayed_dentries = false;
6913 	trace_btrfs_log_new_delayed_dentries_exit(trans, inode, ret);
6914 
6915 	return ret;
6916 }
6917 
6918 /* log a single inode in the tree log.
6919  * At least one parent directory for this inode must exist in the tree
6920  * or be logged already.
6921  *
6922  * Any items from this inode changed by the current transaction are copied
6923  * to the log tree.  An extra reference is taken on any extents in this
6924  * file, allowing us to avoid a whole pile of corner cases around logging
6925  * blocks that have been removed from the tree.
6926  *
6927  * See LOG_INODE_ALL and related defines for a description of what inode_only
6928  * does.
6929  *
6930  * This handles both files and directories.
6931  */
6932 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
6933 			   struct btrfs_inode *inode,
6934 			   enum btrfs_log_mode log_mode,
6935 			   struct btrfs_log_ctx *ctx)
6936 {
6937 	struct btrfs_path *path;
6938 	struct btrfs_path *dst_path = NULL;
6939 	struct btrfs_key min_key;
6940 	struct btrfs_key max_key;
6941 	struct btrfs_root *log = inode->root->log_root;
6942 	int ret;
6943 	bool fast_search = false;
6944 	u64 ino = btrfs_ino(inode);
6945 	struct extent_map_tree *em_tree = &inode->extent_tree;
6946 	u64 logged_isize = 0;
6947 	bool need_log_inode_item = true;
6948 	bool xattrs_logged = false;
6949 	bool inode_item_dropped = true;
6950 	bool full_dir_logging = false;
6951 	LIST_HEAD(delayed_ins_list);
6952 	LIST_HEAD(delayed_del_list);
6953 
6954 	trace_btrfs_log_inode_enter(trans, inode, ctx, log_mode);
6955 
6956 	path = btrfs_alloc_path();
6957 	if (!path) {
6958 		ret = -ENOMEM;
6959 		goto out;
6960 	}
6961 	dst_path = btrfs_alloc_path();
6962 	if (!dst_path) {
6963 		ret = -ENOMEM;
6964 		goto out;
6965 	}
6966 
6967 	min_key.objectid = ino;
6968 	min_key.type = BTRFS_INODE_ITEM_KEY;
6969 	min_key.offset = 0;
6970 
6971 	max_key.objectid = ino;
6972 
6973 
6974 	/* today the code can only do partial logging of directories */
6975 	if (S_ISDIR(inode->vfs_inode.i_mode) ||
6976 	    (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6977 		       &inode->runtime_flags) &&
6978 	     log_mode >= LOG_INODE_EXISTS))
6979 		max_key.type = BTRFS_XATTR_ITEM_KEY;
6980 	else
6981 		max_key.type = (u8)-1;
6982 	max_key.offset = (u64)-1;
6983 
6984 	if (S_ISDIR(inode->vfs_inode.i_mode) && log_mode == LOG_INODE_ALL)
6985 		full_dir_logging = true;
6986 
6987 	/*
6988 	 * If we are logging a directory while we are logging dentries of the
6989 	 * delayed items of some other inode, then we need to flush the delayed
6990 	 * items of this directory and not log the delayed items directly. This
6991 	 * is to prevent more than one level of recursion into btrfs_log_inode()
6992 	 * by having something like this:
6993 	 *
6994 	 *     $ mkdir -p a/b/c/d/e/f/g/h/...
6995 	 *     $ xfs_io -c "fsync" a
6996 	 *
6997 	 * Where all directories in the path did not exist before and are
6998 	 * created in the current transaction.
6999 	 * So in such a case we directly log the delayed items of the main
7000 	 * directory ("a") without flushing them first, while for each of its
7001 	 * subdirectories we flush their delayed items before logging them.
7002 	 * This prevents a potential unbounded recursion like this:
7003 	 *
7004 	 * btrfs_log_inode()
7005 	 *   log_new_delayed_dentries()
7006 	 *      btrfs_log_inode()
7007 	 *        log_new_delayed_dentries()
7008 	 *          btrfs_log_inode()
7009 	 *            log_new_delayed_dentries()
7010 	 *              (...)
7011 	 *
7012 	 * We have thresholds for the maximum number of delayed items to have in
7013 	 * memory, and once they are hit, the items are flushed asynchronously.
7014 	 * However the limit is quite high, so lets prevent deep levels of
7015 	 * recursion to happen by limiting the maximum depth to be 1.
7016 	 */
7017 	if (full_dir_logging && ctx->logging_new_delayed_dentries) {
7018 		ret = btrfs_commit_inode_delayed_items(trans, inode);
7019 		if (ret)
7020 			goto out;
7021 	}
7022 
7023 	mutex_lock(&inode->log_mutex);
7024 
7025 	/*
7026 	 * For symlinks, we must always log their content, which is stored in an
7027 	 * inline extent, otherwise we could end up with an empty symlink after
7028 	 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
7029 	 * one attempts to create an empty symlink).
7030 	 * We don't need to worry about flushing delalloc, because when we create
7031 	 * the inline extent when the symlink is created (we never have delalloc
7032 	 * for symlinks).
7033 	 */
7034 	if (S_ISLNK(inode->vfs_inode.i_mode))
7035 		log_mode = LOG_INODE_ALL;
7036 
7037 	/*
7038 	 * Before logging the inode item, cache the value returned by
7039 	 * inode_logged(), because after that we have the need to figure out if
7040 	 * the inode was previously logged in this transaction.
7041 	 */
7042 	ret = inode_logged(trans, inode, path);
7043 	if (ret < 0)
7044 		goto out_unlock;
7045 	ctx->logged_before = (ret == 1);
7046 	ret = 0;
7047 
7048 	/*
7049 	 * This is for cases where logging a directory could result in losing a
7050 	 * a file after replaying the log. For example, if we move a file from a
7051 	 * directory A to a directory B, then fsync directory A, we have no way
7052 	 * to known the file was moved from A to B, so logging just A would
7053 	 * result in losing the file after a log replay.
7054 	 */
7055 	if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
7056 		ret = BTRFS_LOG_FORCE_COMMIT;
7057 		goto out_unlock;
7058 	}
7059 
7060 	/*
7061 	 * a brute force approach to making sure we get the most uptodate
7062 	 * copies of everything.
7063 	 */
7064 	if (S_ISDIR(inode->vfs_inode.i_mode)) {
7065 		clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
7066 		if (ctx->logged_before)
7067 			ret = drop_inode_items(trans, log, path, inode,
7068 					       BTRFS_XATTR_ITEM_KEY);
7069 	} else {
7070 		if (log_mode == LOG_INODE_EXISTS) {
7071 			/*
7072 			 * Make sure the new inode item we write to the log has
7073 			 * the same isize as the current one (if it exists).
7074 			 * This is necessary to prevent data loss after log
7075 			 * replay, and also to prevent doing a wrong expanding
7076 			 * truncate - for e.g. create file, write 4K into offset
7077 			 * 0, fsync, write 4K into offset 4096, add hard link,
7078 			 * fsync some other file (to sync log), power fail - if
7079 			 * we use the inode's current i_size, after log replay
7080 			 * we get a 8Kb file, with the last 4Kb extent as a hole
7081 			 * (zeroes), as if an expanding truncate happened,
7082 			 * instead of getting a file of 4Kb only.
7083 			 */
7084 			ret = get_inode_size_to_log(trans, inode, path, &logged_isize);
7085 			if (ret)
7086 				goto out_unlock;
7087 		}
7088 		if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7089 			     &inode->runtime_flags)) {
7090 			if (log_mode == LOG_INODE_EXISTS) {
7091 				max_key.type = BTRFS_XATTR_ITEM_KEY;
7092 				if (ctx->logged_before)
7093 					ret = drop_inode_items(trans, log, path,
7094 							       inode, max_key.type);
7095 			} else {
7096 				clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7097 					  &inode->runtime_flags);
7098 				clear_bit(BTRFS_INODE_COPY_EVERYTHING,
7099 					  &inode->runtime_flags);
7100 				if (ctx->logged_before)
7101 					ret = truncate_inode_items(trans, log,
7102 								   inode, 0, 0);
7103 			}
7104 		} else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
7105 					      &inode->runtime_flags) ||
7106 			   log_mode == LOG_INODE_EXISTS) {
7107 			if (log_mode == LOG_INODE_ALL)
7108 				fast_search = true;
7109 			max_key.type = BTRFS_XATTR_ITEM_KEY;
7110 			if (ctx->logged_before)
7111 				ret = drop_inode_items(trans, log, path, inode,
7112 						       max_key.type);
7113 		} else {
7114 			if (log_mode == LOG_INODE_ALL)
7115 				fast_search = true;
7116 			inode_item_dropped = false;
7117 			goto log_extents;
7118 		}
7119 
7120 	}
7121 	if (ret)
7122 		goto out_unlock;
7123 
7124 	/*
7125 	 * If we are logging a directory in full mode, collect the delayed items
7126 	 * before iterating the subvolume tree, so that we don't miss any new
7127 	 * dir index items in case they get flushed while or right after we are
7128 	 * iterating the subvolume tree.
7129 	 */
7130 	if (full_dir_logging && !ctx->logging_new_delayed_dentries)
7131 		btrfs_log_get_delayed_items(inode, &delayed_ins_list,
7132 					    &delayed_del_list);
7133 
7134 	/*
7135 	 * If we are fsyncing a file with 0 hard links, then commit the delayed
7136 	 * inode because the last inode ref (or extref) item may still be in the
7137 	 * subvolume tree and if we log it the file will still exist after a log
7138 	 * replay. So commit the delayed inode to delete that last ref and we
7139 	 * skip logging it.
7140 	 */
7141 	if (inode->vfs_inode.i_nlink == 0) {
7142 		ret = btrfs_commit_inode_delayed_inode(inode);
7143 		if (ret)
7144 			goto out_unlock;
7145 	}
7146 
7147 	ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
7148 				      path, dst_path, logged_isize,
7149 				      log_mode, ctx, &need_log_inode_item);
7150 	if (ret)
7151 		goto out_unlock;
7152 
7153 	btrfs_release_path(path);
7154 	btrfs_release_path(dst_path);
7155 	ret = btrfs_log_all_xattrs(trans, inode, path, dst_path, ctx);
7156 	if (ret)
7157 		goto out_unlock;
7158 	xattrs_logged = true;
7159 	if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
7160 		btrfs_release_path(path);
7161 		btrfs_release_path(dst_path);
7162 		ret = btrfs_log_holes(trans, inode, path);
7163 		if (ret)
7164 			goto out_unlock;
7165 	}
7166 log_extents:
7167 	btrfs_release_path(path);
7168 	btrfs_release_path(dst_path);
7169 	if (need_log_inode_item) {
7170 		ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
7171 		if (ret)
7172 			goto out_unlock;
7173 		/*
7174 		 * If we are doing a fast fsync and the inode was logged before
7175 		 * in this transaction, we don't need to log the xattrs because
7176 		 * they were logged before. If xattrs were added, changed or
7177 		 * deleted since the last time we logged the inode, then we have
7178 		 * already logged them because the inode had the runtime flag
7179 		 * BTRFS_INODE_COPY_EVERYTHING set.
7180 		 */
7181 		if (!xattrs_logged && inode->logged_trans < trans->transid) {
7182 			ret = btrfs_log_all_xattrs(trans, inode, path, dst_path, ctx);
7183 			if (ret)
7184 				goto out_unlock;
7185 			btrfs_release_path(path);
7186 		}
7187 	}
7188 	if (fast_search) {
7189 		ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
7190 		if (ret)
7191 			goto out_unlock;
7192 	} else if (log_mode == LOG_INODE_ALL) {
7193 		struct extent_map *em, *n;
7194 
7195 		write_lock(&em_tree->lock);
7196 		list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
7197 			list_del_init(&em->list);
7198 		write_unlock(&em_tree->lock);
7199 	}
7200 
7201 	if (full_dir_logging) {
7202 		ret = log_directory_changes(trans, inode, path, dst_path, ctx);
7203 		if (ret)
7204 			goto out_unlock;
7205 		ret = log_delayed_insertion_items(trans, inode, path,
7206 						  &delayed_ins_list, ctx);
7207 		if (ret)
7208 			goto out_unlock;
7209 		ret = log_delayed_deletion_items(trans, inode, path,
7210 						 &delayed_del_list, ctx);
7211 		if (ret)
7212 			goto out_unlock;
7213 	}
7214 
7215 	spin_lock(&inode->lock);
7216 	inode->logged_trans = trans->transid;
7217 	/*
7218 	 * Don't update last_log_commit if we logged that an inode exists.
7219 	 * We do this for three reasons:
7220 	 *
7221 	 * 1) We might have had buffered writes to this inode that were
7222 	 *    flushed and had their ordered extents completed in this
7223 	 *    transaction, but we did not previously log the inode with
7224 	 *    LOG_INODE_ALL. Later the inode was evicted and after that
7225 	 *    it was loaded again and this LOG_INODE_EXISTS log operation
7226 	 *    happened. We must make sure that if an explicit fsync against
7227 	 *    the inode is performed later, it logs the new extents, an
7228 	 *    updated inode item, etc, and syncs the log. The same logic
7229 	 *    applies to direct IO writes instead of buffered writes.
7230 	 *
7231 	 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
7232 	 *    is logged with an i_size of 0 or whatever value was logged
7233 	 *    before. If later the i_size of the inode is increased by a
7234 	 *    truncate operation, the log is synced through an fsync of
7235 	 *    some other inode and then finally an explicit fsync against
7236 	 *    this inode is made, we must make sure this fsync logs the
7237 	 *    inode with the new i_size, the hole between old i_size and
7238 	 *    the new i_size, and syncs the log.
7239 	 *
7240 	 * 3) If we are logging that an ancestor inode exists as part of
7241 	 *    logging a new name from a link or rename operation, don't update
7242 	 *    its last_log_commit - otherwise if an explicit fsync is made
7243 	 *    against an ancestor, the fsync considers the inode in the log
7244 	 *    and doesn't sync the log, resulting in the ancestor missing after
7245 	 *    a power failure unless the log was synced as part of an fsync
7246 	 *    against any other unrelated inode.
7247 	 */
7248 	if (!ctx->logging_new_name && log_mode != LOG_INODE_EXISTS)
7249 		inode->last_log_commit = inode->last_sub_trans;
7250 	spin_unlock(&inode->lock);
7251 
7252 	/*
7253 	 * Reset the last_reflink_trans so that the next fsync does not need to
7254 	 * go through the slower path when logging extents and their checksums.
7255 	 */
7256 	if (log_mode == LOG_INODE_ALL)
7257 		inode->last_reflink_trans = 0;
7258 
7259 out_unlock:
7260 	mutex_unlock(&inode->log_mutex);
7261 out:
7262 	btrfs_free_path(path);
7263 	btrfs_free_path(dst_path);
7264 
7265 	if (ret)
7266 		free_conflicting_inodes(ctx);
7267 	else
7268 		ret = log_conflicting_inodes(trans, inode->root, ctx);
7269 
7270 	if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
7271 		if (!ret)
7272 			ret = log_new_delayed_dentries(trans, inode,
7273 						       &delayed_ins_list, ctx);
7274 
7275 		btrfs_log_put_delayed_items(inode, &delayed_ins_list,
7276 					    &delayed_del_list);
7277 	}
7278 
7279 	trace_btrfs_log_inode_exit(trans, inode, ret);
7280 
7281 	return ret;
7282 }
7283 
7284 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
7285 				 struct btrfs_inode *inode,
7286 				 struct btrfs_log_ctx *ctx)
7287 {
7288 	int ret;
7289 	BTRFS_PATH_AUTO_FREE(path);
7290 	struct btrfs_key key;
7291 	struct btrfs_root *root = inode->root;
7292 	const u64 ino = btrfs_ino(inode);
7293 
7294 	trace_btrfs_log_all_parents_enter(trans, inode);
7295 
7296 	path = btrfs_alloc_path();
7297 	if (!path) {
7298 		ret = -ENOMEM;
7299 		goto out;
7300 	}
7301 	path->skip_locking = true;
7302 	path->search_commit_root = true;
7303 
7304 	key.objectid = ino;
7305 	key.type = BTRFS_INODE_REF_KEY;
7306 	key.offset = 0;
7307 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7308 	if (ret < 0)
7309 		goto out;
7310 
7311 	while (true) {
7312 		struct extent_buffer *leaf = path->nodes[0];
7313 		int slot = path->slots[0];
7314 		u32 cur_offset = 0;
7315 		u32 item_size;
7316 		unsigned long ptr;
7317 
7318 		if (slot >= btrfs_header_nritems(leaf)) {
7319 			ret = btrfs_next_leaf(root, path);
7320 			if (ret < 0)
7321 				goto out;
7322 			if (ret > 0) {
7323 				ret = 0;
7324 				break;
7325 			}
7326 			continue;
7327 		}
7328 
7329 		btrfs_item_key_to_cpu(leaf, &key, slot);
7330 		/* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
7331 		if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
7332 			break;
7333 
7334 		item_size = btrfs_item_size(leaf, slot);
7335 		ptr = btrfs_item_ptr_offset(leaf, slot);
7336 		while (cur_offset < item_size) {
7337 			u64 dir_id;
7338 			struct btrfs_inode *dir_inode;
7339 
7340 			if (key.type == BTRFS_INODE_EXTREF_KEY) {
7341 				struct btrfs_inode_extref *extref;
7342 
7343 				extref = (struct btrfs_inode_extref *)
7344 					(ptr + cur_offset);
7345 				dir_id = btrfs_inode_extref_parent(leaf, extref);
7346 				cur_offset += sizeof(*extref);
7347 				cur_offset += btrfs_inode_extref_name_len(leaf,
7348 					extref);
7349 			} else {
7350 				dir_id = key.offset;
7351 				cur_offset = item_size;
7352 			}
7353 
7354 			dir_inode = btrfs_iget_logging(dir_id, root);
7355 			/*
7356 			 * If the parent inode was deleted, return an error to
7357 			 * fallback to a transaction commit. This is to prevent
7358 			 * getting an inode that was moved from one parent A to
7359 			 * a parent B, got its former parent A deleted and then
7360 			 * it got fsync'ed, from existing at both parents after
7361 			 * a log replay (and the old parent still existing).
7362 			 * Example:
7363 			 *
7364 			 * mkdir /mnt/A
7365 			 * mkdir /mnt/B
7366 			 * touch /mnt/B/bar
7367 			 * sync
7368 			 * mv /mnt/B/bar /mnt/A/bar
7369 			 * mv -T /mnt/A /mnt/B
7370 			 * fsync /mnt/B/bar
7371 			 * <power fail>
7372 			 *
7373 			 * If we ignore the old parent B which got deleted,
7374 			 * after a log replay we would have file bar linked
7375 			 * at both parents and the old parent B would still
7376 			 * exist.
7377 			 */
7378 			if (IS_ERR(dir_inode)) {
7379 				ret = PTR_ERR(dir_inode);
7380 				goto out;
7381 			}
7382 
7383 			if (!need_log_inode(trans, dir_inode)) {
7384 				btrfs_add_delayed_iput(dir_inode);
7385 				continue;
7386 			}
7387 
7388 			ctx->log_new_dentries = false;
7389 			ret = btrfs_log_inode(trans, dir_inode, LOG_INODE_ALL, ctx);
7390 			if (!ret && ctx->log_new_dentries)
7391 				ret = log_new_dir_dentries(trans, dir_inode, ctx);
7392 			btrfs_add_delayed_iput(dir_inode);
7393 			if (ret)
7394 				goto out;
7395 		}
7396 		path->slots[0]++;
7397 	}
7398 out:
7399 	trace_btrfs_log_all_parents_exit(trans, inode, ret);
7400 
7401 	return ret;
7402 }
7403 
7404 static int log_new_ancestors(struct btrfs_trans_handle *trans,
7405 			     struct btrfs_root *root,
7406 			     struct btrfs_path *path,
7407 			     struct btrfs_log_ctx *ctx)
7408 {
7409 	struct btrfs_key found_key;
7410 
7411 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
7412 
7413 	while (true) {
7414 		struct extent_buffer *leaf;
7415 		int slot;
7416 		struct btrfs_key search_key;
7417 		struct btrfs_inode *inode;
7418 		u64 ino;
7419 		int ret = 0;
7420 
7421 		btrfs_release_path(path);
7422 
7423 		ino = found_key.offset;
7424 
7425 		search_key.objectid = found_key.offset;
7426 		search_key.type = BTRFS_INODE_ITEM_KEY;
7427 		search_key.offset = 0;
7428 		inode = btrfs_iget_logging(ino, root);
7429 		if (IS_ERR(inode))
7430 			return PTR_ERR(inode);
7431 
7432 		if (inode->generation >= trans->transid &&
7433 		    need_log_inode(trans, inode))
7434 			ret = btrfs_log_inode(trans, inode, LOG_INODE_EXISTS, ctx);
7435 		btrfs_add_delayed_iput(inode);
7436 		if (ret)
7437 			return ret;
7438 
7439 		if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
7440 			break;
7441 
7442 		search_key.type = BTRFS_INODE_REF_KEY;
7443 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
7444 		if (ret < 0)
7445 			return ret;
7446 
7447 		leaf = path->nodes[0];
7448 		slot = path->slots[0];
7449 		if (slot >= btrfs_header_nritems(leaf)) {
7450 			ret = btrfs_next_leaf(root, path);
7451 			if (ret < 0)
7452 				return ret;
7453 			else if (ret > 0)
7454 				return -ENOENT;
7455 			leaf = path->nodes[0];
7456 			slot = path->slots[0];
7457 		}
7458 
7459 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
7460 		if (found_key.objectid != search_key.objectid ||
7461 		    found_key.type != BTRFS_INODE_REF_KEY)
7462 			return -ENOENT;
7463 	}
7464 	return 0;
7465 }
7466 
7467 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
7468 				  struct btrfs_inode *inode,
7469 				  struct dentry *parent,
7470 				  struct btrfs_log_ctx *ctx)
7471 {
7472 	struct btrfs_root *root = inode->root;
7473 	struct dentry *old_parent = NULL;
7474 	struct super_block *sb = inode->vfs_inode.i_sb;
7475 	int ret = 0;
7476 
7477 	while (true) {
7478 		if (!parent || d_really_is_negative(parent) ||
7479 		    sb != parent->d_sb)
7480 			break;
7481 
7482 		inode = BTRFS_I(d_inode(parent));
7483 		if (root != inode->root)
7484 			break;
7485 
7486 		if (inode->generation >= trans->transid &&
7487 		    need_log_inode(trans, inode)) {
7488 			ret = btrfs_log_inode(trans, inode,
7489 					      LOG_INODE_EXISTS, ctx);
7490 			if (ret)
7491 				break;
7492 		}
7493 		if (IS_ROOT(parent))
7494 			break;
7495 
7496 		parent = dget_parent(parent);
7497 		dput(old_parent);
7498 		old_parent = parent;
7499 	}
7500 	dput(old_parent);
7501 
7502 	return ret;
7503 }
7504 
7505 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
7506 				 struct btrfs_inode *inode,
7507 				 struct dentry *parent,
7508 				 struct btrfs_log_ctx *ctx)
7509 {
7510 	struct btrfs_root *root = inode->root;
7511 	const u64 ino = btrfs_ino(inode);
7512 	BTRFS_PATH_AUTO_FREE(path);
7513 	struct btrfs_key search_key;
7514 	int ret;
7515 
7516 	trace_btrfs_log_all_new_ancestors_enter(trans, inode);
7517 
7518 	/*
7519 	 * For a single hard link case, go through a fast path that does not
7520 	 * need to iterate the fs/subvolume tree.
7521 	 */
7522 	if (inode->vfs_inode.i_nlink < 2) {
7523 		ret = log_new_ancestors_fast(trans, inode, parent, ctx);
7524 		goto out;
7525 	}
7526 
7527 	path = btrfs_alloc_path();
7528 	if (!path) {
7529 		ret = -ENOMEM;
7530 		goto out;
7531 	}
7532 
7533 	search_key.objectid = ino;
7534 	search_key.type = BTRFS_INODE_REF_KEY;
7535 	search_key.offset = 0;
7536 again:
7537 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
7538 	if (ret < 0)
7539 		goto out;
7540 	if (ret == 0)
7541 		path->slots[0]++;
7542 
7543 	while (true) {
7544 		struct extent_buffer *leaf = path->nodes[0];
7545 		int slot = path->slots[0];
7546 		struct btrfs_key found_key;
7547 
7548 		if (slot >= btrfs_header_nritems(leaf)) {
7549 			ret = btrfs_next_leaf(root, path);
7550 			if (ret < 0)
7551 				goto out;
7552 			if (ret > 0) {
7553 				ret = 0;
7554 				break;
7555 			}
7556 			continue;
7557 		}
7558 
7559 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
7560 		if (found_key.objectid != ino ||
7561 		    found_key.type > BTRFS_INODE_EXTREF_KEY)
7562 			break;
7563 
7564 		/*
7565 		 * Don't deal with extended references because they are rare
7566 		 * cases and too complex to deal with (we would need to keep
7567 		 * track of which subitem we are processing for each item in
7568 		 * this loop, etc). So just return some error to fallback to
7569 		 * a transaction commit.
7570 		 */
7571 		if (found_key.type == BTRFS_INODE_EXTREF_KEY) {
7572 			ret = -EMLINK;
7573 			goto out;
7574 		}
7575 
7576 		/*
7577 		 * Logging ancestors needs to do more searches on the fs/subvol
7578 		 * tree, so it releases the path as needed to avoid deadlocks.
7579 		 * Keep track of the last inode ref key and resume from that key
7580 		 * after logging all new ancestors for the current hard link.
7581 		 */
7582 		memcpy(&search_key, &found_key, sizeof(search_key));
7583 
7584 		ret = log_new_ancestors(trans, root, path, ctx);
7585 		if (ret)
7586 			goto out;
7587 		btrfs_release_path(path);
7588 		goto again;
7589 	}
7590 out:
7591 	trace_btrfs_log_all_new_ancestors_exit(trans, inode, ret);
7592 	return ret;
7593 }
7594 
7595 /*
7596  * helper function around btrfs_log_inode to make sure newly created
7597  * parent directories also end up in the log.  A minimal inode and backref
7598  * only logging is done of any parent directories that are older than
7599  * the last committed transaction
7600  */
7601 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
7602 				  struct btrfs_inode *inode,
7603 				  struct dentry *parent,
7604 				  enum btrfs_log_mode log_mode,
7605 				  struct btrfs_log_ctx *ctx)
7606 {
7607 	struct btrfs_root *root = inode->root;
7608 	struct btrfs_fs_info *fs_info = root->fs_info;
7609 	int ret = 0;
7610 	bool log_dentries;
7611 
7612 	trace_btrfs_log_inode_parent_enter(trans, inode);
7613 
7614 	if (btrfs_test_opt(fs_info, NOTREELOG)) {
7615 		ret = BTRFS_LOG_FORCE_COMMIT;
7616 		goto out;
7617 	}
7618 
7619 	if (btrfs_root_refs(&root->root_item) == 0) {
7620 		ret = BTRFS_LOG_FORCE_COMMIT;
7621 		goto out;
7622 	}
7623 
7624 	/*
7625 	 * If we're logging an inode from a subvolume created in the current
7626 	 * transaction we must force a commit since the root is not persisted.
7627 	 */
7628 	if (btrfs_root_generation(&root->root_item) == trans->transid) {
7629 		ret = BTRFS_LOG_FORCE_COMMIT;
7630 		goto out;
7631 	}
7632 
7633 	/* Skip already logged inodes and without new extents. */
7634 	if (btrfs_inode_in_log(inode, trans->transid) &&
7635 	    list_empty(&ctx->ordered_extents)) {
7636 		ret = BTRFS_NO_LOG_SYNC;
7637 		goto out;
7638 	}
7639 
7640 	ret = start_log_trans(trans, root, ctx);
7641 	if (ret)
7642 		goto out;
7643 
7644 	ret = btrfs_log_inode(trans, inode, log_mode, ctx);
7645 	if (ret)
7646 		goto end_trans;
7647 
7648 	/*
7649 	 * for regular files, if its inode is already on disk, we don't
7650 	 * have to worry about the parents at all.  This is because
7651 	 * we can use the last_unlink_trans field to record renames
7652 	 * and other fun in this file.
7653 	 */
7654 	if (S_ISREG(inode->vfs_inode.i_mode) &&
7655 	    inode->generation < trans->transid &&
7656 	    inode->last_unlink_trans < trans->transid) {
7657 		ret = 0;
7658 		goto end_trans;
7659 	}
7660 
7661 	/*
7662 	 * Track if we need to log dentries because ctx->log_new_dentries can
7663 	 * be modified in the call chains below.
7664 	 */
7665 	log_dentries = ctx->log_new_dentries;
7666 
7667 	/*
7668 	 * On unlink we must make sure all our current and old parent directory
7669 	 * inodes are fully logged. This is to prevent leaving dangling
7670 	 * directory index entries in directories that were our parents but are
7671 	 * not anymore. Not doing this results in old parent directory being
7672 	 * impossible to delete after log replay (rmdir will always fail with
7673 	 * error -ENOTEMPTY).
7674 	 *
7675 	 * Example 1:
7676 	 *
7677 	 * mkdir testdir
7678 	 * touch testdir/foo
7679 	 * ln testdir/foo testdir/bar
7680 	 * sync
7681 	 * unlink testdir/bar
7682 	 * xfs_io -c fsync testdir/foo
7683 	 * <power failure>
7684 	 * mount fs, triggers log replay
7685 	 *
7686 	 * If we don't log the parent directory (testdir), after log replay the
7687 	 * directory still has an entry pointing to the file inode using the bar
7688 	 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
7689 	 * the file inode has a link count of 1.
7690 	 *
7691 	 * Example 2:
7692 	 *
7693 	 * mkdir testdir
7694 	 * touch foo
7695 	 * ln foo testdir/foo2
7696 	 * ln foo testdir/foo3
7697 	 * sync
7698 	 * unlink testdir/foo3
7699 	 * xfs_io -c fsync foo
7700 	 * <power failure>
7701 	 * mount fs, triggers log replay
7702 	 *
7703 	 * Similar as the first example, after log replay the parent directory
7704 	 * testdir still has an entry pointing to the inode file with name foo3
7705 	 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
7706 	 * and has a link count of 2.
7707 	 */
7708 	if (inode->last_unlink_trans >= trans->transid) {
7709 		ret = btrfs_log_all_parents(trans, inode, ctx);
7710 		if (ret)
7711 			goto end_trans;
7712 	}
7713 
7714 	ret = log_all_new_ancestors(trans, inode, parent, ctx);
7715 	if (ret)
7716 		goto end_trans;
7717 
7718 	if (log_dentries)
7719 		ret = log_new_dir_dentries(trans, inode, ctx);
7720 end_trans:
7721 	if (ret < 0) {
7722 		btrfs_set_log_full_commit(trans);
7723 		ret = BTRFS_LOG_FORCE_COMMIT;
7724 	}
7725 
7726 	if (ret)
7727 		btrfs_remove_log_ctx(root, ctx);
7728 	btrfs_end_log_trans(root);
7729 
7730 out:
7731 	trace_btrfs_log_inode_parent_exit(trans, inode, ret);
7732 
7733 	return ret;
7734 }
7735 
7736 /*
7737  * it is not safe to log dentry if the chunk root has added new
7738  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
7739  * If this returns 1, you must commit the transaction to safely get your
7740  * data on disk.
7741  */
7742 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7743 			  struct dentry *dentry,
7744 			  struct btrfs_log_ctx *ctx)
7745 {
7746 	struct dentry *parent = dget_parent(dentry);
7747 	int ret;
7748 
7749 	ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
7750 				     LOG_INODE_ALL, ctx);
7751 	dput(parent);
7752 
7753 	return ret;
7754 }
7755 
7756 /*
7757  * should be called during mount to recover any replay any log trees
7758  * from the FS
7759  */
7760 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7761 {
7762 	int ret;
7763 	struct btrfs_path *path;
7764 	struct btrfs_trans_handle *trans;
7765 	struct btrfs_key key;
7766 	struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7767 	struct walk_control wc = {
7768 		.process_func = process_one_buffer,
7769 		.stage = LOG_WALK_PIN_ONLY,
7770 	};
7771 
7772 	path = btrfs_alloc_path();
7773 	if (!path)
7774 		return -ENOMEM;
7775 
7776 	set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7777 
7778 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
7779 	if (IS_ERR(trans)) {
7780 		ret = PTR_ERR(trans);
7781 		goto error;
7782 	}
7783 
7784 	wc.trans = trans;
7785 	wc.pin = true;
7786 	wc.log = log_root_tree;
7787 
7788 	ret = walk_log_tree(&wc);
7789 	wc.log = NULL;
7790 	if (unlikely(ret)) {
7791 		btrfs_abort_transaction(trans, ret);
7792 		goto error;
7793 	}
7794 
7795 again:
7796 	key.objectid = BTRFS_TREE_LOG_OBJECTID;
7797 	key.type = BTRFS_ROOT_ITEM_KEY;
7798 	key.offset = (u64)-1;
7799 
7800 	while (1) {
7801 		struct btrfs_key found_key;
7802 
7803 		ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
7804 
7805 		if (unlikely(ret < 0)) {
7806 			btrfs_abort_transaction(trans, ret);
7807 			goto error;
7808 		}
7809 		if (ret > 0) {
7810 			if (path->slots[0] == 0)
7811 				break;
7812 			path->slots[0]--;
7813 		}
7814 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7815 				      path->slots[0]);
7816 		btrfs_release_path(path);
7817 		if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7818 			break;
7819 
7820 		wc.log = btrfs_read_tree_root(log_root_tree, &found_key);
7821 		if (IS_ERR(wc.log)) {
7822 			ret = PTR_ERR(wc.log);
7823 			wc.log = NULL;
7824 			btrfs_abort_transaction(trans, ret);
7825 			goto error;
7826 		}
7827 
7828 		wc.root = btrfs_get_fs_root(fs_info, found_key.offset, true);
7829 		if (IS_ERR(wc.root)) {
7830 			ret = PTR_ERR(wc.root);
7831 			wc.root = NULL;
7832 			if (unlikely(ret != -ENOENT)) {
7833 				btrfs_abort_transaction(trans, ret);
7834 				goto error;
7835 			}
7836 
7837 			/*
7838 			 * We didn't find the subvol, likely because it was
7839 			 * deleted.  This is ok, simply skip this log and go to
7840 			 * the next one.
7841 			 *
7842 			 * We need to exclude the root because we can't have
7843 			 * other log replays overwriting this log as we'll read
7844 			 * it back in a few more times.  This will keep our
7845 			 * block from being modified, and we'll just bail for
7846 			 * each subsequent pass.
7847 			 */
7848 			ret = btrfs_pin_extent_for_log_replay(trans, wc.log->node);
7849 			if (unlikely(ret)) {
7850 				btrfs_abort_transaction(trans, ret);
7851 				goto error;
7852 			}
7853 			goto next;
7854 		}
7855 
7856 		wc.root->log_root = wc.log;
7857 		ret = btrfs_record_root_in_trans(trans, wc.root);
7858 		if (unlikely(ret)) {
7859 			btrfs_abort_transaction(trans, ret);
7860 			goto next;
7861 		}
7862 
7863 		ret = walk_log_tree(&wc);
7864 		if (unlikely(ret)) {
7865 			btrfs_abort_transaction(trans, ret);
7866 			goto next;
7867 		}
7868 
7869 		if (wc.stage == LOG_WALK_REPLAY_ALL) {
7870 			struct btrfs_root *root = wc.root;
7871 
7872 			wc.subvol_path = path;
7873 			ret = fixup_inode_link_counts(&wc);
7874 			wc.subvol_path = NULL;
7875 			if (unlikely(ret)) {
7876 				btrfs_abort_transaction(trans, ret);
7877 				goto next;
7878 			}
7879 			/*
7880 			 * We have just replayed everything, and the highest
7881 			 * objectid of fs roots probably has changed in case
7882 			 * some inode_item's got replayed.
7883 			 *
7884 			 * root->objectid_mutex is not acquired as log replay
7885 			 * could only happen during mount.
7886 			 */
7887 			ret = btrfs_init_root_free_objectid(root);
7888 			if (unlikely(ret)) {
7889 				btrfs_abort_transaction(trans, ret);
7890 				goto next;
7891 			}
7892 		}
7893 next:
7894 		if (wc.root) {
7895 			wc.root->log_root = NULL;
7896 			btrfs_put_root(wc.root);
7897 		}
7898 		btrfs_put_root(wc.log);
7899 		wc.log = NULL;
7900 
7901 		if (ret)
7902 			goto error;
7903 		if (found_key.offset == 0)
7904 			break;
7905 		key.offset = found_key.offset - 1;
7906 	}
7907 	btrfs_release_path(path);
7908 
7909 	/* step one is to pin it all, step two is to replay just inodes */
7910 	if (wc.pin) {
7911 		wc.pin = false;
7912 		wc.process_func = replay_one_buffer;
7913 		wc.stage = LOG_WALK_REPLAY_INODES;
7914 		goto again;
7915 	}
7916 	/* step three is to replay everything */
7917 	if (wc.stage < LOG_WALK_REPLAY_ALL) {
7918 		wc.stage++;
7919 		goto again;
7920 	}
7921 
7922 	btrfs_free_path(path);
7923 
7924 	/* step 4: commit the transaction, which also unpins the blocks */
7925 	ret = btrfs_commit_transaction(trans);
7926 	if (ret)
7927 		return ret;
7928 
7929 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7930 
7931 	return 0;
7932 error:
7933 	if (wc.trans)
7934 		btrfs_end_transaction(wc.trans);
7935 	btrfs_put_root(wc.log);
7936 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7937 	btrfs_free_path(path);
7938 	return ret;
7939 }
7940 
7941 /*
7942  * there are some corner cases where we want to force a full
7943  * commit instead of allowing a directory to be logged.
7944  *
7945  * They revolve around files there were unlinked from the directory, and
7946  * this function updates the parent directory so that a full commit is
7947  * properly done if it is fsync'd later after the unlinks are done.
7948  *
7949  * Must be called before the unlink operations (updates to the subvolume tree,
7950  * inodes, etc) are done.
7951  */
7952 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
7953 			     struct btrfs_inode *dir, struct btrfs_inode *inode,
7954 			     bool for_rename)
7955 {
7956 	trace_btrfs_record_unlink_dir(trans, dir, inode, for_rename);
7957 
7958 	/*
7959 	 * when we're logging a file, if it hasn't been renamed
7960 	 * or unlinked, and its inode is fully committed on disk,
7961 	 * we don't have to worry about walking up the directory chain
7962 	 * to log its parents.
7963 	 *
7964 	 * So, we use the last_unlink_trans field to put this transid
7965 	 * into the file.  When the file is logged we check it and
7966 	 * don't log the parents if the file is fully on disk.
7967 	 */
7968 	mutex_lock(&inode->log_mutex);
7969 	inode->last_unlink_trans = trans->transid;
7970 	mutex_unlock(&inode->log_mutex);
7971 
7972 	if (!for_rename)
7973 		return;
7974 
7975 	/*
7976 	 * If this directory was already logged, any new names will be logged
7977 	 * with btrfs_log_new_name() and old names will be deleted from the log
7978 	 * tree with btrfs_del_dir_entries_in_log() or with
7979 	 * btrfs_del_inode_ref_in_log().
7980 	 */
7981 	if (inode_logged(trans, dir, NULL) == 1)
7982 		return;
7983 
7984 	/*
7985 	 * If the inode we're about to unlink was logged before, the log will be
7986 	 * properly updated with the new name with btrfs_log_new_name() and the
7987 	 * old name removed with btrfs_del_dir_entries_in_log() or with
7988 	 * btrfs_del_inode_ref_in_log().
7989 	 */
7990 	if (inode_logged(trans, inode, NULL) == 1)
7991 		return;
7992 
7993 	/*
7994 	 * when renaming files across directories, if the directory
7995 	 * there we're unlinking from gets fsync'd later on, there's
7996 	 * no way to find the destination directory later and fsync it
7997 	 * properly.  So, we have to be conservative and force commits
7998 	 * so the new name gets discovered.
7999 	 */
8000 	mutex_lock(&dir->log_mutex);
8001 	dir->last_unlink_trans = trans->transid;
8002 	mutex_unlock(&dir->log_mutex);
8003 }
8004 
8005 /*
8006  * Make sure that if someone attempts to fsync the parent directory of a deleted
8007  * snapshot, it ends up triggering a transaction commit. This is to guarantee
8008  * that after replaying the log tree of the parent directory's root we will not
8009  * see the snapshot anymore and at log replay time we will not see any log tree
8010  * corresponding to the deleted snapshot's root, which could lead to replaying
8011  * it after replaying the log tree of the parent directory (which would replay
8012  * the snapshot delete operation).
8013  *
8014  * Must be called before the actual snapshot destroy operation (updates to the
8015  * parent root and tree of tree roots trees, etc) are done.
8016  */
8017 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
8018 				   struct btrfs_inode *dir)
8019 {
8020 	trace_btrfs_record_snapshot_destroy(trans, dir);
8021 
8022 	mutex_lock(&dir->log_mutex);
8023 	dir->last_unlink_trans = trans->transid;
8024 	mutex_unlock(&dir->log_mutex);
8025 }
8026 
8027 /*
8028  * Call this when creating a subvolume in a directory.
8029  * Because we don't commit a transaction when creating a subvolume, we can't
8030  * allow the directory pointing to the subvolume to be logged with an entry that
8031  * points to an unpersisted root if we are still in the transaction used to
8032  * create the subvolume, so make any attempt to log the directory to result in a
8033  * full log sync.
8034  * Also we don't need to worry with renames, since btrfs_rename() marks the log
8035  * for full commit when renaming a subvolume.
8036  *
8037  * Must be called before creating the subvolume entry in its parent directory.
8038  */
8039 void btrfs_record_new_subvolume(const struct btrfs_trans_handle *trans,
8040 				struct btrfs_inode *dir)
8041 {
8042 	trace_btrfs_record_new_subvolume(trans, dir);
8043 
8044 	mutex_lock(&dir->log_mutex);
8045 	dir->last_unlink_trans = trans->transid;
8046 	mutex_unlock(&dir->log_mutex);
8047 }
8048 
8049 /*
8050  * Update the log after adding a new name for an inode.
8051  *
8052  * @trans:              Transaction handle.
8053  * @old_dentry:         The dentry associated with the old name and the old
8054  *                      parent directory.
8055  * @old_dir:            The inode of the previous parent directory for the case
8056  *                      of a rename. For a link operation, it must be NULL.
8057  * @old_dir_index:      The index number associated with the old name, meaningful
8058  *                      only for rename operations (when @old_dir is not NULL).
8059  *                      Ignored for link operations.
8060  * @parent:             The dentry associated with the directory under which the
8061  *                      new name is located.
8062  *
8063  * Call this after adding a new name for an inode, as a result of a link or
8064  * rename operation, and it will properly update the log to reflect the new name.
8065  */
8066 void btrfs_log_new_name(struct btrfs_trans_handle *trans,
8067 			struct dentry *old_dentry, struct btrfs_inode *old_dir,
8068 			u64 old_dir_index, struct dentry *parent)
8069 {
8070 	struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
8071 	struct btrfs_root *root = inode->root;
8072 	struct btrfs_log_ctx ctx;
8073 	bool log_pinned = false;
8074 	int ret;
8075 
8076 	trace_btrfs_log_new_name_enter(trans, inode, old_dir, old_dir_index);
8077 
8078 	/* The inode has a new name (ref/extref), so make sure we log it. */
8079 	set_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
8080 
8081 	btrfs_init_log_ctx(&ctx, inode);
8082 	ctx.logging_new_name = true;
8083 
8084 	/*
8085 	 * this will force the logging code to walk the dentry chain
8086 	 * up for the file
8087 	 */
8088 	if (!S_ISDIR(inode->vfs_inode.i_mode))
8089 		inode->last_unlink_trans = trans->transid;
8090 
8091 	/*
8092 	 * if this inode hasn't been logged and directory we're renaming it
8093 	 * from hasn't been logged, we don't need to log it
8094 	 */
8095 	ret = inode_logged(trans, inode, NULL);
8096 	if (ret < 0) {
8097 		goto out;
8098 	} else if (ret == 0) {
8099 		if (!old_dir)
8100 			goto out;
8101 		/*
8102 		 * If the inode was not logged and we are doing a rename (old_dir is not
8103 		 * NULL), check if old_dir was logged - if it was not we can return and
8104 		 * do nothing.
8105 		 */
8106 		ret = inode_logged(trans, old_dir, NULL);
8107 		if (ret < 0)
8108 			goto out;
8109 		else if (ret == 0)
8110 			goto out;
8111 	}
8112 	ret = 0;
8113 
8114 	/*
8115 	 * Now that we know we need to update the log, allocate the scratch eb
8116 	 * for the context before joining a log transaction below, as this can
8117 	 * take time and therefore we could delay log commits from other tasks.
8118 	 */
8119 	btrfs_init_log_ctx_scratch_eb(&ctx);
8120 
8121 	/*
8122 	 * If we are doing a rename (old_dir is not NULL) from a directory that
8123 	 * was previously logged, make sure that on log replay we get the old
8124 	 * dir entry deleted. This is needed because we will also log the new
8125 	 * name of the renamed inode, so we need to make sure that after log
8126 	 * replay we don't end up with both the new and old dir entries existing.
8127 	 */
8128 	if (old_dir && old_dir->logged_trans == trans->transid) {
8129 		struct btrfs_root *log = old_dir->root->log_root;
8130 		struct btrfs_path *path;
8131 		struct fscrypt_name fname;
8132 
8133 		ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX,
8134 		       "old_dir_index=%llu", old_dir_index);
8135 
8136 		ret = fscrypt_setup_filename(&old_dir->vfs_inode,
8137 					     &old_dentry->d_name, 0, &fname);
8138 		if (ret)
8139 			goto out;
8140 
8141 		path = btrfs_alloc_path();
8142 		if (!path) {
8143 			ret = -ENOMEM;
8144 			fscrypt_free_filename(&fname);
8145 			goto out;
8146 		}
8147 
8148 		/*
8149 		 * We have two inodes to update in the log, the old directory and
8150 		 * the inode that got renamed, so we must pin the log to prevent
8151 		 * anyone from syncing the log until we have updated both inodes
8152 		 * in the log.
8153 		 */
8154 		ret = join_running_log_trans(root);
8155 		/*
8156 		 * At least one of the inodes was logged before, so this should
8157 		 * not fail, but if it does, it's not serious, just bail out and
8158 		 * mark the log for a full commit.
8159 		 */
8160 		if (WARN_ON_ONCE(ret < 0)) {
8161 			btrfs_free_path(path);
8162 			fscrypt_free_filename(&fname);
8163 			goto out;
8164 		}
8165 
8166 		log_pinned = true;
8167 
8168 		/*
8169 		 * Other concurrent task might be logging the old directory,
8170 		 * as it can be triggered when logging other inode that had or
8171 		 * still has a dentry in the old directory. We lock the old
8172 		 * directory's log_mutex to ensure the deletion of the old
8173 		 * name is persisted, because during directory logging we
8174 		 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
8175 		 * the old name's dir index item is in the delayed items, so
8176 		 * it could be missed by an in progress directory logging.
8177 		 */
8178 		mutex_lock(&old_dir->log_mutex);
8179 		ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
8180 					&fname.disk_name, old_dir_index);
8181 		if (ret > 0) {
8182 			/*
8183 			 * The dentry does not exist in the log, so record its
8184 			 * deletion.
8185 			 */
8186 			btrfs_release_path(path);
8187 			ret = insert_dir_log_key(trans, log, path,
8188 						 btrfs_ino(old_dir),
8189 						 old_dir_index, old_dir_index);
8190 		}
8191 		mutex_unlock(&old_dir->log_mutex);
8192 
8193 		btrfs_free_path(path);
8194 		fscrypt_free_filename(&fname);
8195 		if (ret < 0)
8196 			goto out;
8197 	}
8198 
8199 	/*
8200 	 * We don't care about the return value. If we fail to log the new name
8201 	 * then we know the next attempt to sync the log will fallback to a full
8202 	 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
8203 	 * we don't need to worry about getting a log committed that has an
8204 	 * inconsistent state after a rename operation.
8205 	 */
8206 	btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
8207 	ASSERT(list_empty(&ctx.conflict_inodes));
8208 out:
8209 	trace_btrfs_log_new_name_exit(trans, inode, old_dir, ret);
8210 	/*
8211 	 * If an error happened mark the log for a full commit because it's not
8212 	 * consistent and up to date or we couldn't find out if one of the
8213 	 * inodes was logged before in this transaction. Do it before unpinning
8214 	 * the log, to avoid any races with someone else trying to commit it.
8215 	 */
8216 	if (ret < 0)
8217 		btrfs_set_log_full_commit(trans);
8218 	if (log_pinned)
8219 		btrfs_end_log_trans(root);
8220 	free_extent_buffer(ctx.scratch_eb);
8221 }
8222 
8223