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