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