]> asedeno.scripts.mit.edu Git - linux.git/blob - fs/btrfs/inode.c
f8af40d025951a8c7716e29c87050f09ccfdc154
[linux.git] / fs / btrfs / inode.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/kernel.h>
7 #include <linux/bio.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
10 #include <linux/fs.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/mpage.h>
18 #include <linux/swap.h>
19 #include <linux/writeback.h>
20 #include <linux/compat.h>
21 #include <linux/bit_spinlock.h>
22 #include <linux/xattr.h>
23 #include <linux/posix_acl.h>
24 #include <linux/falloc.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/mount.h>
28 #include <linux/btrfs.h>
29 #include <linux/blkdev.h>
30 #include <linux/posix_acl_xattr.h>
31 #include <linux/uio.h>
32 #include <linux/magic.h>
33 #include <linux/iversion.h>
34 #include <asm/unaligned.h>
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "ordered-data.h"
41 #include "xattr.h"
42 #include "tree-log.h"
43 #include "volumes.h"
44 #include "compression.h"
45 #include "locking.h"
46 #include "free-space-cache.h"
47 #include "inode-map.h"
48 #include "backref.h"
49 #include "props.h"
50 #include "qgroup.h"
51 #include "dedupe.h"
52
53 struct btrfs_iget_args {
54         struct btrfs_key *location;
55         struct btrfs_root *root;
56 };
57
58 struct btrfs_dio_data {
59         u64 reserve;
60         u64 unsubmitted_oe_range_start;
61         u64 unsubmitted_oe_range_end;
62         int overwrite;
63 };
64
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static const struct extent_io_ops btrfs_extent_io_ops;
74
75 static struct kmem_cache *btrfs_inode_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
79
80 #define S_SHIFT 12
81 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
82         [S_IFREG >> S_SHIFT]    = BTRFS_FT_REG_FILE,
83         [S_IFDIR >> S_SHIFT]    = BTRFS_FT_DIR,
84         [S_IFCHR >> S_SHIFT]    = BTRFS_FT_CHRDEV,
85         [S_IFBLK >> S_SHIFT]    = BTRFS_FT_BLKDEV,
86         [S_IFIFO >> S_SHIFT]    = BTRFS_FT_FIFO,
87         [S_IFSOCK >> S_SHIFT]   = BTRFS_FT_SOCK,
88         [S_IFLNK >> S_SHIFT]    = BTRFS_FT_SYMLINK,
89 };
90
91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 static noinline int cow_file_range(struct inode *inode,
95                                    struct page *locked_page,
96                                    u64 start, u64 end, u64 delalloc_end,
97                                    int *page_started, unsigned long *nr_written,
98                                    int unlock, struct btrfs_dedupe_hash *hash);
99 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
100                                        u64 orig_start, u64 block_start,
101                                        u64 block_len, u64 orig_block_len,
102                                        u64 ram_bytes, int compress_type,
103                                        int type);
104
105 static void __endio_write_update_ordered(struct inode *inode,
106                                          const u64 offset, const u64 bytes,
107                                          const bool uptodate);
108
109 /*
110  * Cleanup all submitted ordered extents in specified range to handle errors
111  * from the fill_dellaloc() callback.
112  *
113  * NOTE: caller must ensure that when an error happens, it can not call
114  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
115  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
116  * to be released, which we want to happen only when finishing the ordered
117  * extent (btrfs_finish_ordered_io()). Also note that the caller of the
118  * fill_delalloc() callback already does proper cleanup for the first page of
119  * the range, that is, it invokes the callback writepage_end_io_hook() for the
120  * range of the first page.
121  */
122 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
123                                                  const u64 offset,
124                                                  const u64 bytes)
125 {
126         unsigned long index = offset >> PAGE_SHIFT;
127         unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
128         struct page *page;
129
130         while (index <= end_index) {
131                 page = find_get_page(inode->i_mapping, index);
132                 index++;
133                 if (!page)
134                         continue;
135                 ClearPagePrivate2(page);
136                 put_page(page);
137         }
138         return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139                                             bytes - PAGE_SIZE, false);
140 }
141
142 static int btrfs_dirty_inode(struct inode *inode);
143
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
146 {
147         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
148 }
149 #endif
150
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152                                      struct inode *inode,  struct inode *dir,
153                                      const struct qstr *qstr)
154 {
155         int err;
156
157         err = btrfs_init_acl(trans, inode, dir);
158         if (!err)
159                 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
160         return err;
161 }
162
163 /*
164  * this does all the hard work for inserting an inline extent into
165  * the btree.  The caller should have done a btrfs_drop_extents so that
166  * no overlapping inline items exist in the btree
167  */
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169                                 struct btrfs_path *path, int extent_inserted,
170                                 struct btrfs_root *root, struct inode *inode,
171                                 u64 start, size_t size, size_t compressed_size,
172                                 int compress_type,
173                                 struct page **compressed_pages)
174 {
175         struct extent_buffer *leaf;
176         struct page *page = NULL;
177         char *kaddr;
178         unsigned long ptr;
179         struct btrfs_file_extent_item *ei;
180         int ret;
181         size_t cur_size = size;
182         unsigned long offset;
183
184         if (compressed_size && compressed_pages)
185                 cur_size = compressed_size;
186
187         inode_add_bytes(inode, size);
188
189         if (!extent_inserted) {
190                 struct btrfs_key key;
191                 size_t datasize;
192
193                 key.objectid = btrfs_ino(BTRFS_I(inode));
194                 key.offset = start;
195                 key.type = BTRFS_EXTENT_DATA_KEY;
196
197                 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198                 path->leave_spinning = 1;
199                 ret = btrfs_insert_empty_item(trans, root, path, &key,
200                                               datasize);
201                 if (ret)
202                         goto fail;
203         }
204         leaf = path->nodes[0];
205         ei = btrfs_item_ptr(leaf, path->slots[0],
206                             struct btrfs_file_extent_item);
207         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208         btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209         btrfs_set_file_extent_encryption(leaf, ei, 0);
210         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211         btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212         ptr = btrfs_file_extent_inline_start(ei);
213
214         if (compress_type != BTRFS_COMPRESS_NONE) {
215                 struct page *cpage;
216                 int i = 0;
217                 while (compressed_size > 0) {
218                         cpage = compressed_pages[i];
219                         cur_size = min_t(unsigned long, compressed_size,
220                                        PAGE_SIZE);
221
222                         kaddr = kmap_atomic(cpage);
223                         write_extent_buffer(leaf, kaddr, ptr, cur_size);
224                         kunmap_atomic(kaddr);
225
226                         i++;
227                         ptr += cur_size;
228                         compressed_size -= cur_size;
229                 }
230                 btrfs_set_file_extent_compression(leaf, ei,
231                                                   compress_type);
232         } else {
233                 page = find_get_page(inode->i_mapping,
234                                      start >> PAGE_SHIFT);
235                 btrfs_set_file_extent_compression(leaf, ei, 0);
236                 kaddr = kmap_atomic(page);
237                 offset = start & (PAGE_SIZE - 1);
238                 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239                 kunmap_atomic(kaddr);
240                 put_page(page);
241         }
242         btrfs_mark_buffer_dirty(leaf);
243         btrfs_release_path(path);
244
245         /*
246          * we're an inline extent, so nobody can
247          * extend the file past i_size without locking
248          * a page we already have locked.
249          *
250          * We must do any isize and inode updates
251          * before we unlock the pages.  Otherwise we
252          * could end up racing with unlink.
253          */
254         BTRFS_I(inode)->disk_i_size = inode->i_size;
255         ret = btrfs_update_inode(trans, root, inode);
256
257 fail:
258         return ret;
259 }
260
261
262 /*
263  * conditionally insert an inline extent into the file.  This
264  * does the checks required to make sure the data is small enough
265  * to fit as an inline extent.
266  */
267 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
268                                           u64 end, size_t compressed_size,
269                                           int compress_type,
270                                           struct page **compressed_pages)
271 {
272         struct btrfs_root *root = BTRFS_I(inode)->root;
273         struct btrfs_fs_info *fs_info = root->fs_info;
274         struct btrfs_trans_handle *trans;
275         u64 isize = i_size_read(inode);
276         u64 actual_end = min(end + 1, isize);
277         u64 inline_len = actual_end - start;
278         u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279         u64 data_len = inline_len;
280         int ret;
281         struct btrfs_path *path;
282         int extent_inserted = 0;
283         u32 extent_item_size;
284
285         if (compressed_size)
286                 data_len = compressed_size;
287
288         if (start > 0 ||
289             actual_end > fs_info->sectorsize ||
290             data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
291             (!compressed_size &&
292             (actual_end & (fs_info->sectorsize - 1)) == 0) ||
293             end + 1 < isize ||
294             data_len > fs_info->max_inline) {
295                 return 1;
296         }
297
298         path = btrfs_alloc_path();
299         if (!path)
300                 return -ENOMEM;
301
302         trans = btrfs_join_transaction(root);
303         if (IS_ERR(trans)) {
304                 btrfs_free_path(path);
305                 return PTR_ERR(trans);
306         }
307         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
308
309         if (compressed_size && compressed_pages)
310                 extent_item_size = btrfs_file_extent_calc_inline_size(
311                    compressed_size);
312         else
313                 extent_item_size = btrfs_file_extent_calc_inline_size(
314                     inline_len);
315
316         ret = __btrfs_drop_extents(trans, root, inode, path,
317                                    start, aligned_end, NULL,
318                                    1, 1, extent_item_size, &extent_inserted);
319         if (ret) {
320                 btrfs_abort_transaction(trans, ret);
321                 goto out;
322         }
323
324         if (isize > actual_end)
325                 inline_len = min_t(u64, isize, actual_end);
326         ret = insert_inline_extent(trans, path, extent_inserted,
327                                    root, inode, start,
328                                    inline_len, compressed_size,
329                                    compress_type, compressed_pages);
330         if (ret && ret != -ENOSPC) {
331                 btrfs_abort_transaction(trans, ret);
332                 goto out;
333         } else if (ret == -ENOSPC) {
334                 ret = 1;
335                 goto out;
336         }
337
338         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339         btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
340 out:
341         /*
342          * Don't forget to free the reserved space, as for inlined extent
343          * it won't count as data extent, free them directly here.
344          * And at reserve time, it's always aligned to page size, so
345          * just free one page here.
346          */
347         btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
348         btrfs_free_path(path);
349         btrfs_end_transaction(trans);
350         return ret;
351 }
352
353 struct async_extent {
354         u64 start;
355         u64 ram_size;
356         u64 compressed_size;
357         struct page **pages;
358         unsigned long nr_pages;
359         int compress_type;
360         struct list_head list;
361 };
362
363 struct async_cow {
364         struct inode *inode;
365         struct btrfs_root *root;
366         struct page *locked_page;
367         u64 start;
368         u64 end;
369         unsigned int write_flags;
370         struct list_head extents;
371         struct btrfs_work work;
372 };
373
374 static noinline int add_async_extent(struct async_cow *cow,
375                                      u64 start, u64 ram_size,
376                                      u64 compressed_size,
377                                      struct page **pages,
378                                      unsigned long nr_pages,
379                                      int compress_type)
380 {
381         struct async_extent *async_extent;
382
383         async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384         BUG_ON(!async_extent); /* -ENOMEM */
385         async_extent->start = start;
386         async_extent->ram_size = ram_size;
387         async_extent->compressed_size = compressed_size;
388         async_extent->pages = pages;
389         async_extent->nr_pages = nr_pages;
390         async_extent->compress_type = compress_type;
391         list_add_tail(&async_extent->list, &cow->extents);
392         return 0;
393 }
394
395 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
396 {
397         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
398
399         /* force compress */
400         if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
401                 return 1;
402         /* defrag ioctl */
403         if (BTRFS_I(inode)->defrag_compress)
404                 return 1;
405         /* bad compression ratios */
406         if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
407                 return 0;
408         if (btrfs_test_opt(fs_info, COMPRESS) ||
409             BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
410             BTRFS_I(inode)->prop_compress)
411                 return btrfs_compress_heuristic(inode, start, end);
412         return 0;
413 }
414
415 static inline void inode_should_defrag(struct btrfs_inode *inode,
416                 u64 start, u64 end, u64 num_bytes, u64 small_write)
417 {
418         /* If this is a small write inside eof, kick off a defrag */
419         if (num_bytes < small_write &&
420             (start > 0 || end + 1 < inode->disk_i_size))
421                 btrfs_add_inode_defrag(NULL, inode);
422 }
423
424 /*
425  * we create compressed extents in two phases.  The first
426  * phase compresses a range of pages that have already been
427  * locked (both pages and state bits are locked).
428  *
429  * This is done inside an ordered work queue, and the compression
430  * is spread across many cpus.  The actual IO submission is step
431  * two, and the ordered work queue takes care of making sure that
432  * happens in the same order things were put onto the queue by
433  * writepages and friends.
434  *
435  * If this code finds it can't get good compression, it puts an
436  * entry onto the work queue to write the uncompressed bytes.  This
437  * makes sure that both compressed inodes and uncompressed inodes
438  * are written in the same order that the flusher thread sent them
439  * down.
440  */
441 static noinline void compress_file_range(struct inode *inode,
442                                         struct page *locked_page,
443                                         u64 start, u64 end,
444                                         struct async_cow *async_cow,
445                                         int *num_added)
446 {
447         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
448         u64 blocksize = fs_info->sectorsize;
449         u64 actual_end;
450         u64 isize = i_size_read(inode);
451         int ret = 0;
452         struct page **pages = NULL;
453         unsigned long nr_pages;
454         unsigned long total_compressed = 0;
455         unsigned long total_in = 0;
456         int i;
457         int will_compress;
458         int compress_type = fs_info->compress_type;
459         int redirty = 0;
460
461         inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
462                         SZ_16K);
463
464         actual_end = min_t(u64, isize, end + 1);
465 again:
466         will_compress = 0;
467         nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
468         BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
469         nr_pages = min_t(unsigned long, nr_pages,
470                         BTRFS_MAX_COMPRESSED / PAGE_SIZE);
471
472         /*
473          * we don't want to send crud past the end of i_size through
474          * compression, that's just a waste of CPU time.  So, if the
475          * end of the file is before the start of our current
476          * requested range of bytes, we bail out to the uncompressed
477          * cleanup code that can deal with all of this.
478          *
479          * It isn't really the fastest way to fix things, but this is a
480          * very uncommon corner.
481          */
482         if (actual_end <= start)
483                 goto cleanup_and_bail_uncompressed;
484
485         total_compressed = actual_end - start;
486
487         /*
488          * skip compression for a small file range(<=blocksize) that
489          * isn't an inline extent, since it doesn't save disk space at all.
490          */
491         if (total_compressed <= blocksize &&
492            (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
493                 goto cleanup_and_bail_uncompressed;
494
495         total_compressed = min_t(unsigned long, total_compressed,
496                         BTRFS_MAX_UNCOMPRESSED);
497         total_in = 0;
498         ret = 0;
499
500         /*
501          * we do compression for mount -o compress and when the
502          * inode has not been flagged as nocompress.  This flag can
503          * change at any time if we discover bad compression ratios.
504          */
505         if (inode_need_compress(inode, start, end)) {
506                 WARN_ON(pages);
507                 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
508                 if (!pages) {
509                         /* just bail out to the uncompressed code */
510                         goto cont;
511                 }
512
513                 if (BTRFS_I(inode)->defrag_compress)
514                         compress_type = BTRFS_I(inode)->defrag_compress;
515                 else if (BTRFS_I(inode)->prop_compress)
516                         compress_type = BTRFS_I(inode)->prop_compress;
517
518                 /*
519                  * we need to call clear_page_dirty_for_io on each
520                  * page in the range.  Otherwise applications with the file
521                  * mmap'd can wander in and change the page contents while
522                  * we are compressing them.
523                  *
524                  * If the compression fails for any reason, we set the pages
525                  * dirty again later on.
526                  *
527                  * Note that the remaining part is redirtied, the start pointer
528                  * has moved, the end is the original one.
529                  */
530                 if (!redirty) {
531                         extent_range_clear_dirty_for_io(inode, start, end);
532                         redirty = 1;
533                 }
534
535                 /* Compression level is applied here and only here */
536                 ret = btrfs_compress_pages(
537                         compress_type | (fs_info->compress_level << 4),
538                                            inode->i_mapping, start,
539                                            pages,
540                                            &nr_pages,
541                                            &total_in,
542                                            &total_compressed);
543
544                 if (!ret) {
545                         unsigned long offset = total_compressed &
546                                 (PAGE_SIZE - 1);
547                         struct page *page = pages[nr_pages - 1];
548                         char *kaddr;
549
550                         /* zero the tail end of the last page, we might be
551                          * sending it down to disk
552                          */
553                         if (offset) {
554                                 kaddr = kmap_atomic(page);
555                                 memset(kaddr + offset, 0,
556                                        PAGE_SIZE - offset);
557                                 kunmap_atomic(kaddr);
558                         }
559                         will_compress = 1;
560                 }
561         }
562 cont:
563         if (start == 0) {
564                 /* lets try to make an inline extent */
565                 if (ret || total_in < actual_end) {
566                         /* we didn't compress the entire range, try
567                          * to make an uncompressed inline extent.
568                          */
569                         ret = cow_file_range_inline(inode, start, end, 0,
570                                                     BTRFS_COMPRESS_NONE, NULL);
571                 } else {
572                         /* try making a compressed inline extent */
573                         ret = cow_file_range_inline(inode, start, end,
574                                                     total_compressed,
575                                                     compress_type, pages);
576                 }
577                 if (ret <= 0) {
578                         unsigned long clear_flags = EXTENT_DELALLOC |
579                                 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
580                                 EXTENT_DO_ACCOUNTING;
581                         unsigned long page_error_op;
582
583                         page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
584
585                         /*
586                          * inline extent creation worked or returned error,
587                          * we don't need to create any more async work items.
588                          * Unlock and free up our temp pages.
589                          *
590                          * We use DO_ACCOUNTING here because we need the
591                          * delalloc_release_metadata to be done _after_ we drop
592                          * our outstanding extent for clearing delalloc for this
593                          * range.
594                          */
595                         extent_clear_unlock_delalloc(inode, start, end, end,
596                                                      NULL, clear_flags,
597                                                      PAGE_UNLOCK |
598                                                      PAGE_CLEAR_DIRTY |
599                                                      PAGE_SET_WRITEBACK |
600                                                      page_error_op |
601                                                      PAGE_END_WRITEBACK);
602                         goto free_pages_out;
603                 }
604         }
605
606         if (will_compress) {
607                 /*
608                  * we aren't doing an inline extent round the compressed size
609                  * up to a block size boundary so the allocator does sane
610                  * things
611                  */
612                 total_compressed = ALIGN(total_compressed, blocksize);
613
614                 /*
615                  * one last check to make sure the compression is really a
616                  * win, compare the page count read with the blocks on disk,
617                  * compression must free at least one sector size
618                  */
619                 total_in = ALIGN(total_in, PAGE_SIZE);
620                 if (total_compressed + blocksize <= total_in) {
621                         *num_added += 1;
622
623                         /*
624                          * The async work queues will take care of doing actual
625                          * allocation on disk for these compressed pages, and
626                          * will submit them to the elevator.
627                          */
628                         add_async_extent(async_cow, start, total_in,
629                                         total_compressed, pages, nr_pages,
630                                         compress_type);
631
632                         if (start + total_in < end) {
633                                 start += total_in;
634                                 pages = NULL;
635                                 cond_resched();
636                                 goto again;
637                         }
638                         return;
639                 }
640         }
641         if (pages) {
642                 /*
643                  * the compression code ran but failed to make things smaller,
644                  * free any pages it allocated and our page pointer array
645                  */
646                 for (i = 0; i < nr_pages; i++) {
647                         WARN_ON(pages[i]->mapping);
648                         put_page(pages[i]);
649                 }
650                 kfree(pages);
651                 pages = NULL;
652                 total_compressed = 0;
653                 nr_pages = 0;
654
655                 /* flag the file so we don't compress in the future */
656                 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
657                     !(BTRFS_I(inode)->prop_compress)) {
658                         BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
659                 }
660         }
661 cleanup_and_bail_uncompressed:
662         /*
663          * No compression, but we still need to write the pages in the file
664          * we've been given so far.  redirty the locked page if it corresponds
665          * to our extent and set things up for the async work queue to run
666          * cow_file_range to do the normal delalloc dance.
667          */
668         if (page_offset(locked_page) >= start &&
669             page_offset(locked_page) <= end)
670                 __set_page_dirty_nobuffers(locked_page);
671                 /* unlocked later on in the async handlers */
672
673         if (redirty)
674                 extent_range_redirty_for_io(inode, start, end);
675         add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
676                          BTRFS_COMPRESS_NONE);
677         *num_added += 1;
678
679         return;
680
681 free_pages_out:
682         for (i = 0; i < nr_pages; i++) {
683                 WARN_ON(pages[i]->mapping);
684                 put_page(pages[i]);
685         }
686         kfree(pages);
687 }
688
689 static void free_async_extent_pages(struct async_extent *async_extent)
690 {
691         int i;
692
693         if (!async_extent->pages)
694                 return;
695
696         for (i = 0; i < async_extent->nr_pages; i++) {
697                 WARN_ON(async_extent->pages[i]->mapping);
698                 put_page(async_extent->pages[i]);
699         }
700         kfree(async_extent->pages);
701         async_extent->nr_pages = 0;
702         async_extent->pages = NULL;
703 }
704
705 /*
706  * phase two of compressed writeback.  This is the ordered portion
707  * of the code, which only gets called in the order the work was
708  * queued.  We walk all the async extents created by compress_file_range
709  * and send them down to the disk.
710  */
711 static noinline void submit_compressed_extents(struct inode *inode,
712                                               struct async_cow *async_cow)
713 {
714         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
715         struct async_extent *async_extent;
716         u64 alloc_hint = 0;
717         struct btrfs_key ins;
718         struct extent_map *em;
719         struct btrfs_root *root = BTRFS_I(inode)->root;
720         struct extent_io_tree *io_tree;
721         int ret = 0;
722
723 again:
724         while (!list_empty(&async_cow->extents)) {
725                 async_extent = list_entry(async_cow->extents.next,
726                                           struct async_extent, list);
727                 list_del(&async_extent->list);
728
729                 io_tree = &BTRFS_I(inode)->io_tree;
730
731 retry:
732                 /* did the compression code fall back to uncompressed IO? */
733                 if (!async_extent->pages) {
734                         int page_started = 0;
735                         unsigned long nr_written = 0;
736
737                         lock_extent(io_tree, async_extent->start,
738                                          async_extent->start +
739                                          async_extent->ram_size - 1);
740
741                         /* allocate blocks */
742                         ret = cow_file_range(inode, async_cow->locked_page,
743                                              async_extent->start,
744                                              async_extent->start +
745                                              async_extent->ram_size - 1,
746                                              async_extent->start +
747                                              async_extent->ram_size - 1,
748                                              &page_started, &nr_written, 0,
749                                              NULL);
750
751                         /* JDM XXX */
752
753                         /*
754                          * if page_started, cow_file_range inserted an
755                          * inline extent and took care of all the unlocking
756                          * and IO for us.  Otherwise, we need to submit
757                          * all those pages down to the drive.
758                          */
759                         if (!page_started && !ret)
760                                 extent_write_locked_range(inode,
761                                                   async_extent->start,
762                                                   async_extent->start +
763                                                   async_extent->ram_size - 1,
764                                                   WB_SYNC_ALL);
765                         else if (ret)
766                                 unlock_page(async_cow->locked_page);
767                         kfree(async_extent);
768                         cond_resched();
769                         continue;
770                 }
771
772                 lock_extent(io_tree, async_extent->start,
773                             async_extent->start + async_extent->ram_size - 1);
774
775                 ret = btrfs_reserve_extent(root, async_extent->ram_size,
776                                            async_extent->compressed_size,
777                                            async_extent->compressed_size,
778                                            0, alloc_hint, &ins, 1, 1);
779                 if (ret) {
780                         free_async_extent_pages(async_extent);
781
782                         if (ret == -ENOSPC) {
783                                 unlock_extent(io_tree, async_extent->start,
784                                               async_extent->start +
785                                               async_extent->ram_size - 1);
786
787                                 /*
788                                  * we need to redirty the pages if we decide to
789                                  * fallback to uncompressed IO, otherwise we
790                                  * will not submit these pages down to lower
791                                  * layers.
792                                  */
793                                 extent_range_redirty_for_io(inode,
794                                                 async_extent->start,
795                                                 async_extent->start +
796                                                 async_extent->ram_size - 1);
797
798                                 goto retry;
799                         }
800                         goto out_free;
801                 }
802                 /*
803                  * here we're doing allocation and writeback of the
804                  * compressed pages
805                  */
806                 em = create_io_em(inode, async_extent->start,
807                                   async_extent->ram_size, /* len */
808                                   async_extent->start, /* orig_start */
809                                   ins.objectid, /* block_start */
810                                   ins.offset, /* block_len */
811                                   ins.offset, /* orig_block_len */
812                                   async_extent->ram_size, /* ram_bytes */
813                                   async_extent->compress_type,
814                                   BTRFS_ORDERED_COMPRESSED);
815                 if (IS_ERR(em))
816                         /* ret value is not necessary due to void function */
817                         goto out_free_reserve;
818                 free_extent_map(em);
819
820                 ret = btrfs_add_ordered_extent_compress(inode,
821                                                 async_extent->start,
822                                                 ins.objectid,
823                                                 async_extent->ram_size,
824                                                 ins.offset,
825                                                 BTRFS_ORDERED_COMPRESSED,
826                                                 async_extent->compress_type);
827                 if (ret) {
828                         btrfs_drop_extent_cache(BTRFS_I(inode),
829                                                 async_extent->start,
830                                                 async_extent->start +
831                                                 async_extent->ram_size - 1, 0);
832                         goto out_free_reserve;
833                 }
834                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
835
836                 /*
837                  * clear dirty, set writeback and unlock the pages.
838                  */
839                 extent_clear_unlock_delalloc(inode, async_extent->start,
840                                 async_extent->start +
841                                 async_extent->ram_size - 1,
842                                 async_extent->start +
843                                 async_extent->ram_size - 1,
844                                 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
845                                 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
846                                 PAGE_SET_WRITEBACK);
847                 if (btrfs_submit_compressed_write(inode,
848                                     async_extent->start,
849                                     async_extent->ram_size,
850                                     ins.objectid,
851                                     ins.offset, async_extent->pages,
852                                     async_extent->nr_pages,
853                                     async_cow->write_flags)) {
854                         struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
855                         struct page *p = async_extent->pages[0];
856                         const u64 start = async_extent->start;
857                         const u64 end = start + async_extent->ram_size - 1;
858
859                         p->mapping = inode->i_mapping;
860                         tree->ops->writepage_end_io_hook(p, start, end,
861                                                          NULL, 0);
862                         p->mapping = NULL;
863                         extent_clear_unlock_delalloc(inode, start, end, end,
864                                                      NULL, 0,
865                                                      PAGE_END_WRITEBACK |
866                                                      PAGE_SET_ERROR);
867                         free_async_extent_pages(async_extent);
868                 }
869                 alloc_hint = ins.objectid + ins.offset;
870                 kfree(async_extent);
871                 cond_resched();
872         }
873         return;
874 out_free_reserve:
875         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
877 out_free:
878         extent_clear_unlock_delalloc(inode, async_extent->start,
879                                      async_extent->start +
880                                      async_extent->ram_size - 1,
881                                      async_extent->start +
882                                      async_extent->ram_size - 1,
883                                      NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884                                      EXTENT_DELALLOC_NEW |
885                                      EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
886                                      PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887                                      PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
888                                      PAGE_SET_ERROR);
889         free_async_extent_pages(async_extent);
890         kfree(async_extent);
891         goto again;
892 }
893
894 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
895                                       u64 num_bytes)
896 {
897         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
898         struct extent_map *em;
899         u64 alloc_hint = 0;
900
901         read_lock(&em_tree->lock);
902         em = search_extent_mapping(em_tree, start, num_bytes);
903         if (em) {
904                 /*
905                  * if block start isn't an actual block number then find the
906                  * first block in this inode and use that as a hint.  If that
907                  * block is also bogus then just don't worry about it.
908                  */
909                 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
910                         free_extent_map(em);
911                         em = search_extent_mapping(em_tree, 0, 0);
912                         if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
913                                 alloc_hint = em->block_start;
914                         if (em)
915                                 free_extent_map(em);
916                 } else {
917                         alloc_hint = em->block_start;
918                         free_extent_map(em);
919                 }
920         }
921         read_unlock(&em_tree->lock);
922
923         return alloc_hint;
924 }
925
926 /*
927  * when extent_io.c finds a delayed allocation range in the file,
928  * the call backs end up in this code.  The basic idea is to
929  * allocate extents on disk for the range, and create ordered data structs
930  * in ram to track those extents.
931  *
932  * locked_page is the page that writepage had locked already.  We use
933  * it to make sure we don't do extra locks or unlocks.
934  *
935  * *page_started is set to one if we unlock locked_page and do everything
936  * required to start IO on it.  It may be clean and already done with
937  * IO when we return.
938  */
939 static noinline int cow_file_range(struct inode *inode,
940                                    struct page *locked_page,
941                                    u64 start, u64 end, u64 delalloc_end,
942                                    int *page_started, unsigned long *nr_written,
943                                    int unlock, struct btrfs_dedupe_hash *hash)
944 {
945         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946         struct btrfs_root *root = BTRFS_I(inode)->root;
947         u64 alloc_hint = 0;
948         u64 num_bytes;
949         unsigned long ram_size;
950         u64 cur_alloc_size = 0;
951         u64 blocksize = fs_info->sectorsize;
952         struct btrfs_key ins;
953         struct extent_map *em;
954         unsigned clear_bits;
955         unsigned long page_ops;
956         bool extent_reserved = false;
957         int ret = 0;
958
959         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
960                 WARN_ON_ONCE(1);
961                 ret = -EINVAL;
962                 goto out_unlock;
963         }
964
965         num_bytes = ALIGN(end - start + 1, blocksize);
966         num_bytes = max(blocksize,  num_bytes);
967         ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
968
969         inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
970
971         if (start == 0) {
972                 /* lets try to make an inline extent */
973                 ret = cow_file_range_inline(inode, start, end, 0,
974                                             BTRFS_COMPRESS_NONE, NULL);
975                 if (ret == 0) {
976                         /*
977                          * We use DO_ACCOUNTING here because we need the
978                          * delalloc_release_metadata to be run _after_ we drop
979                          * our outstanding extent for clearing delalloc for this
980                          * range.
981                          */
982                         extent_clear_unlock_delalloc(inode, start, end,
983                                      delalloc_end, NULL,
984                                      EXTENT_LOCKED | EXTENT_DELALLOC |
985                                      EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986                                      EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987                                      PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
988                                      PAGE_END_WRITEBACK);
989                         *nr_written = *nr_written +
990                              (end - start + PAGE_SIZE) / PAGE_SIZE;
991                         *page_started = 1;
992                         goto out;
993                 } else if (ret < 0) {
994                         goto out_unlock;
995                 }
996         }
997
998         alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999         btrfs_drop_extent_cache(BTRFS_I(inode), start,
1000                         start + num_bytes - 1, 0);
1001
1002         while (num_bytes > 0) {
1003                 cur_alloc_size = num_bytes;
1004                 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005                                            fs_info->sectorsize, 0, alloc_hint,
1006                                            &ins, 1, 1);
1007                 if (ret < 0)
1008                         goto out_unlock;
1009                 cur_alloc_size = ins.offset;
1010                 extent_reserved = true;
1011
1012                 ram_size = ins.offset;
1013                 em = create_io_em(inode, start, ins.offset, /* len */
1014                                   start, /* orig_start */
1015                                   ins.objectid, /* block_start */
1016                                   ins.offset, /* block_len */
1017                                   ins.offset, /* orig_block_len */
1018                                   ram_size, /* ram_bytes */
1019                                   BTRFS_COMPRESS_NONE, /* compress_type */
1020                                   BTRFS_ORDERED_REGULAR /* type */);
1021                 if (IS_ERR(em))
1022                         goto out_reserve;
1023                 free_extent_map(em);
1024
1025                 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1026                                                ram_size, cur_alloc_size, 0);
1027                 if (ret)
1028                         goto out_drop_extent_cache;
1029
1030                 if (root->root_key.objectid ==
1031                     BTRFS_DATA_RELOC_TREE_OBJECTID) {
1032                         ret = btrfs_reloc_clone_csums(inode, start,
1033                                                       cur_alloc_size);
1034                         /*
1035                          * Only drop cache here, and process as normal.
1036                          *
1037                          * We must not allow extent_clear_unlock_delalloc()
1038                          * at out_unlock label to free meta of this ordered
1039                          * extent, as its meta should be freed by
1040                          * btrfs_finish_ordered_io().
1041                          *
1042                          * So we must continue until @start is increased to
1043                          * skip current ordered extent.
1044                          */
1045                         if (ret)
1046                                 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1047                                                 start + ram_size - 1, 0);
1048                 }
1049
1050                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1051
1052                 /* we're not doing compressed IO, don't unlock the first
1053                  * page (which the caller expects to stay locked), don't
1054                  * clear any dirty bits and don't set any writeback bits
1055                  *
1056                  * Do set the Private2 bit so we know this page was properly
1057                  * setup for writepage
1058                  */
1059                 page_ops = unlock ? PAGE_UNLOCK : 0;
1060                 page_ops |= PAGE_SET_PRIVATE2;
1061
1062                 extent_clear_unlock_delalloc(inode, start,
1063                                              start + ram_size - 1,
1064                                              delalloc_end, locked_page,
1065                                              EXTENT_LOCKED | EXTENT_DELALLOC,
1066                                              page_ops);
1067                 if (num_bytes < cur_alloc_size)
1068                         num_bytes = 0;
1069                 else
1070                         num_bytes -= cur_alloc_size;
1071                 alloc_hint = ins.objectid + ins.offset;
1072                 start += cur_alloc_size;
1073                 extent_reserved = false;
1074
1075                 /*
1076                  * btrfs_reloc_clone_csums() error, since start is increased
1077                  * extent_clear_unlock_delalloc() at out_unlock label won't
1078                  * free metadata of current ordered extent, we're OK to exit.
1079                  */
1080                 if (ret)
1081                         goto out_unlock;
1082         }
1083 out:
1084         return ret;
1085
1086 out_drop_extent_cache:
1087         btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1088 out_reserve:
1089         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1090         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1091 out_unlock:
1092         clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1093                 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1094         page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1095                 PAGE_END_WRITEBACK;
1096         /*
1097          * If we reserved an extent for our delalloc range (or a subrange) and
1098          * failed to create the respective ordered extent, then it means that
1099          * when we reserved the extent we decremented the extent's size from
1100          * the data space_info's bytes_may_use counter and incremented the
1101          * space_info's bytes_reserved counter by the same amount. We must make
1102          * sure extent_clear_unlock_delalloc() does not try to decrement again
1103          * the data space_info's bytes_may_use counter, therefore we do not pass
1104          * it the flag EXTENT_CLEAR_DATA_RESV.
1105          */
1106         if (extent_reserved) {
1107                 extent_clear_unlock_delalloc(inode, start,
1108                                              start + cur_alloc_size,
1109                                              start + cur_alloc_size,
1110                                              locked_page,
1111                                              clear_bits,
1112                                              page_ops);
1113                 start += cur_alloc_size;
1114                 if (start >= end)
1115                         goto out;
1116         }
1117         extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1118                                      locked_page,
1119                                      clear_bits | EXTENT_CLEAR_DATA_RESV,
1120                                      page_ops);
1121         goto out;
1122 }
1123
1124 /*
1125  * work queue call back to started compression on a file and pages
1126  */
1127 static noinline void async_cow_start(struct btrfs_work *work)
1128 {
1129         struct async_cow *async_cow;
1130         int num_added = 0;
1131         async_cow = container_of(work, struct async_cow, work);
1132
1133         compress_file_range(async_cow->inode, async_cow->locked_page,
1134                             async_cow->start, async_cow->end, async_cow,
1135                             &num_added);
1136         if (num_added == 0) {
1137                 btrfs_add_delayed_iput(async_cow->inode);
1138                 async_cow->inode = NULL;
1139         }
1140 }
1141
1142 /*
1143  * work queue call back to submit previously compressed pages
1144  */
1145 static noinline void async_cow_submit(struct btrfs_work *work)
1146 {
1147         struct btrfs_fs_info *fs_info;
1148         struct async_cow *async_cow;
1149         struct btrfs_root *root;
1150         unsigned long nr_pages;
1151
1152         async_cow = container_of(work, struct async_cow, work);
1153
1154         root = async_cow->root;
1155         fs_info = root->fs_info;
1156         nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1157                 PAGE_SHIFT;
1158
1159         /* atomic_sub_return implies a barrier */
1160         if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1161             5 * SZ_1M)
1162                 cond_wake_up_nomb(&fs_info->async_submit_wait);
1163
1164         if (async_cow->inode)
1165                 submit_compressed_extents(async_cow->inode, async_cow);
1166 }
1167
1168 static noinline void async_cow_free(struct btrfs_work *work)
1169 {
1170         struct async_cow *async_cow;
1171         async_cow = container_of(work, struct async_cow, work);
1172         if (async_cow->inode)
1173                 btrfs_add_delayed_iput(async_cow->inode);
1174         kfree(async_cow);
1175 }
1176
1177 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1178                                 u64 start, u64 end, int *page_started,
1179                                 unsigned long *nr_written,
1180                                 unsigned int write_flags)
1181 {
1182         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1183         struct async_cow *async_cow;
1184         struct btrfs_root *root = BTRFS_I(inode)->root;
1185         unsigned long nr_pages;
1186         u64 cur_end;
1187
1188         clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1189                          1, 0, NULL);
1190         while (start < end) {
1191                 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1192                 BUG_ON(!async_cow); /* -ENOMEM */
1193                 async_cow->inode = igrab(inode);
1194                 async_cow->root = root;
1195                 async_cow->locked_page = locked_page;
1196                 async_cow->start = start;
1197                 async_cow->write_flags = write_flags;
1198
1199                 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1200                     !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1201                         cur_end = end;
1202                 else
1203                         cur_end = min(end, start + SZ_512K - 1);
1204
1205                 async_cow->end = cur_end;
1206                 INIT_LIST_HEAD(&async_cow->extents);
1207
1208                 btrfs_init_work(&async_cow->work,
1209                                 btrfs_delalloc_helper,
1210                                 async_cow_start, async_cow_submit,
1211                                 async_cow_free);
1212
1213                 nr_pages = (cur_end - start + PAGE_SIZE) >>
1214                         PAGE_SHIFT;
1215                 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1216
1217                 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1218
1219                 *nr_written += nr_pages;
1220                 start = cur_end + 1;
1221         }
1222         *page_started = 1;
1223         return 0;
1224 }
1225
1226 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1227                                         u64 bytenr, u64 num_bytes)
1228 {
1229         int ret;
1230         struct btrfs_ordered_sum *sums;
1231         LIST_HEAD(list);
1232
1233         ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1234                                        bytenr + num_bytes - 1, &list, 0);
1235         if (ret == 0 && list_empty(&list))
1236                 return 0;
1237
1238         while (!list_empty(&list)) {
1239                 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1240                 list_del(&sums->list);
1241                 kfree(sums);
1242         }
1243         if (ret < 0)
1244                 return ret;
1245         return 1;
1246 }
1247
1248 /*
1249  * when nowcow writeback call back.  This checks for snapshots or COW copies
1250  * of the extents that exist in the file, and COWs the file as required.
1251  *
1252  * If no cow copies or snapshots exist, we write directly to the existing
1253  * blocks on disk
1254  */
1255 static noinline int run_delalloc_nocow(struct inode *inode,
1256                                        struct page *locked_page,
1257                               u64 start, u64 end, int *page_started, int force,
1258                               unsigned long *nr_written)
1259 {
1260         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1261         struct btrfs_root *root = BTRFS_I(inode)->root;
1262         struct extent_buffer *leaf;
1263         struct btrfs_path *path;
1264         struct btrfs_file_extent_item *fi;
1265         struct btrfs_key found_key;
1266         struct extent_map *em;
1267         u64 cow_start;
1268         u64 cur_offset;
1269         u64 extent_end;
1270         u64 extent_offset;
1271         u64 disk_bytenr;
1272         u64 num_bytes;
1273         u64 disk_num_bytes;
1274         u64 ram_bytes;
1275         int extent_type;
1276         int ret, err;
1277         int type;
1278         int nocow;
1279         int check_prev = 1;
1280         bool nolock;
1281         u64 ino = btrfs_ino(BTRFS_I(inode));
1282
1283         path = btrfs_alloc_path();
1284         if (!path) {
1285                 extent_clear_unlock_delalloc(inode, start, end, end,
1286                                              locked_page,
1287                                              EXTENT_LOCKED | EXTENT_DELALLOC |
1288                                              EXTENT_DO_ACCOUNTING |
1289                                              EXTENT_DEFRAG, PAGE_UNLOCK |
1290                                              PAGE_CLEAR_DIRTY |
1291                                              PAGE_SET_WRITEBACK |
1292                                              PAGE_END_WRITEBACK);
1293                 return -ENOMEM;
1294         }
1295
1296         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1297
1298         cow_start = (u64)-1;
1299         cur_offset = start;
1300         while (1) {
1301                 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1302                                                cur_offset, 0);
1303                 if (ret < 0)
1304                         goto error;
1305                 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1306                         leaf = path->nodes[0];
1307                         btrfs_item_key_to_cpu(leaf, &found_key,
1308                                               path->slots[0] - 1);
1309                         if (found_key.objectid == ino &&
1310                             found_key.type == BTRFS_EXTENT_DATA_KEY)
1311                                 path->slots[0]--;
1312                 }
1313                 check_prev = 0;
1314 next_slot:
1315                 leaf = path->nodes[0];
1316                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1317                         ret = btrfs_next_leaf(root, path);
1318                         if (ret < 0) {
1319                                 if (cow_start != (u64)-1)
1320                                         cur_offset = cow_start;
1321                                 goto error;
1322                         }
1323                         if (ret > 0)
1324                                 break;
1325                         leaf = path->nodes[0];
1326                 }
1327
1328                 nocow = 0;
1329                 disk_bytenr = 0;
1330                 num_bytes = 0;
1331                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1332
1333                 if (found_key.objectid > ino)
1334                         break;
1335                 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1336                     found_key.type < BTRFS_EXTENT_DATA_KEY) {
1337                         path->slots[0]++;
1338                         goto next_slot;
1339                 }
1340                 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1341                     found_key.offset > end)
1342                         break;
1343
1344                 if (found_key.offset > cur_offset) {
1345                         extent_end = found_key.offset;
1346                         extent_type = 0;
1347                         goto out_check;
1348                 }
1349
1350                 fi = btrfs_item_ptr(leaf, path->slots[0],
1351                                     struct btrfs_file_extent_item);
1352                 extent_type = btrfs_file_extent_type(leaf, fi);
1353
1354                 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1355                 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1356                     extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1357                         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1358                         extent_offset = btrfs_file_extent_offset(leaf, fi);
1359                         extent_end = found_key.offset +
1360                                 btrfs_file_extent_num_bytes(leaf, fi);
1361                         disk_num_bytes =
1362                                 btrfs_file_extent_disk_num_bytes(leaf, fi);
1363                         if (extent_end <= start) {
1364                                 path->slots[0]++;
1365                                 goto next_slot;
1366                         }
1367                         if (disk_bytenr == 0)
1368                                 goto out_check;
1369                         if (btrfs_file_extent_compression(leaf, fi) ||
1370                             btrfs_file_extent_encryption(leaf, fi) ||
1371                             btrfs_file_extent_other_encoding(leaf, fi))
1372                                 goto out_check;
1373                         if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1374                                 goto out_check;
1375                         if (btrfs_extent_readonly(fs_info, disk_bytenr))
1376                                 goto out_check;
1377                         ret = btrfs_cross_ref_exist(root, ino,
1378                                                     found_key.offset -
1379                                                     extent_offset, disk_bytenr);
1380                         if (ret) {
1381                                 /*
1382                                  * ret could be -EIO if the above fails to read
1383                                  * metadata.
1384                                  */
1385                                 if (ret < 0) {
1386                                         if (cow_start != (u64)-1)
1387                                                 cur_offset = cow_start;
1388                                         goto error;
1389                                 }
1390
1391                                 WARN_ON_ONCE(nolock);
1392                                 goto out_check;
1393                         }
1394                         disk_bytenr += extent_offset;
1395                         disk_bytenr += cur_offset - found_key.offset;
1396                         num_bytes = min(end + 1, extent_end) - cur_offset;
1397                         /*
1398                          * if there are pending snapshots for this root,
1399                          * we fall into common COW way.
1400                          */
1401                         if (!nolock) {
1402                                 err = btrfs_start_write_no_snapshotting(root);
1403                                 if (!err)
1404                                         goto out_check;
1405                         }
1406                         /*
1407                          * force cow if csum exists in the range.
1408                          * this ensure that csum for a given extent are
1409                          * either valid or do not exist.
1410                          */
1411                         ret = csum_exist_in_range(fs_info, disk_bytenr,
1412                                                   num_bytes);
1413                         if (ret) {
1414                                 if (!nolock)
1415                                         btrfs_end_write_no_snapshotting(root);
1416
1417                                 /*
1418                                  * ret could be -EIO if the above fails to read
1419                                  * metadata.
1420                                  */
1421                                 if (ret < 0) {
1422                                         if (cow_start != (u64)-1)
1423                                                 cur_offset = cow_start;
1424                                         goto error;
1425                                 }
1426                                 WARN_ON_ONCE(nolock);
1427                                 goto out_check;
1428                         }
1429                         if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1430                                 if (!nolock)
1431                                         btrfs_end_write_no_snapshotting(root);
1432                                 goto out_check;
1433                         }
1434                         nocow = 1;
1435                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1436                         extent_end = found_key.offset +
1437                                 btrfs_file_extent_inline_len(leaf,
1438                                                      path->slots[0], fi);
1439                         extent_end = ALIGN(extent_end,
1440                                            fs_info->sectorsize);
1441                 } else {
1442                         BUG_ON(1);
1443                 }
1444 out_check:
1445                 if (extent_end <= start) {
1446                         path->slots[0]++;
1447                         if (!nolock && nocow)
1448                                 btrfs_end_write_no_snapshotting(root);
1449                         if (nocow)
1450                                 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1451                         goto next_slot;
1452                 }
1453                 if (!nocow) {
1454                         if (cow_start == (u64)-1)
1455                                 cow_start = cur_offset;
1456                         cur_offset = extent_end;
1457                         if (cur_offset > end)
1458                                 break;
1459                         path->slots[0]++;
1460                         goto next_slot;
1461                 }
1462
1463                 btrfs_release_path(path);
1464                 if (cow_start != (u64)-1) {
1465                         ret = cow_file_range(inode, locked_page,
1466                                              cow_start, found_key.offset - 1,
1467                                              end, page_started, nr_written, 1,
1468                                              NULL);
1469                         if (ret) {
1470                                 if (!nolock && nocow)
1471                                         btrfs_end_write_no_snapshotting(root);
1472                                 if (nocow)
1473                                         btrfs_dec_nocow_writers(fs_info,
1474                                                                 disk_bytenr);
1475                                 goto error;
1476                         }
1477                         cow_start = (u64)-1;
1478                 }
1479
1480                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1481                         u64 orig_start = found_key.offset - extent_offset;
1482
1483                         em = create_io_em(inode, cur_offset, num_bytes,
1484                                           orig_start,
1485                                           disk_bytenr, /* block_start */
1486                                           num_bytes, /* block_len */
1487                                           disk_num_bytes, /* orig_block_len */
1488                                           ram_bytes, BTRFS_COMPRESS_NONE,
1489                                           BTRFS_ORDERED_PREALLOC);
1490                         if (IS_ERR(em)) {
1491                                 if (!nolock && nocow)
1492                                         btrfs_end_write_no_snapshotting(root);
1493                                 if (nocow)
1494                                         btrfs_dec_nocow_writers(fs_info,
1495                                                                 disk_bytenr);
1496                                 ret = PTR_ERR(em);
1497                                 goto error;
1498                         }
1499                         free_extent_map(em);
1500                 }
1501
1502                 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1503                         type = BTRFS_ORDERED_PREALLOC;
1504                 } else {
1505                         type = BTRFS_ORDERED_NOCOW;
1506                 }
1507
1508                 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1509                                                num_bytes, num_bytes, type);
1510                 if (nocow)
1511                         btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1512                 BUG_ON(ret); /* -ENOMEM */
1513
1514                 if (root->root_key.objectid ==
1515                     BTRFS_DATA_RELOC_TREE_OBJECTID)
1516                         /*
1517                          * Error handled later, as we must prevent
1518                          * extent_clear_unlock_delalloc() in error handler
1519                          * from freeing metadata of created ordered extent.
1520                          */
1521                         ret = btrfs_reloc_clone_csums(inode, cur_offset,
1522                                                       num_bytes);
1523
1524                 extent_clear_unlock_delalloc(inode, cur_offset,
1525                                              cur_offset + num_bytes - 1, end,
1526                                              locked_page, EXTENT_LOCKED |
1527                                              EXTENT_DELALLOC |
1528                                              EXTENT_CLEAR_DATA_RESV,
1529                                              PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1530
1531                 if (!nolock && nocow)
1532                         btrfs_end_write_no_snapshotting(root);
1533                 cur_offset = extent_end;
1534
1535                 /*
1536                  * btrfs_reloc_clone_csums() error, now we're OK to call error
1537                  * handler, as metadata for created ordered extent will only
1538                  * be freed by btrfs_finish_ordered_io().
1539                  */
1540                 if (ret)
1541                         goto error;
1542                 if (cur_offset > end)
1543                         break;
1544         }
1545         btrfs_release_path(path);
1546
1547         if (cur_offset <= end && cow_start == (u64)-1) {
1548                 cow_start = cur_offset;
1549                 cur_offset = end;
1550         }
1551
1552         if (cow_start != (u64)-1) {
1553                 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1554                                      page_started, nr_written, 1, NULL);
1555                 if (ret)
1556                         goto error;
1557         }
1558
1559 error:
1560         if (ret && cur_offset < end)
1561                 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1562                                              locked_page, EXTENT_LOCKED |
1563                                              EXTENT_DELALLOC | EXTENT_DEFRAG |
1564                                              EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1565                                              PAGE_CLEAR_DIRTY |
1566                                              PAGE_SET_WRITEBACK |
1567                                              PAGE_END_WRITEBACK);
1568         btrfs_free_path(path);
1569         return ret;
1570 }
1571
1572 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1573 {
1574
1575         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1576             !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1577                 return 0;
1578
1579         /*
1580          * @defrag_bytes is a hint value, no spinlock held here,
1581          * if is not zero, it means the file is defragging.
1582          * Force cow if given extent needs to be defragged.
1583          */
1584         if (BTRFS_I(inode)->defrag_bytes &&
1585             test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1586                            EXTENT_DEFRAG, 0, NULL))
1587                 return 1;
1588
1589         return 0;
1590 }
1591
1592 /*
1593  * extent_io.c call back to do delayed allocation processing
1594  */
1595 static int run_delalloc_range(void *private_data, struct page *locked_page,
1596                               u64 start, u64 end, int *page_started,
1597                               unsigned long *nr_written,
1598                               struct writeback_control *wbc)
1599 {
1600         struct inode *inode = private_data;
1601         int ret;
1602         int force_cow = need_force_cow(inode, start, end);
1603         unsigned int write_flags = wbc_to_write_flags(wbc);
1604
1605         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1606                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1607                                          page_started, 1, nr_written);
1608         } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1609                 ret = run_delalloc_nocow(inode, locked_page, start, end,
1610                                          page_started, 0, nr_written);
1611         } else if (!inode_need_compress(inode, start, end)) {
1612                 ret = cow_file_range(inode, locked_page, start, end, end,
1613                                       page_started, nr_written, 1, NULL);
1614         } else {
1615                 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1616                         &BTRFS_I(inode)->runtime_flags);
1617                 ret = cow_file_range_async(inode, locked_page, start, end,
1618                                            page_started, nr_written,
1619                                            write_flags);
1620         }
1621         if (ret)
1622                 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1623         return ret;
1624 }
1625
1626 static void btrfs_split_extent_hook(void *private_data,
1627                                     struct extent_state *orig, u64 split)
1628 {
1629         struct inode *inode = private_data;
1630         u64 size;
1631
1632         /* not delalloc, ignore it */
1633         if (!(orig->state & EXTENT_DELALLOC))
1634                 return;
1635
1636         size = orig->end - orig->start + 1;
1637         if (size > BTRFS_MAX_EXTENT_SIZE) {
1638                 u32 num_extents;
1639                 u64 new_size;
1640
1641                 /*
1642                  * See the explanation in btrfs_merge_extent_hook, the same
1643                  * applies here, just in reverse.
1644                  */
1645                 new_size = orig->end - split + 1;
1646                 num_extents = count_max_extents(new_size);
1647                 new_size = split - orig->start;
1648                 num_extents += count_max_extents(new_size);
1649                 if (count_max_extents(size) >= num_extents)
1650                         return;
1651         }
1652
1653         spin_lock(&BTRFS_I(inode)->lock);
1654         btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1655         spin_unlock(&BTRFS_I(inode)->lock);
1656 }
1657
1658 /*
1659  * extent_io.c merge_extent_hook, used to track merged delayed allocation
1660  * extents so we can keep track of new extents that are just merged onto old
1661  * extents, such as when we are doing sequential writes, so we can properly
1662  * account for the metadata space we'll need.
1663  */
1664 static void btrfs_merge_extent_hook(void *private_data,
1665                                     struct extent_state *new,
1666                                     struct extent_state *other)
1667 {
1668         struct inode *inode = private_data;
1669         u64 new_size, old_size;
1670         u32 num_extents;
1671
1672         /* not delalloc, ignore it */
1673         if (!(other->state & EXTENT_DELALLOC))
1674                 return;
1675
1676         if (new->start > other->start)
1677                 new_size = new->end - other->start + 1;
1678         else
1679                 new_size = other->end - new->start + 1;
1680
1681         /* we're not bigger than the max, unreserve the space and go */
1682         if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1683                 spin_lock(&BTRFS_I(inode)->lock);
1684                 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1685                 spin_unlock(&BTRFS_I(inode)->lock);
1686                 return;
1687         }
1688
1689         /*
1690          * We have to add up either side to figure out how many extents were
1691          * accounted for before we merged into one big extent.  If the number of
1692          * extents we accounted for is <= the amount we need for the new range
1693          * then we can return, otherwise drop.  Think of it like this
1694          *
1695          * [ 4k][MAX_SIZE]
1696          *
1697          * So we've grown the extent by a MAX_SIZE extent, this would mean we
1698          * need 2 outstanding extents, on one side we have 1 and the other side
1699          * we have 1 so they are == and we can return.  But in this case
1700          *
1701          * [MAX_SIZE+4k][MAX_SIZE+4k]
1702          *
1703          * Each range on their own accounts for 2 extents, but merged together
1704          * they are only 3 extents worth of accounting, so we need to drop in
1705          * this case.
1706          */
1707         old_size = other->end - other->start + 1;
1708         num_extents = count_max_extents(old_size);
1709         old_size = new->end - new->start + 1;
1710         num_extents += count_max_extents(old_size);
1711         if (count_max_extents(new_size) >= num_extents)
1712                 return;
1713
1714         spin_lock(&BTRFS_I(inode)->lock);
1715         btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1716         spin_unlock(&BTRFS_I(inode)->lock);
1717 }
1718
1719 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1720                                       struct inode *inode)
1721 {
1722         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1723
1724         spin_lock(&root->delalloc_lock);
1725         if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1726                 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1727                               &root->delalloc_inodes);
1728                 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1729                         &BTRFS_I(inode)->runtime_flags);
1730                 root->nr_delalloc_inodes++;
1731                 if (root->nr_delalloc_inodes == 1) {
1732                         spin_lock(&fs_info->delalloc_root_lock);
1733                         BUG_ON(!list_empty(&root->delalloc_root));
1734                         list_add_tail(&root->delalloc_root,
1735                                       &fs_info->delalloc_roots);
1736                         spin_unlock(&fs_info->delalloc_root_lock);
1737                 }
1738         }
1739         spin_unlock(&root->delalloc_lock);
1740 }
1741
1742
1743 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1744                                 struct btrfs_inode *inode)
1745 {
1746         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1747
1748         if (!list_empty(&inode->delalloc_inodes)) {
1749                 list_del_init(&inode->delalloc_inodes);
1750                 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1751                           &inode->runtime_flags);
1752                 root->nr_delalloc_inodes--;
1753                 if (!root->nr_delalloc_inodes) {
1754                         ASSERT(list_empty(&root->delalloc_inodes));
1755                         spin_lock(&fs_info->delalloc_root_lock);
1756                         BUG_ON(list_empty(&root->delalloc_root));
1757                         list_del_init(&root->delalloc_root);
1758                         spin_unlock(&fs_info->delalloc_root_lock);
1759                 }
1760         }
1761 }
1762
1763 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1764                                      struct btrfs_inode *inode)
1765 {
1766         spin_lock(&root->delalloc_lock);
1767         __btrfs_del_delalloc_inode(root, inode);
1768         spin_unlock(&root->delalloc_lock);
1769 }
1770
1771 /*
1772  * extent_io.c set_bit_hook, used to track delayed allocation
1773  * bytes in this file, and to maintain the list of inodes that
1774  * have pending delalloc work to be done.
1775  */
1776 static void btrfs_set_bit_hook(void *private_data,
1777                                struct extent_state *state, unsigned *bits)
1778 {
1779         struct inode *inode = private_data;
1780
1781         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1782
1783         if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1784                 WARN_ON(1);
1785         /*
1786          * set_bit and clear bit hooks normally require _irqsave/restore
1787          * but in this case, we are only testing for the DELALLOC
1788          * bit, which is only set or cleared with irqs on
1789          */
1790         if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1791                 struct btrfs_root *root = BTRFS_I(inode)->root;
1792                 u64 len = state->end + 1 - state->start;
1793                 u32 num_extents = count_max_extents(len);
1794                 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1795
1796                 spin_lock(&BTRFS_I(inode)->lock);
1797                 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1798                 spin_unlock(&BTRFS_I(inode)->lock);
1799
1800                 /* For sanity tests */
1801                 if (btrfs_is_testing(fs_info))
1802                         return;
1803
1804                 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1805                                          fs_info->delalloc_batch);
1806                 spin_lock(&BTRFS_I(inode)->lock);
1807                 BTRFS_I(inode)->delalloc_bytes += len;
1808                 if (*bits & EXTENT_DEFRAG)
1809                         BTRFS_I(inode)->defrag_bytes += len;
1810                 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1811                                          &BTRFS_I(inode)->runtime_flags))
1812                         btrfs_add_delalloc_inodes(root, inode);
1813                 spin_unlock(&BTRFS_I(inode)->lock);
1814         }
1815
1816         if (!(state->state & EXTENT_DELALLOC_NEW) &&
1817             (*bits & EXTENT_DELALLOC_NEW)) {
1818                 spin_lock(&BTRFS_I(inode)->lock);
1819                 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1820                         state->start;
1821                 spin_unlock(&BTRFS_I(inode)->lock);
1822         }
1823 }
1824
1825 /*
1826  * extent_io.c clear_bit_hook, see set_bit_hook for why
1827  */
1828 static void btrfs_clear_bit_hook(void *private_data,
1829                                  struct extent_state *state,
1830                                  unsigned *bits)
1831 {
1832         struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1833         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1834         u64 len = state->end + 1 - state->start;
1835         u32 num_extents = count_max_extents(len);
1836
1837         if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1838                 spin_lock(&inode->lock);
1839                 inode->defrag_bytes -= len;
1840                 spin_unlock(&inode->lock);
1841         }
1842
1843         /*
1844          * set_bit and clear bit hooks normally require _irqsave/restore
1845          * but in this case, we are only testing for the DELALLOC
1846          * bit, which is only set or cleared with irqs on
1847          */
1848         if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1849                 struct btrfs_root *root = inode->root;
1850                 bool do_list = !btrfs_is_free_space_inode(inode);
1851
1852                 spin_lock(&inode->lock);
1853                 btrfs_mod_outstanding_extents(inode, -num_extents);
1854                 spin_unlock(&inode->lock);
1855
1856                 /*
1857                  * We don't reserve metadata space for space cache inodes so we
1858                  * don't need to call dellalloc_release_metadata if there is an
1859                  * error.
1860                  */
1861                 if (*bits & EXTENT_CLEAR_META_RESV &&
1862                     root != fs_info->tree_root)
1863                         btrfs_delalloc_release_metadata(inode, len, false);
1864
1865                 /* For sanity tests. */
1866                 if (btrfs_is_testing(fs_info))
1867                         return;
1868
1869                 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1870                     do_list && !(state->state & EXTENT_NORESERVE) &&
1871                     (*bits & EXTENT_CLEAR_DATA_RESV))
1872                         btrfs_free_reserved_data_space_noquota(
1873                                         &inode->vfs_inode,
1874                                         state->start, len);
1875
1876                 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1877                                          fs_info->delalloc_batch);
1878                 spin_lock(&inode->lock);
1879                 inode->delalloc_bytes -= len;
1880                 if (do_list && inode->delalloc_bytes == 0 &&
1881                     test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1882                                         &inode->runtime_flags))
1883                         btrfs_del_delalloc_inode(root, inode);
1884                 spin_unlock(&inode->lock);
1885         }
1886
1887         if ((state->state & EXTENT_DELALLOC_NEW) &&
1888             (*bits & EXTENT_DELALLOC_NEW)) {
1889                 spin_lock(&inode->lock);
1890                 ASSERT(inode->new_delalloc_bytes >= len);
1891                 inode->new_delalloc_bytes -= len;
1892                 spin_unlock(&inode->lock);
1893         }
1894 }
1895
1896 /*
1897  * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1898  * we don't create bios that span stripes or chunks
1899  *
1900  * return 1 if page cannot be merged to bio
1901  * return 0 if page can be merged to bio
1902  * return error otherwise
1903  */
1904 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1905                          size_t size, struct bio *bio,
1906                          unsigned long bio_flags)
1907 {
1908         struct inode *inode = page->mapping->host;
1909         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1910         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1911         u64 length = 0;
1912         u64 map_length;
1913         int ret;
1914
1915         if (bio_flags & EXTENT_BIO_COMPRESSED)
1916                 return 0;
1917
1918         length = bio->bi_iter.bi_size;
1919         map_length = length;
1920         ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1921                               NULL, 0);
1922         if (ret < 0)
1923                 return ret;
1924         if (map_length < length + size)
1925                 return 1;
1926         return 0;
1927 }
1928
1929 /*
1930  * in order to insert checksums into the metadata in large chunks,
1931  * we wait until bio submission time.   All the pages in the bio are
1932  * checksummed and sums are attached onto the ordered extent record.
1933  *
1934  * At IO completion time the cums attached on the ordered extent record
1935  * are inserted into the btree
1936  */
1937 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1938                                     u64 bio_offset)
1939 {
1940         struct inode *inode = private_data;
1941         blk_status_t ret = 0;
1942
1943         ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1944         BUG_ON(ret); /* -ENOMEM */
1945         return 0;
1946 }
1947
1948 /*
1949  * in order to insert checksums into the metadata in large chunks,
1950  * we wait until bio submission time.   All the pages in the bio are
1951  * checksummed and sums are attached onto the ordered extent record.
1952  *
1953  * At IO completion time the cums attached on the ordered extent record
1954  * are inserted into the btree
1955  */
1956 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1957                           int mirror_num)
1958 {
1959         struct inode *inode = private_data;
1960         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1961         blk_status_t ret;
1962
1963         ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1964         if (ret) {
1965                 bio->bi_status = ret;
1966                 bio_endio(bio);
1967         }
1968         return ret;
1969 }
1970
1971 /*
1972  * extent_io.c submission hook. This does the right thing for csum calculation
1973  * on write, or reading the csums from the tree before a read.
1974  *
1975  * Rules about async/sync submit,
1976  * a) read:                             sync submit
1977  *
1978  * b) write without checksum:           sync submit
1979  *
1980  * c) write with checksum:
1981  *    c-1) if bio is issued by fsync:   sync submit
1982  *         (sync_writers != 0)
1983  *
1984  *    c-2) if root is reloc root:       sync submit
1985  *         (only in case of buffered IO)
1986  *
1987  *    c-3) otherwise:                   async submit
1988  */
1989 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1990                                  int mirror_num, unsigned long bio_flags,
1991                                  u64 bio_offset)
1992 {
1993         struct inode *inode = private_data;
1994         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1995         struct btrfs_root *root = BTRFS_I(inode)->root;
1996         enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1997         blk_status_t ret = 0;
1998         int skip_sum;
1999         int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2000
2001         skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2002
2003         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2004                 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2005
2006         if (bio_op(bio) != REQ_OP_WRITE) {
2007                 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2008                 if (ret)
2009                         goto out;
2010
2011                 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2012                         ret = btrfs_submit_compressed_read(inode, bio,
2013                                                            mirror_num,
2014                                                            bio_flags);
2015                         goto out;
2016                 } else if (!skip_sum) {
2017                         ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2018                         if (ret)
2019                                 goto out;
2020                 }
2021                 goto mapit;
2022         } else if (async && !skip_sum) {
2023                 /* csum items have already been cloned */
2024                 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2025                         goto mapit;
2026                 /* we're doing a write, do the async checksumming */
2027                 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2028                                           bio_offset, inode,
2029                                           btrfs_submit_bio_start,
2030                                           btrfs_submit_bio_done);
2031                 goto out;
2032         } else if (!skip_sum) {
2033                 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2034                 if (ret)
2035                         goto out;
2036         }
2037
2038 mapit:
2039         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2040
2041 out:
2042         if (ret) {
2043                 bio->bi_status = ret;
2044                 bio_endio(bio);
2045         }
2046         return ret;
2047 }
2048
2049 /*
2050  * given a list of ordered sums record them in the inode.  This happens
2051  * at IO completion time based on sums calculated at bio submission time.
2052  */
2053 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2054                              struct inode *inode, struct list_head *list)
2055 {
2056         struct btrfs_ordered_sum *sum;
2057         int ret;
2058
2059         list_for_each_entry(sum, list, list) {
2060                 trans->adding_csums = true;
2061                 ret = btrfs_csum_file_blocks(trans,
2062                        BTRFS_I(inode)->root->fs_info->csum_root, sum);
2063                 trans->adding_csums = false;
2064                 if (ret)
2065                         return ret;
2066         }
2067         return 0;
2068 }
2069
2070 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2071                               unsigned int extra_bits,
2072                               struct extent_state **cached_state, int dedupe)
2073 {
2074         WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2075         return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2076                                    extra_bits, cached_state);
2077 }
2078
2079 /* see btrfs_writepage_start_hook for details on why this is required */
2080 struct btrfs_writepage_fixup {
2081         struct page *page;
2082         struct btrfs_work work;
2083 };
2084
2085 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2086 {
2087         struct btrfs_writepage_fixup *fixup;
2088         struct btrfs_ordered_extent *ordered;
2089         struct extent_state *cached_state = NULL;
2090         struct extent_changeset *data_reserved = NULL;
2091         struct page *page;
2092         struct inode *inode;
2093         u64 page_start;
2094         u64 page_end;
2095         int ret;
2096
2097         fixup = container_of(work, struct btrfs_writepage_fixup, work);
2098         page = fixup->page;
2099 again:
2100         lock_page(page);
2101         if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2102                 ClearPageChecked(page);
2103                 goto out_page;
2104         }
2105
2106         inode = page->mapping->host;
2107         page_start = page_offset(page);
2108         page_end = page_offset(page) + PAGE_SIZE - 1;
2109
2110         lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2111                          &cached_state);
2112
2113         /* already ordered? We're done */
2114         if (PagePrivate2(page))
2115                 goto out;
2116
2117         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2118                                         PAGE_SIZE);
2119         if (ordered) {
2120                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2121                                      page_end, &cached_state);
2122                 unlock_page(page);
2123                 btrfs_start_ordered_extent(inode, ordered, 1);
2124                 btrfs_put_ordered_extent(ordered);
2125                 goto again;
2126         }
2127
2128         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2129                                            PAGE_SIZE);
2130         if (ret) {
2131                 mapping_set_error(page->mapping, ret);
2132                 end_extent_writepage(page, ret, page_start, page_end);
2133                 ClearPageChecked(page);
2134                 goto out;
2135          }
2136
2137         ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2138                                         &cached_state, 0);
2139         if (ret) {
2140                 mapping_set_error(page->mapping, ret);
2141                 end_extent_writepage(page, ret, page_start, page_end);
2142                 ClearPageChecked(page);
2143                 goto out;
2144         }
2145
2146         ClearPageChecked(page);
2147         set_page_dirty(page);
2148         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2149 out:
2150         unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2151                              &cached_state);
2152 out_page:
2153         unlock_page(page);
2154         put_page(page);
2155         kfree(fixup);
2156         extent_changeset_free(data_reserved);
2157 }
2158
2159 /*
2160  * There are a few paths in the higher layers of the kernel that directly
2161  * set the page dirty bit without asking the filesystem if it is a
2162  * good idea.  This causes problems because we want to make sure COW
2163  * properly happens and the data=ordered rules are followed.
2164  *
2165  * In our case any range that doesn't have the ORDERED bit set
2166  * hasn't been properly setup for IO.  We kick off an async process
2167  * to fix it up.  The async helper will wait for ordered extents, set
2168  * the delalloc bit and make it safe to write the page.
2169  */
2170 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2171 {
2172         struct inode *inode = page->mapping->host;
2173         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2174         struct btrfs_writepage_fixup *fixup;
2175
2176         /* this page is properly in the ordered list */
2177         if (TestClearPagePrivate2(page))
2178                 return 0;
2179
2180         if (PageChecked(page))
2181                 return -EAGAIN;
2182
2183         fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2184         if (!fixup)
2185                 return -EAGAIN;
2186
2187         SetPageChecked(page);
2188         get_page(page);
2189         btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2190                         btrfs_writepage_fixup_worker, NULL, NULL);
2191         fixup->page = page;
2192         btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2193         return -EBUSY;
2194 }
2195
2196 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2197                                        struct inode *inode, u64 file_pos,
2198                                        u64 disk_bytenr, u64 disk_num_bytes,
2199                                        u64 num_bytes, u64 ram_bytes,
2200                                        u8 compression, u8 encryption,
2201                                        u16 other_encoding, int extent_type)
2202 {
2203         struct btrfs_root *root = BTRFS_I(inode)->root;
2204         struct btrfs_file_extent_item *fi;
2205         struct btrfs_path *path;
2206         struct extent_buffer *leaf;
2207         struct btrfs_key ins;
2208         u64 qg_released;
2209         int extent_inserted = 0;
2210         int ret;
2211
2212         path = btrfs_alloc_path();
2213         if (!path)
2214                 return -ENOMEM;
2215
2216         /*
2217          * we may be replacing one extent in the tree with another.
2218          * The new extent is pinned in the extent map, and we don't want
2219          * to drop it from the cache until it is completely in the btree.
2220          *
2221          * So, tell btrfs_drop_extents to leave this extent in the cache.
2222          * the caller is expected to unpin it and allow it to be merged
2223          * with the others.
2224          */
2225         ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2226                                    file_pos + num_bytes, NULL, 0,
2227                                    1, sizeof(*fi), &extent_inserted);
2228         if (ret)
2229                 goto out;
2230
2231         if (!extent_inserted) {
2232                 ins.objectid = btrfs_ino(BTRFS_I(inode));
2233                 ins.offset = file_pos;
2234                 ins.type = BTRFS_EXTENT_DATA_KEY;
2235
2236                 path->leave_spinning = 1;
2237                 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2238                                               sizeof(*fi));
2239                 if (ret)
2240                         goto out;
2241         }
2242         leaf = path->nodes[0];
2243         fi = btrfs_item_ptr(leaf, path->slots[0],
2244                             struct btrfs_file_extent_item);
2245         btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2246         btrfs_set_file_extent_type(leaf, fi, extent_type);
2247         btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2248         btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2249         btrfs_set_file_extent_offset(leaf, fi, 0);
2250         btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2251         btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2252         btrfs_set_file_extent_compression(leaf, fi, compression);
2253         btrfs_set_file_extent_encryption(leaf, fi, encryption);
2254         btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2255
2256         btrfs_mark_buffer_dirty(leaf);
2257         btrfs_release_path(path);
2258
2259         inode_add_bytes(inode, num_bytes);
2260
2261         ins.objectid = disk_bytenr;
2262         ins.offset = disk_num_bytes;
2263         ins.type = BTRFS_EXTENT_ITEM_KEY;
2264
2265         /*
2266          * Release the reserved range from inode dirty range map, as it is
2267          * already moved into delayed_ref_head
2268          */
2269         ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2270         if (ret < 0)
2271                 goto out;
2272         qg_released = ret;
2273         ret = btrfs_alloc_reserved_file_extent(trans, root,
2274                                                btrfs_ino(BTRFS_I(inode)),
2275                                                file_pos, qg_released, &ins);
2276 out:
2277         btrfs_free_path(path);
2278
2279         return ret;
2280 }
2281
2282 /* snapshot-aware defrag */
2283 struct sa_defrag_extent_backref {
2284         struct rb_node node;
2285         struct old_sa_defrag_extent *old;
2286         u64 root_id;
2287         u64 inum;
2288         u64 file_pos;
2289         u64 extent_offset;
2290         u64 num_bytes;
2291         u64 generation;
2292 };
2293
2294 struct old_sa_defrag_extent {
2295         struct list_head list;
2296         struct new_sa_defrag_extent *new;
2297
2298         u64 extent_offset;
2299         u64 bytenr;
2300         u64 offset;
2301         u64 len;
2302         int count;
2303 };
2304
2305 struct new_sa_defrag_extent {
2306         struct rb_root root;
2307         struct list_head head;
2308         struct btrfs_path *path;
2309         struct inode *inode;
2310         u64 file_pos;
2311         u64 len;
2312         u64 bytenr;
2313         u64 disk_len;
2314         u8 compress_type;
2315 };
2316
2317 static int backref_comp(struct sa_defrag_extent_backref *b1,
2318                         struct sa_defrag_extent_backref *b2)
2319 {
2320         if (b1->root_id < b2->root_id)
2321                 return -1;
2322         else if (b1->root_id > b2->root_id)
2323                 return 1;
2324
2325         if (b1->inum < b2->inum)
2326                 return -1;
2327         else if (b1->inum > b2->inum)
2328                 return 1;
2329
2330         if (b1->file_pos < b2->file_pos)
2331                 return -1;
2332         else if (b1->file_pos > b2->file_pos)
2333                 return 1;
2334
2335         /*
2336          * [------------------------------] ===> (a range of space)
2337          *     |<--->|   |<---->| =============> (fs/file tree A)
2338          * |<---------------------------->| ===> (fs/file tree B)
2339          *
2340          * A range of space can refer to two file extents in one tree while
2341          * refer to only one file extent in another tree.
2342          *
2343          * So we may process a disk offset more than one time(two extents in A)
2344          * and locate at the same extent(one extent in B), then insert two same
2345          * backrefs(both refer to the extent in B).
2346          */
2347         return 0;
2348 }
2349
2350 static void backref_insert(struct rb_root *root,
2351                            struct sa_defrag_extent_backref *backref)
2352 {
2353         struct rb_node **p = &root->rb_node;
2354         struct rb_node *parent = NULL;
2355         struct sa_defrag_extent_backref *entry;
2356         int ret;
2357
2358         while (*p) {
2359                 parent = *p;
2360                 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2361
2362                 ret = backref_comp(backref, entry);
2363                 if (ret < 0)
2364                         p = &(*p)->rb_left;
2365                 else
2366                         p = &(*p)->rb_right;
2367         }
2368
2369         rb_link_node(&backref->node, parent, p);
2370         rb_insert_color(&backref->node, root);
2371 }
2372
2373 /*
2374  * Note the backref might has changed, and in this case we just return 0.
2375  */
2376 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2377                                        void *ctx)
2378 {
2379         struct btrfs_file_extent_item *extent;
2380         struct old_sa_defrag_extent *old = ctx;
2381         struct new_sa_defrag_extent *new = old->new;
2382         struct btrfs_path *path = new->path;
2383         struct btrfs_key key;
2384         struct btrfs_root *root;
2385         struct sa_defrag_extent_backref *backref;
2386         struct extent_buffer *leaf;
2387         struct inode *inode = new->inode;
2388         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2389         int slot;
2390         int ret;
2391         u64 extent_offset;
2392         u64 num_bytes;
2393
2394         if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2395             inum == btrfs_ino(BTRFS_I(inode)))
2396                 return 0;
2397
2398         key.objectid = root_id;
2399         key.type = BTRFS_ROOT_ITEM_KEY;
2400         key.offset = (u64)-1;
2401
2402         root = btrfs_read_fs_root_no_name(fs_info, &key);
2403         if (IS_ERR(root)) {
2404                 if (PTR_ERR(root) == -ENOENT)
2405                         return 0;
2406                 WARN_ON(1);
2407                 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2408                          inum, offset, root_id);
2409                 return PTR_ERR(root);
2410         }
2411
2412         key.objectid = inum;
2413         key.type = BTRFS_EXTENT_DATA_KEY;
2414         if (offset > (u64)-1 << 32)
2415                 key.offset = 0;
2416         else
2417                 key.offset = offset;
2418
2419         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2420         if (WARN_ON(ret < 0))
2421                 return ret;
2422         ret = 0;
2423
2424         while (1) {
2425                 cond_resched();
2426
2427                 leaf = path->nodes[0];
2428                 slot = path->slots[0];
2429
2430                 if (slot >= btrfs_header_nritems(leaf)) {
2431                         ret = btrfs_next_leaf(root, path);
2432                         if (ret < 0) {
2433                                 goto out;
2434                         } else if (ret > 0) {
2435                                 ret = 0;
2436                                 goto out;
2437                         }
2438                         continue;
2439                 }
2440
2441                 path->slots[0]++;
2442
2443                 btrfs_item_key_to_cpu(leaf, &key, slot);
2444
2445                 if (key.objectid > inum)
2446                         goto out;
2447
2448                 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2449                         continue;
2450
2451                 extent = btrfs_item_ptr(leaf, slot,
2452                                         struct btrfs_file_extent_item);
2453
2454                 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2455                         continue;
2456
2457                 /*
2458                  * 'offset' refers to the exact key.offset,
2459                  * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2460                  * (key.offset - extent_offset).
2461                  */
2462                 if (key.offset != offset)
2463                         continue;
2464
2465                 extent_offset = btrfs_file_extent_offset(leaf, extent);
2466                 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2467
2468                 if (extent_offset >= old->extent_offset + old->offset +
2469                     old->len || extent_offset + num_bytes <=
2470                     old->extent_offset + old->offset)
2471                         continue;
2472                 break;
2473         }
2474
2475         backref = kmalloc(sizeof(*backref), GFP_NOFS);
2476         if (!backref) {
2477                 ret = -ENOENT;
2478                 goto out;
2479         }
2480
2481         backref->root_id = root_id;
2482         backref->inum = inum;
2483         backref->file_pos = offset;
2484         backref->num_bytes = num_bytes;
2485         backref->extent_offset = extent_offset;
2486         backref->generation = btrfs_file_extent_generation(leaf, extent);
2487         backref->old = old;
2488         backref_insert(&new->root, backref);
2489         old->count++;
2490 out:
2491         btrfs_release_path(path);
2492         WARN_ON(ret);
2493         return ret;
2494 }
2495
2496 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2497                                    struct new_sa_defrag_extent *new)
2498 {
2499         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2500         struct old_sa_defrag_extent *old, *tmp;
2501         int ret;
2502
2503         new->path = path;
2504
2505         list_for_each_entry_safe(old, tmp, &new->head, list) {
2506                 ret = iterate_inodes_from_logical(old->bytenr +
2507                                                   old->extent_offset, fs_info,
2508                                                   path, record_one_backref,
2509                                                   old, false);
2510                 if (ret < 0 && ret != -ENOENT)
2511                         return false;
2512
2513                 /* no backref to be processed for this extent */
2514                 if (!old->count) {
2515                         list_del(&old->list);
2516                         kfree(old);
2517                 }
2518         }
2519
2520         if (list_empty(&new->head))
2521                 return false;
2522
2523         return true;
2524 }
2525
2526 static int relink_is_mergable(struct extent_buffer *leaf,
2527                               struct btrfs_file_extent_item *fi,
2528                               struct new_sa_defrag_extent *new)
2529 {
2530         if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2531                 return 0;
2532
2533         if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2534                 return 0;
2535
2536         if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2537                 return 0;
2538
2539         if (btrfs_file_extent_encryption(leaf, fi) ||
2540             btrfs_file_extent_other_encoding(leaf, fi))
2541                 return 0;
2542
2543         return 1;
2544 }
2545
2546 /*
2547  * Note the backref might has changed, and in this case we just return 0.
2548  */
2549 static noinline int relink_extent_backref(struct btrfs_path *path,
2550                                  struct sa_defrag_extent_backref *prev,
2551                                  struct sa_defrag_extent_backref *backref)
2552 {
2553         struct btrfs_file_extent_item *extent;
2554         struct btrfs_file_extent_item *item;
2555         struct btrfs_ordered_extent *ordered;
2556         struct btrfs_trans_handle *trans;
2557         struct btrfs_root *root;
2558         struct btrfs_key key;
2559         struct extent_buffer *leaf;
2560         struct old_sa_defrag_extent *old = backref->old;
2561         struct new_sa_defrag_extent *new = old->new;
2562         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2563         struct inode *inode;
2564         struct extent_state *cached = NULL;
2565         int ret = 0;
2566         u64 start;
2567         u64 len;
2568         u64 lock_start;
2569         u64 lock_end;
2570         bool merge = false;
2571         int index;
2572
2573         if (prev && prev->root_id == backref->root_id &&
2574             prev->inum == backref->inum &&
2575             prev->file_pos + prev->num_bytes == backref->file_pos)
2576                 merge = true;
2577
2578         /* step 1: get root */
2579         key.objectid = backref->root_id;
2580         key.type = BTRFS_ROOT_ITEM_KEY;
2581         key.offset = (u64)-1;
2582
2583         index = srcu_read_lock(&fs_info->subvol_srcu);
2584
2585         root = btrfs_read_fs_root_no_name(fs_info, &key);
2586         if (IS_ERR(root)) {
2587                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2588                 if (PTR_ERR(root) == -ENOENT)
2589                         return 0;
2590                 return PTR_ERR(root);
2591         }
2592
2593         if (btrfs_root_readonly(root)) {
2594                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2595                 return 0;
2596         }
2597
2598         /* step 2: get inode */
2599         key.objectid = backref->inum;
2600         key.type = BTRFS_INODE_ITEM_KEY;
2601         key.offset = 0;
2602
2603         inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2604         if (IS_ERR(inode)) {
2605                 srcu_read_unlock(&fs_info->subvol_srcu, index);
2606                 return 0;
2607         }
2608
2609         srcu_read_unlock(&fs_info->subvol_srcu, index);
2610
2611         /* step 3: relink backref */
2612         lock_start = backref->file_pos;
2613         lock_end = backref->file_pos + backref->num_bytes - 1;
2614         lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2615                          &cached);
2616
2617         ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2618         if (ordered) {
2619                 btrfs_put_ordered_extent(ordered);
2620                 goto out_unlock;
2621         }
2622
2623         trans = btrfs_join_transaction(root);
2624         if (IS_ERR(trans)) {
2625                 ret = PTR_ERR(trans);
2626                 goto out_unlock;
2627         }
2628
2629         key.objectid = backref->inum;
2630         key.type = BTRFS_EXTENT_DATA_KEY;
2631         key.offset = backref->file_pos;
2632
2633         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2634         if (ret < 0) {
2635                 goto out_free_path;
2636         } else if (ret > 0) {
2637                 ret = 0;
2638                 goto out_free_path;
2639         }
2640
2641         extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2642                                 struct btrfs_file_extent_item);
2643
2644         if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2645             backref->generation)
2646                 goto out_free_path;
2647
2648         btrfs_release_path(path);
2649
2650         start = backref->file_pos;
2651         if (backref->extent_offset < old->extent_offset + old->offset)
2652                 start += old->extent_offset + old->offset -
2653                          backref->extent_offset;
2654
2655         len = min(backref->extent_offset + backref->num_bytes,
2656                   old->extent_offset + old->offset + old->len);
2657         len -= max(backref->extent_offset, old->extent_offset + old->offset);
2658
2659         ret = btrfs_drop_extents(trans, root, inode, start,
2660                                  start + len, 1);
2661         if (ret)
2662                 goto out_free_path;
2663 again:
2664         key.objectid = btrfs_ino(BTRFS_I(inode));
2665         key.type = BTRFS_EXTENT_DATA_KEY;
2666         key.offset = start;
2667
2668         path->leave_spinning = 1;
2669         if (merge) {
2670                 struct btrfs_file_extent_item *fi;
2671                 u64 extent_len;
2672                 struct btrfs_key found_key;
2673
2674                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2675                 if (ret < 0)
2676                         goto out_free_path;
2677
2678                 path->slots[0]--;
2679                 leaf = path->nodes[0];
2680                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2681
2682                 fi = btrfs_item_ptr(leaf, path->slots[0],
2683                                     struct btrfs_file_extent_item);
2684                 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2685
2686                 if (extent_len + found_key.offset == start &&
2687                     relink_is_mergable(leaf, fi, new)) {
2688                         btrfs_set_file_extent_num_bytes(leaf, fi,
2689                                                         extent_len + len);
2690                         btrfs_mark_buffer_dirty(leaf);
2691                         inode_add_bytes(inode, len);
2692
2693                         ret = 1;
2694                         goto out_free_path;
2695                 } else {
2696                         merge = false;
2697                         btrfs_release_path(path);
2698                         goto again;
2699                 }
2700         }
2701
2702         ret = btrfs_insert_empty_item(trans, root, path, &key,
2703                                         sizeof(*extent));
2704         if (ret) {
2705                 btrfs_abort_transaction(trans, ret);
2706                 goto out_free_path;
2707         }
2708
2709         leaf = path->nodes[0];
2710         item = btrfs_item_ptr(leaf, path->slots[0],
2711                                 struct btrfs_file_extent_item);
2712         btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2713         btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2714         btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2715         btrfs_set_file_extent_num_bytes(leaf, item, len);
2716         btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2717         btrfs_set_file_extent_generation(leaf, item, trans->transid);
2718         btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2719         btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2720         btrfs_set_file_extent_encryption(leaf, item, 0);
2721         btrfs_set_file_extent_other_encoding(leaf, item, 0);
2722
2723         btrfs_mark_buffer_dirty(leaf);
2724         inode_add_bytes(inode, len);
2725         btrfs_release_path(path);
2726
2727         ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2728                         new->disk_len, 0,
2729                         backref->root_id, backref->inum,
2730                         new->file_pos); /* start - extent_offset */
2731         if (ret) {
2732                 btrfs_abort_transaction(trans, ret);
2733                 goto out_free_path;
2734         }
2735
2736         ret = 1;
2737 out_free_path:
2738         btrfs_release_path(path);
2739         path->leave_spinning = 0;
2740         btrfs_end_transaction(trans);
2741 out_unlock:
2742         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2743                              &cached);
2744         iput(inode);
2745         return ret;
2746 }
2747
2748 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2749 {
2750         struct old_sa_defrag_extent *old, *tmp;
2751
2752         if (!new)
2753                 return;
2754
2755         list_for_each_entry_safe(old, tmp, &new->head, list) {
2756                 kfree(old);
2757         }
2758         kfree(new);
2759 }
2760
2761 static void relink_file_extents(struct new_sa_defrag_extent *new)
2762 {
2763         struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2764         struct btrfs_path *path;
2765         struct sa_defrag_extent_backref *backref;
2766         struct sa_defrag_extent_backref *prev = NULL;
2767         struct inode *inode;
2768         struct rb_node *node;
2769         int ret;
2770
2771         inode = new->inode;
2772
2773         path = btrfs_alloc_path();
2774         if (!path)
2775                 return;
2776
2777         if (!record_extent_backrefs(path, new)) {
2778                 btrfs_free_path(path);
2779                 goto out;
2780         }
2781         btrfs_release_path(path);
2782
2783         while (1) {
2784                 node = rb_first(&new->root);
2785                 if (!node)
2786                         break;
2787                 rb_erase(node, &new->root);
2788
2789                 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2790
2791                 ret = relink_extent_backref(path, prev, backref);
2792                 WARN_ON(ret < 0);
2793
2794                 kfree(prev);
2795
2796                 if (ret == 1)
2797                         prev = backref;
2798                 else
2799                         prev = NULL;
2800                 cond_resched();
2801         }
2802         kfree(prev);
2803
2804         btrfs_free_path(path);
2805 out:
2806         free_sa_defrag_extent(new);
2807
2808         atomic_dec(&fs_info->defrag_running);
2809         wake_up(&fs_info->transaction_wait);
2810 }
2811
2812 static struct new_sa_defrag_extent *
2813 record_old_file_extents(struct inode *inode,
2814                         struct btrfs_ordered_extent *ordered)
2815 {
2816         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2817         struct btrfs_root *root = BTRFS_I(inode)->root;
2818         struct btrfs_path *path;
2819         struct btrfs_key key;
2820         struct old_sa_defrag_extent *old;
2821         struct new_sa_defrag_extent *new;
2822         int ret;
2823
2824         new = kmalloc(sizeof(*new), GFP_NOFS);
2825         if (!new)
2826                 return NULL;
2827
2828         new->inode = inode;
2829         new->file_pos = ordered->file_offset;
2830         new->len = ordered->len;
2831         new->bytenr = ordered->start;
2832         new->disk_len = ordered->disk_len;
2833         new->compress_type = ordered->compress_type;
2834         new->root = RB_ROOT;
2835         INIT_LIST_HEAD(&new->head);
2836
2837         path = btrfs_alloc_path();
2838         if (!path)
2839                 goto out_kfree;
2840
2841         key.objectid = btrfs_ino(BTRFS_I(inode));
2842         key.type = BTRFS_EXTENT_DATA_KEY;
2843         key.offset = new->file_pos;
2844
2845         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2846         if (ret < 0)
2847                 goto out_free_path;
2848         if (ret > 0 && path->slots[0] > 0)
2849                 path->slots[0]--;
2850
2851         /* find out all the old extents for the file range */
2852         while (1) {
2853                 struct btrfs_file_extent_item *extent;
2854                 struct extent_buffer *l;
2855                 int slot;
2856                 u64 num_bytes;
2857                 u64 offset;
2858                 u64 end;
2859                 u64 disk_bytenr;
2860                 u64 extent_offset;
2861
2862                 l = path->nodes[0];
2863                 slot = path->slots[0];
2864
2865                 if (slot >= btrfs_header_nritems(l)) {
2866                         ret = btrfs_next_leaf(root, path);
2867                         if (ret < 0)
2868                                 goto out_free_path;
2869                         else if (ret > 0)
2870                                 break;
2871                         continue;
2872                 }
2873
2874                 btrfs_item_key_to_cpu(l, &key, slot);
2875
2876                 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2877                         break;
2878                 if (key.type != BTRFS_EXTENT_DATA_KEY)
2879                         break;
2880                 if (key.offset >= new->file_pos + new->len)
2881                         break;
2882
2883                 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2884
2885                 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2886                 if (key.offset + num_bytes < new->file_pos)
2887                         goto next;
2888
2889                 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2890                 if (!disk_bytenr)
2891                         goto next;
2892
2893                 extent_offset = btrfs_file_extent_offset(l, extent);
2894
2895                 old = kmalloc(sizeof(*old), GFP_NOFS);
2896                 if (!old)
2897                         goto out_free_path;
2898
2899                 offset = max(new->file_pos, key.offset);
2900                 end = min(new->file_pos + new->len, key.offset + num_bytes);
2901
2902                 old->bytenr = disk_bytenr;
2903                 old->extent_offset = extent_offset;
2904                 old->offset = offset - key.offset;
2905                 old->len = end - offset;
2906                 old->new = new;
2907                 old->count = 0;
2908                 list_add_tail(&old->list, &new->head);
2909 next:
2910                 path->slots[0]++;
2911                 cond_resched();
2912         }
2913
2914         btrfs_free_path(path);
2915         atomic_inc(&fs_info->defrag_running);
2916
2917         return new;
2918
2919 out_free_path:
2920         btrfs_free_path(path);
2921 out_kfree:
2922         free_sa_defrag_extent(new);
2923         return NULL;
2924 }
2925
2926 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2927                                          u64 start, u64 len)
2928 {
2929         struct btrfs_block_group_cache *cache;
2930
2931         cache = btrfs_lookup_block_group(fs_info, start);
2932         ASSERT(cache);
2933
2934         spin_lock(&cache->lock);
2935         cache->delalloc_bytes -= len;
2936         spin_unlock(&cache->lock);
2937
2938         btrfs_put_block_group(cache);
2939 }
2940
2941 /* as ordered data IO finishes, this gets called so we can finish
2942  * an ordered extent if the range of bytes in the file it covers are
2943  * fully written.
2944  */
2945 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2946 {
2947         struct inode *inode = ordered_extent->inode;
2948         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2949         struct btrfs_root *root = BTRFS_I(inode)->root;
2950         struct btrfs_trans_handle *trans = NULL;
2951         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2952         struct extent_state *cached_state = NULL;
2953         struct new_sa_defrag_extent *new = NULL;
2954         int compress_type = 0;
2955         int ret = 0;
2956         u64 logical_len = ordered_extent->len;
2957         bool nolock;
2958         bool truncated = false;
2959         bool range_locked = false;
2960         bool clear_new_delalloc_bytes = false;
2961
2962         if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2963             !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2964             !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2965                 clear_new_delalloc_bytes = true;
2966
2967         nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2968
2969         if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2970                 ret = -EIO;
2971                 goto out;
2972         }
2973
2974         btrfs_free_io_failure_record(BTRFS_I(inode),
2975                         ordered_extent->file_offset,
2976                         ordered_extent->file_offset +
2977                         ordered_extent->len - 1);
2978
2979         if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2980                 truncated = true;
2981                 logical_len = ordered_extent->truncated_len;
2982                 /* Truncated the entire extent, don't bother adding */
2983                 if (!logical_len)
2984                         goto out;
2985         }
2986
2987         if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2988                 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2989
2990                 /*
2991                  * For mwrite(mmap + memset to write) case, we still reserve
2992                  * space for NOCOW range.
2993                  * As NOCOW won't cause a new delayed ref, just free the space
2994                  */
2995                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
2996                                        ordered_extent->len);
2997                 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2998                 if (nolock)
2999                         trans = btrfs_join_transaction_nolock(root);
3000                 else
3001                         trans = btrfs_join_transaction(root);
3002                 if (IS_ERR(trans)) {
3003                         ret = PTR_ERR(trans);
3004                         trans = NULL;
3005                         goto out;
3006                 }
3007                 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3008                 ret = btrfs_update_inode_fallback(trans, root, inode);
3009                 if (ret) /* -ENOMEM or corruption */
3010                         btrfs_abort_transaction(trans, ret);
3011                 goto out;
3012         }
3013
3014         range_locked = true;
3015         lock_extent_bits(io_tree, ordered_extent->file_offset,
3016                          ordered_extent->file_offset + ordered_extent->len - 1,
3017                          &cached_state);
3018
3019         ret = test_range_bit(io_tree, ordered_extent->file_offset,
3020                         ordered_extent->file_offset + ordered_extent->len - 1,
3021                         EXTENT_DEFRAG, 0, cached_state);
3022         if (ret) {
3023                 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3024                 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3025                         /* the inode is shared */
3026                         new = record_old_file_extents(inode, ordered_extent);
3027
3028                 clear_extent_bit(io_tree, ordered_extent->file_offset,
3029                         ordered_extent->file_offset + ordered_extent->len - 1,
3030                         EXTENT_DEFRAG, 0, 0, &cached_state);
3031         }
3032
3033         if (nolock)
3034                 trans = btrfs_join_transaction_nolock(root);
3035         else
3036                 trans = btrfs_join_transaction(root);
3037         if (IS_ERR(trans)) {
3038                 ret = PTR_ERR(trans);
3039                 trans = NULL;
3040                 goto out;
3041         }
3042
3043         trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3044
3045         if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3046                 compress_type = ordered_extent->compress_type;
3047         if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3048                 BUG_ON(compress_type);
3049                 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3050                                        ordered_extent->len);
3051                 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3052                                                 ordered_extent->file_offset,
3053                                                 ordered_extent->file_offset +
3054                                                 logical_len);
3055         } else {
3056                 BUG_ON(root == fs_info->tree_root);
3057                 ret = insert_reserved_file_extent(trans, inode,
3058                                                 ordered_extent->file_offset,
3059                                                 ordered_extent->start,
3060                                                 ordered_extent->disk_len,
3061                                                 logical_len, logical_len,
3062                                                 compress_type, 0, 0,
3063                                                 BTRFS_FILE_EXTENT_REG);
3064                 if (!ret)
3065                         btrfs_release_delalloc_bytes(fs_info,
3066                                                      ordered_extent->start,
3067                                                      ordered_extent->disk_len);
3068         }
3069         unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3070                            ordered_extent->file_offset, ordered_extent->len,
3071                            trans->transid);
3072         if (ret < 0) {
3073                 btrfs_abort_transaction(trans, ret);
3074                 goto out;
3075         }
3076
3077         ret = add_pending_csums(trans, inode, &ordered_extent->list);
3078         if (ret) {
3079                 btrfs_abort_transaction(trans, ret);
3080                 goto out;
3081         }
3082
3083         btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3084         ret = btrfs_update_inode_fallback(trans, root, inode);
3085         if (ret) { /* -ENOMEM or corruption */
3086                 btrfs_abort_transaction(trans, ret);
3087                 goto out;
3088         }
3089         ret = 0;
3090 out:
3091         if (range_locked || clear_new_delalloc_bytes) {
3092                 unsigned int clear_bits = 0;
3093
3094                 if (range_locked)
3095                         clear_bits |= EXTENT_LOCKED;
3096                 if (clear_new_delalloc_bytes)
3097                         clear_bits |= EXTENT_DELALLOC_NEW;
3098                 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3099                                  ordered_extent->file_offset,
3100                                  ordered_extent->file_offset +
3101                                  ordered_extent->len - 1,
3102                                  clear_bits,
3103                                  (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3104                                  0, &cached_state);
3105         }
3106
3107         if (trans)
3108                 btrfs_end_transaction(trans);
3109
3110         if (ret || truncated) {
3111                 u64 start, end;
3112
3113                 if (truncated)
3114                         start = ordered_extent->file_offset + logical_len;
3115                 else
3116                         start = ordered_extent->file_offset;
3117                 end = ordered_extent->file_offset + ordered_extent->len - 1;
3118                 clear_extent_uptodate(io_tree, start, end, NULL);
3119
3120                 /* Drop the cache for the part of the extent we didn't write. */
3121                 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3122
3123                 /*
3124                  * If the ordered extent had an IOERR or something else went
3125                  * wrong we need to return the space for this ordered extent
3126                  * back to the allocator.  We only free the extent in the
3127                  * truncated case if we didn't write out the extent at all.
3128                  */
3129                 if ((ret || !logical_len) &&
3130                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3131                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3132                         btrfs_free_reserved_extent(fs_info,
3133                                                    ordered_extent->start,
3134                                                    ordered_extent->disk_len, 1);
3135         }
3136
3137
3138         /*
3139          * This needs to be done to make sure anybody waiting knows we are done
3140          * updating everything for this ordered extent.
3141          */
3142         btrfs_remove_ordered_extent(inode, ordered_extent);
3143
3144         /* for snapshot-aware defrag */
3145         if (new) {
3146                 if (ret) {
3147                         free_sa_defrag_extent(new);
3148                         atomic_dec(&fs_info->defrag_running);
3149                 } else {
3150                         relink_file_extents(new);
3151                 }
3152         }
3153
3154         /* once for us */
3155         btrfs_put_ordered_extent(ordered_extent);
3156         /* once for the tree */
3157         btrfs_put_ordered_extent(ordered_extent);
3158
3159         return ret;
3160 }
3161
3162 static void finish_ordered_fn(struct btrfs_work *work)
3163 {
3164         struct btrfs_ordered_extent *ordered_extent;
3165         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3166         btrfs_finish_ordered_io(ordered_extent);
3167 }
3168
3169 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3170                                 struct extent_state *state, int uptodate)
3171 {
3172         struct inode *inode = page->mapping->host;
3173         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3174         struct btrfs_ordered_extent *ordered_extent = NULL;
3175         struct btrfs_workqueue *wq;
3176         btrfs_work_func_t func;
3177
3178         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3179
3180         ClearPagePrivate2(page);
3181         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3182                                             end - start + 1, uptodate))
3183                 return;
3184
3185         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3186                 wq = fs_info->endio_freespace_worker;
3187                 func = btrfs_freespace_write_helper;
3188         } else {
3189                 wq = fs_info->endio_write_workers;
3190                 func = btrfs_endio_write_helper;
3191         }
3192
3193         btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3194                         NULL);
3195         btrfs_queue_work(wq, &ordered_extent->work);
3196 }
3197
3198 static int __readpage_endio_check(struct inode *inode,
3199                                   struct btrfs_io_bio *io_bio,
3200                                   int icsum, struct page *page,
3201                                   int pgoff, u64 start, size_t len)
3202 {
3203         char *kaddr;
3204         u32 csum_expected;
3205         u32 csum = ~(u32)0;
3206
3207         csum_expected = *(((u32 *)io_bio->csum) + icsum);
3208
3209         kaddr = kmap_atomic(page);
3210         csum = btrfs_csum_data(kaddr + pgoff, csum,  len);
3211         btrfs_csum_final(csum, (u8 *)&csum);
3212         if (csum != csum_expected)
3213                 goto zeroit;
3214
3215         kunmap_atomic(kaddr);
3216         return 0;
3217 zeroit:
3218         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3219                                     io_bio->mirror_num);
3220         memset(kaddr + pgoff, 1, len);
3221         flush_dcache_page(page);
3222         kunmap_atomic(kaddr);
3223         return -EIO;
3224 }
3225
3226 /*
3227  * when reads are done, we need to check csums to verify the data is correct
3228  * if there's a match, we allow the bio to finish.  If not, the code in
3229  * extent_io.c will try to find good copies for us.
3230  */
3231 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3232                                       u64 phy_offset, struct page *page,
3233                                       u64 start, u64 end, int mirror)
3234 {
3235         size_t offset = start - page_offset(page);
3236         struct inode *inode = page->mapping->host;
3237         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3238         struct btrfs_root *root = BTRFS_I(inode)->root;
3239
3240         if (PageChecked(page)) {
3241                 ClearPageChecked(page);
3242                 return 0;
3243         }
3244
3245         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3246                 return 0;
3247
3248         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3249             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3250                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3251                 return 0;
3252         }
3253
3254         phy_offset >>= inode->i_sb->s_blocksize_bits;
3255         return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3256                                       start, (size_t)(end - start + 1));
3257 }
3258
3259 /*
3260  * btrfs_add_delayed_iput - perform a delayed iput on @inode
3261  *
3262  * @inode: The inode we want to perform iput on
3263  *
3264  * This function uses the generic vfs_inode::i_count to track whether we should
3265  * just decrement it (in case it's > 1) or if this is the last iput then link
3266  * the inode to the delayed iput machinery. Delayed iputs are processed at
3267  * transaction commit time/superblock commit/cleaner kthread.
3268  */
3269 void btrfs_add_delayed_iput(struct inode *inode)
3270 {
3271         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3272         struct btrfs_inode *binode = BTRFS_I(inode);
3273
3274         if (atomic_add_unless(&inode->i_count, -1, 1))
3275                 return;
3276
3277         spin_lock(&fs_info->delayed_iput_lock);
3278         ASSERT(list_empty(&binode->delayed_iput));
3279         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3280         spin_unlock(&fs_info->delayed_iput_lock);
3281 }
3282
3283 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3284 {
3285
3286         spin_lock(&fs_info->delayed_iput_lock);
3287         while (!list_empty(&fs_info->delayed_iputs)) {
3288                 struct btrfs_inode *inode;
3289
3290                 inode = list_first_entry(&fs_info->delayed_iputs,
3291                                 struct btrfs_inode, delayed_iput);
3292                 list_del_init(&inode->delayed_iput);
3293                 spin_unlock(&fs_info->delayed_iput_lock);
3294                 iput(&inode->vfs_inode);
3295                 spin_lock(&fs_info->delayed_iput_lock);
3296         }
3297         spin_unlock(&fs_info->delayed_iput_lock);
3298 }
3299
3300 /*
3301  * This is called in transaction commit time. If there are no orphan
3302  * files in the subvolume, it removes orphan item and frees block_rsv
3303  * structure.
3304  */
3305 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3306                               struct btrfs_root *root)
3307 {
3308         struct btrfs_fs_info *fs_info = root->fs_info;
3309         struct btrfs_block_rsv *block_rsv;
3310
3311         if (atomic_read(&root->orphan_inodes) ||
3312             root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3313                 return;
3314
3315         spin_lock(&root->orphan_lock);
3316         if (atomic_read(&root->orphan_inodes)) {
3317                 spin_unlock(&root->orphan_lock);
3318                 return;
3319         }
3320
3321         if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3322                 spin_unlock(&root->orphan_lock);
3323                 return;
3324         }
3325
3326         block_rsv = root->orphan_block_rsv;
3327         root->orphan_block_rsv = NULL;
3328         spin_unlock(&root->orphan_lock);
3329
3330         if (block_rsv) {
3331                 WARN_ON(block_rsv->size > 0);
3332                 btrfs_free_block_rsv(fs_info, block_rsv);
3333         }
3334 }
3335
3336 /*
3337  * This creates an orphan entry for the given inode in case something goes wrong
3338  * in the middle of an unlink.
3339  */
3340 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3341                      struct btrfs_inode *inode)
3342 {
3343         int ret;
3344
3345         ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3346         if (ret && ret != -EEXIST) {
3347                 btrfs_abort_transaction(trans, ret);
3348                 return ret;
3349         }
3350
3351         return 0;
3352 }
3353
3354 /*
3355  * We have done the delete so we can go ahead and remove the orphan item for
3356  * this particular inode.
3357  */
3358 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3359                             struct btrfs_inode *inode)
3360 {
3361         return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3362 }
3363
3364 /*
3365  * this cleans up any orphans that may be left on the list from the last use
3366  * of this root.
3367  */
3368 int btrfs_orphan_cleanup(struct btrfs_root *root)
3369 {
3370         struct btrfs_fs_info *fs_info = root->fs_info;
3371         struct btrfs_path *path;
3372         struct extent_buffer *leaf;
3373         struct btrfs_key key, found_key;
3374         struct btrfs_trans_handle *trans;
3375         struct inode *inode;
3376         u64 last_objectid = 0;
3377         int ret = 0, nr_unlink = 0;
3378
3379         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3380                 return 0;
3381
3382         path = btrfs_alloc_path();
3383         if (!path) {
3384                 ret = -ENOMEM;
3385                 goto out;
3386         }
3387         path->reada = READA_BACK;
3388
3389         key.objectid = BTRFS_ORPHAN_OBJECTID;
3390         key.type = BTRFS_ORPHAN_ITEM_KEY;
3391         key.offset = (u64)-1;
3392
3393         while (1) {
3394                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3395                 if (ret < 0)
3396                         goto out;
3397
3398                 /*
3399                  * if ret == 0 means we found what we were searching for, which
3400                  * is weird, but possible, so only screw with path if we didn't
3401                  * find the key and see if we have stuff that matches
3402                  */
3403                 if (ret > 0) {
3404                         ret = 0;
3405                         if (path->slots[0] == 0)
3406                                 break;
3407                         path->slots[0]--;
3408                 }
3409
3410                 /* pull out the item */
3411                 leaf = path->nodes[0];
3412                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3413
3414                 /* make sure the item matches what we want */
3415                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3416                         break;
3417                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3418                         break;
3419
3420                 /* release the path since we're done with it */
3421                 btrfs_release_path(path);
3422
3423                 /*
3424                  * this is where we are basically btrfs_lookup, without the
3425                  * crossing root thing.  we store the inode number in the
3426                  * offset of the orphan item.
3427                  */
3428
3429                 if (found_key.offset == last_objectid) {
3430                         btrfs_err(fs_info,
3431                                   "Error removing orphan entry, stopping orphan cleanup");
3432                         ret = -EINVAL;
3433                         goto out;
3434                 }
3435
3436                 last_objectid = found_key.offset;
3437
3438                 found_key.objectid = found_key.offset;
3439                 found_key.type = BTRFS_INODE_ITEM_KEY;
3440                 found_key.offset = 0;
3441                 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3442                 ret = PTR_ERR_OR_ZERO(inode);
3443                 if (ret && ret != -ENOENT)
3444                         goto out;
3445
3446                 if (ret == -ENOENT && root == fs_info->tree_root) {
3447                         struct btrfs_root *dead_root;
3448                         struct btrfs_fs_info *fs_info = root->fs_info;
3449                         int is_dead_root = 0;
3450
3451                         /*
3452                          * this is an orphan in the tree root. Currently these
3453                          * could come from 2 sources:
3454                          *  a) a snapshot deletion in progress
3455                          *  b) a free space cache inode
3456                          * We need to distinguish those two, as the snapshot
3457                          * orphan must not get deleted.
3458                          * find_dead_roots already ran before us, so if this
3459                          * is a snapshot deletion, we should find the root
3460                          * in the dead_roots list
3461                          */
3462                         spin_lock(&fs_info->trans_lock);
3463                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3464                                             root_list) {
3465                                 if (dead_root->root_key.objectid ==
3466                                     found_key.objectid) {
3467                                         is_dead_root = 1;
3468                                         break;
3469                                 }
3470                         }
3471                         spin_unlock(&fs_info->trans_lock);
3472                         if (is_dead_root) {
3473                                 /* prevent this orphan from being found again */
3474                                 key.offset = found_key.objectid - 1;
3475                                 continue;
3476                         }
3477
3478                 }
3479
3480                 /*
3481                  * If we have an inode with links, there are a couple of
3482                  * possibilities. Old kernels (before v3.12) used to create an
3483                  * orphan item for truncate indicating that there were possibly
3484                  * extent items past i_size that needed to be deleted. In v3.12,
3485                  * truncate was changed to update i_size in sync with the extent
3486                  * items, but the (useless) orphan item was still created. Since
3487                  * v4.18, we don't create the orphan item for truncate at all.
3488                  *
3489                  * So, this item could mean that we need to do a truncate, but
3490                  * only if this filesystem was last used on a pre-v3.12 kernel
3491                  * and was not cleanly unmounted. The odds of that are quite
3492                  * slim, and it's a pain to do the truncate now, so just delete
3493                  * the orphan item.
3494                  *
3495                  * It's also possible that this orphan item was supposed to be
3496                  * deleted but wasn't. The inode number may have been reused,
3497                  * but either way, we can delete the orphan item.
3498                  */
3499                 if (ret == -ENOENT || inode->i_nlink) {
3500                         if (!ret)
3501                                 iput(inode);
3502                         trans = btrfs_start_transaction(root, 1);
3503                         if (IS_ERR(trans)) {
3504                                 ret = PTR_ERR(trans);
3505                                 goto out;
3506                         }
3507                         btrfs_debug(fs_info, "auto deleting %Lu",
3508                                     found_key.objectid);
3509                         ret = btrfs_del_orphan_item(trans, root,
3510                                                     found_key.objectid);
3511                         btrfs_end_transaction(trans);
3512                         if (ret)
3513                                 goto out;
3514                         continue;
3515                 }
3516
3517                 nr_unlink++;
3518
3519                 /* this will do delete_inode and everything for us */
3520                 iput(inode);
3521                 if (ret)
3522                         goto out;
3523         }
3524         /* release the path since we're done with it */
3525         btrfs_release_path(path);
3526
3527         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3528
3529         if (root->orphan_block_rsv)
3530                 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3531                                         (u64)-1);
3532
3533         if (root->orphan_block_rsv ||
3534             test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3535                 trans = btrfs_join_transaction(root);
3536                 if (!IS_ERR(trans))
3537                         btrfs_end_transaction(trans);
3538         }
3539
3540         if (nr_unlink)
3541                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3542
3543 out:
3544         if (ret)
3545                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3546         btrfs_free_path(path);
3547         return ret;
3548 }
3549
3550 /*
3551  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3552  * don't find any xattrs, we know there can't be any acls.
3553  *
3554  * slot is the slot the inode is in, objectid is the objectid of the inode
3555  */
3556 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3557                                           int slot, u64 objectid,
3558                                           int *first_xattr_slot)
3559 {
3560         u32 nritems = btrfs_header_nritems(leaf);
3561         struct btrfs_key found_key;
3562         static u64 xattr_access = 0;
3563         static u64 xattr_default = 0;
3564         int scanned = 0;
3565
3566         if (!xattr_access) {
3567                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3568                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3569                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3570                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3571         }
3572
3573         slot++;
3574         *first_xattr_slot = -1;
3575         while (slot < nritems) {
3576                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3577
3578                 /* we found a different objectid, there must not be acls */
3579                 if (found_key.objectid != objectid)
3580                         return 0;
3581
3582                 /* we found an xattr, assume we've got an acl */
3583                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3584                         if (*first_xattr_slot == -1)
3585                                 *first_xattr_slot = slot;
3586                         if (found_key.offset == xattr_access ||
3587                             found_key.offset == xattr_default)
3588                                 return 1;
3589                 }
3590
3591                 /*
3592                  * we found a key greater than an xattr key, there can't
3593                  * be any acls later on
3594                  */
3595                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3596                         return 0;
3597
3598                 slot++;
3599                 scanned++;
3600
3601                 /*
3602                  * it goes inode, inode backrefs, xattrs, extents,
3603                  * so if there are a ton of hard links to an inode there can
3604                  * be a lot of backrefs.  Don't waste time searching too hard,
3605                  * this is just an optimization
3606                  */
3607                 if (scanned >= 8)
3608                         break;
3609         }
3610         /* we hit the end of the leaf before we found an xattr or
3611          * something larger than an xattr.  We have to assume the inode
3612          * has acls
3613          */
3614         if (*first_xattr_slot == -1)
3615                 *first_xattr_slot = slot;
3616         return 1;
3617 }
3618
3619 /*
3620  * read an inode from the btree into the in-memory inode
3621  */
3622 static int btrfs_read_locked_inode(struct inode *inode)
3623 {
3624         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3625         struct btrfs_path *path;
3626         struct extent_buffer *leaf;
3627         struct btrfs_inode_item *inode_item;
3628         struct btrfs_root *root = BTRFS_I(inode)->root;
3629         struct btrfs_key location;
3630         unsigned long ptr;
3631         int maybe_acls;
3632         u32 rdev;
3633         int ret;
3634         bool filled = false;
3635         int first_xattr_slot;
3636
3637         ret = btrfs_fill_inode(inode, &rdev);
3638         if (!ret)
3639                 filled = true;
3640
3641         path = btrfs_alloc_path();
3642         if (!path) {
3643                 ret = -ENOMEM;
3644                 goto make_bad;
3645         }
3646
3647         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3648
3649         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3650         if (ret) {
3651                 if (ret > 0)
3652                         ret = -ENOENT;
3653                 goto make_bad;
3654         }
3655
3656         leaf = path->nodes[0];
3657
3658         if (filled)
3659                 goto cache_index;
3660
3661         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3662                                     struct btrfs_inode_item);
3663         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3664         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3665         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3666         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3667         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3668
3669         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3670         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3671
3672         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3673         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3674
3675         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3676         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3677
3678         BTRFS_I(inode)->i_otime.tv_sec =
3679                 btrfs_timespec_sec(leaf, &inode_item->otime);
3680         BTRFS_I(inode)->i_otime.tv_nsec =
3681                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3682
3683         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3684         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3685         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3686
3687         inode_set_iversion_queried(inode,
3688                                    btrfs_inode_sequence(leaf, inode_item));
3689         inode->i_generation = BTRFS_I(inode)->generation;
3690         inode->i_rdev = 0;
3691         rdev = btrfs_inode_rdev(leaf, inode_item);
3692
3693         BTRFS_I(inode)->index_cnt = (u64)-1;
3694         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3695
3696 cache_index:
3697         /*
3698          * If we were modified in the current generation and evicted from memory
3699          * and then re-read we need to do a full sync since we don't have any
3700          * idea about which extents were modified before we were evicted from
3701          * cache.
3702          *
3703          * This is required for both inode re-read from disk and delayed inode
3704          * in delayed_nodes_tree.
3705          */
3706         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3707                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3708                         &BTRFS_I(inode)->runtime_flags);
3709
3710         /*
3711          * We don't persist the id of the transaction where an unlink operation
3712          * against the inode was last made. So here we assume the inode might
3713          * have been evicted, and therefore the exact value of last_unlink_trans
3714          * lost, and set it to last_trans to avoid metadata inconsistencies
3715          * between the inode and its parent if the inode is fsync'ed and the log
3716          * replayed. For example, in the scenario:
3717          *
3718          * touch mydir/foo
3719          * ln mydir/foo mydir/bar
3720          * sync
3721          * unlink mydir/bar
3722          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3723          * xfs_io -c fsync mydir/foo
3724          * <power failure>
3725          * mount fs, triggers fsync log replay
3726          *
3727          * We must make sure that when we fsync our inode foo we also log its
3728          * parent inode, otherwise after log replay the parent still has the
3729          * dentry with the "bar" name but our inode foo has a link count of 1
3730          * and doesn't have an inode ref with the name "bar" anymore.
3731          *
3732          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3733          * but it guarantees correctness at the expense of occasional full
3734          * transaction commits on fsync if our inode is a directory, or if our
3735          * inode is not a directory, logging its parent unnecessarily.
3736          */
3737         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3738
3739         path->slots[0]++;
3740         if (inode->i_nlink != 1 ||
3741             path->slots[0] >= btrfs_header_nritems(leaf))
3742                 goto cache_acl;
3743
3744         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3745         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3746                 goto cache_acl;
3747
3748         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3749         if (location.type == BTRFS_INODE_REF_KEY) {
3750                 struct btrfs_inode_ref *ref;
3751
3752                 ref = (struct btrfs_inode_ref *)ptr;
3753                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3754         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3755                 struct btrfs_inode_extref *extref;
3756
3757                 extref = (struct btrfs_inode_extref *)ptr;
3758                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3759                                                                      extref);
3760         }
3761 cache_acl:
3762         /*
3763          * try to precache a NULL acl entry for files that don't have
3764          * any xattrs or acls
3765          */
3766         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3767                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3768         if (first_xattr_slot != -1) {
3769                 path->slots[0] = first_xattr_slot;
3770                 ret = btrfs_load_inode_props(inode, path);
3771                 if (ret)
3772                         btrfs_err(fs_info,
3773                                   "error loading props for ino %llu (root %llu): %d",
3774                                   btrfs_ino(BTRFS_I(inode)),
3775                                   root->root_key.objectid, ret);
3776         }
3777         btrfs_free_path(path);
3778
3779         if (!maybe_acls)
3780                 cache_no_acl(inode);
3781
3782         switch (inode->i_mode & S_IFMT) {
3783         case S_IFREG:
3784                 inode->i_mapping->a_ops = &btrfs_aops;
3785                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3786                 inode->i_fop = &btrfs_file_operations;
3787                 inode->i_op = &btrfs_file_inode_operations;
3788                 break;
3789         case S_IFDIR:
3790                 inode->i_fop = &btrfs_dir_file_operations;
3791                 inode->i_op = &btrfs_dir_inode_operations;
3792                 break;
3793         case S_IFLNK:
3794                 inode->i_op = &btrfs_symlink_inode_operations;
3795                 inode_nohighmem(inode);
3796                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3797                 break;
3798         default:
3799                 inode->i_op = &btrfs_special_inode_operations;
3800                 init_special_inode(inode, inode->i_mode, rdev);
3801                 break;
3802         }
3803
3804         btrfs_sync_inode_flags_to_i_flags(inode);
3805         return 0;
3806
3807 make_bad:
3808         btrfs_free_path(path);
3809         make_bad_inode(inode);
3810         return ret;
3811 }
3812
3813 /*
3814  * given a leaf and an inode, copy the inode fields into the leaf
3815  */
3816 static void fill_inode_item(struct btrfs_trans_handle *trans,
3817                             struct extent_buffer *leaf,
3818                             struct btrfs_inode_item *item,
3819                             struct inode *inode)
3820 {
3821         struct btrfs_map_token token;
3822
3823         btrfs_init_map_token(&token);
3824
3825         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3826         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3827         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3828                                    &token);
3829         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3830         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3831
3832         btrfs_set_token_timespec_sec(leaf, &item->atime,
3833                                      inode->i_atime.tv_sec, &token);
3834         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3835                                       inode->i_atime.tv_nsec, &token);
3836
3837         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3838                                      inode->i_mtime.tv_sec, &token);
3839         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3840                                       inode->i_mtime.tv_nsec, &token);
3841
3842         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3843                                      inode->i_ctime.tv_sec, &token);
3844         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3845                                       inode->i_ctime.tv_nsec, &token);
3846
3847         btrfs_set_token_timespec_sec(leaf, &item->otime,
3848                                      BTRFS_I(inode)->i_otime.tv_sec, &token);
3849         btrfs_set_token_timespec_nsec(leaf, &item->otime,
3850                                       BTRFS_I(inode)->i_otime.tv_nsec, &token);
3851
3852         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3853                                      &token);
3854         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3855                                          &token);
3856         btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3857                                        &token);
3858         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3859         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3860         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3861         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3862 }
3863
3864 /*
3865  * copy everything in the in-memory inode into the btree.
3866  */
3867 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3868                                 struct btrfs_root *root, struct inode *inode)
3869 {
3870         struct btrfs_inode_item *inode_item;
3871         struct btrfs_path *path;
3872         struct extent_buffer *leaf;
3873         int ret;
3874
3875         path = btrfs_alloc_path();
3876         if (!path)
3877                 return -ENOMEM;
3878
3879         path->leave_spinning = 1;
3880         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3881                                  1);
3882         if (ret) {
3883                 if (ret > 0)
3884                         ret = -ENOENT;
3885                 goto failed;
3886         }
3887
3888         leaf = path->nodes[0];
3889         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3890                                     struct btrfs_inode_item);
3891
3892         fill_inode_item(trans, leaf, inode_item, inode);
3893         btrfs_mark_buffer_dirty(leaf);
3894         btrfs_set_inode_last_trans(trans, inode);
3895         ret = 0;
3896 failed:
3897         btrfs_free_path(path);
3898         return ret;
3899 }
3900
3901 /*
3902  * copy everything in the in-memory inode into the btree.
3903  */
3904 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3905                                 struct btrfs_root *root, struct inode *inode)
3906 {
3907         struct btrfs_fs_info *fs_info = root->fs_info;
3908         int ret;
3909
3910         /*
3911          * If the inode is a free space inode, we can deadlock during commit
3912          * if we put it into the delayed code.
3913          *
3914          * The data relocation inode should also be directly updated
3915          * without delay
3916          */
3917         if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3918             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3919             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3920                 btrfs_update_root_times(trans, root);
3921
3922                 ret = btrfs_delayed_update_inode(trans, root, inode);
3923                 if (!ret)
3924                         btrfs_set_inode_last_trans(trans, inode);
3925                 return ret;
3926         }
3927
3928         return btrfs_update_inode_item(trans, root, inode);
3929 }
3930
3931 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3932                                          struct btrfs_root *root,
3933                                          struct inode *inode)
3934 {
3935         int ret;
3936
3937         ret = btrfs_update_inode(trans, root, inode);
3938         if (ret == -ENOSPC)
3939                 return btrfs_update_inode_item(trans, root, inode);
3940         return ret;
3941 }
3942
3943 /*
3944  * unlink helper that gets used here in inode.c and in the tree logging
3945  * recovery code.  It remove a link in a directory with a given name, and
3946  * also drops the back refs in the inode to the directory
3947  */
3948 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3949                                 struct btrfs_root *root,
3950                                 struct btrfs_inode *dir,
3951                                 struct btrfs_inode *inode,
3952                                 const char *name, int name_len)
3953 {
3954         struct btrfs_fs_info *fs_info = root->fs_info;
3955         struct btrfs_path *path;
3956         int ret = 0;
3957         struct extent_buffer *leaf;
3958         struct btrfs_dir_item *di;
3959         struct btrfs_key key;
3960         u64 index;
3961         u64 ino = btrfs_ino(inode);
3962         u64 dir_ino = btrfs_ino(dir);
3963
3964         path = btrfs_alloc_path();
3965         if (!path) {
3966                 ret = -ENOMEM;
3967                 goto out;
3968         }
3969
3970         path->leave_spinning = 1;
3971         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3972                                     name, name_len, -1);
3973         if (IS_ERR(di)) {
3974                 ret = PTR_ERR(di);
3975                 goto err;
3976         }
3977         if (!di) {
3978                 ret = -ENOENT;
3979                 goto err;
3980         }
3981         leaf = path->nodes[0];
3982         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3983         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3984         if (ret)
3985                 goto err;
3986         btrfs_release_path(path);
3987
3988         /*
3989          * If we don't have dir index, we have to get it by looking up
3990          * the inode ref, since we get the inode ref, remove it directly,
3991          * it is unnecessary to do delayed deletion.
3992          *
3993          * But if we have dir index, needn't search inode ref to get it.
3994          * Since the inode ref is close to the inode item, it is better
3995          * that we delay to delete it, and just do this deletion when
3996          * we update the inode item.
3997          */
3998         if (inode->dir_index) {
3999                 ret = btrfs_delayed_delete_inode_ref(inode);
4000                 if (!ret) {
4001                         index = inode->dir_index;
4002                         goto skip_backref;
4003                 }
4004         }
4005
4006         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4007                                   dir_ino, &index);
4008         if (ret) {
4009                 btrfs_info(fs_info,
4010                         "failed to delete reference to %.*s, inode %llu parent %llu",
4011                         name_len, name, ino, dir_ino);
4012                 btrfs_abort_transaction(trans, ret);
4013                 goto err;
4014         }
4015 skip_backref:
4016         ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4017         if (ret) {
4018                 btrfs_abort_transaction(trans, ret);
4019                 goto err;
4020         }
4021
4022         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4023                         dir_ino);
4024         if (ret != 0 && ret != -ENOENT) {
4025                 btrfs_abort_transaction(trans, ret);
4026                 goto err;
4027         }
4028
4029         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4030                         index);
4031         if (ret == -ENOENT)
4032                 ret = 0;
4033         else if (ret)
4034                 btrfs_abort_transaction(trans, ret);
4035 err:
4036         btrfs_free_path(path);
4037         if (ret)
4038                 goto out;
4039
4040         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4041         inode_inc_iversion(&inode->vfs_inode);
4042         inode_inc_iversion(&dir->vfs_inode);
4043         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4044                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4045         ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4046 out:
4047         return ret;
4048 }
4049
4050 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4051                        struct btrfs_root *root,
4052                        struct btrfs_inode *dir, struct btrfs_inode *inode,
4053                        const char *name, int name_len)
4054 {
4055         int ret;
4056         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4057         if (!ret) {
4058                 drop_nlink(&inode->vfs_inode);
4059                 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4060         }
4061         return ret;
4062 }
4063
4064 /*
4065  * helper to start transaction for unlink and rmdir.
4066  *
4067  * unlink and rmdir are special in btrfs, they do not always free space, so
4068  * if we cannot make our reservations the normal way try and see if there is
4069  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4070  * allow the unlink to occur.
4071  */
4072 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4073 {
4074         struct btrfs_root *root = BTRFS_I(dir)->root;
4075
4076         /*
4077          * 1 for the possible orphan item
4078          * 1 for the dir item
4079          * 1 for the dir index
4080          * 1 for the inode ref
4081          * 1 for the inode
4082          */
4083         return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4084 }
4085
4086 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4087 {
4088         struct btrfs_root *root = BTRFS_I(dir)->root;
4089         struct btrfs_trans_handle *trans;
4090         struct inode *inode = d_inode(dentry);
4091         int ret;
4092
4093         trans = __unlink_start_trans(dir);
4094         if (IS_ERR(trans))
4095                 return PTR_ERR(trans);
4096
4097         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4098                         0);
4099
4100         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4101                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4102                         dentry->d_name.len);
4103         if (ret)
4104                 goto out;
4105
4106         if (inode->i_nlink == 0) {
4107                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4108                 if (ret)
4109                         goto out;
4110         }
4111
4112 out:
4113         btrfs_end_transaction(trans);
4114         btrfs_btree_balance_dirty(root->fs_info);
4115         return ret;
4116 }
4117
4118 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4119                         struct btrfs_root *root,
4120                         struct inode *dir, u64 objectid,
4121                         const char *name, int name_len)
4122 {
4123         struct btrfs_fs_info *fs_info = root->fs_info;
4124         struct btrfs_path *path;
4125         struct extent_buffer *leaf;
4126         struct btrfs_dir_item *di;
4127         struct btrfs_key key;
4128         u64 index;
4129         int ret;
4130         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4131
4132         path = btrfs_alloc_path();
4133         if (!path)
4134                 return -ENOMEM;
4135
4136         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4137                                    name, name_len, -1);
4138         if (IS_ERR_OR_NULL(di)) {
4139                 if (!di)
4140                         ret = -ENOENT;
4141                 else
4142                         ret = PTR_ERR(di);
4143                 goto out;
4144         }
4145
4146         leaf = path->nodes[0];
4147         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4148         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4149         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4150         if (ret) {
4151                 btrfs_abort_transaction(trans, ret);
4152                 goto out;
4153         }
4154         btrfs_release_path(path);
4155
4156         ret = btrfs_del_root_ref(trans, fs_info, objectid,
4157                                  root->root_key.objectid, dir_ino,
4158                                  &index, name, name_len);
4159         if (ret < 0) {
4160                 if (ret != -ENOENT) {
4161                         btrfs_abort_transaction(trans, ret);
4162                         goto out;
4163                 }
4164                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4165                                                  name, name_len);
4166                 if (IS_ERR_OR_NULL(di)) {
4167                         if (!di)
4168                                 ret = -ENOENT;
4169                         else
4170                                 ret = PTR_ERR(di);
4171                         btrfs_abort_transaction(trans, ret);
4172                         goto out;
4173                 }
4174
4175                 leaf = path->nodes[0];
4176                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4177                 btrfs_release_path(path);
4178                 index = key.offset;
4179         }
4180         btrfs_release_path(path);
4181
4182         ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4183         if (ret) {
4184                 btrfs_abort_transaction(trans, ret);
4185                 goto out;
4186         }
4187
4188         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4189         inode_inc_iversion(dir);
4190         dir->i_mtime = dir->i_ctime = current_time(dir);
4191         ret = btrfs_update_inode_fallback(trans, root, dir);
4192         if (ret)
4193                 btrfs_abort_transaction(trans, ret);
4194 out:
4195         btrfs_free_path(path);
4196         return ret;
4197 }
4198
4199 /*
4200  * Helper to check if the subvolume references other subvolumes or if it's
4201  * default.
4202  */
4203 static noinline int may_destroy_subvol(struct btrfs_root *root)
4204 {
4205         struct btrfs_fs_info *fs_info = root->fs_info;
4206         struct btrfs_path *path;
4207         struct btrfs_dir_item *di;
4208         struct btrfs_key key;
4209         u64 dir_id;
4210         int ret;
4211
4212         path = btrfs_alloc_path();
4213         if (!path)
4214                 return -ENOMEM;
4215
4216         /* Make sure this root isn't set as the default subvol */
4217         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4218         di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4219                                    dir_id, "default", 7, 0);
4220         if (di && !IS_ERR(di)) {
4221                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4222                 if (key.objectid == root->root_key.objectid) {
4223                         ret = -EPERM;
4224                         btrfs_err(fs_info,
4225                                   "deleting default subvolume %llu is not allowed",
4226                                   key.objectid);
4227                         goto out;
4228                 }
4229                 btrfs_release_path(path);
4230         }
4231
4232         key.objectid = root->root_key.objectid;
4233         key.type = BTRFS_ROOT_REF_KEY;
4234         key.offset = (u64)-1;
4235
4236         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4237         if (ret < 0)
4238                 goto out;
4239         BUG_ON(ret == 0);
4240
4241         ret = 0;
4242         if (path->slots[0] > 0) {
4243                 path->slots[0]--;
4244                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4245                 if (key.objectid == root->root_key.objectid &&
4246                     key.type == BTRFS_ROOT_REF_KEY)
4247                         ret = -ENOTEMPTY;
4248         }
4249 out:
4250         btrfs_free_path(path);
4251         return ret;
4252 }
4253
4254 /* Delete all dentries for inodes belonging to the root */
4255 static void btrfs_prune_dentries(struct btrfs_root *root)
4256 {
4257         struct btrfs_fs_info *fs_info = root->fs_info;
4258         struct rb_node *node;
4259         struct rb_node *prev;
4260         struct btrfs_inode *entry;
4261         struct inode *inode;
4262         u64 objectid = 0;
4263
4264         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4265                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4266
4267         spin_lock(&root->inode_lock);
4268 again:
4269         node = root->inode_tree.rb_node;
4270         prev = NULL;
4271         while (node) {
4272                 prev = node;
4273                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4274
4275                 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4276                         node = node->rb_left;
4277                 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4278                         node = node->rb_right;
4279                 else
4280                         break;
4281         }
4282         if (!node) {
4283                 while (prev) {
4284                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4285                         if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
4286                                 node = prev;
4287                                 break;
4288                         }
4289                         prev = rb_next(prev);
4290                 }
4291         }
4292         while (node) {
4293                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4294                 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
4295                 inode = igrab(&entry->vfs_inode);
4296                 if (inode) {
4297                         spin_unlock(&root->inode_lock);
4298                         if (atomic_read(&inode->i_count) > 1)
4299                                 d_prune_aliases(inode);
4300                         /*
4301                          * btrfs_drop_inode will have it removed from the inode
4302                          * cache when its usage count hits zero.
4303                          */
4304                         iput(inode);
4305                         cond_resched();
4306                         spin_lock(&root->inode_lock);
4307                         goto again;
4308                 }
4309
4310                 if (cond_resched_lock(&root->inode_lock))
4311                         goto again;
4312
4313                 node = rb_next(node);
4314         }
4315         spin_unlock(&root->inode_lock);
4316 }
4317
4318 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4319 {
4320         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4321         struct btrfs_root *root = BTRFS_I(dir)->root;
4322         struct inode *inode = d_inode(dentry);
4323         struct btrfs_root *dest = BTRFS_I(inode)->root;
4324         struct btrfs_trans_handle *trans;
4325         struct btrfs_block_rsv block_rsv;
4326         u64 root_flags;
4327         u64 qgroup_reserved;
4328         int ret;
4329         int err;
4330
4331         /*
4332          * Don't allow to delete a subvolume with send in progress. This is
4333          * inside the inode lock so the error handling that has to drop the bit
4334          * again is not run concurrently.
4335          */
4336         spin_lock(&dest->root_item_lock);
4337         root_flags = btrfs_root_flags(&dest->root_item);
4338         if (dest->send_in_progress == 0) {
4339                 btrfs_set_root_flags(&dest->root_item,
4340                                 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4341                 spin_unlock(&dest->root_item_lock);
4342         } else {
4343                 spin_unlock(&dest->root_item_lock);
4344                 btrfs_warn(fs_info,
4345                            "attempt to delete subvolume %llu during send",
4346                            dest->root_key.objectid);
4347                 return -EPERM;
4348         }
4349
4350         down_write(&fs_info->subvol_sem);
4351
4352         err = may_destroy_subvol(dest);
4353         if (err)
4354                 goto out_up_write;
4355
4356         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4357         /*
4358          * One for dir inode,
4359          * two for dir entries,
4360          * two for root ref/backref.
4361          */
4362         err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
4363                                                5, &qgroup_reserved, true);
4364         if (err)
4365                 goto out_up_write;
4366
4367         trans = btrfs_start_transaction(root, 0);
4368         if (IS_ERR(trans)) {
4369                 err = PTR_ERR(trans);
4370                 goto out_release;
4371         }
4372         trans->block_rsv = &block_rsv;
4373         trans->bytes_reserved = block_rsv.size;
4374
4375         btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4376
4377         ret = btrfs_unlink_subvol(trans, root, dir,
4378                                 dest->root_key.objectid,
4379                                 dentry->d_name.name,
4380                                 dentry->d_name.len);
4381         if (ret) {
4382                 err = ret;
4383                 btrfs_abort_transaction(trans, ret);
4384                 goto out_end_trans;
4385         }
4386
4387         btrfs_record_root_in_trans(trans, dest);
4388
4389         memset(&dest->root_item.drop_progress, 0,
4390                 sizeof(dest->root_item.drop_progress));
4391         dest->root_item.drop_level = 0;
4392         btrfs_set_root_refs(&dest->root_item, 0);
4393
4394         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4395                 ret = btrfs_insert_orphan_item(trans,
4396                                         fs_info->tree_root,
4397                                         dest->root_key.objectid);
4398                 if (ret) {
4399                         btrfs_abort_transaction(trans, ret);
4400                         err = ret;
4401                         goto out_end_trans;
4402                 }
4403         }
4404
4405         ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
4406                                   BTRFS_UUID_KEY_SUBVOL,
4407                                   dest->root_key.objectid);
4408         if (ret && ret != -ENOENT) {
4409                 btrfs_abort_transaction(trans, ret);
4410                 err = ret;
4411                 goto out_end_trans;
4412         }
4413         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4414                 ret = btrfs_uuid_tree_rem(trans, fs_info,
4415                                           dest->root_item.received_uuid,
4416                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4417                                           dest->root_key.objectid);
4418                 if (ret && ret != -ENOENT) {
4419                         btrfs_abort_transaction(trans, ret);
4420                         err = ret;
4421                         goto out_end_trans;
4422                 }
4423         }
4424
4425 out_end_trans:
4426         trans->block_rsv = NULL;
4427         trans->bytes_reserved = 0;
4428         ret = btrfs_end_transaction(trans);
4429         if (ret && !err)
4430                 err = ret;
4431         inode->i_flags |= S_DEAD;
4432 out_release:
4433         btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4434 out_up_write:
4435         up_write(&fs_info->subvol_sem);
4436         if (err) {
4437                 spin_lock(&dest->root_item_lock);
4438                 root_flags = btrfs_root_flags(&dest->root_item);
4439                 btrfs_set_root_flags(&dest->root_item,
4440                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4441                 spin_unlock(&dest->root_item_lock);
4442         } else {
4443                 d_invalidate(dentry);
4444                 btrfs_prune_dentries(dest);
4445                 ASSERT(dest->send_in_progress == 0);
4446
4447                 /* the last ref */
4448                 if (dest->ino_cache_inode) {
4449                         iput(dest->ino_cache_inode);
4450                         dest->ino_cache_inode = NULL;
4451                 }
4452         }
4453
4454         return err;
4455 }
4456
4457 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4458 {
4459         struct inode *inode = d_inode(dentry);
4460         int err = 0;
4461         struct btrfs_root *root = BTRFS_I(dir)->root;
4462         struct btrfs_trans_handle *trans;
4463         u64 last_unlink_trans;
4464
4465         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4466                 return -ENOTEMPTY;
4467         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4468                 return btrfs_delete_subvolume(dir, dentry);
4469
4470         trans = __unlink_start_trans(dir);
4471         if (IS_ERR(trans))
4472                 return PTR_ERR(trans);
4473
4474         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4475                 err = btrfs_unlink_subvol(trans, root, dir,
4476                                           BTRFS_I(inode)->location.objectid,
4477                                           dentry->d_name.name,
4478                                           dentry->d_name.len);
4479                 goto out;
4480         }
4481
4482         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4483         if (err)
4484                 goto out;
4485
4486         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4487
4488         /* now the directory is empty */
4489         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4490                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4491                         dentry->d_name.len);
4492         if (!err) {
4493                 btrfs_i_size_write(BTRFS_I(inode), 0);
4494                 /*
4495                  * Propagate the last_unlink_trans value of the deleted dir to
4496                  * its parent directory. This is to prevent an unrecoverable
4497                  * log tree in the case we do something like this:
4498                  * 1) create dir foo
4499                  * 2) create snapshot under dir foo
4500                  * 3) delete the snapshot
4501                  * 4) rmdir foo
4502                  * 5) mkdir foo
4503                  * 6) fsync foo or some file inside foo
4504                  */
4505                 if (last_unlink_trans >= trans->transid)
4506                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4507         }
4508 out:
4509         btrfs_end_transaction(trans);
4510         btrfs_btree_balance_dirty(root->fs_info);
4511
4512         return err;
4513 }
4514
4515 static int truncate_space_check(struct btrfs_trans_handle *trans,
4516                                 struct btrfs_root *root,
4517                                 u64 bytes_deleted)
4518 {
4519         struct btrfs_fs_info *fs_info = root->fs_info;
4520         int ret;
4521
4522         /*
4523          * This is only used to apply pressure to the enospc system, we don't
4524          * intend to use this reservation at all.
4525          */
4526         bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4527         bytes_deleted *= fs_info->nodesize;
4528         ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4529                                   bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4530         if (!ret) {
4531                 trace_btrfs_space_reservation(fs_info, "transaction",
4532                                               trans->transid,
4533                                               bytes_deleted, 1);
4534                 trans->bytes_reserved += bytes_deleted;
4535         }
4536         return ret;
4537
4538 }
4539
4540 /*
4541  * Return this if we need to call truncate_block for the last bit of the
4542  * truncate.
4543  */
4544 #define NEED_TRUNCATE_BLOCK 1
4545
4546 /*
4547  * this can truncate away extent items, csum items and directory items.
4548  * It starts at a high offset and removes keys until it can't find
4549  * any higher than new_size
4550  *
4551  * csum items that cross the new i_size are truncated to the new size
4552  * as well.
4553  *
4554  * min_type is the minimum key type to truncate down to.  If set to 0, this
4555  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4556  */
4557 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4558                                struct btrfs_root *root,
4559                                struct inode *inode,
4560                                u64 new_size, u32 min_type)
4561 {
4562         struct btrfs_fs_info *fs_info = root->fs_info;
4563         struct btrfs_path *path;
4564         struct extent_buffer *leaf;
4565         struct btrfs_file_extent_item *fi;
4566         struct btrfs_key key;
4567         struct btrfs_key found_key;
4568         u64 extent_start = 0;
4569         u64 extent_num_bytes = 0;
4570         u64 extent_offset = 0;
4571         u64 item_end = 0;
4572         u64 last_size = new_size;
4573         u32 found_type = (u8)-1;
4574         int found_extent;
4575         int del_item;
4576         int pending_del_nr = 0;
4577         int pending_del_slot = 0;
4578         int extent_type = -1;
4579         int ret;
4580         u64 ino = btrfs_ino(BTRFS_I(inode));
4581         u64 bytes_deleted = 0;
4582         bool be_nice = false;
4583         bool should_throttle = false;
4584         bool should_end = false;
4585
4586         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4587
4588         /*
4589          * for non-free space inodes and ref cows, we want to back off from
4590          * time to time
4591          */
4592         if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4593             test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4594                 be_nice = true;
4595
4596         path = btrfs_alloc_path();
4597         if (!path)
4598                 return -ENOMEM;
4599         path->reada = READA_BACK;
4600
4601         /*
4602          * We want to drop from the next block forward in case this new size is
4603          * not block aligned since we will be keeping the last block of the
4604          * extent just the way it is.
4605          */
4606         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4607             root == fs_info->tree_root)
4608                 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4609                                         fs_info->sectorsize),
4610                                         (u64)-1, 0);
4611
4612         /*
4613          * This function is also used to drop the items in the log tree before
4614          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4615          * it is used to drop the loged items. So we shouldn't kill the delayed
4616          * items.
4617          */
4618         if (min_type == 0 && root == BTRFS_I(inode)->root)
4619                 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4620
4621         key.objectid = ino;
4622         key.offset = (u64)-1;
4623         key.type = (u8)-1;
4624
4625 search_again:
4626         /*
4627          * with a 16K leaf size and 128MB extents, you can actually queue
4628          * up a huge file in a single leaf.  Most of the time that
4629          * bytes_deleted is > 0, it will be huge by the time we get here
4630          */
4631         if (be_nice && bytes_deleted > SZ_32M &&
4632             btrfs_should_end_transaction(trans)) {
4633                 ret = -EAGAIN;
4634                 goto out;
4635         }
4636
4637         path->leave_spinning = 1;
4638         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4639         if (ret < 0)
4640                 goto out;
4641
4642         if (ret > 0) {
4643                 ret = 0;
4644                 /* there are no items in the tree for us to truncate, we're
4645                  * done
4646                  */
4647                 if (path->slots[0] == 0)
4648                         goto out;
4649                 path->slots[0]--;
4650         }
4651
4652         while (1) {
4653                 fi = NULL;
4654                 leaf = path->nodes[0];
4655                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4656                 found_type = found_key.type;
4657
4658                 if (found_key.objectid != ino)
4659                         break;
4660
4661                 if (found_type < min_type)
4662                         break;
4663
4664                 item_end = found_key.offset;
4665                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4666                         fi = btrfs_item_ptr(leaf, path->slots[0],
4667                                             struct btrfs_file_extent_item);
4668                         extent_type = btrfs_file_extent_type(leaf, fi);
4669                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4670                                 item_end +=
4671                                     btrfs_file_extent_num_bytes(leaf, fi);
4672
4673                                 trace_btrfs_truncate_show_fi_regular(
4674                                         BTRFS_I(inode), leaf, fi,
4675                                         found_key.offset);
4676                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4677                                 item_end += btrfs_file_extent_inline_len(leaf,
4678                                                          path->slots[0], fi);
4679
4680                                 trace_btrfs_truncate_show_fi_inline(
4681                                         BTRFS_I(inode), leaf, fi, path->slots[0],
4682                                         found_key.offset);
4683                         }
4684                         item_end--;
4685                 }
4686                 if (found_type > min_type) {
4687                         del_item = 1;
4688                 } else {
4689                         if (item_end < new_size)
4690                                 break;
4691                         if (found_key.offset >= new_size)
4692                                 del_item = 1;
4693                         else
4694                                 del_item = 0;
4695                 }
4696                 found_extent = 0;
4697                 /* FIXME, shrink the extent if the ref count is only 1 */
4698                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4699                         goto delete;
4700
4701                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4702                         u64 num_dec;
4703                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4704                         if (!del_item) {
4705                                 u64 orig_num_bytes =
4706                                         btrfs_file_extent_num_bytes(leaf, fi);
4707                                 extent_num_bytes = ALIGN(new_size -
4708                                                 found_key.offset,
4709                                                 fs_info->sectorsize);
4710                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4711                                                          extent_num_bytes);
4712                                 num_dec = (orig_num_bytes -
4713                                            extent_num_bytes);
4714                                 if (test_bit(BTRFS_ROOT_REF_COWS,
4715                                              &root->state) &&
4716                                     extent_start != 0)
4717                                         inode_sub_bytes(inode, num_dec);
4718                                 btrfs_mark_buffer_dirty(leaf);
4719                         } else {
4720                                 extent_num_bytes =
4721                                         btrfs_file_extent_disk_num_bytes(leaf,
4722                                                                          fi);
4723                                 extent_offset = found_key.offset -
4724                                         btrfs_file_extent_offset(leaf, fi);
4725
4726                                 /* FIXME blocksize != 4096 */
4727                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4728                                 if (extent_start != 0) {
4729                                         found_extent = 1;
4730                                         if (test_bit(BTRFS_ROOT_REF_COWS,
4731                                                      &root->state))
4732                                                 inode_sub_bytes(inode, num_dec);
4733                                 }
4734                         }
4735                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4736                         /*
4737                          * we can't truncate inline items that have had
4738                          * special encodings
4739                          */
4740                         if (!del_item &&
4741                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4742                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4743                             btrfs_file_extent_compression(leaf, fi) == 0) {
4744                                 u32 size = (u32)(new_size - found_key.offset);
4745
4746                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4747                                 size = btrfs_file_extent_calc_inline_size(size);
4748                                 btrfs_truncate_item(root->fs_info, path, size, 1);
4749                         } else if (!del_item) {
4750                                 /*
4751                                  * We have to bail so the last_size is set to
4752                                  * just before this extent.
4753                                  */
4754                                 ret = NEED_TRUNCATE_BLOCK;
4755                                 break;
4756                         }
4757
4758                         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4759                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4760                 }
4761 delete:
4762                 if (del_item)
4763                         last_size = found_key.offset;
4764                 else
4765                         last_size = new_size;
4766                 if (del_item) {
4767                         if (!pending_del_nr) {
4768                                 /* no pending yet, add ourselves */
4769                                 pending_del_slot = path->slots[0];
4770                                 pending_del_nr = 1;
4771                         } else if (pending_del_nr &&
4772                                    path->slots[0] + 1 == pending_del_slot) {
4773                                 /* hop on the pending chunk */
4774                                 pending_del_nr++;
4775                                 pending_del_slot = path->slots[0];
4776                         } else {
4777                                 BUG();
4778                         }
4779                 } else {
4780                         break;
4781                 }
4782                 should_throttle = false;
4783
4784                 if (found_extent &&
4785                     (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4786                      root == fs_info->tree_root)) {
4787                         btrfs_set_path_blocking(path);
4788                         bytes_deleted += extent_num_bytes;
4789                         ret = btrfs_free_extent(trans, root, extent_start,
4790                                                 extent_num_bytes, 0,
4791                                                 btrfs_header_owner(leaf),
4792                                                 ino, extent_offset);
4793                         if (ret) {
4794                                 btrfs_abort_transaction(trans, ret);
4795                                 break;
4796                         }
4797                         if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4798                                 btrfs_async_run_delayed_refs(fs_info,
4799                                         trans->delayed_ref_updates * 2,
4800                                         trans->transid, 0);
4801                         if (be_nice) {
4802                                 if (truncate_space_check(trans, root,
4803                                                          extent_num_bytes)) {
4804                                         should_end = true;
4805                                 }
4806                                 if (btrfs_should_throttle_delayed_refs(trans,
4807                                                                        fs_info))
4808                                         should_throttle = true;
4809                         }
4810                 }
4811
4812                 if (found_type == BTRFS_INODE_ITEM_KEY)
4813                         break;
4814
4815                 if (path->slots[0] == 0 ||
4816                     path->slots[0] != pending_del_slot ||
4817                     should_throttle || should_end) {
4818                         if (pending_del_nr) {
4819                                 ret = btrfs_del_items(trans, root, path,
4820                                                 pending_del_slot,
4821                                                 pending_del_nr);
4822                                 if (ret) {
4823                                         btrfs_abort_transaction(trans, ret);
4824                                         break;
4825                                 }
4826                                 pending_del_nr = 0;
4827                         }
4828                         btrfs_release_path(path);
4829                         if (should_throttle) {
4830                                 unsigned long updates = trans->delayed_ref_updates;
4831                                 if (updates) {
4832                                         trans->delayed_ref_updates = 0;
4833                                         ret = btrfs_run_delayed_refs(trans,
4834                                                                    updates * 2);
4835                                         if (ret)
4836                                                 break;
4837                                 }
4838                         }
4839                         /*
4840                          * if we failed to refill our space rsv, bail out
4841                          * and let the transaction restart
4842                          */
4843                         if (should_end) {
4844                                 ret = -EAGAIN;
4845                                 break;
4846                         }
4847                         goto search_again;
4848                 } else {
4849                         path->slots[0]--;
4850                 }
4851         }
4852 out:
4853         if (ret >= 0 && pending_del_nr) {
4854                 int err;
4855
4856                 err = btrfs_del_items(trans, root, path, pending_del_slot,
4857                                       pending_del_nr);
4858                 if (err) {
4859                         btrfs_abort_transaction(trans, err);
4860                         ret = err;
4861                 }
4862         }
4863         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4864                 ASSERT(last_size >= new_size);
4865                 if (!ret && last_size > new_size)
4866                         last_size = new_size;
4867                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4868         }
4869
4870         btrfs_free_path(path);
4871
4872         if (be_nice && bytes_deleted > SZ_32M && (ret >= 0 || ret == -EAGAIN)) {
4873                 unsigned long updates = trans->delayed_ref_updates;
4874                 int err;
4875
4876                 if (updates) {
4877                         trans->delayed_ref_updates = 0;
4878                         err = btrfs_run_delayed_refs(trans, updates * 2);
4879                         if (err)
4880                                 ret = err;
4881                 }
4882         }
4883         return ret;
4884 }
4885
4886 /*
4887  * btrfs_truncate_block - read, zero a chunk and write a block
4888  * @inode - inode that we're zeroing
4889  * @from - the offset to start zeroing
4890  * @len - the length to zero, 0 to zero the entire range respective to the
4891  *      offset
4892  * @front - zero up to the offset instead of from the offset on
4893  *
4894  * This will find the block for the "from" offset and cow the block and zero the
4895  * part we want to zero.  This is used with truncate and hole punching.
4896  */
4897 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4898                         int front)
4899 {
4900         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4901         struct address_space *mapping = inode->i_mapping;
4902         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4903         struct btrfs_ordered_extent *ordered;
4904         struct extent_state *cached_state = NULL;
4905         struct extent_changeset *data_reserved = NULL;
4906         char *kaddr;
4907         u32 blocksize = fs_info->sectorsize;
4908         pgoff_t index = from >> PAGE_SHIFT;
4909         unsigned offset = from & (blocksize - 1);
4910         struct page *page;
4911         gfp_t mask = btrfs_alloc_write_mask(mapping);
4912         int ret = 0;
4913         u64 block_start;
4914         u64 block_end;
4915
4916         if (IS_ALIGNED(offset, blocksize) &&
4917             (!len || IS_ALIGNED(len, blocksize)))
4918                 goto out;
4919
4920         block_start = round_down(from, blocksize);
4921         block_end = block_start + blocksize - 1;
4922
4923         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4924                                            block_start, blocksize);
4925         if (ret)
4926                 goto out;
4927
4928 again:
4929         page = find_or_create_page(mapping, index, mask);
4930         if (!page) {
4931                 btrfs_delalloc_release_space(inode, data_reserved,
4932                                              block_start, blocksize, true);
4933                 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4934                 ret = -ENOMEM;
4935                 goto out;
4936         }
4937
4938         if (!PageUptodate(page)) {
4939                 ret = btrfs_readpage(NULL, page);
4940                 lock_page(page);
4941                 if (page->mapping != mapping) {
4942                         unlock_page(page);
4943                         put_page(page);
4944                         goto again;
4945                 }
4946                 if (!PageUptodate(page)) {
4947                         ret = -EIO;
4948                         goto out_unlock;
4949                 }
4950         }
4951         wait_on_page_writeback(page);
4952
4953         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4954         set_page_extent_mapped(page);
4955
4956         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4957         if (ordered) {
4958                 unlock_extent_cached(io_tree, block_start, block_end,
4959                                      &cached_state);
4960                 unlock_page(page);
4961                 put_page(page);
4962                 btrfs_start_ordered_extent(inode, ordered, 1);
4963                 btrfs_put_ordered_extent(ordered);
4964                 goto again;
4965         }
4966
4967         clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4968                           EXTENT_DIRTY | EXTENT_DELALLOC |
4969                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4970                           0, 0, &cached_state);
4971
4972         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4973                                         &cached_state, 0);
4974         if (ret) {
4975                 unlock_extent_cached(io_tree, block_start, block_end,
4976                                      &cached_state);
4977                 goto out_unlock;
4978         }
4979
4980         if (offset != blocksize) {
4981                 if (!len)
4982                         len = blocksize - offset;
4983                 kaddr = kmap(page);
4984                 if (front)
4985                         memset(kaddr + (block_start - page_offset(page)),
4986                                 0, offset);
4987                 else
4988                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4989                                 0, len);
4990                 flush_dcache_page(page);
4991                 kunmap(page);
4992         }
4993         ClearPageChecked(page);
4994         set_page_dirty(page);
4995         unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4996
4997 out_unlock:
4998         if (ret)
4999                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5000                                              blocksize, true);
5001         btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
5002         unlock_page(page);
5003         put_page(page);
5004 out:
5005         extent_changeset_free(data_reserved);
5006         return ret;
5007 }
5008
5009 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
5010                              u64 offset, u64 len)
5011 {
5012         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5013         struct btrfs_trans_handle *trans;
5014         int ret;
5015
5016         /*
5017          * Still need to make sure the inode looks like it's been updated so
5018          * that any holes get logged if we fsync.
5019          */
5020         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5021                 BTRFS_I(inode)->last_trans = fs_info->generation;
5022                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5023                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5024                 return 0;
5025         }
5026
5027         /*
5028          * 1 - for the one we're dropping
5029          * 1 - for the one we're adding
5030          * 1 - for updating the inode.
5031          */
5032         trans = btrfs_start_transaction(root, 3);
5033         if (IS_ERR(trans))
5034                 return PTR_ERR(trans);
5035
5036         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5037         if (ret) {
5038                 btrfs_abort_transaction(trans, ret);
5039                 btrfs_end_transaction(trans);
5040                 return ret;
5041         }
5042
5043         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5044                         offset, 0, 0, len, 0, len, 0, 0, 0);
5045         if (ret)
5046                 btrfs_abort_transaction(trans, ret);
5047         else
5048                 btrfs_update_inode(trans, root, inode);
5049         btrfs_end_transaction(trans);
5050         return ret;
5051 }
5052
5053 /*
5054  * This function puts in dummy file extents for the area we're creating a hole
5055  * for.  So if we are truncating this file to a larger size we need to insert
5056  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5057  * the range between oldsize and size
5058  */
5059 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5060 {
5061         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5062         struct btrfs_root *root = BTRFS_I(inode)->root;
5063         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5064         struct extent_map *em = NULL;
5065         struct extent_state *cached_state = NULL;
5066         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5067         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5068         u64 block_end = ALIGN(size, fs_info->sectorsize);
5069         u64 last_byte;
5070         u64 cur_offset;
5071         u64 hole_size;
5072         int err = 0;
5073
5074         /*
5075          * If our size started in the middle of a block we need to zero out the
5076          * rest of the block before we expand the i_size, otherwise we could
5077          * expose stale data.
5078          */
5079         err = btrfs_truncate_block(inode, oldsize, 0, 0);
5080         if (err)
5081                 return err;
5082
5083         if (size <= hole_start)
5084                 return 0;
5085
5086         while (1) {
5087                 struct btrfs_ordered_extent *ordered;
5088
5089                 lock_extent_bits(io_tree, hole_start, block_end - 1,
5090                                  &cached_state);
5091                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5092                                                      block_end - hole_start);
5093                 if (!ordered)
5094                         break;
5095                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5096                                      &cached_state);
5097                 btrfs_start_ordered_extent(inode, ordered, 1);
5098                 btrfs_put_ordered_extent(ordered);
5099         }
5100
5101         cur_offset = hole_start;
5102         while (1) {
5103                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5104                                 block_end - cur_offset, 0);
5105                 if (IS_ERR(em)) {
5106                         err = PTR_ERR(em);
5107                         em = NULL;
5108                         break;
5109                 }
5110                 last_byte = min(extent_map_end(em), block_end);
5111                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5112                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5113                         struct extent_map *hole_em;
5114                         hole_size = last_byte - cur_offset;
5115
5116                         err = maybe_insert_hole(root, inode, cur_offset,
5117                                                 hole_size);
5118                         if (err)
5119                                 break;
5120                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5121                                                 cur_offset + hole_size - 1, 0);
5122                         hole_em = alloc_extent_map();
5123                         if (!hole_em) {
5124                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5125                                         &BTRFS_I(inode)->runtime_flags);
5126                                 goto next;
5127                         }
5128                         hole_em->start = cur_offset;
5129                         hole_em->len = hole_size;
5130                         hole_em->orig_start = cur_offset;
5131
5132                         hole_em->block_start = EXTENT_MAP_HOLE;
5133                         hole_em->block_len = 0;
5134                         hole_em->orig_block_len = 0;
5135                         hole_em->ram_bytes = hole_size;
5136                         hole_em->bdev = fs_info->fs_devices->latest_bdev;
5137                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
5138                         hole_em->generation = fs_info->generation;
5139
5140                         while (1) {
5141                                 write_lock(&em_tree->lock);
5142                                 err = add_extent_mapping(em_tree, hole_em, 1);
5143                                 write_unlock(&em_tree->lock);
5144                                 if (err != -EEXIST)
5145                                         break;
5146                                 btrfs_drop_extent_cache(BTRFS_I(inode),
5147                                                         cur_offset,
5148                                                         cur_offset +
5149                                                         hole_size - 1, 0);
5150                         }
5151                         free_extent_map(hole_em);
5152                 }
5153 next:
5154                 free_extent_map(em);
5155                 em = NULL;
5156                 cur_offset = last_byte;
5157                 if (cur_offset >= block_end)
5158                         break;
5159         }
5160         free_extent_map(em);
5161         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5162         return err;
5163 }
5164
5165 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5166 {
5167         struct btrfs_root *root = BTRFS_I(inode)->root;
5168         struct btrfs_trans_handle *trans;
5169         loff_t oldsize = i_size_read(inode);
5170         loff_t newsize = attr->ia_size;
5171         int mask = attr->ia_valid;
5172         int ret;
5173
5174         /*
5175          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5176          * special case where we need to update the times despite not having
5177          * these flags set.  For all other operations the VFS set these flags
5178          * explicitly if it wants a timestamp update.
5179          */
5180         if (newsize != oldsize) {
5181                 inode_inc_iversion(inode);
5182                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5183                         inode->i_ctime = inode->i_mtime =
5184                                 current_time(inode);
5185         }
5186
5187         if (newsize > oldsize) {
5188                 /*
5189                  * Don't do an expanding truncate while snapshotting is ongoing.
5190                  * This is to ensure the snapshot captures a fully consistent
5191                  * state of this file - if the snapshot captures this expanding
5192                  * truncation, it must capture all writes that happened before
5193                  * this truncation.
5194                  */
5195                 btrfs_wait_for_snapshot_creation(root);
5196                 ret = btrfs_cont_expand(inode, oldsize, newsize);
5197                 if (ret) {
5198                         btrfs_end_write_no_snapshotting(root);
5199                         return ret;
5200                 }
5201
5202                 trans = btrfs_start_transaction(root, 1);
5203                 if (IS_ERR(trans)) {
5204                         btrfs_end_write_no_snapshotting(root);
5205                         return PTR_ERR(trans);
5206                 }
5207
5208                 i_size_write(inode, newsize);
5209                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5210                 pagecache_isize_extended(inode, oldsize, newsize);
5211                 ret = btrfs_update_inode(trans, root, inode);
5212                 btrfs_end_write_no_snapshotting(root);
5213                 btrfs_end_transaction(trans);
5214         } else {
5215
5216                 /*
5217                  * We're truncating a file that used to have good data down to
5218                  * zero. Make sure it gets into the ordered flush list so that
5219                  * any new writes get down to disk quickly.
5220                  */
5221                 if (newsize == 0)
5222                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5223                                 &BTRFS_I(inode)->runtime_flags);
5224
5225                 truncate_setsize(inode, newsize);
5226
5227                 /* Disable nonlocked read DIO to avoid the end less truncate */
5228                 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5229                 inode_dio_wait(inode);
5230                 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5231
5232                 ret = btrfs_truncate(inode, newsize == oldsize);
5233                 if (ret && inode->i_nlink) {
5234                         int err;
5235
5236                         /*
5237                          * Truncate failed, so fix up the in-memory size. We
5238                          * adjusted disk_i_size down as we removed extents, so
5239                          * wait for disk_i_size to be stable and then update the
5240                          * in-memory size to match.
5241                          */
5242                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5243                         if (err)
5244                                 return err;
5245                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5246                 }
5247         }
5248
5249         return ret;
5250 }
5251
5252 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5253 {
5254         struct inode *inode = d_inode(dentry);
5255         struct btrfs_root *root = BTRFS_I(inode)->root;
5256         int err;
5257
5258         if (btrfs_root_readonly(root))
5259                 return -EROFS;
5260
5261         err = setattr_prepare(dentry, attr);
5262         if (err)
5263                 return err;
5264
5265         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5266                 err = btrfs_setsize(inode, attr);
5267                 if (err)
5268                         return err;
5269         }
5270
5271         if (attr->ia_valid) {
5272                 setattr_copy(inode, attr);
5273                 inode_inc_iversion(inode);
5274                 err = btrfs_dirty_inode(inode);
5275
5276                 if (!err && attr->ia_valid & ATTR_MODE)
5277                         err = posix_acl_chmod(inode, inode->i_mode);
5278         }
5279
5280         return err;
5281 }
5282
5283 /*
5284  * While truncating the inode pages during eviction, we get the VFS calling
5285  * btrfs_invalidatepage() against each page of the inode. This is slow because
5286  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5287  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5288  * extent_state structures over and over, wasting lots of time.
5289  *
5290  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5291  * those expensive operations on a per page basis and do only the ordered io
5292  * finishing, while we release here the extent_map and extent_state structures,
5293  * without the excessive merging and splitting.
5294  */
5295 static void evict_inode_truncate_pages(struct inode *inode)
5296 {
5297         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5298         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5299         struct rb_node *node;
5300
5301         ASSERT(inode->i_state & I_FREEING);
5302         truncate_inode_pages_final(&inode->i_data);
5303
5304         write_lock(&map_tree->lock);
5305         while (!RB_EMPTY_ROOT(&map_tree->map)) {
5306                 struct extent_map *em;
5307
5308                 node = rb_first(&map_tree->map);
5309                 em = rb_entry(node, struct extent_map, rb_node);
5310                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5311                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5312                 remove_extent_mapping(map_tree, em);
5313                 free_extent_map(em);
5314                 if (need_resched()) {
5315                         write_unlock(&map_tree->lock);
5316                         cond_resched();
5317                         write_lock(&map_tree->lock);
5318                 }
5319         }
5320         write_unlock(&map_tree->lock);
5321
5322         /*
5323          * Keep looping until we have no more ranges in the io tree.
5324          * We can have ongoing bios started by readpages (called from readahead)
5325          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5326          * still in progress (unlocked the pages in the bio but did not yet
5327          * unlocked the ranges in the io tree). Therefore this means some
5328          * ranges can still be locked and eviction started because before
5329          * submitting those bios, which are executed by a separate task (work
5330          * queue kthread), inode references (inode->i_count) were not taken
5331          * (which would be dropped in the end io callback of each bio).
5332          * Therefore here we effectively end up waiting for those bios and
5333          * anyone else holding locked ranges without having bumped the inode's
5334          * reference count - if we don't do it, when they access the inode's
5335          * io_tree to unlock a range it may be too late, leading to an
5336          * use-after-free issue.
5337          */
5338         spin_lock(&io_tree->lock);
5339         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5340                 struct extent_state *state;
5341                 struct extent_state *cached_state = NULL;
5342                 u64 start;
5343                 u64 end;
5344
5345                 node = rb_first(&io_tree->state);
5346                 state = rb_entry(node, struct extent_state, rb_node);
5347                 start = state->start;
5348                 end = state->end;
5349                 spin_unlock(&io_tree->lock);
5350
5351                 lock_extent_bits(io_tree, start, end, &cached_state);
5352
5353                 /*
5354                  * If still has DELALLOC flag, the extent didn't reach disk,
5355                  * and its reserved space won't be freed by delayed_ref.
5356                  * So we need to free its reserved space here.
5357                  * (Refer to comment in btrfs_invalidatepage, case 2)
5358                  *
5359                  * Note, end is the bytenr of last byte, so we need + 1 here.
5360                  */
5361                 if (state->state & EXTENT_DELALLOC)
5362                         btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5363
5364                 clear_extent_bit(io_tree, start, end,
5365                                  EXTENT_LOCKED | EXTENT_DIRTY |
5366                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5367                                  EXTENT_DEFRAG, 1, 1, &cached_state);
5368
5369                 cond_resched();
5370                 spin_lock(&io_tree->lock);
5371         }
5372         spin_unlock(&io_tree->lock);
5373 }
5374
5375 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5376                                                         struct btrfs_block_rsv *rsv,
5377                                                         u64 min_size)
5378 {
5379         struct btrfs_fs_info *fs_info = root->fs_info;
5380         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5381         int failures = 0;
5382
5383         for (;;) {
5384                 struct btrfs_trans_handle *trans;
5385                 int ret;
5386
5387                 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5388                                              BTRFS_RESERVE_FLUSH_LIMIT);
5389
5390                 if (ret && ++failures > 2) {
5391                         btrfs_warn(fs_info,
5392                                    "could not allocate space for a delete; will truncate on mount");
5393                         return ERR_PTR(-ENOSPC);
5394                 }
5395
5396                 trans = btrfs_join_transaction(root);
5397                 if (IS_ERR(trans) || !ret)
5398                         return trans;
5399
5400                 /*
5401                  * Try to steal from the global reserve if there is space for
5402                  * it.
5403                  */
5404                 if (!btrfs_check_space_for_delayed_refs(trans, fs_info) &&
5405                     !btrfs_block_rsv_migrate(global_rsv, rsv, min_size, 0))
5406                         return trans;
5407
5408                 /* If not, commit and try again. */
5409                 ret = btrfs_commit_transaction(trans);
5410                 if (ret)
5411                         return ERR_PTR(ret);
5412         }
5413 }
5414
5415 void btrfs_evict_inode(struct inode *inode)
5416 {
5417         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5418         struct btrfs_trans_handle *trans;
5419         struct btrfs_root *root = BTRFS_I(inode)->root;
5420         struct btrfs_block_rsv *rsv;
5421         u64 min_size;
5422         int ret;
5423
5424         trace_btrfs_inode_evict(inode);
5425
5426         if (!root) {
5427                 clear_inode(inode);
5428                 return;
5429         }
5430
5431         min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5432
5433         evict_inode_truncate_pages(inode);
5434
5435         if (inode->i_nlink &&
5436             ((btrfs_root_refs(&root->root_item) != 0 &&
5437               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5438              btrfs_is_free_space_inode(BTRFS_I(inode))))
5439                 goto no_delete;
5440
5441         if (is_bad_inode(inode))
5442                 goto no_delete;
5443         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5444         if (!special_file(inode->i_mode))
5445                 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5446
5447         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5448
5449         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5450                 goto no_delete;
5451
5452         if (inode->i_nlink > 0) {
5453                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5454                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5455                 goto no_delete;
5456         }
5457
5458         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5459         if (ret)
5460                 goto no_delete;
5461
5462         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5463         if (!rsv)
5464                 goto no_delete;
5465         rsv->size = min_size;
5466         rsv->failfast = 1;
5467
5468         btrfs_i_size_write(BTRFS_I(inode), 0);
5469
5470         while (1) {
5471                 trans = evict_refill_and_join(root, rsv, min_size);
5472                 if (IS_ERR(trans))
5473                         goto free_rsv;
5474
5475                 trans->block_rsv = rsv;
5476
5477                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5478                 trans->block_rsv = &fs_info->trans_block_rsv;
5479                 btrfs_end_transaction(trans);
5480                 btrfs_btree_balance_dirty(fs_info);
5481                 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5482                         goto free_rsv;
5483                 else if (!ret)
5484                         break;
5485         }
5486
5487         /*
5488          * Errors here aren't a big deal, it just means we leave orphan items in
5489          * the tree. They will be cleaned up on the next mount. If the inode
5490          * number gets reused, cleanup deletes the orphan item without doing
5491          * anything, and unlink reuses the existing orphan item.
5492          *
5493          * If it turns out that we are dropping too many of these, we might want
5494          * to add a mechanism for retrying these after a commit.
5495          */
5496         trans = evict_refill_and_join(root, rsv, min_size);
5497         if (!IS_ERR(trans)) {
5498                 trans->block_rsv = rsv;
5499                 btrfs_orphan_del(trans, BTRFS_I(inode));
5500                 trans->block_rsv = &fs_info->trans_block_rsv;
5501                 btrfs_end_transaction(trans);
5502         }
5503
5504         if (!(root == fs_info->tree_root ||
5505               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5506                 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5507
5508 free_rsv:
5509         btrfs_free_block_rsv(fs_info, rsv);
5510 no_delete:
5511         /*
5512          * If we didn't successfully delete, the orphan item will still be in
5513          * the tree and we'll retry on the next mount. Again, we might also want
5514          * to retry these periodically in the future.
5515          */
5516         btrfs_remove_delayed_node(BTRFS_I(inode));
5517         clear_inode(inode);
5518 }
5519
5520 /*
5521  * this returns the key found in the dir entry in the location pointer.
5522  * If no dir entries were found, returns -ENOENT.
5523  * If found a corrupted location in dir entry, returns -EUCLEAN.
5524  */
5525 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5526                                struct btrfs_key *location)
5527 {
5528         const char *name = dentry->d_name.name;
5529         int namelen = dentry->d_name.len;
5530         struct btrfs_dir_item *di;
5531         struct btrfs_path *path;
5532         struct btrfs_root *root = BTRFS_I(dir)->root;
5533         int ret = 0;
5534
5535         path = btrfs_alloc_path();
5536         if (!path)
5537                 return -ENOMEM;
5538
5539         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5540                         name, namelen, 0);
5541         if (!di) {
5542                 ret = -ENOENT;
5543                 goto out;
5544         }
5545         if (IS_ERR(di)) {
5546                 ret = PTR_ERR(di);
5547                 goto out;
5548         }
5549
5550         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5551         if (location->type != BTRFS_INODE_ITEM_KEY &&
5552             location->type != BTRFS_ROOT_ITEM_KEY) {
5553                 ret = -EUCLEAN;
5554                 btrfs_warn(root->fs_info,
5555 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5556                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5557                            location->objectid, location->type, location->offset);
5558         }
5559 out:
5560         btrfs_free_path(path);
5561         return ret;
5562 }
5563
5564 /*
5565  * when we hit a tree root in a directory, the btrfs part of the inode
5566  * needs to be changed to reflect the root directory of the tree root.  This
5567  * is kind of like crossing a mount point.
5568  */
5569 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5570                                     struct inode *dir,
5571                                     struct dentry *dentry,
5572                                     struct btrfs_key *location,
5573                                     struct btrfs_root **sub_root)
5574 {
5575         struct btrfs_path *path;
5576         struct btrfs_root *new_root;
5577         struct btrfs_root_ref *ref;
5578         struct extent_buffer *leaf;
5579         struct btrfs_key key;
5580         int ret;
5581         int err = 0;
5582
5583         path = btrfs_alloc_path();
5584         if (!path) {
5585                 err = -ENOMEM;
5586                 goto out;
5587         }
5588
5589         err = -ENOENT;
5590         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5591         key.type = BTRFS_ROOT_REF_KEY;
5592         key.offset = location->objectid;
5593
5594         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5595         if (ret) {
5596                 if (ret < 0)
5597                         err = ret;
5598                 goto out;
5599         }
5600
5601         leaf = path->nodes[0];
5602         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5603         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5604             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5605                 goto out;
5606
5607         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5608                                    (unsigned long)(ref + 1),
5609                                    dentry->d_name.len);
5610         if (ret)
5611                 goto out;
5612
5613         btrfs_release_path(path);
5614
5615         new_root = btrfs_read_fs_root_no_name(fs_info, location);
5616         if (IS_ERR(new_root)) {
5617                 err = PTR_ERR(new_root);
5618                 goto out;
5619         }
5620
5621         *sub_root = new_root;
5622         location->objectid = btrfs_root_dirid(&new_root->root_item);
5623         location->type = BTRFS_INODE_ITEM_KEY;
5624         location->offset = 0;
5625         err = 0;
5626 out:
5627         btrfs_free_path(path);
5628         return err;
5629 }
5630
5631 static void inode_tree_add(struct inode *inode)
5632 {
5633         struct btrfs_root *root = BTRFS_I(inode)->root;
5634         struct btrfs_inode *entry;
5635         struct rb_node **p;
5636         struct rb_node *parent;
5637         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5638         u64 ino = btrfs_ino(BTRFS_I(inode));
5639
5640         if (inode_unhashed(inode))
5641                 return;
5642         parent = NULL;
5643         spin_lock(&root->inode_lock);
5644         p = &root->inode_tree.rb_node;
5645         while (*p) {
5646                 parent = *p;
5647                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5648
5649                 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5650                         p = &parent->rb_left;
5651                 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5652                         p = &parent->rb_right;
5653                 else {
5654                         WARN_ON(!(entry->vfs_inode.i_state &
5655                                   (I_WILL_FREE | I_FREEING)));
5656                         rb_replace_node(parent, new, &root->inode_tree);
5657                         RB_CLEAR_NODE(parent);
5658                         spin_unlock(&root->inode_lock);
5659                         return;
5660                 }
5661         }
5662         rb_link_node(new, parent, p);
5663         rb_insert_color(new, &root->inode_tree);
5664         spin_unlock(&root->inode_lock);
5665 }
5666
5667 static void inode_tree_del(struct inode *inode)
5668 {
5669         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5670         struct btrfs_root *root = BTRFS_I(inode)->root;
5671         int empty = 0;
5672
5673         spin_lock(&root->inode_lock);
5674         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5675                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5676                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5677                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5678         }
5679         spin_unlock(&root->inode_lock);
5680
5681         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5682                 synchronize_srcu(&fs_info->subvol_srcu);
5683                 spin_lock(&root->inode_lock);
5684                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5685                 spin_unlock(&root->inode_lock);
5686                 if (empty)
5687                         btrfs_add_dead_root(root);
5688         }
5689 }
5690
5691
5692 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5693 {
5694         struct btrfs_iget_args *args = p;
5695         inode->i_ino = args->location->objectid;
5696         memcpy(&BTRFS_I(inode)->location, args->location,
5697                sizeof(*args->location));
5698         BTRFS_I(inode)->root = args->root;
5699         return 0;
5700 }
5701
5702 static int btrfs_find_actor(struct inode *inode, void *opaque)
5703 {
5704         struct btrfs_iget_args *args = opaque;
5705         return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5706                 args->root == BTRFS_I(inode)->root;
5707 }
5708
5709 static struct inode *btrfs_iget_locked(struct super_block *s,
5710                                        struct btrfs_key *location,
5711                                        struct btrfs_root *root)
5712 {
5713         struct inode *inode;
5714         struct btrfs_iget_args args;
5715         unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5716
5717         args.location = location;
5718         args.root = root;
5719
5720         inode = iget5_locked(s, hashval, btrfs_find_actor,
5721                              btrfs_init_locked_inode,
5722                              (void *)&args);
5723         return inode;
5724 }
5725
5726 /* Get an inode object given its location and corresponding root.
5727  * Returns in *is_new if the inode was read from disk
5728  */
5729 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5730                          struct btrfs_root *root, int *new)
5731 {
5732         struct inode *inode;
5733
5734         inode = btrfs_iget_locked(s, location, root);
5735         if (!inode)
5736                 return ERR_PTR(-ENOMEM);
5737
5738         if (inode->i_state & I_NEW) {
5739                 int ret;
5740
5741                 ret = btrfs_read_locked_inode(inode);
5742                 if (!is_bad_inode(inode)) {
5743                         inode_tree_add(inode);
5744                         unlock_new_inode(inode);
5745                         if (new)
5746                                 *new = 1;
5747                 } else {
5748                         unlock_new_inode(inode);
5749                         iput(inode);
5750                         ASSERT(ret < 0);
5751                         inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5752                 }
5753         }
5754
5755         return inode;
5756 }
5757
5758 static struct inode *new_simple_dir(struct super_block *s,
5759                                     struct btrfs_key *key,
5760                                     struct btrfs_root *root)
5761 {
5762         struct inode *inode = new_inode(s);
5763
5764         if (!inode)
5765                 return ERR_PTR(-ENOMEM);
5766
5767         BTRFS_I(inode)->root = root;
5768         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5769         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5770
5771         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5772         inode->i_op = &btrfs_dir_ro_inode_operations;
5773         inode->i_opflags &= ~IOP_XATTR;
5774         inode->i_fop = &simple_dir_operations;
5775         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5776         inode->i_mtime = current_time(inode);
5777         inode->i_atime = inode->i_mtime;
5778         inode->i_ctime = inode->i_mtime;
5779         BTRFS_I(inode)->i_otime = inode->i_mtime;
5780
5781         return inode;
5782 }
5783
5784 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5785 {
5786         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5787         struct inode *inode;
5788         struct btrfs_root *root = BTRFS_I(dir)->root;
5789         struct btrfs_root *sub_root = root;
5790         struct btrfs_key location;
5791         int index;
5792         int ret = 0;
5793
5794         if (dentry->d_name.len > BTRFS_NAME_LEN)
5795                 return ERR_PTR(-ENAMETOOLONG);
5796
5797         ret = btrfs_inode_by_name(dir, dentry, &location);
5798         if (ret < 0)
5799                 return ERR_PTR(ret);
5800
5801         if (location.type == BTRFS_INODE_ITEM_KEY) {
5802                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5803                 return inode;
5804         }
5805
5806         index = srcu_read_lock(&fs_info->subvol_srcu);
5807         ret = fixup_tree_root_location(fs_info, dir, dentry,
5808                                        &location, &sub_root);
5809         if (ret < 0) {
5810                 if (ret != -ENOENT)
5811                         inode = ERR_PTR(ret);
5812                 else
5813                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5814         } else {
5815                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5816         }
5817         srcu_read_unlock(&fs_info->subvol_srcu, index);
5818
5819         if (!IS_ERR(inode) && root != sub_root) {
5820                 down_read(&fs_info->cleanup_work_sem);
5821                 if (!sb_rdonly(inode->i_sb))
5822                         ret = btrfs_orphan_cleanup(sub_root);
5823                 up_read(&fs_info->cleanup_work_sem);
5824                 if (ret) {
5825                         iput(inode);
5826                         inode = ERR_PTR(ret);
5827                 }
5828         }
5829
5830         return inode;
5831 }
5832
5833 static int btrfs_dentry_delete(const struct dentry *dentry)
5834 {
5835         struct btrfs_root *root;
5836         struct inode *inode = d_inode(dentry);
5837
5838         if (!inode && !IS_ROOT(dentry))
5839                 inode = d_inode(dentry->d_parent);
5840
5841         if (inode) {
5842                 root = BTRFS_I(inode)->root;
5843                 if (btrfs_root_refs(&root->root_item) == 0)
5844                         return 1;
5845
5846                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5847                         return 1;
5848         }
5849         return 0;
5850 }
5851
5852 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5853                                    unsigned int flags)
5854 {
5855         struct inode *inode;
5856
5857         inode = btrfs_lookup_dentry(dir, dentry);
5858         if (IS_ERR(inode)) {
5859                 if (PTR_ERR(inode) == -ENOENT)
5860                         inode = NULL;
5861                 else
5862                         return ERR_CAST(inode);
5863         }
5864
5865         return d_splice_alias(inode, dentry);
5866 }
5867
5868 unsigned char btrfs_filetype_table[] = {
5869         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5870 };
5871
5872 /*
5873  * All this infrastructure exists because dir_emit can fault, and we are holding
5874  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5875  * our information into that, and then dir_emit from the buffer.  This is
5876  * similar to what NFS does, only we don't keep the buffer around in pagecache
5877  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5878  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5879  * tree lock.
5880  */
5881 static int btrfs_opendir(struct inode *inode, struct file *file)
5882 {
5883         struct btrfs_file_private *private;
5884
5885         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5886         if (!private)
5887                 return -ENOMEM;
5888         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5889         if (!private->filldir_buf) {
5890                 kfree(private);
5891                 return -ENOMEM;
5892         }
5893         file->private_data = private;
5894         return 0;
5895 }
5896
5897 struct dir_entry {
5898         u64 ino;
5899         u64 offset;
5900         unsigned type;
5901         int name_len;
5902 };
5903
5904 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5905 {
5906         while (entries--) {
5907                 struct dir_entry *entry = addr;
5908                 char *name = (char *)(entry + 1);
5909
5910                 ctx->pos = get_unaligned(&entry->offset);
5911                 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5912                                          get_unaligned(&entry->ino),
5913                                          get_unaligned(&entry->type)))
5914                         return 1;
5915                 addr += sizeof(struct dir_entry) +
5916                         get_unaligned(&entry->name_len);
5917                 ctx->pos++;
5918         }
5919         return 0;
5920 }
5921
5922 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5923 {
5924         struct inode *inode = file_inode(file);
5925         struct btrfs_root *root = BTRFS_I(inode)->root;
5926         struct btrfs_file_private *private = file->private_data;
5927         struct btrfs_dir_item *di;
5928         struct btrfs_key key;
5929         struct btrfs_key found_key;
5930         struct btrfs_path *path;
5931         void *addr;
5932         struct list_head ins_list;
5933         struct list_head del_list;
5934         int ret;
5935         struct extent_buffer *leaf;
5936         int slot;
5937         char *name_ptr;
5938         int name_len;
5939         int entries = 0;
5940         int total_len = 0;
5941         bool put = false;
5942         struct btrfs_key location;
5943
5944         if (!dir_emit_dots(file, ctx))
5945                 return 0;
5946
5947         path = btrfs_alloc_path();
5948         if (!path)
5949                 return -ENOMEM;
5950
5951         addr = private->filldir_buf;
5952         path->reada = READA_FORWARD;
5953
5954         INIT_LIST_HEAD(&ins_list);
5955         INIT_LIST_HEAD(&del_list);
5956         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5957
5958 again:
5959         key.type = BTRFS_DIR_INDEX_KEY;
5960         key.offset = ctx->pos;
5961         key.objectid = btrfs_ino(BTRFS_I(inode));
5962
5963         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5964         if (ret < 0)
5965                 goto err;
5966
5967         while (1) {
5968                 struct dir_entry *entry;
5969
5970                 leaf = path->nodes[0];
5971                 slot = path->slots[0];
5972                 if (slot >= btrfs_header_nritems(leaf)) {
5973                         ret = btrfs_next_leaf(root, path);
5974                         if (ret < 0)
5975                                 goto err;
5976                         else if (ret > 0)
5977                                 break;
5978                         continue;
5979                 }
5980
5981                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5982
5983                 if (found_key.objectid != key.objectid)
5984                         break;
5985                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5986                         break;
5987                 if (found_key.offset < ctx->pos)
5988                         goto next;
5989                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5990                         goto next;
5991                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5992                 name_len = btrfs_dir_name_len(leaf, di);
5993                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5994                     PAGE_SIZE) {
5995                         btrfs_release_path(path);
5996                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5997                         if (ret)
5998                                 goto nopos;
5999                         addr = private->filldir_buf;
6000                         entries = 0;
6001                         total_len = 0;
6002                         goto again;
6003                 }
6004
6005                 entry = addr;
6006                 put_unaligned(name_len, &entry->name_len);
6007                 name_ptr = (char *)(entry + 1);
6008                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6009                                    name_len);
6010                 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
6011                                 &entry->type);
6012                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6013                 put_unaligned(location.objectid, &entry->ino);
6014                 put_unaligned(found_key.offset, &entry->offset);
6015                 entries++;
6016                 addr += sizeof(struct dir_entry) + name_len;
6017                 total_len += sizeof(struct dir_entry) + name_len;
6018 next:
6019                 path->slots[0]++;
6020         }
6021         btrfs_release_path(path);
6022
6023         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6024         if (ret)
6025                 goto nopos;
6026
6027         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6028         if (ret)
6029                 goto nopos;
6030
6031         /*
6032          * Stop new entries from being returned after we return the last
6033          * entry.
6034          *
6035          * New directory entries are assigned a strictly increasing
6036          * offset.  This means that new entries created during readdir
6037          * are *guaranteed* to be seen in the future by that readdir.
6038          * This has broken buggy programs which operate on names as
6039          * they're returned by readdir.  Until we re-use freed offsets
6040          * we have this hack to stop new entries from being returned
6041          * under the assumption that they'll never reach this huge
6042          * offset.
6043          *
6044          * This is being careful not to overflow 32bit loff_t unless the
6045          * last entry requires it because doing so has broken 32bit apps
6046          * in the past.
6047          */
6048         if (ctx->pos >= INT_MAX)
6049                 ctx->pos = LLONG_MAX;
6050         else
6051                 ctx->pos = INT_MAX;
6052 nopos:
6053         ret = 0;
6054 err:
6055         if (put)
6056                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6057         btrfs_free_path(path);
6058         return ret;
6059 }
6060
6061 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6062 {
6063         struct btrfs_root *root = BTRFS_I(inode)->root;
6064         struct btrfs_trans_handle *trans;
6065         int ret = 0;
6066         bool nolock = false;
6067
6068         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6069                 return 0;
6070
6071         if (btrfs_fs_closing(root->fs_info) &&
6072                         btrfs_is_free_space_inode(BTRFS_I(inode)))
6073                 nolock = true;
6074
6075         if (wbc->sync_mode == WB_SYNC_ALL) {
6076                 if (nolock)
6077                         trans = btrfs_join_transaction_nolock(root);
6078                 else
6079                         trans = btrfs_join_transaction(root);
6080                 if (IS_ERR(trans))
6081                         return PTR_ERR(trans);
6082                 ret = btrfs_commit_transaction(trans);
6083         }
6084         return ret;
6085 }
6086
6087 /*
6088  * This is somewhat expensive, updating the tree every time the
6089  * inode changes.  But, it is most likely to find the inode in cache.
6090  * FIXME, needs more benchmarking...there are no reasons other than performance
6091  * to keep or drop this code.
6092  */
6093 static int btrfs_dirty_inode(struct inode *inode)
6094 {
6095         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6096         struct btrfs_root *root = BTRFS_I(inode)->root;
6097         struct btrfs_trans_handle *trans;
6098         int ret;
6099
6100         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6101                 return 0;
6102
6103         trans = btrfs_join_transaction(root);
6104         if (IS_ERR(trans))
6105                 return PTR_ERR(trans);
6106
6107         ret = btrfs_update_inode(trans, root, inode);
6108         if (ret && ret == -ENOSPC) {
6109                 /* whoops, lets try again with the full transaction */
6110                 btrfs_end_transaction(trans);
6111                 trans = btrfs_start_transaction(root, 1);
6112                 if (IS_ERR(trans))
6113                         return PTR_ERR(trans);
6114
6115                 ret = btrfs_update_inode(trans, root, inode);
6116         }
6117         btrfs_end_transaction(trans);
6118         if (BTRFS_I(inode)->delayed_node)
6119                 btrfs_balance_delayed_items(fs_info);
6120
6121         return ret;
6122 }
6123
6124 /*
6125  * This is a copy of file_update_time.  We need this so we can return error on
6126  * ENOSPC for updating the inode in the case of file write and mmap writes.
6127  */
6128 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6129                              int flags)
6130 {
6131         struct btrfs_root *root = BTRFS_I(inode)->root;
6132         bool dirty = flags & ~S_VERSION;
6133
6134         if (btrfs_root_readonly(root))
6135                 return -EROFS;
6136
6137         if (flags & S_VERSION)
6138                 dirty |= inode_maybe_inc_iversion(inode, dirty);
6139         if (flags & S_CTIME)
6140                 inode->i_ctime = *now;
6141         if (flags & S_MTIME)
6142                 inode->i_mtime = *now;
6143         if (flags & S_ATIME)
6144                 inode->i_atime = *now;
6145         return dirty ? btrfs_dirty_inode(inode) : 0;
6146 }
6147
6148 /*
6149  * find the highest existing sequence number in a directory
6150  * and then set the in-memory index_cnt variable to reflect
6151  * free sequence numbers
6152  */
6153 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6154 {
6155         struct btrfs_root *root = inode->root;
6156         struct btrfs_key key, found_key;
6157         struct btrfs_path *path;
6158         struct extent_buffer *leaf;
6159         int ret;
6160
6161         key.objectid = btrfs_ino(inode);
6162         key.type = BTRFS_DIR_INDEX_KEY;
6163         key.offset = (u64)-1;
6164
6165         path = btrfs_alloc_path();
6166         if (!path)
6167                 return -ENOMEM;
6168
6169         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6170         if (ret < 0)
6171                 goto out;
6172         /* FIXME: we should be able to handle this */
6173         if (ret == 0)
6174                 goto out;
6175         ret = 0;
6176
6177         /*
6178          * MAGIC NUMBER EXPLANATION:
6179          * since we search a directory based on f_pos we have to start at 2
6180          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6181          * else has to start at 2
6182          */
6183         if (path->slots[0] == 0) {
6184                 inode->index_cnt = 2;
6185                 goto out;
6186         }
6187
6188         path->slots[0]--;
6189
6190         leaf = path->nodes[0];
6191         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6192
6193         if (found_key.objectid != btrfs_ino(inode) ||
6194             found_key.type != BTRFS_DIR_INDEX_KEY) {
6195                 inode->index_cnt = 2;
6196                 goto out;
6197         }
6198
6199         inode->index_cnt = found_key.offset + 1;
6200 out:
6201         btrfs_free_path(path);
6202         return ret;
6203 }
6204
6205 /*
6206  * helper to find a free sequence number in a given directory.  This current
6207  * code is very simple, later versions will do smarter things in the btree
6208  */
6209 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6210 {
6211         int ret = 0;
6212
6213         if (dir->index_cnt == (u64)-1) {
6214                 ret = btrfs_inode_delayed_dir_index_count(dir);
6215                 if (ret) {
6216                         ret = btrfs_set_inode_index_count(dir);
6217                         if (ret)
6218                                 return ret;
6219                 }
6220         }
6221
6222         *index = dir->index_cnt;
6223         dir->index_cnt++;
6224
6225         return ret;
6226 }
6227
6228 static int btrfs_insert_inode_locked(struct inode *inode)
6229 {
6230         struct btrfs_iget_args args;
6231         args.location = &BTRFS_I(inode)->location;
6232         args.root = BTRFS_I(inode)->root;
6233
6234         return insert_inode_locked4(inode,
6235                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6236                    btrfs_find_actor, &args);
6237 }
6238
6239 /*
6240  * Inherit flags from the parent inode.
6241  *
6242  * Currently only the compression flags and the cow flags are inherited.
6243  */
6244 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6245 {
6246         unsigned int flags;
6247
6248         if (!dir)
6249                 return;
6250
6251         flags = BTRFS_I(dir)->flags;
6252
6253         if (flags & BTRFS_INODE_NOCOMPRESS) {
6254                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6255                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6256         } else if (flags & BTRFS_INODE_COMPRESS) {
6257                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6258                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6259         }
6260
6261         if (flags & BTRFS_INODE_NODATACOW) {
6262                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6263                 if (S_ISREG(inode->i_mode))
6264                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6265         }
6266
6267         btrfs_sync_inode_flags_to_i_flags(inode);
6268 }
6269
6270 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6271                                      struct btrfs_root *root,
6272                                      struct inode *dir,
6273                                      const char *name, int name_len,
6274                                      u64 ref_objectid, u64 objectid,
6275                                      umode_t mode, u64 *index)
6276 {
6277         struct btrfs_fs_info *fs_info = root->fs_info;
6278         struct inode *inode;
6279         struct btrfs_inode_item *inode_item;
6280         struct btrfs_key *location;
6281         struct btrfs_path *path;
6282         struct btrfs_inode_ref *ref;
6283         struct btrfs_key key[2];
6284         u32 sizes[2];
6285         int nitems = name ? 2 : 1;
6286         unsigned long ptr;
6287         int ret;
6288
6289         path = btrfs_alloc_path();
6290         if (!path)
6291                 return ERR_PTR(-ENOMEM);
6292
6293         inode = new_inode(fs_info->sb);
6294         if (!inode) {
6295                 btrfs_free_path(path);
6296                 return ERR_PTR(-ENOMEM);
6297         }
6298
6299         /*
6300          * O_TMPFILE, set link count to 0, so that after this point,
6301          * we fill in an inode item with the correct link count.
6302          */
6303         if (!name)
6304                 set_nlink(inode, 0);
6305
6306         /*
6307          * we have to initialize this early, so we can reclaim the inode
6308          * number if we fail afterwards in this function.
6309          */
6310         inode->i_ino = objectid;
6311
6312         if (dir && name) {
6313                 trace_btrfs_inode_request(dir);
6314
6315                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6316                 if (ret) {
6317                         btrfs_free_path(path);
6318                         iput(inode);
6319                         return ERR_PTR(ret);
6320                 }
6321         } else if (dir) {
6322                 *index = 0;
6323         }
6324         /*
6325          * index_cnt is ignored for everything but a dir,
6326          * btrfs_set_inode_index_count has an explanation for the magic
6327          * number
6328          */
6329         BTRFS_I(inode)->index_cnt = 2;
6330         BTRFS_I(inode)->dir_index = *index;
6331         BTRFS_I(inode)->root = root;
6332         BTRFS_I(inode)->generation = trans->transid;
6333         inode->i_generation = BTRFS_I(inode)->generation;
6334
6335         /*
6336          * We could have gotten an inode number from somebody who was fsynced
6337          * and then removed in this same transaction, so let's just set full
6338          * sync since it will be a full sync anyway and this will blow away the
6339          * old info in the log.
6340          */
6341         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6342
6343         key[0].objectid = objectid;
6344         key[0].type = BTRFS_INODE_ITEM_KEY;
6345         key[0].offset = 0;
6346
6347         sizes[0] = sizeof(struct btrfs_inode_item);
6348
6349         if (name) {
6350                 /*
6351                  * Start new inodes with an inode_ref. This is slightly more
6352                  * efficient for small numbers of hard links since they will
6353                  * be packed into one item. Extended refs will kick in if we
6354                  * add more hard links than can fit in the ref item.
6355                  */
6356                 key[1].objectid = objectid;
6357                 key[1].type = BTRFS_INODE_REF_KEY;
6358                 key[1].offset = ref_objectid;
6359
6360                 sizes[1] = name_len + sizeof(*ref);
6361         }
6362
6363         location = &BTRFS_I(inode)->location;
6364         location->objectid = objectid;
6365         location->offset = 0;
6366         location->type = BTRFS_INODE_ITEM_KEY;
6367
6368         ret = btrfs_insert_inode_locked(inode);
6369         if (ret < 0)
6370                 goto fail;
6371
6372         path->leave_spinning = 1;
6373         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6374         if (ret != 0)
6375                 goto fail_unlock;
6376
6377         inode_init_owner(inode, dir, mode);
6378         inode_set_bytes(inode, 0);
6379
6380         inode->i_mtime = current_time(inode);
6381         inode->i_atime = inode->i_mtime;
6382         inode->i_ctime = inode->i_mtime;
6383         BTRFS_I(inode)->i_otime = inode->i_mtime;
6384
6385         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6386                                   struct btrfs_inode_item);
6387         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6388                              sizeof(*inode_item));
6389         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6390
6391         if (name) {
6392                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6393                                      struct btrfs_inode_ref);
6394                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6395                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6396                 ptr = (unsigned long)(ref + 1);
6397                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6398         }
6399
6400         btrfs_mark_buffer_dirty(path->nodes[0]);
6401         btrfs_free_path(path);
6402
6403         btrfs_inherit_iflags(inode, dir);
6404
6405         if (S_ISREG(mode)) {
6406                 if (btrfs_test_opt(fs_info, NODATASUM))
6407                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6408                 if (btrfs_test_opt(fs_info, NODATACOW))
6409                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6410                                 BTRFS_INODE_NODATASUM;
6411         }
6412
6413         inode_tree_add(inode);
6414
6415         trace_btrfs_inode_new(inode);
6416         btrfs_set_inode_last_trans(trans, inode);
6417
6418         btrfs_update_root_times(trans, root);
6419
6420         ret = btrfs_inode_inherit_props(trans, inode, dir);
6421         if (ret)
6422                 btrfs_err(fs_info,
6423                           "error inheriting props for ino %llu (root %llu): %d",
6424                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6425
6426         return inode;
6427
6428 fail_unlock:
6429         unlock_new_inode(inode);
6430 fail:
6431         if (dir && name)
6432                 BTRFS_I(dir)->index_cnt--;
6433         btrfs_free_path(path);
6434         iput(inode);
6435         return ERR_PTR(ret);
6436 }
6437
6438 static inline u8 btrfs_inode_type(struct inode *inode)
6439 {
6440         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6441 }
6442
6443 /*
6444  * utility function to add 'inode' into 'parent_inode' with
6445  * a give name and a given sequence number.
6446  * if 'add_backref' is true, also insert a backref from the
6447  * inode to the parent directory.
6448  */
6449 int btrfs_add_link(struct btrfs_trans_handle *trans,
6450                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6451                    const char *name, int name_len, int add_backref, u64 index)
6452 {
6453         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6454         int ret = 0;
6455         struct btrfs_key key;
6456         struct btrfs_root *root = parent_inode->root;
6457         u64 ino = btrfs_ino(inode);
6458         u64 parent_ino = btrfs_ino(parent_inode);
6459
6460         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6461                 memcpy(&key, &inode->root->root_key, sizeof(key));
6462         } else {
6463                 key.objectid = ino;
6464                 key.type = BTRFS_INODE_ITEM_KEY;
6465                 key.offset = 0;
6466         }
6467
6468         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6469                 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6470                                          root->root_key.objectid, parent_ino,
6471                                          index, name, name_len);
6472         } else if (add_backref) {
6473                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6474                                              parent_ino, index);
6475         }
6476
6477         /* Nothing to clean up yet */
6478         if (ret)
6479                 return ret;
6480
6481         ret = btrfs_insert_dir_item(trans, root, name, name_len,
6482                                     parent_inode, &key,
6483                                     btrfs_inode_type(&inode->vfs_inode), index);
6484         if (ret == -EEXIST || ret == -EOVERFLOW)
6485                 goto fail_dir_item;
6486         else if (ret) {
6487                 btrfs_abort_transaction(trans, ret);
6488                 return ret;
6489         }
6490
6491         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6492                            name_len * 2);
6493         inode_inc_iversion(&parent_inode->vfs_inode);
6494         parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6495                 current_time(&parent_inode->vfs_inode);
6496         ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6497         if (ret)
6498                 btrfs_abort_transaction(trans, ret);
6499         return ret;
6500
6501 fail_dir_item:
6502         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6503                 u64 local_index;
6504                 int err;
6505                 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6506                                          root->root_key.objectid, parent_ino,
6507                                          &local_index, name, name_len);
6508
6509         } else if (add_backref) {
6510                 u64 local_index;
6511                 int err;
6512
6513                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6514                                           ino, parent_ino, &local_index);
6515         }
6516         return ret;
6517 }
6518
6519 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6520                             struct btrfs_inode *dir, struct dentry *dentry,
6521                             struct btrfs_inode *inode, int backref, u64 index)
6522 {
6523         int err = btrfs_add_link(trans, dir, inode,
6524                                  dentry->d_name.name, dentry->d_name.len,
6525                                  backref, index);
6526         if (err > 0)
6527                 err = -EEXIST;
6528         return err;
6529 }
6530
6531 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6532                         umode_t mode, dev_t rdev)
6533 {
6534         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6535         struct btrfs_trans_handle *trans;
6536         struct btrfs_root *root = BTRFS_I(dir)->root;
6537         struct inode *inode = NULL;
6538         int err;
6539         int drop_inode = 0;
6540         u64 objectid;
6541         u64 index = 0;
6542
6543         /*
6544          * 2 for inode item and ref
6545          * 2 for dir items
6546          * 1 for xattr if selinux is on
6547          */
6548         trans = btrfs_start_transaction(root, 5);
6549         if (IS_ERR(trans))
6550                 return PTR_ERR(trans);
6551
6552         err = btrfs_find_free_ino(root, &objectid);
6553         if (err)
6554                 goto out_unlock;
6555
6556         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6557                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6558                         mode, &index);
6559         if (IS_ERR(inode)) {
6560                 err = PTR_ERR(inode);
6561                 goto out_unlock;
6562         }
6563
6564         /*
6565         * If the active LSM wants to access the inode during
6566         * d_instantiate it needs these. Smack checks to see
6567         * if the filesystem supports xattrs by looking at the
6568         * ops vector.
6569         */
6570         inode->i_op = &btrfs_special_inode_operations;
6571         init_special_inode(inode, inode->i_mode, rdev);
6572
6573         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6574         if (err)
6575                 goto out_unlock_inode;
6576
6577         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6578                         0, index);
6579         if (err) {
6580                 goto out_unlock_inode;
6581         } else {
6582                 btrfs_update_inode(trans, root, inode);
6583                 d_instantiate_new(dentry, inode);
6584         }
6585
6586 out_unlock:
6587         btrfs_end_transaction(trans);
6588         btrfs_btree_balance_dirty(fs_info);
6589         if (drop_inode) {
6590                 inode_dec_link_count(inode);
6591                 iput(inode);
6592         }
6593         return err;
6594
6595 out_unlock_inode:
6596         drop_inode = 1;
6597         unlock_new_inode(inode);
6598         goto out_unlock;
6599
6600 }
6601
6602 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6603                         umode_t mode, bool excl)
6604 {
6605         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6606         struct btrfs_trans_handle *trans;
6607         struct btrfs_root *root = BTRFS_I(dir)->root;
6608         struct inode *inode = NULL;
6609         int drop_inode_on_err = 0;
6610         int err;
6611         u64 objectid;
6612         u64 index = 0;
6613
6614         /*
6615          * 2 for inode item and ref
6616          * 2 for dir items
6617          * 1 for xattr if selinux is on
6618          */
6619         trans = btrfs_start_transaction(root, 5);
6620         if (IS_ERR(trans))
6621                 return PTR_ERR(trans);
6622
6623         err = btrfs_find_free_ino(root, &objectid);
6624         if (err)
6625                 goto out_unlock;
6626
6627         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6628                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6629                         mode, &index);
6630         if (IS_ERR(inode)) {
6631                 err = PTR_ERR(inode);
6632                 goto out_unlock;
6633         }
6634         drop_inode_on_err = 1;
6635         /*
6636         * If the active LSM wants to access the inode during
6637         * d_instantiate it needs these. Smack checks to see
6638         * if the filesystem supports xattrs by looking at the
6639         * ops vector.
6640         */
6641         inode->i_fop = &btrfs_file_operations;
6642         inode->i_op = &btrfs_file_inode_operations;
6643         inode->i_mapping->a_ops = &btrfs_aops;
6644
6645         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6646         if (err)
6647                 goto out_unlock_inode;
6648
6649         err = btrfs_update_inode(trans, root, inode);
6650         if (err)
6651                 goto out_unlock_inode;
6652
6653         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6654                         0, index);
6655         if (err)
6656                 goto out_unlock_inode;
6657
6658         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6659         d_instantiate_new(dentry, inode);
6660
6661 out_unlock:
6662         btrfs_end_transaction(trans);
6663         if (err && drop_inode_on_err) {
6664                 inode_dec_link_count(inode);
6665                 iput(inode);
6666         }
6667         btrfs_btree_balance_dirty(fs_info);
6668         return err;
6669
6670 out_unlock_inode:
6671         unlock_new_inode(inode);
6672         goto out_unlock;
6673
6674 }
6675
6676 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6677                       struct dentry *dentry)
6678 {
6679         struct btrfs_trans_handle *trans = NULL;
6680         struct btrfs_root *root = BTRFS_I(dir)->root;
6681         struct inode *inode = d_inode(old_dentry);
6682         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6683         u64 index;
6684         int err;
6685         int drop_inode = 0;
6686
6687         /* do not allow sys_link's with other subvols of the same device */
6688         if (root->objectid != BTRFS_I(inode)->root->objectid)
6689                 return -EXDEV;
6690
6691         if (inode->i_nlink >= BTRFS_LINK_MAX)
6692                 return -EMLINK;
6693
6694         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6695         if (err)
6696                 goto fail;
6697
6698         /*
6699          * 2 items for inode and inode ref
6700          * 2 items for dir items
6701          * 1 item for parent inode
6702          */
6703         trans = btrfs_start_transaction(root, 5);
6704         if (IS_ERR(trans)) {
6705                 err = PTR_ERR(trans);
6706                 trans = NULL;
6707                 goto fail;
6708         }
6709
6710         /* There are several dir indexes for this inode, clear the cache. */
6711         BTRFS_I(inode)->dir_index = 0ULL;
6712         inc_nlink(inode);
6713         inode_inc_iversion(inode);
6714         inode->i_ctime = current_time(inode);
6715         ihold(inode);
6716         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6717
6718         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6719                         1, index);
6720
6721         if (err) {
6722                 drop_inode = 1;
6723         } else {
6724                 struct dentry *parent = dentry->d_parent;
6725                 err = btrfs_update_inode(trans, root, inode);
6726                 if (err)
6727                         goto fail;
6728                 if (inode->i_nlink == 1) {
6729                         /*
6730                          * If new hard link count is 1, it's a file created
6731                          * with open(2) O_TMPFILE flag.
6732                          */
6733                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6734                         if (err)
6735                                 goto fail;
6736                 }
6737                 d_instantiate(dentry, inode);
6738                 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6739         }
6740
6741 fail:
6742         if (trans)
6743                 btrfs_end_transaction(trans);
6744         if (drop_inode) {
6745                 inode_dec_link_count(inode);
6746                 iput(inode);
6747         }
6748         btrfs_btree_balance_dirty(fs_info);
6749         return err;
6750 }
6751
6752 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6753 {
6754         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6755         struct inode *inode = NULL;
6756         struct btrfs_trans_handle *trans;
6757         struct btrfs_root *root = BTRFS_I(dir)->root;
6758         int err = 0;
6759         int drop_on_err = 0;
6760         u64 objectid = 0;
6761         u64 index = 0;
6762
6763         /*
6764          * 2 items for inode and ref
6765          * 2 items for dir items
6766          * 1 for xattr if selinux is on
6767          */
6768         trans = btrfs_start_transaction(root, 5);
6769         if (IS_ERR(trans))
6770                 return PTR_ERR(trans);
6771
6772         err = btrfs_find_free_ino(root, &objectid);
6773         if (err)
6774                 goto out_fail;
6775
6776         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6777                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6778                         S_IFDIR | mode, &index);
6779         if (IS_ERR(inode)) {
6780                 err = PTR_ERR(inode);
6781                 goto out_fail;
6782         }
6783
6784         drop_on_err = 1;
6785         /* these must be set before we unlock the inode */
6786         inode->i_op = &btrfs_dir_inode_operations;
6787         inode->i_fop = &btrfs_dir_file_operations;
6788
6789         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6790         if (err)
6791                 goto out_fail_inode;
6792
6793         btrfs_i_size_write(BTRFS_I(inode), 0);
6794         err = btrfs_update_inode(trans, root, inode);
6795         if (err)
6796                 goto out_fail_inode;
6797
6798         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6799                         dentry->d_name.name,
6800                         dentry->d_name.len, 0, index);
6801         if (err)
6802                 goto out_fail_inode;
6803
6804         d_instantiate_new(dentry, inode);
6805         drop_on_err = 0;
6806
6807 out_fail:
6808         btrfs_end_transaction(trans);
6809         if (drop_on_err) {
6810                 inode_dec_link_count(inode);
6811                 iput(inode);
6812         }
6813         btrfs_btree_balance_dirty(fs_info);
6814         return err;
6815
6816 out_fail_inode:
6817         unlock_new_inode(inode);
6818         goto out_fail;
6819 }
6820
6821 static noinline int uncompress_inline(struct btrfs_path *path,
6822                                       struct page *page,
6823                                       size_t pg_offset, u64 extent_offset,
6824                                       struct btrfs_file_extent_item *item)
6825 {
6826         int ret;
6827         struct extent_buffer *leaf = path->nodes[0];
6828         char *tmp;
6829         size_t max_size;
6830         unsigned long inline_size;
6831         unsigned long ptr;
6832         int compress_type;
6833
6834         WARN_ON(pg_offset != 0);
6835         compress_type = btrfs_file_extent_compression(leaf, item);
6836         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6837         inline_size = btrfs_file_extent_inline_item_len(leaf,
6838                                         btrfs_item_nr(path->slots[0]));
6839         tmp = kmalloc(inline_size, GFP_NOFS);
6840         if (!tmp)
6841                 return -ENOMEM;
6842         ptr = btrfs_file_extent_inline_start(item);
6843
6844         read_extent_buffer(leaf, tmp, ptr, inline_size);
6845
6846         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6847         ret = btrfs_decompress(compress_type, tmp, page,
6848                                extent_offset, inline_size, max_size);
6849
6850         /*
6851          * decompression code contains a memset to fill in any space between the end
6852          * of the uncompressed data and the end of max_size in case the decompressed
6853          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6854          * the end of an inline extent and the beginning of the next block, so we
6855          * cover that region here.
6856          */
6857
6858         if (max_size + pg_offset < PAGE_SIZE) {
6859                 char *map = kmap(page);
6860                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6861                 kunmap(page);
6862         }
6863         kfree(tmp);
6864         return ret;
6865 }
6866
6867 /*
6868  * a bit scary, this does extent mapping from logical file offset to the disk.
6869  * the ugly parts come from merging extents from the disk with the in-ram
6870  * representation.  This gets more complex because of the data=ordered code,
6871  * where the in-ram extents might be locked pending data=ordered completion.
6872  *
6873  * This also copies inline extents directly into the page.
6874  */
6875 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6876                 struct page *page,
6877             size_t pg_offset, u64 start, u64 len,
6878                 int create)
6879 {
6880         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6881         int ret;
6882         int err = 0;
6883         u64 extent_start = 0;
6884         u64 extent_end = 0;
6885         u64 objectid = btrfs_ino(inode);
6886         u32 found_type;
6887         struct btrfs_path *path = NULL;
6888         struct btrfs_root *root = inode->root;
6889         struct btrfs_file_extent_item *item;
6890         struct extent_buffer *leaf;
6891         struct btrfs_key found_key;
6892         struct extent_map *em = NULL;
6893         struct extent_map_tree *em_tree = &inode->extent_tree;
6894         struct extent_io_tree *io_tree = &inode->io_tree;
6895         const bool new_inline = !page || create;
6896
6897         read_lock(&em_tree->lock);
6898         em = lookup_extent_mapping(em_tree, start, len);
6899         if (em)
6900                 em->bdev = fs_info->fs_devices->latest_bdev;
6901         read_unlock(&em_tree->lock);
6902
6903         if (em) {
6904                 if (em->start > start || em->start + em->len <= start)
6905                         free_extent_map(em);
6906                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6907                         free_extent_map(em);
6908                 else
6909                         goto out;
6910         }
6911         em = alloc_extent_map();
6912         if (!em) {
6913                 err = -ENOMEM;
6914                 goto out;
6915         }
6916         em->bdev = fs_info->fs_devices->latest_bdev;
6917         em->start = EXTENT_MAP_HOLE;
6918         em->orig_start = EXTENT_MAP_HOLE;
6919         em->len = (u64)-1;
6920         em->block_len = (u64)-1;
6921
6922         if (!path) {
6923                 path = btrfs_alloc_path();
6924                 if (!path) {
6925                         err = -ENOMEM;
6926                         goto out;
6927                 }
6928                 /*
6929                  * Chances are we'll be called again, so go ahead and do
6930                  * readahead
6931                  */
6932                 path->reada = READA_FORWARD;
6933         }
6934
6935         ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6936         if (ret < 0) {
6937                 err = ret;
6938                 goto out;
6939         }
6940
6941         if (ret != 0) {
6942                 if (path->slots[0] == 0)
6943                         goto not_found;
6944                 path->slots[0]--;
6945         }
6946
6947         leaf = path->nodes[0];
6948         item = btrfs_item_ptr(leaf, path->slots[0],
6949                               struct btrfs_file_extent_item);
6950         /* are we inside the extent that was found? */
6951         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6952         found_type = found_key.type;
6953         if (found_key.objectid != objectid ||
6954             found_type != BTRFS_EXTENT_DATA_KEY) {
6955                 /*
6956                  * If we backup past the first extent we want to move forward
6957                  * and see if there is an extent in front of us, otherwise we'll
6958                  * say there is a hole for our whole search range which can
6959                  * cause problems.
6960                  */
6961                 extent_end = start;
6962                 goto next;
6963         }
6964
6965         found_type = btrfs_file_extent_type(leaf, item);
6966         extent_start = found_key.offset;
6967         if (found_type == BTRFS_FILE_EXTENT_REG ||
6968             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6969                 extent_end = extent_start +
6970                        btrfs_file_extent_num_bytes(leaf, item);
6971
6972                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6973                                                        extent_start);
6974         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6975                 size_t size;
6976                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6977                 extent_end = ALIGN(extent_start + size,
6978                                    fs_info->sectorsize);
6979
6980                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6981                                                       path->slots[0],
6982                                                       extent_start);
6983         }
6984 next:
6985         if (start >= extent_end) {
6986                 path->slots[0]++;
6987                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6988                         ret = btrfs_next_leaf(root, path);
6989                         if (ret < 0) {
6990                                 err = ret;
6991                                 goto out;
6992                         }
6993                         if (ret > 0)
6994                                 goto not_found;
6995                         leaf = path->nodes[0];
6996                 }
6997                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6998                 if (found_key.objectid != objectid ||
6999                     found_key.type != BTRFS_EXTENT_DATA_KEY)
7000                         goto not_found;
7001                 if (start + len <= found_key.offset)
7002                         goto not_found;
7003                 if (start > found_key.offset)
7004                         goto next;
7005                 em->start = start;
7006                 em->orig_start = start;
7007                 em->len = found_key.offset - start;
7008                 goto not_found_em;
7009         }
7010
7011         btrfs_extent_item_to_extent_map(inode, path, item,
7012                         new_inline, em);
7013
7014         if (found_type == BTRFS_FILE_EXTENT_REG ||
7015             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7016                 goto insert;
7017         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7018                 unsigned long ptr;
7019                 char *map;
7020                 size_t size;
7021                 size_t extent_offset;
7022                 size_t copy_size;
7023
7024                 if (new_inline)
7025                         goto out;
7026
7027                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7028                 extent_offset = page_offset(page) + pg_offset - extent_start;
7029                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7030                                   size - extent_offset);
7031                 em->start = extent_start + extent_offset;
7032                 em->len = ALIGN(copy_size, fs_info->sectorsize);
7033                 em->orig_block_len = em->len;
7034                 em->orig_start = em->start;
7035                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7036                 if (!PageUptodate(page)) {
7037                         if (btrfs_file_extent_compression(leaf, item) !=
7038                             BTRFS_COMPRESS_NONE) {
7039                                 ret = uncompress_inline(path, page, pg_offset,
7040                                                         extent_offset, item);
7041                                 if (ret) {
7042                                         err = ret;
7043                                         goto out;
7044                                 }
7045                         } else {
7046                                 map = kmap(page);
7047                                 read_extent_buffer(leaf, map + pg_offset, ptr,
7048                                                    copy_size);
7049                                 if (pg_offset + copy_size < PAGE_SIZE) {
7050                                         memset(map + pg_offset + copy_size, 0,
7051                                                PAGE_SIZE - pg_offset -
7052                                                copy_size);
7053                                 }
7054                                 kunmap(page);
7055                         }
7056                         flush_dcache_page(page);
7057                 }
7058                 set_extent_uptodate(io_tree, em->start,
7059                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
7060                 goto insert;
7061         }
7062 not_found:
7063         em->start = start;
7064         em->orig_start = start;
7065         em->len = len;
7066 not_found_em:
7067         em->block_start = EXTENT_MAP_HOLE;
7068 insert:
7069         btrfs_release_path(path);
7070         if (em->start > start || extent_map_end(em) <= start) {
7071                 btrfs_err(fs_info,
7072                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7073                           em->start, em->len, start, len);
7074                 err = -EIO;
7075                 goto out;
7076         }
7077
7078         err = 0;
7079         write_lock(&em_tree->lock);
7080         err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7081         write_unlock(&em_tree->lock);
7082 out:
7083
7084         trace_btrfs_get_extent(root, inode, em);
7085
7086         btrfs_free_path(path);
7087         if (err) {
7088                 free_extent_map(em);
7089                 return ERR_PTR(err);
7090         }
7091         BUG_ON(!em); /* Error is always set */
7092         return em;
7093 }
7094
7095 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7096                 struct page *page,
7097                 size_t pg_offset, u64 start, u64 len,
7098                 int create)
7099 {
7100         struct extent_map *em;
7101         struct extent_map *hole_em = NULL;
7102         u64 range_start = start;
7103         u64 end;
7104         u64 found;
7105         u64 found_end;
7106         int err = 0;
7107
7108         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7109         if (IS_ERR(em))
7110                 return em;
7111         /*
7112          * If our em maps to:
7113          * - a hole or
7114          * - a pre-alloc extent,
7115          * there might actually be delalloc bytes behind it.
7116          */
7117         if (em->block_start != EXTENT_MAP_HOLE &&
7118             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7119                 return em;
7120         else
7121                 hole_em = em;
7122
7123         /* check to see if we've wrapped (len == -1 or similar) */
7124         end = start + len;
7125         if (end < start)
7126                 end = (u64)-1;
7127         else
7128                 end -= 1;
7129
7130         em = NULL;
7131
7132         /* ok, we didn't find anything, lets look for delalloc */
7133         found = count_range_bits(&inode->io_tree, &range_start,
7134                                  end, len, EXTENT_DELALLOC, 1);
7135         found_end = range_start + found;
7136         if (found_end < range_start)
7137                 found_end = (u64)-1;
7138
7139         /*
7140          * we didn't find anything useful, return
7141          * the original results from get_extent()
7142          */
7143         if (range_start > end || found_end <= start) {
7144                 em = hole_em;
7145                 hole_em = NULL;
7146                 goto out;
7147         }
7148
7149         /* adjust the range_start to make sure it doesn't
7150          * go backwards from the start they passed in
7151          */
7152         range_start = max(start, range_start);
7153         found = found_end - range_start;
7154
7155         if (found > 0) {
7156                 u64 hole_start = start;
7157                 u64 hole_len = len;
7158
7159                 em = alloc_extent_map();
7160                 if (!em) {
7161                         err = -ENOMEM;
7162                         goto out;
7163                 }
7164                 /*
7165                  * when btrfs_get_extent can't find anything it
7166                  * returns one huge hole
7167                  *
7168                  * make sure what it found really fits our range, and
7169                  * adjust to make sure it is based on the start from
7170                  * the caller
7171                  */
7172                 if (hole_em) {
7173                         u64 calc_end = extent_map_end(hole_em);
7174
7175                         if (calc_end <= start || (hole_em->start > end)) {
7176                                 free_extent_map(hole_em);
7177                                 hole_em = NULL;
7178                         } else {
7179                                 hole_start = max(hole_em->start, start);
7180                                 hole_len = calc_end - hole_start;
7181                         }
7182                 }
7183                 em->bdev = NULL;
7184                 if (hole_em && range_start > hole_start) {
7185                         /* our hole starts before our delalloc, so we
7186                          * have to return just the parts of the hole
7187                          * that go until  the delalloc starts
7188                          */
7189                         em->len = min(hole_len,
7190                                       range_start - hole_start);
7191                         em->start = hole_start;
7192                         em->orig_start = hole_start;
7193                         /*
7194                          * don't adjust block start at all,
7195                          * it is fixed at EXTENT_MAP_HOLE
7196                          */
7197                         em->block_start = hole_em->block_start;
7198                         em->block_len = hole_len;
7199                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7200                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7201                 } else {
7202                         em->start = range_start;
7203                         em->len = found;
7204                         em->orig_start = range_start;
7205                         em->block_start = EXTENT_MAP_DELALLOC;
7206                         em->block_len = found;
7207                 }
7208         } else {
7209                 return hole_em;
7210         }
7211 out:
7212
7213         free_extent_map(hole_em);
7214         if (err) {
7215                 free_extent_map(em);
7216                 return ERR_PTR(err);
7217         }
7218         return em;
7219 }
7220
7221 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7222                                                   const u64 start,
7223                                                   const u64 len,
7224                                                   const u64 orig_start,
7225                                                   const u64 block_start,
7226                                                   const u64 block_len,
7227                                                   const u64 orig_block_len,
7228                                                   const u64 ram_bytes,
7229                                                   const int type)
7230 {
7231         struct extent_map *em = NULL;
7232         int ret;
7233
7234         if (type != BTRFS_ORDERED_NOCOW) {
7235                 em = create_io_em(inode, start, len, orig_start,
7236                                   block_start, block_len, orig_block_len,
7237                                   ram_bytes,
7238                                   BTRFS_COMPRESS_NONE, /* compress_type */
7239                                   type);
7240                 if (IS_ERR(em))
7241                         goto out;
7242         }
7243         ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7244                                            len, block_len, type);
7245         if (ret) {
7246                 if (em) {
7247                         free_extent_map(em);
7248                         btrfs_drop_extent_cache(BTRFS_I(inode), start,
7249                                                 start + len - 1, 0);
7250                 }
7251                 em = ERR_PTR(ret);
7252         }
7253  out:
7254
7255         return em;
7256 }
7257
7258 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7259                                                   u64 start, u64 len)
7260 {
7261         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7262         struct btrfs_root *root = BTRFS_I(inode)->root;
7263         struct extent_map *em;
7264         struct btrfs_key ins;
7265         u64 alloc_hint;
7266         int ret;
7267
7268         alloc_hint = get_extent_allocation_hint(inode, start, len);
7269         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7270                                    0, alloc_hint, &ins, 1, 1);
7271         if (ret)
7272                 return ERR_PTR(ret);
7273
7274         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7275                                      ins.objectid, ins.offset, ins.offset,
7276                                      ins.offset, BTRFS_ORDERED_REGULAR);
7277         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7278         if (IS_ERR(em))
7279                 btrfs_free_reserved_extent(fs_info, ins.objectid,
7280                                            ins.offset, 1);
7281
7282         return em;
7283 }
7284
7285 /*
7286  * returns 1 when the nocow is safe, < 1 on error, 0 if the
7287  * block must be cow'd
7288  */
7289 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7290                               u64 *orig_start, u64 *orig_block_len,
7291                               u64 *ram_bytes)
7292 {
7293         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7294         struct btrfs_path *path;
7295         int ret;
7296         struct extent_buffer *leaf;
7297         struct btrfs_root *root = BTRFS_I(inode)->root;
7298         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7299         struct btrfs_file_extent_item *fi;
7300         struct btrfs_key key;
7301         u64 disk_bytenr;
7302         u64 backref_offset;
7303         u64 extent_end;
7304         u64 num_bytes;
7305         int slot;
7306         int found_type;
7307         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7308
7309         path = btrfs_alloc_path();
7310         if (!path)
7311                 return -ENOMEM;
7312
7313         ret = btrfs_lookup_file_extent(NULL, root, path,
7314                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7315         if (ret < 0)
7316                 goto out;
7317
7318         slot = path->slots[0];
7319         if (ret == 1) {
7320                 if (slot == 0) {
7321                         /* can't find the item, must cow */
7322                         ret = 0;
7323                         goto out;
7324                 }
7325                 slot--;
7326         }
7327         ret = 0;
7328         leaf = path->nodes[0];
7329         btrfs_item_key_to_cpu(leaf, &key, slot);
7330         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7331             key.type != BTRFS_EXTENT_DATA_KEY) {
7332                 /* not our file or wrong item type, must cow */
7333                 goto out;
7334         }
7335
7336         if (key.offset > offset) {
7337                 /* Wrong offset, must cow */
7338                 goto out;
7339         }
7340
7341         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7342         found_type = btrfs_file_extent_type(leaf, fi);
7343         if (found_type != BTRFS_FILE_EXTENT_REG &&
7344             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7345                 /* not a regular extent, must cow */
7346                 goto out;
7347         }
7348
7349         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7350                 goto out;
7351
7352         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7353         if (extent_end <= offset)
7354                 goto out;
7355
7356         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7357         if (disk_bytenr == 0)
7358                 goto out;
7359
7360         if (btrfs_file_extent_compression(leaf, fi) ||
7361             btrfs_file_extent_encryption(leaf, fi) ||
7362             btrfs_file_extent_other_encoding(leaf, fi))
7363                 goto out;
7364
7365         backref_offset = btrfs_file_extent_offset(leaf, fi);
7366
7367         if (orig_start) {
7368                 *orig_start = key.offset - backref_offset;
7369                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7370                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7371         }
7372
7373         if (btrfs_extent_readonly(fs_info, disk_bytenr))
7374                 goto out;
7375
7376         num_bytes = min(offset + *len, extent_end) - offset;
7377         if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7378                 u64 range_end;
7379
7380                 range_end = round_up(offset + num_bytes,
7381                                      root->fs_info->sectorsize) - 1;
7382                 ret = test_range_bit(io_tree, offset, range_end,
7383                                      EXTENT_DELALLOC, 0, NULL);
7384                 if (ret) {
7385                         ret = -EAGAIN;
7386                         goto out;
7387                 }
7388         }
7389
7390         btrfs_release_path(path);
7391
7392         /*
7393          * look for other files referencing this extent, if we
7394          * find any we must cow
7395          */
7396
7397         ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7398                                     key.offset - backref_offset, disk_bytenr);
7399         if (ret) {
7400                 ret = 0;
7401                 goto out;
7402         }
7403
7404         /*
7405          * adjust disk_bytenr and num_bytes to cover just the bytes
7406          * in this extent we are about to write.  If there
7407          * are any csums in that range we have to cow in order
7408          * to keep the csums correct
7409          */
7410         disk_bytenr += backref_offset;
7411         disk_bytenr += offset - key.offset;
7412         if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7413                 goto out;
7414         /*
7415          * all of the above have passed, it is safe to overwrite this extent
7416          * without cow
7417          */
7418         *len = num_bytes;
7419         ret = 1;
7420 out:
7421         btrfs_free_path(path);
7422         return ret;
7423 }
7424
7425 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7426                               struct extent_state **cached_state, int writing)
7427 {
7428         struct btrfs_ordered_extent *ordered;
7429         int ret = 0;
7430
7431         while (1) {
7432                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7433                                  cached_state);
7434                 /*
7435                  * We're concerned with the entire range that we're going to be
7436                  * doing DIO to, so we need to make sure there's no ordered
7437                  * extents in this range.
7438                  */
7439                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7440                                                      lockend - lockstart + 1);
7441
7442                 /*
7443                  * We need to make sure there are no buffered pages in this
7444                  * range either, we could have raced between the invalidate in
7445                  * generic_file_direct_write and locking the extent.  The
7446                  * invalidate needs to happen so that reads after a write do not
7447                  * get stale data.
7448                  */
7449                 if (!ordered &&
7450                     (!writing || !filemap_range_has_page(inode->i_mapping,
7451                                                          lockstart, lockend)))
7452                         break;
7453
7454                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7455                                      cached_state);
7456
7457                 if (ordered) {
7458                         /*
7459                          * If we are doing a DIO read and the ordered extent we
7460                          * found is for a buffered write, we can not wait for it
7461                          * to complete and retry, because if we do so we can
7462                          * deadlock with concurrent buffered writes on page
7463                          * locks. This happens only if our DIO read covers more
7464                          * than one extent map, if at this point has already
7465                          * created an ordered extent for a previous extent map
7466                          * and locked its range in the inode's io tree, and a
7467                          * concurrent write against that previous extent map's
7468                          * range and this range started (we unlock the ranges
7469                          * in the io tree only when the bios complete and
7470                          * buffered writes always lock pages before attempting
7471                          * to lock range in the io tree).
7472                          */
7473                         if (writing ||
7474                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7475                                 btrfs_start_ordered_extent(inode, ordered, 1);
7476                         else
7477                                 ret = -ENOTBLK;
7478                         btrfs_put_ordered_extent(ordered);
7479                 } else {
7480                         /*
7481                          * We could trigger writeback for this range (and wait
7482                          * for it to complete) and then invalidate the pages for
7483                          * this range (through invalidate_inode_pages2_range()),
7484                          * but that can lead us to a deadlock with a concurrent
7485                          * call to readpages() (a buffered read or a defrag call
7486                          * triggered a readahead) on a page lock due to an
7487                          * ordered dio extent we created before but did not have
7488                          * yet a corresponding bio submitted (whence it can not
7489                          * complete), which makes readpages() wait for that
7490                          * ordered extent to complete while holding a lock on
7491                          * that page.
7492                          */
7493                         ret = -ENOTBLK;
7494                 }
7495
7496                 if (ret)
7497                         break;
7498
7499                 cond_resched();
7500         }
7501
7502         return ret;
7503 }
7504
7505 /* The callers of this must take lock_extent() */
7506 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7507                                        u64 orig_start, u64 block_start,
7508                                        u64 block_len, u64 orig_block_len,
7509                                        u64 ram_bytes, int compress_type,
7510                                        int type)
7511 {
7512         struct extent_map_tree *em_tree;
7513         struct extent_map *em;
7514         struct btrfs_root *root = BTRFS_I(inode)->root;
7515         int ret;
7516
7517         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7518                type == BTRFS_ORDERED_COMPRESSED ||
7519                type == BTRFS_ORDERED_NOCOW ||
7520                type == BTRFS_ORDERED_REGULAR);
7521
7522         em_tree = &BTRFS_I(inode)->extent_tree;
7523         em = alloc_extent_map();
7524         if (!em)
7525                 return ERR_PTR(-ENOMEM);
7526
7527         em->start = start;
7528         em->orig_start = orig_start;
7529         em->len = len;
7530         em->block_len = block_len;
7531         em->block_start = block_start;
7532         em->bdev = root->fs_info->fs_devices->latest_bdev;
7533         em->orig_block_len = orig_block_len;
7534         em->ram_bytes = ram_bytes;
7535         em->generation = -1;
7536         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7537         if (type == BTRFS_ORDERED_PREALLOC) {
7538                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7539         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7540                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7541                 em->compress_type = compress_type;
7542         }
7543
7544         do {
7545                 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7546                                 em->start + em->len - 1, 0);
7547                 write_lock(&em_tree->lock);
7548                 ret = add_extent_mapping(em_tree, em, 1);
7549                 write_unlock(&em_tree->lock);
7550                 /*
7551                  * The caller has taken lock_extent(), who could race with us
7552                  * to add em?
7553                  */
7554         } while (ret == -EEXIST);
7555
7556         if (ret) {
7557                 free_extent_map(em);
7558                 return ERR_PTR(ret);
7559         }
7560
7561         /* em got 2 refs now, callers needs to do free_extent_map once. */
7562         return em;
7563 }
7564
7565 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7566                                    struct buffer_head *bh_result, int create)
7567 {
7568         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7569         struct extent_map *em;
7570         struct extent_state *cached_state = NULL;
7571         struct btrfs_dio_data *dio_data = NULL;
7572         u64 start = iblock << inode->i_blkbits;
7573         u64 lockstart, lockend;
7574         u64 len = bh_result->b_size;
7575         int unlock_bits = EXTENT_LOCKED;
7576         int ret = 0;
7577
7578         if (create)
7579                 unlock_bits |= EXTENT_DIRTY;
7580         else
7581                 len = min_t(u64, len, fs_info->sectorsize);
7582
7583         lockstart = start;
7584         lockend = start + len - 1;
7585
7586         if (current->journal_info) {
7587                 /*
7588                  * Need to pull our outstanding extents and set journal_info to NULL so
7589                  * that anything that needs to check if there's a transaction doesn't get
7590                  * confused.
7591                  */
7592                 dio_data = current->journal_info;
7593                 current->journal_info = NULL;
7594         }
7595
7596         /*
7597          * If this errors out it's because we couldn't invalidate pagecache for
7598          * this range and we need to fallback to buffered.
7599          */
7600         if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7601                                create)) {
7602                 ret = -ENOTBLK;
7603                 goto err;
7604         }
7605
7606         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7607         if (IS_ERR(em)) {
7608                 ret = PTR_ERR(em);
7609                 goto unlock_err;
7610         }
7611
7612         /*
7613          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7614          * io.  INLINE is special, and we could probably kludge it in here, but
7615          * it's still buffered so for safety lets just fall back to the generic
7616          * buffered path.
7617          *
7618          * For COMPRESSED we _have_ to read the entire extent in so we can
7619          * decompress it, so there will be buffering required no matter what we
7620          * do, so go ahead and fallback to buffered.
7621          *
7622          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7623          * to buffered IO.  Don't blame me, this is the price we pay for using
7624          * the generic code.
7625          */
7626         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7627             em->block_start == EXTENT_MAP_INLINE) {
7628                 free_extent_map(em);
7629                 ret = -ENOTBLK;
7630                 goto unlock_err;
7631         }
7632
7633         /* Just a good old fashioned hole, return */
7634         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7635                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7636                 free_extent_map(em);
7637                 goto unlock_err;
7638         }
7639
7640         /*
7641          * We don't allocate a new extent in the following cases
7642          *
7643          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
7644          * existing extent.
7645          * 2) The extent is marked as PREALLOC.  We're good to go here and can
7646          * just use the extent.
7647          *
7648          */
7649         if (!create) {
7650                 len = min(len, em->len - (start - em->start));
7651                 lockstart = start + len;
7652                 goto unlock;
7653         }
7654
7655         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7656             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7657              em->block_start != EXTENT_MAP_HOLE)) {
7658                 int type;
7659                 u64 block_start, orig_start, orig_block_len, ram_bytes;
7660
7661                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7662                         type = BTRFS_ORDERED_PREALLOC;
7663                 else
7664                         type = BTRFS_ORDERED_NOCOW;
7665                 len = min(len, em->len - (start - em->start));
7666                 block_start = em->block_start + (start - em->start);
7667
7668                 if (can_nocow_extent(inode, start, &len, &orig_start,
7669                                      &orig_block_len, &ram_bytes) == 1 &&
7670                     btrfs_inc_nocow_writers(fs_info, block_start)) {
7671                         struct extent_map *em2;
7672
7673                         em2 = btrfs_create_dio_extent(inode, start, len,
7674                                                       orig_start, block_start,
7675                                                       len, orig_block_len,
7676                                                       ram_bytes, type);
7677                         btrfs_dec_nocow_writers(fs_info, block_start);
7678                         if (type == BTRFS_ORDERED_PREALLOC) {
7679                                 free_extent_map(em);
7680                                 em = em2;
7681                         }
7682                         if (em2 && IS_ERR(em2)) {
7683                                 ret = PTR_ERR(em2);
7684                                 goto unlock_err;
7685                         }
7686                         /*
7687                          * For inode marked NODATACOW or extent marked PREALLOC,
7688                          * use the existing or preallocated extent, so does not
7689                          * need to adjust btrfs_space_info's bytes_may_use.
7690                          */
7691                         btrfs_free_reserved_data_space_noquota(inode,
7692                                         start, len);
7693                         goto unlock;
7694                 }
7695         }
7696
7697         /*
7698          * this will cow the extent, reset the len in case we changed
7699          * it above
7700          */
7701         len = bh_result->b_size;
7702         free_extent_map(em);
7703         em = btrfs_new_extent_direct(inode, start, len);
7704         if (IS_ERR(em)) {
7705                 ret = PTR_ERR(em);
7706                 goto unlock_err;
7707         }
7708         len = min(len, em->len - (start - em->start));
7709 unlock:
7710         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7711                 inode->i_blkbits;
7712         bh_result->b_size = len;
7713         bh_result->b_bdev = em->bdev;
7714         set_buffer_mapped(bh_result);
7715         if (create) {
7716                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7717                         set_buffer_new(bh_result);
7718
7719                 /*
7720                  * Need to update the i_size under the extent lock so buffered
7721                  * readers will get the updated i_size when we unlock.
7722                  */
7723                 if (!dio_data->overwrite && start + len > i_size_read(inode))
7724                         i_size_write(inode, start + len);
7725
7726                 WARN_ON(dio_data->reserve < len);
7727                 dio_data->reserve -= len;
7728                 dio_data->unsubmitted_oe_range_end = start + len;
7729                 current->journal_info = dio_data;
7730         }
7731
7732         /*
7733          * In the case of write we need to clear and unlock the entire range,
7734          * in the case of read we need to unlock only the end area that we
7735          * aren't using if there is any left over space.
7736          */
7737         if (lockstart < lockend) {
7738                 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7739                                  lockend, unlock_bits, 1, 0,
7740                                  &cached_state);
7741         } else {
7742                 free_extent_state(cached_state);
7743         }
7744
7745         free_extent_map(em);
7746
7747         return 0;
7748
7749 unlock_err:
7750         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7751                          unlock_bits, 1, 0, &cached_state);
7752 err:
7753         if (dio_data)
7754                 current->journal_info = dio_data;
7755         return ret;
7756 }
7757
7758 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7759                                                  struct bio *bio,
7760                                                  int mirror_num)
7761 {
7762         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7763         blk_status_t ret;
7764
7765         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7766
7767         ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7768         if (ret)
7769                 return ret;
7770
7771         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7772
7773         return ret;
7774 }
7775
7776 static int btrfs_check_dio_repairable(struct inode *inode,
7777                                       struct bio *failed_bio,
7778                                       struct io_failure_record *failrec,
7779                                       int failed_mirror)
7780 {
7781         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7782         int num_copies;
7783
7784         num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7785         if (num_copies == 1) {
7786                 /*
7787                  * we only have a single copy of the data, so don't bother with
7788                  * all the retry and error correction code that follows. no
7789                  * matter what the error is, it is very likely to persist.
7790                  */
7791                 btrfs_debug(fs_info,
7792                         "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7793                         num_copies, failrec->this_mirror, failed_mirror);
7794                 return 0;
7795         }
7796
7797         failrec->failed_mirror = failed_mirror;
7798         failrec->this_mirror++;
7799         if (failrec->this_mirror == failed_mirror)
7800                 failrec->this_mirror++;
7801
7802         if (failrec->this_mirror > num_copies) {
7803                 btrfs_debug(fs_info,
7804                         "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7805                         num_copies, failrec->this_mirror, failed_mirror);
7806                 return 0;
7807         }
7808
7809         return 1;
7810 }
7811
7812 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7813                                    struct page *page, unsigned int pgoff,
7814                                    u64 start, u64 end, int failed_mirror,
7815                                    bio_end_io_t *repair_endio, void *repair_arg)
7816 {
7817         struct io_failure_record *failrec;
7818         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7819         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7820         struct bio *bio;
7821         int isector;
7822         unsigned int read_mode = 0;
7823         int segs;
7824         int ret;
7825         blk_status_t status;
7826         struct bio_vec bvec;
7827
7828         BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7829
7830         ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7831         if (ret)
7832                 return errno_to_blk_status(ret);
7833
7834         ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7835                                          failed_mirror);
7836         if (!ret) {
7837                 free_io_failure(failure_tree, io_tree, failrec);
7838                 return BLK_STS_IOERR;
7839         }
7840
7841         segs = bio_segments(failed_bio);
7842         bio_get_first_bvec(failed_bio, &bvec);
7843         if (segs > 1 ||
7844             (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7845                 read_mode |= REQ_FAILFAST_DEV;
7846
7847         isector = start - btrfs_io_bio(failed_bio)->logical;
7848         isector >>= inode->i_sb->s_blocksize_bits;
7849         bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7850                                 pgoff, isector, repair_endio, repair_arg);
7851         bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7852
7853         btrfs_debug(BTRFS_I(inode)->root->fs_info,
7854                     "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7855                     read_mode, failrec->this_mirror, failrec->in_validation);
7856
7857         status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7858         if (status) {
7859                 free_io_failure(failure_tree, io_tree, failrec);
7860                 bio_put(bio);
7861         }
7862
7863         return status;
7864 }
7865
7866 struct btrfs_retry_complete {
7867         struct completion done;
7868         struct inode *inode;
7869         u64 start;
7870         int uptodate;
7871 };
7872
7873 static void btrfs_retry_endio_nocsum(struct bio *bio)
7874 {
7875         struct btrfs_retry_complete *done = bio->bi_private;
7876         struct inode *inode = done->inode;
7877         struct bio_vec *bvec;
7878         struct extent_io_tree *io_tree, *failure_tree;
7879         int i;
7880
7881         if (bio->bi_status)
7882                 goto end;
7883
7884         ASSERT(bio->bi_vcnt == 1);
7885         io_tree = &BTRFS_I(inode)->io_tree;
7886         failure_tree = &BTRFS_I(inode)->io_failure_tree;
7887         ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7888
7889         done->uptodate = 1;
7890         ASSERT(!bio_flagged(bio, BIO_CLONED));
7891         bio_for_each_segment_all(bvec, bio, i)
7892                 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7893                                  io_tree, done->start, bvec->bv_page,
7894                                  btrfs_ino(BTRFS_I(inode)), 0);
7895 end:
7896         complete(&done->done);
7897         bio_put(bio);
7898 }
7899
7900 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7901                                                 struct btrfs_io_bio *io_bio)
7902 {
7903         struct btrfs_fs_info *fs_info;
7904         struct bio_vec bvec;
7905         struct bvec_iter iter;
7906         struct btrfs_retry_complete done;
7907         u64 start;
7908         unsigned int pgoff;
7909         u32 sectorsize;
7910         int nr_sectors;
7911         blk_status_t ret;
7912         blk_status_t err = BLK_STS_OK;
7913
7914         fs_info = BTRFS_I(inode)->root->fs_info;
7915         sectorsize = fs_info->sectorsize;
7916
7917         start = io_bio->logical;
7918         done.inode = inode;
7919         io_bio->bio.bi_iter = io_bio->iter;
7920
7921         bio_for_each_segment(bvec, &io_bio->bio, iter) {
7922                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7923                 pgoff = bvec.bv_offset;
7924
7925 next_block_or_try_again:
7926                 done.uptodate = 0;
7927                 done.start = start;
7928                 init_completion(&done.done);
7929
7930                 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7931                                 pgoff, start, start + sectorsize - 1,
7932                                 io_bio->mirror_num,
7933                                 btrfs_retry_endio_nocsum, &done);
7934                 if (ret) {
7935                         err = ret;
7936                         goto next;
7937                 }
7938
7939                 wait_for_completion_io(&done.done);
7940
7941                 if (!done.uptodate) {
7942                         /* We might have another mirror, so try again */
7943                         goto next_block_or_try_again;
7944                 }
7945
7946 next:
7947                 start += sectorsize;
7948
7949                 nr_sectors--;
7950                 if (nr_sectors) {
7951                         pgoff += sectorsize;
7952                         ASSERT(pgoff < PAGE_SIZE);
7953                         goto next_block_or_try_again;
7954                 }
7955         }
7956
7957         return err;
7958 }
7959
7960 static void btrfs_retry_endio(struct bio *bio)
7961 {
7962         struct btrfs_retry_complete *done = bio->bi_private;
7963         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7964         struct extent_io_tree *io_tree, *failure_tree;
7965         struct inode *inode = done->inode;
7966         struct bio_vec *bvec;
7967         int uptodate;
7968         int ret;
7969         int i;
7970
7971         if (bio->bi_status)
7972                 goto end;
7973
7974         uptodate = 1;
7975
7976         ASSERT(bio->bi_vcnt == 1);
7977         ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7978
7979         io_tree = &BTRFS_I(inode)->io_tree;
7980         failure_tree = &BTRFS_I(inode)->io_failure_tree;
7981
7982         ASSERT(!bio_flagged(bio, BIO_CLONED));
7983         bio_for_each_segment_all(bvec, bio, i) {
7984                 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7985                                              bvec->bv_offset, done->start,
7986                                              bvec->bv_len);
7987                 if (!ret)
7988                         clean_io_failure(BTRFS_I(inode)->root->fs_info,
7989                                          failure_tree, io_tree, done->start,
7990                                          bvec->bv_page,
7991                                          btrfs_ino(BTRFS_I(inode)),
7992                                          bvec->bv_offset);
7993                 else
7994                         uptodate = 0;
7995         }
7996
7997         done->uptodate = uptodate;
7998 end:
7999         complete(&done->done);
8000         bio_put(bio);
8001 }
8002
8003 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8004                 struct btrfs_io_bio *io_bio, blk_status_t err)
8005 {
8006         struct btrfs_fs_info *fs_info;
8007         struct bio_vec bvec;
8008         struct bvec_iter iter;
8009         struct btrfs_retry_complete done;
8010         u64 start;
8011         u64 offset = 0;
8012         u32 sectorsize;
8013         int nr_sectors;
8014         unsigned int pgoff;
8015         int csum_pos;
8016         bool uptodate = (err == 0);
8017         int ret;
8018         blk_status_t status;
8019
8020         fs_info = BTRFS_I(inode)->root->fs_info;
8021         sectorsize = fs_info->sectorsize;
8022
8023         err = BLK_STS_OK;
8024         start = io_bio->logical;
8025         done.inode = inode;
8026         io_bio->bio.bi_iter = io_bio->iter;
8027
8028         bio_for_each_segment(bvec, &io_bio->bio, iter) {
8029                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8030
8031                 pgoff = bvec.bv_offset;
8032 next_block:
8033                 if (uptodate) {
8034                         csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8035                         ret = __readpage_endio_check(inode, io_bio, csum_pos,
8036                                         bvec.bv_page, pgoff, start, sectorsize);
8037                         if (likely(!ret))
8038                                 goto next;
8039                 }
8040 try_again:
8041                 done.uptodate = 0;
8042                 done.start = start;
8043                 init_completion(&done.done);
8044
8045                 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8046                                         pgoff, start, start + sectorsize - 1,
8047                                         io_bio->mirror_num, btrfs_retry_endio,
8048                                         &done);
8049                 if (status) {
8050                         err = status;
8051                         goto next;
8052                 }
8053
8054                 wait_for_completion_io(&done.done);
8055
8056                 if (!done.uptodate) {
8057                         /* We might have another mirror, so try again */
8058                         goto try_again;
8059                 }
8060 next:
8061                 offset += sectorsize;
8062                 start += sectorsize;
8063
8064                 ASSERT(nr_sectors);
8065
8066                 nr_sectors--;
8067                 if (nr_sectors) {
8068                         pgoff += sectorsize;
8069                         ASSERT(pgoff < PAGE_SIZE);
8070                         goto next_block;
8071                 }
8072         }
8073
8074         return err;
8075 }
8076
8077 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8078                 struct btrfs_io_bio *io_bio, blk_status_t err)
8079 {
8080         bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8081
8082         if (skip_csum) {
8083                 if (unlikely(err))
8084                         return __btrfs_correct_data_nocsum(inode, io_bio);
8085                 else
8086                         return BLK_STS_OK;
8087         } else {
8088                 return __btrfs_subio_endio_read(inode, io_bio, err);
8089         }
8090 }
8091
8092 static void btrfs_endio_direct_read(struct bio *bio)
8093 {
8094         struct btrfs_dio_private *dip = bio->bi_private;
8095         struct inode *inode = dip->inode;
8096         struct bio *dio_bio;
8097         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8098         blk_status_t err = bio->bi_status;
8099
8100         if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8101                 err = btrfs_subio_endio_read(inode, io_bio, err);
8102
8103         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8104                       dip->logical_offset + dip->bytes - 1);
8105         dio_bio = dip->dio_bio;
8106
8107         kfree(dip);
8108
8109         dio_bio->bi_status = err;
8110         dio_end_io(dio_bio);
8111
8112         if (io_bio->end_io)
8113                 io_bio->end_io(io_bio, blk_status_to_errno(err));
8114         bio_put(bio);
8115 }
8116
8117 static void __endio_write_update_ordered(struct inode *inode,
8118                                          const u64 offset, const u64 bytes,
8119                                          const bool uptodate)
8120 {
8121         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8122         struct btrfs_ordered_extent *ordered = NULL;
8123         struct btrfs_workqueue *wq;
8124         btrfs_work_func_t func;
8125         u64 ordered_offset = offset;
8126         u64 ordered_bytes = bytes;
8127         u64 last_offset;
8128
8129         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8130                 wq = fs_info->endio_freespace_worker;
8131                 func = btrfs_freespace_write_helper;
8132         } else {
8133                 wq = fs_info->endio_write_workers;
8134                 func = btrfs_endio_write_helper;
8135         }
8136
8137         while (ordered_offset < offset + bytes) {
8138                 last_offset = ordered_offset;
8139                 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8140                                                            &ordered_offset,
8141                                                            ordered_bytes,
8142                                                            uptodate)) {
8143                         btrfs_init_work(&ordered->work, func,
8144                                         finish_ordered_fn,
8145                                         NULL, NULL);
8146                         btrfs_queue_work(wq, &ordered->work);
8147                 }
8148                 /*
8149                  * If btrfs_dec_test_ordered_pending does not find any ordered
8150                  * extent in the range, we can exit.
8151                  */
8152                 if (ordered_offset == last_offset)
8153                         return;
8154                 /*
8155                  * Our bio might span multiple ordered extents. In this case
8156                  * we keep goin until we have accounted the whole dio.
8157                  */
8158                 if (ordered_offset < offset + bytes) {
8159                         ordered_bytes = offset + bytes - ordered_offset;
8160                         ordered = NULL;
8161                 }
8162         }
8163 }
8164
8165 static void btrfs_endio_direct_write(struct bio *bio)
8166 {
8167         struct btrfs_dio_private *dip = bio->bi_private;
8168         struct bio *dio_bio = dip->dio_bio;
8169
8170         __endio_write_update_ordered(dip->inode, dip->logical_offset,
8171                                      dip->bytes, !bio->bi_status);
8172
8173         kfree(dip);
8174
8175         dio_bio->bi_status = bio->bi_status;
8176         dio_end_io(dio_bio);
8177         bio_put(bio);
8178 }
8179
8180 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8181                                     struct bio *bio, u64 offset)
8182 {
8183         struct inode *inode = private_data;
8184         blk_status_t ret;
8185         ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8186         BUG_ON(ret); /* -ENOMEM */
8187         return 0;
8188 }
8189
8190 static void btrfs_end_dio_bio(struct bio *bio)
8191 {
8192         struct btrfs_dio_private *dip = bio->bi_private;
8193         blk_status_t err = bio->bi_status;
8194
8195         if (err)
8196                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8197                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8198                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8199                            bio->bi_opf,
8200                            (unsigned long long)bio->bi_iter.bi_sector,
8201                            bio->bi_iter.bi_size, err);
8202
8203         if (dip->subio_endio)
8204                 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8205
8206         if (err) {
8207                 /*
8208                  * We want to perceive the errors flag being set before
8209                  * decrementing the reference count. We don't need a barrier
8210                  * since atomic operations with a return value are fully
8211                  * ordered as per atomic_t.txt
8212                  */
8213                 dip->errors = 1;
8214         }
8215
8216         /* if there are more bios still pending for this dio, just exit */
8217         if (!atomic_dec_and_test(&dip->pending_bios))
8218                 goto out;
8219
8220         if (dip->errors) {
8221                 bio_io_error(dip->orig_bio);
8222         } else {
8223                 dip->dio_bio->bi_status = BLK_STS_OK;
8224                 bio_endio(dip->orig_bio);
8225         }
8226 out:
8227         bio_put(bio);
8228 }
8229
8230 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8231                                                  struct btrfs_dio_private *dip,
8232                                                  struct bio *bio,
8233                                                  u64 file_offset)
8234 {
8235         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8236         struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8237         blk_status_t ret;
8238
8239         /*
8240          * We load all the csum data we need when we submit
8241          * the first bio to reduce the csum tree search and
8242          * contention.
8243          */
8244         if (dip->logical_offset == file_offset) {
8245                 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8246                                                 file_offset);
8247                 if (ret)
8248                         return ret;
8249         }
8250
8251         if (bio == dip->orig_bio)
8252                 return 0;
8253
8254         file_offset -= dip->logical_offset;
8255         file_offset >>= inode->i_sb->s_blocksize_bits;
8256         io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8257
8258         return 0;
8259 }
8260
8261 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8262                 struct inode *inode, u64 file_offset, int async_submit)
8263 {
8264         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8265         struct btrfs_dio_private *dip = bio->bi_private;
8266         bool write = bio_op(bio) == REQ_OP_WRITE;
8267         blk_status_t ret;
8268
8269         /* Check btrfs_submit_bio_hook() for rules about async submit. */
8270         if (async_submit)
8271                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8272
8273         if (!write) {
8274                 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8275                 if (ret)
8276                         goto err;
8277         }
8278
8279         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8280                 goto map;
8281
8282         if (write && async_submit) {
8283                 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8284                                           file_offset, inode,
8285                                           btrfs_submit_bio_start_direct_io,
8286                                           btrfs_submit_bio_done);
8287                 goto err;
8288         } else if (write) {
8289                 /*
8290                  * If we aren't doing async submit, calculate the csum of the
8291                  * bio now.
8292                  */
8293                 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8294                 if (ret)
8295                         goto err;
8296         } else {
8297                 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8298                                                      file_offset);
8299                 if (ret)
8300                         goto err;
8301         }
8302 map:
8303         ret = btrfs_map_bio(fs_info, bio, 0, 0);
8304 err:
8305         return ret;
8306 }
8307
8308 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8309 {
8310         struct inode *inode = dip->inode;
8311         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8312         struct bio *bio;
8313         struct bio *orig_bio = dip->orig_bio;
8314         u64 start_sector = orig_bio->bi_iter.bi_sector;
8315         u64 file_offset = dip->logical_offset;
8316         u64 map_length;
8317         int async_submit = 0;
8318         u64 submit_len;
8319         int clone_offset = 0;
8320         int clone_len;
8321         int ret;
8322         blk_status_t status;
8323
8324         map_length = orig_bio->bi_iter.bi_size;
8325         submit_len = map_length;
8326         ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8327                               &map_length, NULL, 0);
8328         if (ret)
8329                 return -EIO;
8330
8331         if (map_length >= submit_len) {
8332                 bio = orig_bio;
8333                 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8334                 goto submit;
8335         }
8336
8337         /* async crcs make it difficult to collect full stripe writes. */
8338         if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8339                 async_submit = 0;
8340         else
8341                 async_submit = 1;
8342
8343         /* bio split */
8344         ASSERT(map_length <= INT_MAX);
8345         atomic_inc(&dip->pending_bios);
8346         do {
8347                 clone_len = min_t(int, submit_len, map_length);
8348
8349                 /*
8350                  * This will never fail as it's passing GPF_NOFS and
8351                  * the allocation is backed by btrfs_bioset.
8352                  */
8353                 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8354                                               clone_len);
8355                 bio->bi_private = dip;
8356                 bio->bi_end_io = btrfs_end_dio_bio;
8357                 btrfs_io_bio(bio)->logical = file_offset;
8358
8359                 ASSERT(submit_len >= clone_len);
8360                 submit_len -= clone_len;
8361                 if (submit_len == 0)
8362                         break;
8363
8364                 /*
8365                  * Increase the count before we submit the bio so we know
8366                  * the end IO handler won't happen before we increase the
8367                  * count. Otherwise, the dip might get freed before we're
8368                  * done setting it up.
8369                  */
8370                 atomic_inc(&dip->pending_bios);
8371
8372                 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8373                                                 async_submit);
8374                 if (status) {
8375                         bio_put(bio);
8376                         atomic_dec(&dip->pending_bios);
8377                         goto out_err;
8378                 }
8379
8380                 clone_offset += clone_len;
8381                 start_sector += clone_len >> 9;
8382                 file_offset += clone_len;
8383
8384                 map_length = submit_len;
8385                 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8386                                       start_sector << 9, &map_length, NULL, 0);
8387                 if (ret)
8388                         goto out_err;
8389         } while (submit_len > 0);
8390
8391 submit:
8392         status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8393         if (!status)
8394                 return 0;
8395
8396         bio_put(bio);
8397 out_err:
8398         dip->errors = 1;
8399         /*
8400          * Before atomic variable goto zero, we must  make sure dip->errors is
8401          * perceived to be set. This ordering is ensured by the fact that an
8402          * atomic operations with a return value are fully ordered as per
8403          * atomic_t.txt
8404          */
8405         if (atomic_dec_and_test(&dip->pending_bios))
8406                 bio_io_error(dip->orig_bio);
8407
8408         /* bio_end_io() will handle error, so we needn't return it */
8409         return 0;
8410 }
8411
8412 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8413                                 loff_t file_offset)
8414 {
8415         struct btrfs_dio_private *dip = NULL;
8416         struct bio *bio = NULL;
8417         struct btrfs_io_bio *io_bio;
8418         bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8419         int ret = 0;
8420
8421         bio = btrfs_bio_clone(dio_bio);
8422
8423         dip = kzalloc(sizeof(*dip), GFP_NOFS);
8424         if (!dip) {
8425                 ret = -ENOMEM;
8426                 goto free_ordered;
8427         }
8428
8429         dip->private = dio_bio->bi_private;
8430         dip->inode = inode;
8431         dip->logical_offset = file_offset;
8432         dip->bytes = dio_bio->bi_iter.bi_size;
8433         dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8434         bio->bi_private = dip;
8435         dip->orig_bio = bio;
8436         dip->dio_bio = dio_bio;
8437         atomic_set(&dip->pending_bios, 0);
8438         io_bio = btrfs_io_bio(bio);
8439         io_bio->logical = file_offset;
8440
8441         if (write) {
8442                 bio->bi_end_io = btrfs_endio_direct_write;
8443         } else {
8444                 bio->bi_end_io = btrfs_endio_direct_read;
8445                 dip->subio_endio = btrfs_subio_endio_read;
8446         }
8447
8448         /*
8449          * Reset the range for unsubmitted ordered extents (to a 0 length range)
8450          * even if we fail to submit a bio, because in such case we do the
8451          * corresponding error handling below and it must not be done a second
8452          * time by btrfs_direct_IO().
8453          */
8454         if (write) {
8455                 struct btrfs_dio_data *dio_data = current->journal_info;
8456
8457                 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8458                         dip->bytes;
8459                 dio_data->unsubmitted_oe_range_start =
8460                         dio_data->unsubmitted_oe_range_end;
8461         }
8462
8463         ret = btrfs_submit_direct_hook(dip);
8464         if (!ret)
8465                 return;
8466
8467         if (io_bio->end_io)
8468                 io_bio->end_io(io_bio, ret);
8469
8470 free_ordered:
8471         /*
8472          * If we arrived here it means either we failed to submit the dip
8473          * or we either failed to clone the dio_bio or failed to allocate the
8474          * dip. If we cloned the dio_bio and allocated the dip, we can just
8475          * call bio_endio against our io_bio so that we get proper resource
8476          * cleanup if we fail to submit the dip, otherwise, we must do the
8477          * same as btrfs_endio_direct_[write|read] because we can't call these
8478          * callbacks - they require an allocated dip and a clone of dio_bio.
8479          */
8480         if (bio && dip) {
8481                 bio_io_error(bio);
8482                 /*
8483                  * The end io callbacks free our dip, do the final put on bio
8484                  * and all the cleanup and final put for dio_bio (through
8485                  * dio_end_io()).
8486                  */
8487                 dip = NULL;
8488                 bio = NULL;
8489         } else {
8490                 if (write)
8491                         __endio_write_update_ordered(inode,
8492                                                 file_offset,
8493                                                 dio_bio->bi_iter.bi_size,
8494                                                 false);
8495                 else
8496                         unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8497                               file_offset + dio_bio->bi_iter.bi_size - 1);
8498
8499                 dio_bio->bi_status = BLK_STS_IOERR;
8500                 /*
8501                  * Releases and cleans up our dio_bio, no need to bio_put()
8502                  * nor bio_endio()/bio_io_error() against dio_bio.
8503                  */
8504                 dio_end_io(dio_bio);
8505         }
8506         if (bio)
8507                 bio_put(bio);
8508         kfree(dip);
8509 }
8510
8511 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8512                                const struct iov_iter *iter, loff_t offset)
8513 {
8514         int seg;
8515         int i;
8516         unsigned int blocksize_mask = fs_info->sectorsize - 1;
8517         ssize_t retval = -EINVAL;
8518
8519         if (offset & blocksize_mask)
8520                 goto out;
8521
8522         if (iov_iter_alignment(iter) & blocksize_mask)
8523                 goto out;
8524
8525         /* If this is a write we don't need to check anymore */
8526         if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8527                 return 0;
8528         /*
8529          * Check to make sure we don't have duplicate iov_base's in this
8530          * iovec, if so return EINVAL, otherwise we'll get csum errors
8531          * when reading back.
8532          */
8533         for (seg = 0; seg < iter->nr_segs; seg++) {
8534                 for (i = seg + 1; i < iter->nr_segs; i++) {
8535                         if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8536                                 goto out;
8537                 }
8538         }
8539         retval = 0;
8540 out:
8541         return retval;
8542 }
8543
8544 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8545 {
8546         struct file *file = iocb->ki_filp;
8547         struct inode *inode = file->f_mapping->host;
8548         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8549         struct btrfs_dio_data dio_data = { 0 };
8550         struct extent_changeset *data_reserved = NULL;
8551         loff_t offset = iocb->ki_pos;
8552         size_t count = 0;
8553         int flags = 0;
8554         bool wakeup = true;
8555         bool relock = false;
8556         ssize_t ret;
8557
8558         if (check_direct_IO(fs_info, iter, offset))
8559                 return 0;
8560
8561         inode_dio_begin(inode);
8562
8563         /*
8564          * The generic stuff only does filemap_write_and_wait_range, which
8565          * isn't enough if we've written compressed pages to this area, so
8566          * we need to flush the dirty pages again to make absolutely sure
8567          * that any outstanding dirty pages are on disk.
8568          */
8569         count = iov_iter_count(iter);
8570         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8571                      &BTRFS_I(inode)->runtime_flags))
8572                 filemap_fdatawrite_range(inode->i_mapping, offset,
8573                                          offset + count - 1);
8574
8575         if (iov_iter_rw(iter) == WRITE) {
8576                 /*
8577                  * If the write DIO is beyond the EOF, we need update
8578                  * the isize, but it is protected by i_mutex. So we can
8579                  * not unlock the i_mutex at this case.
8580                  */
8581                 if (offset + count <= inode->i_size) {
8582                         dio_data.overwrite = 1;
8583                         inode_unlock(inode);
8584                         relock = true;
8585                 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8586                         ret = -EAGAIN;
8587                         goto out;
8588                 }
8589                 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8590                                                    offset, count);
8591                 if (ret)
8592                         goto out;
8593
8594                 /*
8595                  * We need to know how many extents we reserved so that we can
8596                  * do the accounting properly if we go over the number we
8597                  * originally calculated.  Abuse current->journal_info for this.
8598                  */
8599                 dio_data.reserve = round_up(count,
8600                                             fs_info->sectorsize);
8601                 dio_data.unsubmitted_oe_range_start = (u64)offset;
8602                 dio_data.unsubmitted_oe_range_end = (u64)offset;
8603                 current->journal_info = &dio_data;
8604                 down_read(&BTRFS_I(inode)->dio_sem);
8605         } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8606                                      &BTRFS_I(inode)->runtime_flags)) {
8607                 inode_dio_end(inode);
8608                 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8609                 wakeup = false;
8610         }
8611
8612         ret = __blockdev_direct_IO(iocb, inode,
8613                                    fs_info->fs_devices->latest_bdev,
8614                                    iter, btrfs_get_blocks_direct, NULL,
8615                                    btrfs_submit_direct, flags);
8616         if (iov_iter_rw(iter) == WRITE) {
8617                 up_read(&BTRFS_I(inode)->dio_sem);
8618                 current->journal_info = NULL;
8619                 if (ret < 0 && ret != -EIOCBQUEUED) {
8620                         if (dio_data.reserve)
8621                                 btrfs_delalloc_release_space(inode, data_reserved,
8622                                         offset, dio_data.reserve, true);
8623                         /*
8624                          * On error we might have left some ordered extents
8625                          * without submitting corresponding bios for them, so
8626                          * cleanup them up to avoid other tasks getting them
8627                          * and waiting for them to complete forever.
8628                          */
8629                         if (dio_data.unsubmitted_oe_range_start <
8630                             dio_data.unsubmitted_oe_range_end)
8631                                 __endio_write_update_ordered(inode,
8632                                         dio_data.unsubmitted_oe_range_start,
8633                                         dio_data.unsubmitted_oe_range_end -
8634                                         dio_data.unsubmitted_oe_range_start,
8635                                         false);
8636                 } else if (ret >= 0 && (size_t)ret < count)
8637                         btrfs_delalloc_release_space(inode, data_reserved,
8638                                         offset, count - (size_t)ret, true);
8639                 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8640         }
8641 out:
8642         if (wakeup)
8643                 inode_dio_end(inode);
8644         if (relock)
8645                 inode_lock(inode);
8646
8647         extent_changeset_free(data_reserved);
8648         return ret;
8649 }
8650
8651 #define BTRFS_FIEMAP_FLAGS      (FIEMAP_FLAG_SYNC)
8652
8653 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8654                 __u64 start, __u64 len)
8655 {
8656         int     ret;
8657
8658         ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8659         if (ret)
8660                 return ret;
8661
8662         return extent_fiemap(inode, fieinfo, start, len);
8663 }
8664
8665 int btrfs_readpage(struct file *file, struct page *page)
8666 {
8667         struct extent_io_tree *tree;
8668         tree = &BTRFS_I(page->mapping->host)->io_tree;
8669         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8670 }
8671
8672 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8673 {
8674         struct inode *inode = page->mapping->host;
8675         int ret;
8676
8677         if (current->flags & PF_MEMALLOC) {
8678                 redirty_page_for_writepage(wbc, page);
8679                 unlock_page(page);
8680                 return 0;
8681         }
8682
8683         /*
8684          * If we are under memory pressure we will call this directly from the
8685          * VM, we need to make sure we have the inode referenced for the ordered
8686          * extent.  If not just return like we didn't do anything.
8687          */
8688         if (!igrab(inode)) {
8689                 redirty_page_for_writepage(wbc, page);
8690                 return AOP_WRITEPAGE_ACTIVATE;
8691         }
8692         ret = extent_write_full_page(page, wbc);
8693         btrfs_add_delayed_iput(inode);
8694         return ret;
8695 }
8696
8697 static int btrfs_writepages(struct address_space *mapping,
8698                             struct writeback_control *wbc)
8699 {
8700         return extent_writepages(mapping, wbc);
8701 }
8702
8703 static int
8704 btrfs_readpages(struct file *file, struct address_space *mapping,
8705                 struct list_head *pages, unsigned nr_pages)
8706 {
8707         return extent_readpages(mapping, pages, nr_pages);
8708 }
8709
8710 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8711 {
8712         int ret = try_release_extent_mapping(page, gfp_flags);
8713         if (ret == 1) {
8714                 ClearPagePrivate(page);
8715                 set_page_private(page, 0);
8716                 put_page(page);
8717         }
8718         return ret;
8719 }
8720
8721 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8722 {
8723         if (PageWriteback(page) || PageDirty(page))
8724                 return 0;
8725         return __btrfs_releasepage(page, gfp_flags);
8726 }
8727
8728 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8729                                  unsigned int length)
8730 {
8731         struct inode *inode = page->mapping->host;
8732         struct extent_io_tree *tree;
8733         struct btrfs_ordered_extent *ordered;
8734         struct extent_state *cached_state = NULL;
8735         u64 page_start = page_offset(page);
8736         u64 page_end = page_start + PAGE_SIZE - 1;
8737         u64 start;
8738         u64 end;
8739         int inode_evicting = inode->i_state & I_FREEING;
8740
8741         /*
8742          * we have the page locked, so new writeback can't start,
8743          * and the dirty bit won't be cleared while we are here.
8744          *
8745          * Wait for IO on this page so that we can safely clear
8746          * the PagePrivate2 bit and do ordered accounting
8747          */
8748         wait_on_page_writeback(page);
8749
8750         tree = &BTRFS_I(inode)->io_tree;
8751         if (offset) {
8752                 btrfs_releasepage(page, GFP_NOFS);
8753                 return;
8754         }
8755
8756         if (!inode_evicting)
8757                 lock_extent_bits(tree, page_start, page_end, &cached_state);
8758 again:
8759         start = page_start;
8760         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8761                                         page_end - start + 1);
8762         if (ordered) {
8763                 end = min(page_end, ordered->file_offset + ordered->len - 1);
8764                 /*
8765                  * IO on this page will never be started, so we need
8766                  * to account for any ordered extents now
8767                  */
8768                 if (!inode_evicting)
8769                         clear_extent_bit(tree, start, end,
8770                                          EXTENT_DIRTY | EXTENT_DELALLOC |
8771                                          EXTENT_DELALLOC_NEW |
8772                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8773                                          EXTENT_DEFRAG, 1, 0, &cached_state);
8774                 /*
8775                  * whoever cleared the private bit is responsible
8776                  * for the finish_ordered_io
8777                  */
8778                 if (TestClearPagePrivate2(page)) {
8779                         struct btrfs_ordered_inode_tree *tree;
8780                         u64 new_len;
8781
8782                         tree = &BTRFS_I(inode)->ordered_tree;
8783
8784                         spin_lock_irq(&tree->lock);
8785                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8786                         new_len = start - ordered->file_offset;
8787                         if (new_len < ordered->truncated_len)
8788                                 ordered->truncated_len = new_len;
8789                         spin_unlock_irq(&tree->lock);
8790
8791                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
8792                                                            start,
8793                                                            end - start + 1, 1))
8794                                 btrfs_finish_ordered_io(ordered);
8795                 }
8796                 btrfs_put_ordered_extent(ordered);
8797                 if (!inode_evicting) {
8798                         cached_state = NULL;
8799                         lock_extent_bits(tree, start, end,
8800                                          &cached_state);
8801                 }
8802
8803                 start = end + 1;
8804                 if (start < page_end)
8805                         goto again;
8806         }
8807
8808         /*
8809          * Qgroup reserved space handler
8810          * Page here will be either
8811          * 1) Already written to disk
8812          *    In this case, its reserved space is released from data rsv map
8813          *    and will be freed by delayed_ref handler finally.
8814          *    So even we call qgroup_free_data(), it won't decrease reserved
8815          *    space.
8816          * 2) Not written to disk
8817          *    This means the reserved space should be freed here. However,
8818          *    if a truncate invalidates the page (by clearing PageDirty)
8819          *    and the page is accounted for while allocating extent
8820          *    in btrfs_check_data_free_space() we let delayed_ref to
8821          *    free the entire extent.
8822          */
8823         if (PageDirty(page))
8824                 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8825         if (!inode_evicting) {
8826                 clear_extent_bit(tree, page_start, page_end,
8827                                  EXTENT_LOCKED | EXTENT_DIRTY |
8828                                  EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8829                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8830                                  &cached_state);
8831
8832                 __btrfs_releasepage(page, GFP_NOFS);
8833         }
8834
8835         ClearPageChecked(page);
8836         if (PagePrivate(page)) {
8837                 ClearPagePrivate(page);
8838                 set_page_private(page, 0);
8839                 put_page(page);
8840         }
8841 }
8842
8843 /*
8844  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8845  * called from a page fault handler when a page is first dirtied. Hence we must
8846  * be careful to check for EOF conditions here. We set the page up correctly
8847  * for a written page which means we get ENOSPC checking when writing into
8848  * holes and correct delalloc and unwritten extent mapping on filesystems that
8849  * support these features.
8850  *
8851  * We are not allowed to take the i_mutex here so we have to play games to
8852  * protect against truncate races as the page could now be beyond EOF.  Because
8853  * truncate_setsize() writes the inode size before removing pages, once we have
8854  * the page lock we can determine safely if the page is beyond EOF. If it is not
8855  * beyond EOF, then the page is guaranteed safe against truncation until we
8856  * unlock the page.
8857  */
8858 int btrfs_page_mkwrite(struct vm_fault *vmf)
8859 {
8860         struct page *page = vmf->page;
8861         struct inode *inode = file_inode(vmf->vma->vm_file);
8862         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8863         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8864         struct btrfs_ordered_extent *ordered;
8865         struct extent_state *cached_state = NULL;
8866         struct extent_changeset *data_reserved = NULL;
8867         char *kaddr;
8868         unsigned long zero_start;
8869         loff_t size;
8870         int ret;
8871         int reserved = 0;
8872         u64 reserved_space;
8873         u64 page_start;
8874         u64 page_end;
8875         u64 end;
8876
8877         reserved_space = PAGE_SIZE;
8878
8879         sb_start_pagefault(inode->i_sb);
8880         page_start = page_offset(page);
8881         page_end = page_start + PAGE_SIZE - 1;
8882         end = page_end;
8883
8884         /*
8885          * Reserving delalloc space after obtaining the page lock can lead to
8886          * deadlock. For example, if a dirty page is locked by this function
8887          * and the call to btrfs_delalloc_reserve_space() ends up triggering
8888          * dirty page write out, then the btrfs_writepage() function could
8889          * end up waiting indefinitely to get a lock on the page currently
8890          * being processed by btrfs_page_mkwrite() function.
8891          */
8892         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8893                                            reserved_space);
8894         if (!ret) {
8895                 ret = file_update_time(vmf->vma->vm_file);
8896                 reserved = 1;
8897         }
8898         if (ret) {
8899                 if (ret == -ENOMEM)
8900                         ret = VM_FAULT_OOM;
8901                 else /* -ENOSPC, -EIO, etc */
8902                         ret = VM_FAULT_SIGBUS;
8903                 if (reserved)
8904                         goto out;
8905                 goto out_noreserve;
8906         }
8907
8908         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8909 again:
8910         lock_page(page);
8911         size = i_size_read(inode);
8912
8913         if ((page->mapping != inode->i_mapping) ||
8914             (page_start >= size)) {
8915                 /* page got truncated out from underneath us */
8916                 goto out_unlock;
8917         }
8918         wait_on_page_writeback(page);
8919
8920         lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8921         set_page_extent_mapped(page);
8922
8923         /*
8924          * we can't set the delalloc bits if there are pending ordered
8925          * extents.  Drop our locks and wait for them to finish
8926          */
8927         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8928                         PAGE_SIZE);
8929         if (ordered) {
8930                 unlock_extent_cached(io_tree, page_start, page_end,
8931                                      &cached_state);
8932                 unlock_page(page);
8933                 btrfs_start_ordered_extent(inode, ordered, 1);
8934                 btrfs_put_ordered_extent(ordered);
8935                 goto again;
8936         }
8937
8938         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8939                 reserved_space = round_up(size - page_start,
8940                                           fs_info->sectorsize);
8941                 if (reserved_space < PAGE_SIZE) {
8942                         end = page_start + reserved_space - 1;
8943                         btrfs_delalloc_release_space(inode, data_reserved,
8944                                         page_start, PAGE_SIZE - reserved_space,
8945                                         true);
8946                 }
8947         }
8948
8949         /*
8950          * page_mkwrite gets called when the page is firstly dirtied after it's
8951          * faulted in, but write(2) could also dirty a page and set delalloc
8952          * bits, thus in this case for space account reason, we still need to
8953          * clear any delalloc bits within this page range since we have to
8954          * reserve data&meta space before lock_page() (see above comments).
8955          */
8956         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8957                           EXTENT_DIRTY | EXTENT_DELALLOC |
8958                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8959                           0, 0, &cached_state);
8960
8961         ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8962                                         &cached_state, 0);
8963         if (ret) {
8964                 unlock_extent_cached(io_tree, page_start, page_end,
8965                                      &cached_state);
8966                 ret = VM_FAULT_SIGBUS;
8967                 goto out_unlock;
8968         }
8969         ret = 0;
8970
8971         /* page is wholly or partially inside EOF */
8972         if (page_start + PAGE_SIZE > size)
8973                 zero_start = size & ~PAGE_MASK;
8974         else
8975                 zero_start = PAGE_SIZE;
8976
8977         if (zero_start != PAGE_SIZE) {
8978                 kaddr = kmap(page);
8979                 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8980                 flush_dcache_page(page);
8981                 kunmap(page);
8982         }
8983         ClearPageChecked(page);
8984         set_page_dirty(page);
8985         SetPageUptodate(page);
8986
8987         BTRFS_I(inode)->last_trans = fs_info->generation;
8988         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8989         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8990
8991         unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8992
8993 out_unlock:
8994         if (!ret) {
8995                 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8996                 sb_end_pagefault(inode->i_sb);
8997                 extent_changeset_free(data_reserved);
8998                 return VM_FAULT_LOCKED;
8999         }
9000         unlock_page(page);
9001 out:
9002         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9003         btrfs_delalloc_release_space(inode, data_reserved, page_start,
9004                                      reserved_space, (ret != 0));
9005 out_noreserve:
9006         sb_end_pagefault(inode->i_sb);
9007         extent_changeset_free(data_reserved);
9008         return ret;
9009 }
9010
9011 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9012 {
9013         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9014         struct btrfs_root *root = BTRFS_I(inode)->root;
9015         struct btrfs_block_rsv *rsv;
9016         int ret = 0;
9017         int err = 0;
9018         struct btrfs_trans_handle *trans;
9019         u64 mask = fs_info->sectorsize - 1;
9020         u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9021
9022         if (!skip_writeback) {
9023                 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9024                                                (u64)-1);
9025                 if (ret)
9026                         return ret;
9027         }
9028
9029         /*
9030          * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
9031          * things going on here:
9032          *
9033          * 1) We need to reserve space to update our inode.
9034          *
9035          * 2) We need to have something to cache all the space that is going to
9036          * be free'd up by the truncate operation, but also have some slack
9037          * space reserved in case it uses space during the truncate (thank you
9038          * very much snapshotting).
9039          *
9040          * And we need these to be separate.  The fact is we can use a lot of
9041          * space doing the truncate, and we have no earthly idea how much space
9042          * we will use, so we need the truncate reservation to be separate so it
9043          * doesn't end up using space reserved for updating the inode.  We also
9044          * need to be able to stop the transaction and start a new one, which
9045          * means we need to be able to update the inode several times, and we
9046          * have no idea of knowing how many times that will be, so we can't just
9047          * reserve 1 item for the entirety of the operation, so that has to be
9048          * done separately as well.
9049          *
9050          * So that leaves us with
9051          *
9052          * 1) rsv - for the truncate reservation, which we will steal from the
9053          * transaction reservation.
9054          * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9055          * updating the inode.
9056          */
9057         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9058         if (!rsv)
9059                 return -ENOMEM;
9060         rsv->size = min_size;
9061         rsv->failfast = 1;
9062
9063         /*
9064          * 1 for the truncate slack space
9065          * 1 for updating the inode.
9066          */
9067         trans = btrfs_start_transaction(root, 2);
9068         if (IS_ERR(trans)) {
9069                 err = PTR_ERR(trans);
9070                 goto out;
9071         }
9072
9073         /* Migrate the slack space for the truncate to our reserve */
9074         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9075                                       min_size, 0);
9076         BUG_ON(ret);
9077
9078         /*
9079          * So if we truncate and then write and fsync we normally would just
9080          * write the extents that changed, which is a problem if we need to
9081          * first truncate that entire inode.  So set this flag so we write out
9082          * all of the extents in the inode to the sync log so we're completely
9083          * safe.
9084          */
9085         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9086         trans->block_rsv = rsv;
9087
9088         while (1) {
9089                 ret = btrfs_truncate_inode_items(trans, root, inode,
9090                                                  inode->i_size,
9091                                                  BTRFS_EXTENT_DATA_KEY);
9092                 trans->block_rsv = &fs_info->trans_block_rsv;
9093                 if (ret != -ENOSPC && ret != -EAGAIN) {
9094                         if (ret < 0)
9095                                 err = ret;
9096                         break;
9097                 }
9098
9099                 ret = btrfs_update_inode(trans, root, inode);
9100                 if (ret) {
9101                         err = ret;
9102                         break;
9103                 }
9104
9105                 btrfs_end_transaction(trans);
9106                 btrfs_btree_balance_dirty(fs_info);
9107
9108                 trans = btrfs_start_transaction(root, 2);
9109                 if (IS_ERR(trans)) {
9110                         ret = err = PTR_ERR(trans);
9111                         trans = NULL;
9112                         break;
9113                 }
9114
9115                 btrfs_block_rsv_release(fs_info, rsv, -1);
9116                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9117                                               rsv, min_size, 0);
9118                 BUG_ON(ret);    /* shouldn't happen */
9119                 trans->block_rsv = rsv;
9120         }
9121
9122         /*
9123          * We can't call btrfs_truncate_block inside a trans handle as we could
9124          * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9125          * we've truncated everything except the last little bit, and can do
9126          * btrfs_truncate_block and then update the disk_i_size.
9127          */
9128         if (ret == NEED_TRUNCATE_BLOCK) {
9129                 btrfs_end_transaction(trans);
9130                 btrfs_btree_balance_dirty(fs_info);
9131
9132                 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9133                 if (ret)
9134                         goto out;
9135                 trans = btrfs_start_transaction(root, 1);
9136                 if (IS_ERR(trans)) {
9137                         ret = PTR_ERR(trans);
9138                         goto out;
9139                 }
9140                 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9141         }
9142
9143         if (trans) {
9144                 trans->block_rsv = &fs_info->trans_block_rsv;
9145                 ret = btrfs_update_inode(trans, root, inode);
9146                 if (ret && !err)
9147                         err = ret;
9148
9149                 ret = btrfs_end_transaction(trans);
9150                 btrfs_btree_balance_dirty(fs_info);
9151         }
9152 out:
9153         btrfs_free_block_rsv(fs_info, rsv);
9154
9155         if (ret && !err)
9156                 err = ret;
9157
9158         return err;
9159 }
9160
9161 /*
9162  * create a new subvolume directory/inode (helper for the ioctl).
9163  */
9164 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9165                              struct btrfs_root *new_root,
9166                              struct btrfs_root *parent_root,
9167                              u64 new_dirid)
9168 {
9169         struct inode *inode;
9170         int err;
9171         u64 index = 0;
9172
9173         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9174                                 new_dirid, new_dirid,
9175                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
9176                                 &index);
9177         if (IS_ERR(inode))
9178                 return PTR_ERR(inode);
9179         inode->i_op = &btrfs_dir_inode_operations;
9180         inode->i_fop = &btrfs_dir_file_operations;
9181
9182         set_nlink(inode, 1);
9183         btrfs_i_size_write(BTRFS_I(inode), 0);
9184         unlock_new_inode(inode);
9185
9186         err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9187         if (err)
9188                 btrfs_err(new_root->fs_info,
9189                           "error inheriting subvolume %llu properties: %d",
9190                           new_root->root_key.objectid, err);
9191
9192         err = btrfs_update_inode(trans, new_root, inode);
9193
9194         iput(inode);
9195         return err;
9196 }
9197
9198 struct inode *btrfs_alloc_inode(struct super_block *sb)
9199 {
9200         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9201         struct btrfs_inode *ei;
9202         struct inode *inode;
9203
9204         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9205         if (!ei)
9206                 return NULL;
9207
9208         ei->root = NULL;
9209         ei->generation = 0;
9210         ei->last_trans = 0;
9211         ei->last_sub_trans = 0;
9212         ei->logged_trans = 0;
9213         ei->delalloc_bytes = 0;
9214         ei->new_delalloc_bytes = 0;
9215         ei->defrag_bytes = 0;
9216         ei->disk_i_size = 0;
9217         ei->flags = 0;
9218         ei->csum_bytes = 0;
9219         ei->index_cnt = (u64)-1;
9220         ei->dir_index = 0;
9221         ei->last_unlink_trans = 0;
9222         ei->last_log_commit = 0;
9223
9224         spin_lock_init(&ei->lock);
9225         ei->outstanding_extents = 0;
9226         if (sb->s_magic != BTRFS_TEST_MAGIC)
9227                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9228                                               BTRFS_BLOCK_RSV_DELALLOC);
9229         ei->runtime_flags = 0;
9230         ei->prop_compress = BTRFS_COMPRESS_NONE;
9231         ei->defrag_compress = BTRFS_COMPRESS_NONE;
9232
9233         ei->delayed_node = NULL;
9234
9235         ei->i_otime.tv_sec = 0;
9236         ei->i_otime.tv_nsec = 0;
9237
9238         inode = &ei->vfs_inode;
9239         extent_map_tree_init(&ei->extent_tree);
9240         extent_io_tree_init(&ei->io_tree, inode);
9241         extent_io_tree_init(&ei->io_failure_tree, inode);
9242         ei->io_tree.track_uptodate = 1;
9243         ei->io_failure_tree.track_uptodate = 1;
9244         atomic_set(&ei->sync_writers, 0);
9245         mutex_init(&ei->log_mutex);
9246         mutex_init(&ei->delalloc_mutex);
9247         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9248         INIT_LIST_HEAD(&ei->delalloc_inodes);
9249         INIT_LIST_HEAD(&ei->delayed_iput);
9250         RB_CLEAR_NODE(&ei->rb_node);
9251         init_rwsem(&ei->dio_sem);
9252
9253         return inode;
9254 }
9255
9256 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9257 void btrfs_test_destroy_inode(struct inode *inode)
9258 {
9259         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9260         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9261 }
9262 #endif
9263
9264 static void btrfs_i_callback(struct rcu_head *head)
9265 {
9266         struct inode *inode = container_of(head, struct inode, i_rcu);
9267         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9268 }
9269
9270 void btrfs_destroy_inode(struct inode *inode)
9271 {
9272         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9273         struct btrfs_ordered_extent *ordered;
9274         struct btrfs_root *root = BTRFS_I(inode)->root;
9275
9276         WARN_ON(!hlist_empty(&inode->i_dentry));
9277         WARN_ON(inode->i_data.nrpages);
9278         WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9279         WARN_ON(BTRFS_I(inode)->block_rsv.size);
9280         WARN_ON(BTRFS_I(inode)->outstanding_extents);
9281         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9282         WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9283         WARN_ON(BTRFS_I(inode)->csum_bytes);
9284         WARN_ON(BTRFS_I(inode)->defrag_bytes);
9285
9286         /*
9287          * This can happen where we create an inode, but somebody else also
9288          * created the same inode and we need to destroy the one we already
9289          * created.
9290          */
9291         if (!root)
9292                 goto free;
9293
9294         while (1) {
9295                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9296                 if (!ordered)
9297                         break;
9298                 else {
9299                         btrfs_err(fs_info,
9300                                   "found ordered extent %llu %llu on inode cleanup",
9301                                   ordered->file_offset, ordered->len);
9302                         btrfs_remove_ordered_extent(inode, ordered);
9303                         btrfs_put_ordered_extent(ordered);
9304                         btrfs_put_ordered_extent(ordered);
9305                 }
9306         }
9307         btrfs_qgroup_check_reserved_leak(inode);
9308         inode_tree_del(inode);
9309         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9310 free:
9311         call_rcu(&inode->i_rcu, btrfs_i_callback);
9312 }
9313
9314 int btrfs_drop_inode(struct inode *inode)
9315 {
9316         struct btrfs_root *root = BTRFS_I(inode)->root;
9317
9318         if (root == NULL)
9319                 return 1;
9320
9321         /* the snap/subvol tree is on deleting */
9322         if (btrfs_root_refs(&root->root_item) == 0)
9323                 return 1;
9324         else
9325                 return generic_drop_inode(inode);
9326 }
9327
9328 static void init_once(void *foo)
9329 {
9330         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9331
9332         inode_init_once(&ei->vfs_inode);
9333 }
9334
9335 void __cold btrfs_destroy_cachep(void)
9336 {
9337         /*
9338          * Make sure all delayed rcu free inodes are flushed before we
9339          * destroy cache.
9340          */
9341         rcu_barrier();
9342         kmem_cache_destroy(btrfs_inode_cachep);
9343         kmem_cache_destroy(btrfs_trans_handle_cachep);
9344         kmem_cache_destroy(btrfs_path_cachep);
9345         kmem_cache_destroy(btrfs_free_space_cachep);
9346 }
9347
9348 int __init btrfs_init_cachep(void)
9349 {
9350         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9351                         sizeof(struct btrfs_inode), 0,
9352                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9353                         init_once);
9354         if (!btrfs_inode_cachep)
9355                 goto fail;
9356
9357         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9358                         sizeof(struct btrfs_trans_handle), 0,
9359                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9360         if (!btrfs_trans_handle_cachep)
9361                 goto fail;
9362
9363         btrfs_path_cachep = kmem_cache_create("btrfs_path",
9364                         sizeof(struct btrfs_path), 0,
9365                         SLAB_MEM_SPREAD, NULL);
9366         if (!btrfs_path_cachep)
9367                 goto fail;
9368
9369         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9370                         sizeof(struct btrfs_free_space), 0,
9371                         SLAB_MEM_SPREAD, NULL);
9372         if (!btrfs_free_space_cachep)
9373                 goto fail;
9374
9375         return 0;
9376 fail:
9377         btrfs_destroy_cachep();
9378         return -ENOMEM;
9379 }
9380
9381 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9382                          u32 request_mask, unsigned int flags)
9383 {
9384         u64 delalloc_bytes;
9385         struct inode *inode = d_inode(path->dentry);
9386         u32 blocksize = inode->i_sb->s_blocksize;
9387         u32 bi_flags = BTRFS_I(inode)->flags;
9388
9389         stat->result_mask |= STATX_BTIME;
9390         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9391         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9392         if (bi_flags & BTRFS_INODE_APPEND)
9393                 stat->attributes |= STATX_ATTR_APPEND;
9394         if (bi_flags & BTRFS_INODE_COMPRESS)
9395                 stat->attributes |= STATX_ATTR_COMPRESSED;
9396         if (bi_flags & BTRFS_INODE_IMMUTABLE)
9397                 stat->attributes |= STATX_ATTR_IMMUTABLE;
9398         if (bi_flags & BTRFS_INODE_NODUMP)
9399                 stat->attributes |= STATX_ATTR_NODUMP;
9400
9401         stat->attributes_mask |= (STATX_ATTR_APPEND |
9402                                   STATX_ATTR_COMPRESSED |
9403                                   STATX_ATTR_IMMUTABLE |
9404                                   STATX_ATTR_NODUMP);
9405
9406         generic_fillattr(inode, stat);
9407         stat->dev = BTRFS_I(inode)->root->anon_dev;
9408
9409         spin_lock(&BTRFS_I(inode)->lock);
9410         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9411         spin_unlock(&BTRFS_I(inode)->lock);
9412         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9413                         ALIGN(delalloc_bytes, blocksize)) >> 9;
9414         return 0;
9415 }
9416
9417 static int btrfs_rename_exchange(struct inode *old_dir,
9418                               struct dentry *old_dentry,
9419                               struct inode *new_dir,
9420                               struct dentry *new_dentry)
9421 {
9422         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9423         struct btrfs_trans_handle *trans;
9424         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9425         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9426         struct inode *new_inode = new_dentry->d_inode;
9427         struct inode *old_inode = old_dentry->d_inode;
9428         struct timespec ctime = current_time(old_inode);
9429         struct dentry *parent;
9430         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9431         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9432         u64 old_idx = 0;
9433         u64 new_idx = 0;
9434         u64 root_objectid;
9435         int ret;
9436         bool root_log_pinned = false;
9437         bool dest_log_pinned = false;
9438
9439         /* we only allow rename subvolume link between subvolumes */
9440         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9441                 return -EXDEV;
9442
9443         /* close the race window with snapshot create/destroy ioctl */
9444         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9445                 down_read(&fs_info->subvol_sem);
9446         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9447                 down_read(&fs_info->subvol_sem);
9448
9449         /*
9450          * We want to reserve the absolute worst case amount of items.  So if
9451          * both inodes are subvols and we need to unlink them then that would
9452          * require 4 item modifications, but if they are both normal inodes it
9453          * would require 5 item modifications, so we'll assume their normal
9454          * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9455          * should cover the worst case number of items we'll modify.
9456          */
9457         trans = btrfs_start_transaction(root, 12);
9458         if (IS_ERR(trans)) {
9459                 ret = PTR_ERR(trans);
9460                 goto out_notrans;
9461         }
9462
9463         /*
9464          * We need to find a free sequence number both in the source and
9465          * in the destination directory for the exchange.
9466          */
9467         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9468         if (ret)
9469                 goto out_fail;
9470         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9471         if (ret)
9472                 goto out_fail;
9473
9474         BTRFS_I(old_inode)->dir_index = 0ULL;
9475         BTRFS_I(new_inode)->dir_index = 0ULL;
9476
9477         /* Reference for the source. */
9478         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9479                 /* force full log commit if subvolume involved. */
9480                 btrfs_set_log_full_commit(fs_info, trans);
9481         } else {
9482                 btrfs_pin_log_trans(root);
9483                 root_log_pinned = true;
9484                 ret = btrfs_insert_inode_ref(trans, dest,
9485                                              new_dentry->d_name.name,
9486                                              new_dentry->d_name.len,
9487                                              old_ino,
9488                                              btrfs_ino(BTRFS_I(new_dir)),
9489                                              old_idx);
9490                 if (ret)
9491                         goto out_fail;
9492         }
9493
9494         /* And now for the dest. */
9495         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9496                 /* force full log commit if subvolume involved. */
9497                 btrfs_set_log_full_commit(fs_info, trans);
9498         } else {
9499                 btrfs_pin_log_trans(dest);
9500                 dest_log_pinned = true;
9501                 ret = btrfs_insert_inode_ref(trans, root,
9502                                              old_dentry->d_name.name,
9503                                              old_dentry->d_name.len,
9504                                              new_ino,
9505                                              btrfs_ino(BTRFS_I(old_dir)),
9506                                              new_idx);
9507                 if (ret)
9508                         goto out_fail;
9509         }
9510
9511         /* Update inode version and ctime/mtime. */
9512         inode_inc_iversion(old_dir);
9513         inode_inc_iversion(new_dir);
9514         inode_inc_iversion(old_inode);
9515         inode_inc_iversion(new_inode);
9516         old_dir->i_ctime = old_dir->i_mtime = ctime;
9517         new_dir->i_ctime = new_dir->i_mtime = ctime;
9518         old_inode->i_ctime = ctime;
9519         new_inode->i_ctime = ctime;
9520
9521         if (old_dentry->d_parent != new_dentry->d_parent) {
9522                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9523                                 BTRFS_I(old_inode), 1);
9524                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9525                                 BTRFS_I(new_inode), 1);
9526         }
9527
9528         /* src is a subvolume */
9529         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9530                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9531                 ret = btrfs_unlink_subvol(trans, root, old_dir,
9532                                           root_objectid,
9533                                           old_dentry->d_name.name,
9534                                           old_dentry->d_name.len);
9535         } else { /* src is an inode */
9536                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9537                                            BTRFS_I(old_dentry->d_inode),
9538                                            old_dentry->d_name.name,
9539                                            old_dentry->d_name.len);
9540                 if (!ret)
9541                         ret = btrfs_update_inode(trans, root, old_inode);
9542         }
9543         if (ret) {
9544                 btrfs_abort_transaction(trans, ret);
9545                 goto out_fail;
9546         }
9547
9548         /* dest is a subvolume */
9549         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9550                 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9551                 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9552                                           root_objectid,
9553                                           new_dentry->d_name.name,
9554                                           new_dentry->d_name.len);
9555         } else { /* dest is an inode */
9556                 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9557                                            BTRFS_I(new_dentry->d_inode),
9558                                            new_dentry->d_name.name,
9559                                            new_dentry->d_name.len);
9560                 if (!ret)
9561                         ret = btrfs_update_inode(trans, dest, new_inode);
9562         }
9563         if (ret) {
9564                 btrfs_abort_transaction(trans, ret);
9565                 goto out_fail;
9566         }
9567
9568         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9569                              new_dentry->d_name.name,
9570                              new_dentry->d_name.len, 0, old_idx);
9571         if (ret) {
9572                 btrfs_abort_transaction(trans, ret);
9573                 goto out_fail;
9574         }
9575
9576         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9577                              old_dentry->d_name.name,
9578                              old_dentry->d_name.len, 0, new_idx);
9579         if (ret) {
9580                 btrfs_abort_transaction(trans, ret);
9581                 goto out_fail;
9582         }
9583
9584         if (old_inode->i_nlink == 1)
9585                 BTRFS_I(old_inode)->dir_index = old_idx;
9586         if (new_inode->i_nlink == 1)
9587                 BTRFS_I(new_inode)->dir_index = new_idx;
9588
9589         if (root_log_pinned) {
9590                 parent = new_dentry->d_parent;
9591                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9592                                 parent);
9593                 btrfs_end_log_trans(root);
9594                 root_log_pinned = false;
9595         }
9596         if (dest_log_pinned) {
9597                 parent = old_dentry->d_parent;
9598                 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9599                                 parent);
9600                 btrfs_end_log_trans(dest);
9601                 dest_log_pinned = false;
9602         }
9603 out_fail:
9604         /*
9605          * If we have pinned a log and an error happened, we unpin tasks
9606          * trying to sync the log and force them to fallback to a transaction
9607          * commit if the log currently contains any of the inodes involved in
9608          * this rename operation (to ensure we do not persist a log with an
9609          * inconsistent state for any of these inodes or leading to any
9610          * inconsistencies when replayed). If the transaction was aborted, the
9611          * abortion reason is propagated to userspace when attempting to commit
9612          * the transaction. If the log does not contain any of these inodes, we
9613          * allow the tasks to sync it.
9614          */
9615         if (ret && (root_log_pinned || dest_log_pinned)) {
9616                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9617                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9618                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9619                     (new_inode &&
9620                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9621                         btrfs_set_log_full_commit(fs_info, trans);
9622
9623                 if (root_log_pinned) {
9624                         btrfs_end_log_trans(root);
9625                         root_log_pinned = false;
9626                 }
9627                 if (dest_log_pinned) {
9628                         btrfs_end_log_trans(dest);
9629                         dest_log_pinned = false;
9630                 }
9631         }
9632         ret = btrfs_end_transaction(trans);
9633 out_notrans:
9634         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9635                 up_read(&fs_info->subvol_sem);
9636         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9637                 up_read(&fs_info->subvol_sem);
9638
9639         return ret;
9640 }
9641
9642 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9643                                      struct btrfs_root *root,
9644                                      struct inode *dir,
9645                                      struct dentry *dentry)
9646 {
9647         int ret;
9648         struct inode *inode;
9649         u64 objectid;
9650         u64 index;
9651
9652         ret = btrfs_find_free_ino(root, &objectid);
9653         if (ret)
9654                 return ret;
9655
9656         inode = btrfs_new_inode(trans, root, dir,
9657                                 dentry->d_name.name,
9658                                 dentry->d_name.len,
9659                                 btrfs_ino(BTRFS_I(dir)),
9660                                 objectid,
9661                                 S_IFCHR | WHITEOUT_MODE,
9662                                 &index);
9663
9664         if (IS_ERR(inode)) {
9665                 ret = PTR_ERR(inode);
9666                 return ret;
9667         }
9668
9669         inode->i_op = &btrfs_special_inode_operations;
9670         init_special_inode(inode, inode->i_mode,
9671                 WHITEOUT_DEV);
9672
9673         ret = btrfs_init_inode_security(trans, inode, dir,
9674                                 &dentry->d_name);
9675         if (ret)
9676                 goto out;
9677
9678         ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9679                                 BTRFS_I(inode), 0, index);
9680         if (ret)
9681                 goto out;
9682
9683         ret = btrfs_update_inode(trans, root, inode);
9684 out:
9685         unlock_new_inode(inode);
9686         if (ret)
9687                 inode_dec_link_count(inode);
9688         iput(inode);
9689
9690         return ret;
9691 }
9692
9693 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9694                            struct inode *new_dir, struct dentry *new_dentry,
9695                            unsigned int flags)
9696 {
9697         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9698         struct btrfs_trans_handle *trans;
9699         unsigned int trans_num_items;
9700         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9701         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9702         struct inode *new_inode = d_inode(new_dentry);
9703         struct inode *old_inode = d_inode(old_dentry);
9704         u64 index = 0;
9705         u64 root_objectid;
9706         int ret;
9707         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9708         bool log_pinned = false;
9709
9710         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9711                 return -EPERM;
9712
9713         /* we only allow rename subvolume link between subvolumes */
9714         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9715                 return -EXDEV;
9716
9717         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9718             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9719                 return -ENOTEMPTY;
9720
9721         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9722             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9723                 return -ENOTEMPTY;
9724
9725
9726         /* check for collisions, even if the  name isn't there */
9727         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9728                              new_dentry->d_name.name,
9729                              new_dentry->d_name.len);
9730
9731         if (ret) {
9732                 if (ret == -EEXIST) {
9733                         /* we shouldn't get
9734                          * eexist without a new_inode */
9735                         if (WARN_ON(!new_inode)) {
9736                                 return ret;
9737                         }
9738                 } else {
9739                         /* maybe -EOVERFLOW */
9740                         return ret;
9741                 }
9742         }
9743         ret = 0;
9744
9745         /*
9746          * we're using rename to replace one file with another.  Start IO on it
9747          * now so  we don't add too much work to the end of the transaction
9748          */
9749         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9750                 filemap_flush(old_inode->i_mapping);
9751
9752         /* close the racy window with snapshot create/destroy ioctl */
9753         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9754                 down_read(&fs_info->subvol_sem);
9755         /*
9756          * We want to reserve the absolute worst case amount of items.  So if
9757          * both inodes are subvols and we need to unlink them then that would
9758          * require 4 item modifications, but if they are both normal inodes it
9759          * would require 5 item modifications, so we'll assume they are normal
9760          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9761          * should cover the worst case number of items we'll modify.
9762          * If our rename has the whiteout flag, we need more 5 units for the
9763          * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9764          * when selinux is enabled).
9765          */
9766         trans_num_items = 11;
9767         if (flags & RENAME_WHITEOUT)
9768                 trans_num_items += 5;
9769         trans = btrfs_start_transaction(root, trans_num_items);
9770         if (IS_ERR(trans)) {
9771                 ret = PTR_ERR(trans);
9772                 goto out_notrans;
9773         }
9774
9775         if (dest != root)
9776                 btrfs_record_root_in_trans(trans, dest);
9777
9778         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9779         if (ret)
9780                 goto out_fail;
9781
9782         BTRFS_I(old_inode)->dir_index = 0ULL;
9783         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9784                 /* force full log commit if subvolume involved. */
9785                 btrfs_set_log_full_commit(fs_info, trans);
9786         } else {
9787                 btrfs_pin_log_trans(root);
9788                 log_pinned = true;
9789                 ret = btrfs_insert_inode_ref(trans, dest,
9790                                              new_dentry->d_name.name,
9791                                              new_dentry->d_name.len,
9792                                              old_ino,
9793                                              btrfs_ino(BTRFS_I(new_dir)), index);
9794                 if (ret)
9795                         goto out_fail;
9796         }
9797
9798         inode_inc_iversion(old_dir);
9799         inode_inc_iversion(new_dir);
9800         inode_inc_iversion(old_inode);
9801         old_dir->i_ctime = old_dir->i_mtime =
9802         new_dir->i_ctime = new_dir->i_mtime =
9803         old_inode->i_ctime = current_time(old_dir);
9804
9805         if (old_dentry->d_parent != new_dentry->d_parent)
9806                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9807                                 BTRFS_I(old_inode), 1);
9808
9809         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9810                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9811                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9812                                         old_dentry->d_name.name,
9813                                         old_dentry->d_name.len);
9814         } else {
9815                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9816                                         BTRFS_I(d_inode(old_dentry)),
9817                                         old_dentry->d_name.name,
9818                                         old_dentry->d_name.len);
9819                 if (!ret)
9820                         ret = btrfs_update_inode(trans, root, old_inode);
9821         }
9822         if (ret) {
9823                 btrfs_abort_transaction(trans, ret);
9824                 goto out_fail;
9825         }
9826
9827         if (new_inode) {
9828                 inode_inc_iversion(new_inode);
9829                 new_inode->i_ctime = current_time(new_inode);
9830                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9831                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9832                         root_objectid = BTRFS_I(new_inode)->location.objectid;
9833                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
9834                                                 root_objectid,
9835                                                 new_dentry->d_name.name,
9836                                                 new_dentry->d_name.len);
9837                         BUG_ON(new_inode->i_nlink == 0);
9838                 } else {
9839                         ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9840                                                  BTRFS_I(d_inode(new_dentry)),
9841                                                  new_dentry->d_name.name,
9842                                                  new_dentry->d_name.len);
9843                 }
9844                 if (!ret && new_inode->i_nlink == 0)
9845                         ret = btrfs_orphan_add(trans,
9846                                         BTRFS_I(d_inode(new_dentry)));
9847                 if (ret) {
9848                         btrfs_abort_transaction(trans, ret);
9849                         goto out_fail;
9850                 }
9851         }
9852
9853         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9854                              new_dentry->d_name.name,
9855                              new_dentry->d_name.len, 0, index);
9856         if (ret) {
9857                 btrfs_abort_transaction(trans, ret);
9858                 goto out_fail;
9859         }
9860
9861         if (old_inode->i_nlink == 1)
9862                 BTRFS_I(old_inode)->dir_index = index;
9863
9864         if (log_pinned) {
9865                 struct dentry *parent = new_dentry->d_parent;
9866
9867                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9868                                 parent);
9869                 btrfs_end_log_trans(root);
9870                 log_pinned = false;
9871         }
9872
9873         if (flags & RENAME_WHITEOUT) {
9874                 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9875                                                 old_dentry);
9876
9877                 if (ret) {
9878                         btrfs_abort_transaction(trans, ret);
9879                         goto out_fail;
9880                 }
9881         }
9882 out_fail:
9883         /*
9884          * If we have pinned the log and an error happened, we unpin tasks
9885          * trying to sync the log and force them to fallback to a transaction
9886          * commit if the log currently contains any of the inodes involved in
9887          * this rename operation (to ensure we do not persist a log with an
9888          * inconsistent state for any of these inodes or leading to any
9889          * inconsistencies when replayed). If the transaction was aborted, the
9890          * abortion reason is propagated to userspace when attempting to commit
9891          * the transaction. If the log does not contain any of these inodes, we
9892          * allow the tasks to sync it.
9893          */
9894         if (ret && log_pinned) {
9895                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9896                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9897                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9898                     (new_inode &&
9899                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9900                         btrfs_set_log_full_commit(fs_info, trans);
9901
9902                 btrfs_end_log_trans(root);
9903                 log_pinned = false;
9904         }
9905         btrfs_end_transaction(trans);
9906 out_notrans:
9907         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9908                 up_read(&fs_info->subvol_sem);
9909
9910         return ret;
9911 }
9912
9913 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9914                          struct inode *new_dir, struct dentry *new_dentry,
9915                          unsigned int flags)
9916 {
9917         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9918                 return -EINVAL;
9919
9920         if (flags & RENAME_EXCHANGE)
9921                 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9922                                           new_dentry);
9923
9924         return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9925 }
9926
9927 struct btrfs_delalloc_work {
9928         struct inode *inode;
9929         struct completion completion;
9930         struct list_head list;
9931         struct btrfs_work work;
9932 };
9933
9934 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9935 {
9936         struct btrfs_delalloc_work *delalloc_work;
9937         struct inode *inode;
9938
9939         delalloc_work = container_of(work, struct btrfs_delalloc_work,
9940                                      work);
9941         inode = delalloc_work->inode;
9942         filemap_flush(inode->i_mapping);
9943         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9944                                 &BTRFS_I(inode)->runtime_flags))
9945                 filemap_flush(inode->i_mapping);
9946
9947         iput(inode);
9948         complete(&delalloc_work->completion);
9949 }
9950
9951 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9952 {
9953         struct btrfs_delalloc_work *work;
9954
9955         work = kmalloc(sizeof(*work), GFP_NOFS);
9956         if (!work)
9957                 return NULL;
9958
9959         init_completion(&work->completion);
9960         INIT_LIST_HEAD(&work->list);
9961         work->inode = inode;
9962         WARN_ON_ONCE(!inode);
9963         btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9964                         btrfs_run_delalloc_work, NULL, NULL);
9965
9966         return work;
9967 }
9968
9969 /*
9970  * some fairly slow code that needs optimization. This walks the list
9971  * of all the inodes with pending delalloc and forces them to disk.
9972  */
9973 static int start_delalloc_inodes(struct btrfs_root *root, int nr)
9974 {
9975         struct btrfs_inode *binode;
9976         struct inode *inode;
9977         struct btrfs_delalloc_work *work, *next;
9978         struct list_head works;
9979         struct list_head splice;
9980         int ret = 0;
9981
9982         INIT_LIST_HEAD(&works);
9983         INIT_LIST_HEAD(&splice);
9984
9985         mutex_lock(&root->delalloc_mutex);
9986         spin_lock(&root->delalloc_lock);
9987         list_splice_init(&root->delalloc_inodes, &splice);
9988         while (!list_empty(&splice)) {
9989                 binode = list_entry(splice.next, struct btrfs_inode,
9990                                     delalloc_inodes);
9991
9992                 list_move_tail(&binode->delalloc_inodes,
9993                                &root->delalloc_inodes);
9994                 inode = igrab(&binode->vfs_inode);
9995                 if (!inode) {
9996                         cond_resched_lock(&root->delalloc_lock);
9997                         continue;
9998                 }
9999                 spin_unlock(&root->delalloc_lock);
10000
10001                 work = btrfs_alloc_delalloc_work(inode);
10002                 if (!work) {
10003                         iput(inode);
10004                         ret = -ENOMEM;
10005                         goto out;
10006                 }
10007                 list_add_tail(&work->list, &works);
10008                 btrfs_queue_work(root->fs_info->flush_workers,
10009                                  &work->work);
10010                 ret++;
10011                 if (nr != -1 && ret >= nr)
10012                         goto out;
10013                 cond_resched();
10014                 spin_lock(&root->delalloc_lock);
10015         }
10016         spin_unlock(&root->delalloc_lock);
10017
10018 out:
10019         list_for_each_entry_safe(work, next, &works, list) {
10020                 list_del_init(&work->list);
10021                 wait_for_completion(&work->completion);
10022                 kfree(work);
10023         }
10024
10025         if (!list_empty(&splice)) {
10026                 spin_lock(&root->delalloc_lock);
10027                 list_splice_tail(&splice, &root->delalloc_inodes);
10028                 spin_unlock(&root->delalloc_lock);
10029         }
10030         mutex_unlock(&root->delalloc_mutex);
10031         return ret;
10032 }
10033
10034 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
10035 {
10036         struct btrfs_fs_info *fs_info = root->fs_info;
10037         int ret;
10038
10039         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10040                 return -EROFS;
10041
10042         ret = start_delalloc_inodes(root, -1);
10043         if (ret > 0)
10044                 ret = 0;
10045         return ret;
10046 }
10047
10048 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10049 {
10050         struct btrfs_root *root;
10051         struct list_head splice;
10052         int ret;
10053
10054         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10055                 return -EROFS;
10056
10057         INIT_LIST_HEAD(&splice);
10058
10059         mutex_lock(&fs_info->delalloc_root_mutex);
10060         spin_lock(&fs_info->delalloc_root_lock);
10061         list_splice_init(&fs_info->delalloc_roots, &splice);
10062         while (!list_empty(&splice) && nr) {
10063                 root = list_first_entry(&splice, struct btrfs_root,
10064                                         delalloc_root);
10065                 root = btrfs_grab_fs_root(root);
10066                 BUG_ON(!root);
10067                 list_move_tail(&root->delalloc_root,
10068                                &fs_info->delalloc_roots);
10069                 spin_unlock(&fs_info->delalloc_root_lock);
10070
10071                 ret = start_delalloc_inodes(root, nr);
10072                 btrfs_put_fs_root(root);
10073                 if (ret < 0)
10074                         goto out;
10075
10076                 if (nr != -1) {
10077                         nr -= ret;
10078                         WARN_ON(nr < 0);
10079                 }
10080                 spin_lock(&fs_info->delalloc_root_lock);
10081         }
10082         spin_unlock(&fs_info->delalloc_root_lock);
10083
10084         ret = 0;
10085 out:
10086         if (!list_empty(&splice)) {
10087                 spin_lock(&fs_info->delalloc_root_lock);
10088                 list_splice_tail(&splice, &fs_info->delalloc_roots);
10089                 spin_unlock(&fs_info->delalloc_root_lock);
10090         }
10091         mutex_unlock(&fs_info->delalloc_root_mutex);
10092         return ret;
10093 }
10094
10095 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10096                          const char *symname)
10097 {
10098         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10099         struct btrfs_trans_handle *trans;
10100         struct btrfs_root *root = BTRFS_I(dir)->root;
10101         struct btrfs_path *path;
10102         struct btrfs_key key;
10103         struct inode *inode = NULL;
10104         int err;
10105         int drop_inode = 0;
10106         u64 objectid;
10107         u64 index = 0;
10108         int name_len;
10109         int datasize;
10110         unsigned long ptr;
10111         struct btrfs_file_extent_item *ei;
10112         struct extent_buffer *leaf;
10113
10114         name_len = strlen(symname);
10115         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10116                 return -ENAMETOOLONG;
10117
10118         /*
10119          * 2 items for inode item and ref
10120          * 2 items for dir items
10121          * 1 item for updating parent inode item
10122          * 1 item for the inline extent item
10123          * 1 item for xattr if selinux is on
10124          */
10125         trans = btrfs_start_transaction(root, 7);
10126         if (IS_ERR(trans))
10127                 return PTR_ERR(trans);
10128
10129         err = btrfs_find_free_ino(root, &objectid);
10130         if (err)
10131                 goto out_unlock;
10132
10133         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10134                                 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10135                                 objectid, S_IFLNK|S_IRWXUGO, &index);
10136         if (IS_ERR(inode)) {
10137                 err = PTR_ERR(inode);
10138                 goto out_unlock;
10139         }
10140
10141         /*
10142         * If the active LSM wants to access the inode during
10143         * d_instantiate it needs these. Smack checks to see
10144         * if the filesystem supports xattrs by looking at the
10145         * ops vector.
10146         */
10147         inode->i_fop = &btrfs_file_operations;
10148         inode->i_op = &btrfs_file_inode_operations;
10149         inode->i_mapping->a_ops = &btrfs_aops;
10150         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10151
10152         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10153         if (err)
10154                 goto out_unlock_inode;
10155
10156         path = btrfs_alloc_path();
10157         if (!path) {
10158                 err = -ENOMEM;
10159                 goto out_unlock_inode;
10160         }
10161         key.objectid = btrfs_ino(BTRFS_I(inode));
10162         key.offset = 0;
10163         key.type = BTRFS_EXTENT_DATA_KEY;
10164         datasize = btrfs_file_extent_calc_inline_size(name_len);
10165         err = btrfs_insert_empty_item(trans, root, path, &key,
10166                                       datasize);
10167         if (err) {
10168                 btrfs_free_path(path);
10169                 goto out_unlock_inode;
10170         }
10171         leaf = path->nodes[0];
10172         ei = btrfs_item_ptr(leaf, path->slots[0],
10173                             struct btrfs_file_extent_item);
10174         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10175         btrfs_set_file_extent_type(leaf, ei,
10176                                    BTRFS_FILE_EXTENT_INLINE);
10177         btrfs_set_file_extent_encryption(leaf, ei, 0);
10178         btrfs_set_file_extent_compression(leaf, ei, 0);
10179         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10180         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10181
10182         ptr = btrfs_file_extent_inline_start(ei);
10183         write_extent_buffer(leaf, symname, ptr, name_len);
10184         btrfs_mark_buffer_dirty(leaf);
10185         btrfs_free_path(path);
10186
10187         inode->i_op = &btrfs_symlink_inode_operations;
10188         inode_nohighmem(inode);
10189         inode->i_mapping->a_ops = &btrfs_symlink_aops;
10190         inode_set_bytes(inode, name_len);
10191         btrfs_i_size_write(BTRFS_I(inode), name_len);
10192         err = btrfs_update_inode(trans, root, inode);
10193         /*
10194          * Last step, add directory indexes for our symlink inode. This is the
10195          * last step to avoid extra cleanup of these indexes if an error happens
10196          * elsewhere above.
10197          */
10198         if (!err)
10199                 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10200                                 BTRFS_I(inode), 0, index);
10201         if (err) {
10202                 drop_inode = 1;
10203                 goto out_unlock_inode;
10204         }
10205
10206         d_instantiate_new(dentry, inode);
10207
10208 out_unlock:
10209         btrfs_end_transaction(trans);
10210         if (drop_inode) {
10211                 inode_dec_link_count(inode);
10212                 iput(inode);
10213         }
10214         btrfs_btree_balance_dirty(fs_info);
10215         return err;
10216
10217 out_unlock_inode:
10218         drop_inode = 1;
10219         unlock_new_inode(inode);
10220         goto out_unlock;
10221 }
10222
10223 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10224                                        u64 start, u64 num_bytes, u64 min_size,
10225                                        loff_t actual_len, u64 *alloc_hint,
10226                                        struct btrfs_trans_handle *trans)
10227 {
10228         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10229         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10230         struct extent_map *em;
10231         struct btrfs_root *root = BTRFS_I(inode)->root;
10232         struct btrfs_key ins;
10233         u64 cur_offset = start;
10234         u64 i_size;
10235         u64 cur_bytes;
10236         u64 last_alloc = (u64)-1;
10237         int ret = 0;
10238         bool own_trans = true;
10239         u64 end = start + num_bytes - 1;
10240
10241         if (trans)
10242                 own_trans = false;
10243         while (num_bytes > 0) {
10244                 if (own_trans) {
10245                         trans = btrfs_start_transaction(root, 3);
10246                         if (IS_ERR(trans)) {
10247                                 ret = PTR_ERR(trans);
10248                                 break;
10249                         }
10250                 }
10251
10252                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10253                 cur_bytes = max(cur_bytes, min_size);
10254                 /*
10255                  * If we are severely fragmented we could end up with really
10256                  * small allocations, so if the allocator is returning small
10257                  * chunks lets make its job easier by only searching for those
10258                  * sized chunks.
10259                  */
10260                 cur_bytes = min(cur_bytes, last_alloc);
10261                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10262                                 min_size, 0, *alloc_hint, &ins, 1, 0);
10263                 if (ret) {
10264                         if (own_trans)
10265                                 btrfs_end_transaction(trans);
10266                         break;
10267                 }
10268                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10269
10270                 last_alloc = ins.offset;
10271                 ret = insert_reserved_file_extent(trans, inode,
10272                                                   cur_offset, ins.objectid,
10273                                                   ins.offset, ins.offset,
10274                                                   ins.offset, 0, 0, 0,
10275                                                   BTRFS_FILE_EXTENT_PREALLOC);
10276                 if (ret) {
10277                         btrfs_free_reserved_extent(fs_info, ins.objectid,
10278                                                    ins.offset, 0);
10279                         btrfs_abort_transaction(trans, ret);
10280                         if (own_trans)
10281                                 btrfs_end_transaction(trans);
10282                         break;
10283                 }
10284
10285                 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10286                                         cur_offset + ins.offset -1, 0);
10287
10288                 em = alloc_extent_map();
10289                 if (!em) {
10290                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10291                                 &BTRFS_I(inode)->runtime_flags);
10292                         goto next;
10293                 }
10294
10295                 em->start = cur_offset;
10296                 em->orig_start = cur_offset;
10297                 em->len = ins.offset;
10298                 em->block_start = ins.objectid;
10299                 em->block_len = ins.offset;
10300                 em->orig_block_len = ins.offset;
10301                 em->ram_bytes = ins.offset;
10302                 em->bdev = fs_info->fs_devices->latest_bdev;
10303                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10304                 em->generation = trans->transid;
10305
10306                 while (1) {
10307                         write_lock(&em_tree->lock);
10308                         ret = add_extent_mapping(em_tree, em, 1);
10309                         write_unlock(&em_tree->lock);
10310                         if (ret != -EEXIST)
10311                                 break;
10312                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10313                                                 cur_offset + ins.offset - 1,
10314                                                 0);
10315                 }
10316                 free_extent_map(em);
10317 next:
10318                 num_bytes -= ins.offset;
10319                 cur_offset += ins.offset;
10320                 *alloc_hint = ins.objectid + ins.offset;
10321
10322                 inode_inc_iversion(inode);
10323                 inode->i_ctime = current_time(inode);
10324                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10325                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10326                     (actual_len > inode->i_size) &&
10327                     (cur_offset > inode->i_size)) {
10328                         if (cur_offset > actual_len)
10329                                 i_size = actual_len;
10330                         else
10331                                 i_size = cur_offset;
10332                         i_size_write(inode, i_size);
10333                         btrfs_ordered_update_i_size(inode, i_size, NULL);
10334                 }
10335
10336                 ret = btrfs_update_inode(trans, root, inode);
10337
10338                 if (ret) {
10339                         btrfs_abort_transaction(trans, ret);
10340                         if (own_trans)
10341                                 btrfs_end_transaction(trans);
10342                         break;
10343                 }
10344
10345                 if (own_trans)
10346                         btrfs_end_transaction(trans);
10347         }
10348         if (cur_offset < end)
10349                 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10350                         end - cur_offset + 1);
10351         return ret;
10352 }
10353
10354 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10355                               u64 start, u64 num_bytes, u64 min_size,
10356                               loff_t actual_len, u64 *alloc_hint)
10357 {
10358         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10359                                            min_size, actual_len, alloc_hint,
10360                                            NULL);
10361 }
10362
10363 int btrfs_prealloc_file_range_trans(struct inode *inode,
10364                                     struct btrfs_trans_handle *trans, int mode,
10365                                     u64 start, u64 num_bytes, u64 min_size,
10366                                     loff_t actual_len, u64 *alloc_hint)
10367 {
10368         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10369                                            min_size, actual_len, alloc_hint, trans);
10370 }
10371
10372 static int btrfs_set_page_dirty(struct page *page)
10373 {
10374         return __set_page_dirty_nobuffers(page);
10375 }
10376
10377 static int btrfs_permission(struct inode *inode, int mask)
10378 {
10379         struct btrfs_root *root = BTRFS_I(inode)->root;
10380         umode_t mode = inode->i_mode;
10381
10382         if (mask & MAY_WRITE &&
10383             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10384                 if (btrfs_root_readonly(root))
10385                         return -EROFS;
10386                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10387                         return -EACCES;
10388         }
10389         return generic_permission(inode, mask);
10390 }
10391
10392 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10393 {
10394         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10395         struct btrfs_trans_handle *trans;
10396         struct btrfs_root *root = BTRFS_I(dir)->root;
10397         struct inode *inode = NULL;
10398         u64 objectid;
10399         u64 index;
10400         int ret = 0;
10401
10402         /*
10403          * 5 units required for adding orphan entry
10404          */
10405         trans = btrfs_start_transaction(root, 5);
10406         if (IS_ERR(trans))
10407                 return PTR_ERR(trans);
10408
10409         ret = btrfs_find_free_ino(root, &objectid);
10410         if (ret)
10411                 goto out;
10412
10413         inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10414                         btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10415         if (IS_ERR(inode)) {
10416                 ret = PTR_ERR(inode);
10417                 inode = NULL;
10418                 goto out;
10419         }
10420
10421         inode->i_fop = &btrfs_file_operations;
10422         inode->i_op = &btrfs_file_inode_operations;
10423
10424         inode->i_mapping->a_ops = &btrfs_aops;
10425         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10426
10427         ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10428         if (ret)
10429                 goto out_inode;
10430
10431         ret = btrfs_update_inode(trans, root, inode);
10432         if (ret)
10433                 goto out_inode;
10434         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10435         if (ret)
10436                 goto out_inode;
10437
10438         /*
10439          * We set number of links to 0 in btrfs_new_inode(), and here we set
10440          * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10441          * through:
10442          *
10443          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10444          */
10445         set_nlink(inode, 1);
10446         unlock_new_inode(inode);
10447         d_tmpfile(dentry, inode);
10448         mark_inode_dirty(inode);
10449
10450 out:
10451         btrfs_end_transaction(trans);
10452         if (ret)
10453                 iput(inode);
10454         btrfs_btree_balance_dirty(fs_info);
10455         return ret;
10456
10457 out_inode:
10458         unlock_new_inode(inode);
10459         goto out;
10460
10461 }
10462
10463 __attribute__((const))
10464 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10465 {
10466         return -EAGAIN;
10467 }
10468
10469 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10470 {
10471         struct inode *inode = private_data;
10472         return btrfs_sb(inode->i_sb);
10473 }
10474
10475 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10476                                         u64 start, u64 end)
10477 {
10478         struct inode *inode = private_data;
10479         u64 isize;
10480
10481         isize = i_size_read(inode);
10482         if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10483                 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10484                     "%s: ino %llu isize %llu odd range [%llu,%llu]",
10485                         caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10486         }
10487 }
10488
10489 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10490 {
10491         struct inode *inode = private_data;
10492         unsigned long index = start >> PAGE_SHIFT;
10493         unsigned long end_index = end >> PAGE_SHIFT;
10494         struct page *page;
10495
10496         while (index <= end_index) {
10497                 page = find_get_page(inode->i_mapping, index);
10498                 ASSERT(page); /* Pages should be in the extent_io_tree */
10499                 set_page_writeback(page);
10500                 put_page(page);
10501                 index++;
10502         }
10503 }
10504
10505 static const struct inode_operations btrfs_dir_inode_operations = {
10506         .getattr        = btrfs_getattr,
10507         .lookup         = btrfs_lookup,
10508         .create         = btrfs_create,
10509         .unlink         = btrfs_unlink,
10510         .link           = btrfs_link,
10511         .mkdir          = btrfs_mkdir,
10512         .rmdir          = btrfs_rmdir,
10513         .rename         = btrfs_rename2,
10514         .symlink        = btrfs_symlink,
10515         .setattr        = btrfs_setattr,
10516         .mknod          = btrfs_mknod,
10517         .listxattr      = btrfs_listxattr,
10518         .permission     = btrfs_permission,
10519         .get_acl        = btrfs_get_acl,
10520         .set_acl        = btrfs_set_acl,
10521         .update_time    = btrfs_update_time,
10522         .tmpfile        = btrfs_tmpfile,
10523 };
10524 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10525         .lookup         = btrfs_lookup,
10526         .permission     = btrfs_permission,
10527         .update_time    = btrfs_update_time,
10528 };
10529
10530 static const struct file_operations btrfs_dir_file_operations = {
10531         .llseek         = generic_file_llseek,
10532         .read           = generic_read_dir,
10533         .iterate_shared = btrfs_real_readdir,
10534         .open           = btrfs_opendir,
10535         .unlocked_ioctl = btrfs_ioctl,
10536 #ifdef CONFIG_COMPAT
10537         .compat_ioctl   = btrfs_compat_ioctl,
10538 #endif
10539         .release        = btrfs_release_file,
10540         .fsync          = btrfs_sync_file,
10541 };
10542
10543 static const struct extent_io_ops btrfs_extent_io_ops = {
10544         /* mandatory callbacks */
10545         .submit_bio_hook = btrfs_submit_bio_hook,
10546         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10547         .merge_bio_hook = btrfs_merge_bio_hook,
10548         .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10549         .tree_fs_info = iotree_fs_info,
10550         .set_range_writeback = btrfs_set_range_writeback,
10551
10552         /* optional callbacks */
10553         .fill_delalloc = run_delalloc_range,
10554         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10555         .writepage_start_hook = btrfs_writepage_start_hook,
10556         .set_bit_hook = btrfs_set_bit_hook,
10557         .clear_bit_hook = btrfs_clear_bit_hook,
10558         .merge_extent_hook = btrfs_merge_extent_hook,
10559         .split_extent_hook = btrfs_split_extent_hook,
10560         .check_extent_io_range = btrfs_check_extent_io_range,
10561 };
10562
10563 /*
10564  * btrfs doesn't support the bmap operation because swapfiles
10565  * use bmap to make a mapping of extents in the file.  They assume
10566  * these extents won't change over the life of the file and they
10567  * use the bmap result to do IO directly to the drive.
10568  *
10569  * the btrfs bmap call would return logical addresses that aren't
10570  * suitable for IO and they also will change frequently as COW
10571  * operations happen.  So, swapfile + btrfs == corruption.
10572  *
10573  * For now we're avoiding this by dropping bmap.
10574  */
10575 static const struct address_space_operations btrfs_aops = {
10576         .readpage       = btrfs_readpage,
10577         .writepage      = btrfs_writepage,
10578         .writepages     = btrfs_writepages,
10579         .readpages      = btrfs_readpages,
10580         .direct_IO      = btrfs_direct_IO,
10581         .invalidatepage = btrfs_invalidatepage,
10582         .releasepage    = btrfs_releasepage,
10583         .set_page_dirty = btrfs_set_page_dirty,
10584         .error_remove_page = generic_error_remove_page,
10585 };
10586
10587 static const struct address_space_operations btrfs_symlink_aops = {
10588         .readpage       = btrfs_readpage,
10589         .writepage      = btrfs_writepage,
10590         .invalidatepage = btrfs_invalidatepage,
10591         .releasepage    = btrfs_releasepage,
10592 };
10593
10594 static const struct inode_operations btrfs_file_inode_operations = {
10595         .getattr        = btrfs_getattr,
10596         .setattr        = btrfs_setattr,
10597         .listxattr      = btrfs_listxattr,
10598         .permission     = btrfs_permission,
10599         .fiemap         = btrfs_fiemap,
10600         .get_acl        = btrfs_get_acl,
10601         .set_acl        = btrfs_set_acl,
10602         .update_time    = btrfs_update_time,
10603 };
10604 static const struct inode_operations btrfs_special_inode_operations = {
10605         .getattr        = btrfs_getattr,
10606         .setattr        = btrfs_setattr,
10607         .permission     = btrfs_permission,
10608         .listxattr      = btrfs_listxattr,
10609         .get_acl        = btrfs_get_acl,
10610         .set_acl        = btrfs_set_acl,
10611         .update_time    = btrfs_update_time,
10612 };
10613 static const struct inode_operations btrfs_symlink_inode_operations = {
10614         .get_link       = page_get_link,
10615         .getattr        = btrfs_getattr,
10616         .setattr        = btrfs_setattr,
10617         .permission     = btrfs_permission,
10618         .listxattr      = btrfs_listxattr,
10619         .update_time    = btrfs_update_time,
10620 };
10621
10622 const struct dentry_operations btrfs_dentry_operations = {
10623         .d_delete       = btrfs_dentry_delete,
10624 };