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