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