]> Pileus Git - ~andy/linux/blob - fs/btrfs/tree-log.c
Btrfs: make things static and include the right headers
[~andy/linux] / fs / btrfs / tree-log.c
1 /*
2  * Copyright (C) 2008 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/sched.h>
20 #include "ctree.h"
21 #include "transaction.h"
22 #include "disk-io.h"
23 #include "locking.h"
24 #include "print-tree.h"
25 #include "compat.h"
26 #include "tree-log.h"
27
28 /* magic values for the inode_only field in btrfs_log_inode:
29  *
30  * LOG_INODE_ALL means to log everything
31  * LOG_INODE_EXISTS means to log just enough to recreate the inode
32  * during log replay
33  */
34 #define LOG_INODE_ALL 0
35 #define LOG_INODE_EXISTS 1
36
37 /*
38  * stages for the tree walking.  The first
39  * stage (0) is to only pin down the blocks we find
40  * the second stage (1) is to make sure that all the inodes
41  * we find in the log are created in the subvolume.
42  *
43  * The last stage is to deal with directories and links and extents
44  * and all the other fun semantics
45  */
46 #define LOG_WALK_PIN_ONLY 0
47 #define LOG_WALK_REPLAY_INODES 1
48 #define LOG_WALK_REPLAY_ALL 2
49
50 static int __btrfs_log_inode(struct btrfs_trans_handle *trans,
51                              struct btrfs_root *root, struct inode *inode,
52                              int inode_only);
53
54 /*
55  * tree logging is a special write ahead log used to make sure that
56  * fsyncs and O_SYNCs can happen without doing full tree commits.
57  *
58  * Full tree commits are expensive because they require commonly
59  * modified blocks to be recowed, creating many dirty pages in the
60  * extent tree an 4x-6x higher write load than ext3.
61  *
62  * Instead of doing a tree commit on every fsync, we use the
63  * key ranges and transaction ids to find items for a given file or directory
64  * that have changed in this transaction.  Those items are copied into
65  * a special tree (one per subvolume root), that tree is written to disk
66  * and then the fsync is considered complete.
67  *
68  * After a crash, items are copied out of the log-tree back into the
69  * subvolume tree.  Any file data extents found are recorded in the extent
70  * allocation tree, and the log-tree freed.
71  *
72  * The log tree is read three times, once to pin down all the extents it is
73  * using in ram and once, once to create all the inodes logged in the tree
74  * and once to do all the other items.
75  */
76
77 /*
78  * btrfs_add_log_tree adds a new per-subvolume log tree into the
79  * tree of log tree roots.  This must be called with a tree log transaction
80  * running (see start_log_trans).
81  */
82 static int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
83                       struct btrfs_root *root)
84 {
85         struct btrfs_key key;
86         struct btrfs_root_item root_item;
87         struct btrfs_inode_item *inode_item;
88         struct extent_buffer *leaf;
89         struct btrfs_root *new_root = root;
90         int ret;
91         u64 objectid = root->root_key.objectid;
92
93         leaf = btrfs_alloc_free_block(trans, root, root->leafsize, 0,
94                                       BTRFS_TREE_LOG_OBJECTID,
95                                       trans->transid, 0, 0, 0);
96         if (IS_ERR(leaf)) {
97                 ret = PTR_ERR(leaf);
98                 return ret;
99         }
100
101         btrfs_set_header_nritems(leaf, 0);
102         btrfs_set_header_level(leaf, 0);
103         btrfs_set_header_bytenr(leaf, leaf->start);
104         btrfs_set_header_generation(leaf, trans->transid);
105         btrfs_set_header_owner(leaf, BTRFS_TREE_LOG_OBJECTID);
106
107         write_extent_buffer(leaf, root->fs_info->fsid,
108                             (unsigned long)btrfs_header_fsid(leaf),
109                             BTRFS_FSID_SIZE);
110         btrfs_mark_buffer_dirty(leaf);
111
112         inode_item = &root_item.inode;
113         memset(inode_item, 0, sizeof(*inode_item));
114         inode_item->generation = cpu_to_le64(1);
115         inode_item->size = cpu_to_le64(3);
116         inode_item->nlink = cpu_to_le32(1);
117         inode_item->nbytes = cpu_to_le64(root->leafsize);
118         inode_item->mode = cpu_to_le32(S_IFDIR | 0755);
119
120         btrfs_set_root_bytenr(&root_item, leaf->start);
121         btrfs_set_root_generation(&root_item, trans->transid);
122         btrfs_set_root_level(&root_item, 0);
123         btrfs_set_root_refs(&root_item, 0);
124         btrfs_set_root_used(&root_item, 0);
125
126         memset(&root_item.drop_progress, 0, sizeof(root_item.drop_progress));
127         root_item.drop_level = 0;
128
129         btrfs_tree_unlock(leaf);
130         free_extent_buffer(leaf);
131         leaf = NULL;
132
133         btrfs_set_root_dirid(&root_item, 0);
134
135         key.objectid = BTRFS_TREE_LOG_OBJECTID;
136         key.offset = objectid;
137         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
138         ret = btrfs_insert_root(trans, root->fs_info->log_root_tree, &key,
139                                 &root_item);
140         if (ret)
141                 goto fail;
142
143         new_root = btrfs_read_fs_root_no_radix(root->fs_info->log_root_tree,
144                                                &key);
145         BUG_ON(!new_root);
146
147         WARN_ON(root->log_root);
148         root->log_root = new_root;
149
150         /*
151          * log trees do not get reference counted because they go away
152          * before a real commit is actually done.  They do store pointers
153          * to file data extents, and those reference counts still get
154          * updated (along with back refs to the log tree).
155          */
156         new_root->ref_cows = 0;
157         new_root->last_trans = trans->transid;
158 fail:
159         return ret;
160 }
161
162 /*
163  * start a sub transaction and setup the log tree
164  * this increments the log tree writer count to make the people
165  * syncing the tree wait for us to finish
166  */
167 static int start_log_trans(struct btrfs_trans_handle *trans,
168                            struct btrfs_root *root)
169 {
170         int ret;
171         mutex_lock(&root->fs_info->tree_log_mutex);
172         if (!root->fs_info->log_root_tree) {
173                 ret = btrfs_init_log_root_tree(trans, root->fs_info);
174                 BUG_ON(ret);
175         }
176         if (!root->log_root) {
177                 ret = btrfs_add_log_tree(trans, root);
178                 BUG_ON(ret);
179         }
180         atomic_inc(&root->fs_info->tree_log_writers);
181         root->fs_info->tree_log_batch++;
182         mutex_unlock(&root->fs_info->tree_log_mutex);
183         return 0;
184 }
185
186 /*
187  * returns 0 if there was a log transaction running and we were able
188  * to join, or returns -ENOENT if there were not transactions
189  * in progress
190  */
191 static int join_running_log_trans(struct btrfs_root *root)
192 {
193         int ret = -ENOENT;
194
195         smp_mb();
196         if (!root->log_root)
197                 return -ENOENT;
198
199         mutex_lock(&root->fs_info->tree_log_mutex);
200         if (root->log_root) {
201                 ret = 0;
202                 atomic_inc(&root->fs_info->tree_log_writers);
203                 root->fs_info->tree_log_batch++;
204         }
205         mutex_unlock(&root->fs_info->tree_log_mutex);
206         return ret;
207 }
208
209 /*
210  * indicate we're done making changes to the log tree
211  * and wake up anyone waiting to do a sync
212  */
213 static int end_log_trans(struct btrfs_root *root)
214 {
215         atomic_dec(&root->fs_info->tree_log_writers);
216         smp_mb();
217         if (waitqueue_active(&root->fs_info->tree_log_wait))
218                 wake_up(&root->fs_info->tree_log_wait);
219         return 0;
220 }
221
222
223 /*
224  * the walk control struct is used to pass state down the chain when
225  * processing the log tree.  The stage field tells us which part
226  * of the log tree processing we are currently doing.  The others
227  * are state fields used for that specific part
228  */
229 struct walk_control {
230         /* should we free the extent on disk when done?  This is used
231          * at transaction commit time while freeing a log tree
232          */
233         int free;
234
235         /* should we write out the extent buffer?  This is used
236          * while flushing the log tree to disk during a sync
237          */
238         int write;
239
240         /* should we wait for the extent buffer io to finish?  Also used
241          * while flushing the log tree to disk for a sync
242          */
243         int wait;
244
245         /* pin only walk, we record which extents on disk belong to the
246          * log trees
247          */
248         int pin;
249
250         /* what stage of the replay code we're currently in */
251         int stage;
252
253         /* the root we are currently replaying */
254         struct btrfs_root *replay_dest;
255
256         /* the trans handle for the current replay */
257         struct btrfs_trans_handle *trans;
258
259         /* the function that gets used to process blocks we find in the
260          * tree.  Note the extent_buffer might not be up to date when it is
261          * passed in, and it must be checked or read if you need the data
262          * inside it
263          */
264         int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
265                             struct walk_control *wc, u64 gen);
266 };
267
268 /*
269  * process_func used to pin down extents, write them or wait on them
270  */
271 static int process_one_buffer(struct btrfs_root *log,
272                               struct extent_buffer *eb,
273                               struct walk_control *wc, u64 gen)
274 {
275         if (wc->pin) {
276                 mutex_lock(&log->fs_info->pinned_mutex);
277                 btrfs_update_pinned_extents(log->fs_info->extent_root,
278                                             eb->start, eb->len, 1);
279                 mutex_unlock(&log->fs_info->pinned_mutex);
280         }
281
282         if (btrfs_buffer_uptodate(eb, gen)) {
283                 if (wc->write)
284                         btrfs_write_tree_block(eb);
285                 if (wc->wait)
286                         btrfs_wait_tree_block_writeback(eb);
287         }
288         return 0;
289 }
290
291 /*
292  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
293  * to the src data we are copying out.
294  *
295  * root is the tree we are copying into, and path is a scratch
296  * path for use in this function (it should be released on entry and
297  * will be released on exit).
298  *
299  * If the key is already in the destination tree the existing item is
300  * overwritten.  If the existing item isn't big enough, it is extended.
301  * If it is too large, it is truncated.
302  *
303  * If the key isn't in the destination yet, a new item is inserted.
304  */
305 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
306                                    struct btrfs_root *root,
307                                    struct btrfs_path *path,
308                                    struct extent_buffer *eb, int slot,
309                                    struct btrfs_key *key)
310 {
311         int ret;
312         u32 item_size;
313         u64 saved_i_size = 0;
314         int save_old_i_size = 0;
315         unsigned long src_ptr;
316         unsigned long dst_ptr;
317         int overwrite_root = 0;
318
319         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
320                 overwrite_root = 1;
321
322         item_size = btrfs_item_size_nr(eb, slot);
323         src_ptr = btrfs_item_ptr_offset(eb, slot);
324
325         /* look for the key in the destination tree */
326         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
327         if (ret == 0) {
328                 char *src_copy;
329                 char *dst_copy;
330                 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
331                                                   path->slots[0]);
332                 if (dst_size != item_size)
333                         goto insert;
334
335                 if (item_size == 0) {
336                         btrfs_release_path(root, path);
337                         return 0;
338                 }
339                 dst_copy = kmalloc(item_size, GFP_NOFS);
340                 src_copy = kmalloc(item_size, GFP_NOFS);
341
342                 read_extent_buffer(eb, src_copy, src_ptr, item_size);
343
344                 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
345                 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
346                                    item_size);
347                 ret = memcmp(dst_copy, src_copy, item_size);
348
349                 kfree(dst_copy);
350                 kfree(src_copy);
351                 /*
352                  * they have the same contents, just return, this saves
353                  * us from cowing blocks in the destination tree and doing
354                  * extra writes that may not have been done by a previous
355                  * sync
356                  */
357                 if (ret == 0) {
358                         btrfs_release_path(root, path);
359                         return 0;
360                 }
361
362         }
363 insert:
364         btrfs_release_path(root, path);
365         /* try to insert the key into the destination tree */
366         ret = btrfs_insert_empty_item(trans, root, path,
367                                       key, item_size);
368
369         /* make sure any existing item is the correct size */
370         if (ret == -EEXIST) {
371                 u32 found_size;
372                 found_size = btrfs_item_size_nr(path->nodes[0],
373                                                 path->slots[0]);
374                 if (found_size > item_size) {
375                         btrfs_truncate_item(trans, root, path, item_size, 1);
376                 } else if (found_size < item_size) {
377                         ret = btrfs_del_item(trans, root,
378                                              path);
379                         BUG_ON(ret);
380
381                         btrfs_release_path(root, path);
382                         ret = btrfs_insert_empty_item(trans,
383                                   root, path, key, item_size);
384                         BUG_ON(ret);
385                 }
386         } else if (ret) {
387                 BUG();
388         }
389         dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
390                                         path->slots[0]);
391
392         /* don't overwrite an existing inode if the generation number
393          * was logged as zero.  This is done when the tree logging code
394          * is just logging an inode to make sure it exists after recovery.
395          *
396          * Also, don't overwrite i_size on directories during replay.
397          * log replay inserts and removes directory items based on the
398          * state of the tree found in the subvolume, and i_size is modified
399          * as it goes
400          */
401         if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
402                 struct btrfs_inode_item *src_item;
403                 struct btrfs_inode_item *dst_item;
404
405                 src_item = (struct btrfs_inode_item *)src_ptr;
406                 dst_item = (struct btrfs_inode_item *)dst_ptr;
407
408                 if (btrfs_inode_generation(eb, src_item) == 0)
409                         goto no_copy;
410
411                 if (overwrite_root &&
412                     S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
413                     S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
414                         save_old_i_size = 1;
415                         saved_i_size = btrfs_inode_size(path->nodes[0],
416                                                         dst_item);
417                 }
418         }
419
420         copy_extent_buffer(path->nodes[0], eb, dst_ptr,
421                            src_ptr, item_size);
422
423         if (save_old_i_size) {
424                 struct btrfs_inode_item *dst_item;
425                 dst_item = (struct btrfs_inode_item *)dst_ptr;
426                 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
427         }
428
429         /* make sure the generation is filled in */
430         if (key->type == BTRFS_INODE_ITEM_KEY) {
431                 struct btrfs_inode_item *dst_item;
432                 dst_item = (struct btrfs_inode_item *)dst_ptr;
433                 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
434                         btrfs_set_inode_generation(path->nodes[0], dst_item,
435                                                    trans->transid);
436                 }
437         }
438
439         if (overwrite_root &&
440             key->type == BTRFS_EXTENT_DATA_KEY) {
441                 int extent_type;
442                 struct btrfs_file_extent_item *fi;
443
444                 fi = (struct btrfs_file_extent_item *)dst_ptr;
445                 extent_type = btrfs_file_extent_type(path->nodes[0], fi);
446                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
447                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
448                         struct btrfs_key ins;
449                         ins.objectid = btrfs_file_extent_disk_bytenr(
450                                                         path->nodes[0], fi);
451                         ins.offset = btrfs_file_extent_disk_num_bytes(
452                                                         path->nodes[0], fi);
453                         ins.type = BTRFS_EXTENT_ITEM_KEY;
454
455                         /*
456                          * is this extent already allocated in the extent
457                          * allocation tree?  If so, just add a reference
458                          */
459                         ret = btrfs_lookup_extent(root, ins.objectid,
460                                                   ins.offset);
461                         if (ret == 0) {
462                                 ret = btrfs_inc_extent_ref(trans, root,
463                                                 ins.objectid, ins.offset,
464                                                 path->nodes[0]->start,
465                                                 root->root_key.objectid,
466                                                 trans->transid, key->objectid);
467                         } else {
468                                 /*
469                                  * insert the extent pointer in the extent
470                                  * allocation tree
471                                  */
472                                 ret = btrfs_alloc_logged_extent(trans, root,
473                                                 path->nodes[0]->start,
474                                                 root->root_key.objectid,
475                                                 trans->transid, key->objectid,
476                                                 &ins);
477                                 BUG_ON(ret);
478                         }
479                 }
480         }
481 no_copy:
482         btrfs_mark_buffer_dirty(path->nodes[0]);
483         btrfs_release_path(root, path);
484         return 0;
485 }
486
487 /*
488  * simple helper to read an inode off the disk from a given root
489  * This can only be called for subvolume roots and not for the log
490  */
491 static noinline struct inode *read_one_inode(struct btrfs_root *root,
492                                              u64 objectid)
493 {
494         struct inode *inode;
495         inode = btrfs_iget_locked(root->fs_info->sb, objectid, root);
496         if (inode->i_state & I_NEW) {
497                 BTRFS_I(inode)->root = root;
498                 BTRFS_I(inode)->location.objectid = objectid;
499                 BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
500                 BTRFS_I(inode)->location.offset = 0;
501                 btrfs_read_locked_inode(inode);
502                 unlock_new_inode(inode);
503
504         }
505         if (is_bad_inode(inode)) {
506                 iput(inode);
507                 inode = NULL;
508         }
509         return inode;
510 }
511
512 /* replays a single extent in 'eb' at 'slot' with 'key' into the
513  * subvolume 'root'.  path is released on entry and should be released
514  * on exit.
515  *
516  * extents in the log tree have not been allocated out of the extent
517  * tree yet.  So, this completes the allocation, taking a reference
518  * as required if the extent already exists or creating a new extent
519  * if it isn't in the extent allocation tree yet.
520  *
521  * The extent is inserted into the file, dropping any existing extents
522  * from the file that overlap the new one.
523  */
524 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
525                                       struct btrfs_root *root,
526                                       struct btrfs_path *path,
527                                       struct extent_buffer *eb, int slot,
528                                       struct btrfs_key *key)
529 {
530         int found_type;
531         u64 mask = root->sectorsize - 1;
532         u64 extent_end;
533         u64 alloc_hint;
534         u64 start = key->offset;
535         struct btrfs_file_extent_item *item;
536         struct inode *inode = NULL;
537         unsigned long size;
538         int ret = 0;
539
540         item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
541         found_type = btrfs_file_extent_type(eb, item);
542
543         if (found_type == BTRFS_FILE_EXTENT_REG ||
544             found_type == BTRFS_FILE_EXTENT_PREALLOC)
545                 extent_end = start + btrfs_file_extent_num_bytes(eb, item);
546         else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
547                 size = btrfs_file_extent_inline_len(eb, item);
548                 extent_end = (start + size + mask) & ~mask;
549         } else {
550                 ret = 0;
551                 goto out;
552         }
553
554         inode = read_one_inode(root, key->objectid);
555         if (!inode) {
556                 ret = -EIO;
557                 goto out;
558         }
559
560         /*
561          * first check to see if we already have this extent in the
562          * file.  This must be done before the btrfs_drop_extents run
563          * so we don't try to drop this extent.
564          */
565         ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
566                                        start, 0);
567
568         if (ret == 0 &&
569             (found_type == BTRFS_FILE_EXTENT_REG ||
570              found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
571                 struct btrfs_file_extent_item cmp1;
572                 struct btrfs_file_extent_item cmp2;
573                 struct btrfs_file_extent_item *existing;
574                 struct extent_buffer *leaf;
575
576                 leaf = path->nodes[0];
577                 existing = btrfs_item_ptr(leaf, path->slots[0],
578                                           struct btrfs_file_extent_item);
579
580                 read_extent_buffer(eb, &cmp1, (unsigned long)item,
581                                    sizeof(cmp1));
582                 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
583                                    sizeof(cmp2));
584
585                 /*
586                  * we already have a pointer to this exact extent,
587                  * we don't have to do anything
588                  */
589                 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
590                         btrfs_release_path(root, path);
591                         goto out;
592                 }
593         }
594         btrfs_release_path(root, path);
595
596         /* drop any overlapping extents */
597         ret = btrfs_drop_extents(trans, root, inode,
598                          start, extent_end, start, &alloc_hint);
599         BUG_ON(ret);
600
601         /* insert the extent */
602         ret = overwrite_item(trans, root, path, eb, slot, key);
603         BUG_ON(ret);
604
605         /* btrfs_drop_extents changes i_bytes & i_blocks, update it here */
606         inode_add_bytes(inode, extent_end - start);
607         btrfs_update_inode(trans, root, inode);
608 out:
609         if (inode)
610                 iput(inode);
611         return ret;
612 }
613
614 /*
615  * when cleaning up conflicts between the directory names in the
616  * subvolume, directory names in the log and directory names in the
617  * inode back references, we may have to unlink inodes from directories.
618  *
619  * This is a helper function to do the unlink of a specific directory
620  * item
621  */
622 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
623                                       struct btrfs_root *root,
624                                       struct btrfs_path *path,
625                                       struct inode *dir,
626                                       struct btrfs_dir_item *di)
627 {
628         struct inode *inode;
629         char *name;
630         int name_len;
631         struct extent_buffer *leaf;
632         struct btrfs_key location;
633         int ret;
634
635         leaf = path->nodes[0];
636
637         btrfs_dir_item_key_to_cpu(leaf, di, &location);
638         name_len = btrfs_dir_name_len(leaf, di);
639         name = kmalloc(name_len, GFP_NOFS);
640         read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
641         btrfs_release_path(root, path);
642
643         inode = read_one_inode(root, location.objectid);
644         BUG_ON(!inode);
645
646         btrfs_inc_nlink(inode);
647         ret = btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
648         kfree(name);
649
650         iput(inode);
651         return ret;
652 }
653
654 /*
655  * helper function to see if a given name and sequence number found
656  * in an inode back reference are already in a directory and correctly
657  * point to this inode
658  */
659 static noinline int inode_in_dir(struct btrfs_root *root,
660                                  struct btrfs_path *path,
661                                  u64 dirid, u64 objectid, u64 index,
662                                  const char *name, int name_len)
663 {
664         struct btrfs_dir_item *di;
665         struct btrfs_key location;
666         int match = 0;
667
668         di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
669                                          index, name, name_len, 0);
670         if (di && !IS_ERR(di)) {
671                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
672                 if (location.objectid != objectid)
673                         goto out;
674         } else
675                 goto out;
676         btrfs_release_path(root, path);
677
678         di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
679         if (di && !IS_ERR(di)) {
680                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
681                 if (location.objectid != objectid)
682                         goto out;
683         } else
684                 goto out;
685         match = 1;
686 out:
687         btrfs_release_path(root, path);
688         return match;
689 }
690
691 /*
692  * helper function to check a log tree for a named back reference in
693  * an inode.  This is used to decide if a back reference that is
694  * found in the subvolume conflicts with what we find in the log.
695  *
696  * inode backreferences may have multiple refs in a single item,
697  * during replay we process one reference at a time, and we don't
698  * want to delete valid links to a file from the subvolume if that
699  * link is also in the log.
700  */
701 static noinline int backref_in_log(struct btrfs_root *log,
702                                    struct btrfs_key *key,
703                                    char *name, int namelen)
704 {
705         struct btrfs_path *path;
706         struct btrfs_inode_ref *ref;
707         unsigned long ptr;
708         unsigned long ptr_end;
709         unsigned long name_ptr;
710         int found_name_len;
711         int item_size;
712         int ret;
713         int match = 0;
714
715         path = btrfs_alloc_path();
716         ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
717         if (ret != 0)
718                 goto out;
719
720         item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
721         ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
722         ptr_end = ptr + item_size;
723         while (ptr < ptr_end) {
724                 ref = (struct btrfs_inode_ref *)ptr;
725                 found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
726                 if (found_name_len == namelen) {
727                         name_ptr = (unsigned long)(ref + 1);
728                         ret = memcmp_extent_buffer(path->nodes[0], name,
729                                                    name_ptr, namelen);
730                         if (ret == 0) {
731                                 match = 1;
732                                 goto out;
733                         }
734                 }
735                 ptr = (unsigned long)(ref + 1) + found_name_len;
736         }
737 out:
738         btrfs_free_path(path);
739         return match;
740 }
741
742
743 /*
744  * replay one inode back reference item found in the log tree.
745  * eb, slot and key refer to the buffer and key found in the log tree.
746  * root is the destination we are replaying into, and path is for temp
747  * use by this function.  (it should be released on return).
748  */
749 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
750                                   struct btrfs_root *root,
751                                   struct btrfs_root *log,
752                                   struct btrfs_path *path,
753                                   struct extent_buffer *eb, int slot,
754                                   struct btrfs_key *key)
755 {
756         struct inode *dir;
757         int ret;
758         struct btrfs_key location;
759         struct btrfs_inode_ref *ref;
760         struct btrfs_dir_item *di;
761         struct inode *inode;
762         char *name;
763         int namelen;
764         unsigned long ref_ptr;
765         unsigned long ref_end;
766
767         location.objectid = key->objectid;
768         location.type = BTRFS_INODE_ITEM_KEY;
769         location.offset = 0;
770
771         /*
772          * it is possible that we didn't log all the parent directories
773          * for a given inode.  If we don't find the dir, just don't
774          * copy the back ref in.  The link count fixup code will take
775          * care of the rest
776          */
777         dir = read_one_inode(root, key->offset);
778         if (!dir)
779                 return -ENOENT;
780
781         inode = read_one_inode(root, key->objectid);
782         BUG_ON(!dir);
783
784         ref_ptr = btrfs_item_ptr_offset(eb, slot);
785         ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
786
787 again:
788         ref = (struct btrfs_inode_ref *)ref_ptr;
789
790         namelen = btrfs_inode_ref_name_len(eb, ref);
791         name = kmalloc(namelen, GFP_NOFS);
792         BUG_ON(!name);
793
794         read_extent_buffer(eb, name, (unsigned long)(ref + 1), namelen);
795
796         /* if we already have a perfect match, we're done */
797         if (inode_in_dir(root, path, dir->i_ino, inode->i_ino,
798                          btrfs_inode_ref_index(eb, ref),
799                          name, namelen)) {
800                 goto out;
801         }
802
803         /*
804          * look for a conflicting back reference in the metadata.
805          * if we find one we have to unlink that name of the file
806          * before we add our new link.  Later on, we overwrite any
807          * existing back reference, and we don't want to create
808          * dangling pointers in the directory.
809          */
810 conflict_again:
811         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
812         if (ret == 0) {
813                 char *victim_name;
814                 int victim_name_len;
815                 struct btrfs_inode_ref *victim_ref;
816                 unsigned long ptr;
817                 unsigned long ptr_end;
818                 struct extent_buffer *leaf = path->nodes[0];
819
820                 /* are we trying to overwrite a back ref for the root directory
821                  * if so, just jump out, we're done
822                  */
823                 if (key->objectid == key->offset)
824                         goto out_nowrite;
825
826                 /* check all the names in this back reference to see
827                  * if they are in the log.  if so, we allow them to stay
828                  * otherwise they must be unlinked as a conflict
829                  */
830                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
831                 ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
832                 while(ptr < ptr_end) {
833                         victim_ref = (struct btrfs_inode_ref *)ptr;
834                         victim_name_len = btrfs_inode_ref_name_len(leaf,
835                                                                    victim_ref);
836                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
837                         BUG_ON(!victim_name);
838
839                         read_extent_buffer(leaf, victim_name,
840                                            (unsigned long)(victim_ref + 1),
841                                            victim_name_len);
842
843                         if (!backref_in_log(log, key, victim_name,
844                                             victim_name_len)) {
845                                 btrfs_inc_nlink(inode);
846                                 btrfs_release_path(root, path);
847                                 ret = btrfs_unlink_inode(trans, root, dir,
848                                                          inode, victim_name,
849                                                          victim_name_len);
850                                 kfree(victim_name);
851                                 btrfs_release_path(root, path);
852                                 goto conflict_again;
853                         }
854                         kfree(victim_name);
855                         ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
856                 }
857                 BUG_ON(ret);
858         }
859         btrfs_release_path(root, path);
860
861         /* look for a conflicting sequence number */
862         di = btrfs_lookup_dir_index_item(trans, root, path, dir->i_ino,
863                                          btrfs_inode_ref_index(eb, ref),
864                                          name, namelen, 0);
865         if (di && !IS_ERR(di)) {
866                 ret = drop_one_dir_item(trans, root, path, dir, di);
867                 BUG_ON(ret);
868         }
869         btrfs_release_path(root, path);
870
871
872         /* look for a conflicting name */
873         di = btrfs_lookup_dir_item(trans, root, path, dir->i_ino,
874                                    name, namelen, 0);
875         if (di && !IS_ERR(di)) {
876                 ret = drop_one_dir_item(trans, root, path, dir, di);
877                 BUG_ON(ret);
878         }
879         btrfs_release_path(root, path);
880
881         /* insert our name */
882         ret = btrfs_add_link(trans, dir, inode, name, namelen, 0,
883                              btrfs_inode_ref_index(eb, ref));
884         BUG_ON(ret);
885
886         btrfs_update_inode(trans, root, inode);
887
888 out:
889         ref_ptr = (unsigned long)(ref + 1) + namelen;
890         kfree(name);
891         if (ref_ptr < ref_end)
892                 goto again;
893
894         /* finally write the back reference in the inode */
895         ret = overwrite_item(trans, root, path, eb, slot, key);
896         BUG_ON(ret);
897
898 out_nowrite:
899         btrfs_release_path(root, path);
900         iput(dir);
901         iput(inode);
902         return 0;
903 }
904
905 /*
906  * replay one csum item from the log tree into the subvolume 'root'
907  * eb, slot and key all refer to the log tree
908  * path is for temp use by this function and should be released on return
909  *
910  * This copies the checksums out of the log tree and inserts them into
911  * the subvolume.  Any existing checksums for this range in the file
912  * are overwritten, and new items are added where required.
913  *
914  * We keep this simple by reusing the btrfs_ordered_sum code from
915  * the data=ordered mode.  This basically means making a copy
916  * of all the checksums in ram, which we have to do anyway for kmap
917  * rules.
918  *
919  * The copy is then sent down to btrfs_csum_file_blocks, which
920  * does all the hard work of finding existing items in the file
921  * or adding new ones.
922  */
923 static noinline int replay_one_csum(struct btrfs_trans_handle *trans,
924                                       struct btrfs_root *root,
925                                       struct btrfs_path *path,
926                                       struct extent_buffer *eb, int slot,
927                                       struct btrfs_key *key)
928 {
929         int ret;
930         u32 item_size = btrfs_item_size_nr(eb, slot);
931         u64 cur_offset;
932         unsigned long file_bytes;
933         struct btrfs_ordered_sum *sums;
934         struct btrfs_sector_sum *sector_sum;
935         struct inode *inode;
936         unsigned long ptr;
937
938         file_bytes = (item_size / BTRFS_CRC32_SIZE) * root->sectorsize;
939         inode = read_one_inode(root, key->objectid);
940         if (!inode) {
941                 return -EIO;
942         }
943
944         sums = kzalloc(btrfs_ordered_sum_size(root, file_bytes), GFP_NOFS);
945         if (!sums) {
946                 iput(inode);
947                 return -ENOMEM;
948         }
949
950         INIT_LIST_HEAD(&sums->list);
951         sums->len = file_bytes;
952         sums->file_offset = key->offset;
953
954         /*
955          * copy all the sums into the ordered sum struct
956          */
957         sector_sum = sums->sums;
958         cur_offset = key->offset;
959         ptr = btrfs_item_ptr_offset(eb, slot);
960         while(item_size > 0) {
961                 sector_sum->offset = cur_offset;
962                 read_extent_buffer(eb, &sector_sum->sum, ptr, BTRFS_CRC32_SIZE);
963                 sector_sum++;
964                 item_size -= BTRFS_CRC32_SIZE;
965                 ptr += BTRFS_CRC32_SIZE;
966                 cur_offset += root->sectorsize;
967         }
968
969         /* let btrfs_csum_file_blocks add them into the file */
970         ret = btrfs_csum_file_blocks(trans, root, inode, sums);
971         BUG_ON(ret);
972         kfree(sums);
973         iput(inode);
974
975         return 0;
976 }
977 /*
978  * There are a few corners where the link count of the file can't
979  * be properly maintained during replay.  So, instead of adding
980  * lots of complexity to the log code, we just scan the backrefs
981  * for any file that has been through replay.
982  *
983  * The scan will update the link count on the inode to reflect the
984  * number of back refs found.  If it goes down to zero, the iput
985  * will free the inode.
986  */
987 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
988                                            struct btrfs_root *root,
989                                            struct inode *inode)
990 {
991         struct btrfs_path *path;
992         int ret;
993         struct btrfs_key key;
994         u64 nlink = 0;
995         unsigned long ptr;
996         unsigned long ptr_end;
997         int name_len;
998
999         key.objectid = inode->i_ino;
1000         key.type = BTRFS_INODE_REF_KEY;
1001         key.offset = (u64)-1;
1002
1003         path = btrfs_alloc_path();
1004
1005         while(1) {
1006                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1007                 if (ret < 0)
1008                         break;
1009                 if (ret > 0) {
1010                         if (path->slots[0] == 0)
1011                                 break;
1012                         path->slots[0]--;
1013                 }
1014                 btrfs_item_key_to_cpu(path->nodes[0], &key,
1015                                       path->slots[0]);
1016                 if (key.objectid != inode->i_ino ||
1017                     key.type != BTRFS_INODE_REF_KEY)
1018                         break;
1019                 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1020                 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1021                                                    path->slots[0]);
1022                 while(ptr < ptr_end) {
1023                         struct btrfs_inode_ref *ref;
1024
1025                         ref = (struct btrfs_inode_ref *)ptr;
1026                         name_len = btrfs_inode_ref_name_len(path->nodes[0],
1027                                                             ref);
1028                         ptr = (unsigned long)(ref + 1) + name_len;
1029                         nlink++;
1030                 }
1031
1032                 if (key.offset == 0)
1033                         break;
1034                 key.offset--;
1035                 btrfs_release_path(root, path);
1036         }
1037         btrfs_free_path(path);
1038         if (nlink != inode->i_nlink) {
1039                 inode->i_nlink = nlink;
1040                 btrfs_update_inode(trans, root, inode);
1041         }
1042         BTRFS_I(inode)->index_cnt = (u64)-1;
1043
1044         return 0;
1045 }
1046
1047 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1048                                             struct btrfs_root *root,
1049                                             struct btrfs_path *path)
1050 {
1051         int ret;
1052         struct btrfs_key key;
1053         struct inode *inode;
1054
1055         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1056         key.type = BTRFS_ORPHAN_ITEM_KEY;
1057         key.offset = (u64)-1;
1058         while(1) {
1059                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1060                 if (ret < 0)
1061                         break;
1062
1063                 if (ret == 1) {
1064                         if (path->slots[0] == 0)
1065                                 break;
1066                         path->slots[0]--;
1067                 }
1068
1069                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1070                 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1071                     key.type != BTRFS_ORPHAN_ITEM_KEY)
1072                         break;
1073
1074                 ret = btrfs_del_item(trans, root, path);
1075                 BUG_ON(ret);
1076
1077                 btrfs_release_path(root, path);
1078                 inode = read_one_inode(root, key.offset);
1079                 BUG_ON(!inode);
1080
1081                 ret = fixup_inode_link_count(trans, root, inode);
1082                 BUG_ON(ret);
1083
1084                 iput(inode);
1085
1086                 if (key.offset == 0)
1087                         break;
1088                 key.offset--;
1089         }
1090         btrfs_release_path(root, path);
1091         return 0;
1092 }
1093
1094
1095 /*
1096  * record a given inode in the fixup dir so we can check its link
1097  * count when replay is done.  The link count is incremented here
1098  * so the inode won't go away until we check it
1099  */
1100 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1101                                       struct btrfs_root *root,
1102                                       struct btrfs_path *path,
1103                                       u64 objectid)
1104 {
1105         struct btrfs_key key;
1106         int ret = 0;
1107         struct inode *inode;
1108
1109         inode = read_one_inode(root, objectid);
1110         BUG_ON(!inode);
1111
1112         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1113         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
1114         key.offset = objectid;
1115
1116         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1117
1118         btrfs_release_path(root, path);
1119         if (ret == 0) {
1120                 btrfs_inc_nlink(inode);
1121                 btrfs_update_inode(trans, root, inode);
1122         } else if (ret == -EEXIST) {
1123                 ret = 0;
1124         } else {
1125                 BUG();
1126         }
1127         iput(inode);
1128
1129         return ret;
1130 }
1131
1132 /*
1133  * when replaying the log for a directory, we only insert names
1134  * for inodes that actually exist.  This means an fsync on a directory
1135  * does not implicitly fsync all the new files in it
1136  */
1137 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1138                                     struct btrfs_root *root,
1139                                     struct btrfs_path *path,
1140                                     u64 dirid, u64 index,
1141                                     char *name, int name_len, u8 type,
1142                                     struct btrfs_key *location)
1143 {
1144         struct inode *inode;
1145         struct inode *dir;
1146         int ret;
1147
1148         inode = read_one_inode(root, location->objectid);
1149         if (!inode)
1150                 return -ENOENT;
1151
1152         dir = read_one_inode(root, dirid);
1153         if (!dir) {
1154                 iput(inode);
1155                 return -EIO;
1156         }
1157         ret = btrfs_add_link(trans, dir, inode, name, name_len, 1, index);
1158
1159         /* FIXME, put inode into FIXUP list */
1160
1161         iput(inode);
1162         iput(dir);
1163         return ret;
1164 }
1165
1166 /*
1167  * take a single entry in a log directory item and replay it into
1168  * the subvolume.
1169  *
1170  * if a conflicting item exists in the subdirectory already,
1171  * the inode it points to is unlinked and put into the link count
1172  * fix up tree.
1173  *
1174  * If a name from the log points to a file or directory that does
1175  * not exist in the FS, it is skipped.  fsyncs on directories
1176  * do not force down inodes inside that directory, just changes to the
1177  * names or unlinks in a directory.
1178  */
1179 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1180                                     struct btrfs_root *root,
1181                                     struct btrfs_path *path,
1182                                     struct extent_buffer *eb,
1183                                     struct btrfs_dir_item *di,
1184                                     struct btrfs_key *key)
1185 {
1186         char *name;
1187         int name_len;
1188         struct btrfs_dir_item *dst_di;
1189         struct btrfs_key found_key;
1190         struct btrfs_key log_key;
1191         struct inode *dir;
1192         u8 log_type;
1193         int exists;
1194         int ret;
1195
1196         dir = read_one_inode(root, key->objectid);
1197         BUG_ON(!dir);
1198
1199         name_len = btrfs_dir_name_len(eb, di);
1200         name = kmalloc(name_len, GFP_NOFS);
1201         log_type = btrfs_dir_type(eb, di);
1202         read_extent_buffer(eb, name, (unsigned long)(di + 1),
1203                    name_len);
1204
1205         btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1206         exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1207         if (exists == 0)
1208                 exists = 1;
1209         else
1210                 exists = 0;
1211         btrfs_release_path(root, path);
1212
1213         if (key->type == BTRFS_DIR_ITEM_KEY) {
1214                 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1215                                        name, name_len, 1);
1216         }
1217         else if (key->type == BTRFS_DIR_INDEX_KEY) {
1218                 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1219                                                      key->objectid,
1220                                                      key->offset, name,
1221                                                      name_len, 1);
1222         } else {
1223                 BUG();
1224         }
1225         if (!dst_di || IS_ERR(dst_di)) {
1226                 /* we need a sequence number to insert, so we only
1227                  * do inserts for the BTRFS_DIR_INDEX_KEY types
1228                  */
1229                 if (key->type != BTRFS_DIR_INDEX_KEY)
1230                         goto out;
1231                 goto insert;
1232         }
1233
1234         btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1235         /* the existing item matches the logged item */
1236         if (found_key.objectid == log_key.objectid &&
1237             found_key.type == log_key.type &&
1238             found_key.offset == log_key.offset &&
1239             btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
1240                 goto out;
1241         }
1242
1243         /*
1244          * don't drop the conflicting directory entry if the inode
1245          * for the new entry doesn't exist
1246          */
1247         if (!exists)
1248                 goto out;
1249
1250         ret = drop_one_dir_item(trans, root, path, dir, dst_di);
1251         BUG_ON(ret);
1252
1253         if (key->type == BTRFS_DIR_INDEX_KEY)
1254                 goto insert;
1255 out:
1256         btrfs_release_path(root, path);
1257         kfree(name);
1258         iput(dir);
1259         return 0;
1260
1261 insert:
1262         btrfs_release_path(root, path);
1263         ret = insert_one_name(trans, root, path, key->objectid, key->offset,
1264                               name, name_len, log_type, &log_key);
1265
1266         if (ret && ret != -ENOENT)
1267                 BUG();
1268         goto out;
1269 }
1270
1271 /*
1272  * find all the names in a directory item and reconcile them into
1273  * the subvolume.  Only BTRFS_DIR_ITEM_KEY types will have more than
1274  * one name in a directory item, but the same code gets used for
1275  * both directory index types
1276  */
1277 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1278                                         struct btrfs_root *root,
1279                                         struct btrfs_path *path,
1280                                         struct extent_buffer *eb, int slot,
1281                                         struct btrfs_key *key)
1282 {
1283         int ret;
1284         u32 item_size = btrfs_item_size_nr(eb, slot);
1285         struct btrfs_dir_item *di;
1286         int name_len;
1287         unsigned long ptr;
1288         unsigned long ptr_end;
1289
1290         ptr = btrfs_item_ptr_offset(eb, slot);
1291         ptr_end = ptr + item_size;
1292         while(ptr < ptr_end) {
1293                 di = (struct btrfs_dir_item *)ptr;
1294                 name_len = btrfs_dir_name_len(eb, di);
1295                 ret = replay_one_name(trans, root, path, eb, di, key);
1296                 BUG_ON(ret);
1297                 ptr = (unsigned long)(di + 1);
1298                 ptr += name_len;
1299         }
1300         return 0;
1301 }
1302
1303 /*
1304  * directory replay has two parts.  There are the standard directory
1305  * items in the log copied from the subvolume, and range items
1306  * created in the log while the subvolume was logged.
1307  *
1308  * The range items tell us which parts of the key space the log
1309  * is authoritative for.  During replay, if a key in the subvolume
1310  * directory is in a logged range item, but not actually in the log
1311  * that means it was deleted from the directory before the fsync
1312  * and should be removed.
1313  */
1314 static noinline int find_dir_range(struct btrfs_root *root,
1315                                    struct btrfs_path *path,
1316                                    u64 dirid, int key_type,
1317                                    u64 *start_ret, u64 *end_ret)
1318 {
1319         struct btrfs_key key;
1320         u64 found_end;
1321         struct btrfs_dir_log_item *item;
1322         int ret;
1323         int nritems;
1324
1325         if (*start_ret == (u64)-1)
1326                 return 1;
1327
1328         key.objectid = dirid;
1329         key.type = key_type;
1330         key.offset = *start_ret;
1331
1332         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1333         if (ret < 0)
1334                 goto out;
1335         if (ret > 0) {
1336                 if (path->slots[0] == 0)
1337                         goto out;
1338                 path->slots[0]--;
1339         }
1340         if (ret != 0)
1341                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1342
1343         if (key.type != key_type || key.objectid != dirid) {
1344                 ret = 1;
1345                 goto next;
1346         }
1347         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1348                               struct btrfs_dir_log_item);
1349         found_end = btrfs_dir_log_end(path->nodes[0], item);
1350
1351         if (*start_ret >= key.offset && *start_ret <= found_end) {
1352                 ret = 0;
1353                 *start_ret = key.offset;
1354                 *end_ret = found_end;
1355                 goto out;
1356         }
1357         ret = 1;
1358 next:
1359         /* check the next slot in the tree to see if it is a valid item */
1360         nritems = btrfs_header_nritems(path->nodes[0]);
1361         if (path->slots[0] >= nritems) {
1362                 ret = btrfs_next_leaf(root, path);
1363                 if (ret)
1364                         goto out;
1365         } else {
1366                 path->slots[0]++;
1367         }
1368
1369         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1370
1371         if (key.type != key_type || key.objectid != dirid) {
1372                 ret = 1;
1373                 goto out;
1374         }
1375         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1376                               struct btrfs_dir_log_item);
1377         found_end = btrfs_dir_log_end(path->nodes[0], item);
1378         *start_ret = key.offset;
1379         *end_ret = found_end;
1380         ret = 0;
1381 out:
1382         btrfs_release_path(root, path);
1383         return ret;
1384 }
1385
1386 /*
1387  * this looks for a given directory item in the log.  If the directory
1388  * item is not in the log, the item is removed and the inode it points
1389  * to is unlinked
1390  */
1391 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
1392                                       struct btrfs_root *root,
1393                                       struct btrfs_root *log,
1394                                       struct btrfs_path *path,
1395                                       struct btrfs_path *log_path,
1396                                       struct inode *dir,
1397                                       struct btrfs_key *dir_key)
1398 {
1399         int ret;
1400         struct extent_buffer *eb;
1401         int slot;
1402         u32 item_size;
1403         struct btrfs_dir_item *di;
1404         struct btrfs_dir_item *log_di;
1405         int name_len;
1406         unsigned long ptr;
1407         unsigned long ptr_end;
1408         char *name;
1409         struct inode *inode;
1410         struct btrfs_key location;
1411
1412 again:
1413         eb = path->nodes[0];
1414         slot = path->slots[0];
1415         item_size = btrfs_item_size_nr(eb, slot);
1416         ptr = btrfs_item_ptr_offset(eb, slot);
1417         ptr_end = ptr + item_size;
1418         while(ptr < ptr_end) {
1419                 di = (struct btrfs_dir_item *)ptr;
1420                 name_len = btrfs_dir_name_len(eb, di);
1421                 name = kmalloc(name_len, GFP_NOFS);
1422                 if (!name) {
1423                         ret = -ENOMEM;
1424                         goto out;
1425                 }
1426                 read_extent_buffer(eb, name, (unsigned long)(di + 1),
1427                                   name_len);
1428                 log_di = NULL;
1429                 if (dir_key->type == BTRFS_DIR_ITEM_KEY) {
1430                         log_di = btrfs_lookup_dir_item(trans, log, log_path,
1431                                                        dir_key->objectid,
1432                                                        name, name_len, 0);
1433                 } else if (dir_key->type == BTRFS_DIR_INDEX_KEY) {
1434                         log_di = btrfs_lookup_dir_index_item(trans, log,
1435                                                      log_path,
1436                                                      dir_key->objectid,
1437                                                      dir_key->offset,
1438                                                      name, name_len, 0);
1439                 }
1440                 if (!log_di || IS_ERR(log_di)) {
1441                         btrfs_dir_item_key_to_cpu(eb, di, &location);
1442                         btrfs_release_path(root, path);
1443                         btrfs_release_path(log, log_path);
1444                         inode = read_one_inode(root, location.objectid);
1445                         BUG_ON(!inode);
1446
1447                         ret = link_to_fixup_dir(trans, root,
1448                                                 path, location.objectid);
1449                         BUG_ON(ret);
1450                         btrfs_inc_nlink(inode);
1451                         ret = btrfs_unlink_inode(trans, root, dir, inode,
1452                                                  name, name_len);
1453                         BUG_ON(ret);
1454                         kfree(name);
1455                         iput(inode);
1456
1457                         /* there might still be more names under this key
1458                          * check and repeat if required
1459                          */
1460                         ret = btrfs_search_slot(NULL, root, dir_key, path,
1461                                                 0, 0);
1462                         if (ret == 0)
1463                                 goto again;
1464                         ret = 0;
1465                         goto out;
1466                 }
1467                 btrfs_release_path(log, log_path);
1468                 kfree(name);
1469
1470                 ptr = (unsigned long)(di + 1);
1471                 ptr += name_len;
1472         }
1473         ret = 0;
1474 out:
1475         btrfs_release_path(root, path);
1476         btrfs_release_path(log, log_path);
1477         return ret;
1478 }
1479
1480 /*
1481  * deletion replay happens before we copy any new directory items
1482  * out of the log or out of backreferences from inodes.  It
1483  * scans the log to find ranges of keys that log is authoritative for,
1484  * and then scans the directory to find items in those ranges that are
1485  * not present in the log.
1486  *
1487  * Anything we don't find in the log is unlinked and removed from the
1488  * directory.
1489  */
1490 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
1491                                        struct btrfs_root *root,
1492                                        struct btrfs_root *log,
1493                                        struct btrfs_path *path,
1494                                        u64 dirid)
1495 {
1496         u64 range_start;
1497         u64 range_end;
1498         int key_type = BTRFS_DIR_LOG_ITEM_KEY;
1499         int ret = 0;
1500         struct btrfs_key dir_key;
1501         struct btrfs_key found_key;
1502         struct btrfs_path *log_path;
1503         struct inode *dir;
1504
1505         dir_key.objectid = dirid;
1506         dir_key.type = BTRFS_DIR_ITEM_KEY;
1507         log_path = btrfs_alloc_path();
1508         if (!log_path)
1509                 return -ENOMEM;
1510
1511         dir = read_one_inode(root, dirid);
1512         /* it isn't an error if the inode isn't there, that can happen
1513          * because we replay the deletes before we copy in the inode item
1514          * from the log
1515          */
1516         if (!dir) {
1517                 btrfs_free_path(log_path);
1518                 return 0;
1519         }
1520 again:
1521         range_start = 0;
1522         range_end = 0;
1523         while(1) {
1524                 ret = find_dir_range(log, path, dirid, key_type,
1525                                      &range_start, &range_end);
1526                 if (ret != 0)
1527                         break;
1528
1529                 dir_key.offset = range_start;
1530                 while(1) {
1531                         int nritems;
1532                         ret = btrfs_search_slot(NULL, root, &dir_key, path,
1533                                                 0, 0);
1534                         if (ret < 0)
1535                                 goto out;
1536
1537                         nritems = btrfs_header_nritems(path->nodes[0]);
1538                         if (path->slots[0] >= nritems) {
1539                                 ret = btrfs_next_leaf(root, path);
1540                                 if (ret)
1541                                         break;
1542                         }
1543                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1544                                               path->slots[0]);
1545                         if (found_key.objectid != dirid ||
1546                             found_key.type != dir_key.type)
1547                                 goto next_type;
1548
1549                         if (found_key.offset > range_end)
1550                                 break;
1551
1552                         ret = check_item_in_log(trans, root, log, path,
1553                                                 log_path, dir, &found_key);
1554                         BUG_ON(ret);
1555                         if (found_key.offset == (u64)-1)
1556                                 break;
1557                         dir_key.offset = found_key.offset + 1;
1558                 }
1559                 btrfs_release_path(root, path);
1560                 if (range_end == (u64)-1)
1561                         break;
1562                 range_start = range_end + 1;
1563         }
1564
1565 next_type:
1566         ret = 0;
1567         if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
1568                 key_type = BTRFS_DIR_LOG_INDEX_KEY;
1569                 dir_key.type = BTRFS_DIR_INDEX_KEY;
1570                 btrfs_release_path(root, path);
1571                 goto again;
1572         }
1573 out:
1574         btrfs_release_path(root, path);
1575         btrfs_free_path(log_path);
1576         iput(dir);
1577         return ret;
1578 }
1579
1580 /*
1581  * the process_func used to replay items from the log tree.  This
1582  * gets called in two different stages.  The first stage just looks
1583  * for inodes and makes sure they are all copied into the subvolume.
1584  *
1585  * The second stage copies all the other item types from the log into
1586  * the subvolume.  The two stage approach is slower, but gets rid of
1587  * lots of complexity around inodes referencing other inodes that exist
1588  * only in the log (references come from either directory items or inode
1589  * back refs).
1590  */
1591 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
1592                              struct walk_control *wc, u64 gen)
1593 {
1594         int nritems;
1595         struct btrfs_path *path;
1596         struct btrfs_root *root = wc->replay_dest;
1597         struct btrfs_key key;
1598         u32 item_size;
1599         int level;
1600         int i;
1601         int ret;
1602
1603         btrfs_read_buffer(eb, gen);
1604
1605         level = btrfs_header_level(eb);
1606
1607         if (level != 0)
1608                 return 0;
1609
1610         path = btrfs_alloc_path();
1611         BUG_ON(!path);
1612
1613         nritems = btrfs_header_nritems(eb);
1614         for (i = 0; i < nritems; i++) {
1615                 btrfs_item_key_to_cpu(eb, &key, i);
1616                 item_size = btrfs_item_size_nr(eb, i);
1617
1618                 /* inode keys are done during the first stage */
1619                 if (key.type == BTRFS_INODE_ITEM_KEY &&
1620                     wc->stage == LOG_WALK_REPLAY_INODES) {
1621                         struct inode *inode;
1622                         struct btrfs_inode_item *inode_item;
1623                         u32 mode;
1624
1625                         inode_item = btrfs_item_ptr(eb, i,
1626                                             struct btrfs_inode_item);
1627                         mode = btrfs_inode_mode(eb, inode_item);
1628                         if (S_ISDIR(mode)) {
1629                                 ret = replay_dir_deletes(wc->trans,
1630                                          root, log, path, key.objectid);
1631                                 BUG_ON(ret);
1632                         }
1633                         ret = overwrite_item(wc->trans, root, path,
1634                                              eb, i, &key);
1635                         BUG_ON(ret);
1636
1637                         /* for regular files, truncate away
1638                          * extents past the new EOF
1639                          */
1640                         if (S_ISREG(mode)) {
1641                                 inode = read_one_inode(root,
1642                                                        key.objectid);
1643                                 BUG_ON(!inode);
1644
1645                                 ret = btrfs_truncate_inode_items(wc->trans,
1646                                         root, inode, inode->i_size,
1647                                         BTRFS_EXTENT_DATA_KEY);
1648                                 BUG_ON(ret);
1649                                 iput(inode);
1650                         }
1651                         ret = link_to_fixup_dir(wc->trans, root,
1652                                                 path, key.objectid);
1653                         BUG_ON(ret);
1654                 }
1655                 if (wc->stage < LOG_WALK_REPLAY_ALL)
1656                         continue;
1657
1658                 /* these keys are simply copied */
1659                 if (key.type == BTRFS_XATTR_ITEM_KEY) {
1660                         ret = overwrite_item(wc->trans, root, path,
1661                                              eb, i, &key);
1662                         BUG_ON(ret);
1663                 } else if (key.type == BTRFS_INODE_REF_KEY) {
1664                         ret = add_inode_ref(wc->trans, root, log, path,
1665                                             eb, i, &key);
1666                         BUG_ON(ret && ret != -ENOENT);
1667                 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
1668                         ret = replay_one_extent(wc->trans, root, path,
1669                                                 eb, i, &key);
1670                         BUG_ON(ret);
1671                 } else if (key.type == BTRFS_CSUM_ITEM_KEY) {
1672                         ret = replay_one_csum(wc->trans, root, path,
1673                                               eb, i, &key);
1674                         BUG_ON(ret);
1675                 } else if (key.type == BTRFS_DIR_ITEM_KEY ||
1676                            key.type == BTRFS_DIR_INDEX_KEY) {
1677                         ret = replay_one_dir_item(wc->trans, root, path,
1678                                                   eb, i, &key);
1679                         BUG_ON(ret);
1680                 }
1681         }
1682         btrfs_free_path(path);
1683         return 0;
1684 }
1685
1686 static int noinline walk_down_log_tree(struct btrfs_trans_handle *trans,
1687                                    struct btrfs_root *root,
1688                                    struct btrfs_path *path, int *level,
1689                                    struct walk_control *wc)
1690 {
1691         u64 root_owner;
1692         u64 root_gen;
1693         u64 bytenr;
1694         u64 ptr_gen;
1695         struct extent_buffer *next;
1696         struct extent_buffer *cur;
1697         struct extent_buffer *parent;
1698         u32 blocksize;
1699         int ret = 0;
1700
1701         WARN_ON(*level < 0);
1702         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1703
1704         while(*level > 0) {
1705                 WARN_ON(*level < 0);
1706                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
1707                 cur = path->nodes[*level];
1708
1709                 if (btrfs_header_level(cur) != *level)
1710                         WARN_ON(1);
1711
1712                 if (path->slots[*level] >=
1713                     btrfs_header_nritems(cur))
1714                         break;
1715
1716                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
1717                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
1718                 blocksize = btrfs_level_size(root, *level - 1);
1719
1720                 parent = path->nodes[*level];
1721                 root_owner = btrfs_header_owner(parent);
1722                 root_gen = btrfs_header_generation(parent);
1723
1724                 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
1725
1726                 wc->process_func(root, next, wc, ptr_gen);
1727
1728                 if (*level == 1) {
1729                         path->slots[*level]++;
1730                         if (wc->free) {
1731                                 btrfs_read_buffer(next, ptr_gen);
1732
1733                                 btrfs_tree_lock(next);
1734                                 clean_tree_block(trans, root, next);
1735                                 btrfs_wait_tree_block_writeback(next);
1736                                 btrfs_tree_unlock(next);
1737
1738                                 ret = btrfs_drop_leaf_ref(trans, root, next);
1739                                 BUG_ON(ret);
1740
1741                                 WARN_ON(root_owner !=
1742                                         BTRFS_TREE_LOG_OBJECTID);
1743                                 ret = btrfs_free_reserved_extent(root,
1744                                                          bytenr, blocksize);
1745                                 BUG_ON(ret);
1746                         }
1747                         free_extent_buffer(next);
1748                         continue;
1749                 }
1750                 btrfs_read_buffer(next, ptr_gen);
1751
1752                 WARN_ON(*level <= 0);
1753                 if (path->nodes[*level-1])
1754                         free_extent_buffer(path->nodes[*level-1]);
1755                 path->nodes[*level-1] = next;
1756                 *level = btrfs_header_level(next);
1757                 path->slots[*level] = 0;
1758                 cond_resched();
1759         }
1760         WARN_ON(*level < 0);
1761         WARN_ON(*level >= BTRFS_MAX_LEVEL);
1762
1763         if (path->nodes[*level] == root->node) {
1764                 parent = path->nodes[*level];
1765         } else {
1766                 parent = path->nodes[*level + 1];
1767         }
1768         bytenr = path->nodes[*level]->start;
1769
1770         blocksize = btrfs_level_size(root, *level);
1771         root_owner = btrfs_header_owner(parent);
1772         root_gen = btrfs_header_generation(parent);
1773
1774         wc->process_func(root, path->nodes[*level], wc,
1775                          btrfs_header_generation(path->nodes[*level]));
1776
1777         if (wc->free) {
1778                 next = path->nodes[*level];
1779                 btrfs_tree_lock(next);
1780                 clean_tree_block(trans, root, next);
1781                 btrfs_wait_tree_block_writeback(next);
1782                 btrfs_tree_unlock(next);
1783
1784                 if (*level == 0) {
1785                         ret = btrfs_drop_leaf_ref(trans, root, next);
1786                         BUG_ON(ret);
1787                 }
1788                 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
1789                 ret = btrfs_free_reserved_extent(root, bytenr, blocksize);
1790                 BUG_ON(ret);
1791         }
1792         free_extent_buffer(path->nodes[*level]);
1793         path->nodes[*level] = NULL;
1794         *level += 1;
1795
1796         cond_resched();
1797         return 0;
1798 }
1799
1800 static int noinline walk_up_log_tree(struct btrfs_trans_handle *trans,
1801                                  struct btrfs_root *root,
1802                                  struct btrfs_path *path, int *level,
1803                                  struct walk_control *wc)
1804 {
1805         u64 root_owner;
1806         u64 root_gen;
1807         int i;
1808         int slot;
1809         int ret;
1810
1811         for(i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
1812                 slot = path->slots[i];
1813                 if (slot < btrfs_header_nritems(path->nodes[i]) - 1) {
1814                         struct extent_buffer *node;
1815                         node = path->nodes[i];
1816                         path->slots[i]++;
1817                         *level = i;
1818                         WARN_ON(*level == 0);
1819                         return 0;
1820                 } else {
1821                         struct extent_buffer *parent;
1822                         if (path->nodes[*level] == root->node)
1823                                 parent = path->nodes[*level];
1824                         else
1825                                 parent = path->nodes[*level + 1];
1826
1827                         root_owner = btrfs_header_owner(parent);
1828                         root_gen = btrfs_header_generation(parent);
1829                         wc->process_func(root, path->nodes[*level], wc,
1830                                  btrfs_header_generation(path->nodes[*level]));
1831                         if (wc->free) {
1832                                 struct extent_buffer *next;
1833
1834                                 next = path->nodes[*level];
1835
1836                                 btrfs_tree_lock(next);
1837                                 clean_tree_block(trans, root, next);
1838                                 btrfs_wait_tree_block_writeback(next);
1839                                 btrfs_tree_unlock(next);
1840
1841                                 if (*level == 0) {
1842                                         ret = btrfs_drop_leaf_ref(trans, root,
1843                                                                   next);
1844                                         BUG_ON(ret);
1845                                 }
1846
1847                                 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
1848                                 ret = btrfs_free_reserved_extent(root,
1849                                                 path->nodes[*level]->start,
1850                                                 path->nodes[*level]->len);
1851                                 BUG_ON(ret);
1852                         }
1853                         free_extent_buffer(path->nodes[*level]);
1854                         path->nodes[*level] = NULL;
1855                         *level = i + 1;
1856                 }
1857         }
1858         return 1;
1859 }
1860
1861 /*
1862  * drop the reference count on the tree rooted at 'snap'.  This traverses
1863  * the tree freeing any blocks that have a ref count of zero after being
1864  * decremented.
1865  */
1866 static int walk_log_tree(struct btrfs_trans_handle *trans,
1867                          struct btrfs_root *log, struct walk_control *wc)
1868 {
1869         int ret = 0;
1870         int wret;
1871         int level;
1872         struct btrfs_path *path;
1873         int i;
1874         int orig_level;
1875
1876         path = btrfs_alloc_path();
1877         BUG_ON(!path);
1878
1879         level = btrfs_header_level(log->node);
1880         orig_level = level;
1881         path->nodes[level] = log->node;
1882         extent_buffer_get(log->node);
1883         path->slots[level] = 0;
1884
1885         while(1) {
1886                 wret = walk_down_log_tree(trans, log, path, &level, wc);
1887                 if (wret > 0)
1888                         break;
1889                 if (wret < 0)
1890                         ret = wret;
1891
1892                 wret = walk_up_log_tree(trans, log, path, &level, wc);
1893                 if (wret > 0)
1894                         break;
1895                 if (wret < 0)
1896                         ret = wret;
1897         }
1898
1899         /* was the root node processed? if not, catch it here */
1900         if (path->nodes[orig_level]) {
1901                 wc->process_func(log, path->nodes[orig_level], wc,
1902                          btrfs_header_generation(path->nodes[orig_level]));
1903                 if (wc->free) {
1904                         struct extent_buffer *next;
1905
1906                         next = path->nodes[orig_level];
1907
1908                         btrfs_tree_lock(next);
1909                         clean_tree_block(trans, log, next);
1910                         btrfs_wait_tree_block_writeback(next);
1911                         btrfs_tree_unlock(next);
1912
1913                         if (orig_level == 0) {
1914                                 ret = btrfs_drop_leaf_ref(trans, log,
1915                                                           next);
1916                                 BUG_ON(ret);
1917                         }
1918                         WARN_ON(log->root_key.objectid !=
1919                                 BTRFS_TREE_LOG_OBJECTID);
1920                         ret = btrfs_free_reserved_extent(log, next->start,
1921                                                          next->len);
1922                         BUG_ON(ret);
1923                 }
1924         }
1925
1926         for (i = 0; i <= orig_level; i++) {
1927                 if (path->nodes[i]) {
1928                         free_extent_buffer(path->nodes[i]);
1929                         path->nodes[i] = NULL;
1930                 }
1931         }
1932         btrfs_free_path(path);
1933         if (wc->free)
1934                 free_extent_buffer(log->node);
1935         return ret;
1936 }
1937
1938 static int wait_log_commit(struct btrfs_root *log)
1939 {
1940         DEFINE_WAIT(wait);
1941         u64 transid = log->fs_info->tree_log_transid;
1942
1943         do {
1944                 prepare_to_wait(&log->fs_info->tree_log_wait, &wait,
1945                                 TASK_UNINTERRUPTIBLE);
1946                 mutex_unlock(&log->fs_info->tree_log_mutex);
1947                 if (atomic_read(&log->fs_info->tree_log_commit))
1948                         schedule();
1949                 finish_wait(&log->fs_info->tree_log_wait, &wait);
1950                 mutex_lock(&log->fs_info->tree_log_mutex);
1951         } while(transid == log->fs_info->tree_log_transid &&
1952                 atomic_read(&log->fs_info->tree_log_commit));
1953         return 0;
1954 }
1955
1956 /*
1957  * btrfs_sync_log does sends a given tree log down to the disk and
1958  * updates the super blocks to record it.  When this call is done,
1959  * you know that any inodes previously logged are safely on disk
1960  */
1961 int btrfs_sync_log(struct btrfs_trans_handle *trans,
1962                    struct btrfs_root *root)
1963 {
1964         int ret;
1965         unsigned long batch;
1966         struct btrfs_root *log = root->log_root;
1967
1968         mutex_lock(&log->fs_info->tree_log_mutex);
1969         if (atomic_read(&log->fs_info->tree_log_commit)) {
1970                 wait_log_commit(log);
1971                 goto out;
1972         }
1973         atomic_set(&log->fs_info->tree_log_commit, 1);
1974
1975         while(1) {
1976                 batch = log->fs_info->tree_log_batch;
1977                 mutex_unlock(&log->fs_info->tree_log_mutex);
1978                 schedule_timeout_uninterruptible(1);
1979                 mutex_lock(&log->fs_info->tree_log_mutex);
1980
1981                 while(atomic_read(&log->fs_info->tree_log_writers)) {
1982                         DEFINE_WAIT(wait);
1983                         prepare_to_wait(&log->fs_info->tree_log_wait, &wait,
1984                                         TASK_UNINTERRUPTIBLE);
1985                         mutex_unlock(&log->fs_info->tree_log_mutex);
1986                         if (atomic_read(&log->fs_info->tree_log_writers))
1987                                 schedule();
1988                         mutex_lock(&log->fs_info->tree_log_mutex);
1989                         finish_wait(&log->fs_info->tree_log_wait, &wait);
1990                 }
1991                 if (batch == log->fs_info->tree_log_batch)
1992                         break;
1993         }
1994
1995         ret = btrfs_write_and_wait_marked_extents(log, &log->dirty_log_pages);
1996         BUG_ON(ret);
1997         ret = btrfs_write_and_wait_marked_extents(root->fs_info->log_root_tree,
1998                                &root->fs_info->log_root_tree->dirty_log_pages);
1999         BUG_ON(ret);
2000
2001         btrfs_set_super_log_root(&root->fs_info->super_for_commit,
2002                                  log->fs_info->log_root_tree->node->start);
2003         btrfs_set_super_log_root_level(&root->fs_info->super_for_commit,
2004                        btrfs_header_level(log->fs_info->log_root_tree->node));
2005
2006         write_ctree_super(trans, log->fs_info->tree_root);
2007         log->fs_info->tree_log_transid++;
2008         log->fs_info->tree_log_batch = 0;
2009         atomic_set(&log->fs_info->tree_log_commit, 0);
2010         smp_mb();
2011         if (waitqueue_active(&log->fs_info->tree_log_wait))
2012                 wake_up(&log->fs_info->tree_log_wait);
2013 out:
2014         mutex_unlock(&log->fs_info->tree_log_mutex);
2015         return 0;
2016
2017 }
2018
2019 /* * free all the extents used by the tree log.  This should be called
2020  * at commit time of the full transaction
2021  */
2022 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
2023 {
2024         int ret;
2025         struct btrfs_root *log;
2026         struct key;
2027         u64 start;
2028         u64 end;
2029         struct walk_control wc = {
2030                 .free = 1,
2031                 .process_func = process_one_buffer
2032         };
2033
2034         if (!root->log_root)
2035                 return 0;
2036
2037         log = root->log_root;
2038         ret = walk_log_tree(trans, log, &wc);
2039         BUG_ON(ret);
2040
2041         while(1) {
2042                 ret = find_first_extent_bit(&log->dirty_log_pages,
2043                                     0, &start, &end, EXTENT_DIRTY);
2044                 if (ret)
2045                         break;
2046
2047                 clear_extent_dirty(&log->dirty_log_pages,
2048                                    start, end, GFP_NOFS);
2049         }
2050
2051         log = root->log_root;
2052         ret = btrfs_del_root(trans, root->fs_info->log_root_tree,
2053                              &log->root_key);
2054         BUG_ON(ret);
2055         root->log_root = NULL;
2056         kfree(root->log_root);
2057         return 0;
2058 }
2059
2060 /*
2061  * helper function to update the item for a given subvolumes log root
2062  * in the tree of log roots
2063  */
2064 static int update_log_root(struct btrfs_trans_handle *trans,
2065                            struct btrfs_root *log)
2066 {
2067         u64 bytenr = btrfs_root_bytenr(&log->root_item);
2068         int ret;
2069
2070         if (log->node->start == bytenr)
2071                 return 0;
2072
2073         btrfs_set_root_bytenr(&log->root_item, log->node->start);
2074         btrfs_set_root_generation(&log->root_item, trans->transid);
2075         btrfs_set_root_level(&log->root_item, btrfs_header_level(log->node));
2076         ret = btrfs_update_root(trans, log->fs_info->log_root_tree,
2077                                 &log->root_key, &log->root_item);
2078         BUG_ON(ret);
2079         return ret;
2080 }
2081
2082 /*
2083  * If both a file and directory are logged, and unlinks or renames are
2084  * mixed in, we have a few interesting corners:
2085  *
2086  * create file X in dir Y
2087  * link file X to X.link in dir Y
2088  * fsync file X
2089  * unlink file X but leave X.link
2090  * fsync dir Y
2091  *
2092  * After a crash we would expect only X.link to exist.  But file X
2093  * didn't get fsync'd again so the log has back refs for X and X.link.
2094  *
2095  * We solve this by removing directory entries and inode backrefs from the
2096  * log when a file that was logged in the current transaction is
2097  * unlinked.  Any later fsync will include the updated log entries, and
2098  * we'll be able to reconstruct the proper directory items from backrefs.
2099  *
2100  * This optimizations allows us to avoid relogging the entire inode
2101  * or the entire directory.
2102  */
2103 int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
2104                                  struct btrfs_root *root,
2105                                  const char *name, int name_len,
2106                                  struct inode *dir, u64 index)
2107 {
2108         struct btrfs_root *log;
2109         struct btrfs_dir_item *di;
2110         struct btrfs_path *path;
2111         int ret;
2112         int bytes_del = 0;
2113
2114         if (BTRFS_I(dir)->logged_trans < trans->transid)
2115                 return 0;
2116
2117         ret = join_running_log_trans(root);
2118         if (ret)
2119                 return 0;
2120
2121         mutex_lock(&BTRFS_I(dir)->log_mutex);
2122
2123         log = root->log_root;
2124         path = btrfs_alloc_path();
2125         di = btrfs_lookup_dir_item(trans, log, path, dir->i_ino,
2126                                    name, name_len, -1);
2127         if (di && !IS_ERR(di)) {
2128                 ret = btrfs_delete_one_dir_name(trans, log, path, di);
2129                 bytes_del += name_len;
2130                 BUG_ON(ret);
2131         }
2132         btrfs_release_path(log, path);
2133         di = btrfs_lookup_dir_index_item(trans, log, path, dir->i_ino,
2134                                          index, name, name_len, -1);
2135         if (di && !IS_ERR(di)) {
2136                 ret = btrfs_delete_one_dir_name(trans, log, path, di);
2137                 bytes_del += name_len;
2138                 BUG_ON(ret);
2139         }
2140
2141         /* update the directory size in the log to reflect the names
2142          * we have removed
2143          */
2144         if (bytes_del) {
2145                 struct btrfs_key key;
2146
2147                 key.objectid = dir->i_ino;
2148                 key.offset = 0;
2149                 key.type = BTRFS_INODE_ITEM_KEY;
2150                 btrfs_release_path(log, path);
2151
2152                 ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
2153                 if (ret == 0) {
2154                         struct btrfs_inode_item *item;
2155                         u64 i_size;
2156
2157                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2158                                               struct btrfs_inode_item);
2159                         i_size = btrfs_inode_size(path->nodes[0], item);
2160                         if (i_size > bytes_del)
2161                                 i_size -= bytes_del;
2162                         else
2163                                 i_size = 0;
2164                         btrfs_set_inode_size(path->nodes[0], item, i_size);
2165                         btrfs_mark_buffer_dirty(path->nodes[0]);
2166                 } else
2167                         ret = 0;
2168                 btrfs_release_path(log, path);
2169         }
2170
2171         btrfs_free_path(path);
2172         mutex_unlock(&BTRFS_I(dir)->log_mutex);
2173         end_log_trans(root);
2174
2175         return 0;
2176 }
2177
2178 /* see comments for btrfs_del_dir_entries_in_log */
2179 int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
2180                                struct btrfs_root *root,
2181                                const char *name, int name_len,
2182                                struct inode *inode, u64 dirid)
2183 {
2184         struct btrfs_root *log;
2185         u64 index;
2186         int ret;
2187
2188         if (BTRFS_I(inode)->logged_trans < trans->transid)
2189                 return 0;
2190
2191         ret = join_running_log_trans(root);
2192         if (ret)
2193                 return 0;
2194         log = root->log_root;
2195         mutex_lock(&BTRFS_I(inode)->log_mutex);
2196
2197         ret = btrfs_del_inode_ref(trans, log, name, name_len, inode->i_ino,
2198                                   dirid, &index);
2199         mutex_unlock(&BTRFS_I(inode)->log_mutex);
2200         end_log_trans(root);
2201
2202         return ret;
2203 }
2204
2205 /*
2206  * creates a range item in the log for 'dirid'.  first_offset and
2207  * last_offset tell us which parts of the key space the log should
2208  * be considered authoritative for.
2209  */
2210 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
2211                                        struct btrfs_root *log,
2212                                        struct btrfs_path *path,
2213                                        int key_type, u64 dirid,
2214                                        u64 first_offset, u64 last_offset)
2215 {
2216         int ret;
2217         struct btrfs_key key;
2218         struct btrfs_dir_log_item *item;
2219
2220         key.objectid = dirid;
2221         key.offset = first_offset;
2222         if (key_type == BTRFS_DIR_ITEM_KEY)
2223                 key.type = BTRFS_DIR_LOG_ITEM_KEY;
2224         else
2225                 key.type = BTRFS_DIR_LOG_INDEX_KEY;
2226         ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
2227         BUG_ON(ret);
2228
2229         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2230                               struct btrfs_dir_log_item);
2231         btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
2232         btrfs_mark_buffer_dirty(path->nodes[0]);
2233         btrfs_release_path(log, path);
2234         return 0;
2235 }
2236
2237 /*
2238  * log all the items included in the current transaction for a given
2239  * directory.  This also creates the range items in the log tree required
2240  * to replay anything deleted before the fsync
2241  */
2242 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
2243                           struct btrfs_root *root, struct inode *inode,
2244                           struct btrfs_path *path,
2245                           struct btrfs_path *dst_path, int key_type,
2246                           u64 min_offset, u64 *last_offset_ret)
2247 {
2248         struct btrfs_key min_key;
2249         struct btrfs_key max_key;
2250         struct btrfs_root *log = root->log_root;
2251         struct extent_buffer *src;
2252         int ret;
2253         int i;
2254         int nritems;
2255         u64 first_offset = min_offset;
2256         u64 last_offset = (u64)-1;
2257
2258         log = root->log_root;
2259         max_key.objectid = inode->i_ino;
2260         max_key.offset = (u64)-1;
2261         max_key.type = key_type;
2262
2263         min_key.objectid = inode->i_ino;
2264         min_key.type = key_type;
2265         min_key.offset = min_offset;
2266
2267         path->keep_locks = 1;
2268
2269         ret = btrfs_search_forward(root, &min_key, &max_key,
2270                                    path, 0, trans->transid);
2271
2272         /*
2273          * we didn't find anything from this transaction, see if there
2274          * is anything at all
2275          */
2276         if (ret != 0 || min_key.objectid != inode->i_ino ||
2277             min_key.type != key_type) {
2278                 min_key.objectid = inode->i_ino;
2279                 min_key.type = key_type;
2280                 min_key.offset = (u64)-1;
2281                 btrfs_release_path(root, path);
2282                 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
2283                 if (ret < 0) {
2284                         btrfs_release_path(root, path);
2285                         return ret;
2286                 }
2287                 ret = btrfs_previous_item(root, path, inode->i_ino, key_type);
2288
2289                 /* if ret == 0 there are items for this type,
2290                  * create a range to tell us the last key of this type.
2291                  * otherwise, there are no items in this directory after
2292                  * *min_offset, and we create a range to indicate that.
2293                  */
2294                 if (ret == 0) {
2295                         struct btrfs_key tmp;
2296                         btrfs_item_key_to_cpu(path->nodes[0], &tmp,
2297                                               path->slots[0]);
2298                         if (key_type == tmp.type) {
2299                                 first_offset = max(min_offset, tmp.offset) + 1;
2300                         }
2301                 }
2302                 goto done;
2303         }
2304
2305         /* go backward to find any previous key */
2306         ret = btrfs_previous_item(root, path, inode->i_ino, key_type);
2307         if (ret == 0) {
2308                 struct btrfs_key tmp;
2309                 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
2310                 if (key_type == tmp.type) {
2311                         first_offset = tmp.offset;
2312                         ret = overwrite_item(trans, log, dst_path,
2313                                              path->nodes[0], path->slots[0],
2314                                              &tmp);
2315                 }
2316         }
2317         btrfs_release_path(root, path);
2318
2319         /* find the first key from this transaction again */
2320         ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
2321         if (ret != 0) {
2322                 WARN_ON(1);
2323                 goto done;
2324         }
2325
2326         /*
2327          * we have a block from this transaction, log every item in it
2328          * from our directory
2329          */
2330         while(1) {
2331                 struct btrfs_key tmp;
2332                 src = path->nodes[0];
2333                 nritems = btrfs_header_nritems(src);
2334                 for (i = path->slots[0]; i < nritems; i++) {
2335                         btrfs_item_key_to_cpu(src, &min_key, i);
2336
2337                         if (min_key.objectid != inode->i_ino ||
2338                             min_key.type != key_type)
2339                                 goto done;
2340                         ret = overwrite_item(trans, log, dst_path, src, i,
2341                                              &min_key);
2342                         BUG_ON(ret);
2343                 }
2344                 path->slots[0] = nritems;
2345
2346                 /*
2347                  * look ahead to the next item and see if it is also
2348                  * from this directory and from this transaction
2349                  */
2350                 ret = btrfs_next_leaf(root, path);
2351                 if (ret == 1) {
2352                         last_offset = (u64)-1;
2353                         goto done;
2354                 }
2355                 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
2356                 if (tmp.objectid != inode->i_ino || tmp.type != key_type) {
2357                         last_offset = (u64)-1;
2358                         goto done;
2359                 }
2360                 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
2361                         ret = overwrite_item(trans, log, dst_path,
2362                                              path->nodes[0], path->slots[0],
2363                                              &tmp);
2364
2365                         BUG_ON(ret);
2366                         last_offset = tmp.offset;
2367                         goto done;
2368                 }
2369         }
2370 done:
2371         *last_offset_ret = last_offset;
2372         btrfs_release_path(root, path);
2373         btrfs_release_path(log, dst_path);
2374
2375         /* insert the log range keys to indicate where the log is valid */
2376         ret = insert_dir_log_key(trans, log, path, key_type, inode->i_ino,
2377                                  first_offset, last_offset);
2378         BUG_ON(ret);
2379         return 0;
2380 }
2381
2382 /*
2383  * logging directories is very similar to logging inodes, We find all the items
2384  * from the current transaction and write them to the log.
2385  *
2386  * The recovery code scans the directory in the subvolume, and if it finds a
2387  * key in the range logged that is not present in the log tree, then it means
2388  * that dir entry was unlinked during the transaction.
2389  *
2390  * In order for that scan to work, we must include one key smaller than
2391  * the smallest logged by this transaction and one key larger than the largest
2392  * key logged by this transaction.
2393  */
2394 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
2395                           struct btrfs_root *root, struct inode *inode,
2396                           struct btrfs_path *path,
2397                           struct btrfs_path *dst_path)
2398 {
2399         u64 min_key;
2400         u64 max_key;
2401         int ret;
2402         int key_type = BTRFS_DIR_ITEM_KEY;
2403
2404 again:
2405         min_key = 0;
2406         max_key = 0;
2407         while(1) {
2408                 ret = log_dir_items(trans, root, inode, path,
2409                                     dst_path, key_type, min_key,
2410                                     &max_key);
2411                 BUG_ON(ret);
2412                 if (max_key == (u64)-1)
2413                         break;
2414                 min_key = max_key + 1;
2415         }
2416
2417         if (key_type == BTRFS_DIR_ITEM_KEY) {
2418                 key_type = BTRFS_DIR_INDEX_KEY;
2419                 goto again;
2420         }
2421         return 0;
2422 }
2423
2424 /*
2425  * a helper function to drop items from the log before we relog an
2426  * inode.  max_key_type indicates the highest item type to remove.
2427  * This cannot be run for file data extents because it does not
2428  * free the extents they point to.
2429  */
2430 static int drop_objectid_items(struct btrfs_trans_handle *trans,
2431                                   struct btrfs_root *log,
2432                                   struct btrfs_path *path,
2433                                   u64 objectid, int max_key_type)
2434 {
2435         int ret;
2436         struct btrfs_key key;
2437         struct btrfs_key found_key;
2438
2439         key.objectid = objectid;
2440         key.type = max_key_type;
2441         key.offset = (u64)-1;
2442
2443         while(1) {
2444                 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
2445
2446                 if (ret != 1)
2447                         break;
2448
2449                 if (path->slots[0] == 0)
2450                         break;
2451
2452                 path->slots[0]--;
2453                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2454                                       path->slots[0]);
2455
2456                 if (found_key.objectid != objectid)
2457                         break;
2458
2459                 ret = btrfs_del_item(trans, log, path);
2460                 BUG_ON(ret);
2461                 btrfs_release_path(log, path);
2462         }
2463         btrfs_release_path(log, path);
2464         return 0;
2465 }
2466
2467 static noinline int copy_items(struct btrfs_trans_handle *trans,
2468                                struct btrfs_root *log,
2469                                struct btrfs_path *dst_path,
2470                                struct extent_buffer *src,
2471                                int start_slot, int nr, int inode_only)
2472 {
2473         unsigned long src_offset;
2474         unsigned long dst_offset;
2475         struct btrfs_file_extent_item *extent;
2476         struct btrfs_inode_item *inode_item;
2477         int ret;
2478         struct btrfs_key *ins_keys;
2479         u32 *ins_sizes;
2480         char *ins_data;
2481         int i;
2482
2483         ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
2484                            nr * sizeof(u32), GFP_NOFS);
2485         ins_sizes = (u32 *)ins_data;
2486         ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
2487
2488         for (i = 0; i < nr; i++) {
2489                 ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
2490                 btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
2491         }
2492         ret = btrfs_insert_empty_items(trans, log, dst_path,
2493                                        ins_keys, ins_sizes, nr);
2494         BUG_ON(ret);
2495
2496         for (i = 0; i < nr; i++) {
2497                 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
2498                                                    dst_path->slots[0]);
2499
2500                 src_offset = btrfs_item_ptr_offset(src, start_slot + i);
2501
2502                 copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
2503                                    src_offset, ins_sizes[i]);
2504
2505                 if (inode_only == LOG_INODE_EXISTS &&
2506                     ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
2507                         inode_item = btrfs_item_ptr(dst_path->nodes[0],
2508                                                     dst_path->slots[0],
2509                                                     struct btrfs_inode_item);
2510                         btrfs_set_inode_size(dst_path->nodes[0], inode_item, 0);
2511
2512                         /* set the generation to zero so the recover code
2513                          * can tell the difference between an logging
2514                          * just to say 'this inode exists' and a logging
2515                          * to say 'update this inode with these values'
2516                          */
2517                         btrfs_set_inode_generation(dst_path->nodes[0],
2518                                                    inode_item, 0);
2519                 }
2520                 /* take a reference on file data extents so that truncates
2521                  * or deletes of this inode don't have to relog the inode
2522                  * again
2523                  */
2524                 if (btrfs_key_type(ins_keys + i) == BTRFS_EXTENT_DATA_KEY) {
2525                         int found_type;
2526                         extent = btrfs_item_ptr(src, start_slot + i,
2527                                                 struct btrfs_file_extent_item);
2528
2529                         found_type = btrfs_file_extent_type(src, extent);
2530                         if (found_type == BTRFS_FILE_EXTENT_REG ||
2531                             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
2532                                 u64 ds = btrfs_file_extent_disk_bytenr(src,
2533                                                                    extent);
2534                                 u64 dl = btrfs_file_extent_disk_num_bytes(src,
2535                                                                       extent);
2536                                 /* ds == 0 is a hole */
2537                                 if (ds != 0) {
2538                                         ret = btrfs_inc_extent_ref(trans, log,
2539                                                    ds, dl,
2540                                                    dst_path->nodes[0]->start,
2541                                                    BTRFS_TREE_LOG_OBJECTID,
2542                                                    trans->transid,
2543                                                    ins_keys[i].objectid);
2544                                         BUG_ON(ret);
2545                                 }
2546                         }
2547                 }
2548                 dst_path->slots[0]++;
2549         }
2550
2551         btrfs_mark_buffer_dirty(dst_path->nodes[0]);
2552         btrfs_release_path(log, dst_path);
2553         kfree(ins_data);
2554         return 0;
2555 }
2556
2557 /* log a single inode in the tree log.
2558  * At least one parent directory for this inode must exist in the tree
2559  * or be logged already.
2560  *
2561  * Any items from this inode changed by the current transaction are copied
2562  * to the log tree.  An extra reference is taken on any extents in this
2563  * file, allowing us to avoid a whole pile of corner cases around logging
2564  * blocks that have been removed from the tree.
2565  *
2566  * See LOG_INODE_ALL and related defines for a description of what inode_only
2567  * does.
2568  *
2569  * This handles both files and directories.
2570  */
2571 static int __btrfs_log_inode(struct btrfs_trans_handle *trans,
2572                              struct btrfs_root *root, struct inode *inode,
2573                              int inode_only)
2574 {
2575         struct btrfs_path *path;
2576         struct btrfs_path *dst_path;
2577         struct btrfs_key min_key;
2578         struct btrfs_key max_key;
2579         struct btrfs_root *log = root->log_root;
2580         struct extent_buffer *src = NULL;
2581         u32 size;
2582         int ret;
2583         int nritems;
2584         int ins_start_slot = 0;
2585         int ins_nr;
2586
2587         log = root->log_root;
2588
2589         path = btrfs_alloc_path();
2590         dst_path = btrfs_alloc_path();
2591
2592         min_key.objectid = inode->i_ino;
2593         min_key.type = BTRFS_INODE_ITEM_KEY;
2594         min_key.offset = 0;
2595
2596         max_key.objectid = inode->i_ino;
2597         if (inode_only == LOG_INODE_EXISTS || S_ISDIR(inode->i_mode))
2598                 max_key.type = BTRFS_XATTR_ITEM_KEY;
2599         else
2600                 max_key.type = (u8)-1;
2601         max_key.offset = (u64)-1;
2602
2603         /*
2604          * if this inode has already been logged and we're in inode_only
2605          * mode, we don't want to delete the things that have already
2606          * been written to the log.
2607          *
2608          * But, if the inode has been through an inode_only log,
2609          * the logged_trans field is not set.  This allows us to catch
2610          * any new names for this inode in the backrefs by logging it
2611          * again
2612          */
2613         if (inode_only == LOG_INODE_EXISTS &&
2614             BTRFS_I(inode)->logged_trans == trans->transid) {
2615                 btrfs_free_path(path);
2616                 btrfs_free_path(dst_path);
2617                 goto out;
2618         }
2619         mutex_lock(&BTRFS_I(inode)->log_mutex);
2620
2621         /*
2622          * a brute force approach to making sure we get the most uptodate
2623          * copies of everything.
2624          */
2625         if (S_ISDIR(inode->i_mode)) {
2626                 int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
2627
2628                 if (inode_only == LOG_INODE_EXISTS)
2629                         max_key_type = BTRFS_XATTR_ITEM_KEY;
2630                 ret = drop_objectid_items(trans, log, path,
2631                                           inode->i_ino, max_key_type);
2632         } else {
2633                 ret = btrfs_truncate_inode_items(trans, log, inode, 0, 0);
2634         }
2635         BUG_ON(ret);
2636         path->keep_locks = 1;
2637
2638         while(1) {
2639                 ins_nr = 0;
2640                 ret = btrfs_search_forward(root, &min_key, &max_key,
2641                                            path, 0, trans->transid);
2642                 if (ret != 0)
2643                         break;
2644 again:
2645                 /* note, ins_nr might be > 0 here, cleanup outside the loop */
2646                 if (min_key.objectid != inode->i_ino)
2647                         break;
2648                 if (min_key.type > max_key.type)
2649                         break;
2650
2651                 src = path->nodes[0];
2652                 size = btrfs_item_size_nr(src, path->slots[0]);
2653                 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
2654                         ins_nr++;
2655                         goto next_slot;
2656                 } else if (!ins_nr) {
2657                         ins_start_slot = path->slots[0];
2658                         ins_nr = 1;
2659                         goto next_slot;
2660                 }
2661
2662                 ret = copy_items(trans, log, dst_path, src, ins_start_slot,
2663                                  ins_nr, inode_only);
2664                 BUG_ON(ret);
2665                 ins_nr = 1;
2666                 ins_start_slot = path->slots[0];
2667 next_slot:
2668
2669                 nritems = btrfs_header_nritems(path->nodes[0]);
2670                 path->slots[0]++;
2671                 if (path->slots[0] < nritems) {
2672                         btrfs_item_key_to_cpu(path->nodes[0], &min_key,
2673                                               path->slots[0]);
2674                         goto again;
2675                 }
2676                 if (ins_nr) {
2677                         ret = copy_items(trans, log, dst_path, src,
2678                                          ins_start_slot,
2679                                          ins_nr, inode_only);
2680                         BUG_ON(ret);
2681                         ins_nr = 0;
2682                 }
2683                 btrfs_release_path(root, path);
2684
2685                 if (min_key.offset < (u64)-1)
2686                         min_key.offset++;
2687                 else if (min_key.type < (u8)-1)
2688                         min_key.type++;
2689                 else if (min_key.objectid < (u64)-1)
2690                         min_key.objectid++;
2691                 else
2692                         break;
2693         }
2694         if (ins_nr) {
2695                 ret = copy_items(trans, log, dst_path, src,
2696                                  ins_start_slot,
2697                                  ins_nr, inode_only);
2698                 BUG_ON(ret);
2699                 ins_nr = 0;
2700         }
2701         WARN_ON(ins_nr);
2702         if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->i_mode)) {
2703                 btrfs_release_path(root, path);
2704                 btrfs_release_path(log, dst_path);
2705                 BTRFS_I(inode)->log_dirty_trans = 0;
2706                 ret = log_directory_changes(trans, root, inode, path, dst_path);
2707                 BUG_ON(ret);
2708         }
2709         BTRFS_I(inode)->logged_trans = trans->transid;
2710         mutex_unlock(&BTRFS_I(inode)->log_mutex);
2711
2712         btrfs_free_path(path);
2713         btrfs_free_path(dst_path);
2714
2715         mutex_lock(&root->fs_info->tree_log_mutex);
2716         ret = update_log_root(trans, log);
2717         BUG_ON(ret);
2718         mutex_unlock(&root->fs_info->tree_log_mutex);
2719 out:
2720         return 0;
2721 }
2722
2723 int btrfs_log_inode(struct btrfs_trans_handle *trans,
2724                     struct btrfs_root *root, struct inode *inode,
2725                     int inode_only)
2726 {
2727         int ret;
2728
2729         start_log_trans(trans, root);
2730         ret = __btrfs_log_inode(trans, root, inode, inode_only);
2731         end_log_trans(root);
2732         return ret;
2733 }
2734
2735 /*
2736  * helper function around btrfs_log_inode to make sure newly created
2737  * parent directories also end up in the log.  A minimal inode and backref
2738  * only logging is done of any parent directories that are older than
2739  * the last committed transaction
2740  */
2741 int btrfs_log_dentry(struct btrfs_trans_handle *trans,
2742                     struct btrfs_root *root, struct dentry *dentry)
2743 {
2744         int inode_only = LOG_INODE_ALL;
2745         struct super_block *sb;
2746         int ret;
2747
2748         start_log_trans(trans, root);
2749         sb = dentry->d_inode->i_sb;
2750         while(1) {
2751                 ret = __btrfs_log_inode(trans, root, dentry->d_inode,
2752                                         inode_only);
2753                 BUG_ON(ret);
2754                 inode_only = LOG_INODE_EXISTS;
2755
2756                 dentry = dentry->d_parent;
2757                 if (!dentry || !dentry->d_inode || sb != dentry->d_inode->i_sb)
2758                         break;
2759
2760                 if (BTRFS_I(dentry->d_inode)->generation <=
2761                     root->fs_info->last_trans_committed)
2762                         break;
2763         }
2764         end_log_trans(root);
2765         return 0;
2766 }
2767
2768 /*
2769  * it is not safe to log dentry if the chunk root has added new
2770  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
2771  * If this returns 1, you must commit the transaction to safely get your
2772  * data on disk.
2773  */
2774 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
2775                           struct btrfs_root *root, struct dentry *dentry)
2776 {
2777         u64 gen;
2778         gen = root->fs_info->last_trans_new_blockgroup;
2779         if (gen > root->fs_info->last_trans_committed)
2780                 return 1;
2781         else
2782                 return btrfs_log_dentry(trans, root, dentry);
2783 }
2784
2785 /*
2786  * should be called during mount to recover any replay any log trees
2787  * from the FS
2788  */
2789 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
2790 {
2791         int ret;
2792         struct btrfs_path *path;
2793         struct btrfs_trans_handle *trans;
2794         struct btrfs_key key;
2795         struct btrfs_key found_key;
2796         struct btrfs_key tmp_key;
2797         struct btrfs_root *log;
2798         struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
2799         u64 highest_inode;
2800         struct walk_control wc = {
2801                 .process_func = process_one_buffer,
2802                 .stage = 0,
2803         };
2804
2805         fs_info->log_root_recovering = 1;
2806         path = btrfs_alloc_path();
2807         BUG_ON(!path);
2808
2809         trans = btrfs_start_transaction(fs_info->tree_root, 1);
2810
2811         wc.trans = trans;
2812         wc.pin = 1;
2813
2814         walk_log_tree(trans, log_root_tree, &wc);
2815
2816 again:
2817         key.objectid = BTRFS_TREE_LOG_OBJECTID;
2818         key.offset = (u64)-1;
2819         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
2820
2821         while(1) {
2822                 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
2823                 if (ret < 0)
2824                         break;
2825                 if (ret > 0) {
2826                         if (path->slots[0] == 0)
2827                                 break;
2828                         path->slots[0]--;
2829                 }
2830                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2831                                       path->slots[0]);
2832                 btrfs_release_path(log_root_tree, path);
2833                 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
2834                         break;
2835
2836                 log = btrfs_read_fs_root_no_radix(log_root_tree,
2837                                                   &found_key);
2838                 BUG_ON(!log);
2839
2840
2841                 tmp_key.objectid = found_key.offset;
2842                 tmp_key.type = BTRFS_ROOT_ITEM_KEY;
2843                 tmp_key.offset = (u64)-1;
2844
2845                 wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
2846
2847                 BUG_ON(!wc.replay_dest);
2848
2849                 btrfs_record_root_in_trans(wc.replay_dest);
2850                 ret = walk_log_tree(trans, log, &wc);
2851                 BUG_ON(ret);
2852
2853                 if (wc.stage == LOG_WALK_REPLAY_ALL) {
2854                         ret = fixup_inode_link_counts(trans, wc.replay_dest,
2855                                                       path);
2856                         BUG_ON(ret);
2857                 }
2858                 ret = btrfs_find_highest_inode(wc.replay_dest, &highest_inode);
2859                 if (ret == 0) {
2860                         wc.replay_dest->highest_inode = highest_inode;
2861                         wc.replay_dest->last_inode_alloc = highest_inode;
2862                 }
2863
2864                 key.offset = found_key.offset - 1;
2865                 free_extent_buffer(log->node);
2866                 kfree(log);
2867
2868                 if (found_key.offset == 0)
2869                         break;
2870         }
2871         btrfs_release_path(log_root_tree, path);
2872
2873         /* step one is to pin it all, step two is to replay just inodes */
2874         if (wc.pin) {
2875                 wc.pin = 0;
2876                 wc.process_func = replay_one_buffer;
2877                 wc.stage = LOG_WALK_REPLAY_INODES;
2878                 goto again;
2879         }
2880         /* step three is to replay everything */
2881         if (wc.stage < LOG_WALK_REPLAY_ALL) {
2882                 wc.stage++;
2883                 goto again;
2884         }
2885
2886         btrfs_free_path(path);
2887
2888         free_extent_buffer(log_root_tree->node);
2889         log_root_tree->log_root = NULL;
2890         fs_info->log_root_recovering = 0;
2891
2892         /* step 4: commit the transaction, which also unpins the blocks */
2893         btrfs_commit_transaction(trans, fs_info->tree_root);
2894
2895         kfree(log_root_tree);
2896         return 0;
2897 }