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