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