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