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