btrfs: simplify pointer chasing of local fs_info variables
[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 int btrfs_pin_log_trans(struct btrfs_root *root)
209 {
210         int ret = -ENOENT;
211
212         mutex_lock(&root->log_mutex);
213         atomic_inc(&root->log_writers);
214         mutex_unlock(&root->log_mutex);
215         return ret;
216 }
217
218 /*
219  * indicate we're done making changes to the log tree
220  * and wake up anyone waiting to do a sync
221  */
222 void btrfs_end_log_trans(struct btrfs_root *root)
223 {
224         if (atomic_dec_and_test(&root->log_writers)) {
225                 /* atomic_dec_and_test implies a barrier */
226                 cond_wake_up_nomb(&root->log_writer_wait);
227         }
228 }
229
230
231 /*
232  * the walk control struct is used to pass state down the chain when
233  * processing the log tree.  The stage field tells us which part
234  * of the log tree processing we are currently doing.  The others
235  * are state fields used for that specific part
236  */
237 struct walk_control {
238         /* should we free the extent on disk when done?  This is used
239          * at transaction commit time while freeing a log tree
240          */
241         int free;
242
243         /* should we write out the extent buffer?  This is used
244          * while flushing the log tree to disk during a sync
245          */
246         int write;
247
248         /* should we wait for the extent buffer io to finish?  Also used
249          * while flushing the log tree to disk for a sync
250          */
251         int wait;
252
253         /* pin only walk, we record which extents on disk belong to the
254          * log trees
255          */
256         int pin;
257
258         /* what stage of the replay code we're currently in */
259         int stage;
260
261         /* the root we are currently replaying */
262         struct btrfs_root *replay_dest;
263
264         /* the trans handle for the current replay */
265         struct btrfs_trans_handle *trans;
266
267         /* the function that gets used to process blocks we find in the
268          * tree.  Note the extent_buffer might not be up to date when it is
269          * passed in, and it must be checked or read if you need the data
270          * inside it
271          */
272         int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
273                             struct walk_control *wc, u64 gen, int level);
274 };
275
276 /*
277  * process_func used to pin down extents, write them or wait on them
278  */
279 static int process_one_buffer(struct btrfs_root *log,
280                               struct extent_buffer *eb,
281                               struct walk_control *wc, u64 gen, int level)
282 {
283         struct btrfs_fs_info *fs_info = log->fs_info;
284         int ret = 0;
285
286         /*
287          * If this fs is mixed then we need to be able to process the leaves to
288          * pin down any logged extents, so we have to read the block.
289          */
290         if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
291                 ret = btrfs_read_buffer(eb, gen, level, NULL);
292                 if (ret)
293                         return ret;
294         }
295
296         if (wc->pin)
297                 ret = btrfs_pin_extent_for_log_replay(fs_info, eb->start,
298                                                       eb->len);
299
300         if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
301                 if (wc->pin && btrfs_header_level(eb) == 0)
302                         ret = btrfs_exclude_logged_extents(fs_info, eb);
303                 if (wc->write)
304                         btrfs_write_tree_block(eb);
305                 if (wc->wait)
306                         btrfs_wait_tree_block_writeback(eb);
307         }
308         return ret;
309 }
310
311 /*
312  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
313  * to the src data we are copying out.
314  *
315  * root is the tree we are copying into, and path is a scratch
316  * path for use in this function (it should be released on entry and
317  * will be released on exit).
318  *
319  * If the key is already in the destination tree the existing item is
320  * overwritten.  If the existing item isn't big enough, it is extended.
321  * If it is too large, it is truncated.
322  *
323  * If the key isn't in the destination yet, a new item is inserted.
324  */
325 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
326                                    struct btrfs_root *root,
327                                    struct btrfs_path *path,
328                                    struct extent_buffer *eb, int slot,
329                                    struct btrfs_key *key)
330 {
331         struct btrfs_fs_info *fs_info = root->fs_info;
332         int ret;
333         u32 item_size;
334         u64 saved_i_size = 0;
335         int save_old_i_size = 0;
336         unsigned long src_ptr;
337         unsigned long dst_ptr;
338         int overwrite_root = 0;
339         bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
340
341         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
342                 overwrite_root = 1;
343
344         item_size = btrfs_item_size_nr(eb, slot);
345         src_ptr = btrfs_item_ptr_offset(eb, slot);
346
347         /* look for the key in the destination tree */
348         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
349         if (ret < 0)
350                 return ret;
351
352         if (ret == 0) {
353                 char *src_copy;
354                 char *dst_copy;
355                 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
356                                                   path->slots[0]);
357                 if (dst_size != item_size)
358                         goto insert;
359
360                 if (item_size == 0) {
361                         btrfs_release_path(path);
362                         return 0;
363                 }
364                 dst_copy = kmalloc(item_size, GFP_NOFS);
365                 src_copy = kmalloc(item_size, GFP_NOFS);
366                 if (!dst_copy || !src_copy) {
367                         btrfs_release_path(path);
368                         kfree(dst_copy);
369                         kfree(src_copy);
370                         return -ENOMEM;
371                 }
372
373                 read_extent_buffer(eb, src_copy, src_ptr, item_size);
374
375                 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
376                 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
377                                    item_size);
378                 ret = memcmp(dst_copy, src_copy, item_size);
379
380                 kfree(dst_copy);
381                 kfree(src_copy);
382                 /*
383                  * they have the same contents, just return, this saves
384                  * us from cowing blocks in the destination tree and doing
385                  * extra writes that may not have been done by a previous
386                  * sync
387                  */
388                 if (ret == 0) {
389                         btrfs_release_path(path);
390                         return 0;
391                 }
392
393                 /*
394                  * We need to load the old nbytes into the inode so when we
395                  * replay the extents we've logged we get the right nbytes.
396                  */
397                 if (inode_item) {
398                         struct btrfs_inode_item *item;
399                         u64 nbytes;
400                         u32 mode;
401
402                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
403                                               struct btrfs_inode_item);
404                         nbytes = btrfs_inode_nbytes(path->nodes[0], item);
405                         item = btrfs_item_ptr(eb, slot,
406                                               struct btrfs_inode_item);
407                         btrfs_set_inode_nbytes(eb, item, nbytes);
408
409                         /*
410                          * If this is a directory we need to reset the i_size to
411                          * 0 so that we can set it up properly when replaying
412                          * the rest of the items in this log.
413                          */
414                         mode = btrfs_inode_mode(eb, item);
415                         if (S_ISDIR(mode))
416                                 btrfs_set_inode_size(eb, item, 0);
417                 }
418         } else if (inode_item) {
419                 struct btrfs_inode_item *item;
420                 u32 mode;
421
422                 /*
423                  * New inode, set nbytes to 0 so that the nbytes comes out
424                  * properly when we replay the extents.
425                  */
426                 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
427                 btrfs_set_inode_nbytes(eb, item, 0);
428
429                 /*
430                  * If this is a directory we need to reset the i_size to 0 so
431                  * that we can set it up properly when replaying the rest of
432                  * the items in this log.
433                  */
434                 mode = btrfs_inode_mode(eb, item);
435                 if (S_ISDIR(mode))
436                         btrfs_set_inode_size(eb, item, 0);
437         }
438 insert:
439         btrfs_release_path(path);
440         /* try to insert the key into the destination tree */
441         path->skip_release_on_error = 1;
442         ret = btrfs_insert_empty_item(trans, root, path,
443                                       key, item_size);
444         path->skip_release_on_error = 0;
445
446         /* make sure any existing item is the correct size */
447         if (ret == -EEXIST || ret == -EOVERFLOW) {
448                 u32 found_size;
449                 found_size = btrfs_item_size_nr(path->nodes[0],
450                                                 path->slots[0]);
451                 if (found_size > item_size)
452                         btrfs_truncate_item(fs_info, path, item_size, 1);
453                 else if (found_size < item_size)
454                         btrfs_extend_item(fs_info, path,
455                                           item_size - found_size);
456         } else if (ret) {
457                 return ret;
458         }
459         dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
460                                         path->slots[0]);
461
462         /* don't overwrite an existing inode if the generation number
463          * was logged as zero.  This is done when the tree logging code
464          * is just logging an inode to make sure it exists after recovery.
465          *
466          * Also, don't overwrite i_size on directories during replay.
467          * log replay inserts and removes directory items based on the
468          * state of the tree found in the subvolume, and i_size is modified
469          * as it goes
470          */
471         if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
472                 struct btrfs_inode_item *src_item;
473                 struct btrfs_inode_item *dst_item;
474
475                 src_item = (struct btrfs_inode_item *)src_ptr;
476                 dst_item = (struct btrfs_inode_item *)dst_ptr;
477
478                 if (btrfs_inode_generation(eb, src_item) == 0) {
479                         struct extent_buffer *dst_eb = path->nodes[0];
480                         const u64 ino_size = btrfs_inode_size(eb, src_item);
481
482                         /*
483                          * For regular files an ino_size == 0 is used only when
484                          * logging that an inode exists, as part of a directory
485                          * fsync, and the inode wasn't fsynced before. In this
486                          * case don't set the size of the inode in the fs/subvol
487                          * tree, otherwise we would be throwing valid data away.
488                          */
489                         if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
490                             S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
491                             ino_size != 0) {
492                                 struct btrfs_map_token token;
493
494                                 btrfs_init_map_token(&token);
495                                 btrfs_set_token_inode_size(dst_eb, dst_item,
496                                                            ino_size, &token);
497                         }
498                         goto no_copy;
499                 }
500
501                 if (overwrite_root &&
502                     S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
503                     S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
504                         save_old_i_size = 1;
505                         saved_i_size = btrfs_inode_size(path->nodes[0],
506                                                         dst_item);
507                 }
508         }
509
510         copy_extent_buffer(path->nodes[0], eb, dst_ptr,
511                            src_ptr, item_size);
512
513         if (save_old_i_size) {
514                 struct btrfs_inode_item *dst_item;
515                 dst_item = (struct btrfs_inode_item *)dst_ptr;
516                 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
517         }
518
519         /* make sure the generation is filled in */
520         if (key->type == BTRFS_INODE_ITEM_KEY) {
521                 struct btrfs_inode_item *dst_item;
522                 dst_item = (struct btrfs_inode_item *)dst_ptr;
523                 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
524                         btrfs_set_inode_generation(path->nodes[0], dst_item,
525                                                    trans->transid);
526                 }
527         }
528 no_copy:
529         btrfs_mark_buffer_dirty(path->nodes[0]);
530         btrfs_release_path(path);
531         return 0;
532 }
533
534 /*
535  * simple helper to read an inode off the disk from a given root
536  * This can only be called for subvolume roots and not for the log
537  */
538 static noinline struct inode *read_one_inode(struct btrfs_root *root,
539                                              u64 objectid)
540 {
541         struct btrfs_key key;
542         struct inode *inode;
543
544         key.objectid = objectid;
545         key.type = BTRFS_INODE_ITEM_KEY;
546         key.offset = 0;
547         inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
548         if (IS_ERR(inode)) {
549                 inode = NULL;
550         } else if (is_bad_inode(inode)) {
551                 iput(inode);
552                 inode = NULL;
553         }
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, fs_info,
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 conflicing 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 /*
1294  * replay one inode back reference item found in the log tree.
1295  * eb, slot and key refer to the buffer and key found in the log tree.
1296  * root is the destination we are replaying into, and path is for temp
1297  * use by this function.  (it should be released on return).
1298  */
1299 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1300                                   struct btrfs_root *root,
1301                                   struct btrfs_root *log,
1302                                   struct btrfs_path *path,
1303                                   struct extent_buffer *eb, int slot,
1304                                   struct btrfs_key *key)
1305 {
1306         struct inode *dir = NULL;
1307         struct inode *inode = NULL;
1308         unsigned long ref_ptr;
1309         unsigned long ref_end;
1310         char *name = NULL;
1311         int namelen;
1312         int ret;
1313         int search_done = 0;
1314         int log_ref_ver = 0;
1315         u64 parent_objectid;
1316         u64 inode_objectid;
1317         u64 ref_index = 0;
1318         int ref_struct_size;
1319
1320         ref_ptr = btrfs_item_ptr_offset(eb, slot);
1321         ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1322
1323         if (key->type == BTRFS_INODE_EXTREF_KEY) {
1324                 struct btrfs_inode_extref *r;
1325
1326                 ref_struct_size = sizeof(struct btrfs_inode_extref);
1327                 log_ref_ver = 1;
1328                 r = (struct btrfs_inode_extref *)ref_ptr;
1329                 parent_objectid = btrfs_inode_extref_parent(eb, r);
1330         } else {
1331                 ref_struct_size = sizeof(struct btrfs_inode_ref);
1332                 parent_objectid = key->offset;
1333         }
1334         inode_objectid = key->objectid;
1335
1336         /*
1337          * it is possible that we didn't log all the parent directories
1338          * for a given inode.  If we don't find the dir, just don't
1339          * copy the back ref in.  The link count fixup code will take
1340          * care of the rest
1341          */
1342         dir = read_one_inode(root, parent_objectid);
1343         if (!dir) {
1344                 ret = -ENOENT;
1345                 goto out;
1346         }
1347
1348         inode = read_one_inode(root, inode_objectid);
1349         if (!inode) {
1350                 ret = -EIO;
1351                 goto out;
1352         }
1353
1354         while (ref_ptr < ref_end) {
1355                 if (log_ref_ver) {
1356                         ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1357                                                 &ref_index, &parent_objectid);
1358                         /*
1359                          * parent object can change from one array
1360                          * item to another.
1361                          */
1362                         if (!dir)
1363                                 dir = read_one_inode(root, parent_objectid);
1364                         if (!dir) {
1365                                 ret = -ENOENT;
1366                                 goto out;
1367                         }
1368                 } else {
1369                         ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1370                                              &ref_index);
1371                 }
1372                 if (ret)
1373                         goto out;
1374
1375                 /* if we already have a perfect match, we're done */
1376                 if (!inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1377                                         btrfs_ino(BTRFS_I(inode)), ref_index,
1378                                         name, namelen)) {
1379                         /*
1380                          * look for a conflicting back reference in the
1381                          * metadata. if we find one we have to unlink that name
1382                          * of the file before we add our new link.  Later on, we
1383                          * overwrite any existing back reference, and we don't
1384                          * want to create dangling pointers in the directory.
1385                          */
1386
1387                         if (!search_done) {
1388                                 ret = __add_inode_ref(trans, root, path, log,
1389                                                       BTRFS_I(dir),
1390                                                       BTRFS_I(inode),
1391                                                       inode_objectid,
1392                                                       parent_objectid,
1393                                                       ref_index, name, namelen,
1394                                                       &search_done);
1395                                 if (ret) {
1396                                         if (ret == 1)
1397                                                 ret = 0;
1398                                         goto out;
1399                                 }
1400                         }
1401
1402                         /* insert our name */
1403                         ret = btrfs_add_link(trans, BTRFS_I(dir),
1404                                         BTRFS_I(inode),
1405                                         name, namelen, 0, ref_index);
1406                         if (ret)
1407                                 goto out;
1408
1409                         btrfs_update_inode(trans, root, inode);
1410                 }
1411
1412                 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1413                 kfree(name);
1414                 name = NULL;
1415                 if (log_ref_ver) {
1416                         iput(dir);
1417                         dir = NULL;
1418                 }
1419         }
1420
1421         /*
1422          * Before we overwrite the inode reference item in the subvolume tree
1423          * with the item from the log tree, we must unlink all names from the
1424          * parent directory that are in the subvolume's tree inode reference
1425          * item, otherwise we end up with an inconsistent subvolume tree where
1426          * dir index entries exist for a name but there is no inode reference
1427          * item with the same name.
1428          */
1429         ret = unlink_old_inode_refs(trans, root, path, BTRFS_I(inode), eb, slot,
1430                                     key);
1431         if (ret)
1432                 goto out;
1433
1434         /* finally write the back reference in the inode */
1435         ret = overwrite_item(trans, root, path, eb, slot, key);
1436 out:
1437         btrfs_release_path(path);
1438         kfree(name);
1439         iput(dir);
1440         iput(inode);
1441         return ret;
1442 }
1443
1444 static int insert_orphan_item(struct btrfs_trans_handle *trans,
1445                               struct btrfs_root *root, u64 ino)
1446 {
1447         int ret;
1448
1449         ret = btrfs_insert_orphan_item(trans, root, ino);
1450         if (ret == -EEXIST)
1451                 ret = 0;
1452
1453         return ret;
1454 }
1455
1456 static int count_inode_extrefs(struct btrfs_root *root,
1457                 struct btrfs_inode *inode, struct btrfs_path *path)
1458 {
1459         int ret = 0;
1460         int name_len;
1461         unsigned int nlink = 0;
1462         u32 item_size;
1463         u32 cur_offset = 0;
1464         u64 inode_objectid = btrfs_ino(inode);
1465         u64 offset = 0;
1466         unsigned long ptr;
1467         struct btrfs_inode_extref *extref;
1468         struct extent_buffer *leaf;
1469
1470         while (1) {
1471                 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1472                                             &extref, &offset);
1473                 if (ret)
1474                         break;
1475
1476                 leaf = path->nodes[0];
1477                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1478                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1479                 cur_offset = 0;
1480
1481                 while (cur_offset < item_size) {
1482                         extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1483                         name_len = btrfs_inode_extref_name_len(leaf, extref);
1484
1485                         nlink++;
1486
1487                         cur_offset += name_len + sizeof(*extref);
1488                 }
1489
1490                 offset++;
1491                 btrfs_release_path(path);
1492         }
1493         btrfs_release_path(path);
1494
1495         if (ret < 0 && ret != -ENOENT)
1496                 return ret;
1497         return nlink;
1498 }
1499
1500 static int count_inode_refs(struct btrfs_root *root,
1501                         struct btrfs_inode *inode, struct btrfs_path *path)
1502 {
1503         int ret;
1504         struct btrfs_key key;
1505         unsigned int nlink = 0;
1506         unsigned long ptr;
1507         unsigned long ptr_end;
1508         int name_len;
1509         u64 ino = btrfs_ino(inode);
1510
1511         key.objectid = ino;
1512         key.type = BTRFS_INODE_REF_KEY;
1513         key.offset = (u64)-1;
1514
1515         while (1) {
1516                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1517                 if (ret < 0)
1518                         break;
1519                 if (ret > 0) {
1520                         if (path->slots[0] == 0)
1521                                 break;
1522                         path->slots[0]--;
1523                 }
1524 process_slot:
1525                 btrfs_item_key_to_cpu(path->nodes[0], &key,
1526                                       path->slots[0]);
1527                 if (key.objectid != ino ||
1528                     key.type != BTRFS_INODE_REF_KEY)
1529                         break;
1530                 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1531                 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1532                                                    path->slots[0]);
1533                 while (ptr < ptr_end) {
1534                         struct btrfs_inode_ref *ref;
1535
1536                         ref = (struct btrfs_inode_ref *)ptr;
1537                         name_len = btrfs_inode_ref_name_len(path->nodes[0],
1538                                                             ref);
1539                         ptr = (unsigned long)(ref + 1) + name_len;
1540                         nlink++;
1541                 }
1542
1543                 if (key.offset == 0)
1544                         break;
1545                 if (path->slots[0] > 0) {
1546                         path->slots[0]--;
1547                         goto process_slot;
1548                 }
1549                 key.offset--;
1550                 btrfs_release_path(path);
1551         }
1552         btrfs_release_path(path);
1553
1554         return nlink;
1555 }
1556
1557 /*
1558  * There are a few corners where the link count of the file can't
1559  * be properly maintained during replay.  So, instead of adding
1560  * lots of complexity to the log code, we just scan the backrefs
1561  * for any file that has been through replay.
1562  *
1563  * The scan will update the link count on the inode to reflect the
1564  * number of back refs found.  If it goes down to zero, the iput
1565  * will free the inode.
1566  */
1567 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1568                                            struct btrfs_root *root,
1569                                            struct inode *inode)
1570 {
1571         struct btrfs_path *path;
1572         int ret;
1573         u64 nlink = 0;
1574         u64 ino = btrfs_ino(BTRFS_I(inode));
1575
1576         path = btrfs_alloc_path();
1577         if (!path)
1578                 return -ENOMEM;
1579
1580         ret = count_inode_refs(root, BTRFS_I(inode), path);
1581         if (ret < 0)
1582                 goto out;
1583
1584         nlink = ret;
1585
1586         ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1587         if (ret < 0)
1588                 goto out;
1589
1590         nlink += ret;
1591
1592         ret = 0;
1593
1594         if (nlink != inode->i_nlink) {
1595                 set_nlink(inode, nlink);
1596                 btrfs_update_inode(trans, root, inode);
1597         }
1598         BTRFS_I(inode)->index_cnt = (u64)-1;
1599
1600         if (inode->i_nlink == 0) {
1601                 if (S_ISDIR(inode->i_mode)) {
1602                         ret = replay_dir_deletes(trans, root, NULL, path,
1603                                                  ino, 1);
1604                         if (ret)
1605                                 goto out;
1606                 }
1607                 ret = insert_orphan_item(trans, root, ino);
1608         }
1609
1610 out:
1611         btrfs_free_path(path);
1612         return ret;
1613 }
1614
1615 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1616                                             struct btrfs_root *root,
1617                                             struct btrfs_path *path)
1618 {
1619         int ret;
1620         struct btrfs_key key;
1621         struct inode *inode;
1622
1623         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1624         key.type = BTRFS_ORPHAN_ITEM_KEY;
1625         key.offset = (u64)-1;
1626         while (1) {
1627                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1628                 if (ret < 0)
1629                         break;
1630
1631                 if (ret == 1) {
1632                         if (path->slots[0] == 0)
1633                                 break;
1634                         path->slots[0]--;
1635                 }
1636
1637                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1638                 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1639                     key.type != BTRFS_ORPHAN_ITEM_KEY)
1640                         break;
1641
1642                 ret = btrfs_del_item(trans, root, path);
1643                 if (ret)
1644                         goto out;
1645
1646                 btrfs_release_path(path);
1647                 inode = read_one_inode(root, key.offset);
1648                 if (!inode)
1649                         return -EIO;
1650
1651                 ret = fixup_inode_link_count(trans, root, inode);
1652                 iput(inode);
1653                 if (ret)
1654                         goto out;
1655
1656                 /*
1657                  * fixup on a directory may create new entries,
1658                  * make sure we always look for the highset possible
1659                  * offset
1660                  */
1661                 key.offset = (u64)-1;
1662         }
1663         ret = 0;
1664 out:
1665         btrfs_release_path(path);
1666         return ret;
1667 }
1668
1669
1670 /*
1671  * record a given inode in the fixup dir so we can check its link
1672  * count when replay is done.  The link count is incremented here
1673  * so the inode won't go away until we check it
1674  */
1675 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1676                                       struct btrfs_root *root,
1677                                       struct btrfs_path *path,
1678                                       u64 objectid)
1679 {
1680         struct btrfs_key key;
1681         int ret = 0;
1682         struct inode *inode;
1683
1684         inode = read_one_inode(root, objectid);
1685         if (!inode)
1686                 return -EIO;
1687
1688         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1689         key.type = BTRFS_ORPHAN_ITEM_KEY;
1690         key.offset = objectid;
1691
1692         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1693
1694         btrfs_release_path(path);
1695         if (ret == 0) {
1696                 if (!inode->i_nlink)
1697                         set_nlink(inode, 1);
1698                 else
1699                         inc_nlink(inode);
1700                 ret = btrfs_update_inode(trans, root, inode);
1701         } else if (ret == -EEXIST) {
1702                 ret = 0;
1703         } else {
1704                 BUG(); /* Logic Error */
1705         }
1706         iput(inode);
1707
1708         return ret;
1709 }
1710
1711 /*
1712  * when replaying the log for a directory, we only insert names
1713  * for inodes that actually exist.  This means an fsync on a directory
1714  * does not implicitly fsync all the new files in it
1715  */
1716 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1717                                     struct btrfs_root *root,
1718                                     u64 dirid, u64 index,
1719                                     char *name, int name_len,
1720                                     struct btrfs_key *location)
1721 {
1722         struct inode *inode;
1723         struct inode *dir;
1724         int ret;
1725
1726         inode = read_one_inode(root, location->objectid);
1727         if (!inode)
1728                 return -ENOENT;
1729
1730         dir = read_one_inode(root, dirid);
1731         if (!dir) {
1732                 iput(inode);
1733                 return -EIO;
1734         }
1735
1736         ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1737                         name_len, 1, index);
1738
1739         /* FIXME, put inode into FIXUP list */
1740
1741         iput(inode);
1742         iput(dir);
1743         return ret;
1744 }
1745
1746 /*
1747  * Return true if an inode reference exists in the log for the given name,
1748  * inode and parent inode.
1749  */
1750 static bool name_in_log_ref(struct btrfs_root *log_root,
1751                             const char *name, const int name_len,
1752                             const u64 dirid, const u64 ino)
1753 {
1754         struct btrfs_key search_key;
1755
1756         search_key.objectid = ino;
1757         search_key.type = BTRFS_INODE_REF_KEY;
1758         search_key.offset = dirid;
1759         if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1760                 return true;
1761
1762         search_key.type = BTRFS_INODE_EXTREF_KEY;
1763         search_key.offset = btrfs_extref_hash(dirid, name, name_len);
1764         if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1765                 return true;
1766
1767         return false;
1768 }
1769
1770 /*
1771  * take a single entry in a log directory item and replay it into
1772  * the subvolume.
1773  *
1774  * if a conflicting item exists in the subdirectory already,
1775  * the inode it points to is unlinked and put into the link count
1776  * fix up tree.
1777  *
1778  * If a name from the log points to a file or directory that does
1779  * not exist in the FS, it is skipped.  fsyncs on directories
1780  * do not force down inodes inside that directory, just changes to the
1781  * names or unlinks in a directory.
1782  *
1783  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1784  * non-existing inode) and 1 if the name was replayed.
1785  */
1786 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1787                                     struct btrfs_root *root,
1788                                     struct btrfs_path *path,
1789                                     struct extent_buffer *eb,
1790                                     struct btrfs_dir_item *di,
1791                                     struct btrfs_key *key)
1792 {
1793         char *name;
1794         int name_len;
1795         struct btrfs_dir_item *dst_di;
1796         struct btrfs_key found_key;
1797         struct btrfs_key log_key;
1798         struct inode *dir;
1799         u8 log_type;
1800         int exists;
1801         int ret = 0;
1802         bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
1803         bool name_added = false;
1804
1805         dir = read_one_inode(root, key->objectid);
1806         if (!dir)
1807                 return -EIO;
1808
1809         name_len = btrfs_dir_name_len(eb, di);
1810         name = kmalloc(name_len, GFP_NOFS);
1811         if (!name) {
1812                 ret = -ENOMEM;
1813                 goto out;
1814         }
1815
1816         log_type = btrfs_dir_type(eb, di);
1817         read_extent_buffer(eb, name, (unsigned long)(di + 1),
1818                    name_len);
1819
1820         btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1821         exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1822         if (exists == 0)
1823                 exists = 1;
1824         else
1825                 exists = 0;
1826         btrfs_release_path(path);
1827
1828         if (key->type == BTRFS_DIR_ITEM_KEY) {
1829                 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1830                                        name, name_len, 1);
1831         } else if (key->type == BTRFS_DIR_INDEX_KEY) {
1832                 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1833                                                      key->objectid,
1834                                                      key->offset, name,
1835                                                      name_len, 1);
1836         } else {
1837                 /* Corruption */
1838                 ret = -EINVAL;
1839                 goto out;
1840         }
1841         if (IS_ERR_OR_NULL(dst_di)) {
1842                 /* we need a sequence number to insert, so we only
1843                  * do inserts for the BTRFS_DIR_INDEX_KEY types
1844                  */
1845                 if (key->type != BTRFS_DIR_INDEX_KEY)
1846                         goto out;
1847                 goto insert;
1848         }
1849
1850         btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1851         /* the existing item matches the logged item */
1852         if (found_key.objectid == log_key.objectid &&
1853             found_key.type == log_key.type &&
1854             found_key.offset == log_key.offset &&
1855             btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
1856                 update_size = false;
1857                 goto out;
1858         }
1859
1860         /*
1861          * don't drop the conflicting directory entry if the inode
1862          * for the new entry doesn't exist
1863          */
1864         if (!exists)
1865                 goto out;
1866
1867         ret = drop_one_dir_item(trans, root, path, BTRFS_I(dir), dst_di);
1868         if (ret)
1869                 goto out;
1870
1871         if (key->type == BTRFS_DIR_INDEX_KEY)
1872                 goto insert;
1873 out:
1874         btrfs_release_path(path);
1875         if (!ret && update_size) {
1876                 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
1877                 ret = btrfs_update_inode(trans, root, dir);
1878         }
1879         kfree(name);
1880         iput(dir);
1881         if (!ret && name_added)
1882                 ret = 1;
1883         return ret;
1884
1885 insert:
1886         if (name_in_log_ref(root->log_root, name, name_len,
1887                             key->objectid, log_key.objectid)) {
1888                 /* The dentry will be added later. */
1889                 ret = 0;
1890                 update_size = false;
1891                 goto out;
1892         }
1893         btrfs_release_path(path);
1894         ret = insert_one_name(trans, root, key->objectid, key->offset,
1895                               name, name_len, &log_key);
1896         if (ret && ret != -ENOENT && ret != -EEXIST)
1897                 goto out;
1898         if (!ret)
1899                 name_added = true;
1900         update_size = false;
1901         ret = 0;
1902         goto out;
1903 }
1904
1905 /*
1906  * find all the names in a directory item and reconcile them into
1907  * the subvolume.  Only BTRFS_DIR_ITEM_KEY types will have more than
1908  * one name in a directory item, but the same code gets used for
1909  * both directory index types
1910  */
1911 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1912                                         struct btrfs_root *root,
1913                                         struct btrfs_path *path,
1914                                         struct extent_buffer *eb, int slot,
1915                                         struct btrfs_key *key)
1916 {
1917         int ret = 0;
1918         u32 item_size = btrfs_item_size_nr(eb, slot);
1919         struct btrfs_dir_item *di;
1920         int name_len;
1921         unsigned long ptr;
1922         unsigned long ptr_end;
1923         struct btrfs_path *fixup_path = NULL;
1924
1925         ptr = btrfs_item_ptr_offset(eb, slot);
1926         ptr_end = ptr + item_size;
1927         while (ptr < ptr_end) {
1928                 di = (struct btrfs_dir_item *)ptr;
1929                 name_len = btrfs_dir_name_len(eb, di);
1930                 ret = replay_one_name(trans, root, path, eb, di, key);
1931                 if (ret < 0)
1932                         break;
1933                 ptr = (unsigned long)(di + 1);
1934                 ptr += name_len;
1935
1936                 /*
1937                  * If this entry refers to a non-directory (directories can not
1938                  * have a link count > 1) and it was added in the transaction
1939                  * that was not committed, make sure we fixup the link count of
1940                  * the inode it the entry points to. Otherwise something like
1941                  * the following would result in a directory pointing to an
1942                  * inode with a wrong link that does not account for this dir
1943                  * entry:
1944                  *
1945                  * mkdir testdir
1946                  * touch testdir/foo
1947                  * touch testdir/bar
1948                  * sync
1949                  *
1950                  * ln testdir/bar testdir/bar_link
1951                  * ln testdir/foo testdir/foo_link
1952                  * xfs_io -c "fsync" testdir/bar
1953                  *
1954                  * <power failure>
1955                  *
1956                  * mount fs, log replay happens
1957                  *
1958                  * File foo would remain with a link count of 1 when it has two
1959                  * entries pointing to it in the directory testdir. This would
1960                  * make it impossible to ever delete the parent directory has
1961                  * it would result in stale dentries that can never be deleted.
1962                  */
1963                 if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
1964                         struct btrfs_key di_key;
1965
1966                         if (!fixup_path) {
1967                                 fixup_path = btrfs_alloc_path();
1968                                 if (!fixup_path) {
1969                                         ret = -ENOMEM;
1970                                         break;
1971                                 }
1972                         }
1973
1974                         btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1975                         ret = link_to_fixup_dir(trans, root, fixup_path,
1976                                                 di_key.objectid);
1977                         if (ret)
1978                                 break;
1979                 }
1980                 ret = 0;
1981         }
1982         btrfs_free_path(fixup_path);
1983         return ret;
1984 }
1985
1986 /*
1987  * directory replay has two parts.  There are the standard directory
1988  * items in the log copied from the subvolume, and range items
1989  * created in the log while the subvolume was logged.
1990  *
1991  * The range items tell us which parts of the key space the log
1992  * is authoritative for.  During replay, if a key in the subvolume
1993  * directory is in a logged range item, but not actually in the log
1994  * that means it was deleted from the directory before the fsync
1995  * and should be removed.
1996  */
1997 static noinline int find_dir_range(struct btrfs_root *root,
1998                                    struct btrfs_path *path,
1999                                    u64 dirid, int key_type,
2000                                    u64 *start_ret, u64 *end_ret)
2001 {
2002         struct btrfs_key key;
2003         u64 found_end;
2004         struct btrfs_dir_log_item *item;
2005         int ret;
2006         int nritems;
2007
2008         if (*start_ret == (u64)-1)
2009                 return 1;
2010
2011         key.objectid = dirid;
2012         key.type = key_type;
2013         key.offset = *start_ret;
2014
2015         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2016         if (ret < 0)
2017                 goto out;
2018         if (ret > 0) {
2019                 if (path->slots[0] == 0)
2020                         goto out;
2021                 path->slots[0]--;
2022         }
2023         if (ret != 0)
2024                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2025
2026         if (key.type != key_type || key.objectid != dirid) {
2027                 ret = 1;
2028                 goto next;
2029         }
2030         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2031                               struct btrfs_dir_log_item);
2032         found_end = btrfs_dir_log_end(path->nodes[0], item);
2033
2034         if (*start_ret >= key.offset && *start_ret <= found_end) {
2035                 ret = 0;
2036                 *start_ret = key.offset;
2037                 *end_ret = found_end;
2038                 goto out;
2039         }
2040         ret = 1;
2041 next:
2042         /* check the next slot in the tree to see if it is a valid item */
2043         nritems = btrfs_header_nritems(path->nodes[0]);
2044         path->slots[0]++;
2045         if (path->slots[0] >= nritems) {
2046                 ret = btrfs_next_leaf(root, path);
2047                 if (ret)
2048                         goto out;
2049         }
2050
2051         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2052
2053         if (key.type != key_type || key.objectid != dirid) {
2054                 ret = 1;
2055                 goto out;
2056         }
2057         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2058                               struct btrfs_dir_log_item);
2059         found_end = btrfs_dir_log_end(path->nodes[0], item);
2060         *start_ret = key.offset;
2061         *end_ret = found_end;
2062         ret = 0;
2063 out:
2064         btrfs_release_path(path);
2065         return ret;
2066 }
2067
2068 /*
2069  * this looks for a given directory item in the log.  If the directory
2070  * item is not in the log, the item is removed and the inode it points
2071  * to is unlinked
2072  */
2073 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2074                                       struct btrfs_root *root,
2075                                       struct btrfs_root *log,
2076                                       struct btrfs_path *path,
2077                                       struct btrfs_path *log_path,
2078                                       struct inode *dir,
2079                                       struct btrfs_key *dir_key)
2080 {
2081         int ret;
2082         struct extent_buffer *eb;
2083         int slot;
2084         u32 item_size;
2085         struct btrfs_dir_item *di;
2086         struct btrfs_dir_item *log_di;
2087         int name_len;
2088         unsigned long ptr;
2089         unsigned long ptr_end;
2090         char *name;
2091         struct inode *inode;
2092         struct btrfs_key location;
2093
2094 again:
2095         eb = path->nodes[0];
2096         slot = path->slots[0];
2097         item_size = btrfs_item_size_nr(eb, slot);
2098         ptr = btrfs_item_ptr_offset(eb, slot);
2099         ptr_end = ptr + item_size;
2100         while (ptr < ptr_end) {
2101                 di = (struct btrfs_dir_item *)ptr;
2102                 name_len = btrfs_dir_name_len(eb, di);
2103                 name = kmalloc(name_len, GFP_NOFS);
2104                 if (!name) {
2105                         ret = -ENOMEM;
2106                         goto out;
2107                 }
2108                 read_extent_buffer(eb, name, (unsigned long)(di + 1),
2109                                   name_len);
2110                 log_di = NULL;
2111                 if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
2112                         log_di = btrfs_lookup_dir_item(trans, log, log_path,
2113                                                        dir_key->objectid,
2114                                                        name, name_len, 0);
2115                 } else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
2116                         log_di = btrfs_lookup_dir_index_item(trans, log,
2117                                                      log_path,
2118                                                      dir_key->objectid,
2119                                                      dir_key->offset,
2120                                                      name, name_len, 0);
2121                 }
2122                 if (!log_di || (IS_ERR(log_di) && PTR_ERR(log_di) == -ENOENT)) {
2123                         btrfs_dir_item_key_to_cpu(eb, di, &location);
2124                         btrfs_release_path(path);
2125                         btrfs_release_path(log_path);
2126                         inode = read_one_inode(root, location.objectid);
2127                         if (!inode) {
2128                                 kfree(name);
2129                                 return -EIO;
2130                         }
2131
2132                         ret = link_to_fixup_dir(trans, root,
2133                                                 path, location.objectid);
2134                         if (ret) {
2135                                 kfree(name);
2136                                 iput(inode);
2137                                 goto out;
2138                         }
2139
2140                         inc_nlink(inode);
2141                         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
2142                                         BTRFS_I(inode), name, name_len);
2143                         if (!ret)
2144                                 ret = btrfs_run_delayed_items(trans);
2145                         kfree(name);
2146                         iput(inode);
2147                         if (ret)
2148                                 goto out;
2149
2150                         /* there might still be more names under this key
2151                          * check and repeat if required
2152                          */
2153                         ret = btrfs_search_slot(NULL, root, dir_key, path,
2154                                                 0, 0);
2155                         if (ret == 0)
2156                                 goto again;
2157                         ret = 0;
2158                         goto out;
2159                 } else if (IS_ERR(log_di)) {
2160                         kfree(name);
2161                         return PTR_ERR(log_di);
2162                 }
2163                 btrfs_release_path(log_path);
2164                 kfree(name);
2165
2166                 ptr = (unsigned long)(di + 1);
2167                 ptr += name_len;
2168         }
2169         ret = 0;
2170 out:
2171         btrfs_release_path(path);
2172         btrfs_release_path(log_path);
2173         return ret;
2174 }
2175
2176 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2177                               struct btrfs_root *root,
2178                               struct btrfs_root *log,
2179                               struct btrfs_path *path,
2180                               const u64 ino)
2181 {
2182         struct btrfs_key search_key;
2183         struct btrfs_path *log_path;
2184         int i;
2185         int nritems;
2186         int ret;
2187
2188         log_path = btrfs_alloc_path();
2189         if (!log_path)
2190                 return -ENOMEM;
2191
2192         search_key.objectid = ino;
2193         search_key.type = BTRFS_XATTR_ITEM_KEY;
2194         search_key.offset = 0;
2195 again:
2196         ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2197         if (ret < 0)
2198                 goto out;
2199 process_leaf:
2200         nritems = btrfs_header_nritems(path->nodes[0]);
2201         for (i = path->slots[0]; i < nritems; i++) {
2202                 struct btrfs_key key;
2203                 struct btrfs_dir_item *di;
2204                 struct btrfs_dir_item *log_di;
2205                 u32 total_size;
2206                 u32 cur;
2207
2208                 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2209                 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2210                         ret = 0;
2211                         goto out;
2212                 }
2213
2214                 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2215                 total_size = btrfs_item_size_nr(path->nodes[0], i);
2216                 cur = 0;
2217                 while (cur < total_size) {
2218                         u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2219                         u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2220                         u32 this_len = sizeof(*di) + name_len + data_len;
2221                         char *name;
2222
2223                         name = kmalloc(name_len, GFP_NOFS);
2224                         if (!name) {
2225                                 ret = -ENOMEM;
2226                                 goto out;
2227                         }
2228                         read_extent_buffer(path->nodes[0], name,
2229                                            (unsigned long)(di + 1), name_len);
2230
2231                         log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2232                                                     name, name_len, 0);
2233                         btrfs_release_path(log_path);
2234                         if (!log_di) {
2235                                 /* Doesn't exist in log tree, so delete it. */
2236                                 btrfs_release_path(path);
2237                                 di = btrfs_lookup_xattr(trans, root, path, ino,
2238                                                         name, name_len, -1);
2239                                 kfree(name);
2240                                 if (IS_ERR(di)) {
2241                                         ret = PTR_ERR(di);
2242                                         goto out;
2243                                 }
2244                                 ASSERT(di);
2245                                 ret = btrfs_delete_one_dir_name(trans, root,
2246                                                                 path, di);
2247                                 if (ret)
2248                                         goto out;
2249                                 btrfs_release_path(path);
2250                                 search_key = key;
2251                                 goto again;
2252                         }
2253                         kfree(name);
2254                         if (IS_ERR(log_di)) {
2255                                 ret = PTR_ERR(log_di);
2256                                 goto out;
2257                         }
2258                         cur += this_len;
2259                         di = (struct btrfs_dir_item *)((char *)di + this_len);
2260                 }
2261         }
2262         ret = btrfs_next_leaf(root, path);
2263         if (ret > 0)
2264                 ret = 0;
2265         else if (ret == 0)
2266                 goto process_leaf;
2267 out:
2268         btrfs_free_path(log_path);
2269         btrfs_release_path(path);
2270         return ret;
2271 }
2272
2273
2274 /*
2275  * deletion replay happens before we copy any new directory items
2276  * out of the log or out of backreferences from inodes.  It
2277  * scans the log to find ranges of keys that log is authoritative for,
2278  * and then scans the directory to find items in those ranges that are
2279  * not present in the log.
2280  *
2281  * Anything we don't find in the log is unlinked and removed from the
2282  * directory.
2283  */
2284 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2285                                        struct btrfs_root *root,
2286                                        struct btrfs_root *log,
2287                                        struct btrfs_path *path,
2288                                        u64 dirid, int del_all)
2289 {
2290         u64 range_start;
2291         u64 range_end;
2292         int key_type = BTRFS_DIR_LOG_ITEM_KEY;
2293         int ret = 0;
2294         struct btrfs_key dir_key;
2295         struct btrfs_key found_key;
2296         struct btrfs_path *log_path;
2297         struct inode *dir;
2298
2299         dir_key.objectid = dirid;
2300         dir_key.type = BTRFS_DIR_ITEM_KEY;
2301         log_path = btrfs_alloc_path();
2302         if (!log_path)
2303                 return -ENOMEM;
2304
2305         dir = read_one_inode(root, dirid);
2306         /* it isn't an error if the inode isn't there, that can happen
2307          * because we replay the deletes before we copy in the inode item
2308          * from the log
2309          */
2310         if (!dir) {
2311                 btrfs_free_path(log_path);
2312                 return 0;
2313         }
2314 again:
2315         range_start = 0;
2316         range_end = 0;
2317         while (1) {
2318                 if (del_all)
2319                         range_end = (u64)-1;
2320                 else {
2321                         ret = find_dir_range(log, path, dirid, key_type,
2322                                              &range_start, &range_end);
2323                         if (ret != 0)
2324                                 break;
2325                 }
2326
2327                 dir_key.offset = range_start;
2328                 while (1) {
2329                         int nritems;
2330                         ret = btrfs_search_slot(NULL, root, &dir_key, path,
2331                                                 0, 0);
2332                         if (ret < 0)
2333                                 goto out;
2334
2335                         nritems = btrfs_header_nritems(path->nodes[0]);
2336                         if (path->slots[0] >= nritems) {
2337                                 ret = btrfs_next_leaf(root, path);
2338                                 if (ret == 1)
2339                                         break;
2340                                 else if (ret < 0)
2341                                         goto out;
2342                         }
2343                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2344                                               path->slots[0]);
2345                         if (found_key.objectid != dirid ||
2346                             found_key.type != dir_key.type)
2347                                 goto next_type;
2348
2349                         if (found_key.offset > range_end)
2350                                 break;
2351
2352                         ret = check_item_in_log(trans, root, log, path,
2353                                                 log_path, dir,
2354                                                 &found_key);
2355                         if (ret)
2356                                 goto out;
2357                         if (found_key.offset == (u64)-1)
2358                                 break;
2359                         dir_key.offset = found_key.offset + 1;
2360                 }
2361                 btrfs_release_path(path);
2362                 if (range_end == (u64)-1)
2363                         break;
2364                 range_start = range_end + 1;
2365         }
2366
2367 next_type:
2368         ret = 0;
2369         if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
2370                 key_type = BTRFS_DIR_LOG_INDEX_KEY;
2371                 dir_key.type = BTRFS_DIR_INDEX_KEY;
2372                 btrfs_release_path(path);
2373                 goto again;
2374         }
2375 out:
2376         btrfs_release_path(path);
2377         btrfs_free_path(log_path);
2378         iput(dir);
2379         return ret;
2380 }
2381
2382 /*
2383  * the process_func used to replay items from the log tree.  This
2384  * gets called in two different stages.  The first stage just looks
2385  * for inodes and makes sure they are all copied into the subvolume.
2386  *
2387  * The second stage copies all the other item types from the log into
2388  * the subvolume.  The two stage approach is slower, but gets rid of
2389  * lots of complexity around inodes referencing other inodes that exist
2390  * only in the log (references come from either directory items or inode
2391  * back refs).
2392  */
2393 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2394                              struct walk_control *wc, u64 gen, int level)
2395 {
2396         int nritems;
2397         struct btrfs_path *path;
2398         struct btrfs_root *root = wc->replay_dest;
2399         struct btrfs_key key;
2400         int i;
2401         int ret;
2402
2403         ret = btrfs_read_buffer(eb, gen, level, NULL);
2404         if (ret)
2405                 return ret;
2406
2407         level = btrfs_header_level(eb);
2408
2409         if (level != 0)
2410                 return 0;
2411
2412         path = btrfs_alloc_path();
2413         if (!path)
2414                 return -ENOMEM;
2415
2416         nritems = btrfs_header_nritems(eb);
2417         for (i = 0; i < nritems; i++) {
2418                 btrfs_item_key_to_cpu(eb, &key, i);
2419
2420                 /* inode keys are done during the first stage */
2421                 if (key.type == BTRFS_INODE_ITEM_KEY &&
2422                     wc->stage == LOG_WALK_REPLAY_INODES) {
2423                         struct btrfs_inode_item *inode_item;
2424                         u32 mode;
2425
2426                         inode_item = btrfs_item_ptr(eb, i,
2427                                             struct btrfs_inode_item);
2428                         ret = replay_xattr_deletes(wc->trans, root, log,
2429                                                    path, key.objectid);
2430                         if (ret)
2431                                 break;
2432                         mode = btrfs_inode_mode(eb, inode_item);
2433                         if (S_ISDIR(mode)) {
2434                                 ret = replay_dir_deletes(wc->trans,
2435                                          root, log, path, key.objectid, 0);
2436                                 if (ret)
2437                                         break;
2438                         }
2439                         ret = overwrite_item(wc->trans, root, path,
2440                                              eb, i, &key);
2441                         if (ret)
2442                                 break;
2443
2444                         /*
2445                          * Before replaying extents, truncate the inode to its
2446                          * size. We need to do it now and not after log replay
2447                          * because before an fsync we can have prealloc extents
2448                          * added beyond the inode's i_size. If we did it after,
2449                          * through orphan cleanup for example, we would drop
2450                          * those prealloc extents just after replaying them.
2451                          */
2452                         if (S_ISREG(mode)) {
2453                                 struct inode *inode;
2454                                 u64 from;
2455
2456                                 inode = read_one_inode(root, key.objectid);
2457                                 if (!inode) {
2458                                         ret = -EIO;
2459                                         break;
2460                                 }
2461                                 from = ALIGN(i_size_read(inode),
2462                                              root->fs_info->sectorsize);
2463                                 ret = btrfs_drop_extents(wc->trans, root, inode,
2464                                                          from, (u64)-1, 1);
2465                                 /*
2466                                  * If the nlink count is zero here, the iput
2467                                  * will free the inode.  We bump it to make
2468                                  * sure it doesn't get freed until the link
2469                                  * count fixup is done.
2470                                  */
2471                                 if (!ret) {
2472                                         if (inode->i_nlink == 0)
2473                                                 inc_nlink(inode);
2474                                         /* Update link count and nbytes. */
2475                                         ret = btrfs_update_inode(wc->trans,
2476                                                                  root, inode);
2477                                 }
2478                                 iput(inode);
2479                                 if (ret)
2480                                         break;
2481                         }
2482
2483                         ret = link_to_fixup_dir(wc->trans, root,
2484                                                 path, key.objectid);
2485                         if (ret)
2486                                 break;
2487                 }
2488
2489                 if (key.type == BTRFS_DIR_INDEX_KEY &&
2490                     wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2491                         ret = replay_one_dir_item(wc->trans, root, path,
2492                                                   eb, i, &key);
2493                         if (ret)
2494                                 break;
2495                 }
2496
2497                 if (wc->stage < LOG_WALK_REPLAY_ALL)
2498                         continue;
2499
2500                 /* these keys are simply copied */
2501                 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2502                         ret = overwrite_item(wc->trans, root, path,
2503                                              eb, i, &key);
2504                         if (ret)
2505                                 break;
2506                 } else if (key.type == BTRFS_INODE_REF_KEY ||
2507                            key.type == BTRFS_INODE_EXTREF_KEY) {
2508                         ret = add_inode_ref(wc->trans, root, log, path,
2509                                             eb, i, &key);
2510                         if (ret && ret != -ENOENT)
2511                                 break;
2512                         ret = 0;
2513                 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2514                         ret = replay_one_extent(wc->trans, root, path,
2515                                                 eb, i, &key);
2516                         if (ret)
2517                                 break;
2518                 } else if (key.type == BTRFS_DIR_ITEM_KEY) {
2519                         ret = replay_one_dir_item(wc->trans, root, path,
2520                                                   eb, i, &key);
2521                         if (ret)
2522                                 break;
2523                 }
2524         }
2525         btrfs_free_path(path);
2526         return ret;
2527 }
2528
2529 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2530                                    struct btrfs_root *root,
2531                                    struct btrfs_path *path, int *level,
2532                                    struct walk_control *wc)
2533 {
2534         struct btrfs_fs_info *fs_info = root->fs_info;
2535         u64 root_owner;
2536         u64 bytenr;
2537         u64 ptr_gen;
2538         struct extent_buffer *next;
2539         struct extent_buffer *cur;
2540         struct extent_buffer *parent;
2541         u32 blocksize;
2542         int ret = 0;
2543
2544         WARN_ON(*level < 0);
2545         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2546
2547         while (*level > 0) {
2548                 struct btrfs_key first_key;
2549
2550                 WARN_ON(*level < 0);
2551                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2552                 cur = path->nodes[*level];
2553
2554                 WARN_ON(btrfs_header_level(cur) != *level);
2555
2556                 if (path->slots[*level] >=
2557                     btrfs_header_nritems(cur))
2558                         break;
2559
2560                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2561                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2562                 btrfs_node_key_to_cpu(cur, &first_key, path->slots[*level]);
2563                 blocksize = fs_info->nodesize;
2564
2565                 parent = path->nodes[*level];
2566                 root_owner = btrfs_header_owner(parent);
2567
2568                 next = btrfs_find_create_tree_block(fs_info, bytenr);
2569                 if (IS_ERR(next))
2570                         return PTR_ERR(next);
2571
2572                 if (*level == 1) {
2573                         ret = wc->process_func(root, next, wc, ptr_gen,
2574                                                *level - 1);
2575                         if (ret) {
2576                                 free_extent_buffer(next);
2577                                 return ret;
2578                         }
2579
2580                         path->slots[*level]++;
2581                         if (wc->free) {
2582                                 ret = btrfs_read_buffer(next, ptr_gen,
2583                                                         *level - 1, &first_key);
2584                                 if (ret) {
2585                                         free_extent_buffer(next);
2586                                         return ret;
2587                                 }
2588
2589                                 if (trans) {
2590                                         btrfs_tree_lock(next);
2591                                         btrfs_set_lock_blocking(next);
2592                                         clean_tree_block(fs_info, next);
2593                                         btrfs_wait_tree_block_writeback(next);
2594                                         btrfs_tree_unlock(next);
2595                                 } else {
2596                                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2597                                                 clear_extent_buffer_dirty(next);
2598                                 }
2599
2600                                 WARN_ON(root_owner !=
2601                                         BTRFS_TREE_LOG_OBJECTID);
2602                                 ret = btrfs_free_and_pin_reserved_extent(
2603                                                         fs_info, bytenr,
2604                                                         blocksize);
2605                                 if (ret) {
2606                                         free_extent_buffer(next);
2607                                         return ret;
2608                                 }
2609                         }
2610                         free_extent_buffer(next);
2611                         continue;
2612                 }
2613                 ret = btrfs_read_buffer(next, ptr_gen, *level - 1, &first_key);
2614                 if (ret) {
2615                         free_extent_buffer(next);
2616                         return ret;
2617                 }
2618
2619                 WARN_ON(*level <= 0);
2620                 if (path->nodes[*level-1])
2621                         free_extent_buffer(path->nodes[*level-1]);
2622                 path->nodes[*level-1] = next;
2623                 *level = btrfs_header_level(next);
2624                 path->slots[*level] = 0;
2625                 cond_resched();
2626         }
2627         WARN_ON(*level < 0);
2628         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2629
2630         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2631
2632         cond_resched();
2633         return 0;
2634 }
2635
2636 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2637                                  struct btrfs_root *root,
2638                                  struct btrfs_path *path, int *level,
2639                                  struct walk_control *wc)
2640 {
2641         struct btrfs_fs_info *fs_info = root->fs_info;
2642         u64 root_owner;
2643         int i;
2644         int slot;
2645         int ret;
2646
2647         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2648                 slot = path->slots[i];
2649                 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2650                         path->slots[i]++;
2651                         *level = i;
2652                         WARN_ON(*level == 0);
2653                         return 0;
2654                 } else {
2655                         struct extent_buffer *parent;
2656                         if (path->nodes[*level] == root->node)
2657                                 parent = path->nodes[*level];
2658                         else
2659                                 parent = path->nodes[*level + 1];
2660
2661                         root_owner = btrfs_header_owner(parent);
2662                         ret = wc->process_func(root, path->nodes[*level], wc,
2663                                  btrfs_header_generation(path->nodes[*level]),
2664                                  *level);
2665                         if (ret)
2666                                 return ret;
2667
2668                         if (wc->free) {
2669                                 struct extent_buffer *next;
2670
2671                                 next = path->nodes[*level];
2672
2673                                 if (trans) {
2674                                         btrfs_tree_lock(next);
2675                                         btrfs_set_lock_blocking(next);
2676                                         clean_tree_block(fs_info, next);
2677                                         btrfs_wait_tree_block_writeback(next);
2678                                         btrfs_tree_unlock(next);
2679                                 } else {
2680                                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2681                                                 clear_extent_buffer_dirty(next);
2682                                 }
2683
2684                                 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2685                                 ret = btrfs_free_and_pin_reserved_extent(
2686                                                 fs_info,
2687                                                 path->nodes[*level]->start,
2688                                                 path->nodes[*level]->len);
2689                                 if (ret)
2690                                         return ret;
2691                         }
2692                         free_extent_buffer(path->nodes[*level]);
2693                         path->nodes[*level] = NULL;
2694                         *level = i + 1;
2695                 }
2696         }
2697         return 1;
2698 }
2699
2700 /*
2701  * drop the reference count on the tree rooted at 'snap'.  This traverses
2702  * the tree freeing any blocks that have a ref count of zero after being
2703  * decremented.
2704  */
2705 static int walk_log_tree(struct btrfs_trans_handle *trans,
2706                          struct btrfs_root *log, struct walk_control *wc)
2707 {
2708         struct btrfs_fs_info *fs_info = log->fs_info;
2709         int ret = 0;
2710         int wret;
2711         int level;
2712         struct btrfs_path *path;
2713         int orig_level;
2714
2715         path = btrfs_alloc_path();
2716         if (!path)
2717                 return -ENOMEM;
2718
2719         level = btrfs_header_level(log->node);
2720         orig_level = level;
2721         path->nodes[level] = log->node;
2722         extent_buffer_get(log->node);
2723         path->slots[level] = 0;
2724
2725         while (1) {
2726                 wret = walk_down_log_tree(trans, log, path, &level, wc);
2727                 if (wret > 0)
2728                         break;
2729                 if (wret < 0) {
2730                         ret = wret;
2731                         goto out;
2732                 }
2733
2734                 wret = walk_up_log_tree(trans, log, path, &level, wc);
2735                 if (wret > 0)
2736                         break;
2737                 if (wret < 0) {
2738                         ret = wret;
2739                         goto out;
2740                 }
2741         }
2742
2743         /* was the root node processed? if not, catch it here */
2744         if (path->nodes[orig_level]) {
2745                 ret = wc->process_func(log, path->nodes[orig_level], wc,
2746                          btrfs_header_generation(path->nodes[orig_level]),
2747                          orig_level);
2748                 if (ret)
2749                         goto out;
2750                 if (wc->free) {
2751                         struct extent_buffer *next;
2752
2753                         next = path->nodes[orig_level];
2754
2755                         if (trans) {
2756                                 btrfs_tree_lock(next);
2757                                 btrfs_set_lock_blocking(next);
2758                                 clean_tree_block(fs_info, next);
2759                                 btrfs_wait_tree_block_writeback(next);
2760                                 btrfs_tree_unlock(next);
2761                         } else {
2762                                 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2763                                         clear_extent_buffer_dirty(next);
2764                         }
2765
2766                         WARN_ON(log->root_key.objectid !=
2767                                 BTRFS_TREE_LOG_OBJECTID);
2768                         ret = btrfs_free_and_pin_reserved_extent(fs_info,
2769                                                         next->start, next->len);
2770                         if (ret)
2771                                 goto out;
2772                 }
2773         }
2774
2775 out:
2776         btrfs_free_path(path);
2777         return ret;
2778 }
2779
2780 /*
2781  * helper function to update the item for a given subvolumes log root
2782  * in the tree of log roots
2783  */
2784 static int update_log_root(struct btrfs_trans_handle *trans,
2785                            struct btrfs_root *log)
2786 {
2787         struct btrfs_fs_info *fs_info = log->fs_info;
2788         int ret;
2789
2790         if (log->log_transid == 1) {
2791                 /* insert root item on the first sync */
2792                 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2793                                 &log->root_key, &log->root_item);
2794         } else {
2795                 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2796                                 &log->root_key, &log->root_item);
2797         }
2798         return ret;
2799 }
2800
2801 static void wait_log_commit(struct btrfs_root *root, int transid)
2802 {
2803         DEFINE_WAIT(wait);
2804         int index = transid % 2;
2805
2806         /*
2807          * we only allow two pending log transactions at a time,
2808          * so we know that if ours is more than 2 older than the
2809          * current transaction, we're done
2810          */
2811         for (;;) {
2812                 prepare_to_wait(&root->log_commit_wait[index],
2813                                 &wait, TASK_UNINTERRUPTIBLE);
2814
2815                 if (!(root->log_transid_committed < transid &&
2816                       atomic_read(&root->log_commit[index])))
2817                         break;
2818
2819                 mutex_unlock(&root->log_mutex);
2820                 schedule();
2821                 mutex_lock(&root->log_mutex);
2822         }
2823         finish_wait(&root->log_commit_wait[index], &wait);
2824 }
2825
2826 static void wait_for_writer(struct btrfs_root *root)
2827 {
2828         DEFINE_WAIT(wait);
2829
2830         for (;;) {
2831                 prepare_to_wait(&root->log_writer_wait, &wait,
2832                                 TASK_UNINTERRUPTIBLE);
2833                 if (!atomic_read(&root->log_writers))
2834                         break;
2835
2836                 mutex_unlock(&root->log_mutex);
2837                 schedule();
2838                 mutex_lock(&root->log_mutex);
2839         }
2840         finish_wait(&root->log_writer_wait, &wait);
2841 }
2842
2843 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2844                                         struct btrfs_log_ctx *ctx)
2845 {
2846         if (!ctx)
2847                 return;
2848
2849         mutex_lock(&root->log_mutex);
2850         list_del_init(&ctx->list);
2851         mutex_unlock(&root->log_mutex);
2852 }
2853
2854 /* 
2855  * Invoked in log mutex context, or be sure there is no other task which
2856  * can access the list.
2857  */
2858 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2859                                              int index, int error)
2860 {
2861         struct btrfs_log_ctx *ctx;
2862         struct btrfs_log_ctx *safe;
2863
2864         list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2865                 list_del_init(&ctx->list);
2866                 ctx->log_ret = error;
2867         }
2868
2869         INIT_LIST_HEAD(&root->log_ctxs[index]);
2870 }
2871
2872 /*
2873  * btrfs_sync_log does sends a given tree log down to the disk and
2874  * updates the super blocks to record it.  When this call is done,
2875  * you know that any inodes previously logged are safely on disk only
2876  * if it returns 0.
2877  *
2878  * Any other return value means you need to call btrfs_commit_transaction.
2879  * Some of the edge cases for fsyncing directories that have had unlinks
2880  * or renames done in the past mean that sometimes the only safe
2881  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
2882  * that has happened.
2883  */
2884 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2885                    struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2886 {
2887         int index1;
2888         int index2;
2889         int mark;
2890         int ret;
2891         struct btrfs_fs_info *fs_info = root->fs_info;
2892         struct btrfs_root *log = root->log_root;
2893         struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2894         int log_transid = 0;
2895         struct btrfs_log_ctx root_log_ctx;
2896         struct blk_plug plug;
2897
2898         mutex_lock(&root->log_mutex);
2899         log_transid = ctx->log_transid;
2900         if (root->log_transid_committed >= log_transid) {
2901                 mutex_unlock(&root->log_mutex);
2902                 return ctx->log_ret;
2903         }
2904
2905         index1 = log_transid % 2;
2906         if (atomic_read(&root->log_commit[index1])) {
2907                 wait_log_commit(root, log_transid);
2908                 mutex_unlock(&root->log_mutex);
2909                 return ctx->log_ret;
2910         }
2911         ASSERT(log_transid == root->log_transid);
2912         atomic_set(&root->log_commit[index1], 1);
2913
2914         /* wait for previous tree log sync to complete */
2915         if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2916                 wait_log_commit(root, log_transid - 1);
2917
2918         while (1) {
2919                 int batch = atomic_read(&root->log_batch);
2920                 /* when we're on an ssd, just kick the log commit out */
2921                 if (!btrfs_test_opt(fs_info, SSD) &&
2922                     test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
2923                         mutex_unlock(&root->log_mutex);
2924                         schedule_timeout_uninterruptible(1);
2925                         mutex_lock(&root->log_mutex);
2926                 }
2927                 wait_for_writer(root);
2928                 if (batch == atomic_read(&root->log_batch))
2929                         break;
2930         }
2931
2932         /* bail out if we need to do a full commit */
2933         if (btrfs_need_log_full_commit(fs_info, trans)) {
2934                 ret = -EAGAIN;
2935                 mutex_unlock(&root->log_mutex);
2936                 goto out;
2937         }
2938
2939         if (log_transid % 2 == 0)
2940                 mark = EXTENT_DIRTY;
2941         else
2942                 mark = EXTENT_NEW;
2943
2944         /* we start IO on  all the marked extents here, but we don't actually
2945          * wait for them until later.
2946          */
2947         blk_start_plug(&plug);
2948         ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2949         if (ret) {
2950                 blk_finish_plug(&plug);
2951                 btrfs_abort_transaction(trans, ret);
2952                 btrfs_set_log_full_commit(fs_info, trans);
2953                 mutex_unlock(&root->log_mutex);
2954                 goto out;
2955         }
2956
2957         btrfs_set_root_node(&log->root_item, log->node);
2958
2959         root->log_transid++;
2960         log->log_transid = root->log_transid;
2961         root->log_start_pid = 0;
2962         /*
2963          * IO has been started, blocks of the log tree have WRITTEN flag set
2964          * in their headers. new modifications of the log will be written to
2965          * new positions. so it's safe to allow log writers to go in.
2966          */
2967         mutex_unlock(&root->log_mutex);
2968
2969         btrfs_init_log_ctx(&root_log_ctx, NULL);
2970
2971         mutex_lock(&log_root_tree->log_mutex);
2972         atomic_inc(&log_root_tree->log_batch);
2973         atomic_inc(&log_root_tree->log_writers);
2974
2975         index2 = log_root_tree->log_transid % 2;
2976         list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
2977         root_log_ctx.log_transid = log_root_tree->log_transid;
2978
2979         mutex_unlock(&log_root_tree->log_mutex);
2980
2981         ret = update_log_root(trans, log);
2982
2983         mutex_lock(&log_root_tree->log_mutex);
2984         if (atomic_dec_and_test(&log_root_tree->log_writers)) {
2985                 /* atomic_dec_and_test implies a barrier */
2986                 cond_wake_up_nomb(&log_root_tree->log_writer_wait);
2987         }
2988
2989         if (ret) {
2990                 if (!list_empty(&root_log_ctx.list))
2991                         list_del_init(&root_log_ctx.list);
2992
2993                 blk_finish_plug(&plug);
2994                 btrfs_set_log_full_commit(fs_info, trans);
2995
2996                 if (ret != -ENOSPC) {
2997                         btrfs_abort_transaction(trans, ret);
2998                         mutex_unlock(&log_root_tree->log_mutex);