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