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