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