70d41f6690251b2fe75711f539d62295538864a7
[sfrench/cifs-2.6.git] / fs / btrfs / tree-log.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2008 Oracle.  All rights reserved.
4  */
5
6 #include <linux/sched.h>
7 #include <linux/slab.h>
8 #include <linux/blkdev.h>
9 #include <linux/list_sort.h>
10 #include <linux/iversion.h>
11 #include "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 void btrfs_pin_log_trans(struct btrfs_root *root)
209 {
210         mutex_lock(&root->log_mutex);
211         atomic_inc(&root->log_writers);
212         mutex_unlock(&root->log_mutex);
213 }
214
215 /*
216  * indicate we're done making changes to the log tree
217  * and wake up anyone waiting to do a sync
218  */
219 void btrfs_end_log_trans(struct btrfs_root *root)
220 {
221         if (atomic_dec_and_test(&root->log_writers)) {
222                 /* atomic_dec_and_test implies a barrier */
223                 cond_wake_up_nomb(&root->log_writer_wait);
224         }
225 }
226
227
228 /*
229  * the walk control struct is used to pass state down the chain when
230  * processing the log tree.  The stage field tells us which part
231  * of the log tree processing we are currently doing.  The others
232  * are state fields used for that specific part
233  */
234 struct walk_control {
235         /* should we free the extent on disk when done?  This is used
236          * at transaction commit time while freeing a log tree
237          */
238         int free;
239
240         /* should we write out the extent buffer?  This is used
241          * while flushing the log tree to disk during a sync
242          */
243         int write;
244
245         /* should we wait for the extent buffer io to finish?  Also used
246          * while flushing the log tree to disk for a sync
247          */
248         int wait;
249
250         /* pin only walk, we record which extents on disk belong to the
251          * log trees
252          */
253         int pin;
254
255         /* what stage of the replay code we're currently in */
256         int stage;
257
258         /*
259          * Ignore any items from the inode currently being processed. Needs
260          * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
261          * the LOG_WALK_REPLAY_INODES stage.
262          */
263         bool ignore_cur_inode;
264
265         /* the root we are currently replaying */
266         struct btrfs_root *replay_dest;
267
268         /* the trans handle for the current replay */
269         struct btrfs_trans_handle *trans;
270
271         /* the function that gets used to process blocks we find in the
272          * tree.  Note the extent_buffer might not be up to date when it is
273          * passed in, and it must be checked or read if you need the data
274          * inside it
275          */
276         int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
277                             struct walk_control *wc, u64 gen, int level);
278 };
279
280 /*
281  * process_func used to pin down extents, write them or wait on them
282  */
283 static int process_one_buffer(struct btrfs_root *log,
284                               struct extent_buffer *eb,
285                               struct walk_control *wc, u64 gen, int level)
286 {
287         struct btrfs_fs_info *fs_info = log->fs_info;
288         int ret = 0;
289
290         /*
291          * If this fs is mixed then we need to be able to process the leaves to
292          * pin down any logged extents, so we have to read the block.
293          */
294         if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
295                 ret = btrfs_read_buffer(eb, gen, level, NULL);
296                 if (ret)
297                         return ret;
298         }
299
300         if (wc->pin)
301                 ret = btrfs_pin_extent_for_log_replay(fs_info, eb->start,
302                                                       eb->len);
303
304         if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
305                 if (wc->pin && btrfs_header_level(eb) == 0)
306                         ret = btrfs_exclude_logged_extents(fs_info, eb);
307                 if (wc->write)
308                         btrfs_write_tree_block(eb);
309                 if (wc->wait)
310                         btrfs_wait_tree_block_writeback(eb);
311         }
312         return ret;
313 }
314
315 /*
316  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
317  * to the src data we are copying out.
318  *
319  * root is the tree we are copying into, and path is a scratch
320  * path for use in this function (it should be released on entry and
321  * will be released on exit).
322  *
323  * If the key is already in the destination tree the existing item is
324  * overwritten.  If the existing item isn't big enough, it is extended.
325  * If it is too large, it is truncated.
326  *
327  * If the key isn't in the destination yet, a new item is inserted.
328  */
329 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
330                                    struct btrfs_root *root,
331                                    struct btrfs_path *path,
332                                    struct extent_buffer *eb, int slot,
333                                    struct btrfs_key *key)
334 {
335         struct btrfs_fs_info *fs_info = root->fs_info;
336         int ret;
337         u32 item_size;
338         u64 saved_i_size = 0;
339         int save_old_i_size = 0;
340         unsigned long src_ptr;
341         unsigned long dst_ptr;
342         int overwrite_root = 0;
343         bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
344
345         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
346                 overwrite_root = 1;
347
348         item_size = btrfs_item_size_nr(eb, slot);
349         src_ptr = btrfs_item_ptr_offset(eb, slot);
350
351         /* look for the key in the destination tree */
352         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
353         if (ret < 0)
354                 return ret;
355
356         if (ret == 0) {
357                 char *src_copy;
358                 char *dst_copy;
359                 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
360                                                   path->slots[0]);
361                 if (dst_size != item_size)
362                         goto insert;
363
364                 if (item_size == 0) {
365                         btrfs_release_path(path);
366                         return 0;
367                 }
368                 dst_copy = kmalloc(item_size, GFP_NOFS);
369                 src_copy = kmalloc(item_size, GFP_NOFS);
370                 if (!dst_copy || !src_copy) {
371                         btrfs_release_path(path);
372                         kfree(dst_copy);
373                         kfree(src_copy);
374                         return -ENOMEM;
375                 }
376
377                 read_extent_buffer(eb, src_copy, src_ptr, item_size);
378
379                 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
380                 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
381                                    item_size);
382                 ret = memcmp(dst_copy, src_copy, item_size);
383
384                 kfree(dst_copy);
385                 kfree(src_copy);
386                 /*
387                  * they have the same contents, just return, this saves
388                  * us from cowing blocks in the destination tree and doing
389                  * extra writes that may not have been done by a previous
390                  * sync
391                  */
392                 if (ret == 0) {
393                         btrfs_release_path(path);
394                         return 0;
395                 }
396
397                 /*
398                  * We need to load the old nbytes into the inode so when we
399                  * replay the extents we've logged we get the right nbytes.
400                  */
401                 if (inode_item) {
402                         struct btrfs_inode_item *item;
403                         u64 nbytes;
404                         u32 mode;
405
406                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
407                                               struct btrfs_inode_item);
408                         nbytes = btrfs_inode_nbytes(path->nodes[0], item);
409                         item = btrfs_item_ptr(eb, slot,
410                                               struct btrfs_inode_item);
411                         btrfs_set_inode_nbytes(eb, item, nbytes);
412
413                         /*
414                          * If this is a directory we need to reset the i_size to
415                          * 0 so that we can set it up properly when replaying
416                          * the rest of the items in this log.
417                          */
418                         mode = btrfs_inode_mode(eb, item);
419                         if (S_ISDIR(mode))
420                                 btrfs_set_inode_size(eb, item, 0);
421                 }
422         } else if (inode_item) {
423                 struct btrfs_inode_item *item;
424                 u32 mode;
425
426                 /*
427                  * New inode, set nbytes to 0 so that the nbytes comes out
428                  * properly when we replay the extents.
429                  */
430                 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
431                 btrfs_set_inode_nbytes(eb, item, 0);
432
433                 /*
434                  * If this is a directory we need to reset the i_size to 0 so
435                  * that we can set it up properly when replaying the rest of
436                  * the items in this log.
437                  */
438                 mode = btrfs_inode_mode(eb, item);
439                 if (S_ISDIR(mode))
440                         btrfs_set_inode_size(eb, item, 0);
441         }
442 insert:
443         btrfs_release_path(path);
444         /* try to insert the key into the destination tree */
445         path->skip_release_on_error = 1;
446         ret = btrfs_insert_empty_item(trans, root, path,
447                                       key, item_size);
448         path->skip_release_on_error = 0;
449
450         /* make sure any existing item is the correct size */
451         if (ret == -EEXIST || ret == -EOVERFLOW) {
452                 u32 found_size;
453                 found_size = btrfs_item_size_nr(path->nodes[0],
454                                                 path->slots[0]);
455                 if (found_size > item_size)
456                         btrfs_truncate_item(fs_info, path, item_size, 1);
457                 else if (found_size < item_size)
458                         btrfs_extend_item(fs_info, path,
459                                           item_size - found_size);
460         } else if (ret) {
461                 return ret;
462         }
463         dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
464                                         path->slots[0]);
465
466         /* don't overwrite an existing inode if the generation number
467          * was logged as zero.  This is done when the tree logging code
468          * is just logging an inode to make sure it exists after recovery.
469          *
470          * Also, don't overwrite i_size on directories during replay.
471          * log replay inserts and removes directory items based on the
472          * state of the tree found in the subvolume, and i_size is modified
473          * as it goes
474          */
475         if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
476                 struct btrfs_inode_item *src_item;
477                 struct btrfs_inode_item *dst_item;
478
479                 src_item = (struct btrfs_inode_item *)src_ptr;
480                 dst_item = (struct btrfs_inode_item *)dst_ptr;
481
482                 if (btrfs_inode_generation(eb, src_item) == 0) {
483                         struct extent_buffer *dst_eb = path->nodes[0];
484                         const u64 ino_size = btrfs_inode_size(eb, src_item);
485
486                         /*
487                          * For regular files an ino_size == 0 is used only when
488                          * logging that an inode exists, as part of a directory
489                          * fsync, and the inode wasn't fsynced before. In this
490                          * case don't set the size of the inode in the fs/subvol
491                          * tree, otherwise we would be throwing valid data away.
492                          */
493                         if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
494                             S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
495                             ino_size != 0) {
496                                 struct btrfs_map_token token;
497
498                                 btrfs_init_map_token(&token);
499                                 btrfs_set_token_inode_size(dst_eb, dst_item,
500                                                            ino_size, &token);
501                         }
502                         goto no_copy;
503                 }
504
505                 if (overwrite_root &&
506                     S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
507                     S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
508                         save_old_i_size = 1;
509                         saved_i_size = btrfs_inode_size(path->nodes[0],
510                                                         dst_item);
511                 }
512         }
513
514         copy_extent_buffer(path->nodes[0], eb, dst_ptr,
515                            src_ptr, item_size);
516
517         if (save_old_i_size) {
518                 struct btrfs_inode_item *dst_item;
519                 dst_item = (struct btrfs_inode_item *)dst_ptr;
520                 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
521         }
522
523         /* make sure the generation is filled in */
524         if (key->type == BTRFS_INODE_ITEM_KEY) {
525                 struct btrfs_inode_item *dst_item;
526                 dst_item = (struct btrfs_inode_item *)dst_ptr;
527                 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
528                         btrfs_set_inode_generation(path->nodes[0], dst_item,
529                                                    trans->transid);
530                 }
531         }
532 no_copy:
533         btrfs_mark_buffer_dirty(path->nodes[0]);
534         btrfs_release_path(path);
535         return 0;
536 }
537
538 /*
539  * simple helper to read an inode off the disk from a given root
540  * This can only be called for subvolume roots and not for the log
541  */
542 static noinline struct inode *read_one_inode(struct btrfs_root *root,
543                                              u64 objectid)
544 {
545         struct btrfs_key key;
546         struct inode *inode;
547
548         key.objectid = objectid;
549         key.type = BTRFS_INODE_ITEM_KEY;
550         key.offset = 0;
551         inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
552         if (IS_ERR(inode))
553                 inode = NULL;
554         return inode;
555 }
556
557 /* replays a single extent in 'eb' at 'slot' with 'key' into the
558  * subvolume 'root'.  path is released on entry and should be released
559  * on exit.
560  *
561  * extents in the log tree have not been allocated out of the extent
562  * tree yet.  So, this completes the allocation, taking a reference
563  * as required if the extent already exists or creating a new extent
564  * if it isn't in the extent allocation tree yet.
565  *
566  * The extent is inserted into the file, dropping any existing extents
567  * from the file that overlap the new one.
568  */
569 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
570                                       struct btrfs_root *root,
571                                       struct btrfs_path *path,
572                                       struct extent_buffer *eb, int slot,
573                                       struct btrfs_key *key)
574 {
575         struct btrfs_fs_info *fs_info = root->fs_info;
576         int found_type;
577         u64 extent_end;
578         u64 start = key->offset;
579         u64 nbytes = 0;
580         struct btrfs_file_extent_item *item;
581         struct inode *inode = NULL;
582         unsigned long size;
583         int ret = 0;
584
585         item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
586         found_type = btrfs_file_extent_type(eb, item);
587
588         if (found_type == BTRFS_FILE_EXTENT_REG ||
589             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
590                 nbytes = btrfs_file_extent_num_bytes(eb, item);
591                 extent_end = start + nbytes;
592
593                 /*
594                  * We don't add to the inodes nbytes if we are prealloc or a
595                  * hole.
596                  */
597                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
598                         nbytes = 0;
599         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
600                 size = btrfs_file_extent_ram_bytes(eb, item);
601                 nbytes = btrfs_file_extent_ram_bytes(eb, item);
602                 extent_end = ALIGN(start + size,
603                                    fs_info->sectorsize);
604         } else {
605                 ret = 0;
606                 goto out;
607         }
608
609         inode = read_one_inode(root, key->objectid);
610         if (!inode) {
611                 ret = -EIO;
612                 goto out;
613         }
614
615         /*
616          * first check to see if we already have this extent in the
617          * file.  This must be done before the btrfs_drop_extents run
618          * so we don't try to drop this extent.
619          */
620         ret = btrfs_lookup_file_extent(trans, root, path,
621                         btrfs_ino(BTRFS_I(inode)), start, 0);
622
623         if (ret == 0 &&
624             (found_type == BTRFS_FILE_EXTENT_REG ||
625              found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
626                 struct btrfs_file_extent_item cmp1;
627                 struct btrfs_file_extent_item cmp2;
628                 struct btrfs_file_extent_item *existing;
629                 struct extent_buffer *leaf;
630
631                 leaf = path->nodes[0];
632                 existing = btrfs_item_ptr(leaf, path->slots[0],
633                                           struct btrfs_file_extent_item);
634
635                 read_extent_buffer(eb, &cmp1, (unsigned long)item,
636                                    sizeof(cmp1));
637                 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
638                                    sizeof(cmp2));
639
640                 /*
641                  * we already have a pointer to this exact extent,
642                  * we don't have to do anything
643                  */
644                 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
645                         btrfs_release_path(path);
646                         goto out;
647                 }
648         }
649         btrfs_release_path(path);
650
651         /* drop any overlapping extents */
652         ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
653         if (ret)
654                 goto out;
655
656         if (found_type == BTRFS_FILE_EXTENT_REG ||
657             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
658                 u64 offset;
659                 unsigned long dest_offset;
660                 struct btrfs_key ins;
661
662                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
663                     btrfs_fs_incompat(fs_info, NO_HOLES))
664                         goto update_inode;
665
666                 ret = btrfs_insert_empty_item(trans, root, path, key,
667                                               sizeof(*item));
668                 if (ret)
669                         goto out;
670                 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
671                                                     path->slots[0]);
672                 copy_extent_buffer(path->nodes[0], eb, dest_offset,
673                                 (unsigned long)item,  sizeof(*item));
674
675                 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
676                 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
677                 ins.type = BTRFS_EXTENT_ITEM_KEY;
678                 offset = key->offset - btrfs_file_extent_offset(eb, item);
679
680                 /*
681                  * Manually record dirty extent, as here we did a shallow
682                  * file extent item copy and skip normal backref update,
683                  * but modifying extent tree all by ourselves.
684                  * So need to manually record dirty extent for qgroup,
685                  * as the owner of the file extent changed from log tree
686                  * (doesn't affect qgroup) to fs/file tree(affects qgroup)
687                  */
688                 ret = btrfs_qgroup_trace_extent(trans,
689                                 btrfs_file_extent_disk_bytenr(eb, item),
690                                 btrfs_file_extent_disk_num_bytes(eb, item),
691                                 GFP_NOFS);
692                 if (ret < 0)
693                         goto out;
694
695                 if (ins.objectid > 0) {
696                         u64 csum_start;
697                         u64 csum_end;
698                         LIST_HEAD(ordered_sums);
699                         /*
700                          * is this extent already allocated in the extent
701                          * allocation tree?  If so, just add a reference
702                          */
703                         ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
704                                                 ins.offset);
705                         if (ret == 0) {
706                                 ret = btrfs_inc_extent_ref(trans, root,
707                                                 ins.objectid, ins.offset,
708                                                 0, root->root_key.objectid,
709                                                 key->objectid, offset);
710                                 if (ret)
711                                         goto out;
712                         } else {
713                                 /*
714                                  * insert the extent pointer in the extent
715                                  * allocation tree
716                                  */
717                                 ret = btrfs_alloc_logged_file_extent(trans,
718                                                 root->root_key.objectid,
719                                                 key->objectid, offset, &ins);
720                                 if (ret)
721                                         goto out;
722                         }
723                         btrfs_release_path(path);
724
725                         if (btrfs_file_extent_compression(eb, item)) {
726                                 csum_start = ins.objectid;
727                                 csum_end = csum_start + ins.offset;
728                         } else {
729                                 csum_start = ins.objectid +
730                                         btrfs_file_extent_offset(eb, item);
731                                 csum_end = csum_start +
732                                         btrfs_file_extent_num_bytes(eb, item);
733                         }
734
735                         ret = btrfs_lookup_csums_range(root->log_root,
736                                                 csum_start, csum_end - 1,
737                                                 &ordered_sums, 0);
738                         if (ret)
739                                 goto out;
740                         /*
741                          * Now delete all existing cums in the csum root that
742                          * cover our range. We do this because we can have an
743                          * extent that is completely referenced by one file
744                          * extent item and partially referenced by another
745                          * file extent item (like after using the clone or
746                          * extent_same ioctls). In this case if we end up doing
747                          * the replay of the one that partially references the
748                          * extent first, and we do not do the csum deletion
749                          * below, we can get 2 csum items in the csum tree that
750                          * overlap each other. For example, imagine our log has
751                          * the two following file extent items:
752                          *
753                          * key (257 EXTENT_DATA 409600)
754                          *     extent data disk byte 12845056 nr 102400
755                          *     extent data offset 20480 nr 20480 ram 102400
756                          *
757                          * key (257 EXTENT_DATA 819200)
758                          *     extent data disk byte 12845056 nr 102400
759                          *     extent data offset 0 nr 102400 ram 102400
760                          *
761                          * Where the second one fully references the 100K extent
762                          * that starts at disk byte 12845056, and the log tree
763                          * has a single csum item that covers the entire range
764                          * of the extent:
765                          *
766                          * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
767                          *
768                          * After the first file extent item is replayed, the
769                          * csum tree gets the following csum item:
770                          *
771                          * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
772                          *
773                          * Which covers the 20K sub-range starting at offset 20K
774                          * of our extent. Now when we replay the second file
775                          * extent item, if we do not delete existing csum items
776                          * that cover any of its blocks, we end up getting two
777                          * csum items in our csum tree that overlap each other:
778                          *
779                          * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
780                          * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
781                          *
782                          * Which is a problem, because after this anyone trying
783                          * to lookup up for the checksum of any block of our
784                          * extent starting at an offset of 40K or higher, will
785                          * end up looking at the second csum item only, which
786                          * does not contain the checksum for any block starting
787                          * at offset 40K or higher of our extent.
788                          */
789                         while (!list_empty(&ordered_sums)) {
790                                 struct btrfs_ordered_sum *sums;
791                                 sums = list_entry(ordered_sums.next,
792                                                 struct btrfs_ordered_sum,
793                                                 list);
794                                 if (!ret)
795                                         ret = btrfs_del_csums(trans, fs_info,
796                                                               sums->bytenr,
797                                                               sums->len);
798                                 if (!ret)
799                                         ret = btrfs_csum_file_blocks(trans,
800                                                 fs_info->csum_root, sums);
801                                 list_del(&sums->list);
802                                 kfree(sums);
803                         }
804                         if (ret)
805                                 goto out;
806                 } else {
807                         btrfs_release_path(path);
808                 }
809         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
810                 /* inline extents are easy, we just overwrite them */
811                 ret = overwrite_item(trans, root, path, eb, slot, key);
812                 if (ret)
813                         goto out;
814         }
815
816         inode_add_bytes(inode, nbytes);
817 update_inode:
818         ret = btrfs_update_inode(trans, root, inode);
819 out:
820         if (inode)
821                 iput(inode);
822         return ret;
823 }
824
825 /*
826  * when cleaning up conflicts between the directory names in the
827  * subvolume, directory names in the log and directory names in the
828  * inode back references, we may have to unlink inodes from directories.
829  *
830  * This is a helper function to do the unlink of a specific directory
831  * item
832  */
833 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
834                                       struct btrfs_root *root,
835                                       struct btrfs_path *path,
836                                       struct btrfs_inode *dir,
837                                       struct btrfs_dir_item *di)
838 {
839         struct inode *inode;
840         char *name;
841         int name_len;
842         struct extent_buffer *leaf;
843         struct btrfs_key location;
844         int ret;
845
846         leaf = path->nodes[0];
847
848         btrfs_dir_item_key_to_cpu(leaf, di, &location);
849         name_len = btrfs_dir_name_len(leaf, di);
850         name = kmalloc(name_len, GFP_NOFS);
851         if (!name)
852                 return -ENOMEM;
853
854         read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
855         btrfs_release_path(path);
856
857         inode = read_one_inode(root, location.objectid);
858         if (!inode) {
859                 ret = -EIO;
860                 goto out;
861         }
862
863         ret = link_to_fixup_dir(trans, root, path, location.objectid);
864         if (ret)
865                 goto out;
866
867         ret = btrfs_unlink_inode(trans, root, dir, BTRFS_I(inode), name,
868                         name_len);
869         if (ret)
870                 goto out;
871         else
872                 ret = btrfs_run_delayed_items(trans);
873 out:
874         kfree(name);
875         iput(inode);
876         return ret;
877 }
878
879 /*
880  * helper function to see if a given name and sequence number found
881  * in an inode back reference are already in a directory and correctly
882  * point to this inode
883  */
884 static noinline int inode_in_dir(struct btrfs_root *root,
885                                  struct btrfs_path *path,
886                                  u64 dirid, u64 objectid, u64 index,
887                                  const char *name, int name_len)
888 {
889         struct btrfs_dir_item *di;
890         struct btrfs_key location;
891         int match = 0;
892
893         di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
894                                          index, name, name_len, 0);
895         if (di && !IS_ERR(di)) {
896                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
897                 if (location.objectid != objectid)
898                         goto out;
899         } else
900                 goto out;
901         btrfs_release_path(path);
902
903         di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
904         if (di && !IS_ERR(di)) {
905                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
906                 if (location.objectid != objectid)
907                         goto out;
908         } else
909                 goto out;
910         match = 1;
911 out:
912         btrfs_release_path(path);
913         return match;
914 }
915
916 /*
917  * helper function to check a log tree for a named back reference in
918  * an inode.  This is used to decide if a back reference that is
919  * found in the subvolume conflicts with what we find in the log.
920  *
921  * inode backreferences may have multiple refs in a single item,
922  * during replay we process one reference at a time, and we don't
923  * want to delete valid links to a file from the subvolume if that
924  * link is also in the log.
925  */
926 static noinline int backref_in_log(struct btrfs_root *log,
927                                    struct btrfs_key *key,
928                                    u64 ref_objectid,
929                                    const char *name, int namelen)
930 {
931         struct btrfs_path *path;
932         struct btrfs_inode_ref *ref;
933         unsigned long ptr;
934         unsigned long ptr_end;
935         unsigned long name_ptr;
936         int found_name_len;
937         int item_size;
938         int ret;
939         int match = 0;
940
941         path = btrfs_alloc_path();
942         if (!path)
943                 return -ENOMEM;
944
945         ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
946         if (ret != 0)
947                 goto out;
948
949         ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
950
951         if (key->type == BTRFS_INODE_EXTREF_KEY) {
952                 if (btrfs_find_name_in_ext_backref(path->nodes[0],
953                                                    path->slots[0],
954                                                    ref_objectid,
955                                                    name, namelen, NULL))
956                         match = 1;
957
958                 goto out;
959         }
960
961         item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
962         ptr_end = ptr + item_size;
963         while (ptr < ptr_end) {
964                 ref = (struct btrfs_inode_ref *)ptr;
965                 found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
966                 if (found_name_len == namelen) {
967                         name_ptr = (unsigned long)(ref + 1);
968                         ret = memcmp_extent_buffer(path->nodes[0], name,
969                                                    name_ptr, namelen);
970                         if (ret == 0) {
971                                 match = 1;
972                                 goto out;
973                         }
974                 }
975                 ptr = (unsigned long)(ref + 1) + found_name_len;
976         }
977 out:
978         btrfs_free_path(path);
979         return match;
980 }
981
982 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
983                                   struct btrfs_root *root,
984                                   struct btrfs_path *path,
985                                   struct btrfs_root *log_root,
986                                   struct btrfs_inode *dir,
987                                   struct btrfs_inode *inode,
988                                   u64 inode_objectid, u64 parent_objectid,
989                                   u64 ref_index, char *name, int namelen,
990                                   int *search_done)
991 {
992         int ret;
993         char *victim_name;
994         int victim_name_len;
995         struct extent_buffer *leaf;
996         struct btrfs_dir_item *di;
997         struct btrfs_key search_key;
998         struct btrfs_inode_extref *extref;
999
1000 again:
1001         /* Search old style refs */
1002         search_key.objectid = inode_objectid;
1003         search_key.type = BTRFS_INODE_REF_KEY;
1004         search_key.offset = parent_objectid;
1005         ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1006         if (ret == 0) {
1007                 struct btrfs_inode_ref *victim_ref;
1008                 unsigned long ptr;
1009                 unsigned long ptr_end;
1010
1011                 leaf = path->nodes[0];
1012
1013                 /* are we trying to overwrite a back ref for the root directory
1014                  * if so, just jump out, we're done
1015                  */
1016                 if (search_key.objectid == search_key.offset)
1017                         return 1;
1018
1019                 /* check all the names in this back reference to see
1020                  * if they are in the log.  if so, we allow them to stay
1021                  * otherwise they must be unlinked as a conflict
1022                  */
1023                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1024                 ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
1025                 while (ptr < ptr_end) {
1026                         victim_ref = (struct btrfs_inode_ref *)ptr;
1027                         victim_name_len = btrfs_inode_ref_name_len(leaf,
1028                                                                    victim_ref);
1029                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
1030                         if (!victim_name)
1031                                 return -ENOMEM;
1032
1033                         read_extent_buffer(leaf, victim_name,
1034                                            (unsigned long)(victim_ref + 1),
1035                                            victim_name_len);
1036
1037                         if (!backref_in_log(log_root, &search_key,
1038                                             parent_objectid,
1039                                             victim_name,
1040                                             victim_name_len)) {
1041                                 inc_nlink(&inode->vfs_inode);
1042                                 btrfs_release_path(path);
1043
1044                                 ret = btrfs_unlink_inode(trans, root, dir, inode,
1045                                                 victim_name, victim_name_len);
1046                                 kfree(victim_name);
1047                                 if (ret)
1048                                         return ret;
1049                                 ret = btrfs_run_delayed_items(trans);
1050                                 if (ret)
1051                                         return ret;
1052                                 *search_done = 1;
1053                                 goto again;
1054                         }
1055                         kfree(victim_name);
1056
1057                         ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
1058                 }
1059
1060                 /*
1061                  * NOTE: we have searched root tree and checked the
1062                  * corresponding ref, it does not need to check again.
1063                  */
1064                 *search_done = 1;
1065         }
1066         btrfs_release_path(path);
1067
1068         /* Same search but for extended refs */
1069         extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
1070                                            inode_objectid, parent_objectid, 0,
1071                                            0);
1072         if (!IS_ERR_OR_NULL(extref)) {
1073                 u32 item_size;
1074                 u32 cur_offset = 0;
1075                 unsigned long base;
1076                 struct inode *victim_parent;
1077
1078                 leaf = path->nodes[0];
1079
1080                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1081                 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1082
1083                 while (cur_offset < item_size) {
1084                         extref = (struct btrfs_inode_extref *)(base + cur_offset);
1085
1086                         victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
1087
1088                         if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1089                                 goto next;
1090
1091                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
1092                         if (!victim_name)
1093                                 return -ENOMEM;
1094                         read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1095                                            victim_name_len);
1096
1097                         search_key.objectid = inode_objectid;
1098                         search_key.type = BTRFS_INODE_EXTREF_KEY;
1099                         search_key.offset = btrfs_extref_hash(parent_objectid,
1100                                                               victim_name,
1101                                                               victim_name_len);
1102                         ret = 0;
1103                         if (!backref_in_log(log_root, &search_key,
1104                                             parent_objectid, victim_name,
1105                                             victim_name_len)) {
1106                                 ret = -ENOENT;
1107                                 victim_parent = read_one_inode(root,
1108                                                 parent_objectid);
1109                                 if (victim_parent) {
1110                                         inc_nlink(&inode->vfs_inode);
1111                                         btrfs_release_path(path);
1112
1113                                         ret = btrfs_unlink_inode(trans, root,
1114                                                         BTRFS_I(victim_parent),
1115                                                         inode,
1116                                                         victim_name,
1117                                                         victim_name_len);
1118                                         if (!ret)
1119                                                 ret = btrfs_run_delayed_items(
1120                                                                   trans);
1121                                 }
1122                                 iput(victim_parent);
1123                                 kfree(victim_name);
1124                                 if (ret)
1125                                         return ret;
1126                                 *search_done = 1;
1127                                 goto again;
1128                         }
1129                         kfree(victim_name);
1130 next:
1131                         cur_offset += victim_name_len + sizeof(*extref);
1132                 }
1133                 *search_done = 1;
1134         }
1135         btrfs_release_path(path);
1136
1137         /* look for a conflicting sequence number */
1138         di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1139                                          ref_index, name, namelen, 0);
1140         if (di && !IS_ERR(di)) {
1141                 ret = drop_one_dir_item(trans, root, path, dir, di);
1142                 if (ret)
1143                         return ret;
1144         }
1145         btrfs_release_path(path);
1146
1147         /* look for a conflicting name */
1148         di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
1149                                    name, namelen, 0);
1150         if (di && !IS_ERR(di)) {
1151                 ret = drop_one_dir_item(trans, root, path, dir, di);
1152                 if (ret)
1153                         return ret;
1154         }
1155         btrfs_release_path(path);
1156
1157         return 0;
1158 }
1159
1160 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1161                              u32 *namelen, char **name, u64 *index,
1162                              u64 *parent_objectid)
1163 {
1164         struct btrfs_inode_extref *extref;
1165
1166         extref = (struct btrfs_inode_extref *)ref_ptr;
1167
1168         *namelen = btrfs_inode_extref_name_len(eb, extref);
1169         *name = kmalloc(*namelen, GFP_NOFS);
1170         if (*name == NULL)
1171                 return -ENOMEM;
1172
1173         read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1174                            *namelen);
1175
1176         if (index)
1177                 *index = btrfs_inode_extref_index(eb, extref);
1178         if (parent_objectid)
1179                 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1180
1181         return 0;
1182 }
1183
1184 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1185                           u32 *namelen, char **name, u64 *index)
1186 {
1187         struct btrfs_inode_ref *ref;
1188
1189         ref = (struct btrfs_inode_ref *)ref_ptr;
1190
1191         *namelen = btrfs_inode_ref_name_len(eb, ref);
1192         *name = kmalloc(*namelen, GFP_NOFS);
1193         if (*name == NULL)
1194                 return -ENOMEM;
1195
1196         read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1197
1198         if (index)
1199                 *index = btrfs_inode_ref_index(eb, ref);
1200
1201         return 0;
1202 }
1203
1204 /*
1205  * Take an inode reference item from the log tree and iterate all names from the
1206  * inode reference item in the subvolume tree with the same key (if it exists).
1207  * For any name that is not in the inode reference item from the log tree, do a
1208  * proper unlink of that name (that is, remove its entry from the inode
1209  * reference item and both dir index keys).
1210  */
1211 static int unlink_old_inode_refs(struct btrfs_trans_handle *trans,
1212                                  struct btrfs_root *root,
1213                                  struct btrfs_path *path,
1214                                  struct btrfs_inode *inode,
1215                                  struct extent_buffer *log_eb,
1216                                  int log_slot,
1217                                  struct btrfs_key *key)
1218 {
1219         int ret;
1220         unsigned long ref_ptr;
1221         unsigned long ref_end;
1222         struct extent_buffer *eb;
1223
1224 again:
1225         btrfs_release_path(path);
1226         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1227         if (ret > 0) {
1228                 ret = 0;
1229                 goto out;
1230         }
1231         if (ret < 0)
1232                 goto out;
1233
1234         eb = path->nodes[0];
1235         ref_ptr = btrfs_item_ptr_offset(eb, path->slots[0]);
1236         ref_end = ref_ptr + btrfs_item_size_nr(eb, path->slots[0]);
1237         while (ref_ptr < ref_end) {
1238                 char *name = NULL;
1239                 int namelen;
1240                 u64 parent_id;
1241
1242                 if (key->type == BTRFS_INODE_EXTREF_KEY) {
1243                         ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1244                                                 NULL, &parent_id);
1245                 } else {
1246                         parent_id = key->offset;
1247                         ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1248                                              NULL);
1249                 }
1250                 if (ret)
1251                         goto out;
1252
1253                 if (key->type == BTRFS_INODE_EXTREF_KEY)
1254                         ret = btrfs_find_name_in_ext_backref(log_eb, log_slot,
1255                                                              parent_id, name,
1256                                                              namelen, NULL);
1257                 else
1258                         ret = btrfs_find_name_in_backref(log_eb, log_slot, name,
1259                                                          namelen, NULL);
1260
1261                 if (!ret) {
1262                         struct inode *dir;
1263
1264                         btrfs_release_path(path);
1265                         dir = read_one_inode(root, parent_id);
1266                         if (!dir) {
1267                                 ret = -ENOENT;
1268                                 kfree(name);
1269                                 goto out;
1270                         }
1271                         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
1272                                                  inode, name, namelen);
1273                         kfree(name);
1274                         iput(dir);
1275                         if (ret)
1276                                 goto out;
1277                         goto again;
1278                 }
1279
1280                 kfree(name);
1281                 ref_ptr += namelen;
1282                 if (key->type == BTRFS_INODE_EXTREF_KEY)
1283                         ref_ptr += sizeof(struct btrfs_inode_extref);
1284                 else
1285                         ref_ptr += sizeof(struct btrfs_inode_ref);
1286         }
1287         ret = 0;
1288  out:
1289         btrfs_release_path(path);
1290         return ret;
1291 }
1292
1293 static int btrfs_inode_ref_exists(struct inode *inode, struct inode *dir,
1294                                   const u8 ref_type, const char *name,
1295                                   const int namelen)
1296 {
1297         struct btrfs_key key;
1298         struct btrfs_path *path;
1299         const u64 parent_id = btrfs_ino(BTRFS_I(dir));
1300         int ret;
1301
1302         path = btrfs_alloc_path();
1303         if (!path)
1304                 return -ENOMEM;
1305
1306         key.objectid = btrfs_ino(BTRFS_I(inode));
1307         key.type = ref_type;
1308         if (key.type == BTRFS_INODE_REF_KEY)
1309                 key.offset = parent_id;
1310         else
1311                 key.offset = btrfs_extref_hash(parent_id, name, namelen);
1312
1313         ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &key, path, 0, 0);
1314         if (ret < 0)
1315                 goto out;
1316         if (ret > 0) {
1317                 ret = 0;
1318                 goto out;
1319         }
1320         if (key.type == BTRFS_INODE_EXTREF_KEY)
1321                 ret = btrfs_find_name_in_ext_backref(path->nodes[0],
1322                                                      path->slots[0], parent_id,
1323                                                      name, namelen, NULL);
1324         else
1325                 ret = btrfs_find_name_in_backref(path->nodes[0], path->slots[0],
1326                                                  name, namelen, NULL);
1327
1328 out:
1329         btrfs_free_path(path);
1330         return ret;
1331 }
1332
1333 static int add_link(struct btrfs_trans_handle *trans, struct btrfs_root *root,
1334                     struct inode *dir, struct inode *inode, const char *name,
1335                     int namelen, u64 ref_index)
1336 {
1337         struct btrfs_dir_item *dir_item;
1338         struct btrfs_key key;
1339         struct btrfs_path *path;
1340         struct inode *other_inode = NULL;
1341         int ret;
1342
1343         path = btrfs_alloc_path();
1344         if (!path)
1345                 return -ENOMEM;
1346
1347         dir_item = btrfs_lookup_dir_item(NULL, root, path,
1348                                          btrfs_ino(BTRFS_I(dir)),
1349                                          name, namelen, 0);
1350         if (!dir_item) {
1351                 btrfs_release_path(path);
1352                 goto add_link;
1353         } else if (IS_ERR(dir_item)) {
1354                 ret = PTR_ERR(dir_item);
1355                 goto out;
1356         }
1357
1358         /*
1359          * Our inode's dentry collides with the dentry of another inode which is
1360          * in the log but not yet processed since it has a higher inode number.
1361          * So delete that other dentry.
1362          */
1363         btrfs_dir_item_key_to_cpu(path->nodes[0], dir_item, &key);
1364         btrfs_release_path(path);
1365         other_inode = read_one_inode(root, key.objectid);
1366         if (!other_inode) {
1367                 ret = -ENOENT;
1368                 goto out;
1369         }
1370         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir), BTRFS_I(other_inode),
1371                                  name, namelen);
1372         if (ret)
1373                 goto out;
1374         /*
1375          * If we dropped the link count to 0, bump it so that later the iput()
1376          * on the inode will not free it. We will fixup the link count later.
1377          */
1378         if (other_inode->i_nlink == 0)
1379                 inc_nlink(other_inode);
1380
1381         ret = btrfs_run_delayed_items(trans);
1382         if (ret)
1383                 goto out;
1384 add_link:
1385         ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
1386                              name, namelen, 0, ref_index);
1387 out:
1388         iput(other_inode);
1389         btrfs_free_path(path);
1390
1391         return ret;
1392 }
1393
1394 /*
1395  * replay one inode back reference item found in the log tree.
1396  * eb, slot and key refer to the buffer and key found in the log tree.
1397  * root is the destination we are replaying into, and path is for temp
1398  * use by this function.  (it should be released on return).
1399  */
1400 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1401                                   struct btrfs_root *root,
1402                                   struct btrfs_root *log,
1403                                   struct btrfs_path *path,
1404                                   struct extent_buffer *eb, int slot,
1405                                   struct btrfs_key *key)
1406 {
1407         struct inode *dir = NULL;
1408         struct inode *inode = NULL;
1409         unsigned long ref_ptr;
1410         unsigned long ref_end;
1411         char *name = NULL;
1412         int namelen;
1413         int ret;
1414         int search_done = 0;
1415         int log_ref_ver = 0;
1416         u64 parent_objectid;
1417         u64 inode_objectid;
1418         u64 ref_index = 0;
1419         int ref_struct_size;
1420
1421         ref_ptr = btrfs_item_ptr_offset(eb, slot);
1422         ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1423
1424         if (key->type == BTRFS_INODE_EXTREF_KEY) {
1425                 struct btrfs_inode_extref *r;
1426
1427                 ref_struct_size = sizeof(struct btrfs_inode_extref);
1428                 log_ref_ver = 1;
1429                 r = (struct btrfs_inode_extref *)ref_ptr;
1430                 parent_objectid = btrfs_inode_extref_parent(eb, r);
1431         } else {
1432                 ref_struct_size = sizeof(struct btrfs_inode_ref);
1433                 parent_objectid = key->offset;
1434         }
1435         inode_objectid = key->objectid;
1436
1437         /*
1438          * it is possible that we didn't log all the parent directories
1439          * for a given inode.  If we don't find the dir, just don't
1440          * copy the back ref in.  The link count fixup code will take
1441          * care of the rest
1442          */
1443         dir = read_one_inode(root, parent_objectid);
1444         if (!dir) {
1445                 ret = -ENOENT;
1446                 goto out;
1447         }
1448
1449         inode = read_one_inode(root, inode_objectid);
1450         if (!inode) {
1451                 ret = -EIO;
1452                 goto out;
1453         }
1454
1455         while (ref_ptr < ref_end) {
1456                 if (log_ref_ver) {
1457                         ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1458                                                 &ref_index, &parent_objectid);
1459                         /*
1460                          * parent object can change from one array
1461                          * item to another.
1462                          */
1463                         if (!dir)
1464                                 dir = read_one_inode(root, parent_objectid);
1465                         if (!dir) {
1466                                 ret = -ENOENT;
1467                                 goto out;
1468                         }
1469                 } else {
1470                         ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1471                                              &ref_index);
1472                 }
1473                 if (ret)
1474                         goto out;
1475
1476                 /* if we already have a perfect match, we're done */
1477                 if (!inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1478                                         btrfs_ino(BTRFS_I(inode)), ref_index,
1479                                         name, namelen)) {
1480                         /*
1481                          * look for a conflicting back reference in the
1482                          * metadata. if we find one we have to unlink that name
1483                          * of the file before we add our new link.  Later on, we
1484                          * overwrite any existing back reference, and we don't
1485                          * want to create dangling pointers in the directory.
1486                          */
1487
1488                         if (!search_done) {
1489                                 ret = __add_inode_ref(trans, root, path, log,
1490                                                       BTRFS_I(dir),
1491                                                       BTRFS_I(inode),
1492                                                       inode_objectid,
1493                                                       parent_objectid,
1494                                                       ref_index, name, namelen,
1495                                                       &search_done);
1496                                 if (ret) {
1497                                         if (ret == 1)
1498                                                 ret = 0;
1499                                         goto out;
1500                                 }
1501                         }
1502
1503                         /*
1504                          * If a reference item already exists for this inode
1505                          * with the same parent and name, but different index,
1506                          * drop it and the corresponding directory index entries
1507                          * from the parent before adding the new reference item
1508                          * and dir index entries, otherwise we would fail with
1509                          * -EEXIST returned from btrfs_add_link() below.
1510                          */
1511                         ret = btrfs_inode_ref_exists(inode, dir, key->type,
1512                                                      name, namelen);
1513                         if (ret > 0) {
1514                                 ret = btrfs_unlink_inode(trans, root,
1515                                                          BTRFS_I(dir),
1516                                                          BTRFS_I(inode),
1517                                                          name, namelen);
1518                                 /*
1519                                  * If we dropped the link count to 0, bump it so
1520                                  * that later the iput() on the inode will not
1521                                  * free it. We will fixup the link count later.
1522                                  */
1523                                 if (!ret && inode->i_nlink == 0)
1524                                         inc_nlink(inode);
1525                         }
1526                         if (ret < 0)
1527                                 goto out;
1528
1529                         /* insert our name */
1530                         ret = add_link(trans, root, dir, inode, name, namelen,
1531                                        ref_index);
1532                         if (ret)
1533                                 goto out;
1534
1535                         btrfs_update_inode(trans, root, inode);
1536                 }
1537
1538                 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1539                 kfree(name);
1540                 name = NULL;
1541                 if (log_ref_ver) {
1542                         iput(dir);
1543                         dir = NULL;
1544                 }
1545         }
1546
1547         /*
1548          * Before we overwrite the inode reference item in the subvolume tree
1549          * with the item from the log tree, we must unlink all names from the
1550          * parent directory that are in the subvolume's tree inode reference
1551          * item, otherwise we end up with an inconsistent subvolume tree where
1552          * dir index entries exist for a name but there is no inode reference
1553          * item with the same name.
1554          */
1555         ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1556                                     key);
1557         if (ret)
1558                 goto out;
1559
1560         /* finally write the back reference in the inode */
1561         ret = overwrite_item(trans, root, path, eb, slot, key);
1562 out:
1563         btrfs_release_path(path);
1564         kfree(name);
1565         iput(dir);
1566         iput(inode);
1567         return ret;
1568 }
1569
1570 static int insert_orphan_item(struct btrfs_trans_handle *trans,
1571                               struct btrfs_root *root, u64 ino)
1572 {
1573         int ret;
1574
1575         ret = btrfs_insert_orphan_item(trans, root, ino);
1576         if (ret == -EEXIST)
1577                 ret = 0;
1578
1579         return ret;
1580 }
1581
1582 static int count_inode_extrefs(struct btrfs_root *root,
1583                 struct btrfs_inode *inode, struct btrfs_path *path)
1584 {
1585         int ret = 0;
1586         int name_len;
1587         unsigned int nlink = 0;
1588         u32 item_size;
1589         u32 cur_offset = 0;
1590         u64 inode_objectid = btrfs_ino(inode);
1591         u64 offset = 0;
1592         unsigned long ptr;
1593         struct btrfs_inode_extref *extref;
1594         struct extent_buffer *leaf;
1595
1596         while (1) {
1597                 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1598                                             &extref, &offset);
1599                 if (ret)
1600                         break;
1601
1602                 leaf = path->nodes[0];
1603                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1604                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1605                 cur_offset = 0;
1606
1607                 while (cur_offset < item_size) {
1608                         extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1609                         name_len = btrfs_inode_extref_name_len(leaf, extref);
1610
1611                         nlink++;
1612
1613                         cur_offset += name_len + sizeof(*extref);
1614                 }
1615
1616                 offset++;
1617                 btrfs_release_path(path);
1618         }
1619         btrfs_release_path(path);
1620
1621         if (ret < 0 && ret != -ENOENT)
1622                 return ret;
1623         return nlink;
1624 }
1625
1626 static int count_inode_refs(struct btrfs_root *root,
1627                         struct btrfs_inode *inode, struct btrfs_path *path)
1628 {
1629         int ret;
1630         struct btrfs_key key;
1631         unsigned int nlink = 0;
1632         unsigned long ptr;
1633         unsigned long ptr_end;
1634         int name_len;
1635         u64 ino = btrfs_ino(inode);
1636
1637         key.objectid = ino;
1638         key.type = BTRFS_INODE_REF_KEY;
1639         key.offset = (u64)-1;
1640
1641         while (1) {
1642                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1643                 if (ret < 0)
1644                         break;
1645                 if (ret > 0) {
1646                         if (path->slots[0] == 0)
1647                                 break;
1648                         path->slots[0]--;
1649                 }
1650 process_slot:
1651                 btrfs_item_key_to_cpu(path->nodes[0], &key,
1652                                       path->slots[0]);
1653                 if (key.objectid != ino ||
1654                     key.type != BTRFS_INODE_REF_KEY)
1655                         break;
1656                 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1657                 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1658                                                    path->slots[0]);
1659                 while (ptr < ptr_end) {
1660                         struct btrfs_inode_ref *ref;
1661
1662                         ref = (struct btrfs_inode_ref *)ptr;
1663                         name_len = btrfs_inode_ref_name_len(path->nodes[0],
1664                                                             ref);
1665                         ptr = (unsigned long)(ref + 1) + name_len;
1666                         nlink++;
1667                 }
1668
1669                 if (key.offset == 0)
1670                         break;
1671                 if (path->slots[0] > 0) {
1672                         path->slots[0]--;
1673                         goto process_slot;
1674                 }
1675                 key.offset--;
1676                 btrfs_release_path(path);
1677         }
1678         btrfs_release_path(path);
1679
1680         return nlink;
1681 }
1682
1683 /*
1684  * There are a few corners where the link count of the file can't
1685  * be properly maintained during replay.  So, instead of adding
1686  * lots of complexity to the log code, we just scan the backrefs
1687  * for any file that has been through replay.
1688  *
1689  * The scan will update the link count on the inode to reflect the
1690  * number of back refs found.  If it goes down to zero, the iput
1691  * will free the inode.
1692  */
1693 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1694                                            struct btrfs_root *root,
1695                                            struct inode *inode)
1696 {
1697         struct btrfs_path *path;
1698         int ret;
1699         u64 nlink = 0;
1700         u64 ino = btrfs_ino(BTRFS_I(inode));
1701
1702         path = btrfs_alloc_path();
1703         if (!path)
1704                 return -ENOMEM;
1705
1706         ret = count_inode_refs(root, BTRFS_I(inode), path);
1707         if (ret < 0)
1708                 goto out;
1709
1710         nlink = ret;
1711
1712         ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1713         if (ret < 0)
1714                 goto out;
1715
1716         nlink += ret;
1717
1718         ret = 0;
1719
1720         if (nlink != inode->i_nlink) {
1721                 set_nlink(inode, nlink);
1722                 btrfs_update_inode(trans, root, inode);
1723         }
1724         BTRFS_I(inode)->index_cnt = (u64)-1;
1725
1726         if (inode->i_nlink == 0) {
1727                 if (S_ISDIR(inode->i_mode)) {
1728                         ret = replay_dir_deletes(trans, root, NULL, path,
1729                                                  ino, 1);
1730                         if (ret)
1731                                 goto out;
1732                 }
1733                 ret = insert_orphan_item(trans, root, ino);
1734         }
1735
1736 out:
1737         btrfs_free_path(path);
1738         return ret;
1739 }
1740
1741 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1742                                             struct btrfs_root *root,
1743                                             struct btrfs_path *path)
1744 {
1745         int ret;
1746         struct btrfs_key key;
1747         struct inode *inode;
1748
1749         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1750         key.type = BTRFS_ORPHAN_ITEM_KEY;
1751         key.offset = (u64)-1;
1752         while (1) {
1753                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1754                 if (ret < 0)
1755                         break;
1756
1757                 if (ret == 1) {
1758                         if (path->slots[0] == 0)
1759                                 break;
1760                         path->slots[0]--;
1761                 }
1762
1763                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1764                 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1765                     key.type != BTRFS_ORPHAN_ITEM_KEY)
1766                         break;
1767
1768                 ret = btrfs_del_item(trans, root, path);
1769                 if (ret)
1770                         goto out;
1771
1772                 btrfs_release_path(path);
1773                 inode = read_one_inode(root, key.offset);
1774                 if (!inode)
1775                         return -EIO;
1776
1777                 ret = fixup_inode_link_count(trans, root, inode);
1778                 iput(inode);
1779                 if (ret)
1780                         goto out;
1781
1782                 /*
1783                  * fixup on a directory may create new entries,
1784                  * make sure we always look for the highset possible
1785                  * offset
1786                  */
1787                 key.offset = (u64)-1;
1788         }
1789         ret = 0;
1790 out:
1791         btrfs_release_path(path);
1792         return ret;
1793 }
1794
1795
1796 /*
1797  * record a given inode in the fixup dir so we can check its link
1798  * count when replay is done.  The link count is incremented here
1799  * so the inode won't go away until we check it
1800  */
1801 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1802                                       struct btrfs_root *root,
1803                                       struct btrfs_path *path,
1804                                       u64 objectid)
1805 {
1806         struct btrfs_key key;
1807         int ret = 0;
1808         struct inode *inode;
1809
1810         inode = read_one_inode(root, objectid);
1811         if (!inode)
1812                 return -EIO;
1813
1814         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1815         key.type = BTRFS_ORPHAN_ITEM_KEY;
1816         key.offset = objectid;
1817
1818         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1819
1820         btrfs_release_path(path);
1821         if (ret == 0) {
1822                 if (!inode->i_nlink)
1823                         set_nlink(inode, 1);
1824                 else
1825                         inc_nlink(inode);
1826                 ret = btrfs_update_inode(trans, root, inode);
1827         } else if (ret == -EEXIST) {
1828                 ret = 0;
1829         } else {
1830                 BUG(); /* Logic Error */
1831         }
1832         iput(inode);
1833
1834         return ret;
1835 }
1836
1837 /*
1838  * when replaying the log for a directory, we only insert names
1839  * for inodes that actually exist.  This means an fsync on a directory
1840  * does not implicitly fsync all the new files in it
1841  */
1842 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1843                                     struct btrfs_root *root,
1844                                     u64 dirid, u64 index,
1845                                     char *name, int name_len,
1846                                     struct btrfs_key *location)
1847 {
1848         struct inode *inode;
1849         struct inode *dir;
1850         int ret;
1851
1852         inode = read_one_inode(root, location->objectid);
1853         if (!inode)
1854                 return -ENOENT;
1855
1856         dir = read_one_inode(root, dirid);
1857         if (!dir) {
1858                 iput(inode);
1859                 return -EIO;
1860         }
1861
1862         ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1863                         name_len, 1, index);
1864
1865         /* FIXME, put inode into FIXUP list */
1866
1867         iput(inode);
1868         iput(dir);
1869         return ret;
1870 }
1871
1872 /*
1873  * Return true if an inode reference exists in the log for the given name,
1874  * inode and parent inode.
1875  */
1876 static bool name_in_log_ref(struct btrfs_root *log_root,
1877                             const char *name, const int name_len,
1878                             const u64 dirid, const u64 ino)
1879 {
1880         struct btrfs_key search_key;
1881
1882         search_key.objectid = ino;
1883         search_key.type = BTRFS_INODE_REF_KEY;
1884         search_key.offset = dirid;
1885         if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1886                 return true;
1887
1888         search_key.type = BTRFS_INODE_EXTREF_KEY;
1889         search_key.offset = btrfs_extref_hash(dirid, name, name_len);
1890         if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1891                 return true;
1892
1893         return false;
1894 }
1895
1896 /*
1897  * take a single entry in a log directory item and replay it into
1898  * the subvolume.
1899  *
1900  * if a conflicting item exists in the subdirectory already,
1901  * the inode it points to is unlinked and put into the link count
1902  * fix up tree.
1903  *
1904  * If a name from the log points to a file or directory that does
1905  * not exist in the FS, it is skipped.  fsyncs on directories
1906  * do not force down inodes inside that directory, just changes to the
1907  * names or unlinks in a directory.
1908  *
1909  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1910  * non-existing inode) and 1 if the name was replayed.
1911  */
1912 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1913                                     struct btrfs_root *root,
1914                                     struct btrfs_path *path,
1915                                     struct extent_buffer *eb,
1916                                     struct btrfs_dir_item *di,
1917                                     struct btrfs_key *key)
1918 {
1919         char *name;
1920         int name_len;
1921         struct btrfs_dir_item *dst_di;
1922         struct btrfs_key found_key;
1923         struct btrfs_key log_key;
1924         struct inode *dir;
1925         u8 log_type;
1926         int exists;
1927         int ret = 0;
1928         bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
1929         bool name_added = false;
1930
1931         dir = read_one_inode(root, key->objectid);
1932         if (!dir)
1933                 return -EIO;
1934
1935         name_len = btrfs_dir_name_len(eb, di);
1936         name = kmalloc(name_len, GFP_NOFS);
1937         if (!name) {
1938                 ret = -ENOMEM;
1939                 goto out;
1940         }
1941
1942         log_type = btrfs_dir_type(eb, di);
1943         read_extent_buffer(eb, name, (unsigned long)(di + 1),
1944                    name_len);
1945
1946         btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1947         exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1948         if (exists == 0)
1949                 exists = 1;
1950         else
1951                 exists = 0;
1952         btrfs_release_path(path);
1953
1954         if (key->type == BTRFS_DIR_ITEM_KEY) {
1955                 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1956                                        name, name_len, 1);
1957         } else if (key->type == BTRFS_DIR_INDEX_KEY) {
1958                 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1959                                                      key->objectid,
1960                                                      key->offset, name,
1961                                                      name_len, 1);
1962         } else {
1963                 /* Corruption */
1964                 ret = -EINVAL;
1965                 goto out;
1966         }
1967         if (IS_ERR_OR_NULL(dst_di)) {
1968                 /* we need a sequence number to insert, so we only
1969                  * do inserts for the BTRFS_DIR_INDEX_KEY types
1970                  */
1971                 if (key->type != BTRFS_DIR_INDEX_KEY)
1972                         goto out;
1973                 goto insert;
1974         }
1975
1976         btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1977         /* the existing item matches the logged item */
1978         if (found_key.objectid == log_key.objectid &&
1979             found_key.type == log_key.type &&
1980             found_key.offset == log_key.offset &&
1981             btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
1982                 update_size = false;
1983                 goto out;
1984         }
1985
1986         /*
1987          * don't drop the conflicting directory entry if the inode
1988          * for the new entry doesn't exist
1989          */
1990         if (!exists)
1991                 goto out;
1992
1993         ret = drop_one_dir_item(trans, root, path, BTRFS_I(dir), dst_di);
1994         if (ret)
1995                 goto out;
1996
1997         if (key->type == BTRFS_DIR_INDEX_KEY)
1998                 goto insert;
1999 out:
2000         btrfs_release_path(path);
2001         if (!ret && update_size) {
2002                 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
2003                 ret = btrfs_update_inode(trans, root, dir);
2004         }
2005         kfree(name);
2006         iput(dir);
2007         if (!ret && name_added)
2008                 ret = 1;
2009         return ret;
2010
2011 insert:
2012         if (name_in_log_ref(root->log_root, name, name_len,
2013                             key->objectid, log_key.objectid)) {
2014                 /* The dentry will be added later. */
2015                 ret = 0;
2016                 update_size = false;
2017                 goto out;
2018         }
2019         btrfs_release_path(path);
2020         ret = insert_one_name(trans, root, key->objectid, key->offset,
2021                               name, name_len, &log_key);
2022         if (ret && ret != -ENOENT && ret != -EEXIST)
2023                 goto out;
2024         if (!ret)
2025                 name_added = true;
2026         update_size = false;
2027         ret = 0;
2028         goto out;
2029 }
2030
2031 /*
2032  * find all the names in a directory item and reconcile them into
2033  * the subvolume.  Only BTRFS_DIR_ITEM_KEY types will have more than
2034  * one name in a directory item, but the same code gets used for
2035  * both directory index types
2036  */
2037 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
2038                                         struct btrfs_root *root,
2039                                         struct btrfs_path *path,
2040                                         struct extent_buffer *eb, int slot,
2041                                         struct btrfs_key *key)
2042 {
2043         int ret = 0;
2044         u32 item_size = btrfs_item_size_nr(eb, slot);
2045         struct btrfs_dir_item *di;
2046         int name_len;
2047         unsigned long ptr;
2048         unsigned long ptr_end;
2049         struct btrfs_path *fixup_path = NULL;
2050
2051         ptr = btrfs_item_ptr_offset(eb, slot);
2052         ptr_end = ptr + item_size;
2053         while (ptr < ptr_end) {
2054                 di = (struct btrfs_dir_item *)ptr;
2055                 name_len = btrfs_dir_name_len(eb, di);
2056                 ret = replay_one_name(trans, root, path, eb, di, key);
2057                 if (ret < 0)
2058                         break;
2059                 ptr = (unsigned long)(di + 1);
2060                 ptr += name_len;
2061
2062                 /*
2063                  * If this entry refers to a non-directory (directories can not
2064                  * have a link count > 1) and it was added in the transaction
2065                  * that was not committed, make sure we fixup the link count of
2066                  * the inode it the entry points to. Otherwise something like
2067                  * the following would result in a directory pointing to an
2068                  * inode with a wrong link that does not account for this dir
2069                  * entry:
2070                  *
2071                  * mkdir testdir
2072                  * touch testdir/foo
2073                  * touch testdir/bar
2074                  * sync
2075                  *
2076                  * ln testdir/bar testdir/bar_link
2077                  * ln testdir/foo testdir/foo_link
2078                  * xfs_io -c "fsync" testdir/bar
2079                  *
2080                  * <power failure>
2081                  *
2082                  * mount fs, log replay happens
2083                  *
2084                  * File foo would remain with a link count of 1 when it has two
2085                  * entries pointing to it in the directory testdir. This would
2086                  * make it impossible to ever delete the parent directory has
2087                  * it would result in stale dentries that can never be deleted.
2088                  */
2089                 if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
2090                         struct btrfs_key di_key;
2091
2092                         if (!fixup_path) {
2093                                 fixup_path = btrfs_alloc_path();
2094                                 if (!fixup_path) {
2095                                         ret = -ENOMEM;
2096                                         break;
2097                                 }
2098                         }
2099
2100                         btrfs_dir_item_key_to_cpu(eb, di, &di_key);
2101                         ret = link_to_fixup_dir(trans, root, fixup_path,
2102                                                 di_key.objectid);
2103                         if (ret)
2104                                 break;
2105                 }
2106                 ret = 0;
2107         }
2108         btrfs_free_path(fixup_path);
2109         return ret;
2110 }
2111
2112 /*
2113  * directory replay has two parts.  There are the standard directory
2114  * items in the log copied from the subvolume, and range items
2115  * created in the log while the subvolume was logged.
2116  *
2117  * The range items tell us which parts of the key space the log
2118  * is authoritative for.  During replay, if a key in the subvolume
2119  * directory is in a logged range item, but not actually in the log
2120  * that means it was deleted from the directory before the fsync
2121  * and should be removed.
2122  */
2123 static noinline int find_dir_range(struct btrfs_root *root,
2124                                    struct btrfs_path *path,
2125                                    u64 dirid, int key_type,
2126                                    u64 *start_ret, u64 *end_ret)
2127 {
2128         struct btrfs_key key;
2129         u64 found_end;
2130         struct btrfs_dir_log_item *item;
2131         int ret;
2132         int nritems;
2133
2134         if (*start_ret == (u64)-1)
2135                 return 1;
2136
2137         key.objectid = dirid;
2138         key.type = key_type;
2139         key.offset = *start_ret;
2140
2141         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2142         if (ret < 0)
2143                 goto out;
2144         if (ret > 0) {
2145                 if (path->slots[0] == 0)
2146                         goto out;
2147                 path->slots[0]--;
2148         }
2149         if (ret != 0)
2150                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2151
2152         if (key.type != key_type || key.objectid != dirid) {
2153                 ret = 1;
2154                 goto next;
2155         }
2156         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2157                               struct btrfs_dir_log_item);
2158         found_end = btrfs_dir_log_end(path->nodes[0], item);
2159
2160         if (*start_ret >= key.offset && *start_ret <= found_end) {
2161                 ret = 0;
2162                 *start_ret = key.offset;
2163                 *end_ret = found_end;
2164                 goto out;
2165         }
2166         ret = 1;
2167 next:
2168         /* check the next slot in the tree to see if it is a valid item */
2169         nritems = btrfs_header_nritems(path->nodes[0]);
2170         path->slots[0]++;
2171         if (path->slots[0] >= nritems) {
2172                 ret = btrfs_next_leaf(root, path);
2173                 if (ret)
2174                         goto out;
2175         }
2176
2177         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2178
2179         if (key.type != key_type || key.objectid != dirid) {
2180                 ret = 1;
2181                 goto out;
2182         }
2183         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2184                               struct btrfs_dir_log_item);
2185         found_end = btrfs_dir_log_end(path->nodes[0], item);
2186         *start_ret = key.offset;
2187         *end_ret = found_end;
2188         ret = 0;
2189 out:
2190         btrfs_release_path(path);
2191         return ret;
2192 }
2193
2194 /*
2195  * this looks for a given directory item in the log.  If the directory
2196  * item is not in the log, the item is removed and the inode it points
2197  * to is unlinked
2198  */
2199 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2200                                       struct btrfs_root *root,
2201                                       struct btrfs_root *log,
2202                                       struct btrfs_path *path,
2203                                       struct btrfs_path *log_path,
2204                                       struct inode *dir,
2205                                       struct btrfs_key *dir_key)
2206 {
2207         int ret;
2208         struct extent_buffer *eb;
2209         int slot;
2210         u32 item_size;
2211         struct btrfs_dir_item *di;
2212         struct btrfs_dir_item *log_di;
2213         int name_len;
2214         unsigned long ptr;
2215         unsigned long ptr_end;
2216         char *name;
2217         struct inode *inode;
2218         struct btrfs_key location;
2219
2220 again:
2221         eb = path->nodes[0];
2222         slot = path->slots[0];
2223         item_size = btrfs_item_size_nr(eb, slot);
2224         ptr = btrfs_item_ptr_offset(eb, slot);
2225         ptr_end = ptr + item_size;
2226         while (ptr < ptr_end) {
2227                 di = (struct btrfs_dir_item *)ptr;
2228                 name_len = btrfs_dir_name_len(eb, di);
2229                 name = kmalloc(name_len, GFP_NOFS);
2230                 if (!name) {
2231                         ret = -ENOMEM;
2232                         goto out;
2233                 }
2234                 read_extent_buffer(eb, name, (unsigned long)(di + 1),
2235                                   name_len);
2236                 log_di = NULL;
2237                 if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
2238                         log_di = btrfs_lookup_dir_item(trans, log, log_path,
2239                                                        dir_key->objectid,
2240                                                        name, name_len, 0);
2241                 } else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
2242                         log_di = btrfs_lookup_dir_index_item(trans, log,
2243                                                      log_path,
2244                                                      dir_key->objectid,
2245                                                      dir_key->offset,
2246                                                      name, name_len, 0);
2247                 }
2248                 if (!log_di || log_di == ERR_PTR(-ENOENT)) {
2249                         btrfs_dir_item_key_to_cpu(eb, di, &location);
2250                         btrfs_release_path(path);
2251                         btrfs_release_path(log_path);
2252                         inode = read_one_inode(root, location.objectid);
2253                         if (!inode) {
2254                                 kfree(name);
2255                                 return -EIO;
2256                         }
2257
2258                         ret = link_to_fixup_dir(trans, root,
2259                                                 path, location.objectid);
2260                         if (ret) {
2261                                 kfree(name);
2262                                 iput(inode);
2263                                 goto out;
2264                         }
2265
2266                         inc_nlink(inode);
2267                         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
2268                                         BTRFS_I(inode), name, name_len);
2269                         if (!ret)
2270                                 ret = btrfs_run_delayed_items(trans);
2271                         kfree(name);
2272                         iput(inode);
2273                         if (ret)
2274                                 goto out;
2275
2276                         /* there might still be more names under this key
2277                          * check and repeat if required
2278                          */
2279                         ret = btrfs_search_slot(NULL, root, dir_key, path,
2280                                                 0, 0);
2281                         if (ret == 0)
2282                                 goto again;
2283                         ret = 0;
2284                         goto out;
2285                 } else if (IS_ERR(log_di)) {
2286                         kfree(name);
2287                         return PTR_ERR(log_di);
2288                 }
2289                 btrfs_release_path(log_path);
2290                 kfree(name);
2291
2292                 ptr = (unsigned long)(di + 1);
2293                 ptr += name_len;
2294         }
2295         ret = 0;
2296 out:
2297         btrfs_release_path(path);
2298         btrfs_release_path(log_path);
2299         return ret;
2300 }
2301
2302 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2303                               struct btrfs_root *root,
2304                               struct btrfs_root *log,
2305                               struct btrfs_path *path,
2306                               const u64 ino)
2307 {
2308         struct btrfs_key search_key;
2309         struct btrfs_path *log_path;
2310         int i;
2311         int nritems;
2312         int ret;
2313
2314         log_path = btrfs_alloc_path();
2315         if (!log_path)
2316                 return -ENOMEM;
2317
2318         search_key.objectid = ino;
2319         search_key.type = BTRFS_XATTR_ITEM_KEY;
2320         search_key.offset = 0;
2321 again:
2322         ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2323         if (ret < 0)
2324                 goto out;
2325 process_leaf:
2326         nritems = btrfs_header_nritems(path->nodes[0]);
2327         for (i = path->slots[0]; i < nritems; i++) {
2328                 struct btrfs_key key;
2329                 struct btrfs_dir_item *di;
2330                 struct btrfs_dir_item *log_di;
2331                 u32 total_size;
2332                 u32 cur;
2333
2334                 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2335                 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2336                         ret = 0;
2337                         goto out;
2338                 }
2339
2340                 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2341                 total_size = btrfs_item_size_nr(path->nodes[0], i);
2342                 cur = 0;
2343                 while (cur < total_size) {
2344                         u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2345                         u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2346                         u32 this_len = sizeof(*di) + name_len + data_len;
2347                         char *name;
2348
2349                         name = kmalloc(name_len, GFP_NOFS);
2350                         if (!name) {
2351                                 ret = -ENOMEM;
2352                                 goto out;
2353                         }
2354                         read_extent_buffer(path->nodes[0], name,
2355                                            (unsigned long)(di + 1), name_len);
2356
2357                         log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2358                                                     name, name_len, 0);
2359                         btrfs_release_path(log_path);
2360                         if (!log_di) {
2361                                 /* Doesn't exist in log tree, so delete it. */
2362                                 btrfs_release_path(path);
2363                                 di = btrfs_lookup_xattr(trans, root, path, ino,
2364                                                         name, name_len, -1);
2365                                 kfree(name);
2366                                 if (IS_ERR(di)) {
2367                                         ret = PTR_ERR(di);
2368                                         goto out;
2369                                 }
2370                                 ASSERT(di);
2371                                 ret = btrfs_delete_one_dir_name(trans, root,
2372                                                                 path, di);
2373                                 if (ret)
2374                                         goto out;
2375                                 btrfs_release_path(path);
2376                                 search_key = key;
2377                                 goto again;
2378                         }
2379                         kfree(name);
2380                         if (IS_ERR(log_di)) {
2381                                 ret = PTR_ERR(log_di);
2382                                 goto out;
2383                         }
2384                         cur += this_len;
2385                         di = (struct btrfs_dir_item *)((char *)di + this_len);
2386                 }
2387         }
2388         ret = btrfs_next_leaf(root, path);
2389         if (ret > 0)
2390                 ret = 0;
2391         else if (ret == 0)
2392                 goto process_leaf;
2393 out:
2394         btrfs_free_path(log_path);
2395         btrfs_release_path(path);
2396         return ret;
2397 }
2398
2399
2400 /*
2401  * deletion replay happens before we copy any new directory items
2402  * out of the log or out of backreferences from inodes.  It
2403  * scans the log to find ranges of keys that log is authoritative for,
2404  * and then scans the directory to find items in those ranges that are
2405  * not present in the log.
2406  *
2407  * Anything we don't find in the log is unlinked and removed from the
2408  * directory.
2409  */
2410 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2411                                        struct btrfs_root *root,
2412                                        struct btrfs_root *log,
2413                                        struct btrfs_path *path,
2414                                        u64 dirid, int del_all)
2415 {
2416         u64 range_start;
2417         u64 range_end;
2418         int key_type = BTRFS_DIR_LOG_ITEM_KEY;
2419         int ret = 0;
2420         struct btrfs_key dir_key;
2421         struct btrfs_key found_key;
2422         struct btrfs_path *log_path;
2423         struct inode *dir;
2424
2425         dir_key.objectid = dirid;
2426         dir_key.type = BTRFS_DIR_ITEM_KEY;
2427         log_path = btrfs_alloc_path();
2428         if (!log_path)
2429                 return -ENOMEM;
2430
2431         dir = read_one_inode(root, dirid);
2432         /* it isn't an error if the inode isn't there, that can happen
2433          * because we replay the deletes before we copy in the inode item
2434          * from the log
2435          */
2436         if (!dir) {
2437                 btrfs_free_path(log_path);
2438                 return 0;
2439         }
2440 again:
2441         range_start = 0;
2442         range_end = 0;
2443         while (1) {
2444                 if (del_all)
2445                         range_end = (u64)-1;
2446                 else {
2447                         ret = find_dir_range(log, path, dirid, key_type,
2448                                              &range_start, &range_end);
2449                         if (ret != 0)
2450                                 break;
2451                 }
2452
2453                 dir_key.offset = range_start;
2454                 while (1) {
2455                         int nritems;
2456                         ret = btrfs_search_slot(NULL, root, &dir_key, path,
2457                                                 0, 0);
2458                         if (ret < 0)
2459                                 goto out;
2460
2461                         nritems = btrfs_header_nritems(path->nodes[0]);
2462                         if (path->slots[0] >= nritems) {
2463                                 ret = btrfs_next_leaf(root, path);
2464                                 if (ret == 1)
2465                                         break;
2466                                 else if (ret < 0)
2467                                         goto out;
2468                         }
2469                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2470                                               path->slots[0]);
2471                         if (found_key.objectid != dirid ||
2472                             found_key.type != dir_key.type)
2473                                 goto next_type;
2474
2475                         if (found_key.offset > range_end)
2476                                 break;
2477
2478                         ret = check_item_in_log(trans, root, log, path,
2479                                                 log_path, dir,
2480                                                 &found_key);
2481                         if (ret)
2482                                 goto out;
2483                         if (found_key.offset == (u64)-1)
2484                                 break;
2485                         dir_key.offset = found_key.offset + 1;
2486                 }
2487                 btrfs_release_path(path);
2488                 if (range_end == (u64)-1)
2489                         break;
2490                 range_start = range_end + 1;
2491         }
2492
2493 next_type:
2494         ret = 0;
2495         if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
2496                 key_type = BTRFS_DIR_LOG_INDEX_KEY;
2497                 dir_key.type = BTRFS_DIR_INDEX_KEY;
2498                 btrfs_release_path(path);
2499                 goto again;
2500         }
2501 out:
2502         btrfs_release_path(path);
2503         btrfs_free_path(log_path);
2504         iput(dir);
2505         return ret;
2506 }
2507
2508 /*
2509  * the process_func used to replay items from the log tree.  This
2510  * gets called in two different stages.  The first stage just looks
2511  * for inodes and makes sure they are all copied into the subvolume.
2512  *
2513  * The second stage copies all the other item types from the log into
2514  * the subvolume.  The two stage approach is slower, but gets rid of
2515  * lots of complexity around inodes referencing other inodes that exist
2516  * only in the log (references come from either directory items or inode
2517  * back refs).
2518  */
2519 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2520                              struct walk_control *wc, u64 gen, int level)
2521 {
2522         int nritems;
2523         struct btrfs_path *path;
2524         struct btrfs_root *root = wc->replay_dest;
2525         struct btrfs_key key;
2526         int i;
2527         int ret;
2528
2529         ret = btrfs_read_buffer(eb, gen, level, NULL);
2530         if (ret)
2531                 return ret;
2532
2533         level = btrfs_header_level(eb);
2534
2535         if (level != 0)
2536                 return 0;
2537
2538         path = btrfs_alloc_path();
2539         if (!path)
2540                 return -ENOMEM;
2541
2542         nritems = btrfs_header_nritems(eb);
2543         for (i = 0; i < nritems; i++) {
2544                 btrfs_item_key_to_cpu(eb, &key, i);
2545
2546                 /* inode keys are done during the first stage */
2547                 if (key.type == BTRFS_INODE_ITEM_KEY &&
2548                     wc->stage == LOG_WALK_REPLAY_INODES) {
2549                         struct btrfs_inode_item *inode_item;
2550                         u32 mode;
2551
2552                         inode_item = btrfs_item_ptr(eb, i,
2553                                             struct btrfs_inode_item);
2554                         /*
2555                          * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2556                          * and never got linked before the fsync, skip it, as
2557                          * replaying it is pointless since it would be deleted
2558                          * later. We skip logging tmpfiles, but it's always
2559                          * possible we are replaying a log created with a kernel
2560                          * that used to log tmpfiles.
2561                          */
2562                         if (btrfs_inode_nlink(eb, inode_item) == 0) {
2563                                 wc->ignore_cur_inode = true;
2564                                 continue;
2565                         } else {
2566                                 wc->ignore_cur_inode = false;
2567                         }
2568                         ret = replay_xattr_deletes(wc->trans, root, log,
2569                                                    path, key.objectid);
2570                         if (ret)
2571                                 break;
2572                         mode = btrfs_inode_mode(eb, inode_item);
2573                         if (S_ISDIR(mode)) {
2574                                 ret = replay_dir_deletes(wc->trans,
2575                                          root, log, path, key.objectid, 0);
2576                                 if (ret)
2577                                         break;
2578                         }
2579                         ret = overwrite_item(wc->trans, root, path,
2580                                              eb, i, &key);
2581                         if (ret)
2582                                 break;
2583
2584                         /*
2585                          * Before replaying extents, truncate the inode to its
2586                          * size. We need to do it now and not after log replay
2587                          * because before an fsync we can have prealloc extents
2588                          * added beyond the inode's i_size. If we did it after,
2589                          * through orphan cleanup for example, we would drop
2590                          * those prealloc extents just after replaying them.
2591                          */
2592                         if (S_ISREG(mode)) {
2593                                 struct inode *inode;
2594                                 u64 from;
2595
2596                                 inode = read_one_inode(root, key.objectid);
2597                                 if (!inode) {
2598                                         ret = -EIO;
2599                                         break;
2600                                 }
2601                                 from = ALIGN(i_size_read(inode),
2602                                              root->fs_info->sectorsize);
2603                                 ret = btrfs_drop_extents(wc->trans, root, inode,
2604                                                          from, (u64)-1, 1);
2605                                 if (!ret) {
2606                                         /* Update the inode's nbytes. */
2607                                         ret = btrfs_update_inode(wc->trans,
2608                                                                  root, inode);
2609                                 }
2610                                 iput(inode);
2611                                 if (ret)
2612                                         break;
2613                         }
2614
2615                         ret = link_to_fixup_dir(wc->trans, root,
2616                                                 path, key.objectid);
2617                         if (ret)
2618                                 break;
2619                 }
2620
2621                 if (wc->ignore_cur_inode)
2622                         continue;
2623
2624                 if (key.type == BTRFS_DIR_INDEX_KEY &&
2625                     wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2626                         ret = replay_one_dir_item(wc->trans, root, path,
2627                                                   eb, i, &key);
2628                         if (ret)
2629                                 break;
2630                 }
2631
2632                 if (wc->stage < LOG_WALK_REPLAY_ALL)
2633                         continue;
2634
2635                 /* these keys are simply copied */
2636                 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2637                         ret = overwrite_item(wc->trans, root, path,
2638                                              eb, i, &key);
2639                         if (ret)
2640                                 break;
2641                 } else if (key.type == BTRFS_INODE_REF_KEY ||
2642                            key.type == BTRFS_INODE_EXTREF_KEY) {
2643                         ret = add_inode_ref(wc->trans, root, log, path,
2644                                             eb, i, &key);
2645                         if (ret && ret != -ENOENT)
2646                                 break;
2647                         ret = 0;
2648                 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2649                         ret = replay_one_extent(wc->trans, root, path,
2650                                                 eb, i, &key);
2651                         if (ret)
2652                                 break;
2653                 } else if (key.type == BTRFS_DIR_ITEM_KEY) {
2654                         ret = replay_one_dir_item(wc->trans, root, path,
2655                                                   eb, i, &key);
2656                         if (ret)
2657                                 break;
2658                 }
2659         }
2660         btrfs_free_path(path);
2661         return ret;
2662 }
2663
2664 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2665                                    struct btrfs_root *root,
2666                                    struct btrfs_path *path, int *level,
2667                                    struct walk_control *wc)
2668 {
2669         struct btrfs_fs_info *fs_info = root->fs_info;
2670         u64 root_owner;
2671         u64 bytenr;
2672         u64 ptr_gen;
2673         struct extent_buffer *next;
2674         struct extent_buffer *cur;
2675         struct extent_buffer *parent;
2676         u32 blocksize;
2677         int ret = 0;
2678
2679         WARN_ON(*level < 0);
2680         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2681
2682         while (*level > 0) {
2683                 struct btrfs_key first_key;
2684
2685                 WARN_ON(*level < 0);
2686                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2687                 cur = path->nodes[*level];
2688
2689                 WARN_ON(btrfs_header_level(cur) != *level);
2690
2691                 if (path->slots[*level] >=
2692                     btrfs_header_nritems(cur))
2693                         break;
2694
2695                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2696                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2697                 btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2698                 blocksize = fs_info->nodesize;
2699
2700                 parent = path->nodes[*level];
2701                 root_owner = btrfs_header_owner(parent);
2702
2703                 next = btrfs_find_create_tree_block(fs_info, bytenr);
2704                 if (IS_ERR(next))
2705                         return PTR_ERR(next);
2706
2707                 if (*level == 1) {
2708                         ret = wc->process_func(root, next, wc, ptr_gen,
2709                                                *level - 1);
2710                         if (ret) {
2711                                 free_extent_buffer(next);
2712                                 return ret;
2713                         }
2714
2715                         path->slots[*level]++;
2716                         if (wc->free) {
2717                                 ret = btrfs_read_buffer(next, ptr_gen,
2718                                                         *level - 1, &first_key);
2719                                 if (ret) {
2720                                         free_extent_buffer(next);
2721                                         return ret;
2722                                 }
2723
2724                                 if (trans) {
2725                                         btrfs_tree_lock(next);
2726                                         btrfs_set_lock_blocking_write(next);
2727                                         clean_tree_block(fs_info, next);
2728                                         btrfs_wait_tree_block_writeback(next);
2729                                         btrfs_tree_unlock(next);
2730                                 } else {
2731                                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2732                                                 clear_extent_buffer_dirty(next);
2733                                 }
2734
2735                                 WARN_ON(root_owner !=
2736                                         BTRFS_TREE_LOG_OBJECTID);
2737                                 ret = btrfs_free_and_pin_reserved_extent(
2738                                                         fs_info, bytenr,
2739                                                         blocksize);
2740                                 if (ret) {
2741                                         free_extent_buffer(next);
2742                                         return ret;
2743                                 }
2744                         }
2745                         free_extent_buffer(next);
2746                         continue;
2747                 }
2748                 ret = btrfs_read_buffer(next, ptr_gen, *level - 1, &first_key);
2749                 if (ret) {
2750                         free_extent_buffer(next);
2751                         return ret;
2752                 }
2753
2754                 WARN_ON(*level <= 0);
2755                 if (path->nodes[*level-1])
2756                         free_extent_buffer(path->nodes[*level-1]);
2757                 path->nodes[*level-1] = next;
2758                 *level = btrfs_header_level(next);
2759                 path->slots[*level] = 0;
2760                 cond_resched();
2761         }
2762         WARN_ON(*level < 0);
2763         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2764
2765         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2766
2767         cond_resched();
2768         return 0;
2769 }
2770
2771 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2772                                  struct btrfs_root *root,
2773                                  struct btrfs_path *path, int *level,
2774                                  struct walk_control *wc)
2775 {
2776         struct btrfs_fs_info *fs_info = root->fs_info;
2777         u64 root_owner;
2778         int i;
2779         int slot;
2780         int ret;
2781
2782         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2783                 slot = path->slots[i];
2784                 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2785                         path->slots[i]++;
2786                         *level = i;
2787                         WARN_ON(*level == 0);
2788                         return 0;
2789                 } else {
2790                         struct extent_buffer *parent;
2791                         if (path->nodes[*level] == root->node)
2792                                 parent = path->nodes[*level];
2793                         else
2794                                 parent = path->nodes[*level + 1];
2795
2796                         root_owner = btrfs_header_owner(parent);
2797                         ret = wc->process_func(root, path->nodes[*level], wc,
2798                                  btrfs_header_generation(path->nodes[*level]),
2799                                  *level);
2800                         if (ret)
2801                                 return ret;
2802
2803                         if (wc->free) {
2804                                 struct extent_buffer *next;
2805
2806                                 next = path->nodes[*level];
2807
2808                                 if (trans) {
2809                                         btrfs_tree_lock(next);
2810                                         btrfs_set_lock_blocking_write(next);
2811                                         clean_tree_block(fs_info, next);
2812                                         btrfs_wait_tree_block_writeback(next);
2813                                         btrfs_tree_unlock(next);
2814                                 } else {
2815                                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2816                                                 clear_extent_buffer_dirty(next);
2817                                 }
2818
2819                                 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2820                                 ret = btrfs_free_and_pin_reserved_extent(
2821                                                 fs_info,
2822                                                 path->nodes[*level]->start,
2823                                                 path->nodes[*level]->len);
2824                                 if (ret)
2825                                         return ret;
2826                         }
2827                         free_extent_buffer(path->nodes[*level]);
2828                         path->nodes[*level] = NULL;
2829                         *level = i + 1;
2830                 }
2831         }
2832         return 1;
2833 }
2834
2835 /*
2836  * drop the reference count on the tree rooted at 'snap'.  This traverses
2837  * the tree freeing any blocks that have a ref count of zero after being
2838  * decremented.
2839  */
2840 static int walk_log_tree(struct btrfs_trans_handle *trans,
2841                          struct btrfs_root *log, struct walk_control *wc)
2842 {
2843         struct btrfs_fs_info *fs_info = log->fs_info;
2844         int ret = 0;
2845         int wret;
2846         int level;
2847         struct btrfs_path *path;
2848         int orig_level;
2849
2850         path = btrfs_alloc_path();
2851         if (!path)
2852                 return -ENOMEM;
2853
2854         level = btrfs_header_level(log->node);
2855         orig_level = level;
2856         path->nodes[level] = log->node;
2857         extent_buffer_get(log->node);
2858         path->slots[level] = 0;
2859
2860         while (1) {
2861                 wret = walk_down_log_tree(trans, log, path, &level, wc);
2862                 if (wret > 0)
2863                         break;
2864                 if (wret < 0) {
2865                         ret = wret;
2866                         goto out;
2867                 }
2868
2869                 wret = walk_up_log_tree(trans, log, path, &level, wc);
2870                 if (wret > 0)
2871                         break;
2872                 if (wret < 0) {
2873                         ret = wret;
2874                         goto out;
2875                 }
2876         }
2877
2878         /* was the root node processed? if not, catch it here */
2879         if (path->nodes[orig_level]) {
2880                 ret = wc->process_func(log, path->nodes[orig_level], wc,
2881                          btrfs_header_generation(path->nodes[orig_level]),
2882                          orig_level);
2883                 if (ret)
2884                         goto out;
2885                 if (wc->free) {
2886                         struct extent_buffer *next;
2887
2888                         next = path->nodes[orig_level];
2889
2890                         if (trans) {
2891                                 btrfs_tree_lock(next);
2892                                 btrfs_set_lock_blocking_write(next);
2893                                 clean_tree_block(fs_info, next);
2894                                 btrfs_wait_tree_block_writeback(next);
2895                                 btrfs_tree_unlock(next);
2896                         } else {
2897                                 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2898                                         clear_extent_buffer_dirty(next);
2899                         }
2900
2901                         WARN_ON(log->root_key.objectid !=
2902                                 BTRFS_TREE_LOG_OBJECTID);
2903                         ret = btrfs_free_and_pin_reserved_extent(fs_info,
2904                                                         next->start, next->len);
2905                         if (ret)
2906                                 goto out;
2907                 }
2908         }
2909
2910 out:
2911         btrfs_free_path(path);
2912         return ret;
2913 }
2914
2915 /*
2916  * helper function to update the item for a given subvolumes log root
2917  * in the tree of log roots
2918  */
2919 static int update_log_root(struct btrfs_trans_handle *trans,
2920                            struct btrfs_root *log)
2921 {
2922         struct btrfs_fs_info *fs_info = log->fs_info;
2923         int ret;
2924
2925         if (log->log_transid == 1) {
2926                 /* insert root item on the first sync */
2927                 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2928                                 &log->root_key, &log->root_item);
2929         } else {
2930                 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2931                                 &log->root_key, &log->root_item);
2932         }
2933         return ret;
2934 }
2935
2936 static void wait_log_commit(struct btrfs_root *root, int transid)
2937 {
2938         DEFINE_WAIT(wait);
2939         int index = transid % 2;
2940
2941         /*
2942          * we only allow two pending log transactions at a time,
2943          * so we know that if ours is more than 2 older than the
2944          * current transaction, we're done
2945          */
2946         for (;;) {
2947                 prepare_to_wait(&root->log_commit_wait[index],
2948                                 &wait, TASK_UNINTERRUPTIBLE);
2949
2950                 if (!(root->log_transid_committed < transid &&
2951                       atomic_read(&root->log_commit[index])))
2952                         break;
2953
2954                 mutex_unlock(&root->log_mutex);
2955                 schedule();
2956                 mutex_lock(&root->log_mutex);
2957         }
2958         finish_wait(&root->log_commit_wait[index], &wait);
2959 }
2960
2961 static void wait_for_writer(struct btrfs_root *root)
2962 {
2963         DEFINE_WAIT(wait);
2964
2965         for (;;) {
2966                 prepare_to_wait(&root->log_writer_wait, &wait,
2967                                 TASK_UNINTERRUPTIBLE);
2968                 if (!atomic_read(&root->log_writers))
2969                         break;
2970
2971                 mutex_unlock(&root->log_mutex);
2972                 schedule();
2973                 mutex_lock(&root->log_mutex);
2974         }
2975         finish_wait(&root->log_writer_wait, &wait);
2976 }
2977
2978 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2979                                         struct btrfs_log_ctx *ctx)
2980 {
2981         if (!ctx)
2982                 return;
2983
2984         mutex_lock(&root->log_mutex);
2985         list_del_init(&ctx->list);
2986         mutex_unlock(&root->log_mutex);
2987 }