xref: /linux/fs/btrfs/tree-log.c (revision b51ad67773fbe9a03945843215b2cabffafa4084)
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 gen = BTRFS_I(inode)->generation;
4620 	u64 flags;
4621 
4622 	if (log_inode_only) {
4623 		/*
4624 		 * Set the generation to zero so the recover code can tell the
4625 		 * difference between a logging just to say 'this inode exists'
4626 		 * and a logging to say 'update this inode with these values'.
4627 		 * But only if the inode was not already logged before.
4628 		 * We access ->logged_trans directly since it was already set
4629 		 * up in the call chain by btrfs_log_inode(), and data_race()
4630 		 * to avoid false alerts from KCSAN and since it was set already
4631 		 * and one can set it to 0 since that only happens on eviction
4632 		 * and we are holding a ref on the inode.
4633 		 */
4634 		ASSERT(data_race(BTRFS_I(inode)->logged_trans) > 0);
4635 		if (data_race(BTRFS_I(inode)->logged_trans) < trans->transid)
4636 			gen = 0;
4637 
4638 		btrfs_set_inode_size(leaf, item, logged_isize);
4639 	} else {
4640 		btrfs_set_inode_size(leaf, item, inode->i_size);
4641 	}
4642 
4643 	btrfs_set_inode_generation(leaf, item, gen);
4644 
4645 	btrfs_set_inode_uid(leaf, item, i_uid_read(inode));
4646 	btrfs_set_inode_gid(leaf, item, i_gid_read(inode));
4647 	btrfs_set_inode_mode(leaf, item, inode->i_mode);
4648 	btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
4649 
4650 	btrfs_set_timespec_sec(leaf, &item->atime, inode_get_atime_sec(inode));
4651 	btrfs_set_timespec_nsec(leaf, &item->atime, inode_get_atime_nsec(inode));
4652 
4653 	btrfs_set_timespec_sec(leaf, &item->mtime, inode_get_mtime_sec(inode));
4654 	btrfs_set_timespec_nsec(leaf, &item->mtime, inode_get_mtime_nsec(inode));
4655 
4656 	btrfs_set_timespec_sec(leaf, &item->ctime, inode_get_ctime_sec(inode));
4657 	btrfs_set_timespec_nsec(leaf, &item->ctime, inode_get_ctime_nsec(inode));
4658 
4659 	btrfs_set_timespec_sec(leaf, &item->otime, BTRFS_I(inode)->i_otime_sec);
4660 	btrfs_set_timespec_nsec(leaf, &item->otime, BTRFS_I(inode)->i_otime_nsec);
4661 
4662 	/*
4663 	 * We do not need to set the nbytes field, in fact during a fast fsync
4664 	 * its value may not even be correct, since a fast fsync does not wait
4665 	 * for ordered extent completion, which is where we update nbytes, it
4666 	 * only waits for writeback to complete. During log replay as we find
4667 	 * file extent items and replay them, we adjust the nbytes field of the
4668 	 * inode item in subvolume tree as needed (see overwrite_item()).
4669 	 */
4670 
4671 	btrfs_set_inode_sequence(leaf, item, inode_peek_iversion(inode));
4672 	btrfs_set_inode_transid(leaf, item, trans->transid);
4673 	btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
4674 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4675 					  BTRFS_I(inode)->ro_flags);
4676 	btrfs_set_inode_flags(leaf, item, flags);
4677 	btrfs_set_inode_block_group(leaf, item, 0);
4678 }
4679 
log_inode_item(struct btrfs_trans_handle * trans,struct btrfs_root * log,struct btrfs_path * path,struct btrfs_inode * inode,bool inode_item_dropped)4680 static int log_inode_item(struct btrfs_trans_handle *trans,
4681 			  struct btrfs_root *log, struct btrfs_path *path,
4682 			  struct btrfs_inode *inode, bool inode_item_dropped)
4683 {
4684 	struct btrfs_inode_item *inode_item;
4685 	struct btrfs_key key;
4686 	int ret;
4687 
4688 	btrfs_get_inode_key(inode, &key);
4689 	/*
4690 	 * If we are doing a fast fsync and the inode was logged before in the
4691 	 * current transaction, then we know the inode was previously logged and
4692 	 * it exists in the log tree. For performance reasons, in this case use
4693 	 * btrfs_search_slot() directly with ins_len set to 0 so that we never
4694 	 * attempt a write lock on the leaf's parent, which adds unnecessary lock
4695 	 * contention in case there are concurrent fsyncs for other inodes of the
4696 	 * same subvolume. Using btrfs_insert_empty_item() when the inode item
4697 	 * already exists can also result in unnecessarily splitting a leaf.
4698 	 */
4699 	if (!inode_item_dropped && inode->logged_trans == trans->transid) {
4700 		ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
4701 		ASSERT(ret <= 0);
4702 		if (ret > 0)
4703 			ret = -ENOENT;
4704 	} else {
4705 		/*
4706 		 * This means it is the first fsync in the current transaction,
4707 		 * so the inode item is not in the log and we need to insert it.
4708 		 * We can never get -EEXIST because we are only called for a fast
4709 		 * fsync and in case an inode eviction happens after the inode was
4710 		 * logged before in the current transaction, when we load again
4711 		 * the inode, we set BTRFS_INODE_NEEDS_FULL_SYNC on its runtime
4712 		 * flags and set ->logged_trans to 0.
4713 		 */
4714 		ret = btrfs_insert_empty_item(trans, log, path, &key,
4715 					      sizeof(*inode_item));
4716 		ASSERT(ret != -EEXIST);
4717 	}
4718 	if (ret)
4719 		return ret;
4720 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4721 				    struct btrfs_inode_item);
4722 	fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
4723 			false, 0);
4724 	btrfs_release_path(path);
4725 	return 0;
4726 }
4727 
log_csums(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_root * log_root,struct btrfs_ordered_sum * sums)4728 static int log_csums(struct btrfs_trans_handle *trans,
4729 		     struct btrfs_inode *inode,
4730 		     struct btrfs_root *log_root,
4731 		     struct btrfs_ordered_sum *sums)
4732 {
4733 	const u64 lock_end = sums->logical + sums->len - 1;
4734 	struct extent_state *cached_state = NULL;
4735 	int ret;
4736 
4737 	/*
4738 	 * If this inode was not used for reflink operations in the current
4739 	 * transaction with new extents, then do the fast path, no need to
4740 	 * worry about logging checksum items with overlapping ranges.
4741 	 */
4742 	if (inode->last_reflink_trans < trans->transid)
4743 		return btrfs_csum_file_blocks(trans, log_root, sums);
4744 
4745 	/*
4746 	 * Serialize logging for checksums. This is to avoid racing with the
4747 	 * same checksum being logged by another task that is logging another
4748 	 * file which happens to refer to the same extent as well. Such races
4749 	 * can leave checksum items in the log with overlapping ranges.
4750 	 */
4751 	ret = btrfs_lock_extent(&log_root->log_csum_range, sums->logical, lock_end,
4752 				&cached_state);
4753 	if (ret)
4754 		return ret;
4755 	/*
4756 	 * Due to extent cloning, we might have logged a csum item that covers a
4757 	 * subrange of a cloned extent, and later we can end up logging a csum
4758 	 * item for a larger subrange of the same extent or the entire range.
4759 	 * This would leave csum items in the log tree that cover the same range
4760 	 * and break the searches for checksums in the log tree, resulting in
4761 	 * some checksums missing in the fs/subvolume tree. So just delete (or
4762 	 * trim and adjust) any existing csum items in the log for this range.
4763 	 */
4764 	ret = btrfs_del_csums(trans, log_root, sums->logical, sums->len);
4765 	if (!ret)
4766 		ret = btrfs_csum_file_blocks(trans, log_root, sums);
4767 
4768 	btrfs_unlock_extent(&log_root->log_csum_range, sums->logical, lock_end,
4769 			    &cached_state);
4770 
4771 	return ret;
4772 }
4773 
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)4774 static noinline int copy_items(struct btrfs_trans_handle *trans,
4775 			       struct btrfs_inode *inode,
4776 			       struct btrfs_path *dst_path,
4777 			       struct btrfs_path *src_path,
4778 			       int start_slot, int nr, int inode_only,
4779 			       u64 logged_isize, struct btrfs_log_ctx *ctx)
4780 {
4781 	struct btrfs_root *log = inode->root->log_root;
4782 	struct btrfs_file_extent_item *extent;
4783 	struct extent_buffer *src;
4784 	int ret;
4785 	struct btrfs_key *ins_keys;
4786 	u32 *ins_sizes;
4787 	struct btrfs_item_batch batch;
4788 	char AUTO_KFREE(ins_data);
4789 	int dst_index;
4790 	const bool skip_csum = (inode->flags & BTRFS_INODE_NODATASUM);
4791 	const u64 i_size = i_size_read(&inode->vfs_inode);
4792 
4793 	/*
4794 	 * To keep lockdep happy and avoid deadlocks, clone the source leaf and
4795 	 * use the clone. This is because otherwise we would be changing the log
4796 	 * tree, to insert items from the subvolume tree or insert csum items,
4797 	 * while holding a read lock on a leaf from the subvolume tree, which
4798 	 * creates a nasty lock dependency when COWing log tree nodes/leaves:
4799 	 *
4800 	 * 1) Modifying the log tree triggers an extent buffer allocation while
4801 	 *    holding a write lock on a parent extent buffer from the log tree.
4802 	 *    Allocating the pages for an extent buffer, or the extent buffer
4803 	 *    struct, can trigger inode eviction and finally the inode eviction
4804 	 *    will trigger a release/remove of a delayed node, which requires
4805 	 *    taking the delayed node's mutex;
4806 	 *
4807 	 * 2) Allocating a metadata extent for a log tree can trigger the async
4808 	 *    reclaim thread and make us wait for it to release enough space and
4809 	 *    unblock our reservation ticket. The reclaim thread can start
4810 	 *    flushing delayed items, and that in turn results in the need to
4811 	 *    lock delayed node mutexes and in the need to write lock extent
4812 	 *    buffers of a subvolume tree - all this while holding a write lock
4813 	 *    on the parent extent buffer in the log tree.
4814 	 *
4815 	 * So one task in scenario 1) running in parallel with another task in
4816 	 * scenario 2) could lead to a deadlock, one wanting to lock a delayed
4817 	 * node mutex while having a read lock on a leaf from the subvolume,
4818 	 * while the other is holding the delayed node's mutex and wants to
4819 	 * write lock the same subvolume leaf for flushing delayed items.
4820 	 */
4821 	ret = clone_leaf(src_path, ctx);
4822 	if (ret < 0)
4823 		return ret;
4824 
4825 	src = src_path->nodes[0];
4826 
4827 	ins_data = kmalloc_array(nr, sizeof(struct btrfs_key) + sizeof(u32), GFP_NOFS);
4828 	if (!ins_data)
4829 		return -ENOMEM;
4830 
4831 	ins_sizes = (u32 *)ins_data;
4832 	ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
4833 	batch.keys = ins_keys;
4834 	batch.data_sizes = ins_sizes;
4835 	batch.total_data_size = 0;
4836 	batch.nr = 0;
4837 
4838 	dst_index = 0;
4839 	for (int i = 0; i < nr; i++) {
4840 		const int src_slot = start_slot + i;
4841 		struct btrfs_root *csum_root;
4842 		struct btrfs_ordered_sum *sums;
4843 		struct btrfs_ordered_sum *sums_next;
4844 		LIST_HEAD(ordered_sums);
4845 		u64 disk_bytenr;
4846 		u64 disk_num_bytes;
4847 		u64 extent_offset;
4848 		u64 extent_num_bytes;
4849 		bool is_old_extent;
4850 
4851 		btrfs_item_key_to_cpu(src, &ins_keys[dst_index], src_slot);
4852 
4853 		if (ins_keys[dst_index].type != BTRFS_EXTENT_DATA_KEY)
4854 			goto add_to_batch;
4855 
4856 		extent = btrfs_item_ptr(src, src_slot,
4857 					struct btrfs_file_extent_item);
4858 
4859 		is_old_extent = (btrfs_file_extent_generation(src, extent) <
4860 				 trans->transid);
4861 
4862 		/*
4863 		 * Don't copy extents from past generations. That would make us
4864 		 * log a lot more metadata for common cases like doing only a
4865 		 * few random writes into a file and then fsync it for the first
4866 		 * time or after the full sync flag is set on the inode. We can
4867 		 * get leaves full of extent items, most of which are from past
4868 		 * generations, so we can skip them - as long as the inode has
4869 		 * not been the target of a reflink operation in this transaction,
4870 		 * as in that case it might have had file extent items with old
4871 		 * generations copied into it. We also must always log prealloc
4872 		 * extents that start at or beyond eof, otherwise we would lose
4873 		 * them on log replay.
4874 		 */
4875 		if (is_old_extent &&
4876 		    ins_keys[dst_index].offset < i_size &&
4877 		    inode->last_reflink_trans < trans->transid)
4878 			continue;
4879 
4880 		if (skip_csum)
4881 			goto add_to_batch;
4882 
4883 		/* Only regular extents have checksums. */
4884 		if (btrfs_file_extent_type(src, extent) != BTRFS_FILE_EXTENT_REG)
4885 			goto add_to_batch;
4886 
4887 		/*
4888 		 * If it's an extent created in a past transaction, then its
4889 		 * checksums are already accessible from the committed csum tree,
4890 		 * no need to log them.
4891 		 */
4892 		if (is_old_extent)
4893 			goto add_to_batch;
4894 
4895 		disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
4896 		/* If it's an explicit hole, there are no checksums. */
4897 		if (disk_bytenr == 0)
4898 			goto add_to_batch;
4899 
4900 		disk_num_bytes = btrfs_file_extent_disk_num_bytes(src, extent);
4901 
4902 		if (btrfs_file_extent_compression(src, extent)) {
4903 			extent_offset = 0;
4904 			extent_num_bytes = disk_num_bytes;
4905 		} else {
4906 			extent_offset = btrfs_file_extent_offset(src, extent);
4907 			extent_num_bytes = btrfs_file_extent_num_bytes(src, extent);
4908 		}
4909 
4910 		csum_root = btrfs_csum_root(trans->fs_info, disk_bytenr);
4911 		if (unlikely(!csum_root)) {
4912 			btrfs_err(trans->fs_info,
4913 				  "missing csum root for extent at bytenr %llu",
4914 				  disk_bytenr);
4915 			return -EUCLEAN;
4916 		}
4917 
4918 		disk_bytenr += extent_offset;
4919 		ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
4920 					      disk_bytenr + extent_num_bytes - 1,
4921 					      &ordered_sums, false);
4922 		if (ret < 0)
4923 			return ret;
4924 		ret = 0;
4925 
4926 		list_for_each_entry_safe(sums, sums_next, &ordered_sums, list) {
4927 			if (!ret)
4928 				ret = log_csums(trans, inode, log, sums);
4929 			list_del(&sums->list);
4930 			kfree(sums);
4931 		}
4932 		if (ret)
4933 			return ret;
4934 
4935 add_to_batch:
4936 		ins_sizes[dst_index] = btrfs_item_size(src, src_slot);
4937 		batch.total_data_size += ins_sizes[dst_index];
4938 		batch.nr++;
4939 		dst_index++;
4940 	}
4941 
4942 	/*
4943 	 * We have a leaf full of old extent items that don't need to be logged,
4944 	 * so we don't need to do anything.
4945 	 */
4946 	if (batch.nr == 0)
4947 		return 0;
4948 
4949 	ret = btrfs_insert_empty_items(trans, log, dst_path, &batch);
4950 	if (ret)
4951 		return ret;
4952 
4953 	dst_index = 0;
4954 	for (int i = 0; i < nr; i++) {
4955 		const int src_slot = start_slot + i;
4956 		const int dst_slot = dst_path->slots[0] + dst_index;
4957 		struct btrfs_key key;
4958 		unsigned long src_offset;
4959 		unsigned long dst_offset;
4960 
4961 		/*
4962 		 * We're done, all the remaining items in the source leaf
4963 		 * correspond to old file extent items.
4964 		 */
4965 		if (dst_index >= batch.nr)
4966 			break;
4967 
4968 		btrfs_item_key_to_cpu(src, &key, src_slot);
4969 
4970 		if (key.type != BTRFS_EXTENT_DATA_KEY)
4971 			goto copy_item;
4972 
4973 		extent = btrfs_item_ptr(src, src_slot,
4974 					struct btrfs_file_extent_item);
4975 
4976 		/* See the comment in the previous loop, same logic. */
4977 		if (btrfs_file_extent_generation(src, extent) < trans->transid &&
4978 		    key.offset < i_size &&
4979 		    inode->last_reflink_trans < trans->transid)
4980 			continue;
4981 
4982 copy_item:
4983 		dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0], dst_slot);
4984 		src_offset = btrfs_item_ptr_offset(src, src_slot);
4985 
4986 		if (key.type == BTRFS_INODE_ITEM_KEY) {
4987 			struct btrfs_inode_item *inode_item;
4988 
4989 			inode_item = btrfs_item_ptr(dst_path->nodes[0], dst_slot,
4990 						    struct btrfs_inode_item);
4991 			fill_inode_item(trans, dst_path->nodes[0], inode_item,
4992 					&inode->vfs_inode,
4993 					inode_only == LOG_INODE_EXISTS,
4994 					logged_isize);
4995 		} else {
4996 			copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
4997 					   src_offset, ins_sizes[dst_index]);
4998 		}
4999 
5000 		dst_index++;
5001 	}
5002 
5003 	btrfs_release_path(dst_path);
5004 
5005 	return ret;
5006 }
5007 
extent_cmp(void * priv,const struct list_head * a,const struct list_head * b)5008 static int extent_cmp(void *priv, const struct list_head *a,
5009 		      const struct list_head *b)
5010 {
5011 	const struct extent_map *em1, *em2;
5012 
5013 	em1 = list_entry(a, struct extent_map, list);
5014 	em2 = list_entry(b, struct extent_map, list);
5015 
5016 	if (em1->start < em2->start)
5017 		return -1;
5018 	else if (em1->start > em2->start)
5019 		return 1;
5020 	return 0;
5021 }
5022 
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)5023 static int log_extent_csums(struct btrfs_trans_handle *trans,
5024 			    struct btrfs_inode *inode,
5025 			    struct btrfs_root *log_root,
5026 			    const struct extent_map *em,
5027 			    struct btrfs_log_ctx *ctx)
5028 {
5029 	struct btrfs_ordered_extent *ordered;
5030 	struct btrfs_root *csum_root;
5031 	u64 block_start;
5032 	u64 csum_offset;
5033 	u64 csum_len;
5034 	u64 mod_start = em->start;
5035 	u64 mod_len = em->len;
5036 	LIST_HEAD(ordered_sums);
5037 	int ret = 0;
5038 
5039 	if (inode->flags & BTRFS_INODE_NODATASUM ||
5040 	    (em->flags & EXTENT_FLAG_PREALLOC) ||
5041 	    em->disk_bytenr == EXTENT_MAP_HOLE)
5042 		return 0;
5043 
5044 	list_for_each_entry(ordered, &ctx->ordered_extents, log_list) {
5045 		const u64 ordered_end = ordered->file_offset + ordered->num_bytes;
5046 		const u64 mod_end = mod_start + mod_len;
5047 		struct btrfs_ordered_sum *sums;
5048 
5049 		if (mod_len == 0)
5050 			break;
5051 
5052 		if (ordered_end <= mod_start)
5053 			continue;
5054 		if (mod_end <= ordered->file_offset)
5055 			break;
5056 
5057 		/*
5058 		 * We are going to copy all the csums on this ordered extent, so
5059 		 * go ahead and adjust mod_start and mod_len in case this ordered
5060 		 * extent has already been logged.
5061 		 */
5062 		if (ordered->file_offset > mod_start) {
5063 			if (ordered_end >= mod_end)
5064 				mod_len = ordered->file_offset - mod_start;
5065 			/*
5066 			 * If we have this case
5067 			 *
5068 			 * |--------- logged extent ---------|
5069 			 *       |----- ordered extent ----|
5070 			 *
5071 			 * Just don't mess with mod_start and mod_len, we'll
5072 			 * just end up logging more csums than we need and it
5073 			 * will be ok.
5074 			 */
5075 		} else {
5076 			if (ordered_end < mod_end) {
5077 				mod_len = mod_end - ordered_end;
5078 				mod_start = ordered_end;
5079 			} else {
5080 				mod_len = 0;
5081 			}
5082 		}
5083 
5084 		/*
5085 		 * To keep us from looping for the above case of an ordered
5086 		 * extent that falls inside of the logged extent.
5087 		 */
5088 		if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM, &ordered->flags))
5089 			continue;
5090 
5091 		list_for_each_entry(sums, &ordered->list, list) {
5092 			ret = log_csums(trans, inode, log_root, sums);
5093 			if (ret)
5094 				return ret;
5095 		}
5096 	}
5097 
5098 	/* We're done, found all csums in the ordered extents. */
5099 	if (mod_len == 0)
5100 		return 0;
5101 
5102 	/* If we're compressed we have to save the entire range of csums. */
5103 	if (btrfs_extent_map_is_compressed(em)) {
5104 		csum_offset = 0;
5105 		csum_len = em->disk_num_bytes;
5106 	} else {
5107 		csum_offset = mod_start - em->start;
5108 		csum_len = mod_len;
5109 	}
5110 
5111 	/* block start is already adjusted for the file extent offset. */
5112 	block_start = btrfs_extent_map_block_start(em);
5113 	csum_root = btrfs_csum_root(trans->fs_info, block_start);
5114 	if (unlikely(!csum_root)) {
5115 		btrfs_err(trans->fs_info,
5116 			  "missing csum root for extent at bytenr %llu",
5117 			  block_start);
5118 		return -EUCLEAN;
5119 	}
5120 
5121 	ret = btrfs_lookup_csums_list(csum_root, block_start + csum_offset,
5122 				      block_start + csum_offset + csum_len - 1,
5123 				      &ordered_sums, false);
5124 	if (ret < 0)
5125 		return ret;
5126 	ret = 0;
5127 
5128 	while (!list_empty(&ordered_sums)) {
5129 		struct btrfs_ordered_sum *sums = list_first_entry(&ordered_sums,
5130 								  struct btrfs_ordered_sum,
5131 								  list);
5132 		if (!ret)
5133 			ret = log_csums(trans, inode, log_root, sums);
5134 		list_del(&sums->list);
5135 		kfree(sums);
5136 	}
5137 
5138 	return ret;
5139 }
5140 
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)5141 static int log_one_extent(struct btrfs_trans_handle *trans,
5142 			  struct btrfs_inode *inode,
5143 			  const struct extent_map *em,
5144 			  struct btrfs_path *path,
5145 			  struct btrfs_log_ctx *ctx)
5146 {
5147 	struct btrfs_drop_extents_args drop_args = { 0 };
5148 	struct btrfs_root *log = inode->root->log_root;
5149 	struct btrfs_file_extent_item fi = { 0 };
5150 	struct extent_buffer *leaf;
5151 	struct btrfs_key key;
5152 	enum btrfs_compression_type compress_type;
5153 	u64 extent_offset = em->offset;
5154 	u64 block_start = btrfs_extent_map_block_start(em);
5155 	u64 block_len;
5156 	int ret;
5157 
5158 	btrfs_set_stack_file_extent_generation(&fi, trans->transid);
5159 	if (em->flags & EXTENT_FLAG_PREALLOC)
5160 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_PREALLOC);
5161 	else
5162 		btrfs_set_stack_file_extent_type(&fi, BTRFS_FILE_EXTENT_REG);
5163 
5164 	block_len = em->disk_num_bytes;
5165 	compress_type = btrfs_extent_map_compression(em);
5166 	if (compress_type != BTRFS_COMPRESS_NONE) {
5167 		btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
5168 		btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
5169 	} else if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) {
5170 		btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start - extent_offset);
5171 		btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
5172 	}
5173 
5174 	btrfs_set_stack_file_extent_offset(&fi, extent_offset);
5175 	btrfs_set_stack_file_extent_num_bytes(&fi, em->len);
5176 	btrfs_set_stack_file_extent_ram_bytes(&fi, em->ram_bytes);
5177 	btrfs_set_stack_file_extent_compression(&fi, compress_type);
5178 
5179 	ret = log_extent_csums(trans, inode, log, em, ctx);
5180 	if (ret)
5181 		return ret;
5182 
5183 	/*
5184 	 * If this is the first time we are logging the inode in the current
5185 	 * transaction, we can avoid btrfs_drop_extents(), which is expensive
5186 	 * because it does a deletion search, which always acquires write locks
5187 	 * for extent buffers at levels 2, 1 and 0. This not only wastes time
5188 	 * but also adds significant contention in a log tree, since log trees
5189 	 * are small, with a root at level 2 or 3 at most, due to their short
5190 	 * life span.
5191 	 */
5192 	if (ctx->logged_before) {
5193 		drop_args.path = path;
5194 		drop_args.start = em->start;
5195 		drop_args.end = btrfs_extent_map_end(em);
5196 		drop_args.replace_extent = true;
5197 		drop_args.extent_item_size = sizeof(fi);
5198 		ret = btrfs_drop_extents(trans, log, inode, &drop_args);
5199 		if (ret)
5200 			return ret;
5201 	}
5202 
5203 	if (!drop_args.extent_inserted) {
5204 		key.objectid = btrfs_ino(inode);
5205 		key.type = BTRFS_EXTENT_DATA_KEY;
5206 		key.offset = em->start;
5207 
5208 		ret = btrfs_insert_empty_item(trans, log, path, &key,
5209 					      sizeof(fi));
5210 		if (ret)
5211 			return ret;
5212 	}
5213 	leaf = path->nodes[0];
5214 	write_extent_buffer(leaf, &fi,
5215 			    btrfs_item_ptr_offset(leaf, path->slots[0]),
5216 			    sizeof(fi));
5217 
5218 	btrfs_release_path(path);
5219 
5220 	return ret;
5221 }
5222 
5223 /*
5224  * Log all prealloc extents beyond the inode's i_size to make sure we do not
5225  * lose them after doing a full/fast fsync and replaying the log. We scan the
5226  * subvolume's root instead of iterating the inode's extent map tree because
5227  * otherwise we can log incorrect extent items based on extent map conversion.
5228  * That can happen due to the fact that extent maps are merged when they
5229  * are not in the extent map tree's list of modified extents.
5230  */
btrfs_log_prealloc_extents(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_path * path,struct btrfs_log_ctx * ctx)5231 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
5232 				      struct btrfs_inode *inode,
5233 				      struct btrfs_path *path,
5234 				      struct btrfs_log_ctx *ctx)
5235 {
5236 	struct btrfs_root *root = inode->root;
5237 	struct btrfs_key key;
5238 	const u64 i_size = i_size_read(&inode->vfs_inode);
5239 	const u64 ino = btrfs_ino(inode);
5240 	BTRFS_PATH_AUTO_FREE(dst_path);
5241 	bool dropped_extents = false;
5242 	u64 truncate_offset = i_size;
5243 	struct extent_buffer *leaf;
5244 	int slot;
5245 	int ins_nr = 0;
5246 	int start_slot = 0;
5247 	int ret;
5248 
5249 	if (!(inode->flags & BTRFS_INODE_PREALLOC))
5250 		return 0;
5251 
5252 	key.objectid = ino;
5253 	key.type = BTRFS_EXTENT_DATA_KEY;
5254 	key.offset = i_size;
5255 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5256 	if (ret < 0)
5257 		goto out;
5258 
5259 	/*
5260 	 * We must check if there is a prealloc extent that starts before the
5261 	 * i_size and crosses the i_size boundary. This is to ensure later we
5262 	 * truncate down to the end of that extent and not to the i_size, as
5263 	 * otherwise we end up losing part of the prealloc extent after a log
5264 	 * replay and with an implicit hole if there is another prealloc extent
5265 	 * that starts at an offset beyond i_size.
5266 	 */
5267 	ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
5268 	if (ret < 0)
5269 		goto out;
5270 
5271 	if (ret == 0) {
5272 		struct btrfs_file_extent_item *ei;
5273 
5274 		leaf = path->nodes[0];
5275 		slot = path->slots[0];
5276 		ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5277 
5278 		if (btrfs_file_extent_type(leaf, ei) ==
5279 		    BTRFS_FILE_EXTENT_PREALLOC) {
5280 			u64 extent_end;
5281 
5282 			btrfs_item_key_to_cpu(leaf, &key, slot);
5283 			extent_end = key.offset +
5284 				btrfs_file_extent_num_bytes(leaf, ei);
5285 
5286 			if (extent_end > i_size)
5287 				truncate_offset = extent_end;
5288 		}
5289 	} else {
5290 		ret = 0;
5291 	}
5292 
5293 	while (true) {
5294 		leaf = path->nodes[0];
5295 		slot = path->slots[0];
5296 
5297 		if (slot >= btrfs_header_nritems(leaf)) {
5298 			if (ins_nr > 0) {
5299 				ret = copy_items(trans, inode, dst_path, path,
5300 						 start_slot, ins_nr, 1, 0, ctx);
5301 				if (ret < 0)
5302 					goto out;
5303 				ins_nr = 0;
5304 			}
5305 			ret = btrfs_next_leaf(root, path);
5306 			if (ret < 0)
5307 				goto out;
5308 			if (ret > 0) {
5309 				ret = 0;
5310 				break;
5311 			}
5312 			continue;
5313 		}
5314 
5315 		btrfs_item_key_to_cpu(leaf, &key, slot);
5316 		if (key.objectid > ino)
5317 			break;
5318 		if (WARN_ON_ONCE(key.objectid < ino) ||
5319 		    key.type < BTRFS_EXTENT_DATA_KEY ||
5320 		    key.offset < i_size) {
5321 			path->slots[0]++;
5322 			continue;
5323 		}
5324 		/*
5325 		 * Avoid overlapping items in the log tree. The first time we
5326 		 * get here, get rid of everything from a past fsync. After
5327 		 * that, if the current extent starts before the end of the last
5328 		 * extent we copied, truncate the last one. This can happen if
5329 		 * an ordered extent completion modifies the subvolume tree
5330 		 * while btrfs_next_leaf() has the tree unlocked.
5331 		 */
5332 		if (!dropped_extents || key.offset < truncate_offset) {
5333 			ret = truncate_inode_items(trans, root->log_root, inode,
5334 						   min(key.offset, truncate_offset),
5335 						   BTRFS_EXTENT_DATA_KEY);
5336 			if (ret)
5337 				goto out;
5338 			dropped_extents = true;
5339 		}
5340 		truncate_offset = btrfs_file_extent_end(path);
5341 		if (ins_nr == 0)
5342 			start_slot = slot;
5343 		ins_nr++;
5344 		path->slots[0]++;
5345 		if (!dst_path) {
5346 			dst_path = btrfs_alloc_path();
5347 			if (!dst_path) {
5348 				ret = -ENOMEM;
5349 				goto out;
5350 			}
5351 		}
5352 	}
5353 	if (ins_nr > 0)
5354 		ret = copy_items(trans, inode, dst_path, path,
5355 				 start_slot, ins_nr, 1, 0, ctx);
5356 out:
5357 	btrfs_release_path(path);
5358 	return ret;
5359 }
5360 
btrfs_log_changed_extents(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_path * path,struct btrfs_log_ctx * ctx)5361 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
5362 				     struct btrfs_inode *inode,
5363 				     struct btrfs_path *path,
5364 				     struct btrfs_log_ctx *ctx)
5365 {
5366 	struct btrfs_ordered_extent *ordered;
5367 	struct btrfs_ordered_extent *tmp;
5368 	struct extent_map *em, *n;
5369 	LIST_HEAD(extents);
5370 	struct extent_map_tree *tree = &inode->extent_tree;
5371 	int ret = 0;
5372 	int num = 0;
5373 
5374 	write_lock(&tree->lock);
5375 
5376 	list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
5377 		list_del_init(&em->list);
5378 		/*
5379 		 * Just an arbitrary number, this can be really CPU intensive
5380 		 * once we start getting a lot of extents, and really once we
5381 		 * have a bunch of extents we just want to commit since it will
5382 		 * be faster.
5383 		 */
5384 		if (++num > 32768) {
5385 			list_del_init(&tree->modified_extents);
5386 			ret = -EFBIG;
5387 			goto process;
5388 		}
5389 
5390 		if (em->generation < trans->transid)
5391 			continue;
5392 
5393 		/* We log prealloc extents beyond eof later. */
5394 		if ((em->flags & EXTENT_FLAG_PREALLOC) &&
5395 		    em->start >= i_size_read(&inode->vfs_inode))
5396 			continue;
5397 
5398 		/* Need a ref to keep it from getting evicted from cache */
5399 		refcount_inc(&em->refs);
5400 		em->flags |= EXTENT_FLAG_LOGGING;
5401 		list_add_tail(&em->list, &extents);
5402 		num++;
5403 	}
5404 
5405 	list_sort(NULL, &extents, extent_cmp);
5406 process:
5407 	while (!list_empty(&extents)) {
5408 		em = list_first_entry(&extents, struct extent_map, list);
5409 
5410 		list_del_init(&em->list);
5411 
5412 		/*
5413 		 * If we had an error we just need to delete everybody from our
5414 		 * private list.
5415 		 */
5416 		if (ret) {
5417 			btrfs_clear_em_logging(inode, em);
5418 			btrfs_free_extent_map(em);
5419 			continue;
5420 		}
5421 
5422 		write_unlock(&tree->lock);
5423 
5424 		ret = log_one_extent(trans, inode, em, path, ctx);
5425 		write_lock(&tree->lock);
5426 		btrfs_clear_em_logging(inode, em);
5427 		btrfs_free_extent_map(em);
5428 	}
5429 	WARN_ON(!list_empty(&extents));
5430 	write_unlock(&tree->lock);
5431 
5432 	if (!ret)
5433 		ret = btrfs_log_prealloc_extents(trans, inode, path, ctx);
5434 	if (ret)
5435 		return ret;
5436 
5437 	/*
5438 	 * We have logged all extents successfully, now make sure the commit of
5439 	 * the current transaction waits for the ordered extents to complete
5440 	 * before it commits and wipes out the log trees, otherwise we would
5441 	 * lose data if an ordered extents completes after the transaction
5442 	 * commits and a power failure happens after the transaction commit.
5443 	 */
5444 	list_for_each_entry_safe(ordered, tmp, &ctx->ordered_extents, log_list) {
5445 		list_del_init(&ordered->log_list);
5446 		set_bit(BTRFS_ORDERED_LOGGED, &ordered->flags);
5447 
5448 		if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
5449 			spin_lock(&inode->ordered_tree_lock);
5450 			if (!test_bit(BTRFS_ORDERED_COMPLETE, &ordered->flags)) {
5451 				set_bit(BTRFS_ORDERED_PENDING, &ordered->flags);
5452 				atomic_inc(&trans->transaction->pending_ordered);
5453 			}
5454 			spin_unlock(&inode->ordered_tree_lock);
5455 		}
5456 		btrfs_put_ordered_extent(ordered);
5457 	}
5458 
5459 	return 0;
5460 }
5461 
get_inode_size_to_log(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_path * path,u64 * size_ret)5462 static int get_inode_size_to_log(struct btrfs_trans_handle *trans,
5463 				 struct btrfs_inode *inode,
5464 				 struct btrfs_path *path, u64 *size_ret)
5465 {
5466 	struct btrfs_key key;
5467 	struct btrfs_inode_item *item;
5468 	int ret;
5469 
5470 	key.objectid = btrfs_ino(inode);
5471 	key.type = BTRFS_INODE_ITEM_KEY;
5472 	key.offset = 0;
5473 
5474 	/*
5475 	 * Our caller called inode_logged(), so logged_trans is up to date.
5476 	 * Use data_race() to silence any warning from KCSAN. Once logged_trans
5477 	 * is set, it can only be reset to 0 after inode eviction.
5478 	 */
5479 	if (data_race(inode->logged_trans) == trans->transid) {
5480 		ret = btrfs_search_slot(NULL, inode->root->log_root, &key, path, 0, 0);
5481 	} else if (inode->generation < trans->transid) {
5482 		path->search_commit_root = true;
5483 		path->skip_locking = true;
5484 		ret = btrfs_search_slot(NULL, inode->root, &key, path, 0, 0);
5485 		path->search_commit_root = false;
5486 		path->skip_locking = false;
5487 
5488 	} else {
5489 		*size_ret = 0;
5490 		return 0;
5491 	}
5492 
5493 	/*
5494 	 * If the inode was logged before or is from a past transaction, then
5495 	 * its inode item must exist in the log root or in the commit root.
5496 	 */
5497 	ASSERT(ret <= 0);
5498 	if (WARN_ON_ONCE(ret > 0))
5499 		ret = -ENOENT;
5500 
5501 	if (ret < 0)
5502 		return ret;
5503 
5504 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5505 			      struct btrfs_inode_item);
5506 	*size_ret = btrfs_inode_size(path->nodes[0], item);
5507 	/*
5508 	 * If the in-memory inode's i_size is smaller then the inode size stored
5509 	 * in the btree, return the inode's i_size, so that we get a correct
5510 	 * inode size after replaying the log when before a power failure we had
5511 	 * a shrinking truncate followed by addition of a new name (rename / new
5512 	 * hard link). Otherwise return the inode size from the btree, to avoid
5513 	 * data loss when replaying a log due to previously doing a write that
5514 	 * expands the inode's size and logging a new name immediately after.
5515 	 */
5516 	if (*size_ret > inode->vfs_inode.i_size)
5517 		*size_ret = inode->vfs_inode.i_size;
5518 
5519 	btrfs_release_path(path);
5520 	return 0;
5521 }
5522 
5523 /*
5524  * At the moment we always log all xattrs. This is to figure out at log replay
5525  * time which xattrs must have their deletion replayed. If a xattr is missing
5526  * in the log tree and exists in the fs/subvol tree, we delete it. This is
5527  * because if a xattr is deleted, the inode is fsynced and a power failure
5528  * happens, causing the log to be replayed the next time the fs is mounted,
5529  * we want the xattr to not exist anymore (same behaviour as other filesystems
5530  * with a journal, ext3/4, xfs, f2fs, etc).
5531  */
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)5532 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
5533 				struct btrfs_inode *inode,
5534 				struct btrfs_path *path,
5535 				struct btrfs_path *dst_path,
5536 				struct btrfs_log_ctx *ctx)
5537 {
5538 	struct btrfs_root *root = inode->root;
5539 	int ret;
5540 	struct btrfs_key key;
5541 	const u64 ino = btrfs_ino(inode);
5542 	int ins_nr = 0;
5543 	int start_slot = 0;
5544 	bool found_xattrs = false;
5545 
5546 	if (test_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags))
5547 		return 0;
5548 
5549 	key.objectid = ino;
5550 	key.type = BTRFS_XATTR_ITEM_KEY;
5551 	key.offset = 0;
5552 
5553 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5554 	if (ret < 0)
5555 		return ret;
5556 
5557 	while (true) {
5558 		int slot = path->slots[0];
5559 		struct extent_buffer *leaf = path->nodes[0];
5560 		int nritems = btrfs_header_nritems(leaf);
5561 
5562 		if (slot >= nritems) {
5563 			if (ins_nr > 0) {
5564 				ret = copy_items(trans, inode, dst_path, path,
5565 						 start_slot, ins_nr, 1, 0, ctx);
5566 				if (ret < 0)
5567 					return ret;
5568 				ins_nr = 0;
5569 			}
5570 			ret = btrfs_next_leaf(root, path);
5571 			if (ret < 0)
5572 				return ret;
5573 			else if (ret > 0)
5574 				break;
5575 			continue;
5576 		}
5577 
5578 		btrfs_item_key_to_cpu(leaf, &key, slot);
5579 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
5580 			break;
5581 
5582 		if (ins_nr == 0)
5583 			start_slot = slot;
5584 		ins_nr++;
5585 		path->slots[0]++;
5586 		found_xattrs = true;
5587 		cond_resched();
5588 	}
5589 	if (ins_nr > 0) {
5590 		ret = copy_items(trans, inode, dst_path, path,
5591 				 start_slot, ins_nr, 1, 0, ctx);
5592 		if (ret < 0)
5593 			return ret;
5594 	}
5595 
5596 	if (!found_xattrs)
5597 		set_bit(BTRFS_INODE_NO_XATTRS, &inode->runtime_flags);
5598 
5599 	return 0;
5600 }
5601 
5602 /*
5603  * When using the NO_HOLES feature if we punched a hole that causes the
5604  * deletion of entire leafs or all the extent items of the first leaf (the one
5605  * that contains the inode item and references) we may end up not processing
5606  * any extents, because there are no leafs with a generation matching the
5607  * current transaction that have extent items for our inode. So we need to find
5608  * if any holes exist and then log them. We also need to log holes after any
5609  * truncate operation that changes the inode's size.
5610  */
btrfs_log_holes(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_path * path)5611 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
5612 			   struct btrfs_inode *inode,
5613 			   struct btrfs_path *path)
5614 {
5615 	struct btrfs_root *root = inode->root;
5616 	struct btrfs_fs_info *fs_info = root->fs_info;
5617 	struct btrfs_key key;
5618 	const u64 ino = btrfs_ino(inode);
5619 	const u64 i_size = i_size_read(&inode->vfs_inode);
5620 	u64 prev_extent_end = 0;
5621 	int ret;
5622 
5623 	if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
5624 		return 0;
5625 
5626 	key.objectid = ino;
5627 	key.type = BTRFS_EXTENT_DATA_KEY;
5628 	key.offset = 0;
5629 
5630 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5631 	if (ret < 0)
5632 		return ret;
5633 
5634 	while (true) {
5635 		struct extent_buffer *leaf = path->nodes[0];
5636 
5637 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
5638 			ret = btrfs_next_leaf(root, path);
5639 			if (ret < 0)
5640 				return ret;
5641 			if (ret > 0) {
5642 				ret = 0;
5643 				break;
5644 			}
5645 			leaf = path->nodes[0];
5646 		}
5647 
5648 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5649 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
5650 			break;
5651 
5652 		/* We have a hole, log it. */
5653 		if (prev_extent_end < key.offset) {
5654 			const u64 hole_len = key.offset - prev_extent_end;
5655 
5656 			/*
5657 			 * Release the path to avoid deadlocks with other code
5658 			 * paths that search the root while holding locks on
5659 			 * leafs from the log root.
5660 			 */
5661 			btrfs_release_path(path);
5662 			ret = btrfs_insert_hole_extent(trans, root->log_root,
5663 						       ino, prev_extent_end,
5664 						       hole_len);
5665 			if (ret < 0)
5666 				return ret;
5667 
5668 			/*
5669 			 * Search for the same key again in the root. Since it's
5670 			 * an extent item and we are holding the inode lock, the
5671 			 * key must still exist. If it doesn't just emit warning
5672 			 * and return an error to fall back to a transaction
5673 			 * commit.
5674 			 */
5675 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5676 			if (ret < 0)
5677 				return ret;
5678 			if (WARN_ON(ret > 0))
5679 				return -ENOENT;
5680 			leaf = path->nodes[0];
5681 		}
5682 
5683 		prev_extent_end = btrfs_file_extent_end(path);
5684 		path->slots[0]++;
5685 		cond_resched();
5686 	}
5687 
5688 	if (prev_extent_end < i_size) {
5689 		u64 hole_len;
5690 
5691 		btrfs_release_path(path);
5692 		hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
5693 		ret = btrfs_insert_hole_extent(trans, root->log_root, ino,
5694 					       prev_extent_end, hole_len);
5695 		if (ret < 0)
5696 			return ret;
5697 	}
5698 
5699 	return 0;
5700 }
5701 
5702 /*
5703  * When we are logging a new inode X, check if it doesn't have a reference that
5704  * matches the reference from some other inode Y created in a past transaction
5705  * and that was renamed in the current transaction. If we don't do this, then at
5706  * log replay time we can lose inode Y (and all its files if it's a directory):
5707  *
5708  * mkdir /mnt/x
5709  * echo "hello world" > /mnt/x/foobar
5710  * sync
5711  * mv /mnt/x /mnt/y
5712  * mkdir /mnt/x                 # or touch /mnt/x
5713  * xfs_io -c fsync /mnt/x
5714  * <power fail>
5715  * mount fs, trigger log replay
5716  *
5717  * After the log replay procedure, we would lose the first directory and all its
5718  * files (file foobar).
5719  * For the case where inode Y is not a directory we simply end up losing it:
5720  *
5721  * echo "123" > /mnt/foo
5722  * sync
5723  * mv /mnt/foo /mnt/bar
5724  * echo "abc" > /mnt/foo
5725  * xfs_io -c fsync /mnt/foo
5726  * <power fail>
5727  *
5728  * We also need this for cases where a snapshot entry is replaced by some other
5729  * entry (file or directory) otherwise we end up with an unreplayable log due to
5730  * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
5731  * if it were a regular entry:
5732  *
5733  * mkdir /mnt/x
5734  * btrfs subvolume snapshot /mnt /mnt/x/snap
5735  * btrfs subvolume delete /mnt/x/snap
5736  * rmdir /mnt/x
5737  * mkdir /mnt/x
5738  * fsync /mnt/x or fsync some new file inside it
5739  * <power fail>
5740  *
5741  * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
5742  * the same transaction.
5743  */
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)5744 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
5745 					 const int slot,
5746 					 const struct btrfs_key *key,
5747 					 struct btrfs_inode *inode,
5748 					 u64 *other_ino, u64 *other_parent)
5749 {
5750 	BTRFS_PATH_AUTO_FREE(search_path);
5751 	char AUTO_KFREE(name);
5752 	u32 name_len = 0;
5753 	u32 item_size = btrfs_item_size(eb, slot);
5754 	u32 cur_offset = 0;
5755 	unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
5756 
5757 	search_path = btrfs_alloc_path();
5758 	if (!search_path)
5759 		return -ENOMEM;
5760 	search_path->search_commit_root = true;
5761 	search_path->skip_locking = true;
5762 
5763 	while (cur_offset < item_size) {
5764 		u64 parent;
5765 		u32 this_name_len;
5766 		u32 this_len;
5767 		unsigned long name_ptr;
5768 		struct btrfs_dir_item *di;
5769 		struct fscrypt_str name_str;
5770 
5771 		if (key->type == BTRFS_INODE_REF_KEY) {
5772 			struct btrfs_inode_ref *iref;
5773 
5774 			iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
5775 			parent = key->offset;
5776 			this_name_len = btrfs_inode_ref_name_len(eb, iref);
5777 			name_ptr = (unsigned long)(iref + 1);
5778 			this_len = sizeof(*iref) + this_name_len;
5779 		} else {
5780 			struct btrfs_inode_extref *extref;
5781 
5782 			extref = (struct btrfs_inode_extref *)(ptr +
5783 							       cur_offset);
5784 			parent = btrfs_inode_extref_parent(eb, extref);
5785 			this_name_len = btrfs_inode_extref_name_len(eb, extref);
5786 			name_ptr = (unsigned long)&extref->name;
5787 			this_len = sizeof(*extref) + this_name_len;
5788 		}
5789 
5790 		if (this_name_len > name_len) {
5791 			char *new_name;
5792 
5793 			new_name = krealloc(name, this_name_len, GFP_NOFS);
5794 			if (!new_name)
5795 				return -ENOMEM;
5796 			name_len = this_name_len;
5797 			name = new_name;
5798 		}
5799 
5800 		read_extent_buffer(eb, name, name_ptr, this_name_len);
5801 
5802 		name_str.name = name;
5803 		name_str.len = this_name_len;
5804 		di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
5805 				parent, &name_str, 0);
5806 		if (di && !IS_ERR(di)) {
5807 			struct btrfs_key di_key;
5808 
5809 			btrfs_dir_item_key_to_cpu(search_path->nodes[0],
5810 						  di, &di_key);
5811 			if (di_key.type == BTRFS_INODE_ITEM_KEY) {
5812 				if (di_key.objectid != key->objectid) {
5813 					*other_ino = di_key.objectid;
5814 					*other_parent = parent;
5815 					return 1;
5816 				} else {
5817 					return 0;
5818 				}
5819 			} else {
5820 				return -EAGAIN;
5821 			}
5822 		} else if (IS_ERR(di)) {
5823 			return PTR_ERR(di);
5824 		}
5825 		btrfs_release_path(search_path);
5826 
5827 		cur_offset += this_len;
5828 	}
5829 
5830 	return 0;
5831 }
5832 
5833 /*
5834  * Check if we need to log an inode. This is used in contexts where while
5835  * logging an inode we need to log another inode (either that it exists or in
5836  * full mode). This is used instead of btrfs_inode_in_log() because the later
5837  * requires the inode to be in the log and have the log transaction committed,
5838  * while here we do not care if the log transaction was already committed - our
5839  * caller will commit the log later - and we want to avoid logging an inode
5840  * multiple times when multiple tasks have joined the same log transaction.
5841  */
need_log_inode(const struct btrfs_trans_handle * trans,struct btrfs_inode * inode)5842 static bool need_log_inode(const struct btrfs_trans_handle *trans,
5843 			   struct btrfs_inode *inode)
5844 {
5845 	/*
5846 	 * If a directory was not modified, no dentries added or removed, we can
5847 	 * and should avoid logging it.
5848 	 */
5849 	if (S_ISDIR(inode->vfs_inode.i_mode) && inode->last_trans < trans->transid)
5850 		return false;
5851 
5852 	/*
5853 	 * If this inode does not have new/updated/deleted xattrs since the last
5854 	 * time it was logged and is flagged as logged in the current transaction,
5855 	 * we can skip logging it. As for new/deleted names, those are updated in
5856 	 * the log by link/unlink/rename operations.
5857 	 * In case the inode was logged and then evicted and reloaded, its
5858 	 * logged_trans will be 0, in which case we have to fully log it since
5859 	 * logged_trans is a transient field, not persisted.
5860 	 */
5861 	if (inode_logged(trans, inode, NULL) == 1 &&
5862 	    !test_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags))
5863 		return false;
5864 
5865 	return true;
5866 }
5867 
5868 struct btrfs_dir_list {
5869 	u64 ino;
5870 	struct list_head list;
5871 };
5872 
5873 /*
5874  * Log the inodes of the new dentries of a directory.
5875  * See process_dir_items_leaf() for details about why it is needed.
5876  * This is a recursive operation - if an existing dentry corresponds to a
5877  * directory, that directory's new entries are logged too (same behaviour as
5878  * ext3/4, xfs, f2fs, nilfs2). Note that when logging the inodes
5879  * the dentries point to we do not acquire their VFS lock, otherwise lockdep
5880  * complains about the following circular lock dependency / possible deadlock:
5881  *
5882  *        CPU0                                        CPU1
5883  *        ----                                        ----
5884  * lock(&type->i_mutex_dir_key#3/2);
5885  *                                            lock(sb_internal#2);
5886  *                                            lock(&type->i_mutex_dir_key#3/2);
5887  * lock(&sb->s_type->i_mutex_key#14);
5888  *
5889  * Where sb_internal is the lock (a counter that works as a lock) acquired by
5890  * sb_start_intwrite() in btrfs_start_transaction().
5891  * Not acquiring the VFS lock of the inodes is still safe because:
5892  *
5893  * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5894  *    that while logging the inode new references (names) are added or removed
5895  *    from the inode, leaving the logged inode item with a link count that does
5896  *    not match the number of logged inode reference items. This is fine because
5897  *    at log replay time we compute the real number of links and correct the
5898  *    link count in the inode item (see replay_one_buffer() and
5899  *    link_to_fixup_dir());
5900  *
5901  * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5902  *    while logging the inode's items new index items (key type
5903  *    BTRFS_DIR_INDEX_KEY) are added to fs/subvol tree and the logged inode item
5904  *    has a size that doesn't match the sum of the lengths of all the logged
5905  *    names - this is ok, not a problem, because at log replay time we set the
5906  *    directory's i_size to the correct value (see replay_one_name() and
5907  *    overwrite_item()).
5908  */
log_new_dir_dentries(struct btrfs_trans_handle * trans,struct btrfs_inode * start_inode,struct btrfs_log_ctx * ctx)5909 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5910 				struct btrfs_inode *start_inode,
5911 				struct btrfs_log_ctx *ctx)
5912 {
5913 	struct btrfs_root *root = start_inode->root;
5914 	struct btrfs_path *path;
5915 	LIST_HEAD(dir_list);
5916 	struct btrfs_dir_list *dir_elem;
5917 	u64 ino = btrfs_ino(start_inode);
5918 	struct btrfs_inode *curr_inode = start_inode;
5919 	int ret = 0;
5920 
5921 	path = btrfs_alloc_path();
5922 	if (!path)
5923 		return -ENOMEM;
5924 
5925 	/* Pairs with btrfs_add_delayed_iput below. */
5926 	ihold(&curr_inode->vfs_inode);
5927 
5928 	while (true) {
5929 		struct btrfs_key key;
5930 		struct btrfs_key found_key;
5931 		u64 next_index;
5932 		bool continue_curr_inode = true;
5933 		int iter_ret;
5934 
5935 		key.objectid = ino;
5936 		key.type = BTRFS_DIR_INDEX_KEY;
5937 		key.offset = btrfs_get_first_dir_index_to_log(curr_inode);
5938 		next_index = key.offset;
5939 again:
5940 		btrfs_for_each_slot(root->log_root, &key, &found_key, path, iter_ret) {
5941 			struct extent_buffer *leaf = path->nodes[0];
5942 			struct btrfs_dir_item *di;
5943 			struct btrfs_key di_key;
5944 			struct btrfs_inode *di_inode;
5945 			int log_mode = LOG_INODE_EXISTS;
5946 			int type;
5947 
5948 			if (found_key.objectid != ino ||
5949 			    found_key.type != BTRFS_DIR_INDEX_KEY) {
5950 				continue_curr_inode = false;
5951 				break;
5952 			}
5953 
5954 			next_index = found_key.offset + 1;
5955 
5956 			di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
5957 			type = btrfs_dir_ftype(leaf, di);
5958 			if (btrfs_dir_transid(leaf, di) < trans->transid)
5959 				continue;
5960 			btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5961 			if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5962 				continue;
5963 
5964 			btrfs_release_path(path);
5965 			di_inode = btrfs_iget_logging(di_key.objectid, root);
5966 			if (IS_ERR(di_inode)) {
5967 				ret = PTR_ERR(di_inode);
5968 				goto out;
5969 			}
5970 
5971 			if (!need_log_inode(trans, di_inode)) {
5972 				btrfs_add_delayed_iput(di_inode);
5973 				break;
5974 			}
5975 
5976 			ctx->log_new_dentries = false;
5977 			if (type == BTRFS_FT_DIR)
5978 				log_mode = LOG_INODE_ALL;
5979 			ret = btrfs_log_inode(trans, di_inode, log_mode, ctx);
5980 			btrfs_add_delayed_iput(di_inode);
5981 			if (ret)
5982 				goto out;
5983 			if (ctx->log_new_dentries) {
5984 				dir_elem = kmalloc_obj(*dir_elem, GFP_NOFS);
5985 				if (!dir_elem) {
5986 					ret = -ENOMEM;
5987 					goto out;
5988 				}
5989 				dir_elem->ino = di_key.objectid;
5990 				list_add_tail(&dir_elem->list, &dir_list);
5991 			}
5992 			break;
5993 		}
5994 
5995 		btrfs_release_path(path);
5996 
5997 		if (iter_ret < 0) {
5998 			ret = iter_ret;
5999 			goto out;
6000 		} else if (iter_ret > 0) {
6001 			continue_curr_inode = false;
6002 		} else {
6003 			key = found_key;
6004 		}
6005 
6006 		if (continue_curr_inode && key.offset < (u64)-1) {
6007 			key.offset++;
6008 			goto again;
6009 		}
6010 
6011 		btrfs_set_first_dir_index_to_log(curr_inode, next_index);
6012 
6013 		if (list_empty(&dir_list))
6014 			break;
6015 
6016 		dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list, list);
6017 		ino = dir_elem->ino;
6018 		list_del(&dir_elem->list);
6019 		kfree(dir_elem);
6020 
6021 		btrfs_add_delayed_iput(curr_inode);
6022 
6023 		curr_inode = btrfs_iget_logging(ino, root);
6024 		if (IS_ERR(curr_inode)) {
6025 			ret = PTR_ERR(curr_inode);
6026 			curr_inode = NULL;
6027 			break;
6028 		}
6029 	}
6030 out:
6031 	btrfs_free_path(path);
6032 	if (curr_inode)
6033 		btrfs_add_delayed_iput(curr_inode);
6034 
6035 	if (ret) {
6036 		struct btrfs_dir_list *next;
6037 
6038 		list_for_each_entry_safe(dir_elem, next, &dir_list, list)
6039 			kfree(dir_elem);
6040 	}
6041 
6042 	return ret;
6043 }
6044 
6045 struct btrfs_ino_list {
6046 	u64 ino;
6047 	u64 parent;
6048 	struct list_head list;
6049 };
6050 
free_conflicting_inodes(struct btrfs_log_ctx * ctx)6051 static void free_conflicting_inodes(struct btrfs_log_ctx *ctx)
6052 {
6053 	struct btrfs_ino_list *curr;
6054 	struct btrfs_ino_list *next;
6055 
6056 	list_for_each_entry_safe(curr, next, &ctx->conflict_inodes, list) {
6057 		list_del(&curr->list);
6058 		kfree(curr);
6059 	}
6060 }
6061 
conflicting_inode_is_dir(struct btrfs_root * root,u64 ino,struct btrfs_path * path)6062 static int conflicting_inode_is_dir(struct btrfs_root *root, u64 ino,
6063 				    struct btrfs_path *path)
6064 {
6065 	struct btrfs_key key;
6066 	int ret;
6067 
6068 	key.objectid = ino;
6069 	key.type = BTRFS_INODE_ITEM_KEY;
6070 	key.offset = 0;
6071 
6072 	path->search_commit_root = true;
6073 	path->skip_locking = true;
6074 
6075 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6076 	if (WARN_ON_ONCE(ret > 0)) {
6077 		/*
6078 		 * We have previously found the inode through the commit root
6079 		 * so this should not happen. If it does, just error out and
6080 		 * fallback to a transaction commit.
6081 		 */
6082 		ret = -ENOENT;
6083 	} else if (ret == 0) {
6084 		struct btrfs_inode_item *item;
6085 
6086 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6087 				      struct btrfs_inode_item);
6088 		if (S_ISDIR(btrfs_inode_mode(path->nodes[0], item)))
6089 			ret = 1;
6090 	}
6091 
6092 	btrfs_release_path(path);
6093 	path->search_commit_root = false;
6094 	path->skip_locking = false;
6095 
6096 	return ret;
6097 }
6098 
can_log_conflicting_inode(const struct btrfs_trans_handle * trans,const struct btrfs_inode * inode)6099 static bool can_log_conflicting_inode(const struct btrfs_trans_handle *trans,
6100 				      const struct btrfs_inode *inode)
6101 {
6102 	if (!S_ISDIR(inode->vfs_inode.i_mode))
6103 		return true;
6104 
6105 	if (inode->last_unlink_trans < trans->transid)
6106 		return true;
6107 
6108 	/*
6109 	 * If this is a directory and its unlink_trans is not from a past
6110 	 * transaction then we must fallback to a transaction commit in order
6111 	 * to avoid getting a directory with 2 hard links after log replay.
6112 	 *
6113 	 * This happens if a directory A is renamed, moved from one parent
6114 	 * directory to another one, a new file is created in the old parent
6115 	 * directory with the old name of our directory A, the new file is
6116 	 * fsynced, then we moved the new file to some other parent directory
6117 	 * and fsync again the new file. This results in a log tree where we
6118 	 * logged that directory A existed, with the INODE_REF item for the
6119 	 * new location but without having logged its old parent inode, so
6120 	 * that on log replay we add a new link for the new location but the
6121 	 * old link remains, resulting in a link count of 2.
6122 	 */
6123 	return false;
6124 }
6125 
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)6126 static int add_conflicting_inode(struct btrfs_trans_handle *trans,
6127 				 struct btrfs_root *root,
6128 				 struct btrfs_path *path,
6129 				 u64 ino, u64 parent,
6130 				 struct btrfs_log_ctx *ctx)
6131 {
6132 	struct btrfs_ino_list *ino_elem;
6133 	struct btrfs_inode *inode;
6134 
6135 	/*
6136 	 * It's rare to have a lot of conflicting inodes, in practice it is not
6137 	 * common to have more than 1 or 2. We don't want to collect too many,
6138 	 * as we could end up logging too many inodes (even if only in
6139 	 * LOG_INODE_EXISTS mode) and slow down other fsyncs or transaction
6140 	 * commits.
6141 	 */
6142 	if (ctx->num_conflict_inodes >= MAX_CONFLICT_INODES)
6143 		return BTRFS_LOG_FORCE_COMMIT;
6144 
6145 	inode = btrfs_iget_logging(ino, root);
6146 	/*
6147 	 * If the other inode that had a conflicting dir entry was deleted in
6148 	 * the current transaction then we either:
6149 	 *
6150 	 * 1) Log the parent directory (later after adding it to the list) if
6151 	 *    the inode is a directory. This is because it may be a deleted
6152 	 *    subvolume/snapshot or it may be a regular directory that had
6153 	 *    deleted subvolumes/snapshots (or subdirectories that had them),
6154 	 *    and at the moment we can't deal with dropping subvolumes/snapshots
6155 	 *    during log replay. So we just log the parent, which will result in
6156 	 *    a fallback to a transaction commit if we are dealing with those
6157 	 *    cases (last_unlink_trans will match the current transaction);
6158 	 *
6159 	 * 2) Do nothing if it's not a directory. During log replay we simply
6160 	 *    unlink the conflicting dentry from the parent directory and then
6161 	 *    add the dentry for our inode. Like this we can avoid logging the
6162 	 *    parent directory (and maybe fallback to a transaction commit in
6163 	 *    case it has a last_unlink_trans == trans->transid, due to moving
6164 	 *    some inode from it to some other directory).
6165 	 */
6166 	if (IS_ERR(inode)) {
6167 		int ret = PTR_ERR(inode);
6168 
6169 		if (ret != -ENOENT)
6170 			return ret;
6171 
6172 		ret = conflicting_inode_is_dir(root, ino, path);
6173 		/* Not a directory or we got an error. */
6174 		if (ret <= 0)
6175 			return ret;
6176 
6177 		/* Conflicting inode is a directory, so we'll log its parent. */
6178 		ino_elem = kmalloc_obj(*ino_elem, GFP_NOFS);
6179 		if (!ino_elem)
6180 			return -ENOMEM;
6181 		ino_elem->ino = ino;
6182 		ino_elem->parent = parent;
6183 		list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
6184 		ctx->num_conflict_inodes++;
6185 
6186 		return 0;
6187 	}
6188 
6189 	/*
6190 	 * If the inode was already logged skip it - otherwise we can hit an
6191 	 * infinite loop. Example:
6192 	 *
6193 	 * From the commit root (previous transaction) we have the following
6194 	 * inodes:
6195 	 *
6196 	 * inode 257 a directory
6197 	 * inode 258 with references "zz" and "zz_link" on inode 257
6198 	 * inode 259 with reference "a" on inode 257
6199 	 *
6200 	 * And in the current (uncommitted) transaction we have:
6201 	 *
6202 	 * inode 257 a directory, unchanged
6203 	 * inode 258 with references "a" and "a2" on inode 257
6204 	 * inode 259 with reference "zz_link" on inode 257
6205 	 * inode 261 with reference "zz" on inode 257
6206 	 *
6207 	 * When logging inode 261 the following infinite loop could
6208 	 * happen if we don't skip already logged inodes:
6209 	 *
6210 	 * - we detect inode 258 as a conflicting inode, with inode 261
6211 	 *   on reference "zz", and log it;
6212 	 *
6213 	 * - we detect inode 259 as a conflicting inode, with inode 258
6214 	 *   on reference "a", and log it;
6215 	 *
6216 	 * - we detect inode 258 as a conflicting inode, with inode 259
6217 	 *   on reference "zz_link", and log it - again! After this we
6218 	 *   repeat the above steps forever.
6219 	 *
6220 	 * Here we can use need_log_inode() because we only need to log the
6221 	 * inode in LOG_INODE_EXISTS mode and rename operations update the log,
6222 	 * so that the log ends up with the new name and without the old name.
6223 	 */
6224 	if (!need_log_inode(trans, inode)) {
6225 		btrfs_add_delayed_iput(inode);
6226 		return 0;
6227 	}
6228 
6229 	if (!can_log_conflicting_inode(trans, inode)) {
6230 		btrfs_add_delayed_iput(inode);
6231 		return BTRFS_LOG_FORCE_COMMIT;
6232 	}
6233 
6234 	btrfs_add_delayed_iput(inode);
6235 
6236 	ino_elem = kmalloc_obj(*ino_elem, GFP_NOFS);
6237 	if (!ino_elem)
6238 		return -ENOMEM;
6239 	ino_elem->ino = ino;
6240 	ino_elem->parent = parent;
6241 	list_add_tail(&ino_elem->list, &ctx->conflict_inodes);
6242 	ctx->num_conflict_inodes++;
6243 
6244 	return 0;
6245 }
6246 
log_conflicting_inodes(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_log_ctx * ctx)6247 static int log_conflicting_inodes(struct btrfs_trans_handle *trans,
6248 				  struct btrfs_root *root,
6249 				  struct btrfs_log_ctx *ctx)
6250 {
6251 	const bool orig_log_new_dentries = ctx->log_new_dentries;
6252 	int ret = 0;
6253 
6254 	/*
6255 	 * Conflicting inodes are logged by the first call to btrfs_log_inode(),
6256 	 * otherwise we could have unbounded recursion of btrfs_log_inode()
6257 	 * calls. This check guarantees we can have only 1 level of recursion.
6258 	 */
6259 	if (ctx->logging_conflict_inodes)
6260 		return 0;
6261 
6262 	ctx->logging_conflict_inodes = true;
6263 
6264 	/*
6265 	 * New conflicting inodes may be found and added to the list while we
6266 	 * are logging a conflicting inode, so keep iterating while the list is
6267 	 * not empty.
6268 	 */
6269 	while (!list_empty(&ctx->conflict_inodes)) {
6270 		struct btrfs_ino_list *curr;
6271 		struct btrfs_inode *inode;
6272 		u64 ino;
6273 		u64 parent;
6274 
6275 		curr = list_first_entry(&ctx->conflict_inodes,
6276 					struct btrfs_ino_list, list);
6277 		ino = curr->ino;
6278 		parent = curr->parent;
6279 		list_del(&curr->list);
6280 		kfree(curr);
6281 
6282 		inode = btrfs_iget_logging(ino, root);
6283 		/*
6284 		 * If the other inode that had a conflicting dir entry was
6285 		 * deleted in the current transaction, we need to log its parent
6286 		 * directory. See the comment at add_conflicting_inode().
6287 		 */
6288 		if (IS_ERR(inode)) {
6289 			ret = PTR_ERR(inode);
6290 			if (ret != -ENOENT)
6291 				break;
6292 
6293 			inode = btrfs_iget_logging(parent, root);
6294 			if (IS_ERR(inode)) {
6295 				ret = PTR_ERR(inode);
6296 				break;
6297 			}
6298 
6299 			if (!can_log_conflicting_inode(trans, inode)) {
6300 				btrfs_add_delayed_iput(inode);
6301 				ret = BTRFS_LOG_FORCE_COMMIT;
6302 				break;
6303 			}
6304 
6305 			/*
6306 			 * Always log the directory, we cannot make this
6307 			 * conditional on need_log_inode() because the directory
6308 			 * might have been logged in LOG_INODE_EXISTS mode or
6309 			 * the dir index of the conflicting inode is not in a
6310 			 * dir index key range logged for the directory. So we
6311 			 * must make sure the deletion is recorded.
6312 			 */
6313 			ctx->log_new_dentries = false;
6314 			ret = btrfs_log_inode(trans, inode, LOG_INODE_ALL, ctx);
6315 			if (!ret && ctx->log_new_dentries)
6316 				ret = log_new_dir_dentries(trans, inode, ctx);
6317 
6318 			btrfs_add_delayed_iput(inode);
6319 			if (ret)
6320 				break;
6321 			continue;
6322 		}
6323 
6324 		/*
6325 		 * Here we can use need_log_inode() because we only need to log
6326 		 * the inode in LOG_INODE_EXISTS mode and rename operations
6327 		 * update the log, so that the log ends up with the new name and
6328 		 * without the old name.
6329 		 *
6330 		 * We did this check at add_conflicting_inode(), but here we do
6331 		 * it again because if some other task logged the inode after
6332 		 * that, we can avoid doing it again.
6333 		 */
6334 		if (!need_log_inode(trans, inode)) {
6335 			btrfs_add_delayed_iput(inode);
6336 			continue;
6337 		}
6338 
6339 		/*
6340 		 * We are safe logging the other inode without acquiring its
6341 		 * lock as long as we log with the LOG_INODE_EXISTS mode. We
6342 		 * are safe against concurrent renames of the other inode as
6343 		 * well because during a rename we pin the log and update the
6344 		 * log with the new name before we unpin it.
6345 		 */
6346 		ret = btrfs_log_inode(trans, inode, LOG_INODE_EXISTS, ctx);
6347 		btrfs_add_delayed_iput(inode);
6348 		if (ret)
6349 			break;
6350 	}
6351 
6352 	ctx->log_new_dentries = orig_log_new_dentries;
6353 	ctx->logging_conflict_inodes = false;
6354 	if (ret)
6355 		free_conflicting_inodes(ctx);
6356 
6357 	return ret;
6358 }
6359 
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)6360 static int copy_inode_items_to_log(struct btrfs_trans_handle *trans,
6361 				   struct btrfs_inode *inode,
6362 				   struct btrfs_key *min_key,
6363 				   const struct btrfs_key *max_key,
6364 				   struct btrfs_path *path,
6365 				   struct btrfs_path *dst_path,
6366 				   const u64 logged_isize,
6367 				   const int inode_only,
6368 				   struct btrfs_log_ctx *ctx,
6369 				   bool *need_log_inode_item)
6370 {
6371 	const u64 i_size = i_size_read(&inode->vfs_inode);
6372 	struct btrfs_root *root = inode->root;
6373 	int ins_start_slot = 0;
6374 	int ins_nr = 0;
6375 	int ret;
6376 
6377 	while (1) {
6378 		ret = btrfs_search_forward(root, min_key, path, trans->transid);
6379 		if (ret < 0)
6380 			return ret;
6381 		if (ret > 0) {
6382 			ret = 0;
6383 			break;
6384 		}
6385 again:
6386 		/* Note, ins_nr might be > 0 here, cleanup outside the loop */
6387 		if (min_key->objectid != max_key->objectid)
6388 			break;
6389 		if (min_key->type > max_key->type)
6390 			break;
6391 
6392 		if (min_key->type == BTRFS_INODE_ITEM_KEY) {
6393 			*need_log_inode_item = false;
6394 		} else if (min_key->type == BTRFS_EXTENT_DATA_KEY &&
6395 			   min_key->offset >= i_size) {
6396 			/*
6397 			 * Extents at and beyond eof are logged with
6398 			 * btrfs_log_prealloc_extents().
6399 			 * Only regular files have BTRFS_EXTENT_DATA_KEY keys,
6400 			 * and no keys greater than that, so bail out.
6401 			 */
6402 			break;
6403 		} else if (min_key->type == BTRFS_INODE_REF_KEY ||
6404 			   min_key->type == BTRFS_INODE_EXTREF_KEY) {
6405 			u64 other_ino = 0;
6406 			u64 other_parent = 0;
6407 
6408 			ret = btrfs_check_ref_name_override(path->nodes[0],
6409 					path->slots[0], min_key, inode,
6410 					&other_ino, &other_parent);
6411 			if (ret < 0) {
6412 				return ret;
6413 			} else if (ret > 0 &&
6414 				   other_ino != btrfs_ino(ctx->inode)) {
6415 				if (ins_nr > 0) {
6416 					ins_nr++;
6417 				} else {
6418 					ins_nr = 1;
6419 					ins_start_slot = path->slots[0];
6420 				}
6421 				ret = copy_items(trans, inode, dst_path, path,
6422 						 ins_start_slot, ins_nr,
6423 						 inode_only, logged_isize, ctx);
6424 				if (ret < 0)
6425 					return ret;
6426 				ins_nr = 0;
6427 
6428 				btrfs_release_path(path);
6429 				ret = add_conflicting_inode(trans, root, path,
6430 							    other_ino,
6431 							    other_parent, ctx);
6432 				if (ret)
6433 					return ret;
6434 				goto next_key;
6435 			}
6436 		} else if (min_key->type == BTRFS_XATTR_ITEM_KEY) {
6437 			/* Skip xattrs, logged later with btrfs_log_all_xattrs() */
6438 			if (ins_nr == 0)
6439 				goto next_slot;
6440 			ret = copy_items(trans, inode, dst_path, path,
6441 					 ins_start_slot,
6442 					 ins_nr, inode_only, logged_isize, ctx);
6443 			if (ret < 0)
6444 				return ret;
6445 			ins_nr = 0;
6446 			goto next_slot;
6447 		}
6448 
6449 		if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
6450 			ins_nr++;
6451 			goto next_slot;
6452 		} else if (!ins_nr) {
6453 			ins_start_slot = path->slots[0];
6454 			ins_nr = 1;
6455 			goto next_slot;
6456 		}
6457 
6458 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
6459 				 ins_nr, inode_only, logged_isize, ctx);
6460 		if (ret < 0)
6461 			return ret;
6462 		ins_nr = 1;
6463 		ins_start_slot = path->slots[0];
6464 next_slot:
6465 		path->slots[0]++;
6466 		if (path->slots[0] < btrfs_header_nritems(path->nodes[0])) {
6467 			btrfs_item_key_to_cpu(path->nodes[0], min_key,
6468 					      path->slots[0]);
6469 			goto again;
6470 		}
6471 		if (ins_nr) {
6472 			ret = copy_items(trans, inode, dst_path, path,
6473 					 ins_start_slot, ins_nr, inode_only,
6474 					 logged_isize, ctx);
6475 			if (ret < 0)
6476 				return ret;
6477 			ins_nr = 0;
6478 		}
6479 		btrfs_release_path(path);
6480 next_key:
6481 		if (min_key->offset < (u64)-1) {
6482 			min_key->offset++;
6483 		} else if (min_key->type < max_key->type) {
6484 			min_key->type++;
6485 			min_key->offset = 0;
6486 		} else {
6487 			break;
6488 		}
6489 
6490 		/*
6491 		 * We may process many leaves full of items for our inode, so
6492 		 * avoid monopolizing a cpu for too long by rescheduling while
6493 		 * not holding locks on any tree.
6494 		 */
6495 		cond_resched();
6496 	}
6497 	if (ins_nr) {
6498 		ret = copy_items(trans, inode, dst_path, path, ins_start_slot,
6499 				 ins_nr, inode_only, logged_isize, ctx);
6500 		if (ret)
6501 			return ret;
6502 	}
6503 
6504 	if (inode_only == LOG_INODE_ALL && S_ISREG(inode->vfs_inode.i_mode)) {
6505 		/*
6506 		 * Release the path because otherwise we might attempt to double
6507 		 * lock the same leaf with btrfs_log_prealloc_extents() below.
6508 		 */
6509 		btrfs_release_path(path);
6510 		ret = btrfs_log_prealloc_extents(trans, inode, dst_path, ctx);
6511 	}
6512 
6513 	return ret;
6514 }
6515 
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)6516 static int insert_delayed_items_batch(struct btrfs_trans_handle *trans,
6517 				      struct btrfs_root *log,
6518 				      struct btrfs_path *path,
6519 				      const struct btrfs_item_batch *batch,
6520 				      const struct btrfs_delayed_item *first_item)
6521 {
6522 	const struct btrfs_delayed_item *curr = first_item;
6523 	int ret;
6524 
6525 	ret = btrfs_insert_empty_items(trans, log, path, batch);
6526 	if (ret)
6527 		return ret;
6528 
6529 	for (int i = 0; i < batch->nr; i++) {
6530 		char *data_ptr;
6531 
6532 		data_ptr = btrfs_item_ptr(path->nodes[0], path->slots[0], char);
6533 		write_extent_buffer(path->nodes[0], &curr->data,
6534 				    (unsigned long)data_ptr, curr->data_len);
6535 		curr = list_next_entry(curr, log_list);
6536 		path->slots[0]++;
6537 	}
6538 
6539 	btrfs_release_path(path);
6540 
6541 	return 0;
6542 }
6543 
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)6544 static int log_delayed_insertion_items(struct btrfs_trans_handle *trans,
6545 				       struct btrfs_inode *inode,
6546 				       struct btrfs_path *path,
6547 				       const struct list_head *delayed_ins_list,
6548 				       struct btrfs_log_ctx *ctx)
6549 {
6550 	/* 195 (4095 bytes of keys and sizes) fits in a single 4K page. */
6551 	const int max_batch_size = 195;
6552 	const int leaf_data_size = BTRFS_LEAF_DATA_SIZE(trans->fs_info);
6553 	const u64 ino = btrfs_ino(inode);
6554 	struct btrfs_root *log = inode->root->log_root;
6555 	struct btrfs_item_batch batch = {
6556 		.nr = 0,
6557 		.total_data_size = 0,
6558 	};
6559 	const struct btrfs_delayed_item *first = NULL;
6560 	const struct btrfs_delayed_item *curr;
6561 	char *ins_data;
6562 	struct btrfs_key *ins_keys;
6563 	u32 *ins_sizes;
6564 	u64 curr_batch_size = 0;
6565 	int batch_idx = 0;
6566 	int ret;
6567 
6568 	/* We are adding dir index items to the log tree. */
6569 	lockdep_assert_held(&inode->log_mutex);
6570 
6571 	/*
6572 	 * We collect delayed items before copying index keys from the subvolume
6573 	 * to the log tree. However just after we collected them, they may have
6574 	 * been flushed (all of them or just some of them), and therefore we
6575 	 * could have copied them from the subvolume tree to the log tree.
6576 	 * So find the first delayed item that was not yet logged (they are
6577 	 * sorted by index number).
6578 	 */
6579 	list_for_each_entry(curr, delayed_ins_list, log_list) {
6580 		if (curr->index > inode->last_dir_index_offset) {
6581 			first = curr;
6582 			break;
6583 		}
6584 	}
6585 
6586 	/* Empty list or all delayed items were already logged. */
6587 	if (!first)
6588 		return 0;
6589 
6590 	ins_data = kmalloc_array(max_batch_size, sizeof(u32) + sizeof(struct btrfs_key), GFP_NOFS);
6591 	if (!ins_data)
6592 		return -ENOMEM;
6593 	ins_sizes = (u32 *)ins_data;
6594 	batch.data_sizes = ins_sizes;
6595 	ins_keys = (struct btrfs_key *)(ins_data + max_batch_size * sizeof(u32));
6596 	batch.keys = ins_keys;
6597 
6598 	curr = first;
6599 	while (!list_entry_is_head(curr, delayed_ins_list, log_list)) {
6600 		const u32 curr_size = curr->data_len + sizeof(struct btrfs_item);
6601 
6602 		if (curr_batch_size + curr_size > leaf_data_size ||
6603 		    batch.nr == max_batch_size) {
6604 			ret = insert_delayed_items_batch(trans, log, path,
6605 							 &batch, first);
6606 			if (ret)
6607 				goto out;
6608 			batch_idx = 0;
6609 			batch.nr = 0;
6610 			batch.total_data_size = 0;
6611 			curr_batch_size = 0;
6612 			first = curr;
6613 		}
6614 
6615 		ins_sizes[batch_idx] = curr->data_len;
6616 		ins_keys[batch_idx].objectid = ino;
6617 		ins_keys[batch_idx].type = BTRFS_DIR_INDEX_KEY;
6618 		ins_keys[batch_idx].offset = curr->index;
6619 		curr_batch_size += curr_size;
6620 		batch.total_data_size += curr->data_len;
6621 		batch.nr++;
6622 		batch_idx++;
6623 		curr = list_next_entry(curr, log_list);
6624 	}
6625 
6626 	ASSERT(batch.nr >= 1, "batch.nr=%d", batch.nr);
6627 	ret = insert_delayed_items_batch(trans, log, path, &batch, first);
6628 
6629 	curr = list_last_entry(delayed_ins_list, struct btrfs_delayed_item,
6630 			       log_list);
6631 	inode->last_dir_index_offset = curr->index;
6632 out:
6633 	kfree(ins_data);
6634 
6635 	return ret;
6636 }
6637 
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)6638 static int log_delayed_deletions_full(struct btrfs_trans_handle *trans,
6639 				      struct btrfs_inode *inode,
6640 				      struct btrfs_path *path,
6641 				      const struct list_head *delayed_del_list,
6642 				      struct btrfs_log_ctx *ctx)
6643 {
6644 	const u64 ino = btrfs_ino(inode);
6645 	const struct btrfs_delayed_item *curr;
6646 
6647 	curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6648 				log_list);
6649 
6650 	while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6651 		u64 first_dir_index = curr->index;
6652 		u64 last_dir_index;
6653 		const struct btrfs_delayed_item *next;
6654 		int ret;
6655 
6656 		/*
6657 		 * Find a range of consecutive dir index items to delete. Like
6658 		 * this we log a single dir range item spanning several contiguous
6659 		 * dir items instead of logging one range item per dir index item.
6660 		 */
6661 		next = list_next_entry(curr, log_list);
6662 		while (!list_entry_is_head(next, delayed_del_list, log_list)) {
6663 			if (next->index != curr->index + 1)
6664 				break;
6665 			curr = next;
6666 			next = list_next_entry(next, log_list);
6667 		}
6668 
6669 		last_dir_index = curr->index;
6670 		ASSERT(last_dir_index >= first_dir_index,
6671 		       "last_dir_index=%llu first_dir_index=%llu",
6672 		       last_dir_index, first_dir_index);
6673 
6674 		ret = insert_dir_log_key(trans, inode->root->log_root, path,
6675 					 ino, first_dir_index, last_dir_index);
6676 		if (ret)
6677 			return ret;
6678 		curr = list_next_entry(curr, log_list);
6679 	}
6680 
6681 	return 0;
6682 }
6683 
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)6684 static int batch_delete_dir_index_items(struct btrfs_trans_handle *trans,
6685 					struct btrfs_inode *inode,
6686 					struct btrfs_path *path,
6687 					const struct list_head *delayed_del_list,
6688 					const struct btrfs_delayed_item *first,
6689 					const struct btrfs_delayed_item **last_ret)
6690 {
6691 	const struct btrfs_delayed_item *next;
6692 	struct extent_buffer *leaf = path->nodes[0];
6693 	const int last_slot = btrfs_header_nritems(leaf) - 1;
6694 	int slot = path->slots[0] + 1;
6695 	const u64 ino = btrfs_ino(inode);
6696 
6697 	next = list_next_entry(first, log_list);
6698 
6699 	while (slot < last_slot &&
6700 	       !list_entry_is_head(next, delayed_del_list, log_list)) {
6701 		struct btrfs_key key;
6702 
6703 		btrfs_item_key_to_cpu(leaf, &key, slot);
6704 		if (key.objectid != ino ||
6705 		    key.type != BTRFS_DIR_INDEX_KEY ||
6706 		    key.offset != next->index)
6707 			break;
6708 
6709 		slot++;
6710 		*last_ret = next;
6711 		next = list_next_entry(next, log_list);
6712 	}
6713 
6714 	return btrfs_del_items(trans, inode->root->log_root, path,
6715 			       path->slots[0], slot - path->slots[0]);
6716 }
6717 
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)6718 static int log_delayed_deletions_incremental(struct btrfs_trans_handle *trans,
6719 					     struct btrfs_inode *inode,
6720 					     struct btrfs_path *path,
6721 					     const struct list_head *delayed_del_list,
6722 					     struct btrfs_log_ctx *ctx)
6723 {
6724 	struct btrfs_root *log = inode->root->log_root;
6725 	const struct btrfs_delayed_item *curr;
6726 	u64 last_range_start = 0;
6727 	u64 last_range_end = 0;
6728 	struct btrfs_key key;
6729 
6730 	key.objectid = btrfs_ino(inode);
6731 	key.type = BTRFS_DIR_INDEX_KEY;
6732 	curr = list_first_entry(delayed_del_list, struct btrfs_delayed_item,
6733 				log_list);
6734 
6735 	while (!list_entry_is_head(curr, delayed_del_list, log_list)) {
6736 		const struct btrfs_delayed_item *last = curr;
6737 		u64 first_dir_index = curr->index;
6738 		u64 last_dir_index;
6739 		bool deleted_items = false;
6740 		int ret;
6741 
6742 		key.offset = curr->index;
6743 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
6744 		if (ret < 0) {
6745 			return ret;
6746 		} else if (ret == 0) {
6747 			ret = batch_delete_dir_index_items(trans, inode, path,
6748 							   delayed_del_list, curr,
6749 							   &last);
6750 			if (ret)
6751 				return ret;
6752 			deleted_items = true;
6753 		}
6754 
6755 		btrfs_release_path(path);
6756 
6757 		/*
6758 		 * If we deleted items from the leaf, it means we have a range
6759 		 * item logging their range, so no need to add one or update an
6760 		 * existing one. Otherwise we have to log a dir range item.
6761 		 */
6762 		if (deleted_items)
6763 			goto next_batch;
6764 
6765 		last_dir_index = last->index;
6766 		ASSERT(last_dir_index >= first_dir_index,
6767 		       "last_dir_index=%llu first_dir_index=%llu",
6768 		       last_dir_index, first_dir_index);
6769 		/*
6770 		 * If this range starts right after where the previous one ends,
6771 		 * then we want to reuse the previous range item and change its
6772 		 * end offset to the end of this range. This is just to minimize
6773 		 * leaf space usage, by avoiding adding a new range item.
6774 		 */
6775 		if (last_range_end != 0 && first_dir_index == last_range_end + 1)
6776 			first_dir_index = last_range_start;
6777 
6778 		ret = insert_dir_log_key(trans, log, path, key.objectid,
6779 					 first_dir_index, last_dir_index);
6780 		if (ret)
6781 			return ret;
6782 
6783 		last_range_start = first_dir_index;
6784 		last_range_end = last_dir_index;
6785 next_batch:
6786 		curr = list_next_entry(last, log_list);
6787 	}
6788 
6789 	return 0;
6790 }
6791 
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)6792 static int log_delayed_deletion_items(struct btrfs_trans_handle *trans,
6793 				      struct btrfs_inode *inode,
6794 				      struct btrfs_path *path,
6795 				      const struct list_head *delayed_del_list,
6796 				      struct btrfs_log_ctx *ctx)
6797 {
6798 	/*
6799 	 * We are deleting dir index items from the log tree or adding range
6800 	 * items to it.
6801 	 */
6802 	lockdep_assert_held(&inode->log_mutex);
6803 
6804 	if (list_empty(delayed_del_list))
6805 		return 0;
6806 
6807 	if (ctx->logged_before)
6808 		return log_delayed_deletions_incremental(trans, inode, path,
6809 							 delayed_del_list, ctx);
6810 
6811 	return log_delayed_deletions_full(trans, inode, path, delayed_del_list,
6812 					  ctx);
6813 }
6814 
6815 /*
6816  * Similar logic as for log_new_dir_dentries(), but it iterates over the delayed
6817  * items instead of the subvolume tree.
6818  */
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)6819 static int log_new_delayed_dentries(struct btrfs_trans_handle *trans,
6820 				    struct btrfs_inode *inode,
6821 				    const struct list_head *delayed_ins_list,
6822 				    struct btrfs_log_ctx *ctx)
6823 {
6824 	const bool orig_log_new_dentries = ctx->log_new_dentries;
6825 	struct btrfs_delayed_item *item;
6826 	int ret = 0;
6827 
6828 	/*
6829 	 * No need for the log mutex, plus to avoid potential deadlocks or
6830 	 * lockdep annotations due to nesting of delayed inode mutexes and log
6831 	 * mutexes.
6832 	 */
6833 	lockdep_assert_not_held(&inode->log_mutex);
6834 
6835 	ASSERT(!ctx->logging_new_delayed_dentries,
6836 	       "ctx->logging_new_delayed_dentries=%d", ctx->logging_new_delayed_dentries);
6837 	ctx->logging_new_delayed_dentries = true;
6838 
6839 	list_for_each_entry(item, delayed_ins_list, log_list) {
6840 		struct btrfs_dir_item *dir_item;
6841 		struct btrfs_inode *di_inode;
6842 		struct btrfs_key key;
6843 		int log_mode = LOG_INODE_EXISTS;
6844 
6845 		dir_item = (struct btrfs_dir_item *)item->data;
6846 		btrfs_disk_key_to_cpu(&key, &dir_item->location);
6847 
6848 		if (key.type == BTRFS_ROOT_ITEM_KEY)
6849 			continue;
6850 
6851 		di_inode = btrfs_iget_logging(key.objectid, inode->root);
6852 		if (IS_ERR(di_inode)) {
6853 			ret = PTR_ERR(di_inode);
6854 			break;
6855 		}
6856 
6857 		if (!need_log_inode(trans, di_inode)) {
6858 			btrfs_add_delayed_iput(di_inode);
6859 			continue;
6860 		}
6861 
6862 		if (btrfs_stack_dir_ftype(dir_item) == BTRFS_FT_DIR)
6863 			log_mode = LOG_INODE_ALL;
6864 
6865 		ctx->log_new_dentries = false;
6866 		ret = btrfs_log_inode(trans, di_inode, log_mode, ctx);
6867 
6868 		if (!ret && ctx->log_new_dentries)
6869 			ret = log_new_dir_dentries(trans, di_inode, ctx);
6870 
6871 		btrfs_add_delayed_iput(di_inode);
6872 
6873 		if (ret)
6874 			break;
6875 	}
6876 
6877 	ctx->log_new_dentries = orig_log_new_dentries;
6878 	ctx->logging_new_delayed_dentries = false;
6879 
6880 	return ret;
6881 }
6882 
6883 /* log a single inode in the tree log.
6884  * At least one parent directory for this inode must exist in the tree
6885  * or be logged already.
6886  *
6887  * Any items from this inode changed by the current transaction are copied
6888  * to the log tree.  An extra reference is taken on any extents in this
6889  * file, allowing us to avoid a whole pile of corner cases around logging
6890  * blocks that have been removed from the tree.
6891  *
6892  * See LOG_INODE_ALL and related defines for a description of what inode_only
6893  * does.
6894  *
6895  * This handles both files and directories.
6896  */
btrfs_log_inode(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,int inode_only,struct btrfs_log_ctx * ctx)6897 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
6898 			   struct btrfs_inode *inode,
6899 			   int inode_only,
6900 			   struct btrfs_log_ctx *ctx)
6901 {
6902 	struct btrfs_path *path;
6903 	struct btrfs_path *dst_path;
6904 	struct btrfs_key min_key;
6905 	struct btrfs_key max_key;
6906 	struct btrfs_root *log = inode->root->log_root;
6907 	int ret;
6908 	bool fast_search = false;
6909 	u64 ino = btrfs_ino(inode);
6910 	struct extent_map_tree *em_tree = &inode->extent_tree;
6911 	u64 logged_isize = 0;
6912 	bool need_log_inode_item = true;
6913 	bool xattrs_logged = false;
6914 	bool inode_item_dropped = true;
6915 	bool full_dir_logging = false;
6916 	LIST_HEAD(delayed_ins_list);
6917 	LIST_HEAD(delayed_del_list);
6918 
6919 	path = btrfs_alloc_path();
6920 	if (!path)
6921 		return -ENOMEM;
6922 	dst_path = btrfs_alloc_path();
6923 	if (!dst_path) {
6924 		btrfs_free_path(path);
6925 		return -ENOMEM;
6926 	}
6927 
6928 	min_key.objectid = ino;
6929 	min_key.type = BTRFS_INODE_ITEM_KEY;
6930 	min_key.offset = 0;
6931 
6932 	max_key.objectid = ino;
6933 
6934 
6935 	/* today the code can only do partial logging of directories */
6936 	if (S_ISDIR(inode->vfs_inode.i_mode) ||
6937 	    (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
6938 		       &inode->runtime_flags) &&
6939 	     inode_only >= LOG_INODE_EXISTS))
6940 		max_key.type = BTRFS_XATTR_ITEM_KEY;
6941 	else
6942 		max_key.type = (u8)-1;
6943 	max_key.offset = (u64)-1;
6944 
6945 	if (S_ISDIR(inode->vfs_inode.i_mode) && inode_only == LOG_INODE_ALL)
6946 		full_dir_logging = true;
6947 
6948 	/*
6949 	 * If we are logging a directory while we are logging dentries of the
6950 	 * delayed items of some other inode, then we need to flush the delayed
6951 	 * items of this directory and not log the delayed items directly. This
6952 	 * is to prevent more than one level of recursion into btrfs_log_inode()
6953 	 * by having something like this:
6954 	 *
6955 	 *     $ mkdir -p a/b/c/d/e/f/g/h/...
6956 	 *     $ xfs_io -c "fsync" a
6957 	 *
6958 	 * Where all directories in the path did not exist before and are
6959 	 * created in the current transaction.
6960 	 * So in such a case we directly log the delayed items of the main
6961 	 * directory ("a") without flushing them first, while for each of its
6962 	 * subdirectories we flush their delayed items before logging them.
6963 	 * This prevents a potential unbounded recursion like this:
6964 	 *
6965 	 * btrfs_log_inode()
6966 	 *   log_new_delayed_dentries()
6967 	 *      btrfs_log_inode()
6968 	 *        log_new_delayed_dentries()
6969 	 *          btrfs_log_inode()
6970 	 *            log_new_delayed_dentries()
6971 	 *              (...)
6972 	 *
6973 	 * We have thresholds for the maximum number of delayed items to have in
6974 	 * memory, and once they are hit, the items are flushed asynchronously.
6975 	 * However the limit is quite high, so lets prevent deep levels of
6976 	 * recursion to happen by limiting the maximum depth to be 1.
6977 	 */
6978 	if (full_dir_logging && ctx->logging_new_delayed_dentries) {
6979 		ret = btrfs_commit_inode_delayed_items(trans, inode);
6980 		if (ret)
6981 			goto out;
6982 	}
6983 
6984 	mutex_lock(&inode->log_mutex);
6985 
6986 	/*
6987 	 * For symlinks, we must always log their content, which is stored in an
6988 	 * inline extent, otherwise we could end up with an empty symlink after
6989 	 * log replay, which is invalid on linux (symlink(2) returns -ENOENT if
6990 	 * one attempts to create an empty symlink).
6991 	 * We don't need to worry about flushing delalloc, because when we create
6992 	 * the inline extent when the symlink is created (we never have delalloc
6993 	 * for symlinks).
6994 	 */
6995 	if (S_ISLNK(inode->vfs_inode.i_mode))
6996 		inode_only = LOG_INODE_ALL;
6997 
6998 	/*
6999 	 * Before logging the inode item, cache the value returned by
7000 	 * inode_logged(), because after that we have the need to figure out if
7001 	 * the inode was previously logged in this transaction.
7002 	 */
7003 	ret = inode_logged(trans, inode, path);
7004 	if (ret < 0)
7005 		goto out_unlock;
7006 	ctx->logged_before = (ret == 1);
7007 	ret = 0;
7008 
7009 	/*
7010 	 * This is for cases where logging a directory could result in losing a
7011 	 * a file after replaying the log. For example, if we move a file from a
7012 	 * directory A to a directory B, then fsync directory A, we have no way
7013 	 * to known the file was moved from A to B, so logging just A would
7014 	 * result in losing the file after a log replay.
7015 	 */
7016 	if (full_dir_logging && inode->last_unlink_trans >= trans->transid) {
7017 		ret = BTRFS_LOG_FORCE_COMMIT;
7018 		goto out_unlock;
7019 	}
7020 
7021 	/*
7022 	 * a brute force approach to making sure we get the most uptodate
7023 	 * copies of everything.
7024 	 */
7025 	if (S_ISDIR(inode->vfs_inode.i_mode)) {
7026 		clear_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
7027 		if (ctx->logged_before)
7028 			ret = drop_inode_items(trans, log, path, inode,
7029 					       BTRFS_XATTR_ITEM_KEY);
7030 	} else {
7031 		if (inode_only == LOG_INODE_EXISTS) {
7032 			/*
7033 			 * Make sure the new inode item we write to the log has
7034 			 * the same isize as the current one (if it exists).
7035 			 * This is necessary to prevent data loss after log
7036 			 * replay, and also to prevent doing a wrong expanding
7037 			 * truncate - for e.g. create file, write 4K into offset
7038 			 * 0, fsync, write 4K into offset 4096, add hard link,
7039 			 * fsync some other file (to sync log), power fail - if
7040 			 * we use the inode's current i_size, after log replay
7041 			 * we get a 8Kb file, with the last 4Kb extent as a hole
7042 			 * (zeroes), as if an expanding truncate happened,
7043 			 * instead of getting a file of 4Kb only.
7044 			 */
7045 			ret = get_inode_size_to_log(trans, inode, path, &logged_isize);
7046 			if (ret)
7047 				goto out_unlock;
7048 		}
7049 		if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7050 			     &inode->runtime_flags)) {
7051 			if (inode_only == LOG_INODE_EXISTS) {
7052 				max_key.type = BTRFS_XATTR_ITEM_KEY;
7053 				if (ctx->logged_before)
7054 					ret = drop_inode_items(trans, log, path,
7055 							       inode, max_key.type);
7056 			} else {
7057 				clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7058 					  &inode->runtime_flags);
7059 				clear_bit(BTRFS_INODE_COPY_EVERYTHING,
7060 					  &inode->runtime_flags);
7061 				if (ctx->logged_before)
7062 					ret = truncate_inode_items(trans, log,
7063 								   inode, 0, 0);
7064 			}
7065 		} else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
7066 					      &inode->runtime_flags) ||
7067 			   inode_only == LOG_INODE_EXISTS) {
7068 			if (inode_only == LOG_INODE_ALL)
7069 				fast_search = true;
7070 			max_key.type = BTRFS_XATTR_ITEM_KEY;
7071 			if (ctx->logged_before)
7072 				ret = drop_inode_items(trans, log, path, inode,
7073 						       max_key.type);
7074 		} else {
7075 			if (inode_only == LOG_INODE_ALL)
7076 				fast_search = true;
7077 			inode_item_dropped = false;
7078 			goto log_extents;
7079 		}
7080 
7081 	}
7082 	if (ret)
7083 		goto out_unlock;
7084 
7085 	/*
7086 	 * If we are logging a directory in full mode, collect the delayed items
7087 	 * before iterating the subvolume tree, so that we don't miss any new
7088 	 * dir index items in case they get flushed while or right after we are
7089 	 * iterating the subvolume tree.
7090 	 */
7091 	if (full_dir_logging && !ctx->logging_new_delayed_dentries)
7092 		btrfs_log_get_delayed_items(inode, &delayed_ins_list,
7093 					    &delayed_del_list);
7094 
7095 	/*
7096 	 * If we are fsyncing a file with 0 hard links, then commit the delayed
7097 	 * inode because the last inode ref (or extref) item may still be in the
7098 	 * subvolume tree and if we log it the file will still exist after a log
7099 	 * replay. So commit the delayed inode to delete that last ref and we
7100 	 * skip logging it.
7101 	 */
7102 	if (inode->vfs_inode.i_nlink == 0) {
7103 		ret = btrfs_commit_inode_delayed_inode(inode);
7104 		if (ret)
7105 			goto out_unlock;
7106 	}
7107 
7108 	ret = copy_inode_items_to_log(trans, inode, &min_key, &max_key,
7109 				      path, dst_path, logged_isize,
7110 				      inode_only, ctx,
7111 				      &need_log_inode_item);
7112 	if (ret)
7113 		goto out_unlock;
7114 
7115 	btrfs_release_path(path);
7116 	btrfs_release_path(dst_path);
7117 	ret = btrfs_log_all_xattrs(trans, inode, path, dst_path, ctx);
7118 	if (ret)
7119 		goto out_unlock;
7120 	xattrs_logged = true;
7121 	if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
7122 		btrfs_release_path(path);
7123 		btrfs_release_path(dst_path);
7124 		ret = btrfs_log_holes(trans, inode, path);
7125 		if (ret)
7126 			goto out_unlock;
7127 	}
7128 log_extents:
7129 	btrfs_release_path(path);
7130 	btrfs_release_path(dst_path);
7131 	if (need_log_inode_item) {
7132 		ret = log_inode_item(trans, log, dst_path, inode, inode_item_dropped);
7133 		if (ret)
7134 			goto out_unlock;
7135 		/*
7136 		 * If we are doing a fast fsync and the inode was logged before
7137 		 * in this transaction, we don't need to log the xattrs because
7138 		 * they were logged before. If xattrs were added, changed or
7139 		 * deleted since the last time we logged the inode, then we have
7140 		 * already logged them because the inode had the runtime flag
7141 		 * BTRFS_INODE_COPY_EVERYTHING set.
7142 		 */
7143 		if (!xattrs_logged && inode->logged_trans < trans->transid) {
7144 			ret = btrfs_log_all_xattrs(trans, inode, path, dst_path, ctx);
7145 			if (ret)
7146 				goto out_unlock;
7147 			btrfs_release_path(path);
7148 		}
7149 	}
7150 	if (fast_search) {
7151 		ret = btrfs_log_changed_extents(trans, inode, dst_path, ctx);
7152 		if (ret)
7153 			goto out_unlock;
7154 	} else if (inode_only == LOG_INODE_ALL) {
7155 		struct extent_map *em, *n;
7156 
7157 		write_lock(&em_tree->lock);
7158 		list_for_each_entry_safe(em, n, &em_tree->modified_extents, list)
7159 			list_del_init(&em->list);
7160 		write_unlock(&em_tree->lock);
7161 	}
7162 
7163 	if (full_dir_logging) {
7164 		ret = log_directory_changes(trans, inode, path, dst_path, ctx);
7165 		if (ret)
7166 			goto out_unlock;
7167 		ret = log_delayed_insertion_items(trans, inode, path,
7168 						  &delayed_ins_list, ctx);
7169 		if (ret)
7170 			goto out_unlock;
7171 		ret = log_delayed_deletion_items(trans, inode, path,
7172 						 &delayed_del_list, ctx);
7173 		if (ret)
7174 			goto out_unlock;
7175 	}
7176 
7177 	spin_lock(&inode->lock);
7178 	inode->logged_trans = trans->transid;
7179 	/*
7180 	 * Don't update last_log_commit if we logged that an inode exists.
7181 	 * We do this for three reasons:
7182 	 *
7183 	 * 1) We might have had buffered writes to this inode that were
7184 	 *    flushed and had their ordered extents completed in this
7185 	 *    transaction, but we did not previously log the inode with
7186 	 *    LOG_INODE_ALL. Later the inode was evicted and after that
7187 	 *    it was loaded again and this LOG_INODE_EXISTS log operation
7188 	 *    happened. We must make sure that if an explicit fsync against
7189 	 *    the inode is performed later, it logs the new extents, an
7190 	 *    updated inode item, etc, and syncs the log. The same logic
7191 	 *    applies to direct IO writes instead of buffered writes.
7192 	 *
7193 	 * 2) When we log the inode with LOG_INODE_EXISTS, its inode item
7194 	 *    is logged with an i_size of 0 or whatever value was logged
7195 	 *    before. If later the i_size of the inode is increased by a
7196 	 *    truncate operation, the log is synced through an fsync of
7197 	 *    some other inode and then finally an explicit fsync against
7198 	 *    this inode is made, we must make sure this fsync logs the
7199 	 *    inode with the new i_size, the hole between old i_size and
7200 	 *    the new i_size, and syncs the log.
7201 	 *
7202 	 * 3) If we are logging that an ancestor inode exists as part of
7203 	 *    logging a new name from a link or rename operation, don't update
7204 	 *    its last_log_commit - otherwise if an explicit fsync is made
7205 	 *    against an ancestor, the fsync considers the inode in the log
7206 	 *    and doesn't sync the log, resulting in the ancestor missing after
7207 	 *    a power failure unless the log was synced as part of an fsync
7208 	 *    against any other unrelated inode.
7209 	 */
7210 	if (!ctx->logging_new_name && inode_only != LOG_INODE_EXISTS)
7211 		inode->last_log_commit = inode->last_sub_trans;
7212 	spin_unlock(&inode->lock);
7213 
7214 	/*
7215 	 * Reset the last_reflink_trans so that the next fsync does not need to
7216 	 * go through the slower path when logging extents and their checksums.
7217 	 */
7218 	if (inode_only == LOG_INODE_ALL)
7219 		inode->last_reflink_trans = 0;
7220 
7221 out_unlock:
7222 	mutex_unlock(&inode->log_mutex);
7223 out:
7224 	btrfs_free_path(path);
7225 	btrfs_free_path(dst_path);
7226 
7227 	if (ret)
7228 		free_conflicting_inodes(ctx);
7229 	else
7230 		ret = log_conflicting_inodes(trans, inode->root, ctx);
7231 
7232 	if (full_dir_logging && !ctx->logging_new_delayed_dentries) {
7233 		if (!ret)
7234 			ret = log_new_delayed_dentries(trans, inode,
7235 						       &delayed_ins_list, ctx);
7236 
7237 		btrfs_log_put_delayed_items(inode, &delayed_ins_list,
7238 					    &delayed_del_list);
7239 	}
7240 
7241 	return ret;
7242 }
7243 
btrfs_log_all_parents(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_log_ctx * ctx)7244 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
7245 				 struct btrfs_inode *inode,
7246 				 struct btrfs_log_ctx *ctx)
7247 {
7248 	int ret;
7249 	BTRFS_PATH_AUTO_FREE(path);
7250 	struct btrfs_key key;
7251 	struct btrfs_root *root = inode->root;
7252 	const u64 ino = btrfs_ino(inode);
7253 
7254 	path = btrfs_alloc_path();
7255 	if (!path)
7256 		return -ENOMEM;
7257 	path->skip_locking = true;
7258 	path->search_commit_root = true;
7259 
7260 	key.objectid = ino;
7261 	key.type = BTRFS_INODE_REF_KEY;
7262 	key.offset = 0;
7263 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7264 	if (ret < 0)
7265 		return ret;
7266 
7267 	while (true) {
7268 		struct extent_buffer *leaf = path->nodes[0];
7269 		int slot = path->slots[0];
7270 		u32 cur_offset = 0;
7271 		u32 item_size;
7272 		unsigned long ptr;
7273 
7274 		if (slot >= btrfs_header_nritems(leaf)) {
7275 			ret = btrfs_next_leaf(root, path);
7276 			if (ret < 0)
7277 				return ret;
7278 			if (ret > 0)
7279 				break;
7280 			continue;
7281 		}
7282 
7283 		btrfs_item_key_to_cpu(leaf, &key, slot);
7284 		/* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
7285 		if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
7286 			break;
7287 
7288 		item_size = btrfs_item_size(leaf, slot);
7289 		ptr = btrfs_item_ptr_offset(leaf, slot);
7290 		while (cur_offset < item_size) {
7291 			u64 dir_id;
7292 			struct btrfs_inode *dir_inode;
7293 
7294 			if (key.type == BTRFS_INODE_EXTREF_KEY) {
7295 				struct btrfs_inode_extref *extref;
7296 
7297 				extref = (struct btrfs_inode_extref *)
7298 					(ptr + cur_offset);
7299 				dir_id = btrfs_inode_extref_parent(leaf, extref);
7300 				cur_offset += sizeof(*extref);
7301 				cur_offset += btrfs_inode_extref_name_len(leaf,
7302 					extref);
7303 			} else {
7304 				dir_id = key.offset;
7305 				cur_offset = item_size;
7306 			}
7307 
7308 			dir_inode = btrfs_iget_logging(dir_id, root);
7309 			/*
7310 			 * If the parent inode was deleted, return an error to
7311 			 * fallback to a transaction commit. This is to prevent
7312 			 * getting an inode that was moved from one parent A to
7313 			 * a parent B, got its former parent A deleted and then
7314 			 * it got fsync'ed, from existing at both parents after
7315 			 * a log replay (and the old parent still existing).
7316 			 * Example:
7317 			 *
7318 			 * mkdir /mnt/A
7319 			 * mkdir /mnt/B
7320 			 * touch /mnt/B/bar
7321 			 * sync
7322 			 * mv /mnt/B/bar /mnt/A/bar
7323 			 * mv -T /mnt/A /mnt/B
7324 			 * fsync /mnt/B/bar
7325 			 * <power fail>
7326 			 *
7327 			 * If we ignore the old parent B which got deleted,
7328 			 * after a log replay we would have file bar linked
7329 			 * at both parents and the old parent B would still
7330 			 * exist.
7331 			 */
7332 			if (IS_ERR(dir_inode))
7333 				return PTR_ERR(dir_inode);
7334 
7335 			if (!need_log_inode(trans, dir_inode)) {
7336 				btrfs_add_delayed_iput(dir_inode);
7337 				continue;
7338 			}
7339 
7340 			ctx->log_new_dentries = false;
7341 			ret = btrfs_log_inode(trans, dir_inode, LOG_INODE_ALL, ctx);
7342 			if (!ret && ctx->log_new_dentries)
7343 				ret = log_new_dir_dentries(trans, dir_inode, ctx);
7344 			btrfs_add_delayed_iput(dir_inode);
7345 			if (ret)
7346 				return ret;
7347 		}
7348 		path->slots[0]++;
7349 	}
7350 	return 0;
7351 }
7352 
log_new_ancestors(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_log_ctx * ctx)7353 static int log_new_ancestors(struct btrfs_trans_handle *trans,
7354 			     struct btrfs_root *root,
7355 			     struct btrfs_path *path,
7356 			     struct btrfs_log_ctx *ctx)
7357 {
7358 	struct btrfs_key found_key;
7359 
7360 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
7361 
7362 	while (true) {
7363 		struct extent_buffer *leaf;
7364 		int slot;
7365 		struct btrfs_key search_key;
7366 		struct btrfs_inode *inode;
7367 		u64 ino;
7368 		int ret = 0;
7369 
7370 		btrfs_release_path(path);
7371 
7372 		ino = found_key.offset;
7373 
7374 		search_key.objectid = found_key.offset;
7375 		search_key.type = BTRFS_INODE_ITEM_KEY;
7376 		search_key.offset = 0;
7377 		inode = btrfs_iget_logging(ino, root);
7378 		if (IS_ERR(inode))
7379 			return PTR_ERR(inode);
7380 
7381 		if (inode->generation >= trans->transid &&
7382 		    need_log_inode(trans, inode))
7383 			ret = btrfs_log_inode(trans, inode, LOG_INODE_EXISTS, ctx);
7384 		btrfs_add_delayed_iput(inode);
7385 		if (ret)
7386 			return ret;
7387 
7388 		if (search_key.objectid == BTRFS_FIRST_FREE_OBJECTID)
7389 			break;
7390 
7391 		search_key.type = BTRFS_INODE_REF_KEY;
7392 		ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
7393 		if (ret < 0)
7394 			return ret;
7395 
7396 		leaf = path->nodes[0];
7397 		slot = path->slots[0];
7398 		if (slot >= btrfs_header_nritems(leaf)) {
7399 			ret = btrfs_next_leaf(root, path);
7400 			if (ret < 0)
7401 				return ret;
7402 			else if (ret > 0)
7403 				return -ENOENT;
7404 			leaf = path->nodes[0];
7405 			slot = path->slots[0];
7406 		}
7407 
7408 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
7409 		if (found_key.objectid != search_key.objectid ||
7410 		    found_key.type != BTRFS_INODE_REF_KEY)
7411 			return -ENOENT;
7412 	}
7413 	return 0;
7414 }
7415 
log_new_ancestors_fast(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct dentry * parent,struct btrfs_log_ctx * ctx)7416 static int log_new_ancestors_fast(struct btrfs_trans_handle *trans,
7417 				  struct btrfs_inode *inode,
7418 				  struct dentry *parent,
7419 				  struct btrfs_log_ctx *ctx)
7420 {
7421 	struct btrfs_root *root = inode->root;
7422 	struct dentry *old_parent = NULL;
7423 	struct super_block *sb = inode->vfs_inode.i_sb;
7424 	int ret = 0;
7425 
7426 	while (true) {
7427 		if (!parent || d_really_is_negative(parent) ||
7428 		    sb != parent->d_sb)
7429 			break;
7430 
7431 		inode = BTRFS_I(d_inode(parent));
7432 		if (root != inode->root)
7433 			break;
7434 
7435 		if (inode->generation >= trans->transid &&
7436 		    need_log_inode(trans, inode)) {
7437 			ret = btrfs_log_inode(trans, inode,
7438 					      LOG_INODE_EXISTS, ctx);
7439 			if (ret)
7440 				break;
7441 		}
7442 		if (IS_ROOT(parent))
7443 			break;
7444 
7445 		parent = dget_parent(parent);
7446 		dput(old_parent);
7447 		old_parent = parent;
7448 	}
7449 	dput(old_parent);
7450 
7451 	return ret;
7452 }
7453 
log_all_new_ancestors(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct dentry * parent,struct btrfs_log_ctx * ctx)7454 static int log_all_new_ancestors(struct btrfs_trans_handle *trans,
7455 				 struct btrfs_inode *inode,
7456 				 struct dentry *parent,
7457 				 struct btrfs_log_ctx *ctx)
7458 {
7459 	struct btrfs_root *root = inode->root;
7460 	const u64 ino = btrfs_ino(inode);
7461 	BTRFS_PATH_AUTO_FREE(path);
7462 	struct btrfs_key search_key;
7463 	int ret;
7464 
7465 	/*
7466 	 * For a single hard link case, go through a fast path that does not
7467 	 * need to iterate the fs/subvolume tree.
7468 	 */
7469 	if (inode->vfs_inode.i_nlink < 2)
7470 		return log_new_ancestors_fast(trans, inode, parent, ctx);
7471 
7472 	path = btrfs_alloc_path();
7473 	if (!path)
7474 		return -ENOMEM;
7475 
7476 	search_key.objectid = ino;
7477 	search_key.type = BTRFS_INODE_REF_KEY;
7478 	search_key.offset = 0;
7479 again:
7480 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
7481 	if (ret < 0)
7482 		return ret;
7483 	if (ret == 0)
7484 		path->slots[0]++;
7485 
7486 	while (true) {
7487 		struct extent_buffer *leaf = path->nodes[0];
7488 		int slot = path->slots[0];
7489 		struct btrfs_key found_key;
7490 
7491 		if (slot >= btrfs_header_nritems(leaf)) {
7492 			ret = btrfs_next_leaf(root, path);
7493 			if (ret < 0)
7494 				return ret;
7495 			if (ret > 0)
7496 				break;
7497 			continue;
7498 		}
7499 
7500 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
7501 		if (found_key.objectid != ino ||
7502 		    found_key.type > BTRFS_INODE_EXTREF_KEY)
7503 			break;
7504 
7505 		/*
7506 		 * Don't deal with extended references because they are rare
7507 		 * cases and too complex to deal with (we would need to keep
7508 		 * track of which subitem we are processing for each item in
7509 		 * this loop, etc). So just return some error to fallback to
7510 		 * a transaction commit.
7511 		 */
7512 		if (found_key.type == BTRFS_INODE_EXTREF_KEY)
7513 			return -EMLINK;
7514 
7515 		/*
7516 		 * Logging ancestors needs to do more searches on the fs/subvol
7517 		 * tree, so it releases the path as needed to avoid deadlocks.
7518 		 * Keep track of the last inode ref key and resume from that key
7519 		 * after logging all new ancestors for the current hard link.
7520 		 */
7521 		memcpy(&search_key, &found_key, sizeof(search_key));
7522 
7523 		ret = log_new_ancestors(trans, root, path, ctx);
7524 		if (ret)
7525 			return ret;
7526 		btrfs_release_path(path);
7527 		goto again;
7528 	}
7529 	return 0;
7530 }
7531 
7532 /*
7533  * helper function around btrfs_log_inode to make sure newly created
7534  * parent directories also end up in the log.  A minimal inode and backref
7535  * only logging is done of any parent directories that are older than
7536  * the last committed transaction
7537  */
btrfs_log_inode_parent(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct dentry * parent,int inode_only,struct btrfs_log_ctx * ctx)7538 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
7539 				  struct btrfs_inode *inode,
7540 				  struct dentry *parent,
7541 				  int inode_only,
7542 				  struct btrfs_log_ctx *ctx)
7543 {
7544 	struct btrfs_root *root = inode->root;
7545 	struct btrfs_fs_info *fs_info = root->fs_info;
7546 	int ret = 0;
7547 	bool log_dentries;
7548 
7549 	if (btrfs_test_opt(fs_info, NOTREELOG))
7550 		return BTRFS_LOG_FORCE_COMMIT;
7551 
7552 	if (btrfs_root_refs(&root->root_item) == 0)
7553 		return BTRFS_LOG_FORCE_COMMIT;
7554 
7555 	/*
7556 	 * If we're logging an inode from a subvolume created in the current
7557 	 * transaction we must force a commit since the root is not persisted.
7558 	 */
7559 	if (btrfs_root_generation(&root->root_item) == trans->transid)
7560 		return BTRFS_LOG_FORCE_COMMIT;
7561 
7562 	/* Skip already logged inodes and without new extents. */
7563 	if (btrfs_inode_in_log(inode, trans->transid) &&
7564 	    list_empty(&ctx->ordered_extents))
7565 		return BTRFS_NO_LOG_SYNC;
7566 
7567 	ret = start_log_trans(trans, root, ctx);
7568 	if (ret)
7569 		return ret;
7570 
7571 	ret = btrfs_log_inode(trans, inode, inode_only, ctx);
7572 	if (ret)
7573 		goto end_trans;
7574 
7575 	/*
7576 	 * for regular files, if its inode is already on disk, we don't
7577 	 * have to worry about the parents at all.  This is because
7578 	 * we can use the last_unlink_trans field to record renames
7579 	 * and other fun in this file.
7580 	 */
7581 	if (S_ISREG(inode->vfs_inode.i_mode) &&
7582 	    inode->generation < trans->transid &&
7583 	    inode->last_unlink_trans < trans->transid) {
7584 		ret = 0;
7585 		goto end_trans;
7586 	}
7587 
7588 	/*
7589 	 * Track if we need to log dentries because ctx->log_new_dentries can
7590 	 * be modified in the call chains below.
7591 	 */
7592 	log_dentries = ctx->log_new_dentries;
7593 
7594 	/*
7595 	 * On unlink we must make sure all our current and old parent directory
7596 	 * inodes are fully logged. This is to prevent leaving dangling
7597 	 * directory index entries in directories that were our parents but are
7598 	 * not anymore. Not doing this results in old parent directory being
7599 	 * impossible to delete after log replay (rmdir will always fail with
7600 	 * error -ENOTEMPTY).
7601 	 *
7602 	 * Example 1:
7603 	 *
7604 	 * mkdir testdir
7605 	 * touch testdir/foo
7606 	 * ln testdir/foo testdir/bar
7607 	 * sync
7608 	 * unlink testdir/bar
7609 	 * xfs_io -c fsync testdir/foo
7610 	 * <power failure>
7611 	 * mount fs, triggers log replay
7612 	 *
7613 	 * If we don't log the parent directory (testdir), after log replay the
7614 	 * directory still has an entry pointing to the file inode using the bar
7615 	 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
7616 	 * the file inode has a link count of 1.
7617 	 *
7618 	 * Example 2:
7619 	 *
7620 	 * mkdir testdir
7621 	 * touch foo
7622 	 * ln foo testdir/foo2
7623 	 * ln foo testdir/foo3
7624 	 * sync
7625 	 * unlink testdir/foo3
7626 	 * xfs_io -c fsync foo
7627 	 * <power failure>
7628 	 * mount fs, triggers log replay
7629 	 *
7630 	 * Similar as the first example, after log replay the parent directory
7631 	 * testdir still has an entry pointing to the inode file with name foo3
7632 	 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
7633 	 * and has a link count of 2.
7634 	 */
7635 	if (inode->last_unlink_trans >= trans->transid) {
7636 		ret = btrfs_log_all_parents(trans, inode, ctx);
7637 		if (ret)
7638 			goto end_trans;
7639 	}
7640 
7641 	ret = log_all_new_ancestors(trans, inode, parent, ctx);
7642 	if (ret)
7643 		goto end_trans;
7644 
7645 	if (log_dentries)
7646 		ret = log_new_dir_dentries(trans, inode, ctx);
7647 end_trans:
7648 	if (ret < 0) {
7649 		btrfs_set_log_full_commit(trans);
7650 		ret = BTRFS_LOG_FORCE_COMMIT;
7651 	}
7652 
7653 	if (ret)
7654 		btrfs_remove_log_ctx(root, ctx);
7655 	btrfs_end_log_trans(root);
7656 
7657 	return ret;
7658 }
7659 
7660 /*
7661  * it is not safe to log dentry if the chunk root has added new
7662  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
7663  * If this returns 1, you must commit the transaction to safely get your
7664  * data on disk.
7665  */
btrfs_log_dentry_safe(struct btrfs_trans_handle * trans,struct dentry * dentry,struct btrfs_log_ctx * ctx)7666 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
7667 			  struct dentry *dentry,
7668 			  struct btrfs_log_ctx *ctx)
7669 {
7670 	struct dentry *parent = dget_parent(dentry);
7671 	int ret;
7672 
7673 	ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
7674 				     LOG_INODE_ALL, ctx);
7675 	dput(parent);
7676 
7677 	return ret;
7678 }
7679 
7680 /*
7681  * should be called during mount to recover any replay any log trees
7682  * from the FS
7683  */
btrfs_recover_log_trees(struct btrfs_root * log_root_tree)7684 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
7685 {
7686 	int ret;
7687 	struct btrfs_path *path;
7688 	struct btrfs_trans_handle *trans;
7689 	struct btrfs_key key;
7690 	struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
7691 	struct walk_control wc = {
7692 		.process_func = process_one_buffer,
7693 		.stage = LOG_WALK_PIN_ONLY,
7694 	};
7695 
7696 	path = btrfs_alloc_path();
7697 	if (!path)
7698 		return -ENOMEM;
7699 
7700 	set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7701 
7702 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
7703 	if (IS_ERR(trans)) {
7704 		ret = PTR_ERR(trans);
7705 		goto error;
7706 	}
7707 
7708 	wc.trans = trans;
7709 	wc.pin = true;
7710 	wc.log = log_root_tree;
7711 
7712 	ret = walk_log_tree(&wc);
7713 	wc.log = NULL;
7714 	if (unlikely(ret)) {
7715 		btrfs_abort_transaction(trans, ret);
7716 		goto error;
7717 	}
7718 
7719 again:
7720 	key.objectid = BTRFS_TREE_LOG_OBJECTID;
7721 	key.type = BTRFS_ROOT_ITEM_KEY;
7722 	key.offset = (u64)-1;
7723 
7724 	while (1) {
7725 		struct btrfs_key found_key;
7726 
7727 		ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
7728 
7729 		if (unlikely(ret < 0)) {
7730 			btrfs_abort_transaction(trans, ret);
7731 			goto error;
7732 		}
7733 		if (ret > 0) {
7734 			if (path->slots[0] == 0)
7735 				break;
7736 			path->slots[0]--;
7737 		}
7738 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
7739 				      path->slots[0]);
7740 		btrfs_release_path(path);
7741 		if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
7742 			break;
7743 
7744 		wc.log = btrfs_read_tree_root(log_root_tree, &found_key);
7745 		if (IS_ERR(wc.log)) {
7746 			ret = PTR_ERR(wc.log);
7747 			wc.log = NULL;
7748 			btrfs_abort_transaction(trans, ret);
7749 			goto error;
7750 		}
7751 
7752 		wc.root = btrfs_get_fs_root(fs_info, found_key.offset, true);
7753 		if (IS_ERR(wc.root)) {
7754 			ret = PTR_ERR(wc.root);
7755 			wc.root = NULL;
7756 			if (unlikely(ret != -ENOENT)) {
7757 				btrfs_abort_transaction(trans, ret);
7758 				goto error;
7759 			}
7760 
7761 			/*
7762 			 * We didn't find the subvol, likely because it was
7763 			 * deleted.  This is ok, simply skip this log and go to
7764 			 * the next one.
7765 			 *
7766 			 * We need to exclude the root because we can't have
7767 			 * other log replays overwriting this log as we'll read
7768 			 * it back in a few more times.  This will keep our
7769 			 * block from being modified, and we'll just bail for
7770 			 * each subsequent pass.
7771 			 */
7772 			ret = btrfs_pin_extent_for_log_replay(trans, wc.log->node);
7773 			if (unlikely(ret)) {
7774 				btrfs_abort_transaction(trans, ret);
7775 				goto error;
7776 			}
7777 			goto next;
7778 		}
7779 
7780 		wc.root->log_root = wc.log;
7781 		ret = btrfs_record_root_in_trans(trans, wc.root);
7782 		if (unlikely(ret)) {
7783 			btrfs_abort_transaction(trans, ret);
7784 			goto next;
7785 		}
7786 
7787 		ret = walk_log_tree(&wc);
7788 		if (unlikely(ret)) {
7789 			btrfs_abort_transaction(trans, ret);
7790 			goto next;
7791 		}
7792 
7793 		if (wc.stage == LOG_WALK_REPLAY_ALL) {
7794 			struct btrfs_root *root = wc.root;
7795 
7796 			wc.subvol_path = path;
7797 			ret = fixup_inode_link_counts(&wc);
7798 			wc.subvol_path = NULL;
7799 			if (unlikely(ret)) {
7800 				btrfs_abort_transaction(trans, ret);
7801 				goto next;
7802 			}
7803 			/*
7804 			 * We have just replayed everything, and the highest
7805 			 * objectid of fs roots probably has changed in case
7806 			 * some inode_item's got replayed.
7807 			 *
7808 			 * root->objectid_mutex is not acquired as log replay
7809 			 * could only happen during mount.
7810 			 */
7811 			ret = btrfs_init_root_free_objectid(root);
7812 			if (unlikely(ret)) {
7813 				btrfs_abort_transaction(trans, ret);
7814 				goto next;
7815 			}
7816 		}
7817 next:
7818 		if (wc.root) {
7819 			wc.root->log_root = NULL;
7820 			btrfs_put_root(wc.root);
7821 		}
7822 		btrfs_put_root(wc.log);
7823 		wc.log = NULL;
7824 
7825 		if (ret)
7826 			goto error;
7827 		if (found_key.offset == 0)
7828 			break;
7829 		key.offset = found_key.offset - 1;
7830 	}
7831 	btrfs_release_path(path);
7832 
7833 	/* step one is to pin it all, step two is to replay just inodes */
7834 	if (wc.pin) {
7835 		wc.pin = false;
7836 		wc.process_func = replay_one_buffer;
7837 		wc.stage = LOG_WALK_REPLAY_INODES;
7838 		goto again;
7839 	}
7840 	/* step three is to replay everything */
7841 	if (wc.stage < LOG_WALK_REPLAY_ALL) {
7842 		wc.stage++;
7843 		goto again;
7844 	}
7845 
7846 	btrfs_free_path(path);
7847 
7848 	/* step 4: commit the transaction, which also unpins the blocks */
7849 	ret = btrfs_commit_transaction(trans);
7850 	if (ret)
7851 		return ret;
7852 
7853 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7854 
7855 	return 0;
7856 error:
7857 	if (wc.trans)
7858 		btrfs_end_transaction(wc.trans);
7859 	btrfs_put_root(wc.log);
7860 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
7861 	btrfs_free_path(path);
7862 	return ret;
7863 }
7864 
7865 /*
7866  * there are some corner cases where we want to force a full
7867  * commit instead of allowing a directory to be logged.
7868  *
7869  * They revolve around files there were unlinked from the directory, and
7870  * this function updates the parent directory so that a full commit is
7871  * properly done if it is fsync'd later after the unlinks are done.
7872  *
7873  * Must be called before the unlink operations (updates to the subvolume tree,
7874  * inodes, etc) are done.
7875  */
btrfs_record_unlink_dir(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct btrfs_inode * inode,bool for_rename)7876 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
7877 			     struct btrfs_inode *dir, struct btrfs_inode *inode,
7878 			     bool for_rename)
7879 {
7880 	/*
7881 	 * when we're logging a file, if it hasn't been renamed
7882 	 * or unlinked, and its inode is fully committed on disk,
7883 	 * we don't have to worry about walking up the directory chain
7884 	 * to log its parents.
7885 	 *
7886 	 * So, we use the last_unlink_trans field to put this transid
7887 	 * into the file.  When the file is logged we check it and
7888 	 * don't log the parents if the file is fully on disk.
7889 	 */
7890 	mutex_lock(&inode->log_mutex);
7891 	inode->last_unlink_trans = trans->transid;
7892 	mutex_unlock(&inode->log_mutex);
7893 
7894 	if (!for_rename)
7895 		return;
7896 
7897 	/*
7898 	 * If this directory was already logged, any new names will be logged
7899 	 * with btrfs_log_new_name() and old names will be deleted from the log
7900 	 * tree with btrfs_del_dir_entries_in_log() or with
7901 	 * btrfs_del_inode_ref_in_log().
7902 	 */
7903 	if (inode_logged(trans, dir, NULL) == 1)
7904 		return;
7905 
7906 	/*
7907 	 * If the inode we're about to unlink was logged before, the log will be
7908 	 * properly updated with the new name with btrfs_log_new_name() and the
7909 	 * old name removed with btrfs_del_dir_entries_in_log() or with
7910 	 * btrfs_del_inode_ref_in_log().
7911 	 */
7912 	if (inode_logged(trans, inode, NULL) == 1)
7913 		return;
7914 
7915 	/*
7916 	 * when renaming files across directories, if the directory
7917 	 * there we're unlinking from gets fsync'd later on, there's
7918 	 * no way to find the destination directory later and fsync it
7919 	 * properly.  So, we have to be conservative and force commits
7920 	 * so the new name gets discovered.
7921 	 */
7922 	mutex_lock(&dir->log_mutex);
7923 	dir->last_unlink_trans = trans->transid;
7924 	mutex_unlock(&dir->log_mutex);
7925 }
7926 
7927 /*
7928  * Make sure that if someone attempts to fsync the parent directory of a deleted
7929  * snapshot, it ends up triggering a transaction commit. This is to guarantee
7930  * that after replaying the log tree of the parent directory's root we will not
7931  * see the snapshot anymore and at log replay time we will not see any log tree
7932  * corresponding to the deleted snapshot's root, which could lead to replaying
7933  * it after replaying the log tree of the parent directory (which would replay
7934  * the snapshot delete operation).
7935  *
7936  * Must be called before the actual snapshot destroy operation (updates to the
7937  * parent root and tree of tree roots trees, etc) are done.
7938  */
btrfs_record_snapshot_destroy(struct btrfs_trans_handle * trans,struct btrfs_inode * dir)7939 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
7940 				   struct btrfs_inode *dir)
7941 {
7942 	mutex_lock(&dir->log_mutex);
7943 	dir->last_unlink_trans = trans->transid;
7944 	mutex_unlock(&dir->log_mutex);
7945 }
7946 
7947 /*
7948  * Call this when creating a subvolume in a directory.
7949  * Because we don't commit a transaction when creating a subvolume, we can't
7950  * allow the directory pointing to the subvolume to be logged with an entry that
7951  * points to an unpersisted root if we are still in the transaction used to
7952  * create the subvolume, so make any attempt to log the directory to result in a
7953  * full log sync.
7954  * Also we don't need to worry with renames, since btrfs_rename() marks the log
7955  * for full commit when renaming a subvolume.
7956  *
7957  * Must be called before creating the subvolume entry in its parent directory.
7958  */
btrfs_record_new_subvolume(const struct btrfs_trans_handle * trans,struct btrfs_inode * dir)7959 void btrfs_record_new_subvolume(const struct btrfs_trans_handle *trans,
7960 				struct btrfs_inode *dir)
7961 {
7962 	mutex_lock(&dir->log_mutex);
7963 	dir->last_unlink_trans = trans->transid;
7964 	mutex_unlock(&dir->log_mutex);
7965 }
7966 
7967 /*
7968  * Update the log after adding a new name for an inode.
7969  *
7970  * @trans:              Transaction handle.
7971  * @old_dentry:         The dentry associated with the old name and the old
7972  *                      parent directory.
7973  * @old_dir:            The inode of the previous parent directory for the case
7974  *                      of a rename. For a link operation, it must be NULL.
7975  * @old_dir_index:      The index number associated with the old name, meaningful
7976  *                      only for rename operations (when @old_dir is not NULL).
7977  *                      Ignored for link operations.
7978  * @parent:             The dentry associated with the directory under which the
7979  *                      new name is located.
7980  *
7981  * Call this after adding a new name for an inode, as a result of a link or
7982  * rename operation, and it will properly update the log to reflect the new name.
7983  */
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)7984 void btrfs_log_new_name(struct btrfs_trans_handle *trans,
7985 			struct dentry *old_dentry, struct btrfs_inode *old_dir,
7986 			u64 old_dir_index, struct dentry *parent)
7987 {
7988 	struct btrfs_inode *inode = BTRFS_I(d_inode(old_dentry));
7989 	struct btrfs_root *root = inode->root;
7990 	struct btrfs_log_ctx ctx;
7991 	bool log_pinned = false;
7992 	int ret;
7993 
7994 	/* The inode has a new name (ref/extref), so make sure we log it. */
7995 	set_bit(BTRFS_INODE_COPY_EVERYTHING, &inode->runtime_flags);
7996 
7997 	btrfs_init_log_ctx(&ctx, inode);
7998 	ctx.logging_new_name = true;
7999 
8000 	/*
8001 	 * this will force the logging code to walk the dentry chain
8002 	 * up for the file
8003 	 */
8004 	if (!S_ISDIR(inode->vfs_inode.i_mode))
8005 		inode->last_unlink_trans = trans->transid;
8006 
8007 	/*
8008 	 * if this inode hasn't been logged and directory we're renaming it
8009 	 * from hasn't been logged, we don't need to log it
8010 	 */
8011 	ret = inode_logged(trans, inode, NULL);
8012 	if (ret < 0) {
8013 		goto out;
8014 	} else if (ret == 0) {
8015 		if (!old_dir)
8016 			return;
8017 		/*
8018 		 * If the inode was not logged and we are doing a rename (old_dir is not
8019 		 * NULL), check if old_dir was logged - if it was not we can return and
8020 		 * do nothing.
8021 		 */
8022 		ret = inode_logged(trans, old_dir, NULL);
8023 		if (ret < 0)
8024 			goto out;
8025 		else if (ret == 0)
8026 			return;
8027 	}
8028 	ret = 0;
8029 
8030 	/*
8031 	 * Now that we know we need to update the log, allocate the scratch eb
8032 	 * for the context before joining a log transaction below, as this can
8033 	 * take time and therefore we could delay log commits from other tasks.
8034 	 */
8035 	btrfs_init_log_ctx_scratch_eb(&ctx);
8036 
8037 	/*
8038 	 * If we are doing a rename (old_dir is not NULL) from a directory that
8039 	 * was previously logged, make sure that on log replay we get the old
8040 	 * dir entry deleted. This is needed because we will also log the new
8041 	 * name of the renamed inode, so we need to make sure that after log
8042 	 * replay we don't end up with both the new and old dir entries existing.
8043 	 */
8044 	if (old_dir && old_dir->logged_trans == trans->transid) {
8045 		struct btrfs_root *log = old_dir->root->log_root;
8046 		struct btrfs_path *path;
8047 		struct fscrypt_name fname;
8048 
8049 		ASSERT(old_dir_index >= BTRFS_DIR_START_INDEX,
8050 		       "old_dir_index=%llu", old_dir_index);
8051 
8052 		ret = fscrypt_setup_filename(&old_dir->vfs_inode,
8053 					     &old_dentry->d_name, 0, &fname);
8054 		if (ret)
8055 			goto out;
8056 
8057 		path = btrfs_alloc_path();
8058 		if (!path) {
8059 			ret = -ENOMEM;
8060 			fscrypt_free_filename(&fname);
8061 			goto out;
8062 		}
8063 
8064 		/*
8065 		 * We have two inodes to update in the log, the old directory and
8066 		 * the inode that got renamed, so we must pin the log to prevent
8067 		 * anyone from syncing the log until we have updated both inodes
8068 		 * in the log.
8069 		 */
8070 		ret = join_running_log_trans(root);
8071 		/*
8072 		 * At least one of the inodes was logged before, so this should
8073 		 * not fail, but if it does, it's not serious, just bail out and
8074 		 * mark the log for a full commit.
8075 		 */
8076 		if (WARN_ON_ONCE(ret < 0)) {
8077 			btrfs_free_path(path);
8078 			fscrypt_free_filename(&fname);
8079 			goto out;
8080 		}
8081 
8082 		log_pinned = true;
8083 
8084 		/*
8085 		 * Other concurrent task might be logging the old directory,
8086 		 * as it can be triggered when logging other inode that had or
8087 		 * still has a dentry in the old directory. We lock the old
8088 		 * directory's log_mutex to ensure the deletion of the old
8089 		 * name is persisted, because during directory logging we
8090 		 * delete all BTRFS_DIR_LOG_INDEX_KEY keys and the deletion of
8091 		 * the old name's dir index item is in the delayed items, so
8092 		 * it could be missed by an in progress directory logging.
8093 		 */
8094 		mutex_lock(&old_dir->log_mutex);
8095 		ret = del_logged_dentry(trans, log, path, btrfs_ino(old_dir),
8096 					&fname.disk_name, old_dir_index);
8097 		if (ret > 0) {
8098 			/*
8099 			 * The dentry does not exist in the log, so record its
8100 			 * deletion.
8101 			 */
8102 			btrfs_release_path(path);
8103 			ret = insert_dir_log_key(trans, log, path,
8104 						 btrfs_ino(old_dir),
8105 						 old_dir_index, old_dir_index);
8106 		}
8107 		mutex_unlock(&old_dir->log_mutex);
8108 
8109 		btrfs_free_path(path);
8110 		fscrypt_free_filename(&fname);
8111 		if (ret < 0)
8112 			goto out;
8113 	}
8114 
8115 	/*
8116 	 * We don't care about the return value. If we fail to log the new name
8117 	 * then we know the next attempt to sync the log will fallback to a full
8118 	 * transaction commit (due to a call to btrfs_set_log_full_commit()), so
8119 	 * we don't need to worry about getting a log committed that has an
8120 	 * inconsistent state after a rename operation.
8121 	 */
8122 	btrfs_log_inode_parent(trans, inode, parent, LOG_INODE_EXISTS, &ctx);
8123 	ASSERT(list_empty(&ctx.conflict_inodes));
8124 out:
8125 	/*
8126 	 * If an error happened mark the log for a full commit because it's not
8127 	 * consistent and up to date or we couldn't find out if one of the
8128 	 * inodes was logged before in this transaction. Do it before unpinning
8129 	 * the log, to avoid any races with someone else trying to commit it.
8130 	 */
8131 	if (ret < 0)
8132 		btrfs_set_log_full_commit(trans);
8133 	if (log_pinned)
8134 		btrfs_end_log_trans(root);
8135 	free_extent_buffer(ctx.scratch_eb);
8136 }
8137 
8138