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