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