Merge branch 'for-4.14/block-postmerge' of git://git.kernel.dk/linux-block
[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_path_cachep;
90 struct kmem_cache *btrfs_free_space_cachep;
91
92 #define S_SHIFT 12
93 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
94         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
95         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
96         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
97         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
98         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
99         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
100         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
101 };
102
103 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
104 static int btrfs_truncate(struct inode *inode);
105 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
106 static noinline int cow_file_range(struct inode *inode,
107                                    struct page *locked_page,
108                                    u64 start, u64 end, u64 delalloc_end,
109                                    int *page_started, unsigned long *nr_written,
110                                    int unlock, struct btrfs_dedupe_hash *hash);
111 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
112                                        u64 orig_start, u64 block_start,
113                                        u64 block_len, u64 orig_block_len,
114                                        u64 ram_bytes, int compress_type,
115                                        int type);
116
117 static void __endio_write_update_ordered(struct inode *inode,
118                                          const u64 offset, const u64 bytes,
119                                          const bool uptodate);
120
121 /*
122  * Cleanup all submitted ordered extents in specified range to handle errors
123  * from the fill_dellaloc() callback.
124  *
125  * NOTE: caller must ensure that when an error happens, it can not call
126  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
127  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
128  * to be released, which we want to happen only when finishing the ordered
129  * extent (btrfs_finish_ordered_io()). Also note that the caller of the
130  * fill_delalloc() callback already does proper cleanup for the first page of
131  * the range, that is, it invokes the callback writepage_end_io_hook() for the
132  * range of the first page.
133  */
134 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
135                                                  const u64 offset,
136                                                  const u64 bytes)
137 {
138         return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139                                             bytes - PAGE_SIZE, false);
140 }
141
142 static int btrfs_dirty_inode(struct inode *inode);
143
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
146 {
147         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 }
149 #endif
150
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152                                      struct inode *inode,  struct inode *dir,
153                                      const struct qstr *qstr)
154 {
155         int err;
156
157         err = btrfs_init_acl(trans, inode, dir);
158         if (!err)
159                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
160         return err;
161 }
162
163 /*
164  * this does all the hard work for inserting an inline extent into
165  * the btree.  The caller should have done a btrfs_drop_extents so that
166  * no overlapping inline items exist in the btree
167  */
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169                                 struct btrfs_path *path, int extent_inserted,
170                                 struct btrfs_root *root, struct inode *inode,
171                                 u64 start, size_t size, size_t compressed_size,
172                                 int compress_type,
173                                 struct page **compressed_pages)
174 {
175         struct extent_buffer *leaf;
176         struct page *page = NULL;
177         char *kaddr;
178         unsigned long ptr;
179         struct btrfs_file_extent_item *ei;
180         int ret;
181         size_t cur_size = size;
182         unsigned long offset;
183
184         if (compressed_size && compressed_pages)
185                 cur_size = compressed_size;
186
187         inode_add_bytes(inode, size);
188
189         if (!extent_inserted) {
190                 struct btrfs_key key;
191                 size_t datasize;
192
193                 key.objectid = btrfs_ino(BTRFS_I(inode));
194                 key.offset = start;
195                 key.type = BTRFS_EXTENT_DATA_KEY;
196
197                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198                 path->leave_spinning = 1;
199                 ret = btrfs_insert_empty_item(trans, root, path, &key,
200                                               datasize);
201                 if (ret)
202                         goto fail;
203         }
204         leaf = path->nodes[0];
205         ei = btrfs_item_ptr(leaf, path->slots[0],
206                             struct btrfs_file_extent_item);
207         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209         btrfs_set_file_extent_encryption(leaf, ei, 0);
210         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212         ptr = btrfs_file_extent_inline_start(ei);
213
214         if (compress_type != BTRFS_COMPRESS_NONE) {
215                 struct page *cpage;
216                 int i = 0;
217                 while (compressed_size > 0) {
218                         cpage = compressed_pages[i];
219                         cur_size = min_t(unsigned long, compressed_size,
220                                        PAGE_SIZE);
221
222                         kaddr = kmap_atomic(cpage);
223                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
224                         kunmap_atomic(kaddr);
225
226                         i++;
227                         ptr += cur_size;
228                         compressed_size -= cur_size;
229                 }
230                 btrfs_set_file_extent_compression(leaf, ei,
231                                                   compress_type);
232         } else {
233                 page = find_get_page(inode->i_mapping,
234                                      start >> PAGE_SHIFT);
235                 btrfs_set_file_extent_compression(leaf, ei, 0);
236                 kaddr = kmap_atomic(page);
237                 offset = start & (PAGE_SIZE - 1);
238                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239                 kunmap_atomic(kaddr);
240                 put_page(page);
241         }
242         btrfs_mark_buffer_dirty(leaf);
243         btrfs_release_path(path);
244
245         /*
246          * we're an inline extent, so nobody can
247          * extend the file past i_size without locking
248          * a page we already have locked.
249          *
250          * We must do any isize and inode updates
251          * before we unlock the pages.  Otherwise we
252          * could end up racing with unlink.
253          */
254         BTRFS_I(inode)->disk_i_size = inode->i_size;
255         ret = btrfs_update_inode(trans, root, inode);
256
257 fail:
258         return ret;
259 }
260
261
262 /*
263  * conditionally insert an inline extent into the file.  This
264  * does the checks required to make sure the data is small enough
265  * to fit as an inline extent.
266  */
267 static noinline int cow_file_range_inline(struct btrfs_root *root,
268                                           struct inode *inode, u64 start,
269                                           u64 end, size_t compressed_size,
270                                           int compress_type,
271                                           struct page **compressed_pages)
272 {
273         struct btrfs_fs_info *fs_info = root->fs_info;
274         struct btrfs_trans_handle *trans;
275         u64 isize = i_size_read(inode);
276         u64 actual_end = min(end + 1, isize);
277         u64 inline_len = actual_end - start;
278         u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279         u64 data_len = inline_len;
280         int ret;
281         struct btrfs_path *path;
282         int extent_inserted = 0;
283         u32 extent_item_size;
284
285         if (compressed_size)
286                 data_len = compressed_size;
287
288         if (start > 0 ||
289             actual_end > fs_info->sectorsize ||
290             data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
291             (!compressed_size &&
292             (actual_end & (fs_info->sectorsize - 1)) == 0) ||
293             end + 1 < isize ||
294             data_len > fs_info->max_inline) {
295                 return 1;
296         }
297
298         path = btrfs_alloc_path();
299         if (!path)
300                 return -ENOMEM;
301
302         trans = btrfs_join_transaction(root);
303         if (IS_ERR(trans)) {
304                 btrfs_free_path(path);
305                 return PTR_ERR(trans);
306         }
307         trans->block_rsv = &fs_info->delalloc_block_rsv;
308
309         if (compressed_size && compressed_pages)
310                 extent_item_size = btrfs_file_extent_calc_inline_size(
311                    compressed_size);
312         else
313                 extent_item_size = btrfs_file_extent_calc_inline_size(
314                     inline_len);
315
316         ret = __btrfs_drop_extents(trans, root, inode, path,
317                                    start, aligned_end, NULL,
318                                    1, 1, extent_item_size, &extent_inserted);
319         if (ret) {
320                 btrfs_abort_transaction(trans, ret);
321                 goto out;
322         }
323
324         if (isize > actual_end)
325                 inline_len = min_t(u64, isize, actual_end);
326         ret = insert_inline_extent(trans, path, extent_inserted,
327                                    root, inode, start,
328                                    inline_len, compressed_size,
329                                    compress_type, compressed_pages);
330         if (ret && ret != -ENOSPC) {
331                 btrfs_abort_transaction(trans, ret);
332                 goto out;
333         } else if (ret == -ENOSPC) {
334                 ret = 1;
335                 goto out;
336         }
337
338         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339         btrfs_delalloc_release_metadata(BTRFS_I(inode), end + 1 - start);
340         btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
341 out:
342         /*
343          * Don't forget to free the reserved space, as for inlined extent
344          * it won't count as data extent, free them directly here.
345          * And at reserve time, it's always aligned to page size, so
346          * just free one page here.
347          */
348         btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
349         btrfs_free_path(path);
350         btrfs_end_transaction(trans);
351         return ret;
352 }
353
354 struct async_extent {
355         u64 start;
356         u64 ram_size;
357         u64 compressed_size;
358         struct page **pages;
359         unsigned long nr_pages;
360         int compress_type;
361         struct list_head list;
362 };
363
364 struct async_cow {
365         struct inode *inode;
366         struct btrfs_root *root;
367         struct page *locked_page;
368         u64 start;
369         u64 end;
370         struct list_head extents;
371         struct btrfs_work work;
372 };
373
374 static noinline int add_async_extent(struct async_cow *cow,
375                                      u64 start, u64 ram_size,
376                                      u64 compressed_size,
377                                      struct page **pages,
378                                      unsigned long nr_pages,
379                                      int compress_type)
380 {
381         struct async_extent *async_extent;
382
383         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384         BUG_ON(!async_extent); /* -ENOMEM */
385         async_extent->start = start;
386         async_extent->ram_size = ram_size;
387         async_extent->compressed_size = compressed_size;
388         async_extent->pages = pages;
389         async_extent->nr_pages = nr_pages;
390         async_extent->compress_type = compress_type;
391         list_add_tail(&async_extent->list, &cow->extents);
392         return 0;
393 }
394
395 static inline int inode_need_compress(struct inode *inode)
396 {
397         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
398
399         /* force compress */
400         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
401                 return 1;
402         /* bad compression ratios */
403         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
404                 return 0;
405         if (btrfs_test_opt(fs_info, COMPRESS) ||
406             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
407             BTRFS_I(inode)->force_compress)
408                 return 1;
409         return 0;
410 }
411
412 static inline void inode_should_defrag(struct btrfs_inode *inode,
413                 u64 start, u64 end, u64 num_bytes, u64 small_write)
414 {
415         /* If this is a small write inside eof, kick off a defrag */
416         if (num_bytes < small_write &&
417             (start > 0 || end + 1 < inode->disk_i_size))
418                 btrfs_add_inode_defrag(NULL, inode);
419 }
420
421 /*
422  * we create compressed extents in two phases.  The first
423  * phase compresses a range of pages that have already been
424  * locked (both pages and state bits are locked).
425  *
426  * This is done inside an ordered work queue, and the compression
427  * is spread across many cpus.  The actual IO submission is step
428  * two, and the ordered work queue takes care of making sure that
429  * happens in the same order things were put onto the queue by
430  * writepages and friends.
431  *
432  * If this code finds it can't get good compression, it puts an
433  * entry onto the work queue to write the uncompressed bytes.  This
434  * makes sure that both compressed inodes and uncompressed inodes
435  * are written in the same order that the flusher thread sent them
436  * down.
437  */
438 static noinline void compress_file_range(struct inode *inode,
439                                         struct page *locked_page,
440                                         u64 start, u64 end,
441                                         struct async_cow *async_cow,
442                                         int *num_added)
443 {
444         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
445         struct btrfs_root *root = BTRFS_I(inode)->root;
446         u64 num_bytes;
447         u64 blocksize = fs_info->sectorsize;
448         u64 actual_end;
449         u64 isize = i_size_read(inode);
450         int ret = 0;
451         struct page **pages = NULL;
452         unsigned long nr_pages;
453         unsigned long total_compressed = 0;
454         unsigned long total_in = 0;
455         int i;
456         int will_compress;
457         int compress_type = fs_info->compress_type;
458         int redirty = 0;
459
460         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
461                         SZ_16K);
462
463         actual_end = min_t(u64, isize, end + 1);
464 again:
465         will_compress = 0;
466         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
467         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
468         nr_pages = min_t(unsigned long, nr_pages,
469                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
470
471         /*
472          * we don't want to send crud past the end of i_size through
473          * compression, that's just a waste of CPU time.  So, if the
474          * end of the file is before the start of our current
475          * requested range of bytes, we bail out to the uncompressed
476          * cleanup code that can deal with all of this.
477          *
478          * It isn't really the fastest way to fix things, but this is a
479          * very uncommon corner.
480          */
481         if (actual_end <= start)
482                 goto cleanup_and_bail_uncompressed;
483
484         total_compressed = actual_end - start;
485
486         /*
487          * skip compression for a small file range(<=blocksize) that
488          * isn't an inline extent, since it doesn't save disk space at all.
489          */
490         if (total_compressed <= blocksize &&
491            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
492                 goto cleanup_and_bail_uncompressed;
493
494         total_compressed = min_t(unsigned long, total_compressed,
495                         BTRFS_MAX_UNCOMPRESSED);
496         num_bytes = ALIGN(end - start + 1, blocksize);
497         num_bytes = max(blocksize,  num_bytes);
498         total_in = 0;
499         ret = 0;
500
501         /*
502          * we do compression for mount -o compress and when the
503          * inode has not been flagged as nocompress.  This flag can
504          * change at any time if we discover bad compression ratios.
505          */
506         if (inode_need_compress(inode)) {
507                 WARN_ON(pages);
508                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
509                 if (!pages) {
510                         /* just bail out to the uncompressed code */
511                         goto cont;
512                 }
513
514                 if (BTRFS_I(inode)->force_compress)
515                         compress_type = BTRFS_I(inode)->force_compress;
516
517                 /*
518                  * we need to call clear_page_dirty_for_io on each
519                  * page in the range.  Otherwise applications with the file
520                  * mmap'd can wander in and change the page contents while
521                  * we are compressing them.
522                  *
523                  * If the compression fails for any reason, we set the pages
524                  * dirty again later on.
525                  */
526                 extent_range_clear_dirty_for_io(inode, start, end);
527                 redirty = 1;
528                 ret = btrfs_compress_pages(compress_type,
529                                            inode->i_mapping, start,
530                                            pages,
531                                            &nr_pages,
532                                            &total_in,
533                                            &total_compressed);
534
535                 if (!ret) {
536                         unsigned long offset = total_compressed &
537                                 (PAGE_SIZE - 1);
538                         struct page *page = pages[nr_pages - 1];
539                         char *kaddr;
540
541                         /* zero the tail end of the last page, we might be
542                          * sending it down to disk
543                          */
544                         if (offset) {
545                                 kaddr = kmap_atomic(page);
546                                 memset(kaddr + offset, 0,
547                                        PAGE_SIZE - offset);
548                                 kunmap_atomic(kaddr);
549                         }
550                         will_compress = 1;
551                 }
552         }
553 cont:
554         if (start == 0) {
555                 /* lets try to make an inline extent */
556                 if (ret || total_in < (actual_end - start)) {
557                         /* we didn't compress the entire range, try
558                          * to make an uncompressed inline extent.
559                          */
560                         ret = cow_file_range_inline(root, inode, start, end,
561                                             0, BTRFS_COMPRESS_NONE, NULL);
562                 } else {
563                         /* try making a compressed inline extent */
564                         ret = cow_file_range_inline(root, inode, start, end,
565                                                     total_compressed,
566                                                     compress_type, pages);
567                 }
568                 if (ret <= 0) {
569                         unsigned long clear_flags = EXTENT_DELALLOC |
570                                 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG;
571                         unsigned long page_error_op;
572
573                         clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
574                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
575
576                         /*
577                          * inline extent creation worked or returned error,
578                          * we don't need to create any more async work items.
579                          * Unlock and free up our temp pages.
580                          */
581                         extent_clear_unlock_delalloc(inode, start, end, end,
582                                                      NULL, clear_flags,
583                                                      PAGE_UNLOCK |
584                                                      PAGE_CLEAR_DIRTY |
585                                                      PAGE_SET_WRITEBACK |
586                                                      page_error_op |
587                                                      PAGE_END_WRITEBACK);
588                         if (ret == 0)
589                                 btrfs_free_reserved_data_space_noquota(inode,
590                                                                start,
591                                                                end - start + 1);
592                         goto free_pages_out;
593                 }
594         }
595
596         if (will_compress) {
597                 /*
598                  * we aren't doing an inline extent round the compressed size
599                  * up to a block size boundary so the allocator does sane
600                  * things
601                  */
602                 total_compressed = ALIGN(total_compressed, blocksize);
603
604                 /*
605                  * one last check to make sure the compression is really a
606                  * win, compare the page count read with the blocks on disk,
607                  * compression must free at least one sector size
608                  */
609                 total_in = ALIGN(total_in, PAGE_SIZE);
610                 if (total_compressed + blocksize <= total_in) {
611                         num_bytes = total_in;
612                         *num_added += 1;
613
614                         /*
615                          * The async work queues will take care of doing actual
616                          * allocation on disk for these compressed pages, and
617                          * will submit them to the elevator.
618                          */
619                         add_async_extent(async_cow, start, num_bytes,
620                                         total_compressed, pages, nr_pages,
621                                         compress_type);
622
623                         if (start + num_bytes < end) {
624                                 start += num_bytes;
625                                 pages = NULL;
626                                 cond_resched();
627                                 goto again;
628                         }
629                         return;
630                 }
631         }
632         if (pages) {
633                 /*
634                  * the compression code ran but failed to make things smaller,
635                  * free any pages it allocated and our page pointer array
636                  */
637                 for (i = 0; i < nr_pages; i++) {
638                         WARN_ON(pages[i]->mapping);
639                         put_page(pages[i]);
640                 }
641                 kfree(pages);
642                 pages = NULL;
643                 total_compressed = 0;
644                 nr_pages = 0;
645
646                 /* flag the file so we don't compress in the future */
647                 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
648                     !(BTRFS_I(inode)->force_compress)) {
649                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
650                 }
651         }
652 cleanup_and_bail_uncompressed:
653         /*
654          * No compression, but we still need to write the pages in the file
655          * we've been given so far.  redirty the locked page if it corresponds
656          * to our extent and set things up for the async work queue to run
657          * cow_file_range to do the normal delalloc dance.
658          */
659         if (page_offset(locked_page) >= start &&
660             page_offset(locked_page) <= end)
661                 __set_page_dirty_nobuffers(locked_page);
662                 /* unlocked later on in the async handlers */
663
664         if (redirty)
665                 extent_range_redirty_for_io(inode, start, end);
666         add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
667                          BTRFS_COMPRESS_NONE);
668         *num_added += 1;
669
670         return;
671
672 free_pages_out:
673         for (i = 0; i < nr_pages; i++) {
674                 WARN_ON(pages[i]->mapping);
675                 put_page(pages[i]);
676         }
677         kfree(pages);
678 }
679
680 static void free_async_extent_pages(struct async_extent *async_extent)
681 {
682         int i;
683
684         if (!async_extent->pages)
685                 return;
686
687         for (i = 0; i < async_extent->nr_pages; i++) {
688                 WARN_ON(async_extent->pages[i]->mapping);
689                 put_page(async_extent->pages[i]);
690         }
691         kfree(async_extent->pages);
692         async_extent->nr_pages = 0;
693         async_extent->pages = NULL;
694 }
695
696 /*
697  * phase two of compressed writeback.  This is the ordered portion
698  * of the code, which only gets called in the order the work was
699  * queued.  We walk all the async extents created by compress_file_range
700  * and send them down to the disk.
701  */
702 static noinline void submit_compressed_extents(struct inode *inode,
703                                               struct async_cow *async_cow)
704 {
705         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
706         struct async_extent *async_extent;
707         u64 alloc_hint = 0;
708         struct btrfs_key ins;
709         struct extent_map *em;
710         struct btrfs_root *root = BTRFS_I(inode)->root;
711         struct extent_io_tree *io_tree;
712         int ret = 0;
713
714 again:
715         while (!list_empty(&async_cow->extents)) {
716                 async_extent = list_entry(async_cow->extents.next,
717                                           struct async_extent, list);
718                 list_del(&async_extent->list);
719
720                 io_tree = &BTRFS_I(inode)->io_tree;
721
722 retry:
723                 /* did the compression code fall back to uncompressed IO? */
724                 if (!async_extent->pages) {
725                         int page_started = 0;
726                         unsigned long nr_written = 0;
727
728                         lock_extent(io_tree, async_extent->start,
729                                          async_extent->start +
730                                          async_extent->ram_size - 1);
731
732                         /* allocate blocks */
733                         ret = cow_file_range(inode, async_cow->locked_page,
734                                              async_extent->start,
735                                              async_extent->start +
736                                              async_extent->ram_size - 1,
737                                              async_extent->start +
738                                              async_extent->ram_size - 1,
739                                              &page_started, &nr_written, 0,
740                                              NULL);
741
742                         /* JDM XXX */
743
744                         /*
745                          * if page_started, cow_file_range inserted an
746                          * inline extent and took care of all the unlocking
747                          * and IO for us.  Otherwise, we need to submit
748                          * all those pages down to the drive.
749                          */
750                         if (!page_started && !ret)
751                                 extent_write_locked_range(io_tree,
752                                                   inode, async_extent->start,
753                                                   async_extent->start +
754                                                   async_extent->ram_size - 1,
755                                                   btrfs_get_extent,
756                                                   WB_SYNC_ALL);
757                         else if (ret)
758                                 unlock_page(async_cow->locked_page);
759                         kfree(async_extent);
760                         cond_resched();
761                         continue;
762                 }
763
764                 lock_extent(io_tree, async_extent->start,
765                             async_extent->start + async_extent->ram_size - 1);
766
767                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
768                                            async_extent->compressed_size,
769                                            async_extent->compressed_size,
770                                            0, alloc_hint, &ins, 1, 1);
771                 if (ret) {
772                         free_async_extent_pages(async_extent);
773
774                         if (ret == -ENOSPC) {
775                                 unlock_extent(io_tree, async_extent->start,
776                                               async_extent->start +
777                                               async_extent->ram_size - 1);
778
779                                 /*
780                                  * we need to redirty the pages if we decide to
781                                  * fallback to uncompressed IO, otherwise we
782                                  * will not submit these pages down to lower
783                                  * layers.
784                                  */
785                                 extent_range_redirty_for_io(inode,
786                                                 async_extent->start,
787                                                 async_extent->start +
788                                                 async_extent->ram_size - 1);
789
790                                 goto retry;
791                         }
792                         goto out_free;
793                 }
794                 /*
795                  * here we're doing allocation and writeback of the
796                  * compressed pages
797                  */
798                 em = create_io_em(inode, async_extent->start,
799                                   async_extent->ram_size, /* len */
800                                   async_extent->start, /* orig_start */
801                                   ins.objectid, /* block_start */
802                                   ins.offset, /* block_len */
803                                   ins.offset, /* orig_block_len */
804                                   async_extent->ram_size, /* ram_bytes */
805                                   async_extent->compress_type,
806                                   BTRFS_ORDERED_COMPRESSED);
807                 if (IS_ERR(em))
808                         /* ret value is not necessary due to void function */
809                         goto out_free_reserve;
810                 free_extent_map(em);
811
812                 ret = btrfs_add_ordered_extent_compress(inode,
813                                                 async_extent->start,
814                                                 ins.objectid,
815                                                 async_extent->ram_size,
816                                                 ins.offset,
817                                                 BTRFS_ORDERED_COMPRESSED,
818                                                 async_extent->compress_type);
819                 if (ret) {
820                         btrfs_drop_extent_cache(BTRFS_I(inode),
821                                                 async_extent->start,
822                                                 async_extent->start +
823                                                 async_extent->ram_size - 1, 0);
824                         goto out_free_reserve;
825                 }
826                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
827
828                 /*
829                  * clear dirty, set writeback and unlock the pages.
830                  */
831                 extent_clear_unlock_delalloc(inode, async_extent->start,
832                                 async_extent->start +
833                                 async_extent->ram_size - 1,
834                                 async_extent->start +
835                                 async_extent->ram_size - 1,
836                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
837                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
838                                 PAGE_SET_WRITEBACK);
839                 if (btrfs_submit_compressed_write(inode,
840                                     async_extent->start,
841                                     async_extent->ram_size,
842                                     ins.objectid,
843                                     ins.offset, async_extent->pages,
844                                     async_extent->nr_pages)) {
845                         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
846                         struct page *p = async_extent->pages[0];
847                         const u64 start = async_extent->start;
848                         const u64 end = start + async_extent->ram_size - 1;
849
850                         p->mapping = inode->i_mapping;
851                         tree->ops->writepage_end_io_hook(p, start, end,
852                                                          NULL, 0);
853                         p->mapping = NULL;
854                         extent_clear_unlock_delalloc(inode, start, end, end,
855                                                      NULL, 0,
856                                                      PAGE_END_WRITEBACK |
857                                                      PAGE_SET_ERROR);
858                         free_async_extent_pages(async_extent);
859                 }
860                 alloc_hint = ins.objectid + ins.offset;
861                 kfree(async_extent);
862                 cond_resched();
863         }
864         return;
865 out_free_reserve:
866         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
867         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
868 out_free:
869         extent_clear_unlock_delalloc(inode, async_extent->start,
870                                      async_extent->start +
871                                      async_extent->ram_size - 1,
872                                      async_extent->start +
873                                      async_extent->ram_size - 1,
874                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
875                                      EXTENT_DELALLOC_NEW |
876                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
877                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
878                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
879                                      PAGE_SET_ERROR);
880         free_async_extent_pages(async_extent);
881         kfree(async_extent);
882         goto again;
883 }
884
885 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
886                                       u64 num_bytes)
887 {
888         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
889         struct extent_map *em;
890         u64 alloc_hint = 0;
891
892         read_lock(&em_tree->lock);
893         em = search_extent_mapping(em_tree, start, num_bytes);
894         if (em) {
895                 /*
896                  * if block start isn't an actual block number then find the
897                  * first block in this inode and use that as a hint.  If that
898                  * block is also bogus then just don't worry about it.
899                  */
900                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
901                         free_extent_map(em);
902                         em = search_extent_mapping(em_tree, 0, 0);
903                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
904                                 alloc_hint = em->block_start;
905                         if (em)
906                                 free_extent_map(em);
907                 } else {
908                         alloc_hint = em->block_start;
909                         free_extent_map(em);
910                 }
911         }
912         read_unlock(&em_tree->lock);
913
914         return alloc_hint;
915 }
916
917 /*
918  * when extent_io.c finds a delayed allocation range in the file,
919  * the call backs end up in this code.  The basic idea is to
920  * allocate extents on disk for the range, and create ordered data structs
921  * in ram to track those extents.
922  *
923  * locked_page is the page that writepage had locked already.  We use
924  * it to make sure we don't do extra locks or unlocks.
925  *
926  * *page_started is set to one if we unlock locked_page and do everything
927  * required to start IO on it.  It may be clean and already done with
928  * IO when we return.
929  */
930 static noinline int cow_file_range(struct inode *inode,
931                                    struct page *locked_page,
932                                    u64 start, u64 end, u64 delalloc_end,
933                                    int *page_started, unsigned long *nr_written,
934                                    int unlock, struct btrfs_dedupe_hash *hash)
935 {
936         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
937         struct btrfs_root *root = BTRFS_I(inode)->root;
938         u64 alloc_hint = 0;
939         u64 num_bytes;
940         unsigned long ram_size;
941         u64 disk_num_bytes;
942         u64 cur_alloc_size = 0;
943         u64 blocksize = fs_info->sectorsize;
944         struct btrfs_key ins;
945         struct extent_map *em;
946         unsigned clear_bits;
947         unsigned long page_ops;
948         bool extent_reserved = false;
949         int ret = 0;
950
951         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
952                 WARN_ON_ONCE(1);
953                 ret = -EINVAL;
954                 goto out_unlock;
955         }
956
957         num_bytes = ALIGN(end - start + 1, blocksize);
958         num_bytes = max(blocksize,  num_bytes);
959         disk_num_bytes = num_bytes;
960
961         inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
962
963         if (start == 0) {
964                 /* lets try to make an inline extent */
965                 ret = cow_file_range_inline(root, inode, start, end, 0,
966                                         BTRFS_COMPRESS_NONE, NULL);
967                 if (ret == 0) {
968                         extent_clear_unlock_delalloc(inode, start, end,
969                                      delalloc_end, NULL,
970                                      EXTENT_LOCKED | EXTENT_DELALLOC |
971                                      EXTENT_DELALLOC_NEW |
972                                      EXTENT_DEFRAG, PAGE_UNLOCK |
973                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
974                                      PAGE_END_WRITEBACK);
975                         btrfs_free_reserved_data_space_noquota(inode, start,
976                                                 end - start + 1);
977                         *nr_written = *nr_written +
978                              (end - start + PAGE_SIZE) / PAGE_SIZE;
979                         *page_started = 1;
980                         goto out;
981                 } else if (ret < 0) {
982                         goto out_unlock;
983                 }
984         }
985
986         BUG_ON(disk_num_bytes >
987                btrfs_super_total_bytes(fs_info->super_copy));
988
989         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
990         btrfs_drop_extent_cache(BTRFS_I(inode), start,
991                         start + num_bytes - 1, 0);
992
993         while (disk_num_bytes > 0) {
994                 cur_alloc_size = disk_num_bytes;
995                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
996                                            fs_info->sectorsize, 0, alloc_hint,
997                                            &ins, 1, 1);
998                 if (ret < 0)
999                         goto out_unlock;
1000                 cur_alloc_size = ins.offset;
1001                 extent_reserved = true;
1002
1003                 ram_size = ins.offset;
1004                 em = create_io_em(inode, start, ins.offset, /* len */
1005                                   start, /* orig_start */
1006                                   ins.objectid, /* block_start */
1007                                   ins.offset, /* block_len */
1008                                   ins.offset, /* orig_block_len */
1009                                   ram_size, /* ram_bytes */
1010                                   BTRFS_COMPRESS_NONE, /* compress_type */
1011                                   BTRFS_ORDERED_REGULAR /* type */);
1012                 if (IS_ERR(em))
1013                         goto out_reserve;
1014                 free_extent_map(em);
1015
1016                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1017                                                ram_size, cur_alloc_size, 0);
1018                 if (ret)
1019                         goto out_drop_extent_cache;
1020
1021                 if (root->root_key.objectid ==
1022                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1023                         ret = btrfs_reloc_clone_csums(inode, start,
1024                                                       cur_alloc_size);
1025                         /*
1026                          * Only drop cache here, and process as normal.
1027                          *
1028                          * We must not allow extent_clear_unlock_delalloc()
1029                          * at out_unlock label to free meta of this ordered
1030                          * extent, as its meta should be freed by
1031                          * btrfs_finish_ordered_io().
1032                          *
1033                          * So we must continue until @start is increased to
1034                          * skip current ordered extent.
1035                          */
1036                         if (ret)
1037                                 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1038                                                 start + ram_size - 1, 0);
1039                 }
1040
1041                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1042
1043                 /* we're not doing compressed IO, don't unlock the first
1044                  * page (which the caller expects to stay locked), don't
1045                  * clear any dirty bits and don't set any writeback bits
1046                  *
1047                  * Do set the Private2 bit so we know this page was properly
1048                  * setup for writepage
1049                  */
1050                 page_ops = unlock ? PAGE_UNLOCK : 0;
1051                 page_ops |= PAGE_SET_PRIVATE2;
1052
1053                 extent_clear_unlock_delalloc(inode, start,
1054                                              start + ram_size - 1,
1055                                              delalloc_end, locked_page,
1056                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1057                                              page_ops);
1058                 if (disk_num_bytes < cur_alloc_size)
1059                         disk_num_bytes = 0;
1060                 else
1061                         disk_num_bytes -= cur_alloc_size;
1062                 num_bytes -= cur_alloc_size;
1063                 alloc_hint = ins.objectid + ins.offset;
1064                 start += cur_alloc_size;
1065                 extent_reserved = false;
1066
1067                 /*
1068                  * btrfs_reloc_clone_csums() error, since start is increased
1069                  * extent_clear_unlock_delalloc() at out_unlock label won't
1070                  * free metadata of current ordered extent, we're OK to exit.
1071                  */
1072                 if (ret)
1073                         goto out_unlock;
1074         }
1075 out:
1076         return ret;
1077
1078 out_drop_extent_cache:
1079         btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1080 out_reserve:
1081         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1082         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1083 out_unlock:
1084         clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1085                 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1086         page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1087                 PAGE_END_WRITEBACK;
1088         /*
1089          * If we reserved an extent for our delalloc range (or a subrange) and
1090          * failed to create the respective ordered extent, then it means that
1091          * when we reserved the extent we decremented the extent's size from
1092          * the data space_info's bytes_may_use counter and incremented the
1093          * space_info's bytes_reserved counter by the same amount. We must make
1094          * sure extent_clear_unlock_delalloc() does not try to decrement again
1095          * the data space_info's bytes_may_use counter, therefore we do not pass
1096          * it the flag EXTENT_CLEAR_DATA_RESV.
1097          */
1098         if (extent_reserved) {
1099                 extent_clear_unlock_delalloc(inode, start,
1100                                              start + cur_alloc_size,
1101                                              start + cur_alloc_size,
1102                                              locked_page,
1103                                              clear_bits,
1104                                              page_ops);
1105                 start += cur_alloc_size;
1106                 if (start >= end)
1107                         goto out;
1108         }
1109         extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1110                                      locked_page,
1111                                      clear_bits | EXTENT_CLEAR_DATA_RESV,
1112                                      page_ops);
1113         goto out;
1114 }
1115
1116 /*
1117  * work queue call back to started compression on a file and pages
1118  */
1119 static noinline void async_cow_start(struct btrfs_work *work)
1120 {
1121         struct async_cow *async_cow;
1122         int num_added = 0;
1123         async_cow = container_of(work, struct async_cow, work);
1124
1125         compress_file_range(async_cow->inode, async_cow->locked_page,
1126                             async_cow->start, async_cow->end, async_cow,
1127                             &num_added);
1128         if (num_added == 0) {
1129                 btrfs_add_delayed_iput(async_cow->inode);
1130                 async_cow->inode = NULL;
1131         }
1132 }
1133
1134 /*
1135  * work queue call back to submit previously compressed pages
1136  */
1137 static noinline void async_cow_submit(struct btrfs_work *work)
1138 {
1139         struct btrfs_fs_info *fs_info;
1140         struct async_cow *async_cow;
1141         struct btrfs_root *root;
1142         unsigned long nr_pages;
1143
1144         async_cow = container_of(work, struct async_cow, work);
1145
1146         root = async_cow->root;
1147         fs_info = root->fs_info;
1148         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1149                 PAGE_SHIFT;
1150
1151         /*
1152          * atomic_sub_return implies a barrier for waitqueue_active
1153          */
1154         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1155             5 * SZ_1M &&
1156             waitqueue_active(&fs_info->async_submit_wait))
1157                 wake_up(&fs_info->async_submit_wait);
1158
1159         if (async_cow->inode)
1160                 submit_compressed_extents(async_cow->inode, async_cow);
1161 }
1162
1163 static noinline void async_cow_free(struct btrfs_work *work)
1164 {
1165         struct async_cow *async_cow;
1166         async_cow = container_of(work, struct async_cow, work);
1167         if (async_cow->inode)
1168                 btrfs_add_delayed_iput(async_cow->inode);
1169         kfree(async_cow);
1170 }
1171
1172 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1173                                 u64 start, u64 end, int *page_started,
1174                                 unsigned long *nr_written)
1175 {
1176         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1177         struct async_cow *async_cow;
1178         struct btrfs_root *root = BTRFS_I(inode)->root;
1179         unsigned long nr_pages;
1180         u64 cur_end;
1181
1182         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1183                          1, 0, NULL, GFP_NOFS);
1184         while (start < end) {
1185                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1186                 BUG_ON(!async_cow); /* -ENOMEM */
1187                 async_cow->inode = igrab(inode);
1188                 async_cow->root = root;
1189                 async_cow->locked_page = locked_page;
1190                 async_cow->start = start;
1191
1192                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1193                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1194                         cur_end = end;
1195                 else
1196                         cur_end = min(end, start + SZ_512K - 1);
1197
1198                 async_cow->end = cur_end;
1199                 INIT_LIST_HEAD(&async_cow->extents);
1200
1201                 btrfs_init_work(&async_cow->work,
1202                                 btrfs_delalloc_helper,
1203                                 async_cow_start, async_cow_submit,
1204                                 async_cow_free);
1205
1206                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1207                         PAGE_SHIFT;
1208                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1209
1210                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1211
1212                 while (atomic_read(&fs_info->async_submit_draining) &&
1213                        atomic_read(&fs_info->async_delalloc_pages)) {
1214                         wait_event(fs_info->async_submit_wait,
1215                                    (atomic_read(&fs_info->async_delalloc_pages) ==
1216                                     0));
1217                 }
1218
1219                 *nr_written += nr_pages;
1220                 start = cur_end + 1;
1221         }
1222         *page_started = 1;
1223         return 0;
1224 }
1225
1226 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1227                                         u64 bytenr, u64 num_bytes)
1228 {
1229         int ret;
1230         struct btrfs_ordered_sum *sums;
1231         LIST_HEAD(list);
1232
1233         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1234                                        bytenr + num_bytes - 1, &list, 0);
1235         if (ret == 0 && list_empty(&list))
1236                 return 0;
1237
1238         while (!list_empty(&list)) {
1239                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1240                 list_del(&sums->list);
1241                 kfree(sums);
1242         }
1243         return 1;
1244 }
1245
1246 /*
1247  * when nowcow writeback call back.  This checks for snapshots or COW copies
1248  * of the extents that exist in the file, and COWs the file as required.
1249  *
1250  * If no cow copies or snapshots exist, we write directly to the existing
1251  * blocks on disk
1252  */
1253 static noinline int run_delalloc_nocow(struct inode *inode,
1254                                        struct page *locked_page,
1255                               u64 start, u64 end, int *page_started, int force,
1256                               unsigned long *nr_written)
1257 {
1258         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1259         struct btrfs_root *root = BTRFS_I(inode)->root;
1260         struct extent_buffer *leaf;
1261         struct btrfs_path *path;
1262         struct btrfs_file_extent_item *fi;
1263         struct btrfs_key found_key;
1264         struct extent_map *em;
1265         u64 cow_start;
1266         u64 cur_offset;
1267         u64 extent_end;
1268         u64 extent_offset;
1269         u64 disk_bytenr;
1270         u64 num_bytes;
1271         u64 disk_num_bytes;
1272         u64 ram_bytes;
1273         int extent_type;
1274         int ret, err;
1275         int type;
1276         int nocow;
1277         int check_prev = 1;
1278         bool nolock;
1279         u64 ino = btrfs_ino(BTRFS_I(inode));
1280
1281         path = btrfs_alloc_path();
1282         if (!path) {
1283                 extent_clear_unlock_delalloc(inode, start, end, end,
1284                                              locked_page,
1285                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1286                                              EXTENT_DO_ACCOUNTING |
1287                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1288                                              PAGE_CLEAR_DIRTY |
1289                                              PAGE_SET_WRITEBACK |
1290                                              PAGE_END_WRITEBACK);
1291                 return -ENOMEM;
1292         }
1293
1294         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1295
1296         cow_start = (u64)-1;
1297         cur_offset = start;
1298         while (1) {
1299                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1300                                                cur_offset, 0);
1301                 if (ret < 0)
1302                         goto error;
1303                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1304                         leaf = path->nodes[0];
1305                         btrfs_item_key_to_cpu(leaf, &found_key,
1306                                               path->slots[0] - 1);
1307                         if (found_key.objectid == ino &&
1308                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1309                                 path->slots[0]--;
1310                 }
1311                 check_prev = 0;
1312 next_slot:
1313                 leaf = path->nodes[0];
1314                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1315                         ret = btrfs_next_leaf(root, path);
1316                         if (ret < 0)
1317                                 goto error;
1318                         if (ret > 0)
1319                                 break;
1320                         leaf = path->nodes[0];
1321                 }
1322
1323                 nocow = 0;
1324                 disk_bytenr = 0;
1325                 num_bytes = 0;
1326                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1327
1328                 if (found_key.objectid > ino)
1329                         break;
1330                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1331                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1332                         path->slots[0]++;
1333                         goto next_slot;
1334                 }
1335                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1336                     found_key.offset > end)
1337                         break;
1338
1339                 if (found_key.offset > cur_offset) {
1340                         extent_end = found_key.offset;
1341                         extent_type = 0;
1342                         goto out_check;
1343                 }
1344
1345                 fi = btrfs_item_ptr(leaf, path->slots[0],
1346                                     struct btrfs_file_extent_item);
1347                 extent_type = btrfs_file_extent_type(leaf, fi);
1348
1349                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1350                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1351                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1352                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1353                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1354                         extent_end = found_key.offset +
1355                                 btrfs_file_extent_num_bytes(leaf, fi);
1356                         disk_num_bytes =
1357                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1358                         if (extent_end <= start) {
1359                                 path->slots[0]++;
1360                                 goto next_slot;
1361                         }
1362                         if (disk_bytenr == 0)
1363                                 goto out_check;
1364                         if (btrfs_file_extent_compression(leaf, fi) ||
1365                             btrfs_file_extent_encryption(leaf, fi) ||
1366                             btrfs_file_extent_other_encoding(leaf, fi))
1367                                 goto out_check;
1368                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1369                                 goto out_check;
1370                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1371                                 goto out_check;
1372                         if (btrfs_cross_ref_exist(root, ino,
1373                                                   found_key.offset -
1374                                                   extent_offset, disk_bytenr))
1375                                 goto out_check;
1376                         disk_bytenr += extent_offset;
1377                         disk_bytenr += cur_offset - found_key.offset;
1378                         num_bytes = min(end + 1, extent_end) - cur_offset;
1379                         /*
1380                          * if there are pending snapshots for this root,
1381                          * we fall into common COW way.
1382                          */
1383                         if (!nolock) {
1384                                 err = btrfs_start_write_no_snapshoting(root);
1385                                 if (!err)
1386                                         goto out_check;
1387                         }
1388                         /*
1389                          * force cow if csum exists in the range.
1390                          * this ensure that csum for a given extent are
1391                          * either valid or do not exist.
1392                          */
1393                         if (csum_exist_in_range(fs_info, disk_bytenr,
1394                                                 num_bytes)) {
1395                                 if (!nolock)
1396                                         btrfs_end_write_no_snapshoting(root);
1397                                 goto out_check;
1398                         }
1399                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1400                                 if (!nolock)
1401                                         btrfs_end_write_no_snapshoting(root);
1402                                 goto out_check;
1403                         }
1404                         nocow = 1;
1405                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1406                         extent_end = found_key.offset +
1407                                 btrfs_file_extent_inline_len(leaf,
1408                                                      path->slots[0], fi);
1409                         extent_end = ALIGN(extent_end,
1410                                            fs_info->sectorsize);
1411                 } else {
1412                         BUG_ON(1);
1413                 }
1414 out_check:
1415                 if (extent_end <= start) {
1416                         path->slots[0]++;
1417                         if (!nolock && nocow)
1418                                 btrfs_end_write_no_snapshoting(root);
1419                         if (nocow)
1420                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1421                         goto next_slot;
1422                 }
1423                 if (!nocow) {
1424                         if (cow_start == (u64)-1)
1425                                 cow_start = cur_offset;
1426                         cur_offset = extent_end;
1427                         if (cur_offset > end)
1428                                 break;
1429                         path->slots[0]++;
1430                         goto next_slot;
1431                 }
1432
1433                 btrfs_release_path(path);
1434                 if (cow_start != (u64)-1) {
1435                         ret = cow_file_range(inode, locked_page,
1436                                              cow_start, found_key.offset - 1,
1437                                              end, page_started, nr_written, 1,
1438                                              NULL);
1439                         if (ret) {
1440                                 if (!nolock && nocow)
1441                                         btrfs_end_write_no_snapshoting(root);
1442                                 if (nocow)
1443                                         btrfs_dec_nocow_writers(fs_info,
1444                                                                 disk_bytenr);
1445                                 goto error;
1446                         }
1447                         cow_start = (u64)-1;
1448                 }
1449
1450                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1451                         u64 orig_start = found_key.offset - extent_offset;
1452
1453                         em = create_io_em(inode, cur_offset, num_bytes,
1454                                           orig_start,
1455                                           disk_bytenr, /* block_start */
1456                                           num_bytes, /* block_len */
1457                                           disk_num_bytes, /* orig_block_len */
1458                                           ram_bytes, BTRFS_COMPRESS_NONE,
1459                                           BTRFS_ORDERED_PREALLOC);
1460                         if (IS_ERR(em)) {
1461                                 if (!nolock && nocow)
1462                                         btrfs_end_write_no_snapshoting(root);
1463                                 if (nocow)
1464                                         btrfs_dec_nocow_writers(fs_info,
1465                                                                 disk_bytenr);
1466                                 ret = PTR_ERR(em);
1467                                 goto error;
1468                         }
1469                         free_extent_map(em);
1470                 }
1471
1472                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1473                         type = BTRFS_ORDERED_PREALLOC;
1474                 } else {
1475                         type = BTRFS_ORDERED_NOCOW;
1476                 }
1477
1478                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1479                                                num_bytes, num_bytes, type);
1480                 if (nocow)
1481                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1482                 BUG_ON(ret); /* -ENOMEM */
1483
1484                 if (root->root_key.objectid ==
1485                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1486                         /*
1487                          * Error handled later, as we must prevent
1488                          * extent_clear_unlock_delalloc() in error handler
1489                          * from freeing metadata of created ordered extent.
1490                          */
1491                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1492                                                       num_bytes);
1493
1494                 extent_clear_unlock_delalloc(inode, cur_offset,
1495                                              cur_offset + num_bytes - 1, end,
1496                                              locked_page, EXTENT_LOCKED |
1497                                              EXTENT_DELALLOC |
1498                                              EXTENT_CLEAR_DATA_RESV,
1499                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1500
1501                 if (!nolock && nocow)
1502                         btrfs_end_write_no_snapshoting(root);
1503                 cur_offset = extent_end;
1504
1505                 /*
1506                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1507                  * handler, as metadata for created ordered extent will only
1508                  * be freed by btrfs_finish_ordered_io().
1509                  */
1510                 if (ret)
1511                         goto error;
1512                 if (cur_offset > end)
1513                         break;
1514         }
1515         btrfs_release_path(path);
1516
1517         if (cur_offset <= end && cow_start == (u64)-1) {
1518                 cow_start = cur_offset;
1519                 cur_offset = end;
1520         }
1521
1522         if (cow_start != (u64)-1) {
1523                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1524                                      page_started, nr_written, 1, NULL);
1525                 if (ret)
1526                         goto error;
1527         }
1528
1529 error:
1530         if (ret && cur_offset < end)
1531                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1532                                              locked_page, EXTENT_LOCKED |
1533                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1534                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1535                                              PAGE_CLEAR_DIRTY |
1536                                              PAGE_SET_WRITEBACK |
1537                                              PAGE_END_WRITEBACK);
1538         btrfs_free_path(path);
1539         return ret;
1540 }
1541
1542 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1543 {
1544
1545         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1546             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1547                 return 0;
1548
1549         /*
1550          * @defrag_bytes is a hint value, no spinlock held here,
1551          * if is not zero, it means the file is defragging.
1552          * Force cow if given extent needs to be defragged.
1553          */
1554         if (BTRFS_I(inode)->defrag_bytes &&
1555             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1556                            EXTENT_DEFRAG, 0, NULL))
1557                 return 1;
1558
1559         return 0;
1560 }
1561
1562 /*
1563  * extent_io.c call back to do delayed allocation processing
1564  */
1565 static int run_delalloc_range(void *private_data, struct page *locked_page,
1566                               u64 start, u64 end, int *page_started,
1567                               unsigned long *nr_written)
1568 {
1569         struct inode *inode = private_data;
1570         int ret;
1571         int force_cow = need_force_cow(inode, start, end);
1572
1573         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1574                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1575                                          page_started, 1, nr_written);
1576         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1577                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1578                                          page_started, 0, nr_written);
1579         } else if (!inode_need_compress(inode)) {
1580                 ret = cow_file_range(inode, locked_page, start, end, end,
1581                                       page_started, nr_written, 1, NULL);
1582         } else {
1583                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1584                         &BTRFS_I(inode)->runtime_flags);
1585                 ret = cow_file_range_async(inode, locked_page, start, end,
1586                                            page_started, nr_written);
1587         }
1588         if (ret)
1589                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1590         return ret;
1591 }
1592
1593 static void btrfs_split_extent_hook(void *private_data,
1594                                     struct extent_state *orig, u64 split)
1595 {
1596         struct inode *inode = private_data;
1597         u64 size;
1598
1599         /* not delalloc, ignore it */
1600         if (!(orig->state & EXTENT_DELALLOC))
1601                 return;
1602
1603         size = orig->end - orig->start + 1;
1604         if (size > BTRFS_MAX_EXTENT_SIZE) {
1605                 u32 num_extents;
1606                 u64 new_size;
1607
1608                 /*
1609                  * See the explanation in btrfs_merge_extent_hook, the same
1610                  * applies here, just in reverse.
1611                  */
1612                 new_size = orig->end - split + 1;
1613                 num_extents = count_max_extents(new_size);
1614                 new_size = split - orig->start;
1615                 num_extents += count_max_extents(new_size);
1616                 if (count_max_extents(size) >= num_extents)
1617                         return;
1618         }
1619
1620         spin_lock(&BTRFS_I(inode)->lock);
1621         BTRFS_I(inode)->outstanding_extents++;
1622         spin_unlock(&BTRFS_I(inode)->lock);
1623 }
1624
1625 /*
1626  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1627  * extents so we can keep track of new extents that are just merged onto old
1628  * extents, such as when we are doing sequential writes, so we can properly
1629  * account for the metadata space we'll need.
1630  */
1631 static void btrfs_merge_extent_hook(void *private_data,
1632                                     struct extent_state *new,
1633                                     struct extent_state *other)
1634 {
1635         struct inode *inode = private_data;
1636         u64 new_size, old_size;
1637         u32 num_extents;
1638
1639         /* not delalloc, ignore it */
1640         if (!(other->state & EXTENT_DELALLOC))
1641                 return;
1642
1643         if (new->start > other->start)
1644                 new_size = new->end - other->start + 1;
1645         else
1646                 new_size = other->end - new->start + 1;
1647
1648         /* we're not bigger than the max, unreserve the space and go */
1649         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1650                 spin_lock(&BTRFS_I(inode)->lock);
1651                 BTRFS_I(inode)->outstanding_extents--;
1652                 spin_unlock(&BTRFS_I(inode)->lock);
1653                 return;
1654         }
1655
1656         /*
1657          * We have to add up either side to figure out how many extents were
1658          * accounted for before we merged into one big extent.  If the number of
1659          * extents we accounted for is <= the amount we need for the new range
1660          * then we can return, otherwise drop.  Think of it like this
1661          *
1662          * [ 4k][MAX_SIZE]
1663          *
1664          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1665          * need 2 outstanding extents, on one side we have 1 and the other side
1666          * we have 1 so they are == and we can return.  But in this case
1667          *
1668          * [MAX_SIZE+4k][MAX_SIZE+4k]
1669          *
1670          * Each range on their own accounts for 2 extents, but merged together
1671          * they are only 3 extents worth of accounting, so we need to drop in
1672          * this case.
1673          */
1674         old_size = other->end - other->start + 1;
1675         num_extents = count_max_extents(old_size);
1676         old_size = new->end - new->start + 1;
1677         num_extents += count_max_extents(old_size);
1678         if (count_max_extents(new_size) >= num_extents)
1679                 return;
1680
1681         spin_lock(&BTRFS_I(inode)->lock);
1682         BTRFS_I(inode)->outstanding_extents--;
1683         spin_unlock(&BTRFS_I(inode)->lock);
1684 }
1685
1686 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1687                                       struct inode *inode)
1688 {
1689         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1690
1691         spin_lock(&root->delalloc_lock);
1692         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1693                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1694                               &root->delalloc_inodes);
1695                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1696                         &BTRFS_I(inode)->runtime_flags);
1697                 root->nr_delalloc_inodes++;
1698                 if (root->nr_delalloc_inodes == 1) {
1699                         spin_lock(&fs_info->delalloc_root_lock);
1700                         BUG_ON(!list_empty(&root->delalloc_root));
1701                         list_add_tail(&root->delalloc_root,
1702                                       &fs_info->delalloc_roots);
1703                         spin_unlock(&fs_info->delalloc_root_lock);
1704                 }
1705         }
1706         spin_unlock(&root->delalloc_lock);
1707 }
1708
1709 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1710                                      struct btrfs_inode *inode)
1711 {
1712         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1713
1714         spin_lock(&root->delalloc_lock);
1715         if (!list_empty(&inode->delalloc_inodes)) {
1716                 list_del_init(&inode->delalloc_inodes);
1717                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1718                           &inode->runtime_flags);
1719                 root->nr_delalloc_inodes--;
1720                 if (!root->nr_delalloc_inodes) {
1721                         spin_lock(&fs_info->delalloc_root_lock);
1722                         BUG_ON(list_empty(&root->delalloc_root));
1723                         list_del_init(&root->delalloc_root);
1724                         spin_unlock(&fs_info->delalloc_root_lock);
1725                 }
1726         }
1727         spin_unlock(&root->delalloc_lock);
1728 }
1729
1730 /*
1731  * extent_io.c set_bit_hook, used to track delayed allocation
1732  * bytes in this file, and to maintain the list of inodes that
1733  * have pending delalloc work to be done.
1734  */
1735 static void btrfs_set_bit_hook(void *private_data,
1736                                struct extent_state *state, unsigned *bits)
1737 {
1738         struct inode *inode = private_data;
1739
1740         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1741
1742         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1743                 WARN_ON(1);
1744         /*
1745          * set_bit and clear bit hooks normally require _irqsave/restore
1746          * but in this case, we are only testing for the DELALLOC
1747          * bit, which is only set or cleared with irqs on
1748          */
1749         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1750                 struct btrfs_root *root = BTRFS_I(inode)->root;
1751                 u64 len = state->end + 1 - state->start;
1752                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1753
1754                 if (*bits & EXTENT_FIRST_DELALLOC) {
1755                         *bits &= ~EXTENT_FIRST_DELALLOC;
1756                 } else {
1757                         spin_lock(&BTRFS_I(inode)->lock);
1758                         BTRFS_I(inode)->outstanding_extents++;
1759                         spin_unlock(&BTRFS_I(inode)->lock);
1760                 }
1761
1762                 /* For sanity tests */
1763                 if (btrfs_is_testing(fs_info))
1764                         return;
1765
1766                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1767                                          fs_info->delalloc_batch);
1768                 spin_lock(&BTRFS_I(inode)->lock);
1769                 BTRFS_I(inode)->delalloc_bytes += len;
1770                 if (*bits & EXTENT_DEFRAG)
1771                         BTRFS_I(inode)->defrag_bytes += len;
1772                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1773                                          &BTRFS_I(inode)->runtime_flags))
1774                         btrfs_add_delalloc_inodes(root, inode);
1775                 spin_unlock(&BTRFS_I(inode)->lock);
1776         }
1777
1778         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1779             (*bits & EXTENT_DELALLOC_NEW)) {
1780                 spin_lock(&BTRFS_I(inode)->lock);
1781                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1782                         state->start;
1783                 spin_unlock(&BTRFS_I(inode)->lock);
1784         }
1785 }
1786
1787 /*
1788  * extent_io.c clear_bit_hook, see set_bit_hook for why
1789  */
1790 static void btrfs_clear_bit_hook(void *private_data,
1791                                  struct extent_state *state,
1792                                  unsigned *bits)
1793 {
1794         struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1795         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1796         u64 len = state->end + 1 - state->start;
1797         u32 num_extents = count_max_extents(len);
1798
1799         spin_lock(&inode->lock);
1800         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1801                 inode->defrag_bytes -= len;
1802         spin_unlock(&inode->lock);
1803
1804         /*
1805          * set_bit and clear bit hooks normally require _irqsave/restore
1806          * but in this case, we are only testing for the DELALLOC
1807          * bit, which is only set or cleared with irqs on
1808          */
1809         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1810                 struct btrfs_root *root = inode->root;
1811                 bool do_list = !btrfs_is_free_space_inode(inode);
1812
1813                 if (*bits & EXTENT_FIRST_DELALLOC) {
1814                         *bits &= ~EXTENT_FIRST_DELALLOC;
1815                 } else if (!(*bits & EXTENT_CLEAR_META_RESV)) {
1816                         spin_lock(&inode->lock);
1817                         inode->outstanding_extents -= num_extents;
1818                         spin_unlock(&inode->lock);
1819                 }
1820
1821                 /*
1822                  * We don't reserve metadata space for space cache inodes so we
1823                  * don't need to call dellalloc_release_metadata if there is an
1824                  * error.
1825                  */
1826                 if (*bits & EXTENT_CLEAR_META_RESV &&
1827                     root != fs_info->tree_root)
1828                         btrfs_delalloc_release_metadata(inode, len);
1829
1830                 /* For sanity tests. */
1831                 if (btrfs_is_testing(fs_info))
1832                         return;
1833
1834                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1835                     do_list && !(state->state & EXTENT_NORESERVE) &&
1836                     (*bits & EXTENT_CLEAR_DATA_RESV))
1837                         btrfs_free_reserved_data_space_noquota(
1838                                         &inode->vfs_inode,
1839                                         state->start, len);
1840
1841                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1842                                          fs_info->delalloc_batch);
1843                 spin_lock(&inode->lock);
1844                 inode->delalloc_bytes -= len;
1845                 if (do_list && inode->delalloc_bytes == 0 &&
1846                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1847                                         &inode->runtime_flags))
1848                         btrfs_del_delalloc_inode(root, inode);
1849                 spin_unlock(&inode->lock);
1850         }
1851
1852         if ((state->state & EXTENT_DELALLOC_NEW) &&
1853             (*bits & EXTENT_DELALLOC_NEW)) {
1854                 spin_lock(&inode->lock);
1855                 ASSERT(inode->new_delalloc_bytes >= len);
1856                 inode->new_delalloc_bytes -= len;
1857                 spin_unlock(&inode->lock);
1858         }
1859 }
1860
1861 /*
1862  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1863  * we don't create bios that span stripes or chunks
1864  *
1865  * return 1 if page cannot be merged to bio
1866  * return 0 if page can be merged to bio
1867  * return error otherwise
1868  */
1869 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1870                          size_t size, struct bio *bio,
1871                          unsigned long bio_flags)
1872 {
1873         struct inode *inode = page->mapping->host;
1874         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1875         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1876         u64 length = 0;
1877         u64 map_length;
1878         int ret;
1879
1880         if (bio_flags & EXTENT_BIO_COMPRESSED)
1881                 return 0;
1882
1883         length = bio->bi_iter.bi_size;
1884         map_length = length;
1885         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1886                               NULL, 0);
1887         if (ret < 0)
1888                 return ret;
1889         if (map_length < length + size)
1890                 return 1;
1891         return 0;
1892 }
1893
1894 /*
1895  * in order to insert checksums into the metadata in large chunks,
1896  * we wait until bio submission time.   All the pages in the bio are
1897  * checksummed and sums are attached onto the ordered extent record.
1898  *
1899  * At IO completion time the cums attached on the ordered extent record
1900  * are inserted into the btree
1901  */
1902 static blk_status_t __btrfs_submit_bio_start(void *private_data, struct bio *bio,
1903                                     int mirror_num, unsigned long bio_flags,
1904                                     u64 bio_offset)
1905 {
1906         struct inode *inode = private_data;
1907         blk_status_t ret = 0;
1908
1909         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1910         BUG_ON(ret); /* -ENOMEM */
1911         return 0;
1912 }
1913
1914 /*
1915  * in order to insert checksums into the metadata in large chunks,
1916  * we wait until bio submission time.   All the pages in the bio are
1917  * checksummed and sums are attached onto the ordered extent record.
1918  *
1919  * At IO completion time the cums attached on the ordered extent record
1920  * are inserted into the btree
1921  */
1922 static blk_status_t __btrfs_submit_bio_done(void *private_data, struct bio *bio,
1923                           int mirror_num, unsigned long bio_flags,
1924                           u64 bio_offset)
1925 {
1926         struct inode *inode = private_data;
1927         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1928         blk_status_t ret;
1929
1930         ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1931         if (ret) {
1932                 bio->bi_status = ret;
1933                 bio_endio(bio);
1934         }
1935         return ret;
1936 }
1937
1938 /*
1939  * extent_io.c submission hook. This does the right thing for csum calculation
1940  * on write, or reading the csums from the tree before a read
1941  */
1942 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1943                                  int mirror_num, unsigned long bio_flags,
1944                                  u64 bio_offset)
1945 {
1946         struct inode *inode = private_data;
1947         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1948         struct btrfs_root *root = BTRFS_I(inode)->root;
1949         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1950         blk_status_t ret = 0;
1951         int skip_sum;
1952         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1953
1954         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1955
1956         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
1957                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1958
1959         if (bio_op(bio) != REQ_OP_WRITE) {
1960                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
1961                 if (ret)
1962                         goto out;
1963
1964                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1965                         ret = btrfs_submit_compressed_read(inode, bio,
1966                                                            mirror_num,
1967                                                            bio_flags);
1968                         goto out;
1969                 } else if (!skip_sum) {
1970                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
1971                         if (ret)
1972                                 goto out;
1973                 }
1974                 goto mapit;
1975         } else if (async && !skip_sum) {
1976                 /* csum items have already been cloned */
1977                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1978                         goto mapit;
1979                 /* we're doing a write, do the async checksumming */
1980                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
1981                                           bio_offset, inode,
1982                                           __btrfs_submit_bio_start,
1983                                           __btrfs_submit_bio_done);
1984                 goto out;
1985         } else if (!skip_sum) {
1986                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1987                 if (ret)
1988                         goto out;
1989         }
1990
1991 mapit:
1992         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
1993
1994 out:
1995         if (ret) {
1996                 bio->bi_status = ret;
1997                 bio_endio(bio);
1998         }
1999         return ret;
2000 }
2001
2002 /*
2003  * given a list of ordered sums record them in the inode.  This happens
2004  * at IO completion time based on sums calculated at bio submission time.
2005  */
2006 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2007                              struct inode *inode, struct list_head *list)
2008 {
2009         struct btrfs_ordered_sum *sum;
2010
2011         list_for_each_entry(sum, list, list) {
2012                 trans->adding_csums = 1;
2013                 btrfs_csum_file_blocks(trans,
2014                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2015                 trans->adding_csums = 0;
2016         }
2017         return 0;
2018 }
2019
2020 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2021                               struct extent_state **cached_state, int dedupe)
2022 {
2023         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2024         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2025                                    cached_state);
2026 }
2027
2028 /* see btrfs_writepage_start_hook for details on why this is required */
2029 struct btrfs_writepage_fixup {
2030         struct page *page;
2031         struct btrfs_work work;
2032 };
2033
2034 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2035 {
2036         struct btrfs_writepage_fixup *fixup;
2037         struct btrfs_ordered_extent *ordered;
2038         struct extent_state *cached_state = NULL;
2039         struct extent_changeset *data_reserved = NULL;
2040         struct page *page;
2041         struct inode *inode;
2042         u64 page_start;
2043         u64 page_end;
2044         int ret;
2045
2046         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2047         page = fixup->page;
2048 again:
2049         lock_page(page);
2050         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2051                 ClearPageChecked(page);
2052                 goto out_page;
2053         }
2054
2055         inode = page->mapping->host;
2056         page_start = page_offset(page);
2057         page_end = page_offset(page) + PAGE_SIZE - 1;
2058
2059         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2060                          &cached_state);
2061
2062         /* already ordered? We're done */
2063         if (PagePrivate2(page))
2064                 goto out;
2065
2066         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2067                                         PAGE_SIZE);
2068         if (ordered) {
2069                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2070                                      page_end, &cached_state, GFP_NOFS);
2071                 unlock_page(page);
2072                 btrfs_start_ordered_extent(inode, ordered, 1);
2073                 btrfs_put_ordered_extent(ordered);
2074                 goto again;
2075         }
2076
2077         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2078                                            PAGE_SIZE);
2079         if (ret) {
2080                 mapping_set_error(page->mapping, ret);
2081                 end_extent_writepage(page, ret, page_start, page_end);
2082                 ClearPageChecked(page);
2083                 goto out;
2084          }
2085
2086         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state,
2087                                   0);
2088         ClearPageChecked(page);
2089         set_page_dirty(page);
2090 out:
2091         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2092                              &cached_state, GFP_NOFS);
2093 out_page:
2094         unlock_page(page);
2095         put_page(page);
2096         kfree(fixup);
2097         extent_changeset_free(data_reserved);
2098 }
2099
2100 /*
2101  * There are a few paths in the higher layers of the kernel that directly
2102  * set the page dirty bit without asking the filesystem if it is a
2103  * good idea.  This causes problems because we want to make sure COW
2104  * properly happens and the data=ordered rules are followed.
2105  *
2106  * In our case any range that doesn't have the ORDERED bit set
2107  * hasn't been properly setup for IO.  We kick off an async process
2108  * to fix it up.  The async helper will wait for ordered extents, set
2109  * the delalloc bit and make it safe to write the page.
2110  */
2111 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2112 {
2113         struct inode *inode = page->mapping->host;
2114         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2115         struct btrfs_writepage_fixup *fixup;
2116
2117         /* this page is properly in the ordered list */
2118         if (TestClearPagePrivate2(page))
2119                 return 0;
2120
2121         if (PageChecked(page))
2122                 return -EAGAIN;
2123
2124         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2125         if (!fixup)
2126                 return -EAGAIN;
2127
2128         SetPageChecked(page);
2129         get_page(page);
2130         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2131                         btrfs_writepage_fixup_worker, NULL, NULL);
2132         fixup->page = page;
2133         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2134         return -EBUSY;
2135 }
2136
2137 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2138                                        struct inode *inode, u64 file_pos,
2139                                        u64 disk_bytenr, u64 disk_num_bytes,
2140                                        u64 num_bytes, u64 ram_bytes,
2141                                        u8 compression, u8 encryption,
2142                                        u16 other_encoding, int extent_type)
2143 {
2144         struct btrfs_root *root = BTRFS_I(inode)->root;
2145         struct btrfs_file_extent_item *fi;
2146         struct btrfs_path *path;
2147         struct extent_buffer *leaf;
2148         struct btrfs_key ins;
2149         u64 qg_released;
2150         int extent_inserted = 0;
2151         int ret;
2152
2153         path = btrfs_alloc_path();
2154         if (!path)
2155                 return -ENOMEM;
2156
2157         /*
2158          * we may be replacing one extent in the tree with another.
2159          * The new extent is pinned in the extent map, and we don't want
2160          * to drop it from the cache until it is completely in the btree.
2161          *
2162          * So, tell btrfs_drop_extents to leave this extent in the cache.
2163          * the caller is expected to unpin it and allow it to be merged
2164          * with the others.
2165          */
2166         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2167                                    file_pos + num_bytes, NULL, 0,
2168                                    1, sizeof(*fi), &extent_inserted);
2169         if (ret)
2170                 goto out;
2171
2172         if (!extent_inserted) {
2173                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2174                 ins.offset = file_pos;
2175                 ins.type = BTRFS_EXTENT_DATA_KEY;
2176
2177                 path->leave_spinning = 1;
2178                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2179                                               sizeof(*fi));
2180                 if (ret)
2181                         goto out;
2182         }
2183         leaf = path->nodes[0];
2184         fi = btrfs_item_ptr(leaf, path->slots[0],
2185                             struct btrfs_file_extent_item);
2186         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2187         btrfs_set_file_extent_type(leaf, fi, extent_type);
2188         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2189         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2190         btrfs_set_file_extent_offset(leaf, fi, 0);
2191         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2192         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2193         btrfs_set_file_extent_compression(leaf, fi, compression);
2194         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2195         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2196
2197         btrfs_mark_buffer_dirty(leaf);
2198         btrfs_release_path(path);
2199
2200         inode_add_bytes(inode, num_bytes);
2201
2202         ins.objectid = disk_bytenr;
2203         ins.offset = disk_num_bytes;
2204         ins.type = BTRFS_EXTENT_ITEM_KEY;
2205
2206         /*
2207          * Release the reserved range from inode dirty range map, as it is
2208          * already moved into delayed_ref_head
2209          */
2210         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2211         if (ret < 0)
2212                 goto out;
2213         qg_released = ret;
2214         ret = btrfs_alloc_reserved_file_extent(trans, root->root_key.objectid,
2215                         btrfs_ino(BTRFS_I(inode)), file_pos, qg_released, &ins);
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, NULL, 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))