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