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