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