• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "ctree.h"
12 #include "tree-log.h"
13 #include "disk-io.h"
14 #include "locking.h"
15 #include "print-tree.h"
16 #include "backref.h"
17 #include "compression.h"
18 #include "qgroup.h"
19 #include "inode-map.h"
20 
21 /* magic values for the inode_only field in btrfs_log_inode:
22  *
23  * LOG_INODE_ALL means to log everything
24  * LOG_INODE_EXISTS means to log just enough to recreate the inode
25  * during log replay
26  */
27 #define LOG_INODE_ALL 0
28 #define LOG_INODE_EXISTS 1
29 #define LOG_OTHER_INODE 2
30 
31 /*
32  * directory trouble cases
33  *
34  * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
35  * log, we must force a full commit before doing an fsync of the directory
36  * where the unlink was done.
37  * ---> record transid of last unlink/rename per directory
38  *
39  * mkdir foo/some_dir
40  * normal commit
41  * rename foo/some_dir foo2/some_dir
42  * mkdir foo/some_dir
43  * fsync foo/some_dir/some_file
44  *
45  * The fsync above will unlink the original some_dir without recording
46  * it in its new location (foo2).  After a crash, some_dir will be gone
47  * unless the fsync of some_file forces a full commit
48  *
49  * 2) we must log any new names for any file or dir that is in the fsync
50  * log. ---> check inode while renaming/linking.
51  *
52  * 2a) we must log any new names for any file or dir during rename
53  * when the directory they are being removed from was logged.
54  * ---> check inode and old parent dir during rename
55  *
56  *  2a is actually the more important variant.  With the extra logging
57  *  a crash might unlink the old name without recreating the new one
58  *
59  * 3) after a crash, we must go through any directories with a link count
60  * of zero and redo the rm -rf
61  *
62  * mkdir f1/foo
63  * normal commit
64  * rm -rf f1/foo
65  * fsync(f1)
66  *
67  * The directory f1 was fully removed from the FS, but fsync was never
68  * called on f1, only its parent dir.  After a crash the rm -rf must
69  * be replayed.  This must be able to recurse down the entire
70  * directory tree.  The inode link count fixup code takes care of the
71  * ugly details.
72  */
73 
74 /*
75  * stages for the tree walking.  The first
76  * stage (0) is to only pin down the blocks we find
77  * the second stage (1) is to make sure that all the inodes
78  * we find in the log are created in the subvolume.
79  *
80  * The last stage is to deal with directories and links and extents
81  * and all the other fun semantics
82  */
83 #define LOG_WALK_PIN_ONLY 0
84 #define LOG_WALK_REPLAY_INODES 1
85 #define LOG_WALK_REPLAY_DIR_INDEX 2
86 #define LOG_WALK_REPLAY_ALL 3
87 
88 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
89 			   struct btrfs_root *root, struct btrfs_inode *inode,
90 			   int inode_only,
91 			   const loff_t start,
92 			   const loff_t end,
93 			   struct btrfs_log_ctx *ctx);
94 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
95 			     struct btrfs_root *root,
96 			     struct btrfs_path *path, u64 objectid);
97 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
98 				       struct btrfs_root *root,
99 				       struct btrfs_root *log,
100 				       struct btrfs_path *path,
101 				       u64 dirid, int del_all);
102 
103 /*
104  * tree logging is a special write ahead log used to make sure that
105  * fsyncs and O_SYNCs can happen without doing full tree commits.
106  *
107  * Full tree commits are expensive because they require commonly
108  * modified blocks to be recowed, creating many dirty pages in the
109  * extent tree an 4x-6x higher write load than ext3.
110  *
111  * Instead of doing a tree commit on every fsync, we use the
112  * key ranges and transaction ids to find items for a given file or directory
113  * that have changed in this transaction.  Those items are copied into
114  * a special tree (one per subvolume root), that tree is written to disk
115  * and then the fsync is considered complete.
116  *
117  * After a crash, items are copied out of the log-tree back into the
118  * subvolume tree.  Any file data extents found are recorded in the extent
119  * allocation tree, and the log-tree freed.
120  *
121  * The log tree is read three times, once to pin down all the extents it is
122  * using in ram and once, once to create all the inodes logged in the tree
123  * and once to do all the other items.
124  */
125 
126 /*
127  * start a sub transaction and setup the log tree
128  * this increments the log tree writer count to make the people
129  * syncing the tree wait for us to finish
130  */
start_log_trans(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_log_ctx * ctx)131 static int start_log_trans(struct btrfs_trans_handle *trans,
132 			   struct btrfs_root *root,
133 			   struct btrfs_log_ctx *ctx)
134 {
135 	struct btrfs_fs_info *fs_info = root->fs_info;
136 	int ret = 0;
137 
138 	mutex_lock(&root->log_mutex);
139 
140 	if (root->log_root) {
141 		if (btrfs_need_log_full_commit(fs_info, trans)) {
142 			ret = -EAGAIN;
143 			goto out;
144 		}
145 
146 		if (!root->log_start_pid) {
147 			clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
148 			root->log_start_pid = current->pid;
149 		} else if (root->log_start_pid != current->pid) {
150 			set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
151 		}
152 	} else {
153 		mutex_lock(&fs_info->tree_log_mutex);
154 		if (!fs_info->log_root_tree)
155 			ret = btrfs_init_log_root_tree(trans, fs_info);
156 		mutex_unlock(&fs_info->tree_log_mutex);
157 		if (ret)
158 			goto out;
159 
160 		ret = btrfs_add_log_tree(trans, root);
161 		if (ret)
162 			goto out;
163 
164 		clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
165 		root->log_start_pid = current->pid;
166 	}
167 
168 	atomic_inc(&root->log_batch);
169 	atomic_inc(&root->log_writers);
170 	if (ctx) {
171 		int index = root->log_transid % 2;
172 		list_add_tail(&ctx->list, &root->log_ctxs[index]);
173 		ctx->log_transid = root->log_transid;
174 	}
175 
176 out:
177 	mutex_unlock(&root->log_mutex);
178 	return ret;
179 }
180 
181 /*
182  * returns 0 if there was a log transaction running and we were able
183  * to join, or returns -ENOENT if there were not transactions
184  * in progress
185  */
join_running_log_trans(struct btrfs_root * root)186 static int join_running_log_trans(struct btrfs_root *root)
187 {
188 	int ret = -ENOENT;
189 
190 	smp_mb();
191 	if (!root->log_root)
192 		return -ENOENT;
193 
194 	mutex_lock(&root->log_mutex);
195 	if (root->log_root) {
196 		ret = 0;
197 		atomic_inc(&root->log_writers);
198 	}
199 	mutex_unlock(&root->log_mutex);
200 	return ret;
201 }
202 
203 /*
204  * This either makes the current running log transaction wait
205  * until you call btrfs_end_log_trans() or it makes any future
206  * log transactions wait until you call btrfs_end_log_trans()
207  */
btrfs_pin_log_trans(struct btrfs_root * root)208 int btrfs_pin_log_trans(struct btrfs_root *root)
209 {
210 	int ret = -ENOENT;
211 
212 	mutex_lock(&root->log_mutex);
213 	atomic_inc(&root->log_writers);
214 	mutex_unlock(&root->log_mutex);
215 	return ret;
216 }
217 
218 /*
219  * indicate we're done making changes to the log tree
220  * and wake up anyone waiting to do a sync
221  */
btrfs_end_log_trans(struct btrfs_root * root)222 void btrfs_end_log_trans(struct btrfs_root *root)
223 {
224 	if (atomic_dec_and_test(&root->log_writers)) {
225 		/* atomic_dec_and_test implies a barrier */
226 		cond_wake_up_nomb(&root->log_writer_wait);
227 	}
228 }
229 
230 
231 /*
232  * the walk control struct is used to pass state down the chain when
233  * processing the log tree.  The stage field tells us which part
234  * of the log tree processing we are currently doing.  The others
235  * are state fields used for that specific part
236  */
237 struct walk_control {
238 	/* should we free the extent on disk when done?  This is used
239 	 * at transaction commit time while freeing a log tree
240 	 */
241 	int free;
242 
243 	/* should we write out the extent buffer?  This is used
244 	 * while flushing the log tree to disk during a sync
245 	 */
246 	int write;
247 
248 	/* should we wait for the extent buffer io to finish?  Also used
249 	 * while flushing the log tree to disk for a sync
250 	 */
251 	int wait;
252 
253 	/* pin only walk, we record which extents on disk belong to the
254 	 * log trees
255 	 */
256 	int pin;
257 
258 	/* what stage of the replay code we're currently in */
259 	int stage;
260 
261 	/*
262 	 * Ignore any items from the inode currently being processed. Needs
263 	 * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
264 	 * the LOG_WALK_REPLAY_INODES stage.
265 	 */
266 	bool ignore_cur_inode;
267 
268 	/* the root we are currently replaying */
269 	struct btrfs_root *replay_dest;
270 
271 	/* the trans handle for the current replay */
272 	struct btrfs_trans_handle *trans;
273 
274 	/* the function that gets used to process blocks we find in the
275 	 * tree.  Note the extent_buffer might not be up to date when it is
276 	 * passed in, and it must be checked or read if you need the data
277 	 * inside it
278 	 */
279 	int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
280 			    struct walk_control *wc, u64 gen, int level);
281 };
282 
283 /*
284  * process_func used to pin down extents, write them or wait on them
285  */
process_one_buffer(struct btrfs_root * log,struct extent_buffer * eb,struct walk_control * wc,u64 gen,int level)286 static int process_one_buffer(struct btrfs_root *log,
287 			      struct extent_buffer *eb,
288 			      struct walk_control *wc, u64 gen, int level)
289 {
290 	struct btrfs_fs_info *fs_info = log->fs_info;
291 	int ret = 0;
292 
293 	/*
294 	 * If this fs is mixed then we need to be able to process the leaves to
295 	 * pin down any logged extents, so we have to read the block.
296 	 */
297 	if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
298 		ret = btrfs_read_buffer(eb, gen, level, NULL);
299 		if (ret)
300 			return ret;
301 	}
302 
303 	if (wc->pin)
304 		ret = btrfs_pin_extent_for_log_replay(fs_info, eb->start,
305 						      eb->len);
306 
307 	if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
308 		if (wc->pin && btrfs_header_level(eb) == 0)
309 			ret = btrfs_exclude_logged_extents(fs_info, eb);
310 		if (wc->write)
311 			btrfs_write_tree_block(eb);
312 		if (wc->wait)
313 			btrfs_wait_tree_block_writeback(eb);
314 	}
315 	return ret;
316 }
317 
318 /*
319  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
320  * to the src data we are copying out.
321  *
322  * root is the tree we are copying into, and path is a scratch
323  * path for use in this function (it should be released on entry and
324  * will be released on exit).
325  *
326  * If the key is already in the destination tree the existing item is
327  * overwritten.  If the existing item isn't big enough, it is extended.
328  * If it is too large, it is truncated.
329  *
330  * If the key isn't in the destination yet, a new item is inserted.
331  */
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)332 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
333 				   struct btrfs_root *root,
334 				   struct btrfs_path *path,
335 				   struct extent_buffer *eb, int slot,
336 				   struct btrfs_key *key)
337 {
338 	struct btrfs_fs_info *fs_info = root->fs_info;
339 	int ret;
340 	u32 item_size;
341 	u64 saved_i_size = 0;
342 	int save_old_i_size = 0;
343 	unsigned long src_ptr;
344 	unsigned long dst_ptr;
345 	int overwrite_root = 0;
346 	bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
347 
348 	if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
349 		overwrite_root = 1;
350 
351 	item_size = btrfs_item_size_nr(eb, slot);
352 	src_ptr = btrfs_item_ptr_offset(eb, slot);
353 
354 	/* look for the key in the destination tree */
355 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
356 	if (ret < 0)
357 		return ret;
358 
359 	if (ret == 0) {
360 		char *src_copy;
361 		char *dst_copy;
362 		u32 dst_size = btrfs_item_size_nr(path->nodes[0],
363 						  path->slots[0]);
364 		if (dst_size != item_size)
365 			goto insert;
366 
367 		if (item_size == 0) {
368 			btrfs_release_path(path);
369 			return 0;
370 		}
371 		dst_copy = kmalloc(item_size, GFP_NOFS);
372 		src_copy = kmalloc(item_size, GFP_NOFS);
373 		if (!dst_copy || !src_copy) {
374 			btrfs_release_path(path);
375 			kfree(dst_copy);
376 			kfree(src_copy);
377 			return -ENOMEM;
378 		}
379 
380 		read_extent_buffer(eb, src_copy, src_ptr, item_size);
381 
382 		dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
383 		read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
384 				   item_size);
385 		ret = memcmp(dst_copy, src_copy, item_size);
386 
387 		kfree(dst_copy);
388 		kfree(src_copy);
389 		/*
390 		 * they have the same contents, just return, this saves
391 		 * us from cowing blocks in the destination tree and doing
392 		 * extra writes that may not have been done by a previous
393 		 * sync
394 		 */
395 		if (ret == 0) {
396 			btrfs_release_path(path);
397 			return 0;
398 		}
399 
400 		/*
401 		 * We need to load the old nbytes into the inode so when we
402 		 * replay the extents we've logged we get the right nbytes.
403 		 */
404 		if (inode_item) {
405 			struct btrfs_inode_item *item;
406 			u64 nbytes;
407 			u32 mode;
408 
409 			item = btrfs_item_ptr(path->nodes[0], path->slots[0],
410 					      struct btrfs_inode_item);
411 			nbytes = btrfs_inode_nbytes(path->nodes[0], item);
412 			item = btrfs_item_ptr(eb, slot,
413 					      struct btrfs_inode_item);
414 			btrfs_set_inode_nbytes(eb, item, nbytes);
415 
416 			/*
417 			 * If this is a directory we need to reset the i_size to
418 			 * 0 so that we can set it up properly when replaying
419 			 * the rest of the items in this log.
420 			 */
421 			mode = btrfs_inode_mode(eb, item);
422 			if (S_ISDIR(mode))
423 				btrfs_set_inode_size(eb, item, 0);
424 		}
425 	} else if (inode_item) {
426 		struct btrfs_inode_item *item;
427 		u32 mode;
428 
429 		/*
430 		 * New inode, set nbytes to 0 so that the nbytes comes out
431 		 * properly when we replay the extents.
432 		 */
433 		item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
434 		btrfs_set_inode_nbytes(eb, item, 0);
435 
436 		/*
437 		 * If this is a directory we need to reset the i_size to 0 so
438 		 * that we can set it up properly when replaying the rest of
439 		 * the items in this log.
440 		 */
441 		mode = btrfs_inode_mode(eb, item);
442 		if (S_ISDIR(mode))
443 			btrfs_set_inode_size(eb, item, 0);
444 	}
445 insert:
446 	btrfs_release_path(path);
447 	/* try to insert the key into the destination tree */
448 	path->skip_release_on_error = 1;
449 	ret = btrfs_insert_empty_item(trans, root, path,
450 				      key, item_size);
451 	path->skip_release_on_error = 0;
452 
453 	/* make sure any existing item is the correct size */
454 	if (ret == -EEXIST || ret == -EOVERFLOW) {
455 		u32 found_size;
456 		found_size = btrfs_item_size_nr(path->nodes[0],
457 						path->slots[0]);
458 		if (found_size > item_size)
459 			btrfs_truncate_item(fs_info, path, item_size, 1);
460 		else if (found_size < item_size)
461 			btrfs_extend_item(fs_info, path,
462 					  item_size - found_size);
463 	} else if (ret) {
464 		return ret;
465 	}
466 	dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
467 					path->slots[0]);
468 
469 	/* don't overwrite an existing inode if the generation number
470 	 * was logged as zero.  This is done when the tree logging code
471 	 * is just logging an inode to make sure it exists after recovery.
472 	 *
473 	 * Also, don't overwrite i_size on directories during replay.
474 	 * log replay inserts and removes directory items based on the
475 	 * state of the tree found in the subvolume, and i_size is modified
476 	 * as it goes
477 	 */
478 	if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
479 		struct btrfs_inode_item *src_item;
480 		struct btrfs_inode_item *dst_item;
481 
482 		src_item = (struct btrfs_inode_item *)src_ptr;
483 		dst_item = (struct btrfs_inode_item *)dst_ptr;
484 
485 		if (btrfs_inode_generation(eb, src_item) == 0) {
486 			struct extent_buffer *dst_eb = path->nodes[0];
487 			const u64 ino_size = btrfs_inode_size(eb, src_item);
488 
489 			/*
490 			 * For regular files an ino_size == 0 is used only when
491 			 * logging that an inode exists, as part of a directory
492 			 * fsync, and the inode wasn't fsynced before. In this
493 			 * case don't set the size of the inode in the fs/subvol
494 			 * tree, otherwise we would be throwing valid data away.
495 			 */
496 			if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
497 			    S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
498 			    ino_size != 0) {
499 				struct btrfs_map_token token;
500 
501 				btrfs_init_map_token(&token);
502 				btrfs_set_token_inode_size(dst_eb, dst_item,
503 							   ino_size, &token);
504 			}
505 			goto no_copy;
506 		}
507 
508 		if (overwrite_root &&
509 		    S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
510 		    S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
511 			save_old_i_size = 1;
512 			saved_i_size = btrfs_inode_size(path->nodes[0],
513 							dst_item);
514 		}
515 	}
516 
517 	copy_extent_buffer(path->nodes[0], eb, dst_ptr,
518 			   src_ptr, item_size);
519 
520 	if (save_old_i_size) {
521 		struct btrfs_inode_item *dst_item;
522 		dst_item = (struct btrfs_inode_item *)dst_ptr;
523 		btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
524 	}
525 
526 	/* make sure the generation is filled in */
527 	if (key->type == BTRFS_INODE_ITEM_KEY) {
528 		struct btrfs_inode_item *dst_item;
529 		dst_item = (struct btrfs_inode_item *)dst_ptr;
530 		if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
531 			btrfs_set_inode_generation(path->nodes[0], dst_item,
532 						   trans->transid);
533 		}
534 	}
535 no_copy:
536 	btrfs_mark_buffer_dirty(path->nodes[0]);
537 	btrfs_release_path(path);
538 	return 0;
539 }
540 
541 /*
542  * simple helper to read an inode off the disk from a given root
543  * This can only be called for subvolume roots and not for the log
544  */
read_one_inode(struct btrfs_root * root,u64 objectid)545 static noinline struct inode *read_one_inode(struct btrfs_root *root,
546 					     u64 objectid)
547 {
548 	struct btrfs_key key;
549 	struct inode *inode;
550 
551 	key.objectid = objectid;
552 	key.type = BTRFS_INODE_ITEM_KEY;
553 	key.offset = 0;
554 	inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
555 	if (IS_ERR(inode))
556 		inode = NULL;
557 	return inode;
558 }
559 
560 /* replays a single extent in 'eb' at 'slot' with 'key' into the
561  * subvolume 'root'.  path is released on entry and should be released
562  * on exit.
563  *
564  * extents in the log tree have not been allocated out of the extent
565  * tree yet.  So, this completes the allocation, taking a reference
566  * as required if the extent already exists or creating a new extent
567  * if it isn't in the extent allocation tree yet.
568  *
569  * The extent is inserted into the file, dropping any existing extents
570  * from the file that overlap the new one.
571  */
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)572 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
573 				      struct btrfs_root *root,
574 				      struct btrfs_path *path,
575 				      struct extent_buffer *eb, int slot,
576 				      struct btrfs_key *key)
577 {
578 	struct btrfs_fs_info *fs_info = root->fs_info;
579 	int found_type;
580 	u64 extent_end;
581 	u64 start = key->offset;
582 	u64 nbytes = 0;
583 	struct btrfs_file_extent_item *item;
584 	struct inode *inode = NULL;
585 	unsigned long size;
586 	int ret = 0;
587 
588 	item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
589 	found_type = btrfs_file_extent_type(eb, item);
590 
591 	if (found_type == BTRFS_FILE_EXTENT_REG ||
592 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
593 		nbytes = btrfs_file_extent_num_bytes(eb, item);
594 		extent_end = start + nbytes;
595 
596 		/*
597 		 * We don't add to the inodes nbytes if we are prealloc or a
598 		 * hole.
599 		 */
600 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
601 			nbytes = 0;
602 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
603 		size = btrfs_file_extent_ram_bytes(eb, item);
604 		nbytes = btrfs_file_extent_ram_bytes(eb, item);
605 		extent_end = ALIGN(start + size,
606 				   fs_info->sectorsize);
607 	} else {
608 		ret = 0;
609 		goto out;
610 	}
611 
612 	inode = read_one_inode(root, key->objectid);
613 	if (!inode) {
614 		ret = -EIO;
615 		goto out;
616 	}
617 
618 	/*
619 	 * first check to see if we already have this extent in the
620 	 * file.  This must be done before the btrfs_drop_extents run
621 	 * so we don't try to drop this extent.
622 	 */
623 	ret = btrfs_lookup_file_extent(trans, root, path,
624 			btrfs_ino(BTRFS_I(inode)), start, 0);
625 
626 	if (ret == 0 &&
627 	    (found_type == BTRFS_FILE_EXTENT_REG ||
628 	     found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
629 		struct btrfs_file_extent_item cmp1;
630 		struct btrfs_file_extent_item cmp2;
631 		struct btrfs_file_extent_item *existing;
632 		struct extent_buffer *leaf;
633 
634 		leaf = path->nodes[0];
635 		existing = btrfs_item_ptr(leaf, path->slots[0],
636 					  struct btrfs_file_extent_item);
637 
638 		read_extent_buffer(eb, &cmp1, (unsigned long)item,
639 				   sizeof(cmp1));
640 		read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
641 				   sizeof(cmp2));
642 
643 		/*
644 		 * we already have a pointer to this exact extent,
645 		 * we don't have to do anything
646 		 */
647 		if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
648 			btrfs_release_path(path);
649 			goto out;
650 		}
651 	}
652 	btrfs_release_path(path);
653 
654 	/* drop any overlapping extents */
655 	ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
656 	if (ret)
657 		goto out;
658 
659 	if (found_type == BTRFS_FILE_EXTENT_REG ||
660 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
661 		u64 offset;
662 		unsigned long dest_offset;
663 		struct btrfs_key ins;
664 
665 		if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
666 		    btrfs_fs_incompat(fs_info, NO_HOLES))
667 			goto update_inode;
668 
669 		ret = btrfs_insert_empty_item(trans, root, path, key,
670 					      sizeof(*item));
671 		if (ret)
672 			goto out;
673 		dest_offset = btrfs_item_ptr_offset(path->nodes[0],
674 						    path->slots[0]);
675 		copy_extent_buffer(path->nodes[0], eb, dest_offset,
676 				(unsigned long)item,  sizeof(*item));
677 
678 		ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
679 		ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
680 		ins.type = BTRFS_EXTENT_ITEM_KEY;
681 		offset = key->offset - btrfs_file_extent_offset(eb, item);
682 
683 		/*
684 		 * Manually record dirty extent, as here we did a shallow
685 		 * file extent item copy and skip normal backref update,
686 		 * but modifying extent tree all by ourselves.
687 		 * So need to manually record dirty extent for qgroup,
688 		 * as the owner of the file extent changed from log tree
689 		 * (doesn't affect qgroup) to fs/file tree(affects qgroup)
690 		 */
691 		ret = btrfs_qgroup_trace_extent(trans,
692 				btrfs_file_extent_disk_bytenr(eb, item),
693 				btrfs_file_extent_disk_num_bytes(eb, item),
694 				GFP_NOFS);
695 		if (ret < 0)
696 			goto out;
697 
698 		if (ins.objectid > 0) {
699 			u64 csum_start;
700 			u64 csum_end;
701 			LIST_HEAD(ordered_sums);
702 			/*
703 			 * is this extent already allocated in the extent
704 			 * allocation tree?  If so, just add a reference
705 			 */
706 			ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
707 						ins.offset);
708 			if (ret == 0) {
709 				ret = btrfs_inc_extent_ref(trans, root,
710 						ins.objectid, ins.offset,
711 						0, root->root_key.objectid,
712 						key->objectid, offset);
713 				if (ret)
714 					goto out;
715 			} else {
716 				/*
717 				 * insert the extent pointer in the extent
718 				 * allocation tree
719 				 */
720 				ret = btrfs_alloc_logged_file_extent(trans,
721 						root->root_key.objectid,
722 						key->objectid, offset, &ins);
723 				if (ret)
724 					goto out;
725 			}
726 			btrfs_release_path(path);
727 
728 			if (btrfs_file_extent_compression(eb, item)) {
729 				csum_start = ins.objectid;
730 				csum_end = csum_start + ins.offset;
731 			} else {
732 				csum_start = ins.objectid +
733 					btrfs_file_extent_offset(eb, item);
734 				csum_end = csum_start +
735 					btrfs_file_extent_num_bytes(eb, item);
736 			}
737 
738 			ret = btrfs_lookup_csums_range(root->log_root,
739 						csum_start, csum_end - 1,
740 						&ordered_sums, 0);
741 			if (ret)
742 				goto out;
743 			/*
744 			 * Now delete all existing cums in the csum root that
745 			 * cover our range. We do this because we can have an
746 			 * extent that is completely referenced by one file
747 			 * extent item and partially referenced by another
748 			 * file extent item (like after using the clone or
749 			 * extent_same ioctls). In this case if we end up doing
750 			 * the replay of the one that partially references the
751 			 * extent first, and we do not do the csum deletion
752 			 * below, we can get 2 csum items in the csum tree that
753 			 * overlap each other. For example, imagine our log has
754 			 * the two following file extent items:
755 			 *
756 			 * key (257 EXTENT_DATA 409600)
757 			 *     extent data disk byte 12845056 nr 102400
758 			 *     extent data offset 20480 nr 20480 ram 102400
759 			 *
760 			 * key (257 EXTENT_DATA 819200)
761 			 *     extent data disk byte 12845056 nr 102400
762 			 *     extent data offset 0 nr 102400 ram 102400
763 			 *
764 			 * Where the second one fully references the 100K extent
765 			 * that starts at disk byte 12845056, and the log tree
766 			 * has a single csum item that covers the entire range
767 			 * of the extent:
768 			 *
769 			 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
770 			 *
771 			 * After the first file extent item is replayed, the
772 			 * csum tree gets the following csum item:
773 			 *
774 			 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
775 			 *
776 			 * Which covers the 20K sub-range starting at offset 20K
777 			 * of our extent. Now when we replay the second file
778 			 * extent item, if we do not delete existing csum items
779 			 * that cover any of its blocks, we end up getting two
780 			 * csum items in our csum tree that overlap each other:
781 			 *
782 			 * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
783 			 * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
784 			 *
785 			 * Which is a problem, because after this anyone trying
786 			 * to lookup up for the checksum of any block of our
787 			 * extent starting at an offset of 40K or higher, will
788 			 * end up looking at the second csum item only, which
789 			 * does not contain the checksum for any block starting
790 			 * at offset 40K or higher of our extent.
791 			 */
792 			while (!list_empty(&ordered_sums)) {
793 				struct btrfs_ordered_sum *sums;
794 				sums = list_entry(ordered_sums.next,
795 						struct btrfs_ordered_sum,
796 						list);
797 				if (!ret)
798 					ret = btrfs_del_csums(trans,
799 							      fs_info->csum_root,
800 							      sums->bytenr,
801 							      sums->len);
802 				if (!ret)
803 					ret = btrfs_csum_file_blocks(trans,
804 						fs_info->csum_root, sums);
805 				list_del(&sums->list);
806 				kfree(sums);
807 			}
808 			if (ret)
809 				goto out;
810 		} else {
811 			btrfs_release_path(path);
812 		}
813 	} else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
814 		/* inline extents are easy, we just overwrite them */
815 		ret = overwrite_item(trans, root, path, eb, slot, key);
816 		if (ret)
817 			goto out;
818 	}
819 
820 	inode_add_bytes(inode, nbytes);
821 update_inode:
822 	ret = btrfs_update_inode(trans, root, inode);
823 out:
824 	if (inode)
825 		iput(inode);
826 	return ret;
827 }
828 
829 /*
830  * when cleaning up conflicts between the directory names in the
831  * subvolume, directory names in the log and directory names in the
832  * inode back references, we may have to unlink inodes from directories.
833  *
834  * This is a helper function to do the unlink of a specific directory
835  * item
836  */
drop_one_dir_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,struct btrfs_inode * dir,struct btrfs_dir_item * di)837 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
838 				      struct btrfs_root *root,
839 				      struct btrfs_path *path,
840 				      struct btrfs_inode *dir,
841 				      struct btrfs_dir_item *di)
842 {
843 	struct inode *inode;
844 	char *name;
845 	int name_len;
846 	struct extent_buffer *leaf;
847 	struct btrfs_key location;
848 	int ret;
849 
850 	leaf = path->nodes[0];
851 
852 	btrfs_dir_item_key_to_cpu(leaf, di, &location);
853 	name_len = btrfs_dir_name_len(leaf, di);
854 	name = kmalloc(name_len, GFP_NOFS);
855 	if (!name)
856 		return -ENOMEM;
857 
858 	read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
859 	btrfs_release_path(path);
860 
861 	inode = read_one_inode(root, location.objectid);
862 	if (!inode) {
863 		ret = -EIO;
864 		goto out;
865 	}
866 
867 	ret = link_to_fixup_dir(trans, root, path, location.objectid);
868 	if (ret)
869 		goto out;
870 
871 	ret = btrfs_unlink_inode(trans, root, dir, BTRFS_I(inode), name,
872 			name_len);
873 	if (ret)
874 		goto out;
875 	else
876 		ret = btrfs_run_delayed_items(trans);
877 out:
878 	kfree(name);
879 	iput(inode);
880 	return ret;
881 }
882 
883 /*
884  * helper function to see if a given name and sequence number found
885  * in an inode back reference are already in a directory and correctly
886  * point to this inode
887  */
inode_in_dir(struct btrfs_root * root,struct btrfs_path * path,u64 dirid,u64 objectid,u64 index,const char * name,int name_len)888 static noinline int inode_in_dir(struct btrfs_root *root,
889 				 struct btrfs_path *path,
890 				 u64 dirid, u64 objectid, u64 index,
891 				 const char *name, int name_len)
892 {
893 	struct btrfs_dir_item *di;
894 	struct btrfs_key location;
895 	int match = 0;
896 
897 	di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
898 					 index, name, name_len, 0);
899 	if (di && !IS_ERR(di)) {
900 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
901 		if (location.objectid != objectid)
902 			goto out;
903 	} else
904 		goto out;
905 	btrfs_release_path(path);
906 
907 	di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
908 	if (di && !IS_ERR(di)) {
909 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
910 		if (location.objectid != objectid)
911 			goto out;
912 	} else
913 		goto out;
914 	match = 1;
915 out:
916 	btrfs_release_path(path);
917 	return match;
918 }
919 
920 /*
921  * helper function to check a log tree for a named back reference in
922  * an inode.  This is used to decide if a back reference that is
923  * found in the subvolume conflicts with what we find in the log.
924  *
925  * inode backreferences may have multiple refs in a single item,
926  * during replay we process one reference at a time, and we don't
927  * want to delete valid links to a file from the subvolume if that
928  * link is also in the log.
929  */
backref_in_log(struct btrfs_root * log,struct btrfs_key * key,u64 ref_objectid,const char * name,int namelen)930 static noinline int backref_in_log(struct btrfs_root *log,
931 				   struct btrfs_key *key,
932 				   u64 ref_objectid,
933 				   const char *name, int namelen)
934 {
935 	struct btrfs_path *path;
936 	struct btrfs_inode_ref *ref;
937 	unsigned long ptr;
938 	unsigned long ptr_end;
939 	unsigned long name_ptr;
940 	int found_name_len;
941 	int item_size;
942 	int ret;
943 	int match = 0;
944 
945 	path = btrfs_alloc_path();
946 	if (!path)
947 		return -ENOMEM;
948 
949 	ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
950 	if (ret != 0)
951 		goto out;
952 
953 	ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
954 
955 	if (key->type == BTRFS_INODE_EXTREF_KEY) {
956 		if (btrfs_find_name_in_ext_backref(path->nodes[0],
957 						   path->slots[0],
958 						   ref_objectid,
959 						   name, namelen, NULL))
960 			match = 1;
961 
962 		goto out;
963 	}
964 
965 	item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
966 	ptr_end = ptr + item_size;
967 	while (ptr < ptr_end) {
968 		ref = (struct btrfs_inode_ref *)ptr;
969 		found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
970 		if (found_name_len == namelen) {
971 			name_ptr = (unsigned long)(ref + 1);
972 			ret = memcmp_extent_buffer(path->nodes[0], name,
973 						   name_ptr, namelen);
974 			if (ret == 0) {
975 				match = 1;
976 				goto out;
977 			}
978 		}
979 		ptr = (unsigned long)(ref + 1) + found_name_len;
980 	}
981 out:
982 	btrfs_free_path(path);
983 	return match;
984 }
985 
__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,char * name,int namelen,int * search_done)986 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
987 				  struct btrfs_root *root,
988 				  struct btrfs_path *path,
989 				  struct btrfs_root *log_root,
990 				  struct btrfs_inode *dir,
991 				  struct btrfs_inode *inode,
992 				  u64 inode_objectid, u64 parent_objectid,
993 				  u64 ref_index, char *name, int namelen,
994 				  int *search_done)
995 {
996 	int ret;
997 	char *victim_name;
998 	int victim_name_len;
999 	struct extent_buffer *leaf;
1000 	struct btrfs_dir_item *di;
1001 	struct btrfs_key search_key;
1002 	struct btrfs_inode_extref *extref;
1003 
1004 again:
1005 	/* Search old style refs */
1006 	search_key.objectid = inode_objectid;
1007 	search_key.type = BTRFS_INODE_REF_KEY;
1008 	search_key.offset = parent_objectid;
1009 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1010 	if (ret == 0) {
1011 		struct btrfs_inode_ref *victim_ref;
1012 		unsigned long ptr;
1013 		unsigned long ptr_end;
1014 
1015 		leaf = path->nodes[0];
1016 
1017 		/* are we trying to overwrite a back ref for the root directory
1018 		 * if so, just jump out, we're done
1019 		 */
1020 		if (search_key.objectid == search_key.offset)
1021 			return 1;
1022 
1023 		/* check all the names in this back reference to see
1024 		 * if they are in the log.  if so, we allow them to stay
1025 		 * otherwise they must be unlinked as a conflict
1026 		 */
1027 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1028 		ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
1029 		while (ptr < ptr_end) {
1030 			victim_ref = (struct btrfs_inode_ref *)ptr;
1031 			victim_name_len = btrfs_inode_ref_name_len(leaf,
1032 								   victim_ref);
1033 			victim_name = kmalloc(victim_name_len, GFP_NOFS);
1034 			if (!victim_name)
1035 				return -ENOMEM;
1036 
1037 			read_extent_buffer(leaf, victim_name,
1038 					   (unsigned long)(victim_ref + 1),
1039 					   victim_name_len);
1040 
1041 			if (!backref_in_log(log_root, &search_key,
1042 					    parent_objectid,
1043 					    victim_name,
1044 					    victim_name_len)) {
1045 				inc_nlink(&inode->vfs_inode);
1046 				btrfs_release_path(path);
1047 
1048 				ret = btrfs_unlink_inode(trans, root, dir, inode,
1049 						victim_name, victim_name_len);
1050 				kfree(victim_name);
1051 				if (ret)
1052 					return ret;
1053 				ret = btrfs_run_delayed_items(trans);
1054 				if (ret)
1055 					return ret;
1056 				*search_done = 1;
1057 				goto again;
1058 			}
1059 			kfree(victim_name);
1060 
1061 			ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
1062 		}
1063 
1064 		/*
1065 		 * NOTE: we have searched root tree and checked the
1066 		 * corresponding ref, it does not need to check again.
1067 		 */
1068 		*search_done = 1;
1069 	}
1070 	btrfs_release_path(path);
1071 
1072 	/* Same search but for extended refs */
1073 	extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
1074 					   inode_objectid, parent_objectid, 0,
1075 					   0);
1076 	if (!IS_ERR_OR_NULL(extref)) {
1077 		u32 item_size;
1078 		u32 cur_offset = 0;
1079 		unsigned long base;
1080 		struct inode *victim_parent;
1081 
1082 		leaf = path->nodes[0];
1083 
1084 		item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1085 		base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1086 
1087 		while (cur_offset < item_size) {
1088 			extref = (struct btrfs_inode_extref *)(base + cur_offset);
1089 
1090 			victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
1091 
1092 			if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1093 				goto next;
1094 
1095 			victim_name = kmalloc(victim_name_len, GFP_NOFS);
1096 			if (!victim_name)
1097 				return -ENOMEM;
1098 			read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1099 					   victim_name_len);
1100 
1101 			search_key.objectid = inode_objectid;
1102 			search_key.type = BTRFS_INODE_EXTREF_KEY;
1103 			search_key.offset = btrfs_extref_hash(parent_objectid,
1104 							      victim_name,
1105 							      victim_name_len);
1106 			ret = 0;
1107 			if (!backref_in_log(log_root, &search_key,
1108 					    parent_objectid, victim_name,
1109 					    victim_name_len)) {
1110 				ret = -ENOENT;
1111 				victim_parent = read_one_inode(root,
1112 						parent_objectid);
1113 				if (victim_parent) {
1114 					inc_nlink(&inode->vfs_inode);
1115 					btrfs_release_path(path);
1116 
1117 					ret = btrfs_unlink_inode(trans, root,
1118 							BTRFS_I(victim_parent),
1119 							inode,
1120 							victim_name,
1121 							victim_name_len);
1122 					if (!ret)
1123 						ret = btrfs_run_delayed_items(
1124 								  trans);
1125 				}
1126 				iput(victim_parent);
1127 				kfree(victim_name);
1128 				if (ret)
1129 					return ret;
1130 				*search_done = 1;
1131 				goto again;
1132 			}
1133 			kfree(victim_name);
1134 next:
1135 			cur_offset += victim_name_len + sizeof(*extref);
1136 		}
1137 		*search_done = 1;
1138 	}
1139 	btrfs_release_path(path);
1140 
1141 	/* look for a conflicting sequence number */
1142 	di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1143 					 ref_index, name, namelen, 0);
1144 	if (di && !IS_ERR(di)) {
1145 		ret = drop_one_dir_item(trans, root, path, dir, di);
1146 		if (ret)
1147 			return ret;
1148 	}
1149 	btrfs_release_path(path);
1150 
1151 	/* look for a conflicing name */
1152 	di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
1153 				   name, namelen, 0);
1154 	if (di && !IS_ERR(di)) {
1155 		ret = drop_one_dir_item(trans, root, path, dir, di);
1156 		if (ret)
1157 			return ret;
1158 	}
1159 	btrfs_release_path(path);
1160 
1161 	return 0;
1162 }
1163 
extref_get_fields(struct extent_buffer * eb,unsigned long ref_ptr,u32 * namelen,char ** name,u64 * index,u64 * parent_objectid)1164 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1165 			     u32 *namelen, char **name, u64 *index,
1166 			     u64 *parent_objectid)
1167 {
1168 	struct btrfs_inode_extref *extref;
1169 
1170 	extref = (struct btrfs_inode_extref *)ref_ptr;
1171 
1172 	*namelen = btrfs_inode_extref_name_len(eb, extref);
1173 	*name = kmalloc(*namelen, GFP_NOFS);
1174 	if (*name == NULL)
1175 		return -ENOMEM;
1176 
1177 	read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1178 			   *namelen);
1179 
1180 	if (index)
1181 		*index = btrfs_inode_extref_index(eb, extref);
1182 	if (parent_objectid)
1183 		*parent_objectid = btrfs_inode_extref_parent(eb, extref);
1184 
1185 	return 0;
1186 }
1187 
ref_get_fields(struct extent_buffer * eb,unsigned long ref_ptr,u32 * namelen,char ** name,u64 * index)1188 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1189 			  u32 *namelen, char **name, u64 *index)
1190 {
1191 	struct btrfs_inode_ref *ref;
1192 
1193 	ref = (struct btrfs_inode_ref *)ref_ptr;
1194 
1195 	*namelen = btrfs_inode_ref_name_len(eb, ref);
1196 	*name = kmalloc(*namelen, GFP_NOFS);
1197 	if (*name == NULL)
1198 		return -ENOMEM;
1199 
1200 	read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1201 
1202 	if (index)
1203 		*index = btrfs_inode_ref_index(eb, ref);
1204 
1205 	return 0;
1206 }
1207 
1208 /*
1209  * Take an inode reference item from the log tree and iterate all names from the
1210  * inode reference item in the subvolume tree with the same key (if it exists).
1211  * For any name that is not in the inode reference item from the log tree, do a
1212  * proper unlink of that name (that is, remove its entry from the inode
1213  * reference item and both dir index keys).
1214  */
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)1215 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1216 				 struct btrfs_root *root,
1217 				 struct btrfs_path *path,
1218 				 struct btrfs_inode *inode,
1219 				 struct extent_buffer *log_eb,
1220 				 int log_slot,
1221 				 struct btrfs_key *key)
1222 {
1223 	int ret;
1224 	unsigned long ref_ptr;
1225 	unsigned long ref_end;
1226 	struct extent_buffer *eb;
1227 
1228 again:
1229 	btrfs_release_path(path);
1230 	ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1231 	if (ret > 0) {
1232 		ret = 0;
1233 		goto out;
1234 	}
1235 	if (ret < 0)
1236 		goto out;
1237 
1238 	eb = path->nodes[0];
1239 	ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1240 	ref_end = ref_ptr + btrfs_item_size_nr(eb, path->slots[0]);
1241 	while (ref_ptr < ref_end) {
1242 		char *name = NULL;
1243 		int namelen;
1244 		u64 parent_id;
1245 
1246 		if (key->type == BTRFS_INODE_EXTREF_KEY) {
1247 			ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1248 						NULL, &parent_id);
1249 		} else {
1250 			parent_id = key->offset;
1251 			ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1252 					     NULL);
1253 		}
1254 		if (ret)
1255 			goto out;
1256 
1257 		if (key->type == BTRFS_INODE_EXTREF_KEY)
1258 			ret = btrfs_find_name_in_ext_backref(log_eb, log_slot,
1259 							     parent_id, name,
1260 							     namelen, NULL);
1261 		else
1262 			ret = btrfs_find_name_in_backref(log_eb, log_slot, name,
1263 							 namelen, NULL);
1264 
1265 		if (!ret) {
1266 			struct inode *dir;
1267 
1268 			btrfs_release_path(path);
1269 			dir = read_one_inode(root, parent_id);
1270 			if (!dir) {
1271 				ret = -ENOENT;
1272 				kfree(name);
1273 				goto out;
1274 			}
1275 			ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
1276 						 inode, name, namelen);
1277 			kfree(name);
1278 			iput(dir);
1279 			if (ret)
1280 				goto out;
1281 			goto again;
1282 		}
1283 
1284 		kfree(name);
1285 		ref_ptr += namelen;
1286 		if (key->type == BTRFS_INODE_EXTREF_KEY)
1287 			ref_ptr += sizeof(struct btrfs_inode_extref);
1288 		else
1289 			ref_ptr += sizeof(struct btrfs_inode_ref);
1290 	}
1291 	ret = 0;
1292  out:
1293 	btrfs_release_path(path);
1294 	return ret;
1295 }
1296 
btrfs_inode_ref_exists(struct inode * inode,struct inode * dir,const u8 ref_type,const char * name,const int namelen)1297 static int btrfs_inode_ref_exists(struct inode *inode, struct inode *dir,
1298 				  const u8 ref_type, const char *name,
1299 				  const int namelen)
1300 {
1301 	struct btrfs_key key;
1302 	struct btrfs_path *path;
1303 	const u64 parent_id = btrfs_ino(BTRFS_I(dir));
1304 	int ret;
1305 
1306 	path = btrfs_alloc_path();
1307 	if (!path)
1308 		return -ENOMEM;
1309 
1310 	key.objectid = btrfs_ino(BTRFS_I(inode));
1311 	key.type = ref_type;
1312 	if (key.type == BTRFS_INODE_REF_KEY)
1313 		key.offset = parent_id;
1314 	else
1315 		key.offset = btrfs_extref_hash(parent_id, name, namelen);
1316 
1317 	ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
1318 	if (ret < 0)
1319 		goto out;
1320 	if (ret > 0) {
1321 		ret = 0;
1322 		goto out;
1323 	}
1324 	if (key.type == BTRFS_INODE_EXTREF_KEY)
1325 		ret = btrfs_find_name_in_ext_backref(path->nodes[0],
1326 						     path->slots[0], parent_id,
1327 						     name, namelen, NULL);
1328 	else
1329 		ret = btrfs_find_name_in_backref(path->nodes[0], path->slots[0],
1330 						 name, namelen, NULL);
1331 
1332 out:
1333 	btrfs_free_path(path);
1334 	return ret;
1335 }
1336 
1337 /*
1338  * replay one inode back reference item found in the log tree.
1339  * eb, slot and key refer to the buffer and key found in the log tree.
1340  * root is the destination we are replaying into, and path is for temp
1341  * use by this function.  (it should be released on return).
1342  */
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)1343 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1344 				  struct btrfs_root *root,
1345 				  struct btrfs_root *log,
1346 				  struct btrfs_path *path,
1347 				  struct extent_buffer *eb, int slot,
1348 				  struct btrfs_key *key)
1349 {
1350 	struct inode *dir = NULL;
1351 	struct inode *inode = NULL;
1352 	unsigned long ref_ptr;
1353 	unsigned long ref_end;
1354 	char *name = NULL;
1355 	int namelen;
1356 	int ret;
1357 	int search_done = 0;
1358 	int log_ref_ver = 0;
1359 	u64 parent_objectid;
1360 	u64 inode_objectid;
1361 	u64 ref_index = 0;
1362 	int ref_struct_size;
1363 
1364 	ref_ptr = btrfs_item_ptr_offset(eb, slot);
1365 	ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1366 
1367 	if (key->type == BTRFS_INODE_EXTREF_KEY) {
1368 		struct btrfs_inode_extref *r;
1369 
1370 		ref_struct_size = sizeof(struct btrfs_inode_extref);
1371 		log_ref_ver = 1;
1372 		r = (struct btrfs_inode_extref *)ref_ptr;
1373 		parent_objectid = btrfs_inode_extref_parent(eb, r);
1374 	} else {
1375 		ref_struct_size = sizeof(struct btrfs_inode_ref);
1376 		parent_objectid = key->offset;
1377 	}
1378 	inode_objectid = key->objectid;
1379 
1380 	/*
1381 	 * it is possible that we didn't log all the parent directories
1382 	 * for a given inode.  If we don't find the dir, just don't
1383 	 * copy the back ref in.  The link count fixup code will take
1384 	 * care of the rest
1385 	 */
1386 	dir = read_one_inode(root, parent_objectid);
1387 	if (!dir) {
1388 		ret = -ENOENT;
1389 		goto out;
1390 	}
1391 
1392 	inode = read_one_inode(root, inode_objectid);
1393 	if (!inode) {
1394 		ret = -EIO;
1395 		goto out;
1396 	}
1397 
1398 	while (ref_ptr < ref_end) {
1399 		if (log_ref_ver) {
1400 			ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1401 						&ref_index, &parent_objectid);
1402 			/*
1403 			 * parent object can change from one array
1404 			 * item to another.
1405 			 */
1406 			if (!dir)
1407 				dir = read_one_inode(root, parent_objectid);
1408 			if (!dir) {
1409 				ret = -ENOENT;
1410 				goto out;
1411 			}
1412 		} else {
1413 			ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1414 					     &ref_index);
1415 		}
1416 		if (ret)
1417 			goto out;
1418 
1419 		/* if we already have a perfect match, we're done */
1420 		if (!inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1421 					btrfs_ino(BTRFS_I(inode)), ref_index,
1422 					name, namelen)) {
1423 			/*
1424 			 * look for a conflicting back reference in the
1425 			 * metadata. if we find one we have to unlink that name
1426 			 * of the file before we add our new link.  Later on, we
1427 			 * overwrite any existing back reference, and we don't
1428 			 * want to create dangling pointers in the directory.
1429 			 */
1430 
1431 			if (!search_done) {
1432 				ret = __add_inode_ref(trans, root, path, log,
1433 						      BTRFS_I(dir),
1434 						      BTRFS_I(inode),
1435 						      inode_objectid,
1436 						      parent_objectid,
1437 						      ref_index, name, namelen,
1438 						      &search_done);
1439 				if (ret) {
1440 					if (ret == 1)
1441 						ret = 0;
1442 					goto out;
1443 				}
1444 			}
1445 
1446 			/*
1447 			 * If a reference item already exists for this inode
1448 			 * with the same parent and name, but different index,
1449 			 * drop it and the corresponding directory index entries
1450 			 * from the parent before adding the new reference item
1451 			 * and dir index entries, otherwise we would fail with
1452 			 * -EEXIST returned from btrfs_add_link() below.
1453 			 */
1454 			ret = btrfs_inode_ref_exists(inode, dir, key->type,
1455 						     name, namelen);
1456 			if (ret > 0) {
1457 				ret = btrfs_unlink_inode(trans, root,
1458 							 BTRFS_I(dir),
1459 							 BTRFS_I(inode),
1460 							 name, namelen);
1461 				/*
1462 				 * If we dropped the link count to 0, bump it so
1463 				 * that later the iput() on the inode will not
1464 				 * free it. We will fixup the link count later.
1465 				 */
1466 				if (!ret && inode->i_nlink == 0)
1467 					inc_nlink(inode);
1468 			}
1469 			if (ret < 0)
1470 				goto out;
1471 
1472 			/* insert our name */
1473 			ret = btrfs_add_link(trans, BTRFS_I(dir),
1474 					BTRFS_I(inode),
1475 					name, namelen, 0, ref_index);
1476 			if (ret)
1477 				goto out;
1478 
1479 			btrfs_update_inode(trans, root, inode);
1480 		}
1481 
1482 		ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1483 		kfree(name);
1484 		name = NULL;
1485 		if (log_ref_ver) {
1486 			iput(dir);
1487 			dir = NULL;
1488 		}
1489 	}
1490 
1491 	/*
1492 	 * Before we overwrite the inode reference item in the subvolume tree
1493 	 * with the item from the log tree, we must unlink all names from the
1494 	 * parent directory that are in the subvolume's tree inode reference
1495 	 * item, otherwise we end up with an inconsistent subvolume tree where
1496 	 * dir index entries exist for a name but there is no inode reference
1497 	 * item with the same name.
1498 	 */
1499 	ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1500 				    key);
1501 	if (ret)
1502 		goto out;
1503 
1504 	/* finally write the back reference in the inode */
1505 	ret = overwrite_item(trans, root, path, eb, slot, key);
1506 out:
1507 	btrfs_release_path(path);
1508 	kfree(name);
1509 	iput(dir);
1510 	iput(inode);
1511 	return ret;
1512 }
1513 
insert_orphan_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 ino)1514 static int insert_orphan_item(struct btrfs_trans_handle *trans,
1515 			      struct btrfs_root *root, u64 ino)
1516 {
1517 	int ret;
1518 
1519 	ret = btrfs_insert_orphan_item(trans, root, ino);
1520 	if (ret == -EEXIST)
1521 		ret = 0;
1522 
1523 	return ret;
1524 }
1525 
count_inode_extrefs(struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path)1526 static int count_inode_extrefs(struct btrfs_root *root,
1527 		struct btrfs_inode *inode, struct btrfs_path *path)
1528 {
1529 	int ret = 0;
1530 	int name_len;
1531 	unsigned int nlink = 0;
1532 	u32 item_size;
1533 	u32 cur_offset = 0;
1534 	u64 inode_objectid = btrfs_ino(inode);
1535 	u64 offset = 0;
1536 	unsigned long ptr;
1537 	struct btrfs_inode_extref *extref;
1538 	struct extent_buffer *leaf;
1539 
1540 	while (1) {
1541 		ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1542 					    &extref, &offset);
1543 		if (ret)
1544 			break;
1545 
1546 		leaf = path->nodes[0];
1547 		item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1548 		ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1549 		cur_offset = 0;
1550 
1551 		while (cur_offset < item_size) {
1552 			extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1553 			name_len = btrfs_inode_extref_name_len(leaf, extref);
1554 
1555 			nlink++;
1556 
1557 			cur_offset += name_len + sizeof(*extref);
1558 		}
1559 
1560 		offset++;
1561 		btrfs_release_path(path);
1562 	}
1563 	btrfs_release_path(path);
1564 
1565 	if (ret < 0 && ret != -ENOENT)
1566 		return ret;
1567 	return nlink;
1568 }
1569 
count_inode_refs(struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path)1570 static int count_inode_refs(struct btrfs_root *root,
1571 			struct btrfs_inode *inode, struct btrfs_path *path)
1572 {
1573 	int ret;
1574 	struct btrfs_key key;
1575 	unsigned int nlink = 0;
1576 	unsigned long ptr;
1577 	unsigned long ptr_end;
1578 	int name_len;
1579 	u64 ino = btrfs_ino(inode);
1580 
1581 	key.objectid = ino;
1582 	key.type = BTRFS_INODE_REF_KEY;
1583 	key.offset = (u64)-1;
1584 
1585 	while (1) {
1586 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1587 		if (ret < 0)
1588 			break;
1589 		if (ret > 0) {
1590 			if (path->slots[0] == 0)
1591 				break;
1592 			path->slots[0]--;
1593 		}
1594 process_slot:
1595 		btrfs_item_key_to_cpu(path->nodes[0], &key,
1596 				      path->slots[0]);
1597 		if (key.objectid != ino ||
1598 		    key.type != BTRFS_INODE_REF_KEY)
1599 			break;
1600 		ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1601 		ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1602 						   path->slots[0]);
1603 		while (ptr < ptr_end) {
1604 			struct btrfs_inode_ref *ref;
1605 
1606 			ref = (struct btrfs_inode_ref *)ptr;
1607 			name_len = btrfs_inode_ref_name_len(path->nodes[0],
1608 							    ref);
1609 			ptr = (unsigned long)(ref + 1) + name_len;
1610 			nlink++;
1611 		}
1612 
1613 		if (key.offset == 0)
1614 			break;
1615 		if (path->slots[0] > 0) {
1616 			path->slots[0]--;
1617 			goto process_slot;
1618 		}
1619 		key.offset--;
1620 		btrfs_release_path(path);
1621 	}
1622 	btrfs_release_path(path);
1623 
1624 	return nlink;
1625 }
1626 
1627 /*
1628  * There are a few corners where the link count of the file can't
1629  * be properly maintained during replay.  So, instead of adding
1630  * lots of complexity to the log code, we just scan the backrefs
1631  * for any file that has been through replay.
1632  *
1633  * The scan will update the link count on the inode to reflect the
1634  * number of back refs found.  If it goes down to zero, the iput
1635  * will free the inode.
1636  */
fixup_inode_link_count(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct inode * inode)1637 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1638 					   struct btrfs_root *root,
1639 					   struct inode *inode)
1640 {
1641 	struct btrfs_path *path;
1642 	int ret;
1643 	u64 nlink = 0;
1644 	u64 ino = btrfs_ino(BTRFS_I(inode));
1645 
1646 	path = btrfs_alloc_path();
1647 	if (!path)
1648 		return -ENOMEM;
1649 
1650 	ret = count_inode_refs(root, BTRFS_I(inode), path);
1651 	if (ret < 0)
1652 		goto out;
1653 
1654 	nlink = ret;
1655 
1656 	ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1657 	if (ret < 0)
1658 		goto out;
1659 
1660 	nlink += ret;
1661 
1662 	ret = 0;
1663 
1664 	if (nlink != inode->i_nlink) {
1665 		set_nlink(inode, nlink);
1666 		btrfs_update_inode(trans, root, inode);
1667 	}
1668 	BTRFS_I(inode)->index_cnt = (u64)-1;
1669 
1670 	if (inode->i_nlink == 0) {
1671 		if (S_ISDIR(inode->i_mode)) {
1672 			ret = replay_dir_deletes(trans, root, NULL, path,
1673 						 ino, 1);
1674 			if (ret)
1675 				goto out;
1676 		}
1677 		ret = insert_orphan_item(trans, root, ino);
1678 	}
1679 
1680 out:
1681 	btrfs_free_path(path);
1682 	return ret;
1683 }
1684 
fixup_inode_link_counts(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path)1685 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1686 					    struct btrfs_root *root,
1687 					    struct btrfs_path *path)
1688 {
1689 	int ret;
1690 	struct btrfs_key key;
1691 	struct inode *inode;
1692 
1693 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1694 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1695 	key.offset = (u64)-1;
1696 	while (1) {
1697 		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1698 		if (ret < 0)
1699 			break;
1700 
1701 		if (ret == 1) {
1702 			if (path->slots[0] == 0)
1703 				break;
1704 			path->slots[0]--;
1705 		}
1706 
1707 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1708 		if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1709 		    key.type != BTRFS_ORPHAN_ITEM_KEY)
1710 			break;
1711 
1712 		ret = btrfs_del_item(trans, root, path);
1713 		if (ret)
1714 			goto out;
1715 
1716 		btrfs_release_path(path);
1717 		inode = read_one_inode(root, key.offset);
1718 		if (!inode)
1719 			return -EIO;
1720 
1721 		ret = fixup_inode_link_count(trans, root, inode);
1722 		iput(inode);
1723 		if (ret)
1724 			goto out;
1725 
1726 		/*
1727 		 * fixup on a directory may create new entries,
1728 		 * make sure we always look for the highset possible
1729 		 * offset
1730 		 */
1731 		key.offset = (u64)-1;
1732 	}
1733 	ret = 0;
1734 out:
1735 	btrfs_release_path(path);
1736 	return ret;
1737 }
1738 
1739 
1740 /*
1741  * record a given inode in the fixup dir so we can check its link
1742  * count when replay is done.  The link count is incremented here
1743  * so the inode won't go away until we check it
1744  */
link_to_fixup_dir(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,u64 objectid)1745 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1746 				      struct btrfs_root *root,
1747 				      struct btrfs_path *path,
1748 				      u64 objectid)
1749 {
1750 	struct btrfs_key key;
1751 	int ret = 0;
1752 	struct inode *inode;
1753 
1754 	inode = read_one_inode(root, objectid);
1755 	if (!inode)
1756 		return -EIO;
1757 
1758 	key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1759 	key.type = BTRFS_ORPHAN_ITEM_KEY;
1760 	key.offset = objectid;
1761 
1762 	ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1763 
1764 	btrfs_release_path(path);
1765 	if (ret == 0) {
1766 		if (!inode->i_nlink)
1767 			set_nlink(inode, 1);
1768 		else
1769 			inc_nlink(inode);
1770 		ret = btrfs_update_inode(trans, root, inode);
1771 	} else if (ret == -EEXIST) {
1772 		ret = 0;
1773 	} else {
1774 		BUG(); /* Logic Error */
1775 	}
1776 	iput(inode);
1777 
1778 	return ret;
1779 }
1780 
1781 /*
1782  * when replaying the log for a directory, we only insert names
1783  * for inodes that actually exist.  This means an fsync on a directory
1784  * does not implicitly fsync all the new files in it
1785  */
insert_one_name(struct btrfs_trans_handle * trans,struct btrfs_root * root,u64 dirid,u64 index,char * name,int name_len,struct btrfs_key * location)1786 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1787 				    struct btrfs_root *root,
1788 				    u64 dirid, u64 index,
1789 				    char *name, int name_len,
1790 				    struct btrfs_key *location)
1791 {
1792 	struct inode *inode;
1793 	struct inode *dir;
1794 	int ret;
1795 
1796 	inode = read_one_inode(root, location->objectid);
1797 	if (!inode)
1798 		return -ENOENT;
1799 
1800 	dir = read_one_inode(root, dirid);
1801 	if (!dir) {
1802 		iput(inode);
1803 		return -EIO;
1804 	}
1805 
1806 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1807 			name_len, 1, index);
1808 
1809 	/* FIXME, put inode into FIXUP list */
1810 
1811 	iput(inode);
1812 	iput(dir);
1813 	return ret;
1814 }
1815 
1816 /*
1817  * Return true if an inode reference exists in the log for the given name,
1818  * inode and parent inode.
1819  */
name_in_log_ref(struct btrfs_root * log_root,const char * name,const int name_len,const u64 dirid,const u64 ino)1820 static bool name_in_log_ref(struct btrfs_root *log_root,
1821 			    const char *name, const int name_len,
1822 			    const u64 dirid, const u64 ino)
1823 {
1824 	struct btrfs_key search_key;
1825 
1826 	search_key.objectid = ino;
1827 	search_key.type = BTRFS_INODE_REF_KEY;
1828 	search_key.offset = dirid;
1829 	if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1830 		return true;
1831 
1832 	search_key.type = BTRFS_INODE_EXTREF_KEY;
1833 	search_key.offset = btrfs_extref_hash(dirid, name, name_len);
1834 	if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1835 		return true;
1836 
1837 	return false;
1838 }
1839 
1840 /*
1841  * take a single entry in a log directory item and replay it into
1842  * the subvolume.
1843  *
1844  * if a conflicting item exists in the subdirectory already,
1845  * the inode it points to is unlinked and put into the link count
1846  * fix up tree.
1847  *
1848  * If a name from the log points to a file or directory that does
1849  * not exist in the FS, it is skipped.  fsyncs on directories
1850  * do not force down inodes inside that directory, just changes to the
1851  * names or unlinks in a directory.
1852  *
1853  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1854  * non-existing inode) and 1 if the name was replayed.
1855  */
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)1856 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1857 				    struct btrfs_root *root,
1858 				    struct btrfs_path *path,
1859 				    struct extent_buffer *eb,
1860 				    struct btrfs_dir_item *di,
1861 				    struct btrfs_key *key)
1862 {
1863 	char *name;
1864 	int name_len;
1865 	struct btrfs_dir_item *dst_di;
1866 	struct btrfs_key found_key;
1867 	struct btrfs_key log_key;
1868 	struct inode *dir;
1869 	u8 log_type;
1870 	int exists;
1871 	int ret = 0;
1872 	bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
1873 	bool name_added = false;
1874 
1875 	dir = read_one_inode(root, key->objectid);
1876 	if (!dir)
1877 		return -EIO;
1878 
1879 	name_len = btrfs_dir_name_len(eb, di);
1880 	name = kmalloc(name_len, GFP_NOFS);
1881 	if (!name) {
1882 		ret = -ENOMEM;
1883 		goto out;
1884 	}
1885 
1886 	log_type = btrfs_dir_type(eb, di);
1887 	read_extent_buffer(eb, name, (unsigned long)(di + 1),
1888 		   name_len);
1889 
1890 	btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1891 	exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1892 	if (exists == 0)
1893 		exists = 1;
1894 	else
1895 		exists = 0;
1896 	btrfs_release_path(path);
1897 
1898 	if (key->type == BTRFS_DIR_ITEM_KEY) {
1899 		dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1900 				       name, name_len, 1);
1901 	} else if (key->type == BTRFS_DIR_INDEX_KEY) {
1902 		dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1903 						     key->objectid,
1904 						     key->offset, name,
1905 						     name_len, 1);
1906 	} else {
1907 		/* Corruption */
1908 		ret = -EINVAL;
1909 		goto out;
1910 	}
1911 	if (IS_ERR_OR_NULL(dst_di)) {
1912 		/* we need a sequence number to insert, so we only
1913 		 * do inserts for the BTRFS_DIR_INDEX_KEY types
1914 		 */
1915 		if (key->type != BTRFS_DIR_INDEX_KEY)
1916 			goto out;
1917 		goto insert;
1918 	}
1919 
1920 	btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1921 	/* the existing item matches the logged item */
1922 	if (found_key.objectid == log_key.objectid &&
1923 	    found_key.type == log_key.type &&
1924 	    found_key.offset == log_key.offset &&
1925 	    btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
1926 		update_size = false;
1927 		goto out;
1928 	}
1929 
1930 	/*
1931 	 * don't drop the conflicting directory entry if the inode
1932 	 * for the new entry doesn't exist
1933 	 */
1934 	if (!exists)
1935 		goto out;
1936 
1937 	ret = drop_one_dir_item(trans, root, path, BTRFS_I(dir), dst_di);
1938 	if (ret)
1939 		goto out;
1940 
1941 	if (key->type == BTRFS_DIR_INDEX_KEY)
1942 		goto insert;
1943 out:
1944 	btrfs_release_path(path);
1945 	if (!ret && update_size) {
1946 		btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
1947 		ret = btrfs_update_inode(trans, root, dir);
1948 	}
1949 	kfree(name);
1950 	iput(dir);
1951 	if (!ret && name_added)
1952 		ret = 1;
1953 	return ret;
1954 
1955 insert:
1956 	if (name_in_log_ref(root->log_root, name, name_len,
1957 			    key->objectid, log_key.objectid)) {
1958 		/* The dentry will be added later. */
1959 		ret = 0;
1960 		update_size = false;
1961 		goto out;
1962 	}
1963 	btrfs_release_path(path);
1964 	ret = insert_one_name(trans, root, key->objectid, key->offset,
1965 			      name, name_len, &log_key);
1966 	if (ret && ret != -ENOENT && ret != -EEXIST)
1967 		goto out;
1968 	if (!ret)
1969 		name_added = true;
1970 	update_size = false;
1971 	ret = 0;
1972 	goto out;
1973 }
1974 
1975 /*
1976  * find all the names in a directory item and reconcile them into
1977  * the subvolume.  Only BTRFS_DIR_ITEM_KEY types will have more than
1978  * one name in a directory item, but the same code gets used for
1979  * both directory index types
1980  */
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)1981 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1982 					struct btrfs_root *root,
1983 					struct btrfs_path *path,
1984 					struct extent_buffer *eb, int slot,
1985 					struct btrfs_key *key)
1986 {
1987 	int ret = 0;
1988 	u32 item_size = btrfs_item_size_nr(eb, slot);
1989 	struct btrfs_dir_item *di;
1990 	int name_len;
1991 	unsigned long ptr;
1992 	unsigned long ptr_end;
1993 	struct btrfs_path *fixup_path = NULL;
1994 
1995 	ptr = btrfs_item_ptr_offset(eb, slot);
1996 	ptr_end = ptr + item_size;
1997 	while (ptr < ptr_end) {
1998 		di = (struct btrfs_dir_item *)ptr;
1999 		name_len = btrfs_dir_name_len(eb, di);
2000 		ret = replay_one_name(trans, root, path, eb, di, key);
2001 		if (ret < 0)
2002 			break;
2003 		ptr = (unsigned long)(di + 1);
2004 		ptr += name_len;
2005 
2006 		/*
2007 		 * If this entry refers to a non-directory (directories can not
2008 		 * have a link count > 1) and it was added in the transaction
2009 		 * that was not committed, make sure we fixup the link count of
2010 		 * the inode it the entry points to. Otherwise something like
2011 		 * the following would result in a directory pointing to an
2012 		 * inode with a wrong link that does not account for this dir
2013 		 * entry:
2014 		 *
2015 		 * mkdir testdir
2016 		 * touch testdir/foo
2017 		 * touch testdir/bar
2018 		 * sync
2019 		 *
2020 		 * ln testdir/bar testdir/bar_link
2021 		 * ln testdir/foo testdir/foo_link
2022 		 * xfs_io -c "fsync" testdir/bar
2023 		 *
2024 		 * <power failure>
2025 		 *
2026 		 * mount fs, log replay happens
2027 		 *
2028 		 * File foo would remain with a link count of 1 when it has two
2029 		 * entries pointing to it in the directory testdir. This would
2030 		 * make it impossible to ever delete the parent directory has
2031 		 * it would result in stale dentries that can never be deleted.
2032 		 */
2033 		if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
2034 			struct btrfs_key di_key;
2035 
2036 			if (!fixup_path) {
2037 				fixup_path = btrfs_alloc_path();
2038 				if (!fixup_path) {
2039 					ret = -ENOMEM;
2040 					break;
2041 				}
2042 			}
2043 
2044 			btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2045 			ret = link_to_fixup_dir(trans, root, fixup_path,
2046 						di_key.objectid);
2047 			if (ret)
2048 				break;
2049 		}
2050 		ret = 0;
2051 	}
2052 	btrfs_free_path(fixup_path);
2053 	return ret;
2054 }
2055 
2056 /*
2057  * directory replay has two parts.  There are the standard directory
2058  * items in the log copied from the subvolume, and range items
2059  * created in the log while the subvolume was logged.
2060  *
2061  * The range items tell us which parts of the key space the log
2062  * is authoritative for.  During replay, if a key in the subvolume
2063  * directory is in a logged range item, but not actually in the log
2064  * that means it was deleted from the directory before the fsync
2065  * and should be removed.
2066  */
find_dir_range(struct btrfs_root * root,struct btrfs_path * path,u64 dirid,int key_type,u64 * start_ret,u64 * end_ret)2067 static noinline int find_dir_range(struct btrfs_root *root,
2068 				   struct btrfs_path *path,
2069 				   u64 dirid, int key_type,
2070 				   u64 *start_ret, u64 *end_ret)
2071 {
2072 	struct btrfs_key key;
2073 	u64 found_end;
2074 	struct btrfs_dir_log_item *item;
2075 	int ret;
2076 	int nritems;
2077 
2078 	if (*start_ret == (u64)-1)
2079 		return 1;
2080 
2081 	key.objectid = dirid;
2082 	key.type = key_type;
2083 	key.offset = *start_ret;
2084 
2085 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2086 	if (ret < 0)
2087 		goto out;
2088 	if (ret > 0) {
2089 		if (path->slots[0] == 0)
2090 			goto out;
2091 		path->slots[0]--;
2092 	}
2093 	if (ret != 0)
2094 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2095 
2096 	if (key.type != key_type || key.objectid != dirid) {
2097 		ret = 1;
2098 		goto next;
2099 	}
2100 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2101 			      struct btrfs_dir_log_item);
2102 	found_end = btrfs_dir_log_end(path->nodes[0], item);
2103 
2104 	if (*start_ret >= key.offset && *start_ret <= found_end) {
2105 		ret = 0;
2106 		*start_ret = key.offset;
2107 		*end_ret = found_end;
2108 		goto out;
2109 	}
2110 	ret = 1;
2111 next:
2112 	/* check the next slot in the tree to see if it is a valid item */
2113 	nritems = btrfs_header_nritems(path->nodes[0]);
2114 	path->slots[0]++;
2115 	if (path->slots[0] >= nritems) {
2116 		ret = btrfs_next_leaf(root, path);
2117 		if (ret)
2118 			goto out;
2119 	}
2120 
2121 	btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2122 
2123 	if (key.type != key_type || key.objectid != dirid) {
2124 		ret = 1;
2125 		goto out;
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 	*start_ret = key.offset;
2131 	*end_ret = found_end;
2132 	ret = 0;
2133 out:
2134 	btrfs_release_path(path);
2135 	return ret;
2136 }
2137 
2138 /*
2139  * this looks for a given directory item in the log.  If the directory
2140  * item is not in the log, the item is removed and the inode it points
2141  * to is unlinked
2142  */
check_item_in_log(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_root * log,struct btrfs_path * path,struct btrfs_path * log_path,struct inode * dir,struct btrfs_key * dir_key)2143 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2144 				      struct btrfs_root *root,
2145 				      struct btrfs_root *log,
2146 				      struct btrfs_path *path,
2147 				      struct btrfs_path *log_path,
2148 				      struct inode *dir,
2149 				      struct btrfs_key *dir_key)
2150 {
2151 	int ret;
2152 	struct extent_buffer *eb;
2153 	int slot;
2154 	u32 item_size;
2155 	struct btrfs_dir_item *di;
2156 	struct btrfs_dir_item *log_di;
2157 	int name_len;
2158 	unsigned long ptr;
2159 	unsigned long ptr_end;
2160 	char *name;
2161 	struct inode *inode;
2162 	struct btrfs_key location;
2163 
2164 again:
2165 	eb = path->nodes[0];
2166 	slot = path->slots[0];
2167 	item_size = btrfs_item_size_nr(eb, slot);
2168 	ptr = btrfs_item_ptr_offset(eb, slot);
2169 	ptr_end = ptr + item_size;
2170 	while (ptr < ptr_end) {
2171 		di = (struct btrfs_dir_item *)ptr;
2172 		name_len = btrfs_dir_name_len(eb, di);
2173 		name = kmalloc(name_len, GFP_NOFS);
2174 		if (!name) {
2175 			ret = -ENOMEM;
2176 			goto out;
2177 		}
2178 		read_extent_buffer(eb, name, (unsigned long)(di + 1),
2179 				  name_len);
2180 		log_di = NULL;
2181 		if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
2182 			log_di = btrfs_lookup_dir_item(trans, log, log_path,
2183 						       dir_key->objectid,
2184 						       name, name_len, 0);
2185 		} else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
2186 			log_di = btrfs_lookup_dir_index_item(trans, log,
2187 						     log_path,
2188 						     dir_key->objectid,
2189 						     dir_key->offset,
2190 						     name, name_len, 0);
2191 		}
2192 		if (!log_di || log_di == ERR_PTR(-ENOENT)) {
2193 			btrfs_dir_item_key_to_cpu(eb, di, &location);
2194 			btrfs_release_path(path);
2195 			btrfs_release_path(log_path);
2196 			inode = read_one_inode(root, location.objectid);
2197 			if (!inode) {
2198 				kfree(name);
2199 				return -EIO;
2200 			}
2201 
2202 			ret = link_to_fixup_dir(trans, root,
2203 						path, location.objectid);
2204 			if (ret) {
2205 				kfree(name);
2206 				iput(inode);
2207 				goto out;
2208 			}
2209 
2210 			inc_nlink(inode);
2211 			ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
2212 					BTRFS_I(inode), name, name_len);
2213 			if (!ret)
2214 				ret = btrfs_run_delayed_items(trans);
2215 			kfree(name);
2216 			iput(inode);
2217 			if (ret)
2218 				goto out;
2219 
2220 			/* there might still be more names under this key
2221 			 * check and repeat if required
2222 			 */
2223 			ret = btrfs_search_slot(NULL, root, dir_key, path,
2224 						0, 0);
2225 			if (ret == 0)
2226 				goto again;
2227 			ret = 0;
2228 			goto out;
2229 		} else if (IS_ERR(log_di)) {
2230 			kfree(name);
2231 			return PTR_ERR(log_di);
2232 		}
2233 		btrfs_release_path(log_path);
2234 		kfree(name);
2235 
2236 		ptr = (unsigned long)(di + 1);
2237 		ptr += name_len;
2238 	}
2239 	ret = 0;
2240 out:
2241 	btrfs_release_path(path);
2242 	btrfs_release_path(log_path);
2243 	return ret;
2244 }
2245 
replay_xattr_deletes(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_root * log,struct btrfs_path * path,const u64 ino)2246 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2247 			      struct btrfs_root *root,
2248 			      struct btrfs_root *log,
2249 			      struct btrfs_path *path,
2250 			      const u64 ino)
2251 {
2252 	struct btrfs_key search_key;
2253 	struct btrfs_path *log_path;
2254 	int i;
2255 	int nritems;
2256 	int ret;
2257 
2258 	log_path = btrfs_alloc_path();
2259 	if (!log_path)
2260 		return -ENOMEM;
2261 
2262 	search_key.objectid = ino;
2263 	search_key.type = BTRFS_XATTR_ITEM_KEY;
2264 	search_key.offset = 0;
2265 again:
2266 	ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2267 	if (ret < 0)
2268 		goto out;
2269 process_leaf:
2270 	nritems = btrfs_header_nritems(path->nodes[0]);
2271 	for (i = path->slots[0]; i < nritems; i++) {
2272 		struct btrfs_key key;
2273 		struct btrfs_dir_item *di;
2274 		struct btrfs_dir_item *log_di;
2275 		u32 total_size;
2276 		u32 cur;
2277 
2278 		btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2279 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2280 			ret = 0;
2281 			goto out;
2282 		}
2283 
2284 		di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2285 		total_size = btrfs_item_size_nr(path->nodes[0], i);
2286 		cur = 0;
2287 		while (cur < total_size) {
2288 			u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2289 			u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2290 			u32 this_len = sizeof(*di) + name_len + data_len;
2291 			char *name;
2292 
2293 			name = kmalloc(name_len, GFP_NOFS);
2294 			if (!name) {
2295 				ret = -ENOMEM;
2296 				goto out;
2297 			}
2298 			read_extent_buffer(path->nodes[0], name,
2299 					   (unsigned long)(di + 1), name_len);
2300 
2301 			log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2302 						    name, name_len, 0);
2303 			btrfs_release_path(log_path);
2304 			if (!log_di) {
2305 				/* Doesn't exist in log tree, so delete it. */
2306 				btrfs_release_path(path);
2307 				di = btrfs_lookup_xattr(trans, root, path, ino,
2308 							name, name_len, -1);
2309 				kfree(name);
2310 				if (IS_ERR(di)) {
2311 					ret = PTR_ERR(di);
2312 					goto out;
2313 				}
2314 				ASSERT(di);
2315 				ret = btrfs_delete_one_dir_name(trans, root,
2316 								path, di);
2317 				if (ret)
2318 					goto out;
2319 				btrfs_release_path(path);
2320 				search_key = key;
2321 				goto again;
2322 			}
2323 			kfree(name);
2324 			if (IS_ERR(log_di)) {
2325 				ret = PTR_ERR(log_di);
2326 				goto out;
2327 			}
2328 			cur += this_len;
2329 			di = (struct btrfs_dir_item *)((char *)di + this_len);
2330 		}
2331 	}
2332 	ret = btrfs_next_leaf(root, path);
2333 	if (ret > 0)
2334 		ret = 0;
2335 	else if (ret == 0)
2336 		goto process_leaf;
2337 out:
2338 	btrfs_free_path(log_path);
2339 	btrfs_release_path(path);
2340 	return ret;
2341 }
2342 
2343 
2344 /*
2345  * deletion replay happens before we copy any new directory items
2346  * out of the log or out of backreferences from inodes.  It
2347  * scans the log to find ranges of keys that log is authoritative for,
2348  * and then scans the directory to find items in those ranges that are
2349  * not present in the log.
2350  *
2351  * Anything we don't find in the log is unlinked and removed from the
2352  * directory.
2353  */
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)2354 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2355 				       struct btrfs_root *root,
2356 				       struct btrfs_root *log,
2357 				       struct btrfs_path *path,
2358 				       u64 dirid, int del_all)
2359 {
2360 	u64 range_start;
2361 	u64 range_end;
2362 	int key_type = BTRFS_DIR_LOG_ITEM_KEY;
2363 	int ret = 0;
2364 	struct btrfs_key dir_key;
2365 	struct btrfs_key found_key;
2366 	struct btrfs_path *log_path;
2367 	struct inode *dir;
2368 
2369 	dir_key.objectid = dirid;
2370 	dir_key.type = BTRFS_DIR_ITEM_KEY;
2371 	log_path = btrfs_alloc_path();
2372 	if (!log_path)
2373 		return -ENOMEM;
2374 
2375 	dir = read_one_inode(root, dirid);
2376 	/* it isn't an error if the inode isn't there, that can happen
2377 	 * because we replay the deletes before we copy in the inode item
2378 	 * from the log
2379 	 */
2380 	if (!dir) {
2381 		btrfs_free_path(log_path);
2382 		return 0;
2383 	}
2384 again:
2385 	range_start = 0;
2386 	range_end = 0;
2387 	while (1) {
2388 		if (del_all)
2389 			range_end = (u64)-1;
2390 		else {
2391 			ret = find_dir_range(log, path, dirid, key_type,
2392 					     &range_start, &range_end);
2393 			if (ret != 0)
2394 				break;
2395 		}
2396 
2397 		dir_key.offset = range_start;
2398 		while (1) {
2399 			int nritems;
2400 			ret = btrfs_search_slot(NULL, root, &dir_key, path,
2401 						0, 0);
2402 			if (ret < 0)
2403 				goto out;
2404 
2405 			nritems = btrfs_header_nritems(path->nodes[0]);
2406 			if (path->slots[0] >= nritems) {
2407 				ret = btrfs_next_leaf(root, path);
2408 				if (ret == 1)
2409 					break;
2410 				else if (ret < 0)
2411 					goto out;
2412 			}
2413 			btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2414 					      path->slots[0]);
2415 			if (found_key.objectid != dirid ||
2416 			    found_key.type != dir_key.type)
2417 				goto next_type;
2418 
2419 			if (found_key.offset > range_end)
2420 				break;
2421 
2422 			ret = check_item_in_log(trans, root, log, path,
2423 						log_path, dir,
2424 						&found_key);
2425 			if (ret)
2426 				goto out;
2427 			if (found_key.offset == (u64)-1)
2428 				break;
2429 			dir_key.offset = found_key.offset + 1;
2430 		}
2431 		btrfs_release_path(path);
2432 		if (range_end == (u64)-1)
2433 			break;
2434 		range_start = range_end + 1;
2435 	}
2436 
2437 next_type:
2438 	ret = 0;
2439 	if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
2440 		key_type = BTRFS_DIR_LOG_INDEX_KEY;
2441 		dir_key.type = BTRFS_DIR_INDEX_KEY;
2442 		btrfs_release_path(path);
2443 		goto again;
2444 	}
2445 out:
2446 	btrfs_release_path(path);
2447 	btrfs_free_path(log_path);
2448 	iput(dir);
2449 	return ret;
2450 }
2451 
2452 /*
2453  * the process_func used to replay items from the log tree.  This
2454  * gets called in two different stages.  The first stage just looks
2455  * for inodes and makes sure they are all copied into the subvolume.
2456  *
2457  * The second stage copies all the other item types from the log into
2458  * the subvolume.  The two stage approach is slower, but gets rid of
2459  * lots of complexity around inodes referencing other inodes that exist
2460  * only in the log (references come from either directory items or inode
2461  * back refs).
2462  */
replay_one_buffer(struct btrfs_root * log,struct extent_buffer * eb,struct walk_control * wc,u64 gen,int level)2463 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2464 			     struct walk_control *wc, u64 gen, int level)
2465 {
2466 	int nritems;
2467 	struct btrfs_path *path;
2468 	struct btrfs_root *root = wc->replay_dest;
2469 	struct btrfs_key key;
2470 	int i;
2471 	int ret;
2472 
2473 	ret = btrfs_read_buffer(eb, gen, level, NULL);
2474 	if (ret)
2475 		return ret;
2476 
2477 	level = btrfs_header_level(eb);
2478 
2479 	if (level != 0)
2480 		return 0;
2481 
2482 	path = btrfs_alloc_path();
2483 	if (!path)
2484 		return -ENOMEM;
2485 
2486 	nritems = btrfs_header_nritems(eb);
2487 	for (i = 0; i < nritems; i++) {
2488 		btrfs_item_key_to_cpu(eb, &key, i);
2489 
2490 		/* inode keys are done during the first stage */
2491 		if (key.type == BTRFS_INODE_ITEM_KEY &&
2492 		    wc->stage == LOG_WALK_REPLAY_INODES) {
2493 			struct btrfs_inode_item *inode_item;
2494 			u32 mode;
2495 
2496 			inode_item = btrfs_item_ptr(eb, i,
2497 					    struct btrfs_inode_item);
2498 			/*
2499 			 * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2500 			 * and never got linked before the fsync, skip it, as
2501 			 * replaying it is pointless since it would be deleted
2502 			 * later. We skip logging tmpfiles, but it's always
2503 			 * possible we are replaying a log created with a kernel
2504 			 * that used to log tmpfiles.
2505 			 */
2506 			if (btrfs_inode_nlink(eb, inode_item) == 0) {
2507 				wc->ignore_cur_inode = true;
2508 				continue;
2509 			} else {
2510 				wc->ignore_cur_inode = false;
2511 			}
2512 			ret = replay_xattr_deletes(wc->trans, root, log,
2513 						   path, key.objectid);
2514 			if (ret)
2515 				break;
2516 			mode = btrfs_inode_mode(eb, inode_item);
2517 			if (S_ISDIR(mode)) {
2518 				ret = replay_dir_deletes(wc->trans,
2519 					 root, log, path, key.objectid, 0);
2520 				if (ret)
2521 					break;
2522 			}
2523 			ret = overwrite_item(wc->trans, root, path,
2524 					     eb, i, &key);
2525 			if (ret)
2526 				break;
2527 
2528 			/*
2529 			 * Before replaying extents, truncate the inode to its
2530 			 * size. We need to do it now and not after log replay
2531 			 * because before an fsync we can have prealloc extents
2532 			 * added beyond the inode's i_size. If we did it after,
2533 			 * through orphan cleanup for example, we would drop
2534 			 * those prealloc extents just after replaying them.
2535 			 */
2536 			if (S_ISREG(mode)) {
2537 				struct inode *inode;
2538 				u64 from;
2539 
2540 				inode = read_one_inode(root, key.objectid);
2541 				if (!inode) {
2542 					ret = -EIO;
2543 					break;
2544 				}
2545 				from = ALIGN(i_size_read(inode),
2546 					     root->fs_info->sectorsize);
2547 				ret = btrfs_drop_extents(wc->trans, root, inode,
2548 							 from, (u64)-1, 1);
2549 				if (!ret) {
2550 					/* Update the inode's nbytes. */
2551 					ret = btrfs_update_inode(wc->trans,
2552 								 root, inode);
2553 				}
2554 				iput(inode);
2555 				if (ret)
2556 					break;
2557 			}
2558 
2559 			ret = link_to_fixup_dir(wc->trans, root,
2560 						path, key.objectid);
2561 			if (ret)
2562 				break;
2563 		}
2564 
2565 		if (wc->ignore_cur_inode)
2566 			continue;
2567 
2568 		if (key.type == BTRFS_DIR_INDEX_KEY &&
2569 		    wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2570 			ret = replay_one_dir_item(wc->trans, root, path,
2571 						  eb, i, &key);
2572 			if (ret)
2573 				break;
2574 		}
2575 
2576 		if (wc->stage < LOG_WALK_REPLAY_ALL)
2577 			continue;
2578 
2579 		/* these keys are simply copied */
2580 		if (key.type == BTRFS_XATTR_ITEM_KEY) {
2581 			ret = overwrite_item(wc->trans, root, path,
2582 					     eb, i, &key);
2583 			if (ret)
2584 				break;
2585 		} else if (key.type == BTRFS_INODE_REF_KEY ||
2586 			   key.type == BTRFS_INODE_EXTREF_KEY) {
2587 			ret = add_inode_ref(wc->trans, root, log, path,
2588 					    eb, i, &key);
2589 			if (ret && ret != -ENOENT)
2590 				break;
2591 			ret = 0;
2592 		} else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2593 			ret = replay_one_extent(wc->trans, root, path,
2594 						eb, i, &key);
2595 			if (ret)
2596 				break;
2597 		} else if (key.type == BTRFS_DIR_ITEM_KEY) {
2598 			ret = replay_one_dir_item(wc->trans, root, path,
2599 						  eb, i, &key);
2600 			if (ret)
2601 				break;
2602 		}
2603 	}
2604 	btrfs_free_path(path);
2605 	return ret;
2606 }
2607 
walk_down_log_tree(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int * level,struct walk_control * wc)2608 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2609 				   struct btrfs_root *root,
2610 				   struct btrfs_path *path, int *level,
2611 				   struct walk_control *wc)
2612 {
2613 	struct btrfs_fs_info *fs_info = root->fs_info;
2614 	u64 root_owner;
2615 	u64 bytenr;
2616 	u64 ptr_gen;
2617 	struct extent_buffer *next;
2618 	struct extent_buffer *cur;
2619 	struct extent_buffer *parent;
2620 	u32 blocksize;
2621 	int ret = 0;
2622 
2623 	WARN_ON(*level < 0);
2624 	WARN_ON(*level >= BTRFS_MAX_LEVEL);
2625 
2626 	while (*level > 0) {
2627 		struct btrfs_key first_key;
2628 
2629 		WARN_ON(*level < 0);
2630 		WARN_ON(*level >= BTRFS_MAX_LEVEL);
2631 		cur = path->nodes[*level];
2632 
2633 		WARN_ON(btrfs_header_level(cur) != *level);
2634 
2635 		if (path->slots[*level] >=
2636 		    btrfs_header_nritems(cur))
2637 			break;
2638 
2639 		bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2640 		ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2641 		btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2642 		blocksize = fs_info->nodesize;
2643 
2644 		parent = path->nodes[*level];
2645 		root_owner = btrfs_header_owner(parent);
2646 
2647 		next = btrfs_find_create_tree_block(fs_info, bytenr);
2648 		if (IS_ERR(next))
2649 			return PTR_ERR(next);
2650 
2651 		if (*level == 1) {
2652 			ret = wc->process_func(root, next, wc, ptr_gen,
2653 					       *level - 1);
2654 			if (ret) {
2655 				free_extent_buffer(next);
2656 				return ret;
2657 			}
2658 
2659 			path->slots[*level]++;
2660 			if (wc->free) {
2661 				ret = btrfs_read_buffer(next, ptr_gen,
2662 							*level - 1, &first_key);
2663 				if (ret) {
2664 					free_extent_buffer(next);
2665 					return ret;
2666 				}
2667 
2668 				if (trans) {
2669 					btrfs_tree_lock(next);
2670 					btrfs_set_lock_blocking(next);
2671 					clean_tree_block(fs_info, next);
2672 					btrfs_wait_tree_block_writeback(next);
2673 					btrfs_tree_unlock(next);
2674 				} else {
2675 					if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2676 						clear_extent_buffer_dirty(next);
2677 				}
2678 
2679 				WARN_ON(root_owner !=
2680 					BTRFS_TREE_LOG_OBJECTID);
2681 				ret = btrfs_free_and_pin_reserved_extent(
2682 							fs_info, bytenr,
2683 							blocksize);
2684 				if (ret) {
2685 					free_extent_buffer(next);
2686 					return ret;
2687 				}
2688 			}
2689 			free_extent_buffer(next);
2690 			continue;
2691 		}
2692 		ret = btrfs_read_buffer(next, ptr_gen, *level - 1, &first_key);
2693 		if (ret) {
2694 			free_extent_buffer(next);
2695 			return ret;
2696 		}
2697 
2698 		WARN_ON(*level <= 0);
2699 		if (path->nodes[*level-1])
2700 			free_extent_buffer(path->nodes[*level-1]);
2701 		path->nodes[*level-1] = next;
2702 		*level = btrfs_header_level(next);
2703 		path->slots[*level] = 0;
2704 		cond_resched();
2705 	}
2706 	WARN_ON(*level < 0);
2707 	WARN_ON(*level >= BTRFS_MAX_LEVEL);
2708 
2709 	path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2710 
2711 	cond_resched();
2712 	return 0;
2713 }
2714 
walk_up_log_tree(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_path * path,int * level,struct walk_control * wc)2715 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2716 				 struct btrfs_root *root,
2717 				 struct btrfs_path *path, int *level,
2718 				 struct walk_control *wc)
2719 {
2720 	struct btrfs_fs_info *fs_info = root->fs_info;
2721 	u64 root_owner;
2722 	int i;
2723 	int slot;
2724 	int ret;
2725 
2726 	for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2727 		slot = path->slots[i];
2728 		if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2729 			path->slots[i]++;
2730 			*level = i;
2731 			WARN_ON(*level == 0);
2732 			return 0;
2733 		} else {
2734 			struct extent_buffer *parent;
2735 			if (path->nodes[*level] == root->node)
2736 				parent = path->nodes[*level];
2737 			else
2738 				parent = path->nodes[*level + 1];
2739 
2740 			root_owner = btrfs_header_owner(parent);
2741 			ret = wc->process_func(root, path->nodes[*level], wc,
2742 				 btrfs_header_generation(path->nodes[*level]),
2743 				 *level);
2744 			if (ret)
2745 				return ret;
2746 
2747 			if (wc->free) {
2748 				struct extent_buffer *next;
2749 
2750 				next = path->nodes[*level];
2751 
2752 				if (trans) {
2753 					btrfs_tree_lock(next);
2754 					btrfs_set_lock_blocking(next);
2755 					clean_tree_block(fs_info, next);
2756 					btrfs_wait_tree_block_writeback(next);
2757 					btrfs_tree_unlock(next);
2758 				} else {
2759 					if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2760 						clear_extent_buffer_dirty(next);
2761 				}
2762 
2763 				WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2764 				ret = btrfs_free_and_pin_reserved_extent(
2765 						fs_info,
2766 						path->nodes[*level]->start,
2767 						path->nodes[*level]->len);
2768 				if (ret)
2769 					return ret;
2770 			}
2771 			free_extent_buffer(path->nodes[*level]);
2772 			path->nodes[*level] = NULL;
2773 			*level = i + 1;
2774 		}
2775 	}
2776 	return 1;
2777 }
2778 
2779 /*
2780  * drop the reference count on the tree rooted at 'snap'.  This traverses
2781  * the tree freeing any blocks that have a ref count of zero after being
2782  * decremented.
2783  */
walk_log_tree(struct btrfs_trans_handle * trans,struct btrfs_root * log,struct walk_control * wc)2784 static int walk_log_tree(struct btrfs_trans_handle *trans,
2785 			 struct btrfs_root *log, struct walk_control *wc)
2786 {
2787 	struct btrfs_fs_info *fs_info = log->fs_info;
2788 	int ret = 0;
2789 	int wret;
2790 	int level;
2791 	struct btrfs_path *path;
2792 	int orig_level;
2793 
2794 	path = btrfs_alloc_path();
2795 	if (!path)
2796 		return -ENOMEM;
2797 
2798 	level = btrfs_header_level(log->node);
2799 	orig_level = level;
2800 	path->nodes[level] = log->node;
2801 	extent_buffer_get(log->node);
2802 	path->slots[level] = 0;
2803 
2804 	while (1) {
2805 		wret = walk_down_log_tree(trans, log, path, &level, wc);
2806 		if (wret > 0)
2807 			break;
2808 		if (wret < 0) {
2809 			ret = wret;
2810 			goto out;
2811 		}
2812 
2813 		wret = walk_up_log_tree(trans, log, path, &level, wc);
2814 		if (wret > 0)
2815 			break;
2816 		if (wret < 0) {
2817 			ret = wret;
2818 			goto out;
2819 		}
2820 	}
2821 
2822 	/* was the root node processed? if not, catch it here */
2823 	if (path->nodes[orig_level]) {
2824 		ret = wc->process_func(log, path->nodes[orig_level], wc,
2825 			 btrfs_header_generation(path->nodes[orig_level]),
2826 			 orig_level);
2827 		if (ret)
2828 			goto out;
2829 		if (wc->free) {
2830 			struct extent_buffer *next;
2831 
2832 			next = path->nodes[orig_level];
2833 
2834 			if (trans) {
2835 				btrfs_tree_lock(next);
2836 				btrfs_set_lock_blocking(next);
2837 				clean_tree_block(fs_info, next);
2838 				btrfs_wait_tree_block_writeback(next);
2839 				btrfs_tree_unlock(next);
2840 			} else {
2841 				if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2842 					clear_extent_buffer_dirty(next);
2843 			}
2844 
2845 			WARN_ON(log->root_key.objectid !=
2846 				BTRFS_TREE_LOG_OBJECTID);
2847 			ret = btrfs_free_and_pin_reserved_extent(fs_info,
2848 							next->start, next->len);
2849 			if (ret)
2850 				goto out;
2851 		}
2852 	}
2853 
2854 out:
2855 	btrfs_free_path(path);
2856 	return ret;
2857 }
2858 
2859 /*
2860  * helper function to update the item for a given subvolumes log root
2861  * in the tree of log roots
2862  */
update_log_root(struct btrfs_trans_handle * trans,struct btrfs_root * log,struct btrfs_root_item * root_item)2863 static int update_log_root(struct btrfs_trans_handle *trans,
2864 			   struct btrfs_root *log,
2865 			   struct btrfs_root_item *root_item)
2866 {
2867 	struct btrfs_fs_info *fs_info = log->fs_info;
2868 	int ret;
2869 
2870 	if (log->log_transid == 1) {
2871 		/* insert root item on the first sync */
2872 		ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2873 				&log->root_key, root_item);
2874 	} else {
2875 		ret = btrfs_update_root(trans, fs_info->log_root_tree,
2876 				&log->root_key, root_item);
2877 	}
2878 	return ret;
2879 }
2880 
wait_log_commit(struct btrfs_root * root,int transid)2881 static void wait_log_commit(struct btrfs_root *root, int transid)
2882 {
2883 	DEFINE_WAIT(wait);
2884 	int index = transid % 2;
2885 
2886 	/*
2887 	 * we only allow two pending log transactions at a time,
2888 	 * so we know that if ours is more than 2 older than the
2889 	 * current transaction, we're done
2890 	 */
2891 	for (;;) {
2892 		prepare_to_wait(&root->log_commit_wait[index],
2893 				&wait, TASK_UNINTERRUPTIBLE);
2894 
2895 		if (!(root->log_transid_committed < transid &&
2896 		      atomic_read(&root->log_commit[index])))
2897 			break;
2898 
2899 		mutex_unlock(&root->log_mutex);
2900 		schedule();
2901 		mutex_lock(&root->log_mutex);
2902 	}
2903 	finish_wait(&root->log_commit_wait[index], &wait);
2904 }
2905 
wait_for_writer(struct btrfs_root * root)2906 static void wait_for_writer(struct btrfs_root *root)
2907 {
2908 	DEFINE_WAIT(wait);
2909 
2910 	for (;;) {
2911 		prepare_to_wait(&root->log_writer_wait, &wait,
2912 				TASK_UNINTERRUPTIBLE);
2913 		if (!atomic_read(&root->log_writers))
2914 			break;
2915 
2916 		mutex_unlock(&root->log_mutex);
2917 		schedule();
2918 		mutex_lock(&root->log_mutex);
2919 	}
2920 	finish_wait(&root->log_writer_wait, &wait);
2921 }
2922 
btrfs_remove_log_ctx(struct btrfs_root * root,struct btrfs_log_ctx * ctx)2923 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2924 					struct btrfs_log_ctx *ctx)
2925 {
2926 	if (!ctx)
2927 		return;
2928 
2929 	mutex_lock(&root->log_mutex);
2930 	list_del_init(&ctx->list);
2931 	mutex_unlock(&root->log_mutex);
2932 }
2933 
2934 /*
2935  * Invoked in log mutex context, or be sure there is no other task which
2936  * can access the list.
2937  */
btrfs_remove_all_log_ctxs(struct btrfs_root * root,int index,int error)2938 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2939 					     int index, int error)
2940 {
2941 	struct btrfs_log_ctx *ctx;
2942 	struct btrfs_log_ctx *safe;
2943 
2944 	list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2945 		list_del_init(&ctx->list);
2946 		ctx->log_ret = error;
2947 	}
2948 
2949 	INIT_LIST_HEAD(&root->log_ctxs[index]);
2950 }
2951 
2952 /*
2953  * btrfs_sync_log does sends a given tree log down to the disk and
2954  * updates the super blocks to record it.  When this call is done,
2955  * you know that any inodes previously logged are safely on disk only
2956  * if it returns 0.
2957  *
2958  * Any other return value means you need to call btrfs_commit_transaction.
2959  * Some of the edge cases for fsyncing directories that have had unlinks
2960  * or renames done in the past mean that sometimes the only safe
2961  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
2962  * that has happened.
2963  */
btrfs_sync_log(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_log_ctx * ctx)2964 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2965 		   struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2966 {
2967 	int index1;
2968 	int index2;
2969 	int mark;
2970 	int ret;
2971 	struct btrfs_fs_info *fs_info = root->fs_info;
2972 	struct btrfs_root *log = root->log_root;
2973 	struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2974 	struct btrfs_root_item new_root_item;
2975 	int log_transid = 0;
2976 	struct btrfs_log_ctx root_log_ctx;
2977 	struct blk_plug plug;
2978 
2979 	mutex_lock(&root->log_mutex);
2980 	log_transid = ctx->log_transid;
2981 	if (root->log_transid_committed >= log_transid) {
2982 		mutex_unlock(&root->log_mutex);
2983 		return ctx->log_ret;
2984 	}
2985 
2986 	index1 = log_transid % 2;
2987 	if (atomic_read(&root->log_commit[index1])) {
2988 		wait_log_commit(root, log_transid);
2989 		mutex_unlock(&root->log_mutex);
2990 		return ctx->log_ret;
2991 	}
2992 	ASSERT(log_transid == root->log_transid);
2993 	atomic_set(&root->log_commit[index1], 1);
2994 
2995 	/* wait for previous tree log sync to complete */
2996 	if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2997 		wait_log_commit(root, log_transid - 1);
2998 
2999 	while (1) {
3000 		int batch = atomic_read(&root->log_batch);
3001 		/* when we're on an ssd, just kick the log commit out */
3002 		if (!btrfs_test_opt(fs_info, SSD) &&
3003 		    test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
3004 			mutex_unlock(&root->log_mutex);
3005 			schedule_timeout_uninterruptible(1);
3006 			mutex_lock(&root->log_mutex);
3007 		}
3008 		wait_for_writer(root);
3009 		if (batch == atomic_read(&root->log_batch))
3010 			break;
3011 	}
3012 
3013 	/* bail out if we need to do a full commit */
3014 	if (btrfs_need_log_full_commit(fs_info, trans)) {
3015 		ret = -EAGAIN;
3016 		mutex_unlock(&root->log_mutex);
3017 		goto out;
3018 	}
3019 
3020 	if (log_transid % 2 == 0)
3021 		mark = EXTENT_DIRTY;
3022 	else
3023 		mark = EXTENT_NEW;
3024 
3025 	/* we start IO on  all the marked extents here, but we don't actually
3026 	 * wait for them until later.
3027 	 */
3028 	blk_start_plug(&plug);
3029 	ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
3030 	if (ret) {
3031 		blk_finish_plug(&plug);
3032 		btrfs_abort_transaction(trans, ret);
3033 		btrfs_set_log_full_commit(fs_info, trans);
3034 		mutex_unlock(&root->log_mutex);
3035 		goto out;
3036 	}
3037 
3038 	/*
3039 	 * We _must_ update under the root->log_mutex in order to make sure we
3040 	 * have a consistent view of the log root we are trying to commit at
3041 	 * this moment.
3042 	 *
3043 	 * We _must_ copy this into a local copy, because we are not holding the
3044 	 * log_root_tree->log_mutex yet.  This is important because when we
3045 	 * commit the log_root_tree we must have a consistent view of the
3046 	 * log_root_tree when we update the super block to point at the
3047 	 * log_root_tree bytenr.  If we update the log_root_tree here we'll race
3048 	 * with the commit and possibly point at the new block which we may not
3049 	 * have written out.
3050 	 */
3051 	btrfs_set_root_node(&log->root_item, log->node);
3052 	memcpy(&new_root_item, &log->root_item, sizeof(new_root_item));
3053 
3054 	root->log_transid++;
3055 	log->log_transid = root->log_transid;
3056 	root->log_start_pid = 0;
3057 	/*
3058 	 * IO has been started, blocks of the log tree have WRITTEN flag set
3059 	 * in their headers. new modifications of the log will be written to
3060 	 * new positions. so it's safe to allow log writers to go in.
3061 	 */
3062 	mutex_unlock(&root->log_mutex);
3063 
3064 	btrfs_init_log_ctx(&root_log_ctx, NULL);
3065 
3066 	mutex_lock(&log_root_tree->log_mutex);
3067 	atomic_inc(&log_root_tree->log_batch);
3068 	atomic_inc(&log_root_tree->log_writers);
3069 
3070 	index2 = log_root_tree->log_transid % 2;
3071 	list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
3072 	root_log_ctx.log_transid = log_root_tree->log_transid;
3073 
3074 	mutex_unlock(&log_root_tree->log_mutex);
3075 
3076 	mutex_lock(&log_root_tree->log_mutex);
3077 
3078 	/*
3079 	 * Now we are safe to update the log_root_tree because we're under the
3080 	 * log_mutex, and we're a current writer so we're holding the commit
3081 	 * open until we drop the log_mutex.
3082 	 */
3083 	ret = update_log_root(trans, log, &new_root_item);
3084 
3085 	if (atomic_dec_and_test(&log_root_tree->log_writers)) {
3086 		/* atomic_dec_and_test implies a barrier */
3087 		cond_wake_up_nomb(&log_root_tree->log_writer_wait);
3088 	}
3089 
3090 	if (ret) {
3091 		if (!list_empty(&root_log_ctx.list))
3092 			list_del_init(&root_log_ctx.list);
3093 
3094 		blk_finish_plug(&plug);
3095 		btrfs_set_log_full_commit(fs_info, trans);
3096 
3097 		if (ret != -ENOSPC) {
3098 			btrfs_abort_transaction(trans, ret);
3099 			mutex_unlock(&log_root_tree->log_mutex);
3100 			goto out;
3101 		}
3102 		btrfs_wait_tree_log_extents(log, mark);
3103 		mutex_unlock(&log_root_tree->log_mutex);
3104 		ret = -EAGAIN;
3105 		goto out;
3106 	}
3107 
3108 	if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
3109 		blk_finish_plug(&plug);
3110 		list_del_init(&root_log_ctx.list);
3111 		mutex_unlock(&log_root_tree->log_mutex);
3112 		ret = root_log_ctx.log_ret;
3113 		goto out;
3114 	}
3115 
3116 	index2 = root_log_ctx.log_transid % 2;
3117 	if (atomic_read(&log_root_tree->log_commit[index2])) {
3118 		blk_finish_plug(&plug);
3119 		ret = btrfs_wait_tree_log_extents(log, mark);
3120 		wait_log_commit(log_root_tree,
3121 				root_log_ctx.log_transid);
3122 		mutex_unlock(&log_root_tree->log_mutex);
3123 		if (!ret)
3124 			ret = root_log_ctx.log_ret;
3125 		goto out;
3126 	}
3127 	ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
3128 	atomic_set(&log_root_tree->log_commit[index2], 1);
3129 
3130 	if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
3131 		wait_log_commit(log_root_tree,
3132 				root_log_ctx.log_transid - 1);
3133 	}
3134 
3135 	wait_for_writer(log_root_tree);
3136 
3137 	/*
3138 	 * now that we've moved on to the tree of log tree roots,
3139 	 * check the full commit flag again
3140 	 */
3141 	if (btrfs_need_log_full_commit(fs_info, trans)) {
3142 		blk_finish_plug(&plug);
3143 		btrfs_wait_tree_log_extents(log, mark);
3144 		mutex_unlock(&log_root_tree->log_mutex);
3145 		ret = -EAGAIN;
3146 		goto out_wake_log_root;
3147 	}
3148 
3149 	ret = btrfs_write_marked_extents(fs_info,
3150 					 &log_root_tree->dirty_log_pages,
3151 					 EXTENT_DIRTY | EXTENT_NEW);
3152 	blk_finish_plug(&plug);
3153 	if (ret) {
3154 		btrfs_set_log_full_commit(fs_info, trans);
3155 		btrfs_abort_transaction(trans, ret);
3156 		mutex_unlock(&log_root_tree->log_mutex);
3157 		goto out_wake_log_root;
3158 	}
3159 	ret = btrfs_wait_tree_log_extents(log, mark);
3160 	if (!ret)
3161 		ret = btrfs_wait_tree_log_extents(log_root_tree,
3162 						  EXTENT_NEW | EXTENT_DIRTY);
3163 	if (ret) {
3164 		btrfs_set_log_full_commit(fs_info, trans);
3165 		mutex_unlock(&log_root_tree->log_mutex);
3166 		goto out_wake_log_root;
3167 	}
3168 
3169 	btrfs_set_super_log_root(fs_info->super_for_commit,
3170 				 log_root_tree->node->start);
3171 	btrfs_set_super_log_root_level(fs_info->super_for_commit,
3172 				       btrfs_header_level(log_root_tree->node));
3173 
3174 	log_root_tree->log_transid++;
3175 	mutex_unlock(&log_root_tree->log_mutex);
3176 
3177 	/*
3178 	 * nobody else is going to jump in and write the the ctree
3179 	 * super here because the log_commit atomic below is protecting
3180 	 * us.  We must be called with a transaction handle pinning
3181 	 * the running transaction open, so a full commit can't hop
3182 	 * in and cause problems either.
3183 	 */
3184 	ret = write_all_supers(fs_info, 1);
3185 	if (ret) {
3186 		btrfs_set_log_full_commit(fs_info, trans);
3187 		btrfs_abort_transaction(trans, ret);
3188 		goto out_wake_log_root;
3189 	}
3190 
3191 	mutex_lock(&root->log_mutex);
3192 	if (root->last_log_commit < log_transid)
3193 		root->last_log_commit = log_transid;
3194 	mutex_unlock(&root->log_mutex);
3195 
3196 out_wake_log_root:
3197 	mutex_lock(&log_root_tree->log_mutex);
3198 	btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3199 
3200 	log_root_tree->log_transid_committed++;
3201 	atomic_set(&log_root_tree->log_commit[index2], 0);
3202 	mutex_unlock(&log_root_tree->log_mutex);
3203 
3204 	/*
3205 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3206 	 * all the updates above are seen by the woken threads. It might not be
3207 	 * necessary, but proving that seems to be hard.
3208 	 */
3209 	cond_wake_up(&log_root_tree->log_commit_wait[index2]);
3210 out:
3211 	mutex_lock(&root->log_mutex);
3212 	btrfs_remove_all_log_ctxs(root, index1, ret);
3213 	root->log_transid_committed++;
3214 	atomic_set(&root->log_commit[index1], 0);
3215 	mutex_unlock(&root->log_mutex);
3216 
3217 	/*
3218 	 * The barrier before waitqueue_active (in cond_wake_up) is needed so
3219 	 * all the updates above are seen by the woken threads. It might not be
3220 	 * necessary, but proving that seems to be hard.
3221 	 */
3222 	cond_wake_up(&root->log_commit_wait[index1]);
3223 	return ret;
3224 }
3225 
free_log_tree(struct btrfs_trans_handle * trans,struct btrfs_root * log)3226 static void free_log_tree(struct btrfs_trans_handle *trans,
3227 			  struct btrfs_root *log)
3228 {
3229 	int ret;
3230 	u64 start;
3231 	u64 end;
3232 	struct walk_control wc = {
3233 		.free = 1,
3234 		.process_func = process_one_buffer
3235 	};
3236 
3237 	ret = walk_log_tree(trans, log, &wc);
3238 	if (ret) {
3239 		if (trans)
3240 			btrfs_abort_transaction(trans, ret);
3241 		else
3242 			btrfs_handle_fs_error(log->fs_info, ret, NULL);
3243 	}
3244 
3245 	while (1) {
3246 		ret = find_first_extent_bit(&log->dirty_log_pages,
3247 				0, &start, &end,
3248 				EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT,
3249 				NULL);
3250 		if (ret)
3251 			break;
3252 
3253 		clear_extent_bits(&log->dirty_log_pages, start, end,
3254 				  EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3255 	}
3256 
3257 	free_extent_buffer(log->node);
3258 	kfree(log);
3259 }
3260 
3261 /*
3262  * free all the extents used by the tree log.  This should be called
3263  * at commit time of the full transaction
3264  */
btrfs_free_log(struct btrfs_trans_handle * trans,struct btrfs_root * root)3265 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3266 {
3267 	if (root->log_root) {
3268 		free_log_tree(trans, root->log_root);
3269 		root->log_root = NULL;
3270 	}
3271 	return 0;
3272 }
3273 
btrfs_free_log_root_tree(struct btrfs_trans_handle * trans,struct btrfs_fs_info * fs_info)3274 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3275 			     struct btrfs_fs_info *fs_info)
3276 {
3277 	if (fs_info->log_root_tree) {
3278 		free_log_tree(trans, fs_info->log_root_tree);
3279 		fs_info->log_root_tree = NULL;
3280 	}
3281 	return 0;
3282 }
3283 
3284 /*
3285  * Check if an inode was logged in the current transaction. We can't always rely
3286  * on an inode's logged_trans value, because it's an in-memory only field and
3287  * therefore not persisted. This means that its value is lost if the inode gets
3288  * evicted and loaded again from disk (in which case it has a value of 0, and
3289  * certainly it is smaller then any possible transaction ID), when that happens
3290  * the full_sync flag is set in the inode's runtime flags, so on that case we
3291  * assume eviction happened and ignore the logged_trans value, assuming the
3292  * worst case, that the inode was logged before in the current transaction.
3293  */
inode_logged(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)3294 static bool inode_logged(struct btrfs_trans_handle *trans,
3295 			 struct btrfs_inode *inode)
3296 {
3297 	if (inode->logged_trans == trans->transid)
3298 		return true;
3299 
3300 	if (inode->last_trans == trans->transid &&
3301 	    test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) &&
3302 	    !test_bit(BTRFS_FS_LOG_RECOVERING, &trans->fs_info->flags))
3303 		return true;
3304 
3305 	return false;
3306 }
3307 
3308 /*
3309  * If both a file and directory are logged, and unlinks or renames are
3310  * mixed in, we have a few interesting corners:
3311  *
3312  * create file X in dir Y
3313  * link file X to X.link in dir Y
3314  * fsync file X
3315  * unlink file X but leave X.link
3316  * fsync dir Y
3317  *
3318  * After a crash we would expect only X.link to exist.  But file X
3319  * didn't get fsync'd again so the log has back refs for X and X.link.
3320  *
3321  * We solve this by removing directory entries and inode backrefs from the
3322  * log when a file that was logged in the current transaction is
3323  * unlinked.  Any later fsync will include the updated log entries, and
3324  * we'll be able to reconstruct the proper directory items from backrefs.
3325  *
3326  * This optimizations allows us to avoid relogging the entire inode
3327  * or the entire directory.
3328  */
btrfs_del_dir_entries_in_log(struct btrfs_trans_handle * trans,struct btrfs_root * root,const char * name,int name_len,struct btrfs_inode * dir,u64 index)3329 int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3330 				 struct btrfs_root *root,
3331 				 const char *name, int name_len,
3332 				 struct btrfs_inode *dir, u64 index)
3333 {
3334 	struct btrfs_root *log;
3335 	struct btrfs_dir_item *di;
3336 	struct btrfs_path *path;
3337 	int ret;
3338 	int err = 0;
3339 	int bytes_del = 0;
3340 	u64 dir_ino = btrfs_ino(dir);
3341 
3342 	if (!inode_logged(trans, dir))
3343 		return 0;
3344 
3345 	ret = join_running_log_trans(root);
3346 	if (ret)
3347 		return 0;
3348 
3349 	mutex_lock(&dir->log_mutex);
3350 
3351 	log = root->log_root;
3352 	path = btrfs_alloc_path();
3353 	if (!path) {
3354 		err = -ENOMEM;
3355 		goto out_unlock;
3356 	}
3357 
3358 	di = btrfs_lookup_dir_item(trans, log, path, dir_ino,
3359 				   name, name_len, -1);
3360 	if (IS_ERR(di)) {
3361 		err = PTR_ERR(di);
3362 		goto fail;
3363 	}
3364 	if (di) {
3365 		ret = btrfs_delete_one_dir_name(trans, log, path, di);
3366 		bytes_del += name_len;
3367 		if (ret) {
3368 			err = ret;
3369 			goto fail;
3370 		}
3371 	}
3372 	btrfs_release_path(path);
3373 	di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3374 					 index, name, name_len, -1);
3375 	if (IS_ERR(di)) {
3376 		err = PTR_ERR(di);
3377 		goto fail;
3378 	}
3379 	if (di) {
3380 		ret = btrfs_delete_one_dir_name(trans, log, path, di);
3381 		bytes_del += name_len;
3382 		if (ret) {
3383 			err = ret;
3384 			goto fail;
3385 		}
3386 	}
3387 
3388 	/* update the directory size in the log to reflect the names
3389 	 * we have removed
3390 	 */
3391 	if (bytes_del) {
3392 		struct btrfs_key key;
3393 
3394 		key.objectid = dir_ino;
3395 		key.offset = 0;
3396 		key.type = BTRFS_INODE_ITEM_KEY;
3397 		btrfs_release_path(path);
3398 
3399 		ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
3400 		if (ret < 0) {
3401 			err = ret;
3402 			goto fail;
3403 		}
3404 		if (ret == 0) {
3405 			struct btrfs_inode_item *item;
3406 			u64 i_size;
3407 
3408 			item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3409 					      struct btrfs_inode_item);
3410 			i_size = btrfs_inode_size(path->nodes[0], item);
3411 			if (i_size > bytes_del)
3412 				i_size -= bytes_del;
3413 			else
3414 				i_size = 0;
3415 			btrfs_set_inode_size(path->nodes[0], item, i_size);
3416 			btrfs_mark_buffer_dirty(path->nodes[0]);
3417 		} else
3418 			ret = 0;
3419 		btrfs_release_path(path);
3420 	}
3421 fail:
3422 	btrfs_free_path(path);
3423 out_unlock:
3424 	mutex_unlock(&dir->log_mutex);
3425 	if (err == -ENOSPC) {
3426 		btrfs_set_log_full_commit(root->fs_info, trans);
3427 		err = 0;
3428 	} else if (err < 0 && err != -ENOENT) {
3429 		/* ENOENT can be returned if the entry hasn't been fsynced yet */
3430 		btrfs_abort_transaction(trans, err);
3431 	}
3432 
3433 	btrfs_end_log_trans(root);
3434 
3435 	return err;
3436 }
3437 
3438 /* 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 char * name,int name_len,struct btrfs_inode * inode,u64 dirid)3439 int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3440 			       struct btrfs_root *root,
3441 			       const char *name, int name_len,
3442 			       struct btrfs_inode *inode, u64 dirid)
3443 {
3444 	struct btrfs_fs_info *fs_info = root->fs_info;
3445 	struct btrfs_root *log;
3446 	u64 index;
3447 	int ret;
3448 
3449 	if (!inode_logged(trans, inode))
3450 		return 0;
3451 
3452 	ret = join_running_log_trans(root);
3453 	if (ret)
3454 		return 0;
3455 	log = root->log_root;
3456 	mutex_lock(&inode->log_mutex);
3457 
3458 	ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
3459 				  dirid, &index);
3460 	mutex_unlock(&inode->log_mutex);
3461 	if (ret == -ENOSPC) {
3462 		btrfs_set_log_full_commit(fs_info, trans);
3463 		ret = 0;
3464 	} else if (ret < 0 && ret != -ENOENT)
3465 		btrfs_abort_transaction(trans, ret);
3466 	btrfs_end_log_trans(root);
3467 
3468 	return ret;
3469 }
3470 
3471 /*
3472  * creates a range item in the log for 'dirid'.  first_offset and
3473  * last_offset tell us which parts of the key space the log should
3474  * be considered authoritative for.
3475  */
insert_dir_log_key(struct btrfs_trans_handle * trans,struct btrfs_root * log,struct btrfs_path * path,int key_type,u64 dirid,u64 first_offset,u64 last_offset)3476 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3477 				       struct btrfs_root *log,
3478 				       struct btrfs_path *path,
3479 				       int key_type, u64 dirid,
3480 				       u64 first_offset, u64 last_offset)
3481 {
3482 	int ret;
3483 	struct btrfs_key key;
3484 	struct btrfs_dir_log_item *item;
3485 
3486 	key.objectid = dirid;
3487 	key.offset = first_offset;
3488 	if (key_type == BTRFS_DIR_ITEM_KEY)
3489 		key.type = BTRFS_DIR_LOG_ITEM_KEY;
3490 	else
3491 		key.type = BTRFS_DIR_LOG_INDEX_KEY;
3492 	ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3493 	if (ret)
3494 		return ret;
3495 
3496 	item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3497 			      struct btrfs_dir_log_item);
3498 	btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3499 	btrfs_mark_buffer_dirty(path->nodes[0]);
3500 	btrfs_release_path(path);
3501 	return 0;
3502 }
3503 
3504 /*
3505  * log all the items included in the current transaction for a given
3506  * directory.  This also creates the range items in the log tree required
3507  * to replay anything deleted before the fsync
3508  */
log_dir_items(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path,struct btrfs_path * dst_path,int key_type,struct btrfs_log_ctx * ctx,u64 min_offset,u64 * last_offset_ret)3509 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3510 			  struct btrfs_root *root, struct btrfs_inode *inode,
3511 			  struct btrfs_path *path,
3512 			  struct btrfs_path *dst_path, int key_type,
3513 			  struct btrfs_log_ctx *ctx,
3514 			  u64 min_offset, u64 *last_offset_ret)
3515 {
3516 	struct btrfs_key min_key;
3517 	struct btrfs_root *log = root->log_root;
3518 	struct extent_buffer *src;
3519 	int err = 0;
3520 	int ret;
3521 	int i;
3522 	int nritems;
3523 	u64 first_offset = min_offset;
3524 	u64 last_offset = (u64)-1;
3525 	u64 ino = btrfs_ino(inode);
3526 
3527 	log = root->log_root;
3528 
3529 	min_key.objectid = ino;
3530 	min_key.type = key_type;
3531 	min_key.offset = min_offset;
3532 
3533 	ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3534 
3535 	/*
3536 	 * we didn't find anything from this transaction, see if there
3537 	 * is anything at all
3538 	 */
3539 	if (ret != 0 || min_key.objectid != ino || min_key.type != key_type) {
3540 		min_key.objectid = ino;
3541 		min_key.type = key_type;
3542 		min_key.offset = (u64)-1;
3543 		btrfs_release_path(path);
3544 		ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3545 		if (ret < 0) {
3546 			btrfs_release_path(path);
3547 			return ret;
3548 		}
3549 		ret = btrfs_previous_item(root, path, ino, key_type);
3550 
3551 		/* if ret == 0 there are items for this type,
3552 		 * create a range to tell us the last key of this type.
3553 		 * otherwise, there are no items in this directory after
3554 		 * *min_offset, and we create a range to indicate that.
3555 		 */
3556 		if (ret == 0) {
3557 			struct btrfs_key tmp;
3558 			btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3559 					      path->slots[0]);
3560 			if (key_type == tmp.type)
3561 				first_offset = max(min_offset, tmp.offset) + 1;
3562 		}
3563 		goto done;
3564 	}
3565 
3566 	/* go backward to find any previous key */
3567 	ret = btrfs_previous_item(root, path, ino, key_type);
3568 	if (ret == 0) {
3569 		struct btrfs_key tmp;
3570 		btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3571 		if (key_type == tmp.type) {
3572 			first_offset = tmp.offset;
3573 			ret = overwrite_item(trans, log, dst_path,
3574 					     path->nodes[0], path->slots[0],
3575 					     &tmp);
3576 			if (ret) {
3577 				err = ret;
3578 				goto done;
3579 			}
3580 		}
3581 	}
3582 	btrfs_release_path(path);
3583 
3584 	/*
3585 	 * Find the first key from this transaction again.  See the note for
3586 	 * log_new_dir_dentries, if we're logging a directory recursively we
3587 	 * won't be holding its i_mutex, which means we can modify the directory
3588 	 * while we're logging it.  If we remove an entry between our first
3589 	 * search and this search we'll not find the key again and can just
3590 	 * bail.
3591 	 */
3592 search:
3593 	ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3594 	if (ret != 0)
3595 		goto done;
3596 
3597 	/*
3598 	 * we have a block from this transaction, log every item in it
3599 	 * from our directory
3600 	 */
3601 	while (1) {
3602 		struct btrfs_key tmp;
3603 		src = path->nodes[0];
3604 		nritems = btrfs_header_nritems(src);
3605 		for (i = path->slots[0]; i < nritems; i++) {
3606 			struct btrfs_dir_item *di;
3607 
3608 			btrfs_item_key_to_cpu(src, &min_key, i);
3609 
3610 			if (min_key.objectid != ino || min_key.type != key_type)
3611 				goto done;
3612 
3613 			if (need_resched()) {
3614 				btrfs_release_path(path);
3615 				cond_resched();
3616 				goto search;
3617 			}
3618 
3619 			ret = overwrite_item(trans, log, dst_path, src, i,
3620 					     &min_key);
3621 			if (ret) {
3622 				err = ret;
3623 				goto done;
3624 			}
3625 
3626 			/*
3627 			 * We must make sure that when we log a directory entry,
3628 			 * the corresponding inode, after log replay, has a
3629 			 * matching link count. For example:
3630 			 *
3631 			 * touch foo
3632 			 * mkdir mydir
3633 			 * sync
3634 			 * ln foo mydir/bar
3635 			 * xfs_io -c "fsync" mydir
3636 			 * <crash>
3637 			 * <mount fs and log replay>
3638 			 *
3639 			 * Would result in a fsync log that when replayed, our
3640 			 * file inode would have a link count of 1, but we get
3641 			 * two directory entries pointing to the same inode.
3642 			 * After removing one of the names, it would not be
3643 			 * possible to remove the other name, which resulted
3644 			 * always in stale file handle errors, and would not
3645 			 * be possible to rmdir the parent directory, since
3646 			 * its i_size could never decrement to the value
3647 			 * BTRFS_EMPTY_DIR_SIZE, resulting in -ENOTEMPTY errors.
3648 			 */
3649 			di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3650 			btrfs_dir_item_key_to_cpu(src, di, &tmp);
3651 			if (ctx &&
3652 			    (btrfs_dir_transid(src, di) == trans->transid ||
3653 			     btrfs_dir_type(src, di) == BTRFS_FT_DIR) &&
3654 			    tmp.type != BTRFS_ROOT_ITEM_KEY)
3655 				ctx->log_new_dentries = true;
3656 		}
3657 		path->slots[0] = nritems;
3658 
3659 		/*
3660 		 * look ahead to the next item and see if it is also
3661 		 * from this directory and from this transaction
3662 		 */
3663 		ret = btrfs_next_leaf(root, path);
3664 		if (ret) {
3665 			if (ret == 1)
3666 				last_offset = (u64)-1;
3667 			else
3668 				err = ret;
3669 			goto done;
3670 		}
3671 		btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3672 		if (tmp.objectid != ino || tmp.type != key_type) {
3673 			last_offset = (u64)-1;
3674 			goto done;
3675 		}
3676 		if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3677 			ret = overwrite_item(trans, log, dst_path,
3678 					     path->nodes[0], path->slots[0],
3679 					     &tmp);
3680 			if (ret)
3681 				err = ret;
3682 			else
3683 				last_offset = tmp.offset;
3684 			goto done;
3685 		}
3686 	}
3687 done:
3688 	btrfs_release_path(path);
3689 	btrfs_release_path(dst_path);
3690 
3691 	if (err == 0) {
3692 		*last_offset_ret = last_offset;
3693 		/*
3694 		 * insert the log range keys to indicate where the log
3695 		 * is valid
3696 		 */
3697 		ret = insert_dir_log_key(trans, log, path, key_type,
3698 					 ino, first_offset, last_offset);
3699 		if (ret)
3700 			err = ret;
3701 	}
3702 	return err;
3703 }
3704 
3705 /*
3706  * logging directories is very similar to logging inodes, We find all the items
3707  * from the current transaction and write them to the log.
3708  *
3709  * The recovery code scans the directory in the subvolume, and if it finds a
3710  * key in the range logged that is not present in the log tree, then it means
3711  * that dir entry was unlinked during the transaction.
3712  *
3713  * In order for that scan to work, we must include one key smaller than
3714  * the smallest logged by this transaction and one key larger than the largest
3715  * key logged by this transaction.
3716  */
log_directory_changes(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path,struct btrfs_path * dst_path,struct btrfs_log_ctx * ctx)3717 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
3718 			  struct btrfs_root *root, struct btrfs_inode *inode,
3719 			  struct btrfs_path *path,
3720 			  struct btrfs_path *dst_path,
3721 			  struct btrfs_log_ctx *ctx)
3722 {
3723 	u64 min_key;
3724 	u64 max_key;
3725 	int ret;
3726 	int key_type = BTRFS_DIR_ITEM_KEY;
3727 
3728 again:
3729 	min_key = 0;
3730 	max_key = 0;
3731 	while (1) {
3732 		ret = log_dir_items(trans, root, inode, path, dst_path, key_type,
3733 				ctx, min_key, &max_key);
3734 		if (ret)
3735 			return ret;
3736 		if (max_key == (u64)-1)
3737 			break;
3738 		min_key = max_key + 1;
3739 	}
3740 
3741 	if (key_type == BTRFS_DIR_ITEM_KEY) {
3742 		key_type = BTRFS_DIR_INDEX_KEY;
3743 		goto again;
3744 	}
3745 	return 0;
3746 }
3747 
3748 /*
3749  * a helper function to drop items from the log before we relog an
3750  * inode.  max_key_type indicates the highest item type to remove.
3751  * This cannot be run for file data extents because it does not
3752  * free the extents they point to.
3753  */
drop_objectid_items(struct btrfs_trans_handle * trans,struct btrfs_root * log,struct btrfs_path * path,u64 objectid,int max_key_type)3754 static int drop_objectid_items(struct btrfs_trans_handle *trans,
3755 				  struct btrfs_root *log,
3756 				  struct btrfs_path *path,
3757 				  u64 objectid, int max_key_type)
3758 {
3759 	int ret;
3760 	struct btrfs_key key;
3761 	struct btrfs_key found_key;
3762 	int start_slot;
3763 
3764 	key.objectid = objectid;
3765 	key.type = max_key_type;
3766 	key.offset = (u64)-1;
3767 
3768 	while (1) {
3769 		ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
3770 		BUG_ON(ret == 0); /* Logic error */
3771 		if (ret < 0)
3772 			break;
3773 
3774 		if (path->slots[0] == 0)
3775 			break;
3776 
3777 		path->slots[0]--;
3778 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
3779 				      path->slots[0]);
3780 
3781 		if (found_key.objectid != objectid)
3782 			break;
3783 
3784 		found_key.offset = 0;
3785 		found_key.type = 0;
3786 		ret = btrfs_bin_search(path->nodes[0], &found_key, 0,
3787 				       &start_slot);
3788 
3789 		ret = btrfs_del_items(trans, log, path, start_slot,
3790 				      path->slots[0] - start_slot + 1);
3791 		/*
3792 		 * If start slot isn't 0 then we don't need to re-search, we've
3793 		 * found the last guy with the objectid in this tree.
3794 		 */
3795 		if (ret || start_slot != 0)
3796 			break;
3797 		btrfs_release_path(path);
3798 	}
3799 	btrfs_release_path(path);
3800 	if (ret > 0)
3801 		ret = 0;
3802 	return ret;
3803 }
3804 
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)3805 static void fill_inode_item(struct btrfs_trans_handle *trans,
3806 			    struct extent_buffer *leaf,
3807 			    struct btrfs_inode_item *item,
3808 			    struct inode *inode, int log_inode_only,
3809 			    u64 logged_isize)
3810 {
3811 	struct btrfs_map_token token;
3812 
3813 	btrfs_init_map_token(&token);
3814 
3815 	if (log_inode_only) {
3816 		/* set the generation to zero so the recover code
3817 		 * can tell the difference between an logging
3818 		 * just to say 'this inode exists' and a logging
3819 		 * to say 'update this inode with these values'
3820 		 */
3821 		btrfs_set_token_inode_generation(leaf, item, 0, &token);
3822 		btrfs_set_token_inode_size(leaf, item, logged_isize, &token);
3823 	} else {
3824 		btrfs_set_token_inode_generation(leaf, item,
3825 						 BTRFS_I(inode)->generation,
3826 						 &token);
3827 		btrfs_set_token_inode_size(leaf, item, inode->i_size, &token);
3828 	}
3829 
3830 	btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3831 	btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3832 	btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3833 	btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3834 
3835 	btrfs_set_token_timespec_sec(leaf, &item->atime,
3836 				     inode->i_atime.tv_sec, &token);
3837 	btrfs_set_token_timespec_nsec(leaf, &item->atime,
3838 				      inode->i_atime.tv_nsec, &token);
3839 
3840 	btrfs_set_token_timespec_sec(leaf, &item->mtime,
3841 				     inode->i_mtime.tv_sec, &token);
3842 	btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3843 				      inode->i_mtime.tv_nsec, &token);
3844 
3845 	btrfs_set_token_timespec_sec(leaf, &item->ctime,
3846 				     inode->i_ctime.tv_sec, &token);
3847 	btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3848 				      inode->i_ctime.tv_nsec, &token);
3849 
3850 	btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3851 				     &token);
3852 
3853 	btrfs_set_token_inode_sequence(leaf, item,
3854 				       inode_peek_iversion(inode), &token);
3855 	btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3856 	btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3857 	btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3858 	btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3859 }
3860 
log_inode_item(struct btrfs_trans_handle * trans,struct btrfs_root * log,struct btrfs_path * path,struct btrfs_inode * inode)3861 static int log_inode_item(struct btrfs_trans_handle *trans,
3862 			  struct btrfs_root *log, struct btrfs_path *path,
3863 			  struct btrfs_inode *inode)
3864 {
3865 	struct btrfs_inode_item *inode_item;
3866 	int ret;
3867 
3868 	ret = btrfs_insert_empty_item(trans, log, path,
3869 				      &inode->location, sizeof(*inode_item));
3870 	if (ret && ret != -EEXIST)
3871 		return ret;
3872 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3873 				    struct btrfs_inode_item);
3874 	fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
3875 			0, 0);
3876 	btrfs_release_path(path);
3877 	return 0;
3878 }
3879 
log_csums(struct btrfs_trans_handle * trans,struct btrfs_root * log_root,struct btrfs_ordered_sum * sums)3880 static int log_csums(struct btrfs_trans_handle *trans,
3881 		     struct btrfs_root *log_root,
3882 		     struct btrfs_ordered_sum *sums)
3883 {
3884 	int ret;
3885 
3886 	/*
3887 	 * Due to extent cloning, we might have logged a csum item that covers a
3888 	 * subrange of a cloned extent, and later we can end up logging a csum
3889 	 * item for a larger subrange of the same extent or the entire range.
3890 	 * This would leave csum items in the log tree that cover the same range
3891 	 * and break the searches for checksums in the log tree, resulting in
3892 	 * some checksums missing in the fs/subvolume tree. So just delete (or
3893 	 * trim and adjust) any existing csum items in the log for this range.
3894 	 */
3895 	ret = btrfs_del_csums(trans, log_root, sums->bytenr, sums->len);
3896 	if (ret)
3897 		return ret;
3898 
3899 	return btrfs_csum_file_blocks(trans, log_root, sums);
3900 }
3901 
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)3902 static noinline int copy_items(struct btrfs_trans_handle *trans,
3903 			       struct btrfs_inode *inode,
3904 			       struct btrfs_path *dst_path,
3905 			       struct btrfs_path *src_path,
3906 			       int start_slot, int nr, int inode_only,
3907 			       u64 logged_isize)
3908 {
3909 	struct btrfs_fs_info *fs_info = trans->fs_info;
3910 	unsigned long src_offset;
3911 	unsigned long dst_offset;
3912 	struct btrfs_root *log = inode->root->log_root;
3913 	struct btrfs_file_extent_item *extent;
3914 	struct btrfs_inode_item *inode_item;
3915 	struct extent_buffer *src = src_path->nodes[0];
3916 	int ret;
3917 	struct btrfs_key *ins_keys;
3918 	u32 *ins_sizes;
3919 	char *ins_data;
3920 	int i;
3921 	struct list_head ordered_sums;
3922 	int skip_csum = inode->flags & BTRFS_INODE_NODATASUM;
3923 
3924 	INIT_LIST_HEAD(&ordered_sums);
3925 
3926 	ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
3927 			   nr * sizeof(u32), GFP_NOFS);
3928 	if (!ins_data)
3929 		return -ENOMEM;
3930 
3931 	ins_sizes = (u32 *)ins_data;
3932 	ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
3933 
3934 	for (i = 0; i < nr; i++) {
3935 		ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
3936 		btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
3937 	}
3938 	ret = btrfs_insert_empty_items(trans, log, dst_path,
3939 				       ins_keys, ins_sizes, nr);
3940 	if (ret) {
3941 		kfree(ins_data);
3942 		return ret;
3943 	}
3944 
3945 	for (i = 0; i < nr; i++, dst_path->slots[0]++) {
3946 		dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
3947 						   dst_path->slots[0]);
3948 
3949 		src_offset = btrfs_item_ptr_offset(src, start_slot + i);
3950 
3951 		if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
3952 			inode_item = btrfs_item_ptr(dst_path->nodes[0],
3953 						    dst_path->slots[0],
3954 						    struct btrfs_inode_item);
3955 			fill_inode_item(trans, dst_path->nodes[0], inode_item,
3956 					&inode->vfs_inode,
3957 					inode_only == LOG_INODE_EXISTS,
3958 					logged_isize);
3959 		} else {
3960 			copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
3961 					   src_offset, ins_sizes[i]);
3962 		}
3963 
3964 		/* take a reference on file data extents so that truncates
3965 		 * or deletes of this inode don't have to relog the inode
3966 		 * again
3967 		 */
3968 		if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY &&
3969 		    !skip_csum) {
3970 			int found_type;
3971 			extent = btrfs_item_ptr(src, start_slot + i,
3972 						struct btrfs_file_extent_item);
3973 
3974 			if (btrfs_file_extent_generation(src, extent) < trans->transid)
3975 				continue;
3976 
3977 			found_type = btrfs_file_extent_type(src, extent);
3978 			if (found_type == BTRFS_FILE_EXTENT_REG) {
3979 				u64 ds, dl, cs, cl;
3980 				ds = btrfs_file_extent_disk_bytenr(src,
3981 								extent);
3982 				/* ds == 0 is a hole */
3983 				if (ds == 0)
3984 					continue;
3985 
3986 				dl = btrfs_file_extent_disk_num_bytes(src,
3987 								extent);
3988 				cs = btrfs_file_extent_offset(src, extent);
3989 				cl = btrfs_file_extent_num_bytes(src,
3990 								extent);
3991 				if (btrfs_file_extent_compression(src,
3992 								  extent)) {
3993 					cs = 0;
3994 					cl = dl;
3995 				}
3996 
3997 				ret = btrfs_lookup_csums_range(
3998 						fs_info->csum_root,
3999 						ds + cs, ds + cs + cl - 1,
4000 						&ordered_sums, 0);
4001 				if (ret)
4002 					break;
4003 			}
4004 		}
4005 	}
4006 
4007 	btrfs_mark_buffer_dirty(dst_path->nodes[0]);
4008 	btrfs_release_path(dst_path);
4009 	kfree(ins_data);
4010 
4011 	/*
4012 	 * we have to do this after the loop above to avoid changing the
4013 	 * log tree while trying to change the log tree.
4014 	 */
4015 	while (!list_empty(&ordered_sums)) {
4016 		struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4017 						   struct btrfs_ordered_sum,
4018 						   list);
4019 		if (!ret)
4020 			ret = log_csums(trans, log, sums);
4021 		list_del(&sums->list);
4022 		kfree(sums);
4023 	}
4024 
4025 	return ret;
4026 }
4027 
extent_cmp(void * priv,struct list_head * a,struct list_head * b)4028 static int extent_cmp(void *priv, struct list_head *a, struct list_head *b)
4029 {
4030 	struct extent_map *em1, *em2;
4031 
4032 	em1 = list_entry(a, struct extent_map, list);
4033 	em2 = list_entry(b, struct extent_map, list);
4034 
4035 	if (em1->start < em2->start)
4036 		return -1;
4037 	else if (em1->start > em2->start)
4038 		return 1;
4039 	return 0;
4040 }
4041 
log_extent_csums(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_root * log_root,const struct extent_map * em)4042 static int log_extent_csums(struct btrfs_trans_handle *trans,
4043 			    struct btrfs_inode *inode,
4044 			    struct btrfs_root *log_root,
4045 			    const struct extent_map *em)
4046 {
4047 	u64 csum_offset;
4048 	u64 csum_len;
4049 	LIST_HEAD(ordered_sums);
4050 	int ret = 0;
4051 
4052 	if (inode->flags & BTRFS_INODE_NODATASUM ||
4053 	    test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
4054 	    em->block_start == EXTENT_MAP_HOLE)
4055 		return 0;
4056 
4057 	/* If we're compressed we have to save the entire range of csums. */
4058 	if (em->compress_type) {
4059 		csum_offset = 0;
4060 		csum_len = max(em->block_len, em->orig_block_len);
4061 	} else {
4062 		csum_offset = em->mod_start - em->start;
4063 		csum_len = em->mod_len;
4064 	}
4065 
4066 	/* block start is already adjusted for the file extent offset. */
4067 	ret = btrfs_lookup_csums_range(trans->fs_info->csum_root,
4068 				       em->block_start + csum_offset,
4069 				       em->block_start + csum_offset +
4070 				       csum_len - 1, &ordered_sums, 0);
4071 	if (ret)
4072 		return ret;
4073 
4074 	while (!list_empty(&ordered_sums)) {
4075 		struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4076 						   struct btrfs_ordered_sum,
4077 						   list);
4078 		if (!ret)
4079 			ret = log_csums(trans, log_root, sums);
4080 		list_del(&sums->list);
4081 		kfree(sums);
4082 	}
4083 
4084 	return ret;
4085 }
4086 
log_one_extent(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_root * root,const struct extent_map * em,struct btrfs_path * path,struct btrfs_log_ctx * ctx)4087 static int log_one_extent(struct btrfs_trans_handle *trans,
4088 			  struct btrfs_inode *inode, struct btrfs_root *root,
4089 			  const struct extent_map *em,
4090 			  struct btrfs_path *path,
4091 			  struct btrfs_log_ctx *ctx)
4092 {
4093 	struct btrfs_root *log = root->log_root;
4094 	struct btrfs_file_extent_item *fi;
4095 	struct extent_buffer *leaf;
4096 	struct btrfs_map_token token;
4097 	struct btrfs_key key;
4098 	u64 extent_offset = em->start - em->orig_start;
4099 	u64 block_len;
4100 	int ret;
4101 	int extent_inserted = 0;
4102 
4103 	ret = log_extent_csums(trans, inode, log, em);
4104 	if (ret)
4105 		return ret;
4106 
4107 	btrfs_init_map_token(&token);
4108 
4109 	ret = __btrfs_drop_extents(trans, log, &inode->vfs_inode, path, em->start,
4110 				   em->start + em->len, NULL, 0, 1,
4111 				   sizeof(*fi), &extent_inserted);
4112 	if (ret)
4113 		return ret;
4114 
4115 	if (!extent_inserted) {
4116 		key.objectid = btrfs_ino(inode);
4117 		key.type = BTRFS_EXTENT_DATA_KEY;
4118 		key.offset = em->start;
4119 
4120 		ret = btrfs_insert_empty_item(trans, log, path, &key,
4121 					      sizeof(*fi));
4122 		if (ret)
4123 			return ret;
4124 	}
4125 	leaf = path->nodes[0];
4126 	fi = btrfs_item_ptr(leaf, path->slots[0],
4127 			    struct btrfs_file_extent_item);
4128 
4129 	btrfs_set_token_file_extent_generation(leaf, fi, trans->transid,
4130 					       &token);
4131 	if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4132 		btrfs_set_token_file_extent_type(leaf, fi,
4133 						 BTRFS_FILE_EXTENT_PREALLOC,
4134 						 &token);
4135 	else
4136 		btrfs_set_token_file_extent_type(leaf, fi,
4137 						 BTRFS_FILE_EXTENT_REG,
4138 						 &token);
4139 
4140 	block_len = max(em->block_len, em->orig_block_len);
4141 	if (em->compress_type != BTRFS_COMPRESS_NONE) {
4142 		btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4143 							em->block_start,
4144 							&token);
4145 		btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4146 							   &token);
4147 	} else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4148 		btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4149 							em->block_start -
4150 							extent_offset, &token);
4151 		btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4152 							   &token);
4153 	} else {
4154 		btrfs_set_token_file_extent_disk_bytenr(leaf, fi, 0, &token);
4155 		btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, 0,
4156 							   &token);
4157 	}
4158 
4159 	btrfs_set_token_file_extent_offset(leaf, fi, extent_offset, &token);
4160 	btrfs_set_token_file_extent_num_bytes(leaf, fi, em->len, &token);
4161 	btrfs_set_token_file_extent_ram_bytes(leaf, fi, em->ram_bytes, &token);
4162 	btrfs_set_token_file_extent_compression(leaf, fi, em->compress_type,
4163 						&token);
4164 	btrfs_set_token_file_extent_encryption(leaf, fi, 0, &token);
4165 	btrfs_set_token_file_extent_other_encoding(leaf, fi, 0, &token);
4166 	btrfs_mark_buffer_dirty(leaf);
4167 
4168 	btrfs_release_path(path);
4169 
4170 	return ret;
4171 }
4172 
4173 /*
4174  * Log all prealloc extents beyond the inode's i_size to make sure we do not
4175  * lose them after doing a fast fsync and replaying the log. We scan the
4176  * subvolume's root instead of iterating the inode's extent map tree because
4177  * otherwise we can log incorrect extent items based on extent map conversion.
4178  * That can happen due to the fact that extent maps are merged when they
4179  * are not in the extent map tree's list of modified extents.
4180  */
btrfs_log_prealloc_extents(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_path * path)4181 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4182 				      struct btrfs_inode *inode,
4183 				      struct btrfs_path *path)
4184 {
4185 	struct btrfs_root *root = inode->root;
4186 	struct btrfs_key key;
4187 	const u64 i_size = i_size_read(&inode->vfs_inode);
4188 	const u64 ino = btrfs_ino(inode);
4189 	struct btrfs_path *dst_path = NULL;
4190 	bool dropped_extents = false;
4191 	u64 truncate_offset = i_size;
4192 	struct extent_buffer *leaf;
4193 	int slot;
4194 	int ins_nr = 0;
4195 	int start_slot;
4196 	int ret;
4197 
4198 	if (!(inode->flags & BTRFS_INODE_PREALLOC))
4199 		return 0;
4200 
4201 	key.objectid = ino;
4202 	key.type = BTRFS_EXTENT_DATA_KEY;
4203 	key.offset = i_size;
4204 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4205 	if (ret < 0)
4206 		goto out;
4207 
4208 	/*
4209 	 * We must check if there is a prealloc extent that starts before the
4210 	 * i_size and crosses the i_size boundary. This is to ensure later we
4211 	 * truncate down to the end of that extent and not to the i_size, as
4212 	 * otherwise we end up losing part of the prealloc extent after a log
4213 	 * replay and with an implicit hole if there is another prealloc extent
4214 	 * that starts at an offset beyond i_size.
4215 	 */
4216 	ret = btrfs_previous_item(root, path, ino, BTRFS_EXTENT_DATA_KEY);
4217 	if (ret < 0)
4218 		goto out;
4219 
4220 	if (ret == 0) {
4221 		struct btrfs_file_extent_item *ei;
4222 
4223 		leaf = path->nodes[0];
4224 		slot = path->slots[0];
4225 		ei = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4226 
4227 		if (btrfs_file_extent_type(leaf, ei) ==
4228 		    BTRFS_FILE_EXTENT_PREALLOC) {
4229 			u64 extent_end;
4230 
4231 			btrfs_item_key_to_cpu(leaf, &key, slot);
4232 			extent_end = key.offset +
4233 				btrfs_file_extent_num_bytes(leaf, ei);
4234 
4235 			if (extent_end > i_size)
4236 				truncate_offset = extent_end;
4237 		}
4238 	} else {
4239 		ret = 0;
4240 	}
4241 
4242 	while (true) {
4243 		leaf = path->nodes[0];
4244 		slot = path->slots[0];
4245 
4246 		if (slot >= btrfs_header_nritems(leaf)) {
4247 			if (ins_nr > 0) {
4248 				ret = copy_items(trans, inode, dst_path, path,
4249 						 start_slot, ins_nr, 1, 0);
4250 				if (ret < 0)
4251 					goto out;
4252 				ins_nr = 0;
4253 			}
4254 			ret = btrfs_next_leaf(root, path);
4255 			if (ret < 0)
4256 				goto out;
4257 			if (ret > 0) {
4258 				ret = 0;
4259 				break;
4260 			}
4261 			continue;
4262 		}
4263 
4264 		btrfs_item_key_to_cpu(leaf, &key, slot);
4265 		if (key.objectid > ino)
4266 			break;
4267 		if (WARN_ON_ONCE(key.objectid < ino) ||
4268 		    key.type < BTRFS_EXTENT_DATA_KEY ||
4269 		    key.offset < i_size) {
4270 			path->slots[0]++;
4271 			continue;
4272 		}
4273 		if (!dropped_extents) {
4274 			/*
4275 			 * Avoid logging extent items logged in past fsync calls
4276 			 * and leading to duplicate keys in the log tree.
4277 			 */
4278 			do {
4279 				ret = btrfs_truncate_inode_items(trans,
4280 							 root->log_root,
4281 							 &inode->vfs_inode,
4282 							 truncate_offset,
4283 							 BTRFS_EXTENT_DATA_KEY);
4284 			} while (ret == -EAGAIN);
4285 			if (ret)
4286 				goto out;
4287 			dropped_extents = true;
4288 		}
4289 		if (ins_nr == 0)
4290 			start_slot = slot;
4291 		ins_nr++;
4292 		path->slots[0]++;
4293 		if (!dst_path) {
4294 			dst_path = btrfs_alloc_path();
4295 			if (!dst_path) {
4296 				ret = -ENOMEM;
4297 				goto out;
4298 			}
4299 		}
4300 	}
4301 	if (ins_nr > 0) {
4302 		ret = copy_items(trans, inode, dst_path, path,
4303 				 start_slot, ins_nr, 1, 0);
4304 		if (ret > 0)
4305 			ret = 0;
4306 	}
4307 out:
4308 	btrfs_release_path(path);
4309 	btrfs_free_path(dst_path);
4310 	return ret;
4311 }
4312 
btrfs_log_changed_extents(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path,struct btrfs_log_ctx * ctx,const u64 start,const u64 end)4313 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4314 				     struct btrfs_root *root,
4315 				     struct btrfs_inode *inode,
4316 				     struct btrfs_path *path,
4317 				     struct btrfs_log_ctx *ctx,
4318 				     const u64 start,
4319 				     const u64 end)
4320 {
4321 	struct extent_map *em, *n;
4322 	struct list_head extents;
4323 	struct extent_map_tree *tree = &inode->extent_tree;
4324 	u64 logged_start, logged_end;
4325 	u64 test_gen;
4326 	int ret = 0;
4327 	int num = 0;
4328 
4329 	INIT_LIST_HEAD(&extents);
4330 
4331 	write_lock(&tree->lock);
4332 	test_gen = root->fs_info->last_trans_committed;
4333 	logged_start = start;
4334 	logged_end = end;
4335 
4336 	list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4337 		/*
4338 		 * Skip extents outside our logging range. It's important to do
4339 		 * it for correctness because if we don't ignore them, we may
4340 		 * log them before their ordered extent completes, and therefore
4341 		 * we could log them without logging their respective checksums
4342 		 * (the checksum items are added to the csum tree at the very
4343 		 * end of btrfs_finish_ordered_io()). Also leave such extents
4344 		 * outside of our range in the list, since we may have another
4345 		 * ranged fsync in the near future that needs them. If an extent
4346 		 * outside our range corresponds to a hole, log it to avoid
4347 		 * leaving gaps between extents (fsck will complain when we are
4348 		 * not using the NO_HOLES feature).
4349 		 */
4350 		if ((em->start > end || em->start + em->len <= start) &&
4351 		    em->block_start != EXTENT_MAP_HOLE)
4352 			continue;
4353 
4354 		list_del_init(&em->list);
4355 		/*
4356 		 * Just an arbitrary number, this can be really CPU intensive
4357 		 * once we start getting a lot of extents, and really once we
4358 		 * have a bunch of extents we just want to commit since it will
4359 		 * be faster.
4360 		 */
4361 		if (++num > 32768) {
4362 			list_del_init(&tree->modified_extents);
4363 			ret = -EFBIG;
4364 			goto process;
4365 		}
4366 
4367 		if (em->generation <= test_gen)
4368 			continue;
4369 
4370 		/* We log prealloc extents beyond eof later. */
4371 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
4372 		    em->start >= i_size_read(&inode->vfs_inode))
4373 			continue;
4374 
4375 		if (em->start < logged_start)
4376 			logged_start = em->start;
4377 		if ((em->start + em->len - 1) > logged_end)
4378 			logged_end = em->start + em->len - 1;
4379 
4380 		/* Need a ref to keep it from getting evicted from cache */
4381 		refcount_inc(&em->refs);
4382 		set_bit(EXTENT_FLAG_LOGGING, &em->flags);
4383 		list_add_tail(&em->list, &extents);
4384 		num++;
4385 	}
4386 
4387 	list_sort(NULL, &extents, extent_cmp);
4388 process:
4389 	while (!list_empty(&extents)) {
4390 		em = list_entry(extents.next, struct extent_map, list);
4391 
4392 		list_del_init(&em->list);
4393 
4394 		/*
4395 		 * If we had an error we just need to delete everybody from our
4396 		 * private list.
4397 		 */
4398 		if (ret) {
4399 			clear_em_logging(tree, em);
4400 			free_extent_map(em);
4401 			continue;
4402 		}
4403 
4404 		write_unlock(&tree->lock);
4405 
4406 		ret = log_one_extent(trans, inode, root, em, path, ctx);
4407 		write_lock(&tree->lock);
4408 		clear_em_logging(tree, em);
4409 		free_extent_map(em);
4410 	}
4411 	WARN_ON(!list_empty(&extents));
4412 	write_unlock(&tree->lock);
4413 
4414 	btrfs_release_path(path);
4415 	if (!ret)
4416 		ret = btrfs_log_prealloc_extents(trans, inode, path);
4417 
4418 	return ret;
4419 }
4420 
logged_inode_size(struct btrfs_root * log,struct btrfs_inode * inode,struct btrfs_path * path,u64 * size_ret)4421 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
4422 			     struct btrfs_path *path, u64 *size_ret)
4423 {
4424 	struct btrfs_key key;
4425 	int ret;
4426 
4427 	key.objectid = btrfs_ino(inode);
4428 	key.type = BTRFS_INODE_ITEM_KEY;
4429 	key.offset = 0;
4430 
4431 	ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4432 	if (ret < 0) {
4433 		return ret;
4434 	} else if (ret > 0) {
4435 		*size_ret = 0;
4436 	} else {
4437 		struct btrfs_inode_item *item;
4438 
4439 		item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4440 				      struct btrfs_inode_item);
4441 		*size_ret = btrfs_inode_size(path->nodes[0], item);
4442 		/*
4443 		 * If the in-memory inode's i_size is smaller then the inode
4444 		 * size stored in the btree, return the inode's i_size, so
4445 		 * that we get a correct inode size after replaying the log
4446 		 * when before a power failure we had a shrinking truncate
4447 		 * followed by addition of a new name (rename / new hard link).
4448 		 * Otherwise return the inode size from the btree, to avoid
4449 		 * data loss when replaying a log due to previously doing a
4450 		 * write that expands the inode's size and logging a new name
4451 		 * immediately after.
4452 		 */
4453 		if (*size_ret > inode->vfs_inode.i_size)
4454 			*size_ret = inode->vfs_inode.i_size;
4455 	}
4456 
4457 	btrfs_release_path(path);
4458 	return 0;
4459 }
4460 
4461 /*
4462  * At the moment we always log all xattrs. This is to figure out at log replay
4463  * time which xattrs must have their deletion replayed. If a xattr is missing
4464  * in the log tree and exists in the fs/subvol tree, we delete it. This is
4465  * because if a xattr is deleted, the inode is fsynced and a power failure
4466  * happens, causing the log to be replayed the next time the fs is mounted,
4467  * we want the xattr to not exist anymore (same behaviour as other filesystems
4468  * with a journal, ext3/4, xfs, f2fs, etc).
4469  */
btrfs_log_all_xattrs(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path,struct btrfs_path * dst_path)4470 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
4471 				struct btrfs_root *root,
4472 				struct btrfs_inode *inode,
4473 				struct btrfs_path *path,
4474 				struct btrfs_path *dst_path)
4475 {
4476 	int ret;
4477 	struct btrfs_key key;
4478 	const u64 ino = btrfs_ino(inode);
4479 	int ins_nr = 0;
4480 	int start_slot = 0;
4481 
4482 	key.objectid = ino;
4483 	key.type = BTRFS_XATTR_ITEM_KEY;
4484 	key.offset = 0;
4485 
4486 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4487 	if (ret < 0)
4488 		return ret;
4489 
4490 	while (true) {
4491 		int slot = path->slots[0];
4492 		struct extent_buffer *leaf = path->nodes[0];
4493 		int nritems = btrfs_header_nritems(leaf);
4494 
4495 		if (slot >= nritems) {
4496 			if (ins_nr > 0) {
4497 				ret = copy_items(trans, inode, dst_path, path,
4498 						 start_slot, ins_nr, 1, 0);
4499 				if (ret < 0)
4500 					return ret;
4501 				ins_nr = 0;
4502 			}
4503 			ret = btrfs_next_leaf(root, path);
4504 			if (ret < 0)
4505 				return ret;
4506 			else if (ret > 0)
4507 				break;
4508 			continue;
4509 		}
4510 
4511 		btrfs_item_key_to_cpu(leaf, &key, slot);
4512 		if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
4513 			break;
4514 
4515 		if (ins_nr == 0)
4516 			start_slot = slot;
4517 		ins_nr++;
4518 		path->slots[0]++;
4519 		cond_resched();
4520 	}
4521 	if (ins_nr > 0) {
4522 		ret = copy_items(trans, inode, dst_path, path,
4523 				 start_slot, ins_nr, 1, 0);
4524 		if (ret < 0)
4525 			return ret;
4526 	}
4527 
4528 	return 0;
4529 }
4530 
4531 /*
4532  * When using the NO_HOLES feature if we punched a hole that causes the
4533  * deletion of entire leafs or all the extent items of the first leaf (the one
4534  * that contains the inode item and references) we may end up not processing
4535  * any extents, because there are no leafs with a generation matching the
4536  * current transaction that have extent items for our inode. So we need to find
4537  * if any holes exist and then log them. We also need to log holes after any
4538  * truncate operation that changes the inode's size.
4539  */
btrfs_log_holes(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * inode,struct btrfs_path * path)4540 static int btrfs_log_holes(struct btrfs_trans_handle *trans,
4541 			   struct btrfs_root *root,
4542 			   struct btrfs_inode *inode,
4543 			   struct btrfs_path *path)
4544 {
4545 	struct btrfs_fs_info *fs_info = root->fs_info;
4546 	struct btrfs_key key;
4547 	const u64 ino = btrfs_ino(inode);
4548 	const u64 i_size = i_size_read(&inode->vfs_inode);
4549 	u64 prev_extent_end = 0;
4550 	int ret;
4551 
4552 	if (!btrfs_fs_incompat(fs_info, NO_HOLES) || i_size == 0)
4553 		return 0;
4554 
4555 	key.objectid = ino;
4556 	key.type = BTRFS_EXTENT_DATA_KEY;
4557 	key.offset = 0;
4558 
4559 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4560 	if (ret < 0)
4561 		return ret;
4562 
4563 	while (true) {
4564 		struct btrfs_file_extent_item *extent;
4565 		struct extent_buffer *leaf = path->nodes[0];
4566 		u64 len;
4567 
4568 		if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
4569 			ret = btrfs_next_leaf(root, path);
4570 			if (ret < 0)
4571 				return ret;
4572 			if (ret > 0) {
4573 				ret = 0;
4574 				break;
4575 			}
4576 			leaf = path->nodes[0];
4577 		}
4578 
4579 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4580 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
4581 			break;
4582 
4583 		/* We have a hole, log it. */
4584 		if (prev_extent_end < key.offset) {
4585 			const u64 hole_len = key.offset - prev_extent_end;
4586 
4587 			/*
4588 			 * Release the path to avoid deadlocks with other code
4589 			 * paths that search the root while holding locks on
4590 			 * leafs from the log root.
4591 			 */
4592 			btrfs_release_path(path);
4593 			ret = btrfs_insert_file_extent(trans, root->log_root,
4594 						       ino, prev_extent_end, 0,
4595 						       0, hole_len, 0, hole_len,
4596 						       0, 0, 0);
4597 			if (ret < 0)
4598 				return ret;
4599 
4600 			/*
4601 			 * Search for the same key again in the root. Since it's
4602 			 * an extent item and we are holding the inode lock, the
4603 			 * key must still exist. If it doesn't just emit warning
4604 			 * and return an error to fall back to a transaction
4605 			 * commit.
4606 			 */
4607 			ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4608 			if (ret < 0)
4609 				return ret;
4610 			if (WARN_ON(ret > 0))
4611 				return -ENOENT;
4612 			leaf = path->nodes[0];
4613 		}
4614 
4615 		extent = btrfs_item_ptr(leaf, path->slots[0],
4616 					struct btrfs_file_extent_item);
4617 		if (btrfs_file_extent_type(leaf, extent) ==
4618 		    BTRFS_FILE_EXTENT_INLINE) {
4619 			len = btrfs_file_extent_ram_bytes(leaf, extent);
4620 			prev_extent_end = ALIGN(key.offset + len,
4621 						fs_info->sectorsize);
4622 		} else {
4623 			len = btrfs_file_extent_num_bytes(leaf, extent);
4624 			prev_extent_end = key.offset + len;
4625 		}
4626 
4627 		path->slots[0]++;
4628 		cond_resched();
4629 	}
4630 
4631 	if (prev_extent_end < i_size) {
4632 		u64 hole_len;
4633 
4634 		btrfs_release_path(path);
4635 		hole_len = ALIGN(i_size - prev_extent_end, fs_info->sectorsize);
4636 		ret = btrfs_insert_file_extent(trans, root->log_root,
4637 					       ino, prev_extent_end, 0, 0,
4638 					       hole_len, 0, hole_len,
4639 					       0, 0, 0);
4640 		if (ret < 0)
4641 			return ret;
4642 	}
4643 
4644 	return 0;
4645 }
4646 
4647 /*
4648  * When we are logging a new inode X, check if it doesn't have a reference that
4649  * matches the reference from some other inode Y created in a past transaction
4650  * and that was renamed in the current transaction. If we don't do this, then at
4651  * log replay time we can lose inode Y (and all its files if it's a directory):
4652  *
4653  * mkdir /mnt/x
4654  * echo "hello world" > /mnt/x/foobar
4655  * sync
4656  * mv /mnt/x /mnt/y
4657  * mkdir /mnt/x                 # or touch /mnt/x
4658  * xfs_io -c fsync /mnt/x
4659  * <power fail>
4660  * mount fs, trigger log replay
4661  *
4662  * After the log replay procedure, we would lose the first directory and all its
4663  * files (file foobar).
4664  * For the case where inode Y is not a directory we simply end up losing it:
4665  *
4666  * echo "123" > /mnt/foo
4667  * sync
4668  * mv /mnt/foo /mnt/bar
4669  * echo "abc" > /mnt/foo
4670  * xfs_io -c fsync /mnt/foo
4671  * <power fail>
4672  *
4673  * We also need this for cases where a snapshot entry is replaced by some other
4674  * entry (file or directory) otherwise we end up with an unreplayable log due to
4675  * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
4676  * if it were a regular entry:
4677  *
4678  * mkdir /mnt/x
4679  * btrfs subvolume snapshot /mnt /mnt/x/snap
4680  * btrfs subvolume delete /mnt/x/snap
4681  * rmdir /mnt/x
4682  * mkdir /mnt/x
4683  * fsync /mnt/x or fsync some new file inside it
4684  * <power fail>
4685  *
4686  * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
4687  * the same transaction.
4688  */
btrfs_check_ref_name_override(struct extent_buffer * eb,const int slot,const struct btrfs_key * key,struct btrfs_inode * inode,u64 * other_ino)4689 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
4690 					 const int slot,
4691 					 const struct btrfs_key *key,
4692 					 struct btrfs_inode *inode,
4693 					 u64 *other_ino)
4694 {
4695 	int ret;
4696 	struct btrfs_path *search_path;
4697 	char *name = NULL;
4698 	u32 name_len = 0;
4699 	u32 item_size = btrfs_item_size_nr(eb, slot);
4700 	u32 cur_offset = 0;
4701 	unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
4702 
4703 	search_path = btrfs_alloc_path();
4704 	if (!search_path)
4705 		return -ENOMEM;
4706 	search_path->search_commit_root = 1;
4707 	search_path->skip_locking = 1;
4708 
4709 	while (cur_offset < item_size) {
4710 		u64 parent;
4711 		u32 this_name_len;
4712 		u32 this_len;
4713 		unsigned long name_ptr;
4714 		struct btrfs_dir_item *di;
4715 
4716 		if (key->type == BTRFS_INODE_REF_KEY) {
4717 			struct btrfs_inode_ref *iref;
4718 
4719 			iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
4720 			parent = key->offset;
4721 			this_name_len = btrfs_inode_ref_name_len(eb, iref);
4722 			name_ptr = (unsigned long)(iref + 1);
4723 			this_len = sizeof(*iref) + this_name_len;
4724 		} else {
4725 			struct btrfs_inode_extref *extref;
4726 
4727 			extref = (struct btrfs_inode_extref *)(ptr +
4728 							       cur_offset);
4729 			parent = btrfs_inode_extref_parent(eb, extref);
4730 			this_name_len = btrfs_inode_extref_name_len(eb, extref);
4731 			name_ptr = (unsigned long)&extref->name;
4732 			this_len = sizeof(*extref) + this_name_len;
4733 		}
4734 
4735 		if (this_name_len > name_len) {
4736 			char *new_name;
4737 
4738 			new_name = krealloc(name, this_name_len, GFP_NOFS);
4739 			if (!new_name) {
4740 				ret = -ENOMEM;
4741 				goto out;
4742 			}
4743 			name_len = this_name_len;
4744 			name = new_name;
4745 		}
4746 
4747 		read_extent_buffer(eb, name, name_ptr, this_name_len);
4748 		di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
4749 				parent, name, this_name_len, 0);
4750 		if (di && !IS_ERR(di)) {
4751 			struct btrfs_key di_key;
4752 
4753 			btrfs_dir_item_key_to_cpu(search_path->nodes[0],
4754 						  di, &di_key);
4755 			if (di_key.type == BTRFS_INODE_ITEM_KEY) {
4756 				ret = 1;
4757 				*other_ino = di_key.objectid;
4758 			} else {
4759 				ret = -EAGAIN;
4760 			}
4761 			goto out;
4762 		} else if (IS_ERR(di)) {
4763 			ret = PTR_ERR(di);
4764 			goto out;
4765 		}
4766 		btrfs_release_path(search_path);
4767 
4768 		cur_offset += this_len;
4769 	}
4770 	ret = 0;
4771 out:
4772 	btrfs_free_path(search_path);
4773 	kfree(name);
4774 	return ret;
4775 }
4776 
4777 /* log a single inode in the tree log.
4778  * At least one parent directory for this inode must exist in the tree
4779  * or be logged already.
4780  *
4781  * Any items from this inode changed by the current transaction are copied
4782  * to the log tree.  An extra reference is taken on any extents in this
4783  * file, allowing us to avoid a whole pile of corner cases around logging
4784  * blocks that have been removed from the tree.
4785  *
4786  * See LOG_INODE_ALL and related defines for a description of what inode_only
4787  * does.
4788  *
4789  * This handles both files and directories.
4790  */
btrfs_log_inode(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * inode,int inode_only,const loff_t start,const loff_t end,struct btrfs_log_ctx * ctx)4791 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
4792 			   struct btrfs_root *root, struct btrfs_inode *inode,
4793 			   int inode_only,
4794 			   const loff_t start,
4795 			   const loff_t end,
4796 			   struct btrfs_log_ctx *ctx)
4797 {
4798 	struct btrfs_fs_info *fs_info = root->fs_info;
4799 	struct btrfs_path *path;
4800 	struct btrfs_path *dst_path;
4801 	struct btrfs_key min_key;
4802 	struct btrfs_key max_key;
4803 	struct btrfs_root *log = root->log_root;
4804 	int err = 0;
4805 	int ret;
4806 	int nritems;
4807 	int ins_start_slot = 0;
4808 	int ins_nr;
4809 	bool fast_search = false;
4810 	u64 ino = btrfs_ino(inode);
4811 	struct extent_map_tree *em_tree = &inode->extent_tree;
4812 	u64 logged_isize = 0;
4813 	bool need_log_inode_item = true;
4814 	bool xattrs_logged = false;
4815 
4816 	path = btrfs_alloc_path();
4817 	if (!path)
4818 		return -ENOMEM;
4819 	dst_path = btrfs_alloc_path();
4820 	if (!dst_path) {
4821 		btrfs_free_path(path);
4822 		return -ENOMEM;
4823 	}
4824 
4825 	min_key.objectid = ino;
4826 	min_key.type = BTRFS_INODE_ITEM_KEY;
4827 	min_key.offset = 0;
4828 
4829 	max_key.objectid = ino;
4830 
4831 
4832 	/* today the code can only do partial logging of directories */
4833 	if (S_ISDIR(inode->vfs_inode.i_mode) ||
4834 	    (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4835 		       &inode->runtime_flags) &&
4836 	     inode_only >= LOG_INODE_EXISTS))
4837 		max_key.type = BTRFS_XATTR_ITEM_KEY;
4838 	else
4839 		max_key.type = (u8)-1;
4840 	max_key.offset = (u64)-1;
4841 
4842 	/*
4843 	 * Only run delayed items if we are a dir or a new file.
4844 	 * Otherwise commit the delayed inode only, which is needed in
4845 	 * order for the log replay code to mark inodes for link count
4846 	 * fixup (create temporary BTRFS_TREE_LOG_FIXUP_OBJECTID items).
4847 	 */
4848 	if (S_ISDIR(inode->vfs_inode.i_mode) ||
4849 	    inode->generation > fs_info->last_trans_committed)
4850 		ret = btrfs_commit_inode_delayed_items(trans, inode);
4851 	else
4852 		ret = btrfs_commit_inode_delayed_inode(inode);
4853 
4854 	if (ret) {
4855 		btrfs_free_path(path);
4856 		btrfs_free_path(dst_path);
4857 		return ret;
4858 	}
4859 
4860 	if (inode_only == LOG_OTHER_INODE) {
4861 		inode_only = LOG_INODE_EXISTS;
4862 		mutex_lock_nested(&inode->log_mutex, SINGLE_DEPTH_NESTING);
4863 	} else {
4864 		mutex_lock(&inode->log_mutex);
4865 	}
4866 
4867 	/*
4868 	 * a brute force approach to making sure we get the most uptodate
4869 	 * copies of everything.
4870 	 */
4871 	if (S_ISDIR(inode->vfs_inode.i_mode)) {
4872 		int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
4873 
4874 		if (inode_only == LOG_INODE_EXISTS)
4875 			max_key_type = BTRFS_XATTR_ITEM_KEY;
4876 		ret = drop_objectid_items(trans, log, path, ino, max_key_type);
4877 	} else {
4878 		if (inode_only == LOG_INODE_EXISTS) {
4879 			/*
4880 			 * Make sure the new inode item we write to the log has
4881 			 * the same isize as the current one (if it exists).
4882 			 * This is necessary to prevent data loss after log
4883 			 * replay, and also to prevent doing a wrong expanding
4884 			 * truncate - for e.g. create file, write 4K into offset
4885 			 * 0, fsync, write 4K into offset 4096, add hard link,
4886 			 * fsync some other file (to sync log), power fail - if
4887 			 * we use the inode's current i_size, after log replay
4888 			 * we get a 8Kb file, with the last 4Kb extent as a hole
4889 			 * (zeroes), as if an expanding truncate happened,
4890 			 * instead of getting a file of 4Kb only.
4891 			 */
4892 			err = logged_inode_size(log, inode, path, &logged_isize);
4893 			if (err)
4894 				goto out_unlock;
4895 		}
4896 		if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4897 			     &inode->runtime_flags)) {
4898 			if (inode_only == LOG_INODE_EXISTS) {
4899 				max_key.type = BTRFS_XATTR_ITEM_KEY;
4900 				ret = drop_objectid_items(trans, log, path, ino,
4901 							  max_key.type);
4902 			} else {
4903 				clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4904 					  &inode->runtime_flags);
4905 				clear_bit(BTRFS_INODE_COPY_EVERYTHING,
4906 					  &inode->runtime_flags);
4907 				while(1) {
4908 					ret = btrfs_truncate_inode_items(trans,
4909 						log, &inode->vfs_inode, 0, 0);
4910 					if (ret != -EAGAIN)
4911 						break;
4912 				}
4913 			}
4914 		} else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
4915 					      &inode->runtime_flags) ||
4916 			   inode_only == LOG_INODE_EXISTS) {
4917 			if (inode_only == LOG_INODE_ALL)
4918 				fast_search = true;
4919 			max_key.type = BTRFS_XATTR_ITEM_KEY;
4920 			ret = drop_objectid_items(trans, log, path, ino,
4921 						  max_key.type);
4922 		} else {
4923 			if (inode_only == LOG_INODE_ALL)
4924 				fast_search = true;
4925 			goto log_extents;
4926 		}
4927 
4928 	}
4929 	if (ret) {
4930 		err = ret;
4931 		goto out_unlock;
4932 	}
4933 
4934 	while (1) {
4935 		ins_nr = 0;
4936 		ret = btrfs_search_forward(root, &min_key,
4937 					   path, trans->transid);
4938 		if (ret < 0) {
4939 			err = ret;
4940 			goto out_unlock;
4941 		}
4942 		if (ret != 0)
4943 			break;
4944 again:
4945 		/* note, ins_nr might be > 0 here, cleanup outside the loop */
4946 		if (min_key.objectid != ino)
4947 			break;
4948 		if (min_key.type > max_key.type)
4949 			break;
4950 
4951 		if (min_key.type == BTRFS_INODE_ITEM_KEY)
4952 			need_log_inode_item = false;
4953 
4954 		if ((min_key.type == BTRFS_INODE_REF_KEY ||
4955 		     min_key.type == BTRFS_INODE_EXTREF_KEY) &&
4956 		    inode->generation == trans->transid) {
4957 			u64 other_ino = 0;
4958 
4959 			ret = btrfs_check_ref_name_override(path->nodes[0],
4960 					path->slots[0], &min_key, inode,
4961 					&other_ino);
4962 			if (ret < 0) {
4963 				err = ret;
4964 				goto out_unlock;
4965 			} else if (ret > 0 && ctx &&
4966 				   other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
4967 				struct btrfs_key inode_key;
4968 				struct inode *other_inode;
4969 
4970 				if (ins_nr > 0) {
4971 					ins_nr++;
4972 				} else {
4973 					ins_nr = 1;
4974 					ins_start_slot = path->slots[0];
4975 				}
4976 				ret = copy_items(trans, inode, dst_path, path,
4977 						 ins_start_slot,
4978 						 ins_nr, inode_only,
4979 						 logged_isize);
4980 				if (ret < 0) {
4981 					err = ret;
4982 					goto out_unlock;
4983 				}
4984 				ins_nr = 0;
4985 				btrfs_release_path(path);
4986 				inode_key.objectid = other_ino;
4987 				inode_key.type = BTRFS_INODE_ITEM_KEY;
4988 				inode_key.offset = 0;
4989 				other_inode = btrfs_iget(fs_info->sb,
4990 							 &inode_key, root,
4991 							 NULL);
4992 				/*
4993 				 * If the other inode that had a conflicting dir
4994 				 * entry was deleted in the current transaction,
4995 				 * we don't need to do more work nor fallback to
4996 				 * a transaction commit.
4997 				 */
4998 				if (other_inode == ERR_PTR(-ENOENT)) {
4999 					goto next_key;
5000 				} else if (IS_ERR(other_inode)) {
5001 					err = PTR_ERR(other_inode);
5002 					goto out_unlock;
5003 				}
5004 				/*
5005 				 * We are safe logging the other inode without
5006 				 * acquiring its i_mutex as long as we log with
5007 				 * the LOG_INODE_EXISTS mode. We're safe against
5008 				 * concurrent renames of the other inode as well
5009 				 * because during a rename we pin the log and
5010 				 * update the log with the new name before we
5011 				 * unpin it.
5012 				 */
5013 				err = btrfs_log_inode(trans, root,
5014 						BTRFS_I(other_inode),
5015 						LOG_OTHER_INODE, 0, LLONG_MAX,
5016 						ctx);
5017 				btrfs_add_delayed_iput(other_inode);
5018 				if (err)
5019 					goto out_unlock;
5020 				else
5021 					goto next_key;
5022 			}
5023 		}
5024 
5025 		/* Skip xattrs, we log them later with btrfs_log_all_xattrs() */
5026 		if (min_key.type == BTRFS_XATTR_ITEM_KEY) {
5027 			if (ins_nr == 0)
5028 				goto next_slot;
5029 			ret = copy_items(trans, inode, dst_path, path,
5030 					 ins_start_slot,
5031 					 ins_nr, inode_only, logged_isize);
5032 			if (ret < 0) {
5033 				err = ret;
5034 				goto out_unlock;
5035 			}
5036 			ins_nr = 0;
5037 			goto next_slot;
5038 		}
5039 
5040 		if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5041 			ins_nr++;
5042 			goto next_slot;
5043 		} else if (!ins_nr) {
5044 			ins_start_slot = path->slots[0];
5045 			ins_nr = 1;
5046 			goto next_slot;
5047 		}
5048 
5049 		ret = copy_items(trans, inode, dst_path, path,
5050 				 ins_start_slot, ins_nr, inode_only,
5051 				 logged_isize);
5052 		if (ret < 0) {
5053 			err = ret;
5054 			goto out_unlock;
5055 		}
5056 		ins_nr = 1;
5057 		ins_start_slot = path->slots[0];
5058 next_slot:
5059 
5060 		nritems = btrfs_header_nritems(path->nodes[0]);
5061 		path->slots[0]++;
5062 		if (path->slots[0] < nritems) {
5063 			btrfs_item_key_to_cpu(path->nodes[0], &min_key,
5064 					      path->slots[0]);
5065 			goto again;
5066 		}
5067 		if (ins_nr) {
5068 			ret = copy_items(trans, inode, dst_path, path,
5069 					 ins_start_slot,
5070 					 ins_nr, inode_only, logged_isize);
5071 			if (ret < 0) {
5072 				err = ret;
5073 				goto out_unlock;
5074 			}
5075 			ins_nr = 0;
5076 		}
5077 		btrfs_release_path(path);
5078 next_key:
5079 		if (min_key.offset < (u64)-1) {
5080 			min_key.offset++;
5081 		} else if (min_key.type < max_key.type) {
5082 			min_key.type++;
5083 			min_key.offset = 0;
5084 		} else {
5085 			break;
5086 		}
5087 	}
5088 	if (ins_nr) {
5089 		ret = copy_items(trans, inode, dst_path, path,
5090 				 ins_start_slot, ins_nr, inode_only,
5091 				 logged_isize);
5092 		if (ret < 0) {
5093 			err = ret;
5094 			goto out_unlock;
5095 		}
5096 		ins_nr = 0;
5097 	}
5098 
5099 	btrfs_release_path(path);
5100 	btrfs_release_path(dst_path);
5101 	err = btrfs_log_all_xattrs(trans, root, inode, path, dst_path);
5102 	if (err)
5103 		goto out_unlock;
5104 	xattrs_logged = true;
5105 	if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
5106 		btrfs_release_path(path);
5107 		btrfs_release_path(dst_path);
5108 		err = btrfs_log_holes(trans, root, inode, path);
5109 		if (err)
5110 			goto out_unlock;
5111 	}
5112 log_extents:
5113 	btrfs_release_path(path);
5114 	btrfs_release_path(dst_path);
5115 	if (need_log_inode_item) {
5116 		err = log_inode_item(trans, log, dst_path, inode);
5117 		if (!err && !xattrs_logged) {
5118 			err = btrfs_log_all_xattrs(trans, root, inode, path,
5119 						   dst_path);
5120 			btrfs_release_path(path);
5121 		}
5122 		if (err)
5123 			goto out_unlock;
5124 	}
5125 	if (fast_search) {
5126 		ret = btrfs_log_changed_extents(trans, root, inode, dst_path,
5127 						ctx, start, end);
5128 		if (ret) {
5129 			err = ret;
5130 			goto out_unlock;
5131 		}
5132 	} else if (inode_only == LOG_INODE_ALL) {
5133 		struct extent_map *em, *n;
5134 
5135 		write_lock(&em_tree->lock);
5136 		/*
5137 		 * We can't just remove every em if we're called for a ranged
5138 		 * fsync - that is, one that doesn't cover the whole possible
5139 		 * file range (0 to LLONG_MAX). This is because we can have
5140 		 * em's that fall outside the range we're logging and therefore
5141 		 * their ordered operations haven't completed yet
5142 		 * (btrfs_finish_ordered_io() not invoked yet). This means we
5143 		 * didn't get their respective file extent item in the fs/subvol
5144 		 * tree yet, and need to let the next fast fsync (one which
5145 		 * consults the list of modified extent maps) find the em so
5146 		 * that it logs a matching file extent item and waits for the
5147 		 * respective ordered operation to complete (if it's still
5148 		 * running).
5149 		 *
5150 		 * Removing every em outside the range we're logging would make
5151 		 * the next fast fsync not log their matching file extent items,
5152 		 * therefore making us lose data after a log replay.
5153 		 */
5154 		list_for_each_entry_safe(em, n, &em_tree->modified_extents,
5155 					 list) {
5156 			const u64 mod_end = em->mod_start + em->mod_len - 1;
5157 
5158 			if (em->mod_start >= start && mod_end <= end)
5159 				list_del_init(&em->list);
5160 		}
5161 		write_unlock(&em_tree->lock);
5162 	}
5163 
5164 	if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->vfs_inode.i_mode)) {
5165 		ret = log_directory_changes(trans, root, inode, path, dst_path,
5166 					ctx);
5167 		if (ret) {
5168 			err = ret;
5169 			goto out_unlock;
5170 		}
5171 	}
5172 
5173 	/*
5174 	 * Don't update last_log_commit if we logged that an inode exists after
5175 	 * it was loaded to memory (full_sync bit set).
5176 	 * This is to prevent data loss when we do a write to the inode, then
5177 	 * the inode gets evicted after all delalloc was flushed, then we log
5178 	 * it exists (due to a rename for example) and then fsync it. This last
5179 	 * fsync would do nothing (not logging the extents previously written).
5180 	 */
5181 	spin_lock(&inode->lock);
5182 	inode->logged_trans = trans->transid;
5183 	if (inode_only != LOG_INODE_EXISTS ||
5184 	    !test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags))
5185 		inode->last_log_commit = inode->last_sub_trans;
5186 	spin_unlock(&inode->lock);
5187 out_unlock:
5188 	mutex_unlock(&inode->log_mutex);
5189 
5190 	btrfs_free_path(path);
5191 	btrfs_free_path(dst_path);
5192 	return err;
5193 }
5194 
5195 /*
5196  * Check if we must fallback to a transaction commit when logging an inode.
5197  * This must be called after logging the inode and is used only in the context
5198  * when fsyncing an inode requires the need to log some other inode - in which
5199  * case we can't lock the i_mutex of each other inode we need to log as that
5200  * can lead to deadlocks with concurrent fsync against other inodes (as we can
5201  * log inodes up or down in the hierarchy) or rename operations for example. So
5202  * we take the log_mutex of the inode after we have logged it and then check for
5203  * its last_unlink_trans value - this is safe because any task setting
5204  * last_unlink_trans must take the log_mutex and it must do this before it does
5205  * the actual unlink operation, so if we do this check before a concurrent task
5206  * sets last_unlink_trans it means we've logged a consistent version/state of
5207  * all the inode items, otherwise we are not sure and must do a transaction
5208  * commit (the concurrent task might have only updated last_unlink_trans before
5209  * we logged the inode or it might have also done the unlink).
5210  */
btrfs_must_commit_transaction(struct btrfs_trans_handle * trans,struct btrfs_inode * inode)5211 static bool btrfs_must_commit_transaction(struct btrfs_trans_handle *trans,
5212 					  struct btrfs_inode *inode)
5213 {
5214 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5215 	bool ret = false;
5216 
5217 	mutex_lock(&inode->log_mutex);
5218 	if (inode->last_unlink_trans > fs_info->last_trans_committed) {
5219 		/*
5220 		 * Make sure any commits to the log are forced to be full
5221 		 * commits.
5222 		 */
5223 		btrfs_set_log_full_commit(fs_info, trans);
5224 		ret = true;
5225 	}
5226 	mutex_unlock(&inode->log_mutex);
5227 
5228 	return ret;
5229 }
5230 
5231 /*
5232  * follow the dentry parent pointers up the chain and see if any
5233  * of the directories in it require a full commit before they can
5234  * be logged.  Returns zero if nothing special needs to be done or 1 if
5235  * a full commit is required.
5236  */
check_parent_dirs_for_sync(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct dentry * parent,struct super_block * sb,u64 last_committed)5237 static noinline int check_parent_dirs_for_sync(struct btrfs_trans_handle *trans,
5238 					       struct btrfs_inode *inode,
5239 					       struct dentry *parent,
5240 					       struct super_block *sb,
5241 					       u64 last_committed)
5242 {
5243 	int ret = 0;
5244 	struct dentry *old_parent = NULL;
5245 
5246 	/*
5247 	 * for regular files, if its inode is already on disk, we don't
5248 	 * have to worry about the parents at all.  This is because
5249 	 * we can use the last_unlink_trans field to record renames
5250 	 * and other fun in this file.
5251 	 */
5252 	if (S_ISREG(inode->vfs_inode.i_mode) &&
5253 	    inode->generation <= last_committed &&
5254 	    inode->last_unlink_trans <= last_committed)
5255 		goto out;
5256 
5257 	if (!S_ISDIR(inode->vfs_inode.i_mode)) {
5258 		if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5259 			goto out;
5260 		inode = BTRFS_I(d_inode(parent));
5261 	}
5262 
5263 	while (1) {
5264 		if (btrfs_must_commit_transaction(trans, inode)) {
5265 			ret = 1;
5266 			break;
5267 		}
5268 
5269 		if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5270 			break;
5271 
5272 		if (IS_ROOT(parent)) {
5273 			inode = BTRFS_I(d_inode(parent));
5274 			if (btrfs_must_commit_transaction(trans, inode))
5275 				ret = 1;
5276 			break;
5277 		}
5278 
5279 		parent = dget_parent(parent);
5280 		dput(old_parent);
5281 		old_parent = parent;
5282 		inode = BTRFS_I(d_inode(parent));
5283 
5284 	}
5285 	dput(old_parent);
5286 out:
5287 	return ret;
5288 }
5289 
5290 struct btrfs_dir_list {
5291 	u64 ino;
5292 	struct list_head list;
5293 };
5294 
5295 /*
5296  * Log the inodes of the new dentries of a directory. See log_dir_items() for
5297  * details about the why it is needed.
5298  * This is a recursive operation - if an existing dentry corresponds to a
5299  * directory, that directory's new entries are logged too (same behaviour as
5300  * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5301  * the dentries point to we do not lock their i_mutex, otherwise lockdep
5302  * complains about the following circular lock dependency / possible deadlock:
5303  *
5304  *        CPU0                                        CPU1
5305  *        ----                                        ----
5306  * lock(&type->i_mutex_dir_key#3/2);
5307  *                                            lock(sb_internal#2);
5308  *                                            lock(&type->i_mutex_dir_key#3/2);
5309  * lock(&sb->s_type->i_mutex_key#14);
5310  *
5311  * Where sb_internal is the lock (a counter that works as a lock) acquired by
5312  * sb_start_intwrite() in btrfs_start_transaction().
5313  * Not locking i_mutex of the inodes is still safe because:
5314  *
5315  * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5316  *    that while logging the inode new references (names) are added or removed
5317  *    from the inode, leaving the logged inode item with a link count that does
5318  *    not match the number of logged inode reference items. This is fine because
5319  *    at log replay time we compute the real number of links and correct the
5320  *    link count in the inode item (see replay_one_buffer() and
5321  *    link_to_fixup_dir());
5322  *
5323  * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5324  *    while logging the inode's items new items with keys BTRFS_DIR_ITEM_KEY and
5325  *    BTRFS_DIR_INDEX_KEY are added to fs/subvol tree and the logged inode item
5326  *    has a size that doesn't match the sum of the lengths of all the logged
5327  *    names. This does not result in a problem because if a dir_item key is
5328  *    logged but its matching dir_index key is not logged, at log replay time we
5329  *    don't use it to replay the respective name (see replay_one_name()). On the
5330  *    other hand if only the dir_index key ends up being logged, the respective
5331  *    name is added to the fs/subvol tree with both the dir_item and dir_index
5332  *    keys created (see replay_one_name()).
5333  *    The directory's inode item with a wrong i_size is not a problem as well,
5334  *    since we don't use it at log replay time to set the i_size in the inode
5335  *    item of the fs/subvol tree (see overwrite_item()).
5336  */
log_new_dir_dentries(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct btrfs_inode * start_inode,struct btrfs_log_ctx * ctx)5337 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5338 				struct btrfs_root *root,
5339 				struct btrfs_inode *start_inode,
5340 				struct btrfs_log_ctx *ctx)
5341 {
5342 	struct btrfs_fs_info *fs_info = root->fs_info;
5343 	struct btrfs_root *log = root->log_root;
5344 	struct btrfs_path *path;
5345 	LIST_HEAD(dir_list);
5346 	struct btrfs_dir_list *dir_elem;
5347 	int ret = 0;
5348 
5349 	path = btrfs_alloc_path();
5350 	if (!path)
5351 		return -ENOMEM;
5352 
5353 	dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5354 	if (!dir_elem) {
5355 		btrfs_free_path(path);
5356 		return -ENOMEM;
5357 	}
5358 	dir_elem->ino = btrfs_ino(start_inode);
5359 	list_add_tail(&dir_elem->list, &dir_list);
5360 
5361 	while (!list_empty(&dir_list)) {
5362 		struct extent_buffer *leaf;
5363 		struct btrfs_key min_key;
5364 		int nritems;
5365 		int i;
5366 
5367 		dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list,
5368 					    list);
5369 		if (ret)
5370 			goto next_dir_inode;
5371 
5372 		min_key.objectid = dir_elem->ino;
5373 		min_key.type = BTRFS_DIR_ITEM_KEY;
5374 		min_key.offset = 0;
5375 again:
5376 		btrfs_release_path(path);
5377 		ret = btrfs_search_forward(log, &min_key, path, trans->transid);
5378 		if (ret < 0) {
5379 			goto next_dir_inode;
5380 		} else if (ret > 0) {
5381 			ret = 0;
5382 			goto next_dir_inode;
5383 		}
5384 
5385 process_leaf:
5386 		leaf = path->nodes[0];
5387 		nritems = btrfs_header_nritems(leaf);
5388 		for (i = path->slots[0]; i < nritems; i++) {
5389 			struct btrfs_dir_item *di;
5390 			struct btrfs_key di_key;
5391 			struct inode *di_inode;
5392 			struct btrfs_dir_list *new_dir_elem;
5393 			int log_mode = LOG_INODE_EXISTS;
5394 			int type;
5395 
5396 			btrfs_item_key_to_cpu(leaf, &min_key, i);
5397 			if (min_key.objectid != dir_elem->ino ||
5398 			    min_key.type != BTRFS_DIR_ITEM_KEY)
5399 				goto next_dir_inode;
5400 
5401 			di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5402 			type = btrfs_dir_type(leaf, di);
5403 			if (btrfs_dir_transid(leaf, di) < trans->transid &&
5404 			    type != BTRFS_FT_DIR)
5405 				continue;
5406 			btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5407 			if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5408 				continue;
5409 
5410 			btrfs_release_path(path);
5411 			di_inode = btrfs_iget(fs_info->sb, &di_key, root, NULL);
5412 			if (IS_ERR(di_inode)) {
5413 				ret = PTR_ERR(di_inode);
5414 				goto next_dir_inode;
5415 			}
5416 
5417 			if (btrfs_inode_in_log(BTRFS_I(di_inode), trans->transid)) {
5418 				btrfs_add_delayed_iput(di_inode);
5419 				break;
5420 			}
5421 
5422 			ctx->log_new_dentries = false;
5423 			if (type == BTRFS_FT_DIR || type == BTRFS_FT_SYMLINK)
5424 				log_mode = LOG_INODE_ALL;
5425 			ret = btrfs_log_inode(trans, root, BTRFS_I(di_inode),
5426 					      log_mode, 0, LLONG_MAX, ctx);
5427 			if (!ret &&
5428 			    btrfs_must_commit_transaction(trans, BTRFS_I(di_inode)))
5429 				ret = 1;
5430 			btrfs_add_delayed_iput(di_inode);
5431 			if (ret)
5432 				goto next_dir_inode;
5433 			if (ctx->log_new_dentries) {
5434 				new_dir_elem = kmalloc(sizeof(*new_dir_elem),
5435 						       GFP_NOFS);
5436 				if (!new_dir_elem) {
5437 					ret = -ENOMEM;
5438 					goto next_dir_inode;
5439 				}
5440 				new_dir_elem->ino = di_key.objectid;
5441 				list_add_tail(&new_dir_elem->list, &dir_list);
5442 			}
5443 			break;
5444 		}
5445 		if (i == nritems) {
5446 			ret = btrfs_next_leaf(log, path);
5447 			if (ret < 0) {
5448 				goto next_dir_inode;
5449 			} else if (ret > 0) {
5450 				ret = 0;
5451 				goto next_dir_inode;
5452 			}
5453 			goto process_leaf;
5454 		}
5455 		if (min_key.offset < (u64)-1) {
5456 			min_key.offset++;
5457 			goto again;
5458 		}
5459 next_dir_inode:
5460 		list_del(&dir_elem->list);
5461 		kfree(dir_elem);
5462 	}
5463 
5464 	btrfs_free_path(path);
5465 	return ret;
5466 }
5467 
btrfs_log_all_parents(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_log_ctx * ctx)5468 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
5469 				 struct btrfs_inode *inode,
5470 				 struct btrfs_log_ctx *ctx)
5471 {
5472 	struct btrfs_fs_info *fs_info = trans->fs_info;
5473 	int ret;
5474 	struct btrfs_path *path;
5475 	struct btrfs_key key;
5476 	struct btrfs_root *root = inode->root;
5477 	const u64 ino = btrfs_ino(inode);
5478 
5479 	path = btrfs_alloc_path();
5480 	if (!path)
5481 		return -ENOMEM;
5482 	path->skip_locking = 1;
5483 	path->search_commit_root = 1;
5484 
5485 	key.objectid = ino;
5486 	key.type = BTRFS_INODE_REF_KEY;
5487 	key.offset = 0;
5488 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5489 	if (ret < 0)
5490 		goto out;
5491 
5492 	while (true) {
5493 		struct extent_buffer *leaf = path->nodes[0];
5494 		int slot = path->slots[0];
5495 		u32 cur_offset = 0;
5496 		u32 item_size;
5497 		unsigned long ptr;
5498 
5499 		if (slot >= btrfs_header_nritems(leaf)) {
5500 			ret = btrfs_next_leaf(root, path);
5501 			if (ret < 0)
5502 				goto out;
5503 			else if (ret > 0)
5504 				break;
5505 			continue;
5506 		}
5507 
5508 		btrfs_item_key_to_cpu(leaf, &key, slot);
5509 		/* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
5510 		if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
5511 			break;
5512 
5513 		item_size = btrfs_item_size_nr(leaf, slot);
5514 		ptr = btrfs_item_ptr_offset(leaf, slot);
5515 		while (cur_offset < item_size) {
5516 			struct btrfs_key inode_key;
5517 			struct inode *dir_inode;
5518 
5519 			inode_key.type = BTRFS_INODE_ITEM_KEY;
5520 			inode_key.offset = 0;
5521 
5522 			if (key.type == BTRFS_INODE_EXTREF_KEY) {
5523 				struct btrfs_inode_extref *extref;
5524 
5525 				extref = (struct btrfs_inode_extref *)
5526 					(ptr + cur_offset);
5527 				inode_key.objectid = btrfs_inode_extref_parent(
5528 					leaf, extref);
5529 				cur_offset += sizeof(*extref);
5530 				cur_offset += btrfs_inode_extref_name_len(leaf,
5531 					extref);
5532 			} else {
5533 				inode_key.objectid = key.offset;
5534 				cur_offset = item_size;
5535 			}
5536 
5537 			dir_inode = btrfs_iget(fs_info->sb, &inode_key,
5538 					       root, NULL);
5539 			/*
5540 			 * If the parent inode was deleted, return an error to
5541 			 * fallback to a transaction commit. This is to prevent
5542 			 * getting an inode that was moved from one parent A to
5543 			 * a parent B, got its former parent A deleted and then
5544 			 * it got fsync'ed, from existing at both parents after
5545 			 * a log replay (and the old parent still existing).
5546 			 * Example:
5547 			 *
5548 			 * mkdir /mnt/A
5549 			 * mkdir /mnt/B
5550 			 * touch /mnt/B/bar
5551 			 * sync
5552 			 * mv /mnt/B/bar /mnt/A/bar
5553 			 * mv -T /mnt/A /mnt/B
5554 			 * fsync /mnt/B/bar
5555 			 * <power fail>
5556 			 *
5557 			 * If we ignore the old parent B which got deleted,
5558 			 * after a log replay we would have file bar linked
5559 			 * at both parents and the old parent B would still
5560 			 * exist.
5561 			 */
5562 			if (IS_ERR(dir_inode)) {
5563 				ret = PTR_ERR(dir_inode);
5564 				goto out;
5565 			}
5566 
5567 			if (ctx)
5568 				ctx->log_new_dentries = false;
5569 			ret = btrfs_log_inode(trans, root, BTRFS_I(dir_inode),
5570 					      LOG_INODE_ALL, 0, LLONG_MAX, ctx);
5571 			if (!ret &&
5572 			    btrfs_must_commit_transaction(trans, BTRFS_I(dir_inode)))
5573 				ret = 1;
5574 			if (!ret && ctx && ctx->log_new_dentries)
5575 				ret = log_new_dir_dentries(trans, root,
5576 						   BTRFS_I(dir_inode), ctx);
5577 			btrfs_add_delayed_iput(dir_inode);
5578 			if (ret)
5579 				goto out;
5580 		}
5581 		path->slots[0]++;
5582 	}
5583 	ret = 0;
5584 out:
5585 	btrfs_free_path(path);
5586 	return ret;
5587 }
5588 
5589 /*
5590  * helper function around btrfs_log_inode to make sure newly created
5591  * parent directories also end up in the log.  A minimal inode and backref
5592  * only logging is done of any parent directories that are older than
5593  * the last committed transaction
5594  */
btrfs_log_inode_parent(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct dentry * parent,const loff_t start,const loff_t end,int inode_only,struct btrfs_log_ctx * ctx)5595 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
5596 				  struct btrfs_inode *inode,
5597 				  struct dentry *parent,
5598 				  const loff_t start,
5599 				  const loff_t end,
5600 				  int inode_only,
5601 				  struct btrfs_log_ctx *ctx)
5602 {
5603 	struct btrfs_root *root = inode->root;
5604 	struct btrfs_fs_info *fs_info = root->fs_info;
5605 	struct super_block *sb;
5606 	struct dentry *old_parent = NULL;
5607 	int ret = 0;
5608 	u64 last_committed = fs_info->last_trans_committed;
5609 	bool log_dentries = false;
5610 	struct btrfs_inode *orig_inode = inode;
5611 
5612 	sb = inode->vfs_inode.i_sb;
5613 
5614 	if (btrfs_test_opt(fs_info, NOTREELOG)) {
5615 		ret = 1;
5616 		goto end_no_trans;
5617 	}
5618 
5619 	/*
5620 	 * The prev transaction commit doesn't complete, we need do
5621 	 * full commit by ourselves.
5622 	 */
5623 	if (fs_info->last_trans_log_full_commit >
5624 	    fs_info->last_trans_committed) {
5625 		ret = 1;
5626 		goto end_no_trans;
5627 	}
5628 
5629 	if (btrfs_root_refs(&root->root_item) == 0) {
5630 		ret = 1;
5631 		goto end_no_trans;
5632 	}
5633 
5634 	ret = check_parent_dirs_for_sync(trans, inode, parent, sb,
5635 			last_committed);
5636 	if (ret)
5637 		goto end_no_trans;
5638 
5639 	/*
5640 	 * Skip already logged inodes or inodes corresponding to tmpfiles
5641 	 * (since logging them is pointless, a link count of 0 means they
5642 	 * will never be accessible).
5643 	 */
5644 	if (btrfs_inode_in_log(inode, trans->transid) ||
5645 	    inode->vfs_inode.i_nlink == 0) {
5646 		ret = BTRFS_NO_LOG_SYNC;
5647 		goto end_no_trans;
5648 	}
5649 
5650 	ret = start_log_trans(trans, root, ctx);
5651 	if (ret)
5652 		goto end_no_trans;
5653 
5654 	ret = btrfs_log_inode(trans, root, inode, inode_only, start, end, ctx);
5655 	if (ret)
5656 		goto end_trans;
5657 
5658 	/*
5659 	 * for regular files, if its inode is already on disk, we don't
5660 	 * have to worry about the parents at all.  This is because
5661 	 * we can use the last_unlink_trans field to record renames
5662 	 * and other fun in this file.
5663 	 */
5664 	if (S_ISREG(inode->vfs_inode.i_mode) &&
5665 	    inode->generation <= last_committed &&
5666 	    inode->last_unlink_trans <= last_committed) {
5667 		ret = 0;
5668 		goto end_trans;
5669 	}
5670 
5671 	if (S_ISDIR(inode->vfs_inode.i_mode) && ctx && ctx->log_new_dentries)
5672 		log_dentries = true;
5673 
5674 	/*
5675 	 * On unlink we must make sure all our current and old parent directory
5676 	 * inodes are fully logged. This is to prevent leaving dangling
5677 	 * directory index entries in directories that were our parents but are
5678 	 * not anymore. Not doing this results in old parent directory being
5679 	 * impossible to delete after log replay (rmdir will always fail with
5680 	 * error -ENOTEMPTY).
5681 	 *
5682 	 * Example 1:
5683 	 *
5684 	 * mkdir testdir
5685 	 * touch testdir/foo
5686 	 * ln testdir/foo testdir/bar
5687 	 * sync
5688 	 * unlink testdir/bar
5689 	 * xfs_io -c fsync testdir/foo
5690 	 * <power failure>
5691 	 * mount fs, triggers log replay
5692 	 *
5693 	 * If we don't log the parent directory (testdir), after log replay the
5694 	 * directory still has an entry pointing to the file inode using the bar
5695 	 * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
5696 	 * the file inode has a link count of 1.
5697 	 *
5698 	 * Example 2:
5699 	 *
5700 	 * mkdir testdir
5701 	 * touch foo
5702 	 * ln foo testdir/foo2
5703 	 * ln foo testdir/foo3
5704 	 * sync
5705 	 * unlink testdir/foo3
5706 	 * xfs_io -c fsync foo
5707 	 * <power failure>
5708 	 * mount fs, triggers log replay
5709 	 *
5710 	 * Similar as the first example, after log replay the parent directory
5711 	 * testdir still has an entry pointing to the inode file with name foo3
5712 	 * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
5713 	 * and has a link count of 2.
5714 	 */
5715 	if (inode->last_unlink_trans > last_committed) {
5716 		ret = btrfs_log_all_parents(trans, orig_inode, ctx);
5717 		if (ret)
5718 			goto end_trans;
5719 	}
5720 
5721 	/*
5722 	 * If a new hard link was added to the inode in the current transaction
5723 	 * and its link count is now greater than 1, we need to fallback to a
5724 	 * transaction commit, otherwise we can end up not logging all its new
5725 	 * parents for all the hard links. Here just from the dentry used to
5726 	 * fsync, we can not visit the ancestor inodes for all the other hard
5727 	 * links to figure out if any is new, so we fallback to a transaction
5728 	 * commit (instead of adding a lot of complexity of scanning a btree,
5729 	 * since this scenario is not a common use case).
5730 	 */
5731 	if (inode->vfs_inode.i_nlink > 1 &&
5732 	    inode->last_link_trans > last_committed) {
5733 		ret = -EMLINK;
5734 		goto end_trans;
5735 	}
5736 
5737 	while (1) {
5738 		if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5739 			break;
5740 
5741 		inode = BTRFS_I(d_inode(parent));
5742 		if (root != inode->root)
5743 			break;
5744 
5745 		if (inode->generation > last_committed) {
5746 			ret = btrfs_log_inode(trans, root, inode,
5747 					LOG_INODE_EXISTS, 0, LLONG_MAX, ctx);
5748 			if (ret)
5749 				goto end_trans;
5750 		}
5751 		if (IS_ROOT(parent))
5752 			break;
5753 
5754 		parent = dget_parent(parent);
5755 		dput(old_parent);
5756 		old_parent = parent;
5757 	}
5758 	if (log_dentries)
5759 		ret = log_new_dir_dentries(trans, root, orig_inode, ctx);
5760 	else
5761 		ret = 0;
5762 end_trans:
5763 	dput(old_parent);
5764 	if (ret < 0) {
5765 		btrfs_set_log_full_commit(fs_info, trans);
5766 		ret = 1;
5767 	}
5768 
5769 	if (ret)
5770 		btrfs_remove_log_ctx(root, ctx);
5771 	btrfs_end_log_trans(root);
5772 end_no_trans:
5773 	return ret;
5774 }
5775 
5776 /*
5777  * it is not safe to log dentry if the chunk root has added new
5778  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
5779  * If this returns 1, you must commit the transaction to safely get your
5780  * data on disk.
5781  */
btrfs_log_dentry_safe(struct btrfs_trans_handle * trans,struct dentry * dentry,const loff_t start,const loff_t end,struct btrfs_log_ctx * ctx)5782 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
5783 			  struct dentry *dentry,
5784 			  const loff_t start,
5785 			  const loff_t end,
5786 			  struct btrfs_log_ctx *ctx)
5787 {
5788 	struct dentry *parent = dget_parent(dentry);
5789 	int ret;
5790 
5791 	ret = btrfs_log_inode_parent(trans, BTRFS_I(d_inode(dentry)), parent,
5792 				     start, end, LOG_INODE_ALL, ctx);
5793 	dput(parent);
5794 
5795 	return ret;
5796 }
5797 
5798 /*
5799  * should be called during mount to recover any replay any log trees
5800  * from the FS
5801  */
btrfs_recover_log_trees(struct btrfs_root * log_root_tree)5802 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
5803 {
5804 	int ret;
5805 	struct btrfs_path *path;
5806 	struct btrfs_trans_handle *trans;
5807 	struct btrfs_key key;
5808 	struct btrfs_key found_key;
5809 	struct btrfs_key tmp_key;
5810 	struct btrfs_root *log;
5811 	struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
5812 	struct walk_control wc = {
5813 		.process_func = process_one_buffer,
5814 		.stage = 0,
5815 	};
5816 
5817 	path = btrfs_alloc_path();
5818 	if (!path)
5819 		return -ENOMEM;
5820 
5821 	set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
5822 
5823 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
5824 	if (IS_ERR(trans)) {
5825 		ret = PTR_ERR(trans);
5826 		goto error;
5827 	}
5828 
5829 	wc.trans = trans;
5830 	wc.pin = 1;
5831 
5832 	ret = walk_log_tree(trans, log_root_tree, &wc);
5833 	if (ret) {
5834 		btrfs_handle_fs_error(fs_info, ret,
5835 			"Failed to pin buffers while recovering log root tree.");
5836 		goto error;
5837 	}
5838 
5839 again:
5840 	key.objectid = BTRFS_TREE_LOG_OBJECTID;
5841 	key.offset = (u64)-1;
5842 	key.type = BTRFS_ROOT_ITEM_KEY;
5843 
5844 	while (1) {
5845 		ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
5846 
5847 		if (ret < 0) {
5848 			btrfs_handle_fs_error(fs_info, ret,
5849 				    "Couldn't find tree log root.");
5850 			goto error;
5851 		}
5852 		if (ret > 0) {
5853 			if (path->slots[0] == 0)
5854 				break;
5855 			path->slots[0]--;
5856 		}
5857 		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
5858 				      path->slots[0]);
5859 		btrfs_release_path(path);
5860 		if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
5861 			break;
5862 
5863 		log = btrfs_read_fs_root(log_root_tree, &found_key);
5864 		if (IS_ERR(log)) {
5865 			ret = PTR_ERR(log);
5866 			btrfs_handle_fs_error(fs_info, ret,
5867 				    "Couldn't read tree log root.");
5868 			goto error;
5869 		}
5870 
5871 		tmp_key.objectid = found_key.offset;
5872 		tmp_key.type = BTRFS_ROOT_ITEM_KEY;
5873 		tmp_key.offset = (u64)-1;
5874 
5875 		wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
5876 		if (IS_ERR(wc.replay_dest)) {
5877 			ret = PTR_ERR(wc.replay_dest);
5878 
5879 			/*
5880 			 * We didn't find the subvol, likely because it was
5881 			 * deleted.  This is ok, simply skip this log and go to
5882 			 * the next one.
5883 			 *
5884 			 * We need to exclude the root because we can't have
5885 			 * other log replays overwriting this log as we'll read
5886 			 * it back in a few more times.  This will keep our
5887 			 * block from being modified, and we'll just bail for
5888 			 * each subsequent pass.
5889 			 */
5890 			if (ret == -ENOENT)
5891 				ret = btrfs_pin_extent_for_log_replay(fs_info,
5892 							log->node->start,
5893 							log->node->len);
5894 			free_extent_buffer(log->node);
5895 			free_extent_buffer(log->commit_root);
5896 			kfree(log);
5897 
5898 			if (!ret)
5899 				goto next;
5900 			btrfs_handle_fs_error(fs_info, ret,
5901 				"Couldn't read target root for tree log recovery.");
5902 			goto error;
5903 		}
5904 
5905 		wc.replay_dest->log_root = log;
5906 		btrfs_record_root_in_trans(trans, wc.replay_dest);
5907 		ret = walk_log_tree(trans, log, &wc);
5908 
5909 		if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
5910 			ret = fixup_inode_link_counts(trans, wc.replay_dest,
5911 						      path);
5912 		}
5913 
5914 		if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
5915 			struct btrfs_root *root = wc.replay_dest;
5916 
5917 			btrfs_release_path(path);
5918 
5919 			/*
5920 			 * We have just replayed everything, and the highest
5921 			 * objectid of fs roots probably has changed in case
5922 			 * some inode_item's got replayed.
5923 			 *
5924 			 * root->objectid_mutex is not acquired as log replay
5925 			 * could only happen during mount.
5926 			 */
5927 			ret = btrfs_find_highest_objectid(root,
5928 						  &root->highest_objectid);
5929 		}
5930 
5931 		wc.replay_dest->log_root = NULL;
5932 		free_extent_buffer(log->node);
5933 		free_extent_buffer(log->commit_root);
5934 		kfree(log);
5935 
5936 		if (ret)
5937 			goto error;
5938 next:
5939 		if (found_key.offset == 0)
5940 			break;
5941 		key.offset = found_key.offset - 1;
5942 	}
5943 	btrfs_release_path(path);
5944 
5945 	/* step one is to pin it all, step two is to replay just inodes */
5946 	if (wc.pin) {
5947 		wc.pin = 0;
5948 		wc.process_func = replay_one_buffer;
5949 		wc.stage = LOG_WALK_REPLAY_INODES;
5950 		goto again;
5951 	}
5952 	/* step three is to replay everything */
5953 	if (wc.stage < LOG_WALK_REPLAY_ALL) {
5954 		wc.stage++;
5955 		goto again;
5956 	}
5957 
5958 	btrfs_free_path(path);
5959 
5960 	/* step 4: commit the transaction, which also unpins the blocks */
5961 	ret = btrfs_commit_transaction(trans);
5962 	if (ret)
5963 		return ret;
5964 
5965 	free_extent_buffer(log_root_tree->node);
5966 	log_root_tree->log_root = NULL;
5967 	clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
5968 	kfree(log_root_tree);
5969 
5970 	return 0;
5971 error:
5972 	if (wc.trans)
5973 		btrfs_end_transaction(wc.trans);
5974 	btrfs_free_path(path);
5975 	return ret;
5976 }
5977 
5978 /*
5979  * there are some corner cases where we want to force a full
5980  * commit instead of allowing a directory to be logged.
5981  *
5982  * They revolve around files there were unlinked from the directory, and
5983  * this function updates the parent directory so that a full commit is
5984  * properly done if it is fsync'd later after the unlinks are done.
5985  *
5986  * Must be called before the unlink operations (updates to the subvolume tree,
5987  * inodes, etc) are done.
5988  */
btrfs_record_unlink_dir(struct btrfs_trans_handle * trans,struct btrfs_inode * dir,struct btrfs_inode * inode,int for_rename)5989 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
5990 			     struct btrfs_inode *dir, struct btrfs_inode *inode,
5991 			     int for_rename)
5992 {
5993 	/*
5994 	 * when we're logging a file, if it hasn't been renamed
5995 	 * or unlinked, and its inode is fully committed on disk,
5996 	 * we don't have to worry about walking up the directory chain
5997 	 * to log its parents.
5998 	 *
5999 	 * So, we use the last_unlink_trans field to put this transid
6000 	 * into the file.  When the file is logged we check it and
6001 	 * don't log the parents if the file is fully on disk.
6002 	 */
6003 	mutex_lock(&inode->log_mutex);
6004 	inode->last_unlink_trans = trans->transid;
6005 	mutex_unlock(&inode->log_mutex);
6006 
6007 	/*
6008 	 * if this directory was already logged any new
6009 	 * names for this file/dir will get recorded
6010 	 */
6011 	if (dir->logged_trans == trans->transid)
6012 		return;
6013 
6014 	/*
6015 	 * if the inode we're about to unlink was logged,
6016 	 * the log will be properly updated for any new names
6017 	 */
6018 	if (inode->logged_trans == trans->transid)
6019 		return;
6020 
6021 	/*
6022 	 * when renaming files across directories, if the directory
6023 	 * there we're unlinking from gets fsync'd later on, there's
6024 	 * no way to find the destination directory later and fsync it
6025 	 * properly.  So, we have to be conservative and force commits
6026 	 * so the new name gets discovered.
6027 	 */
6028 	if (for_rename)
6029 		goto record;
6030 
6031 	/* we can safely do the unlink without any special recording */
6032 	return;
6033 
6034 record:
6035 	mutex_lock(&dir->log_mutex);
6036 	dir->last_unlink_trans = trans->transid;
6037 	mutex_unlock(&dir->log_mutex);
6038 }
6039 
6040 /*
6041  * Make sure that if someone attempts to fsync the parent directory of a deleted
6042  * snapshot, it ends up triggering a transaction commit. This is to guarantee
6043  * that after replaying the log tree of the parent directory's root we will not
6044  * see the snapshot anymore and at log replay time we will not see any log tree
6045  * corresponding to the deleted snapshot's root, which could lead to replaying
6046  * it after replaying the log tree of the parent directory (which would replay
6047  * the snapshot delete operation).
6048  *
6049  * Must be called before the actual snapshot destroy operation (updates to the
6050  * parent root and tree of tree roots trees, etc) are done.
6051  */
btrfs_record_snapshot_destroy(struct btrfs_trans_handle * trans,struct btrfs_inode * dir)6052 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
6053 				   struct btrfs_inode *dir)
6054 {
6055 	mutex_lock(&dir->log_mutex);
6056 	dir->last_unlink_trans = trans->transid;
6057 	mutex_unlock(&dir->log_mutex);
6058 }
6059 
6060 /*
6061  * Call this after adding a new name for a file and it will properly
6062  * update the log to reflect the new name.
6063  *
6064  * @ctx can not be NULL when @sync_log is false, and should be NULL when it's
6065  * true (because it's not used).
6066  *
6067  * Return value depends on whether @sync_log is true or false.
6068  * When true: returns BTRFS_NEED_TRANS_COMMIT if the transaction needs to be
6069  *            committed by the caller, and BTRFS_DONT_NEED_TRANS_COMMIT
6070  *            otherwise.
6071  * When false: returns BTRFS_DONT_NEED_LOG_SYNC if the caller does not need to
6072  *             to sync the log, BTRFS_NEED_LOG_SYNC if it needs to sync the log,
6073  *             or BTRFS_NEED_TRANS_COMMIT if the transaction needs to be
6074  *             committed (without attempting to sync the log).
6075  */
btrfs_log_new_name(struct btrfs_trans_handle * trans,struct btrfs_inode * inode,struct btrfs_inode * old_dir,struct dentry * parent,bool sync_log,struct btrfs_log_ctx * ctx)6076 int btrfs_log_new_name(struct btrfs_trans_handle *trans,
6077 			struct btrfs_inode *inode, struct btrfs_inode *old_dir,
6078 			struct dentry *parent,
6079 			bool sync_log, struct btrfs_log_ctx *ctx)
6080 {
6081 	struct btrfs_fs_info *fs_info = trans->fs_info;
6082 	int ret;
6083 
6084 	/*
6085 	 * this will force the logging code to walk the dentry chain
6086 	 * up for the file
6087 	 */
6088 	if (!S_ISDIR(inode->vfs_inode.i_mode))
6089 		inode->last_unlink_trans = trans->transid;
6090 
6091 	/*
6092 	 * if this inode hasn't been logged and directory we're renaming it
6093 	 * from hasn't been logged, we don't need to log it
6094 	 */
6095 	if (inode->logged_trans <= fs_info->last_trans_committed &&
6096 	    (!old_dir || old_dir->logged_trans <= fs_info->last_trans_committed))
6097 		return sync_log ? BTRFS_DONT_NEED_TRANS_COMMIT :
6098 			BTRFS_DONT_NEED_LOG_SYNC;
6099 
6100 	if (sync_log) {
6101 		struct btrfs_log_ctx ctx2;
6102 
6103 		btrfs_init_log_ctx(&ctx2, &inode->vfs_inode);
6104 		ret = btrfs_log_inode_parent(trans, inode, parent, 0, LLONG_MAX,
6105 					     LOG_INODE_EXISTS, &ctx2);
6106 		if (ret == BTRFS_NO_LOG_SYNC)
6107 			return BTRFS_DONT_NEED_TRANS_COMMIT;
6108 		else if (ret)
6109 			return BTRFS_NEED_TRANS_COMMIT;
6110 
6111 		ret = btrfs_sync_log(trans, inode->root, &ctx2);
6112 		if (ret)
6113 			return BTRFS_NEED_TRANS_COMMIT;
6114 		return BTRFS_DONT_NEED_TRANS_COMMIT;
6115 	}
6116 
6117 	ASSERT(ctx);
6118 	ret = btrfs_log_inode_parent(trans, inode, parent, 0, LLONG_MAX,
6119 				     LOG_INODE_EXISTS, ctx);
6120 	if (ret == BTRFS_NO_LOG_SYNC)
6121 		return BTRFS_DONT_NEED_LOG_SYNC;
6122 	else if (ret)
6123 		return BTRFS_NEED_TRANS_COMMIT;
6124 
6125 	return BTRFS_NEED_LOG_SYNC;
6126 }
6127 
6128