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