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