b0f421f332ae911b731f4c4eb8705053705504ce
[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(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, bio_op(bio), 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, struct bio *bio,
1867                                     int mirror_num, unsigned long bio_flags,
1868                                     u64 bio_offset)
1869 {
1870         struct btrfs_root *root = BTRFS_I(inode)->root;
1871         int ret = 0;
1872
1873         ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1874         BUG_ON(ret); /* -ENOMEM */
1875         return 0;
1876 }
1877
1878 /*
1879  * in order to insert checksums into the metadata in large chunks,
1880  * we wait until bio submission time.   All the pages in the bio are
1881  * checksummed and sums are attached onto the ordered extent record.
1882  *
1883  * At IO completion time the cums attached on the ordered extent record
1884  * are inserted into the btree
1885  */
1886 static int __btrfs_submit_bio_done(struct inode *inode, struct bio *bio,
1887                           int mirror_num, unsigned long bio_flags,
1888                           u64 bio_offset)
1889 {
1890         struct btrfs_root *root = BTRFS_I(inode)->root;
1891         int ret;
1892
1893         ret = btrfs_map_bio(root, bio, mirror_num, 1);
1894         if (ret) {
1895                 bio->bi_error = ret;
1896                 bio_endio(bio);
1897         }
1898         return ret;
1899 }
1900
1901 /*
1902  * extent_io.c submission hook. This does the right thing for csum calculation
1903  * on write, or reading the csums from the tree before a read
1904  */
1905 static int btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
1906                           int mirror_num, unsigned long bio_flags,
1907                           u64 bio_offset)
1908 {
1909         struct btrfs_root *root = BTRFS_I(inode)->root;
1910         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1911         int ret = 0;
1912         int skip_sum;
1913         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1914
1915         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1916
1917         if (btrfs_is_free_space_inode(inode))
1918                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1919
1920         if (bio_op(bio) != REQ_OP_WRITE) {
1921                 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1922                 if (ret)
1923                         goto out;
1924
1925                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1926                         ret = btrfs_submit_compressed_read(inode, bio,
1927                                                            mirror_num,
1928                                                            bio_flags);
1929                         goto out;
1930                 } else if (!skip_sum) {
1931                         ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1932                         if (ret)
1933                                 goto out;
1934                 }
1935                 goto mapit;
1936         } else if (async && !skip_sum) {
1937                 /* csum items have already been cloned */
1938                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1939                         goto mapit;
1940                 /* we're doing a write, do the async checksumming */
1941                 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1942                                    inode, bio, mirror_num,
1943                                    bio_flags, bio_offset,
1944                                    __btrfs_submit_bio_start,
1945                                    __btrfs_submit_bio_done);
1946                 goto out;
1947         } else if (!skip_sum) {
1948                 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1949                 if (ret)
1950                         goto out;
1951         }
1952
1953 mapit:
1954         ret = btrfs_map_bio(root, bio, mirror_num, 0);
1955
1956 out:
1957         if (ret < 0) {
1958                 bio->bi_error = ret;
1959                 bio_endio(bio);
1960         }
1961         return ret;
1962 }
1963
1964 /*
1965  * given a list of ordered sums record them in the inode.  This happens
1966  * at IO completion time based on sums calculated at bio submission time.
1967  */
1968 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1969                              struct inode *inode, u64 file_offset,
1970                              struct list_head *list)
1971 {
1972         struct btrfs_ordered_sum *sum;
1973
1974         list_for_each_entry(sum, list, list) {
1975                 trans->adding_csums = 1;
1976                 btrfs_csum_file_blocks(trans,
1977                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
1978                 trans->adding_csums = 0;
1979         }
1980         return 0;
1981 }
1982
1983 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1984                               struct extent_state **cached_state)
1985 {
1986         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
1987         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1988                                    cached_state);
1989 }
1990
1991 /* see btrfs_writepage_start_hook for details on why this is required */
1992 struct btrfs_writepage_fixup {
1993         struct page *page;
1994         struct btrfs_work work;
1995 };
1996
1997 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1998 {
1999         struct btrfs_writepage_fixup *fixup;
2000         struct btrfs_ordered_extent *ordered;
2001         struct extent_state *cached_state = NULL;
2002         struct page *page;
2003         struct inode *inode;
2004         u64 page_start;
2005         u64 page_end;
2006         int ret;
2007
2008         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2009         page = fixup->page;
2010 again:
2011         lock_page(page);
2012         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2013                 ClearPageChecked(page);
2014                 goto out_page;
2015         }
2016
2017         inode = page->mapping->host;
2018         page_start = page_offset(page);
2019         page_end = page_offset(page) + PAGE_SIZE - 1;
2020
2021         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2022                          &cached_state);
2023
2024         /* already ordered? We're done */
2025         if (PagePrivate2(page))
2026                 goto out;
2027
2028         ordered = btrfs_lookup_ordered_range(inode, page_start,
2029                                         PAGE_SIZE);
2030         if (ordered) {
2031                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2032                                      page_end, &cached_state, GFP_NOFS);
2033                 unlock_page(page);
2034                 btrfs_start_ordered_extent(inode, ordered, 1);
2035                 btrfs_put_ordered_extent(ordered);
2036                 goto again;
2037         }
2038
2039         ret = btrfs_delalloc_reserve_space(inode, page_start,
2040                                            PAGE_SIZE);
2041         if (ret) {
2042                 mapping_set_error(page->mapping, ret);
2043                 end_extent_writepage(page, ret, page_start, page_end);
2044                 ClearPageChecked(page);
2045                 goto out;
2046          }
2047
2048         btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
2049         ClearPageChecked(page);
2050         set_page_dirty(page);
2051 out:
2052         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2053                              &cached_state, GFP_NOFS);
2054 out_page:
2055         unlock_page(page);
2056         put_page(page);
2057         kfree(fixup);
2058 }
2059
2060 /*
2061  * There are a few paths in the higher layers of the kernel that directly
2062  * set the page dirty bit without asking the filesystem if it is a
2063  * good idea.  This causes problems because we want to make sure COW
2064  * properly happens and the data=ordered rules are followed.
2065  *
2066  * In our case any range that doesn't have the ORDERED bit set
2067  * hasn't been properly setup for IO.  We kick off an async process
2068  * to fix it up.  The async helper will wait for ordered extents, set
2069  * the delalloc bit and make it safe to write the page.
2070  */
2071 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2072 {
2073         struct inode *inode = page->mapping->host;
2074         struct btrfs_writepage_fixup *fixup;
2075         struct btrfs_root *root = BTRFS_I(inode)->root;
2076
2077         /* this page is properly in the ordered list */
2078         if (TestClearPagePrivate2(page))
2079                 return 0;
2080
2081         if (PageChecked(page))
2082                 return -EAGAIN;
2083
2084         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2085         if (!fixup)
2086                 return -EAGAIN;
2087
2088         SetPageChecked(page);
2089         get_page(page);
2090         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2091                         btrfs_writepage_fixup_worker, NULL, NULL);
2092         fixup->page = page;
2093         btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2094         return -EBUSY;
2095 }
2096
2097 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2098                                        struct inode *inode, u64 file_pos,
2099                                        u64 disk_bytenr, u64 disk_num_bytes,
2100                                        u64 num_bytes, u64 ram_bytes,
2101                                        u8 compression, u8 encryption,
2102                                        u16 other_encoding, int extent_type)
2103 {
2104         struct btrfs_root *root = BTRFS_I(inode)->root;
2105         struct btrfs_file_extent_item *fi;
2106         struct btrfs_path *path;
2107         struct extent_buffer *leaf;
2108         struct btrfs_key ins;
2109         int extent_inserted = 0;
2110         int ret;
2111
2112         path = btrfs_alloc_path();
2113         if (!path)
2114                 return -ENOMEM;
2115
2116         /*
2117          * we may be replacing one extent in the tree with another.
2118          * The new extent is pinned in the extent map, and we don't want
2119          * to drop it from the cache until it is completely in the btree.
2120          *
2121          * So, tell btrfs_drop_extents to leave this extent in the cache.
2122          * the caller is expected to unpin it and allow it to be merged
2123          * with the others.
2124          */
2125         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2126                                    file_pos + num_bytes, NULL, 0,
2127                                    1, sizeof(*fi), &extent_inserted);
2128         if (ret)
2129                 goto out;
2130
2131         if (!extent_inserted) {
2132                 ins.objectid = btrfs_ino(inode);
2133                 ins.offset = file_pos;
2134                 ins.type = BTRFS_EXTENT_DATA_KEY;
2135
2136                 path->leave_spinning = 1;
2137                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2138                                               sizeof(*fi));
2139                 if (ret)
2140                         goto out;
2141         }
2142         leaf = path->nodes[0];
2143         fi = btrfs_item_ptr(leaf, path->slots[0],
2144                             struct btrfs_file_extent_item);
2145         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2146         btrfs_set_file_extent_type(leaf, fi, extent_type);
2147         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2148         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2149         btrfs_set_file_extent_offset(leaf, fi, 0);
2150         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2151         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2152         btrfs_set_file_extent_compression(leaf, fi, compression);
2153         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2154         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2155
2156         btrfs_mark_buffer_dirty(leaf);
2157         btrfs_release_path(path);
2158
2159         inode_add_bytes(inode, num_bytes);
2160
2161         ins.objectid = disk_bytenr;
2162         ins.offset = disk_num_bytes;
2163         ins.type = BTRFS_EXTENT_ITEM_KEY;
2164         ret = btrfs_alloc_reserved_file_extent(trans, root,
2165                                         root->root_key.objectid,
2166                                         btrfs_ino(inode), file_pos,
2167                                         ram_bytes, &ins);
2168         /*
2169          * Release the reserved range from inode dirty range map, as it is
2170          * already moved into delayed_ref_head
2171          */
2172         btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2173 out:
2174         btrfs_free_path(path);
2175
2176         return ret;
2177 }
2178
2179 /* snapshot-aware defrag */
2180 struct sa_defrag_extent_backref {
2181         struct rb_node node;
2182         struct old_sa_defrag_extent *old;
2183         u64 root_id;
2184         u64 inum;
2185         u64 file_pos;
2186         u64 extent_offset;
2187         u64 num_bytes;
2188         u64 generation;
2189 };
2190
2191 struct old_sa_defrag_extent {
2192         struct list_head list;
2193         struct new_sa_defrag_extent *new;
2194
2195         u64 extent_offset;
2196         u64 bytenr;
2197         u64 offset;
2198         u64 len;
2199         int count;
2200 };
2201
2202 struct new_sa_defrag_extent {
2203         struct rb_root root;
2204         struct list_head head;
2205         struct btrfs_path *path;
2206         struct inode *inode;
2207         u64 file_pos;
2208         u64 len;
2209         u64 bytenr;
2210         u64 disk_len;
2211         u8 compress_type;
2212 };
2213
2214 static int backref_comp(struct sa_defrag_extent_backref *b1,
2215                         struct sa_defrag_extent_backref *b2)
2216 {
2217         if (b1->root_id < b2->root_id)
2218                 return -1;
2219         else if (b1->root_id > b2->root_id)
2220                 return 1;
2221
2222         if (b1->inum < b2->inum)
2223                 return -1;
2224         else if (b1->inum > b2->inum)
2225                 return 1;
2226
2227         if (b1->file_pos < b2->file_pos)
2228                 return -1;
2229         else if (b1->file_pos > b2->file_pos)
2230                 return 1;
2231
2232         /*
2233          * [------------------------------] ===> (a range of space)
2234          *     |<--->|   |<---->| =============> (fs/file tree A)
2235          * |<---------------------------->| ===> (fs/file tree B)
2236          *
2237          * A range of space can refer to two file extents in one tree while
2238          * refer to only one file extent in another tree.
2239          *
2240          * So we may process a disk offset more than one time(two extents in A)
2241          * and locate at the same extent(one extent in B), then insert two same
2242          * backrefs(both refer to the extent in B).
2243          */
2244         return 0;
2245 }
2246
2247 static void backref_insert(struct rb_root *root,
2248                            struct sa_defrag_extent_backref *backref)
2249 {
2250         struct rb_node **p = &root->rb_node;
2251         struct rb_node *parent = NULL;
2252         struct sa_defrag_extent_backref *entry;
2253         int ret;
2254
2255         while (*p) {
2256                 parent = *p;
2257                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2258
2259                 ret = backref_comp(backref, entry);
2260                 if (ret < 0)
2261                         p = &(*p)->rb_left;
2262                 else
2263                         p = &(*p)->rb_right;
2264         }
2265
2266         rb_link_node(&backref->node, parent, p);
2267         rb_insert_color(&backref->node, root);
2268 }
2269
2270 /*
2271  * Note the backref might has changed, and in this case we just return 0.
2272  */
2273 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2274                                        void *ctx)
2275 {
2276         struct btrfs_file_extent_item *extent;
2277         struct btrfs_fs_info *fs_info;
2278         struct old_sa_defrag_extent *old = ctx;
2279         struct new_sa_defrag_extent *new = old->new;
2280         struct btrfs_path *path = new->path;
2281         struct btrfs_key key;
2282         struct btrfs_root *root;
2283         struct sa_defrag_extent_backref *backref;
2284         struct extent_buffer *leaf;
2285         struct inode *inode = new->inode;
2286         int slot;
2287         int ret;
2288         u64 extent_offset;
2289         u64 num_bytes;
2290
2291         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2292             inum == btrfs_ino(inode))
2293                 return 0;
2294
2295         key.objectid = root_id;
2296         key.type = BTRFS_ROOT_ITEM_KEY;
2297         key.offset = (u64)-1;
2298
2299         fs_info = BTRFS_I(inode)->root->fs_info;
2300         root = btrfs_read_fs_root_no_name(fs_info, &key);
2301         if (IS_ERR(root)) {
2302                 if (PTR_ERR(root) == -ENOENT)
2303                         return 0;
2304                 WARN_ON(1);
2305                 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2306                          inum, offset, root_id);
2307                 return PTR_ERR(root);
2308         }
2309
2310         key.objectid = inum;
2311         key.type = BTRFS_EXTENT_DATA_KEY;
2312         if (offset > (u64)-1 << 32)
2313                 key.offset = 0;
2314         else
2315                 key.offset = offset;
2316
2317         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2318         if (WARN_ON(ret < 0))
2319                 return ret;
2320         ret = 0;
2321
2322         while (1) {
2323                 cond_resched();
2324
2325                 leaf = path->nodes[0];
2326                 slot = path->slots[0];
2327
2328                 if (slot >= btrfs_header_nritems(leaf)) {
2329                         ret = btrfs_next_leaf(root, path);
2330                         if (ret < 0) {
2331                                 goto out;
2332                         } else if (ret > 0) {
2333                                 ret = 0;
2334                                 goto out;
2335                         }
2336                         continue;
2337                 }
2338
2339                 path->slots[0]++;
2340
2341                 btrfs_item_key_to_cpu(leaf, &key, slot);
2342
2343                 if (key.objectid > inum)
2344                         goto out;
2345
2346                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2347                         continue;
2348
2349                 extent = btrfs_item_ptr(leaf, slot,
2350                                         struct btrfs_file_extent_item);
2351
2352                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2353                         continue;
2354
2355                 /*
2356                  * 'offset' refers to the exact key.offset,
2357                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2358                  * (key.offset - extent_offset).
2359                  */
2360                 if (key.offset != offset)
2361                         continue;
2362
2363                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2364                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2365
2366                 if (extent_offset >= old->extent_offset + old->offset +
2367                     old->len || extent_offset + num_bytes <=
2368                     old->extent_offset + old->offset)
2369                         continue;
2370                 break;
2371         }
2372
2373         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2374         if (!backref) {
2375                 ret = -ENOENT;
2376                 goto out;
2377         }
2378
2379         backref->root_id = root_id;
2380         backref->inum = inum;
2381         backref->file_pos = offset;
2382         backref->num_bytes = num_bytes;
2383         backref->extent_offset = extent_offset;
2384         backref->generation = btrfs_file_extent_generation(leaf, extent);
2385         backref->old = old;
2386         backref_insert(&new->root, backref);
2387         old->count++;
2388 out:
2389         btrfs_release_path(path);
2390         WARN_ON(ret);
2391         return ret;
2392 }
2393
2394 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2395                                    struct new_sa_defrag_extent *new)
2396 {
2397         struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2398         struct old_sa_defrag_extent *old, *tmp;
2399         int ret;
2400
2401         new->path = path;
2402
2403         list_for_each_entry_safe(old, tmp, &new->head, list) {
2404                 ret = iterate_inodes_from_logical(old->bytenr +
2405                                                   old->extent_offset, fs_info,
2406                                                   path, record_one_backref,
2407                                                   old);
2408                 if (ret < 0 && ret != -ENOENT)
2409                         return false;
2410
2411                 /* no backref to be processed for this extent */
2412                 if (!old->count) {
2413                         list_del(&old->list);
2414                         kfree(old);
2415                 }
2416         }
2417
2418         if (list_empty(&new->head))
2419                 return false;
2420
2421         return true;
2422 }
2423
2424 static int relink_is_mergable(struct extent_buffer *leaf,
2425                               struct btrfs_file_extent_item *fi,
2426                               struct new_sa_defrag_extent *new)
2427 {
2428         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2429                 return 0;
2430
2431         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2432                 return 0;
2433
2434         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2435                 return 0;
2436
2437         if (btrfs_file_extent_encryption(leaf, fi) ||
2438             btrfs_file_extent_other_encoding(leaf, fi))
2439                 return 0;
2440
2441         return 1;
2442 }
2443
2444 /*
2445  * Note the backref might has changed, and in this case we just return 0.
2446  */
2447 static noinline int relink_extent_backref(struct btrfs_path *path,
2448                                  struct sa_defrag_extent_backref *prev,
2449                                  struct sa_defrag_extent_backref *backref)
2450 {
2451         struct btrfs_file_extent_item *extent;
2452         struct btrfs_file_extent_item *item;
2453         struct btrfs_ordered_extent *ordered;
2454         struct btrfs_trans_handle *trans;
2455         struct btrfs_fs_info *fs_info;
2456         struct btrfs_root *root;
2457         struct btrfs_key key;
2458         struct extent_buffer *leaf;
2459         struct old_sa_defrag_extent *old = backref->old;
2460         struct new_sa_defrag_extent *new = old->new;
2461         struct inode *src_inode = new->inode;
2462         struct inode *inode;
2463         struct extent_state *cached = NULL;
2464         int ret = 0;
2465         u64 start;
2466         u64 len;
2467         u64 lock_start;
2468         u64 lock_end;
2469         bool merge = false;
2470         int index;
2471
2472         if (prev && prev->root_id == backref->root_id &&
2473             prev->inum == backref->inum &&
2474             prev->file_pos + prev->num_bytes == backref->file_pos)
2475                 merge = true;
2476
2477         /* step 1: get root */
2478         key.objectid = backref->root_id;
2479         key.type = BTRFS_ROOT_ITEM_KEY;
2480         key.offset = (u64)-1;
2481
2482         fs_info = BTRFS_I(src_inode)->root->fs_info;
2483         index = srcu_read_lock(&fs_info->subvol_srcu);
2484
2485         root = btrfs_read_fs_root_no_name(fs_info, &key);
2486         if (IS_ERR(root)) {
2487                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2488                 if (PTR_ERR(root) == -ENOENT)
2489                         return 0;
2490                 return PTR_ERR(root);
2491         }
2492
2493         if (btrfs_root_readonly(root)) {
2494                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2495                 return 0;
2496         }
2497
2498         /* step 2: get inode */
2499         key.objectid = backref->inum;
2500         key.type = BTRFS_INODE_ITEM_KEY;
2501         key.offset = 0;
2502
2503         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2504         if (IS_ERR(inode)) {
2505                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2506                 return 0;
2507         }
2508
2509         srcu_read_unlock(&fs_info->subvol_srcu, index);
2510
2511         /* step 3: relink backref */
2512         lock_start = backref->file_pos;
2513         lock_end = backref->file_pos + backref->num_bytes - 1;
2514         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2515                          &cached);
2516
2517         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2518         if (ordered) {
2519                 btrfs_put_ordered_extent(ordered);
2520                 goto out_unlock;
2521         }
2522
2523         trans = btrfs_join_transaction(root);
2524         if (IS_ERR(trans)) {
2525                 ret = PTR_ERR(trans);
2526                 goto out_unlock;
2527         }
2528
2529         key.objectid = backref->inum;
2530         key.type = BTRFS_EXTENT_DATA_KEY;
2531         key.offset = backref->file_pos;
2532
2533         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2534         if (ret < 0) {
2535                 goto out_free_path;
2536         } else if (ret > 0) {
2537                 ret = 0;
2538                 goto out_free_path;
2539         }
2540
2541         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2542                                 struct btrfs_file_extent_item);
2543
2544         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2545             backref->generation)
2546                 goto out_free_path;
2547
2548         btrfs_release_path(path);
2549
2550         start = backref->file_pos;
2551         if (backref->extent_offset < old->extent_offset + old->offset)
2552                 start += old->extent_offset + old->offset -
2553                          backref->extent_offset;
2554
2555         len = min(backref->extent_offset + backref->num_bytes,
2556                   old->extent_offset + old->offset + old->len);
2557         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2558
2559         ret = btrfs_drop_extents(trans, root, inode, start,
2560                                  start + len, 1);
2561         if (ret)
2562                 goto out_free_path;
2563 again:
2564         key.objectid = btrfs_ino(inode);
2565         key.type = BTRFS_EXTENT_DATA_KEY;
2566         key.offset = start;
2567
2568         path->leave_spinning = 1;
2569         if (merge) {
2570                 struct btrfs_file_extent_item *fi;
2571                 u64 extent_len;
2572                 struct btrfs_key found_key;
2573
2574                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2575                 if (ret < 0)
2576                         goto out_free_path;
2577
2578                 path->slots[0]--;
2579                 leaf = path->nodes[0];
2580                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2581
2582                 fi = btrfs_item_ptr(leaf, path->slots[0],
2583                                     struct btrfs_file_extent_item);
2584                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2585
2586                 if (extent_len + found_key.offset == start &&
2587                     relink_is_mergable(leaf, fi, new)) {
2588                         btrfs_set_file_extent_num_bytes(leaf, fi,
2589                                                         extent_len + len);
2590                         btrfs_mark_buffer_dirty(leaf);
2591                         inode_add_bytes(inode, len);
2592
2593                         ret = 1;
2594                         goto out_free_path;
2595                 } else {
2596                         merge = false;
2597                         btrfs_release_path(path);
2598                         goto again;
2599                 }
2600         }
2601
2602         ret = btrfs_insert_empty_item(trans, root, path, &key,
2603                                         sizeof(*extent));
2604         if (ret) {
2605                 btrfs_abort_transaction(trans, ret);
2606                 goto out_free_path;
2607         }
2608
2609         leaf = path->nodes[0];
2610         item = btrfs_item_ptr(leaf, path->slots[0],
2611                                 struct btrfs_file_extent_item);
2612         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2613         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2614         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2615         btrfs_set_file_extent_num_bytes(leaf, item, len);
2616         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2617         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2618         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2619         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2620         btrfs_set_file_extent_encryption(leaf, item, 0);
2621         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2622
2623         btrfs_mark_buffer_dirty(leaf);
2624         inode_add_bytes(inode, len);
2625         btrfs_release_path(path);
2626
2627         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2628                         new->disk_len, 0,
2629                         backref->root_id, backref->inum,
2630                         new->file_pos); /* start - extent_offset */
2631         if (ret) {
2632                 btrfs_abort_transaction(trans, ret);
2633                 goto out_free_path;
2634         }
2635
2636         ret = 1;
2637 out_free_path:
2638         btrfs_release_path(path);
2639         path->leave_spinning = 0;
2640         btrfs_end_transaction(trans, root);
2641 out_unlock:
2642         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2643                              &cached, GFP_NOFS);
2644         iput(inode);
2645         return ret;
2646 }
2647
2648 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2649 {
2650         struct old_sa_defrag_extent *old, *tmp;
2651
2652         if (!new)
2653                 return;
2654
2655         list_for_each_entry_safe(old, tmp, &new->head, list) {
2656                 kfree(old);
2657         }
2658         kfree(new);
2659 }
2660
2661 static void relink_file_extents(struct new_sa_defrag_extent *new)
2662 {
2663         struct btrfs_path *path;
2664         struct sa_defrag_extent_backref *backref;
2665         struct sa_defrag_extent_backref *prev = NULL;
2666         struct inode *inode;
2667         struct btrfs_root *root;
2668         struct rb_node *node;
2669         int ret;
2670
2671         inode = new->inode;
2672         root = BTRFS_I(inode)->root;
2673
2674         path = btrfs_alloc_path();
2675         if (!path)
2676                 return;
2677
2678         if (!record_extent_backrefs(path, new)) {
2679                 btrfs_free_path(path);
2680                 goto out;
2681         }
2682         btrfs_release_path(path);
2683
2684         while (1) {
2685                 node = rb_first(&new->root);
2686                 if (!node)
2687                         break;
2688                 rb_erase(node, &new->root);
2689
2690                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2691
2692                 ret = relink_extent_backref(path, prev, backref);
2693                 WARN_ON(ret < 0);
2694
2695                 kfree(prev);
2696
2697                 if (ret == 1)
2698                         prev = backref;
2699                 else
2700                         prev = NULL;
2701                 cond_resched();
2702         }
2703         kfree(prev);
2704
2705         btrfs_free_path(path);
2706 out:
2707         free_sa_defrag_extent(new);
2708
2709         atomic_dec(&root->fs_info->defrag_running);
2710         wake_up(&root->fs_info->transaction_wait);
2711 }
2712
2713 static struct new_sa_defrag_extent *
2714 record_old_file_extents(struct inode *inode,
2715                         struct btrfs_ordered_extent *ordered)
2716 {
2717         struct btrfs_root *root = BTRFS_I(inode)->root;
2718         struct btrfs_path *path;
2719         struct btrfs_key key;
2720         struct old_sa_defrag_extent *old;
2721         struct new_sa_defrag_extent *new;
2722         int ret;
2723
2724         new = kmalloc(sizeof(*new), GFP_NOFS);
2725         if (!new)
2726                 return NULL;
2727
2728         new->inode = inode;
2729         new->file_pos = ordered->file_offset;
2730         new->len = ordered->len;
2731         new->bytenr = ordered->start;
2732         new->disk_len = ordered->disk_len;
2733         new->compress_type = ordered->compress_type;
2734         new->root = RB_ROOT;
2735         INIT_LIST_HEAD(&new->head);
2736
2737         path = btrfs_alloc_path();
2738         if (!path)
2739                 goto out_kfree;
2740
2741         key.objectid = btrfs_ino(inode);
2742         key.type = BTRFS_EXTENT_DATA_KEY;
2743         key.offset = new->file_pos;
2744
2745         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2746         if (ret < 0)
2747                 goto out_free_path;
2748         if (ret > 0 && path->slots[0] > 0)
2749                 path->slots[0]--;
2750
2751         /* find out all the old extents for the file range */
2752         while (1) {
2753                 struct btrfs_file_extent_item *extent;
2754                 struct extent_buffer *l;
2755                 int slot;
2756                 u64 num_bytes;
2757                 u64 offset;
2758                 u64 end;
2759                 u64 disk_bytenr;
2760                 u64 extent_offset;
2761
2762                 l = path->nodes[0];
2763                 slot = path->slots[0];
2764
2765                 if (slot >= btrfs_header_nritems(l)) {
2766                         ret = btrfs_next_leaf(root, path);
2767                         if (ret < 0)
2768                                 goto out_free_path;
2769                         else if (ret > 0)
2770                                 break;
2771                         continue;
2772                 }
2773
2774                 btrfs_item_key_to_cpu(l, &key, slot);
2775
2776                 if (key.objectid != btrfs_ino(inode))
2777                         break;
2778                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2779                         break;
2780                 if (key.offset >= new->file_pos + new->len)
2781                         break;
2782
2783                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2784
2785                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2786                 if (key.offset + num_bytes < new->file_pos)
2787                         goto next;
2788
2789                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2790                 if (!disk_bytenr)
2791                         goto next;
2792
2793                 extent_offset = btrfs_file_extent_offset(l, extent);
2794
2795                 old = kmalloc(sizeof(*old), GFP_NOFS);
2796                 if (!old)
2797                         goto out_free_path;
2798
2799                 offset = max(new->file_pos, key.offset);
2800                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2801
2802                 old->bytenr = disk_bytenr;
2803                 old->extent_offset = extent_offset;
2804                 old->offset = offset - key.offset;
2805                 old->len = end - offset;
2806                 old->new = new;
2807                 old->count = 0;
2808                 list_add_tail(&old->list, &new->head);
2809 next:
2810                 path->slots[0]++;
2811                 cond_resched();
2812         }
2813
2814         btrfs_free_path(path);
2815         atomic_inc(&root->fs_info->defrag_running);
2816
2817         return new;
2818
2819 out_free_path:
2820         btrfs_free_path(path);
2821 out_kfree:
2822         free_sa_defrag_extent(new);
2823         return NULL;
2824 }
2825
2826 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2827                                          u64 start, u64 len)
2828 {
2829         struct btrfs_block_group_cache *cache;
2830
2831         cache = btrfs_lookup_block_group(root->fs_info, start);
2832         ASSERT(cache);
2833
2834         spin_lock(&cache->lock);
2835         cache->delalloc_bytes -= len;
2836         spin_unlock(&cache->lock);
2837
2838         btrfs_put_block_group(cache);
2839 }
2840
2841 /* as ordered data IO finishes, this gets called so we can finish
2842  * an ordered extent if the range of bytes in the file it covers are
2843  * fully written.
2844  */
2845 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2846 {
2847         struct inode *inode = ordered_extent->inode;
2848         struct btrfs_root *root = BTRFS_I(inode)->root;
2849         struct btrfs_trans_handle *trans = NULL;
2850         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2851         struct extent_state *cached_state = NULL;
2852         struct new_sa_defrag_extent *new = NULL;
2853         int compress_type = 0;
2854         int ret = 0;
2855         u64 logical_len = ordered_extent->len;
2856         bool nolock;
2857         bool truncated = false;
2858
2859         nolock = btrfs_is_free_space_inode(inode);
2860
2861         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2862                 ret = -EIO;
2863                 goto out;
2864         }
2865
2866         btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2867                                      ordered_extent->file_offset +
2868                                      ordered_extent->len - 1);
2869
2870         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2871                 truncated = true;
2872                 logical_len = ordered_extent->truncated_len;
2873                 /* Truncated the entire extent, don't bother adding */
2874                 if (!logical_len)
2875                         goto out;
2876         }
2877
2878         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2879                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2880
2881                 /*
2882                  * For mwrite(mmap + memset to write) case, we still reserve
2883                  * space for NOCOW range.
2884                  * As NOCOW won't cause a new delayed ref, just free the space
2885                  */
2886                 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2887                                        ordered_extent->len);
2888                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2889                 if (nolock)
2890                         trans = btrfs_join_transaction_nolock(root);
2891                 else
2892                         trans = btrfs_join_transaction(root);
2893                 if (IS_ERR(trans)) {
2894                         ret = PTR_ERR(trans);
2895                         trans = NULL;
2896                         goto out;
2897                 }
2898                 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2899                 ret = btrfs_update_inode_fallback(trans, root, inode);
2900                 if (ret) /* -ENOMEM or corruption */
2901                         btrfs_abort_transaction(trans, ret);
2902                 goto out;
2903         }
2904
2905         lock_extent_bits(io_tree, ordered_extent->file_offset,
2906                          ordered_extent->file_offset + ordered_extent->len - 1,
2907                          &cached_state);
2908
2909         ret = test_range_bit(io_tree, ordered_extent->file_offset,
2910                         ordered_extent->file_offset + ordered_extent->len - 1,
2911                         EXTENT_DEFRAG, 1, cached_state);
2912         if (ret) {
2913                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2914                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2915                         /* the inode is shared */
2916                         new = record_old_file_extents(inode, ordered_extent);
2917
2918                 clear_extent_bit(io_tree, ordered_extent->file_offset,
2919                         ordered_extent->file_offset + ordered_extent->len - 1,
2920                         EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2921         }
2922
2923         if (nolock)
2924                 trans = btrfs_join_transaction_nolock(root);
2925         else
2926                 trans = btrfs_join_transaction(root);
2927         if (IS_ERR(trans)) {
2928                 ret = PTR_ERR(trans);
2929                 trans = NULL;
2930                 goto out_unlock;
2931         }
2932
2933         trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2934
2935         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2936                 compress_type = ordered_extent->compress_type;
2937         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2938                 BUG_ON(compress_type);
2939                 ret = btrfs_mark_extent_written(trans, inode,
2940                                                 ordered_extent->file_offset,
2941                                                 ordered_extent->file_offset +
2942                                                 logical_len);
2943         } else {
2944                 BUG_ON(root == root->fs_info->tree_root);
2945                 ret = insert_reserved_file_extent(trans, inode,
2946                                                 ordered_extent->file_offset,
2947                                                 ordered_extent->start,
2948                                                 ordered_extent->disk_len,
2949                                                 logical_len, logical_len,
2950                                                 compress_type, 0, 0,
2951                                                 BTRFS_FILE_EXTENT_REG);
2952                 if (!ret)
2953                         btrfs_release_delalloc_bytes(root,
2954                                                      ordered_extent->start,
2955                                                      ordered_extent->disk_len);
2956         }
2957         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2958                            ordered_extent->file_offset, ordered_extent->len,
2959                            trans->transid);
2960         if (ret < 0) {
2961                 btrfs_abort_transaction(trans, ret);
2962                 goto out_unlock;
2963         }
2964
2965         add_pending_csums(trans, inode, ordered_extent->file_offset,
2966                           &ordered_extent->list);
2967
2968         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2969         ret = btrfs_update_inode_fallback(trans, root, inode);
2970         if (ret) { /* -ENOMEM or corruption */
2971                 btrfs_abort_transaction(trans, ret);
2972                 goto out_unlock;
2973         }
2974         ret = 0;
2975 out_unlock:
2976         unlock_extent_cached(io_tree, ordered_extent->file_offset,
2977                              ordered_extent->file_offset +
2978                              ordered_extent->len - 1, &cached_state, GFP_NOFS);
2979 out:
2980         if (root != root->fs_info->tree_root)
2981                 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2982         if (trans)
2983                 btrfs_end_transaction(trans, root);
2984
2985         if (ret || truncated) {
2986                 u64 start, end;
2987
2988                 if (truncated)
2989                         start = ordered_extent->file_offset + logical_len;
2990                 else
2991                         start = ordered_extent->file_offset;
2992                 end = ordered_extent->file_offset + ordered_extent->len - 1;
2993                 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2994
2995                 /* Drop the cache for the part of the extent we didn't write. */
2996                 btrfs_drop_extent_cache(inode, start, end, 0);
2997
2998                 /*
2999                  * If the ordered extent had an IOERR or something else went
3000                  * wrong we need to return the space for this ordered extent
3001                  * back to the allocator.  We only free the extent in the
3002                  * truncated case if we didn't write out the extent at all.
3003                  */
3004                 if ((ret || !logical_len) &&
3005                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3006                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3007                         btrfs_free_reserved_extent(root, ordered_extent->start,
3008                                                    ordered_extent->disk_len, 1);
3009         }
3010
3011
3012         /*
3013          * This needs to be done to make sure anybody waiting knows we are done
3014          * updating everything for this ordered extent.
3015          */
3016         btrfs_remove_ordered_extent(inode, ordered_extent);
3017
3018         /* for snapshot-aware defrag */
3019         if (new) {
3020                 if (ret) {
3021                         free_sa_defrag_extent(new);
3022                         atomic_dec(&root->fs_info->defrag_running);
3023                 } else {
3024                         relink_file_extents(new);
3025                 }
3026         }
3027
3028         /* once for us */
3029         btrfs_put_ordered_extent(ordered_extent);
3030         /* once for the tree */
3031         btrfs_put_ordered_extent(ordered_extent);
3032
3033         return ret;
3034 }
3035
3036 static void finish_ordered_fn(struct btrfs_work *work)
3037 {
3038         struct btrfs_ordered_extent *ordered_extent;
3039         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3040         btrfs_finish_ordered_io(ordered_extent);
3041 }
3042
3043 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3044                                 struct extent_state *state, int uptodate)
3045 {
3046         struct inode *inode = page->mapping->host;
3047         struct btrfs_root *root = BTRFS_I(inode)->root;
3048         struct btrfs_ordered_extent *ordered_extent = NULL;
3049         struct btrfs_workqueue *wq;
3050         btrfs_work_func_t func;
3051
3052         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3053
3054         ClearPagePrivate2(page);
3055         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3056                                             end - start + 1, uptodate))
3057                 return 0;
3058
3059         if (btrfs_is_free_space_inode(inode)) {
3060                 wq = root->fs_info->endio_freespace_worker;
3061                 func = btrfs_freespace_write_helper;
3062         } else {
3063                 wq = root->fs_info->endio_write_workers;
3064                 func = btrfs_endio_write_helper;
3065         }
3066
3067         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3068                         NULL);
3069         btrfs_queue_work(wq, &ordered_extent->work);
3070
3071         return 0;
3072 }
3073
3074 static int __readpage_endio_check(struct inode *inode,
3075                                   struct btrfs_io_bio *io_bio,
3076                                   int icsum, struct page *page,
3077                                   int pgoff, u64 start, size_t len)
3078 {
3079         char *kaddr;
3080         u32 csum_expected;
3081         u32 csum = ~(u32)0;
3082
3083         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3084
3085         kaddr = kmap_atomic(page);
3086         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3087         btrfs_csum_final(csum, (char *)&csum);
3088         if (csum != csum_expected)
3089                 goto zeroit;