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