Btrfs: fix skipped error handle when log sync failed
[cascardo/linux.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 <linux/blkdev.h>
22 #include <linux/list_sort.h>
23 #include "ctree.h"
24 #include "transaction.h"
25 #include "disk-io.h"
26 #include "locking.h"
27 #include "print-tree.h"
28 #include "backref.h"
29 #include "tree-log.h"
30 #include "hash.h"
31
32 /* magic values for the inode_only field in btrfs_log_inode:
33  *
34  * LOG_INODE_ALL means to log everything
35  * LOG_INODE_EXISTS means to log just enough to recreate the inode
36  * during log replay
37  */
38 #define LOG_INODE_ALL 0
39 #define LOG_INODE_EXISTS 1
40
41 /*
42  * directory trouble cases
43  *
44  * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
45  * log, we must force a full commit before doing an fsync of the directory
46  * where the unlink was done.
47  * ---> record transid of last unlink/rename per directory
48  *
49  * mkdir foo/some_dir
50  * normal commit
51  * rename foo/some_dir foo2/some_dir
52  * mkdir foo/some_dir
53  * fsync foo/some_dir/some_file
54  *
55  * The fsync above will unlink the original some_dir without recording
56  * it in its new location (foo2).  After a crash, some_dir will be gone
57  * unless the fsync of some_file forces a full commit
58  *
59  * 2) we must log any new names for any file or dir that is in the fsync
60  * log. ---> check inode while renaming/linking.
61  *
62  * 2a) we must log any new names for any file or dir during rename
63  * when the directory they are being removed from was logged.
64  * ---> check inode and old parent dir during rename
65  *
66  *  2a is actually the more important variant.  With the extra logging
67  *  a crash might unlink the old name without recreating the new one
68  *
69  * 3) after a crash, we must go through any directories with a link count
70  * of zero and redo the rm -rf
71  *
72  * mkdir f1/foo
73  * normal commit
74  * rm -rf f1/foo
75  * fsync(f1)
76  *
77  * The directory f1 was fully removed from the FS, but fsync was never
78  * called on f1, only its parent dir.  After a crash the rm -rf must
79  * be replayed.  This must be able to recurse down the entire
80  * directory tree.  The inode link count fixup code takes care of the
81  * ugly details.
82  */
83
84 /*
85  * stages for the tree walking.  The first
86  * stage (0) is to only pin down the blocks we find
87  * the second stage (1) is to make sure that all the inodes
88  * we find in the log are created in the subvolume.
89  *
90  * The last stage is to deal with directories and links and extents
91  * and all the other fun semantics
92  */
93 #define LOG_WALK_PIN_ONLY 0
94 #define LOG_WALK_REPLAY_INODES 1
95 #define LOG_WALK_REPLAY_DIR_INDEX 2
96 #define LOG_WALK_REPLAY_ALL 3
97
98 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
99                              struct btrfs_root *root, struct inode *inode,
100                              int inode_only);
101 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
102                              struct btrfs_root *root,
103                              struct btrfs_path *path, u64 objectid);
104 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
105                                        struct btrfs_root *root,
106                                        struct btrfs_root *log,
107                                        struct btrfs_path *path,
108                                        u64 dirid, int del_all);
109
110 /*
111  * tree logging is a special write ahead log used to make sure that
112  * fsyncs and O_SYNCs can happen without doing full tree commits.
113  *
114  * Full tree commits are expensive because they require commonly
115  * modified blocks to be recowed, creating many dirty pages in the
116  * extent tree an 4x-6x higher write load than ext3.
117  *
118  * Instead of doing a tree commit on every fsync, we use the
119  * key ranges and transaction ids to find items for a given file or directory
120  * that have changed in this transaction.  Those items are copied into
121  * a special tree (one per subvolume root), that tree is written to disk
122  * and then the fsync is considered complete.
123  *
124  * After a crash, items are copied out of the log-tree back into the
125  * subvolume tree.  Any file data extents found are recorded in the extent
126  * allocation tree, and the log-tree freed.
127  *
128  * The log tree is read three times, once to pin down all the extents it is
129  * using in ram and once, once to create all the inodes logged in the tree
130  * and once to do all the other items.
131  */
132
133 /*
134  * start a sub transaction and setup the log tree
135  * this increments the log tree writer count to make the people
136  * syncing the tree wait for us to finish
137  */
138 static int start_log_trans(struct btrfs_trans_handle *trans,
139                            struct btrfs_root *root,
140                            struct btrfs_log_ctx *ctx)
141 {
142         int index;
143         int ret;
144
145         mutex_lock(&root->log_mutex);
146         if (root->log_root) {
147                 if (!root->log_start_pid) {
148                         root->log_start_pid = current->pid;
149                         root->log_multiple_pids = false;
150                 } else if (root->log_start_pid != current->pid) {
151                         root->log_multiple_pids = true;
152                 }
153
154                 atomic_inc(&root->log_batch);
155                 atomic_inc(&root->log_writers);
156                 if (ctx) {
157                         index = root->log_transid % 2;
158                         list_add_tail(&ctx->list, &root->log_ctxs[index]);
159                 }
160                 mutex_unlock(&root->log_mutex);
161                 return 0;
162         }
163
164         ret = 0;
165         mutex_lock(&root->fs_info->tree_log_mutex);
166         if (!root->fs_info->log_root_tree)
167                 ret = btrfs_init_log_root_tree(trans, root->fs_info);
168         mutex_unlock(&root->fs_info->tree_log_mutex);
169         if (ret)
170                 goto out;
171
172         if (!root->log_root) {
173                 ret = btrfs_add_log_tree(trans, root);
174                 if (ret)
175                         goto out;
176         }
177         root->log_multiple_pids = false;
178         root->log_start_pid = current->pid;
179         atomic_inc(&root->log_batch);
180         atomic_inc(&root->log_writers);
181         if (ctx) {
182                 index = root->log_transid % 2;
183                 list_add_tail(&ctx->list, &root->log_ctxs[index]);
184         }
185 out:
186         mutex_unlock(&root->log_mutex);
187         return ret;
188 }
189
190 /*
191  * returns 0 if there was a log transaction running and we were able
192  * to join, or returns -ENOENT if there were not transactions
193  * in progress
194  */
195 static int join_running_log_trans(struct btrfs_root *root)
196 {
197         int ret = -ENOENT;
198
199         smp_mb();
200         if (!root->log_root)
201                 return -ENOENT;
202
203         mutex_lock(&root->log_mutex);
204         if (root->log_root) {
205                 ret = 0;
206                 atomic_inc(&root->log_writers);
207         }
208         mutex_unlock(&root->log_mutex);
209         return ret;
210 }
211
212 /*
213  * This either makes the current running log transaction wait
214  * until you call btrfs_end_log_trans() or it makes any future
215  * log transactions wait until you call btrfs_end_log_trans()
216  */
217 int btrfs_pin_log_trans(struct btrfs_root *root)
218 {
219         int ret = -ENOENT;
220
221         mutex_lock(&root->log_mutex);
222         atomic_inc(&root->log_writers);
223         mutex_unlock(&root->log_mutex);
224         return ret;
225 }
226
227 /*
228  * indicate we're done making changes to the log tree
229  * and wake up anyone waiting to do a sync
230  */
231 void btrfs_end_log_trans(struct btrfs_root *root)
232 {
233         if (atomic_dec_and_test(&root->log_writers)) {
234                 smp_mb();
235                 if (waitqueue_active(&root->log_writer_wait))
236                         wake_up(&root->log_writer_wait);
237         }
238 }
239
240
241 /*
242  * the walk control struct is used to pass state down the chain when
243  * processing the log tree.  The stage field tells us which part
244  * of the log tree processing we are currently doing.  The others
245  * are state fields used for that specific part
246  */
247 struct walk_control {
248         /* should we free the extent on disk when done?  This is used
249          * at transaction commit time while freeing a log tree
250          */
251         int free;
252
253         /* should we write out the extent buffer?  This is used
254          * while flushing the log tree to disk during a sync
255          */
256         int write;
257
258         /* should we wait for the extent buffer io to finish?  Also used
259          * while flushing the log tree to disk for a sync
260          */
261         int wait;
262
263         /* pin only walk, we record which extents on disk belong to the
264          * log trees
265          */
266         int pin;
267
268         /* what stage of the replay code we're currently in */
269         int stage;
270
271         /* the root we are currently replaying */
272         struct btrfs_root *replay_dest;
273
274         /* the trans handle for the current replay */
275         struct btrfs_trans_handle *trans;
276
277         /* the function that gets used to process blocks we find in the
278          * tree.  Note the extent_buffer might not be up to date when it is
279          * passed in, and it must be checked or read if you need the data
280          * inside it
281          */
282         int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
283                             struct walk_control *wc, u64 gen);
284 };
285
286 /*
287  * process_func used to pin down extents, write them or wait on them
288  */
289 static int process_one_buffer(struct btrfs_root *log,
290                               struct extent_buffer *eb,
291                               struct walk_control *wc, u64 gen)
292 {
293         int ret = 0;
294
295         /*
296          * If this fs is mixed then we need to be able to process the leaves to
297          * pin down any logged extents, so we have to read the block.
298          */
299         if (btrfs_fs_incompat(log->fs_info, MIXED_GROUPS)) {
300                 ret = btrfs_read_buffer(eb, gen);
301                 if (ret)
302                         return ret;
303         }
304
305         if (wc->pin)
306                 ret = btrfs_pin_extent_for_log_replay(log->fs_info->extent_root,
307                                                       eb->start, eb->len);
308
309         if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
310                 if (wc->pin && btrfs_header_level(eb) == 0)
311                         ret = btrfs_exclude_logged_extents(log, eb);
312                 if (wc->write)
313                         btrfs_write_tree_block(eb);
314                 if (wc->wait)
315                         btrfs_wait_tree_block_writeback(eb);
316         }
317         return ret;
318 }
319
320 /*
321  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
322  * to the src data we are copying out.
323  *
324  * root is the tree we are copying into, and path is a scratch
325  * path for use in this function (it should be released on entry and
326  * will be released on exit).
327  *
328  * If the key is already in the destination tree the existing item is
329  * overwritten.  If the existing item isn't big enough, it is extended.
330  * If it is too large, it is truncated.
331  *
332  * If the key isn't in the destination yet, a new item is inserted.
333  */
334 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
335                                    struct btrfs_root *root,
336                                    struct btrfs_path *path,
337                                    struct extent_buffer *eb, int slot,
338                                    struct btrfs_key *key)
339 {
340         int ret;
341         u32 item_size;
342         u64 saved_i_size = 0;
343         int save_old_i_size = 0;
344         unsigned long src_ptr;
345         unsigned long dst_ptr;
346         int overwrite_root = 0;
347         bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
348
349         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
350                 overwrite_root = 1;
351
352         item_size = btrfs_item_size_nr(eb, slot);
353         src_ptr = btrfs_item_ptr_offset(eb, slot);
354
355         /* look for the key in the destination tree */
356         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
357         if (ret < 0)
358                 return ret;
359
360         if (ret == 0) {
361                 char *src_copy;
362                 char *dst_copy;
363                 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
364                                                   path->slots[0]);
365                 if (dst_size != item_size)
366                         goto insert;
367
368                 if (item_size == 0) {
369                         btrfs_release_path(path);
370                         return 0;
371                 }
372                 dst_copy = kmalloc(item_size, GFP_NOFS);
373                 src_copy = kmalloc(item_size, GFP_NOFS);
374                 if (!dst_copy || !src_copy) {
375                         btrfs_release_path(path);
376                         kfree(dst_copy);
377                         kfree(src_copy);
378                         return -ENOMEM;
379                 }
380
381                 read_extent_buffer(eb, src_copy, src_ptr, item_size);
382
383                 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
384                 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
385                                    item_size);
386                 ret = memcmp(dst_copy, src_copy, item_size);
387
388                 kfree(dst_copy);
389                 kfree(src_copy);
390                 /*
391                  * they have the same contents, just return, this saves
392                  * us from cowing blocks in the destination tree and doing
393                  * extra writes that may not have been done by a previous
394                  * sync
395                  */
396                 if (ret == 0) {
397                         btrfs_release_path(path);
398                         return 0;
399                 }
400
401                 /*
402                  * We need to load the old nbytes into the inode so when we
403                  * replay the extents we've logged we get the right nbytes.
404                  */
405                 if (inode_item) {
406                         struct btrfs_inode_item *item;
407                         u64 nbytes;
408                         u32 mode;
409
410                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
411                                               struct btrfs_inode_item);
412                         nbytes = btrfs_inode_nbytes(path->nodes[0], item);
413                         item = btrfs_item_ptr(eb, slot,
414                                               struct btrfs_inode_item);
415                         btrfs_set_inode_nbytes(eb, item, nbytes);
416
417                         /*
418                          * If this is a directory we need to reset the i_size to
419                          * 0 so that we can set it up properly when replaying
420                          * the rest of the items in this log.
421                          */
422                         mode = btrfs_inode_mode(eb, item);
423                         if (S_ISDIR(mode))
424                                 btrfs_set_inode_size(eb, item, 0);
425                 }
426         } else if (inode_item) {
427                 struct btrfs_inode_item *item;
428                 u32 mode;
429
430                 /*
431                  * New inode, set nbytes to 0 so that the nbytes comes out
432                  * properly when we replay the extents.
433                  */
434                 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
435                 btrfs_set_inode_nbytes(eb, item, 0);
436
437                 /*
438                  * If this is a directory we need to reset the i_size to 0 so
439                  * that we can set it up properly when replaying the rest of
440                  * the items in this log.
441                  */
442                 mode = btrfs_inode_mode(eb, item);
443                 if (S_ISDIR(mode))
444                         btrfs_set_inode_size(eb, item, 0);
445         }
446 insert:
447         btrfs_release_path(path);
448         /* try to insert the key into the destination tree */
449         ret = btrfs_insert_empty_item(trans, root, path,
450                                       key, item_size);
451
452         /* make sure any existing item is the correct size */
453         if (ret == -EEXIST) {
454                 u32 found_size;
455                 found_size = btrfs_item_size_nr(path->nodes[0],
456                                                 path->slots[0]);
457                 if (found_size > item_size)
458                         btrfs_truncate_item(root, path, item_size, 1);
459                 else if (found_size < item_size)
460                         btrfs_extend_item(root, path,
461                                           item_size - found_size);
462         } else if (ret) {
463                 return ret;
464         }
465         dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
466                                         path->slots[0]);
467
468         /* don't overwrite an existing inode if the generation number
469          * was logged as zero.  This is done when the tree logging code
470          * is just logging an inode to make sure it exists after recovery.
471          *
472          * Also, don't overwrite i_size on directories during replay.
473          * log replay inserts and removes directory items based on the
474          * state of the tree found in the subvolume, and i_size is modified
475          * as it goes
476          */
477         if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
478                 struct btrfs_inode_item *src_item;
479                 struct btrfs_inode_item *dst_item;
480
481                 src_item = (struct btrfs_inode_item *)src_ptr;
482                 dst_item = (struct btrfs_inode_item *)dst_ptr;
483
484                 if (btrfs_inode_generation(eb, src_item) == 0)
485                         goto no_copy;
486
487                 if (overwrite_root &&
488                     S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
489                     S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
490                         save_old_i_size = 1;
491                         saved_i_size = btrfs_inode_size(path->nodes[0],
492                                                         dst_item);
493                 }
494         }
495
496         copy_extent_buffer(path->nodes[0], eb, dst_ptr,
497                            src_ptr, item_size);
498
499         if (save_old_i_size) {
500                 struct btrfs_inode_item *dst_item;
501                 dst_item = (struct btrfs_inode_item *)dst_ptr;
502                 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
503         }
504
505         /* make sure the generation is filled in */
506         if (key->type == BTRFS_INODE_ITEM_KEY) {
507                 struct btrfs_inode_item *dst_item;
508                 dst_item = (struct btrfs_inode_item *)dst_ptr;
509                 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
510                         btrfs_set_inode_generation(path->nodes[0], dst_item,
511                                                    trans->transid);
512                 }
513         }
514 no_copy:
515         btrfs_mark_buffer_dirty(path->nodes[0]);
516         btrfs_release_path(path);
517         return 0;
518 }
519
520 /*
521  * simple helper to read an inode off the disk from a given root
522  * This can only be called for subvolume roots and not for the log
523  */
524 static noinline struct inode *read_one_inode(struct btrfs_root *root,
525                                              u64 objectid)
526 {
527         struct btrfs_key key;
528         struct inode *inode;
529
530         key.objectid = objectid;
531         key.type = BTRFS_INODE_ITEM_KEY;
532         key.offset = 0;
533         inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
534         if (IS_ERR(inode)) {
535                 inode = NULL;
536         } else if (is_bad_inode(inode)) {
537                 iput(inode);
538                 inode = NULL;
539         }
540         return inode;
541 }
542
543 /* replays a single extent in 'eb' at 'slot' with 'key' into the
544  * subvolume 'root'.  path is released on entry and should be released
545  * on exit.
546  *
547  * extents in the log tree have not been allocated out of the extent
548  * tree yet.  So, this completes the allocation, taking a reference
549  * as required if the extent already exists or creating a new extent
550  * if it isn't in the extent allocation tree yet.
551  *
552  * The extent is inserted into the file, dropping any existing extents
553  * from the file that overlap the new one.
554  */
555 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
556                                       struct btrfs_root *root,
557                                       struct btrfs_path *path,
558                                       struct extent_buffer *eb, int slot,
559                                       struct btrfs_key *key)
560 {
561         int found_type;
562         u64 extent_end;
563         u64 start = key->offset;
564         u64 nbytes = 0;
565         struct btrfs_file_extent_item *item;
566         struct inode *inode = NULL;
567         unsigned long size;
568         int ret = 0;
569
570         item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
571         found_type = btrfs_file_extent_type(eb, item);
572
573         if (found_type == BTRFS_FILE_EXTENT_REG ||
574             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
575                 nbytes = btrfs_file_extent_num_bytes(eb, item);
576                 extent_end = start + nbytes;
577
578                 /*
579                  * We don't add to the inodes nbytes if we are prealloc or a
580                  * hole.
581                  */
582                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
583                         nbytes = 0;
584         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
585                 size = btrfs_file_extent_inline_len(eb, slot, item);
586                 nbytes = btrfs_file_extent_ram_bytes(eb, item);
587                 extent_end = ALIGN(start + size, root->sectorsize);
588         } else {
589                 ret = 0;
590                 goto out;
591         }
592
593         inode = read_one_inode(root, key->objectid);
594         if (!inode) {
595                 ret = -EIO;
596                 goto out;
597         }
598
599         /*
600          * first check to see if we already have this extent in the
601          * file.  This must be done before the btrfs_drop_extents run
602          * so we don't try to drop this extent.
603          */
604         ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
605                                        start, 0);
606
607         if (ret == 0 &&
608             (found_type == BTRFS_FILE_EXTENT_REG ||
609              found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
610                 struct btrfs_file_extent_item cmp1;
611                 struct btrfs_file_extent_item cmp2;
612                 struct btrfs_file_extent_item *existing;
613                 struct extent_buffer *leaf;
614
615                 leaf = path->nodes[0];
616                 existing = btrfs_item_ptr(leaf, path->slots[0],
617                                           struct btrfs_file_extent_item);
618
619                 read_extent_buffer(eb, &cmp1, (unsigned long)item,
620                                    sizeof(cmp1));
621                 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
622                                    sizeof(cmp2));
623
624                 /*
625                  * we already have a pointer to this exact extent,
626                  * we don't have to do anything
627                  */
628                 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
629                         btrfs_release_path(path);
630                         goto out;
631                 }
632         }
633         btrfs_release_path(path);
634
635         /* drop any overlapping extents */
636         ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
637         if (ret)
638                 goto out;
639
640         if (found_type == BTRFS_FILE_EXTENT_REG ||
641             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
642                 u64 offset;
643                 unsigned long dest_offset;
644                 struct btrfs_key ins;
645
646                 ret = btrfs_insert_empty_item(trans, root, path, key,
647                                               sizeof(*item));
648                 if (ret)
649                         goto out;
650                 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
651                                                     path->slots[0]);
652                 copy_extent_buffer(path->nodes[0], eb, dest_offset,
653                                 (unsigned long)item,  sizeof(*item));
654
655                 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
656                 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
657                 ins.type = BTRFS_EXTENT_ITEM_KEY;
658                 offset = key->offset - btrfs_file_extent_offset(eb, item);
659
660                 if (ins.objectid > 0) {
661                         u64 csum_start;
662                         u64 csum_end;
663                         LIST_HEAD(ordered_sums);
664                         /*
665                          * is this extent already allocated in the extent
666                          * allocation tree?  If so, just add a reference
667                          */
668                         ret = btrfs_lookup_extent(root, ins.objectid,
669                                                 ins.offset);
670                         if (ret == 0) {
671                                 ret = btrfs_inc_extent_ref(trans, root,
672                                                 ins.objectid, ins.offset,
673                                                 0, root->root_key.objectid,
674                                                 key->objectid, offset, 0);
675                                 if (ret)
676                                         goto out;
677                         } else {
678                                 /*
679                                  * insert the extent pointer in the extent
680                                  * allocation tree
681                                  */
682                                 ret = btrfs_alloc_logged_file_extent(trans,
683                                                 root, root->root_key.objectid,
684                                                 key->objectid, offset, &ins);
685                                 if (ret)
686                                         goto out;
687                         }
688                         btrfs_release_path(path);
689
690                         if (btrfs_file_extent_compression(eb, item)) {
691                                 csum_start = ins.objectid;
692                                 csum_end = csum_start + ins.offset;
693                         } else {
694                                 csum_start = ins.objectid +
695                                         btrfs_file_extent_offset(eb, item);
696                                 csum_end = csum_start +
697                                         btrfs_file_extent_num_bytes(eb, item);
698                         }
699
700                         ret = btrfs_lookup_csums_range(root->log_root,
701                                                 csum_start, csum_end - 1,
702                                                 &ordered_sums, 0);
703                         if (ret)
704                                 goto out;
705                         while (!list_empty(&ordered_sums)) {
706                                 struct btrfs_ordered_sum *sums;
707                                 sums = list_entry(ordered_sums.next,
708                                                 struct btrfs_ordered_sum,
709                                                 list);
710                                 if (!ret)
711                                         ret = btrfs_csum_file_blocks(trans,
712                                                 root->fs_info->csum_root,
713                                                 sums);
714                                 list_del(&sums->list);
715                                 kfree(sums);
716                         }
717                         if (ret)
718                                 goto out;
719                 } else {
720                         btrfs_release_path(path);
721                 }
722         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
723                 /* inline extents are easy, we just overwrite them */
724                 ret = overwrite_item(trans, root, path, eb, slot, key);
725                 if (ret)
726                         goto out;
727         }
728
729         inode_add_bytes(inode, nbytes);
730         ret = btrfs_update_inode(trans, root, inode);
731 out:
732         if (inode)
733                 iput(inode);
734         return ret;
735 }
736
737 /*
738  * when cleaning up conflicts between the directory names in the
739  * subvolume, directory names in the log and directory names in the
740  * inode back references, we may have to unlink inodes from directories.
741  *
742  * This is a helper function to do the unlink of a specific directory
743  * item
744  */
745 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
746                                       struct btrfs_root *root,
747                                       struct btrfs_path *path,
748                                       struct inode *dir,
749                                       struct btrfs_dir_item *di)
750 {
751         struct inode *inode;
752         char *name;
753         int name_len;
754         struct extent_buffer *leaf;
755         struct btrfs_key location;
756         int ret;
757
758         leaf = path->nodes[0];
759
760         btrfs_dir_item_key_to_cpu(leaf, di, &location);
761         name_len = btrfs_dir_name_len(leaf, di);
762         name = kmalloc(name_len, GFP_NOFS);
763         if (!name)
764                 return -ENOMEM;
765
766         read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
767         btrfs_release_path(path);
768
769         inode = read_one_inode(root, location.objectid);
770         if (!inode) {
771                 ret = -EIO;
772                 goto out;
773         }
774
775         ret = link_to_fixup_dir(trans, root, path, location.objectid);
776         if (ret)
777                 goto out;
778
779         ret = btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
780         if (ret)
781                 goto out;
782         else
783                 ret = btrfs_run_delayed_items(trans, root);
784 out:
785         kfree(name);
786         iput(inode);
787         return ret;
788 }
789
790 /*
791  * helper function to see if a given name and sequence number found
792  * in an inode back reference are already in a directory and correctly
793  * point to this inode
794  */
795 static noinline int inode_in_dir(struct btrfs_root *root,
796                                  struct btrfs_path *path,
797                                  u64 dirid, u64 objectid, u64 index,
798                                  const char *name, int name_len)
799 {
800         struct btrfs_dir_item *di;
801         struct btrfs_key location;
802         int match = 0;
803
804         di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
805                                          index, name, name_len, 0);
806         if (di && !IS_ERR(di)) {
807                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
808                 if (location.objectid != objectid)
809                         goto out;
810         } else
811                 goto out;
812         btrfs_release_path(path);
813
814         di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
815         if (di && !IS_ERR(di)) {
816                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
817                 if (location.objectid != objectid)
818                         goto out;
819         } else
820                 goto out;
821         match = 1;
822 out:
823         btrfs_release_path(path);
824         return match;
825 }
826
827 /*
828  * helper function to check a log tree for a named back reference in
829  * an inode.  This is used to decide if a back reference that is
830  * found in the subvolume conflicts with what we find in the log.
831  *
832  * inode backreferences may have multiple refs in a single item,
833  * during replay we process one reference at a time, and we don't
834  * want to delete valid links to a file from the subvolume if that
835  * link is also in the log.
836  */
837 static noinline int backref_in_log(struct btrfs_root *log,
838                                    struct btrfs_key *key,
839                                    u64 ref_objectid,
840                                    char *name, int namelen)
841 {
842         struct btrfs_path *path;
843         struct btrfs_inode_ref *ref;
844         unsigned long ptr;
845         unsigned long ptr_end;
846         unsigned long name_ptr;
847         int found_name_len;
848         int item_size;
849         int ret;
850         int match = 0;
851
852         path = btrfs_alloc_path();
853         if (!path)
854                 return -ENOMEM;
855
856         ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
857         if (ret != 0)
858                 goto out;
859
860         ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
861
862         if (key->type == BTRFS_INODE_EXTREF_KEY) {
863                 if (btrfs_find_name_in_ext_backref(path, ref_objectid,
864                                                    name, namelen, NULL))
865                         match = 1;
866
867                 goto out;
868         }
869
870         item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
871         ptr_end = ptr + item_size;
872         while (ptr < ptr_end) {
873                 ref = (struct btrfs_inode_ref *)ptr;
874                 found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
875                 if (found_name_len == namelen) {
876                         name_ptr = (unsigned long)(ref + 1);
877                         ret = memcmp_extent_buffer(path->nodes[0], name,
878                                                    name_ptr, namelen);
879                         if (ret == 0) {
880                                 match = 1;
881                                 goto out;
882                         }
883                 }
884                 ptr = (unsigned long)(ref + 1) + found_name_len;
885         }
886 out:
887         btrfs_free_path(path);
888         return match;
889 }
890
891 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
892                                   struct btrfs_root *root,
893                                   struct btrfs_path *path,
894                                   struct btrfs_root *log_root,
895                                   struct inode *dir, struct inode *inode,
896                                   struct extent_buffer *eb,
897                                   u64 inode_objectid, u64 parent_objectid,
898                                   u64 ref_index, char *name, int namelen,
899                                   int *search_done)
900 {
901         int ret;
902         char *victim_name;
903         int victim_name_len;
904         struct extent_buffer *leaf;
905         struct btrfs_dir_item *di;
906         struct btrfs_key search_key;
907         struct btrfs_inode_extref *extref;
908
909 again:
910         /* Search old style refs */
911         search_key.objectid = inode_objectid;
912         search_key.type = BTRFS_INODE_REF_KEY;
913         search_key.offset = parent_objectid;
914         ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
915         if (ret == 0) {
916                 struct btrfs_inode_ref *victim_ref;
917                 unsigned long ptr;
918                 unsigned long ptr_end;
919
920                 leaf = path->nodes[0];
921
922                 /* are we trying to overwrite a back ref for the root directory
923                  * if so, just jump out, we're done
924                  */
925                 if (search_key.objectid == search_key.offset)
926                         return 1;
927
928                 /* check all the names in this back reference to see
929                  * if they are in the log.  if so, we allow them to stay
930                  * otherwise they must be unlinked as a conflict
931                  */
932                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
933                 ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
934                 while (ptr < ptr_end) {
935                         victim_ref = (struct btrfs_inode_ref *)ptr;
936                         victim_name_len = btrfs_inode_ref_name_len(leaf,
937                                                                    victim_ref);
938                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
939                         if (!victim_name)
940                                 return -ENOMEM;
941
942                         read_extent_buffer(leaf, victim_name,
943                                            (unsigned long)(victim_ref + 1),
944                                            victim_name_len);
945
946                         if (!backref_in_log(log_root, &search_key,
947                                             parent_objectid,
948                                             victim_name,
949                                             victim_name_len)) {
950                                 inc_nlink(inode);
951                                 btrfs_release_path(path);
952
953                                 ret = btrfs_unlink_inode(trans, root, dir,
954                                                          inode, victim_name,
955                                                          victim_name_len);
956                                 kfree(victim_name);
957                                 if (ret)
958                                         return ret;
959                                 ret = btrfs_run_delayed_items(trans, root);
960                                 if (ret)
961                                         return ret;
962                                 *search_done = 1;
963                                 goto again;
964                         }
965                         kfree(victim_name);
966
967                         ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
968                 }
969
970                 /*
971                  * NOTE: we have searched root tree and checked the
972                  * coresponding ref, it does not need to check again.
973                  */
974                 *search_done = 1;
975         }
976         btrfs_release_path(path);
977
978         /* Same search but for extended refs */
979         extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
980                                            inode_objectid, parent_objectid, 0,
981                                            0);
982         if (!IS_ERR_OR_NULL(extref)) {
983                 u32 item_size;
984                 u32 cur_offset = 0;
985                 unsigned long base;
986                 struct inode *victim_parent;
987
988                 leaf = path->nodes[0];
989
990                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
991                 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
992
993                 while (cur_offset < item_size) {
994                         extref = (struct btrfs_inode_extref *)base + cur_offset;
995
996                         victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
997
998                         if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
999                                 goto next;
1000
1001                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
1002                         if (!victim_name)
1003                                 return -ENOMEM;
1004                         read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1005                                            victim_name_len);
1006
1007                         search_key.objectid = inode_objectid;
1008                         search_key.type = BTRFS_INODE_EXTREF_KEY;
1009                         search_key.offset = btrfs_extref_hash(parent_objectid,
1010                                                               victim_name,
1011                                                               victim_name_len);
1012                         ret = 0;
1013                         if (!backref_in_log(log_root, &search_key,
1014                                             parent_objectid, victim_name,
1015                                             victim_name_len)) {
1016                                 ret = -ENOENT;
1017                                 victim_parent = read_one_inode(root,
1018                                                                parent_objectid);
1019                                 if (victim_parent) {
1020                                         inc_nlink(inode);
1021                                         btrfs_release_path(path);
1022
1023                                         ret = btrfs_unlink_inode(trans, root,
1024                                                                  victim_parent,
1025                                                                  inode,
1026                                                                  victim_name,
1027                                                                  victim_name_len);
1028                                         if (!ret)
1029                                                 ret = btrfs_run_delayed_items(
1030                                                                   trans, root);
1031                                 }
1032                                 iput(victim_parent);
1033                                 kfree(victim_name);
1034                                 if (ret)
1035                                         return ret;
1036                                 *search_done = 1;
1037                                 goto again;
1038                         }
1039                         kfree(victim_name);
1040                         if (ret)
1041                                 return ret;
1042 next:
1043                         cur_offset += victim_name_len + sizeof(*extref);
1044                 }
1045                 *search_done = 1;
1046         }
1047         btrfs_release_path(path);
1048
1049         /* look for a conflicting sequence number */
1050         di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1051                                          ref_index, name, namelen, 0);
1052         if (di && !IS_ERR(di)) {
1053                 ret = drop_one_dir_item(trans, root, path, dir, di);
1054                 if (ret)
1055                         return ret;
1056         }
1057         btrfs_release_path(path);
1058
1059         /* look for a conflicing name */
1060         di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
1061                                    name, namelen, 0);
1062         if (di && !IS_ERR(di)) {
1063                 ret = drop_one_dir_item(trans, root, path, dir, di);
1064                 if (ret)
1065                         return ret;
1066         }
1067         btrfs_release_path(path);
1068
1069         return 0;
1070 }
1071
1072 static int extref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1073                              u32 *namelen, char **name, u64 *index,
1074                              u64 *parent_objectid)
1075 {
1076         struct btrfs_inode_extref *extref;
1077
1078         extref = (struct btrfs_inode_extref *)ref_ptr;
1079
1080         *namelen = btrfs_inode_extref_name_len(eb, extref);
1081         *name = kmalloc(*namelen, GFP_NOFS);
1082         if (*name == NULL)
1083                 return -ENOMEM;
1084
1085         read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1086                            *namelen);
1087
1088         *index = btrfs_inode_extref_index(eb, extref);
1089         if (parent_objectid)
1090                 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1091
1092         return 0;
1093 }
1094
1095 static int ref_get_fields(struct extent_buffer *eb, unsigned long ref_ptr,
1096                           u32 *namelen, char **name, u64 *index)
1097 {
1098         struct btrfs_inode_ref *ref;
1099
1100         ref = (struct btrfs_inode_ref *)ref_ptr;
1101
1102         *namelen = btrfs_inode_ref_name_len(eb, ref);
1103         *name = kmalloc(*namelen, GFP_NOFS);
1104         if (*name == NULL)
1105                 return -ENOMEM;
1106
1107         read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1108
1109         *index = btrfs_inode_ref_index(eb, ref);
1110
1111         return 0;
1112 }
1113
1114 /*
1115  * replay one inode back reference item found in the log tree.
1116  * eb, slot and key refer to the buffer and key found in the log tree.
1117  * root is the destination we are replaying into, and path is for temp
1118  * use by this function.  (it should be released on return).
1119  */
1120 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1121                                   struct btrfs_root *root,
1122                                   struct btrfs_root *log,
1123                                   struct btrfs_path *path,
1124                                   struct extent_buffer *eb, int slot,
1125                                   struct btrfs_key *key)
1126 {
1127         struct inode *dir = NULL;
1128         struct inode *inode = NULL;
1129         unsigned long ref_ptr;
1130         unsigned long ref_end;
1131         char *name = NULL;
1132         int namelen;
1133         int ret;
1134         int search_done = 0;
1135         int log_ref_ver = 0;
1136         u64 parent_objectid;
1137         u64 inode_objectid;
1138         u64 ref_index = 0;
1139         int ref_struct_size;
1140
1141         ref_ptr = btrfs_item_ptr_offset(eb, slot);
1142         ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1143
1144         if (key->type == BTRFS_INODE_EXTREF_KEY) {
1145                 struct btrfs_inode_extref *r;
1146
1147                 ref_struct_size = sizeof(struct btrfs_inode_extref);
1148                 log_ref_ver = 1;
1149                 r = (struct btrfs_inode_extref *)ref_ptr;
1150                 parent_objectid = btrfs_inode_extref_parent(eb, r);
1151         } else {
1152                 ref_struct_size = sizeof(struct btrfs_inode_ref);
1153                 parent_objectid = key->offset;
1154         }
1155         inode_objectid = key->objectid;
1156
1157         /*
1158          * it is possible that we didn't log all the parent directories
1159          * for a given inode.  If we don't find the dir, just don't
1160          * copy the back ref in.  The link count fixup code will take
1161          * care of the rest
1162          */
1163         dir = read_one_inode(root, parent_objectid);
1164         if (!dir) {
1165                 ret = -ENOENT;
1166                 goto out;
1167         }
1168
1169         inode = read_one_inode(root, inode_objectid);
1170         if (!inode) {
1171                 ret = -EIO;
1172                 goto out;
1173         }
1174
1175         while (ref_ptr < ref_end) {
1176                 if (log_ref_ver) {
1177                         ret = extref_get_fields(eb, ref_ptr, &namelen, &name,
1178                                                 &ref_index, &parent_objectid);
1179                         /*
1180                          * parent object can change from one array
1181                          * item to another.
1182                          */
1183                         if (!dir)
1184                                 dir = read_one_inode(root, parent_objectid);
1185                         if (!dir) {
1186                                 ret = -ENOENT;
1187                                 goto out;
1188                         }
1189                 } else {
1190                         ret = ref_get_fields(eb, ref_ptr, &namelen, &name,
1191                                              &ref_index);
1192                 }
1193                 if (ret)
1194                         goto out;
1195
1196                 /* if we already have a perfect match, we're done */
1197                 if (!inode_in_dir(root, path, btrfs_ino(dir), btrfs_ino(inode),
1198                                   ref_index, name, namelen)) {
1199                         /*
1200                          * look for a conflicting back reference in the
1201                          * metadata. if we find one we have to unlink that name
1202                          * of the file before we add our new link.  Later on, we
1203                          * overwrite any existing back reference, and we don't
1204                          * want to create dangling pointers in the directory.
1205                          */
1206
1207                         if (!search_done) {
1208                                 ret = __add_inode_ref(trans, root, path, log,
1209                                                       dir, inode, eb,
1210                                                       inode_objectid,
1211                                                       parent_objectid,
1212                                                       ref_index, name, namelen,
1213                                                       &search_done);
1214                                 if (ret) {
1215                                         if (ret == 1)
1216                                                 ret = 0;
1217                                         goto out;
1218                                 }
1219                         }
1220
1221                         /* insert our name */
1222                         ret = btrfs_add_link(trans, dir, inode, name, namelen,
1223                                              0, ref_index);
1224                         if (ret)
1225                                 goto out;
1226
1227                         btrfs_update_inode(trans, root, inode);
1228                 }
1229
1230                 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1231                 kfree(name);
1232                 name = NULL;
1233                 if (log_ref_ver) {
1234                         iput(dir);
1235                         dir = NULL;
1236                 }
1237         }
1238
1239         /* finally write the back reference in the inode */
1240         ret = overwrite_item(trans, root, path, eb, slot, key);
1241 out:
1242         btrfs_release_path(path);
1243         kfree(name);
1244         iput(dir);
1245         iput(inode);
1246         return ret;
1247 }
1248
1249 static int insert_orphan_item(struct btrfs_trans_handle *trans,
1250                               struct btrfs_root *root, u64 offset)
1251 {
1252         int ret;
1253         ret = btrfs_find_item(root, NULL, BTRFS_ORPHAN_OBJECTID,
1254                         offset, BTRFS_ORPHAN_ITEM_KEY, NULL);
1255         if (ret > 0)
1256                 ret = btrfs_insert_orphan_item(trans, root, offset);
1257         return ret;
1258 }
1259
1260 static int count_inode_extrefs(struct btrfs_root *root,
1261                                struct inode *inode, struct btrfs_path *path)
1262 {
1263         int ret = 0;
1264         int name_len;
1265         unsigned int nlink = 0;
1266         u32 item_size;
1267         u32 cur_offset = 0;
1268         u64 inode_objectid = btrfs_ino(inode);
1269         u64 offset = 0;
1270         unsigned long ptr;
1271         struct btrfs_inode_extref *extref;
1272         struct extent_buffer *leaf;
1273
1274         while (1) {
1275                 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1276                                             &extref, &offset);
1277                 if (ret)
1278                         break;
1279
1280                 leaf = path->nodes[0];
1281                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1282                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1283
1284                 while (cur_offset < item_size) {
1285                         extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1286                         name_len = btrfs_inode_extref_name_len(leaf, extref);
1287
1288                         nlink++;
1289
1290                         cur_offset += name_len + sizeof(*extref);
1291                 }
1292
1293                 offset++;
1294                 btrfs_release_path(path);
1295         }
1296         btrfs_release_path(path);
1297
1298         if (ret < 0)
1299                 return ret;
1300         return nlink;
1301 }
1302
1303 static int count_inode_refs(struct btrfs_root *root,
1304                                struct inode *inode, struct btrfs_path *path)
1305 {
1306         int ret;
1307         struct btrfs_key key;
1308         unsigned int nlink = 0;
1309         unsigned long ptr;
1310         unsigned long ptr_end;
1311         int name_len;
1312         u64 ino = btrfs_ino(inode);
1313
1314         key.objectid = ino;
1315         key.type = BTRFS_INODE_REF_KEY;
1316         key.offset = (u64)-1;
1317
1318         while (1) {
1319                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1320                 if (ret < 0)
1321                         break;
1322                 if (ret > 0) {
1323                         if (path->slots[0] == 0)
1324                                 break;
1325                         path->slots[0]--;
1326                 }
1327 process_slot:
1328                 btrfs_item_key_to_cpu(path->nodes[0], &key,
1329                                       path->slots[0]);
1330                 if (key.objectid != ino ||
1331                     key.type != BTRFS_INODE_REF_KEY)
1332                         break;
1333                 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1334                 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1335                                                    path->slots[0]);
1336                 while (ptr < ptr_end) {
1337                         struct btrfs_inode_ref *ref;
1338
1339                         ref = (struct btrfs_inode_ref *)ptr;
1340                         name_len = btrfs_inode_ref_name_len(path->nodes[0],
1341                                                             ref);
1342                         ptr = (unsigned long)(ref + 1) + name_len;
1343                         nlink++;
1344                 }
1345
1346                 if (key.offset == 0)
1347                         break;
1348                 if (path->slots[0] > 0) {
1349                         path->slots[0]--;
1350                         goto process_slot;
1351                 }
1352                 key.offset--;
1353                 btrfs_release_path(path);
1354         }
1355         btrfs_release_path(path);
1356
1357         return nlink;
1358 }
1359
1360 /*
1361  * There are a few corners where the link count of the file can't
1362  * be properly maintained during replay.  So, instead of adding
1363  * lots of complexity to the log code, we just scan the backrefs
1364  * for any file that has been through replay.
1365  *
1366  * The scan will update the link count on the inode to reflect the
1367  * number of back refs found.  If it goes down to zero, the iput
1368  * will free the inode.
1369  */
1370 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1371                                            struct btrfs_root *root,
1372                                            struct inode *inode)
1373 {
1374         struct btrfs_path *path;
1375         int ret;
1376         u64 nlink = 0;
1377         u64 ino = btrfs_ino(inode);
1378
1379         path = btrfs_alloc_path();
1380         if (!path)
1381                 return -ENOMEM;
1382
1383         ret = count_inode_refs(root, inode, path);
1384         if (ret < 0)
1385                 goto out;
1386
1387         nlink = ret;
1388
1389         ret = count_inode_extrefs(root, inode, path);
1390         if (ret == -ENOENT)
1391                 ret = 0;
1392
1393         if (ret < 0)
1394                 goto out;
1395
1396         nlink += ret;
1397
1398         ret = 0;
1399
1400         if (nlink != inode->i_nlink) {
1401                 set_nlink(inode, nlink);
1402                 btrfs_update_inode(trans, root, inode);
1403         }
1404         BTRFS_I(inode)->index_cnt = (u64)-1;
1405
1406         if (inode->i_nlink == 0) {
1407                 if (S_ISDIR(inode->i_mode)) {
1408                         ret = replay_dir_deletes(trans, root, NULL, path,
1409                                                  ino, 1);
1410                         if (ret)
1411                                 goto out;
1412                 }
1413                 ret = insert_orphan_item(trans, root, ino);
1414         }
1415
1416 out:
1417         btrfs_free_path(path);
1418         return ret;
1419 }
1420
1421 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1422                                             struct btrfs_root *root,
1423                                             struct btrfs_path *path)
1424 {
1425         int ret;
1426         struct btrfs_key key;
1427         struct inode *inode;
1428
1429         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1430         key.type = BTRFS_ORPHAN_ITEM_KEY;
1431         key.offset = (u64)-1;
1432         while (1) {
1433                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1434                 if (ret < 0)
1435                         break;
1436
1437                 if (ret == 1) {
1438                         if (path->slots[0] == 0)
1439                                 break;
1440                         path->slots[0]--;
1441                 }
1442
1443                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1444                 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1445                     key.type != BTRFS_ORPHAN_ITEM_KEY)
1446                         break;
1447
1448                 ret = btrfs_del_item(trans, root, path);
1449                 if (ret)
1450                         goto out;
1451
1452                 btrfs_release_path(path);
1453                 inode = read_one_inode(root, key.offset);
1454                 if (!inode)
1455                         return -EIO;
1456
1457                 ret = fixup_inode_link_count(trans, root, inode);
1458                 iput(inode);
1459                 if (ret)
1460                         goto out;
1461
1462                 /*
1463                  * fixup on a directory may create new entries,
1464                  * make sure we always look for the highset possible
1465                  * offset
1466                  */
1467                 key.offset = (u64)-1;
1468         }
1469         ret = 0;
1470 out:
1471         btrfs_release_path(path);
1472         return ret;
1473 }
1474
1475
1476 /*
1477  * record a given inode in the fixup dir so we can check its link
1478  * count when replay is done.  The link count is incremented here
1479  * so the inode won't go away until we check it
1480  */
1481 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1482                                       struct btrfs_root *root,
1483                                       struct btrfs_path *path,
1484                                       u64 objectid)
1485 {
1486         struct btrfs_key key;
1487         int ret = 0;
1488         struct inode *inode;
1489
1490         inode = read_one_inode(root, objectid);
1491         if (!inode)
1492                 return -EIO;
1493
1494         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1495         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
1496         key.offset = objectid;
1497
1498         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1499
1500         btrfs_release_path(path);
1501         if (ret == 0) {
1502                 if (!inode->i_nlink)
1503                         set_nlink(inode, 1);
1504                 else
1505                         inc_nlink(inode);
1506                 ret = btrfs_update_inode(trans, root, inode);
1507         } else if (ret == -EEXIST) {
1508                 ret = 0;
1509         } else {
1510                 BUG(); /* Logic Error */
1511         }
1512         iput(inode);
1513
1514         return ret;
1515 }
1516
1517 /*
1518  * when replaying the log for a directory, we only insert names
1519  * for inodes that actually exist.  This means an fsync on a directory
1520  * does not implicitly fsync all the new files in it
1521  */
1522 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1523                                     struct btrfs_root *root,
1524                                     struct btrfs_path *path,
1525                                     u64 dirid, u64 index,
1526                                     char *name, int name_len, u8 type,
1527                                     struct btrfs_key *location)
1528 {
1529         struct inode *inode;
1530         struct inode *dir;
1531         int ret;
1532
1533         inode = read_one_inode(root, location->objectid);
1534         if (!inode)
1535                 return -ENOENT;
1536
1537         dir = read_one_inode(root, dirid);
1538         if (!dir) {
1539                 iput(inode);
1540                 return -EIO;
1541         }
1542
1543         ret = btrfs_add_link(trans, dir, inode, name, name_len, 1, index);
1544
1545         /* FIXME, put inode into FIXUP list */
1546
1547         iput(inode);
1548         iput(dir);
1549         return ret;
1550 }
1551
1552 /*
1553  * take a single entry in a log directory item and replay it into
1554  * the subvolume.
1555  *
1556  * if a conflicting item exists in the subdirectory already,
1557  * the inode it points to is unlinked and put into the link count
1558  * fix up tree.
1559  *
1560  * If a name from the log points to a file or directory that does
1561  * not exist in the FS, it is skipped.  fsyncs on directories
1562  * do not force down inodes inside that directory, just changes to the
1563  * names or unlinks in a directory.
1564  */
1565 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1566                                     struct btrfs_root *root,
1567                                     struct btrfs_path *path,
1568                                     struct extent_buffer *eb,
1569                                     struct btrfs_dir_item *di,
1570                                     struct btrfs_key *key)
1571 {
1572         char *name;
1573         int name_len;
1574         struct btrfs_dir_item *dst_di;
1575         struct btrfs_key found_key;
1576         struct btrfs_key log_key;
1577         struct inode *dir;
1578         u8 log_type;
1579         int exists;
1580         int ret = 0;
1581         bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
1582
1583         dir = read_one_inode(root, key->objectid);
1584         if (!dir)
1585                 return -EIO;
1586
1587         name_len = btrfs_dir_name_len(eb, di);
1588         name = kmalloc(name_len, GFP_NOFS);
1589         if (!name) {
1590                 ret = -ENOMEM;
1591                 goto out;
1592         }
1593
1594         log_type = btrfs_dir_type(eb, di);
1595         read_extent_buffer(eb, name, (unsigned long)(di + 1),
1596                    name_len);
1597
1598         btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1599         exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1600         if (exists == 0)
1601                 exists = 1;
1602         else
1603                 exists = 0;
1604         btrfs_release_path(path);
1605
1606         if (key->type == BTRFS_DIR_ITEM_KEY) {
1607                 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1608                                        name, name_len, 1);
1609         } else if (key->type == BTRFS_DIR_INDEX_KEY) {
1610                 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1611                                                      key->objectid,
1612                                                      key->offset, name,
1613                                                      name_len, 1);
1614         } else {
1615                 /* Corruption */
1616                 ret = -EINVAL;
1617                 goto out;
1618         }
1619         if (IS_ERR_OR_NULL(dst_di)) {
1620                 /* we need a sequence number to insert, so we only
1621                  * do inserts for the BTRFS_DIR_INDEX_KEY types
1622                  */
1623                 if (key->type != BTRFS_DIR_INDEX_KEY)
1624                         goto out;
1625                 goto insert;
1626         }
1627
1628         btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1629         /* the existing item matches the logged item */
1630         if (found_key.objectid == log_key.objectid &&
1631             found_key.type == log_key.type &&
1632             found_key.offset == log_key.offset &&
1633             btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
1634                 goto out;
1635         }
1636
1637         /*
1638          * don't drop the conflicting directory entry if the inode
1639          * for the new entry doesn't exist
1640          */
1641         if (!exists)
1642                 goto out;
1643
1644         ret = drop_one_dir_item(trans, root, path, dir, dst_di);
1645         if (ret)
1646                 goto out;
1647
1648         if (key->type == BTRFS_DIR_INDEX_KEY)
1649                 goto insert;
1650 out:
1651         btrfs_release_path(path);
1652         if (!ret && update_size) {
1653                 btrfs_i_size_write(dir, dir->i_size + name_len * 2);
1654                 ret = btrfs_update_inode(trans, root, dir);
1655         }
1656         kfree(name);
1657         iput(dir);
1658         return ret;
1659
1660 insert:
1661         btrfs_release_path(path);
1662         ret = insert_one_name(trans, root, path, key->objectid, key->offset,
1663                               name, name_len, log_type, &log_key);
1664         if (ret && ret != -ENOENT)
1665                 goto out;
1666         update_size = false;
1667         ret = 0;
1668         goto out;
1669 }
1670
1671 /*
1672  * find all the names in a directory item and reconcile them into
1673  * the subvolume.  Only BTRFS_DIR_ITEM_KEY types will have more than
1674  * one name in a directory item, but the same code gets used for
1675  * both directory index types
1676  */
1677 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1678                                         struct btrfs_root *root,
1679                                         struct btrfs_path *path,
1680                                         struct extent_buffer *eb, int slot,
1681                                         struct btrfs_key *key)
1682 {
1683         int ret;
1684         u32 item_size = btrfs_item_size_nr(eb, slot);
1685         struct btrfs_dir_item *di;
1686         int name_len;
1687         unsigned long ptr;
1688         unsigned long ptr_end;
1689
1690         ptr = btrfs_item_ptr_offset(eb, slot);
1691         ptr_end = ptr + item_size;
1692         while (ptr < ptr_end) {
1693                 di = (struct btrfs_dir_item *)ptr;
1694                 if (verify_dir_item(root, eb, di))
1695                         return -EIO;
1696                 name_len = btrfs_dir_name_len(eb, di);
1697                 ret = replay_one_name(trans, root, path, eb, di, key);
1698                 if (ret)
1699                         return ret;
1700                 ptr = (unsigned long)(di + 1);
1701                 ptr += name_len;
1702         }
1703         return 0;
1704 }
1705
1706 /*
1707  * directory replay has two parts.  There are the standard directory
1708  * items in the log copied from the subvolume, and range items
1709  * created in the log while the subvolume was logged.
1710  *
1711  * The range items tell us which parts of the key space the log
1712  * is authoritative for.  During replay, if a key in the subvolume
1713  * directory is in a logged range item, but not actually in the log
1714  * that means it was deleted from the directory before the fsync
1715  * and should be removed.
1716  */
1717 static noinline int find_dir_range(struct btrfs_root *root,
1718                                    struct btrfs_path *path,
1719                                    u64 dirid, int key_type,
1720                                    u64 *start_ret, u64 *end_ret)
1721 {
1722         struct btrfs_key key;
1723         u64 found_end;
1724         struct btrfs_dir_log_item *item;
1725         int ret;
1726         int nritems;
1727
1728         if (*start_ret == (u64)-1)
1729                 return 1;
1730
1731         key.objectid = dirid;
1732         key.type = key_type;
1733         key.offset = *start_ret;
1734
1735         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1736         if (ret < 0)
1737                 goto out;
1738         if (ret > 0) {
1739                 if (path->slots[0] == 0)
1740                         goto out;
1741                 path->slots[0]--;
1742         }
1743         if (ret != 0)
1744                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1745
1746         if (key.type != key_type || key.objectid != dirid) {
1747                 ret = 1;
1748                 goto next;
1749         }
1750         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1751                               struct btrfs_dir_log_item);
1752         found_end = btrfs_dir_log_end(path->nodes[0], item);
1753
1754         if (*start_ret >= key.offset && *start_ret <= found_end) {
1755                 ret = 0;
1756                 *start_ret = key.offset;
1757                 *end_ret = found_end;
1758                 goto out;
1759         }
1760         ret = 1;
1761 next:
1762         /* check the next slot in the tree to see if it is a valid item */
1763         nritems = btrfs_header_nritems(path->nodes[0]);
1764         if (path->slots[0] >= nritems) {
1765                 ret = btrfs_next_leaf(root, path);
1766                 if (ret)
1767                         goto out;
1768         } else {
1769                 path->slots[0]++;
1770         }
1771
1772         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1773
1774         if (key.type != key_type || key.objectid != dirid) {
1775                 ret = 1;
1776                 goto out;
1777         }
1778         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1779                               struct btrfs_dir_log_item);
1780         found_end = btrfs_dir_log_end(path->nodes[0], item);
1781         *start_ret = key.offset;
1782         *end_ret = found_end;
1783         ret = 0;
1784 out:
1785         btrfs_release_path(path);
1786         return ret;
1787 }
1788
1789 /*
1790  * this looks for a given directory item in the log.  If the directory
1791  * item is not in the log, the item is removed and the inode it points
1792  * to is unlinked
1793  */
1794 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
1795                                       struct btrfs_root *root,
1796                                       struct btrfs_root *log,
1797                                       struct btrfs_path *path,
1798                                       struct btrfs_path *log_path,
1799                                       struct inode *dir,
1800                                       struct btrfs_key *dir_key)
1801 {
1802         int ret;
1803         struct extent_buffer *eb;
1804         int slot;
1805         u32 item_size;
1806         struct btrfs_dir_item *di;
1807         struct btrfs_dir_item *log_di;
1808         int name_len;
1809         unsigned long ptr;
1810         unsigned long ptr_end;
1811         char *name;
1812         struct inode *inode;
1813         struct btrfs_key location;
1814
1815 again:
1816         eb = path->nodes[0];
1817         slot = path->slots[0];
1818         item_size = btrfs_item_size_nr(eb, slot);
1819         ptr = btrfs_item_ptr_offset(eb, slot);
1820         ptr_end = ptr + item_size;
1821         while (ptr < ptr_end) {
1822                 di = (struct btrfs_dir_item *)ptr;
1823                 if (verify_dir_item(root, eb, di)) {
1824                         ret = -EIO;
1825                         goto out;
1826                 }
1827
1828                 name_len = btrfs_dir_name_len(eb, di);
1829                 name = kmalloc(name_len, GFP_NOFS);
1830                 if (!name) {
1831                         ret = -ENOMEM;
1832                         goto out;
1833                 }
1834                 read_extent_buffer(eb, name, (unsigned long)(di + 1),
1835                                   name_len);
1836                 log_di = NULL;
1837                 if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
1838                         log_di = btrfs_lookup_dir_item(trans, log, log_path,
1839                                                        dir_key->objectid,
1840                                                        name, name_len, 0);
1841                 } else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
1842                         log_di = btrfs_lookup_dir_index_item(trans, log,
1843                                                      log_path,
1844                                                      dir_key->objectid,
1845                                                      dir_key->offset,
1846                                                      name, name_len, 0);
1847                 }
1848                 if (!log_di || (IS_ERR(log_di) && PTR_ERR(log_di) == -ENOENT)) {
1849                         btrfs_dir_item_key_to_cpu(eb, di, &location);
1850                         btrfs_release_path(path);
1851                         btrfs_release_path(log_path);
1852                         inode = read_one_inode(root, location.objectid);
1853                         if (!inode) {
1854                                 kfree(name);
1855                                 return -EIO;
1856                         }
1857
1858                         ret = link_to_fixup_dir(trans, root,
1859                                                 path, location.objectid);
1860                         if (ret) {
1861                                 kfree(name);
1862                                 iput(inode);
1863                                 goto out;
1864                         }
1865
1866                         inc_nlink(inode);
1867                         ret = btrfs_unlink_inode(trans, root, dir, inode,
1868                                                  name, name_len);
1869                         if (!ret)
1870                                 ret = btrfs_run_delayed_items(trans, root);
1871                         kfree(name);
1872                         iput(inode);
1873                         if (ret)
1874                                 goto out;
1875
1876                         /* there might still be more names under this key
1877                          * check and repeat if required
1878                          */
1879                         ret = btrfs_search_slot(NULL, root, dir_key, path,
1880                                                 0, 0);
1881                         if (ret == 0)
1882                                 goto again;
1883                         ret = 0;
1884                         goto out;
1885                 } else if (IS_ERR(log_di)) {
1886                         kfree(name);
1887                         return PTR_ERR(log_di);
1888                 }
1889                 btrfs_release_path(log_path);
1890                 kfree(name);
1891
1892                 ptr = (unsigned long)(di + 1);
1893                 ptr += name_len;
1894         }
1895         ret = 0;
1896 out:
1897         btrfs_release_path(path);
1898         btrfs_release_path(log_path);
1899         return ret;
1900 }
1901
1902 /*
1903  * deletion replay happens before we copy any new directory items
1904  * out of the log or out of backreferences from inodes.  It
1905  * scans the log to find ranges of keys that log is authoritative for,
1906  * and then scans the directory to find items in those ranges that are
1907  * not present in the log.
1908  *
1909  * Anything we don't find in the log is unlinked and removed from the
1910  * directory.
1911  */
1912 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
1913                                        struct btrfs_root *root,
1914                                        struct btrfs_root *log,
1915                                        struct btrfs_path *path,
1916                                        u64 dirid, int del_all)
1917 {
1918         u64 range_start;
1919         u64 range_end;
1920         int key_type = BTRFS_DIR_LOG_ITEM_KEY;
1921         int ret = 0;
1922         struct btrfs_key dir_key;
1923         struct btrfs_key found_key;
1924         struct btrfs_path *log_path;
1925         struct inode *dir;
1926
1927         dir_key.objectid = dirid;
1928         dir_key.type = BTRFS_DIR_ITEM_KEY;
1929         log_path = btrfs_alloc_path();
1930         if (!log_path)
1931                 return -ENOMEM;
1932
1933         dir = read_one_inode(root, dirid);
1934         /* it isn't an error if the inode isn't there, that can happen
1935          * because we replay the deletes before we copy in the inode item
1936          * from the log
1937          */
1938         if (!dir) {
1939                 btrfs_free_path(log_path);
1940                 return 0;
1941         }
1942 again:
1943         range_start = 0;
1944         range_end = 0;
1945         while (1) {
1946                 if (del_all)
1947                         range_end = (u64)-1;
1948                 else {
1949                         ret = find_dir_range(log, path, dirid, key_type,
1950                                              &range_start, &range_end);
1951                         if (ret != 0)
1952                                 break;
1953                 }
1954
1955                 dir_key.offset = range_start;
1956                 while (1) {
1957                         int nritems;
1958                         ret = btrfs_search_slot(NULL, root, &dir_key, path,
1959                                                 0, 0);
1960                         if (ret < 0)
1961                                 goto out;
1962
1963                         nritems = btrfs_header_nritems(path->nodes[0]);
1964                         if (path->slots[0] >= nritems) {
1965                                 ret = btrfs_next_leaf(root, path);
1966                                 if (ret)
1967                                         break;
1968                         }
1969                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1970                                               path->slots[0]);
1971                         if (found_key.objectid != dirid ||
1972                             found_key.type != dir_key.type)
1973                                 goto next_type;
1974
1975                         if (found_key.offset > range_end)
1976                                 break;
1977
1978                         ret = check_item_in_log(trans, root, log, path,
1979                                                 log_path, dir,
1980                                                 &found_key);
1981                         if (ret)
1982                                 goto out;
1983                         if (found_key.offset == (u64)-1)
1984                                 break;
1985                         dir_key.offset = found_key.offset + 1;
1986                 }
1987                 btrfs_release_path(path);
1988                 if (range_end == (u64)-1)
1989                         break;
1990                 range_start = range_end + 1;
1991         }
1992
1993 next_type:
1994         ret = 0;
1995         if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
1996                 key_type = BTRFS_DIR_LOG_INDEX_KEY;
1997                 dir_key.type = BTRFS_DIR_INDEX_KEY;
1998                 btrfs_release_path(path);
1999                 goto again;
2000         }
2001 out:
2002         btrfs_release_path(path);
2003         btrfs_free_path(log_path);
2004         iput(dir);
2005         return ret;
2006 }
2007
2008 /*
2009  * the process_func used to replay items from the log tree.  This
2010  * gets called in two different stages.  The first stage just looks
2011  * for inodes and makes sure they are all copied into the subvolume.
2012  *
2013  * The second stage copies all the other item types from the log into
2014  * the subvolume.  The two stage approach is slower, but gets rid of
2015  * lots of complexity around inodes referencing other inodes that exist
2016  * only in the log (references come from either directory items or inode
2017  * back refs).
2018  */
2019 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2020                              struct walk_control *wc, u64 gen)
2021 {
2022         int nritems;
2023         struct btrfs_path *path;
2024         struct btrfs_root *root = wc->replay_dest;
2025         struct btrfs_key key;
2026         int level;
2027         int i;
2028         int ret;
2029
2030         ret = btrfs_read_buffer(eb, gen);
2031         if (ret)
2032                 return ret;
2033
2034         level = btrfs_header_level(eb);
2035
2036         if (level != 0)
2037                 return 0;
2038
2039         path = btrfs_alloc_path();
2040         if (!path)
2041                 return -ENOMEM;
2042
2043         nritems = btrfs_header_nritems(eb);
2044         for (i = 0; i < nritems; i++) {
2045                 btrfs_item_key_to_cpu(eb, &key, i);
2046
2047                 /* inode keys are done during the first stage */
2048                 if (key.type == BTRFS_INODE_ITEM_KEY &&
2049                     wc->stage == LOG_WALK_REPLAY_INODES) {
2050                         struct btrfs_inode_item *inode_item;
2051                         u32 mode;
2052
2053                         inode_item = btrfs_item_ptr(eb, i,
2054                                             struct btrfs_inode_item);
2055                         mode = btrfs_inode_mode(eb, inode_item);
2056                         if (S_ISDIR(mode)) {
2057                                 ret = replay_dir_deletes(wc->trans,
2058                                          root, log, path, key.objectid, 0);
2059                                 if (ret)
2060                                         break;
2061                         }
2062                         ret = overwrite_item(wc->trans, root, path,
2063                                              eb, i, &key);
2064                         if (ret)
2065                                 break;
2066
2067                         /* for regular files, make sure corresponding
2068                          * orhpan item exist. extents past the new EOF
2069                          * will be truncated later by orphan cleanup.
2070                          */
2071                         if (S_ISREG(mode)) {
2072                                 ret = insert_orphan_item(wc->trans, root,
2073                                                          key.objectid);
2074                                 if (ret)
2075                                         break;
2076                         }
2077
2078                         ret = link_to_fixup_dir(wc->trans, root,
2079                                                 path, key.objectid);
2080                         if (ret)
2081                                 break;
2082                 }
2083
2084                 if (key.type == BTRFS_DIR_INDEX_KEY &&
2085                     wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2086                         ret = replay_one_dir_item(wc->trans, root, path,
2087                                                   eb, i, &key);
2088                         if (ret)
2089                                 break;
2090                 }
2091
2092                 if (wc->stage < LOG_WALK_REPLAY_ALL)
2093                         continue;
2094
2095                 /* these keys are simply copied */
2096                 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2097                         ret = overwrite_item(wc->trans, root, path,
2098                                              eb, i, &key);
2099                         if (ret)
2100                                 break;
2101                 } else if (key.type == BTRFS_INODE_REF_KEY ||
2102                            key.type == BTRFS_INODE_EXTREF_KEY) {
2103                         ret = add_inode_ref(wc->trans, root, log, path,
2104                                             eb, i, &key);
2105                         if (ret && ret != -ENOENT)
2106                                 break;
2107                         ret = 0;
2108                 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2109                         ret = replay_one_extent(wc->trans, root, path,
2110                                                 eb, i, &key);
2111                         if (ret)
2112                                 break;
2113                 } else if (key.type == BTRFS_DIR_ITEM_KEY) {
2114                         ret = replay_one_dir_item(wc->trans, root, path,
2115                                                   eb, i, &key);
2116                         if (ret)
2117                                 break;
2118                 }
2119         }
2120         btrfs_free_path(path);
2121         return ret;
2122 }
2123
2124 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2125                                    struct btrfs_root *root,
2126                                    struct btrfs_path *path, int *level,
2127                                    struct walk_control *wc)
2128 {
2129         u64 root_owner;
2130         u64 bytenr;
2131         u64 ptr_gen;
2132         struct extent_buffer *next;
2133         struct extent_buffer *cur;
2134         struct extent_buffer *parent;
2135         u32 blocksize;
2136         int ret = 0;
2137
2138         WARN_ON(*level < 0);
2139         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2140
2141         while (*level > 0) {
2142                 WARN_ON(*level < 0);
2143                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2144                 cur = path->nodes[*level];
2145
2146                 WARN_ON(btrfs_header_level(cur) != *level);
2147
2148                 if (path->slots[*level] >=
2149                     btrfs_header_nritems(cur))
2150                         break;
2151
2152                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2153                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2154                 blocksize = btrfs_level_size(root, *level - 1);
2155
2156                 parent = path->nodes[*level];
2157                 root_owner = btrfs_header_owner(parent);
2158
2159                 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
2160                 if (!next)
2161                         return -ENOMEM;
2162
2163                 if (*level == 1) {
2164                         ret = wc->process_func(root, next, wc, ptr_gen);
2165                         if (ret) {
2166                                 free_extent_buffer(next);
2167                                 return ret;
2168                         }
2169
2170                         path->slots[*level]++;
2171                         if (wc->free) {
2172                                 ret = btrfs_read_buffer(next, ptr_gen);
2173                                 if (ret) {
2174                                         free_extent_buffer(next);
2175                                         return ret;
2176                                 }
2177
2178                                 if (trans) {
2179                                         btrfs_tree_lock(next);
2180                                         btrfs_set_lock_blocking(next);
2181                                         clean_tree_block(trans, root, next);
2182                                         btrfs_wait_tree_block_writeback(next);
2183                                         btrfs_tree_unlock(next);
2184                                 }
2185
2186                                 WARN_ON(root_owner !=
2187                                         BTRFS_TREE_LOG_OBJECTID);
2188                                 ret = btrfs_free_and_pin_reserved_extent(root,
2189                                                          bytenr, blocksize);
2190                                 if (ret) {
2191                                         free_extent_buffer(next);
2192                                         return ret;
2193                                 }
2194                         }
2195                         free_extent_buffer(next);
2196                         continue;
2197                 }
2198                 ret = btrfs_read_buffer(next, ptr_gen);
2199                 if (ret) {
2200                         free_extent_buffer(next);
2201                         return ret;
2202                 }
2203
2204                 WARN_ON(*level <= 0);
2205                 if (path->nodes[*level-1])
2206                         free_extent_buffer(path->nodes[*level-1]);
2207                 path->nodes[*level-1] = next;
2208                 *level = btrfs_header_level(next);
2209                 path->slots[*level] = 0;
2210                 cond_resched();
2211         }
2212         WARN_ON(*level < 0);
2213         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2214
2215         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2216
2217         cond_resched();
2218         return 0;
2219 }
2220
2221 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2222                                  struct btrfs_root *root,
2223                                  struct btrfs_path *path, int *level,
2224                                  struct walk_control *wc)
2225 {
2226         u64 root_owner;
2227         int i;
2228         int slot;
2229         int ret;
2230
2231         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2232                 slot = path->slots[i];
2233                 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2234                         path->slots[i]++;
2235                         *level = i;
2236                         WARN_ON(*level == 0);
2237                         return 0;
2238                 } else {
2239                         struct extent_buffer *parent;
2240                         if (path->nodes[*level] == root->node)
2241                                 parent = path->nodes[*level];
2242                         else
2243                                 parent = path->nodes[*level + 1];
2244
2245                         root_owner = btrfs_header_owner(parent);
2246                         ret = wc->process_func(root, path->nodes[*level], wc,
2247                                  btrfs_header_generation(path->nodes[*level]));
2248                         if (ret)
2249                                 return ret;
2250
2251                         if (wc->free) {
2252                                 struct extent_buffer *next;
2253
2254                                 next = path->nodes[*level];
2255
2256                                 if (trans) {
2257                                         btrfs_tree_lock(next);
2258                                         btrfs_set_lock_blocking(next);
2259                                         clean_tree_block(trans, root, next);
2260                                         btrfs_wait_tree_block_writeback(next);
2261                                         btrfs_tree_unlock(next);
2262                                 }
2263
2264                                 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2265                                 ret = btrfs_free_and_pin_reserved_extent(root,
2266                                                 path->nodes[*level]->start,
2267                                                 path->nodes[*level]->len);
2268                                 if (ret)
2269                                         return ret;
2270                         }
2271                         free_extent_buffer(path->nodes[*level]);
2272                         path->nodes[*level] = NULL;
2273                         *level = i + 1;
2274                 }
2275         }
2276         return 1;
2277 }
2278
2279 /*
2280  * drop the reference count on the tree rooted at 'snap'.  This traverses
2281  * the tree freeing any blocks that have a ref count of zero after being
2282  * decremented.
2283  */
2284 static int walk_log_tree(struct btrfs_trans_handle *trans,
2285                          struct btrfs_root *log, struct walk_control *wc)
2286 {
2287         int ret = 0;
2288         int wret;
2289         int level;
2290         struct btrfs_path *path;
2291         int orig_level;
2292
2293         path = btrfs_alloc_path();
2294         if (!path)
2295                 return -ENOMEM;
2296
2297         level = btrfs_header_level(log->node);
2298         orig_level = level;
2299         path->nodes[level] = log->node;
2300         extent_buffer_get(log->node);
2301         path->slots[level] = 0;
2302
2303         while (1) {
2304                 wret = walk_down_log_tree(trans, log, path, &level, wc);
2305                 if (wret > 0)
2306                         break;
2307                 if (wret < 0) {
2308                         ret = wret;
2309                         goto out;
2310                 }
2311
2312                 wret = walk_up_log_tree(trans, log, path, &level, wc);
2313                 if (wret > 0)
2314                         break;
2315                 if (wret < 0) {
2316                         ret = wret;
2317                         goto out;
2318                 }
2319         }
2320
2321         /* was the root node processed? if not, catch it here */
2322         if (path->nodes[orig_level]) {
2323                 ret = wc->process_func(log, path->nodes[orig_level], wc,
2324                          btrfs_header_generation(path->nodes[orig_level]));
2325                 if (ret)
2326                         goto out;
2327                 if (wc->free) {
2328                         struct extent_buffer *next;
2329
2330                         next = path->nodes[orig_level];
2331
2332                         if (trans) {
2333                                 btrfs_tree_lock(next);
2334                                 btrfs_set_lock_blocking(next);
2335                                 clean_tree_block(trans, log, next);
2336                                 btrfs_wait_tree_block_writeback(next);
2337                                 btrfs_tree_unlock(next);
2338                         }
2339
2340                         WARN_ON(log->root_key.objectid !=
2341                                 BTRFS_TREE_LOG_OBJECTID);
2342                         ret = btrfs_free_and_pin_reserved_extent(log, next->start,
2343                                                          next->len);
2344                         if (ret)
2345                                 goto out;
2346                 }
2347         }
2348
2349 out:
2350         btrfs_free_path(path);
2351         return ret;
2352 }
2353
2354 /*
2355  * helper function to update the item for a given subvolumes log root
2356  * in the tree of log roots
2357  */
2358 static int update_log_root(struct btrfs_trans_handle *trans,
2359                            struct btrfs_root *log)
2360 {
2361         int ret;
2362
2363         if (log->log_transid == 1) {
2364                 /* insert root item on the first sync */
2365                 ret = btrfs_insert_root(trans, log->fs_info->log_root_tree,
2366                                 &log->root_key, &log->root_item);
2367         } else {
2368                 ret = btrfs_update_root(trans, log->fs_info->log_root_tree,
2369                                 &log->root_key, &log->root_item);
2370         }
2371         return ret;
2372 }
2373
2374 static void wait_log_commit(struct btrfs_trans_handle *trans,
2375                             struct btrfs_root *root, int transid)
2376 {
2377         DEFINE_WAIT(wait);
2378         int index = transid % 2;
2379
2380         /*
2381          * we only allow two pending log transactions at a time,
2382          * so we know that if ours is more than 2 older than the
2383          * current transaction, we're done
2384          */
2385         do {
2386                 prepare_to_wait(&root->log_commit_wait[index],
2387                                 &wait, TASK_UNINTERRUPTIBLE);
2388                 mutex_unlock(&root->log_mutex);
2389
2390                 if (root->log_transid < transid + 2 &&
2391                     atomic_read(&root->log_commit[index]))
2392                         schedule();
2393
2394                 finish_wait(&root->log_commit_wait[index], &wait);
2395                 mutex_lock(&root->log_mutex);
2396         } while (root->log_transid < transid + 2 &&
2397                  atomic_read(&root->log_commit[index]));
2398 }
2399
2400 static void wait_for_writer(struct btrfs_trans_handle *trans,
2401                             struct btrfs_root *root)
2402 {
2403         DEFINE_WAIT(wait);
2404
2405         while (atomic_read(&root->log_writers)) {
2406                 prepare_to_wait(&root->log_writer_wait,
2407                                 &wait, TASK_UNINTERRUPTIBLE);
2408                 mutex_unlock(&root->log_mutex);
2409                 if (atomic_read(&root->log_writers))
2410                         schedule();
2411                 mutex_lock(&root->log_mutex);
2412                 finish_wait(&root->log_writer_wait, &wait);
2413         }
2414 }
2415
2416 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2417                                         struct btrfs_log_ctx *ctx)
2418 {
2419         if (!ctx)
2420                 return;
2421
2422         mutex_lock(&root->log_mutex);
2423         list_del_init(&ctx->list);
2424         mutex_unlock(&root->log_mutex);
2425 }
2426
2427 /* 
2428  * Invoked in log mutex context, or be sure there is no other task which
2429  * can access the list.
2430  */
2431 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2432                                              int index, int error)
2433 {
2434         struct btrfs_log_ctx *ctx;
2435
2436         if (!error) {
2437                 INIT_LIST_HEAD(&root->log_ctxs[index]);
2438                 return;
2439         }
2440
2441         list_for_each_entry(ctx, &root->log_ctxs[index], list)
2442                 ctx->log_ret = error;
2443
2444         INIT_LIST_HEAD(&root->log_ctxs[index]);
2445 }
2446
2447 /*
2448  * btrfs_sync_log does sends a given tree log down to the disk and
2449  * updates the super blocks to record it.  When this call is done,
2450  * you know that any inodes previously logged are safely on disk only
2451  * if it returns 0.
2452  *
2453  * Any other return value means you need to call btrfs_commit_transaction.
2454  * Some of the edge cases for fsyncing directories that have had unlinks
2455  * or renames done in the past mean that sometimes the only safe
2456  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
2457  * that has happened.
2458  */
2459 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2460                    struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2461 {
2462         int index1;
2463         int index2;
2464         int mark;
2465         int ret;
2466         struct btrfs_root *log = root->log_root;
2467         struct btrfs_root *log_root_tree = root->fs_info->log_root_tree;
2468         int log_transid = 0;
2469         struct btrfs_log_ctx root_log_ctx;
2470         struct blk_plug plug;
2471
2472         mutex_lock(&root->log_mutex);
2473         log_transid = root->log_transid;
2474         index1 = root->log_transid % 2;
2475         if (atomic_read(&root->log_commit[index1])) {
2476                 wait_log_commit(trans, root, root->log_transid);
2477                 mutex_unlock(&root->log_mutex);
2478                 return ctx->log_ret;
2479         }
2480         atomic_set(&root->log_commit[index1], 1);
2481
2482         /* wait for previous tree log sync to complete */
2483         if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2484                 wait_log_commit(trans, root, root->log_transid - 1);
2485
2486         while (1) {
2487                 int batch = atomic_read(&root->log_batch);
2488                 /* when we're on an ssd, just kick the log commit out */
2489                 if (!btrfs_test_opt(root, SSD) && root->log_multiple_pids) {
2490                         mutex_unlock(&root->log_mutex);
2491                         schedule_timeout_uninterruptible(1);
2492                         mutex_lock(&root->log_mutex);
2493                 }
2494                 wait_for_writer(trans, root);
2495                 if (batch == atomic_read(&root->log_batch))
2496                         break;
2497         }
2498
2499         /* bail out if we need to do a full commit */
2500         if (ACCESS_ONCE(root->fs_info->last_trans_log_full_commit) ==
2501             trans->transid) {
2502                 ret = -EAGAIN;
2503                 btrfs_free_logged_extents(log, log_transid);
2504                 mutex_unlock(&root->log_mutex);
2505                 goto out;
2506         }
2507
2508         if (log_transid % 2 == 0)
2509                 mark = EXTENT_DIRTY;
2510         else
2511                 mark = EXTENT_NEW;
2512
2513         /* we start IO on  all the marked extents here, but we don't actually
2514          * wait for them until later.
2515          */
2516         blk_start_plug(&plug);
2517         ret = btrfs_write_marked_extents(log, &log->dirty_log_pages, mark);
2518         if (ret) {
2519                 blk_finish_plug(&plug);
2520                 btrfs_abort_transaction(trans, root, ret);
2521                 btrfs_free_logged_extents(log, log_transid);
2522                 mutex_unlock(&root->log_mutex);
2523                 goto out;
2524         }
2525
2526         btrfs_set_root_node(&log->root_item, log->node);
2527
2528         root->log_transid++;
2529         log->log_transid = root->log_transid;
2530         root->log_start_pid = 0;
2531         /*
2532          * IO has been started, blocks of the log tree have WRITTEN flag set
2533          * in their headers. new modifications of the log will be written to
2534          * new positions. so it's safe to allow log writers to go in.
2535          */
2536         mutex_unlock(&root->log_mutex);
2537
2538         mutex_lock(&log_root_tree->log_mutex);
2539         atomic_inc(&log_root_tree->log_batch);
2540         atomic_inc(&log_root_tree->log_writers);
2541         mutex_unlock(&log_root_tree->log_mutex);
2542
2543         ret = update_log_root(trans, log);
2544
2545         mutex_lock(&log_root_tree->log_mutex);
2546         if (atomic_dec_and_test(&log_root_tree->log_writers)) {
2547                 smp_mb();
2548                 if (waitqueue_active(&log_root_tree->log_writer_wait))
2549                         wake_up(&log_root_tree->log_writer_wait);
2550         }
2551
2552         if (ret) {
2553                 blk_finish_plug(&plug);
2554                 if (ret != -ENOSPC) {
2555                         btrfs_abort_transaction(trans, root, ret);
2556                         mutex_unlock(&log_root_tree->log_mutex);
2557                         goto out;
2558                 }
2559                 ACCESS_ONCE(root->fs_info->last_trans_log_full_commit) =
2560                                                                 trans->transid;
2561                 btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
2562                 btrfs_free_logged_extents(log, log_transid);
2563                 mutex_unlock(&log_root_tree->log_mutex);
2564                 ret = -EAGAIN;
2565                 goto out;
2566         }
2567
2568         index2 = log_root_tree->log_transid % 2;
2569
2570         btrfs_init_log_ctx(&root_log_ctx);
2571         list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
2572
2573         if (atomic_read(&log_root_tree->log_commit[index2])) {
2574                 blk_finish_plug(&plug);
2575                 btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
2576                 wait_log_commit(trans, log_root_tree,
2577                                 log_root_tree->log_transid);
2578                 btrfs_free_logged_extents(log, log_transid);
2579                 mutex_unlock(&log_root_tree->log_mutex);
2580                 ret = root_log_ctx.log_ret;
2581                 goto out;
2582         }
2583         atomic_set(&log_root_tree->log_commit[index2], 1);
2584
2585         if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
2586                 wait_log_commit(trans, log_root_tree,
2587                                 log_root_tree->log_transid - 1);
2588         }
2589
2590         wait_for_writer(trans, log_root_tree);
2591
2592         /*
2593          * now that we've moved on to the tree of log tree roots,
2594          * check the full commit flag again
2595          */
2596         if (ACCESS_ONCE(root->fs_info->last_trans_log_full_commit) ==
2597             trans->transid) {
2598                 blk_finish_plug(&plug);
2599                 btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
2600                 btrfs_free_logged_extents(log, log_transid);
2601                 mutex_unlock(&log_root_tree->log_mutex);
2602                 ret = -EAGAIN;
2603                 goto out_wake_log_root;
2604         }
2605
2606         ret = btrfs_write_marked_extents(log_root_tree,
2607                                          &log_root_tree->dirty_log_pages,
2608                                          EXTENT_DIRTY | EXTENT_NEW);
2609         blk_finish_plug(&plug);
2610         if (ret) {
2611                 btrfs_abort_transaction(trans, root, ret);
2612                 btrfs_free_logged_extents(log, log_transid);
2613                 mutex_unlock(&log_root_tree->log_mutex);
2614                 goto out_wake_log_root;
2615         }
2616         btrfs_wait_marked_extents(log, &log->dirty_log_pages, mark);
2617         btrfs_wait_marked_extents(log_root_tree,
2618                                   &log_root_tree->dirty_log_pages,
2619                                   EXTENT_NEW | EXTENT_DIRTY);
2620         btrfs_wait_logged_extents(log, log_transid);
2621
2622         btrfs_set_super_log_root(root->fs_info->super_for_commit,
2623                                 log_root_tree->node->start);
2624         btrfs_set_super_log_root_level(root->fs_info->super_for_commit,
2625                                 btrfs_header_level(log_root_tree->node));
2626
2627         log_root_tree->log_transid++;
2628         mutex_unlock(&log_root_tree->log_mutex);
2629
2630         /*
2631          * nobody else is going to jump in and write the the ctree
2632          * super here because the log_commit atomic below is protecting
2633          * us.  We must be called with a transaction handle pinning
2634          * the running transaction open, so a full commit can't hop
2635          * in and cause problems either.
2636          */
2637         ret = write_ctree_super(trans, root->fs_info->tree_root, 1);
2638         if (ret) {
2639                 btrfs_abort_transaction(trans, root, ret);
2640                 goto out_wake_log_root;
2641         }
2642
2643         mutex_lock(&root->log_mutex);
2644         if (root->last_log_commit < log_transid)
2645                 root->last_log_commit = log_transid;
2646         mutex_unlock(&root->log_mutex);
2647
2648 out_wake_log_root:
2649         /*
2650          * We needn't get log_mutex here because we are sure all
2651          * the other tasks are blocked.
2652          */
2653         btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
2654
2655         /*
2656          * It is dangerous if log_commit is changed before we set
2657          * ->log_ret of log ctx. Because the readers may not get
2658          *  the return value.
2659          */
2660         smp_wmb();
2661
2662         atomic_set(&log_root_tree->log_commit[index2], 0);
2663         smp_mb();
2664         if (waitqueue_active(&log_root_tree->log_commit_wait[index2]))
2665                 wake_up(&log_root_tree->log_commit_wait[index2]);
2666 out:
2667         /* See above. */
2668         btrfs_remove_all_log_ctxs(root, index1, ret);
2669
2670         /* See above. */
2671         smp_wmb();
2672         atomic_set(&root->log_commit[index1], 0);
2673
2674         smp_mb();
2675         if (waitqueue_active(&root->log_commit_wait[index1]))
2676                 wake_up(&root->log_commit_wait[index1]);
2677         return ret;
2678 }
2679
2680 static void free_log_tree(struct btrfs_trans_handle *trans,
2681                           struct btrfs_root *log)
2682 {
2683         int ret;
2684         u64 start;
2685         u64 end;
2686         struct walk_control wc = {
2687                 .free = 1,
2688                 .process_func = process_one_buffer
2689         };
2690
2691         ret = walk_log_tree(trans, log, &wc);
2692         /* I don't think this can happen but just in case */
2693         if (ret)
2694                 btrfs_abort_transaction(trans, log, ret);
2695
2696         while (1) {
2697                 ret = find_first_extent_bit(&log->dirty_log_pages,
2698                                 0, &start, &end, EXTENT_DIRTY | EXTENT_NEW,
2699                                 NULL);
2700                 if (ret)
2701                         break;
2702
2703                 clear_extent_bits(&log->dirty_log_pages, start, end,
2704                                   EXTENT_DIRTY | EXTENT_NEW, GFP_NOFS);
2705         }
2706
2707         /*
2708          * We may have short-circuited the log tree with the full commit logic
2709          * and left ordered extents on our list, so clear these out to keep us
2710          * from leaking inodes and memory.
2711          */
2712         btrfs_free_logged_extents(log, 0);
2713         btrfs_free_logged_extents(log, 1);
2714
2715         free_extent_buffer(log->node);
2716         kfree(log);
2717 }
2718
2719 /*
2720  * free all the extents used by the tree log.  This should be called
2721  * at commit time of the full transaction
2722  */
2723 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
2724 {
2725         if (root->log_root) {
2726                 free_log_tree(trans, root->log_root);
2727                 root->log_root = NULL;
2728         }
2729         return 0;
2730 }
2731
2732 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
2733                              struct btrfs_fs_info *fs_info)
2734 {
2735         if (fs_info->log_root_tree) {
2736                 free_log_tree(trans, fs_info->log_root_tree);
2737                 fs_info->log_root_tree = NULL;
2738         }
2739         return 0;
2740 }
2741
2742 /*
2743  * If both a file and directory are logged, and unlinks or renames are
2744  * mixed in, we have a few interesting corners:
2745  *
2746  * create file X in dir Y
2747  * link file X to X.link in dir Y
2748  * fsync file X
2749  * unlink file X but leave X.link
2750  * fsync dir Y
2751  *
2752  * After a crash we would expect only X.link to exist.  But file X
2753  * didn't get fsync'd again so the log has back refs for X and X.link.
2754  *
2755  * We solve this by removing directory entries and inode backrefs from the
2756  * log when a file that was logged in the current transaction is
2757  * unlinked.  Any later fsync will include the updated log entries, and
2758  * we'll be able to reconstruct the proper directory items from backrefs.
2759  *
2760  * This optimizations allows us to avoid relogging the entire inode
2761  * or the entire directory.
2762  */
2763 int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
2764                                  struct btrfs_root *root,
2765                                  const char *name, int name_len,
2766                                  struct inode *dir, u64 index)
2767 {
2768         struct btrfs_root *log;
2769         struct btrfs_dir_item *di;
2770         struct btrfs_path *path;
2771         int ret;
2772         int err = 0;
2773         int bytes_del = 0;
2774         u64 dir_ino = btrfs_ino(dir);
2775
2776         if (BTRFS_I(dir)->logged_trans < trans->transid)
2777                 return 0;
2778
2779         ret = join_running_log_trans(root);
2780         if (ret)
2781                 return 0;
2782
2783         mutex_lock(&BTRFS_I(dir)->log_mutex);
2784
2785         log = root->log_root;
2786         path = btrfs_alloc_path();
2787         if (!path) {
2788                 err = -ENOMEM;
2789                 goto out_unlock;
2790         }
2791
2792         di = btrfs_lookup_dir_item(trans, log, path, dir_ino,
2793                                    name, name_len, -1);
2794         if (IS_ERR(di)) {
2795                 err = PTR_ERR(di);
2796                 goto fail;
2797         }
2798         if (di) {
2799                 ret = btrfs_delete_one_dir_name(trans, log, path, di);
2800                 bytes_del += name_len;
2801                 if (ret) {
2802                         err = ret;
2803                         goto fail;
2804                 }
2805         }
2806         btrfs_release_path(path);
2807         di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
2808                                          index, name, name_len, -1);
2809         if (IS_ERR(di)) {
2810                 err = PTR_ERR(di);
2811                 goto fail;
2812         }
2813         if (di) {
2814                 ret = btrfs_delete_one_dir_name(trans, log, path, di);
2815                 bytes_del += name_len;
2816                 if (ret) {
2817                         err = ret;
2818                         goto fail;
2819                 }
2820         }
2821
2822         /* update the directory size in the log to reflect the names
2823          * we have removed
2824          */
2825         if (bytes_del) {
2826                 struct btrfs_key key;
2827
2828                 key.objectid = dir_ino;
2829                 key.offset = 0;
2830                 key.type = BTRFS_INODE_ITEM_KEY;
2831                 btrfs_release_path(path);
2832
2833                 ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
2834                 if (ret < 0) {
2835                         err = ret;
2836                         goto fail;
2837                 }
2838                 if (ret == 0) {
2839                         struct btrfs_inode_item *item;
2840                         u64 i_size;
2841
2842                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2843                                               struct btrfs_inode_item);
2844                         i_size = btrfs_inode_size(path->nodes[0], item);
2845                         if (i_size > bytes_del)
2846                                 i_size -= bytes_del;
2847                         else
2848                                 i_size = 0;
2849                         btrfs_set_inode_size(path->nodes[0], item, i_size);
2850                         btrfs_mark_buffer_dirty(path->nodes[0]);
2851                 } else
2852                         ret = 0;
2853                 btrfs_release_path(path);
2854         }
2855 fail:
2856         btrfs_free_path(path);
2857 out_unlock:
2858         mutex_unlock(&BTRFS_I(dir)->log_mutex);
2859         if (ret == -ENOSPC) {
2860                 root->fs_info->last_trans_log_full_commit = trans->transid;
2861                 ret = 0;
2862         } else if (ret < 0)
2863                 btrfs_abort_transaction(trans, root, ret);
2864
2865         btrfs_end_log_trans(root);
2866
2867         return err;
2868 }
2869
2870 /* see comments for btrfs_del_dir_entries_in_log */
2871 int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
2872                                struct btrfs_root *root,
2873                                const char *name, int name_len,
2874                                struct inode *inode, u64 dirid)
2875 {
2876         struct btrfs_root *log;
2877         u64 index;
2878         int ret;
2879
2880         if (BTRFS_I(inode)->logged_trans < trans->transid)
2881                 return 0;
2882
2883         ret = join_running_log_trans(root);
2884         if (ret)
2885                 return 0;
2886         log = root->log_root;
2887         mutex_lock(&BTRFS_I(inode)->log_mutex);
2888
2889         ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
2890                                   dirid, &index);
2891         mutex_unlock(&BTRFS_I(inode)->log_mutex);
2892         if (ret == -ENOSPC) {
2893                 root->fs_info->last_trans_log_full_commit = trans->transid;
2894                 ret = 0;
2895         } else if (ret < 0 && ret != -ENOENT)
2896                 btrfs_abort_transaction(trans, root, ret);
2897         btrfs_end_log_trans(root);
2898
2899         return ret;
2900 }
2901
2902 /*
2903  * creates a range item in the log for 'dirid'.  first_offset and
2904  * last_offset tell us which parts of the key space the log should
2905  * be considered authoritative for.
2906  */
2907 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
2908                                        struct btrfs_root *log,
2909                                        struct btrfs_path *path,
2910                                        int key_type, u64 dirid,
2911                                        u64 first_offset, u64 last_offset)
2912 {
2913         int ret;
2914         struct btrfs_key key;
2915         struct btrfs_dir_log_item *item;
2916
2917         key.objectid = dirid;
2918         key.offset = first_offset;
2919         if (key_type == BTRFS_DIR_ITEM_KEY)
2920                 key.type = BTRFS_DIR_LOG_ITEM_KEY;
2921         else
2922                 key.type = BTRFS_DIR_LOG_INDEX_KEY;
2923         ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
2924         if (ret)
2925                 return ret;
2926
2927         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
2928                               struct btrfs_dir_log_item);
2929         btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
2930         btrfs_mark_buffer_dirty(path->nodes[0]);
2931         btrfs_release_path(path);
2932         return 0;
2933 }
2934
2935 /*
2936  * log all the items included in the current transaction for a given
2937  * directory.  This also creates the range items in the log tree required
2938  * to replay anything deleted before the fsync
2939  */
2940 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
2941                           struct btrfs_root *root, struct inode *inode,
2942                           struct btrfs_path *path,
2943                           struct btrfs_path *dst_path, int key_type,
2944                           u64 min_offset, u64 *last_offset_ret)
2945 {
2946         struct btrfs_key min_key;
2947         struct btrfs_root *log = root->log_root;
2948         struct extent_buffer *src;
2949         int err = 0;
2950         int ret;
2951         int i;
2952         int nritems;
2953         u64 first_offset = min_offset;
2954         u64 last_offset = (u64)-1;
2955         u64 ino = btrfs_ino(inode);
2956
2957         log = root->log_root;
2958
2959         min_key.objectid = ino;
2960         min_key.type = key_type;
2961         min_key.offset = min_offset;
2962
2963         path->keep_locks = 1;
2964
2965         ret = btrfs_search_forward(root, &min_key, path, trans->transid);
2966
2967         /*
2968          * we didn't find anything from this transaction, see if there
2969          * is anything at all
2970          */
2971         if (ret != 0 || min_key.objectid != ino || min_key.type != key_type) {
2972                 min_key.objectid = ino;
2973                 min_key.type = key_type;
2974                 min_key.offset = (u64)-1;
2975                 btrfs_release_path(path);
2976                 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
2977                 if (ret < 0) {
2978                         btrfs_release_path(path);
2979                         return ret;
2980                 }
2981                 ret = btrfs_previous_item(root, path, ino, key_type);
2982
2983                 /* if ret == 0 there are items for this type,
2984                  * create a range to tell us the last key of this type.
2985                  * otherwise, there are no items in this directory after
2986                  * *min_offset, and we create a range to indicate that.
2987                  */
2988                 if (ret == 0) {
2989                         struct btrfs_key tmp;
2990                         btrfs_item_key_to_cpu(path->nodes[0], &tmp,
2991                                               path->slots[0]);
2992                         if (key_type == tmp.type)
2993                                 first_offset = max(min_offset, tmp.offset) + 1;
2994                 }
2995                 goto done;
2996         }
2997
2998         /* go backward to find any previous key */
2999         ret = btrfs_previous_item(root, path, ino, key_type);
3000         if (ret == 0) {
3001                 struct btrfs_key tmp;
3002                 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3003                 if (key_type == tmp.type) {
3004                         first_offset = tmp.offset;
3005                         ret = overwrite_item(trans, log, dst_path,
3006                                              path->nodes[0], path->slots[0],
3007                                              &tmp);
3008                         if (ret) {
3009                                 err = ret;
3010                                 goto done;
3011                         }
3012                 }
3013         }
3014         btrfs_release_path(path);
3015
3016         /* find the first key from this transaction again */
3017         ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3018         if (WARN_ON(ret != 0))
3019                 goto done;
3020
3021         /*
3022          * we have a block from this transaction, log every item in it
3023          * from our directory
3024          */
3025         while (1) {
3026                 struct btrfs_key tmp;
3027                 src = path->nodes[0];
3028                 nritems = btrfs_header_nritems(src);
3029                 for (i = path->slots[0]; i < nritems; i++) {
3030                         btrfs_item_key_to_cpu(src, &min_key, i);
3031
3032                         if (min_key.objectid != ino || min_key.type != key_type)
3033                                 goto done;
3034                         ret = overwrite_item(trans, log, dst_path, src, i,
3035                                              &min_key);
3036                         if (ret) {
3037                                 err = ret;
3038                                 goto done;
3039                         }
3040                 }
3041                 path->slots[0] = nritems;
3042
3043                 /*
3044                  * look ahead to the next item and see if it is also
3045                  * from this directory and from this transaction
3046                  */
3047                 ret = btrfs_next_leaf(root, path);
3048                 if (ret == 1) {
3049                         last_offset = (u64)-1;
3050                         goto done;
3051                 }
3052                 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3053                 if (tmp.objectid != ino || tmp.type != key_type) {
3054                         last_offset = (u64)-1;
3055                         goto done;
3056                 }
3057                 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3058                         ret = overwrite_item(trans, log, dst_path,
3059                                              path->nodes[0], path->slots[0],
3060                                              &tmp);
3061                         if (ret)
3062                                 err = ret;
3063                         else
3064                                 last_offset = tmp.offset;
3065                         goto done;
3066                 }
3067         }
3068 done:
3069         btrfs_release_path(path);
3070         btrfs_release_path(dst_path);
3071
3072         if (err == 0) {
3073                 *last_offset_ret = last_offset;
3074                 /*
3075                  * insert the log range keys to indicate where the log
3076                  * is valid
3077                  */
3078                 ret = insert_dir_log_key(trans, log, path, key_type,
3079                                          ino, first_offset, last_offset);
3080                 if (ret)
3081                         err = ret;
3082         }
3083         return err;
3084 }
3085
3086 /*
3087  * logging directories is very similar to logging inodes, We find all the items
3088  * from the current transaction and write them to the log.
3089  *
3090  * The recovery code scans the directory in the subvolume, and if it finds a
3091  * key in the range logged that is not present in the log tree, then it means
3092  * that dir entry was unlinked during the transaction.
3093  *
3094  * In order for that scan to work, we must include one key smaller than
3095  * the smallest logged by this transaction and one key larger than the largest
3096  * key logged by this transaction.
3097  */
3098 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
3099                           struct btrfs_root *root, struct inode *inode,
3100                           struct btrfs_path *path,
3101                           struct btrfs_path *dst_path)
3102 {
3103         u64 min_key;
3104         u64 max_key;
3105         int ret;
3106         int key_type = BTRFS_DIR_ITEM_KEY;
3107
3108 again:
3109         min_key = 0;
3110         max_key = 0;
3111         while (1) {
3112                 ret = log_dir_items(trans, root, inode, path,
3113                                     dst_path, key_type, min_key,
3114                                     &max_key);
3115                 if (ret)
3116                         return ret;
3117                 if (max_key == (u64)-1)
3118                         break;
3119                 min_key = max_key + 1;
3120         }
3121
3122         if (key_type == BTRFS_DIR_ITEM_KEY) {
3123                 key_type = BTRFS_DIR_INDEX_KEY;
3124                 goto again;
3125         }
3126         return 0;
3127 }
3128
3129 /*
3130  * a helper function to drop items from the log before we relog an
3131  * inode.  max_key_type indicates the highest item type to remove.
3132  * This cannot be run for file data extents because it does not
3133  * free the extents they point to.
3134  */
3135 static int drop_objectid_items(struct btrfs_trans_handle *trans,
3136                                   struct btrfs_root *log,
3137                                   struct btrfs_path *path,
3138                                   u64 objectid, int max_key_type)
3139 {
3140         int ret;
3141         struct btrfs_key key;
3142         struct btrfs_key found_key;
3143         int start_slot;
3144
3145         key.objectid = objectid;
3146         key.type = max_key_type;
3147         key.offset = (u64)-1;
3148
3149         while (1) {
3150                 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
3151                 BUG_ON(ret == 0); /* Logic error */
3152                 if (ret < 0)
3153                         break;
3154
3155                 if (path->slots[0] == 0)
3156                         break;
3157
3158                 path->slots[0]--;
3159                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
3160                                       path->slots[0]);
3161
3162                 if (found_key.objectid != objectid)
3163                         break;
3164
3165                 found_key.offset = 0;
3166                 found_key.type = 0;
3167                 ret = btrfs_bin_search(path->nodes[0], &found_key, 0,
3168                                        &start_slot);
3169
3170                 ret = btrfs_del_items(trans, log, path, start_slot,
3171                                       path->slots[0] - start_slot + 1);
3172                 /*
3173                  * If start slot isn't 0 then we don't need to re-search, we've
3174                  * found the last guy with the objectid in this tree.
3175                  */
3176                 if (ret || start_slot != 0)
3177                         break;
3178                 btrfs_release_path(path);
3179         }
3180         btrfs_release_path(path);
3181         if (ret > 0)
3182                 ret = 0;
3183         return ret;
3184 }
3185
3186 static void fill_inode_item(struct btrfs_trans_handle *trans,
3187                             struct extent_buffer *leaf,
3188                             struct btrfs_inode_item *item,
3189                             struct inode *inode, int log_inode_only)
3190 {
3191         struct btrfs_map_token token;
3192
3193         btrfs_init_map_token(&token);
3194
3195         if (log_inode_only) {
3196                 /* set the generation to zero so the recover code
3197                  * can tell the difference between an logging
3198                  * just to say 'this inode exists' and a logging
3199                  * to say 'update this inode with these values'
3200                  */
3201                 btrfs_set_token_inode_generation(leaf, item, 0, &token);
3202                 btrfs_set_token_inode_size(leaf, item, 0, &token);
3203         } else {
3204                 btrfs_set_token_inode_generation(leaf, item,
3205                                                  BTRFS_I(inode)->generation,
3206                                                  &token);
3207                 btrfs_set_token_inode_size(leaf, item, inode->i_size, &token);
3208         }
3209
3210         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3211         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3212         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3213         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3214
3215         btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3216                                      inode->i_atime.tv_sec, &token);
3217         btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3218                                       inode->i_atime.tv_nsec, &token);
3219
3220         btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3221                                      inode->i_mtime.tv_sec, &token);
3222         btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3223                                       inode->i_mtime.tv_nsec, &token);
3224
3225         btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3226                                      inode->i_ctime.tv_sec, &token);
3227         btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3228                                       inode->i_ctime.tv_nsec, &token);
3229
3230         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3231                                      &token);
3232
3233         btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3234         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3235         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3236         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3237         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3238 }
3239
3240 static int log_inode_item(struct btrfs_trans_handle *trans,
3241                           struct btrfs_root *log, struct btrfs_path *path,
3242                           struct inode *inode)
3243 {
3244         struct btrfs_inode_item *inode_item;
3245         int ret;
3246
3247         ret = btrfs_insert_empty_item(trans, log, path,
3248                                       &BTRFS_I(inode)->location,
3249                                       sizeof(*inode_item));
3250         if (ret && ret != -EEXIST)
3251                 return ret;
3252         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3253                                     struct btrfs_inode_item);
3254         fill_inode_item(trans, path->nodes[0], inode_item, inode, 0);
3255         btrfs_release_path(path);
3256         return 0;
3257 }
3258
3259 static noinline int copy_items(struct btrfs_trans_handle *trans,
3260                                struct inode *inode,
3261                                struct btrfs_path *dst_path,
3262                                struct btrfs_path *src_path, u64 *last_extent,
3263                                int start_slot, int nr, int inode_only)
3264 {
3265         unsigned long src_offset;
3266         unsigned long dst_offset;
3267         struct btrfs_root *log = BTRFS_I(inode)->root->log_root;
3268         struct btrfs_file_extent_item *extent;
3269         struct btrfs_inode_item *inode_item;
3270         struct extent_buffer *src = src_path->nodes[0];
3271         struct btrfs_key first_key, last_key, key;
3272         int ret;
3273         struct btrfs_key *ins_keys;
3274         u32 *ins_sizes;
3275         char *ins_data;
3276         int i;
3277         struct list_head ordered_sums;
3278         int skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
3279         bool has_extents = false;
3280         bool need_find_last_extent = (*last_extent == 0);
3281         bool done = false;
3282
3283         INIT_LIST_HEAD(&ordered_sums);
3284
3285         ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
3286                            nr * sizeof(u32), GFP_NOFS);
3287         if (!ins_data)
3288                 return -ENOMEM;
3289
3290         first_key.objectid = (u64)-1;
3291
3292         ins_sizes = (u32 *)ins_data;
3293         ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
3294
3295         for (i = 0; i < nr; i++) {
3296                 ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
3297                 btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
3298         }
3299         ret = btrfs_insert_empty_items(trans, log, dst_path,
3300                                        ins_keys, ins_sizes, nr);
3301         if (ret) {
3302                 kfree(ins_data);
3303                 return ret;
3304         }
3305
3306         for (i = 0; i < nr; i++, dst_path->slots[0]++) {
3307                 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
3308                                                    dst_path->slots[0]);
3309
3310                 src_offset = btrfs_item_ptr_offset(src, start_slot + i);
3311
3312                 if ((i == (nr - 1)))
3313                         last_key = ins_keys[i];
3314
3315                 if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
3316                         inode_item = btrfs_item_ptr(dst_path->nodes[0],
3317                                                     dst_path->slots[0],
3318                                                     struct btrfs_inode_item);
3319                         fill_inode_item(trans, dst_path->nodes[0], inode_item,
3320                                         inode, inode_only == LOG_INODE_EXISTS);
3321                 } else {
3322                         copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
3323                                            src_offset, ins_sizes[i]);
3324                 }
3325
3326                 /*
3327                  * We set need_find_last_extent here in case we know we were
3328                  * processing other items and then walk into the first extent in
3329                  * the inode.  If we don't hit an extent then nothing changes,
3330                  * we'll do the last search the next time around.
3331                  */
3332                 if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY) {
3333                         has_extents = true;
3334                         if (need_find_last_extent &&
3335                             first_key.objectid == (u64)-1)
3336                                 first_key = ins_keys[i];
3337                 } else {
3338                         need_find_last_extent = false;
3339                 }
3340
3341                 /* take a reference on file data extents so that truncates
3342                  * or deletes of this inode don't have to relog the inode
3343                  * again
3344                  */
3345                 if (btrfs_key_type(ins_keys + i) == BTRFS_EXTENT_DATA_KEY &&
3346                     !skip_csum) {
3347                         int found_type;
3348                         extent = btrfs_item_ptr(src, start_slot + i,
3349                                                 struct btrfs_file_extent_item);
3350
3351                         if (btrfs_file_extent_generation(src, extent) < trans->transid)
3352                                 continue;
3353
3354                         found_type = btrfs_file_extent_type(src, extent);
3355                         if (found_type == BTRFS_FILE_EXTENT_REG) {
3356                                 u64 ds, dl, cs, cl;
3357                                 ds = btrfs_file_extent_disk_bytenr(src,
3358                                                                 extent);
3359                                 /* ds == 0 is a hole */
3360                                 if (ds == 0)
3361                                         continue;
3362
3363                                 dl = btrfs_file_extent_disk_num_bytes(src,
3364                                                                 extent);
3365                                 cs = btrfs_file_extent_offset(src, extent);
3366                                 cl = btrfs_file_extent_num_bytes(src,
3367                                                                 extent);
3368                                 if (btrfs_file_extent_compression(src,
3369                                                                   extent)) {
3370                                         cs = 0;
3371                                         cl = dl;
3372                                 }
3373
3374                                 ret = btrfs_lookup_csums_range(
3375                                                 log->fs_info->csum_root,
3376                                                 ds + cs, ds + cs + cl - 1,
3377                                                 &ordered_sums, 0);
3378                                 if (ret) {
3379                                         btrfs_release_path(dst_path);
3380                                         kfree(ins_data);
3381                                         return ret;
3382                                 }
3383                         }
3384                 }
3385         }
3386
3387         btrfs_mark_buffer_dirty(dst_path->nodes[0]);
3388         btrfs_release_path(dst_path);
3389         kfree(ins_data);
3390
3391         /*
3392          * we have to do this after the loop above to avoid changing the
3393          * log tree while trying to change the log tree.
3394          */
3395         ret = 0;
3396         while (!list_empty(&ordered_sums)) {
3397                 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
3398                                                    struct btrfs_ordered_sum,
3399                                                    list);
3400                 if (!ret)
3401                         ret = btrfs_csum_file_blocks(trans, log, sums);
3402                 list_del(&sums->list);
3403                 kfree(sums);
3404         }
3405
3406         if (!has_extents)
3407                 return ret;
3408
3409         /*
3410          * Because we use btrfs_search_forward we could skip leaves that were
3411          * not modified and then assume *last_extent is valid when it really
3412          * isn't.  So back up to the previous leaf and read the end of the last
3413          * extent before we go and fill in holes.
3414          */
3415         if (need_find_last_extent) {
3416                 u64 len;
3417
3418                 ret = btrfs_prev_leaf(BTRFS_I(inode)->root, src_path);
3419                 if (ret < 0)
3420                         return ret;
3421                 if (ret)
3422                         goto fill_holes;
3423                 if (src_path->slots[0])
3424                         src_path->slots[0]--;
3425                 src = src_path->nodes[0];
3426                 btrfs_item_key_to_cpu(src, &key, src_path->slots[0]);
3427                 if (key.objectid != btrfs_ino(inode) ||
3428                     key.type != BTRFS_EXTENT_DATA_KEY)
3429                         goto fill_holes;
3430                 extent = btrfs_item_ptr(src, src_path->slots[0],
3431                                         struct btrfs_file_extent_item);
3432                 if (btrfs_file_extent_type(src, extent) ==
3433                     BTRFS_FILE_EXTENT_INLINE) {
3434                         len = btrfs_file_extent_inline_len(src,
3435                                                            src_path->slots[0],
3436                                                            extent);
3437                         *last_extent = ALIGN(key.offset + len,
3438                                              log->sectorsize);
3439                 } else {
3440                         len = btrfs_file_extent_num_bytes(src, extent);
3441                         *last_extent = key.offset + len;
3442                 }
3443         }
3444 fill_holes:
3445         /* So we did prev_leaf, now we need to move to the next leaf, but a few
3446          * things could have happened
3447          *
3448          * 1) A merge could have happened, so we could currently be on a leaf
3449          * that holds what we were copying in the first place.
3450          * 2) A split could have happened, and now not all of the items we want
3451          * are on the same leaf.
3452          *
3453          * So we need to adjust how we search for holes, we need to drop the
3454          * path and re-search for the first extent key we found, and then walk
3455          * forward until we hit the last one we copied.
3456          */
3457         if (need_find_last_extent) {
3458                 /* btrfs_prev_leaf could return 1 without releasing the path */
3459                 btrfs_release_path(src_path);
3460                 ret = btrfs_search_slot(NULL, BTRFS_I(inode)->root, &first_key,
3461                                         src_path, 0, 0);
3462                 if (ret < 0)
3463                         return ret;
3464                 ASSERT(ret == 0);
3465                 src = src_path->nodes[0];
3466                 i = src_path->slots[0];
3467         } else {
3468                 i = start_slot;
3469         }
3470
3471         /*
3472          * Ok so here we need to go through and fill in any holes we may have
3473          * to make sure that holes are punched for those areas in case they had
3474          * extents previously.
3475          */
3476         while (!done) {
3477                 u64 offset, len;
3478                 u64 extent_end;
3479
3480                 if (i >= btrfs_header_nritems(src_path->nodes[0])) {
3481                         ret = btrfs_next_leaf(BTRFS_I(inode)->root, src_path);
3482                         if (ret < 0)
3483                                 return ret;
3484                         ASSERT(ret == 0);
3485                         src = src_path->nodes[0];
3486                         i = 0;
3487                 }
3488
3489                 btrfs_item_key_to_cpu(src, &key, i);
3490                 if (!btrfs_comp_cpu_keys(&key, &last_key))
3491                         done = true;
3492                 if (key.objectid != btrfs_ino(inode) ||
3493                     key.type != BTRFS_EXTENT_DATA_KEY) {
3494                         i++;
3495                         continue;
3496                 }
3497                 extent = btrfs_item_ptr(src, i, struct btrfs_file_extent_item);
3498                 if (btrfs_file_extent_type(src, extent) ==
3499                     BTRFS_FILE_EXTENT_INLINE) {
3500                         len = btrfs_file_extent_inline_len(src, i, extent);
3501                         extent_end = ALIGN(key.offset + len, log->sectorsize);
3502                 } else {
3503                         len = btrfs_file_extent_num_bytes(src, extent);
3504                         extent_end = key.offset + len;
3505                 }
3506                 i++;
3507
3508                 if (*last_extent == key.offset) {
3509                         *last_extent = extent_end;
3510                         continue;
3511                 }
3512                 offset = *last_extent;
3513                 len = key.offset - *last_extent;
3514                 ret = btrfs_insert_file_extent(trans, log, btrfs_ino(inode),
3515                                                offset, 0, 0, len, 0, len, 0,
3516                                                0, 0);
3517                 if (ret)
3518                         break;
3519                 *last_extent = offset + len;
3520         }
3521         /*
3522          * Need to let the callers know we dropped the path so they should
3523          * re-search.
3524          */
3525         if (!ret && need_find_last_extent)
3526                 ret = 1;
3527         return ret;
3528 }
3529
3530 static int extent_cmp(void *priv, struct list_head *a, struct list_head *b)
3531 {
3532         struct extent_map *em1, *em2;
3533
3534         em1 = list_entry(a, struct extent_map, list);
3535         em2 = list_entry(b, struct extent_map, list);
3536
3537         if (em1->start < em2->start)
3538                 return -1;
3539         else if (em1->start > em2->start)
3540                 return 1;
3541         return 0;
3542 }
3543
3544 static int log_one_extent(struct btrfs_trans_handle *trans,
3545                           struct inode *inode, struct btrfs_root *root,
3546                           struct extent_map *em, struct btrfs_path *path,
3547                           struct list_head *logged_list)
3548 {
3549         struct btrfs_root *log = root->log_root;
3550         struct btrfs_file_extent_item *fi;
3551         struct extent_buffer *leaf;
3552         struct btrfs_ordered_extent *ordered;
3553         struct list_head ordered_sums;
3554         struct btrfs_map_token token;
3555         struct btrfs_key key;
3556         u64 mod_start = em->mod_start;
3557         u64 mod_len = em->mod_len;
3558         u64 csum_offset;
3559         u64 csum_len;
3560         u64 extent_offset = em->start - em->orig_start;
3561         u64 block_len;
3562         int ret;
3563         bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
3564         int extent_inserted = 0;
3565
3566         INIT_LIST_HEAD(&ordered_sums);
3567         btrfs_init_map_token(&token);
3568
3569         ret = __btrfs_drop_extents(trans, log, inode, path, em->start,
3570                                    em->start + em->len, NULL, 0, 1,
3571                                    sizeof(*fi), &extent_inserted);
3572         if (ret)
3573                 return ret;
3574
3575         if (!extent_inserted) {
3576                 key.objectid = btrfs_ino(inode);
3577                 key.type = BTRFS_EXTENT_DATA_KEY;
3578                 key.offset = em->start;
3579
3580                 ret = btrfs_insert_empty_item(trans, log, path, &key,
3581                                               sizeof(*fi));
3582                 if (ret)
3583                         return ret;
3584         }
3585         leaf = path->nodes[0];
3586         fi = btrfs_item_ptr(leaf, path->slots[0],
3587                             struct btrfs_file_extent_item);
3588
3589         btrfs_set_token_file_extent_generation(leaf, fi, em->generation,
3590                                                &token);
3591         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3592                 skip_csum = true;
3593                 btrfs_set_token_file_extent_type(leaf, fi,
3594                                                  BTRFS_FILE_EXTENT_PREALLOC,
3595                                                  &token);
3596         } else {
3597                 btrfs_set_token_file_extent_type(leaf, fi,
3598                                                  BTRFS_FILE_EXTENT_REG,
3599                                                  &token);
3600                 if (em->block_start == EXTENT_MAP_HOLE)
3601                         skip_csum = true;
3602         }
3603
3604         block_len = max(em->block_len, em->orig_block_len);
3605         if (em->compress_type != BTRFS_COMPRESS_NONE) {
3606                 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
3607                                                         em->block_start,
3608                                                         &token);
3609                 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
3610                                                            &token);
3611         } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
3612                 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
3613                                                         em->block_start -
3614                                                         extent_offset, &token);
3615                 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
3616                                                            &token);
3617         } else {
3618                 btrfs_set_token_file_extent_disk_bytenr(leaf, fi, 0, &token);
3619                 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, 0,
3620                                                            &token);
3621         }
3622
3623         btrfs_set_token_file_extent_offset(leaf, fi,
3624                                            em->start - em->orig_start,
3625                                            &token);
3626         btrfs_set_token_file_extent_num_bytes(leaf, fi, em->len, &token);
3627         btrfs_set_token_file_extent_ram_bytes(leaf, fi, em->ram_bytes, &token);
3628         btrfs_set_token_file_extent_compression(leaf, fi, em->compress_type,
3629                                                 &token);
3630         btrfs_set_token_file_extent_encryption(leaf, fi, 0, &token);
3631         btrfs_set_token_file_extent_other_encoding(leaf, fi, 0, &token);
3632         btrfs_mark_buffer_dirty(leaf);
3633
3634         btrfs_release_path(path);
3635         if (ret) {
3636                 return ret;
3637         }
3638
3639         if (skip_csum)
3640                 return 0;
3641
3642         /*
3643          * First check and see if our csums are on our outstanding ordered
3644          * extents.
3645          */
3646         list_for_each_entry(ordered, logged_list, log_list) {
3647                 struct btrfs_ordered_sum *sum;
3648
3649                 if (!mod_len)
3650                         break;
3651
3652                 if (ordered->file_offset + ordered->len <= mod_start ||
3653                     mod_start + mod_len <= ordered->file_offset)
3654                         continue;
3655
3656                 /*
3657                  * We are going to copy all the csums on this ordered extent, so
3658                  * go ahead and adjust mod_start and mod_len in case this
3659                  * ordered extent has already been logged.
3660                  */
3661                 if (ordered->file_offset > mod_start) {
3662                         if (ordered->file_offset + ordered->len >=
3663                             mod_start + mod_len)
3664                                 mod_len = ordered->file_offset - mod_start;
3665                         /*
3666                          * If we have this case
3667                          *
3668                          * |--------- logged extent ---------|
3669                          *       |----- ordered extent ----|
3670                          *
3671                          * Just don't mess with mod_start and mod_len, we'll
3672                          * just end up logging more csums than we need and it
3673                          * will be ok.
3674                          */
3675                 } else {
3676                         if (ordered->file_offset + ordered->len <
3677                             mod_start + mod_len) {
3678                                 mod_len = (mod_start + mod_len) -
3679                                         (ordered->file_offset + ordered->len);
3680                                 mod_start = ordered->file_offset +
3681                                         ordered->len;
3682                         } else {
3683                                 mod_len = 0;
3684                         }
3685                 }
3686
3687                 /*
3688                  * To keep us from looping for the above case of an ordered
3689                  * extent that falls inside of the logged extent.
3690                  */
3691                 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM,
3692                                      &ordered->flags))
3693                         continue;
3694
3695                 if (ordered->csum_bytes_left) {
3696                         btrfs_start_ordered_extent(inode, ordered, 0);
3697                         wait_event(ordered->wait,
3698                                    ordered->csum_bytes_left == 0);
3699                 }
3700
3701                 list_for_each_entry(sum, &ordered->list, list) {
3702                         ret = btrfs_csum_file_blocks(trans, log, sum);
3703                         if (ret)
3704                                 goto unlocked;
3705                 }
3706
3707         }
3708 unlocked:
3709
3710         if (!mod_len || ret)
3711                 return ret;
3712
3713         if (em->compress_type) {
3714                 csum_offset = 0;
3715                 csum_len = block_len;
3716         } else {
3717                 csum_offset = mod_start - em->start;
3718                 csum_len = mod_len;
3719         }
3720
3721         /* block start is already adjusted for the file extent offset. */
3722         ret = btrfs_lookup_csums_range(log->fs_info->csum_root,
3723                                        em->block_start + csum_offset,
3724                                        em->block_start + csum_offset +
3725                                        csum_len - 1, &ordered_sums, 0);
3726         if (ret)
3727                 return ret;
3728
3729         while (!list_empty(&ordered_sums)) {
3730                 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
3731                                                    struct btrfs_ordered_sum,
3732                                                    list);
3733                 if (!ret)
3734                         ret = btrfs_csum_file_blocks(trans, log, sums);
3735                 list_del(&sums->list);
3736                 kfree(sums);
3737         }
3738
3739         return ret;
3740 }
3741
3742 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
3743                                      struct btrfs_root *root,
3744                                      struct inode *inode,
3745                                      struct btrfs_path *path,
3746                                      struct list_head *logged_list)
3747 {
3748         struct extent_map *em, *n;
3749         struct list_head extents;
3750         struct extent_map_tree *tree = &BTRFS_I(inode)->extent_tree;
3751         u64 test_gen;
3752         int ret = 0;
3753         int num = 0;
3754
3755         INIT_LIST_HEAD(&extents);
3756
3757         write_lock(&tree->lock);
3758         test_gen = root->fs_info->last_trans_committed;
3759
3760         list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
3761                 list_del_init(&em->list);
3762
3763                 /*
3764                  * Just an arbitrary number, this can be really CPU intensive
3765                  * once we start getting a lot of extents, and really once we
3766                  * have a bunch of extents we just want to commit since it will
3767                  * be faster.
3768                  */
3769                 if (++num > 32768) {
3770                         list_del_init(&tree->modified_extents);
3771                         ret = -EFBIG;
3772                         goto process;
3773                 }
3774
3775                 if (em->generation <= test_gen)
3776                         continue;
3777                 /* Need a ref to keep it from getting evicted from cache */
3778                 atomic_inc(&em->refs);
3779                 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
3780                 list_add_tail(&em->list, &extents);
3781                 num++;
3782         }
3783
3784         list_sort(NULL, &extents, extent_cmp);
3785
3786 process:
3787         while (!list_empty(&extents)) {
3788                 em = list_entry(extents.next, struct extent_map, list);
3789
3790                 list_del_init(&em->list);
3791
3792                 /*
3793                  * If we had an error we just need to delete everybody from our
3794                  * private list.
3795                  */
3796                 if (ret) {
3797                         clear_em_logging(tree, em);
3798                         free_extent_map(em);
3799                         continue;
3800                 }
3801
3802                 write_unlock(&tree->lock);
3803
3804                 ret = log_one_extent(trans, inode, root, em, path, logged_list);
3805                 write_lock(&tree->lock);
3806                 clear_em_logging(tree, em);
3807                 free_extent_map(em);
3808         }
3809         WARN_ON(!list_empty(&extents));
3810         write_unlock(&tree->lock);
3811
3812         btrfs_release_path(path);
3813         return ret;
3814 }
3815
3816 /* log a single inode in the tree log.
3817  * At least one parent directory for this inode must exist in the tree
3818  * or be logged already.
3819  *
3820  * Any items from this inode changed by the current transaction are copied
3821  * to the log tree.  An extra reference is taken on any extents in this
3822  * file, allowing us to avoid a whole pile of corner cases around logging
3823  * blocks that have been removed from the tree.
3824  *
3825  * See LOG_INODE_ALL and related defines for a description of what inode_only
3826  * does.
3827  *
3828  * This handles both files and directories.
3829  */
3830 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
3831                              struct btrfs_root *root, struct inode *inode,
3832                              int inode_only)
3833 {
3834         struct btrfs_path *path;
3835         struct btrfs_path *dst_path;
3836         struct btrfs_key min_key;
3837         struct btrfs_key max_key;
3838         struct btrfs_root *log = root->log_root;
3839         struct extent_buffer *src = NULL;
3840         LIST_HEAD(logged_list);
3841         u64 last_extent = 0;
3842         int err = 0;
3843         int ret;
3844         int nritems;
3845         int ins_start_slot = 0;
3846         int ins_nr;
3847         bool fast_search = false;
3848         u64 ino = btrfs_ino(inode);
3849
3850         path = btrfs_alloc_path();
3851         if (!path)
3852                 return -ENOMEM;
3853         dst_path = btrfs_alloc_path();
3854         if (!dst_path) {
3855                 btrfs_free_path(path);
3856                 return -ENOMEM;
3857         }
3858
3859         min_key.objectid = ino;
3860         min_key.type = BTRFS_INODE_ITEM_KEY;
3861         min_key.offset = 0;
3862
3863         max_key.objectid = ino;
3864
3865
3866         /* today the code can only do partial logging of directories */
3867         if (S_ISDIR(inode->i_mode) ||
3868             (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3869                        &BTRFS_I(inode)->runtime_flags) &&
3870              inode_only == LOG_INODE_EXISTS))
3871                 max_key.type = BTRFS_XATTR_ITEM_KEY;
3872         else
3873                 max_key.type = (u8)-1;
3874         max_key.offset = (u64)-1;
3875
3876         /* Only run delayed items if we are a dir or a new file */
3877         if (S_ISDIR(inode->i_mode) ||
3878             BTRFS_I(inode)->generation > root->fs_info->last_trans_committed) {
3879                 ret = btrfs_commit_inode_delayed_items(trans, inode);
3880                 if (ret) {
3881                         btrfs_free_path(path);
3882                         btrfs_free_path(dst_path);
3883                         return ret;
3884                 }
3885         }
3886
3887         mutex_lock(&BTRFS_I(inode)->log_mutex);
3888
3889         btrfs_get_logged_extents(inode, &logged_list);
3890
3891         /*
3892          * a brute force approach to making sure we get the most uptodate
3893          * copies of everything.
3894          */
3895         if (S_ISDIR(inode->i_mode)) {
3896                 int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
3897
3898                 if (inode_only == LOG_INODE_EXISTS)
3899                         max_key_type = BTRFS_XATTR_ITEM_KEY;
3900                 ret = drop_objectid_items(trans, log, path, ino, max_key_type);
3901         } else {
3902                 if (test_and_clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3903                                        &BTRFS_I(inode)->runtime_flags)) {
3904                         clear_bit(BTRFS_INODE_COPY_EVERYTHING,
3905                                   &BTRFS_I(inode)->runtime_flags);
3906                         ret = btrfs_truncate_inode_items(trans, log,
3907                                                          inode, 0, 0);
3908                 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
3909                                               &BTRFS_I(inode)->runtime_flags) ||
3910                            inode_only == LOG_INODE_EXISTS) {
3911                         if (inode_only == LOG_INODE_ALL)
3912                                 fast_search = true;
3913                         max_key.type = BTRFS_XATTR_ITEM_KEY;
3914                         ret = drop_objectid_items(trans, log, path, ino,
3915                                                   max_key.type);
3916                 } else {
3917                         if (inode_only == LOG_INODE_ALL)
3918                                 fast_search = true;
3919                         ret = log_inode_item(trans, log, dst_path, inode);
3920                         if (ret) {
3921                                 err = ret;
3922                                 goto out_unlock;
3923                         }
3924                         goto log_extents;
3925                 }
3926
3927         }
3928         if (ret) {
3929                 err = ret;
3930                 goto out_unlock;
3931         }
3932         path->keep_locks = 1;
3933
3934         while (1) {
3935                 ins_nr = 0;
3936                 ret = btrfs_search_forward(root, &min_key,
3937                                            path, trans->transid);
3938                 if (ret != 0)
3939                         break;
3940 again:
3941                 /* note, ins_nr might be > 0 here, cleanup outside the loop */
3942                 if (min_key.objectid != ino)
3943                         break;
3944                 if (min_key.type > max_key.type)
3945                         break;
3946
3947                 src = path->nodes[0];
3948                 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
3949                         ins_nr++;
3950                         goto next_slot;
3951                 } else if (!ins_nr) {
3952                         ins_start_slot = path->slots[0];
3953                         ins_nr = 1;
3954                         goto next_slot;
3955                 }
3956
3957                 ret = copy_items(trans, inode, dst_path, path, &last_extent,
3958                                  ins_start_slot, ins_nr, inode_only);
3959                 if (ret < 0) {
3960                         err = ret;
3961                         goto out_unlock;
3962                 } if (ret) {
3963                         ins_nr = 0;
3964                         btrfs_release_path(path);
3965                         continue;
3966                 }
3967                 ins_nr = 1;
3968                 ins_start_slot = path->slots[0];
3969 next_slot:
3970
3971                 nritems = btrfs_header_nritems(path->nodes[0]);
3972                 path->slots[0]++;
3973                 if (path->slots[0] < nritems) {
3974                         btrfs_item_key_to_cpu(path->nodes[0], &min_key,
3975                                               path->slots[0]);
3976                         goto again;
3977                 }
3978                 if (ins_nr) {
3979                         ret = copy_items(trans, inode, dst_path, path,
3980                                          &last_extent, ins_start_slot,
3981                                          ins_nr, inode_only);
3982                         if (ret < 0) {
3983                                 err = ret;
3984                                 goto out_unlock;
3985                         }
3986                         ret = 0;
3987                         ins_nr = 0;
3988                 }
3989                 btrfs_release_path(path);
3990
3991                 if (min_key.offset < (u64)-1) {
3992                         min_key.offset++;
3993                 } else if (min_key.type < max_key.type) {
3994                         min_key.type++;
3995                         min_key.offset = 0;
3996                 } else {
3997                         break;
3998                 }
3999         }
4000         if (ins_nr) {
4001                 ret = copy_items(trans, inode, dst_path, path, &last_extent,
4002                                  ins_start_slot, ins_nr, inode_only);
4003                 if (ret < 0) {
4004                         err = ret;
4005                         goto out_unlock;
4006                 }
4007                 ret = 0;
4008                 ins_nr = 0;
4009         }
4010
4011 log_extents:
4012         btrfs_release_path(path);
4013         btrfs_release_path(dst_path);
4014         if (fast_search) {
4015                 ret = btrfs_log_changed_extents(trans, root, inode, dst_path,
4016                                                 &logged_list);
4017                 if (ret) {
4018                         err = ret;
4019                         goto out_unlock;
4020                 }
4021         } else if (inode_only == LOG_INODE_ALL) {
4022                 struct extent_map_tree *tree = &BTRFS_I(inode)->extent_tree;
4023                 struct extent_map *em, *n;
4024
4025                 write_lock(&tree->lock);
4026                 list_for_each_entry_safe(em, n, &tree->modified_extents, list)
4027                         list_del_init(&em->list);
4028                 write_unlock(&tree->lock);
4029         }
4030
4031         if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->i_mode)) {
4032                 ret = log_directory_changes(trans, root, inode, path, dst_path);
4033                 if (ret) {
4034                         err = ret;
4035                         goto out_unlock;
4036                 }
4037         }
4038         BTRFS_I(inode)->logged_trans = trans->transid;
4039         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->last_sub_trans;
4040 out_unlock:
4041         if (unlikely(err))
4042                 btrfs_put_logged_extents(&logged_list);
4043         else
4044                 btrfs_submit_logged_extents(&logged_list, log);
4045         mutex_unlock(&BTRFS_I(inode)->log_mutex);
4046
4047         btrfs_free_path(path);
4048         btrfs_free_path(dst_path);
4049         return err;
4050 }
4051
4052 /*
4053  * follow the dentry parent pointers up the chain and see if any
4054  * of the directories in it require a full commit before they can
4055  * be logged.  Returns zero if nothing special needs to be done or 1 if
4056  * a full commit is required.
4057  */
4058 static noinline int check_parent_dirs_for_sync(struct btrfs_trans_handle *trans,
4059                                                struct inode *inode,
4060                                                struct dentry *parent,
4061                                                struct super_block *sb,
4062                                                u64 last_committed)
4063 {
4064         int ret = 0;
4065         struct btrfs_root *root;
4066         struct dentry *old_parent = NULL;
4067         struct inode *orig_inode = inode;
4068
4069         /*
4070          * for regular files, if its inode is already on disk, we don't
4071          * have to worry about the parents at all.  This is because
4072          * we can use the last_unlink_trans field to record renames
4073          * and other fun in this file.
4074          */
4075         if (S_ISREG(inode->i_mode) &&
4076             BTRFS_I(inode)->generation <= last_committed &&
4077             BTRFS_I(inode)->last_unlink_trans <= last_committed)
4078                         goto out;
4079
4080         if (!S_ISDIR(inode->i_mode)) {
4081                 if (!parent || !parent->d_inode || sb != parent->d_inode->i_sb)
4082                         goto out;
4083                 inode = parent->d_inode;
4084         }
4085
4086         while (1) {
4087                 /*
4088                  * If we are logging a directory then we start with our inode,
4089                  * not our parents inode, so we need to skipp setting the
4090                  * logged_trans so that further down in the log code we don't
4091                  * think this inode has already been logged.
4092                  */
4093                 if (inode != orig_inode)
4094                         BTRFS_I(inode)->logged_trans = trans->transid;
4095                 smp_mb();
4096
4097                 if (BTRFS_I(inode)->last_unlink_trans > last_committed) {
4098                         root = BTRFS_I(inode)->root;
4099
4100                         /*
4101                          * make sure any commits to the log are forced
4102                          * to be full commits
4103                          */
4104                         root->fs_info->last_trans_log_full_commit =
4105                                 trans->transid;
4106                         ret = 1;
4107                         break;
4108                 }
4109
4110                 if (!parent || !parent->d_inode || sb != parent->d_inode->i_sb)
4111                         break;
4112
4113                 if (IS_ROOT(parent))
4114                         break;
4115
4116                 parent = dget_parent(parent);
4117                 dput(old_parent);
4118                 old_parent = parent;
4119                 inode = parent->d_inode;
4120
4121         }
4122         dput(old_parent);
4123 out:
4124         return ret;
4125 }
4126
4127 /*
4128  * helper function around btrfs_log_inode to make sure newly created
4129  * parent directories also end up in the log.  A minimal inode and backref
4130  * only logging is done of any parent directories that are older than
4131  * the last committed transaction
4132  */
4133 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
4134                                   struct btrfs_root *root, struct inode *inode,
4135                                   struct dentry *parent, int exists_only,
4136                                   struct btrfs_log_ctx *ctx)
4137 {
4138         int inode_only = exists_only ? LOG_INODE_EXISTS : LOG_INODE_ALL;
4139         struct super_block *sb;
4140         struct dentry *old_parent = NULL;
4141         int ret = 0;
4142         u64 last_committed = root->fs_info->last_trans_committed;
4143
4144         sb = inode->i_sb;
4145
4146         if (btrfs_test_opt(root, NOTREELOG)) {
4147                 ret = 1;
4148                 goto end_no_trans;
4149         }
4150
4151         if (root->fs_info->last_trans_log_full_commit >
4152             root->fs_info->last_trans_committed) {
4153                 ret = 1;
4154                 goto end_no_trans;
4155         }
4156
4157         if (root != BTRFS_I(inode)->root ||
4158             btrfs_root_refs(&root->root_item) == 0) {
4159                 ret = 1;
4160                 goto end_no_trans;
4161         }
4162
4163         ret = check_parent_dirs_for_sync(trans, inode, parent,
4164                                          sb, last_committed);
4165         if (ret)
4166                 goto end_no_trans;
4167
4168         if (btrfs_inode_in_log(inode, trans->transid)) {
4169                 ret = BTRFS_NO_LOG_SYNC;
4170                 goto end_no_trans;
4171         }
4172
4173         ret = start_log_trans(trans, root, ctx);
4174         if (ret)
4175                 goto end_no_trans;
4176
4177         ret = btrfs_log_inode(trans, root, inode, inode_only);
4178         if (ret)
4179                 goto end_trans;
4180
4181         /*
4182          * for regular files, if its inode is already on disk, we don't
4183          * have to worry about the parents at all.  This is because
4184          * we can use the last_unlink_trans field to record renames
4185          * and other fun in this file.
4186          */
4187         if (S_ISREG(inode->i_mode) &&
4188             BTRFS_I(inode)->generation <= last_committed &&
4189             BTRFS_I(inode)->last_unlink_trans <= last_committed) {
4190                 ret = 0;
4191                 goto end_trans;
4192         }
4193
4194         inode_only = LOG_INODE_EXISTS;
4195         while (1) {
4196                 if (!parent || !parent->d_inode || sb != parent->d_inode->i_sb)
4197                         break;
4198
4199                 inode = parent->d_inode;
4200                 if (root != BTRFS_I(inode)->root)
4201                         break;
4202
4203                 if (BTRFS_I(inode)->generation >
4204                     root->fs_info->last_trans_committed) {
4205                         ret = btrfs_log_inode(trans, root, inode, inode_only);
4206                         if (ret)
4207                                 goto end_trans;
4208                 }
4209                 if (IS_ROOT(parent))
4210                         break;
4211
4212                 parent = dget_parent(parent);
4213                 dput(old_parent);
4214                 old_parent = parent;
4215         }
4216         ret = 0;
4217 end_trans:
4218         dput(old_parent);
4219         if (ret < 0) {
4220                 root->fs_info->last_trans_log_full_commit = trans->transid;
4221                 ret = 1;
4222         }
4223
4224         if (ret)
4225                 btrfs_remove_log_ctx(root, ctx);
4226         btrfs_end_log_trans(root);
4227 end_no_trans:
4228         return ret;
4229 }
4230
4231 /*
4232  * it is not safe to log dentry if the chunk root has added new
4233  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
4234  * If this returns 1, you must commit the transaction to safely get your
4235  * data on disk.
4236  */
4237 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
4238                           struct btrfs_root *root, struct dentry *dentry,
4239                           struct btrfs_log_ctx *ctx)
4240 {
4241         struct dentry *parent = dget_parent(dentry);
4242         int ret;
4243
4244         ret = btrfs_log_inode_parent(trans, root, dentry->d_inode, parent,
4245                                      0, ctx);
4246         dput(parent);
4247
4248         return ret;
4249 }
4250
4251 /*
4252  * should be called during mount to recover any replay any log trees
4253  * from the FS
4254  */
4255 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
4256 {
4257         int ret;
4258         struct btrfs_path *path;
4259         struct btrfs_trans_handle *trans;
4260         struct btrfs_key key;
4261         struct btrfs_key found_key;
4262         struct btrfs_key tmp_key;
4263         struct btrfs_root *log;
4264         struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
4265         struct walk_control wc = {
4266                 .process_func = process_one_buffer,
4267                 .stage = 0,
4268         };
4269
4270         path = btrfs_alloc_path();
4271         if (!path)
4272                 return -ENOMEM;
4273
4274         fs_info->log_root_recovering = 1;
4275
4276         trans = btrfs_start_transaction(fs_info->tree_root, 0);
4277         if (IS_ERR(trans)) {
4278                 ret = PTR_ERR(trans);
4279                 goto error;
4280         }
4281
4282         wc.trans = trans;
4283         wc.pin = 1;
4284
4285         ret = walk_log_tree(trans, log_root_tree, &wc);
4286         if (ret) {
4287                 btrfs_error(fs_info, ret, "Failed to pin buffers while "
4288                             "recovering log root tree.");
4289                 goto error;
4290         }
4291
4292 again:
4293         key.objectid = BTRFS_TREE_LOG_OBJECTID;
4294         key.offset = (u64)-1;
4295         btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
4296
4297         while (1) {
4298                 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
4299
4300                 if (ret < 0) {
4301                         btrfs_error(fs_info, ret,
4302                                     "Couldn't find tree log root.");
4303                         goto error;
4304                 }
4305                 if (ret > 0) {
4306                         if (path->slots[0] == 0)
4307                                 break;
4308                         path->slots[0]--;
4309                 }
4310                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
4311                                       path->slots[0]);
4312                 btrfs_release_path(path);
4313                 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4314                         break;
4315
4316                 log = btrfs_read_fs_root(log_root_tree, &found_key);
4317                 if (IS_ERR(log)) {
4318                         ret = PTR_ERR(log);
4319                         btrfs_error(fs_info, ret,
4320                                     "Couldn't read tree log root.");
4321                         goto error;
4322                 }
4323
4324                 tmp_key.objectid = found_key.offset;
4325                 tmp_key.type = BTRFS_ROOT_ITEM_KEY;
4326                 tmp_key.offset = (u64)-1;
4327
4328                 wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
4329                 if (IS_ERR(wc.replay_dest)) {
4330                         ret = PTR_ERR(wc.replay_dest);
4331                         free_extent_buffer(log->node);
4332                         free_extent_buffer(log->commit_root);
4333                         kfree(log);
4334                         btrfs_error(fs_info, ret, "Couldn't read target root "
4335                                     "for tree log recovery.");
4336                         goto error;
4337                 }
4338
4339                 wc.replay_dest->log_root = log;
4340                 btrfs_record_root_in_trans(trans, wc.replay_dest);
4341                 ret = walk_log_tree(trans, log, &wc);
4342
4343                 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
4344                         ret = fixup_inode_link_counts(trans, wc.replay_dest,
4345                                                       path);
4346                 }
4347
4348                 key.offset = found_key.offset - 1;
4349                 wc.replay_dest->log_root = NULL;
4350                 free_extent_buffer(log->node);
4351                 free_extent_buffer(log->commit_root);
4352                 kfree(log);
4353
4354                 if (ret)
4355                         goto error;
4356
4357                 if (found_key.offset == 0)
4358                         break;
4359         }
4360         btrfs_release_path(path);
4361
4362         /* step one is to pin it all, step two is to replay just inodes */
4363         if (wc.pin) {
4364                 wc.pin = 0;
4365                 wc.process_func = replay_one_buffer;
4366                 wc.stage = LOG_WALK_REPLAY_INODES;
4367                 goto again;
4368         }
4369         /* step three is to replay everything */
4370         if (wc.stage < LOG_WALK_REPLAY_ALL) {
4371                 wc.stage++;
4372                 goto again;
4373         }
4374
4375         btrfs_free_path(path);
4376
4377         /* step 4: commit the transaction, which also unpins the blocks */
4378         ret = btrfs_commit_transaction(trans, fs_info->tree_root);
4379         if (ret)
4380                 return ret;
4381
4382         free_extent_buffer(log_root_tree->node);
4383         log_root_tree->log_root = NULL;
4384         fs_info->log_root_recovering = 0;
4385         kfree(log_root_tree);
4386
4387         return 0;
4388 error:
4389         if (wc.trans)
4390                 btrfs_end_transaction(wc.trans, fs_info->tree_root);
4391         btrfs_free_path(path);
4392         return ret;
4393 }
4394
4395 /*
4396  * there are some corner cases where we want to force a full
4397  * commit instead of allowing a directory to be logged.
4398  *
4399  * They revolve around files there were unlinked from the directory, and
4400  * this function updates the parent directory so that a full commit is
4401  * properly done if it is fsync'd later after the unlinks are done.
4402  */
4403 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
4404                              struct inode *dir, struct inode *inode,
4405                              int for_rename)
4406 {
4407         /*
4408          * when we're logging a file, if it hasn't been renamed
4409          * or unlinked, and its inode is fully committed on disk,
4410          * we don't have to worry about walking up the directory chain
4411          * to log its parents.
4412          *
4413          * So, we use the last_unlink_trans field to put this transid
4414          * into the file.  When the file is logged we check it and
4415          * don't log the parents if the file is fully on disk.
4416          */
4417         if (S_ISREG(inode->i_mode))
4418                 BTRFS_I(inode)->last_unlink_trans = trans->transid;
4419
4420         /*
4421          * if this directory was already logged any new
4422          * names for this file/dir will get recorded
4423          */
4424         smp_mb();
4425         if (BTRFS_I(dir)->logged_trans == trans->transid)
4426                 return;
4427
4428         /*
4429          * if the inode we're about to unlink was logged,
4430          * the log will be properly updated for any new names
4431          */
4432         if (BTRFS_I(inode)->logged_trans == trans->transid)
4433                 return;
4434
4435         /*
4436          * when renaming files across directories, if the directory
4437          * there we're unlinking from gets fsync'd later on, there's
4438          * no way to find the destination directory later and fsync it
4439          * properly.  So, we have to be conservative and force commits
4440          * so the new name gets discovered.
4441          */
4442         if (for_rename)
4443                 goto record;
4444
4445         /* we can safely do the unlink without any special recording */
4446         return;
4447
4448 record:
4449         BTRFS_I(dir)->last_unlink_trans = trans->transid;
4450 }
4451
4452 /*
4453  * Call this after adding a new name for a file and it will properly
4454  * update the log to reflect the new name.
4455  *
4456  * It will return zero if all goes well, and it will return 1 if a
4457  * full transaction commit is required.
4458  */
4459 int btrfs_log_new_name(struct btrfs_trans_handle *trans,
4460                         struct inode *inode, struct inode *old_dir,
4461                         struct dentry *parent)
4462 {
4463         struct btrfs_root * root = BTRFS_I(inode)->root;
4464
4465         /*
4466          * this will force the logging code to walk the dentry chain
4467          * up for the file
4468          */
4469         if (S_ISREG(inode->i_mode))
4470                 BTRFS_I(inode)->last_unlink_trans = trans->transid;
4471
4472         /*
4473          * if this inode hasn't been logged and directory we're renaming it
4474          * from hasn't been logged, we don't need to log it
4475          */
4476         if (BTRFS_I(inode)->logged_trans <=
4477             root->fs_info->last_trans_committed &&
4478             (!old_dir || BTRFS_I(old_dir)->logged_trans <=
4479                     root->fs_info->last_trans_committed))
4480                 return 0;
4481
4482         return btrfs_log_inode_parent(trans, root, inode, parent, 1, NULL);
4483 }
4484