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