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