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