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