ext4: force inode writes when nfsd calls commit_metadata()
[platform/kernel/linux-exynos.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 "tree-log.h"
24 #include "disk-io.h"
25 #include "locking.h"
26 #include "print-tree.h"
27 #include "backref.h"
28 #include "hash.h"
29 #include "compression.h"
30 #include "qgroup.h"
31 #include "inode-map.h"
32
33 /* magic values for the inode_only field in btrfs_log_inode:
34  *
35  * LOG_INODE_ALL means to log everything
36  * LOG_INODE_EXISTS means to log just enough to recreate the inode
37  * during log replay
38  */
39 #define LOG_INODE_ALL 0
40 #define LOG_INODE_EXISTS 1
41 #define LOG_OTHER_INODE 2
42
43 /*
44  * directory trouble cases
45  *
46  * 1) on rename or unlink, if the inode being unlinked isn't in the fsync
47  * log, we must force a full commit before doing an fsync of the directory
48  * where the unlink was done.
49  * ---> record transid of last unlink/rename per directory
50  *
51  * mkdir foo/some_dir
52  * normal commit
53  * rename foo/some_dir foo2/some_dir
54  * mkdir foo/some_dir
55  * fsync foo/some_dir/some_file
56  *
57  * The fsync above will unlink the original some_dir without recording
58  * it in its new location (foo2).  After a crash, some_dir will be gone
59  * unless the fsync of some_file forces a full commit
60  *
61  * 2) we must log any new names for any file or dir that is in the fsync
62  * log. ---> check inode while renaming/linking.
63  *
64  * 2a) we must log any new names for any file or dir during rename
65  * when the directory they are being removed from was logged.
66  * ---> check inode and old parent dir during rename
67  *
68  *  2a is actually the more important variant.  With the extra logging
69  *  a crash might unlink the old name without recreating the new one
70  *
71  * 3) after a crash, we must go through any directories with a link count
72  * of zero and redo the rm -rf
73  *
74  * mkdir f1/foo
75  * normal commit
76  * rm -rf f1/foo
77  * fsync(f1)
78  *
79  * The directory f1 was fully removed from the FS, but fsync was never
80  * called on f1, only its parent dir.  After a crash the rm -rf must
81  * be replayed.  This must be able to recurse down the entire
82  * directory tree.  The inode link count fixup code takes care of the
83  * ugly details.
84  */
85
86 /*
87  * stages for the tree walking.  The first
88  * stage (0) is to only pin down the blocks we find
89  * the second stage (1) is to make sure that all the inodes
90  * we find in the log are created in the subvolume.
91  *
92  * The last stage is to deal with directories and links and extents
93  * and all the other fun semantics
94  */
95 #define LOG_WALK_PIN_ONLY 0
96 #define LOG_WALK_REPLAY_INODES 1
97 #define LOG_WALK_REPLAY_DIR_INDEX 2
98 #define LOG_WALK_REPLAY_ALL 3
99
100 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
101                            struct btrfs_root *root, struct btrfs_inode *inode,
102                            int inode_only,
103                            const loff_t start,
104                            const loff_t end,
105                            struct btrfs_log_ctx *ctx);
106 static int link_to_fixup_dir(struct btrfs_trans_handle *trans,
107                              struct btrfs_root *root,
108                              struct btrfs_path *path, u64 objectid);
109 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
110                                        struct btrfs_root *root,
111                                        struct btrfs_root *log,
112                                        struct btrfs_path *path,
113                                        u64 dirid, int del_all);
114
115 /*
116  * tree logging is a special write ahead log used to make sure that
117  * fsyncs and O_SYNCs can happen without doing full tree commits.
118  *
119  * Full tree commits are expensive because they require commonly
120  * modified blocks to be recowed, creating many dirty pages in the
121  * extent tree an 4x-6x higher write load than ext3.
122  *
123  * Instead of doing a tree commit on every fsync, we use the
124  * key ranges and transaction ids to find items for a given file or directory
125  * that have changed in this transaction.  Those items are copied into
126  * a special tree (one per subvolume root), that tree is written to disk
127  * and then the fsync is considered complete.
128  *
129  * After a crash, items are copied out of the log-tree back into the
130  * subvolume tree.  Any file data extents found are recorded in the extent
131  * allocation tree, and the log-tree freed.
132  *
133  * The log tree is read three times, once to pin down all the extents it is
134  * using in ram and once, once to create all the inodes logged in the tree
135  * and once to do all the other items.
136  */
137
138 /*
139  * start a sub transaction and setup the log tree
140  * this increments the log tree writer count to make the people
141  * syncing the tree wait for us to finish
142  */
143 static int start_log_trans(struct btrfs_trans_handle *trans,
144                            struct btrfs_root *root,
145                            struct btrfs_log_ctx *ctx)
146 {
147         struct btrfs_fs_info *fs_info = root->fs_info;
148         int ret = 0;
149
150         mutex_lock(&root->log_mutex);
151
152         if (root->log_root) {
153                 if (btrfs_need_log_full_commit(fs_info, trans)) {
154                         ret = -EAGAIN;
155                         goto out;
156                 }
157
158                 if (!root->log_start_pid) {
159                         clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
160                         root->log_start_pid = current->pid;
161                 } else if (root->log_start_pid != current->pid) {
162                         set_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
163                 }
164         } else {
165                 mutex_lock(&fs_info->tree_log_mutex);
166                 if (!fs_info->log_root_tree)
167                         ret = btrfs_init_log_root_tree(trans, fs_info);
168                 mutex_unlock(&fs_info->tree_log_mutex);
169                 if (ret)
170                         goto out;
171
172                 ret = btrfs_add_log_tree(trans, root);
173                 if (ret)
174                         goto out;
175
176                 clear_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state);
177                 root->log_start_pid = current->pid;
178         }
179
180         atomic_inc(&root->log_batch);
181         atomic_inc(&root->log_writers);
182         if (ctx) {
183                 int index = root->log_transid % 2;
184                 list_add_tail(&ctx->list, &root->log_ctxs[index]);
185                 ctx->log_transid = root->log_transid;
186         }
187
188 out:
189         mutex_unlock(&root->log_mutex);
190         return ret;
191 }
192
193 /*
194  * returns 0 if there was a log transaction running and we were able
195  * to join, or returns -ENOENT if there were not transactions
196  * in progress
197  */
198 static int join_running_log_trans(struct btrfs_root *root)
199 {
200         int ret = -ENOENT;
201
202         smp_mb();
203         if (!root->log_root)
204                 return -ENOENT;
205
206         mutex_lock(&root->log_mutex);
207         if (root->log_root) {
208                 ret = 0;
209                 atomic_inc(&root->log_writers);
210         }
211         mutex_unlock(&root->log_mutex);
212         return ret;
213 }
214
215 /*
216  * This either makes the current running log transaction wait
217  * until you call btrfs_end_log_trans() or it makes any future
218  * log transactions wait until you call btrfs_end_log_trans()
219  */
220 int btrfs_pin_log_trans(struct btrfs_root *root)
221 {
222         int ret = -ENOENT;
223
224         mutex_lock(&root->log_mutex);
225         atomic_inc(&root->log_writers);
226         mutex_unlock(&root->log_mutex);
227         return ret;
228 }
229
230 /*
231  * indicate we're done making changes to the log tree
232  * and wake up anyone waiting to do a sync
233  */
234 void btrfs_end_log_trans(struct btrfs_root *root)
235 {
236         if (atomic_dec_and_test(&root->log_writers)) {
237                 /*
238                  * Implicit memory barrier after atomic_dec_and_test
239                  */
240                 if (waitqueue_active(&root->log_writer_wait))
241                         wake_up(&root->log_writer_wait);
242         }
243 }
244
245
246 /*
247  * the walk control struct is used to pass state down the chain when
248  * processing the log tree.  The stage field tells us which part
249  * of the log tree processing we are currently doing.  The others
250  * are state fields used for that specific part
251  */
252 struct walk_control {
253         /* should we free the extent on disk when done?  This is used
254          * at transaction commit time while freeing a log tree
255          */
256         int free;
257
258         /* should we write out the extent buffer?  This is used
259          * while flushing the log tree to disk during a sync
260          */
261         int write;
262
263         /* should we wait for the extent buffer io to finish?  Also used
264          * while flushing the log tree to disk for a sync
265          */
266         int wait;
267
268         /* pin only walk, we record which extents on disk belong to the
269          * log trees
270          */
271         int pin;
272
273         /* what stage of the replay code we're currently in */
274         int stage;
275
276         /*
277          * Ignore any items from the inode currently being processed. Needs
278          * to be set every time we find a BTRFS_INODE_ITEM_KEY and we are in
279          * the LOG_WALK_REPLAY_INODES stage.
280          */
281         bool ignore_cur_inode;
282
283         /* the root we are currently replaying */
284         struct btrfs_root *replay_dest;
285
286         /* the trans handle for the current replay */
287         struct btrfs_trans_handle *trans;
288
289         /* the function that gets used to process blocks we find in the
290          * tree.  Note the extent_buffer might not be up to date when it is
291          * passed in, and it must be checked or read if you need the data
292          * inside it
293          */
294         int (*process_func)(struct btrfs_root *log, struct extent_buffer *eb,
295                             struct walk_control *wc, u64 gen);
296 };
297
298 /*
299  * process_func used to pin down extents, write them or wait on them
300  */
301 static int process_one_buffer(struct btrfs_root *log,
302                               struct extent_buffer *eb,
303                               struct walk_control *wc, u64 gen)
304 {
305         struct btrfs_fs_info *fs_info = log->fs_info;
306         int ret = 0;
307
308         /*
309          * If this fs is mixed then we need to be able to process the leaves to
310          * pin down any logged extents, so we have to read the block.
311          */
312         if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
313                 ret = btrfs_read_buffer(eb, gen);
314                 if (ret)
315                         return ret;
316         }
317
318         if (wc->pin)
319                 ret = btrfs_pin_extent_for_log_replay(fs_info, eb->start,
320                                                       eb->len);
321
322         if (!ret && btrfs_buffer_uptodate(eb, gen, 0)) {
323                 if (wc->pin && btrfs_header_level(eb) == 0)
324                         ret = btrfs_exclude_logged_extents(fs_info, eb);
325                 if (wc->write)
326                         btrfs_write_tree_block(eb);
327                 if (wc->wait)
328                         btrfs_wait_tree_block_writeback(eb);
329         }
330         return ret;
331 }
332
333 /*
334  * Item overwrite used by replay and tree logging.  eb, slot and key all refer
335  * to the src data we are copying out.
336  *
337  * root is the tree we are copying into, and path is a scratch
338  * path for use in this function (it should be released on entry and
339  * will be released on exit).
340  *
341  * If the key is already in the destination tree the existing item is
342  * overwritten.  If the existing item isn't big enough, it is extended.
343  * If it is too large, it is truncated.
344  *
345  * If the key isn't in the destination yet, a new item is inserted.
346  */
347 static noinline int overwrite_item(struct btrfs_trans_handle *trans,
348                                    struct btrfs_root *root,
349                                    struct btrfs_path *path,
350                                    struct extent_buffer *eb, int slot,
351                                    struct btrfs_key *key)
352 {
353         struct btrfs_fs_info *fs_info = root->fs_info;
354         int ret;
355         u32 item_size;
356         u64 saved_i_size = 0;
357         int save_old_i_size = 0;
358         unsigned long src_ptr;
359         unsigned long dst_ptr;
360         int overwrite_root = 0;
361         bool inode_item = key->type == BTRFS_INODE_ITEM_KEY;
362
363         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
364                 overwrite_root = 1;
365
366         item_size = btrfs_item_size_nr(eb, slot);
367         src_ptr = btrfs_item_ptr_offset(eb, slot);
368
369         /* look for the key in the destination tree */
370         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
371         if (ret < 0)
372                 return ret;
373
374         if (ret == 0) {
375                 char *src_copy;
376                 char *dst_copy;
377                 u32 dst_size = btrfs_item_size_nr(path->nodes[0],
378                                                   path->slots[0]);
379                 if (dst_size != item_size)
380                         goto insert;
381
382                 if (item_size == 0) {
383                         btrfs_release_path(path);
384                         return 0;
385                 }
386                 dst_copy = kmalloc(item_size, GFP_NOFS);
387                 src_copy = kmalloc(item_size, GFP_NOFS);
388                 if (!dst_copy || !src_copy) {
389                         btrfs_release_path(path);
390                         kfree(dst_copy);
391                         kfree(src_copy);
392                         return -ENOMEM;
393                 }
394
395                 read_extent_buffer(eb, src_copy, src_ptr, item_size);
396
397                 dst_ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
398                 read_extent_buffer(path->nodes[0], dst_copy, dst_ptr,
399                                    item_size);
400                 ret = memcmp(dst_copy, src_copy, item_size);
401
402                 kfree(dst_copy);
403                 kfree(src_copy);
404                 /*
405                  * they have the same contents, just return, this saves
406                  * us from cowing blocks in the destination tree and doing
407                  * extra writes that may not have been done by a previous
408                  * sync
409                  */
410                 if (ret == 0) {
411                         btrfs_release_path(path);
412                         return 0;
413                 }
414
415                 /*
416                  * We need to load the old nbytes into the inode so when we
417                  * replay the extents we've logged we get the right nbytes.
418                  */
419                 if (inode_item) {
420                         struct btrfs_inode_item *item;
421                         u64 nbytes;
422                         u32 mode;
423
424                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
425                                               struct btrfs_inode_item);
426                         nbytes = btrfs_inode_nbytes(path->nodes[0], item);
427                         item = btrfs_item_ptr(eb, slot,
428                                               struct btrfs_inode_item);
429                         btrfs_set_inode_nbytes(eb, item, nbytes);
430
431                         /*
432                          * If this is a directory we need to reset the i_size to
433                          * 0 so that we can set it up properly when replaying
434                          * the rest of the items in this log.
435                          */
436                         mode = btrfs_inode_mode(eb, item);
437                         if (S_ISDIR(mode))
438                                 btrfs_set_inode_size(eb, item, 0);
439                 }
440         } else if (inode_item) {
441                 struct btrfs_inode_item *item;
442                 u32 mode;
443
444                 /*
445                  * New inode, set nbytes to 0 so that the nbytes comes out
446                  * properly when we replay the extents.
447                  */
448                 item = btrfs_item_ptr(eb, slot, struct btrfs_inode_item);
449                 btrfs_set_inode_nbytes(eb, item, 0);
450
451                 /*
452                  * If this is a directory we need to reset the i_size to 0 so
453                  * that we can set it up properly when replaying the rest of
454                  * the items in this log.
455                  */
456                 mode = btrfs_inode_mode(eb, item);
457                 if (S_ISDIR(mode))
458                         btrfs_set_inode_size(eb, item, 0);
459         }
460 insert:
461         btrfs_release_path(path);
462         /* try to insert the key into the destination tree */
463         path->skip_release_on_error = 1;
464         ret = btrfs_insert_empty_item(trans, root, path,
465                                       key, item_size);
466         path->skip_release_on_error = 0;
467
468         /* make sure any existing item is the correct size */
469         if (ret == -EEXIST || ret == -EOVERFLOW) {
470                 u32 found_size;
471                 found_size = btrfs_item_size_nr(path->nodes[0],
472                                                 path->slots[0]);
473                 if (found_size > item_size)
474                         btrfs_truncate_item(fs_info, path, item_size, 1);
475                 else if (found_size < item_size)
476                         btrfs_extend_item(fs_info, path,
477                                           item_size - found_size);
478         } else if (ret) {
479                 return ret;
480         }
481         dst_ptr = btrfs_item_ptr_offset(path->nodes[0],
482                                         path->slots[0]);
483
484         /* don't overwrite an existing inode if the generation number
485          * was logged as zero.  This is done when the tree logging code
486          * is just logging an inode to make sure it exists after recovery.
487          *
488          * Also, don't overwrite i_size on directories during replay.
489          * log replay inserts and removes directory items based on the
490          * state of the tree found in the subvolume, and i_size is modified
491          * as it goes
492          */
493         if (key->type == BTRFS_INODE_ITEM_KEY && ret == -EEXIST) {
494                 struct btrfs_inode_item *src_item;
495                 struct btrfs_inode_item *dst_item;
496
497                 src_item = (struct btrfs_inode_item *)src_ptr;
498                 dst_item = (struct btrfs_inode_item *)dst_ptr;
499
500                 if (btrfs_inode_generation(eb, src_item) == 0) {
501                         struct extent_buffer *dst_eb = path->nodes[0];
502                         const u64 ino_size = btrfs_inode_size(eb, src_item);
503
504                         /*
505                          * For regular files an ino_size == 0 is used only when
506                          * logging that an inode exists, as part of a directory
507                          * fsync, and the inode wasn't fsynced before. In this
508                          * case don't set the size of the inode in the fs/subvol
509                          * tree, otherwise we would be throwing valid data away.
510                          */
511                         if (S_ISREG(btrfs_inode_mode(eb, src_item)) &&
512                             S_ISREG(btrfs_inode_mode(dst_eb, dst_item)) &&
513                             ino_size != 0) {
514                                 struct btrfs_map_token token;
515
516                                 btrfs_init_map_token(&token);
517                                 btrfs_set_token_inode_size(dst_eb, dst_item,
518                                                            ino_size, &token);
519                         }
520                         goto no_copy;
521                 }
522
523                 if (overwrite_root &&
524                     S_ISDIR(btrfs_inode_mode(eb, src_item)) &&
525                     S_ISDIR(btrfs_inode_mode(path->nodes[0], dst_item))) {
526                         save_old_i_size = 1;
527                         saved_i_size = btrfs_inode_size(path->nodes[0],
528                                                         dst_item);
529                 }
530         }
531
532         copy_extent_buffer(path->nodes[0], eb, dst_ptr,
533                            src_ptr, item_size);
534
535         if (save_old_i_size) {
536                 struct btrfs_inode_item *dst_item;
537                 dst_item = (struct btrfs_inode_item *)dst_ptr;
538                 btrfs_set_inode_size(path->nodes[0], dst_item, saved_i_size);
539         }
540
541         /* make sure the generation is filled in */
542         if (key->type == BTRFS_INODE_ITEM_KEY) {
543                 struct btrfs_inode_item *dst_item;
544                 dst_item = (struct btrfs_inode_item *)dst_ptr;
545                 if (btrfs_inode_generation(path->nodes[0], dst_item) == 0) {
546                         btrfs_set_inode_generation(path->nodes[0], dst_item,
547                                                    trans->transid);
548                 }
549         }
550 no_copy:
551         btrfs_mark_buffer_dirty(path->nodes[0]);
552         btrfs_release_path(path);
553         return 0;
554 }
555
556 /*
557  * simple helper to read an inode off the disk from a given root
558  * This can only be called for subvolume roots and not for the log
559  */
560 static noinline struct inode *read_one_inode(struct btrfs_root *root,
561                                              u64 objectid)
562 {
563         struct btrfs_key key;
564         struct inode *inode;
565
566         key.objectid = objectid;
567         key.type = BTRFS_INODE_ITEM_KEY;
568         key.offset = 0;
569         inode = btrfs_iget(root->fs_info->sb, &key, root, NULL);
570         if (IS_ERR(inode)) {
571                 inode = NULL;
572         } else if (is_bad_inode(inode)) {
573                 iput(inode);
574                 inode = NULL;
575         }
576         return inode;
577 }
578
579 /* replays a single extent in 'eb' at 'slot' with 'key' into the
580  * subvolume 'root'.  path is released on entry and should be released
581  * on exit.
582  *
583  * extents in the log tree have not been allocated out of the extent
584  * tree yet.  So, this completes the allocation, taking a reference
585  * as required if the extent already exists or creating a new extent
586  * if it isn't in the extent allocation tree yet.
587  *
588  * The extent is inserted into the file, dropping any existing extents
589  * from the file that overlap the new one.
590  */
591 static noinline int replay_one_extent(struct btrfs_trans_handle *trans,
592                                       struct btrfs_root *root,
593                                       struct btrfs_path *path,
594                                       struct extent_buffer *eb, int slot,
595                                       struct btrfs_key *key)
596 {
597         struct btrfs_fs_info *fs_info = root->fs_info;
598         int found_type;
599         u64 extent_end;
600         u64 start = key->offset;
601         u64 nbytes = 0;
602         struct btrfs_file_extent_item *item;
603         struct inode *inode = NULL;
604         unsigned long size;
605         int ret = 0;
606
607         item = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
608         found_type = btrfs_file_extent_type(eb, item);
609
610         if (found_type == BTRFS_FILE_EXTENT_REG ||
611             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
612                 nbytes = btrfs_file_extent_num_bytes(eb, item);
613                 extent_end = start + nbytes;
614
615                 /*
616                  * We don't add to the inodes nbytes if we are prealloc or a
617                  * hole.
618                  */
619                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
620                         nbytes = 0;
621         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
622                 size = btrfs_file_extent_inline_len(eb, slot, item);
623                 nbytes = btrfs_file_extent_ram_bytes(eb, item);
624                 extent_end = ALIGN(start + size,
625                                    fs_info->sectorsize);
626         } else {
627                 ret = 0;
628                 goto out;
629         }
630
631         inode = read_one_inode(root, key->objectid);
632         if (!inode) {
633                 ret = -EIO;
634                 goto out;
635         }
636
637         /*
638          * first check to see if we already have this extent in the
639          * file.  This must be done before the btrfs_drop_extents run
640          * so we don't try to drop this extent.
641          */
642         ret = btrfs_lookup_file_extent(trans, root, path,
643                         btrfs_ino(BTRFS_I(inode)), start, 0);
644
645         if (ret == 0 &&
646             (found_type == BTRFS_FILE_EXTENT_REG ||
647              found_type == BTRFS_FILE_EXTENT_PREALLOC)) {
648                 struct btrfs_file_extent_item cmp1;
649                 struct btrfs_file_extent_item cmp2;
650                 struct btrfs_file_extent_item *existing;
651                 struct extent_buffer *leaf;
652
653                 leaf = path->nodes[0];
654                 existing = btrfs_item_ptr(leaf, path->slots[0],
655                                           struct btrfs_file_extent_item);
656
657                 read_extent_buffer(eb, &cmp1, (unsigned long)item,
658                                    sizeof(cmp1));
659                 read_extent_buffer(leaf, &cmp2, (unsigned long)existing,
660                                    sizeof(cmp2));
661
662                 /*
663                  * we already have a pointer to this exact extent,
664                  * we don't have to do anything
665                  */
666                 if (memcmp(&cmp1, &cmp2, sizeof(cmp1)) == 0) {
667                         btrfs_release_path(path);
668                         goto out;
669                 }
670         }
671         btrfs_release_path(path);
672
673         /* drop any overlapping extents */
674         ret = btrfs_drop_extents(trans, root, inode, start, extent_end, 1);
675         if (ret)
676                 goto out;
677
678         if (found_type == BTRFS_FILE_EXTENT_REG ||
679             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
680                 u64 offset;
681                 unsigned long dest_offset;
682                 struct btrfs_key ins;
683
684                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0 &&
685                     btrfs_fs_incompat(fs_info, NO_HOLES))
686                         goto update_inode;
687
688                 ret = btrfs_insert_empty_item(trans, root, path, key,
689                                               sizeof(*item));
690                 if (ret)
691                         goto out;
692                 dest_offset = btrfs_item_ptr_offset(path->nodes[0],
693                                                     path->slots[0]);
694                 copy_extent_buffer(path->nodes[0], eb, dest_offset,
695                                 (unsigned long)item,  sizeof(*item));
696
697                 ins.objectid = btrfs_file_extent_disk_bytenr(eb, item);
698                 ins.offset = btrfs_file_extent_disk_num_bytes(eb, item);
699                 ins.type = BTRFS_EXTENT_ITEM_KEY;
700                 offset = key->offset - btrfs_file_extent_offset(eb, item);
701
702                 /*
703                  * Manually record dirty extent, as here we did a shallow
704                  * file extent item copy and skip normal backref update,
705                  * but modifying extent tree all by ourselves.
706                  * So need to manually record dirty extent for qgroup,
707                  * as the owner of the file extent changed from log tree
708                  * (doesn't affect qgroup) to fs/file tree(affects qgroup)
709                  */
710                 ret = btrfs_qgroup_trace_extent(trans, fs_info,
711                                 btrfs_file_extent_disk_bytenr(eb, item),
712                                 btrfs_file_extent_disk_num_bytes(eb, item),
713                                 GFP_NOFS);
714                 if (ret < 0)
715                         goto out;
716
717                 if (ins.objectid > 0) {
718                         u64 csum_start;
719                         u64 csum_end;
720                         LIST_HEAD(ordered_sums);
721                         /*
722                          * is this extent already allocated in the extent
723                          * allocation tree?  If so, just add a reference
724                          */
725                         ret = btrfs_lookup_data_extent(fs_info, ins.objectid,
726                                                 ins.offset);
727                         if (ret == 0) {
728                                 ret = btrfs_inc_extent_ref(trans, fs_info,
729                                                 ins.objectid, ins.offset,
730                                                 0, root->root_key.objectid,
731                                                 key->objectid, offset);
732                                 if (ret)
733                                         goto out;
734                         } else {
735                                 /*
736                                  * insert the extent pointer in the extent
737                                  * allocation tree
738                                  */
739                                 ret = btrfs_alloc_logged_file_extent(trans,
740                                                 fs_info,
741                                                 root->root_key.objectid,
742                                                 key->objectid, offset, &ins);
743                                 if (ret)
744                                         goto out;
745                         }
746                         btrfs_release_path(path);
747
748                         if (btrfs_file_extent_compression(eb, item)) {
749                                 csum_start = ins.objectid;
750                                 csum_end = csum_start + ins.offset;
751                         } else {
752                                 csum_start = ins.objectid +
753                                         btrfs_file_extent_offset(eb, item);
754                                 csum_end = csum_start +
755                                         btrfs_file_extent_num_bytes(eb, item);
756                         }
757
758                         ret = btrfs_lookup_csums_range(root->log_root,
759                                                 csum_start, csum_end - 1,
760                                                 &ordered_sums, 0);
761                         if (ret)
762                                 goto out;
763                         /*
764                          * Now delete all existing cums in the csum root that
765                          * cover our range. We do this because we can have an
766                          * extent that is completely referenced by one file
767                          * extent item and partially referenced by another
768                          * file extent item (like after using the clone or
769                          * extent_same ioctls). In this case if we end up doing
770                          * the replay of the one that partially references the
771                          * extent first, and we do not do the csum deletion
772                          * below, we can get 2 csum items in the csum tree that
773                          * overlap each other. For example, imagine our log has
774                          * the two following file extent items:
775                          *
776                          * key (257 EXTENT_DATA 409600)
777                          *     extent data disk byte 12845056 nr 102400
778                          *     extent data offset 20480 nr 20480 ram 102400
779                          *
780                          * key (257 EXTENT_DATA 819200)
781                          *     extent data disk byte 12845056 nr 102400
782                          *     extent data offset 0 nr 102400 ram 102400
783                          *
784                          * Where the second one fully references the 100K extent
785                          * that starts at disk byte 12845056, and the log tree
786                          * has a single csum item that covers the entire range
787                          * of the extent:
788                          *
789                          * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
790                          *
791                          * After the first file extent item is replayed, the
792                          * csum tree gets the following csum item:
793                          *
794                          * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
795                          *
796                          * Which covers the 20K sub-range starting at offset 20K
797                          * of our extent. Now when we replay the second file
798                          * extent item, if we do not delete existing csum items
799                          * that cover any of its blocks, we end up getting two
800                          * csum items in our csum tree that overlap each other:
801                          *
802                          * key (EXTENT_CSUM EXTENT_CSUM 12845056) itemsize 100
803                          * key (EXTENT_CSUM EXTENT_CSUM 12865536) itemsize 20
804                          *
805                          * Which is a problem, because after this anyone trying
806                          * to lookup up for the checksum of any block of our
807                          * extent starting at an offset of 40K or higher, will
808                          * end up looking at the second csum item only, which
809                          * does not contain the checksum for any block starting
810                          * at offset 40K or higher of our extent.
811                          */
812                         while (!list_empty(&ordered_sums)) {
813                                 struct btrfs_ordered_sum *sums;
814                                 sums = list_entry(ordered_sums.next,
815                                                 struct btrfs_ordered_sum,
816                                                 list);
817                                 if (!ret)
818                                         ret = btrfs_del_csums(trans, fs_info,
819                                                               sums->bytenr,
820                                                               sums->len);
821                                 if (!ret)
822                                         ret = btrfs_csum_file_blocks(trans,
823                                                 fs_info->csum_root, sums);
824                                 list_del(&sums->list);
825                                 kfree(sums);
826                         }
827                         if (ret)
828                                 goto out;
829                 } else {
830                         btrfs_release_path(path);
831                 }
832         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
833                 /* inline extents are easy, we just overwrite them */
834                 ret = overwrite_item(trans, root, path, eb, slot, key);
835                 if (ret)
836                         goto out;
837         }
838
839         inode_add_bytes(inode, nbytes);
840 update_inode:
841         ret = btrfs_update_inode(trans, root, inode);
842 out:
843         if (inode)
844                 iput(inode);
845         return ret;
846 }
847
848 /*
849  * when cleaning up conflicts between the directory names in the
850  * subvolume, directory names in the log and directory names in the
851  * inode back references, we may have to unlink inodes from directories.
852  *
853  * This is a helper function to do the unlink of a specific directory
854  * item
855  */
856 static noinline int drop_one_dir_item(struct btrfs_trans_handle *trans,
857                                       struct btrfs_root *root,
858                                       struct btrfs_path *path,
859                                       struct btrfs_inode *dir,
860                                       struct btrfs_dir_item *di)
861 {
862         struct btrfs_fs_info *fs_info = root->fs_info;
863         struct inode *inode;
864         char *name;
865         int name_len;
866         struct extent_buffer *leaf;
867         struct btrfs_key location;
868         int ret;
869
870         leaf = path->nodes[0];
871
872         btrfs_dir_item_key_to_cpu(leaf, di, &location);
873         name_len = btrfs_dir_name_len(leaf, di);
874         name = kmalloc(name_len, GFP_NOFS);
875         if (!name)
876                 return -ENOMEM;
877
878         read_extent_buffer(leaf, name, (unsigned long)(di + 1), name_len);
879         btrfs_release_path(path);
880
881         inode = read_one_inode(root, location.objectid);
882         if (!inode) {
883                 ret = -EIO;
884                 goto out;
885         }
886
887         ret = link_to_fixup_dir(trans, root, path, location.objectid);
888         if (ret)
889                 goto out;
890
891         ret = btrfs_unlink_inode(trans, root, dir, BTRFS_I(inode), name,
892                         name_len);
893         if (ret)
894                 goto out;
895         else
896                 ret = btrfs_run_delayed_items(trans, fs_info);
897 out:
898         kfree(name);
899         iput(inode);
900         return ret;
901 }
902
903 /*
904  * helper function to see if a given name and sequence number found
905  * in an inode back reference are already in a directory and correctly
906  * point to this inode
907  */
908 static noinline int inode_in_dir(struct btrfs_root *root,
909                                  struct btrfs_path *path,
910                                  u64 dirid, u64 objectid, u64 index,
911                                  const char *name, int name_len)
912 {
913         struct btrfs_dir_item *di;
914         struct btrfs_key location;
915         int match = 0;
916
917         di = btrfs_lookup_dir_index_item(NULL, root, path, dirid,
918                                          index, name, name_len, 0);
919         if (di && !IS_ERR(di)) {
920                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
921                 if (location.objectid != objectid)
922                         goto out;
923         } else
924                 goto out;
925         btrfs_release_path(path);
926
927         di = btrfs_lookup_dir_item(NULL, root, path, dirid, name, name_len, 0);
928         if (di && !IS_ERR(di)) {
929                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
930                 if (location.objectid != objectid)
931                         goto out;
932         } else
933                 goto out;
934         match = 1;
935 out:
936         btrfs_release_path(path);
937         return match;
938 }
939
940 /*
941  * helper function to check a log tree for a named back reference in
942  * an inode.  This is used to decide if a back reference that is
943  * found in the subvolume conflicts with what we find in the log.
944  *
945  * inode backreferences may have multiple refs in a single item,
946  * during replay we process one reference at a time, and we don't
947  * want to delete valid links to a file from the subvolume if that
948  * link is also in the log.
949  */
950 static noinline int backref_in_log(struct btrfs_root *log,
951                                    struct btrfs_key *key,
952                                    u64 ref_objectid,
953                                    const char *name, int namelen)
954 {
955         struct btrfs_path *path;
956         struct btrfs_inode_ref *ref;
957         unsigned long ptr;
958         unsigned long ptr_end;
959         unsigned long name_ptr;
960         int found_name_len;
961         int item_size;
962         int ret;
963         int match = 0;
964
965         path = btrfs_alloc_path();
966         if (!path)
967                 return -ENOMEM;
968
969         ret = btrfs_search_slot(NULL, log, key, path, 0, 0);
970         if (ret != 0)
971                 goto out;
972
973         ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
974
975         if (key->type == BTRFS_INODE_EXTREF_KEY) {
976                 if (btrfs_find_name_in_ext_backref(path, ref_objectid,
977                                                    name, namelen, NULL))
978                         match = 1;
979
980                 goto out;
981         }
982
983         item_size = btrfs_item_size_nr(path->nodes[0], path->slots[0]);
984         ptr_end = ptr + item_size;
985         while (ptr < ptr_end) {
986                 ref = (struct btrfs_inode_ref *)ptr;
987                 found_name_len = btrfs_inode_ref_name_len(path->nodes[0], ref);
988                 if (found_name_len == namelen) {
989                         name_ptr = (unsigned long)(ref + 1);
990                         ret = memcmp_extent_buffer(path->nodes[0], name,
991                                                    name_ptr, namelen);
992                         if (ret == 0) {
993                                 match = 1;
994                                 goto out;
995                         }
996                 }
997                 ptr = (unsigned long)(ref + 1) + found_name_len;
998         }
999 out:
1000         btrfs_free_path(path);
1001         return match;
1002 }
1003
1004 static inline int __add_inode_ref(struct btrfs_trans_handle *trans,
1005                                   struct btrfs_root *root,
1006                                   struct btrfs_path *path,
1007                                   struct btrfs_root *log_root,
1008                                   struct btrfs_inode *dir,
1009                                   struct btrfs_inode *inode,
1010                                   u64 inode_objectid, u64 parent_objectid,
1011                                   u64 ref_index, char *name, int namelen,
1012                                   int *search_done)
1013 {
1014         struct btrfs_fs_info *fs_info = root->fs_info;
1015         int ret;
1016         char *victim_name;
1017         int victim_name_len;
1018         struct extent_buffer *leaf;
1019         struct btrfs_dir_item *di;
1020         struct btrfs_key search_key;
1021         struct btrfs_inode_extref *extref;
1022
1023 again:
1024         /* Search old style refs */
1025         search_key.objectid = inode_objectid;
1026         search_key.type = BTRFS_INODE_REF_KEY;
1027         search_key.offset = parent_objectid;
1028         ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
1029         if (ret == 0) {
1030                 struct btrfs_inode_ref *victim_ref;
1031                 unsigned long ptr;
1032                 unsigned long ptr_end;
1033
1034                 leaf = path->nodes[0];
1035
1036                 /* are we trying to overwrite a back ref for the root directory
1037                  * if so, just jump out, we're done
1038                  */
1039                 if (search_key.objectid == search_key.offset)
1040                         return 1;
1041
1042                 /* check all the names in this back reference to see
1043                  * if they are in the log.  if so, we allow them to stay
1044                  * otherwise they must be unlinked as a conflict
1045                  */
1046                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1047                 ptr_end = ptr + btrfs_item_size_nr(leaf, path->slots[0]);
1048                 while (ptr < ptr_end) {
1049                         victim_ref = (struct btrfs_inode_ref *)ptr;
1050                         victim_name_len = btrfs_inode_ref_name_len(leaf,
1051                                                                    victim_ref);
1052                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
1053                         if (!victim_name)
1054                                 return -ENOMEM;
1055
1056                         read_extent_buffer(leaf, victim_name,
1057                                            (unsigned long)(victim_ref + 1),
1058                                            victim_name_len);
1059
1060                         if (!backref_in_log(log_root, &search_key,
1061                                             parent_objectid,
1062                                             victim_name,
1063                                             victim_name_len)) {
1064                                 inc_nlink(&inode->vfs_inode);
1065                                 btrfs_release_path(path);
1066
1067                                 ret = btrfs_unlink_inode(trans, root, dir, inode,
1068                                                 victim_name, victim_name_len);
1069                                 kfree(victim_name);
1070                                 if (ret)
1071                                         return ret;
1072                                 ret = btrfs_run_delayed_items(trans, fs_info);
1073                                 if (ret)
1074                                         return ret;
1075                                 *search_done = 1;
1076                                 goto again;
1077                         }
1078                         kfree(victim_name);
1079
1080                         ptr = (unsigned long)(victim_ref + 1) + victim_name_len;
1081                 }
1082
1083                 /*
1084                  * NOTE: we have searched root tree and checked the
1085                  * corresponding ref, it does not need to check again.
1086                  */
1087                 *search_done = 1;
1088         }
1089         btrfs_release_path(path);
1090
1091         /* Same search but for extended refs */
1092         extref = btrfs_lookup_inode_extref(NULL, root, path, name, namelen,
1093                                            inode_objectid, parent_objectid, 0,
1094                                            0);
1095         if (!IS_ERR_OR_NULL(extref)) {
1096                 u32 item_size;
1097                 u32 cur_offset = 0;
1098                 unsigned long base;
1099                 struct inode *victim_parent;
1100
1101                 leaf = path->nodes[0];
1102
1103                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1104                 base = btrfs_item_ptr_offset(leaf, path->slots[0]);
1105
1106                 while (cur_offset < item_size) {
1107                         extref = (struct btrfs_inode_extref *)(base + cur_offset);
1108
1109                         victim_name_len = btrfs_inode_extref_name_len(leaf, extref);
1110
1111                         if (btrfs_inode_extref_parent(leaf, extref) != parent_objectid)
1112                                 goto next;
1113
1114                         victim_name = kmalloc(victim_name_len, GFP_NOFS);
1115                         if (!victim_name)
1116                                 return -ENOMEM;
1117                         read_extent_buffer(leaf, victim_name, (unsigned long)&extref->name,
1118                                            victim_name_len);
1119
1120                         search_key.objectid = inode_objectid;
1121                         search_key.type = BTRFS_INODE_EXTREF_KEY;
1122                         search_key.offset = btrfs_extref_hash(parent_objectid,
1123                                                               victim_name,
1124                                                               victim_name_len);
1125                         ret = 0;
1126                         if (!backref_in_log(log_root, &search_key,
1127                                             parent_objectid, victim_name,
1128                                             victim_name_len)) {
1129                                 ret = -ENOENT;
1130                                 victim_parent = read_one_inode(root,
1131                                                 parent_objectid);
1132                                 if (victim_parent) {
1133                                         inc_nlink(&inode->vfs_inode);
1134                                         btrfs_release_path(path);
1135
1136                                         ret = btrfs_unlink_inode(trans, root,
1137                                                         BTRFS_I(victim_parent),
1138                                                         inode,
1139                                                         victim_name,
1140                                                         victim_name_len);
1141                                         if (!ret)
1142                                                 ret = btrfs_run_delayed_items(
1143                                                                   trans,
1144                                                                   fs_info);
1145                                 }
1146                                 iput(victim_parent);
1147                                 kfree(victim_name);
1148                                 if (ret)
1149                                         return ret;
1150                                 *search_done = 1;
1151                                 goto again;
1152                         }
1153                         kfree(victim_name);
1154 next:
1155                         cur_offset += victim_name_len + sizeof(*extref);
1156                 }
1157                 *search_done = 1;
1158         }
1159         btrfs_release_path(path);
1160
1161         /* look for a conflicting sequence number */
1162         di = btrfs_lookup_dir_index_item(trans, root, path, btrfs_ino(dir),
1163                                          ref_index, name, namelen, 0);
1164         if (di && !IS_ERR(di)) {
1165                 ret = drop_one_dir_item(trans, root, path, dir, di);
1166                 if (ret)
1167                         return ret;
1168         }
1169         btrfs_release_path(path);
1170
1171         /* look for a conflicing name */
1172         di = btrfs_lookup_dir_item(trans, root, path, btrfs_ino(dir),
1173                                    name, namelen, 0);
1174         if (di && !IS_ERR(di)) {
1175                 ret = drop_one_dir_item(trans, root, path, dir, di);
1176                 if (ret)
1177                         return ret;
1178         }
1179         btrfs_release_path(path);
1180
1181         return 0;
1182 }
1183
1184 static int extref_get_fields(struct extent_buffer *eb, int slot,
1185                              unsigned long ref_ptr, u32 *namelen, char **name,
1186                              u64 *index, u64 *parent_objectid)
1187 {
1188         struct btrfs_inode_extref *extref;
1189
1190         extref = (struct btrfs_inode_extref *)ref_ptr;
1191
1192         *namelen = btrfs_inode_extref_name_len(eb, extref);
1193         if (!btrfs_is_name_len_valid(eb, slot, (unsigned long)&extref->name,
1194                                      *namelen))
1195                 return -EIO;
1196
1197         *name = kmalloc(*namelen, GFP_NOFS);
1198         if (*name == NULL)
1199                 return -ENOMEM;
1200
1201         read_extent_buffer(eb, *name, (unsigned long)&extref->name,
1202                            *namelen);
1203
1204         *index = btrfs_inode_extref_index(eb, extref);
1205         if (parent_objectid)
1206                 *parent_objectid = btrfs_inode_extref_parent(eb, extref);
1207
1208         return 0;
1209 }
1210
1211 static int ref_get_fields(struct extent_buffer *eb, int slot,
1212                           unsigned long ref_ptr, u32 *namelen, char **name,
1213                           u64 *index)
1214 {
1215         struct btrfs_inode_ref *ref;
1216
1217         ref = (struct btrfs_inode_ref *)ref_ptr;
1218
1219         *namelen = btrfs_inode_ref_name_len(eb, ref);
1220         if (!btrfs_is_name_len_valid(eb, slot, (unsigned long)(ref + 1),
1221                                      *namelen))
1222                 return -EIO;
1223
1224         *name = kmalloc(*namelen, GFP_NOFS);
1225         if (*name == NULL)
1226                 return -ENOMEM;
1227
1228         read_extent_buffer(eb, *name, (unsigned long)(ref + 1), *namelen);
1229
1230         *index = btrfs_inode_ref_index(eb, ref);
1231
1232         return 0;
1233 }
1234
1235 /*
1236  * replay one inode back reference item found in the log tree.
1237  * eb, slot and key refer to the buffer and key found in the log tree.
1238  * root is the destination we are replaying into, and path is for temp
1239  * use by this function.  (it should be released on return).
1240  */
1241 static noinline int add_inode_ref(struct btrfs_trans_handle *trans,
1242                                   struct btrfs_root *root,
1243                                   struct btrfs_root *log,
1244                                   struct btrfs_path *path,
1245                                   struct extent_buffer *eb, int slot,
1246                                   struct btrfs_key *key)
1247 {
1248         struct inode *dir = NULL;
1249         struct inode *inode = NULL;
1250         unsigned long ref_ptr;
1251         unsigned long ref_end;
1252         char *name = NULL;
1253         int namelen;
1254         int ret;
1255         int search_done = 0;
1256         int log_ref_ver = 0;
1257         u64 parent_objectid;
1258         u64 inode_objectid;
1259         u64 ref_index = 0;
1260         int ref_struct_size;
1261
1262         ref_ptr = btrfs_item_ptr_offset(eb, slot);
1263         ref_end = ref_ptr + btrfs_item_size_nr(eb, slot);
1264
1265         if (key->type == BTRFS_INODE_EXTREF_KEY) {
1266                 struct btrfs_inode_extref *r;
1267
1268                 ref_struct_size = sizeof(struct btrfs_inode_extref);
1269                 log_ref_ver = 1;
1270                 r = (struct btrfs_inode_extref *)ref_ptr;
1271                 parent_objectid = btrfs_inode_extref_parent(eb, r);
1272         } else {
1273                 ref_struct_size = sizeof(struct btrfs_inode_ref);
1274                 parent_objectid = key->offset;
1275         }
1276         inode_objectid = key->objectid;
1277
1278         /*
1279          * it is possible that we didn't log all the parent directories
1280          * for a given inode.  If we don't find the dir, just don't
1281          * copy the back ref in.  The link count fixup code will take
1282          * care of the rest
1283          */
1284         dir = read_one_inode(root, parent_objectid);
1285         if (!dir) {
1286                 ret = -ENOENT;
1287                 goto out;
1288         }
1289
1290         inode = read_one_inode(root, inode_objectid);
1291         if (!inode) {
1292                 ret = -EIO;
1293                 goto out;
1294         }
1295
1296         while (ref_ptr < ref_end) {
1297                 if (log_ref_ver) {
1298                         ret = extref_get_fields(eb, slot, ref_ptr, &namelen,
1299                                           &name, &ref_index, &parent_objectid);
1300                         /*
1301                          * parent object can change from one array
1302                          * item to another.
1303                          */
1304                         if (!dir)
1305                                 dir = read_one_inode(root, parent_objectid);
1306                         if (!dir) {
1307                                 ret = -ENOENT;
1308                                 goto out;
1309                         }
1310                 } else {
1311                         ret = ref_get_fields(eb, slot, ref_ptr, &namelen,
1312                                              &name, &ref_index);
1313                 }
1314                 if (ret)
1315                         goto out;
1316
1317                 /* if we already have a perfect match, we're done */
1318                 if (!inode_in_dir(root, path, btrfs_ino(BTRFS_I(dir)),
1319                                         btrfs_ino(BTRFS_I(inode)), ref_index,
1320                                         name, namelen)) {
1321                         /*
1322                          * look for a conflicting back reference in the
1323                          * metadata. if we find one we have to unlink that name
1324                          * of the file before we add our new link.  Later on, we
1325                          * overwrite any existing back reference, and we don't
1326                          * want to create dangling pointers in the directory.
1327                          */
1328
1329                         if (!search_done) {
1330                                 ret = __add_inode_ref(trans, root, path, log,
1331                                                       BTRFS_I(dir),
1332                                                       BTRFS_I(inode),
1333                                                       inode_objectid,
1334                                                       parent_objectid,
1335                                                       ref_index, name, namelen,
1336                                                       &search_done);
1337                                 if (ret) {
1338                                         if (ret == 1)
1339                                                 ret = 0;
1340                                         goto out;
1341                                 }
1342                         }
1343
1344                         /* insert our name */
1345                         ret = btrfs_add_link(trans, BTRFS_I(dir),
1346                                         BTRFS_I(inode),
1347                                         name, namelen, 0, ref_index);
1348                         if (ret)
1349                                 goto out;
1350
1351                         btrfs_update_inode(trans, root, inode);
1352                 }
1353
1354                 ref_ptr = (unsigned long)(ref_ptr + ref_struct_size) + namelen;
1355                 kfree(name);
1356                 name = NULL;
1357                 if (log_ref_ver) {
1358                         iput(dir);
1359                         dir = NULL;
1360                 }
1361         }
1362
1363         /* finally write the back reference in the inode */
1364         ret = overwrite_item(trans, root, path, eb, slot, key);
1365 out:
1366         btrfs_release_path(path);
1367         kfree(name);
1368         iput(dir);
1369         iput(inode);
1370         return ret;
1371 }
1372
1373 static int insert_orphan_item(struct btrfs_trans_handle *trans,
1374                               struct btrfs_root *root, u64 ino)
1375 {
1376         int ret;
1377
1378         ret = btrfs_insert_orphan_item(trans, root, ino);
1379         if (ret == -EEXIST)
1380                 ret = 0;
1381
1382         return ret;
1383 }
1384
1385 static int count_inode_extrefs(struct btrfs_root *root,
1386                 struct btrfs_inode *inode, struct btrfs_path *path)
1387 {
1388         int ret = 0;
1389         int name_len;
1390         unsigned int nlink = 0;
1391         u32 item_size;
1392         u32 cur_offset = 0;
1393         u64 inode_objectid = btrfs_ino(inode);
1394         u64 offset = 0;
1395         unsigned long ptr;
1396         struct btrfs_inode_extref *extref;
1397         struct extent_buffer *leaf;
1398
1399         while (1) {
1400                 ret = btrfs_find_one_extref(root, inode_objectid, offset, path,
1401                                             &extref, &offset);
1402                 if (ret)
1403                         break;
1404
1405                 leaf = path->nodes[0];
1406                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1407                 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
1408                 cur_offset = 0;
1409
1410                 while (cur_offset < item_size) {
1411                         extref = (struct btrfs_inode_extref *) (ptr + cur_offset);
1412                         name_len = btrfs_inode_extref_name_len(leaf, extref);
1413
1414                         nlink++;
1415
1416                         cur_offset += name_len + sizeof(*extref);
1417                 }
1418
1419                 offset++;
1420                 btrfs_release_path(path);
1421         }
1422         btrfs_release_path(path);
1423
1424         if (ret < 0 && ret != -ENOENT)
1425                 return ret;
1426         return nlink;
1427 }
1428
1429 static int count_inode_refs(struct btrfs_root *root,
1430                         struct btrfs_inode *inode, struct btrfs_path *path)
1431 {
1432         int ret;
1433         struct btrfs_key key;
1434         unsigned int nlink = 0;
1435         unsigned long ptr;
1436         unsigned long ptr_end;
1437         int name_len;
1438         u64 ino = btrfs_ino(inode);
1439
1440         key.objectid = ino;
1441         key.type = BTRFS_INODE_REF_KEY;
1442         key.offset = (u64)-1;
1443
1444         while (1) {
1445                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1446                 if (ret < 0)
1447                         break;
1448                 if (ret > 0) {
1449                         if (path->slots[0] == 0)
1450                                 break;
1451                         path->slots[0]--;
1452                 }
1453 process_slot:
1454                 btrfs_item_key_to_cpu(path->nodes[0], &key,
1455                                       path->slots[0]);
1456                 if (key.objectid != ino ||
1457                     key.type != BTRFS_INODE_REF_KEY)
1458                         break;
1459                 ptr = btrfs_item_ptr_offset(path->nodes[0], path->slots[0]);
1460                 ptr_end = ptr + btrfs_item_size_nr(path->nodes[0],
1461                                                    path->slots[0]);
1462                 while (ptr < ptr_end) {
1463                         struct btrfs_inode_ref *ref;
1464
1465                         ref = (struct btrfs_inode_ref *)ptr;
1466                         name_len = btrfs_inode_ref_name_len(path->nodes[0],
1467                                                             ref);
1468                         ptr = (unsigned long)(ref + 1) + name_len;
1469                         nlink++;
1470                 }
1471
1472                 if (key.offset == 0)
1473                         break;
1474                 if (path->slots[0] > 0) {
1475                         path->slots[0]--;
1476                         goto process_slot;
1477                 }
1478                 key.offset--;
1479                 btrfs_release_path(path);
1480         }
1481         btrfs_release_path(path);
1482
1483         return nlink;
1484 }
1485
1486 /*
1487  * There are a few corners where the link count of the file can't
1488  * be properly maintained during replay.  So, instead of adding
1489  * lots of complexity to the log code, we just scan the backrefs
1490  * for any file that has been through replay.
1491  *
1492  * The scan will update the link count on the inode to reflect the
1493  * number of back refs found.  If it goes down to zero, the iput
1494  * will free the inode.
1495  */
1496 static noinline int fixup_inode_link_count(struct btrfs_trans_handle *trans,
1497                                            struct btrfs_root *root,
1498                                            struct inode *inode)
1499 {
1500         struct btrfs_path *path;
1501         int ret;
1502         u64 nlink = 0;
1503         u64 ino = btrfs_ino(BTRFS_I(inode));
1504
1505         path = btrfs_alloc_path();
1506         if (!path)
1507                 return -ENOMEM;
1508
1509         ret = count_inode_refs(root, BTRFS_I(inode), path);
1510         if (ret < 0)
1511                 goto out;
1512
1513         nlink = ret;
1514
1515         ret = count_inode_extrefs(root, BTRFS_I(inode), path);
1516         if (ret < 0)
1517                 goto out;
1518
1519         nlink += ret;
1520
1521         ret = 0;
1522
1523         if (nlink != inode->i_nlink) {
1524                 set_nlink(inode, nlink);
1525                 btrfs_update_inode(trans, root, inode);
1526         }
1527         BTRFS_I(inode)->index_cnt = (u64)-1;
1528
1529         if (inode->i_nlink == 0) {
1530                 if (S_ISDIR(inode->i_mode)) {
1531                         ret = replay_dir_deletes(trans, root, NULL, path,
1532                                                  ino, 1);
1533                         if (ret)
1534                                 goto out;
1535                 }
1536                 ret = insert_orphan_item(trans, root, ino);
1537         }
1538
1539 out:
1540         btrfs_free_path(path);
1541         return ret;
1542 }
1543
1544 static noinline int fixup_inode_link_counts(struct btrfs_trans_handle *trans,
1545                                             struct btrfs_root *root,
1546                                             struct btrfs_path *path)
1547 {
1548         int ret;
1549         struct btrfs_key key;
1550         struct inode *inode;
1551
1552         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1553         key.type = BTRFS_ORPHAN_ITEM_KEY;
1554         key.offset = (u64)-1;
1555         while (1) {
1556                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1557                 if (ret < 0)
1558                         break;
1559
1560                 if (ret == 1) {
1561                         if (path->slots[0] == 0)
1562                                 break;
1563                         path->slots[0]--;
1564                 }
1565
1566                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1567                 if (key.objectid != BTRFS_TREE_LOG_FIXUP_OBJECTID ||
1568                     key.type != BTRFS_ORPHAN_ITEM_KEY)
1569                         break;
1570
1571                 ret = btrfs_del_item(trans, root, path);
1572                 if (ret)
1573                         goto out;
1574
1575                 btrfs_release_path(path);
1576                 inode = read_one_inode(root, key.offset);
1577                 if (!inode)
1578                         return -EIO;
1579
1580                 ret = fixup_inode_link_count(trans, root, inode);
1581                 iput(inode);
1582                 if (ret)
1583                         goto out;
1584
1585                 /*
1586                  * fixup on a directory may create new entries,
1587                  * make sure we always look for the highset possible
1588                  * offset
1589                  */
1590                 key.offset = (u64)-1;
1591         }
1592         ret = 0;
1593 out:
1594         btrfs_release_path(path);
1595         return ret;
1596 }
1597
1598
1599 /*
1600  * record a given inode in the fixup dir so we can check its link
1601  * count when replay is done.  The link count is incremented here
1602  * so the inode won't go away until we check it
1603  */
1604 static noinline int link_to_fixup_dir(struct btrfs_trans_handle *trans,
1605                                       struct btrfs_root *root,
1606                                       struct btrfs_path *path,
1607                                       u64 objectid)
1608 {
1609         struct btrfs_key key;
1610         int ret = 0;
1611         struct inode *inode;
1612
1613         inode = read_one_inode(root, objectid);
1614         if (!inode)
1615                 return -EIO;
1616
1617         key.objectid = BTRFS_TREE_LOG_FIXUP_OBJECTID;
1618         key.type = BTRFS_ORPHAN_ITEM_KEY;
1619         key.offset = objectid;
1620
1621         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1622
1623         btrfs_release_path(path);
1624         if (ret == 0) {
1625                 if (!inode->i_nlink)
1626                         set_nlink(inode, 1);
1627                 else
1628                         inc_nlink(inode);
1629                 ret = btrfs_update_inode(trans, root, inode);
1630         } else if (ret == -EEXIST) {
1631                 ret = 0;
1632         } else {
1633                 BUG(); /* Logic Error */
1634         }
1635         iput(inode);
1636
1637         return ret;
1638 }
1639
1640 /*
1641  * when replaying the log for a directory, we only insert names
1642  * for inodes that actually exist.  This means an fsync on a directory
1643  * does not implicitly fsync all the new files in it
1644  */
1645 static noinline int insert_one_name(struct btrfs_trans_handle *trans,
1646                                     struct btrfs_root *root,
1647                                     u64 dirid, u64 index,
1648                                     char *name, int name_len,
1649                                     struct btrfs_key *location)
1650 {
1651         struct inode *inode;
1652         struct inode *dir;
1653         int ret;
1654
1655         inode = read_one_inode(root, location->objectid);
1656         if (!inode)
1657                 return -ENOENT;
1658
1659         dir = read_one_inode(root, dirid);
1660         if (!dir) {
1661                 iput(inode);
1662                 return -EIO;
1663         }
1664
1665         ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
1666                         name_len, 1, index);
1667
1668         /* FIXME, put inode into FIXUP list */
1669
1670         iput(inode);
1671         iput(dir);
1672         return ret;
1673 }
1674
1675 /*
1676  * Return true if an inode reference exists in the log for the given name,
1677  * inode and parent inode.
1678  */
1679 static bool name_in_log_ref(struct btrfs_root *log_root,
1680                             const char *name, const int name_len,
1681                             const u64 dirid, const u64 ino)
1682 {
1683         struct btrfs_key search_key;
1684
1685         search_key.objectid = ino;
1686         search_key.type = BTRFS_INODE_REF_KEY;
1687         search_key.offset = dirid;
1688         if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1689                 return true;
1690
1691         search_key.type = BTRFS_INODE_EXTREF_KEY;
1692         search_key.offset = btrfs_extref_hash(dirid, name, name_len);
1693         if (backref_in_log(log_root, &search_key, dirid, name, name_len))
1694                 return true;
1695
1696         return false;
1697 }
1698
1699 /*
1700  * take a single entry in a log directory item and replay it into
1701  * the subvolume.
1702  *
1703  * if a conflicting item exists in the subdirectory already,
1704  * the inode it points to is unlinked and put into the link count
1705  * fix up tree.
1706  *
1707  * If a name from the log points to a file or directory that does
1708  * not exist in the FS, it is skipped.  fsyncs on directories
1709  * do not force down inodes inside that directory, just changes to the
1710  * names or unlinks in a directory.
1711  *
1712  * Returns < 0 on error, 0 if the name wasn't replayed (dentry points to a
1713  * non-existing inode) and 1 if the name was replayed.
1714  */
1715 static noinline int replay_one_name(struct btrfs_trans_handle *trans,
1716                                     struct btrfs_root *root,
1717                                     struct btrfs_path *path,
1718                                     struct extent_buffer *eb,
1719                                     struct btrfs_dir_item *di,
1720                                     struct btrfs_key *key)
1721 {
1722         char *name;
1723         int name_len;
1724         struct btrfs_dir_item *dst_di;
1725         struct btrfs_key found_key;
1726         struct btrfs_key log_key;
1727         struct inode *dir;
1728         u8 log_type;
1729         int exists;
1730         int ret = 0;
1731         bool update_size = (key->type == BTRFS_DIR_INDEX_KEY);
1732         bool name_added = false;
1733
1734         dir = read_one_inode(root, key->objectid);
1735         if (!dir)
1736                 return -EIO;
1737
1738         name_len = btrfs_dir_name_len(eb, di);
1739         name = kmalloc(name_len, GFP_NOFS);
1740         if (!name) {
1741                 ret = -ENOMEM;
1742                 goto out;
1743         }
1744
1745         log_type = btrfs_dir_type(eb, di);
1746         read_extent_buffer(eb, name, (unsigned long)(di + 1),
1747                    name_len);
1748
1749         btrfs_dir_item_key_to_cpu(eb, di, &log_key);
1750         exists = btrfs_lookup_inode(trans, root, path, &log_key, 0);
1751         if (exists == 0)
1752                 exists = 1;
1753         else
1754                 exists = 0;
1755         btrfs_release_path(path);
1756
1757         if (key->type == BTRFS_DIR_ITEM_KEY) {
1758                 dst_di = btrfs_lookup_dir_item(trans, root, path, key->objectid,
1759                                        name, name_len, 1);
1760         } else if (key->type == BTRFS_DIR_INDEX_KEY) {
1761                 dst_di = btrfs_lookup_dir_index_item(trans, root, path,
1762                                                      key->objectid,
1763                                                      key->offset, name,
1764                                                      name_len, 1);
1765         } else {
1766                 /* Corruption */
1767                 ret = -EINVAL;
1768                 goto out;
1769         }
1770         if (IS_ERR_OR_NULL(dst_di)) {
1771                 /* we need a sequence number to insert, so we only
1772                  * do inserts for the BTRFS_DIR_INDEX_KEY types
1773                  */
1774                 if (key->type != BTRFS_DIR_INDEX_KEY)
1775                         goto out;
1776                 goto insert;
1777         }
1778
1779         btrfs_dir_item_key_to_cpu(path->nodes[0], dst_di, &found_key);
1780         /* the existing item matches the logged item */
1781         if (found_key.objectid == log_key.objectid &&
1782             found_key.type == log_key.type &&
1783             found_key.offset == log_key.offset &&
1784             btrfs_dir_type(path->nodes[0], dst_di) == log_type) {
1785                 update_size = false;
1786                 goto out;
1787         }
1788
1789         /*
1790          * don't drop the conflicting directory entry if the inode
1791          * for the new entry doesn't exist
1792          */
1793         if (!exists)
1794                 goto out;
1795
1796         ret = drop_one_dir_item(trans, root, path, BTRFS_I(dir), dst_di);
1797         if (ret)
1798                 goto out;
1799
1800         if (key->type == BTRFS_DIR_INDEX_KEY)
1801                 goto insert;
1802 out:
1803         btrfs_release_path(path);
1804         if (!ret && update_size) {
1805                 btrfs_i_size_write(BTRFS_I(dir), dir->i_size + name_len * 2);
1806                 ret = btrfs_update_inode(trans, root, dir);
1807         }
1808         kfree(name);
1809         iput(dir);
1810         if (!ret && name_added)
1811                 ret = 1;
1812         return ret;
1813
1814 insert:
1815         if (name_in_log_ref(root->log_root, name, name_len,
1816                             key->objectid, log_key.objectid)) {
1817                 /* The dentry will be added later. */
1818                 ret = 0;
1819                 update_size = false;
1820                 goto out;
1821         }
1822         btrfs_release_path(path);
1823         ret = insert_one_name(trans, root, key->objectid, key->offset,
1824                               name, name_len, &log_key);
1825         if (ret && ret != -ENOENT && ret != -EEXIST)
1826                 goto out;
1827         if (!ret)
1828                 name_added = true;
1829         update_size = false;
1830         ret = 0;
1831         goto out;
1832 }
1833
1834 /*
1835  * find all the names in a directory item and reconcile them into
1836  * the subvolume.  Only BTRFS_DIR_ITEM_KEY types will have more than
1837  * one name in a directory item, but the same code gets used for
1838  * both directory index types
1839  */
1840 static noinline int replay_one_dir_item(struct btrfs_trans_handle *trans,
1841                                         struct btrfs_root *root,
1842                                         struct btrfs_path *path,
1843                                         struct extent_buffer *eb, int slot,
1844                                         struct btrfs_key *key)
1845 {
1846         struct btrfs_fs_info *fs_info = root->fs_info;
1847         int ret = 0;
1848         u32 item_size = btrfs_item_size_nr(eb, slot);
1849         struct btrfs_dir_item *di;
1850         int name_len;
1851         unsigned long ptr;
1852         unsigned long ptr_end;
1853         struct btrfs_path *fixup_path = NULL;
1854
1855         ptr = btrfs_item_ptr_offset(eb, slot);
1856         ptr_end = ptr + item_size;
1857         while (ptr < ptr_end) {
1858                 di = (struct btrfs_dir_item *)ptr;
1859                 if (verify_dir_item(fs_info, eb, slot, di))
1860                         return -EIO;
1861                 name_len = btrfs_dir_name_len(eb, di);
1862                 ret = replay_one_name(trans, root, path, eb, di, key);
1863                 if (ret < 0)
1864                         break;
1865                 ptr = (unsigned long)(di + 1);
1866                 ptr += name_len;
1867
1868                 /*
1869                  * If this entry refers to a non-directory (directories can not
1870                  * have a link count > 1) and it was added in the transaction
1871                  * that was not committed, make sure we fixup the link count of
1872                  * the inode it the entry points to. Otherwise something like
1873                  * the following would result in a directory pointing to an
1874                  * inode with a wrong link that does not account for this dir
1875                  * entry:
1876                  *
1877                  * mkdir testdir
1878                  * touch testdir/foo
1879                  * touch testdir/bar
1880                  * sync
1881                  *
1882                  * ln testdir/bar testdir/bar_link
1883                  * ln testdir/foo testdir/foo_link
1884                  * xfs_io -c "fsync" testdir/bar
1885                  *
1886                  * <power failure>
1887                  *
1888                  * mount fs, log replay happens
1889                  *
1890                  * File foo would remain with a link count of 1 when it has two
1891                  * entries pointing to it in the directory testdir. This would
1892                  * make it impossible to ever delete the parent directory has
1893                  * it would result in stale dentries that can never be deleted.
1894                  */
1895                 if (ret == 1 && btrfs_dir_type(eb, di) != BTRFS_FT_DIR) {
1896                         struct btrfs_key di_key;
1897
1898                         if (!fixup_path) {
1899                                 fixup_path = btrfs_alloc_path();
1900                                 if (!fixup_path) {
1901                                         ret = -ENOMEM;
1902                                         break;
1903                                 }
1904                         }
1905
1906                         btrfs_dir_item_key_to_cpu(eb, di, &di_key);
1907                         ret = link_to_fixup_dir(trans, root, fixup_path,
1908                                                 di_key.objectid);
1909                         if (ret)
1910                                 break;
1911                 }
1912                 ret = 0;
1913         }
1914         btrfs_free_path(fixup_path);
1915         return ret;
1916 }
1917
1918 /*
1919  * directory replay has two parts.  There are the standard directory
1920  * items in the log copied from the subvolume, and range items
1921  * created in the log while the subvolume was logged.
1922  *
1923  * The range items tell us which parts of the key space the log
1924  * is authoritative for.  During replay, if a key in the subvolume
1925  * directory is in a logged range item, but not actually in the log
1926  * that means it was deleted from the directory before the fsync
1927  * and should be removed.
1928  */
1929 static noinline int find_dir_range(struct btrfs_root *root,
1930                                    struct btrfs_path *path,
1931                                    u64 dirid, int key_type,
1932                                    u64 *start_ret, u64 *end_ret)
1933 {
1934         struct btrfs_key key;
1935         u64 found_end;
1936         struct btrfs_dir_log_item *item;
1937         int ret;
1938         int nritems;
1939
1940         if (*start_ret == (u64)-1)
1941                 return 1;
1942
1943         key.objectid = dirid;
1944         key.type = key_type;
1945         key.offset = *start_ret;
1946
1947         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1948         if (ret < 0)
1949                 goto out;
1950         if (ret > 0) {
1951                 if (path->slots[0] == 0)
1952                         goto out;
1953                 path->slots[0]--;
1954         }
1955         if (ret != 0)
1956                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1957
1958         if (key.type != key_type || key.objectid != dirid) {
1959                 ret = 1;
1960                 goto next;
1961         }
1962         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1963                               struct btrfs_dir_log_item);
1964         found_end = btrfs_dir_log_end(path->nodes[0], item);
1965
1966         if (*start_ret >= key.offset && *start_ret <= found_end) {
1967                 ret = 0;
1968                 *start_ret = key.offset;
1969                 *end_ret = found_end;
1970                 goto out;
1971         }
1972         ret = 1;
1973 next:
1974         /* check the next slot in the tree to see if it is a valid item */
1975         nritems = btrfs_header_nritems(path->nodes[0]);
1976         path->slots[0]++;
1977         if (path->slots[0] >= nritems) {
1978                 ret = btrfs_next_leaf(root, path);
1979                 if (ret)
1980                         goto out;
1981         }
1982
1983         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
1984
1985         if (key.type != key_type || key.objectid != dirid) {
1986                 ret = 1;
1987                 goto out;
1988         }
1989         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
1990                               struct btrfs_dir_log_item);
1991         found_end = btrfs_dir_log_end(path->nodes[0], item);
1992         *start_ret = key.offset;
1993         *end_ret = found_end;
1994         ret = 0;
1995 out:
1996         btrfs_release_path(path);
1997         return ret;
1998 }
1999
2000 /*
2001  * this looks for a given directory item in the log.  If the directory
2002  * item is not in the log, the item is removed and the inode it points
2003  * to is unlinked
2004  */
2005 static noinline int check_item_in_log(struct btrfs_trans_handle *trans,
2006                                       struct btrfs_root *root,
2007                                       struct btrfs_root *log,
2008                                       struct btrfs_path *path,
2009                                       struct btrfs_path *log_path,
2010                                       struct inode *dir,
2011                                       struct btrfs_key *dir_key)
2012 {
2013         struct btrfs_fs_info *fs_info = root->fs_info;
2014         int ret;
2015         struct extent_buffer *eb;
2016         int slot;
2017         u32 item_size;
2018         struct btrfs_dir_item *di;
2019         struct btrfs_dir_item *log_di;
2020         int name_len;
2021         unsigned long ptr;
2022         unsigned long ptr_end;
2023         char *name;
2024         struct inode *inode;
2025         struct btrfs_key location;
2026
2027 again:
2028         eb = path->nodes[0];
2029         slot = path->slots[0];
2030         item_size = btrfs_item_size_nr(eb, slot);
2031         ptr = btrfs_item_ptr_offset(eb, slot);
2032         ptr_end = ptr + item_size;
2033         while (ptr < ptr_end) {
2034                 di = (struct btrfs_dir_item *)ptr;
2035                 if (verify_dir_item(fs_info, eb, slot, di)) {
2036                         ret = -EIO;
2037                         goto out;
2038                 }
2039
2040                 name_len = btrfs_dir_name_len(eb, di);
2041                 name = kmalloc(name_len, GFP_NOFS);
2042                 if (!name) {
2043                         ret = -ENOMEM;
2044                         goto out;
2045                 }
2046                 read_extent_buffer(eb, name, (unsigned long)(di + 1),
2047                                   name_len);
2048                 log_di = NULL;
2049                 if (log && dir_key->type == BTRFS_DIR_ITEM_KEY) {
2050                         log_di = btrfs_lookup_dir_item(trans, log, log_path,
2051                                                        dir_key->objectid,
2052                                                        name, name_len, 0);
2053                 } else if (log && dir_key->type == BTRFS_DIR_INDEX_KEY) {
2054                         log_di = btrfs_lookup_dir_index_item(trans, log,
2055                                                      log_path,
2056                                                      dir_key->objectid,
2057                                                      dir_key->offset,
2058                                                      name, name_len, 0);
2059                 }
2060                 if (!log_di || (IS_ERR(log_di) && PTR_ERR(log_di) == -ENOENT)) {
2061                         btrfs_dir_item_key_to_cpu(eb, di, &location);
2062                         btrfs_release_path(path);
2063                         btrfs_release_path(log_path);
2064                         inode = read_one_inode(root, location.objectid);
2065                         if (!inode) {
2066                                 kfree(name);
2067                                 return -EIO;
2068                         }
2069
2070                         ret = link_to_fixup_dir(trans, root,
2071                                                 path, location.objectid);
2072                         if (ret) {
2073                                 kfree(name);
2074                                 iput(inode);
2075                                 goto out;
2076                         }
2077
2078                         inc_nlink(inode);
2079                         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
2080                                         BTRFS_I(inode), name, name_len);
2081                         if (!ret)
2082                                 ret = btrfs_run_delayed_items(trans, fs_info);
2083                         kfree(name);
2084                         iput(inode);
2085                         if (ret)
2086                                 goto out;
2087
2088                         /* there might still be more names under this key
2089                          * check and repeat if required
2090                          */
2091                         ret = btrfs_search_slot(NULL, root, dir_key, path,
2092                                                 0, 0);
2093                         if (ret == 0)
2094                                 goto again;
2095                         ret = 0;
2096                         goto out;
2097                 } else if (IS_ERR(log_di)) {
2098                         kfree(name);
2099                         return PTR_ERR(log_di);
2100                 }
2101                 btrfs_release_path(log_path);
2102                 kfree(name);
2103
2104                 ptr = (unsigned long)(di + 1);
2105                 ptr += name_len;
2106         }
2107         ret = 0;
2108 out:
2109         btrfs_release_path(path);
2110         btrfs_release_path(log_path);
2111         return ret;
2112 }
2113
2114 static int replay_xattr_deletes(struct btrfs_trans_handle *trans,
2115                               struct btrfs_root *root,
2116                               struct btrfs_root *log,
2117                               struct btrfs_path *path,
2118                               const u64 ino)
2119 {
2120         struct btrfs_fs_info *fs_info = root->fs_info;
2121         struct btrfs_key search_key;
2122         struct btrfs_path *log_path;
2123         int i;
2124         int nritems;
2125         int ret;
2126
2127         log_path = btrfs_alloc_path();
2128         if (!log_path)
2129                 return -ENOMEM;
2130
2131         search_key.objectid = ino;
2132         search_key.type = BTRFS_XATTR_ITEM_KEY;
2133         search_key.offset = 0;
2134 again:
2135         ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
2136         if (ret < 0)
2137                 goto out;
2138 process_leaf:
2139         nritems = btrfs_header_nritems(path->nodes[0]);
2140         for (i = path->slots[0]; i < nritems; i++) {
2141                 struct btrfs_key key;
2142                 struct btrfs_dir_item *di;
2143                 struct btrfs_dir_item *log_di;
2144                 u32 total_size;
2145                 u32 cur;
2146
2147                 btrfs_item_key_to_cpu(path->nodes[0], &key, i);
2148                 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY) {
2149                         ret = 0;
2150                         goto out;
2151                 }
2152
2153                 di = btrfs_item_ptr(path->nodes[0], i, struct btrfs_dir_item);
2154                 total_size = btrfs_item_size_nr(path->nodes[0], i);
2155                 cur = 0;
2156                 while (cur < total_size) {
2157                         u16 name_len = btrfs_dir_name_len(path->nodes[0], di);
2158                         u16 data_len = btrfs_dir_data_len(path->nodes[0], di);
2159                         u32 this_len = sizeof(*di) + name_len + data_len;
2160                         char *name;
2161
2162                         ret = verify_dir_item(fs_info, path->nodes[0], i, di);
2163                         if (ret) {
2164                                 ret = -EIO;
2165                                 goto out;
2166                         }
2167                         name = kmalloc(name_len, GFP_NOFS);
2168                         if (!name) {
2169                                 ret = -ENOMEM;
2170                                 goto out;
2171                         }
2172                         read_extent_buffer(path->nodes[0], name,
2173                                            (unsigned long)(di + 1), name_len);
2174
2175                         log_di = btrfs_lookup_xattr(NULL, log, log_path, ino,
2176                                                     name, name_len, 0);
2177                         btrfs_release_path(log_path);
2178                         if (!log_di) {
2179                                 /* Doesn't exist in log tree, so delete it. */
2180                                 btrfs_release_path(path);
2181                                 di = btrfs_lookup_xattr(trans, root, path, ino,
2182                                                         name, name_len, -1);
2183                                 kfree(name);
2184                                 if (IS_ERR(di)) {
2185                                         ret = PTR_ERR(di);
2186                                         goto out;
2187                                 }
2188                                 ASSERT(di);
2189                                 ret = btrfs_delete_one_dir_name(trans, root,
2190                                                                 path, di);
2191                                 if (ret)
2192                                         goto out;
2193                                 btrfs_release_path(path);
2194                                 search_key = key;
2195                                 goto again;
2196                         }
2197                         kfree(name);
2198                         if (IS_ERR(log_di)) {
2199                                 ret = PTR_ERR(log_di);
2200                                 goto out;
2201                         }
2202                         cur += this_len;
2203                         di = (struct btrfs_dir_item *)((char *)di + this_len);
2204                 }
2205         }
2206         ret = btrfs_next_leaf(root, path);
2207         if (ret > 0)
2208                 ret = 0;
2209         else if (ret == 0)
2210                 goto process_leaf;
2211 out:
2212         btrfs_free_path(log_path);
2213         btrfs_release_path(path);
2214         return ret;
2215 }
2216
2217
2218 /*
2219  * deletion replay happens before we copy any new directory items
2220  * out of the log or out of backreferences from inodes.  It
2221  * scans the log to find ranges of keys that log is authoritative for,
2222  * and then scans the directory to find items in those ranges that are
2223  * not present in the log.
2224  *
2225  * Anything we don't find in the log is unlinked and removed from the
2226  * directory.
2227  */
2228 static noinline int replay_dir_deletes(struct btrfs_trans_handle *trans,
2229                                        struct btrfs_root *root,
2230                                        struct btrfs_root *log,
2231                                        struct btrfs_path *path,
2232                                        u64 dirid, int del_all)
2233 {
2234         u64 range_start;
2235         u64 range_end;
2236         int key_type = BTRFS_DIR_LOG_ITEM_KEY;
2237         int ret = 0;
2238         struct btrfs_key dir_key;
2239         struct btrfs_key found_key;
2240         struct btrfs_path *log_path;
2241         struct inode *dir;
2242
2243         dir_key.objectid = dirid;
2244         dir_key.type = BTRFS_DIR_ITEM_KEY;
2245         log_path = btrfs_alloc_path();
2246         if (!log_path)
2247                 return -ENOMEM;
2248
2249         dir = read_one_inode(root, dirid);
2250         /* it isn't an error if the inode isn't there, that can happen
2251          * because we replay the deletes before we copy in the inode item
2252          * from the log
2253          */
2254         if (!dir) {
2255                 btrfs_free_path(log_path);
2256                 return 0;
2257         }
2258 again:
2259         range_start = 0;
2260         range_end = 0;
2261         while (1) {
2262                 if (del_all)
2263                         range_end = (u64)-1;
2264                 else {
2265                         ret = find_dir_range(log, path, dirid, key_type,
2266                                              &range_start, &range_end);
2267                         if (ret != 0)
2268                                 break;
2269                 }
2270
2271                 dir_key.offset = range_start;
2272                 while (1) {
2273                         int nritems;
2274                         ret = btrfs_search_slot(NULL, root, &dir_key, path,
2275                                                 0, 0);
2276                         if (ret < 0)
2277                                 goto out;
2278
2279                         nritems = btrfs_header_nritems(path->nodes[0]);
2280                         if (path->slots[0] >= nritems) {
2281                                 ret = btrfs_next_leaf(root, path);
2282                                 if (ret == 1)
2283                                         break;
2284                                 else if (ret < 0)
2285                                         goto out;
2286                         }
2287                         btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2288                                               path->slots[0]);
2289                         if (found_key.objectid != dirid ||
2290                             found_key.type != dir_key.type)
2291                                 goto next_type;
2292
2293                         if (found_key.offset > range_end)
2294                                 break;
2295
2296                         ret = check_item_in_log(trans, root, log, path,
2297                                                 log_path, dir,
2298                                                 &found_key);
2299                         if (ret)
2300                                 goto out;
2301                         if (found_key.offset == (u64)-1)
2302                                 break;
2303                         dir_key.offset = found_key.offset + 1;
2304                 }
2305                 btrfs_release_path(path);
2306                 if (range_end == (u64)-1)
2307                         break;
2308                 range_start = range_end + 1;
2309         }
2310
2311 next_type:
2312         ret = 0;
2313         if (key_type == BTRFS_DIR_LOG_ITEM_KEY) {
2314                 key_type = BTRFS_DIR_LOG_INDEX_KEY;
2315                 dir_key.type = BTRFS_DIR_INDEX_KEY;
2316                 btrfs_release_path(path);
2317                 goto again;
2318         }
2319 out:
2320         btrfs_release_path(path);
2321         btrfs_free_path(log_path);
2322         iput(dir);
2323         return ret;
2324 }
2325
2326 /*
2327  * the process_func used to replay items from the log tree.  This
2328  * gets called in two different stages.  The first stage just looks
2329  * for inodes and makes sure they are all copied into the subvolume.
2330  *
2331  * The second stage copies all the other item types from the log into
2332  * the subvolume.  The two stage approach is slower, but gets rid of
2333  * lots of complexity around inodes referencing other inodes that exist
2334  * only in the log (references come from either directory items or inode
2335  * back refs).
2336  */
2337 static int replay_one_buffer(struct btrfs_root *log, struct extent_buffer *eb,
2338                              struct walk_control *wc, u64 gen)
2339 {
2340         int nritems;
2341         struct btrfs_path *path;
2342         struct btrfs_root *root = wc->replay_dest;
2343         struct btrfs_key key;
2344         int level;
2345         int i;
2346         int ret;
2347
2348         ret = btrfs_read_buffer(eb, gen);
2349         if (ret)
2350                 return ret;
2351
2352         level = btrfs_header_level(eb);
2353
2354         if (level != 0)
2355                 return 0;
2356
2357         path = btrfs_alloc_path();
2358         if (!path)
2359                 return -ENOMEM;
2360
2361         nritems = btrfs_header_nritems(eb);
2362         for (i = 0; i < nritems; i++) {
2363                 btrfs_item_key_to_cpu(eb, &key, i);
2364
2365                 /* inode keys are done during the first stage */
2366                 if (key.type == BTRFS_INODE_ITEM_KEY &&
2367                     wc->stage == LOG_WALK_REPLAY_INODES) {
2368                         struct btrfs_inode_item *inode_item;
2369                         u32 mode;
2370
2371                         inode_item = btrfs_item_ptr(eb, i,
2372                                             struct btrfs_inode_item);
2373                         /*
2374                          * If we have a tmpfile (O_TMPFILE) that got fsync'ed
2375                          * and never got linked before the fsync, skip it, as
2376                          * replaying it is pointless since it would be deleted
2377                          * later. We skip logging tmpfiles, but it's always
2378                          * possible we are replaying a log created with a kernel
2379                          * that used to log tmpfiles.
2380                          */
2381                         if (btrfs_inode_nlink(eb, inode_item) == 0) {
2382                                 wc->ignore_cur_inode = true;
2383                                 continue;
2384                         } else {
2385                                 wc->ignore_cur_inode = false;
2386                         }
2387                         ret = replay_xattr_deletes(wc->trans, root, log,
2388                                                    path, key.objectid);
2389                         if (ret)
2390                                 break;
2391                         mode = btrfs_inode_mode(eb, inode_item);
2392                         if (S_ISDIR(mode)) {
2393                                 ret = replay_dir_deletes(wc->trans,
2394                                          root, log, path, key.objectid, 0);
2395                                 if (ret)
2396                                         break;
2397                         }
2398                         ret = overwrite_item(wc->trans, root, path,
2399                                              eb, i, &key);
2400                         if (ret)
2401                                 break;
2402
2403                         /*
2404                          * Before replaying extents, truncate the inode to its
2405                          * size. We need to do it now and not after log replay
2406                          * because before an fsync we can have prealloc extents
2407                          * added beyond the inode's i_size. If we did it after,
2408                          * through orphan cleanup for example, we would drop
2409                          * those prealloc extents just after replaying them.
2410                          */
2411                         if (S_ISREG(mode)) {
2412                                 struct inode *inode;
2413                                 u64 from;
2414
2415                                 inode = read_one_inode(root, key.objectid);
2416                                 if (!inode) {
2417                                         ret = -EIO;
2418                                         break;
2419                                 }
2420                                 from = ALIGN(i_size_read(inode),
2421                                              root->fs_info->sectorsize);
2422                                 ret = btrfs_drop_extents(wc->trans, root, inode,
2423                                                          from, (u64)-1, 1);
2424                                 if (!ret) {
2425                                         /* Update the inode's nbytes. */
2426                                         ret = btrfs_update_inode(wc->trans,
2427                                                                  root, inode);
2428                                 }
2429                                 iput(inode);
2430                                 if (ret)
2431                                         break;
2432                         }
2433
2434                         ret = link_to_fixup_dir(wc->trans, root,
2435                                                 path, key.objectid);
2436                         if (ret)
2437                                 break;
2438                 }
2439
2440                 if (wc->ignore_cur_inode)
2441                         continue;
2442
2443                 if (key.type == BTRFS_DIR_INDEX_KEY &&
2444                     wc->stage == LOG_WALK_REPLAY_DIR_INDEX) {
2445                         ret = replay_one_dir_item(wc->trans, root, path,
2446                                                   eb, i, &key);
2447                         if (ret)
2448                                 break;
2449                 }
2450
2451                 if (wc->stage < LOG_WALK_REPLAY_ALL)
2452                         continue;
2453
2454                 /* these keys are simply copied */
2455                 if (key.type == BTRFS_XATTR_ITEM_KEY) {
2456                         ret = overwrite_item(wc->trans, root, path,
2457                                              eb, i, &key);
2458                         if (ret)
2459                                 break;
2460                 } else if (key.type == BTRFS_INODE_REF_KEY ||
2461                            key.type == BTRFS_INODE_EXTREF_KEY) {
2462                         ret = add_inode_ref(wc->trans, root, log, path,
2463                                             eb, i, &key);
2464                         if (ret && ret != -ENOENT)
2465                                 break;
2466                         ret = 0;
2467                 } else if (key.type == BTRFS_EXTENT_DATA_KEY) {
2468                         ret = replay_one_extent(wc->trans, root, path,
2469                                                 eb, i, &key);
2470                         if (ret)
2471                                 break;
2472                 } else if (key.type == BTRFS_DIR_ITEM_KEY) {
2473                         ret = replay_one_dir_item(wc->trans, root, path,
2474                                                   eb, i, &key);
2475                         if (ret)
2476                                 break;
2477                 }
2478         }
2479         btrfs_free_path(path);
2480         return ret;
2481 }
2482
2483 static noinline int walk_down_log_tree(struct btrfs_trans_handle *trans,
2484                                    struct btrfs_root *root,
2485                                    struct btrfs_path *path, int *level,
2486                                    struct walk_control *wc)
2487 {
2488         struct btrfs_fs_info *fs_info = root->fs_info;
2489         u64 root_owner;
2490         u64 bytenr;
2491         u64 ptr_gen;
2492         struct extent_buffer *next;
2493         struct extent_buffer *cur;
2494         struct extent_buffer *parent;
2495         u32 blocksize;
2496         int ret = 0;
2497
2498         WARN_ON(*level < 0);
2499         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2500
2501         while (*level > 0) {
2502                 WARN_ON(*level < 0);
2503                 WARN_ON(*level >= BTRFS_MAX_LEVEL);
2504                 cur = path->nodes[*level];
2505
2506                 WARN_ON(btrfs_header_level(cur) != *level);
2507
2508                 if (path->slots[*level] >=
2509                     btrfs_header_nritems(cur))
2510                         break;
2511
2512                 bytenr = btrfs_node_blockptr(cur, path->slots[*level]);
2513                 ptr_gen = btrfs_node_ptr_generation(cur, path->slots[*level]);
2514                 blocksize = fs_info->nodesize;
2515
2516                 parent = path->nodes[*level];
2517                 root_owner = btrfs_header_owner(parent);
2518
2519                 next = btrfs_find_create_tree_block(fs_info, bytenr);
2520                 if (IS_ERR(next))
2521                         return PTR_ERR(next);
2522
2523                 if (*level == 1) {
2524                         ret = wc->process_func(root, next, wc, ptr_gen);
2525                         if (ret) {
2526                                 free_extent_buffer(next);
2527                                 return ret;
2528                         }
2529
2530                         path->slots[*level]++;
2531                         if (wc->free) {
2532                                 ret = btrfs_read_buffer(next, ptr_gen);
2533                                 if (ret) {
2534                                         free_extent_buffer(next);
2535                                         return ret;
2536                                 }
2537
2538                                 if (trans) {
2539                                         btrfs_tree_lock(next);
2540                                         btrfs_set_lock_blocking(next);
2541                                         clean_tree_block(fs_info, next);
2542                                         btrfs_wait_tree_block_writeback(next);
2543                                         btrfs_tree_unlock(next);
2544                                 } else {
2545                                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2546                                                 clear_extent_buffer_dirty(next);
2547                                 }
2548
2549                                 WARN_ON(root_owner !=
2550                                         BTRFS_TREE_LOG_OBJECTID);
2551                                 ret = btrfs_free_and_pin_reserved_extent(
2552                                                         fs_info, bytenr,
2553                                                         blocksize);
2554                                 if (ret) {
2555                                         free_extent_buffer(next);
2556                                         return ret;
2557                                 }
2558                         }
2559                         free_extent_buffer(next);
2560                         continue;
2561                 }
2562                 ret = btrfs_read_buffer(next, ptr_gen);
2563                 if (ret) {
2564                         free_extent_buffer(next);
2565                         return ret;
2566                 }
2567
2568                 WARN_ON(*level <= 0);
2569                 if (path->nodes[*level-1])
2570                         free_extent_buffer(path->nodes[*level-1]);
2571                 path->nodes[*level-1] = next;
2572                 *level = btrfs_header_level(next);
2573                 path->slots[*level] = 0;
2574                 cond_resched();
2575         }
2576         WARN_ON(*level < 0);
2577         WARN_ON(*level >= BTRFS_MAX_LEVEL);
2578
2579         path->slots[*level] = btrfs_header_nritems(path->nodes[*level]);
2580
2581         cond_resched();
2582         return 0;
2583 }
2584
2585 static noinline int walk_up_log_tree(struct btrfs_trans_handle *trans,
2586                                  struct btrfs_root *root,
2587                                  struct btrfs_path *path, int *level,
2588                                  struct walk_control *wc)
2589 {
2590         struct btrfs_fs_info *fs_info = root->fs_info;
2591         u64 root_owner;
2592         int i;
2593         int slot;
2594         int ret;
2595
2596         for (i = *level; i < BTRFS_MAX_LEVEL - 1 && path->nodes[i]; i++) {
2597                 slot = path->slots[i];
2598                 if (slot + 1 < btrfs_header_nritems(path->nodes[i])) {
2599                         path->slots[i]++;
2600                         *level = i;
2601                         WARN_ON(*level == 0);
2602                         return 0;
2603                 } else {
2604                         struct extent_buffer *parent;
2605                         if (path->nodes[*level] == root->node)
2606                                 parent = path->nodes[*level];
2607                         else
2608                                 parent = path->nodes[*level + 1];
2609
2610                         root_owner = btrfs_header_owner(parent);
2611                         ret = wc->process_func(root, path->nodes[*level], wc,
2612                                  btrfs_header_generation(path->nodes[*level]));
2613                         if (ret)
2614                                 return ret;
2615
2616                         if (wc->free) {
2617                                 struct extent_buffer *next;
2618
2619                                 next = path->nodes[*level];
2620
2621                                 if (trans) {
2622                                         btrfs_tree_lock(next);
2623                                         btrfs_set_lock_blocking(next);
2624                                         clean_tree_block(fs_info, next);
2625                                         btrfs_wait_tree_block_writeback(next);
2626                                         btrfs_tree_unlock(next);
2627                                 } else {
2628                                         if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2629                                                 clear_extent_buffer_dirty(next);
2630                                 }
2631
2632                                 WARN_ON(root_owner != BTRFS_TREE_LOG_OBJECTID);
2633                                 ret = btrfs_free_and_pin_reserved_extent(
2634                                                 fs_info,
2635                                                 path->nodes[*level]->start,
2636                                                 path->nodes[*level]->len);
2637                                 if (ret)
2638                                         return ret;
2639                         }
2640                         free_extent_buffer(path->nodes[*level]);
2641                         path->nodes[*level] = NULL;
2642                         *level = i + 1;
2643                 }
2644         }
2645         return 1;
2646 }
2647
2648 /*
2649  * drop the reference count on the tree rooted at 'snap'.  This traverses
2650  * the tree freeing any blocks that have a ref count of zero after being
2651  * decremented.
2652  */
2653 static int walk_log_tree(struct btrfs_trans_handle *trans,
2654                          struct btrfs_root *log, struct walk_control *wc)
2655 {
2656         struct btrfs_fs_info *fs_info = log->fs_info;
2657         int ret = 0;
2658         int wret;
2659         int level;
2660         struct btrfs_path *path;
2661         int orig_level;
2662
2663         path = btrfs_alloc_path();
2664         if (!path)
2665                 return -ENOMEM;
2666
2667         level = btrfs_header_level(log->node);
2668         orig_level = level;
2669         path->nodes[level] = log->node;
2670         extent_buffer_get(log->node);
2671         path->slots[level] = 0;
2672
2673         while (1) {
2674                 wret = walk_down_log_tree(trans, log, path, &level, wc);
2675                 if (wret > 0)
2676                         break;
2677                 if (wret < 0) {
2678                         ret = wret;
2679                         goto out;
2680                 }
2681
2682                 wret = walk_up_log_tree(trans, log, path, &level, wc);
2683                 if (wret > 0)
2684                         break;
2685                 if (wret < 0) {
2686                         ret = wret;
2687                         goto out;
2688                 }
2689         }
2690
2691         /* was the root node processed? if not, catch it here */
2692         if (path->nodes[orig_level]) {
2693                 ret = wc->process_func(log, path->nodes[orig_level], wc,
2694                          btrfs_header_generation(path->nodes[orig_level]));
2695                 if (ret)
2696                         goto out;
2697                 if (wc->free) {
2698                         struct extent_buffer *next;
2699
2700                         next = path->nodes[orig_level];
2701
2702                         if (trans) {
2703                                 btrfs_tree_lock(next);
2704                                 btrfs_set_lock_blocking(next);
2705                                 clean_tree_block(fs_info, next);
2706                                 btrfs_wait_tree_block_writeback(next);
2707                                 btrfs_tree_unlock(next);
2708                         } else {
2709                                 if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &next->bflags))
2710                                         clear_extent_buffer_dirty(next);
2711                         }
2712
2713                         WARN_ON(log->root_key.objectid !=
2714                                 BTRFS_TREE_LOG_OBJECTID);
2715                         ret = btrfs_free_and_pin_reserved_extent(fs_info,
2716                                                         next->start, next->len);
2717                         if (ret)
2718                                 goto out;
2719                 }
2720         }
2721
2722 out:
2723         btrfs_free_path(path);
2724         return ret;
2725 }
2726
2727 /*
2728  * helper function to update the item for a given subvolumes log root
2729  * in the tree of log roots
2730  */
2731 static int update_log_root(struct btrfs_trans_handle *trans,
2732                            struct btrfs_root *log)
2733 {
2734         struct btrfs_fs_info *fs_info = log->fs_info;
2735         int ret;
2736
2737         if (log->log_transid == 1) {
2738                 /* insert root item on the first sync */
2739                 ret = btrfs_insert_root(trans, fs_info->log_root_tree,
2740                                 &log->root_key, &log->root_item);
2741         } else {
2742                 ret = btrfs_update_root(trans, fs_info->log_root_tree,
2743                                 &log->root_key, &log->root_item);
2744         }
2745         return ret;
2746 }
2747
2748 static void wait_log_commit(struct btrfs_root *root, int transid)
2749 {
2750         DEFINE_WAIT(wait);
2751         int index = transid % 2;
2752
2753         /*
2754          * we only allow two pending log transactions at a time,
2755          * so we know that if ours is more than 2 older than the
2756          * current transaction, we're done
2757          */
2758         do {
2759                 prepare_to_wait(&root->log_commit_wait[index],
2760                                 &wait, TASK_UNINTERRUPTIBLE);
2761                 mutex_unlock(&root->log_mutex);
2762
2763                 if (root->log_transid_committed < transid &&
2764                     atomic_read(&root->log_commit[index]))
2765                         schedule();
2766
2767                 finish_wait(&root->log_commit_wait[index], &wait);
2768                 mutex_lock(&root->log_mutex);
2769         } while (root->log_transid_committed < transid &&
2770                  atomic_read(&root->log_commit[index]));
2771 }
2772
2773 static void wait_for_writer(struct btrfs_root *root)
2774 {
2775         DEFINE_WAIT(wait);
2776
2777         while (atomic_read(&root->log_writers)) {
2778                 prepare_to_wait(&root->log_writer_wait,
2779                                 &wait, TASK_UNINTERRUPTIBLE);
2780                 mutex_unlock(&root->log_mutex);
2781                 if (atomic_read(&root->log_writers))
2782                         schedule();
2783                 finish_wait(&root->log_writer_wait, &wait);
2784                 mutex_lock(&root->log_mutex);
2785         }
2786 }
2787
2788 static inline void btrfs_remove_log_ctx(struct btrfs_root *root,
2789                                         struct btrfs_log_ctx *ctx)
2790 {
2791         if (!ctx)
2792                 return;
2793
2794         mutex_lock(&root->log_mutex);
2795         list_del_init(&ctx->list);
2796         mutex_unlock(&root->log_mutex);
2797 }
2798
2799 /* 
2800  * Invoked in log mutex context, or be sure there is no other task which
2801  * can access the list.
2802  */
2803 static inline void btrfs_remove_all_log_ctxs(struct btrfs_root *root,
2804                                              int index, int error)
2805 {
2806         struct btrfs_log_ctx *ctx;
2807         struct btrfs_log_ctx *safe;
2808
2809         list_for_each_entry_safe(ctx, safe, &root->log_ctxs[index], list) {
2810                 list_del_init(&ctx->list);
2811                 ctx->log_ret = error;
2812         }
2813
2814         INIT_LIST_HEAD(&root->log_ctxs[index]);
2815 }
2816
2817 /*
2818  * btrfs_sync_log does sends a given tree log down to the disk and
2819  * updates the super blocks to record it.  When this call is done,
2820  * you know that any inodes previously logged are safely on disk only
2821  * if it returns 0.
2822  *
2823  * Any other return value means you need to call btrfs_commit_transaction.
2824  * Some of the edge cases for fsyncing directories that have had unlinks
2825  * or renames done in the past mean that sometimes the only safe
2826  * fsync is to commit the whole FS.  When btrfs_sync_log returns -EAGAIN,
2827  * that has happened.
2828  */
2829 int btrfs_sync_log(struct btrfs_trans_handle *trans,
2830                    struct btrfs_root *root, struct btrfs_log_ctx *ctx)
2831 {
2832         int index1;
2833         int index2;
2834         int mark;
2835         int ret;
2836         struct btrfs_fs_info *fs_info = root->fs_info;
2837         struct btrfs_root *log = root->log_root;
2838         struct btrfs_root *log_root_tree = fs_info->log_root_tree;
2839         int log_transid = 0;
2840         struct btrfs_log_ctx root_log_ctx;
2841         struct blk_plug plug;
2842
2843         mutex_lock(&root->log_mutex);
2844         log_transid = ctx->log_transid;
2845         if (root->log_transid_committed >= log_transid) {
2846                 mutex_unlock(&root->log_mutex);
2847                 return ctx->log_ret;
2848         }
2849
2850         index1 = log_transid % 2;
2851         if (atomic_read(&root->log_commit[index1])) {
2852                 wait_log_commit(root, log_transid);
2853                 mutex_unlock(&root->log_mutex);
2854                 return ctx->log_ret;
2855         }
2856         ASSERT(log_transid == root->log_transid);
2857         atomic_set(&root->log_commit[index1], 1);
2858
2859         /* wait for previous tree log sync to complete */
2860         if (atomic_read(&root->log_commit[(index1 + 1) % 2]))
2861                 wait_log_commit(root, log_transid - 1);
2862
2863         while (1) {
2864                 int batch = atomic_read(&root->log_batch);
2865                 /* when we're on an ssd, just kick the log commit out */
2866                 if (!btrfs_test_opt(fs_info, SSD) &&
2867                     test_bit(BTRFS_ROOT_MULTI_LOG_TASKS, &root->state)) {
2868                         mutex_unlock(&root->log_mutex);
2869                         schedule_timeout_uninterruptible(1);
2870                         mutex_lock(&root->log_mutex);
2871                 }
2872                 wait_for_writer(root);
2873                 if (batch == atomic_read(&root->log_batch))
2874                         break;
2875         }
2876
2877         /* bail out if we need to do a full commit */
2878         if (btrfs_need_log_full_commit(fs_info, trans)) {
2879                 ret = -EAGAIN;
2880                 btrfs_free_logged_extents(log, log_transid);
2881                 mutex_unlock(&root->log_mutex);
2882                 goto out;
2883         }
2884
2885         if (log_transid % 2 == 0)
2886                 mark = EXTENT_DIRTY;
2887         else
2888                 mark = EXTENT_NEW;
2889
2890         /* we start IO on  all the marked extents here, but we don't actually
2891          * wait for them until later.
2892          */
2893         blk_start_plug(&plug);
2894         ret = btrfs_write_marked_extents(fs_info, &log->dirty_log_pages, mark);
2895         if (ret) {
2896                 blk_finish_plug(&plug);
2897                 btrfs_abort_transaction(trans, ret);
2898                 btrfs_free_logged_extents(log, log_transid);
2899                 btrfs_set_log_full_commit(fs_info, trans);
2900                 mutex_unlock(&root->log_mutex);
2901                 goto out;
2902         }
2903
2904         btrfs_set_root_node(&log->root_item, log->node);
2905
2906         root->log_transid++;
2907         log->log_transid = root->log_transid;
2908         root->log_start_pid = 0;
2909         /*
2910          * IO has been started, blocks of the log tree have WRITTEN flag set
2911          * in their headers. new modifications of the log will be written to
2912          * new positions. so it's safe to allow log writers to go in.
2913          */
2914         mutex_unlock(&root->log_mutex);
2915
2916         btrfs_init_log_ctx(&root_log_ctx, NULL);
2917
2918         mutex_lock(&log_root_tree->log_mutex);
2919         atomic_inc(&log_root_tree->log_batch);
2920         atomic_inc(&log_root_tree->log_writers);
2921
2922         index2 = log_root_tree->log_transid % 2;
2923         list_add_tail(&root_log_ctx.list, &log_root_tree->log_ctxs[index2]);
2924         root_log_ctx.log_transid = log_root_tree->log_transid;
2925
2926         mutex_unlock(&log_root_tree->log_mutex);
2927
2928         ret = update_log_root(trans, log);
2929
2930         mutex_lock(&log_root_tree->log_mutex);
2931         if (atomic_dec_and_test(&log_root_tree->log_writers)) {
2932                 /*
2933                  * Implicit memory barrier after atomic_dec_and_test
2934                  */
2935                 if (waitqueue_active(&log_root_tree->log_writer_wait))
2936                         wake_up(&log_root_tree->log_writer_wait);
2937         }
2938
2939         if (ret) {
2940                 if (!list_empty(&root_log_ctx.list))
2941                         list_del_init(&root_log_ctx.list);
2942
2943                 blk_finish_plug(&plug);
2944                 btrfs_set_log_full_commit(fs_info, trans);
2945
2946                 if (ret != -ENOSPC) {
2947                         btrfs_abort_transaction(trans, ret);
2948                         mutex_unlock(&log_root_tree->log_mutex);
2949                         goto out;
2950                 }
2951                 btrfs_wait_tree_log_extents(log, mark);
2952                 btrfs_free_logged_extents(log, log_transid);
2953                 mutex_unlock(&log_root_tree->log_mutex);
2954                 ret = -EAGAIN;
2955                 goto out;
2956         }
2957
2958         if (log_root_tree->log_transid_committed >= root_log_ctx.log_transid) {
2959                 blk_finish_plug(&plug);
2960                 list_del_init(&root_log_ctx.list);
2961                 mutex_unlock(&log_root_tree->log_mutex);
2962                 ret = root_log_ctx.log_ret;
2963                 goto out;
2964         }
2965
2966         index2 = root_log_ctx.log_transid % 2;
2967         if (atomic_read(&log_root_tree->log_commit[index2])) {
2968                 blk_finish_plug(&plug);
2969                 ret = btrfs_wait_tree_log_extents(log, mark);
2970                 btrfs_wait_logged_extents(trans, log, log_transid);
2971                 wait_log_commit(log_root_tree,
2972                                 root_log_ctx.log_transid);
2973                 mutex_unlock(&log_root_tree->log_mutex);
2974                 if (!ret)
2975                         ret = root_log_ctx.log_ret;
2976                 goto out;
2977         }
2978         ASSERT(root_log_ctx.log_transid == log_root_tree->log_transid);
2979         atomic_set(&log_root_tree->log_commit[index2], 1);
2980
2981         if (atomic_read(&log_root_tree->log_commit[(index2 + 1) % 2])) {
2982                 wait_log_commit(log_root_tree,
2983                                 root_log_ctx.log_transid - 1);
2984         }
2985
2986         wait_for_writer(log_root_tree);
2987
2988         /*
2989          * now that we've moved on to the tree of log tree roots,
2990          * check the full commit flag again
2991          */
2992         if (btrfs_need_log_full_commit(fs_info, trans)) {
2993                 blk_finish_plug(&plug);
2994                 btrfs_wait_tree_log_extents(log, mark);
2995                 btrfs_free_logged_extents(log, log_transid);
2996                 mutex_unlock(&log_root_tree->log_mutex);
2997                 ret = -EAGAIN;
2998                 goto out_wake_log_root;
2999         }
3000
3001         ret = btrfs_write_marked_extents(fs_info,
3002                                          &log_root_tree->dirty_log_pages,
3003                                          EXTENT_DIRTY | EXTENT_NEW);
3004         blk_finish_plug(&plug);
3005         if (ret) {
3006                 btrfs_set_log_full_commit(fs_info, trans);
3007                 btrfs_abort_transaction(trans, ret);
3008                 btrfs_free_logged_extents(log, log_transid);
3009                 mutex_unlock(&log_root_tree->log_mutex);
3010                 goto out_wake_log_root;
3011         }
3012         ret = btrfs_wait_tree_log_extents(log, mark);
3013         if (!ret)
3014                 ret = btrfs_wait_tree_log_extents(log_root_tree,
3015                                                   EXTENT_NEW | EXTENT_DIRTY);
3016         if (ret) {
3017                 btrfs_set_log_full_commit(fs_info, trans);
3018                 btrfs_free_logged_extents(log, log_transid);
3019                 mutex_unlock(&log_root_tree->log_mutex);
3020                 goto out_wake_log_root;
3021         }
3022         btrfs_wait_logged_extents(trans, log, log_transid);
3023
3024         btrfs_set_super_log_root(fs_info->super_for_commit,
3025                                  log_root_tree->node->start);
3026         btrfs_set_super_log_root_level(fs_info->super_for_commit,
3027                                        btrfs_header_level(log_root_tree->node));
3028
3029         log_root_tree->log_transid++;
3030         mutex_unlock(&log_root_tree->log_mutex);
3031
3032         /*
3033          * nobody else is going to jump in and write the the ctree
3034          * super here because the log_commit atomic below is protecting
3035          * us.  We must be called with a transaction handle pinning
3036          * the running transaction open, so a full commit can't hop
3037          * in and cause problems either.
3038          */
3039         ret = write_all_supers(fs_info, 1);
3040         if (ret) {
3041                 btrfs_set_log_full_commit(fs_info, trans);
3042                 btrfs_abort_transaction(trans, ret);
3043                 goto out_wake_log_root;
3044         }
3045
3046         mutex_lock(&root->log_mutex);
3047         if (root->last_log_commit < log_transid)
3048                 root->last_log_commit = log_transid;
3049         mutex_unlock(&root->log_mutex);
3050
3051 out_wake_log_root:
3052         mutex_lock(&log_root_tree->log_mutex);
3053         btrfs_remove_all_log_ctxs(log_root_tree, index2, ret);
3054
3055         log_root_tree->log_transid_committed++;
3056         atomic_set(&log_root_tree->log_commit[index2], 0);
3057         mutex_unlock(&log_root_tree->log_mutex);
3058
3059         /*
3060          * The barrier before waitqueue_active is needed so all the updates
3061          * above are seen by the woken threads. It might not be necessary, but
3062          * proving that seems to be hard.
3063          */
3064         smp_mb();
3065         if (waitqueue_active(&log_root_tree->log_commit_wait[index2]))
3066                 wake_up(&log_root_tree->log_commit_wait[index2]);
3067 out:
3068         mutex_lock(&root->log_mutex);
3069         btrfs_remove_all_log_ctxs(root, index1, ret);
3070         root->log_transid_committed++;
3071         atomic_set(&root->log_commit[index1], 0);
3072         mutex_unlock(&root->log_mutex);
3073
3074         /*
3075          * The barrier before waitqueue_active is needed so all the updates
3076          * above are seen by the woken threads. It might not be necessary, but
3077          * proving that seems to be hard.
3078          */
3079         smp_mb();
3080         if (waitqueue_active(&root->log_commit_wait[index1]))
3081                 wake_up(&root->log_commit_wait[index1]);
3082         return ret;
3083 }
3084
3085 static void free_log_tree(struct btrfs_trans_handle *trans,
3086                           struct btrfs_root *log)
3087 {
3088         int ret;
3089         u64 start;
3090         u64 end;
3091         struct walk_control wc = {
3092                 .free = 1,
3093                 .process_func = process_one_buffer
3094         };
3095
3096         ret = walk_log_tree(trans, log, &wc);
3097         if (ret) {
3098                 if (trans)
3099                         btrfs_abort_transaction(trans, ret);
3100                 else
3101                         btrfs_handle_fs_error(log->fs_info, ret, NULL);
3102         }
3103
3104         while (1) {
3105                 ret = find_first_extent_bit(&log->dirty_log_pages,
3106                                 0, &start, &end,
3107                                 EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT,
3108                                 NULL);
3109                 if (ret)
3110                         break;
3111
3112                 clear_extent_bits(&log->dirty_log_pages, start, end,
3113                                   EXTENT_DIRTY | EXTENT_NEW | EXTENT_NEED_WAIT);
3114         }
3115
3116         /*
3117          * We may have short-circuited the log tree with the full commit logic
3118          * and left ordered extents on our list, so clear these out to keep us
3119          * from leaking inodes and memory.
3120          */
3121         btrfs_free_logged_extents(log, 0);
3122         btrfs_free_logged_extents(log, 1);
3123
3124         free_extent_buffer(log->node);
3125         kfree(log);
3126 }
3127
3128 /*
3129  * free all the extents used by the tree log.  This should be called
3130  * at commit time of the full transaction
3131  */
3132 int btrfs_free_log(struct btrfs_trans_handle *trans, struct btrfs_root *root)
3133 {
3134         if (root->log_root) {
3135                 free_log_tree(trans, root->log_root);
3136                 root->log_root = NULL;
3137         }
3138         return 0;
3139 }
3140
3141 int btrfs_free_log_root_tree(struct btrfs_trans_handle *trans,
3142                              struct btrfs_fs_info *fs_info)
3143 {
3144         if (fs_info->log_root_tree) {
3145                 free_log_tree(trans, fs_info->log_root_tree);
3146                 fs_info->log_root_tree = NULL;
3147         }
3148         return 0;
3149 }
3150
3151 /*
3152  * If both a file and directory are logged, and unlinks or renames are
3153  * mixed in, we have a few interesting corners:
3154  *
3155  * create file X in dir Y
3156  * link file X to X.link in dir Y
3157  * fsync file X
3158  * unlink file X but leave X.link
3159  * fsync dir Y
3160  *
3161  * After a crash we would expect only X.link to exist.  But file X
3162  * didn't get fsync'd again so the log has back refs for X and X.link.
3163  *
3164  * We solve this by removing directory entries and inode backrefs from the
3165  * log when a file that was logged in the current transaction is
3166  * unlinked.  Any later fsync will include the updated log entries, and
3167  * we'll be able to reconstruct the proper directory items from backrefs.
3168  *
3169  * This optimizations allows us to avoid relogging the entire inode
3170  * or the entire directory.
3171  */
3172 int btrfs_del_dir_entries_in_log(struct btrfs_trans_handle *trans,
3173                                  struct btrfs_root *root,
3174                                  const char *name, int name_len,
3175                                  struct btrfs_inode *dir, u64 index)
3176 {
3177         struct btrfs_root *log;
3178         struct btrfs_dir_item *di;
3179         struct btrfs_path *path;
3180         int ret;
3181         int err = 0;
3182         int bytes_del = 0;
3183         u64 dir_ino = btrfs_ino(dir);
3184
3185         if (dir->logged_trans < trans->transid)
3186                 return 0;
3187
3188         ret = join_running_log_trans(root);
3189         if (ret)
3190                 return 0;
3191
3192         mutex_lock(&dir->log_mutex);
3193
3194         log = root->log_root;
3195         path = btrfs_alloc_path();
3196         if (!path) {
3197                 err = -ENOMEM;
3198                 goto out_unlock;
3199         }
3200
3201         di = btrfs_lookup_dir_item(trans, log, path, dir_ino,
3202                                    name, name_len, -1);
3203         if (IS_ERR(di)) {
3204                 err = PTR_ERR(di);
3205                 goto fail;
3206         }
3207         if (di) {
3208                 ret = btrfs_delete_one_dir_name(trans, log, path, di);
3209                 bytes_del += name_len;
3210                 if (ret) {
3211                         err = ret;
3212                         goto fail;
3213                 }
3214         }
3215         btrfs_release_path(path);
3216         di = btrfs_lookup_dir_index_item(trans, log, path, dir_ino,
3217                                          index, name, name_len, -1);
3218         if (IS_ERR(di)) {
3219                 err = PTR_ERR(di);
3220                 goto fail;
3221         }
3222         if (di) {
3223                 ret = btrfs_delete_one_dir_name(trans, log, path, di);
3224                 bytes_del += name_len;
3225                 if (ret) {
3226                         err = ret;
3227                         goto fail;
3228                 }
3229         }
3230
3231         /* update the directory size in the log to reflect the names
3232          * we have removed
3233          */
3234         if (bytes_del) {
3235                 struct btrfs_key key;
3236
3237                 key.objectid = dir_ino;
3238                 key.offset = 0;
3239                 key.type = BTRFS_INODE_ITEM_KEY;
3240                 btrfs_release_path(path);
3241
3242                 ret = btrfs_search_slot(trans, log, &key, path, 0, 1);
3243                 if (ret < 0) {
3244                         err = ret;
3245                         goto fail;
3246                 }
3247                 if (ret == 0) {
3248                         struct btrfs_inode_item *item;
3249                         u64 i_size;
3250
3251                         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3252                                               struct btrfs_inode_item);
3253                         i_size = btrfs_inode_size(path->nodes[0], item);
3254                         if (i_size > bytes_del)
3255                                 i_size -= bytes_del;
3256                         else
3257                                 i_size = 0;
3258                         btrfs_set_inode_size(path->nodes[0], item, i_size);
3259                         btrfs_mark_buffer_dirty(path->nodes[0]);
3260                 } else
3261                         ret = 0;
3262                 btrfs_release_path(path);
3263         }
3264 fail:
3265         btrfs_free_path(path);
3266 out_unlock:
3267         mutex_unlock(&dir->log_mutex);
3268         if (ret == -ENOSPC) {
3269                 btrfs_set_log_full_commit(root->fs_info, trans);
3270                 ret = 0;
3271         } else if (ret < 0)
3272                 btrfs_abort_transaction(trans, ret);
3273
3274         btrfs_end_log_trans(root);
3275
3276         return err;
3277 }
3278
3279 /* see comments for btrfs_del_dir_entries_in_log */
3280 int btrfs_del_inode_ref_in_log(struct btrfs_trans_handle *trans,
3281                                struct btrfs_root *root,
3282                                const char *name, int name_len,
3283                                struct btrfs_inode *inode, u64 dirid)
3284 {
3285         struct btrfs_fs_info *fs_info = root->fs_info;
3286         struct btrfs_root *log;
3287         u64 index;
3288         int ret;
3289
3290         if (inode->logged_trans < trans->transid)
3291                 return 0;
3292
3293         ret = join_running_log_trans(root);
3294         if (ret)
3295                 return 0;
3296         log = root->log_root;
3297         mutex_lock(&inode->log_mutex);
3298
3299         ret = btrfs_del_inode_ref(trans, log, name, name_len, btrfs_ino(inode),
3300                                   dirid, &index);
3301         mutex_unlock(&inode->log_mutex);
3302         if (ret == -ENOSPC) {
3303                 btrfs_set_log_full_commit(fs_info, trans);
3304                 ret = 0;
3305         } else if (ret < 0 && ret != -ENOENT)
3306                 btrfs_abort_transaction(trans, ret);
3307         btrfs_end_log_trans(root);
3308
3309         return ret;
3310 }
3311
3312 /*
3313  * creates a range item in the log for 'dirid'.  first_offset and
3314  * last_offset tell us which parts of the key space the log should
3315  * be considered authoritative for.
3316  */
3317 static noinline int insert_dir_log_key(struct btrfs_trans_handle *trans,
3318                                        struct btrfs_root *log,
3319                                        struct btrfs_path *path,
3320                                        int key_type, u64 dirid,
3321                                        u64 first_offset, u64 last_offset)
3322 {
3323         int ret;
3324         struct btrfs_key key;
3325         struct btrfs_dir_log_item *item;
3326
3327         key.objectid = dirid;
3328         key.offset = first_offset;
3329         if (key_type == BTRFS_DIR_ITEM_KEY)
3330                 key.type = BTRFS_DIR_LOG_ITEM_KEY;
3331         else
3332                 key.type = BTRFS_DIR_LOG_INDEX_KEY;
3333         ret = btrfs_insert_empty_item(trans, log, path, &key, sizeof(*item));
3334         if (ret)
3335                 return ret;
3336
3337         item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3338                               struct btrfs_dir_log_item);
3339         btrfs_set_dir_log_end(path->nodes[0], item, last_offset);
3340         btrfs_mark_buffer_dirty(path->nodes[0]);
3341         btrfs_release_path(path);
3342         return 0;
3343 }
3344
3345 /*
3346  * log all the items included in the current transaction for a given
3347  * directory.  This also creates the range items in the log tree required
3348  * to replay anything deleted before the fsync
3349  */
3350 static noinline int log_dir_items(struct btrfs_trans_handle *trans,
3351                           struct btrfs_root *root, struct btrfs_inode *inode,
3352                           struct btrfs_path *path,
3353                           struct btrfs_path *dst_path, int key_type,
3354                           struct btrfs_log_ctx *ctx,
3355                           u64 min_offset, u64 *last_offset_ret)
3356 {
3357         struct btrfs_key min_key;
3358         struct btrfs_root *log = root->log_root;
3359         struct extent_buffer *src;
3360         int err = 0;
3361         int ret;
3362         int i;
3363         int nritems;
3364         u64 first_offset = min_offset;
3365         u64 last_offset = (u64)-1;
3366         u64 ino = btrfs_ino(inode);
3367
3368         log = root->log_root;
3369
3370         min_key.objectid = ino;
3371         min_key.type = key_type;
3372         min_key.offset = min_offset;
3373
3374         ret = btrfs_search_forward(root, &min_key, path, trans->transid);
3375
3376         /*
3377          * we didn't find anything from this transaction, see if there
3378          * is anything at all
3379          */
3380         if (ret != 0 || min_key.objectid != ino || min_key.type != key_type) {
3381                 min_key.objectid = ino;
3382                 min_key.type = key_type;
3383                 min_key.offset = (u64)-1;
3384                 btrfs_release_path(path);
3385                 ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3386                 if (ret < 0) {
3387                         btrfs_release_path(path);
3388                         return ret;
3389                 }
3390                 ret = btrfs_previous_item(root, path, ino, key_type);
3391
3392                 /* if ret == 0 there are items for this type,
3393                  * create a range to tell us the last key of this type.
3394                  * otherwise, there are no items in this directory after
3395                  * *min_offset, and we create a range to indicate that.
3396                  */
3397                 if (ret == 0) {
3398                         struct btrfs_key tmp;
3399                         btrfs_item_key_to_cpu(path->nodes[0], &tmp,
3400                                               path->slots[0]);
3401                         if (key_type == tmp.type)
3402                                 first_offset = max(min_offset, tmp.offset) + 1;
3403                 }
3404                 goto done;
3405         }
3406
3407         /* go backward to find any previous key */
3408         ret = btrfs_previous_item(root, path, ino, key_type);
3409         if (ret == 0) {
3410                 struct btrfs_key tmp;
3411                 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3412                 if (key_type == tmp.type) {
3413                         first_offset = tmp.offset;
3414                         ret = overwrite_item(trans, log, dst_path,
3415                                              path->nodes[0], path->slots[0],
3416                                              &tmp);
3417                         if (ret) {
3418                                 err = ret;
3419                                 goto done;
3420                         }
3421                 }
3422         }
3423         btrfs_release_path(path);
3424
3425         /* find the first key from this transaction again */
3426         ret = btrfs_search_slot(NULL, root, &min_key, path, 0, 0);
3427         if (WARN_ON(ret != 0))
3428                 goto done;
3429
3430         /*
3431          * we have a block from this transaction, log every item in it
3432          * from our directory
3433          */
3434         while (1) {
3435                 struct btrfs_key tmp;
3436                 src = path->nodes[0];
3437                 nritems = btrfs_header_nritems(src);
3438                 for (i = path->slots[0]; i < nritems; i++) {
3439                         struct btrfs_dir_item *di;
3440
3441                         btrfs_item_key_to_cpu(src, &min_key, i);
3442
3443                         if (min_key.objectid != ino || min_key.type != key_type)
3444                                 goto done;
3445                         ret = overwrite_item(trans, log, dst_path, src, i,
3446                                              &min_key);
3447                         if (ret) {
3448                                 err = ret;
3449                                 goto done;
3450                         }
3451
3452                         /*
3453                          * We must make sure that when we log a directory entry,
3454                          * the corresponding inode, after log replay, has a
3455                          * matching link count. For example:
3456                          *
3457                          * touch foo
3458                          * mkdir mydir
3459                          * sync
3460                          * ln foo mydir/bar
3461                          * xfs_io -c "fsync" mydir
3462                          * <crash>
3463                          * <mount fs and log replay>
3464                          *
3465                          * Would result in a fsync log that when replayed, our
3466                          * file inode would have a link count of 1, but we get
3467                          * two directory entries pointing to the same inode.
3468                          * After removing one of the names, it would not be
3469                          * possible to remove the other name, which resulted
3470                          * always in stale file handle errors, and would not
3471                          * be possible to rmdir the parent directory, since
3472                          * its i_size could never decrement to the value
3473                          * BTRFS_EMPTY_DIR_SIZE, resulting in -ENOTEMPTY errors.
3474                          */
3475                         di = btrfs_item_ptr(src, i, struct btrfs_dir_item);
3476                         btrfs_dir_item_key_to_cpu(src, di, &tmp);
3477                         if (ctx &&
3478                             (btrfs_dir_transid(src, di) == trans->transid ||
3479                              btrfs_dir_type(src, di) == BTRFS_FT_DIR) &&
3480                             tmp.type != BTRFS_ROOT_ITEM_KEY)
3481                                 ctx->log_new_dentries = true;
3482                 }
3483                 path->slots[0] = nritems;
3484
3485                 /*
3486                  * look ahead to the next item and see if it is also
3487                  * from this directory and from this transaction
3488                  */
3489                 ret = btrfs_next_leaf(root, path);
3490                 if (ret) {
3491                         if (ret == 1)
3492                                 last_offset = (u64)-1;
3493                         else
3494                                 err = ret;
3495                         goto done;
3496                 }
3497                 btrfs_item_key_to_cpu(path->nodes[0], &tmp, path->slots[0]);
3498                 if (tmp.objectid != ino || tmp.type != key_type) {
3499                         last_offset = (u64)-1;
3500                         goto done;
3501                 }
3502                 if (btrfs_header_generation(path->nodes[0]) != trans->transid) {
3503                         ret = overwrite_item(trans, log, dst_path,
3504                                              path->nodes[0], path->slots[0],
3505                                              &tmp);
3506                         if (ret)
3507                                 err = ret;
3508                         else
3509                                 last_offset = tmp.offset;
3510                         goto done;
3511                 }
3512         }
3513 done:
3514         btrfs_release_path(path);
3515         btrfs_release_path(dst_path);
3516
3517         if (err == 0) {
3518                 *last_offset_ret = last_offset;
3519                 /*
3520                  * insert the log range keys to indicate where the log
3521                  * is valid
3522                  */
3523                 ret = insert_dir_log_key(trans, log, path, key_type,
3524                                          ino, first_offset, last_offset);
3525                 if (ret)
3526                         err = ret;
3527         }
3528         return err;
3529 }
3530
3531 /*
3532  * logging directories is very similar to logging inodes, We find all the items
3533  * from the current transaction and write them to the log.
3534  *
3535  * The recovery code scans the directory in the subvolume, and if it finds a
3536  * key in the range logged that is not present in the log tree, then it means
3537  * that dir entry was unlinked during the transaction.
3538  *
3539  * In order for that scan to work, we must include one key smaller than
3540  * the smallest logged by this transaction and one key larger than the largest
3541  * key logged by this transaction.
3542  */
3543 static noinline int log_directory_changes(struct btrfs_trans_handle *trans,
3544                           struct btrfs_root *root, struct btrfs_inode *inode,
3545                           struct btrfs_path *path,
3546                           struct btrfs_path *dst_path,
3547                           struct btrfs_log_ctx *ctx)
3548 {
3549         u64 min_key;
3550         u64 max_key;
3551         int ret;
3552         int key_type = BTRFS_DIR_ITEM_KEY;
3553
3554 again:
3555         min_key = 0;
3556         max_key = 0;
3557         while (1) {
3558                 ret = log_dir_items(trans, root, inode, path, dst_path, key_type,
3559                                 ctx, min_key, &max_key);
3560                 if (ret)
3561                         return ret;
3562                 if (max_key == (u64)-1)
3563                         break;
3564                 min_key = max_key + 1;
3565         }
3566
3567         if (key_type == BTRFS_DIR_ITEM_KEY) {
3568                 key_type = BTRFS_DIR_INDEX_KEY;
3569                 goto again;
3570         }
3571         return 0;
3572 }
3573
3574 /*
3575  * a helper function to drop items from the log before we relog an
3576  * inode.  max_key_type indicates the highest item type to remove.
3577  * This cannot be run for file data extents because it does not
3578  * free the extents they point to.
3579  */
3580 static int drop_objectid_items(struct btrfs_trans_handle *trans,
3581                                   struct btrfs_root *log,
3582                                   struct btrfs_path *path,
3583                                   u64 objectid, int max_key_type)
3584 {
3585         int ret;
3586         struct btrfs_key key;
3587         struct btrfs_key found_key;
3588         int start_slot;
3589
3590         key.objectid = objectid;
3591         key.type = max_key_type;
3592         key.offset = (u64)-1;
3593
3594         while (1) {
3595                 ret = btrfs_search_slot(trans, log, &key, path, -1, 1);
3596                 BUG_ON(ret == 0); /* Logic error */
3597                 if (ret < 0)
3598                         break;
3599
3600                 if (path->slots[0] == 0)
3601                         break;
3602
3603                 path->slots[0]--;
3604                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
3605                                       path->slots[0]);
3606
3607                 if (found_key.objectid != objectid)
3608                         break;
3609
3610                 found_key.offset = 0;
3611                 found_key.type = 0;
3612                 ret = btrfs_bin_search(path->nodes[0], &found_key, 0,
3613                                        &start_slot);
3614
3615                 ret = btrfs_del_items(trans, log, path, start_slot,
3616                                       path->slots[0] - start_slot + 1);
3617                 /*
3618                  * If start slot isn't 0 then we don't need to re-search, we've
3619                  * found the last guy with the objectid in this tree.
3620                  */
3621                 if (ret || start_slot != 0)
3622                         break;
3623                 btrfs_release_path(path);
3624         }
3625         btrfs_release_path(path);
3626         if (ret > 0)
3627                 ret = 0;
3628         return ret;
3629 }
3630
3631 static void fill_inode_item(struct btrfs_trans_handle *trans,
3632                             struct extent_buffer *leaf,
3633                             struct btrfs_inode_item *item,
3634                             struct inode *inode, int log_inode_only,
3635                             u64 logged_isize)
3636 {
3637         struct btrfs_map_token token;
3638
3639         btrfs_init_map_token(&token);
3640
3641         if (log_inode_only) {
3642                 /* set the generation to zero so the recover code
3643                  * can tell the difference between an logging
3644                  * just to say 'this inode exists' and a logging
3645                  * to say 'update this inode with these values'
3646                  */
3647                 btrfs_set_token_inode_generation(leaf, item, 0, &token);
3648                 btrfs_set_token_inode_size(leaf, item, logged_isize, &token);
3649         } else {
3650                 btrfs_set_token_inode_generation(leaf, item,
3651                                                  BTRFS_I(inode)->generation,
3652                                                  &token);
3653                 btrfs_set_token_inode_size(leaf, item, inode->i_size, &token);
3654         }
3655
3656         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3657         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3658         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3659         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3660
3661         btrfs_set_token_timespec_sec(leaf, &item->atime,
3662                                      inode->i_atime.tv_sec, &token);
3663         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3664                                       inode->i_atime.tv_nsec, &token);
3665
3666         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3667                                      inode->i_mtime.tv_sec, &token);
3668         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3669                                       inode->i_mtime.tv_nsec, &token);
3670
3671         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3672                                      inode->i_ctime.tv_sec, &token);
3673         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3674                                       inode->i_ctime.tv_nsec, &token);
3675
3676         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3677                                      &token);
3678
3679         btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3680         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3681         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3682         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3683         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3684 }
3685
3686 static int log_inode_item(struct btrfs_trans_handle *trans,
3687                           struct btrfs_root *log, struct btrfs_path *path,
3688                           struct btrfs_inode *inode)
3689 {
3690         struct btrfs_inode_item *inode_item;
3691         int ret;
3692
3693         ret = btrfs_insert_empty_item(trans, log, path,
3694                                       &inode->location, sizeof(*inode_item));
3695         if (ret && ret != -EEXIST)
3696                 return ret;
3697         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
3698                                     struct btrfs_inode_item);
3699         fill_inode_item(trans, path->nodes[0], inode_item, &inode->vfs_inode,
3700                         0, 0);
3701         btrfs_release_path(path);
3702         return 0;
3703 }
3704
3705 static noinline int copy_items(struct btrfs_trans_handle *trans,
3706                                struct btrfs_inode *inode,
3707                                struct btrfs_path *dst_path,
3708                                struct btrfs_path *src_path, u64 *last_extent,
3709                                int start_slot, int nr, int inode_only,
3710                                u64 logged_isize)
3711 {
3712         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3713         unsigned long src_offset;
3714         unsigned long dst_offset;
3715         struct btrfs_root *log = inode->root->log_root;
3716         struct btrfs_file_extent_item *extent;
3717         struct btrfs_inode_item *inode_item;
3718         struct extent_buffer *src = src_path->nodes[0];
3719         struct btrfs_key first_key, last_key, key;
3720         int ret;
3721         struct btrfs_key *ins_keys;
3722         u32 *ins_sizes;
3723         char *ins_data;
3724         int i;
3725         struct list_head ordered_sums;
3726         int skip_csum = inode->flags & BTRFS_INODE_NODATASUM;
3727         bool has_extents = false;
3728         bool need_find_last_extent = true;
3729         bool done = false;
3730
3731         INIT_LIST_HEAD(&ordered_sums);
3732
3733         ins_data = kmalloc(nr * sizeof(struct btrfs_key) +
3734                            nr * sizeof(u32), GFP_NOFS);
3735         if (!ins_data)
3736                 return -ENOMEM;
3737
3738         first_key.objectid = (u64)-1;
3739
3740         ins_sizes = (u32 *)ins_data;
3741         ins_keys = (struct btrfs_key *)(ins_data + nr * sizeof(u32));
3742
3743         for (i = 0; i < nr; i++) {
3744                 ins_sizes[i] = btrfs_item_size_nr(src, i + start_slot);
3745                 btrfs_item_key_to_cpu(src, ins_keys + i, i + start_slot);
3746         }
3747         ret = btrfs_insert_empty_items(trans, log, dst_path,
3748                                        ins_keys, ins_sizes, nr);
3749         if (ret) {
3750                 kfree(ins_data);
3751                 return ret;
3752         }
3753
3754         for (i = 0; i < nr; i++, dst_path->slots[0]++) {
3755                 dst_offset = btrfs_item_ptr_offset(dst_path->nodes[0],
3756                                                    dst_path->slots[0]);
3757
3758                 src_offset = btrfs_item_ptr_offset(src, start_slot + i);
3759
3760                 if (i == nr - 1)
3761                         last_key = ins_keys[i];
3762
3763                 if (ins_keys[i].type == BTRFS_INODE_ITEM_KEY) {
3764                         inode_item = btrfs_item_ptr(dst_path->nodes[0],
3765                                                     dst_path->slots[0],
3766                                                     struct btrfs_inode_item);
3767                         fill_inode_item(trans, dst_path->nodes[0], inode_item,
3768                                         &inode->vfs_inode,
3769                                         inode_only == LOG_INODE_EXISTS,
3770                                         logged_isize);
3771                 } else {
3772                         copy_extent_buffer(dst_path->nodes[0], src, dst_offset,
3773                                            src_offset, ins_sizes[i]);
3774                 }
3775
3776                 /*
3777                  * We set need_find_last_extent here in case we know we were
3778                  * processing other items and then walk into the first extent in
3779                  * the inode.  If we don't hit an extent then nothing changes,
3780                  * we'll do the last search the next time around.
3781                  */
3782                 if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY) {
3783                         has_extents = true;
3784                         if (first_key.objectid == (u64)-1)
3785                                 first_key = ins_keys[i];
3786                 } else {
3787                         need_find_last_extent = false;
3788                 }
3789
3790                 /* take a reference on file data extents so that truncates
3791                  * or deletes of this inode don't have to relog the inode
3792                  * again
3793                  */
3794                 if (ins_keys[i].type == BTRFS_EXTENT_DATA_KEY &&
3795                     !skip_csum) {
3796                         int found_type;
3797                         extent = btrfs_item_ptr(src, start_slot + i,
3798                                                 struct btrfs_file_extent_item);
3799
3800                         if (btrfs_file_extent_generation(src, extent) < trans->transid)
3801                                 continue;
3802
3803                         found_type = btrfs_file_extent_type(src, extent);
3804                         if (found_type == BTRFS_FILE_EXTENT_REG) {
3805                                 u64 ds, dl, cs, cl;
3806                                 ds = btrfs_file_extent_disk_bytenr(src,
3807                                                                 extent);
3808                                 /* ds == 0 is a hole */
3809                                 if (ds == 0)
3810                                         continue;
3811
3812                                 dl = btrfs_file_extent_disk_num_bytes(src,
3813                                                                 extent);
3814                                 cs = btrfs_file_extent_offset(src, extent);
3815                                 cl = btrfs_file_extent_num_bytes(src,
3816                                                                 extent);
3817                                 if (btrfs_file_extent_compression(src,
3818                                                                   extent)) {
3819                                         cs = 0;
3820                                         cl = dl;
3821                                 }
3822
3823                                 ret = btrfs_lookup_csums_range(
3824                                                 fs_info->csum_root,
3825                                                 ds + cs, ds + cs + cl - 1,
3826                                                 &ordered_sums, 0);
3827                                 if (ret) {
3828                                         btrfs_release_path(dst_path);
3829                                         kfree(ins_data);
3830                                         return ret;
3831                                 }
3832                         }
3833                 }
3834         }
3835
3836         btrfs_mark_buffer_dirty(dst_path->nodes[0]);
3837         btrfs_release_path(dst_path);
3838         kfree(ins_data);
3839
3840         /*
3841          * we have to do this after the loop above to avoid changing the
3842          * log tree while trying to change the log tree.
3843          */
3844         ret = 0;
3845         while (!list_empty(&ordered_sums)) {
3846                 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
3847                                                    struct btrfs_ordered_sum,
3848                                                    list);
3849                 if (!ret)
3850                         ret = btrfs_csum_file_blocks(trans, log, sums);
3851                 list_del(&sums->list);
3852                 kfree(sums);
3853         }
3854
3855         if (!has_extents)
3856                 return ret;
3857
3858         if (need_find_last_extent && *last_extent == first_key.offset) {
3859                 /*
3860                  * We don't have any leafs between our current one and the one
3861                  * we processed before that can have file extent items for our
3862                  * inode (and have a generation number smaller than our current
3863                  * transaction id).
3864                  */
3865                 need_find_last_extent = false;
3866         }
3867
3868         /*
3869          * Because we use btrfs_search_forward we could skip leaves that were
3870          * not modified and then assume *last_extent is valid when it really
3871          * isn't.  So back up to the previous leaf and read the end of the last
3872          * extent before we go and fill in holes.
3873          */
3874         if (need_find_last_extent) {
3875                 u64 len;
3876
3877                 ret = btrfs_prev_leaf(inode->root, src_path);
3878                 if (ret < 0)
3879                         return ret;
3880                 if (ret)
3881                         goto fill_holes;
3882                 if (src_path->slots[0])
3883                         src_path->slots[0]--;
3884                 src = src_path->nodes[0];
3885                 btrfs_item_key_to_cpu(src, &key, src_path->slots[0]);
3886                 if (key.objectid != btrfs_ino(inode) ||
3887                     key.type != BTRFS_EXTENT_DATA_KEY)
3888                         goto fill_holes;
3889                 extent = btrfs_item_ptr(src, src_path->slots[0],
3890                                         struct btrfs_file_extent_item);
3891                 if (btrfs_file_extent_type(src, extent) ==
3892                     BTRFS_FILE_EXTENT_INLINE) {
3893                         len = btrfs_file_extent_inline_len(src,
3894                                                            src_path->slots[0],
3895                                                            extent);
3896                         *last_extent = ALIGN(key.offset + len,
3897                                              fs_info->sectorsize);
3898                 } else {
3899                         len = btrfs_file_extent_num_bytes(src, extent);
3900                         *last_extent = key.offset + len;
3901                 }
3902         }
3903 fill_holes:
3904         /* So we did prev_leaf, now we need to move to the next leaf, but a few
3905          * things could have happened
3906          *
3907          * 1) A merge could have happened, so we could currently be on a leaf
3908          * that holds what we were copying in the first place.
3909          * 2) A split could have happened, and now not all of the items we want
3910          * are on the same leaf.
3911          *
3912          * So we need to adjust how we search for holes, we need to drop the
3913          * path and re-search for the first extent key we found, and then walk
3914          * forward until we hit the last one we copied.
3915          */
3916         if (need_find_last_extent) {
3917                 /* btrfs_prev_leaf could return 1 without releasing the path */
3918                 btrfs_release_path(src_path);
3919                 ret = btrfs_search_slot(NULL, inode->root, &first_key,
3920                                 src_path, 0, 0);
3921                 if (ret < 0)
3922                         return ret;
3923                 ASSERT(ret == 0);
3924                 src = src_path->nodes[0];
3925                 i = src_path->slots[0];
3926         } else {
3927                 i = start_slot;
3928         }
3929
3930         /*
3931          * Ok so here we need to go through and fill in any holes we may have
3932          * to make sure that holes are punched for those areas in case they had
3933          * extents previously.
3934          */
3935         while (!done) {
3936                 u64 offset, len;
3937                 u64 extent_end;
3938
3939                 if (i >= btrfs_header_nritems(src_path->nodes[0])) {
3940                         ret = btrfs_next_leaf(inode->root, src_path);
3941                         if (ret < 0)
3942                                 return ret;
3943                         ASSERT(ret == 0);
3944                         src = src_path->nodes[0];
3945                         i = 0;
3946                         need_find_last_extent = true;
3947                 }
3948
3949                 btrfs_item_key_to_cpu(src, &key, i);
3950                 if (!btrfs_comp_cpu_keys(&key, &last_key))
3951                         done = true;
3952                 if (key.objectid != btrfs_ino(inode) ||
3953                     key.type != BTRFS_EXTENT_DATA_KEY) {
3954                         i++;
3955                         continue;
3956                 }
3957                 extent = btrfs_item_ptr(src, i, struct btrfs_file_extent_item);
3958                 if (btrfs_file_extent_type(src, extent) ==
3959                     BTRFS_FILE_EXTENT_INLINE) {
3960                         len = btrfs_file_extent_inline_len(src, i, extent);
3961                         extent_end = ALIGN(key.offset + len,
3962                                            fs_info->sectorsize);
3963                 } else {
3964                         len = btrfs_file_extent_num_bytes(src, extent);
3965                         extent_end = key.offset + len;
3966                 }
3967                 i++;
3968
3969                 if (*last_extent == key.offset) {
3970                         *last_extent = extent_end;
3971                         continue;
3972                 }
3973                 offset = *last_extent;
3974                 len = key.offset - *last_extent;
3975                 ret = btrfs_insert_file_extent(trans, log, btrfs_ino(inode),
3976                                 offset, 0, 0, len, 0, len, 0, 0, 0);
3977                 if (ret)
3978                         break;
3979                 *last_extent = extent_end;
3980         }
3981
3982         /*
3983          * Check if there is a hole between the last extent found in our leaf
3984          * and the first extent in the next leaf. If there is one, we need to
3985          * log an explicit hole so that at replay time we can punch the hole.
3986          */
3987         if (ret == 0 &&
3988             key.objectid == btrfs_ino(inode) &&
3989             key.type == BTRFS_EXTENT_DATA_KEY &&
3990             i == btrfs_header_nritems(src_path->nodes[0])) {
3991                 ret = btrfs_next_leaf(inode->root, src_path);
3992                 need_find_last_extent = true;
3993                 if (ret > 0) {
3994                         ret = 0;
3995                 } else if (ret == 0) {
3996                         btrfs_item_key_to_cpu(src_path->nodes[0], &key,
3997                                               src_path->slots[0]);
3998                         if (key.objectid == btrfs_ino(inode) &&
3999                             key.type == BTRFS_EXTENT_DATA_KEY &&
4000                             *last_extent < key.offset) {
4001                                 const u64 len = key.offset - *last_extent;
4002
4003                                 ret = btrfs_insert_file_extent(trans, log,
4004                                                                btrfs_ino(inode),
4005                                                                *last_extent, 0,
4006                                                                0, len, 0, len,
4007                                                                0, 0, 0);
4008                         }
4009                 }
4010         }
4011         /*
4012          * Need to let the callers know we dropped the path so they should
4013          * re-search.
4014          */
4015         if (!ret && need_find_last_extent)
4016                 ret = 1;
4017         return ret;
4018 }
4019
4020 static int extent_cmp(void *priv, struct list_head *a, struct list_head *b)
4021 {
4022         struct extent_map *em1, *em2;
4023
4024         em1 = list_entry(a, struct extent_map, list);
4025         em2 = list_entry(b, struct extent_map, list);
4026
4027         if (em1->start < em2->start)
4028                 return -1;
4029         else if (em1->start > em2->start)
4030                 return 1;
4031         return 0;
4032 }
4033
4034 static int wait_ordered_extents(struct btrfs_trans_handle *trans,
4035                                 struct inode *inode,
4036                                 struct btrfs_root *root,
4037                                 const struct extent_map *em,
4038                                 const struct list_head *logged_list,
4039                                 bool *ordered_io_error)
4040 {
4041         struct btrfs_fs_info *fs_info = root->fs_info;
4042         struct btrfs_ordered_extent *ordered;
4043         struct btrfs_root *log = root->log_root;
4044         u64 mod_start = em->mod_start;
4045         u64 mod_len = em->mod_len;
4046         const bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
4047         u64 csum_offset;
4048         u64 csum_len;
4049         LIST_HEAD(ordered_sums);
4050         int ret = 0;
4051
4052         *ordered_io_error = false;
4053
4054         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
4055             em->block_start == EXTENT_MAP_HOLE)
4056                 return 0;
4057
4058         /*
4059          * Wait far any ordered extent that covers our extent map. If it
4060          * finishes without an error, first check and see if our csums are on
4061          * our outstanding ordered extents.
4062          */
4063         list_for_each_entry(ordered, logged_list, log_list) {
4064                 struct btrfs_ordered_sum *sum;
4065
4066                 if (!mod_len)
4067                         break;
4068
4069                 if (ordered->file_offset + ordered->len <= mod_start ||
4070                     mod_start + mod_len <= ordered->file_offset)
4071                         continue;
4072
4073                 if (!test_bit(BTRFS_ORDERED_IO_DONE, &ordered->flags) &&
4074                     !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
4075                     !test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags)) {
4076                         const u64 start = ordered->file_offset;
4077                         const u64 end = ordered->file_offset + ordered->len - 1;
4078
4079                         WARN_ON(ordered->inode != inode);
4080                         filemap_fdatawrite_range(inode->i_mapping, start, end);
4081                 }
4082
4083                 wait_event(ordered->wait,
4084                            (test_bit(BTRFS_ORDERED_IO_DONE, &ordered->flags) ||
4085                             test_bit(BTRFS_ORDERED_IOERR, &ordered->flags)));
4086
4087                 if (test_bit(BTRFS_ORDERED_IOERR, &ordered->flags)) {
4088                         /*
4089                          * Clear the AS_EIO/AS_ENOSPC flags from the inode's
4090                          * i_mapping flags, so that the next fsync won't get
4091                          * an outdated io error too.
4092                          */
4093                         filemap_check_errors(inode->i_mapping);
4094                         *ordered_io_error = true;
4095                         break;
4096                 }
4097                 /*
4098                  * We are going to copy all the csums on this ordered extent, so
4099                  * go ahead and adjust mod_start and mod_len in case this
4100                  * ordered extent has already been logged.
4101                  */
4102                 if (ordered->file_offset > mod_start) {
4103                         if (ordered->file_offset + ordered->len >=
4104                             mod_start + mod_len)
4105                                 mod_len = ordered->file_offset - mod_start;
4106                         /*
4107                          * If we have this case
4108                          *
4109                          * |--------- logged extent ---------|
4110                          *       |----- ordered extent ----|
4111                          *
4112                          * Just don't mess with mod_start and mod_len, we'll
4113                          * just end up logging more csums than we need and it
4114                          * will be ok.
4115                          */
4116                 } else {
4117                         if (ordered->file_offset + ordered->len <
4118                             mod_start + mod_len) {
4119                                 mod_len = (mod_start + mod_len) -
4120                                         (ordered->file_offset + ordered->len);
4121                                 mod_start = ordered->file_offset +
4122                                         ordered->len;
4123                         } else {
4124                                 mod_len = 0;
4125                         }
4126                 }
4127
4128                 if (skip_csum)
4129                         continue;
4130
4131                 /*
4132                  * To keep us from looping for the above case of an ordered
4133                  * extent that falls inside of the logged extent.
4134                  */
4135                 if (test_and_set_bit(BTRFS_ORDERED_LOGGED_CSUM,
4136                                      &ordered->flags))
4137                         continue;
4138
4139                 list_for_each_entry(sum, &ordered->list, list) {
4140                         ret = btrfs_csum_file_blocks(trans, log, sum);
4141                         if (ret)
4142                                 break;
4143                 }
4144         }
4145
4146         if (*ordered_io_error || !mod_len || ret || skip_csum)
4147                 return ret;
4148
4149         if (em->compress_type) {
4150                 csum_offset = 0;
4151                 csum_len = max(em->block_len, em->orig_block_len);
4152         } else {
4153                 csum_offset = mod_start - em->start;
4154                 csum_len = mod_len;
4155         }
4156
4157         /* block start is already adjusted for the file extent offset. */
4158         ret = btrfs_lookup_csums_range(fs_info->csum_root,
4159                                        em->block_start + csum_offset,
4160                                        em->block_start + csum_offset +
4161                                        csum_len - 1, &ordered_sums, 0);
4162         if (ret)
4163                 return ret;
4164
4165         while (!list_empty(&ordered_sums)) {
4166                 struct btrfs_ordered_sum *sums = list_entry(ordered_sums.next,
4167                                                    struct btrfs_ordered_sum,
4168                                                    list);
4169                 if (!ret)
4170                         ret = btrfs_csum_file_blocks(trans, log, sums);
4171                 list_del(&sums->list);
4172                 kfree(sums);
4173         }
4174
4175         return ret;
4176 }
4177
4178 static int log_one_extent(struct btrfs_trans_handle *trans,
4179                           struct btrfs_inode *inode, struct btrfs_root *root,
4180                           const struct extent_map *em,
4181                           struct btrfs_path *path,
4182                           const struct list_head *logged_list,
4183                           struct btrfs_log_ctx *ctx)
4184 {
4185         struct btrfs_root *log = root->log_root;
4186         struct btrfs_file_extent_item *fi;
4187         struct extent_buffer *leaf;
4188         struct btrfs_map_token token;
4189         struct btrfs_key key;
4190         u64 extent_offset = em->start - em->orig_start;
4191         u64 block_len;
4192         int ret;
4193         int extent_inserted = 0;
4194         bool ordered_io_err = false;
4195
4196         ret = wait_ordered_extents(trans, &inode->vfs_inode, root, em,
4197                         logged_list, &ordered_io_err);
4198         if (ret)
4199                 return ret;
4200
4201         if (ordered_io_err) {
4202                 ctx->io_err = -EIO;
4203                 return ctx->io_err;
4204         }
4205
4206         btrfs_init_map_token(&token);
4207
4208         ret = __btrfs_drop_extents(trans, log, &inode->vfs_inode, path, em->start,
4209                                    em->start + em->len, NULL, 0, 1,
4210                                    sizeof(*fi), &extent_inserted);
4211         if (ret)
4212                 return ret;
4213
4214         if (!extent_inserted) {
4215                 key.objectid = btrfs_ino(inode);
4216                 key.type = BTRFS_EXTENT_DATA_KEY;
4217                 key.offset = em->start;
4218
4219                 ret = btrfs_insert_empty_item(trans, log, path, &key,
4220                                               sizeof(*fi));
4221                 if (ret)
4222                         return ret;
4223         }
4224         leaf = path->nodes[0];
4225         fi = btrfs_item_ptr(leaf, path->slots[0],
4226                             struct btrfs_file_extent_item);
4227
4228         btrfs_set_token_file_extent_generation(leaf, fi, trans->transid,
4229                                                &token);
4230         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
4231                 btrfs_set_token_file_extent_type(leaf, fi,
4232                                                  BTRFS_FILE_EXTENT_PREALLOC,
4233                                                  &token);
4234         else
4235                 btrfs_set_token_file_extent_type(leaf, fi,
4236                                                  BTRFS_FILE_EXTENT_REG,
4237                                                  &token);
4238
4239         block_len = max(em->block_len, em->orig_block_len);
4240         if (em->compress_type != BTRFS_COMPRESS_NONE) {
4241                 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4242                                                         em->block_start,
4243                                                         &token);
4244                 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4245                                                            &token);
4246         } else if (em->block_start < EXTENT_MAP_LAST_BYTE) {
4247                 btrfs_set_token_file_extent_disk_bytenr(leaf, fi,
4248                                                         em->block_start -
4249                                                         extent_offset, &token);
4250                 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, block_len,
4251                                                            &token);
4252         } else {
4253                 btrfs_set_token_file_extent_disk_bytenr(leaf, fi, 0, &token);
4254                 btrfs_set_token_file_extent_disk_num_bytes(leaf, fi, 0,
4255                                                            &token);
4256         }
4257
4258         btrfs_set_token_file_extent_offset(leaf, fi, extent_offset, &token);
4259         btrfs_set_token_file_extent_num_bytes(leaf, fi, em->len, &token);
4260         btrfs_set_token_file_extent_ram_bytes(leaf, fi, em->ram_bytes, &token);
4261         btrfs_set_token_file_extent_compression(leaf, fi, em->compress_type,
4262                                                 &token);
4263         btrfs_set_token_file_extent_encryption(leaf, fi, 0, &token);
4264         btrfs_set_token_file_extent_other_encoding(leaf, fi, 0, &token);
4265         btrfs_mark_buffer_dirty(leaf);
4266
4267         btrfs_release_path(path);
4268
4269         return ret;
4270 }
4271
4272 /*
4273  * Log all prealloc extents beyond the inode's i_size to make sure we do not
4274  * lose them after doing a fast fsync and replaying the log. We scan the
4275  * subvolume's root instead of iterating the inode's extent map tree because
4276  * otherwise we can log incorrect extent items based on extent map conversion.
4277  * That can happen due to the fact that extent maps are merged when they
4278  * are not in the extent map tree's list of modified extents.
4279  */
4280 static int btrfs_log_prealloc_extents(struct btrfs_trans_handle *trans,
4281                                       struct btrfs_inode *inode,
4282                                       struct btrfs_path *path)
4283 {
4284         struct btrfs_root *root = inode->root;
4285         struct btrfs_key key;
4286         const u64 i_size = i_size_read(&inode->vfs_inode);
4287         const u64 ino = btrfs_ino(inode);
4288         struct btrfs_path *dst_path = NULL;
4289         u64 last_extent = (u64)-1;
4290         int ins_nr = 0;
4291         int start_slot;
4292         int ret;
4293
4294         if (!(inode->flags & BTRFS_INODE_PREALLOC))
4295                 return 0;
4296
4297         key.objectid = ino;
4298         key.type = BTRFS_EXTENT_DATA_KEY;
4299         key.offset = i_size;
4300         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4301         if (ret < 0)
4302                 goto out;
4303
4304         while (true) {
4305                 struct extent_buffer *leaf = path->nodes[0];
4306                 int slot = path->slots[0];
4307
4308                 if (slot >= btrfs_header_nritems(leaf)) {
4309                         if (ins_nr > 0) {
4310                                 ret = copy_items(trans, inode, dst_path, path,
4311                                                  &last_extent, start_slot,
4312                                                  ins_nr, 1, 0);
4313                                 if (ret < 0)
4314                                         goto out;
4315                                 ins_nr = 0;
4316                         }
4317                         ret = btrfs_next_leaf(root, path);
4318                         if (ret < 0)
4319                                 goto out;
4320                         if (ret > 0) {
4321                                 ret = 0;
4322                                 break;
4323                         }
4324                         continue;
4325                 }
4326
4327                 btrfs_item_key_to_cpu(leaf, &key, slot);
4328                 if (key.objectid > ino)
4329                         break;
4330                 if (WARN_ON_ONCE(key.objectid < ino) ||
4331                     key.type < BTRFS_EXTENT_DATA_KEY ||
4332                     key.offset < i_size) {
4333                         path->slots[0]++;
4334                         continue;
4335                 }
4336                 if (last_extent == (u64)-1) {
4337                         last_extent = key.offset;
4338                         /*
4339                          * Avoid logging extent items logged in past fsync calls
4340                          * and leading to duplicate keys in the log tree.
4341                          */
4342                         do {
4343                                 ret = btrfs_truncate_inode_items(trans,
4344                                                          root->log_root,
4345                                                          &inode->vfs_inode,
4346                                                          i_size,
4347                                                          BTRFS_EXTENT_DATA_KEY);
4348                         } while (ret == -EAGAIN);
4349                         if (ret)
4350                                 goto out;
4351                 }
4352                 if (ins_nr == 0)
4353                         start_slot = slot;
4354                 ins_nr++;
4355                 path->slots[0]++;
4356                 if (!dst_path) {
4357                         dst_path = btrfs_alloc_path();
4358                         if (!dst_path) {
4359                                 ret = -ENOMEM;
4360                                 goto out;
4361                         }
4362                 }
4363         }
4364         if (ins_nr > 0) {
4365                 ret = copy_items(trans, inode, dst_path, path, &last_extent,
4366                                  start_slot, ins_nr, 1, 0);
4367                 if (ret > 0)
4368                         ret = 0;
4369         }
4370 out:
4371         btrfs_release_path(path);
4372         btrfs_free_path(dst_path);
4373         return ret;
4374 }
4375
4376 static int btrfs_log_changed_extents(struct btrfs_trans_handle *trans,
4377                                      struct btrfs_root *root,
4378                                      struct btrfs_inode *inode,
4379                                      struct btrfs_path *path,
4380                                      struct list_head *logged_list,
4381                                      struct btrfs_log_ctx *ctx,
4382                                      const u64 start,
4383                                      const u64 end)
4384 {
4385         struct extent_map *em, *n;
4386         struct list_head extents;
4387         struct extent_map_tree *tree = &inode->extent_tree;
4388         u64 logged_start, logged_end;
4389         u64 test_gen;
4390         int ret = 0;
4391         int num = 0;
4392
4393         INIT_LIST_HEAD(&extents);
4394
4395         write_lock(&tree->lock);
4396         test_gen = root->fs_info->last_trans_committed;
4397         logged_start = start;
4398         logged_end = end;
4399
4400         list_for_each_entry_safe(em, n, &tree->modified_extents, list) {
4401                 list_del_init(&em->list);
4402                 /*
4403                  * Just an arbitrary number, this can be really CPU intensive
4404                  * once we start getting a lot of extents, and really once we
4405                  * have a bunch of extents we just want to commit since it will
4406                  * be faster.
4407                  */
4408                 if (++num > 32768) {
4409                         list_del_init(&tree->modified_extents);
4410                         ret = -EFBIG;
4411                         goto process;
4412                 }
4413
4414                 if (em->generation <= test_gen)
4415                         continue;
4416
4417                 /* We log prealloc extents beyond eof later. */
4418                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) &&
4419                     em->start >= i_size_read(&inode->vfs_inode))
4420                         continue;
4421
4422                 if (em->start < logged_start)
4423                         logged_start = em->start;
4424                 if ((em->start + em->len - 1) > logged_end)
4425                         logged_end = em->start + em->len - 1;
4426
4427                 /* Need a ref to keep it from getting evicted from cache */
4428                 refcount_inc(&em->refs);
4429                 set_bit(EXTENT_FLAG_LOGGING, &em->flags);
4430                 list_add_tail(&em->list, &extents);
4431                 num++;
4432         }
4433
4434         list_sort(NULL, &extents, extent_cmp);
4435         btrfs_get_logged_extents(inode, logged_list, logged_start, logged_end);
4436         /*
4437          * Some ordered extents started by fsync might have completed
4438          * before we could collect them into the list logged_list, which
4439          * means they're gone, not in our logged_list nor in the inode's
4440          * ordered tree. We want the application/user space to know an
4441          * error happened while attempting to persist file data so that
4442          * it can take proper action. If such error happened, we leave
4443          * without writing to the log tree and the fsync must report the
4444          * file data write error and not commit the current transaction.
4445          */
4446         ret = filemap_check_errors(inode->vfs_inode.i_mapping);
4447         if (ret)
4448                 ctx->io_err = ret;
4449 process:
4450         while (!list_empty(&extents)) {
4451                 em = list_entry(extents.next, struct extent_map, list);
4452
4453                 list_del_init(&em->list);
4454
4455                 /*
4456                  * If we had an error we just need to delete everybody from our
4457                  * private list.
4458                  */
4459                 if (ret) {
4460                         clear_em_logging(tree, em);
4461                         free_extent_map(em);
4462                         continue;
4463                 }
4464
4465                 write_unlock(&tree->lock);
4466
4467                 ret = log_one_extent(trans, inode, root, em, path, logged_list,
4468                                      ctx);
4469                 write_lock(&tree->lock);
4470                 clear_em_logging(tree, em);
4471                 free_extent_map(em);
4472         }
4473         WARN_ON(!list_empty(&extents));
4474         write_unlock(&tree->lock);
4475
4476         btrfs_release_path(path);
4477         if (!ret)
4478                 ret = btrfs_log_prealloc_extents(trans, inode, path);
4479
4480         return ret;
4481 }
4482
4483 static int logged_inode_size(struct btrfs_root *log, struct btrfs_inode *inode,
4484                              struct btrfs_path *path, u64 *size_ret)
4485 {
4486         struct btrfs_key key;
4487         int ret;
4488
4489         key.objectid = btrfs_ino(inode);
4490         key.type = BTRFS_INODE_ITEM_KEY;
4491         key.offset = 0;
4492
4493         ret = btrfs_search_slot(NULL, log, &key, path, 0, 0);
4494         if (ret < 0) {
4495                 return ret;
4496         } else if (ret > 0) {
4497                 *size_ret = 0;
4498         } else {
4499                 struct btrfs_inode_item *item;
4500
4501                 item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4502                                       struct btrfs_inode_item);
4503                 *size_ret = btrfs_inode_size(path->nodes[0], item);
4504         }
4505
4506         btrfs_release_path(path);
4507         return 0;
4508 }
4509
4510 /*
4511  * At the moment we always log all xattrs. This is to figure out at log replay
4512  * time which xattrs must have their deletion replayed. If a xattr is missing
4513  * in the log tree and exists in the fs/subvol tree, we delete it. This is
4514  * because if a xattr is deleted, the inode is fsynced and a power failure
4515  * happens, causing the log to be replayed the next time the fs is mounted,
4516  * we want the xattr to not exist anymore (same behaviour as other filesystems
4517  * with a journal, ext3/4, xfs, f2fs, etc).
4518  */
4519 static int btrfs_log_all_xattrs(struct btrfs_trans_handle *trans,
4520                                 struct btrfs_root *root,
4521                                 struct btrfs_inode *inode,
4522                                 struct btrfs_path *path,
4523                                 struct btrfs_path *dst_path)
4524 {
4525         int ret;
4526         struct btrfs_key key;
4527         const u64 ino = btrfs_ino(inode);
4528         int ins_nr = 0;
4529         int start_slot = 0;
4530
4531         key.objectid = ino;
4532         key.type = BTRFS_XATTR_ITEM_KEY;
4533         key.offset = 0;
4534
4535         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4536         if (ret < 0)
4537                 return ret;
4538
4539         while (true) {
4540                 int slot = path->slots[0];
4541                 struct extent_buffer *leaf = path->nodes[0];
4542                 int nritems = btrfs_header_nritems(leaf);
4543
4544                 if (slot >= nritems) {
4545                         if (ins_nr > 0) {
4546                                 u64 last_extent = 0;
4547
4548                                 ret = copy_items(trans, inode, dst_path, path,
4549                                                  &last_extent, start_slot,
4550                                                  ins_nr, 1, 0);
4551                                 /* can't be 1, extent items aren't processed */
4552                                 ASSERT(ret <= 0);
4553                                 if (ret < 0)
4554                                         return ret;
4555                                 ins_nr = 0;
4556                         }
4557                         ret = btrfs_next_leaf(root, path);
4558                         if (ret < 0)
4559                                 return ret;
4560                         else if (ret > 0)
4561                                 break;
4562                         continue;
4563                 }
4564
4565                 btrfs_item_key_to_cpu(leaf, &key, slot);
4566                 if (key.objectid != ino || key.type != BTRFS_XATTR_ITEM_KEY)
4567                         break;
4568
4569                 if (ins_nr == 0)
4570                         start_slot = slot;
4571                 ins_nr++;
4572                 path->slots[0]++;
4573                 cond_resched();
4574         }
4575         if (ins_nr > 0) {
4576                 u64 last_extent = 0;
4577
4578                 ret = copy_items(trans, inode, dst_path, path,
4579                                  &last_extent, start_slot,
4580                                  ins_nr, 1, 0);
4581                 /* can't be 1, extent items aren't processed */
4582                 ASSERT(ret <= 0);
4583                 if (ret < 0)
4584                         return ret;
4585         }
4586
4587         return 0;
4588 }
4589
4590 /*
4591  * If the no holes feature is enabled we need to make sure any hole between the
4592  * last extent and the i_size of our inode is explicitly marked in the log. This
4593  * is to make sure that doing something like:
4594  *
4595  *      1) create file with 128Kb of data
4596  *      2) truncate file to 64Kb
4597  *      3) truncate file to 256Kb
4598  *      4) fsync file
4599  *      5) <crash/power failure>
4600  *      6) mount fs and trigger log replay
4601  *
4602  * Will give us a file with a size of 256Kb, the first 64Kb of data match what
4603  * the file had in its first 64Kb of data at step 1 and the last 192Kb of the
4604  * file correspond to a hole. The presence of explicit holes in a log tree is
4605  * what guarantees that log replay will remove/adjust file extent items in the
4606  * fs/subvol tree.
4607  *
4608  * Here we do not need to care about holes between extents, that is already done
4609  * by copy_items(). We also only need to do this in the full sync path, where we
4610  * lookup for extents from the fs/subvol tree only. In the fast path case, we
4611  * lookup the list of modified extent maps and if any represents a hole, we
4612  * insert a corresponding extent representing a hole in the log tree.
4613  */
4614 static int btrfs_log_trailing_hole(struct btrfs_trans_handle *trans,
4615                                    struct btrfs_root *root,
4616                                    struct btrfs_inode *inode,
4617                                    struct btrfs_path *path)
4618 {
4619         struct btrfs_fs_info *fs_info = root->fs_info;
4620         int ret;
4621         struct btrfs_key key;
4622         u64 hole_start;
4623         u64 hole_size;
4624         struct extent_buffer *leaf;
4625         struct btrfs_root *log = root->log_root;
4626         const u64 ino = btrfs_ino(inode);
4627         const u64 i_size = i_size_read(&inode->vfs_inode);
4628
4629         if (!btrfs_fs_incompat(fs_info, NO_HOLES))
4630                 return 0;
4631
4632         key.objectid = ino;
4633         key.type = BTRFS_EXTENT_DATA_KEY;
4634         key.offset = (u64)-1;
4635
4636         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4637         ASSERT(ret != 0);
4638         if (ret < 0)
4639                 return ret;
4640
4641         ASSERT(path->slots[0] > 0);
4642         path->slots[0]--;
4643         leaf = path->nodes[0];
4644         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4645
4646         if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY) {
4647                 /* inode does not have any extents */
4648                 hole_start = 0;
4649                 hole_size = i_size;
4650         } else {
4651                 struct btrfs_file_extent_item *extent;
4652                 u64 len;
4653
4654                 /*
4655                  * If there's an extent beyond i_size, an explicit hole was
4656                  * already inserted by copy_items().
4657                  */
4658                 if (key.offset >= i_size)
4659                         return 0;
4660
4661                 extent = btrfs_item_ptr(leaf, path->slots[0],
4662                                         struct btrfs_file_extent_item);
4663
4664                 if (btrfs_file_extent_type(leaf, extent) ==
4665                     BTRFS_FILE_EXTENT_INLINE) {
4666                         len = btrfs_file_extent_inline_len(leaf,
4667                                                            path->slots[0],
4668                                                            extent);
4669                         ASSERT(len == i_size ||
4670                                (len == fs_info->sectorsize &&
4671                                 btrfs_file_extent_compression(leaf, extent) !=
4672                                 BTRFS_COMPRESS_NONE) ||
4673                                (len < i_size && i_size < fs_info->sectorsize));
4674                         return 0;
4675                 }
4676
4677                 len = btrfs_file_extent_num_bytes(leaf, extent);
4678                 /* Last extent goes beyond i_size, no need to log a hole. */
4679                 if (key.offset + len > i_size)
4680                         return 0;
4681                 hole_start = key.offset + len;
4682                 hole_size = i_size - hole_start;
4683         }
4684         btrfs_release_path(path);
4685
4686         /* Last extent ends at i_size. */
4687         if (hole_size == 0)
4688                 return 0;
4689
4690         hole_size = ALIGN(hole_size, fs_info->sectorsize);
4691         ret = btrfs_insert_file_extent(trans, log, ino, hole_start, 0, 0,
4692                                        hole_size, 0, hole_size, 0, 0, 0);
4693         return ret;
4694 }
4695
4696 /*
4697  * When we are logging a new inode X, check if it doesn't have a reference that
4698  * matches the reference from some other inode Y created in a past transaction
4699  * and that was renamed in the current transaction. If we don't do this, then at
4700  * log replay time we can lose inode Y (and all its files if it's a directory):
4701  *
4702  * mkdir /mnt/x
4703  * echo "hello world" > /mnt/x/foobar
4704  * sync
4705  * mv /mnt/x /mnt/y
4706  * mkdir /mnt/x                 # or touch /mnt/x
4707  * xfs_io -c fsync /mnt/x
4708  * <power fail>
4709  * mount fs, trigger log replay
4710  *
4711  * After the log replay procedure, we would lose the first directory and all its
4712  * files (file foobar).
4713  * For the case where inode Y is not a directory we simply end up losing it:
4714  *
4715  * echo "123" > /mnt/foo
4716  * sync
4717  * mv /mnt/foo /mnt/bar
4718  * echo "abc" > /mnt/foo
4719  * xfs_io -c fsync /mnt/foo
4720  * <power fail>
4721  *
4722  * We also need this for cases where a snapshot entry is replaced by some other
4723  * entry (file or directory) otherwise we end up with an unreplayable log due to
4724  * attempts to delete the snapshot entry (entry of type BTRFS_ROOT_ITEM_KEY) as
4725  * if it were a regular entry:
4726  *
4727  * mkdir /mnt/x
4728  * btrfs subvolume snapshot /mnt /mnt/x/snap
4729  * btrfs subvolume delete /mnt/x/snap
4730  * rmdir /mnt/x
4731  * mkdir /mnt/x
4732  * fsync /mnt/x or fsync some new file inside it
4733  * <power fail>
4734  *
4735  * The snapshot delete, rmdir of x, mkdir of a new x and the fsync all happen in
4736  * the same transaction.
4737  */
4738 static int btrfs_check_ref_name_override(struct extent_buffer *eb,
4739                                          const int slot,
4740                                          const struct btrfs_key *key,
4741                                          struct btrfs_inode *inode,
4742                                          u64 *other_ino)
4743 {
4744         int ret;
4745         struct btrfs_path *search_path;
4746         char *name = NULL;
4747         u32 name_len = 0;
4748         u32 item_size = btrfs_item_size_nr(eb, slot);
4749         u32 cur_offset = 0;
4750         unsigned long ptr = btrfs_item_ptr_offset(eb, slot);
4751
4752         search_path = btrfs_alloc_path();
4753         if (!search_path)
4754                 return -ENOMEM;
4755         search_path->search_commit_root = 1;
4756         search_path->skip_locking = 1;
4757
4758         while (cur_offset < item_size) {
4759                 u64 parent;
4760                 u32 this_name_len;
4761                 u32 this_len;
4762                 unsigned long name_ptr;
4763                 struct btrfs_dir_item *di;
4764
4765                 if (key->type == BTRFS_INODE_REF_KEY) {
4766                         struct btrfs_inode_ref *iref;
4767
4768                         iref = (struct btrfs_inode_ref *)(ptr + cur_offset);
4769                         parent = key->offset;
4770                         this_name_len = btrfs_inode_ref_name_len(eb, iref);
4771                         name_ptr = (unsigned long)(iref + 1);
4772                         this_len = sizeof(*iref) + this_name_len;
4773                 } else {
4774                         struct btrfs_inode_extref *extref;
4775
4776                         extref = (struct btrfs_inode_extref *)(ptr +
4777                                                                cur_offset);
4778                         parent = btrfs_inode_extref_parent(eb, extref);
4779                         this_name_len = btrfs_inode_extref_name_len(eb, extref);
4780                         name_ptr = (unsigned long)&extref->name;
4781                         this_len = sizeof(*extref) + this_name_len;
4782                 }
4783
4784                 ret = btrfs_is_name_len_valid(eb, slot, name_ptr,
4785                                               this_name_len);
4786                 if (!ret) {
4787                         ret = -EIO;
4788                         goto out;
4789                 }
4790                 if (this_name_len > name_len) {
4791                         char *new_name;
4792
4793                         new_name = krealloc(name, this_name_len, GFP_NOFS);
4794                         if (!new_name) {
4795                                 ret = -ENOMEM;
4796                                 goto out;
4797                         }
4798                         name_len = this_name_len;
4799                         name = new_name;
4800                 }
4801
4802                 read_extent_buffer(eb, name, name_ptr, this_name_len);
4803                 di = btrfs_lookup_dir_item(NULL, inode->root, search_path,
4804                                 parent, name, this_name_len, 0);
4805                 if (di && !IS_ERR(di)) {
4806                         struct btrfs_key di_key;
4807
4808                         btrfs_dir_item_key_to_cpu(search_path->nodes[0],
4809                                                   di, &di_key);
4810                         if (di_key.type == BTRFS_INODE_ITEM_KEY) {
4811                                 ret = 1;
4812                                 *other_ino = di_key.objectid;
4813                         } else {
4814                                 ret = -EAGAIN;
4815                         }
4816                         goto out;
4817                 } else if (IS_ERR(di)) {
4818                         ret = PTR_ERR(di);
4819                         goto out;
4820                 }
4821                 btrfs_release_path(search_path);
4822
4823                 cur_offset += this_len;
4824         }
4825         ret = 0;
4826 out:
4827         btrfs_free_path(search_path);
4828         kfree(name);
4829         return ret;
4830 }
4831
4832 /* log a single inode in the tree log.
4833  * At least one parent directory for this inode must exist in the tree
4834  * or be logged already.
4835  *
4836  * Any items from this inode changed by the current transaction are copied
4837  * to the log tree.  An extra reference is taken on any extents in this
4838  * file, allowing us to avoid a whole pile of corner cases around logging
4839  * blocks that have been removed from the tree.
4840  *
4841  * See LOG_INODE_ALL and related defines for a description of what inode_only
4842  * does.
4843  *
4844  * This handles both files and directories.
4845  */
4846 static int btrfs_log_inode(struct btrfs_trans_handle *trans,
4847                            struct btrfs_root *root, struct btrfs_inode *inode,
4848                            int inode_only,
4849                            const loff_t start,
4850                            const loff_t end,
4851                            struct btrfs_log_ctx *ctx)
4852 {
4853         struct btrfs_fs_info *fs_info = root->fs_info;
4854         struct btrfs_path *path;
4855         struct btrfs_path *dst_path;
4856         struct btrfs_key min_key;
4857         struct btrfs_key max_key;
4858         struct btrfs_root *log = root->log_root;
4859         struct extent_buffer *src = NULL;
4860         LIST_HEAD(logged_list);
4861         u64 last_extent = 0;
4862         int err = 0;
4863         int ret;
4864         int nritems;
4865         int ins_start_slot = 0;
4866         int ins_nr;
4867         bool fast_search = false;
4868         u64 ino = btrfs_ino(inode);
4869         struct extent_map_tree *em_tree = &inode->extent_tree;
4870         u64 logged_isize = 0;
4871         bool need_log_inode_item = true;
4872         bool xattrs_logged = false;
4873
4874         path = btrfs_alloc_path();
4875         if (!path)
4876                 return -ENOMEM;
4877         dst_path = btrfs_alloc_path();
4878         if (!dst_path) {
4879                 btrfs_free_path(path);
4880                 return -ENOMEM;
4881         }
4882
4883         min_key.objectid = ino;
4884         min_key.type = BTRFS_INODE_ITEM_KEY;
4885         min_key.offset = 0;
4886
4887         max_key.objectid = ino;
4888
4889
4890         /* today the code can only do partial logging of directories */
4891         if (S_ISDIR(inode->vfs_inode.i_mode) ||
4892             (!test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4893                        &inode->runtime_flags) &&
4894              inode_only >= LOG_INODE_EXISTS))
4895                 max_key.type = BTRFS_XATTR_ITEM_KEY;
4896         else
4897                 max_key.type = (u8)-1;
4898         max_key.offset = (u64)-1;
4899
4900         /*
4901          * Only run delayed items if we are a dir or a new file.
4902          * Otherwise commit the delayed inode only, which is needed in
4903          * order for the log replay code to mark inodes for link count
4904          * fixup (create temporary BTRFS_TREE_LOG_FIXUP_OBJECTID items).
4905          */
4906         if (S_ISDIR(inode->vfs_inode.i_mode) ||
4907             inode->generation > fs_info->last_trans_committed)
4908                 ret = btrfs_commit_inode_delayed_items(trans, inode);
4909         else
4910                 ret = btrfs_commit_inode_delayed_inode(inode);
4911
4912         if (ret) {
4913                 btrfs_free_path(path);
4914                 btrfs_free_path(dst_path);
4915                 return ret;
4916         }
4917
4918         if (inode_only == LOG_OTHER_INODE) {
4919                 inode_only = LOG_INODE_EXISTS;
4920                 mutex_lock_nested(&inode->log_mutex, SINGLE_DEPTH_NESTING);
4921         } else {
4922                 mutex_lock(&inode->log_mutex);
4923         }
4924
4925         /*
4926          * a brute force approach to making sure we get the most uptodate
4927          * copies of everything.
4928          */
4929         if (S_ISDIR(inode->vfs_inode.i_mode)) {
4930                 int max_key_type = BTRFS_DIR_LOG_INDEX_KEY;
4931
4932                 if (inode_only == LOG_INODE_EXISTS)
4933                         max_key_type = BTRFS_XATTR_ITEM_KEY;
4934                 ret = drop_objectid_items(trans, log, path, ino, max_key_type);
4935         } else {
4936                 if (inode_only == LOG_INODE_EXISTS) {
4937                         /*
4938                          * Make sure the new inode item we write to the log has
4939                          * the same isize as the current one (if it exists).
4940                          * This is necessary to prevent data loss after log
4941                          * replay, and also to prevent doing a wrong expanding
4942                          * truncate - for e.g. create file, write 4K into offset
4943                          * 0, fsync, write 4K into offset 4096, add hard link,
4944                          * fsync some other file (to sync log), power fail - if
4945                          * we use the inode's current i_size, after log replay
4946                          * we get a 8Kb file, with the last 4Kb extent as a hole
4947                          * (zeroes), as if an expanding truncate happened,
4948                          * instead of getting a file of 4Kb only.
4949                          */
4950                         err = logged_inode_size(log, inode, path, &logged_isize);
4951                         if (err)
4952                                 goto out_unlock;
4953                 }
4954                 if (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4955                              &inode->runtime_flags)) {
4956                         if (inode_only == LOG_INODE_EXISTS) {
4957                                 max_key.type = BTRFS_XATTR_ITEM_KEY;
4958                                 ret = drop_objectid_items(trans, log, path, ino,
4959                                                           max_key.type);
4960                         } else {
4961                                 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4962                                           &inode->runtime_flags);
4963                                 clear_bit(BTRFS_INODE_COPY_EVERYTHING,
4964                                           &inode->runtime_flags);
4965                                 while(1) {
4966                                         ret = btrfs_truncate_inode_items(trans,
4967                                                 log, &inode->vfs_inode, 0, 0);
4968                                         if (ret != -EAGAIN)
4969                                                 break;
4970                                 }
4971                         }
4972                 } else if (test_and_clear_bit(BTRFS_INODE_COPY_EVERYTHING,
4973                                               &inode->runtime_flags) ||
4974                            inode_only == LOG_INODE_EXISTS) {
4975                         if (inode_only == LOG_INODE_ALL)
4976                                 fast_search = true;
4977                         max_key.type = BTRFS_XATTR_ITEM_KEY;
4978                         ret = drop_objectid_items(trans, log, path, ino,
4979                                                   max_key.type);
4980                 } else {
4981                         if (inode_only == LOG_INODE_ALL)
4982                                 fast_search = true;
4983                         goto log_extents;
4984                 }
4985
4986         }
4987         if (ret) {
4988                 err = ret;
4989                 goto out_unlock;
4990         }
4991
4992         while (1) {
4993                 ins_nr = 0;
4994                 ret = btrfs_search_forward(root, &min_key,
4995                                            path, trans->transid);
4996                 if (ret < 0) {
4997                         err = ret;
4998                         goto out_unlock;
4999                 }
5000                 if (ret != 0)
5001                         break;
5002 again:
5003                 /* note, ins_nr might be > 0 here, cleanup outside the loop */
5004                 if (min_key.objectid != ino)
5005                         break;
5006                 if (min_key.type > max_key.type)
5007                         break;
5008
5009                 if (min_key.type == BTRFS_INODE_ITEM_KEY)
5010                         need_log_inode_item = false;
5011
5012                 if ((min_key.type == BTRFS_INODE_REF_KEY ||
5013                      min_key.type == BTRFS_INODE_EXTREF_KEY) &&
5014                     inode->generation == trans->transid) {
5015                         u64 other_ino = 0;
5016
5017                         ret = btrfs_check_ref_name_override(path->nodes[0],
5018                                         path->slots[0], &min_key, inode,
5019                                         &other_ino);
5020                         if (ret < 0) {
5021                                 err = ret;
5022                                 goto out_unlock;
5023                         } else if (ret > 0 && ctx &&
5024                                    other_ino != btrfs_ino(BTRFS_I(ctx->inode))) {
5025                                 struct btrfs_key inode_key;
5026                                 struct inode *other_inode;
5027
5028                                 if (ins_nr > 0) {
5029                                         ins_nr++;
5030                                 } else {
5031                                         ins_nr = 1;
5032                                         ins_start_slot = path->slots[0];
5033                                 }
5034                                 ret = copy_items(trans, inode, dst_path, path,
5035                                                  &last_extent, ins_start_slot,
5036                                                  ins_nr, inode_only,
5037                                                  logged_isize);
5038                                 if (ret < 0) {
5039                                         err = ret;
5040                                         goto out_unlock;
5041                                 }
5042                                 ins_nr = 0;
5043                                 btrfs_release_path(path);
5044                                 inode_key.objectid = other_ino;
5045                                 inode_key.type = BTRFS_INODE_ITEM_KEY;
5046                                 inode_key.offset = 0;
5047                                 other_inode = btrfs_iget(fs_info->sb,
5048                                                          &inode_key, root,
5049                                                          NULL);
5050                                 /*
5051                                  * If the other inode that had a conflicting dir
5052                                  * entry was deleted in the current transaction,
5053                                  * we don't need to do more work nor fallback to
5054                                  * a transaction commit.
5055                                  */
5056                                 if (IS_ERR(other_inode) &&
5057                                     PTR_ERR(other_inode) == -ENOENT) {
5058                                         goto next_key;
5059                                 } else if (IS_ERR(other_inode)) {
5060                                         err = PTR_ERR(other_inode);
5061                                         goto out_unlock;
5062                                 }
5063                                 /*
5064                                  * We are safe logging the other inode without
5065                                  * acquiring its i_mutex as long as we log with
5066                                  * the LOG_INODE_EXISTS mode. We're safe against
5067                                  * concurrent renames of the other inode as well
5068                                  * because during a rename we pin the log and
5069                                  * update the log with the new name before we
5070                                  * unpin it.
5071                                  */
5072                                 err = btrfs_log_inode(trans, root,
5073                                                 BTRFS_I(other_inode),
5074                                                 LOG_OTHER_INODE, 0, LLONG_MAX,
5075                                                 ctx);
5076                                 iput(other_inode);
5077                                 if (err)
5078                                         goto out_unlock;
5079                                 else
5080                                         goto next_key;
5081                         }
5082                 }
5083
5084                 /* Skip xattrs, we log them later with btrfs_log_all_xattrs() */
5085                 if (min_key.type == BTRFS_XATTR_ITEM_KEY) {
5086                         if (ins_nr == 0)
5087                                 goto next_slot;
5088                         ret = copy_items(trans, inode, dst_path, path,
5089                                          &last_extent, ins_start_slot,
5090                                          ins_nr, inode_only, logged_isize);
5091                         if (ret < 0) {
5092                                 err = ret;
5093                                 goto out_unlock;
5094                         }
5095                         ins_nr = 0;
5096                         if (ret) {
5097                                 btrfs_release_path(path);
5098                                 continue;
5099                         }
5100                         goto next_slot;
5101                 }
5102
5103                 src = path->nodes[0];
5104                 if (ins_nr && ins_start_slot + ins_nr == path->slots[0]) {
5105                         ins_nr++;
5106                         goto next_slot;
5107                 } else if (!ins_nr) {
5108                         ins_start_slot = path->slots[0];
5109                         ins_nr = 1;
5110                         goto next_slot;
5111                 }
5112
5113                 ret = copy_items(trans, inode, dst_path, path, &last_extent,
5114                                  ins_start_slot, ins_nr, inode_only,
5115                                  logged_isize);
5116                 if (ret < 0) {
5117                         err = ret;
5118                         goto out_unlock;
5119                 }
5120                 if (ret) {
5121                         ins_nr = 0;
5122                         btrfs_release_path(path);
5123                         continue;
5124                 }
5125                 ins_nr = 1;
5126                 ins_start_slot = path->slots[0];
5127 next_slot:
5128
5129                 nritems = btrfs_header_nritems(path->nodes[0]);
5130                 path->slots[0]++;
5131                 if (path->slots[0] < nritems) {
5132                         btrfs_item_key_to_cpu(path->nodes[0], &min_key,
5133                                               path->slots[0]);
5134                         goto again;
5135                 }
5136                 if (ins_nr) {
5137                         ret = copy_items(trans, inode, dst_path, path,
5138                                          &last_extent, ins_start_slot,
5139                                          ins_nr, inode_only, logged_isize);
5140                         if (ret < 0) {
5141                                 err = ret;
5142                                 goto out_unlock;
5143                         }
5144                         ret = 0;
5145                         ins_nr = 0;
5146                 }
5147                 btrfs_release_path(path);
5148 next_key:
5149                 if (min_key.offset < (u64)-1) {
5150                         min_key.offset++;
5151                 } else if (min_key.type < max_key.type) {
5152                         min_key.type++;
5153                         min_key.offset = 0;
5154                 } else {
5155                         break;
5156                 }
5157         }
5158         if (ins_nr) {
5159                 ret = copy_items(trans, inode, dst_path, path, &last_extent,
5160                                  ins_start_slot, ins_nr, inode_only,
5161                                  logged_isize);
5162                 if (ret < 0) {
5163                         err = ret;
5164                         goto out_unlock;
5165                 }
5166                 ret = 0;
5167                 ins_nr = 0;
5168         }
5169
5170         btrfs_release_path(path);
5171         btrfs_release_path(dst_path);
5172         err = btrfs_log_all_xattrs(trans, root, inode, path, dst_path);
5173         if (err)
5174                 goto out_unlock;
5175         xattrs_logged = true;
5176         if (max_key.type >= BTRFS_EXTENT_DATA_KEY && !fast_search) {
5177                 btrfs_release_path(path);
5178                 btrfs_release_path(dst_path);
5179                 err = btrfs_log_trailing_hole(trans, root, inode, path);
5180                 if (err)
5181                         goto out_unlock;
5182         }
5183 log_extents:
5184         btrfs_release_path(path);
5185         btrfs_release_path(dst_path);
5186         if (need_log_inode_item) {
5187                 err = log_inode_item(trans, log, dst_path, inode);
5188                 if (!err && !xattrs_logged) {
5189                         err = btrfs_log_all_xattrs(trans, root, inode, path,
5190                                                    dst_path);
5191                         btrfs_release_path(path);
5192                 }
5193                 if (err)
5194                         goto out_unlock;
5195         }
5196         if (fast_search) {
5197                 ret = btrfs_log_changed_extents(trans, root, inode, dst_path,
5198                                                 &logged_list, ctx, start, end);
5199                 if (ret) {
5200                         err = ret;
5201                         goto out_unlock;
5202                 }
5203         } else if (inode_only == LOG_INODE_ALL) {
5204                 struct extent_map *em, *n;
5205
5206                 write_lock(&em_tree->lock);
5207                 /*
5208                  * We can't just remove every em if we're called for a ranged
5209                  * fsync - that is, one that doesn't cover the whole possible
5210                  * file range (0 to LLONG_MAX). This is because we can have
5211                  * em's that fall outside the range we're logging and therefore
5212                  * their ordered operations haven't completed yet
5213                  * (btrfs_finish_ordered_io() not invoked yet). This means we
5214                  * didn't get their respective file extent item in the fs/subvol
5215                  * tree yet, and need to let the next fast fsync (one which
5216                  * consults the list of modified extent maps) find the em so
5217                  * that it logs a matching file extent item and waits for the
5218                  * respective ordered operation to complete (if it's still
5219                  * running).
5220                  *
5221                  * Removing every em outside the range we're logging would make
5222                  * the next fast fsync not log their matching file extent items,
5223                  * therefore making us lose data after a log replay.
5224                  */
5225                 list_for_each_entry_safe(em, n, &em_tree->modified_extents,
5226                                          list) {
5227                         const u64 mod_end = em->mod_start + em->mod_len - 1;
5228
5229                         if (em->mod_start >= start && mod_end <= end)
5230                                 list_del_init(&em->list);
5231                 }
5232                 write_unlock(&em_tree->lock);
5233         }
5234
5235         if (inode_only == LOG_INODE_ALL && S_ISDIR(inode->vfs_inode.i_mode)) {
5236                 ret = log_directory_changes(trans, root, inode, path, dst_path,
5237                                         ctx);
5238                 if (ret) {
5239                         err = ret;
5240                         goto out_unlock;
5241                 }
5242         }
5243
5244         spin_lock(&inode->lock);
5245         inode->logged_trans = trans->transid;
5246         inode->last_log_commit = inode->last_sub_trans;
5247         spin_unlock(&inode->lock);
5248 out_unlock:
5249         if (unlikely(err))
5250                 btrfs_put_logged_extents(&logged_list);
5251         else
5252                 btrfs_submit_logged_extents(&logged_list, log);
5253         mutex_unlock(&inode->log_mutex);
5254
5255         btrfs_free_path(path);
5256         btrfs_free_path(dst_path);
5257         return err;
5258 }
5259
5260 /*
5261  * Check if we must fallback to a transaction commit when logging an inode.
5262  * This must be called after logging the inode and is used only in the context
5263  * when fsyncing an inode requires the need to log some other inode - in which
5264  * case we can't lock the i_mutex of each other inode we need to log as that
5265  * can lead to deadlocks with concurrent fsync against other inodes (as we can
5266  * log inodes up or down in the hierarchy) or rename operations for example. So
5267  * we take the log_mutex of the inode after we have logged it and then check for
5268  * its last_unlink_trans value - this is safe because any task setting
5269  * last_unlink_trans must take the log_mutex and it must do this before it does
5270  * the actual unlink operation, so if we do this check before a concurrent task
5271  * sets last_unlink_trans it means we've logged a consistent version/state of
5272  * all the inode items, otherwise we are not sure and must do a transaction
5273  * commit (the concurrent task might have only updated last_unlink_trans before
5274  * we logged the inode or it might have also done the unlink).
5275  */
5276 static bool btrfs_must_commit_transaction(struct btrfs_trans_handle *trans,
5277                                           struct btrfs_inode *inode)
5278 {
5279         struct btrfs_fs_info *fs_info = inode->root->fs_info;
5280         bool ret = false;
5281
5282         mutex_lock(&inode->log_mutex);
5283         if (inode->last_unlink_trans > fs_info->last_trans_committed) {
5284                 /*
5285                  * Make sure any commits to the log are forced to be full
5286                  * commits.
5287                  */
5288                 btrfs_set_log_full_commit(fs_info, trans);
5289                 ret = true;
5290         }
5291         mutex_unlock(&inode->log_mutex);
5292
5293         return ret;
5294 }
5295
5296 /*
5297  * follow the dentry parent pointers up the chain and see if any
5298  * of the directories in it require a full commit before they can
5299  * be logged.  Returns zero if nothing special needs to be done or 1 if
5300  * a full commit is required.
5301  */
5302 static noinline int check_parent_dirs_for_sync(struct btrfs_trans_handle *trans,
5303                                                struct btrfs_inode *inode,
5304                                                struct dentry *parent,
5305                                                struct super_block *sb,
5306                                                u64 last_committed)
5307 {
5308         int ret = 0;
5309         struct dentry *old_parent = NULL;
5310         struct btrfs_inode *orig_inode = inode;
5311
5312         /*
5313          * for regular files, if its inode is already on disk, we don't
5314          * have to worry about the parents at all.  This is because
5315          * we can use the last_unlink_trans field to record renames
5316          * and other fun in this file.
5317          */
5318         if (S_ISREG(inode->vfs_inode.i_mode) &&
5319             inode->generation <= last_committed &&
5320             inode->last_unlink_trans <= last_committed)
5321                 goto out;
5322
5323         if (!S_ISDIR(inode->vfs_inode.i_mode)) {
5324                 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5325                         goto out;
5326                 inode = BTRFS_I(d_inode(parent));
5327         }
5328
5329         while (1) {
5330                 /*
5331                  * If we are logging a directory then we start with our inode,
5332                  * not our parent's inode, so we need to skip setting the
5333                  * logged_trans so that further down in the log code we don't
5334                  * think this inode has already been logged.
5335                  */
5336                 if (inode != orig_inode)
5337                         inode->logged_trans = trans->transid;
5338                 smp_mb();
5339
5340                 if (btrfs_must_commit_transaction(trans, inode)) {
5341                         ret = 1;
5342                         break;
5343                 }
5344
5345                 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5346                         break;
5347
5348                 if (IS_ROOT(parent)) {
5349                         inode = BTRFS_I(d_inode(parent));
5350                         if (btrfs_must_commit_transaction(trans, inode))
5351                                 ret = 1;
5352                         break;
5353                 }
5354
5355                 parent = dget_parent(parent);
5356                 dput(old_parent);
5357                 old_parent = parent;
5358                 inode = BTRFS_I(d_inode(parent));
5359
5360         }
5361         dput(old_parent);
5362 out:
5363         return ret;
5364 }
5365
5366 struct btrfs_dir_list {
5367         u64 ino;
5368         struct list_head list;
5369 };
5370
5371 /*
5372  * Log the inodes of the new dentries of a directory. See log_dir_items() for
5373  * details about the why it is needed.
5374  * This is a recursive operation - if an existing dentry corresponds to a
5375  * directory, that directory's new entries are logged too (same behaviour as
5376  * ext3/4, xfs, f2fs, reiserfs, nilfs2). Note that when logging the inodes
5377  * the dentries point to we do not lock their i_mutex, otherwise lockdep
5378  * complains about the following circular lock dependency / possible deadlock:
5379  *
5380  *        CPU0                                        CPU1
5381  *        ----                                        ----
5382  * lock(&type->i_mutex_dir_key#3/2);
5383  *                                            lock(sb_internal#2);
5384  *                                            lock(&type->i_mutex_dir_key#3/2);
5385  * lock(&sb->s_type->i_mutex_key#14);
5386  *
5387  * Where sb_internal is the lock (a counter that works as a lock) acquired by
5388  * sb_start_intwrite() in btrfs_start_transaction().
5389  * Not locking i_mutex of the inodes is still safe because:
5390  *
5391  * 1) For regular files we log with a mode of LOG_INODE_EXISTS. It's possible
5392  *    that while logging the inode new references (names) are added or removed
5393  *    from the inode, leaving the logged inode item with a link count that does
5394  *    not match the number of logged inode reference items. This is fine because
5395  *    at log replay time we compute the real number of links and correct the
5396  *    link count in the inode item (see replay_one_buffer() and
5397  *    link_to_fixup_dir());
5398  *
5399  * 2) For directories we log with a mode of LOG_INODE_ALL. It's possible that
5400  *    while logging the inode's items new items with keys BTRFS_DIR_ITEM_KEY and
5401  *    BTRFS_DIR_INDEX_KEY are added to fs/subvol tree and the logged inode item
5402  *    has a size that doesn't match the sum of the lengths of all the logged
5403  *    names. This does not result in a problem because if a dir_item key is
5404  *    logged but its matching dir_index key is not logged, at log replay time we
5405  *    don't use it to replay the respective name (see replay_one_name()). On the
5406  *    other hand if only the dir_index key ends up being logged, the respective
5407  *    name is added to the fs/subvol tree with both the dir_item and dir_index
5408  *    keys created (see replay_one_name()).
5409  *    The directory's inode item with a wrong i_size is not a problem as well,
5410  *    since we don't use it at log replay time to set the i_size in the inode
5411  *    item of the fs/subvol tree (see overwrite_item()).
5412  */
5413 static int log_new_dir_dentries(struct btrfs_trans_handle *trans,
5414                                 struct btrfs_root *root,
5415                                 struct btrfs_inode *start_inode,
5416                                 struct btrfs_log_ctx *ctx)
5417 {
5418         struct btrfs_fs_info *fs_info = root->fs_info;
5419         struct btrfs_root *log = root->log_root;
5420         struct btrfs_path *path;
5421         LIST_HEAD(dir_list);
5422         struct btrfs_dir_list *dir_elem;
5423         int ret = 0;
5424
5425         path = btrfs_alloc_path();
5426         if (!path)
5427                 return -ENOMEM;
5428
5429         dir_elem = kmalloc(sizeof(*dir_elem), GFP_NOFS);
5430         if (!dir_elem) {
5431                 btrfs_free_path(path);
5432                 return -ENOMEM;
5433         }
5434         dir_elem->ino = btrfs_ino(start_inode);
5435         list_add_tail(&dir_elem->list, &dir_list);
5436
5437         while (!list_empty(&dir_list)) {
5438                 struct extent_buffer *leaf;
5439                 struct btrfs_key min_key;
5440                 int nritems;
5441                 int i;
5442
5443                 dir_elem = list_first_entry(&dir_list, struct btrfs_dir_list,
5444                                             list);
5445                 if (ret)
5446                         goto next_dir_inode;
5447
5448                 min_key.objectid = dir_elem->ino;
5449                 min_key.type = BTRFS_DIR_ITEM_KEY;
5450                 min_key.offset = 0;
5451 again:
5452                 btrfs_release_path(path);
5453                 ret = btrfs_search_forward(log, &min_key, path, trans->transid);
5454                 if (ret < 0) {
5455                         goto next_dir_inode;
5456                 } else if (ret > 0) {
5457                         ret = 0;
5458                         goto next_dir_inode;
5459                 }
5460
5461 process_leaf:
5462                 leaf = path->nodes[0];
5463                 nritems = btrfs_header_nritems(leaf);
5464                 for (i = path->slots[0]; i < nritems; i++) {
5465                         struct btrfs_dir_item *di;
5466                         struct btrfs_key di_key;
5467                         struct inode *di_inode;
5468                         struct btrfs_dir_list *new_dir_elem;
5469                         int log_mode = LOG_INODE_EXISTS;
5470                         int type;
5471
5472                         btrfs_item_key_to_cpu(leaf, &min_key, i);
5473                         if (min_key.objectid != dir_elem->ino ||
5474                             min_key.type != BTRFS_DIR_ITEM_KEY)
5475                                 goto next_dir_inode;
5476
5477                         di = btrfs_item_ptr(leaf, i, struct btrfs_dir_item);
5478                         type = btrfs_dir_type(leaf, di);
5479                         if (btrfs_dir_transid(leaf, di) < trans->transid &&
5480                             type != BTRFS_FT_DIR)
5481                                 continue;
5482                         btrfs_dir_item_key_to_cpu(leaf, di, &di_key);
5483                         if (di_key.type == BTRFS_ROOT_ITEM_KEY)
5484                                 continue;
5485
5486                         btrfs_release_path(path);
5487                         di_inode = btrfs_iget(fs_info->sb, &di_key, root, NULL);
5488                         if (IS_ERR(di_inode)) {
5489                                 ret = PTR_ERR(di_inode);
5490                                 goto next_dir_inode;
5491                         }
5492
5493                         if (btrfs_inode_in_log(BTRFS_I(di_inode), trans->transid)) {
5494                                 iput(di_inode);
5495                                 break;
5496                         }
5497
5498                         ctx->log_new_dentries = false;
5499                         if (type == BTRFS_FT_DIR || type == BTRFS_FT_SYMLINK)
5500                                 log_mode = LOG_INODE_ALL;
5501                         ret = btrfs_log_inode(trans, root, BTRFS_I(di_inode),
5502                                               log_mode, 0, LLONG_MAX, ctx);
5503                         if (!ret &&
5504                             btrfs_must_commit_transaction(trans, BTRFS_I(di_inode)))
5505                                 ret = 1;
5506                         iput(di_inode);
5507                         if (ret)
5508                                 goto next_dir_inode;
5509                         if (ctx->log_new_dentries) {
5510                                 new_dir_elem = kmalloc(sizeof(*new_dir_elem),
5511                                                        GFP_NOFS);
5512                                 if (!new_dir_elem) {
5513                                         ret = -ENOMEM;
5514                                         goto next_dir_inode;
5515                                 }
5516                                 new_dir_elem->ino = di_key.objectid;
5517                                 list_add_tail(&new_dir_elem->list, &dir_list);
5518                         }
5519                         break;
5520                 }
5521                 if (i == nritems) {
5522                         ret = btrfs_next_leaf(log, path);
5523                         if (ret < 0) {
5524                                 goto next_dir_inode;
5525                         } else if (ret > 0) {
5526                                 ret = 0;
5527                                 goto next_dir_inode;
5528                         }
5529                         goto process_leaf;
5530                 }
5531                 if (min_key.offset < (u64)-1) {
5532                         min_key.offset++;
5533                         goto again;
5534                 }
5535 next_dir_inode:
5536                 list_del(&dir_elem->list);
5537                 kfree(dir_elem);
5538         }
5539
5540         btrfs_free_path(path);
5541         return ret;
5542 }
5543
5544 static int btrfs_log_all_parents(struct btrfs_trans_handle *trans,
5545                                  struct btrfs_inode *inode,
5546                                  struct btrfs_log_ctx *ctx)
5547 {
5548         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
5549         int ret;
5550         struct btrfs_path *path;
5551         struct btrfs_key key;
5552         struct btrfs_root *root = inode->root;
5553         const u64 ino = btrfs_ino(inode);
5554
5555         path = btrfs_alloc_path();
5556         if (!path)
5557                 return -ENOMEM;
5558         path->skip_locking = 1;
5559         path->search_commit_root = 1;
5560
5561         key.objectid = ino;
5562         key.type = BTRFS_INODE_REF_KEY;
5563         key.offset = 0;
5564         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5565         if (ret < 0)
5566                 goto out;
5567
5568         while (true) {
5569                 struct extent_buffer *leaf = path->nodes[0];
5570                 int slot = path->slots[0];
5571                 u32 cur_offset = 0;
5572                 u32 item_size;
5573                 unsigned long ptr;
5574
5575                 if (slot >= btrfs_header_nritems(leaf)) {
5576                         ret = btrfs_next_leaf(root, path);
5577                         if (ret < 0)
5578                                 goto out;
5579                         else if (ret > 0)
5580                                 break;
5581                         continue;
5582                 }
5583
5584                 btrfs_item_key_to_cpu(leaf, &key, slot);
5585                 /* BTRFS_INODE_EXTREF_KEY is BTRFS_INODE_REF_KEY + 1 */
5586                 if (key.objectid != ino || key.type > BTRFS_INODE_EXTREF_KEY)
5587                         break;
5588
5589                 item_size = btrfs_item_size_nr(leaf, slot);
5590                 ptr = btrfs_item_ptr_offset(leaf, slot);
5591                 while (cur_offset < item_size) {
5592                         struct btrfs_key inode_key;
5593                         struct inode *dir_inode;
5594
5595                         inode_key.type = BTRFS_INODE_ITEM_KEY;
5596                         inode_key.offset = 0;
5597
5598                         if (key.type == BTRFS_INODE_EXTREF_KEY) {
5599                                 struct btrfs_inode_extref *extref;
5600
5601                                 extref = (struct btrfs_inode_extref *)
5602                                         (ptr + cur_offset);
5603                                 inode_key.objectid = btrfs_inode_extref_parent(
5604                                         leaf, extref);
5605                                 cur_offset += sizeof(*extref);
5606                                 cur_offset += btrfs_inode_extref_name_len(leaf,
5607                                         extref);
5608                         } else {
5609                                 inode_key.objectid = key.offset;
5610                                 cur_offset = item_size;
5611                         }
5612
5613                         dir_inode = btrfs_iget(fs_info->sb, &inode_key,
5614                                                root, NULL);
5615                         /*
5616                          * If the parent inode was deleted, return an error to
5617                          * fallback to a transaction commit. This is to prevent
5618                          * getting an inode that was moved from one parent A to
5619                          * a parent B, got its former parent A deleted and then
5620                          * it got fsync'ed, from existing at both parents after
5621                          * a log replay (and the old parent still existing).
5622                          * Example:
5623                          *
5624                          * mkdir /mnt/A
5625                          * mkdir /mnt/B
5626                          * touch /mnt/B/bar
5627                          * sync
5628                          * mv /mnt/B/bar /mnt/A/bar
5629                          * mv -T /mnt/A /mnt/B
5630                          * fsync /mnt/B/bar
5631                          * <power fail>
5632                          *
5633                          * If we ignore the old parent B which got deleted,
5634                          * after a log replay we would have file bar linked
5635                          * at both parents and the old parent B would still
5636                          * exist.
5637                          */
5638                         if (IS_ERR(dir_inode)) {
5639                                 ret = PTR_ERR(dir_inode);
5640                                 goto out;
5641                         }
5642
5643                         if (ctx)
5644                                 ctx->log_new_dentries = false;
5645                         ret = btrfs_log_inode(trans, root, BTRFS_I(dir_inode),
5646                                               LOG_INODE_ALL, 0, LLONG_MAX, ctx);
5647                         if (!ret &&
5648                             btrfs_must_commit_transaction(trans, BTRFS_I(dir_inode)))
5649                                 ret = 1;
5650                         if (!ret && ctx && ctx->log_new_dentries)
5651                                 ret = log_new_dir_dentries(trans, root,
5652                                                    BTRFS_I(dir_inode), ctx);
5653                         iput(dir_inode);
5654                         if (ret)
5655                                 goto out;
5656                 }
5657                 path->slots[0]++;
5658         }
5659         ret = 0;
5660 out:
5661         btrfs_free_path(path);
5662         return ret;
5663 }
5664
5665 /*
5666  * helper function around btrfs_log_inode to make sure newly created
5667  * parent directories also end up in the log.  A minimal inode and backref
5668  * only logging is done of any parent directories that are older than
5669  * the last committed transaction
5670  */
5671 static int btrfs_log_inode_parent(struct btrfs_trans_handle *trans,
5672                                   struct btrfs_root *root,
5673                                   struct btrfs_inode *inode,
5674                                   struct dentry *parent,
5675                                   const loff_t start,
5676                                   const loff_t end,
5677                                   int exists_only,
5678                                   struct btrfs_log_ctx *ctx)
5679 {
5680         struct btrfs_fs_info *fs_info = root->fs_info;
5681         int inode_only = exists_only ? LOG_INODE_EXISTS : LOG_INODE_ALL;
5682         struct super_block *sb;
5683         struct dentry *old_parent = NULL;
5684         int ret = 0;
5685         u64 last_committed = fs_info->last_trans_committed;
5686         bool log_dentries = false;
5687         struct btrfs_inode *orig_inode = inode;
5688
5689         sb = inode->vfs_inode.i_sb;
5690
5691         if (btrfs_test_opt(fs_info, NOTREELOG)) {
5692                 ret = 1;
5693                 goto end_no_trans;
5694         }
5695
5696         /*
5697          * The prev transaction commit doesn't complete, we need do
5698          * full commit by ourselves.
5699          */
5700         if (fs_info->last_trans_log_full_commit >
5701             fs_info->last_trans_committed) {
5702                 ret = 1;
5703                 goto end_no_trans;
5704         }
5705
5706         if (root != inode->root || btrfs_root_refs(&root->root_item) == 0) {
5707                 ret = 1;
5708                 goto end_no_trans;
5709         }
5710
5711         ret = check_parent_dirs_for_sync(trans, inode, parent, sb,
5712                         last_committed);
5713         if (ret)
5714                 goto end_no_trans;
5715
5716         /*
5717          * Skip already logged inodes or inodes corresponding to tmpfiles
5718          * (since logging them is pointless, a link count of 0 means they
5719          * will never be accessible).
5720          */
5721         if (btrfs_inode_in_log(inode, trans->transid) ||
5722             inode->vfs_inode.i_nlink == 0) {
5723                 ret = BTRFS_NO_LOG_SYNC;
5724                 goto end_no_trans;
5725         }
5726
5727         ret = start_log_trans(trans, root, ctx);
5728         if (ret)
5729                 goto end_no_trans;
5730
5731         ret = btrfs_log_inode(trans, root, inode, inode_only, start, end, ctx);
5732         if (ret)
5733                 goto end_trans;
5734
5735         /*
5736          * for regular files, if its inode is already on disk, we don't
5737          * have to worry about the parents at all.  This is because
5738          * we can use the last_unlink_trans field to record renames
5739          * and other fun in this file.
5740          */
5741         if (S_ISREG(inode->vfs_inode.i_mode) &&
5742             inode->generation <= last_committed &&
5743             inode->last_unlink_trans <= last_committed) {
5744                 ret = 0;
5745                 goto end_trans;
5746         }
5747
5748         if (S_ISDIR(inode->vfs_inode.i_mode) && ctx && ctx->log_new_dentries)
5749                 log_dentries = true;
5750
5751         /*
5752          * On unlink we must make sure all our current and old parent directory
5753          * inodes are fully logged. This is to prevent leaving dangling
5754          * directory index entries in directories that were our parents but are
5755          * not anymore. Not doing this results in old parent directory being
5756          * impossible to delete after log replay (rmdir will always fail with
5757          * error -ENOTEMPTY).
5758          *
5759          * Example 1:
5760          *
5761          * mkdir testdir
5762          * touch testdir/foo
5763          * ln testdir/foo testdir/bar
5764          * sync
5765          * unlink testdir/bar
5766          * xfs_io -c fsync testdir/foo
5767          * <power failure>
5768          * mount fs, triggers log replay
5769          *
5770          * If we don't log the parent directory (testdir), after log replay the
5771          * directory still has an entry pointing to the file inode using the bar
5772          * name, but a matching BTRFS_INODE_[REF|EXTREF]_KEY does not exist and
5773          * the file inode has a link count of 1.
5774          *
5775          * Example 2:
5776          *
5777          * mkdir testdir
5778          * touch foo
5779          * ln foo testdir/foo2
5780          * ln foo testdir/foo3
5781          * sync
5782          * unlink testdir/foo3
5783          * xfs_io -c fsync foo
5784          * <power failure>
5785          * mount fs, triggers log replay
5786          *
5787          * Similar as the first example, after log replay the parent directory
5788          * testdir still has an entry pointing to the inode file with name foo3
5789          * but the file inode does not have a matching BTRFS_INODE_REF_KEY item
5790          * and has a link count of 2.
5791          */
5792         if (inode->last_unlink_trans > last_committed) {
5793                 ret = btrfs_log_all_parents(trans, orig_inode, ctx);
5794                 if (ret)
5795                         goto end_trans;
5796         }
5797
5798         while (1) {
5799                 if (!parent || d_really_is_negative(parent) || sb != parent->d_sb)
5800                         break;
5801
5802                 inode = BTRFS_I(d_inode(parent));
5803                 if (root != inode->root)
5804                         break;
5805
5806                 if (inode->generation > last_committed) {
5807                         ret = btrfs_log_inode(trans, root, inode,
5808                                         LOG_INODE_EXISTS, 0, LLONG_MAX, ctx);
5809                         if (ret)
5810                                 goto end_trans;
5811                 }
5812                 if (IS_ROOT(parent))
5813                         break;
5814
5815                 parent = dget_parent(parent);
5816                 dput(old_parent);
5817                 old_parent = parent;
5818         }
5819         if (log_dentries)
5820                 ret = log_new_dir_dentries(trans, root, orig_inode, ctx);
5821         else
5822                 ret = 0;
5823 end_trans:
5824         dput(old_parent);
5825         if (ret < 0) {
5826                 btrfs_set_log_full_commit(fs_info, trans);
5827                 ret = 1;
5828         }
5829
5830         if (ret)
5831                 btrfs_remove_log_ctx(root, ctx);
5832         btrfs_end_log_trans(root);
5833 end_no_trans:
5834         return ret;
5835 }
5836
5837 /*
5838  * it is not safe to log dentry if the chunk root has added new
5839  * chunks.  This returns 0 if the dentry was logged, and 1 otherwise.
5840  * If this returns 1, you must commit the transaction to safely get your
5841  * data on disk.
5842  */
5843 int btrfs_log_dentry_safe(struct btrfs_trans_handle *trans,
5844                           struct btrfs_root *root, struct dentry *dentry,
5845                           const loff_t start,
5846                           const loff_t end,
5847                           struct btrfs_log_ctx *ctx)
5848 {
5849         struct dentry *parent = dget_parent(dentry);
5850         int ret;
5851
5852         ret = btrfs_log_inode_parent(trans, root, BTRFS_I(d_inode(dentry)),
5853                         parent, start, end, 0, ctx);
5854         dput(parent);
5855
5856         return ret;
5857 }
5858
5859 /*
5860  * should be called during mount to recover any replay any log trees
5861  * from the FS
5862  */
5863 int btrfs_recover_log_trees(struct btrfs_root *log_root_tree)
5864 {
5865         int ret;
5866         struct btrfs_path *path;
5867         struct btrfs_trans_handle *trans;
5868         struct btrfs_key key;
5869         struct btrfs_key found_key;
5870         struct btrfs_key tmp_key;
5871         struct btrfs_root *log;
5872         struct btrfs_fs_info *fs_info = log_root_tree->fs_info;
5873         struct walk_control wc = {
5874                 .process_func = process_one_buffer,
5875                 .stage = 0,
5876         };
5877
5878         path = btrfs_alloc_path();
5879         if (!path)
5880                 return -ENOMEM;
5881
5882         set_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
5883
5884         trans = btrfs_start_transaction(fs_info->tree_root, 0);
5885         if (IS_ERR(trans)) {
5886                 ret = PTR_ERR(trans);
5887                 goto error;
5888         }
5889
5890         wc.trans = trans;
5891         wc.pin = 1;
5892
5893         ret = walk_log_tree(trans, log_root_tree, &wc);
5894         if (ret) {
5895                 btrfs_handle_fs_error(fs_info, ret,
5896                         "Failed to pin buffers while recovering log root tree.");
5897                 goto error;
5898         }
5899
5900 again:
5901         key.objectid = BTRFS_TREE_LOG_OBJECTID;
5902         key.offset = (u64)-1;
5903         key.type = BTRFS_ROOT_ITEM_KEY;
5904
5905         while (1) {
5906                 ret = btrfs_search_slot(NULL, log_root_tree, &key, path, 0, 0);
5907
5908                 if (ret < 0) {
5909                         btrfs_handle_fs_error(fs_info, ret,
5910                                     "Couldn't find tree log root.");
5911                         goto error;
5912                 }
5913                 if (ret > 0) {
5914                         if (path->slots[0] == 0)
5915                                 break;
5916                         path->slots[0]--;
5917                 }
5918                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
5919                                       path->slots[0]);
5920                 btrfs_release_path(path);
5921                 if (found_key.objectid != BTRFS_TREE_LOG_OBJECTID)
5922                         break;
5923
5924                 log = btrfs_read_fs_root(log_root_tree, &found_key);
5925                 if (IS_ERR(log)) {
5926                         ret = PTR_ERR(log);
5927                         btrfs_handle_fs_error(fs_info, ret,
5928                                     "Couldn't read tree log root.");
5929                         goto error;
5930                 }
5931
5932                 tmp_key.objectid = found_key.offset;
5933                 tmp_key.type = BTRFS_ROOT_ITEM_KEY;
5934                 tmp_key.offset = (u64)-1;
5935
5936                 wc.replay_dest = btrfs_read_fs_root_no_name(fs_info, &tmp_key);
5937                 if (IS_ERR(wc.replay_dest)) {
5938                         ret = PTR_ERR(wc.replay_dest);
5939                         free_extent_buffer(log->node);
5940                         free_extent_buffer(log->commit_root);
5941                         kfree(log);
5942                         btrfs_handle_fs_error(fs_info, ret,
5943                                 "Couldn't read target root for tree log recovery.");
5944                         goto error;
5945                 }
5946
5947                 wc.replay_dest->log_root = log;
5948                 btrfs_record_root_in_trans(trans, wc.replay_dest);
5949                 ret = walk_log_tree(trans, log, &wc);
5950
5951                 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
5952                         ret = fixup_inode_link_counts(trans, wc.replay_dest,
5953                                                       path);
5954                 }
5955
5956                 if (!ret && wc.stage == LOG_WALK_REPLAY_ALL) {
5957                         struct btrfs_root *root = wc.replay_dest;
5958
5959                         btrfs_release_path(path);
5960
5961                         /*
5962                          * We have just replayed everything, and the highest
5963                          * objectid of fs roots probably has changed in case
5964                          * some inode_item's got replayed.
5965                          *
5966                          * root->objectid_mutex is not acquired as log replay
5967                          * could only happen during mount.
5968                          */
5969                         ret = btrfs_find_highest_objectid(root,
5970                                                   &root->highest_objectid);
5971                 }
5972
5973                 key.offset = found_key.offset - 1;
5974                 wc.replay_dest->log_root = NULL;
5975                 free_extent_buffer(log->node);
5976                 free_extent_buffer(log->commit_root);
5977                 kfree(log);
5978
5979                 if (ret)
5980                         goto error;
5981
5982                 if (found_key.offset == 0)
5983                         break;
5984         }
5985         btrfs_release_path(path);
5986
5987         /* step one is to pin it all, step two is to replay just inodes */
5988         if (wc.pin) {
5989                 wc.pin = 0;
5990                 wc.process_func = replay_one_buffer;
5991                 wc.stage = LOG_WALK_REPLAY_INODES;
5992                 goto again;
5993         }
5994         /* step three is to replay everything */
5995         if (wc.stage < LOG_WALK_REPLAY_ALL) {
5996                 wc.stage++;
5997                 goto again;
5998         }
5999
6000         btrfs_free_path(path);
6001
6002         /* step 4: commit the transaction, which also unpins the blocks */
6003         ret = btrfs_commit_transaction(trans);
6004         if (ret)
6005                 return ret;
6006
6007         free_extent_buffer(log_root_tree->node);
6008         log_root_tree->log_root = NULL;
6009         clear_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags);
6010         kfree(log_root_tree);
6011
6012         return 0;
6013 error:
6014         if (wc.trans)
6015                 btrfs_end_transaction(wc.trans);
6016         btrfs_free_path(path);
6017         return ret;
6018 }
6019
6020 /*
6021  * there are some corner cases where we want to force a full
6022  * commit instead of allowing a directory to be logged.
6023  *
6024  * They revolve around files there were unlinked from the directory, and
6025  * this function updates the parent directory so that a full commit is
6026  * properly done if it is fsync'd later after the unlinks are done.
6027  *
6028  * Must be called before the unlink operations (updates to the subvolume tree,
6029  * inodes, etc) are done.
6030  */
6031 void btrfs_record_unlink_dir(struct btrfs_trans_handle *trans,
6032                              struct btrfs_inode *dir, struct btrfs_inode *inode,
6033                              int for_rename)
6034 {
6035         /*
6036          * when we're logging a file, if it hasn't been renamed
6037          * or unlinked, and its inode is fully committed on disk,
6038          * we don't have to worry about walking up the directory chain
6039          * to log its parents.
6040          *
6041          * So, we use the last_unlink_trans field to put this transid
6042          * into the file.  When the file is logged we check it and
6043          * don't log the parents if the file is fully on disk.
6044          */
6045         mutex_lock(&inode->log_mutex);
6046         inode->last_unlink_trans = trans->transid;
6047         mutex_unlock(&inode->log_mutex);
6048
6049         /*
6050          * if this directory was already logged any new
6051          * names for this file/dir will get recorded
6052          */
6053         smp_mb();
6054         if (dir->logged_trans == trans->transid)
6055                 return;
6056
6057         /*
6058          * if the inode we're about to unlink was logged,
6059          * the log will be properly updated for any new names
6060          */
6061         if (inode->logged_trans == trans->transid)
6062                 return;
6063
6064         /*
6065          * when renaming files across directories, if the directory
6066          * there we're unlinking from gets fsync'd later on, there's
6067          * no way to find the destination directory later and fsync it
6068          * properly.  So, we have to be conservative and force commits
6069          * so the new name gets discovered.
6070          */
6071         if (for_rename)
6072                 goto record;
6073
6074         /* we can safely do the unlink without any special recording */
6075         return;
6076
6077 record:
6078         mutex_lock(&dir->log_mutex);
6079         dir->last_unlink_trans = trans->transid;
6080         mutex_unlock(&dir->log_mutex);
6081 }
6082
6083 /*
6084  * Make sure that if someone attempts to fsync the parent directory of a deleted
6085  * snapshot, it ends up triggering a transaction commit. This is to guarantee
6086  * that after replaying the log tree of the parent directory's root we will not
6087  * see the snapshot anymore and at log replay time we will not see any log tree
6088  * corresponding to the deleted snapshot's root, which could lead to replaying
6089  * it after replaying the log tree of the parent directory (which would replay
6090  * the snapshot delete operation).
6091  *
6092  * Must be called before the actual snapshot destroy operation (updates to the
6093  * parent root and tree of tree roots trees, etc) are done.
6094  */
6095 void btrfs_record_snapshot_destroy(struct btrfs_trans_handle *trans,
6096                                    struct btrfs_inode *dir)
6097 {
6098         mutex_lock(&dir->log_mutex);
6099         dir->last_unlink_trans = trans->transid;
6100         mutex_unlock(&dir->log_mutex);
6101 }
6102
6103 /*
6104  * Call this after adding a new name for a file and it will properly
6105  * update the log to reflect the new name.
6106  *
6107  * It will return zero if all goes well, and it will return 1 if a
6108  * full transaction commit is required.
6109  */
6110 int btrfs_log_new_name(struct btrfs_trans_handle *trans,
6111                         struct btrfs_inode *inode, struct btrfs_inode *old_dir,
6112                         struct dentry *parent)
6113 {
6114         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6115         struct btrfs_root *root = inode->root;
6116
6117         /*
6118          * this will force the logging code to walk the dentry chain
6119          * up for the file
6120          */
6121         if (!S_ISDIR(inode->vfs_inode.i_mode))
6122                 inode->last_unlink_trans = trans->transid;
6123
6124         /*
6125          * if this inode hasn't been logged and directory we're renaming it
6126          * from hasn't been logged, we don't need to log it
6127          */
6128         if (inode->logged_trans <= fs_info->last_trans_committed &&
6129             (!old_dir || old_dir->logged_trans <= fs_info->last_trans_committed))
6130                 return 0;
6131
6132         return btrfs_log_inode_parent(trans, root, inode, parent, 0,
6133                                       LLONG_MAX, 1, NULL);
6134 }
6135