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