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