Merge branch 'for-linus2' of git://git.kernel.org/pub/scm/linux/kernel/git/mason...
[muen/linux.git] / fs / btrfs / inode.c
1 /*
2  * Copyright (C) 2007 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/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.h>
46 #include "ctree.h"
47 #include "disk-io.h"
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
52 #include "xattr.h"
53 #include "tree-log.h"
54 #include "volumes.h"
55 #include "compression.h"
56 #include "locking.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
59 #include "backref.h"
60 #include "hash.h"
61 #include "props.h"
62
63 struct btrfs_iget_args {
64         struct btrfs_key *location;
65         struct btrfs_root *root;
66 };
67
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_dir_ro_inode_operations;
71 static const struct inode_operations btrfs_special_inode_operations;
72 static const struct inode_operations btrfs_file_inode_operations;
73 static const struct address_space_operations btrfs_aops;
74 static const struct address_space_operations btrfs_symlink_aops;
75 static const struct file_operations btrfs_dir_file_operations;
76 static struct extent_io_ops btrfs_extent_io_ops;
77
78 static struct kmem_cache *btrfs_inode_cachep;
79 static struct kmem_cache *btrfs_delalloc_work_cachep;
80 struct kmem_cache *btrfs_trans_handle_cachep;
81 struct kmem_cache *btrfs_transaction_cachep;
82 struct kmem_cache *btrfs_path_cachep;
83 struct kmem_cache *btrfs_free_space_cachep;
84
85 #define S_SHIFT 12
86 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
87         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
88         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
89         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
90         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
91         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
92         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
93         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
94 };
95
96 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
97 static int btrfs_truncate(struct inode *inode);
98 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
99 static noinline int cow_file_range(struct inode *inode,
100                                    struct page *locked_page,
101                                    u64 start, u64 end, int *page_started,
102                                    unsigned long *nr_written, int unlock);
103 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
104                                            u64 len, u64 orig_start,
105                                            u64 block_start, u64 block_len,
106                                            u64 orig_block_len, u64 ram_bytes,
107                                            int type);
108
109 static int btrfs_dirty_inode(struct inode *inode);
110
111 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
112                                      struct inode *inode,  struct inode *dir,
113                                      const struct qstr *qstr)
114 {
115         int err;
116
117         err = btrfs_init_acl(trans, inode, dir);
118         if (!err)
119                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
120         return err;
121 }
122
123 /*
124  * this does all the hard work for inserting an inline extent into
125  * the btree.  The caller should have done a btrfs_drop_extents so that
126  * no overlapping inline items exist in the btree
127  */
128 static int insert_inline_extent(struct btrfs_trans_handle *trans,
129                                 struct btrfs_path *path, int extent_inserted,
130                                 struct btrfs_root *root, struct inode *inode,
131                                 u64 start, size_t size, size_t compressed_size,
132                                 int compress_type,
133                                 struct page **compressed_pages)
134 {
135         struct extent_buffer *leaf;
136         struct page *page = NULL;
137         char *kaddr;
138         unsigned long ptr;
139         struct btrfs_file_extent_item *ei;
140         int err = 0;
141         int ret;
142         size_t cur_size = size;
143         unsigned long offset;
144
145         if (compressed_size && compressed_pages)
146                 cur_size = compressed_size;
147
148         inode_add_bytes(inode, size);
149
150         if (!extent_inserted) {
151                 struct btrfs_key key;
152                 size_t datasize;
153
154                 key.objectid = btrfs_ino(inode);
155                 key.offset = start;
156                 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
157
158                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
159                 path->leave_spinning = 1;
160                 ret = btrfs_insert_empty_item(trans, root, path, &key,
161                                               datasize);
162                 if (ret) {
163                         err = ret;
164                         goto fail;
165                 }
166         }
167         leaf = path->nodes[0];
168         ei = btrfs_item_ptr(leaf, path->slots[0],
169                             struct btrfs_file_extent_item);
170         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
171         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
172         btrfs_set_file_extent_encryption(leaf, ei, 0);
173         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
174         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
175         ptr = btrfs_file_extent_inline_start(ei);
176
177         if (compress_type != BTRFS_COMPRESS_NONE) {
178                 struct page *cpage;
179                 int i = 0;
180                 while (compressed_size > 0) {
181                         cpage = compressed_pages[i];
182                         cur_size = min_t(unsigned long, compressed_size,
183                                        PAGE_CACHE_SIZE);
184
185                         kaddr = kmap_atomic(cpage);
186                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
187                         kunmap_atomic(kaddr);
188
189                         i++;
190                         ptr += cur_size;
191                         compressed_size -= cur_size;
192                 }
193                 btrfs_set_file_extent_compression(leaf, ei,
194                                                   compress_type);
195         } else {
196                 page = find_get_page(inode->i_mapping,
197                                      start >> PAGE_CACHE_SHIFT);
198                 btrfs_set_file_extent_compression(leaf, ei, 0);
199                 kaddr = kmap_atomic(page);
200                 offset = start & (PAGE_CACHE_SIZE - 1);
201                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
202                 kunmap_atomic(kaddr);
203                 page_cache_release(page);
204         }
205         btrfs_mark_buffer_dirty(leaf);
206         btrfs_release_path(path);
207
208         /*
209          * we're an inline extent, so nobody can
210          * extend the file past i_size without locking
211          * a page we already have locked.
212          *
213          * We must do any isize and inode updates
214          * before we unlock the pages.  Otherwise we
215          * could end up racing with unlink.
216          */
217         BTRFS_I(inode)->disk_i_size = inode->i_size;
218         ret = btrfs_update_inode(trans, root, inode);
219
220         return ret;
221 fail:
222         return err;
223 }
224
225
226 /*
227  * conditionally insert an inline extent into the file.  This
228  * does the checks required to make sure the data is small enough
229  * to fit as an inline extent.
230  */
231 static noinline int cow_file_range_inline(struct btrfs_root *root,
232                                           struct inode *inode, u64 start,
233                                           u64 end, size_t compressed_size,
234                                           int compress_type,
235                                           struct page **compressed_pages)
236 {
237         struct btrfs_trans_handle *trans;
238         u64 isize = i_size_read(inode);
239         u64 actual_end = min(end + 1, isize);
240         u64 inline_len = actual_end - start;
241         u64 aligned_end = ALIGN(end, root->sectorsize);
242         u64 data_len = inline_len;
243         int ret;
244         struct btrfs_path *path;
245         int extent_inserted = 0;
246         u32 extent_item_size;
247
248         if (compressed_size)
249                 data_len = compressed_size;
250
251         if (start > 0 ||
252             actual_end >= PAGE_CACHE_SIZE ||
253             data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
254             (!compressed_size &&
255             (actual_end & (root->sectorsize - 1)) == 0) ||
256             end + 1 < isize ||
257             data_len > root->fs_info->max_inline) {
258                 return 1;
259         }
260
261         path = btrfs_alloc_path();
262         if (!path)
263                 return -ENOMEM;
264
265         trans = btrfs_join_transaction(root);
266         if (IS_ERR(trans)) {
267                 btrfs_free_path(path);
268                 return PTR_ERR(trans);
269         }
270         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
271
272         if (compressed_size && compressed_pages)
273                 extent_item_size = btrfs_file_extent_calc_inline_size(
274                    compressed_size);
275         else
276                 extent_item_size = btrfs_file_extent_calc_inline_size(
277                     inline_len);
278
279         ret = __btrfs_drop_extents(trans, root, inode, path,
280                                    start, aligned_end, NULL,
281                                    1, 1, extent_item_size, &extent_inserted);
282         if (ret) {
283                 btrfs_abort_transaction(trans, root, ret);
284                 goto out;
285         }
286
287         if (isize > actual_end)
288                 inline_len = min_t(u64, isize, actual_end);
289         ret = insert_inline_extent(trans, path, extent_inserted,
290                                    root, inode, start,
291                                    inline_len, compressed_size,
292                                    compress_type, compressed_pages);
293         if (ret && ret != -ENOSPC) {
294                 btrfs_abort_transaction(trans, root, ret);
295                 goto out;
296         } else if (ret == -ENOSPC) {
297                 ret = 1;
298                 goto out;
299         }
300
301         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
302         btrfs_delalloc_release_metadata(inode, end + 1 - start);
303         btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
304 out:
305         btrfs_free_path(path);
306         btrfs_end_transaction(trans, root);
307         return ret;
308 }
309
310 struct async_extent {
311         u64 start;
312         u64 ram_size;
313         u64 compressed_size;
314         struct page **pages;
315         unsigned long nr_pages;
316         int compress_type;
317         struct list_head list;
318 };
319
320 struct async_cow {
321         struct inode *inode;
322         struct btrfs_root *root;
323         struct page *locked_page;
324         u64 start;
325         u64 end;
326         struct list_head extents;
327         struct btrfs_work work;
328 };
329
330 static noinline int add_async_extent(struct async_cow *cow,
331                                      u64 start, u64 ram_size,
332                                      u64 compressed_size,
333                                      struct page **pages,
334                                      unsigned long nr_pages,
335                                      int compress_type)
336 {
337         struct async_extent *async_extent;
338
339         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
340         BUG_ON(!async_extent); /* -ENOMEM */
341         async_extent->start = start;
342         async_extent->ram_size = ram_size;
343         async_extent->compressed_size = compressed_size;
344         async_extent->pages = pages;
345         async_extent->nr_pages = nr_pages;
346         async_extent->compress_type = compress_type;
347         list_add_tail(&async_extent->list, &cow->extents);
348         return 0;
349 }
350
351 /*
352  * we create compressed extents in two phases.  The first
353  * phase compresses a range of pages that have already been
354  * locked (both pages and state bits are locked).
355  *
356  * This is done inside an ordered work queue, and the compression
357  * is spread across many cpus.  The actual IO submission is step
358  * two, and the ordered work queue takes care of making sure that
359  * happens in the same order things were put onto the queue by
360  * writepages and friends.
361  *
362  * If this code finds it can't get good compression, it puts an
363  * entry onto the work queue to write the uncompressed bytes.  This
364  * makes sure that both compressed inodes and uncompressed inodes
365  * are written in the same order that the flusher thread sent them
366  * down.
367  */
368 static noinline int compress_file_range(struct inode *inode,
369                                         struct page *locked_page,
370                                         u64 start, u64 end,
371                                         struct async_cow *async_cow,
372                                         int *num_added)
373 {
374         struct btrfs_root *root = BTRFS_I(inode)->root;
375         u64 num_bytes;
376         u64 blocksize = root->sectorsize;
377         u64 actual_end;
378         u64 isize = i_size_read(inode);
379         int ret = 0;
380         struct page **pages = NULL;
381         unsigned long nr_pages;
382         unsigned long nr_pages_ret = 0;
383         unsigned long total_compressed = 0;
384         unsigned long total_in = 0;
385         unsigned long max_compressed = 128 * 1024;
386         unsigned long max_uncompressed = 128 * 1024;
387         int i;
388         int will_compress;
389         int compress_type = root->fs_info->compress_type;
390         int redirty = 0;
391
392         /* if this is a small write inside eof, kick off a defrag */
393         if ((end - start + 1) < 16 * 1024 &&
394             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
395                 btrfs_add_inode_defrag(NULL, inode);
396
397         /*
398          * skip compression for a small file range(<=blocksize) that
399          * isn't an inline extent, since it dosen't save disk space at all.
400          */
401         if ((end - start + 1) <= blocksize &&
402             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
403                 goto cleanup_and_bail_uncompressed;
404
405         actual_end = min_t(u64, isize, end + 1);
406 again:
407         will_compress = 0;
408         nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
409         nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
410
411         /*
412          * we don't want to send crud past the end of i_size through
413          * compression, that's just a waste of CPU time.  So, if the
414          * end of the file is before the start of our current
415          * requested range of bytes, we bail out to the uncompressed
416          * cleanup code that can deal with all of this.
417          *
418          * It isn't really the fastest way to fix things, but this is a
419          * very uncommon corner.
420          */
421         if (actual_end <= start)
422                 goto cleanup_and_bail_uncompressed;
423
424         total_compressed = actual_end - start;
425
426         /* we want to make sure that amount of ram required to uncompress
427          * an extent is reasonable, so we limit the total size in ram
428          * of a compressed extent to 128k.  This is a crucial number
429          * because it also controls how easily we can spread reads across
430          * cpus for decompression.
431          *
432          * We also want to make sure the amount of IO required to do
433          * a random read is reasonably small, so we limit the size of
434          * a compressed extent to 128k.
435          */
436         total_compressed = min(total_compressed, max_uncompressed);
437         num_bytes = ALIGN(end - start + 1, blocksize);
438         num_bytes = max(blocksize,  num_bytes);
439         total_in = 0;
440         ret = 0;
441
442         /*
443          * we do compression for mount -o compress and when the
444          * inode has not been flagged as nocompress.  This flag can
445          * change at any time if we discover bad compression ratios.
446          */
447         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
448             (btrfs_test_opt(root, COMPRESS) ||
449              (BTRFS_I(inode)->force_compress) ||
450              (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
451                 WARN_ON(pages);
452                 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
453                 if (!pages) {
454                         /* just bail out to the uncompressed code */
455                         goto cont;
456                 }
457
458                 if (BTRFS_I(inode)->force_compress)
459                         compress_type = BTRFS_I(inode)->force_compress;
460
461                 /*
462                  * we need to call clear_page_dirty_for_io on each
463                  * page in the range.  Otherwise applications with the file
464                  * mmap'd can wander in and change the page contents while
465                  * we are compressing them.
466                  *
467                  * If the compression fails for any reason, we set the pages
468                  * dirty again later on.
469                  */
470                 extent_range_clear_dirty_for_io(inode, start, end);
471                 redirty = 1;
472                 ret = btrfs_compress_pages(compress_type,
473                                            inode->i_mapping, start,
474                                            total_compressed, pages,
475                                            nr_pages, &nr_pages_ret,
476                                            &total_in,
477                                            &total_compressed,
478                                            max_compressed);
479
480                 if (!ret) {
481                         unsigned long offset = total_compressed &
482                                 (PAGE_CACHE_SIZE - 1);
483                         struct page *page = pages[nr_pages_ret - 1];
484                         char *kaddr;
485
486                         /* zero the tail end of the last page, we might be
487                          * sending it down to disk
488                          */
489                         if (offset) {
490                                 kaddr = kmap_atomic(page);
491                                 memset(kaddr + offset, 0,
492                                        PAGE_CACHE_SIZE - offset);
493                                 kunmap_atomic(kaddr);
494                         }
495                         will_compress = 1;
496                 }
497         }
498 cont:
499         if (start == 0) {
500                 /* lets try to make an inline extent */
501                 if (ret || total_in < (actual_end - start)) {
502                         /* we didn't compress the entire range, try
503                          * to make an uncompressed inline extent.
504                          */
505                         ret = cow_file_range_inline(root, inode, start, end,
506                                                     0, 0, NULL);
507                 } else {
508                         /* try making a compressed inline extent */
509                         ret = cow_file_range_inline(root, inode, start, end,
510                                                     total_compressed,
511                                                     compress_type, pages);
512                 }
513                 if (ret <= 0) {
514                         unsigned long clear_flags = EXTENT_DELALLOC |
515                                 EXTENT_DEFRAG;
516                         clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
517
518                         /*
519                          * inline extent creation worked or returned error,
520                          * we don't need to create any more async work items.
521                          * Unlock and free up our temp pages.
522                          */
523                         extent_clear_unlock_delalloc(inode, start, end, NULL,
524                                                      clear_flags, PAGE_UNLOCK |
525                                                      PAGE_CLEAR_DIRTY |
526                                                      PAGE_SET_WRITEBACK |
527                                                      PAGE_END_WRITEBACK);
528                         goto free_pages_out;
529                 }
530         }
531
532         if (will_compress) {
533                 /*
534                  * we aren't doing an inline extent round the compressed size
535                  * up to a block size boundary so the allocator does sane
536                  * things
537                  */
538                 total_compressed = ALIGN(total_compressed, blocksize);
539
540                 /*
541                  * one last check to make sure the compression is really a
542                  * win, compare the page count read with the blocks on disk
543                  */
544                 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
545                 if (total_compressed >= total_in) {
546                         will_compress = 0;
547                 } else {
548                         num_bytes = total_in;
549                 }
550         }
551         if (!will_compress && pages) {
552                 /*
553                  * the compression code ran but failed to make things smaller,
554                  * free any pages it allocated and our page pointer array
555                  */
556                 for (i = 0; i < nr_pages_ret; i++) {
557                         WARN_ON(pages[i]->mapping);
558                         page_cache_release(pages[i]);
559                 }
560                 kfree(pages);
561                 pages = NULL;
562                 total_compressed = 0;
563                 nr_pages_ret = 0;
564
565                 /* flag the file so we don't compress in the future */
566                 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
567                     !(BTRFS_I(inode)->force_compress)) {
568                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
569                 }
570         }
571         if (will_compress) {
572                 *num_added += 1;
573
574                 /* the async work queues will take care of doing actual
575                  * allocation on disk for these compressed pages,
576                  * and will submit them to the elevator.
577                  */
578                 add_async_extent(async_cow, start, num_bytes,
579                                  total_compressed, pages, nr_pages_ret,
580                                  compress_type);
581
582                 if (start + num_bytes < end) {
583                         start += num_bytes;
584                         pages = NULL;
585                         cond_resched();
586                         goto again;
587                 }
588         } else {
589 cleanup_and_bail_uncompressed:
590                 /*
591                  * No compression, but we still need to write the pages in
592                  * the file we've been given so far.  redirty the locked
593                  * page if it corresponds to our extent and set things up
594                  * for the async work queue to run cow_file_range to do
595                  * the normal delalloc dance
596                  */
597                 if (page_offset(locked_page) >= start &&
598                     page_offset(locked_page) <= end) {
599                         __set_page_dirty_nobuffers(locked_page);
600                         /* unlocked later on in the async handlers */
601                 }
602                 if (redirty)
603                         extent_range_redirty_for_io(inode, start, end);
604                 add_async_extent(async_cow, start, end - start + 1,
605                                  0, NULL, 0, BTRFS_COMPRESS_NONE);
606                 *num_added += 1;
607         }
608
609 out:
610         return ret;
611
612 free_pages_out:
613         for (i = 0; i < nr_pages_ret; i++) {
614                 WARN_ON(pages[i]->mapping);
615                 page_cache_release(pages[i]);
616         }
617         kfree(pages);
618
619         goto out;
620 }
621
622 /*
623  * phase two of compressed writeback.  This is the ordered portion
624  * of the code, which only gets called in the order the work was
625  * queued.  We walk all the async extents created by compress_file_range
626  * and send them down to the disk.
627  */
628 static noinline int submit_compressed_extents(struct inode *inode,
629                                               struct async_cow *async_cow)
630 {
631         struct async_extent *async_extent;
632         u64 alloc_hint = 0;
633         struct btrfs_key ins;
634         struct extent_map *em;
635         struct btrfs_root *root = BTRFS_I(inode)->root;
636         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
637         struct extent_io_tree *io_tree;
638         int ret = 0;
639
640         if (list_empty(&async_cow->extents))
641                 return 0;
642
643 again:
644         while (!list_empty(&async_cow->extents)) {
645                 async_extent = list_entry(async_cow->extents.next,
646                                           struct async_extent, list);
647                 list_del(&async_extent->list);
648
649                 io_tree = &BTRFS_I(inode)->io_tree;
650
651 retry:
652                 /* did the compression code fall back to uncompressed IO? */
653                 if (!async_extent->pages) {
654                         int page_started = 0;
655                         unsigned long nr_written = 0;
656
657                         lock_extent(io_tree, async_extent->start,
658                                          async_extent->start +
659                                          async_extent->ram_size - 1);
660
661                         /* allocate blocks */
662                         ret = cow_file_range(inode, async_cow->locked_page,
663                                              async_extent->start,
664                                              async_extent->start +
665                                              async_extent->ram_size - 1,
666                                              &page_started, &nr_written, 0);
667
668                         /* JDM XXX */
669
670                         /*
671                          * if page_started, cow_file_range inserted an
672                          * inline extent and took care of all the unlocking
673                          * and IO for us.  Otherwise, we need to submit
674                          * all those pages down to the drive.
675                          */
676                         if (!page_started && !ret)
677                                 extent_write_locked_range(io_tree,
678                                                   inode, async_extent->start,
679                                                   async_extent->start +
680                                                   async_extent->ram_size - 1,
681                                                   btrfs_get_extent,
682                                                   WB_SYNC_ALL);
683                         else if (ret)
684                                 unlock_page(async_cow->locked_page);
685                         kfree(async_extent);
686                         cond_resched();
687                         continue;
688                 }
689
690                 lock_extent(io_tree, async_extent->start,
691                             async_extent->start + async_extent->ram_size - 1);
692
693                 ret = btrfs_reserve_extent(root,
694                                            async_extent->compressed_size,
695                                            async_extent->compressed_size,
696                                            0, alloc_hint, &ins, 1, 1);
697                 if (ret) {
698                         int i;
699
700                         for (i = 0; i < async_extent->nr_pages; i++) {
701                                 WARN_ON(async_extent->pages[i]->mapping);
702                                 page_cache_release(async_extent->pages[i]);
703                         }
704                         kfree(async_extent->pages);
705                         async_extent->nr_pages = 0;
706                         async_extent->pages = NULL;
707
708                         if (ret == -ENOSPC) {
709                                 unlock_extent(io_tree, async_extent->start,
710                                               async_extent->start +
711                                               async_extent->ram_size - 1);
712
713                                 /*
714                                  * we need to redirty the pages if we decide to
715                                  * fallback to uncompressed IO, otherwise we
716                                  * will not submit these pages down to lower
717                                  * layers.
718                                  */
719                                 extent_range_redirty_for_io(inode,
720                                                 async_extent->start,
721                                                 async_extent->start +
722                                                 async_extent->ram_size - 1);
723
724                                 goto retry;
725                         }
726                         goto out_free;
727                 }
728
729                 /*
730                  * here we're doing allocation and writeback of the
731                  * compressed pages
732                  */
733                 btrfs_drop_extent_cache(inode, async_extent->start,
734                                         async_extent->start +
735                                         async_extent->ram_size - 1, 0);
736
737                 em = alloc_extent_map();
738                 if (!em) {
739                         ret = -ENOMEM;
740                         goto out_free_reserve;
741                 }
742                 em->start = async_extent->start;
743                 em->len = async_extent->ram_size;
744                 em->orig_start = em->start;
745                 em->mod_start = em->start;
746                 em->mod_len = em->len;
747
748                 em->block_start = ins.objectid;
749                 em->block_len = ins.offset;
750                 em->orig_block_len = ins.offset;
751                 em->ram_bytes = async_extent->ram_size;
752                 em->bdev = root->fs_info->fs_devices->latest_bdev;
753                 em->compress_type = async_extent->compress_type;
754                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
755                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
756                 em->generation = -1;
757
758                 while (1) {
759                         write_lock(&em_tree->lock);
760                         ret = add_extent_mapping(em_tree, em, 1);
761                         write_unlock(&em_tree->lock);
762                         if (ret != -EEXIST) {
763                                 free_extent_map(em);
764                                 break;
765                         }
766                         btrfs_drop_extent_cache(inode, async_extent->start,
767                                                 async_extent->start +
768                                                 async_extent->ram_size - 1, 0);
769                 }
770
771                 if (ret)
772                         goto out_free_reserve;
773
774                 ret = btrfs_add_ordered_extent_compress(inode,
775                                                 async_extent->start,
776                                                 ins.objectid,
777                                                 async_extent->ram_size,
778                                                 ins.offset,
779                                                 BTRFS_ORDERED_COMPRESSED,
780                                                 async_extent->compress_type);
781                 if (ret)
782                         goto out_free_reserve;
783
784                 /*
785                  * clear dirty, set writeback and unlock the pages.
786                  */
787                 extent_clear_unlock_delalloc(inode, async_extent->start,
788                                 async_extent->start +
789                                 async_extent->ram_size - 1,
790                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
791                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
792                                 PAGE_SET_WRITEBACK);
793                 ret = btrfs_submit_compressed_write(inode,
794                                     async_extent->start,
795                                     async_extent->ram_size,
796                                     ins.objectid,
797                                     ins.offset, async_extent->pages,
798                                     async_extent->nr_pages);
799                 alloc_hint = ins.objectid + ins.offset;
800                 kfree(async_extent);
801                 if (ret)
802                         goto out;
803                 cond_resched();
804         }
805         ret = 0;
806 out:
807         return ret;
808 out_free_reserve:
809         btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
810 out_free:
811         extent_clear_unlock_delalloc(inode, async_extent->start,
812                                      async_extent->start +
813                                      async_extent->ram_size - 1,
814                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
815                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
816                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
817                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
818         kfree(async_extent);
819         goto again;
820 }
821
822 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
823                                       u64 num_bytes)
824 {
825         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
826         struct extent_map *em;
827         u64 alloc_hint = 0;
828
829         read_lock(&em_tree->lock);
830         em = search_extent_mapping(em_tree, start, num_bytes);
831         if (em) {
832                 /*
833                  * if block start isn't an actual block number then find the
834                  * first block in this inode and use that as a hint.  If that
835                  * block is also bogus then just don't worry about it.
836                  */
837                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
838                         free_extent_map(em);
839                         em = search_extent_mapping(em_tree, 0, 0);
840                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
841                                 alloc_hint = em->block_start;
842                         if (em)
843                                 free_extent_map(em);
844                 } else {
845                         alloc_hint = em->block_start;
846                         free_extent_map(em);
847                 }
848         }
849         read_unlock(&em_tree->lock);
850
851         return alloc_hint;
852 }
853
854 /*
855  * when extent_io.c finds a delayed allocation range in the file,
856  * the call backs end up in this code.  The basic idea is to
857  * allocate extents on disk for the range, and create ordered data structs
858  * in ram to track those extents.
859  *
860  * locked_page is the page that writepage had locked already.  We use
861  * it to make sure we don't do extra locks or unlocks.
862  *
863  * *page_started is set to one if we unlock locked_page and do everything
864  * required to start IO on it.  It may be clean and already done with
865  * IO when we return.
866  */
867 static noinline int cow_file_range(struct inode *inode,
868                                    struct page *locked_page,
869                                    u64 start, u64 end, int *page_started,
870                                    unsigned long *nr_written,
871                                    int unlock)
872 {
873         struct btrfs_root *root = BTRFS_I(inode)->root;
874         u64 alloc_hint = 0;
875         u64 num_bytes;
876         unsigned long ram_size;
877         u64 disk_num_bytes;
878         u64 cur_alloc_size;
879         u64 blocksize = root->sectorsize;
880         struct btrfs_key ins;
881         struct extent_map *em;
882         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
883         int ret = 0;
884
885         if (btrfs_is_free_space_inode(inode)) {
886                 WARN_ON_ONCE(1);
887                 ret = -EINVAL;
888                 goto out_unlock;
889         }
890
891         num_bytes = ALIGN(end - start + 1, blocksize);
892         num_bytes = max(blocksize,  num_bytes);
893         disk_num_bytes = num_bytes;
894
895         /* if this is a small write inside eof, kick off defrag */
896         if (num_bytes < 64 * 1024 &&
897             (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
898                 btrfs_add_inode_defrag(NULL, inode);
899
900         if (start == 0) {
901                 /* lets try to make an inline extent */
902                 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
903                                             NULL);
904                 if (ret == 0) {
905                         extent_clear_unlock_delalloc(inode, start, end, NULL,
906                                      EXTENT_LOCKED | EXTENT_DELALLOC |
907                                      EXTENT_DEFRAG, PAGE_UNLOCK |
908                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
909                                      PAGE_END_WRITEBACK);
910
911                         *nr_written = *nr_written +
912                              (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
913                         *page_started = 1;
914                         goto out;
915                 } else if (ret < 0) {
916                         goto out_unlock;
917                 }
918         }
919
920         BUG_ON(disk_num_bytes >
921                btrfs_super_total_bytes(root->fs_info->super_copy));
922
923         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
924         btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
925
926         while (disk_num_bytes > 0) {
927                 unsigned long op;
928
929                 cur_alloc_size = disk_num_bytes;
930                 ret = btrfs_reserve_extent(root, cur_alloc_size,
931                                            root->sectorsize, 0, alloc_hint,
932                                            &ins, 1, 1);
933                 if (ret < 0)
934                         goto out_unlock;
935
936                 em = alloc_extent_map();
937                 if (!em) {
938                         ret = -ENOMEM;
939                         goto out_reserve;
940                 }
941                 em->start = start;
942                 em->orig_start = em->start;
943                 ram_size = ins.offset;
944                 em->len = ins.offset;
945                 em->mod_start = em->start;
946                 em->mod_len = em->len;
947
948                 em->block_start = ins.objectid;
949                 em->block_len = ins.offset;
950                 em->orig_block_len = ins.offset;
951                 em->ram_bytes = ram_size;
952                 em->bdev = root->fs_info->fs_devices->latest_bdev;
953                 set_bit(EXTENT_FLAG_PINNED, &em->flags);
954                 em->generation = -1;
955
956                 while (1) {
957                         write_lock(&em_tree->lock);
958                         ret = add_extent_mapping(em_tree, em, 1);
959                         write_unlock(&em_tree->lock);
960                         if (ret != -EEXIST) {
961                                 free_extent_map(em);
962                                 break;
963                         }
964                         btrfs_drop_extent_cache(inode, start,
965                                                 start + ram_size - 1, 0);
966                 }
967                 if (ret)
968                         goto out_reserve;
969
970                 cur_alloc_size = ins.offset;
971                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
972                                                ram_size, cur_alloc_size, 0);
973                 if (ret)
974                         goto out_reserve;
975
976                 if (root->root_key.objectid ==
977                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
978                         ret = btrfs_reloc_clone_csums(inode, start,
979                                                       cur_alloc_size);
980                         if (ret)
981                                 goto out_reserve;
982                 }
983
984                 if (disk_num_bytes < cur_alloc_size)
985                         break;
986
987                 /* we're not doing compressed IO, don't unlock the first
988                  * page (which the caller expects to stay locked), don't
989                  * clear any dirty bits and don't set any writeback bits
990                  *
991                  * Do set the Private2 bit so we know this page was properly
992                  * setup for writepage
993                  */
994                 op = unlock ? PAGE_UNLOCK : 0;
995                 op |= PAGE_SET_PRIVATE2;
996
997                 extent_clear_unlock_delalloc(inode, start,
998                                              start + ram_size - 1, locked_page,
999                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1000                                              op);
1001                 disk_num_bytes -= cur_alloc_size;
1002                 num_bytes -= cur_alloc_size;
1003                 alloc_hint = ins.objectid + ins.offset;
1004                 start += cur_alloc_size;
1005         }
1006 out:
1007         return ret;
1008
1009 out_reserve:
1010         btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1011 out_unlock:
1012         extent_clear_unlock_delalloc(inode, start, end, locked_page,
1013                                      EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1014                                      EXTENT_DELALLOC | EXTENT_DEFRAG,
1015                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1016                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1017         goto out;
1018 }
1019
1020 /*
1021  * work queue call back to started compression on a file and pages
1022  */
1023 static noinline void async_cow_start(struct btrfs_work *work)
1024 {
1025         struct async_cow *async_cow;
1026         int num_added = 0;
1027         async_cow = container_of(work, struct async_cow, work);
1028
1029         compress_file_range(async_cow->inode, async_cow->locked_page,
1030                             async_cow->start, async_cow->end, async_cow,
1031                             &num_added);
1032         if (num_added == 0) {
1033                 btrfs_add_delayed_iput(async_cow->inode);
1034                 async_cow->inode = NULL;
1035         }
1036 }
1037
1038 /*
1039  * work queue call back to submit previously compressed pages
1040  */
1041 static noinline void async_cow_submit(struct btrfs_work *work)
1042 {
1043         struct async_cow *async_cow;
1044         struct btrfs_root *root;
1045         unsigned long nr_pages;
1046
1047         async_cow = container_of(work, struct async_cow, work);
1048
1049         root = async_cow->root;
1050         nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1051                 PAGE_CACHE_SHIFT;
1052
1053         if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1054             5 * 1024 * 1024 &&
1055             waitqueue_active(&root->fs_info->async_submit_wait))
1056                 wake_up(&root->fs_info->async_submit_wait);
1057
1058         if (async_cow->inode)
1059                 submit_compressed_extents(async_cow->inode, async_cow);
1060 }
1061
1062 static noinline void async_cow_free(struct btrfs_work *work)
1063 {
1064         struct async_cow *async_cow;
1065         async_cow = container_of(work, struct async_cow, work);
1066         if (async_cow->inode)
1067                 btrfs_add_delayed_iput(async_cow->inode);
1068         kfree(async_cow);
1069 }
1070
1071 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1072                                 u64 start, u64 end, int *page_started,
1073                                 unsigned long *nr_written)
1074 {
1075         struct async_cow *async_cow;
1076         struct btrfs_root *root = BTRFS_I(inode)->root;
1077         unsigned long nr_pages;
1078         u64 cur_end;
1079         int limit = 10 * 1024 * 1024;
1080
1081         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1082                          1, 0, NULL, GFP_NOFS);
1083         while (start < end) {
1084                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1085                 BUG_ON(!async_cow); /* -ENOMEM */
1086                 async_cow->inode = igrab(inode);
1087                 async_cow->root = root;
1088                 async_cow->locked_page = locked_page;
1089                 async_cow->start = start;
1090
1091                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1092                         cur_end = end;
1093                 else
1094                         cur_end = min(end, start + 512 * 1024 - 1);
1095
1096                 async_cow->end = cur_end;
1097                 INIT_LIST_HEAD(&async_cow->extents);
1098
1099                 btrfs_init_work(&async_cow->work, async_cow_start,
1100                                 async_cow_submit, async_cow_free);
1101
1102                 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1103                         PAGE_CACHE_SHIFT;
1104                 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1105
1106                 btrfs_queue_work(root->fs_info->delalloc_workers,
1107                                  &async_cow->work);
1108
1109                 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1110                         wait_event(root->fs_info->async_submit_wait,
1111                            (atomic_read(&root->fs_info->async_delalloc_pages) <
1112                             limit));
1113                 }
1114
1115                 while (atomic_read(&root->fs_info->async_submit_draining) &&
1116                       atomic_read(&root->fs_info->async_delalloc_pages)) {
1117                         wait_event(root->fs_info->async_submit_wait,
1118                           (atomic_read(&root->fs_info->async_delalloc_pages) ==
1119                            0));
1120                 }
1121
1122                 *nr_written += nr_pages;
1123                 start = cur_end + 1;
1124         }
1125         *page_started = 1;
1126         return 0;
1127 }
1128
1129 static noinline int csum_exist_in_range(struct btrfs_root *root,
1130                                         u64 bytenr, u64 num_bytes)
1131 {
1132         int ret;
1133         struct btrfs_ordered_sum *sums;
1134         LIST_HEAD(list);
1135
1136         ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1137                                        bytenr + num_bytes - 1, &list, 0);
1138         if (ret == 0 && list_empty(&list))
1139                 return 0;
1140
1141         while (!list_empty(&list)) {
1142                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1143                 list_del(&sums->list);
1144                 kfree(sums);
1145         }
1146         return 1;
1147 }
1148
1149 /*
1150  * when nowcow writeback call back.  This checks for snapshots or COW copies
1151  * of the extents that exist in the file, and COWs the file as required.
1152  *
1153  * If no cow copies or snapshots exist, we write directly to the existing
1154  * blocks on disk
1155  */
1156 static noinline int run_delalloc_nocow(struct inode *inode,
1157                                        struct page *locked_page,
1158                               u64 start, u64 end, int *page_started, int force,
1159                               unsigned long *nr_written)
1160 {
1161         struct btrfs_root *root = BTRFS_I(inode)->root;
1162         struct btrfs_trans_handle *trans;
1163         struct extent_buffer *leaf;
1164         struct btrfs_path *path;
1165         struct btrfs_file_extent_item *fi;
1166         struct btrfs_key found_key;
1167         u64 cow_start;
1168         u64 cur_offset;
1169         u64 extent_end;
1170         u64 extent_offset;
1171         u64 disk_bytenr;
1172         u64 num_bytes;
1173         u64 disk_num_bytes;
1174         u64 ram_bytes;
1175         int extent_type;
1176         int ret, err;
1177         int type;
1178         int nocow;
1179         int check_prev = 1;
1180         bool nolock;
1181         u64 ino = btrfs_ino(inode);
1182
1183         path = btrfs_alloc_path();
1184         if (!path) {
1185                 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1186                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1187                                              EXTENT_DO_ACCOUNTING |
1188                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1189                                              PAGE_CLEAR_DIRTY |
1190                                              PAGE_SET_WRITEBACK |
1191                                              PAGE_END_WRITEBACK);
1192                 return -ENOMEM;
1193         }
1194
1195         nolock = btrfs_is_free_space_inode(inode);
1196
1197         if (nolock)
1198                 trans = btrfs_join_transaction_nolock(root);
1199         else
1200                 trans = btrfs_join_transaction(root);
1201
1202         if (IS_ERR(trans)) {
1203                 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1204                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1205                                              EXTENT_DO_ACCOUNTING |
1206                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1207                                              PAGE_CLEAR_DIRTY |
1208                                              PAGE_SET_WRITEBACK |
1209                                              PAGE_END_WRITEBACK);
1210                 btrfs_free_path(path);
1211                 return PTR_ERR(trans);
1212         }
1213
1214         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1215
1216         cow_start = (u64)-1;
1217         cur_offset = start;
1218         while (1) {
1219                 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1220                                                cur_offset, 0);
1221                 if (ret < 0)
1222                         goto error;
1223                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1224                         leaf = path->nodes[0];
1225                         btrfs_item_key_to_cpu(leaf, &found_key,
1226                                               path->slots[0] - 1);
1227                         if (found_key.objectid == ino &&
1228                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1229                                 path->slots[0]--;
1230                 }
1231                 check_prev = 0;
1232 next_slot:
1233                 leaf = path->nodes[0];
1234                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1235                         ret = btrfs_next_leaf(root, path);
1236                         if (ret < 0)
1237                                 goto error;
1238                         if (ret > 0)
1239                                 break;
1240                         leaf = path->nodes[0];
1241                 }
1242
1243                 nocow = 0;
1244                 disk_bytenr = 0;
1245                 num_bytes = 0;
1246                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1247
1248                 if (found_key.objectid > ino ||
1249                     found_key.type > BTRFS_EXTENT_DATA_KEY ||
1250                     found_key.offset > end)
1251                         break;
1252
1253                 if (found_key.offset > cur_offset) {
1254                         extent_end = found_key.offset;
1255                         extent_type = 0;
1256                         goto out_check;
1257                 }
1258
1259                 fi = btrfs_item_ptr(leaf, path->slots[0],
1260                                     struct btrfs_file_extent_item);
1261                 extent_type = btrfs_file_extent_type(leaf, fi);
1262
1263                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1264                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1265                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1266                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1267                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1268                         extent_end = found_key.offset +
1269                                 btrfs_file_extent_num_bytes(leaf, fi);
1270                         disk_num_bytes =
1271                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1272                         if (extent_end <= start) {
1273                                 path->slots[0]++;
1274                                 goto next_slot;
1275                         }
1276                         if (disk_bytenr == 0)
1277                                 goto out_check;
1278                         if (btrfs_file_extent_compression(leaf, fi) ||
1279                             btrfs_file_extent_encryption(leaf, fi) ||
1280                             btrfs_file_extent_other_encoding(leaf, fi))
1281                                 goto out_check;
1282                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1283                                 goto out_check;
1284                         if (btrfs_extent_readonly(root, disk_bytenr))
1285                                 goto out_check;
1286                         if (btrfs_cross_ref_exist(trans, root, ino,
1287                                                   found_key.offset -
1288                                                   extent_offset, disk_bytenr))
1289                                 goto out_check;
1290                         disk_bytenr += extent_offset;
1291                         disk_bytenr += cur_offset - found_key.offset;
1292                         num_bytes = min(end + 1, extent_end) - cur_offset;
1293                         /*
1294                          * if there are pending snapshots for this root,
1295                          * we fall into common COW way.
1296                          */
1297                         if (!nolock) {
1298                                 err = btrfs_start_nocow_write(root);
1299                                 if (!err)
1300                                         goto out_check;
1301                         }
1302                         /*
1303                          * force cow if csum exists in the range.
1304                          * this ensure that csum for a given extent are
1305                          * either valid or do not exist.
1306                          */
1307                         if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1308                                 goto out_check;
1309                         nocow = 1;
1310                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1311                         extent_end = found_key.offset +
1312                                 btrfs_file_extent_inline_len(leaf,
1313                                                      path->slots[0], fi);
1314                         extent_end = ALIGN(extent_end, root->sectorsize);
1315                 } else {
1316                         BUG_ON(1);
1317                 }
1318 out_check:
1319                 if (extent_end <= start) {
1320                         path->slots[0]++;
1321                         if (!nolock && nocow)
1322                                 btrfs_end_nocow_write(root);
1323                         goto next_slot;
1324                 }
1325                 if (!nocow) {
1326                         if (cow_start == (u64)-1)
1327                                 cow_start = cur_offset;
1328                         cur_offset = extent_end;
1329                         if (cur_offset > end)
1330                                 break;
1331                         path->slots[0]++;
1332                         goto next_slot;
1333                 }
1334
1335                 btrfs_release_path(path);
1336                 if (cow_start != (u64)-1) {
1337                         ret = cow_file_range(inode, locked_page,
1338                                              cow_start, found_key.offset - 1,
1339                                              page_started, nr_written, 1);
1340                         if (ret) {
1341                                 if (!nolock && nocow)
1342                                         btrfs_end_nocow_write(root);
1343                                 goto error;
1344                         }
1345                         cow_start = (u64)-1;
1346                 }
1347
1348                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1349                         struct extent_map *em;
1350                         struct extent_map_tree *em_tree;
1351                         em_tree = &BTRFS_I(inode)->extent_tree;
1352                         em = alloc_extent_map();
1353                         BUG_ON(!em); /* -ENOMEM */
1354                         em->start = cur_offset;
1355                         em->orig_start = found_key.offset - extent_offset;
1356                         em->len = num_bytes;
1357                         em->block_len = num_bytes;
1358                         em->block_start = disk_bytenr;
1359                         em->orig_block_len = disk_num_bytes;
1360                         em->ram_bytes = ram_bytes;
1361                         em->bdev = root->fs_info->fs_devices->latest_bdev;
1362                         em->mod_start = em->start;
1363                         em->mod_len = em->len;
1364                         set_bit(EXTENT_FLAG_PINNED, &em->flags);
1365                         set_bit(EXTENT_FLAG_FILLING, &em->flags);
1366                         em->generation = -1;
1367                         while (1) {
1368                                 write_lock(&em_tree->lock);
1369                                 ret = add_extent_mapping(em_tree, em, 1);
1370                                 write_unlock(&em_tree->lock);
1371                                 if (ret != -EEXIST) {
1372                                         free_extent_map(em);
1373                                         break;
1374                                 }
1375                                 btrfs_drop_extent_cache(inode, em->start,
1376                                                 em->start + em->len - 1, 0);
1377                         }
1378                         type = BTRFS_ORDERED_PREALLOC;
1379                 } else {
1380                         type = BTRFS_ORDERED_NOCOW;
1381                 }
1382
1383                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1384                                                num_bytes, num_bytes, type);
1385                 BUG_ON(ret); /* -ENOMEM */
1386
1387                 if (root->root_key.objectid ==
1388                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1389                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1390                                                       num_bytes);
1391                         if (ret) {
1392                                 if (!nolock && nocow)
1393                                         btrfs_end_nocow_write(root);
1394                                 goto error;
1395                         }
1396                 }
1397
1398                 extent_clear_unlock_delalloc(inode, cur_offset,
1399                                              cur_offset + num_bytes - 1,
1400                                              locked_page, EXTENT_LOCKED |
1401                                              EXTENT_DELALLOC, PAGE_UNLOCK |
1402                                              PAGE_SET_PRIVATE2);
1403                 if (!nolock && nocow)
1404                         btrfs_end_nocow_write(root);
1405                 cur_offset = extent_end;
1406                 if (cur_offset > end)
1407                         break;
1408         }
1409         btrfs_release_path(path);
1410
1411         if (cur_offset <= end && cow_start == (u64)-1) {
1412                 cow_start = cur_offset;
1413                 cur_offset = end;
1414         }
1415
1416         if (cow_start != (u64)-1) {
1417                 ret = cow_file_range(inode, locked_page, cow_start, end,
1418                                      page_started, nr_written, 1);
1419                 if (ret)
1420                         goto error;
1421         }
1422
1423 error:
1424         err = btrfs_end_transaction(trans, root);
1425         if (!ret)
1426                 ret = err;
1427
1428         if (ret && cur_offset < end)
1429                 extent_clear_unlock_delalloc(inode, cur_offset, end,
1430                                              locked_page, EXTENT_LOCKED |
1431                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1432                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1433                                              PAGE_CLEAR_DIRTY |
1434                                              PAGE_SET_WRITEBACK |
1435                                              PAGE_END_WRITEBACK);
1436         btrfs_free_path(path);
1437         return ret;
1438 }
1439
1440 /*
1441  * extent_io.c call back to do delayed allocation processing
1442  */
1443 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1444                               u64 start, u64 end, int *page_started,
1445                               unsigned long *nr_written)
1446 {
1447         int ret;
1448         struct btrfs_root *root = BTRFS_I(inode)->root;
1449
1450         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1451                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1452                                          page_started, 1, nr_written);
1453         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1454                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1455                                          page_started, 0, nr_written);
1456         } else if (!btrfs_test_opt(root, COMPRESS) &&
1457                    !(BTRFS_I(inode)->force_compress) &&
1458                    !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1459                 ret = cow_file_range(inode, locked_page, start, end,
1460                                       page_started, nr_written, 1);
1461         } else {
1462                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1463                         &BTRFS_I(inode)->runtime_flags);
1464                 ret = cow_file_range_async(inode, locked_page, start, end,
1465                                            page_started, nr_written);
1466         }
1467         return ret;
1468 }
1469
1470 static void btrfs_split_extent_hook(struct inode *inode,
1471                                     struct extent_state *orig, u64 split)
1472 {
1473         /* not delalloc, ignore it */
1474         if (!(orig->state & EXTENT_DELALLOC))
1475                 return;
1476
1477         spin_lock(&BTRFS_I(inode)->lock);
1478         BTRFS_I(inode)->outstanding_extents++;
1479         spin_unlock(&BTRFS_I(inode)->lock);
1480 }
1481
1482 /*
1483  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1484  * extents so we can keep track of new extents that are just merged onto old
1485  * extents, such as when we are doing sequential writes, so we can properly
1486  * account for the metadata space we'll need.
1487  */
1488 static void btrfs_merge_extent_hook(struct inode *inode,
1489                                     struct extent_state *new,
1490                                     struct extent_state *other)
1491 {
1492         /* not delalloc, ignore it */
1493         if (!(other->state & EXTENT_DELALLOC))
1494                 return;
1495
1496         spin_lock(&BTRFS_I(inode)->lock);
1497         BTRFS_I(inode)->outstanding_extents--;
1498         spin_unlock(&BTRFS_I(inode)->lock);
1499 }
1500
1501 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1502                                       struct inode *inode)
1503 {
1504         spin_lock(&root->delalloc_lock);
1505         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1506                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1507                               &root->delalloc_inodes);
1508                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1509                         &BTRFS_I(inode)->runtime_flags);
1510                 root->nr_delalloc_inodes++;
1511                 if (root->nr_delalloc_inodes == 1) {
1512                         spin_lock(&root->fs_info->delalloc_root_lock);
1513                         BUG_ON(!list_empty(&root->delalloc_root));
1514                         list_add_tail(&root->delalloc_root,
1515                                       &root->fs_info->delalloc_roots);
1516                         spin_unlock(&root->fs_info->delalloc_root_lock);
1517                 }
1518         }
1519         spin_unlock(&root->delalloc_lock);
1520 }
1521
1522 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1523                                      struct inode *inode)
1524 {
1525         spin_lock(&root->delalloc_lock);
1526         if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1527                 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1528                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1529                           &BTRFS_I(inode)->runtime_flags);
1530                 root->nr_delalloc_inodes--;
1531                 if (!root->nr_delalloc_inodes) {
1532                         spin_lock(&root->fs_info->delalloc_root_lock);
1533                         BUG_ON(list_empty(&root->delalloc_root));
1534                         list_del_init(&root->delalloc_root);
1535                         spin_unlock(&root->fs_info->delalloc_root_lock);
1536                 }
1537         }
1538         spin_unlock(&root->delalloc_lock);
1539 }
1540
1541 /*
1542  * extent_io.c set_bit_hook, used to track delayed allocation
1543  * bytes in this file, and to maintain the list of inodes that
1544  * have pending delalloc work to be done.
1545  */
1546 static void btrfs_set_bit_hook(struct inode *inode,
1547                                struct extent_state *state, unsigned long *bits)
1548 {
1549
1550         /*
1551          * set_bit and clear bit hooks normally require _irqsave/restore
1552          * but in this case, we are only testing for the DELALLOC
1553          * bit, which is only set or cleared with irqs on
1554          */
1555         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1556                 struct btrfs_root *root = BTRFS_I(inode)->root;
1557                 u64 len = state->end + 1 - state->start;
1558                 bool do_list = !btrfs_is_free_space_inode(inode);
1559
1560                 if (*bits & EXTENT_FIRST_DELALLOC) {
1561                         *bits &= ~EXTENT_FIRST_DELALLOC;
1562                 } else {
1563                         spin_lock(&BTRFS_I(inode)->lock);
1564                         BTRFS_I(inode)->outstanding_extents++;
1565                         spin_unlock(&BTRFS_I(inode)->lock);
1566                 }
1567
1568                 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1569                                      root->fs_info->delalloc_batch);
1570                 spin_lock(&BTRFS_I(inode)->lock);
1571                 BTRFS_I(inode)->delalloc_bytes += len;
1572                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1573                                          &BTRFS_I(inode)->runtime_flags))
1574                         btrfs_add_delalloc_inodes(root, inode);
1575                 spin_unlock(&BTRFS_I(inode)->lock);
1576         }
1577 }
1578
1579 /*
1580  * extent_io.c clear_bit_hook, see set_bit_hook for why
1581  */
1582 static void btrfs_clear_bit_hook(struct inode *inode,
1583                                  struct extent_state *state,
1584                                  unsigned long *bits)
1585 {
1586         /*
1587          * set_bit and clear bit hooks normally require _irqsave/restore
1588          * but in this case, we are only testing for the DELALLOC
1589          * bit, which is only set or cleared with irqs on
1590          */
1591         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1592                 struct btrfs_root *root = BTRFS_I(inode)->root;
1593                 u64 len = state->end + 1 - state->start;
1594                 bool do_list = !btrfs_is_free_space_inode(inode);
1595
1596                 if (*bits & EXTENT_FIRST_DELALLOC) {
1597                         *bits &= ~EXTENT_FIRST_DELALLOC;
1598                 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1599                         spin_lock(&BTRFS_I(inode)->lock);
1600                         BTRFS_I(inode)->outstanding_extents--;
1601                         spin_unlock(&BTRFS_I(inode)->lock);
1602                 }
1603
1604                 /*
1605                  * We don't reserve metadata space for space cache inodes so we
1606                  * don't need to call dellalloc_release_metadata if there is an
1607                  * error.
1608                  */
1609                 if (*bits & EXTENT_DO_ACCOUNTING &&
1610                     root != root->fs_info->tree_root)
1611                         btrfs_delalloc_release_metadata(inode, len);
1612
1613                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1614                     && do_list && !(state->state & EXTENT_NORESERVE))
1615                         btrfs_free_reserved_data_space(inode, len);
1616
1617                 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1618                                      root->fs_info->delalloc_batch);
1619                 spin_lock(&BTRFS_I(inode)->lock);
1620                 BTRFS_I(inode)->delalloc_bytes -= len;
1621                 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1622                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1623                              &BTRFS_I(inode)->runtime_flags))
1624                         btrfs_del_delalloc_inode(root, inode);
1625                 spin_unlock(&BTRFS_I(inode)->lock);
1626         }
1627 }
1628
1629 /*
1630  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1631  * we don't create bios that span stripes or chunks
1632  */
1633 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1634                          size_t size, struct bio *bio,
1635                          unsigned long bio_flags)
1636 {
1637         struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1638         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1639         u64 length = 0;
1640         u64 map_length;
1641         int ret;
1642
1643         if (bio_flags & EXTENT_BIO_COMPRESSED)
1644                 return 0;
1645
1646         length = bio->bi_iter.bi_size;
1647         map_length = length;
1648         ret = btrfs_map_block(root->fs_info, rw, logical,
1649                               &map_length, NULL, 0);
1650         /* Will always return 0 with map_multi == NULL */
1651         BUG_ON(ret < 0);
1652         if (map_length < length + size)
1653                 return 1;
1654         return 0;
1655 }
1656
1657 /*
1658  * in order to insert checksums into the metadata in large chunks,
1659  * we wait until bio submission time.   All the pages in the bio are
1660  * checksummed and sums are attached onto the ordered extent record.
1661  *
1662  * At IO completion time the cums attached on the ordered extent record
1663  * are inserted into the btree
1664  */
1665 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1666                                     struct bio *bio, int mirror_num,
1667                                     unsigned long bio_flags,
1668                                     u64 bio_offset)
1669 {
1670         struct btrfs_root *root = BTRFS_I(inode)->root;
1671         int ret = 0;
1672
1673         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1674         BUG_ON(ret); /* -ENOMEM */
1675         return 0;
1676 }
1677
1678 /*
1679  * in order to insert checksums into the metadata in large chunks,
1680  * we wait until bio submission time.   All the pages in the bio are
1681  * checksummed and sums are attached onto the ordered extent record.
1682  *
1683  * At IO completion time the cums attached on the ordered extent record
1684  * are inserted into the btree
1685  */
1686 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1687                           int mirror_num, unsigned long bio_flags,
1688                           u64 bio_offset)
1689 {
1690         struct btrfs_root *root = BTRFS_I(inode)->root;
1691         int ret;
1692
1693         ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1694         if (ret)
1695                 bio_endio(bio, ret);
1696         return ret;
1697 }
1698
1699 /*
1700  * extent_io.c submission hook. This does the right thing for csum calculation
1701  * on write, or reading the csums from the tree before a read
1702  */
1703 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1704                           int mirror_num, unsigned long bio_flags,
1705                           u64 bio_offset)
1706 {
1707         struct btrfs_root *root = BTRFS_I(inode)->root;
1708         int ret = 0;
1709         int skip_sum;
1710         int metadata = 0;
1711         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1712
1713         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1714
1715         if (btrfs_is_free_space_inode(inode))
1716                 metadata = 2;
1717
1718         if (!(rw & REQ_WRITE)) {
1719                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1720                 if (ret)
1721                         goto out;
1722
1723                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1724                         ret = btrfs_submit_compressed_read(inode, bio,
1725                                                            mirror_num,
1726                                                            bio_flags);
1727                         goto out;
1728                 } else if (!skip_sum) {
1729                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1730                         if (ret)
1731                                 goto out;
1732                 }
1733                 goto mapit;
1734         } else if (async && !skip_sum) {
1735                 /* csum items have already been cloned */
1736                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1737                         goto mapit;
1738                 /* we're doing a write, do the async checksumming */
1739                 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1740                                    inode, rw, bio, mirror_num,
1741                                    bio_flags, bio_offset,
1742                                    __btrfs_submit_bio_start,
1743                                    __btrfs_submit_bio_done);
1744                 goto out;
1745         } else if (!skip_sum) {
1746                 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1747                 if (ret)
1748                         goto out;
1749         }
1750
1751 mapit:
1752         ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1753
1754 out:
1755         if (ret < 0)
1756                 bio_endio(bio, ret);
1757         return ret;
1758 }
1759
1760 /*
1761  * given a list of ordered sums record them in the inode.  This happens
1762  * at IO completion time based on sums calculated at bio submission time.
1763  */
1764 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1765                              struct inode *inode, u64 file_offset,
1766                              struct list_head *list)
1767 {
1768         struct btrfs_ordered_sum *sum;
1769
1770         list_for_each_entry(sum, list, list) {
1771                 trans->adding_csums = 1;
1772                 btrfs_csum_file_blocks(trans,
1773                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1774                 trans->adding_csums = 0;
1775         }
1776         return 0;
1777 }
1778
1779 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1780                               struct extent_state **cached_state)
1781 {
1782         WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1783         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1784                                    cached_state, GFP_NOFS);
1785 }
1786
1787 /* see btrfs_writepage_start_hook for details on why this is required */
1788 struct btrfs_writepage_fixup {
1789         struct page *page;
1790         struct btrfs_work work;
1791 };
1792
1793 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1794 {
1795         struct btrfs_writepage_fixup *fixup;
1796         struct btrfs_ordered_extent *ordered;
1797         struct extent_state *cached_state = NULL;
1798         struct page *page;
1799         struct inode *inode;
1800         u64 page_start;
1801         u64 page_end;
1802         int ret;
1803
1804         fixup = container_of(work, struct btrfs_writepage_fixup, work);
1805         page = fixup->page;
1806 again:
1807         lock_page(page);
1808         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1809                 ClearPageChecked(page);
1810                 goto out_page;
1811         }
1812
1813         inode = page->mapping->host;
1814         page_start = page_offset(page);
1815         page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1816
1817         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1818                          &cached_state);
1819
1820         /* already ordered? We're done */
1821         if (PagePrivate2(page))
1822                 goto out;
1823
1824         ordered = btrfs_lookup_ordered_extent(inode, page_start);
1825         if (ordered) {
1826                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1827                                      page_end, &cached_state, GFP_NOFS);
1828                 unlock_page(page);
1829                 btrfs_start_ordered_extent(inode, ordered, 1);
1830                 btrfs_put_ordered_extent(ordered);
1831                 goto again;
1832         }
1833
1834         ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1835         if (ret) {
1836                 mapping_set_error(page->mapping, ret);
1837                 end_extent_writepage(page, ret, page_start, page_end);
1838                 ClearPageChecked(page);
1839                 goto out;
1840          }
1841
1842         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1843         ClearPageChecked(page);
1844         set_page_dirty(page);
1845 out:
1846         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1847                              &cached_state, GFP_NOFS);
1848 out_page:
1849         unlock_page(page);
1850         page_cache_release(page);
1851         kfree(fixup);
1852 }
1853
1854 /*
1855  * There are a few paths in the higher layers of the kernel that directly
1856  * set the page dirty bit without asking the filesystem if it is a
1857  * good idea.  This causes problems because we want to make sure COW
1858  * properly happens and the data=ordered rules are followed.
1859  *
1860  * In our case any range that doesn't have the ORDERED bit set
1861  * hasn't been properly setup for IO.  We kick off an async process
1862  * to fix it up.  The async helper will wait for ordered extents, set
1863  * the delalloc bit and make it safe to write the page.
1864  */
1865 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1866 {
1867         struct inode *inode = page->mapping->host;
1868         struct btrfs_writepage_fixup *fixup;
1869         struct btrfs_root *root = BTRFS_I(inode)->root;
1870
1871         /* this page is properly in the ordered list */
1872         if (TestClearPagePrivate2(page))
1873                 return 0;
1874
1875         if (PageChecked(page))
1876                 return -EAGAIN;
1877
1878         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1879         if (!fixup)
1880                 return -EAGAIN;
1881
1882         SetPageChecked(page);
1883         page_cache_get(page);
1884         btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
1885         fixup->page = page;
1886         btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1887         return -EBUSY;
1888 }
1889
1890 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1891                                        struct inode *inode, u64 file_pos,
1892                                        u64 disk_bytenr, u64 disk_num_bytes,
1893                                        u64 num_bytes, u64 ram_bytes,
1894                                        u8 compression, u8 encryption,
1895                                        u16 other_encoding, int extent_type)
1896 {
1897         struct btrfs_root *root = BTRFS_I(inode)->root;
1898         struct btrfs_file_extent_item *fi;
1899         struct btrfs_path *path;
1900         struct extent_buffer *leaf;
1901         struct btrfs_key ins;
1902         int extent_inserted = 0;
1903         int ret;
1904
1905         path = btrfs_alloc_path();
1906         if (!path)
1907                 return -ENOMEM;
1908
1909         /*
1910          * we may be replacing one extent in the tree with another.
1911          * The new extent is pinned in the extent map, and we don't want
1912          * to drop it from the cache until it is completely in the btree.
1913          *
1914          * So, tell btrfs_drop_extents to leave this extent in the cache.
1915          * the caller is expected to unpin it and allow it to be merged
1916          * with the others.
1917          */
1918         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1919                                    file_pos + num_bytes, NULL, 0,
1920                                    1, sizeof(*fi), &extent_inserted);
1921         if (ret)
1922                 goto out;
1923
1924         if (!extent_inserted) {
1925                 ins.objectid = btrfs_ino(inode);
1926                 ins.offset = file_pos;
1927                 ins.type = BTRFS_EXTENT_DATA_KEY;
1928
1929                 path->leave_spinning = 1;
1930                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1931                                               sizeof(*fi));
1932                 if (ret)
1933                         goto out;
1934         }
1935         leaf = path->nodes[0];
1936         fi = btrfs_item_ptr(leaf, path->slots[0],
1937                             struct btrfs_file_extent_item);
1938         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1939         btrfs_set_file_extent_type(leaf, fi, extent_type);
1940         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1941         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1942         btrfs_set_file_extent_offset(leaf, fi, 0);
1943         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1944         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1945         btrfs_set_file_extent_compression(leaf, fi, compression);
1946         btrfs_set_file_extent_encryption(leaf, fi, encryption);
1947         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1948
1949         btrfs_mark_buffer_dirty(leaf);
1950         btrfs_release_path(path);
1951
1952         inode_add_bytes(inode, num_bytes);
1953
1954         ins.objectid = disk_bytenr;
1955         ins.offset = disk_num_bytes;
1956         ins.type = BTRFS_EXTENT_ITEM_KEY;
1957         ret = btrfs_alloc_reserved_file_extent(trans, root,
1958                                         root->root_key.objectid,
1959                                         btrfs_ino(inode), file_pos, &ins);
1960 out:
1961         btrfs_free_path(path);
1962
1963         return ret;
1964 }
1965
1966 /* snapshot-aware defrag */
1967 struct sa_defrag_extent_backref {
1968         struct rb_node node;
1969         struct old_sa_defrag_extent *old;
1970         u64 root_id;
1971         u64 inum;
1972         u64 file_pos;
1973         u64 extent_offset;
1974         u64 num_bytes;
1975         u64 generation;
1976 };
1977
1978 struct old_sa_defrag_extent {
1979         struct list_head list;
1980         struct new_sa_defrag_extent *new;
1981
1982         u64 extent_offset;
1983         u64 bytenr;
1984         u64 offset;
1985         u64 len;
1986         int count;
1987 };
1988
1989 struct new_sa_defrag_extent {
1990         struct rb_root root;
1991         struct list_head head;
1992         struct btrfs_path *path;
1993         struct inode *inode;
1994         u64 file_pos;
1995         u64 len;
1996         u64 bytenr;
1997         u64 disk_len;
1998         u8 compress_type;
1999 };
2000
2001 static int backref_comp(struct sa_defrag_extent_backref *b1,
2002                         struct sa_defrag_extent_backref *b2)
2003 {
2004         if (b1->root_id < b2->root_id)
2005                 return -1;
2006         else if (b1->root_id > b2->root_id)
2007                 return 1;
2008
2009         if (b1->inum < b2->inum)
2010                 return -1;
2011         else if (b1->inum > b2->inum)
2012                 return 1;
2013
2014         if (b1->file_pos < b2->file_pos)
2015                 return -1;
2016         else if (b1->file_pos > b2->file_pos)
2017                 return 1;
2018
2019         /*
2020          * [------------------------------] ===> (a range of space)
2021          *     |<--->|   |<---->| =============> (fs/file tree A)
2022          * |<---------------------------->| ===> (fs/file tree B)
2023          *
2024          * A range of space can refer to two file extents in one tree while
2025          * refer to only one file extent in another tree.
2026          *
2027          * So we may process a disk offset more than one time(two extents in A)
2028          * and locate at the same extent(one extent in B), then insert two same
2029          * backrefs(both refer to the extent in B).
2030          */
2031         return 0;
2032 }
2033
2034 static void backref_insert(struct rb_root *root,
2035                            struct sa_defrag_extent_backref *backref)
2036 {
2037         struct rb_node **p = &root->rb_node;
2038         struct rb_node *parent = NULL;
2039         struct sa_defrag_extent_backref *entry;
2040         int ret;
2041
2042         while (*p) {
2043                 parent = *p;
2044                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2045
2046                 ret = backref_comp(backref, entry);
2047                 if (ret < 0)
2048                         p = &(*p)->rb_left;
2049                 else
2050                         p = &(*p)->rb_right;
2051         }
2052
2053         rb_link_node(&backref->node, parent, p);
2054         rb_insert_color(&backref->node, root);
2055 }
2056
2057 /*
2058  * Note the backref might has changed, and in this case we just return 0.
2059  */
2060 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2061                                        void *ctx)
2062 {
2063         struct btrfs_file_extent_item *extent;
2064         struct btrfs_fs_info *fs_info;
2065         struct old_sa_defrag_extent *old = ctx;
2066         struct new_sa_defrag_extent *new = old->new;
2067         struct btrfs_path *path = new->path;
2068         struct btrfs_key key;
2069         struct btrfs_root *root;
2070         struct sa_defrag_extent_backref *backref;
2071         struct extent_buffer *leaf;
2072         struct inode *inode = new->inode;
2073         int slot;
2074         int ret;
2075         u64 extent_offset;
2076         u64 num_bytes;
2077
2078         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2079             inum == btrfs_ino(inode))
2080                 return 0;
2081
2082         key.objectid = root_id;
2083         key.type = BTRFS_ROOT_ITEM_KEY;
2084         key.offset = (u64)-1;
2085
2086         fs_info = BTRFS_I(inode)->root->fs_info;
2087         root = btrfs_read_fs_root_no_name(fs_info, &key);
2088         if (IS_ERR(root)) {
2089                 if (PTR_ERR(root) == -ENOENT)
2090                         return 0;
2091                 WARN_ON(1);
2092                 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2093                          inum, offset, root_id);
2094                 return PTR_ERR(root);
2095         }
2096
2097         key.objectid = inum;
2098         key.type = BTRFS_EXTENT_DATA_KEY;
2099         if (offset > (u64)-1 << 32)
2100                 key.offset = 0;
2101         else
2102                 key.offset = offset;
2103
2104         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2105         if (WARN_ON(ret < 0))
2106                 return ret;
2107         ret = 0;
2108
2109         while (1) {
2110                 cond_resched();
2111
2112                 leaf = path->nodes[0];
2113                 slot = path->slots[0];
2114
2115                 if (slot >= btrfs_header_nritems(leaf)) {
2116                         ret = btrfs_next_leaf(root, path);
2117                         if (ret < 0) {
2118                                 goto out;
2119                         } else if (ret > 0) {
2120                                 ret = 0;
2121                                 goto out;
2122                         }
2123                         continue;
2124                 }
2125
2126                 path->slots[0]++;
2127
2128                 btrfs_item_key_to_cpu(leaf, &key, slot);
2129
2130                 if (key.objectid > inum)
2131                         goto out;
2132
2133                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2134                         continue;
2135
2136                 extent = btrfs_item_ptr(leaf, slot,
2137                                         struct btrfs_file_extent_item);
2138
2139                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2140                         continue;
2141
2142                 /*
2143                  * 'offset' refers to the exact key.offset,
2144                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2145                  * (key.offset - extent_offset).
2146                  */
2147                 if (key.offset != offset)
2148                         continue;
2149
2150                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2151                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2152
2153                 if (extent_offset >= old->extent_offset + old->offset +
2154                     old->len || extent_offset + num_bytes <=
2155                     old->extent_offset + old->offset)
2156                         continue;
2157                 break;
2158         }
2159
2160         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2161         if (!backref) {
2162                 ret = -ENOENT;
2163                 goto out;
2164         }
2165
2166         backref->root_id = root_id;
2167         backref->inum = inum;
2168         backref->file_pos = offset;
2169         backref->num_bytes = num_bytes;
2170         backref->extent_offset = extent_offset;
2171         backref->generation = btrfs_file_extent_generation(leaf, extent);
2172         backref->old = old;
2173         backref_insert(&new->root, backref);
2174         old->count++;
2175 out:
2176         btrfs_release_path(path);
2177         WARN_ON(ret);
2178         return ret;
2179 }
2180
2181 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2182                                    struct new_sa_defrag_extent *new)
2183 {
2184         struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2185         struct old_sa_defrag_extent *old, *tmp;
2186         int ret;
2187
2188         new->path = path;
2189
2190         list_for_each_entry_safe(old, tmp, &new->head, list) {
2191                 ret = iterate_inodes_from_logical(old->bytenr +
2192                                                   old->extent_offset, fs_info,
2193                                                   path, record_one_backref,
2194                                                   old);
2195                 if (ret < 0 && ret != -ENOENT)
2196                         return false;
2197
2198                 /* no backref to be processed for this extent */
2199                 if (!old->count) {
2200                         list_del(&old->list);
2201                         kfree(old);
2202                 }
2203         }
2204
2205         if (list_empty(&new->head))
2206                 return false;
2207
2208         return true;
2209 }
2210
2211 static int relink_is_mergable(struct extent_buffer *leaf,
2212                               struct btrfs_file_extent_item *fi,
2213                               struct new_sa_defrag_extent *new)
2214 {
2215         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2216                 return 0;
2217
2218         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2219                 return 0;
2220
2221         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2222                 return 0;
2223
2224         if (btrfs_file_extent_encryption(leaf, fi) ||
2225             btrfs_file_extent_other_encoding(leaf, fi))
2226                 return 0;
2227
2228         return 1;
2229 }
2230
2231 /*
2232  * Note the backref might has changed, and in this case we just return 0.
2233  */
2234 static noinline int relink_extent_backref(struct btrfs_path *path,
2235                                  struct sa_defrag_extent_backref *prev,
2236                                  struct sa_defrag_extent_backref *backref)
2237 {
2238         struct btrfs_file_extent_item *extent;
2239         struct btrfs_file_extent_item *item;
2240         struct btrfs_ordered_extent *ordered;
2241         struct btrfs_trans_handle *trans;
2242         struct btrfs_fs_info *fs_info;
2243         struct btrfs_root *root;
2244         struct btrfs_key key;
2245         struct extent_buffer *leaf;
2246         struct old_sa_defrag_extent *old = backref->old;
2247         struct new_sa_defrag_extent *new = old->new;
2248         struct inode *src_inode = new->inode;
2249         struct inode *inode;
2250         struct extent_state *cached = NULL;
2251         int ret = 0;
2252         u64 start;
2253         u64 len;
2254         u64 lock_start;
2255         u64 lock_end;
2256         bool merge = false;
2257         int index;
2258
2259         if (prev && prev->root_id == backref->root_id &&
2260             prev->inum == backref->inum &&
2261             prev->file_pos + prev->num_bytes == backref->file_pos)
2262                 merge = true;
2263
2264         /* step 1: get root */
2265         key.objectid = backref->root_id;
2266         key.type = BTRFS_ROOT_ITEM_KEY;
2267         key.offset = (u64)-1;
2268
2269         fs_info = BTRFS_I(src_inode)->root->fs_info;
2270         index = srcu_read_lock(&fs_info->subvol_srcu);
2271
2272         root = btrfs_read_fs_root_no_name(fs_info, &key);
2273         if (IS_ERR(root)) {
2274                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2275                 if (PTR_ERR(root) == -ENOENT)
2276                         return 0;
2277                 return PTR_ERR(root);
2278         }
2279
2280         if (btrfs_root_readonly(root)) {
2281                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2282                 return 0;
2283         }
2284
2285         /* step 2: get inode */
2286         key.objectid = backref->inum;
2287         key.type = BTRFS_INODE_ITEM_KEY;
2288         key.offset = 0;
2289
2290         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2291         if (IS_ERR(inode)) {
2292                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2293                 return 0;
2294         }
2295
2296         srcu_read_unlock(&fs_info->subvol_srcu, index);
2297
2298         /* step 3: relink backref */
2299         lock_start = backref->file_pos;
2300         lock_end = backref->file_pos + backref->num_bytes - 1;
2301         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2302                          0, &cached);
2303
2304         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2305         if (ordered) {
2306                 btrfs_put_ordered_extent(ordered);
2307                 goto out_unlock;
2308         }
2309
2310         trans = btrfs_join_transaction(root);
2311         if (IS_ERR(trans)) {
2312                 ret = PTR_ERR(trans);
2313                 goto out_unlock;
2314         }
2315
2316         key.objectid = backref->inum;
2317         key.type = BTRFS_EXTENT_DATA_KEY;
2318         key.offset = backref->file_pos;
2319
2320         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2321         if (ret < 0) {
2322                 goto out_free_path;
2323         } else if (ret > 0) {
2324                 ret = 0;
2325                 goto out_free_path;
2326         }
2327
2328         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2329                                 struct btrfs_file_extent_item);
2330
2331         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2332             backref->generation)
2333                 goto out_free_path;
2334
2335         btrfs_release_path(path);
2336
2337         start = backref->file_pos;
2338         if (backref->extent_offset < old->extent_offset + old->offset)
2339                 start += old->extent_offset + old->offset -
2340                          backref->extent_offset;
2341
2342         len = min(backref->extent_offset + backref->num_bytes,
2343                   old->extent_offset + old->offset + old->len);
2344         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2345
2346         ret = btrfs_drop_extents(trans, root, inode, start,
2347                                  start + len, 1);
2348         if (ret)
2349                 goto out_free_path;
2350 again:
2351         key.objectid = btrfs_ino(inode);
2352         key.type = BTRFS_EXTENT_DATA_KEY;
2353         key.offset = start;
2354
2355         path->leave_spinning = 1;
2356         if (merge) {
2357                 struct btrfs_file_extent_item *fi;
2358                 u64 extent_len;
2359                 struct btrfs_key found_key;
2360
2361                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2362                 if (ret < 0)
2363                         goto out_free_path;
2364
2365                 path->slots[0]--;
2366                 leaf = path->nodes[0];
2367                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2368
2369                 fi = btrfs_item_ptr(leaf, path->slots[0],
2370                                     struct btrfs_file_extent_item);
2371                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2372
2373                 if (extent_len + found_key.offset == start &&
2374                     relink_is_mergable(leaf, fi, new)) {
2375                         btrfs_set_file_extent_num_bytes(leaf, fi,
2376                                                         extent_len + len);
2377                         btrfs_mark_buffer_dirty(leaf);
2378                         inode_add_bytes(inode, len);
2379
2380                         ret = 1;
2381                         goto out_free_path;
2382                 } else {
2383                         merge = false;
2384                         btrfs_release_path(path);
2385                         goto again;
2386                 }
2387         }
2388
2389         ret = btrfs_insert_empty_item(trans, root, path, &key,
2390                                         sizeof(*extent));
2391         if (ret) {
2392                 btrfs_abort_transaction(trans, root, ret);
2393                 goto out_free_path;
2394         }
2395
2396         leaf = path->nodes[0];
2397         item = btrfs_item_ptr(leaf, path->slots[0],
2398                                 struct btrfs_file_extent_item);
2399         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2400         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2401         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2402         btrfs_set_file_extent_num_bytes(leaf, item, len);
2403         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2404         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2405         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2406         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2407         btrfs_set_file_extent_encryption(leaf, item, 0);
2408         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2409
2410         btrfs_mark_buffer_dirty(leaf);
2411         inode_add_bytes(inode, len);
2412         btrfs_release_path(path);
2413
2414         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2415                         new->disk_len, 0,
2416                         backref->root_id, backref->inum,
2417                         new->file_pos, 0);      /* start - extent_offset */
2418         if (ret) {
2419                 btrfs_abort_transaction(trans, root, ret);
2420                 goto out_free_path;
2421         }
2422
2423         ret = 1;
2424 out_free_path:
2425         btrfs_release_path(path);
2426         path->leave_spinning = 0;
2427         btrfs_end_transaction(trans, root);
2428 out_unlock:
2429         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2430                              &cached, GFP_NOFS);
2431         iput(inode);
2432         return ret;
2433 }
2434
2435 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2436 {
2437         struct old_sa_defrag_extent *old, *tmp;
2438
2439         if (!new)
2440                 return;
2441
2442         list_for_each_entry_safe(old, tmp, &new->head, list) {
2443                 list_del(&old->list);
2444                 kfree(old);
2445         }
2446         kfree(new);
2447 }
2448
2449 static void relink_file_extents(struct new_sa_defrag_extent *new)
2450 {
2451         struct btrfs_path *path;
2452         struct sa_defrag_extent_backref *backref;
2453         struct sa_defrag_extent_backref *prev = NULL;
2454         struct inode *inode;
2455         struct btrfs_root *root;
2456         struct rb_node *node;
2457         int ret;
2458
2459         inode = new->inode;
2460         root = BTRFS_I(inode)->root;
2461
2462         path = btrfs_alloc_path();
2463         if (!path)
2464                 return;
2465
2466         if (!record_extent_backrefs(path, new)) {
2467                 btrfs_free_path(path);
2468                 goto out;
2469         }
2470         btrfs_release_path(path);
2471
2472         while (1) {
2473                 node = rb_first(&new->root);
2474                 if (!node)
2475                         break;
2476                 rb_erase(node, &new->root);
2477
2478                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2479
2480                 ret = relink_extent_backref(path, prev, backref);
2481                 WARN_ON(ret < 0);
2482
2483                 kfree(prev);
2484
2485                 if (ret == 1)
2486                         prev = backref;
2487                 else
2488                         prev = NULL;
2489                 cond_resched();
2490         }
2491         kfree(prev);
2492
2493         btrfs_free_path(path);
2494 out:
2495         free_sa_defrag_extent(new);
2496
2497         atomic_dec(&root->fs_info->defrag_running);
2498         wake_up(&root->fs_info->transaction_wait);
2499 }
2500
2501 static struct new_sa_defrag_extent *
2502 record_old_file_extents(struct inode *inode,
2503                         struct btrfs_ordered_extent *ordered)
2504 {
2505         struct btrfs_root *root = BTRFS_I(inode)->root;
2506         struct btrfs_path *path;
2507         struct btrfs_key key;
2508         struct old_sa_defrag_extent *old;
2509         struct new_sa_defrag_extent *new;
2510         int ret;
2511
2512         new = kmalloc(sizeof(*new), GFP_NOFS);
2513         if (!new)
2514                 return NULL;
2515
2516         new->inode = inode;
2517         new->file_pos = ordered->file_offset;
2518         new->len = ordered->len;
2519         new->bytenr = ordered->start;
2520         new->disk_len = ordered->disk_len;
2521         new->compress_type = ordered->compress_type;
2522         new->root = RB_ROOT;
2523         INIT_LIST_HEAD(&new->head);
2524
2525         path = btrfs_alloc_path();
2526         if (!path)
2527                 goto out_kfree;
2528
2529         key.objectid = btrfs_ino(inode);
2530         key.type = BTRFS_EXTENT_DATA_KEY;
2531         key.offset = new->file_pos;
2532
2533         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2534         if (ret < 0)
2535                 goto out_free_path;
2536         if (ret > 0 && path->slots[0] > 0)
2537                 path->slots[0]--;
2538
2539         /* find out all the old extents for the file range */
2540         while (1) {
2541                 struct btrfs_file_extent_item *extent;
2542                 struct extent_buffer *l;
2543                 int slot;
2544                 u64 num_bytes;
2545                 u64 offset;
2546                 u64 end;
2547                 u64 disk_bytenr;
2548                 u64 extent_offset;
2549
2550                 l = path->nodes[0];
2551                 slot = path->slots[0];
2552
2553                 if (slot >= btrfs_header_nritems(l)) {
2554                         ret = btrfs_next_leaf(root, path);
2555                         if (ret < 0)
2556                                 goto out_free_path;
2557                         else if (ret > 0)
2558                                 break;
2559                         continue;
2560                 }
2561
2562                 btrfs_item_key_to_cpu(l, &key, slot);
2563
2564                 if (key.objectid != btrfs_ino(inode))
2565                         break;
2566                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2567                         break;
2568                 if (key.offset >= new->file_pos + new->len)
2569                         break;
2570
2571                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2572
2573                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2574                 if (key.offset + num_bytes < new->file_pos)
2575                         goto next;
2576
2577                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2578                 if (!disk_bytenr)
2579                         goto next;
2580
2581                 extent_offset = btrfs_file_extent_offset(l, extent);
2582
2583                 old = kmalloc(sizeof(*old), GFP_NOFS);
2584                 if (!old)
2585                         goto out_free_path;
2586
2587                 offset = max(new->file_pos, key.offset);
2588                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2589
2590                 old->bytenr = disk_bytenr;
2591                 old->extent_offset = extent_offset;
2592                 old->offset = offset - key.offset;
2593                 old->len = end - offset;
2594                 old->new = new;
2595                 old->count = 0;
2596                 list_add_tail(&old->list, &new->head);
2597 next:
2598                 path->slots[0]++;
2599                 cond_resched();
2600         }
2601
2602         btrfs_free_path(path);
2603         atomic_inc(&root->fs_info->defrag_running);
2604
2605         return new;
2606
2607 out_free_path:
2608         btrfs_free_path(path);
2609 out_kfree:
2610         free_sa_defrag_extent(new);
2611         return NULL;
2612 }
2613
2614 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2615                                          u64 start, u64 len)
2616 {
2617         struct btrfs_block_group_cache *cache;
2618
2619         cache = btrfs_lookup_block_group(root->fs_info, start);
2620         ASSERT(cache);
2621
2622         spin_lock(&cache->lock);
2623         cache->delalloc_bytes -= len;
2624         spin_unlock(&cache->lock);
2625
2626         btrfs_put_block_group(cache);
2627 }
2628
2629 /* as ordered data IO finishes, this gets called so we can finish
2630  * an ordered extent if the range of bytes in the file it covers are
2631  * fully written.
2632  */
2633 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2634 {
2635         struct inode *inode = ordered_extent->inode;
2636         struct btrfs_root *root = BTRFS_I(inode)->root;
2637         struct btrfs_trans_handle *trans = NULL;
2638         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2639         struct extent_state *cached_state = NULL;
2640         struct new_sa_defrag_extent *new = NULL;
2641         int compress_type = 0;
2642         int ret = 0;
2643         u64 logical_len = ordered_extent->len;
2644         bool nolock;
2645         bool truncated = false;
2646
2647         nolock = btrfs_is_free_space_inode(inode);
2648
2649         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2650                 ret = -EIO;
2651                 goto out;
2652         }
2653
2654         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2655                 truncated = true;
2656                 logical_len = ordered_extent->truncated_len;
2657                 /* Truncated the entire extent, don't bother adding */
2658                 if (!logical_len)
2659                         goto out;
2660         }
2661
2662         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2663                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2664                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2665                 if (nolock)
2666                         trans = btrfs_join_transaction_nolock(root);
2667                 else
2668                         trans = btrfs_join_transaction(root);
2669                 if (IS_ERR(trans)) {
2670                         ret = PTR_ERR(trans);
2671                         trans = NULL;
2672                         goto out;
2673                 }
2674                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2675                 ret = btrfs_update_inode_fallback(trans, root, inode);
2676                 if (ret) /* -ENOMEM or corruption */
2677                         btrfs_abort_transaction(trans, root, ret);
2678                 goto out;
2679         }
2680
2681         lock_extent_bits(io_tree, ordered_extent->file_offset,
2682                          ordered_extent->file_offset + ordered_extent->len - 1,
2683                          0, &cached_state);
2684
2685         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2686                         ordered_extent->file_offset + ordered_extent->len - 1,
2687                         EXTENT_DEFRAG, 1, cached_state);
2688         if (ret) {
2689                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2690                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2691                         /* the inode is shared */
2692                         new = record_old_file_extents(inode, ordered_extent);
2693
2694                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2695                         ordered_extent->file_offset + ordered_extent->len - 1,
2696                         EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2697         }
2698
2699         if (nolock)
2700                 trans = btrfs_join_transaction_nolock(root);
2701         else
2702                 trans = btrfs_join_transaction(root);
2703         if (IS_ERR(trans)) {
2704                 ret = PTR_ERR(trans);
2705                 trans = NULL;
2706                 goto out_unlock;
2707         }
2708
2709         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2710
2711         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2712                 compress_type = ordered_extent->compress_type;
2713         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2714                 BUG_ON(compress_type);
2715                 ret = btrfs_mark_extent_written(trans, inode,
2716                                                 ordered_extent->file_offset,
2717                                                 ordered_extent->file_offset +
2718                                                 logical_len);
2719         } else {
2720                 BUG_ON(root == root->fs_info->tree_root);
2721                 ret = insert_reserved_file_extent(trans, inode,
2722                                                 ordered_extent->file_offset,
2723                                                 ordered_extent->start,
2724                                                 ordered_extent->disk_len,
2725                                                 logical_len, logical_len,
2726                                                 compress_type, 0, 0,
2727                                                 BTRFS_FILE_EXTENT_REG);
2728                 if (!ret)
2729                         btrfs_release_delalloc_bytes(root,
2730                                                      ordered_extent->start,
2731                                                      ordered_extent->disk_len);
2732         }
2733         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2734                            ordered_extent->file_offset, ordered_extent->len,
2735                            trans->transid);
2736         if (ret < 0) {
2737                 btrfs_abort_transaction(trans, root, ret);
2738                 goto out_unlock;
2739         }
2740
2741         add_pending_csums(trans, inode, ordered_extent->file_offset,
2742                           &ordered_extent->list);
2743
2744         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2745         ret = btrfs_update_inode_fallback(trans, root, inode);
2746         if (ret) { /* -ENOMEM or corruption */
2747                 btrfs_abort_transaction(trans, root, ret);
2748                 goto out_unlock;
2749         }
2750         ret = 0;
2751 out_unlock:
2752         unlock_extent_cached(io_tree, ordered_extent->file_offset,
2753                              ordered_extent->file_offset +
2754                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
2755 out:
2756         if (root != root->fs_info->tree_root)
2757                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2758         if (trans)
2759                 btrfs_end_transaction(trans, root);
2760
2761         if (ret || truncated) {
2762                 u64 start, end;
2763
2764                 if (truncated)
2765                         start = ordered_extent->file_offset + logical_len;
2766                 else
2767                         start = ordered_extent->file_offset;
2768                 end = ordered_extent->file_offset + ordered_extent->len - 1;
2769                 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2770
2771                 /* Drop the cache for the part of the extent we didn't write. */
2772                 btrfs_drop_extent_cache(inode, start, end, 0);
2773
2774                 /*
2775                  * If the ordered extent had an IOERR or something else went
2776                  * wrong we need to return the space for this ordered extent
2777                  * back to the allocator.  We only free the extent in the
2778                  * truncated case if we didn't write out the extent at all.
2779                  */
2780                 if ((ret || !logical_len) &&
2781                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2782                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2783                         btrfs_free_reserved_extent(root, ordered_extent->start,
2784                                                    ordered_extent->disk_len, 1);
2785         }
2786
2787
2788         /*
2789          * This needs to be done to make sure anybody waiting knows we are done
2790          * updating everything for this ordered extent.
2791          */
2792         btrfs_remove_ordered_extent(inode, ordered_extent);
2793
2794         /* for snapshot-aware defrag */
2795         if (new) {
2796                 if (ret) {
2797                         free_sa_defrag_extent(new);
2798                         atomic_dec(&root->fs_info->defrag_running);
2799                 } else {
2800                         relink_file_extents(new);
2801                 }
2802         }
2803
2804         /* once for us */
2805         btrfs_put_ordered_extent(ordered_extent);
2806         /* once for the tree */
2807         btrfs_put_ordered_extent(ordered_extent);
2808
2809         return ret;
2810 }
2811
2812 static void finish_ordered_fn(struct btrfs_work *work)
2813 {
2814         struct btrfs_ordered_extent *ordered_extent;
2815         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2816         btrfs_finish_ordered_io(ordered_extent);
2817 }
2818
2819 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2820                                 struct extent_state *state, int uptodate)
2821 {
2822         struct inode *inode = page->mapping->host;
2823         struct btrfs_root *root = BTRFS_I(inode)->root;
2824         struct btrfs_ordered_extent *ordered_extent = NULL;
2825         struct btrfs_workqueue *workers;
2826
2827         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2828
2829         ClearPagePrivate2(page);
2830         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2831                                             end - start + 1, uptodate))
2832                 return 0;
2833
2834         btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2835
2836         if (btrfs_is_free_space_inode(inode))
2837                 workers = root->fs_info->endio_freespace_worker;
2838         else
2839                 workers = root->fs_info->endio_write_workers;
2840         btrfs_queue_work(workers, &ordered_extent->work);
2841
2842         return 0;
2843 }
2844
2845 /*
2846  * when reads are done, we need to check csums to verify the data is correct
2847  * if there's a match, we allow the bio to finish.  If not, the code in
2848  * extent_io.c will try to find good copies for us.
2849  */
2850 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2851                                       u64 phy_offset, struct page *page,
2852                                       u64 start, u64 end, int mirror)
2853 {
2854         size_t offset = start - page_offset(page);
2855         struct inode *inode = page->mapping->host;
2856         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2857         char *kaddr;
2858         struct btrfs_root *root = BTRFS_I(inode)->root;
2859         u32 csum_expected;
2860         u32 csum = ~(u32)0;
2861         static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2862                                       DEFAULT_RATELIMIT_BURST);
2863
2864         if (PageChecked(page)) {
2865                 ClearPageChecked(page);
2866                 goto good;
2867         }
2868
2869         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2870                 goto good;
2871
2872         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2873             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2874                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2875                                   GFP_NOFS);
2876                 return 0;
2877         }
2878
2879         phy_offset >>= inode->i_sb->s_blocksize_bits;
2880         csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2881
2882         kaddr = kmap_atomic(page);
2883         csum = btrfs_csum_data(kaddr + offset, csum,  end - start + 1);
2884         btrfs_csum_final(csum, (char *)&csum);
2885         if (csum != csum_expected)
2886                 goto zeroit;
2887
2888         kunmap_atomic(kaddr);
2889 good:
2890         return 0;
2891
2892 zeroit:
2893         if (__ratelimit(&_rs))
2894                 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2895                         btrfs_ino(page->mapping->host), start, csum, csum_expected);
2896         memset(kaddr + offset, 1, end - start + 1);
2897         flush_dcache_page(page);
2898         kunmap_atomic(kaddr);
2899         if (csum_expected == 0)
2900                 return 0;
2901         return -EIO;
2902 }
2903
2904 struct delayed_iput {
2905         struct list_head list;
2906         struct inode *inode;
2907 };
2908
2909 /* JDM: If this is fs-wide, why can't we add a pointer to
2910  * btrfs_inode instead and avoid the allocation? */
2911 void btrfs_add_delayed_iput(struct inode *inode)
2912 {
2913         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2914         struct delayed_iput *delayed;
2915
2916         if (atomic_add_unless(&inode->i_count, -1, 1))
2917                 return;
2918
2919         delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2920         delayed->inode = inode;
2921
2922         spin_lock(&fs_info->delayed_iput_lock);
2923         list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2924         spin_unlock(&fs_info->delayed_iput_lock);
2925 }
2926
2927 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2928 {
2929         LIST_HEAD(list);
2930         struct btrfs_fs_info *fs_info = root->fs_info;
2931         struct delayed_iput *delayed;
2932         int empty;
2933
2934         spin_lock(&fs_info->delayed_iput_lock);
2935         empty = list_empty(&fs_info->delayed_iputs);
2936         spin_unlock(&fs_info->delayed_iput_lock);
2937         if (empty)
2938                 return;
2939
2940         spin_lock(&fs_info->delayed_iput_lock);
2941         list_splice_init(&fs_info->delayed_iputs, &list);
2942         spin_unlock(&fs_info->delayed_iput_lock);
2943
2944         while (!list_empty(&list)) {
2945                 delayed = list_entry(list.next, struct delayed_iput, list);
2946                 list_del(&delayed->list);
2947                 iput(delayed->inode);
2948                 kfree(delayed);
2949         }
2950 }
2951
2952 /*
2953  * This is called in transaction commit time. If there are no orphan
2954  * files in the subvolume, it removes orphan item and frees block_rsv
2955  * structure.
2956  */
2957 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2958                               struct btrfs_root *root)
2959 {
2960         struct btrfs_block_rsv *block_rsv;
2961         int ret;
2962
2963         if (atomic_read(&root->orphan_inodes) ||
2964             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2965                 return;
2966
2967         spin_lock(&root->orphan_lock);
2968         if (atomic_read(&root->orphan_inodes)) {
2969                 spin_unlock(&root->orphan_lock);
2970                 return;
2971         }
2972
2973         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2974                 spin_unlock(&root->orphan_lock);
2975                 return;
2976         }
2977
2978         block_rsv = root->orphan_block_rsv;
2979         root->orphan_block_rsv = NULL;
2980         spin_unlock(&root->orphan_lock);
2981
2982         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
2983             btrfs_root_refs(&root->root_item) > 0) {
2984                 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2985                                             root->root_key.objectid);
2986                 if (ret)
2987                         btrfs_abort_transaction(trans, root, ret);
2988                 else
2989                         clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
2990                                   &root->state);
2991         }
2992
2993         if (block_rsv) {
2994                 WARN_ON(block_rsv->size > 0);
2995                 btrfs_free_block_rsv(root, block_rsv);
2996         }
2997 }
2998
2999 /*
3000  * This creates an orphan entry for the given inode in case something goes
3001  * wrong in the middle of an unlink/truncate.
3002  *
3003  * NOTE: caller of this function should reserve 5 units of metadata for
3004  *       this function.
3005  */
3006 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3007 {
3008         struct btrfs_root *root = BTRFS_I(inode)->root;
3009         struct btrfs_block_rsv *block_rsv = NULL;
3010         int reserve = 0;
3011         int insert = 0;
3012         int ret;
3013
3014         if (!root->orphan_block_rsv) {
3015                 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3016                 if (!block_rsv)
3017                         return -ENOMEM;
3018         }
3019
3020         spin_lock(&root->orphan_lock);
3021         if (!root->orphan_block_rsv) {
3022                 root->orphan_block_rsv = block_rsv;
3023         } else if (block_rsv) {
3024                 btrfs_free_block_rsv(root, block_rsv);
3025                 block_rsv = NULL;
3026         }
3027
3028         if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3029                               &BTRFS_I(inode)->runtime_flags)) {
3030 #if 0
3031                 /*
3032                  * For proper ENOSPC handling, we should do orphan
3033                  * cleanup when mounting. But this introduces backward
3034                  * compatibility issue.
3035                  */
3036                 if (!xchg(&root->orphan_item_inserted, 1))
3037                         insert = 2;
3038                 else
3039                         insert = 1;
3040 #endif
3041                 insert = 1;
3042                 atomic_inc(&root->orphan_inodes);
3043         }
3044
3045         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3046                               &BTRFS_I(inode)->runtime_flags))
3047                 reserve = 1;
3048         spin_unlock(&root->orphan_lock);
3049
3050         /* grab metadata reservation from transaction handle */
3051         if (reserve) {
3052                 ret = btrfs_orphan_reserve_metadata(trans, inode);
3053                 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3054         }
3055
3056         /* insert an orphan item to track this unlinked/truncated file */
3057         if (insert >= 1) {
3058                 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3059                 if (ret) {
3060                         atomic_dec(&root->orphan_inodes);
3061                         if (reserve) {
3062                                 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3063                                           &BTRFS_I(inode)->runtime_flags);
3064                                 btrfs_orphan_release_metadata(inode);
3065                         }
3066                         if (ret != -EEXIST) {
3067                                 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3068                                           &BTRFS_I(inode)->runtime_flags);
3069                                 btrfs_abort_transaction(trans, root, ret);
3070                                 return ret;
3071                         }
3072                 }
3073                 ret = 0;
3074         }
3075
3076         /* insert an orphan item to track subvolume contains orphan files */
3077         if (insert >= 2) {
3078                 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3079                                                root->root_key.objectid);
3080                 if (ret && ret != -EEXIST) {
3081                         btrfs_abort_transaction(trans, root, ret);
3082                         return ret;
3083                 }
3084         }
3085         return 0;
3086 }
3087
3088 /*
3089  * We have done the truncate/delete so we can go ahead and remove the orphan
3090  * item for this particular inode.
3091  */
3092 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3093                             struct inode *inode)
3094 {
3095         struct btrfs_root *root = BTRFS_I(inode)->root;
3096         int delete_item = 0;
3097         int release_rsv = 0;
3098         int ret = 0;
3099
3100         spin_lock(&root->orphan_lock);
3101         if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3102                                &BTRFS_I(inode)->runtime_flags))
3103                 delete_item = 1;
3104
3105         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3106                                &BTRFS_I(inode)->runtime_flags))
3107                 release_rsv = 1;
3108         spin_unlock(&root->orphan_lock);
3109
3110         if (delete_item) {
3111                 atomic_dec(&root->orphan_inodes);
3112                 if (trans)
3113                         ret = btrfs_del_orphan_item(trans, root,
3114                                                     btrfs_ino(inode));
3115         }
3116
3117         if (release_rsv)
3118                 btrfs_orphan_release_metadata(inode);
3119
3120         return ret;
3121 }
3122
3123 /*
3124  * this cleans up any orphans that may be left on the list from the last use
3125  * of this root.
3126  */
3127 int btrfs_orphan_cleanup(struct btrfs_root *root)
3128 {
3129         struct btrfs_path *path;
3130         struct extent_buffer *leaf;
3131         struct btrfs_key key, found_key;
3132         struct btrfs_trans_handle *trans;
3133         struct inode *inode;
3134         u64 last_objectid = 0;
3135         int ret = 0, nr_unlink = 0, nr_truncate = 0;
3136
3137         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3138                 return 0;
3139
3140         path = btrfs_alloc_path();
3141         if (!path) {
3142                 ret = -ENOMEM;
3143                 goto out;
3144         }
3145         path->reada = -1;
3146
3147         key.objectid = BTRFS_ORPHAN_OBJECTID;
3148         btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3149         key.offset = (u64)-1;
3150
3151         while (1) {
3152                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3153                 if (ret < 0)
3154                         goto out;
3155
3156                 /*
3157                  * if ret == 0 means we found what we were searching for, which
3158                  * is weird, but possible, so only screw with path if we didn't
3159                  * find the key and see if we have stuff that matches
3160                  */
3161                 if (ret > 0) {
3162                         ret = 0;
3163                         if (path->slots[0] == 0)
3164                                 break;
3165                         path->slots[0]--;
3166                 }
3167
3168                 /* pull out the item */
3169                 leaf = path->nodes[0];
3170                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3171
3172                 /* make sure the item matches what we want */
3173                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3174                         break;
3175                 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3176                         break;
3177
3178                 /* release the path since we're done with it */
3179                 btrfs_release_path(path);
3180
3181                 /*
3182                  * this is where we are basically btrfs_lookup, without the
3183                  * crossing root thing.  we store the inode number in the
3184                  * offset of the orphan item.
3185                  */
3186
3187                 if (found_key.offset == last_objectid) {
3188                         btrfs_err(root->fs_info,
3189                                 "Error removing orphan entry, stopping orphan cleanup");
3190                         ret = -EINVAL;
3191                         goto out;
3192                 }
3193
3194                 last_objectid = found_key.offset;
3195
3196                 found_key.objectid = found_key.offset;
3197                 found_key.type = BTRFS_INODE_ITEM_KEY;
3198                 found_key.offset = 0;
3199                 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3200                 ret = PTR_ERR_OR_ZERO(inode);
3201                 if (ret && ret != -ESTALE)
3202                         goto out;
3203
3204                 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3205                         struct btrfs_root *dead_root;
3206                         struct btrfs_fs_info *fs_info = root->fs_info;
3207                         int is_dead_root = 0;
3208
3209                         /*
3210                          * this is an orphan in the tree root. Currently these
3211                          * could come from 2 sources:
3212                          *  a) a snapshot deletion in progress
3213                          *  b) a free space cache inode
3214                          * We need to distinguish those two, as the snapshot
3215                          * orphan must not get deleted.
3216                          * find_dead_roots already ran before us, so if this
3217                          * is a snapshot deletion, we should find the root
3218                          * in the dead_roots list
3219                          */
3220                         spin_lock(&fs_info->trans_lock);
3221                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3222                                             root_list) {
3223                                 if (dead_root->root_key.objectid ==
3224                                     found_key.objectid) {
3225                                         is_dead_root = 1;
3226                                         break;
3227                                 }
3228                         }
3229                         spin_unlock(&fs_info->trans_lock);
3230                         if (is_dead_root) {
3231                                 /* prevent this orphan from being found again */
3232                                 key.offset = found_key.objectid - 1;
3233                                 continue;
3234                         }
3235                 }
3236                 /*
3237                  * Inode is already gone but the orphan item is still there,
3238                  * kill the orphan item.
3239                  */
3240                 if (ret == -ESTALE) {
3241                         trans = btrfs_start_transaction(root, 1);
3242                         if (IS_ERR(trans)) {
3243                                 ret = PTR_ERR(trans);
3244                                 goto out;
3245                         }
3246                         btrfs_debug(root->fs_info, "auto deleting %Lu",
3247                                 found_key.objectid);
3248                         ret = btrfs_del_orphan_item(trans, root,
3249                                                     found_key.objectid);
3250                         btrfs_end_transaction(trans, root);
3251                         if (ret)
3252                                 goto out;
3253                         continue;