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