]> asedeno.scripts.mit.edu Git - linux.git/blob - fs/btrfs/inode.c
Btrfs: delete dead code in btrfs_orphan_commit_root()
[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  * NOTE: caller of this function should reserve 5 units of metadata for
3341  *       this function.
3342  */
3343 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3344                 struct btrfs_inode *inode)
3345 {
3346         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
3347         struct btrfs_root *root = inode->root;
3348         struct btrfs_block_rsv *block_rsv = NULL;
3349         int reserve = 0;
3350         int ret;
3351
3352         if (!root->orphan_block_rsv) {
3353                 block_rsv = btrfs_alloc_block_rsv(fs_info,
3354                                                   BTRFS_BLOCK_RSV_TEMP);
3355                 if (!block_rsv)
3356                         return -ENOMEM;
3357         }
3358
3359         if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3360                               &inode->runtime_flags))
3361                 reserve = 1;
3362
3363         spin_lock(&root->orphan_lock);
3364         /* If someone has created ->orphan_block_rsv, be happy to use it. */
3365         if (!root->orphan_block_rsv) {
3366                 root->orphan_block_rsv = block_rsv;
3367         } else if (block_rsv) {
3368                 btrfs_free_block_rsv(fs_info, block_rsv);
3369                 block_rsv = NULL;
3370         }
3371
3372         atomic_inc(&root->orphan_inodes);
3373         spin_unlock(&root->orphan_lock);
3374
3375         /* grab metadata reservation from transaction handle */
3376         if (reserve) {
3377                 ret = btrfs_orphan_reserve_metadata(trans, inode);
3378                 ASSERT(!ret);
3379                 if (ret) {
3380                         /*
3381                          * dec doesn't need spin_lock as ->orphan_block_rsv
3382                          * would be released only if ->orphan_inodes is
3383                          * zero.
3384                          */
3385                         atomic_dec(&root->orphan_inodes);
3386                         clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3387                                   &inode->runtime_flags);
3388                         return ret;
3389                 }
3390         }
3391
3392         /* insert an orphan item to track this unlinked file */
3393         ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3394         if (ret) {
3395                 if (reserve) {
3396                         clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3397                                   &inode->runtime_flags);
3398                         btrfs_orphan_release_metadata(inode);
3399                 }
3400                 /*
3401                  * btrfs_orphan_commit_root may race with us and set
3402                  * ->orphan_block_rsv to zero, in order to avoid that,
3403                  * decrease ->orphan_inodes after everything is done.
3404                  */
3405                 atomic_dec(&root->orphan_inodes);
3406                 if (ret != -EEXIST) {
3407                         btrfs_abort_transaction(trans, ret);
3408                         return ret;
3409                 }
3410         }
3411
3412         return 0;
3413 }
3414
3415 /*
3416  * We have done the delete so we can go ahead and remove the orphan item for
3417  * this particular inode.
3418  */
3419 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3420                             struct btrfs_inode *inode)
3421 {
3422         struct btrfs_root *root = inode->root;
3423         int ret = 0;
3424
3425         if (trans)
3426                 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3427
3428         if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3429                                &inode->runtime_flags))
3430                 btrfs_orphan_release_metadata(inode);
3431
3432         /*
3433          * btrfs_orphan_commit_root may race with us and set ->orphan_block_rsv
3434          * to zero, in order to avoid that, decrease ->orphan_inodes after
3435          * everything is done.
3436          */
3437         atomic_dec(&root->orphan_inodes);
3438
3439         return ret;
3440 }
3441
3442 /*
3443  * this cleans up any orphans that may be left on the list from the last use
3444  * of this root.
3445  */
3446 int btrfs_orphan_cleanup(struct btrfs_root *root)
3447 {
3448         struct btrfs_fs_info *fs_info = root->fs_info;
3449         struct btrfs_path *path;
3450         struct extent_buffer *leaf;
3451         struct btrfs_key key, found_key;
3452         struct btrfs_trans_handle *trans;
3453         struct inode *inode;
3454         u64 last_objectid = 0;
3455         int ret = 0, nr_unlink = 0;
3456
3457         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3458                 return 0;
3459
3460         path = btrfs_alloc_path();
3461         if (!path) {
3462                 ret = -ENOMEM;
3463                 goto out;
3464         }
3465         path->reada = READA_BACK;
3466
3467         key.objectid = BTRFS_ORPHAN_OBJECTID;
3468         key.type = BTRFS_ORPHAN_ITEM_KEY;
3469         key.offset = (u64)-1;
3470
3471         while (1) {
3472                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3473                 if (ret < 0)
3474                         goto out;
3475
3476                 /*
3477                  * if ret == 0 means we found what we were searching for, which
3478                  * is weird, but possible, so only screw with path if we didn't
3479                  * find the key and see if we have stuff that matches
3480                  */
3481                 if (ret > 0) {
3482                         ret = 0;
3483                         if (path->slots[0] == 0)
3484                                 break;
3485                         path->slots[0]--;
3486                 }
3487
3488                 /* pull out the item */
3489                 leaf = path->nodes[0];
3490                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3491
3492                 /* make sure the item matches what we want */
3493                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3494                         break;
3495                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3496                         break;
3497
3498                 /* release the path since we're done with it */
3499                 btrfs_release_path(path);
3500
3501                 /*
3502                  * this is where we are basically btrfs_lookup, without the
3503                  * crossing root thing.  we store the inode number in the
3504                  * offset of the orphan item.
3505                  */
3506
3507                 if (found_key.offset == last_objectid) {
3508                         btrfs_err(fs_info,
3509                                   "Error removing orphan entry, stopping orphan cleanup");
3510                         ret = -EINVAL;
3511                         goto out;
3512                 }
3513
3514                 last_objectid = found_key.offset;
3515
3516                 found_key.objectid = found_key.offset;
3517                 found_key.type = BTRFS_INODE_ITEM_KEY;
3518                 found_key.offset = 0;
3519                 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3520                 ret = PTR_ERR_OR_ZERO(inode);
3521                 if (ret && ret != -ENOENT)
3522                         goto out;
3523
3524                 if (ret == -ENOENT && root == fs_info->tree_root) {
3525                         struct btrfs_root *dead_root;
3526                         struct btrfs_fs_info *fs_info = root->fs_info;
3527                         int is_dead_root = 0;
3528
3529                         /*
3530                          * this is an orphan in the tree root. Currently these
3531                          * could come from 2 sources:
3532                          *  a) a snapshot deletion in progress
3533                          *  b) a free space cache inode
3534                          * We need to distinguish those two, as the snapshot
3535                          * orphan must not get deleted.
3536                          * find_dead_roots already ran before us, so if this
3537                          * is a snapshot deletion, we should find the root
3538                          * in the dead_roots list
3539                          */
3540                         spin_lock(&fs_info->trans_lock);
3541                         list_for_each_entry(dead_root, &fs_info->dead_roots,
3542                                             root_list) {
3543                                 if (dead_root->root_key.objectid ==
3544                                     found_key.objectid) {
3545                                         is_dead_root = 1;
3546                                         break;
3547                                 }
3548                         }
3549                         spin_unlock(&fs_info->trans_lock);
3550                         if (is_dead_root) {
3551                                 /* prevent this orphan from being found again */
3552                                 key.offset = found_key.objectid - 1;
3553                                 continue;
3554                         }
3555
3556                 }
3557
3558                 /*
3559                  * If we have an inode with links, there are a couple of
3560                  * possibilities. Old kernels (before v3.12) used to create an
3561                  * orphan item for truncate indicating that there were possibly
3562                  * extent items past i_size that needed to be deleted. In v3.12,
3563                  * truncate was changed to update i_size in sync with the extent
3564                  * items, but the (useless) orphan item was still created. Since
3565                  * v4.18, we don't create the orphan item for truncate at all.
3566                  *
3567                  * So, this item could mean that we need to do a truncate, but
3568                  * only if this filesystem was last used on a pre-v3.12 kernel
3569                  * and was not cleanly unmounted. The odds of that are quite
3570                  * slim, and it's a pain to do the truncate now, so just delete
3571                  * the orphan item.
3572                  *
3573                  * It's also possible that this orphan item was supposed to be
3574                  * deleted but wasn't. The inode number may have been reused,
3575                  * but either way, we can delete the orphan item.
3576                  */
3577                 if (ret == -ENOENT || inode->i_nlink) {
3578                         if (!ret)
3579                                 iput(inode);
3580                         trans = btrfs_start_transaction(root, 1);
3581                         if (IS_ERR(trans)) {
3582                                 ret = PTR_ERR(trans);
3583                                 goto out;
3584                         }
3585                         btrfs_debug(fs_info, "auto deleting %Lu",
3586                                     found_key.objectid);
3587                         ret = btrfs_del_orphan_item(trans, root,
3588                                                     found_key.objectid);
3589                         btrfs_end_transaction(trans);
3590                         if (ret)
3591                                 goto out;
3592                         continue;
3593                 }
3594
3595                 atomic_inc(&root->orphan_inodes);
3596
3597                 nr_unlink++;
3598
3599                 /* this will do delete_inode and everything for us */
3600                 iput(inode);
3601                 if (ret)
3602                         goto out;
3603         }
3604         /* release the path since we're done with it */
3605         btrfs_release_path(path);
3606
3607         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3608
3609         if (root->orphan_block_rsv)
3610                 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv,
3611                                         (u64)-1);
3612
3613         if (root->orphan_block_rsv ||
3614             test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3615                 trans = btrfs_join_transaction(root);
3616                 if (!IS_ERR(trans))
3617                         btrfs_end_transaction(trans);
3618         }
3619
3620         if (nr_unlink)
3621                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3622
3623 out:
3624         if (ret)
3625                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3626         btrfs_free_path(path);
3627         return ret;
3628 }
3629
3630 /*
3631  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3632  * don't find any xattrs, we know there can't be any acls.
3633  *
3634  * slot is the slot the inode is in, objectid is the objectid of the inode
3635  */
3636 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3637                                           int slot, u64 objectid,
3638                                           int *first_xattr_slot)
3639 {
3640         u32 nritems = btrfs_header_nritems(leaf);
3641         struct btrfs_key found_key;
3642         static u64 xattr_access = 0;
3643         static u64 xattr_default = 0;
3644         int scanned = 0;
3645
3646         if (!xattr_access) {
3647                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3648                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3649                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3650                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3651         }
3652
3653         slot++;
3654         *first_xattr_slot = -1;
3655         while (slot < nritems) {
3656                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3657
3658                 /* we found a different objectid, there must not be acls */
3659                 if (found_key.objectid != objectid)
3660                         return 0;
3661
3662                 /* we found an xattr, assume we've got an acl */
3663                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3664                         if (*first_xattr_slot == -1)
3665                                 *first_xattr_slot = slot;
3666                         if (found_key.offset == xattr_access ||
3667                             found_key.offset == xattr_default)
3668                                 return 1;
3669                 }
3670
3671                 /*
3672                  * we found a key greater than an xattr key, there can't
3673                  * be any acls later on
3674                  */
3675                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3676                         return 0;
3677
3678                 slot++;
3679                 scanned++;
3680
3681                 /*
3682                  * it goes inode, inode backrefs, xattrs, extents,
3683                  * so if there are a ton of hard links to an inode there can
3684                  * be a lot of backrefs.  Don't waste time searching too hard,
3685                  * this is just an optimization
3686                  */
3687                 if (scanned >= 8)
3688                         break;
3689         }
3690         /* we hit the end of the leaf before we found an xattr or
3691          * something larger than an xattr.  We have to assume the inode
3692          * has acls
3693          */
3694         if (*first_xattr_slot == -1)
3695                 *first_xattr_slot = slot;
3696         return 1;
3697 }
3698
3699 /*
3700  * read an inode from the btree into the in-memory inode
3701  */
3702 static int btrfs_read_locked_inode(struct inode *inode)
3703 {
3704         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3705         struct btrfs_path *path;
3706         struct extent_buffer *leaf;
3707         struct btrfs_inode_item *inode_item;
3708         struct btrfs_root *root = BTRFS_I(inode)->root;
3709         struct btrfs_key location;
3710         unsigned long ptr;
3711         int maybe_acls;
3712         u32 rdev;
3713         int ret;
3714         bool filled = false;
3715         int first_xattr_slot;
3716
3717         ret = btrfs_fill_inode(inode, &rdev);
3718         if (!ret)
3719                 filled = true;
3720
3721         path = btrfs_alloc_path();
3722         if (!path) {
3723                 ret = -ENOMEM;
3724                 goto make_bad;
3725         }
3726
3727         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3728
3729         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3730         if (ret) {
3731                 if (ret > 0)
3732                         ret = -ENOENT;
3733                 goto make_bad;
3734         }
3735
3736         leaf = path->nodes[0];
3737
3738         if (filled)
3739                 goto cache_index;
3740
3741         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3742                                     struct btrfs_inode_item);
3743         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3744         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3745         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3746         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3747         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3748
3749         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3750         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3751
3752         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3753         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3754
3755         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3756         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3757
3758         BTRFS_I(inode)->i_otime.tv_sec =
3759                 btrfs_timespec_sec(leaf, &inode_item->otime);
3760         BTRFS_I(inode)->i_otime.tv_nsec =
3761                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3762
3763         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3764         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3765         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3766
3767         inode_set_iversion_queried(inode,
3768                                    btrfs_inode_sequence(leaf, inode_item));
3769         inode->i_generation = BTRFS_I(inode)->generation;
3770         inode->i_rdev = 0;
3771         rdev = btrfs_inode_rdev(leaf, inode_item);
3772
3773         BTRFS_I(inode)->index_cnt = (u64)-1;
3774         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3775
3776 cache_index:
3777         /*
3778          * If we were modified in the current generation and evicted from memory
3779          * and then re-read we need to do a full sync since we don't have any
3780          * idea about which extents were modified before we were evicted from
3781          * cache.
3782          *
3783          * This is required for both inode re-read from disk and delayed inode
3784          * in delayed_nodes_tree.
3785          */
3786         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3787                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3788                         &BTRFS_I(inode)->runtime_flags);
3789
3790         /*
3791          * We don't persist the id of the transaction where an unlink operation
3792          * against the inode was last made. So here we assume the inode might
3793          * have been evicted, and therefore the exact value of last_unlink_trans
3794          * lost, and set it to last_trans to avoid metadata inconsistencies
3795          * between the inode and its parent if the inode is fsync'ed and the log
3796          * replayed. For example, in the scenario:
3797          *
3798          * touch mydir/foo
3799          * ln mydir/foo mydir/bar
3800          * sync
3801          * unlink mydir/bar
3802          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3803          * xfs_io -c fsync mydir/foo
3804          * <power failure>
3805          * mount fs, triggers fsync log replay
3806          *
3807          * We must make sure that when we fsync our inode foo we also log its
3808          * parent inode, otherwise after log replay the parent still has the
3809          * dentry with the "bar" name but our inode foo has a link count of 1
3810          * and doesn't have an inode ref with the name "bar" anymore.
3811          *
3812          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3813          * but it guarantees correctness at the expense of occasional full
3814          * transaction commits on fsync if our inode is a directory, or if our
3815          * inode is not a directory, logging its parent unnecessarily.
3816          */
3817         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3818
3819         path->slots[0]++;
3820         if (inode->i_nlink != 1 ||
3821             path->slots[0] >= btrfs_header_nritems(leaf))
3822                 goto cache_acl;
3823
3824         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3825         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3826                 goto cache_acl;
3827
3828         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3829         if (location.type == BTRFS_INODE_REF_KEY) {
3830                 struct btrfs_inode_ref *ref;
3831
3832                 ref = (struct btrfs_inode_ref *)ptr;
3833                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3834         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3835                 struct btrfs_inode_extref *extref;
3836
3837                 extref = (struct btrfs_inode_extref *)ptr;
3838                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3839                                                                      extref);
3840         }
3841 cache_acl:
3842         /*
3843          * try to precache a NULL acl entry for files that don't have
3844          * any xattrs or acls
3845          */
3846         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3847                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3848         if (first_xattr_slot != -1) {
3849                 path->slots[0] = first_xattr_slot;
3850                 ret = btrfs_load_inode_props(inode, path);
3851                 if (ret)
3852                         btrfs_err(fs_info,
3853                                   "error loading props for ino %llu (root %llu): %d",
3854                                   btrfs_ino(BTRFS_I(inode)),
3855                                   root->root_key.objectid, ret);
3856         }
3857         btrfs_free_path(path);
3858
3859         if (!maybe_acls)
3860                 cache_no_acl(inode);
3861
3862         switch (inode->i_mode & S_IFMT) {
3863         case S_IFREG:
3864                 inode->i_mapping->a_ops = &btrfs_aops;
3865                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3866                 inode->i_fop = &btrfs_file_operations;
3867                 inode->i_op = &btrfs_file_inode_operations;
3868                 break;
3869         case S_IFDIR:
3870                 inode->i_fop = &btrfs_dir_file_operations;
3871                 inode->i_op = &btrfs_dir_inode_operations;
3872                 break;
3873         case S_IFLNK:
3874                 inode->i_op = &btrfs_symlink_inode_operations;
3875                 inode_nohighmem(inode);
3876                 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3877                 break;
3878         default:
3879                 inode->i_op = &btrfs_special_inode_operations;
3880                 init_special_inode(inode, inode->i_mode, rdev);
3881                 break;
3882         }
3883
3884         btrfs_sync_inode_flags_to_i_flags(inode);
3885         return 0;
3886
3887 make_bad:
3888         btrfs_free_path(path);
3889         make_bad_inode(inode);
3890         return ret;
3891 }
3892
3893 /*
3894  * given a leaf and an inode, copy the inode fields into the leaf
3895  */
3896 static void fill_inode_item(struct btrfs_trans_handle *trans,
3897                             struct extent_buffer *leaf,
3898                             struct btrfs_inode_item *item,
3899                             struct inode *inode)
3900 {
3901         struct btrfs_map_token token;
3902
3903         btrfs_init_map_token(&token);
3904
3905         btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3906         btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3907         btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3908                                    &token);
3909         btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3910         btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3911
3912         btrfs_set_token_timespec_sec(leaf, &item->atime,
3913                                      inode->i_atime.tv_sec, &token);
3914         btrfs_set_token_timespec_nsec(leaf, &item->atime,
3915                                       inode->i_atime.tv_nsec, &token);
3916
3917         btrfs_set_token_timespec_sec(leaf, &item->mtime,
3918                                      inode->i_mtime.tv_sec, &token);
3919         btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3920                                       inode->i_mtime.tv_nsec, &token);
3921
3922         btrfs_set_token_timespec_sec(leaf, &item->ctime,
3923                                      inode->i_ctime.tv_sec, &token);
3924         btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3925                                       inode->i_ctime.tv_nsec, &token);
3926
3927         btrfs_set_token_timespec_sec(leaf, &item->otime,
3928                                      BTRFS_I(inode)->i_otime.tv_sec, &token);
3929         btrfs_set_token_timespec_nsec(leaf, &item->otime,
3930                                       BTRFS_I(inode)->i_otime.tv_nsec, &token);
3931
3932         btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3933                                      &token);
3934         btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3935                                          &token);
3936         btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3937                                        &token);
3938         btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3939         btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3940         btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3941         btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3942 }
3943
3944 /*
3945  * copy everything in the in-memory inode into the btree.
3946  */
3947 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3948                                 struct btrfs_root *root, struct inode *inode)
3949 {
3950         struct btrfs_inode_item *inode_item;
3951         struct btrfs_path *path;
3952         struct extent_buffer *leaf;
3953         int ret;
3954
3955         path = btrfs_alloc_path();
3956         if (!path)
3957                 return -ENOMEM;
3958
3959         path->leave_spinning = 1;
3960         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3961                                  1);
3962         if (ret) {
3963                 if (ret > 0)
3964                         ret = -ENOENT;
3965                 goto failed;
3966         }
3967
3968         leaf = path->nodes[0];
3969         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3970                                     struct btrfs_inode_item);
3971
3972         fill_inode_item(trans, leaf, inode_item, inode);
3973         btrfs_mark_buffer_dirty(leaf);
3974         btrfs_set_inode_last_trans(trans, inode);
3975         ret = 0;
3976 failed:
3977         btrfs_free_path(path);
3978         return ret;
3979 }
3980
3981 /*
3982  * copy everything in the in-memory inode into the btree.
3983  */
3984 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3985                                 struct btrfs_root *root, struct inode *inode)
3986 {
3987         struct btrfs_fs_info *fs_info = root->fs_info;
3988         int ret;
3989
3990         /*
3991          * If the inode is a free space inode, we can deadlock during commit
3992          * if we put it into the delayed code.
3993          *
3994          * The data relocation inode should also be directly updated
3995          * without delay
3996          */
3997         if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3998             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3999             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4000                 btrfs_update_root_times(trans, root);
4001
4002                 ret = btrfs_delayed_update_inode(trans, root, inode);
4003                 if (!ret)
4004                         btrfs_set_inode_last_trans(trans, inode);
4005                 return ret;
4006         }
4007
4008         return btrfs_update_inode_item(trans, root, inode);
4009 }
4010
4011 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4012                                          struct btrfs_root *root,
4013                                          struct inode *inode)
4014 {
4015         int ret;
4016
4017         ret = btrfs_update_inode(trans, root, inode);
4018         if (ret == -ENOSPC)
4019                 return btrfs_update_inode_item(trans, root, inode);
4020         return ret;
4021 }
4022
4023 /*
4024  * unlink helper that gets used here in inode.c and in the tree logging
4025  * recovery code.  It remove a link in a directory with a given name, and
4026  * also drops the back refs in the inode to the directory
4027  */
4028 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4029                                 struct btrfs_root *root,
4030                                 struct btrfs_inode *dir,
4031                                 struct btrfs_inode *inode,
4032                                 const char *name, int name_len)
4033 {
4034         struct btrfs_fs_info *fs_info = root->fs_info;
4035         struct btrfs_path *path;
4036         int ret = 0;
4037         struct extent_buffer *leaf;
4038         struct btrfs_dir_item *di;
4039         struct btrfs_key key;
4040         u64 index;
4041         u64 ino = btrfs_ino(inode);
4042         u64 dir_ino = btrfs_ino(dir);
4043
4044         path = btrfs_alloc_path();
4045         if (!path) {
4046                 ret = -ENOMEM;
4047                 goto out;
4048         }
4049
4050         path->leave_spinning = 1;
4051         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4052                                     name, name_len, -1);
4053         if (IS_ERR(di)) {
4054                 ret = PTR_ERR(di);
4055                 goto err;
4056         }
4057         if (!di) {
4058                 ret = -ENOENT;
4059                 goto err;
4060         }
4061         leaf = path->nodes[0];
4062         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4063         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4064         if (ret)
4065                 goto err;
4066         btrfs_release_path(path);
4067
4068         /*
4069          * If we don't have dir index, we have to get it by looking up
4070          * the inode ref, since we get the inode ref, remove it directly,
4071          * it is unnecessary to do delayed deletion.
4072          *
4073          * But if we have dir index, needn't search inode ref to get it.
4074          * Since the inode ref is close to the inode item, it is better
4075          * that we delay to delete it, and just do this deletion when
4076          * we update the inode item.
4077          */
4078         if (inode->dir_index) {
4079                 ret = btrfs_delayed_delete_inode_ref(inode);
4080                 if (!ret) {
4081                         index = inode->dir_index;
4082                         goto skip_backref;
4083                 }
4084         }
4085
4086         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4087                                   dir_ino, &index);
4088         if (ret) {
4089                 btrfs_info(fs_info,
4090                         "failed to delete reference to %.*s, inode %llu parent %llu",
4091                         name_len, name, ino, dir_ino);
4092                 btrfs_abort_transaction(trans, ret);
4093                 goto err;
4094         }
4095 skip_backref:
4096         ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
4097         if (ret) {
4098                 btrfs_abort_transaction(trans, ret);
4099                 goto err;
4100         }
4101
4102         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
4103                         dir_ino);
4104         if (ret != 0 && ret != -ENOENT) {
4105                 btrfs_abort_transaction(trans, ret);
4106                 goto err;
4107         }
4108
4109         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4110                         index);
4111         if (ret == -ENOENT)
4112                 ret = 0;
4113         else if (ret)
4114                 btrfs_abort_transaction(trans, ret);
4115 err:
4116         btrfs_free_path(path);
4117         if (ret)
4118                 goto out;
4119
4120         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4121         inode_inc_iversion(&inode->vfs_inode);
4122         inode_inc_iversion(&dir->vfs_inode);
4123         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4124                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4125         ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4126 out:
4127         return ret;
4128 }
4129
4130 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4131                        struct btrfs_root *root,
4132                        struct btrfs_inode *dir, struct btrfs_inode *inode,
4133                        const char *name, int name_len)
4134 {
4135         int ret;
4136         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4137         if (!ret) {
4138                 drop_nlink(&inode->vfs_inode);
4139                 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4140         }
4141         return ret;
4142 }
4143
4144 /*
4145  * helper to start transaction for unlink and rmdir.
4146  *
4147  * unlink and rmdir are special in btrfs, they do not always free space, so
4148  * if we cannot make our reservations the normal way try and see if there is
4149  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4150  * allow the unlink to occur.
4151  */
4152 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4153 {
4154         struct btrfs_root *root = BTRFS_I(dir)->root;
4155
4156         /*
4157          * 1 for the possible orphan item
4158          * 1 for the dir item
4159          * 1 for the dir index
4160          * 1 for the inode ref
4161          * 1 for the inode
4162          */
4163         return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4164 }
4165
4166 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4167 {
4168         struct btrfs_root *root = BTRFS_I(dir)->root;
4169         struct btrfs_trans_handle *trans;
4170         struct inode *inode = d_inode(dentry);
4171         int ret;
4172
4173         trans = __unlink_start_trans(dir);
4174         if (IS_ERR(trans))
4175                 return PTR_ERR(trans);
4176
4177         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4178                         0);
4179
4180         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4181                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4182                         dentry->d_name.len);
4183         if (ret)
4184                 goto out;
4185
4186         if (inode->i_nlink == 0) {
4187                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4188                 if (ret)
4189                         goto out;
4190         }
4191
4192 out:
4193         btrfs_end_transaction(trans);
4194         btrfs_btree_balance_dirty(root->fs_info);
4195         return ret;
4196 }
4197
4198 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4199                         struct btrfs_root *root,
4200                         struct inode *dir, u64 objectid,
4201                         const char *name, int name_len)
4202 {
4203         struct btrfs_fs_info *fs_info = root->fs_info;
4204         struct btrfs_path *path;
4205         struct extent_buffer *leaf;
4206         struct btrfs_dir_item *di;
4207         struct btrfs_key key;
4208         u64 index;
4209         int ret;
4210         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4211
4212         path = btrfs_alloc_path();
4213         if (!path)
4214                 return -ENOMEM;
4215
4216         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4217                                    name, name_len, -1);
4218         if (IS_ERR_OR_NULL(di)) {
4219                 if (!di)
4220                         ret = -ENOENT;
4221                 else
4222                         ret = PTR_ERR(di);
4223                 goto out;
4224         }
4225
4226         leaf = path->nodes[0];
4227         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4228         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4229         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4230         if (ret) {
4231                 btrfs_abort_transaction(trans, ret);
4232                 goto out;
4233         }
4234         btrfs_release_path(path);
4235
4236         ret = btrfs_del_root_ref(trans, fs_info, objectid,
4237                                  root->root_key.objectid, dir_ino,
4238                                  &index, name, name_len);
4239         if (ret < 0) {
4240                 if (ret != -ENOENT) {
4241                         btrfs_abort_transaction(trans, ret);
4242                         goto out;
4243                 }
4244                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4245                                                  name, name_len);
4246                 if (IS_ERR_OR_NULL(di)) {
4247                         if (!di)
4248                                 ret = -ENOENT;
4249                         else
4250                                 ret = PTR_ERR(di);
4251                         btrfs_abort_transaction(trans, ret);
4252                         goto out;
4253                 }
4254
4255                 leaf = path->nodes[0];
4256                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4257                 btrfs_release_path(path);
4258                 index = key.offset;
4259         }
4260         btrfs_release_path(path);
4261
4262         ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4263         if (ret) {
4264                 btrfs_abort_transaction(trans, ret);
4265                 goto out;
4266         }
4267
4268         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4269         inode_inc_iversion(dir);
4270         dir->i_mtime = dir->i_ctime = current_time(dir);
4271         ret = btrfs_update_inode_fallback(trans, root, dir);
4272         if (ret)
4273                 btrfs_abort_transaction(trans, ret);
4274 out:
4275         btrfs_free_path(path);
4276         return ret;
4277 }
4278
4279 /*
4280  * Helper to check if the subvolume references other subvolumes or if it's
4281  * default.
4282  */
4283 static noinline int may_destroy_subvol(struct btrfs_root *root)
4284 {
4285         struct btrfs_fs_info *fs_info = root->fs_info;
4286         struct btrfs_path *path;
4287         struct btrfs_dir_item *di;
4288         struct btrfs_key key;
4289         u64 dir_id;
4290         int ret;
4291
4292         path = btrfs_alloc_path();
4293         if (!path)
4294                 return -ENOMEM;
4295
4296         /* Make sure this root isn't set as the default subvol */
4297         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4298         di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4299                                    dir_id, "default", 7, 0);
4300         if (di && !IS_ERR(di)) {
4301                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4302                 if (key.objectid == root->root_key.objectid) {
4303                         ret = -EPERM;
4304                         btrfs_err(fs_info,
4305                                   "deleting default subvolume %llu is not allowed",
4306                                   key.objectid);
4307                         goto out;
4308                 }
4309                 btrfs_release_path(path);
4310         }
4311
4312         key.objectid = root->root_key.objectid;
4313         key.type = BTRFS_ROOT_REF_KEY;
4314         key.offset = (u64)-1;
4315
4316         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4317         if (ret < 0)
4318                 goto out;
4319         BUG_ON(ret == 0);
4320
4321         ret = 0;
4322         if (path->slots[0] > 0) {
4323                 path->slots[0]--;
4324                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4325                 if (key.objectid == root->root_key.objectid &&
4326                     key.type == BTRFS_ROOT_REF_KEY)
4327                         ret = -ENOTEMPTY;
4328         }
4329 out:
4330         btrfs_free_path(path);
4331         return ret;
4332 }
4333
4334 /* Delete all dentries for inodes belonging to the root */
4335 static void btrfs_prune_dentries(struct btrfs_root *root)
4336 {
4337         struct btrfs_fs_info *fs_info = root->fs_info;
4338         struct rb_node *node;
4339         struct rb_node *prev;
4340         struct btrfs_inode *entry;
4341         struct inode *inode;
4342         u64 objectid = 0;
4343
4344         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4345                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4346
4347         spin_lock(&root->inode_lock);
4348 again:
4349         node = root->inode_tree.rb_node;
4350         prev = NULL;
4351         while (node) {
4352                 prev = node;
4353                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4354
4355                 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4356                         node = node->rb_left;
4357                 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4358                         node = node->rb_right;
4359                 else
4360                         break;
4361         }
4362         if (!node) {
4363                 while (prev) {
4364                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4365                         if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
4366                                 node = prev;
4367                                 break;
4368                         }
4369                         prev = rb_next(prev);
4370                 }
4371         }
4372         while (node) {
4373                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4374                 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
4375                 inode = igrab(&entry->vfs_inode);
4376                 if (inode) {
4377                         spin_unlock(&root->inode_lock);
4378                         if (atomic_read(&inode->i_count) > 1)
4379                                 d_prune_aliases(inode);
4380                         /*
4381                          * btrfs_drop_inode will have it removed from the inode
4382                          * cache when its usage count hits zero.
4383                          */
4384                         iput(inode);
4385                         cond_resched();
4386                         spin_lock(&root->inode_lock);
4387                         goto again;
4388                 }
4389
4390                 if (cond_resched_lock(&root->inode_lock))
4391                         goto again;
4392
4393                 node = rb_next(node);
4394         }
4395         spin_unlock(&root->inode_lock);
4396 }
4397
4398 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4399 {
4400         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4401         struct btrfs_root *root = BTRFS_I(dir)->root;
4402         struct inode *inode = d_inode(dentry);
4403         struct btrfs_root *dest = BTRFS_I(inode)->root;
4404         struct btrfs_trans_handle *trans;
4405         struct btrfs_block_rsv block_rsv;
4406         u64 root_flags;
4407         u64 qgroup_reserved;
4408         int ret;
4409         int err;
4410
4411         /*
4412          * Don't allow to delete a subvolume with send in progress. This is
4413          * inside the inode lock so the error handling that has to drop the bit
4414          * again is not run concurrently.
4415          */
4416         spin_lock(&dest->root_item_lock);
4417         root_flags = btrfs_root_flags(&dest->root_item);
4418         if (dest->send_in_progress == 0) {
4419                 btrfs_set_root_flags(&dest->root_item,
4420                                 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4421                 spin_unlock(&dest->root_item_lock);
4422         } else {
4423                 spin_unlock(&dest->root_item_lock);
4424                 btrfs_warn(fs_info,
4425                            "attempt to delete subvolume %llu during send",
4426                            dest->root_key.objectid);
4427                 return -EPERM;
4428         }
4429
4430         down_write(&fs_info->subvol_sem);
4431
4432         err = may_destroy_subvol(dest);
4433         if (err)
4434                 goto out_up_write;
4435
4436         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4437         /*
4438          * One for dir inode,
4439          * two for dir entries,
4440          * two for root ref/backref.
4441          */
4442         err = btrfs_subvolume_reserve_metadata(root, &block_rsv,
4443                                                5, &qgroup_reserved, true);
4444         if (err)
4445                 goto out_up_write;
4446
4447         trans = btrfs_start_transaction(root, 0);
4448         if (IS_ERR(trans)) {
4449                 err = PTR_ERR(trans);
4450                 goto out_release;
4451         }
4452         trans->block_rsv = &block_rsv;
4453         trans->bytes_reserved = block_rsv.size;
4454
4455         btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4456
4457         ret = btrfs_unlink_subvol(trans, root, dir,
4458                                 dest->root_key.objectid,
4459                                 dentry->d_name.name,
4460                                 dentry->d_name.len);
4461         if (ret) {
4462                 err = ret;
4463                 btrfs_abort_transaction(trans, ret);
4464                 goto out_end_trans;
4465         }
4466
4467         btrfs_record_root_in_trans(trans, dest);
4468
4469         memset(&dest->root_item.drop_progress, 0,
4470                 sizeof(dest->root_item.drop_progress));
4471         dest->root_item.drop_level = 0;
4472         btrfs_set_root_refs(&dest->root_item, 0);
4473
4474         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4475                 ret = btrfs_insert_orphan_item(trans,
4476                                         fs_info->tree_root,
4477                                         dest->root_key.objectid);
4478                 if (ret) {
4479                         btrfs_abort_transaction(trans, ret);
4480                         err = ret;
4481                         goto out_end_trans;
4482                 }
4483         }
4484
4485         ret = btrfs_uuid_tree_rem(trans, fs_info, dest->root_item.uuid,
4486                                   BTRFS_UUID_KEY_SUBVOL,
4487                                   dest->root_key.objectid);
4488         if (ret && ret != -ENOENT) {
4489                 btrfs_abort_transaction(trans, ret);
4490                 err = ret;
4491                 goto out_end_trans;
4492         }
4493         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4494                 ret = btrfs_uuid_tree_rem(trans, fs_info,
4495                                           dest->root_item.received_uuid,
4496                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4497                                           dest->root_key.objectid);
4498                 if (ret && ret != -ENOENT) {
4499                         btrfs_abort_transaction(trans, ret);
4500                         err = ret;
4501                         goto out_end_trans;
4502                 }
4503         }
4504
4505 out_end_trans:
4506         trans->block_rsv = NULL;
4507         trans->bytes_reserved = 0;
4508         ret = btrfs_end_transaction(trans);
4509         if (ret && !err)
4510                 err = ret;
4511         inode->i_flags |= S_DEAD;
4512 out_release:
4513         btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4514 out_up_write:
4515         up_write(&fs_info->subvol_sem);
4516         if (err) {
4517                 spin_lock(&dest->root_item_lock);
4518                 root_flags = btrfs_root_flags(&dest->root_item);
4519                 btrfs_set_root_flags(&dest->root_item,
4520                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4521                 spin_unlock(&dest->root_item_lock);
4522         } else {
4523                 d_invalidate(dentry);
4524                 btrfs_prune_dentries(dest);
4525                 ASSERT(dest->send_in_progress == 0);
4526
4527                 /* the last ref */
4528                 if (dest->ino_cache_inode) {
4529                         iput(dest->ino_cache_inode);
4530                         dest->ino_cache_inode = NULL;
4531                 }
4532         }
4533
4534         return err;
4535 }
4536
4537 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4538 {
4539         struct inode *inode = d_inode(dentry);
4540         int err = 0;
4541         struct btrfs_root *root = BTRFS_I(dir)->root;
4542         struct btrfs_trans_handle *trans;
4543         u64 last_unlink_trans;
4544
4545         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4546                 return -ENOTEMPTY;
4547         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4548                 return btrfs_delete_subvolume(dir, dentry);
4549
4550         trans = __unlink_start_trans(dir);
4551         if (IS_ERR(trans))
4552                 return PTR_ERR(trans);
4553
4554         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4555                 err = btrfs_unlink_subvol(trans, root, dir,
4556                                           BTRFS_I(inode)->location.objectid,
4557                                           dentry->d_name.name,
4558                                           dentry->d_name.len);
4559                 goto out;
4560         }
4561
4562         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4563         if (err)
4564                 goto out;
4565
4566         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4567
4568         /* now the directory is empty */
4569         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4570                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4571                         dentry->d_name.len);
4572         if (!err) {
4573                 btrfs_i_size_write(BTRFS_I(inode), 0);
4574                 /*
4575                  * Propagate the last_unlink_trans value of the deleted dir to
4576                  * its parent directory. This is to prevent an unrecoverable
4577                  * log tree in the case we do something like this:
4578                  * 1) create dir foo
4579                  * 2) create snapshot under dir foo
4580                  * 3) delete the snapshot
4581                  * 4) rmdir foo
4582                  * 5) mkdir foo
4583                  * 6) fsync foo or some file inside foo
4584                  */
4585                 if (last_unlink_trans >= trans->transid)
4586                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4587         }
4588 out:
4589         btrfs_end_transaction(trans);
4590         btrfs_btree_balance_dirty(root->fs_info);
4591
4592         return err;
4593 }
4594
4595 static int truncate_space_check(struct btrfs_trans_handle *trans,
4596                                 struct btrfs_root *root,
4597                                 u64 bytes_deleted)
4598 {
4599         struct btrfs_fs_info *fs_info = root->fs_info;
4600         int ret;
4601
4602         /*
4603          * This is only used to apply pressure to the enospc system, we don't
4604          * intend to use this reservation at all.
4605          */
4606         bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4607         bytes_deleted *= fs_info->nodesize;
4608         ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4609                                   bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4610         if (!ret) {
4611                 trace_btrfs_space_reservation(fs_info, "transaction",
4612                                               trans->transid,
4613                                               bytes_deleted, 1);
4614                 trans->bytes_reserved += bytes_deleted;
4615         }
4616         return ret;
4617
4618 }
4619
4620 /*
4621  * Return this if we need to call truncate_block for the last bit of the
4622  * truncate.
4623  */
4624 #define NEED_TRUNCATE_BLOCK 1
4625
4626 /*
4627  * this can truncate away extent items, csum items and directory items.
4628  * It starts at a high offset and removes keys until it can't find
4629  * any higher than new_size
4630  *
4631  * csum items that cross the new i_size are truncated to the new size
4632  * as well.
4633  *
4634  * min_type is the minimum key type to truncate down to.  If set to 0, this
4635  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4636  */
4637 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4638                                struct btrfs_root *root,
4639                                struct inode *inode,
4640                                u64 new_size, u32 min_type)
4641 {
4642         struct btrfs_fs_info *fs_info = root->fs_info;
4643         struct btrfs_path *path;
4644         struct extent_buffer *leaf;
4645         struct btrfs_file_extent_item *fi;
4646         struct btrfs_key key;
4647         struct btrfs_key found_key;
4648         u64 extent_start = 0;
4649         u64 extent_num_bytes = 0;
4650         u64 extent_offset = 0;
4651         u64 item_end = 0;
4652         u64 last_size = new_size;
4653         u32 found_type = (u8)-1;
4654         int found_extent;
4655         int del_item;
4656         int pending_del_nr = 0;
4657         int pending_del_slot = 0;
4658         int extent_type = -1;
4659         int ret;
4660         u64 ino = btrfs_ino(BTRFS_I(inode));
4661         u64 bytes_deleted = 0;
4662         bool be_nice = false;
4663         bool should_throttle = false;
4664         bool should_end = false;
4665
4666         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4667
4668         /*
4669          * for non-free space inodes and ref cows, we want to back off from
4670          * time to time
4671          */
4672         if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4673             test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4674                 be_nice = true;
4675
4676         path = btrfs_alloc_path();
4677         if (!path)
4678                 return -ENOMEM;
4679         path->reada = READA_BACK;
4680
4681         /*
4682          * We want to drop from the next block forward in case this new size is
4683          * not block aligned since we will be keeping the last block of the
4684          * extent just the way it is.
4685          */
4686         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4687             root == fs_info->tree_root)
4688                 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4689                                         fs_info->sectorsize),
4690                                         (u64)-1, 0);
4691
4692         /*
4693          * This function is also used to drop the items in the log tree before
4694          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4695          * it is used to drop the loged items. So we shouldn't kill the delayed
4696          * items.
4697          */
4698         if (min_type == 0 && root == BTRFS_I(inode)->root)
4699                 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4700
4701         key.objectid = ino;
4702         key.offset = (u64)-1;
4703         key.type = (u8)-1;
4704
4705 search_again:
4706         /*
4707          * with a 16K leaf size and 128MB extents, you can actually queue
4708          * up a huge file in a single leaf.  Most of the time that
4709          * bytes_deleted is > 0, it will be huge by the time we get here
4710          */
4711         if (be_nice && bytes_deleted > SZ_32M &&
4712             btrfs_should_end_transaction(trans)) {
4713                 ret = -EAGAIN;
4714                 goto out;
4715         }
4716
4717         path->leave_spinning = 1;
4718         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4719         if (ret < 0)
4720                 goto out;
4721
4722         if (ret > 0) {
4723                 ret = 0;
4724                 /* there are no items in the tree for us to truncate, we're
4725                  * done
4726                  */
4727                 if (path->slots[0] == 0)
4728                         goto out;
4729                 path->slots[0]--;
4730         }
4731
4732         while (1) {
4733                 fi = NULL;
4734                 leaf = path->nodes[0];
4735                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4736                 found_type = found_key.type;
4737
4738                 if (found_key.objectid != ino)
4739                         break;
4740
4741                 if (found_type < min_type)
4742                         break;
4743
4744                 item_end = found_key.offset;
4745                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4746                         fi = btrfs_item_ptr(leaf, path->slots[0],
4747                                             struct btrfs_file_extent_item);
4748                         extent_type = btrfs_file_extent_type(leaf, fi);
4749                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4750                                 item_end +=
4751                                     btrfs_file_extent_num_bytes(leaf, fi);
4752
4753                                 trace_btrfs_truncate_show_fi_regular(
4754                                         BTRFS_I(inode), leaf, fi,
4755                                         found_key.offset);
4756                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4757                                 item_end += btrfs_file_extent_inline_len(leaf,
4758                                                          path->slots[0], fi);
4759
4760                                 trace_btrfs_truncate_show_fi_inline(
4761                                         BTRFS_I(inode), leaf, fi, path->slots[0],
4762                                         found_key.offset);
4763                         }
4764                         item_end--;
4765                 }
4766                 if (found_type > min_type) {
4767                         del_item = 1;
4768                 } else {
4769                         if (item_end < new_size)
4770                                 break;
4771                         if (found_key.offset >= new_size)
4772                                 del_item = 1;
4773                         else
4774                                 del_item = 0;
4775                 }
4776                 found_extent = 0;
4777                 /* FIXME, shrink the extent if the ref count is only 1 */
4778                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4779                         goto delete;
4780
4781                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4782                         u64 num_dec;
4783                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4784                         if (!del_item) {
4785                                 u64 orig_num_bytes =
4786                                         btrfs_file_extent_num_bytes(leaf, fi);
4787                                 extent_num_bytes = ALIGN(new_size -
4788                                                 found_key.offset,
4789                                                 fs_info->sectorsize);
4790                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4791                                                          extent_num_bytes);
4792                                 num_dec = (orig_num_bytes -
4793                                            extent_num_bytes);
4794                                 if (test_bit(BTRFS_ROOT_REF_COWS,
4795                                              &root->state) &&
4796                                     extent_start != 0)
4797                                         inode_sub_bytes(inode, num_dec);
4798                                 btrfs_mark_buffer_dirty(leaf);
4799                         } else {
4800                                 extent_num_bytes =
4801                                         btrfs_file_extent_disk_num_bytes(leaf,
4802                                                                          fi);
4803                                 extent_offset = found_key.offset -
4804                                         btrfs_file_extent_offset(leaf, fi);
4805
4806                                 /* FIXME blocksize != 4096 */
4807                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4808                                 if (extent_start != 0) {
4809                                         found_extent = 1;
4810                                         if (test_bit(BTRFS_ROOT_REF_COWS,
4811                                                      &root->state))
4812                                                 inode_sub_bytes(inode, num_dec);
4813                                 }
4814                         }
4815                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4816                         /*
4817                          * we can't truncate inline items that have had
4818                          * special encodings
4819                          */
4820                         if (!del_item &&
4821                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4822                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4823                             btrfs_file_extent_compression(leaf, fi) == 0) {
4824                                 u32 size = (u32)(new_size - found_key.offset);
4825
4826                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4827                                 size = btrfs_file_extent_calc_inline_size(size);
4828                                 btrfs_truncate_item(root->fs_info, path, size, 1);
4829                         } else if (!del_item) {
4830                                 /*
4831                                  * We have to bail so the last_size is set to
4832                                  * just before this extent.
4833                                  */
4834                                 ret = NEED_TRUNCATE_BLOCK;
4835                                 break;
4836                         }
4837
4838                         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4839                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4840                 }
4841 delete:
4842                 if (del_item)
4843                         last_size = found_key.offset;
4844                 else
4845                         last_size = new_size;
4846                 if (del_item) {
4847                         if (!pending_del_nr) {
4848                                 /* no pending yet, add ourselves */
4849                                 pending_del_slot = path->slots[0];
4850                                 pending_del_nr = 1;
4851                         } else if (pending_del_nr &&
4852                                    path->slots[0] + 1 == pending_del_slot) {
4853                                 /* hop on the pending chunk */
4854                                 pending_del_nr++;
4855                                 pending_del_slot = path->slots[0];
4856                         } else {
4857                                 BUG();
4858                         }
4859                 } else {
4860                         break;
4861                 }
4862                 should_throttle = false;
4863
4864                 if (found_extent &&
4865                     (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4866                      root == fs_info->tree_root)) {
4867                         btrfs_set_path_blocking(path);
4868                         bytes_deleted += extent_num_bytes;
4869                         ret = btrfs_free_extent(trans, root, extent_start,
4870                                                 extent_num_bytes, 0,
4871                                                 btrfs_header_owner(leaf),
4872                                                 ino, extent_offset);
4873                         if (ret) {
4874                                 btrfs_abort_transaction(trans, ret);
4875                                 break;
4876                         }
4877                         if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4878                                 btrfs_async_run_delayed_refs(fs_info,
4879                                         trans->delayed_ref_updates * 2,
4880                                         trans->transid, 0);
4881                         if (be_nice) {
4882                                 if (truncate_space_check(trans, root,
4883                                                          extent_num_bytes)) {
4884                                         should_end = true;
4885                                 }
4886                                 if (btrfs_should_throttle_delayed_refs(trans,
4887                                                                        fs_info))
4888                                         should_throttle = true;
4889                         }
4890                 }
4891
4892                 if (found_type == BTRFS_INODE_ITEM_KEY)
4893                         break;
4894
4895                 if (path->slots[0] == 0 ||
4896                     path->slots[0] != pending_del_slot ||
4897                     should_throttle || should_end) {
4898                         if (pending_del_nr) {
4899                                 ret = btrfs_del_items(trans, root, path,
4900                                                 pending_del_slot,
4901                                                 pending_del_nr);
4902                                 if (ret) {
4903                                         btrfs_abort_transaction(trans, ret);
4904                                         break;
4905                                 }
4906                                 pending_del_nr = 0;
4907                         }
4908                         btrfs_release_path(path);
4909                         if (should_throttle) {
4910                                 unsigned long updates = trans->delayed_ref_updates;
4911                                 if (updates) {
4912                                         trans->delayed_ref_updates = 0;
4913                                         ret = btrfs_run_delayed_refs(trans,
4914                                                                    updates * 2);
4915                                         if (ret)
4916                                                 break;
4917                                 }
4918                         }
4919                         /*
4920                          * if we failed to refill our space rsv, bail out
4921                          * and let the transaction restart
4922                          */
4923                         if (should_end) {
4924                                 ret = -EAGAIN;
4925                                 break;
4926                         }
4927                         goto search_again;
4928                 } else {
4929                         path->slots[0]--;
4930                 }
4931         }
4932 out:
4933         if (ret >= 0 && pending_del_nr) {
4934                 int err;
4935
4936                 err = btrfs_del_items(trans, root, path, pending_del_slot,
4937                                       pending_del_nr);
4938                 if (err) {
4939                         btrfs_abort_transaction(trans, err);
4940                         ret = err;
4941                 }
4942         }
4943         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4944                 ASSERT(last_size >= new_size);
4945                 if (!ret && last_size > new_size)
4946                         last_size = new_size;
4947                 btrfs_ordered_update_i_size(inode, last_size, NULL);
4948         }
4949
4950         btrfs_free_path(path);
4951
4952         if (be_nice && bytes_deleted > SZ_32M && (ret >= 0 || ret == -EAGAIN)) {
4953                 unsigned long updates = trans->delayed_ref_updates;
4954                 int err;
4955
4956                 if (updates) {
4957                         trans->delayed_ref_updates = 0;
4958                         err = btrfs_run_delayed_refs(trans, updates * 2);
4959                         if (err)
4960                                 ret = err;
4961                 }
4962         }
4963         return ret;
4964 }
4965
4966 /*
4967  * btrfs_truncate_block - read, zero a chunk and write a block
4968  * @inode - inode that we're zeroing
4969  * @from - the offset to start zeroing
4970  * @len - the length to zero, 0 to zero the entire range respective to the
4971  *      offset
4972  * @front - zero up to the offset instead of from the offset on
4973  *
4974  * This will find the block for the "from" offset and cow the block and zero the
4975  * part we want to zero.  This is used with truncate and hole punching.
4976  */
4977 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4978                         int front)
4979 {
4980         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4981         struct address_space *mapping = inode->i_mapping;
4982         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4983         struct btrfs_ordered_extent *ordered;
4984         struct extent_state *cached_state = NULL;
4985         struct extent_changeset *data_reserved = NULL;
4986         char *kaddr;
4987         u32 blocksize = fs_info->sectorsize;
4988         pgoff_t index = from >> PAGE_SHIFT;
4989         unsigned offset = from & (blocksize - 1);
4990         struct page *page;
4991         gfp_t mask = btrfs_alloc_write_mask(mapping);
4992         int ret = 0;
4993         u64 block_start;
4994         u64 block_end;
4995
4996         if (IS_ALIGNED(offset, blocksize) &&
4997             (!len || IS_ALIGNED(len, blocksize)))
4998                 goto out;
4999
5000         block_start = round_down(from, blocksize);
5001         block_end = block_start + blocksize - 1;
5002
5003         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
5004                                            block_start, blocksize);
5005         if (ret)
5006                 goto out;
5007
5008 again:
5009         page = find_or_create_page(mapping, index, mask);
5010         if (!page) {
5011                 btrfs_delalloc_release_space(inode, data_reserved,
5012                                              block_start, blocksize, true);
5013                 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
5014                 ret = -ENOMEM;
5015                 goto out;
5016         }
5017
5018         if (!PageUptodate(page)) {
5019                 ret = btrfs_readpage(NULL, page);
5020                 lock_page(page);
5021                 if (page->mapping != mapping) {
5022                         unlock_page(page);
5023                         put_page(page);
5024                         goto again;
5025                 }
5026                 if (!PageUptodate(page)) {
5027                         ret = -EIO;
5028                         goto out_unlock;
5029                 }
5030         }
5031         wait_on_page_writeback(page);
5032
5033         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
5034         set_page_extent_mapped(page);
5035
5036         ordered = btrfs_lookup_ordered_extent(inode, block_start);
5037         if (ordered) {
5038                 unlock_extent_cached(io_tree, block_start, block_end,
5039                                      &cached_state);
5040                 unlock_page(page);
5041                 put_page(page);
5042                 btrfs_start_ordered_extent(inode, ordered, 1);
5043                 btrfs_put_ordered_extent(ordered);
5044                 goto again;
5045         }
5046
5047         clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
5048                           EXTENT_DIRTY | EXTENT_DELALLOC |
5049                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5050                           0, 0, &cached_state);
5051
5052         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5053                                         &cached_state, 0);
5054         if (ret) {
5055                 unlock_extent_cached(io_tree, block_start, block_end,
5056                                      &cached_state);
5057                 goto out_unlock;
5058         }
5059
5060         if (offset != blocksize) {
5061                 if (!len)
5062                         len = blocksize - offset;
5063                 kaddr = kmap(page);
5064                 if (front)
5065                         memset(kaddr + (block_start - page_offset(page)),
5066                                 0, offset);
5067                 else
5068                         memset(kaddr + (block_start - page_offset(page)) +  offset,
5069                                 0, len);
5070                 flush_dcache_page(page);
5071                 kunmap(page);
5072         }
5073         ClearPageChecked(page);
5074         set_page_dirty(page);
5075         unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
5076
5077 out_unlock:
5078         if (ret)
5079                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
5080                                              blocksize, true);
5081         btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
5082         unlock_page(page);
5083         put_page(page);
5084 out:
5085         extent_changeset_free(data_reserved);
5086         return ret;
5087 }
5088
5089 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
5090                              u64 offset, u64 len)
5091 {
5092         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5093         struct btrfs_trans_handle *trans;
5094         int ret;
5095
5096         /*
5097          * Still need to make sure the inode looks like it's been updated so
5098          * that any holes get logged if we fsync.
5099          */
5100         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
5101                 BTRFS_I(inode)->last_trans = fs_info->generation;
5102                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
5103                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
5104                 return 0;
5105         }
5106
5107         /*
5108          * 1 - for the one we're dropping
5109          * 1 - for the one we're adding
5110          * 1 - for updating the inode.
5111          */
5112         trans = btrfs_start_transaction(root, 3);
5113         if (IS_ERR(trans))
5114                 return PTR_ERR(trans);
5115
5116         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5117         if (ret) {
5118                 btrfs_abort_transaction(trans, ret);
5119                 btrfs_end_transaction(trans);
5120                 return ret;
5121         }
5122
5123         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5124                         offset, 0, 0, len, 0, len, 0, 0, 0);
5125         if (ret)
5126                 btrfs_abort_transaction(trans, ret);
5127         else
5128                 btrfs_update_inode(trans, root, inode);
5129         btrfs_end_transaction(trans);
5130         return ret;
5131 }
5132
5133 /*
5134  * This function puts in dummy file extents for the area we're creating a hole
5135  * for.  So if we are truncating this file to a larger size we need to insert
5136  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5137  * the range between oldsize and size
5138  */
5139 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5140 {
5141         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5142         struct btrfs_root *root = BTRFS_I(inode)->root;
5143         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5144         struct extent_map *em = NULL;
5145         struct extent_state *cached_state = NULL;
5146         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5147         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5148         u64 block_end = ALIGN(size, fs_info->sectorsize);
5149         u64 last_byte;
5150         u64 cur_offset;
5151         u64 hole_size;
5152         int err = 0;
5153
5154         /*
5155          * If our size started in the middle of a block we need to zero out the
5156          * rest of the block before we expand the i_size, otherwise we could
5157          * expose stale data.
5158          */
5159         err = btrfs_truncate_block(inode, oldsize, 0, 0);
5160         if (err)
5161                 return err;
5162
5163         if (size <= hole_start)
5164                 return 0;
5165
5166         while (1) {
5167                 struct btrfs_ordered_extent *ordered;
5168
5169                 lock_extent_bits(io_tree, hole_start, block_end - 1,
5170                                  &cached_state);
5171                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5172                                                      block_end - hole_start);
5173                 if (!ordered)
5174                         break;
5175                 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5176                                      &cached_state);
5177                 btrfs_start_ordered_extent(inode, ordered, 1);
5178                 btrfs_put_ordered_extent(ordered);
5179         }
5180
5181         cur_offset = hole_start;
5182         while (1) {
5183                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5184                                 block_end - cur_offset, 0);
5185                 if (IS_ERR(em)) {
5186                         err = PTR_ERR(em);
5187                         em = NULL;
5188                         break;
5189                 }
5190                 last_byte = min(extent_map_end(em), block_end);
5191                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5192                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5193                         struct extent_map *hole_em;
5194                         hole_size = last_byte - cur_offset;
5195
5196                         err = maybe_insert_hole(root, inode, cur_offset,
5197                                                 hole_size);
5198                         if (err)
5199                                 break;
5200                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5201                                                 cur_offset + hole_size - 1, 0);
5202                         hole_em = alloc_extent_map();
5203                         if (!hole_em) {
5204                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5205                                         &BTRFS_I(inode)->runtime_flags);
5206                                 goto next;
5207                         }
5208                         hole_em->start = cur_offset;
5209                         hole_em->len = hole_size;
5210                         hole_em->orig_start = cur_offset;
5211
5212                         hole_em->block_start = EXTENT_MAP_HOLE;
5213                         hole_em->block_len = 0;
5214                         hole_em->orig_block_len = 0;
5215                         hole_em->ram_bytes = hole_size;
5216                         hole_em->bdev = fs_info->fs_devices->latest_bdev;
5217                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
5218                         hole_em->generation = fs_info->generation;
5219
5220                         while (1) {
5221                                 write_lock(&em_tree->lock);
5222                                 err = add_extent_mapping(em_tree, hole_em, 1);
5223                                 write_unlock(&em_tree->lock);
5224                                 if (err != -EEXIST)
5225                                         break;
5226                                 btrfs_drop_extent_cache(BTRFS_I(inode),
5227                                                         cur_offset,
5228                                                         cur_offset +
5229                                                         hole_size - 1, 0);
5230                         }
5231                         free_extent_map(hole_em);
5232                 }
5233 next:
5234                 free_extent_map(em);
5235                 em = NULL;
5236                 cur_offset = last_byte;
5237                 if (cur_offset >= block_end)
5238                         break;
5239         }
5240         free_extent_map(em);
5241         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5242         return err;
5243 }
5244
5245 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5246 {
5247         struct btrfs_root *root = BTRFS_I(inode)->root;
5248         struct btrfs_trans_handle *trans;
5249         loff_t oldsize = i_size_read(inode);
5250         loff_t newsize = attr->ia_size;
5251         int mask = attr->ia_valid;
5252         int ret;
5253
5254         /*
5255          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5256          * special case where we need to update the times despite not having
5257          * these flags set.  For all other operations the VFS set these flags
5258          * explicitly if it wants a timestamp update.
5259          */
5260         if (newsize != oldsize) {
5261                 inode_inc_iversion(inode);
5262                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5263                         inode->i_ctime = inode->i_mtime =
5264                                 current_time(inode);
5265         }
5266
5267         if (newsize > oldsize) {
5268                 /*
5269                  * Don't do an expanding truncate while snapshotting is ongoing.
5270                  * This is to ensure the snapshot captures a fully consistent
5271                  * state of this file - if the snapshot captures this expanding
5272                  * truncation, it must capture all writes that happened before
5273                  * this truncation.
5274                  */
5275                 btrfs_wait_for_snapshot_creation(root);
5276                 ret = btrfs_cont_expand(inode, oldsize, newsize);
5277                 if (ret) {
5278                         btrfs_end_write_no_snapshotting(root);
5279                         return ret;
5280                 }
5281
5282                 trans = btrfs_start_transaction(root, 1);
5283                 if (IS_ERR(trans)) {
5284                         btrfs_end_write_no_snapshotting(root);
5285                         return PTR_ERR(trans);
5286                 }
5287
5288                 i_size_write(inode, newsize);
5289                 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5290                 pagecache_isize_extended(inode, oldsize, newsize);
5291                 ret = btrfs_update_inode(trans, root, inode);
5292                 btrfs_end_write_no_snapshotting(root);
5293                 btrfs_end_transaction(trans);
5294         } else {
5295
5296                 /*
5297                  * We're truncating a file that used to have good data down to
5298                  * zero. Make sure it gets into the ordered flush list so that
5299                  * any new writes get down to disk quickly.
5300                  */
5301                 if (newsize == 0)
5302                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5303                                 &BTRFS_I(inode)->runtime_flags);
5304
5305                 truncate_setsize(inode, newsize);
5306
5307                 /* Disable nonlocked read DIO to avoid the end less truncate */
5308                 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5309                 inode_dio_wait(inode);
5310                 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5311
5312                 ret = btrfs_truncate(inode, newsize == oldsize);
5313                 if (ret && inode->i_nlink) {
5314                         int err;
5315
5316                         /*
5317                          * Truncate failed, so fix up the in-memory size. We
5318                          * adjusted disk_i_size down as we removed extents, so
5319                          * wait for disk_i_size to be stable and then update the
5320                          * in-memory size to match.
5321                          */
5322                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5323                         if (err)
5324                                 return err;
5325                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5326                 }
5327         }
5328
5329         return ret;
5330 }
5331
5332 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5333 {
5334         struct inode *inode = d_inode(dentry);
5335         struct btrfs_root *root = BTRFS_I(inode)->root;
5336         int err;
5337
5338         if (btrfs_root_readonly(root))
5339                 return -EROFS;
5340
5341         err = setattr_prepare(dentry, attr);
5342         if (err)
5343                 return err;
5344
5345         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5346                 err = btrfs_setsize(inode, attr);
5347                 if (err)
5348                         return err;
5349         }
5350
5351         if (attr->ia_valid) {
5352                 setattr_copy(inode, attr);
5353                 inode_inc_iversion(inode);
5354                 err = btrfs_dirty_inode(inode);
5355
5356                 if (!err && attr->ia_valid & ATTR_MODE)
5357                         err = posix_acl_chmod(inode, inode->i_mode);
5358         }
5359
5360         return err;
5361 }
5362
5363 /*
5364  * While truncating the inode pages during eviction, we get the VFS calling
5365  * btrfs_invalidatepage() against each page of the inode. This is slow because
5366  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5367  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5368  * extent_state structures over and over, wasting lots of time.
5369  *
5370  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5371  * those expensive operations on a per page basis and do only the ordered io
5372  * finishing, while we release here the extent_map and extent_state structures,
5373  * without the excessive merging and splitting.
5374  */
5375 static void evict_inode_truncate_pages(struct inode *inode)
5376 {
5377         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5378         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5379         struct rb_node *node;
5380
5381         ASSERT(inode->i_state & I_FREEING);
5382         truncate_inode_pages_final(&inode->i_data);
5383
5384         write_lock(&map_tree->lock);
5385         while (!RB_EMPTY_ROOT(&map_tree->map)) {
5386                 struct extent_map *em;
5387
5388                 node = rb_first(&map_tree->map);
5389                 em = rb_entry(node, struct extent_map, rb_node);
5390                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5391                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5392                 remove_extent_mapping(map_tree, em);
5393                 free_extent_map(em);
5394                 if (need_resched()) {
5395                         write_unlock(&map_tree->lock);
5396                         cond_resched();
5397                         write_lock(&map_tree->lock);
5398                 }
5399         }
5400         write_unlock(&map_tree->lock);
5401
5402         /*
5403          * Keep looping until we have no more ranges in the io tree.
5404          * We can have ongoing bios started by readpages (called from readahead)
5405          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5406          * still in progress (unlocked the pages in the bio but did not yet
5407          * unlocked the ranges in the io tree). Therefore this means some
5408          * ranges can still be locked and eviction started because before
5409          * submitting those bios, which are executed by a separate task (work
5410          * queue kthread), inode references (inode->i_count) were not taken
5411          * (which would be dropped in the end io callback of each bio).
5412          * Therefore here we effectively end up waiting for those bios and
5413          * anyone else holding locked ranges without having bumped the inode's
5414          * reference count - if we don't do it, when they access the inode's
5415          * io_tree to unlock a range it may be too late, leading to an
5416          * use-after-free issue.
5417          */
5418         spin_lock(&io_tree->lock);
5419         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5420                 struct extent_state *state;
5421                 struct extent_state *cached_state = NULL;
5422                 u64 start;
5423                 u64 end;
5424
5425                 node = rb_first(&io_tree->state);
5426                 state = rb_entry(node, struct extent_state, rb_node);
5427                 start = state->start;
5428                 end = state->end;
5429                 spin_unlock(&io_tree->lock);
5430
5431                 lock_extent_bits(io_tree, start, end, &cached_state);
5432
5433                 /*
5434                  * If still has DELALLOC flag, the extent didn't reach disk,
5435                  * and its reserved space won't be freed by delayed_ref.
5436                  * So we need to free its reserved space here.
5437                  * (Refer to comment in btrfs_invalidatepage, case 2)
5438                  *
5439                  * Note, end is the bytenr of last byte, so we need + 1 here.
5440                  */
5441                 if (state->state & EXTENT_DELALLOC)
5442                         btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5443
5444                 clear_extent_bit(io_tree, start, end,
5445                                  EXTENT_LOCKED | EXTENT_DIRTY |
5446                                  EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5447                                  EXTENT_DEFRAG, 1, 1, &cached_state);
5448
5449                 cond_resched();
5450                 spin_lock(&io_tree->lock);
5451         }
5452         spin_unlock(&io_tree->lock);
5453 }
5454
5455 void btrfs_evict_inode(struct inode *inode)
5456 {
5457         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5458         struct btrfs_trans_handle *trans;
5459         struct btrfs_root *root = BTRFS_I(inode)->root;
5460         struct btrfs_block_rsv *rsv, *global_rsv;
5461         int steal_from_global = 0;
5462         u64 min_size;
5463         int ret;
5464
5465         trace_btrfs_inode_evict(inode);
5466
5467         if (!root) {
5468                 clear_inode(inode);
5469                 return;
5470         }
5471
5472         min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5473
5474         evict_inode_truncate_pages(inode);
5475
5476         if (inode->i_nlink &&
5477             ((btrfs_root_refs(&root->root_item) != 0 &&
5478               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5479              btrfs_is_free_space_inode(BTRFS_I(inode))))
5480                 goto no_delete;
5481
5482         if (is_bad_inode(inode)) {
5483                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5484                 goto no_delete;
5485         }
5486         /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5487         if (!special_file(inode->i_mode))
5488                 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5489
5490         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5491
5492         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5493                 goto no_delete;
5494
5495         if (inode->i_nlink > 0) {
5496                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5497                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5498                 goto no_delete;
5499         }
5500
5501         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5502         if (ret) {
5503                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5504                 goto no_delete;
5505         }
5506
5507         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5508         if (!rsv) {
5509                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5510                 goto no_delete;
5511         }
5512         rsv->size = min_size;
5513         rsv->failfast = 1;
5514         global_rsv = &fs_info->global_block_rsv;
5515
5516         btrfs_i_size_write(BTRFS_I(inode), 0);
5517
5518         /*
5519          * This is a bit simpler than btrfs_truncate since we've already
5520          * reserved our space for our orphan item in the unlink, so we just
5521          * need to reserve some slack space in case we add bytes and update
5522          * inode item when doing the truncate.
5523          */
5524         while (1) {
5525                 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5526                                              BTRFS_RESERVE_FLUSH_LIMIT);
5527
5528                 /*
5529                  * Try and steal from the global reserve since we will
5530                  * likely not use this space anyway, we want to try as
5531                  * hard as possible to get this to work.
5532                  */
5533                 if (ret)
5534                         steal_from_global++;
5535                 else
5536                         steal_from_global = 0;
5537                 ret = 0;
5538
5539                 /*
5540                  * steal_from_global == 0: we reserved stuff, hooray!
5541                  * steal_from_global == 1: we didn't reserve stuff, boo!
5542                  * steal_from_global == 2: we've committed, still not a lot of
5543                  * room but maybe we'll have room in the global reserve this
5544                  * time.
5545                  * steal_from_global == 3: abandon all hope!
5546                  */
5547                 if (steal_from_global > 2) {
5548                         btrfs_warn(fs_info,
5549                                    "Could not get space for a delete, will truncate on mount %d",
5550                                    ret);
5551                         btrfs_orphan_del(NULL, BTRFS_I(inode));
5552                         btrfs_free_block_rsv(fs_info, rsv);
5553                         goto no_delete;
5554                 }
5555
5556                 trans = btrfs_join_transaction(root);
5557                 if (IS_ERR(trans)) {
5558                         btrfs_orphan_del(NULL, BTRFS_I(inode));
5559                         btrfs_free_block_rsv(fs_info, rsv);
5560                         goto no_delete;
5561                 }
5562
5563                 /*
5564                  * We can't just steal from the global reserve, we need to make
5565                  * sure there is room to do it, if not we need to commit and try
5566                  * again.
5567                  */
5568                 if (steal_from_global) {
5569                         if (!btrfs_check_space_for_delayed_refs(trans, fs_info))
5570                                 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5571                                                               min_size, 0);
5572                         else
5573                                 ret = -ENOSPC;
5574                 }
5575
5576                 /*
5577                  * Couldn't steal from the global reserve, we have too much
5578                  * pending stuff built up, commit the transaction and try it
5579                  * again.
5580                  */
5581                 if (ret) {
5582                         ret = btrfs_commit_transaction(trans);
5583                         if (ret) {
5584                                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5585                                 btrfs_free_block_rsv(fs_info, rsv);
5586                                 goto no_delete;
5587                         }
5588                         continue;
5589                 } else {
5590                         steal_from_global = 0;
5591                 }
5592
5593                 trans->block_rsv = rsv;
5594
5595                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5596                 if (ret != -ENOSPC && ret != -EAGAIN)
5597                         break;
5598
5599                 trans->block_rsv = &fs_info->trans_block_rsv;
5600                 btrfs_end_transaction(trans);
5601                 trans = NULL;
5602                 btrfs_btree_balance_dirty(fs_info);
5603         }
5604
5605         btrfs_free_block_rsv(fs_info, rsv);
5606
5607         /*
5608          * Errors here aren't a big deal, it just means we leave orphan items
5609          * in the tree.  They will be cleaned up on the next mount.
5610          */
5611         if (ret == 0) {
5612                 trans->block_rsv = root->orphan_block_rsv;
5613                 btrfs_orphan_del(trans, BTRFS_I(inode));
5614         } else {
5615                 btrfs_orphan_del(NULL, BTRFS_I(inode));
5616         }
5617
5618         trans->block_rsv = &fs_info->trans_block_rsv;
5619         if (!(root == fs_info->tree_root ||
5620               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5621                 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5622
5623         btrfs_end_transaction(trans);
5624         btrfs_btree_balance_dirty(fs_info);
5625 no_delete:
5626         btrfs_remove_delayed_node(BTRFS_I(inode));
5627         clear_inode(inode);
5628 }
5629
5630 /*
5631  * this returns the key found in the dir entry in the location pointer.
5632  * If no dir entries were found, returns -ENOENT.
5633  * If found a corrupted location in dir entry, returns -EUCLEAN.
5634  */
5635 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5636                                struct btrfs_key *location)
5637 {
5638         const char *name = dentry->d_name.name;
5639         int namelen = dentry->d_name.len;
5640         struct btrfs_dir_item *di;
5641         struct btrfs_path *path;
5642         struct btrfs_root *root = BTRFS_I(dir)->root;
5643         int ret = 0;
5644
5645         path = btrfs_alloc_path();
5646         if (!path)
5647                 return -ENOMEM;
5648
5649         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5650                         name, namelen, 0);
5651         if (!di) {
5652                 ret = -ENOENT;
5653                 goto out;
5654         }
5655         if (IS_ERR(di)) {
5656                 ret = PTR_ERR(di);
5657                 goto out;
5658         }
5659
5660         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5661         if (location->type != BTRFS_INODE_ITEM_KEY &&
5662             location->type != BTRFS_ROOT_ITEM_KEY) {
5663                 ret = -EUCLEAN;
5664                 btrfs_warn(root->fs_info,
5665 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5666                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5667                            location->objectid, location->type, location->offset);
5668         }
5669 out:
5670         btrfs_free_path(path);
5671         return ret;
5672 }
5673
5674 /*
5675  * when we hit a tree root in a directory, the btrfs part of the inode
5676  * needs to be changed to reflect the root directory of the tree root.  This
5677  * is kind of like crossing a mount point.
5678  */
5679 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5680                                     struct inode *dir,
5681                                     struct dentry *dentry,
5682                                     struct btrfs_key *location,
5683                                     struct btrfs_root **sub_root)
5684 {
5685         struct btrfs_path *path;
5686         struct btrfs_root *new_root;
5687         struct btrfs_root_ref *ref;
5688         struct extent_buffer *leaf;
5689         struct btrfs_key key;
5690         int ret;
5691         int err = 0;
5692
5693         path = btrfs_alloc_path();
5694         if (!path) {
5695                 err = -ENOMEM;
5696                 goto out;
5697         }
5698
5699         err = -ENOENT;
5700         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5701         key.type = BTRFS_ROOT_REF_KEY;
5702         key.offset = location->objectid;
5703
5704         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5705         if (ret) {
5706                 if (ret < 0)
5707                         err = ret;
5708                 goto out;
5709         }
5710
5711         leaf = path->nodes[0];
5712         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5713         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5714             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5715                 goto out;
5716
5717         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5718                                    (unsigned long)(ref + 1),
5719                                    dentry->d_name.len);
5720         if (ret)
5721                 goto out;
5722
5723         btrfs_release_path(path);
5724
5725         new_root = btrfs_read_fs_root_no_name(fs_info, location);
5726         if (IS_ERR(new_root)) {
5727                 err = PTR_ERR(new_root);
5728                 goto out;
5729         }
5730
5731         *sub_root = new_root;
5732         location->objectid = btrfs_root_dirid(&new_root->root_item);
5733         location->type = BTRFS_INODE_ITEM_KEY;
5734         location->offset = 0;
5735         err = 0;
5736 out:
5737         btrfs_free_path(path);
5738         return err;
5739 }
5740
5741 static void inode_tree_add(struct inode *inode)
5742 {
5743         struct btrfs_root *root = BTRFS_I(inode)->root;
5744         struct btrfs_inode *entry;
5745         struct rb_node **p;
5746         struct rb_node *parent;
5747         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5748         u64 ino = btrfs_ino(BTRFS_I(inode));
5749
5750         if (inode_unhashed(inode))
5751                 return;
5752         parent = NULL;
5753         spin_lock(&root->inode_lock);
5754         p = &root->inode_tree.rb_node;
5755         while (*p) {
5756                 parent = *p;
5757                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5758
5759                 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5760                         p = &parent->rb_left;
5761                 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5762                         p = &parent->rb_right;
5763                 else {
5764                         WARN_ON(!(entry->vfs_inode.i_state &
5765                                   (I_WILL_FREE | I_FREEING)));
5766                         rb_replace_node(parent, new, &root->inode_tree);
5767                         RB_CLEAR_NODE(parent);
5768                         spin_unlock(&root->inode_lock);
5769                         return;
5770                 }
5771         }
5772         rb_link_node(new, parent, p);
5773         rb_insert_color(new, &root->inode_tree);
5774         spin_unlock(&root->inode_lock);
5775 }
5776
5777 static void inode_tree_del(struct inode *inode)
5778 {
5779         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5780         struct btrfs_root *root = BTRFS_I(inode)->root;
5781         int empty = 0;
5782
5783         spin_lock(&root->inode_lock);
5784         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5785                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5786                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5787                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5788         }
5789         spin_unlock(&root->inode_lock);
5790
5791         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5792                 synchronize_srcu(&fs_info->subvol_srcu);
5793                 spin_lock(&root->inode_lock);
5794                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5795                 spin_unlock(&root->inode_lock);
5796                 if (empty)
5797                         btrfs_add_dead_root(root);
5798         }
5799 }
5800
5801
5802 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5803 {
5804         struct btrfs_iget_args *args = p;
5805         inode->i_ino = args->location->objectid;
5806         memcpy(&BTRFS_I(inode)->location, args->location,
5807                sizeof(*args->location));
5808         BTRFS_I(inode)->root = args->root;
5809         return 0;
5810 }
5811
5812 static int btrfs_find_actor(struct inode *inode, void *opaque)
5813 {
5814         struct btrfs_iget_args *args = opaque;
5815         return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5816                 args->root == BTRFS_I(inode)->root;
5817 }
5818
5819 static struct inode *btrfs_iget_locked(struct super_block *s,
5820                                        struct btrfs_key *location,
5821                                        struct btrfs_root *root)
5822 {
5823         struct inode *inode;
5824         struct btrfs_iget_args args;
5825         unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5826
5827         args.location = location;
5828         args.root = root;
5829
5830         inode = iget5_locked(s, hashval, btrfs_find_actor,
5831                              btrfs_init_locked_inode,
5832                              (void *)&args);
5833         return inode;
5834 }
5835
5836 /* Get an inode object given its location and corresponding root.
5837  * Returns in *is_new if the inode was read from disk
5838  */
5839 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5840                          struct btrfs_root *root, int *new)
5841 {
5842         struct inode *inode;
5843
5844         inode = btrfs_iget_locked(s, location, root);
5845         if (!inode)
5846                 return ERR_PTR(-ENOMEM);
5847
5848         if (inode->i_state & I_NEW) {
5849                 int ret;
5850
5851                 ret = btrfs_read_locked_inode(inode);
5852                 if (!is_bad_inode(inode)) {
5853                         inode_tree_add(inode);
5854                         unlock_new_inode(inode);
5855                         if (new)
5856                                 *new = 1;
5857                 } else {
5858                         unlock_new_inode(inode);
5859                         iput(inode);
5860                         ASSERT(ret < 0);
5861                         inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5862                 }
5863         }
5864
5865         return inode;
5866 }
5867
5868 static struct inode *new_simple_dir(struct super_block *s,
5869                                     struct btrfs_key *key,
5870                                     struct btrfs_root *root)
5871 {
5872         struct inode *inode = new_inode(s);
5873
5874         if (!inode)
5875                 return ERR_PTR(-ENOMEM);
5876
5877         BTRFS_I(inode)->root = root;
5878         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5879         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5880
5881         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5882         inode->i_op = &btrfs_dir_ro_inode_operations;
5883         inode->i_opflags &= ~IOP_XATTR;
5884         inode->i_fop = &simple_dir_operations;
5885         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5886         inode->i_mtime = current_time(inode);
5887         inode->i_atime = inode->i_mtime;
5888         inode->i_ctime = inode->i_mtime;
5889         BTRFS_I(inode)->i_otime = inode->i_mtime;
5890
5891         return inode;
5892 }
5893
5894 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5895 {
5896         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5897         struct inode *inode;
5898         struct btrfs_root *root = BTRFS_I(dir)->root;
5899         struct btrfs_root *sub_root = root;
5900         struct btrfs_key location;
5901         int index;
5902         int ret = 0;
5903
5904         if (dentry->d_name.len > BTRFS_NAME_LEN)
5905                 return ERR_PTR(-ENAMETOOLONG);
5906
5907         ret = btrfs_inode_by_name(dir, dentry, &location);
5908         if (ret < 0)
5909                 return ERR_PTR(ret);
5910
5911         if (location.type == BTRFS_INODE_ITEM_KEY) {
5912                 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5913                 return inode;
5914         }
5915
5916         index = srcu_read_lock(&fs_info->subvol_srcu);
5917         ret = fixup_tree_root_location(fs_info, dir, dentry,
5918                                        &location, &sub_root);
5919         if (ret < 0) {
5920                 if (ret != -ENOENT)
5921                         inode = ERR_PTR(ret);
5922                 else
5923                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5924         } else {
5925                 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5926         }
5927         srcu_read_unlock(&fs_info->subvol_srcu, index);
5928
5929         if (!IS_ERR(inode) && root != sub_root) {
5930                 down_read(&fs_info->cleanup_work_sem);
5931                 if (!sb_rdonly(inode->i_sb))
5932                         ret = btrfs_orphan_cleanup(sub_root);
5933                 up_read(&fs_info->cleanup_work_sem);
5934                 if (ret) {
5935                         iput(inode);
5936                         inode = ERR_PTR(ret);
5937                 }
5938         }
5939
5940         return inode;
5941 }
5942
5943 static int btrfs_dentry_delete(const struct dentry *dentry)
5944 {
5945         struct btrfs_root *root;
5946         struct inode *inode = d_inode(dentry);
5947
5948         if (!inode && !IS_ROOT(dentry))
5949                 inode = d_inode(dentry->d_parent);
5950
5951         if (inode) {
5952                 root = BTRFS_I(inode)->root;
5953                 if (btrfs_root_refs(&root->root_item) == 0)
5954                         return 1;
5955
5956                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5957                         return 1;
5958         }
5959         return 0;
5960 }
5961
5962 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5963                                    unsigned int flags)
5964 {
5965         struct inode *inode;
5966
5967         inode = btrfs_lookup_dentry(dir, dentry);
5968         if (IS_ERR(inode)) {
5969                 if (PTR_ERR(inode) == -ENOENT)
5970                         inode = NULL;
5971                 else
5972                         return ERR_CAST(inode);
5973         }
5974
5975         return d_splice_alias(inode, dentry);
5976 }
5977
5978 unsigned char btrfs_filetype_table[] = {
5979         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5980 };
5981
5982 /*
5983  * All this infrastructure exists because dir_emit can fault, and we are holding
5984  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5985  * our information into that, and then dir_emit from the buffer.  This is
5986  * similar to what NFS does, only we don't keep the buffer around in pagecache
5987  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5988  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5989  * tree lock.
5990  */
5991 static int btrfs_opendir(struct inode *inode, struct file *file)
5992 {
5993         struct btrfs_file_private *private;
5994
5995         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5996         if (!private)
5997                 return -ENOMEM;
5998         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5999         if (!private->filldir_buf) {
6000                 kfree(private);
6001                 return -ENOMEM;
6002         }
6003         file->private_data = private;
6004         return 0;
6005 }
6006
6007 struct dir_entry {
6008         u64 ino;
6009         u64 offset;
6010         unsigned type;
6011         int name_len;
6012 };
6013
6014 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6015 {
6016         while (entries--) {
6017                 struct dir_entry *entry = addr;
6018                 char *name = (char *)(entry + 1);
6019
6020                 ctx->pos = get_unaligned(&entry->offset);
6021                 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6022                                          get_unaligned(&entry->ino),
6023                                          get_unaligned(&entry->type)))
6024                         return 1;
6025                 addr += sizeof(struct dir_entry) +
6026                         get_unaligned(&entry->name_len);
6027                 ctx->pos++;
6028         }
6029         return 0;
6030 }
6031
6032 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6033 {
6034         struct inode *inode = file_inode(file);
6035         struct btrfs_root *root = BTRFS_I(inode)->root;
6036         struct btrfs_file_private *private = file->private_data;
6037         struct btrfs_dir_item *di;
6038         struct btrfs_key key;
6039         struct btrfs_key found_key;
6040         struct btrfs_path *path;
6041         void *addr;
6042         struct list_head ins_list;
6043         struct list_head del_list;
6044         int ret;
6045         struct extent_buffer *leaf;
6046         int slot;
6047         char *name_ptr;
6048         int name_len;
6049         int entries = 0;
6050         int total_len = 0;
6051         bool put = false;
6052         struct btrfs_key location;
6053
6054         if (!dir_emit_dots(file, ctx))
6055                 return 0;
6056
6057         path = btrfs_alloc_path();
6058         if (!path)
6059                 return -ENOMEM;
6060
6061         addr = private->filldir_buf;
6062         path->reada = READA_FORWARD;
6063
6064         INIT_LIST_HEAD(&ins_list);
6065         INIT_LIST_HEAD(&del_list);
6066         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
6067
6068 again:
6069         key.type = BTRFS_DIR_INDEX_KEY;
6070         key.offset = ctx->pos;
6071         key.objectid = btrfs_ino(BTRFS_I(inode));
6072
6073         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6074         if (ret < 0)
6075                 goto err;
6076
6077         while (1) {
6078                 struct dir_entry *entry;
6079
6080                 leaf = path->nodes[0];
6081                 slot = path->slots[0];
6082                 if (slot >= btrfs_header_nritems(leaf)) {
6083                         ret = btrfs_next_leaf(root, path);
6084                         if (ret < 0)
6085                                 goto err;
6086                         else if (ret > 0)
6087                                 break;
6088                         continue;
6089                 }
6090
6091                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6092
6093                 if (found_key.objectid != key.objectid)
6094                         break;
6095                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6096                         break;
6097                 if (found_key.offset < ctx->pos)
6098                         goto next;
6099                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6100                         goto next;
6101                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
6102                 name_len = btrfs_dir_name_len(leaf, di);
6103                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6104                     PAGE_SIZE) {
6105                         btrfs_release_path(path);
6106                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6107                         if (ret)
6108                                 goto nopos;
6109                         addr = private->filldir_buf;
6110                         entries = 0;
6111                         total_len = 0;
6112                         goto again;
6113                 }
6114
6115                 entry = addr;
6116                 put_unaligned(name_len, &entry->name_len);
6117                 name_ptr = (char *)(entry + 1);
6118                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6119                                    name_len);
6120                 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
6121                                 &entry->type);
6122                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6123                 put_unaligned(location.objectid, &entry->ino);
6124                 put_unaligned(found_key.offset, &entry->offset);
6125                 entries++;
6126                 addr += sizeof(struct dir_entry) + name_len;
6127                 total_len += sizeof(struct dir_entry) + name_len;
6128 next:
6129                 path->slots[0]++;
6130         }
6131         btrfs_release_path(path);
6132
6133         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6134         if (ret)
6135                 goto nopos;
6136
6137         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6138         if (ret)
6139                 goto nopos;
6140
6141         /*
6142          * Stop new entries from being returned after we return the last
6143          * entry.
6144          *
6145          * New directory entries are assigned a strictly increasing
6146          * offset.  This means that new entries created during readdir
6147          * are *guaranteed* to be seen in the future by that readdir.
6148          * This has broken buggy programs which operate on names as
6149          * they're returned by readdir.  Until we re-use freed offsets
6150          * we have this hack to stop new entries from being returned
6151          * under the assumption that they'll never reach this huge
6152          * offset.
6153          *
6154          * This is being careful not to overflow 32bit loff_t unless the
6155          * last entry requires it because doing so has broken 32bit apps
6156          * in the past.
6157          */
6158         if (ctx->pos >= INT_MAX)
6159                 ctx->pos = LLONG_MAX;
6160         else
6161                 ctx->pos = INT_MAX;
6162 nopos:
6163         ret = 0;
6164 err:
6165         if (put)
6166                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6167         btrfs_free_path(path);
6168         return ret;
6169 }
6170
6171 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
6172 {
6173         struct btrfs_root *root = BTRFS_I(inode)->root;
6174         struct btrfs_trans_handle *trans;
6175         int ret = 0;
6176         bool nolock = false;
6177
6178         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6179                 return 0;
6180
6181         if (btrfs_fs_closing(root->fs_info) &&
6182                         btrfs_is_free_space_inode(BTRFS_I(inode)))
6183                 nolock = true;
6184
6185         if (wbc->sync_mode == WB_SYNC_ALL) {
6186                 if (nolock)
6187                         trans = btrfs_join_transaction_nolock(root);
6188                 else
6189                         trans = btrfs_join_transaction(root);
6190                 if (IS_ERR(trans))
6191                         return PTR_ERR(trans);
6192                 ret = btrfs_commit_transaction(trans);
6193         }
6194         return ret;
6195 }
6196
6197 /*
6198  * This is somewhat expensive, updating the tree every time the
6199  * inode changes.  But, it is most likely to find the inode in cache.
6200  * FIXME, needs more benchmarking...there are no reasons other than performance
6201  * to keep or drop this code.
6202  */
6203 static int btrfs_dirty_inode(struct inode *inode)
6204 {
6205         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6206         struct btrfs_root *root = BTRFS_I(inode)->root;
6207         struct btrfs_trans_handle *trans;
6208         int ret;
6209
6210         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6211                 return 0;
6212
6213         trans = btrfs_join_transaction(root);
6214         if (IS_ERR(trans))
6215                 return PTR_ERR(trans);
6216
6217         ret = btrfs_update_inode(trans, root, inode);
6218         if (ret && ret == -ENOSPC) {
6219                 /* whoops, lets try again with the full transaction */
6220                 btrfs_end_transaction(trans);
6221                 trans = btrfs_start_transaction(root, 1);
6222                 if (IS_ERR(trans))
6223                         return PTR_ERR(trans);
6224
6225                 ret = btrfs_update_inode(trans, root, inode);
6226         }
6227         btrfs_end_transaction(trans);
6228         if (BTRFS_I(inode)->delayed_node)
6229                 btrfs_balance_delayed_items(fs_info);
6230
6231         return ret;
6232 }
6233
6234 /*
6235  * This is a copy of file_update_time.  We need this so we can return error on
6236  * ENOSPC for updating the inode in the case of file write and mmap writes.
6237  */
6238 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6239                              int flags)
6240 {
6241         struct btrfs_root *root = BTRFS_I(inode)->root;
6242         bool dirty = flags & ~S_VERSION;
6243
6244         if (btrfs_root_readonly(root))
6245                 return -EROFS;
6246
6247         if (flags & S_VERSION)
6248                 dirty |= inode_maybe_inc_iversion(inode, dirty);
6249         if (flags & S_CTIME)
6250                 inode->i_ctime = *now;
6251         if (flags & S_MTIME)
6252                 inode->i_mtime = *now;
6253         if (flags & S_ATIME)
6254                 inode->i_atime = *now;
6255         return dirty ? btrfs_dirty_inode(inode) : 0;
6256 }
6257
6258 /*
6259  * find the highest existing sequence number in a directory
6260  * and then set the in-memory index_cnt variable to reflect
6261  * free sequence numbers
6262  */
6263 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6264 {
6265         struct btrfs_root *root = inode->root;
6266         struct btrfs_key key, found_key;
6267         struct btrfs_path *path;
6268         struct extent_buffer *leaf;
6269         int ret;
6270
6271         key.objectid = btrfs_ino(inode);
6272         key.type = BTRFS_DIR_INDEX_KEY;
6273         key.offset = (u64)-1;
6274
6275         path = btrfs_alloc_path();
6276         if (!path)
6277                 return -ENOMEM;
6278
6279         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6280         if (ret < 0)
6281                 goto out;
6282         /* FIXME: we should be able to handle this */
6283         if (ret == 0)
6284                 goto out;
6285         ret = 0;
6286
6287         /*
6288          * MAGIC NUMBER EXPLANATION:
6289          * since we search a directory based on f_pos we have to start at 2
6290          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6291          * else has to start at 2
6292          */
6293         if (path->slots[0] == 0) {
6294                 inode->index_cnt = 2;
6295                 goto out;
6296         }
6297
6298         path->slots[0]--;
6299
6300         leaf = path->nodes[0];
6301         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6302
6303         if (found_key.objectid != btrfs_ino(inode) ||
6304             found_key.type != BTRFS_DIR_INDEX_KEY) {
6305                 inode->index_cnt = 2;
6306                 goto out;
6307         }
6308
6309         inode->index_cnt = found_key.offset + 1;
6310 out:
6311         btrfs_free_path(path);
6312         return ret;
6313 }
6314
6315 /*
6316  * helper to find a free sequence number in a given directory.  This current
6317  * code is very simple, later versions will do smarter things in the btree
6318  */
6319 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6320 {
6321         int ret = 0;
6322
6323         if (dir->index_cnt == (u64)-1) {
6324                 ret = btrfs_inode_delayed_dir_index_count(dir);
6325                 if (ret) {
6326                         ret = btrfs_set_inode_index_count(dir);
6327                         if (ret)
6328                                 return ret;
6329                 }
6330         }
6331
6332         *index = dir->index_cnt;
6333         dir->index_cnt++;
6334
6335         return ret;
6336 }
6337
6338 static int btrfs_insert_inode_locked(struct inode *inode)
6339 {
6340         struct btrfs_iget_args args;
6341         args.location = &BTRFS_I(inode)->location;
6342         args.root = BTRFS_I(inode)->root;
6343
6344         return insert_inode_locked4(inode,
6345                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6346                    btrfs_find_actor, &args);
6347 }
6348
6349 /*
6350  * Inherit flags from the parent inode.
6351  *
6352  * Currently only the compression flags and the cow flags are inherited.
6353  */
6354 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6355 {
6356         unsigned int flags;
6357
6358         if (!dir)
6359                 return;
6360
6361         flags = BTRFS_I(dir)->flags;
6362
6363         if (flags & BTRFS_INODE_NOCOMPRESS) {
6364                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6365                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6366         } else if (flags & BTRFS_INODE_COMPRESS) {
6367                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6368                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6369         }
6370
6371         if (flags & BTRFS_INODE_NODATACOW) {
6372                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6373                 if (S_ISREG(inode->i_mode))
6374                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6375         }
6376
6377         btrfs_sync_inode_flags_to_i_flags(inode);
6378 }
6379
6380 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6381                                      struct btrfs_root *root,
6382                                      struct inode *dir,
6383                                      const char *name, int name_len,
6384                                      u64 ref_objectid, u64 objectid,
6385                                      umode_t mode, u64 *index)
6386 {
6387         struct btrfs_fs_info *fs_info = root->fs_info;
6388         struct inode *inode;
6389         struct btrfs_inode_item *inode_item;
6390         struct btrfs_key *location;
6391         struct btrfs_path *path;
6392         struct btrfs_inode_ref *ref;
6393         struct btrfs_key key[2];
6394         u32 sizes[2];
6395         int nitems = name ? 2 : 1;
6396         unsigned long ptr;
6397         int ret;
6398
6399         path = btrfs_alloc_path();
6400         if (!path)
6401                 return ERR_PTR(-ENOMEM);
6402
6403         inode = new_inode(fs_info->sb);
6404         if (!inode) {
6405                 btrfs_free_path(path);
6406                 return ERR_PTR(-ENOMEM);
6407         }
6408
6409         /*
6410          * O_TMPFILE, set link count to 0, so that after this point,
6411          * we fill in an inode item with the correct link count.
6412          */
6413         if (!name)
6414                 set_nlink(inode, 0);
6415
6416         /*
6417          * we have to initialize this early, so we can reclaim the inode
6418          * number if we fail afterwards in this function.
6419          */
6420         inode->i_ino = objectid;
6421
6422         if (dir && name) {
6423                 trace_btrfs_inode_request(dir);
6424
6425                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6426                 if (ret) {
6427                         btrfs_free_path(path);
6428                         iput(inode);
6429                         return ERR_PTR(ret);
6430                 }
6431         } else if (dir) {
6432                 *index = 0;
6433         }
6434         /*
6435          * index_cnt is ignored for everything but a dir,
6436          * btrfs_set_inode_index_count has an explanation for the magic
6437          * number
6438          */
6439         BTRFS_I(inode)->index_cnt = 2;
6440         BTRFS_I(inode)->dir_index = *index;
6441         BTRFS_I(inode)->root = root;
6442         BTRFS_I(inode)->generation = trans->transid;
6443         inode->i_generation = BTRFS_I(inode)->generation;
6444
6445         /*
6446          * We could have gotten an inode number from somebody who was fsynced
6447          * and then removed in this same transaction, so let's just set full
6448          * sync since it will be a full sync anyway and this will blow away the
6449          * old info in the log.
6450          */
6451         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6452
6453         key[0].objectid = objectid;
6454         key[0].type = BTRFS_INODE_ITEM_KEY;
6455         key[0].offset = 0;
6456
6457         sizes[0] = sizeof(struct btrfs_inode_item);
6458
6459         if (name) {
6460                 /*
6461                  * Start new inodes with an inode_ref. This is slightly more
6462                  * efficient for small numbers of hard links since they will
6463                  * be packed into one item. Extended refs will kick in if we
6464                  * add more hard links than can fit in the ref item.
6465                  */
6466                 key[1].objectid = objectid;
6467                 key[1].type = BTRFS_INODE_REF_KEY;
6468                 key[1].offset = ref_objectid;
6469
6470                 sizes[1] = name_len + sizeof(*ref);
6471         }
6472
6473         location = &BTRFS_I(inode)->location;
6474         location->objectid = objectid;
6475         location->offset = 0;
6476         location->type = BTRFS_INODE_ITEM_KEY;
6477
6478         ret = btrfs_insert_inode_locked(inode);
6479         if (ret < 0)
6480                 goto fail;
6481
6482         path->leave_spinning = 1;
6483         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6484         if (ret != 0)
6485                 goto fail_unlock;
6486
6487         inode_init_owner(inode, dir, mode);
6488         inode_set_bytes(inode, 0);
6489
6490         inode->i_mtime = current_time(inode);
6491         inode->i_atime = inode->i_mtime;
6492         inode->i_ctime = inode->i_mtime;
6493         BTRFS_I(inode)->i_otime = inode->i_mtime;
6494
6495         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6496                                   struct btrfs_inode_item);
6497         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6498                              sizeof(*inode_item));
6499         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6500
6501         if (name) {
6502                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6503                                      struct btrfs_inode_ref);
6504                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6505                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6506                 ptr = (unsigned long)(ref + 1);
6507                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6508         }
6509
6510         btrfs_mark_buffer_dirty(path->nodes[0]);
6511         btrfs_free_path(path);
6512
6513         btrfs_inherit_iflags(inode, dir);
6514
6515         if (S_ISREG(mode)) {
6516                 if (btrfs_test_opt(fs_info, NODATASUM))
6517                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6518                 if (btrfs_test_opt(fs_info, NODATACOW))
6519                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6520                                 BTRFS_INODE_NODATASUM;
6521         }
6522
6523         inode_tree_add(inode);
6524
6525         trace_btrfs_inode_new(inode);
6526         btrfs_set_inode_last_trans(trans, inode);
6527
6528         btrfs_update_root_times(trans, root);
6529
6530         ret = btrfs_inode_inherit_props(trans, inode, dir);
6531         if (ret)
6532                 btrfs_err(fs_info,
6533                           "error inheriting props for ino %llu (root %llu): %d",
6534                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6535
6536         return inode;
6537
6538 fail_unlock:
6539         unlock_new_inode(inode);
6540 fail:
6541         if (dir && name)
6542                 BTRFS_I(dir)->index_cnt--;
6543         btrfs_free_path(path);
6544         iput(inode);
6545         return ERR_PTR(ret);
6546 }
6547
6548 static inline u8 btrfs_inode_type(struct inode *inode)
6549 {
6550         return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6551 }
6552
6553 /*
6554  * utility function to add 'inode' into 'parent_inode' with
6555  * a give name and a given sequence number.
6556  * if 'add_backref' is true, also insert a backref from the
6557  * inode to the parent directory.
6558  */
6559 int btrfs_add_link(struct btrfs_trans_handle *trans,
6560                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6561                    const char *name, int name_len, int add_backref, u64 index)
6562 {
6563         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6564         int ret = 0;
6565         struct btrfs_key key;
6566         struct btrfs_root *root = parent_inode->root;
6567         u64 ino = btrfs_ino(inode);
6568         u64 parent_ino = btrfs_ino(parent_inode);
6569
6570         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6571                 memcpy(&key, &inode->root->root_key, sizeof(key));
6572         } else {
6573                 key.objectid = ino;
6574                 key.type = BTRFS_INODE_ITEM_KEY;
6575                 key.offset = 0;
6576         }
6577
6578         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6579                 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6580                                          root->root_key.objectid, parent_ino,
6581                                          index, name, name_len);
6582         } else if (add_backref) {
6583                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6584                                              parent_ino, index);
6585         }
6586
6587         /* Nothing to clean up yet */
6588         if (ret)
6589                 return ret;
6590
6591         ret = btrfs_insert_dir_item(trans, root, name, name_len,
6592                                     parent_inode, &key,
6593                                     btrfs_inode_type(&inode->vfs_inode), index);
6594         if (ret == -EEXIST || ret == -EOVERFLOW)
6595                 goto fail_dir_item;
6596         else if (ret) {
6597                 btrfs_abort_transaction(trans, ret);
6598                 return ret;
6599         }
6600
6601         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6602                            name_len * 2);
6603         inode_inc_iversion(&parent_inode->vfs_inode);
6604         parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6605                 current_time(&parent_inode->vfs_inode);
6606         ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6607         if (ret)
6608                 btrfs_abort_transaction(trans, ret);
6609         return ret;
6610
6611 fail_dir_item:
6612         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6613                 u64 local_index;
6614                 int err;
6615                 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6616                                          root->root_key.objectid, parent_ino,
6617                                          &local_index, name, name_len);
6618
6619         } else if (add_backref) {
6620                 u64 local_index;
6621                 int err;
6622
6623                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6624                                           ino, parent_ino, &local_index);
6625         }
6626         return ret;
6627 }
6628
6629 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6630                             struct btrfs_inode *dir, struct dentry *dentry,
6631                             struct btrfs_inode *inode, int backref, u64 index)
6632 {
6633         int err = btrfs_add_link(trans, dir, inode,
6634                                  dentry->d_name.name, dentry->d_name.len,
6635                                  backref, index);
6636         if (err > 0)
6637                 err = -EEXIST;
6638         return err;
6639 }
6640
6641 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6642                         umode_t mode, dev_t rdev)
6643 {
6644         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6645         struct btrfs_trans_handle *trans;
6646         struct btrfs_root *root = BTRFS_I(dir)->root;
6647         struct inode *inode = NULL;
6648         int err;
6649         int drop_inode = 0;
6650         u64 objectid;
6651         u64 index = 0;
6652
6653         /*
6654          * 2 for inode item and ref
6655          * 2 for dir items
6656          * 1 for xattr if selinux is on
6657          */
6658         trans = btrfs_start_transaction(root, 5);
6659         if (IS_ERR(trans))
6660                 return PTR_ERR(trans);
6661
6662         err = btrfs_find_free_ino(root, &objectid);
6663         if (err)
6664                 goto out_unlock;
6665
6666         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6667                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6668                         mode, &index);
6669         if (IS_ERR(inode)) {
6670                 err = PTR_ERR(inode);
6671                 goto out_unlock;
6672         }
6673
6674         /*
6675         * If the active LSM wants to access the inode during
6676         * d_instantiate it needs these. Smack checks to see
6677         * if the filesystem supports xattrs by looking at the
6678         * ops vector.
6679         */
6680         inode->i_op = &btrfs_special_inode_operations;
6681         init_special_inode(inode, inode->i_mode, rdev);
6682
6683         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6684         if (err)
6685                 goto out_unlock_inode;
6686
6687         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6688                         0, index);
6689         if (err) {
6690                 goto out_unlock_inode;
6691         } else {
6692                 btrfs_update_inode(trans, root, inode);
6693                 d_instantiate_new(dentry, inode);
6694         }
6695
6696 out_unlock:
6697         btrfs_end_transaction(trans);
6698         btrfs_btree_balance_dirty(fs_info);
6699         if (drop_inode) {
6700                 inode_dec_link_count(inode);
6701                 iput(inode);
6702         }
6703         return err;
6704
6705 out_unlock_inode:
6706         drop_inode = 1;
6707         unlock_new_inode(inode);
6708         goto out_unlock;
6709
6710 }
6711
6712 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6713                         umode_t mode, bool excl)
6714 {
6715         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6716         struct btrfs_trans_handle *trans;
6717         struct btrfs_root *root = BTRFS_I(dir)->root;
6718         struct inode *inode = NULL;
6719         int drop_inode_on_err = 0;
6720         int err;
6721         u64 objectid;
6722         u64 index = 0;
6723
6724         /*
6725          * 2 for inode item and ref
6726          * 2 for dir items
6727          * 1 for xattr if selinux is on
6728          */
6729         trans = btrfs_start_transaction(root, 5);
6730         if (IS_ERR(trans))
6731                 return PTR_ERR(trans);
6732
6733         err = btrfs_find_free_ino(root, &objectid);
6734         if (err)
6735                 goto out_unlock;
6736
6737         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6738                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6739                         mode, &index);
6740         if (IS_ERR(inode)) {
6741                 err = PTR_ERR(inode);
6742                 goto out_unlock;
6743         }
6744         drop_inode_on_err = 1;
6745         /*
6746         * If the active LSM wants to access the inode during
6747         * d_instantiate it needs these. Smack checks to see
6748         * if the filesystem supports xattrs by looking at the
6749         * ops vector.
6750         */
6751         inode->i_fop = &btrfs_file_operations;
6752         inode->i_op = &btrfs_file_inode_operations;
6753         inode->i_mapping->a_ops = &btrfs_aops;
6754
6755         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6756         if (err)
6757                 goto out_unlock_inode;
6758
6759         err = btrfs_update_inode(trans, root, inode);
6760         if (err)
6761                 goto out_unlock_inode;
6762
6763         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6764                         0, index);
6765         if (err)
6766                 goto out_unlock_inode;
6767
6768         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6769         d_instantiate_new(dentry, inode);
6770
6771 out_unlock:
6772         btrfs_end_transaction(trans);
6773         if (err && drop_inode_on_err) {
6774                 inode_dec_link_count(inode);
6775                 iput(inode);
6776         }
6777         btrfs_btree_balance_dirty(fs_info);
6778         return err;
6779
6780 out_unlock_inode:
6781         unlock_new_inode(inode);
6782         goto out_unlock;
6783
6784 }
6785
6786 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6787                       struct dentry *dentry)
6788 {
6789         struct btrfs_trans_handle *trans = NULL;
6790         struct btrfs_root *root = BTRFS_I(dir)->root;
6791         struct inode *inode = d_inode(old_dentry);
6792         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6793         u64 index;
6794         int err;
6795         int drop_inode = 0;
6796
6797         /* do not allow sys_link's with other subvols of the same device */
6798         if (root->objectid != BTRFS_I(inode)->root->objectid)
6799                 return -EXDEV;
6800
6801         if (inode->i_nlink >= BTRFS_LINK_MAX)
6802                 return -EMLINK;
6803
6804         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6805         if (err)
6806                 goto fail;
6807
6808         /*
6809          * 2 items for inode and inode ref
6810          * 2 items for dir items
6811          * 1 item for parent inode
6812          */
6813         trans = btrfs_start_transaction(root, 5);
6814         if (IS_ERR(trans)) {
6815                 err = PTR_ERR(trans);
6816                 trans = NULL;
6817                 goto fail;
6818         }
6819
6820         /* There are several dir indexes for this inode, clear the cache. */
6821         BTRFS_I(inode)->dir_index = 0ULL;
6822         inc_nlink(inode);
6823         inode_inc_iversion(inode);
6824         inode->i_ctime = current_time(inode);
6825         ihold(inode);
6826         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6827
6828         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6829                         1, index);
6830
6831         if (err) {
6832                 drop_inode = 1;
6833         } else {
6834                 struct dentry *parent = dentry->d_parent;
6835                 err = btrfs_update_inode(trans, root, inode);
6836                 if (err)
6837                         goto fail;
6838                 if (inode->i_nlink == 1) {
6839                         /*
6840                          * If new hard link count is 1, it's a file created
6841                          * with open(2) O_TMPFILE flag.
6842                          */
6843                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6844                         if (err)
6845                                 goto fail;
6846                 }
6847                 d_instantiate(dentry, inode);
6848                 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6849         }
6850
6851 fail:
6852         if (trans)
6853                 btrfs_end_transaction(trans);
6854         if (drop_inode) {
6855                 inode_dec_link_count(inode);
6856                 iput(inode);
6857         }
6858         btrfs_btree_balance_dirty(fs_info);
6859         return err;
6860 }
6861
6862 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6863 {
6864         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6865         struct inode *inode = NULL;
6866         struct btrfs_trans_handle *trans;
6867         struct btrfs_root *root = BTRFS_I(dir)->root;
6868         int err = 0;
6869         int drop_on_err = 0;
6870         u64 objectid = 0;
6871         u64 index = 0;
6872
6873         /*
6874          * 2 items for inode and ref
6875          * 2 items for dir items
6876          * 1 for xattr if selinux is on
6877          */
6878         trans = btrfs_start_transaction(root, 5);
6879         if (IS_ERR(trans))
6880                 return PTR_ERR(trans);
6881
6882         err = btrfs_find_free_ino(root, &objectid);
6883         if (err)
6884                 goto out_fail;
6885
6886         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6887                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6888                         S_IFDIR | mode, &index);
6889         if (IS_ERR(inode)) {
6890                 err = PTR_ERR(inode);
6891                 goto out_fail;
6892         }
6893
6894         drop_on_err = 1;
6895         /* these must be set before we unlock the inode */
6896         inode->i_op = &btrfs_dir_inode_operations;
6897         inode->i_fop = &btrfs_dir_file_operations;
6898
6899         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6900         if (err)
6901                 goto out_fail_inode;
6902
6903         btrfs_i_size_write(BTRFS_I(inode), 0);
6904         err = btrfs_update_inode(trans, root, inode);
6905         if (err)
6906                 goto out_fail_inode;
6907
6908         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6909                         dentry->d_name.name,
6910                         dentry->d_name.len, 0, index);
6911         if (err)
6912                 goto out_fail_inode;
6913
6914         d_instantiate_new(dentry, inode);
6915         drop_on_err = 0;
6916
6917 out_fail:
6918         btrfs_end_transaction(trans);
6919         if (drop_on_err) {
6920                 inode_dec_link_count(inode);
6921                 iput(inode);
6922         }
6923         btrfs_btree_balance_dirty(fs_info);
6924         return err;
6925
6926 out_fail_inode:
6927         unlock_new_inode(inode);
6928         goto out_fail;
6929 }
6930
6931 static noinline int uncompress_inline(struct btrfs_path *path,
6932                                       struct page *page,
6933                                       size_t pg_offset, u64 extent_offset,
6934                                       struct btrfs_file_extent_item *item)
6935 {
6936         int ret;
6937         struct extent_buffer *leaf = path->nodes[0];
6938         char *tmp;
6939         size_t max_size;
6940         unsigned long inline_size;
6941         unsigned long ptr;
6942         int compress_type;
6943
6944         WARN_ON(pg_offset != 0);
6945         compress_type = btrfs_file_extent_compression(leaf, item);
6946         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6947         inline_size = btrfs_file_extent_inline_item_len(leaf,
6948                                         btrfs_item_nr(path->slots[0]));
6949         tmp = kmalloc(inline_size, GFP_NOFS);
6950         if (!tmp)
6951                 return -ENOMEM;
6952         ptr = btrfs_file_extent_inline_start(item);
6953
6954         read_extent_buffer(leaf, tmp, ptr, inline_size);
6955
6956         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6957         ret = btrfs_decompress(compress_type, tmp, page,
6958                                extent_offset, inline_size, max_size);
6959
6960         /*
6961          * decompression code contains a memset to fill in any space between the end
6962          * of the uncompressed data and the end of max_size in case the decompressed
6963          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6964          * the end of an inline extent and the beginning of the next block, so we
6965          * cover that region here.
6966          */
6967
6968         if (max_size + pg_offset < PAGE_SIZE) {
6969                 char *map = kmap(page);
6970                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6971                 kunmap(page);
6972         }
6973         kfree(tmp);
6974         return ret;
6975 }
6976
6977 /*
6978  * a bit scary, this does extent mapping from logical file offset to the disk.
6979  * the ugly parts come from merging extents from the disk with the in-ram
6980  * representation.  This gets more complex because of the data=ordered code,
6981  * where the in-ram extents might be locked pending data=ordered completion.
6982  *
6983  * This also copies inline extents directly into the page.
6984  */
6985 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6986                 struct page *page,
6987             size_t pg_offset, u64 start, u64 len,
6988                 int create)
6989 {
6990         struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6991         int ret;
6992         int err = 0;
6993         u64 extent_start = 0;
6994         u64 extent_end = 0;
6995         u64 objectid = btrfs_ino(inode);
6996         u32 found_type;
6997         struct btrfs_path *path = NULL;
6998         struct btrfs_root *root = inode->root;
6999         struct btrfs_file_extent_item *item;
7000         struct extent_buffer *leaf;
7001         struct btrfs_key found_key;
7002         struct extent_map *em = NULL;
7003         struct extent_map_tree *em_tree = &inode->extent_tree;
7004         struct extent_io_tree *io_tree = &inode->io_tree;
7005         const bool new_inline = !page || create;
7006
7007         read_lock(&em_tree->lock);
7008         em = lookup_extent_mapping(em_tree, start, len);
7009         if (em)
7010                 em->bdev = fs_info->fs_devices->latest_bdev;
7011         read_unlock(&em_tree->lock);
7012
7013         if (em) {
7014                 if (em->start > start || em->start + em->len <= start)
7015                         free_extent_map(em);
7016                 else if (em->block_start == EXTENT_MAP_INLINE && page)
7017                         free_extent_map(em);
7018                 else
7019                         goto out;
7020         }
7021         em = alloc_extent_map();
7022         if (!em) {
7023                 err = -ENOMEM;
7024                 goto out;
7025         }
7026         em->bdev = fs_info->fs_devices->latest_bdev;
7027         em->start = EXTENT_MAP_HOLE;
7028         em->orig_start = EXTENT_MAP_HOLE;
7029         em->len = (u64)-1;
7030         em->block_len = (u64)-1;
7031
7032         if (!path) {
7033                 path = btrfs_alloc_path();
7034                 if (!path) {
7035                         err = -ENOMEM;
7036                         goto out;
7037                 }
7038                 /*
7039                  * Chances are we'll be called again, so go ahead and do
7040                  * readahead
7041                  */
7042                 path->reada = READA_FORWARD;
7043         }
7044
7045         ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7046         if (ret < 0) {
7047                 err = ret;
7048                 goto out;
7049         }
7050
7051         if (ret != 0) {
7052                 if (path->slots[0] == 0)
7053                         goto not_found;
7054                 path->slots[0]--;
7055         }
7056
7057         leaf = path->nodes[0];
7058         item = btrfs_item_ptr(leaf, path->slots[0],
7059                               struct btrfs_file_extent_item);
7060         /* are we inside the extent that was found? */
7061         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7062         found_type = found_key.type;
7063         if (found_key.objectid != objectid ||
7064             found_type != BTRFS_EXTENT_DATA_KEY) {
7065                 /*
7066                  * If we backup past the first extent we want to move forward
7067                  * and see if there is an extent in front of us, otherwise we'll
7068                  * say there is a hole for our whole search range which can
7069                  * cause problems.
7070                  */
7071                 extent_end = start;
7072                 goto next;
7073         }
7074
7075         found_type = btrfs_file_extent_type(leaf, item);
7076         extent_start = found_key.offset;
7077         if (found_type == BTRFS_FILE_EXTENT_REG ||
7078             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7079                 extent_end = extent_start +
7080                        btrfs_file_extent_num_bytes(leaf, item);
7081
7082                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7083                                                        extent_start);
7084         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7085                 size_t size;
7086                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7087                 extent_end = ALIGN(extent_start + size,
7088                                    fs_info->sectorsize);
7089
7090                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7091                                                       path->slots[0],
7092                                                       extent_start);
7093         }
7094 next:
7095         if (start >= extent_end) {
7096                 path->slots[0]++;
7097                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7098                         ret = btrfs_next_leaf(root, path);
7099                         if (ret < 0) {
7100                                 err = ret;
7101                                 goto out;
7102                         }
7103                         if (ret > 0)
7104                                 goto not_found;
7105                         leaf = path->nodes[0];
7106                 }
7107                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7108                 if (found_key.objectid != objectid ||
7109                     found_key.type != BTRFS_EXTENT_DATA_KEY)
7110                         goto not_found;
7111                 if (start + len <= found_key.offset)
7112                         goto not_found;
7113                 if (start > found_key.offset)
7114                         goto next;
7115                 em->start = start;
7116                 em->orig_start = start;
7117                 em->len = found_key.offset - start;
7118                 goto not_found_em;
7119         }
7120
7121         btrfs_extent_item_to_extent_map(inode, path, item,
7122                         new_inline, em);
7123
7124         if (found_type == BTRFS_FILE_EXTENT_REG ||
7125             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7126                 goto insert;
7127         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
7128                 unsigned long ptr;
7129                 char *map;
7130                 size_t size;
7131                 size_t extent_offset;
7132                 size_t copy_size;
7133
7134                 if (new_inline)
7135                         goto out;
7136
7137                 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
7138                 extent_offset = page_offset(page) + pg_offset - extent_start;
7139                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7140                                   size - extent_offset);
7141                 em->start = extent_start + extent_offset;
7142                 em->len = ALIGN(copy_size, fs_info->sectorsize);
7143                 em->orig_block_len = em->len;
7144                 em->orig_start = em->start;
7145                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7146                 if (!PageUptodate(page)) {
7147                         if (btrfs_file_extent_compression(leaf, item) !=
7148                             BTRFS_COMPRESS_NONE) {
7149                                 ret = uncompress_inline(path, page, pg_offset,
7150                                                         extent_offset, item);
7151                                 if (ret) {
7152                                         err = ret;
7153                                         goto out;
7154                                 }
7155                         } else {
7156                                 map = kmap(page);
7157                                 read_extent_buffer(leaf, map + pg_offset, ptr,
7158                                                    copy_size);
7159                                 if (pg_offset + copy_size < PAGE_SIZE) {
7160                                         memset(map + pg_offset + copy_size, 0,
7161                                                PAGE_SIZE - pg_offset -
7162                                                copy_size);
7163                                 }
7164                                 kunmap(page);
7165                         }
7166                         flush_dcache_page(page);
7167                 }
7168                 set_extent_uptodate(io_tree, em->start,
7169                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
7170                 goto insert;
7171         }
7172 not_found:
7173         em->start = start;
7174         em->orig_start = start;
7175         em->len = len;
7176 not_found_em:
7177         em->block_start = EXTENT_MAP_HOLE;
7178 insert:
7179         btrfs_release_path(path);
7180         if (em->start > start || extent_map_end(em) <= start) {
7181                 btrfs_err(fs_info,
7182                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7183                           em->start, em->len, start, len);
7184                 err = -EIO;
7185                 goto out;
7186         }
7187
7188         err = 0;
7189         write_lock(&em_tree->lock);
7190         err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7191         write_unlock(&em_tree->lock);
7192 out:
7193
7194         trace_btrfs_get_extent(root, inode, em);
7195
7196         btrfs_free_path(path);
7197         if (err) {
7198                 free_extent_map(em);
7199                 return ERR_PTR(err);
7200         }
7201         BUG_ON(!em); /* Error is always set */
7202         return em;
7203 }
7204
7205 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7206                 struct page *page,
7207                 size_t pg_offset, u64 start, u64 len,
7208                 int create)
7209 {
7210         struct extent_map *em;
7211         struct extent_map *hole_em = NULL;
7212         u64 range_start = start;
7213         u64 end;
7214         u64 found;
7215         u64 found_end;
7216         int err = 0;
7217
7218         em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7219         if (IS_ERR(em))
7220                 return em;
7221         /*
7222          * If our em maps to:
7223          * - a hole or
7224          * - a pre-alloc extent,
7225          * there might actually be delalloc bytes behind it.
7226          */
7227         if (em->block_start != EXTENT_MAP_HOLE &&
7228             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7229                 return em;
7230         else
7231                 hole_em = em;
7232
7233         /* check to see if we've wrapped (len == -1 or similar) */
7234         end = start + len;
7235         if (end < start)
7236                 end = (u64)-1;
7237         else
7238                 end -= 1;
7239
7240         em = NULL;
7241
7242         /* ok, we didn't find anything, lets look for delalloc */
7243         found = count_range_bits(&inode->io_tree, &range_start,
7244                                  end, len, EXTENT_DELALLOC, 1);
7245         found_end = range_start + found;
7246         if (found_end < range_start)
7247                 found_end = (u64)-1;
7248
7249         /*
7250          * we didn't find anything useful, return
7251          * the original results from get_extent()
7252          */
7253         if (range_start > end || found_end <= start) {
7254                 em = hole_em;
7255                 hole_em = NULL;
7256                 goto out;
7257         }
7258
7259         /* adjust the range_start to make sure it doesn't
7260          * go backwards from the start they passed in
7261          */
7262         range_start = max(start, range_start);
7263         found = found_end - range_start;
7264
7265         if (found > 0) {
7266                 u64 hole_start = start;
7267                 u64 hole_len = len;
7268
7269                 em = alloc_extent_map();
7270                 if (!em) {
7271                         err = -ENOMEM;
7272                         goto out;
7273                 }
7274                 /*
7275                  * when btrfs_get_extent can't find anything it
7276                  * returns one huge hole
7277                  *
7278                  * make sure what it found really fits our range, and
7279                  * adjust to make sure it is based on the start from
7280                  * the caller
7281                  */
7282                 if (hole_em) {
7283                         u64 calc_end = extent_map_end(hole_em);
7284
7285                         if (calc_end <= start || (hole_em->start > end)) {
7286                                 free_extent_map(hole_em);
7287                                 hole_em = NULL;
7288                         } else {
7289                                 hole_start = max(hole_em->start, start);
7290                                 hole_len = calc_end - hole_start;
7291                         }
7292                 }
7293                 em->bdev = NULL;
7294                 if (hole_em && range_start > hole_start) {
7295                         /* our hole starts before our delalloc, so we
7296                          * have to return just the parts of the hole
7297                          * that go until  the delalloc starts
7298                          */
7299                         em->len = min(hole_len,
7300                                       range_start - hole_start);
7301                         em->start = hole_start;
7302                         em->orig_start = hole_start;
7303                         /*
7304                          * don't adjust block start at all,
7305                          * it is fixed at EXTENT_MAP_HOLE
7306                          */
7307                         em->block_start = hole_em->block_start;
7308                         em->block_len = hole_len;
7309                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7310                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7311                 } else {
7312                         em->start = range_start;
7313                         em->len = found;
7314                         em->orig_start = range_start;
7315                         em->block_start = EXTENT_MAP_DELALLOC;
7316                         em->block_len = found;
7317                 }
7318         } else {
7319                 return hole_em;
7320         }
7321 out:
7322
7323         free_extent_map(hole_em);
7324         if (err) {
7325                 free_extent_map(em);
7326                 return ERR_PTR(err);
7327         }
7328         return em;
7329 }
7330
7331 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7332                                                   const u64 start,
7333                                                   const u64 len,
7334                                                   const u64 orig_start,
7335                                                   const u64 block_start,
7336                                                   const u64 block_len,
7337                                                   const u64 orig_block_len,
7338                                                   const u64 ram_bytes,
7339                                                   const int type)
7340 {
7341         struct extent_map *em = NULL;
7342         int ret;
7343
7344         if (type != BTRFS_ORDERED_NOCOW) {
7345                 em = create_io_em(inode, start, len, orig_start,
7346                                   block_start, block_len, orig_block_len,
7347                                   ram_bytes,
7348                                   BTRFS_COMPRESS_NONE, /* compress_type */
7349                                   type);
7350                 if (IS_ERR(em))
7351                         goto out;
7352         }
7353         ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7354                                            len, block_len, type);
7355         if (ret) {
7356                 if (em) {
7357                         free_extent_map(em);
7358                         btrfs_drop_extent_cache(BTRFS_I(inode), start,
7359                                                 start + len - 1, 0);
7360                 }
7361                 em = ERR_PTR(ret);
7362         }
7363  out:
7364
7365         return em;
7366 }
7367
7368 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7369                                                   u64 start, u64 len)
7370 {
7371         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7372         struct btrfs_root *root = BTRFS_I(inode)->root;
7373         struct extent_map *em;
7374         struct btrfs_key ins;
7375         u64 alloc_hint;
7376         int ret;
7377
7378         alloc_hint = get_extent_allocation_hint(inode, start, len);
7379         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7380                                    0, alloc_hint, &ins, 1, 1);
7381         if (ret)
7382                 return ERR_PTR(ret);
7383
7384         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7385                                      ins.objectid, ins.offset, ins.offset,
7386                                      ins.offset, BTRFS_ORDERED_REGULAR);
7387         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7388         if (IS_ERR(em))
7389                 btrfs_free_reserved_extent(fs_info, ins.objectid,
7390                                            ins.offset, 1);
7391
7392         return em;
7393 }
7394
7395 /*
7396  * returns 1 when the nocow is safe, < 1 on error, 0 if the
7397  * block must be cow'd
7398  */
7399 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7400                               u64 *orig_start, u64 *orig_block_len,
7401                               u64 *ram_bytes)
7402 {
7403         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7404         struct btrfs_path *path;
7405         int ret;
7406         struct extent_buffer *leaf;
7407         struct btrfs_root *root = BTRFS_I(inode)->root;
7408         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7409         struct btrfs_file_extent_item *fi;
7410         struct btrfs_key key;
7411         u64 disk_bytenr;
7412         u64 backref_offset;
7413         u64 extent_end;
7414         u64 num_bytes;
7415         int slot;
7416         int found_type;
7417         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7418
7419         path = btrfs_alloc_path();
7420         if (!path)
7421                 return -ENOMEM;
7422
7423         ret = btrfs_lookup_file_extent(NULL, root, path,
7424                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7425         if (ret < 0)
7426                 goto out;
7427
7428         slot = path->slots[0];
7429         if (ret == 1) {
7430                 if (slot == 0) {
7431                         /* can't find the item, must cow */
7432                         ret = 0;
7433                         goto out;
7434                 }
7435                 slot--;
7436         }
7437         ret = 0;
7438         leaf = path->nodes[0];
7439         btrfs_item_key_to_cpu(leaf, &key, slot);
7440         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7441             key.type != BTRFS_EXTENT_DATA_KEY) {
7442                 /* not our file or wrong item type, must cow */
7443                 goto out;
7444         }
7445
7446         if (key.offset > offset) {
7447                 /* Wrong offset, must cow */
7448                 goto out;
7449         }
7450
7451         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7452         found_type = btrfs_file_extent_type(leaf, fi);
7453         if (found_type != BTRFS_FILE_EXTENT_REG &&
7454             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7455                 /* not a regular extent, must cow */
7456                 goto out;
7457         }
7458
7459         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7460                 goto out;
7461
7462         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7463         if (extent_end <= offset)
7464                 goto out;
7465
7466         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7467         if (disk_bytenr == 0)
7468                 goto out;
7469
7470         if (btrfs_file_extent_compression(leaf, fi) ||
7471             btrfs_file_extent_encryption(leaf, fi) ||
7472             btrfs_file_extent_other_encoding(leaf, fi))
7473                 goto out;
7474
7475         backref_offset = btrfs_file_extent_offset(leaf, fi);
7476
7477         if (orig_start) {
7478                 *orig_start = key.offset - backref_offset;
7479                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7480                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7481         }
7482
7483         if (btrfs_extent_readonly(fs_info, disk_bytenr))
7484                 goto out;
7485
7486         num_bytes = min(offset + *len, extent_end) - offset;
7487         if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7488                 u64 range_end;
7489
7490                 range_end = round_up(offset + num_bytes,
7491                                      root->fs_info->sectorsize) - 1;
7492                 ret = test_range_bit(io_tree, offset, range_end,
7493                                      EXTENT_DELALLOC, 0, NULL);
7494                 if (ret) {
7495                         ret = -EAGAIN;
7496                         goto out;
7497                 }
7498         }
7499
7500         btrfs_release_path(path);
7501
7502         /*
7503          * look for other files referencing this extent, if we
7504          * find any we must cow
7505          */
7506
7507         ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7508                                     key.offset - backref_offset, disk_bytenr);
7509         if (ret) {
7510                 ret = 0;
7511                 goto out;
7512         }
7513
7514         /*
7515          * adjust disk_bytenr and num_bytes to cover just the bytes
7516          * in this extent we are about to write.  If there
7517          * are any csums in that range we have to cow in order
7518          * to keep the csums correct
7519          */
7520         disk_bytenr += backref_offset;
7521         disk_bytenr += offset - key.offset;
7522         if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7523                 goto out;
7524         /*
7525          * all of the above have passed, it is safe to overwrite this extent
7526          * without cow
7527          */
7528         *len = num_bytes;
7529         ret = 1;
7530 out:
7531         btrfs_free_path(path);
7532         return ret;
7533 }
7534
7535 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7536                               struct extent_state **cached_state, int writing)
7537 {
7538         struct btrfs_ordered_extent *ordered;
7539         int ret = 0;
7540
7541         while (1) {
7542                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7543                                  cached_state);
7544                 /*
7545                  * We're concerned with the entire range that we're going to be
7546                  * doing DIO to, so we need to make sure there's no ordered
7547                  * extents in this range.
7548                  */
7549                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7550                                                      lockend - lockstart + 1);
7551
7552                 /*
7553                  * We need to make sure there are no buffered pages in this
7554                  * range either, we could have raced between the invalidate in
7555                  * generic_file_direct_write and locking the extent.  The
7556                  * invalidate needs to happen so that reads after a write do not
7557                  * get stale data.
7558                  */
7559                 if (!ordered &&
7560                     (!writing || !filemap_range_has_page(inode->i_mapping,
7561                                                          lockstart, lockend)))
7562                         break;
7563
7564                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7565                                      cached_state);
7566
7567                 if (ordered) {
7568                         /*
7569                          * If we are doing a DIO read and the ordered extent we
7570                          * found is for a buffered write, we can not wait for it
7571                          * to complete and retry, because if we do so we can
7572                          * deadlock with concurrent buffered writes on page
7573                          * locks. This happens only if our DIO read covers more
7574                          * than one extent map, if at this point has already
7575                          * created an ordered extent for a previous extent map
7576                          * and locked its range in the inode's io tree, and a
7577                          * concurrent write against that previous extent map's
7578                          * range and this range started (we unlock the ranges
7579                          * in the io tree only when the bios complete and
7580                          * buffered writes always lock pages before attempting
7581                          * to lock range in the io tree).
7582                          */
7583                         if (writing ||
7584                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7585                                 btrfs_start_ordered_extent(inode, ordered, 1);
7586                         else
7587                                 ret = -ENOTBLK;
7588                         btrfs_put_ordered_extent(ordered);
7589                 } else {
7590                         /*
7591                          * We could trigger writeback for this range (and wait
7592                          * for it to complete) and then invalidate the pages for
7593                          * this range (through invalidate_inode_pages2_range()),
7594                          * but that can lead us to a deadlock with a concurrent
7595                          * call to readpages() (a buffered read or a defrag call
7596                          * triggered a readahead) on a page lock due to an
7597                          * ordered dio extent we created before but did not have
7598                          * yet a corresponding bio submitted (whence it can not
7599                          * complete), which makes readpages() wait for that
7600                          * ordered extent to complete while holding a lock on
7601                          * that page.
7602                          */
7603                         ret = -ENOTBLK;
7604                 }
7605
7606                 if (ret)
7607                         break;
7608
7609                 cond_resched();
7610         }
7611
7612         return ret;
7613 }
7614
7615 /* The callers of this must take lock_extent() */
7616 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7617                                        u64 orig_start, u64 block_start,
7618                                        u64 block_len, u64 orig_block_len,
7619                                        u64 ram_bytes, int compress_type,
7620                                        int type)
7621 {
7622         struct extent_map_tree *em_tree;
7623         struct extent_map *em;
7624         struct btrfs_root *root = BTRFS_I(inode)->root;
7625         int ret;
7626
7627         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7628                type == BTRFS_ORDERED_COMPRESSED ||
7629                type == BTRFS_ORDERED_NOCOW ||
7630                type == BTRFS_ORDERED_REGULAR);
7631
7632         em_tree = &BTRFS_I(inode)->extent_tree;
7633         em = alloc_extent_map();
7634         if (!em)
7635                 return ERR_PTR(-ENOMEM);
7636
7637         em->start = start;
7638         em->orig_start = orig_start;
7639         em->len = len;
7640         em->block_len = block_len;
7641         em->block_start = block_start;
7642         em->bdev = root->fs_info->fs_devices->latest_bdev;
7643         em->orig_block_len = orig_block_len;
7644         em->ram_bytes = ram_bytes;
7645         em->generation = -1;
7646         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7647         if (type == BTRFS_ORDERED_PREALLOC) {
7648                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7649         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7650                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7651                 em->compress_type = compress_type;
7652         }
7653
7654         do {
7655                 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7656                                 em->start + em->len - 1, 0);
7657                 write_lock(&em_tree->lock);
7658                 ret = add_extent_mapping(em_tree, em, 1);
7659                 write_unlock(&em_tree->lock);
7660                 /*
7661                  * The caller has taken lock_extent(), who could race with us
7662                  * to add em?
7663                  */
7664         } while (ret == -EEXIST);
7665
7666         if (ret) {
7667                 free_extent_map(em);
7668                 return ERR_PTR(ret);
7669         }
7670
7671         /* em got 2 refs now, callers needs to do free_extent_map once. */
7672         return em;
7673 }
7674
7675 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7676                                    struct buffer_head *bh_result, int create)
7677 {
7678         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7679         struct extent_map *em;
7680         struct extent_state *cached_state = NULL;
7681         struct btrfs_dio_data *dio_data = NULL;
7682         u64 start = iblock << inode->i_blkbits;
7683         u64 lockstart, lockend;
7684         u64 len = bh_result->b_size;
7685         int unlock_bits = EXTENT_LOCKED;
7686         int ret = 0;
7687
7688         if (create)
7689                 unlock_bits |= EXTENT_DIRTY;
7690         else
7691                 len = min_t(u64, len, fs_info->sectorsize);
7692
7693         lockstart = start;
7694         lockend = start + len - 1;
7695
7696         if (current->journal_info) {
7697                 /*
7698                  * Need to pull our outstanding extents and set journal_info to NULL so
7699                  * that anything that needs to check if there's a transaction doesn't get
7700                  * confused.
7701                  */
7702                 dio_data = current->journal_info;
7703                 current->journal_info = NULL;
7704         }
7705
7706         /*
7707          * If this errors out it's because we couldn't invalidate pagecache for
7708          * this range and we need to fallback to buffered.
7709          */
7710         if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7711                                create)) {
7712                 ret = -ENOTBLK;
7713                 goto err;
7714         }
7715
7716         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7717         if (IS_ERR(em)) {
7718                 ret = PTR_ERR(em);
7719                 goto unlock_err;
7720         }
7721
7722         /*
7723          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7724          * io.  INLINE is special, and we could probably kludge it in here, but
7725          * it's still buffered so for safety lets just fall back to the generic
7726          * buffered path.
7727          *
7728          * For COMPRESSED we _have_ to read the entire extent in so we can
7729          * decompress it, so there will be buffering required no matter what we
7730          * do, so go ahead and fallback to buffered.
7731          *
7732          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7733          * to buffered IO.  Don't blame me, this is the price we pay for using
7734          * the generic code.
7735          */
7736         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7737             em->block_start == EXTENT_MAP_INLINE) {
7738                 free_extent_map(em);
7739                 ret = -ENOTBLK;
7740                 goto unlock_err;
7741         }
7742
7743         /* Just a good old fashioned hole, return */
7744         if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7745                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7746                 free_extent_map(em);
7747                 goto unlock_err;
7748         }
7749
7750         /*
7751          * We don't allocate a new extent in the following cases
7752          *
7753          * 1) The inode is marked as NODATACOW.  In this case we'll just use the
7754          * existing extent.
7755          * 2) The extent is marked as PREALLOC.  We're good to go here and can
7756          * just use the extent.
7757          *
7758          */
7759         if (!create) {
7760                 len = min(len, em->len - (start - em->start));
7761                 lockstart = start + len;
7762                 goto unlock;
7763         }
7764
7765         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7766             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7767              em->block_start != EXTENT_MAP_HOLE)) {
7768                 int type;
7769                 u64 block_start, orig_start, orig_block_len, ram_bytes;
7770
7771                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7772                         type = BTRFS_ORDERED_PREALLOC;
7773                 else
7774                         type = BTRFS_ORDERED_NOCOW;
7775                 len = min(len, em->len - (start - em->start));
7776                 block_start = em->block_start + (start - em->start);
7777
7778                 if (can_nocow_extent(inode, start, &len, &orig_start,
7779                                      &orig_block_len, &ram_bytes) == 1 &&
7780                     btrfs_inc_nocow_writers(fs_info, block_start)) {
7781                         struct extent_map *em2;
7782
7783                         em2 = btrfs_create_dio_extent(inode, start, len,
7784                                                       orig_start, block_start,
7785                                                       len, orig_block_len,
7786                                                       ram_bytes, type);
7787                         btrfs_dec_nocow_writers(fs_info, block_start);
7788                         if (type == BTRFS_ORDERED_PREALLOC) {
7789                                 free_extent_map(em);
7790                                 em = em2;
7791                         }
7792                         if (em2 && IS_ERR(em2)) {
7793                                 ret = PTR_ERR(em2);
7794                                 goto unlock_err;
7795                         }
7796                         /*
7797                          * For inode marked NODATACOW or extent marked PREALLOC,
7798                          * use the existing or preallocated extent, so does not
7799                          * need to adjust btrfs_space_info's bytes_may_use.
7800                          */
7801                         btrfs_free_reserved_data_space_noquota(inode,
7802                                         start, len);
7803                         goto unlock;
7804                 }
7805         }
7806
7807         /*
7808          * this will cow the extent, reset the len in case we changed
7809          * it above
7810          */
7811         len = bh_result->b_size;
7812         free_extent_map(em);
7813         em = btrfs_new_extent_direct(inode, start, len);
7814         if (IS_ERR(em)) {
7815                 ret = PTR_ERR(em);
7816                 goto unlock_err;
7817         }
7818         len = min(len, em->len - (start - em->start));
7819 unlock:
7820         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7821                 inode->i_blkbits;
7822         bh_result->b_size = len;
7823         bh_result->b_bdev = em->bdev;
7824         set_buffer_mapped(bh_result);
7825         if (create) {
7826                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7827                         set_buffer_new(bh_result);
7828
7829                 /*
7830                  * Need to update the i_size under the extent lock so buffered
7831                  * readers will get the updated i_size when we unlock.
7832                  */
7833                 if (!dio_data->overwrite && start + len > i_size_read(inode))
7834                         i_size_write(inode, start + len);
7835
7836                 WARN_ON(dio_data->reserve < len);
7837                 dio_data->reserve -= len;
7838                 dio_data->unsubmitted_oe_range_end = start + len;
7839                 current->journal_info = dio_data;
7840         }
7841
7842         /*
7843          * In the case of write we need to clear and unlock the entire range,
7844          * in the case of read we need to unlock only the end area that we
7845          * aren't using if there is any left over space.
7846          */
7847         if (lockstart < lockend) {
7848                 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7849                                  lockend, unlock_bits, 1, 0,
7850                                  &cached_state);
7851         } else {
7852                 free_extent_state(cached_state);
7853         }
7854
7855         free_extent_map(em);
7856
7857         return 0;
7858
7859 unlock_err:
7860         clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7861                          unlock_bits, 1, 0, &cached_state);
7862 err:
7863         if (dio_data)
7864                 current->journal_info = dio_data;
7865         return ret;
7866 }
7867
7868 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7869                                                  struct bio *bio,
7870                                                  int mirror_num)
7871 {
7872         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7873         blk_status_t ret;
7874
7875         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7876
7877         ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7878         if (ret)
7879                 return ret;
7880
7881         ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7882
7883         return ret;
7884 }
7885
7886 static int btrfs_check_dio_repairable(struct inode *inode,
7887                                       struct bio *failed_bio,
7888                                       struct io_failure_record *failrec,
7889                                       int failed_mirror)
7890 {
7891         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7892         int num_copies;
7893
7894         num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7895         if (num_copies == 1) {
7896                 /*
7897                  * we only have a single copy of the data, so don't bother with
7898                  * all the retry and error correction code that follows. no
7899                  * matter what the error is, it is very likely to persist.
7900                  */
7901                 btrfs_debug(fs_info,
7902                         "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7903                         num_copies, failrec->this_mirror, failed_mirror);
7904                 return 0;
7905         }
7906
7907         failrec->failed_mirror = failed_mirror;
7908         failrec->this_mirror++;
7909         if (failrec->this_mirror == failed_mirror)
7910                 failrec->this_mirror++;
7911
7912         if (failrec->this_mirror > num_copies) {
7913                 btrfs_debug(fs_info,
7914                         "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7915                         num_copies, failrec->this_mirror, failed_mirror);
7916                 return 0;
7917         }
7918
7919         return 1;
7920 }
7921
7922 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7923                                    struct page *page, unsigned int pgoff,
7924                                    u64 start, u64 end, int failed_mirror,
7925                                    bio_end_io_t *repair_endio, void *repair_arg)
7926 {
7927         struct io_failure_record *failrec;
7928         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7929         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7930         struct bio *bio;
7931         int isector;
7932         unsigned int read_mode = 0;
7933         int segs;
7934         int ret;
7935         blk_status_t status;
7936         struct bio_vec bvec;
7937
7938         BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7939
7940         ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7941         if (ret)
7942                 return errno_to_blk_status(ret);
7943
7944         ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7945                                          failed_mirror);
7946         if (!ret) {
7947                 free_io_failure(failure_tree, io_tree, failrec);
7948                 return BLK_STS_IOERR;
7949         }
7950
7951         segs = bio_segments(failed_bio);
7952         bio_get_first_bvec(failed_bio, &bvec);
7953         if (segs > 1 ||
7954             (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7955                 read_mode |= REQ_FAILFAST_DEV;
7956
7957         isector = start - btrfs_io_bio(failed_bio)->logical;
7958         isector >>= inode->i_sb->s_blocksize_bits;
7959         bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7960                                 pgoff, isector, repair_endio, repair_arg);
7961         bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7962
7963         btrfs_debug(BTRFS_I(inode)->root->fs_info,
7964                     "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7965                     read_mode, failrec->this_mirror, failrec->in_validation);
7966
7967         status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7968         if (status) {
7969                 free_io_failure(failure_tree, io_tree, failrec);
7970                 bio_put(bio);
7971         }
7972
7973         return status;
7974 }
7975
7976 struct btrfs_retry_complete {
7977         struct completion done;
7978         struct inode *inode;
7979         u64 start;
7980         int uptodate;
7981 };
7982
7983 static void btrfs_retry_endio_nocsum(struct bio *bio)
7984 {
7985         struct btrfs_retry_complete *done = bio->bi_private;
7986         struct inode *inode = done->inode;
7987         struct bio_vec *bvec;
7988         struct extent_io_tree *io_tree, *failure_tree;
7989         int i;
7990
7991         if (bio->bi_status)
7992                 goto end;
7993
7994         ASSERT(bio->bi_vcnt == 1);
7995         io_tree = &BTRFS_I(inode)->io_tree;
7996         failure_tree = &BTRFS_I(inode)->io_failure_tree;
7997         ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7998
7999         done->uptodate = 1;
8000         ASSERT(!bio_flagged(bio, BIO_CLONED));
8001         bio_for_each_segment_all(bvec, bio, i)
8002                 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
8003                                  io_tree, done->start, bvec->bv_page,
8004                                  btrfs_ino(BTRFS_I(inode)), 0);
8005 end:
8006         complete(&done->done);
8007         bio_put(bio);
8008 }
8009
8010 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
8011                                                 struct btrfs_io_bio *io_bio)
8012 {
8013         struct btrfs_fs_info *fs_info;
8014         struct bio_vec bvec;
8015         struct bvec_iter iter;
8016         struct btrfs_retry_complete done;
8017         u64 start;
8018         unsigned int pgoff;
8019         u32 sectorsize;
8020         int nr_sectors;
8021         blk_status_t ret;
8022         blk_status_t err = BLK_STS_OK;
8023
8024         fs_info = BTRFS_I(inode)->root->fs_info;
8025         sectorsize = fs_info->sectorsize;
8026
8027         start = io_bio->logical;
8028         done.inode = inode;
8029         io_bio->bio.bi_iter = io_bio->iter;
8030
8031         bio_for_each_segment(bvec, &io_bio->bio, iter) {
8032                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8033                 pgoff = bvec.bv_offset;
8034
8035 next_block_or_try_again:
8036                 done.uptodate = 0;
8037                 done.start = start;
8038                 init_completion(&done.done);
8039
8040                 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8041                                 pgoff, start, start + sectorsize - 1,
8042                                 io_bio->mirror_num,
8043                                 btrfs_retry_endio_nocsum, &done);
8044                 if (ret) {
8045                         err = ret;
8046                         goto next;
8047                 }
8048
8049                 wait_for_completion_io(&done.done);
8050
8051                 if (!done.uptodate) {
8052                         /* We might have another mirror, so try again */
8053                         goto next_block_or_try_again;
8054                 }
8055
8056 next:
8057                 start += sectorsize;
8058
8059                 nr_sectors--;
8060                 if (nr_sectors) {
8061                         pgoff += sectorsize;
8062                         ASSERT(pgoff < PAGE_SIZE);
8063                         goto next_block_or_try_again;
8064                 }
8065         }
8066
8067         return err;
8068 }
8069
8070 static void btrfs_retry_endio(struct bio *bio)
8071 {
8072         struct btrfs_retry_complete *done = bio->bi_private;
8073         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8074         struct extent_io_tree *io_tree, *failure_tree;
8075         struct inode *inode = done->inode;
8076         struct bio_vec *bvec;
8077         int uptodate;
8078         int ret;
8079         int i;
8080
8081         if (bio->bi_status)
8082                 goto end;
8083
8084         uptodate = 1;
8085
8086         ASSERT(bio->bi_vcnt == 1);
8087         ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
8088
8089         io_tree = &BTRFS_I(inode)->io_tree;
8090         failure_tree = &BTRFS_I(inode)->io_failure_tree;
8091
8092         ASSERT(!bio_flagged(bio, BIO_CLONED));
8093         bio_for_each_segment_all(bvec, bio, i) {
8094                 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
8095                                              bvec->bv_offset, done->start,
8096                                              bvec->bv_len);
8097                 if (!ret)
8098                         clean_io_failure(BTRFS_I(inode)->root->fs_info,
8099                                          failure_tree, io_tree, done->start,
8100                                          bvec->bv_page,
8101                                          btrfs_ino(BTRFS_I(inode)),
8102                                          bvec->bv_offset);
8103                 else
8104                         uptodate = 0;
8105         }
8106
8107         done->uptodate = uptodate;
8108 end:
8109         complete(&done->done);
8110         bio_put(bio);
8111 }
8112
8113 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
8114                 struct btrfs_io_bio *io_bio, blk_status_t err)
8115 {
8116         struct btrfs_fs_info *fs_info;
8117         struct bio_vec bvec;
8118         struct bvec_iter iter;
8119         struct btrfs_retry_complete done;
8120         u64 start;
8121         u64 offset = 0;
8122         u32 sectorsize;
8123         int nr_sectors;
8124         unsigned int pgoff;
8125         int csum_pos;
8126         bool uptodate = (err == 0);
8127         int ret;
8128         blk_status_t status;
8129
8130         fs_info = BTRFS_I(inode)->root->fs_info;
8131         sectorsize = fs_info->sectorsize;
8132
8133         err = BLK_STS_OK;
8134         start = io_bio->logical;
8135         done.inode = inode;
8136         io_bio->bio.bi_iter = io_bio->iter;
8137
8138         bio_for_each_segment(bvec, &io_bio->bio, iter) {
8139                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8140
8141                 pgoff = bvec.bv_offset;
8142 next_block:
8143                 if (uptodate) {
8144                         csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8145                         ret = __readpage_endio_check(inode, io_bio, csum_pos,
8146                                         bvec.bv_page, pgoff, start, sectorsize);
8147                         if (likely(!ret))
8148                                 goto next;
8149                 }
8150 try_again:
8151                 done.uptodate = 0;
8152                 done.start = start;
8153                 init_completion(&done.done);
8154
8155                 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8156                                         pgoff, start, start + sectorsize - 1,
8157                                         io_bio->mirror_num, btrfs_retry_endio,
8158                                         &done);
8159                 if (status) {
8160                         err = status;
8161                         goto next;
8162                 }
8163
8164                 wait_for_completion_io(&done.done);
8165
8166                 if (!done.uptodate) {
8167                         /* We might have another mirror, so try again */
8168                         goto try_again;
8169                 }
8170 next:
8171                 offset += sectorsize;
8172                 start += sectorsize;
8173
8174                 ASSERT(nr_sectors);
8175
8176                 nr_sectors--;
8177                 if (nr_sectors) {
8178                         pgoff += sectorsize;
8179                         ASSERT(pgoff < PAGE_SIZE);
8180                         goto next_block;
8181                 }
8182         }
8183
8184         return err;
8185 }
8186
8187 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8188                 struct btrfs_io_bio *io_bio, blk_status_t err)
8189 {
8190         bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8191
8192         if (skip_csum) {
8193                 if (unlikely(err))
8194                         return __btrfs_correct_data_nocsum(inode, io_bio);
8195                 else
8196                         return BLK_STS_OK;
8197         } else {
8198                 return __btrfs_subio_endio_read(inode, io_bio, err);
8199         }
8200 }
8201
8202 static void btrfs_endio_direct_read(struct bio *bio)
8203 {
8204         struct btrfs_dio_private *dip = bio->bi_private;
8205         struct inode *inode = dip->inode;
8206         struct bio *dio_bio;
8207         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8208         blk_status_t err = bio->bi_status;
8209
8210         if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8211                 err = btrfs_subio_endio_read(inode, io_bio, err);
8212
8213         unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8214                       dip->logical_offset + dip->bytes - 1);
8215         dio_bio = dip->dio_bio;
8216
8217         kfree(dip);
8218
8219         dio_bio->bi_status = err;
8220         dio_end_io(dio_bio);
8221
8222         if (io_bio->end_io)
8223                 io_bio->end_io(io_bio, blk_status_to_errno(err));
8224         bio_put(bio);
8225 }
8226
8227 static void __endio_write_update_ordered(struct inode *inode,
8228                                          const u64 offset, const u64 bytes,
8229                                          const bool uptodate)
8230 {
8231         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8232         struct btrfs_ordered_extent *ordered = NULL;
8233         struct btrfs_workqueue *wq;
8234         btrfs_work_func_t func;
8235         u64 ordered_offset = offset;
8236         u64 ordered_bytes = bytes;
8237         u64 last_offset;
8238
8239         if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8240                 wq = fs_info->endio_freespace_worker;
8241                 func = btrfs_freespace_write_helper;
8242         } else {
8243                 wq = fs_info->endio_write_workers;
8244                 func = btrfs_endio_write_helper;
8245         }
8246
8247         while (ordered_offset < offset + bytes) {
8248                 last_offset = ordered_offset;
8249                 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8250                                                            &ordered_offset,
8251                                                            ordered_bytes,
8252                                                            uptodate)) {
8253                         btrfs_init_work(&ordered->work, func,
8254                                         finish_ordered_fn,
8255                                         NULL, NULL);
8256                         btrfs_queue_work(wq, &ordered->work);
8257                 }
8258                 /*
8259                  * If btrfs_dec_test_ordered_pending does not find any ordered
8260                  * extent in the range, we can exit.
8261                  */
8262                 if (ordered_offset == last_offset)
8263                         return;
8264                 /*
8265                  * Our bio might span multiple ordered extents. In this case
8266                  * we keep goin until we have accounted the whole dio.
8267                  */
8268                 if (ordered_offset < offset + bytes) {
8269                         ordered_bytes = offset + bytes - ordered_offset;
8270                         ordered = NULL;
8271                 }
8272         }
8273 }
8274
8275 static void btrfs_endio_direct_write(struct bio *bio)
8276 {
8277         struct btrfs_dio_private *dip = bio->bi_private;
8278         struct bio *dio_bio = dip->dio_bio;
8279
8280         __endio_write_update_ordered(dip->inode, dip->logical_offset,
8281                                      dip->bytes, !bio->bi_status);
8282
8283         kfree(dip);
8284
8285         dio_bio->bi_status = bio->bi_status;
8286         dio_end_io(dio_bio);
8287         bio_put(bio);
8288 }
8289
8290 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8291                                     struct bio *bio, u64 offset)
8292 {
8293         struct inode *inode = private_data;
8294         blk_status_t ret;
8295         ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8296         BUG_ON(ret); /* -ENOMEM */
8297         return 0;
8298 }
8299
8300 static void btrfs_end_dio_bio(struct bio *bio)
8301 {
8302         struct btrfs_dio_private *dip = bio->bi_private;
8303         blk_status_t err = bio->bi_status;
8304
8305         if (err)
8306                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8307                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8308                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8309                            bio->bi_opf,
8310                            (unsigned long long)bio->bi_iter.bi_sector,
8311                            bio->bi_iter.bi_size, err);
8312
8313         if (dip->subio_endio)
8314                 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8315
8316         if (err) {
8317                 /*
8318                  * We want to perceive the errors flag being set before
8319                  * decrementing the reference count. We don't need a barrier
8320                  * since atomic operations with a return value are fully
8321                  * ordered as per atomic_t.txt
8322                  */
8323                 dip->errors = 1;
8324         }
8325
8326         /* if there are more bios still pending for this dio, just exit */
8327         if (!atomic_dec_and_test(&dip->pending_bios))
8328                 goto out;
8329
8330         if (dip->errors) {
8331                 bio_io_error(dip->orig_bio);
8332         } else {
8333                 dip->dio_bio->bi_status = BLK_STS_OK;
8334                 bio_endio(dip->orig_bio);
8335         }
8336 out:
8337         bio_put(bio);
8338 }
8339
8340 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8341                                                  struct btrfs_dio_private *dip,
8342                                                  struct bio *bio,
8343                                                  u64 file_offset)
8344 {
8345         struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8346         struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8347         blk_status_t ret;
8348
8349         /*
8350          * We load all the csum data we need when we submit
8351          * the first bio to reduce the csum tree search and
8352          * contention.
8353          */
8354         if (dip->logical_offset == file_offset) {
8355                 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8356                                                 file_offset);
8357                 if (ret)
8358                         return ret;
8359         }
8360
8361         if (bio == dip->orig_bio)
8362                 return 0;
8363
8364         file_offset -= dip->logical_offset;
8365         file_offset >>= inode->i_sb->s_blocksize_bits;
8366         io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8367
8368         return 0;
8369 }
8370
8371 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8372                 struct inode *inode, u64 file_offset, int async_submit)
8373 {
8374         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8375         struct btrfs_dio_private *dip = bio->bi_private;
8376         bool write = bio_op(bio) == REQ_OP_WRITE;
8377         blk_status_t ret;
8378
8379         /* Check btrfs_submit_bio_hook() for rules about async submit. */
8380         if (async_submit)
8381                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8382
8383         if (!write) {
8384                 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8385                 if (ret)
8386                         goto err;
8387         }
8388
8389         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8390                 goto map;
8391
8392         if (write && async_submit) {
8393                 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8394                                           file_offset, inode,
8395                                           btrfs_submit_bio_start_direct_io,
8396                                           btrfs_submit_bio_done);
8397                 goto err;
8398         } else if (write) {
8399                 /*
8400                  * If we aren't doing async submit, calculate the csum of the
8401                  * bio now.
8402                  */
8403                 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8404                 if (ret)
8405                         goto err;
8406         } else {
8407                 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8408                                                      file_offset);
8409                 if (ret)
8410                         goto err;
8411         }
8412 map:
8413         ret = btrfs_map_bio(fs_info, bio, 0, 0);
8414 err:
8415         return ret;
8416 }
8417
8418 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8419 {
8420         struct inode *inode = dip->inode;
8421         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8422         struct bio *bio;
8423         struct bio *orig_bio = dip->orig_bio;
8424         u64 start_sector = orig_bio->bi_iter.bi_sector;
8425         u64 file_offset = dip->logical_offset;
8426         u64 map_length;
8427         int async_submit = 0;
8428         u64 submit_len;
8429         int clone_offset = 0;
8430         int clone_len;
8431         int ret;
8432         blk_status_t status;
8433
8434         map_length = orig_bio->bi_iter.bi_size;
8435         submit_len = map_length;
8436         ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8437                               &map_length, NULL, 0);
8438         if (ret)
8439                 return -EIO;
8440
8441         if (map_length >= submit_len) {
8442                 bio = orig_bio;
8443                 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8444                 goto submit;
8445         }
8446
8447         /* async crcs make it difficult to collect full stripe writes. */
8448         if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8449                 async_submit = 0;
8450         else
8451                 async_submit = 1;
8452
8453         /* bio split */
8454         ASSERT(map_length <= INT_MAX);
8455         atomic_inc(&dip->pending_bios);
8456         do {
8457                 clone_len = min_t(int, submit_len, map_length);
8458
8459                 /*
8460                  * This will never fail as it's passing GPF_NOFS and
8461                  * the allocation is backed by btrfs_bioset.
8462                  */
8463                 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8464                                               clone_len);
8465                 bio->bi_private = dip;
8466                 bio->bi_end_io = btrfs_end_dio_bio;
8467                 btrfs_io_bio(bio)->logical = file_offset;
8468
8469                 ASSERT(submit_len >= clone_len);
8470                 submit_len -= clone_len;
8471                 if (submit_len == 0)
8472                         break;
8473
8474                 /*
8475                  * Increase the count before we submit the bio so we know
8476                  * the end IO handler won't happen before we increase the
8477                  * count. Otherwise, the dip might get freed before we're
8478                  * done setting it up.
8479                  */
8480                 atomic_inc(&dip->pending_bios);
8481
8482                 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8483                                                 async_submit);
8484                 if (status) {
8485                         bio_put(bio);
8486                         atomic_dec(&dip->pending_bios);
8487                         goto out_err;
8488                 }
8489
8490                 clone_offset += clone_len;
8491                 start_sector += clone_len >> 9;
8492                 file_offset += clone_len;
8493
8494                 map_length = submit_len;
8495                 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8496                                       start_sector << 9, &map_length, NULL, 0);
8497                 if (ret)
8498                         goto out_err;
8499         } while (submit_len > 0);
8500
8501 submit:
8502         status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8503         if (!status)
8504                 return 0;
8505
8506         bio_put(bio);
8507 out_err:
8508         dip->errors = 1;
8509         /*
8510          * Before atomic variable goto zero, we must  make sure dip->errors is
8511          * perceived to be set. This ordering is ensured by the fact that an
8512          * atomic operations with a return value are fully ordered as per
8513          * atomic_t.txt
8514          */
8515         if (atomic_dec_and_test(&dip->pending_bios))
8516                 bio_io_error(dip->orig_bio);
8517
8518         /* bio_end_io() will handle error, so we needn't return it */
8519         return 0;
8520 }
8521
8522 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8523                                 loff_t file_offset)
8524 {
8525         struct btrfs_dio_private *dip = NULL;
8526         struct bio *bio = NULL;
8527         struct btrfs_io_bio *io_bio;
8528         bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8529         int ret = 0;
8530
8531         bio = btrfs_bio_clone(dio_bio);
8532
8533         dip = kzalloc(sizeof(*dip), GFP_NOFS);
8534         if (!dip) {
8535                 ret = -ENOMEM;
8536                 goto free_ordered;
8537         }
8538
8539         dip->private = dio_bio->bi_private;
8540         dip->inode = inode;
8541         dip->logical_offset = file_offset;
8542         dip->bytes = dio_bio->bi_iter.bi_size;
8543         dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8544         bio->bi_private = dip;
8545         dip->orig_bio = bio;
8546         dip->dio_bio = dio_bio;
8547         atomic_set(&dip->pending_bios, 0);
8548         io_bio = btrfs_io_bio(bio);
8549         io_bio->logical = file_offset;
8550
8551         if (write) {
8552                 bio->bi_end_io = btrfs_endio_direct_write;
8553         } else {
8554                 bio->bi_end_io = btrfs_endio_direct_read;
8555                 dip->subio_endio = btrfs_subio_endio_read;
8556         }
8557
8558         /*
8559          * Reset the range for unsubmitted ordered extents (to a 0 length range)
8560          * even if we fail to submit a bio, because in such case we do the
8561          * corresponding error handling below and it must not be done a second
8562          * time by btrfs_direct_IO().
8563          */
8564         if (write) {
8565                 struct btrfs_dio_data *dio_data = current->journal_info;
8566
8567                 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8568                         dip->bytes;
8569                 dio_data->unsubmitted_oe_range_start =
8570                         dio_data->unsubmitted_oe_range_end;
8571         }
8572
8573         ret = btrfs_submit_direct_hook(dip);
8574         if (!ret)
8575                 return;
8576
8577         if (io_bio->end_io)
8578                 io_bio->end_io(io_bio, ret);
8579
8580 free_ordered:
8581         /*
8582          * If we arrived here it means either we failed to submit the dip
8583          * or we either failed to clone the dio_bio or failed to allocate the
8584          * dip. If we cloned the dio_bio and allocated the dip, we can just
8585          * call bio_endio against our io_bio so that we get proper resource
8586          * cleanup if we fail to submit the dip, otherwise, we must do the
8587          * same as btrfs_endio_direct_[write|read] because we can't call these
8588          * callbacks - they require an allocated dip and a clone of dio_bio.
8589          */
8590         if (bio && dip) {
8591                 bio_io_error(bio);
8592                 /*
8593                  * The end io callbacks free our dip, do the final put on bio
8594                  * and all the cleanup and final put for dio_bio (through
8595                  * dio_end_io()).
8596                  */
8597                 dip = NULL;
8598                 bio = NULL;
8599         } else {
8600                 if (write)
8601                         __endio_write_update_ordered(inode,
8602                                                 file_offset,
8603                                                 dio_bio->bi_iter.bi_size,
8604                                                 false);
8605                 else
8606                         unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8607                               file_offset + dio_bio->bi_iter.bi_size - 1);
8608
8609                 dio_bio->bi_status = BLK_STS_IOERR;
8610                 /*
8611                  * Releases and cleans up our dio_bio, no need to bio_put()
8612                  * nor bio_endio()/bio_io_error() against dio_bio.
8613                  */
8614                 dio_end_io(dio_bio);
8615         }
8616         if (bio)
8617                 bio_put(bio);
8618         kfree(dip);
8619 }
8620
8621 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8622                                const struct iov_iter *iter, loff_t offset)
8623 {
8624         int seg;
8625         int i;
8626         unsigned int blocksize_mask = fs_info->sectorsize - 1;
8627         ssize_t retval = -EINVAL;
8628
8629         if (offset & blocksize_mask)
8630                 goto out;
8631
8632         if (iov_iter_alignment(iter) & blocksize_mask)
8633                 goto out;
8634
8635         /* If this is a write we don't need to check anymore */
8636         if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8637                 return 0;
8638         /*
8639          * Check to make sure we don't have duplicate iov_base's in this
8640          * iovec, if so return EINVAL, otherwise we'll get csum errors
8641          * when reading back.
8642          */
8643         for (seg = 0; seg < iter->nr_segs; seg++) {
8644                 for (i = seg + 1; i < iter->nr_segs; i++) {
8645                         if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8646                                 goto out;
8647                 }
8648         }
8649         retval = 0;
8650 out:
8651         return retval;
8652 }
8653
8654 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8655 {
8656         struct file *file = iocb->ki_filp;
8657         struct inode *inode = file->f_mapping->host;
8658         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8659         struct btrfs_dio_data dio_data = { 0 };
8660         struct extent_changeset *data_reserved = NULL;
8661         loff_t offset = iocb->ki_pos;
8662         size_t count = 0;
8663         int flags = 0;
8664         bool wakeup = true;
8665         bool relock = false;
8666         ssize_t ret;
8667
8668         if (check_direct_IO(fs_info, iter, offset))
8669                 return 0;
8670
8671         inode_dio_begin(inode);
8672
8673         /*
8674          * The generic stuff only does filemap_write_and_wait_range, which
8675          * isn't enough if we've written compressed pages to this area, so
8676          * we need to flush the dirty pages again to make absolutely sure
8677          * that any outstanding dirty pages are on disk.
8678          */
8679         count = iov_iter_count(iter);
8680         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8681                      &BTRFS_I(inode)->runtime_flags))
8682                 filemap_fdatawrite_range(inode->i_mapping, offset,
8683                                          offset + count - 1);
8684
8685         if (iov_iter_rw(iter) == WRITE) {
8686                 /*
8687                  * If the write DIO is beyond the EOF, we need update
8688                  * the isize, but it is protected by i_mutex. So we can
8689                  * not unlock the i_mutex at this case.
8690                  */
8691                 if (offset + count <= inode->i_size) {
8692                         dio_data.overwrite = 1;
8693                         inode_unlock(inode);
8694                         relock = true;
8695                 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8696                         ret = -EAGAIN;
8697                         goto out;
8698                 }
8699                 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8700                                                    offset, count);
8701                 if (ret)
8702                         goto out;
8703
8704                 /*
8705                  * We need to know how many extents we reserved so that we can
8706                  * do the accounting properly if we go over the number we
8707                  * originally calculated.  Abuse current->journal_info for this.
8708                  */
8709                 dio_data.reserve = round_up(count,
8710                                             fs_info->sectorsize);
8711                 dio_data.unsubmitted_oe_range_start = (u64)offset;
8712                 dio_data.unsubmitted_oe_range_end = (u64)offset;
8713                 current->journal_info = &dio_data;
8714                 down_read(&BTRFS_I(inode)->dio_sem);
8715         } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8716                                      &BTRFS_I(inode)->runtime_flags)) {
8717                 inode_dio_end(inode);
8718                 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8719                 wakeup = false;
8720         }
8721
8722         ret = __blockdev_direct_IO(iocb, inode,
8723                                    fs_info->fs_devices->latest_bdev,
8724                                    iter, btrfs_get_blocks_direct, NULL,
8725                                    btrfs_submit_direct, flags);
8726         if (iov_iter_rw(iter) == WRITE) {
8727                 up_read(&BTRFS_I(inode)->dio_sem);
8728                 current->journal_info = NULL;
8729                 if (ret < 0 && ret != -EIOCBQUEUED) {
8730                         if (dio_data.reserve)
8731                                 btrfs_delalloc_release_space(inode, data_reserved,
8732                                         offset, dio_data.reserve, true);
8733                         /*
8734                          * On error we might have left some ordered extents
8735                          * without submitting corresponding bios for them, so
8736                          * cleanup them up to avoid other tasks getting them
8737                          * and waiting for them to complete forever.
8738                          */
8739                         if (dio_data.unsubmitted_oe_range_start <
8740                             dio_data.unsubmitted_oe_range_end)
8741                                 __endio_write_update_ordered(inode,
8742                                         dio_data.unsubmitted_oe_range_start,
8743                                         dio_data.unsubmitted_oe_range_end -
8744                                         dio_data.unsubmitted_oe_range_start,
8745                                         false);
8746                 } else if (ret >= 0 && (size_t)ret < count)
8747                         btrfs_delalloc_release_space(inode, data_reserved,
8748                                         offset, count - (size_t)ret, true);
8749                 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8750         }
8751 out:
8752         if (wakeup)
8753                 inode_dio_end(inode);
8754         if (relock)
8755                 inode_lock(inode);
8756
8757         extent_changeset_free(data_reserved);
8758         return ret;
8759 }
8760
8761 #define BTRFS_FIEMAP_FLAGS      (FIEMAP_FLAG_SYNC)
8762
8763 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8764                 __u64 start, __u64 len)
8765 {
8766         int     ret;
8767
8768         ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8769         if (ret)
8770                 return ret;
8771
8772         return extent_fiemap(inode, fieinfo, start, len);
8773 }
8774
8775 int btrfs_readpage(struct file *file, struct page *page)
8776 {
8777         struct extent_io_tree *tree;
8778         tree = &BTRFS_I(page->mapping->host)->io_tree;
8779         return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8780 }
8781
8782 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8783 {
8784         struct inode *inode = page->mapping->host;
8785         int ret;
8786
8787         if (current->flags & PF_MEMALLOC) {
8788                 redirty_page_for_writepage(wbc, page);
8789                 unlock_page(page);
8790                 return 0;
8791         }
8792
8793         /*
8794          * If we are under memory pressure we will call this directly from the
8795          * VM, we need to make sure we have the inode referenced for the ordered
8796          * extent.  If not just return like we didn't do anything.
8797          */
8798         if (!igrab(inode)) {
8799                 redirty_page_for_writepage(wbc, page);
8800                 return AOP_WRITEPAGE_ACTIVATE;
8801         }
8802         ret = extent_write_full_page(page, wbc);
8803         btrfs_add_delayed_iput(inode);
8804         return ret;
8805 }
8806
8807 static int btrfs_writepages(struct address_space *mapping,
8808                             struct writeback_control *wbc)
8809 {
8810         return extent_writepages(mapping, wbc);
8811 }
8812
8813 static int
8814 btrfs_readpages(struct file *file, struct address_space *mapping,
8815                 struct list_head *pages, unsigned nr_pages)
8816 {
8817         return extent_readpages(mapping, pages, nr_pages);
8818 }
8819
8820 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8821 {
8822         int ret = try_release_extent_mapping(page, gfp_flags);
8823         if (ret == 1) {
8824                 ClearPagePrivate(page);
8825                 set_page_private(page, 0);
8826                 put_page(page);
8827         }
8828         return ret;
8829 }
8830
8831 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8832 {
8833         if (PageWriteback(page) || PageDirty(page))
8834                 return 0;
8835         return __btrfs_releasepage(page, gfp_flags);
8836 }
8837
8838 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8839                                  unsigned int length)
8840 {
8841         struct inode *inode = page->mapping->host;
8842         struct extent_io_tree *tree;
8843         struct btrfs_ordered_extent *ordered;
8844         struct extent_state *cached_state = NULL;
8845         u64 page_start = page_offset(page);
8846         u64 page_end = page_start + PAGE_SIZE - 1;
8847         u64 start;
8848         u64 end;
8849         int inode_evicting = inode->i_state & I_FREEING;
8850
8851         /*
8852          * we have the page locked, so new writeback can't start,
8853          * and the dirty bit won't be cleared while we are here.
8854          *
8855          * Wait for IO on this page so that we can safely clear
8856          * the PagePrivate2 bit and do ordered accounting
8857          */
8858         wait_on_page_writeback(page);
8859
8860         tree = &BTRFS_I(inode)->io_tree;
8861         if (offset) {
8862                 btrfs_releasepage(page, GFP_NOFS);
8863                 return;
8864         }
8865
8866         if (!inode_evicting)
8867                 lock_extent_bits(tree, page_start, page_end, &cached_state);
8868 again:
8869         start = page_start;
8870         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8871                                         page_end - start + 1);
8872         if (ordered) {
8873                 end = min(page_end, ordered->file_offset + ordered->len - 1);
8874                 /*
8875                  * IO on this page will never be started, so we need
8876                  * to account for any ordered extents now
8877                  */
8878                 if (!inode_evicting)
8879                         clear_extent_bit(tree, start, end,
8880                                          EXTENT_DIRTY | EXTENT_DELALLOC |
8881                                          EXTENT_DELALLOC_NEW |
8882                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8883                                          EXTENT_DEFRAG, 1, 0, &cached_state);
8884                 /*
8885                  * whoever cleared the private bit is responsible
8886                  * for the finish_ordered_io
8887                  */
8888                 if (TestClearPagePrivate2(page)) {
8889                         struct btrfs_ordered_inode_tree *tree;
8890                         u64 new_len;
8891
8892                         tree = &BTRFS_I(inode)->ordered_tree;
8893
8894                         spin_lock_irq(&tree->lock);
8895                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8896                         new_len = start - ordered->file_offset;
8897                         if (new_len < ordered->truncated_len)
8898                                 ordered->truncated_len = new_len;
8899                         spin_unlock_irq(&tree->lock);
8900
8901                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
8902                                                            start,
8903                                                            end - start + 1, 1))
8904                                 btrfs_finish_ordered_io(ordered);
8905                 }
8906                 btrfs_put_ordered_extent(ordered);
8907                 if (!inode_evicting) {
8908                         cached_state = NULL;
8909                         lock_extent_bits(tree, start, end,
8910                                          &cached_state);
8911                 }
8912
8913                 start = end + 1;
8914                 if (start < page_end)
8915                         goto again;
8916         }
8917
8918         /*
8919          * Qgroup reserved space handler
8920          * Page here will be either
8921          * 1) Already written to disk
8922          *    In this case, its reserved space is released from data rsv map
8923          *    and will be freed by delayed_ref handler finally.
8924          *    So even we call qgroup_free_data(), it won't decrease reserved
8925          *    space.
8926          * 2) Not written to disk
8927          *    This means the reserved space should be freed here. However,
8928          *    if a truncate invalidates the page (by clearing PageDirty)
8929          *    and the page is accounted for while allocating extent
8930          *    in btrfs_check_data_free_space() we let delayed_ref to
8931          *    free the entire extent.
8932          */
8933         if (PageDirty(page))
8934                 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8935         if (!inode_evicting) {
8936                 clear_extent_bit(tree, page_start, page_end,
8937                                  EXTENT_LOCKED | EXTENT_DIRTY |
8938                                  EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8939                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8940                                  &cached_state);
8941
8942                 __btrfs_releasepage(page, GFP_NOFS);
8943         }
8944
8945         ClearPageChecked(page);
8946         if (PagePrivate(page)) {
8947                 ClearPagePrivate(page);
8948                 set_page_private(page, 0);
8949                 put_page(page);
8950         }
8951 }
8952
8953 /*
8954  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8955  * called from a page fault handler when a page is first dirtied. Hence we must
8956  * be careful to check for EOF conditions here. We set the page up correctly
8957  * for a written page which means we get ENOSPC checking when writing into
8958  * holes and correct delalloc and unwritten extent mapping on filesystems that
8959  * support these features.
8960  *
8961  * We are not allowed to take the i_mutex here so we have to play games to
8962  * protect against truncate races as the page could now be beyond EOF.  Because
8963  * truncate_setsize() writes the inode size before removing pages, once we have
8964  * the page lock we can determine safely if the page is beyond EOF. If it is not
8965  * beyond EOF, then the page is guaranteed safe against truncation until we
8966  * unlock the page.
8967  */
8968 int btrfs_page_mkwrite(struct vm_fault *vmf)
8969 {
8970         struct page *page = vmf->page;
8971         struct inode *inode = file_inode(vmf->vma->vm_file);
8972         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8973         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8974         struct btrfs_ordered_extent *ordered;
8975         struct extent_state *cached_state = NULL;
8976         struct extent_changeset *data_reserved = NULL;
8977         char *kaddr;
8978         unsigned long zero_start;
8979         loff_t size;
8980         int ret;
8981         int reserved = 0;
8982         u64 reserved_space;
8983         u64 page_start;
8984         u64 page_end;
8985         u64 end;
8986
8987         reserved_space = PAGE_SIZE;
8988
8989         sb_start_pagefault(inode->i_sb);
8990         page_start = page_offset(page);
8991         page_end = page_start + PAGE_SIZE - 1;
8992         end = page_end;
8993
8994         /*
8995          * Reserving delalloc space after obtaining the page lock can lead to
8996          * deadlock. For example, if a dirty page is locked by this function
8997          * and the call to btrfs_delalloc_reserve_space() ends up triggering
8998          * dirty page write out, then the btrfs_writepage() function could
8999          * end up waiting indefinitely to get a lock on the page currently
9000          * being processed by btrfs_page_mkwrite() function.
9001          */
9002         ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
9003                                            reserved_space);
9004         if (!ret) {
9005                 ret = file_update_time(vmf->vma->vm_file);
9006                 reserved = 1;
9007         }
9008         if (ret) {
9009                 if (ret == -ENOMEM)
9010                         ret = VM_FAULT_OOM;
9011                 else /* -ENOSPC, -EIO, etc */
9012                         ret = VM_FAULT_SIGBUS;
9013                 if (reserved)
9014                         goto out;
9015                 goto out_noreserve;
9016         }
9017
9018         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
9019 again:
9020         lock_page(page);
9021         size = i_size_read(inode);
9022
9023         if ((page->mapping != inode->i_mapping) ||
9024             (page_start >= size)) {
9025                 /* page got truncated out from underneath us */
9026                 goto out_unlock;
9027         }
9028         wait_on_page_writeback(page);
9029
9030         lock_extent_bits(io_tree, page_start, page_end, &cached_state);
9031         set_page_extent_mapped(page);
9032
9033         /*
9034          * we can't set the delalloc bits if there are pending ordered
9035          * extents.  Drop our locks and wait for them to finish
9036          */
9037         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
9038                         PAGE_SIZE);
9039         if (ordered) {
9040                 unlock_extent_cached(io_tree, page_start, page_end,
9041                                      &cached_state);
9042                 unlock_page(page);
9043                 btrfs_start_ordered_extent(inode, ordered, 1);
9044                 btrfs_put_ordered_extent(ordered);
9045                 goto again;
9046         }
9047
9048         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
9049                 reserved_space = round_up(size - page_start,
9050                                           fs_info->sectorsize);
9051                 if (reserved_space < PAGE_SIZE) {
9052                         end = page_start + reserved_space - 1;
9053                         btrfs_delalloc_release_space(inode, data_reserved,
9054                                         page_start, PAGE_SIZE - reserved_space,
9055                                         true);
9056                 }
9057         }
9058
9059         /*
9060          * page_mkwrite gets called when the page is firstly dirtied after it's
9061          * faulted in, but write(2) could also dirty a page and set delalloc
9062          * bits, thus in this case for space account reason, we still need to
9063          * clear any delalloc bits within this page range since we have to
9064          * reserve data&meta space before lock_page() (see above comments).
9065          */
9066         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
9067                           EXTENT_DIRTY | EXTENT_DELALLOC |
9068                           EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
9069                           0, 0, &cached_state);
9070
9071         ret = btrfs_set_extent_delalloc(inode, page_start, end, 0,
9072                                         &cached_state, 0);
9073         if (ret) {
9074                 unlock_extent_cached(io_tree, page_start, page_end,
9075                                      &cached_state);
9076                 ret = VM_FAULT_SIGBUS;
9077                 goto out_unlock;
9078         }
9079         ret = 0;
9080
9081         /* page is wholly or partially inside EOF */
9082         if (page_start + PAGE_SIZE > size)
9083                 zero_start = size & ~PAGE_MASK;
9084         else
9085                 zero_start = PAGE_SIZE;
9086
9087         if (zero_start != PAGE_SIZE) {
9088                 kaddr = kmap(page);
9089                 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
9090                 flush_dcache_page(page);
9091                 kunmap(page);
9092         }
9093         ClearPageChecked(page);
9094         set_page_dirty(page);
9095         SetPageUptodate(page);
9096
9097         BTRFS_I(inode)->last_trans = fs_info->generation;
9098         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
9099         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
9100
9101         unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
9102
9103 out_unlock:
9104         if (!ret) {
9105                 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
9106                 sb_end_pagefault(inode->i_sb);
9107                 extent_changeset_free(data_reserved);
9108                 return VM_FAULT_LOCKED;
9109         }
9110         unlock_page(page);
9111 out:
9112         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
9113         btrfs_delalloc_release_space(inode, data_reserved, page_start,
9114                                      reserved_space, (ret != 0));
9115 out_noreserve:
9116         sb_end_pagefault(inode->i_sb);
9117         extent_changeset_free(data_reserved);
9118         return ret;
9119 }
9120
9121 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9122 {
9123         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9124         struct btrfs_root *root = BTRFS_I(inode)->root;
9125         struct btrfs_block_rsv *rsv;
9126         int ret = 0;
9127         int err = 0;
9128         struct btrfs_trans_handle *trans;
9129         u64 mask = fs_info->sectorsize - 1;
9130         u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9131
9132         if (!skip_writeback) {
9133                 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9134                                                (u64)-1);
9135                 if (ret)
9136                         return ret;
9137         }
9138
9139         /*
9140          * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
9141          * things going on here:
9142          *
9143          * 1) We need to reserve space to update our inode.
9144          *
9145          * 2) We need to have something to cache all the space that is going to
9146          * be free'd up by the truncate operation, but also have some slack
9147          * space reserved in case it uses space during the truncate (thank you
9148          * very much snapshotting).
9149          *
9150          * And we need these to be separate.  The fact is we can use a lot of
9151          * space doing the truncate, and we have no earthly idea how much space
9152          * we will use, so we need the truncate reservation to be separate so it
9153          * doesn't end up using space reserved for updating the inode.  We also
9154          * need to be able to stop the transaction and start a new one, which
9155          * means we need to be able to update the inode several times, and we
9156          * have no idea of knowing how many times that will be, so we can't just
9157          * reserve 1 item for the entirety of the operation, so that has to be
9158          * done separately as well.
9159          *
9160          * So that leaves us with
9161          *
9162          * 1) rsv - for the truncate reservation, which we will steal from the
9163          * transaction reservation.
9164          * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9165          * updating the inode.
9166          */
9167         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9168         if (!rsv)
9169                 return -ENOMEM;
9170         rsv->size = min_size;
9171         rsv->failfast = 1;
9172
9173         /*
9174          * 1 for the truncate slack space
9175          * 1 for updating the inode.
9176          */
9177         trans = btrfs_start_transaction(root, 2);
9178         if (IS_ERR(trans)) {
9179                 err = PTR_ERR(trans);
9180                 goto out;
9181         }
9182
9183         /* Migrate the slack space for the truncate to our reserve */
9184         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9185                                       min_size, 0);
9186         BUG_ON(ret);
9187
9188         /*
9189          * So if we truncate and then write and fsync we normally would just
9190          * write the extents that changed, which is a problem if we need to
9191          * first truncate that entire inode.  So set this flag so we write out
9192          * all of the extents in the inode to the sync log so we're completely
9193          * safe.
9194          */
9195         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9196         trans->block_rsv = rsv;
9197
9198         while (1) {
9199                 ret = btrfs_truncate_inode_items(trans, root, inode,
9200                                                  inode->i_size,
9201                                                  BTRFS_EXTENT_DATA_KEY);
9202                 trans->block_rsv = &fs_info->trans_block_rsv;
9203                 if (ret != -ENOSPC && ret != -EAGAIN) {
9204                         if (ret < 0)
9205                                 err = ret;
9206                         break;
9207                 }
9208
9209                 ret = btrfs_update_inode(trans, root, inode);
9210                 if (ret) {
9211                         err = ret;
9212                         break;
9213                 }
9214
9215                 btrfs_end_transaction(trans);
9216                 btrfs_btree_balance_dirty(fs_info);
9217
9218                 trans = btrfs_start_transaction(root, 2);
9219                 if (IS_ERR(trans)) {
9220                         ret = err = PTR_ERR(trans);
9221                         trans = NULL;
9222                         break;
9223                 }
9224
9225                 btrfs_block_rsv_release(fs_info, rsv, -1);
9226                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9227                                               rsv, min_size, 0);
9228                 BUG_ON(ret);    /* shouldn't happen */
9229                 trans->block_rsv = rsv;
9230         }
9231
9232         /*
9233          * We can't call btrfs_truncate_block inside a trans handle as we could
9234          * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9235          * we've truncated everything except the last little bit, and can do
9236          * btrfs_truncate_block and then update the disk_i_size.
9237          */
9238         if (ret == NEED_TRUNCATE_BLOCK) {
9239                 btrfs_end_transaction(trans);
9240                 btrfs_btree_balance_dirty(fs_info);
9241
9242                 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9243                 if (ret)
9244                         goto out;
9245                 trans = btrfs_start_transaction(root, 1);
9246                 if (IS_ERR(trans)) {
9247                         ret = PTR_ERR(trans);
9248                         goto out;
9249                 }
9250                 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9251         }
9252
9253         if (trans) {
9254                 trans->block_rsv = &fs_info->trans_block_rsv;
9255                 ret = btrfs_update_inode(trans, root, inode);
9256                 if (ret && !err)
9257                         err = ret;
9258
9259                 ret = btrfs_end_transaction(trans);
9260                 btrfs_btree_balance_dirty(fs_info);
9261         }
9262 out:
9263         btrfs_free_block_rsv(fs_info, rsv);
9264
9265         if (ret && !err)
9266                 err = ret;
9267
9268         return err;
9269 }
9270
9271 /*
9272  * create a new subvolume directory/inode (helper for the ioctl).
9273  */
9274 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9275                              struct btrfs_root *new_root,
9276                              struct btrfs_root *parent_root,
9277                              u64 new_dirid)
9278 {
9279         struct inode *inode;
9280         int err;
9281         u64 index = 0;
9282
9283         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9284                                 new_dirid, new_dirid,
9285                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
9286                                 &index);
9287         if (IS_ERR(inode))
9288                 return PTR_ERR(inode);
9289         inode->i_op = &btrfs_dir_inode_operations;
9290         inode->i_fop = &btrfs_dir_file_operations;
9291
9292         set_nlink(inode, 1);
9293         btrfs_i_size_write(BTRFS_I(inode), 0);
9294         unlock_new_inode(inode);
9295
9296         err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9297         if (err)
9298                 btrfs_err(new_root->fs_info,
9299                           "error inheriting subvolume %llu properties: %d",
9300                           new_root->root_key.objectid, err);
9301
9302         err = btrfs_update_inode(trans, new_root, inode);
9303
9304         iput(inode);
9305         return err;
9306 }
9307
9308 struct inode *btrfs_alloc_inode(struct super_block *sb)
9309 {
9310         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9311         struct btrfs_inode *ei;
9312         struct inode *inode;
9313
9314         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9315         if (!ei)
9316                 return NULL;
9317
9318         ei->root = NULL;
9319         ei->generation = 0;
9320         ei->last_trans = 0;
9321         ei->last_sub_trans = 0;
9322         ei->logged_trans = 0;
9323         ei->delalloc_bytes = 0;
9324         ei->new_delalloc_bytes = 0;
9325         ei->defrag_bytes = 0;
9326         ei->disk_i_size = 0;
9327         ei->flags = 0;
9328         ei->csum_bytes = 0;
9329         ei->index_cnt = (u64)-1;
9330         ei->dir_index = 0;
9331         ei->last_unlink_trans = 0;
9332         ei->last_log_commit = 0;
9333
9334         spin_lock_init(&ei->lock);
9335         ei->outstanding_extents = 0;
9336         if (sb->s_magic != BTRFS_TEST_MAGIC)
9337                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9338                                               BTRFS_BLOCK_RSV_DELALLOC);
9339         ei->runtime_flags = 0;
9340         ei->prop_compress = BTRFS_COMPRESS_NONE;
9341         ei->defrag_compress = BTRFS_COMPRESS_NONE;
9342
9343         ei->delayed_node = NULL;
9344
9345         ei->i_otime.tv_sec = 0;
9346         ei->i_otime.tv_nsec = 0;
9347
9348         inode = &ei->vfs_inode;
9349         extent_map_tree_init(&ei->extent_tree);
9350         extent_io_tree_init(&ei->io_tree, inode);
9351         extent_io_tree_init(&ei->io_failure_tree, inode);
9352         ei->io_tree.track_uptodate = 1;
9353         ei->io_failure_tree.track_uptodate = 1;
9354         atomic_set(&ei->sync_writers, 0);
9355         mutex_init(&ei->log_mutex);
9356         mutex_init(&ei->delalloc_mutex);
9357         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9358         INIT_LIST_HEAD(&ei->delalloc_inodes);
9359         INIT_LIST_HEAD(&ei->delayed_iput);
9360         RB_CLEAR_NODE(&ei->rb_node);
9361         init_rwsem(&ei->dio_sem);
9362
9363         return inode;
9364 }
9365
9366 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9367 void btrfs_test_destroy_inode(struct inode *inode)
9368 {
9369         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9370         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9371 }
9372 #endif
9373
9374 static void btrfs_i_callback(struct rcu_head *head)
9375 {
9376         struct inode *inode = container_of(head, struct inode, i_rcu);
9377         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9378 }
9379
9380 void btrfs_destroy_inode(struct inode *inode)
9381 {
9382         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9383         struct btrfs_ordered_extent *ordered;
9384         struct btrfs_root *root = BTRFS_I(inode)->root;
9385
9386         WARN_ON(!hlist_empty(&inode->i_dentry));
9387         WARN_ON(inode->i_data.nrpages);
9388         WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9389         WARN_ON(BTRFS_I(inode)->block_rsv.size);
9390         WARN_ON(BTRFS_I(inode)->outstanding_extents);
9391         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9392         WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9393         WARN_ON(BTRFS_I(inode)->csum_bytes);
9394         WARN_ON(BTRFS_I(inode)->defrag_bytes);
9395
9396         /*
9397          * This can happen where we create an inode, but somebody else also
9398          * created the same inode and we need to destroy the one we already
9399          * created.
9400          */
9401         if (!root)
9402                 goto free;
9403
9404         while (1) {
9405                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9406                 if (!ordered)
9407                         break;
9408                 else {
9409                         btrfs_err(fs_info,
9410                                   "found ordered extent %llu %llu on inode cleanup",
9411                                   ordered->file_offset, ordered->len);
9412                         btrfs_remove_ordered_extent(inode, ordered);
9413                         btrfs_put_ordered_extent(ordered);
9414                         btrfs_put_ordered_extent(ordered);
9415                 }
9416         }
9417         btrfs_qgroup_check_reserved_leak(inode);
9418         inode_tree_del(inode);
9419         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9420 free:
9421         call_rcu(&inode->i_rcu, btrfs_i_callback);
9422 }
9423
9424 int btrfs_drop_inode(struct inode *inode)
9425 {
9426         struct btrfs_root *root = BTRFS_I(inode)->root;
9427
9428         if (root == NULL)
9429                 return 1;
9430
9431         /* the snap/subvol tree is on deleting */
9432         if (btrfs_root_refs(&root->root_item) == 0)
9433                 return 1;
9434         else
9435                 return generic_drop_inode(inode);
9436 }
9437
9438 static void init_once(void *foo)
9439 {
9440         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9441
9442         inode_init_once(&ei->vfs_inode);
9443 }
9444
9445 void __cold btrfs_destroy_cachep(void)
9446 {
9447         /*
9448          * Make sure all delayed rcu free inodes are flushed before we
9449          * destroy cache.
9450          */
9451         rcu_barrier();
9452         kmem_cache_destroy(btrfs_inode_cachep);
9453         kmem_cache_destroy(btrfs_trans_handle_cachep);
9454         kmem_cache_destroy(btrfs_path_cachep);
9455         kmem_cache_destroy(btrfs_free_space_cachep);
9456 }
9457
9458 int __init btrfs_init_cachep(void)
9459 {
9460         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9461                         sizeof(struct btrfs_inode), 0,
9462                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9463                         init_once);
9464         if (!btrfs_inode_cachep)
9465                 goto fail;
9466
9467         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9468                         sizeof(struct btrfs_trans_handle), 0,
9469                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9470         if (!btrfs_trans_handle_cachep)
9471                 goto fail;
9472
9473         btrfs_path_cachep = kmem_cache_create("btrfs_path",
9474                         sizeof(struct btrfs_path), 0,
9475                         SLAB_MEM_SPREAD, NULL);
9476         if (!btrfs_path_cachep)
9477                 goto fail;
9478
9479         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9480                         sizeof(struct btrfs_free_space), 0,
9481                         SLAB_MEM_SPREAD, NULL);
9482         if (!btrfs_free_space_cachep)
9483                 goto fail;
9484
9485         return 0;
9486 fail:
9487         btrfs_destroy_cachep();
9488         return -ENOMEM;
9489 }
9490
9491 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9492                          u32 request_mask, unsigned int flags)
9493 {
9494         u64 delalloc_bytes;
9495         struct inode *inode = d_inode(path->dentry);
9496         u32 blocksize = inode->i_sb->s_blocksize;
9497         u32 bi_flags = BTRFS_I(inode)->flags;
9498
9499         stat->result_mask |= STATX_BTIME;
9500         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9501         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9502         if (bi_flags & BTRFS_INODE_APPEND)
9503                 stat->attributes |= STATX_ATTR_APPEND;
9504         if (bi_flags & BTRFS_INODE_COMPRESS)
9505                 stat->attributes |= STATX_ATTR_COMPRESSED;
9506         if (bi_flags & BTRFS_INODE_IMMUTABLE)
9507                 stat->attributes |= STATX_ATTR_IMMUTABLE;
9508         if (bi_flags & BTRFS_INODE_NODUMP)
9509                 stat->attributes |= STATX_ATTR_NODUMP;
9510
9511         stat->attributes_mask |= (STATX_ATTR_APPEND |
9512                                   STATX_ATTR_COMPRESSED |
9513                                   STATX_ATTR_IMMUTABLE |
9514                                   STATX_ATTR_NODUMP);
9515
9516         generic_fillattr(inode, stat);
9517         stat->dev = BTRFS_I(inode)->root->anon_dev;
9518
9519         spin_lock(&BTRFS_I(inode)->lock);
9520         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9521         spin_unlock(&BTRFS_I(inode)->lock);
9522         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9523                         ALIGN(delalloc_bytes, blocksize)) >> 9;
9524         return 0;
9525 }
9526
9527 static int btrfs_rename_exchange(struct inode *old_dir,
9528                               struct dentry *old_dentry,
9529                               struct inode *new_dir,
9530                               struct dentry *new_dentry)
9531 {
9532         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9533         struct btrfs_trans_handle *trans;
9534         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9535         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9536         struct inode *new_inode = new_dentry->d_inode;
9537         struct inode *old_inode = old_dentry->d_inode;
9538         struct timespec ctime = current_time(old_inode);
9539         struct dentry *parent;
9540         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9541         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9542         u64 old_idx = 0;
9543         u64 new_idx = 0;
9544         u64 root_objectid;
9545         int ret;
9546         bool root_log_pinned = false;
9547         bool dest_log_pinned = false;
9548
9549         /* we only allow rename subvolume link between subvolumes */
9550         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9551                 return -EXDEV;
9552
9553         /* close the race window with snapshot create/destroy ioctl */
9554         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9555                 down_read(&fs_info->subvol_sem);
9556         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9557                 down_read(&fs_info->subvol_sem);
9558
9559         /*
9560          * We want to reserve the absolute worst case amount of items.  So if
9561          * both inodes are subvols and we need to unlink them then that would
9562          * require 4 item modifications, but if they are both normal inodes it
9563          * would require 5 item modifications, so we'll assume their normal
9564          * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9565          * should cover the worst case number of items we'll modify.
9566          */
9567         trans = btrfs_start_transaction(root, 12);
9568         if (IS_ERR(trans)) {
9569                 ret = PTR_ERR(trans);
9570                 goto out_notrans;
9571         }
9572
9573         /*
9574          * We need to find a free sequence number both in the source and
9575          * in the destination directory for the exchange.
9576          */
9577         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9578         if (ret)
9579                 goto out_fail;
9580         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9581         if (ret)
9582                 goto out_fail;
9583
9584         BTRFS_I(old_inode)->dir_index = 0ULL;
9585         BTRFS_I(new_inode)->dir_index = 0ULL;
9586
9587         /* Reference for the source. */
9588         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9589                 /* force full log commit if subvolume involved. */
9590                 btrfs_set_log_full_commit(fs_info, trans);
9591         } else {
9592                 btrfs_pin_log_trans(root);
9593                 root_log_pinned = true;
9594                 ret = btrfs_insert_inode_ref(trans, dest,
9595                                              new_dentry->d_name.name,
9596                                              new_dentry->d_name.len,
9597                                              old_ino,
9598                                              btrfs_ino(BTRFS_I(new_dir)),
9599                                              old_idx);
9600                 if (ret)
9601                         goto out_fail;
9602         }
9603
9604         /* And now for the dest. */
9605         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9606                 /* force full log commit if subvolume involved. */
9607                 btrfs_set_log_full_commit(fs_info, trans);
9608         } else {
9609                 btrfs_pin_log_trans(dest);
9610                 dest_log_pinned = true;
9611                 ret = btrfs_insert_inode_ref(trans, root,
9612                                              old_dentry->d_name.name,
9613                                              old_dentry->d_name.len,
9614                                              new_ino,
9615                                              btrfs_ino(BTRFS_I(old_dir)),
9616                                              new_idx);
9617                 if (ret)
9618                         goto out_fail;
9619         }
9620
9621         /* Update inode version and ctime/mtime. */
9622         inode_inc_iversion(old_dir);
9623         inode_inc_iversion(new_dir);
9624         inode_inc_iversion(old_inode);
9625         inode_inc_iversion(new_inode);
9626         old_dir->i_ctime = old_dir->i_mtime = ctime;
9627         new_dir->i_ctime = new_dir->i_mtime = ctime;
9628         old_inode->i_ctime = ctime;
9629         new_inode->i_ctime = ctime;
9630
9631         if (old_dentry->d_parent != new_dentry->d_parent) {
9632                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9633                                 BTRFS_I(old_inode), 1);
9634                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9635                                 BTRFS_I(new_inode), 1);
9636         }
9637
9638         /* src is a subvolume */
9639         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9640                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9641                 ret = btrfs_unlink_subvol(trans, root, old_dir,
9642                                           root_objectid,
9643                                           old_dentry->d_name.name,
9644                                           old_dentry->d_name.len);
9645         } else { /* src is an inode */
9646                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9647                                            BTRFS_I(old_dentry->d_inode),
9648                                            old_dentry->d_name.name,
9649                                            old_dentry->d_name.len);
9650                 if (!ret)
9651                         ret = btrfs_update_inode(trans, root, old_inode);
9652         }
9653         if (ret) {
9654                 btrfs_abort_transaction(trans, ret);
9655                 goto out_fail;
9656         }
9657
9658         /* dest is a subvolume */
9659         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9660                 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9661                 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9662                                           root_objectid,
9663                                           new_dentry->d_name.name,
9664                                           new_dentry->d_name.len);
9665         } else { /* dest is an inode */
9666                 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9667                                            BTRFS_I(new_dentry->d_inode),
9668                                            new_dentry->d_name.name,
9669                                            new_dentry->d_name.len);
9670                 if (!ret)
9671                         ret = btrfs_update_inode(trans, dest, new_inode);
9672         }
9673         if (ret) {
9674                 btrfs_abort_transaction(trans, ret);
9675                 goto out_fail;
9676         }
9677
9678         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9679                              new_dentry->d_name.name,
9680                              new_dentry->d_name.len, 0, old_idx);
9681         if (ret) {
9682                 btrfs_abort_transaction(trans, ret);
9683                 goto out_fail;
9684         }
9685
9686         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9687                              old_dentry->d_name.name,
9688                              old_dentry->d_name.len, 0, new_idx);
9689         if (ret) {
9690                 btrfs_abort_transaction(trans, ret);
9691                 goto out_fail;
9692         }
9693
9694         if (old_inode->i_nlink == 1)
9695                 BTRFS_I(old_inode)->dir_index = old_idx;
9696         if (new_inode->i_nlink == 1)
9697                 BTRFS_I(new_inode)->dir_index = new_idx;
9698
9699         if (root_log_pinned) {
9700                 parent = new_dentry->d_parent;
9701                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9702                                 parent);
9703                 btrfs_end_log_trans(root);
9704                 root_log_pinned = false;
9705         }
9706         if (dest_log_pinned) {
9707                 parent = old_dentry->d_parent;
9708                 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9709                                 parent);
9710                 btrfs_end_log_trans(dest);
9711                 dest_log_pinned = false;
9712         }
9713 out_fail:
9714         /*
9715          * If we have pinned a log and an error happened, we unpin tasks
9716          * trying to sync the log and force them to fallback to a transaction
9717          * commit if the log currently contains any of the inodes involved in
9718          * this rename operation (to ensure we do not persist a log with an
9719          * inconsistent state for any of these inodes or leading to any
9720          * inconsistencies when replayed). If the transaction was aborted, the
9721          * abortion reason is propagated to userspace when attempting to commit
9722          * the transaction. If the log does not contain any of these inodes, we
9723          * allow the tasks to sync it.
9724          */
9725         if (ret && (root_log_pinned || dest_log_pinned)) {
9726                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9727                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9728                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9729                     (new_inode &&
9730                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9731                         btrfs_set_log_full_commit(fs_info, trans);
9732
9733                 if (root_log_pinned) {
9734                         btrfs_end_log_trans(root);
9735                         root_log_pinned = false;
9736                 }
9737                 if (dest_log_pinned) {
9738                         btrfs_end_log_trans(dest);
9739                         dest_log_pinned = false;
9740                 }
9741         }
9742         ret = btrfs_end_transaction(trans);
9743 out_notrans:
9744         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9745                 up_read(&fs_info->subvol_sem);
9746         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9747                 up_read(&fs_info->subvol_sem);
9748
9749         return ret;
9750 }
9751
9752 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9753                                      struct btrfs_root *root,
9754                                      struct inode *dir,
9755                                      struct dentry *dentry)
9756 {
9757         int ret;
9758         struct inode *inode;
9759         u64 objectid;
9760         u64 index;
9761
9762         ret = btrfs_find_free_ino(root, &objectid);
9763         if (ret)
9764                 return ret;
9765
9766         inode = btrfs_new_inode(trans, root, dir,
9767                                 dentry->d_name.name,
9768                                 dentry->d_name.len,
9769                                 btrfs_ino(BTRFS_I(dir)),
9770                                 objectid,
9771                                 S_IFCHR | WHITEOUT_MODE,
9772                                 &index);
9773
9774         if (IS_ERR(inode)) {
9775                 ret = PTR_ERR(inode);
9776                 return ret;
9777         }
9778
9779         inode->i_op = &btrfs_special_inode_operations;
9780         init_special_inode(inode, inode->i_mode,
9781                 WHITEOUT_DEV);
9782
9783         ret = btrfs_init_inode_security(trans, inode, dir,
9784                                 &dentry->d_name);
9785         if (ret)
9786                 goto out;
9787
9788         ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9789                                 BTRFS_I(inode), 0, index);
9790         if (ret)
9791                 goto out;
9792
9793         ret = btrfs_update_inode(trans, root, inode);
9794 out:
9795         unlock_new_inode(inode);
9796         if (ret)
9797                 inode_dec_link_count(inode);
9798         iput(inode);
9799
9800         return ret;
9801 }
9802
9803 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9804                            struct inode *new_dir, struct dentry *new_dentry,
9805                            unsigned int flags)
9806 {
9807         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9808         struct btrfs_trans_handle *trans;
9809         unsigned int trans_num_items;
9810         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9811         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9812         struct inode *new_inode = d_inode(new_dentry);
9813         struct inode *old_inode = d_inode(old_dentry);
9814         u64 index = 0;
9815         u64 root_objectid;
9816         int ret;
9817         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9818         bool log_pinned = false;
9819
9820         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9821                 return -EPERM;
9822
9823         /* we only allow rename subvolume link between subvolumes */
9824         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9825                 return -EXDEV;
9826
9827         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9828             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9829                 return -ENOTEMPTY;
9830
9831         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9832             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9833                 return -ENOTEMPTY;
9834
9835
9836         /* check for collisions, even if the  name isn't there */
9837         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9838                              new_dentry->d_name.name,
9839                              new_dentry->d_name.len);
9840
9841         if (ret) {
9842                 if (ret == -EEXIST) {
9843                         /* we shouldn't get
9844                          * eexist without a new_inode */
9845                         if (WARN_ON(!new_inode)) {
9846                                 return ret;
9847                         }
9848                 } else {
9849                         /* maybe -EOVERFLOW */
9850                         return ret;
9851                 }
9852         }
9853         ret = 0;
9854
9855         /*
9856          * we're using rename to replace one file with another.  Start IO on it
9857          * now so  we don't add too much work to the end of the transaction
9858          */
9859         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9860                 filemap_flush(old_inode->i_mapping);
9861
9862         /* close the racy window with snapshot create/destroy ioctl */
9863         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9864                 down_read(&fs_info->subvol_sem);
9865         /*
9866          * We want to reserve the absolute worst case amount of items.  So if
9867          * both inodes are subvols and we need to unlink them then that would
9868          * require 4 item modifications, but if they are both normal inodes it
9869          * would require 5 item modifications, so we'll assume they are normal
9870          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9871          * should cover the worst case number of items we'll modify.
9872          * If our rename has the whiteout flag, we need more 5 units for the
9873          * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9874          * when selinux is enabled).
9875          */
9876         trans_num_items = 11;
9877         if (flags & RENAME_WHITEOUT)
9878                 trans_num_items += 5;
9879         trans = btrfs_start_transaction(root, trans_num_items);
9880         if (IS_ERR(trans)) {
9881                 ret = PTR_ERR(trans);
9882                 goto out_notrans;
9883         }
9884
9885         if (dest != root)
9886                 btrfs_record_root_in_trans(trans, dest);
9887
9888         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9889         if (ret)
9890                 goto out_fail;
9891
9892         BTRFS_I(old_inode)->dir_index = 0ULL;
9893         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9894                 /* force full log commit if subvolume involved. */
9895                 btrfs_set_log_full_commit(fs_info, trans);
9896         } else {
9897                 btrfs_pin_log_trans(root);
9898                 log_pinned = true;
9899                 ret = btrfs_insert_inode_ref(trans, dest,
9900                                              new_dentry->d_name.name,
9901                                              new_dentry->d_name.len,
9902                                              old_ino,
9903                                              btrfs_ino(BTRFS_I(new_dir)), index);
9904                 if (ret)
9905                         goto out_fail;
9906         }
9907
9908         inode_inc_iversion(old_dir);
9909         inode_inc_iversion(new_dir);
9910         inode_inc_iversion(old_inode);
9911         old_dir->i_ctime = old_dir->i_mtime =
9912         new_dir->i_ctime = new_dir->i_mtime =
9913         old_inode->i_ctime = current_time(old_dir);
9914
9915         if (old_dentry->d_parent != new_dentry->d_parent)
9916                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9917                                 BTRFS_I(old_inode), 1);
9918
9919         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9920                 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9921                 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9922                                         old_dentry->d_name.name,
9923                                         old_dentry->d_name.len);
9924         } else {
9925                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9926                                         BTRFS_I(d_inode(old_dentry)),
9927                                         old_dentry->d_name.name,
9928                                         old_dentry->d_name.len);
9929                 if (!ret)
9930                         ret = btrfs_update_inode(trans, root, old_inode);
9931         }
9932         if (ret) {
9933                 btrfs_abort_transaction(trans, ret);
9934                 goto out_fail;
9935         }
9936
9937         if (new_inode) {
9938                 inode_inc_iversion(new_inode);
9939                 new_inode->i_ctime = current_time(new_inode);
9940                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9941                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9942                         root_objectid = BTRFS_I(new_inode)->location.objectid;
9943                         ret = btrfs_unlink_subvol(trans, dest, new_dir,
9944                                                 root_objectid,
9945                                                 new_dentry->d_name.name,
9946                                                 new_dentry->d_name.len);
9947                         BUG_ON(new_inode->i_nlink == 0);
9948                 } else {
9949                         ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9950                                                  BTRFS_I(d_inode(new_dentry)),
9951                                                  new_dentry->d_name.name,
9952                                                  new_dentry->d_name.len);
9953                 }
9954                 if (!ret && new_inode->i_nlink == 0)
9955                         ret = btrfs_orphan_add(trans,
9956                                         BTRFS_I(d_inode(new_dentry)));
9957                 if (ret) {
9958                         btrfs_abort_transaction(trans, ret);
9959                         goto out_fail;
9960                 }
9961         }
9962
9963         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9964                              new_dentry->d_name.name,
9965                              new_dentry->d_name.len, 0, index);
9966         if (ret) {
9967                 btrfs_abort_transaction(trans, ret);
9968                 goto out_fail;
9969         }
9970
9971         if (old_inode->i_nlink == 1)
9972                 BTRFS_I(old_inode)->dir_index = index;
9973
9974         if (log_pinned) {
9975                 struct dentry *parent = new_dentry->d_parent;
9976
9977                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9978                                 parent);
9979                 btrfs_end_log_trans(root);
9980                 log_pinned = false;
9981         }
9982
9983         if (flags & RENAME_WHITEOUT) {
9984                 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9985                                                 old_dentry);
9986
9987                 if (ret) {
9988                         btrfs_abort_transaction(trans, ret);
9989                         goto out_fail;
9990                 }
9991         }
9992 out_fail:
9993         /*
9994          * If we have pinned the log and an error happened, we unpin tasks
9995          * trying to sync the log and force them to fallback to a transaction
9996          * commit if the log currently contains any of the inodes involved in
9997          * this rename operation (to ensure we do not persist a log with an
9998          * inconsistent state for any of these inodes or leading to any
9999          * inconsistencies when replayed). If the transaction was aborted, the
10000          * abortion reason is propagated to userspace when attempting to commit
10001          * the transaction. If the log does not contain any of these inodes, we
10002          * allow the tasks to sync it.
10003          */
10004         if (ret && log_pinned) {
10005                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
10006                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
10007                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
10008                     (new_inode &&
10009                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
10010                         btrfs_set_log_full_commit(fs_info, trans);
10011
10012                 btrfs_end_log_trans(root);
10013                 log_pinned = false;
10014         }
10015         btrfs_end_transaction(trans);
10016 out_notrans:
10017         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
10018                 up_read(&fs_info->subvol_sem);
10019
10020         return ret;
10021 }
10022
10023 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
10024                          struct inode *new_dir, struct dentry *new_dentry,
10025                          unsigned int flags)
10026 {
10027         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
10028                 return -EINVAL;
10029
10030         if (flags & RENAME_EXCHANGE)
10031                 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
10032                                           new_dentry);
10033
10034         return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
10035 }
10036
10037 struct btrfs_delalloc_work {
10038         struct inode *inode;
10039         struct completion completion;
10040         struct list_head list;
10041         struct btrfs_work work;
10042 };
10043
10044 static void btrfs_run_delalloc_work(struct btrfs_work *work)
10045 {
10046         struct btrfs_delalloc_work *delalloc_work;
10047         struct inode *inode;
10048
10049         delalloc_work = container_of(work, struct btrfs_delalloc_work,
10050                                      work);
10051         inode = delalloc_work->inode;
10052         filemap_flush(inode->i_mapping);
10053         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
10054                                 &BTRFS_I(inode)->runtime_flags))
10055                 filemap_flush(inode->i_mapping);
10056
10057         iput(inode);
10058         complete(&delalloc_work->completion);
10059 }
10060
10061 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
10062 {
10063         struct btrfs_delalloc_work *work;
10064
10065         work = kmalloc(sizeof(*work), GFP_NOFS);
10066         if (!work)
10067                 return NULL;
10068
10069         init_completion(&work->completion);
10070         INIT_LIST_HEAD(&work->list);
10071         work->inode = inode;
10072         WARN_ON_ONCE(!inode);
10073         btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
10074                         btrfs_run_delalloc_work, NULL, NULL);
10075
10076         return work;
10077 }
10078
10079 /*
10080  * some fairly slow code that needs optimization. This walks the list
10081  * of all the inodes with pending delalloc and forces them to disk.
10082  */
10083 static int start_delalloc_inodes(struct btrfs_root *root, int nr)
10084 {
10085         struct btrfs_inode *binode;
10086         struct inode *inode;
10087         struct btrfs_delalloc_work *work, *next;
10088         struct list_head works;
10089         struct list_head splice;
10090         int ret = 0;
10091
10092         INIT_LIST_HEAD(&works);
10093         INIT_LIST_HEAD(&splice);
10094
10095         mutex_lock(&root->delalloc_mutex);
10096         spin_lock(&root->delalloc_lock);
10097         list_splice_init(&root->delalloc_inodes, &splice);
10098         while (!list_empty(&splice)) {
10099                 binode = list_entry(splice.next, struct btrfs_inode,
10100                                     delalloc_inodes);
10101
10102                 list_move_tail(&binode->delalloc_inodes,
10103                                &root->delalloc_inodes);
10104                 inode = igrab(&binode->vfs_inode);
10105                 if (!inode) {
10106                         cond_resched_lock(&root->delalloc_lock);
10107                         continue;
10108                 }
10109                 spin_unlock(&root->delalloc_lock);
10110
10111                 work = btrfs_alloc_delalloc_work(inode);
10112                 if (!work) {
10113                         iput(inode);
10114                         ret = -ENOMEM;
10115                         goto out;
10116                 }
10117                 list_add_tail(&work->list, &works);
10118                 btrfs_queue_work(root->fs_info->flush_workers,
10119                                  &work->work);
10120                 ret++;
10121                 if (nr != -1 && ret >= nr)
10122                         goto out;
10123                 cond_resched();
10124                 spin_lock(&root->delalloc_lock);
10125         }
10126         spin_unlock(&root->delalloc_lock);
10127
10128 out:
10129         list_for_each_entry_safe(work, next, &works, list) {
10130                 list_del_init(&work->list);
10131                 wait_for_completion(&work->completion);
10132                 kfree(work);
10133         }
10134
10135         if (!list_empty(&splice)) {
10136                 spin_lock(&root->delalloc_lock);
10137                 list_splice_tail(&splice, &root->delalloc_inodes);
10138                 spin_unlock(&root->delalloc_lock);
10139         }
10140         mutex_unlock(&root->delalloc_mutex);
10141         return ret;
10142 }
10143
10144 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
10145 {
10146         struct btrfs_fs_info *fs_info = root->fs_info;
10147         int ret;
10148
10149         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10150                 return -EROFS;
10151
10152         ret = start_delalloc_inodes(root, -1);
10153         if (ret > 0)
10154                 ret = 0;
10155         return ret;
10156 }
10157
10158 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10159 {
10160         struct btrfs_root *root;
10161         struct list_head splice;
10162         int ret;
10163
10164         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10165                 return -EROFS;
10166
10167         INIT_LIST_HEAD(&splice);
10168
10169         mutex_lock(&fs_info->delalloc_root_mutex);
10170         spin_lock(&fs_info->delalloc_root_lock);
10171         list_splice_init(&fs_info->delalloc_roots, &splice);
10172         while (!list_empty(&splice) && nr) {
10173                 root = list_first_entry(&splice, struct btrfs_root,
10174                                         delalloc_root);
10175                 root = btrfs_grab_fs_root(root);
10176                 BUG_ON(!root);
10177                 list_move_tail(&root->delalloc_root,
10178                                &fs_info->delalloc_roots);
10179                 spin_unlock(&fs_info->delalloc_root_lock);
10180
10181                 ret = start_delalloc_inodes(root, nr);
10182                 btrfs_put_fs_root(root);
10183                 if (ret < 0)
10184                         goto out;
10185
10186                 if (nr != -1) {
10187                         nr -= ret;
10188                         WARN_ON(nr < 0);
10189                 }
10190                 spin_lock(&fs_info->delalloc_root_lock);
10191         }
10192         spin_unlock(&fs_info->delalloc_root_lock);
10193
10194         ret = 0;
10195 out:
10196         if (!list_empty(&splice)) {
10197                 spin_lock(&fs_info->delalloc_root_lock);
10198                 list_splice_tail(&splice, &fs_info->delalloc_roots);
10199                 spin_unlock(&fs_info->delalloc_root_lock);
10200         }
10201         mutex_unlock(&fs_info->delalloc_root_mutex);
10202         return ret;
10203 }
10204
10205 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10206                          const char *symname)
10207 {
10208         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10209         struct btrfs_trans_handle *trans;
10210         struct btrfs_root *root = BTRFS_I(dir)->root;
10211         struct btrfs_path *path;
10212         struct btrfs_key key;
10213         struct inode *inode = NULL;
10214         int err;
10215         int drop_inode = 0;
10216         u64 objectid;
10217         u64 index = 0;
10218         int name_len;
10219         int datasize;
10220         unsigned long ptr;
10221         struct btrfs_file_extent_item *ei;
10222         struct extent_buffer *leaf;
10223
10224         name_len = strlen(symname);
10225         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10226                 return -ENAMETOOLONG;
10227
10228         /*
10229          * 2 items for inode item and ref
10230          * 2 items for dir items
10231          * 1 item for updating parent inode item
10232          * 1 item for the inline extent item
10233          * 1 item for xattr if selinux is on
10234          */
10235         trans = btrfs_start_transaction(root, 7);
10236         if (IS_ERR(trans))
10237                 return PTR_ERR(trans);
10238
10239         err = btrfs_find_free_ino(root, &objectid);
10240         if (err)
10241                 goto out_unlock;
10242
10243         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10244                                 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10245                                 objectid, S_IFLNK|S_IRWXUGO, &index);
10246         if (IS_ERR(inode)) {
10247                 err = PTR_ERR(inode);
10248                 goto out_unlock;
10249         }
10250
10251         /*
10252         * If the active LSM wants to access the inode during
10253         * d_instantiate it needs these. Smack checks to see
10254         * if the filesystem supports xattrs by looking at the
10255         * ops vector.
10256         */
10257         inode->i_fop = &btrfs_file_operations;
10258         inode->i_op = &btrfs_file_inode_operations;
10259         inode->i_mapping->a_ops = &btrfs_aops;
10260         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10261
10262         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10263         if (err)
10264                 goto out_unlock_inode;
10265
10266         path = btrfs_alloc_path();
10267         if (!path) {
10268                 err = -ENOMEM;
10269                 goto out_unlock_inode;
10270         }
10271         key.objectid = btrfs_ino(BTRFS_I(inode));
10272         key.offset = 0;
10273         key.type = BTRFS_EXTENT_DATA_KEY;
10274         datasize = btrfs_file_extent_calc_inline_size(name_len);
10275         err = btrfs_insert_empty_item(trans, root, path, &key,
10276                                       datasize);
10277         if (err) {
10278                 btrfs_free_path(path);
10279                 goto out_unlock_inode;
10280         }
10281         leaf = path->nodes[0];
10282         ei = btrfs_item_ptr(leaf, path->slots[0],
10283                             struct btrfs_file_extent_item);
10284         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10285         btrfs_set_file_extent_type(leaf, ei,
10286                                    BTRFS_FILE_EXTENT_INLINE);
10287         btrfs_set_file_extent_encryption(leaf, ei, 0);
10288         btrfs_set_file_extent_compression(leaf, ei, 0);
10289         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10290         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10291
10292         ptr = btrfs_file_extent_inline_start(ei);
10293         write_extent_buffer(leaf, symname, ptr, name_len);
10294         btrfs_mark_buffer_dirty(leaf);
10295         btrfs_free_path(path);
10296
10297         inode->i_op = &btrfs_symlink_inode_operations;
10298         inode_nohighmem(inode);
10299         inode->i_mapping->a_ops = &btrfs_symlink_aops;
10300         inode_set_bytes(inode, name_len);
10301         btrfs_i_size_write(BTRFS_I(inode), name_len);
10302         err = btrfs_update_inode(trans, root, inode);
10303         /*
10304          * Last step, add directory indexes for our symlink inode. This is the
10305          * last step to avoid extra cleanup of these indexes if an error happens
10306          * elsewhere above.
10307          */
10308         if (!err)
10309                 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10310                                 BTRFS_I(inode), 0, index);
10311         if (err) {
10312                 drop_inode = 1;
10313                 goto out_unlock_inode;
10314         }
10315
10316         d_instantiate_new(dentry, inode);
10317
10318 out_unlock:
10319         btrfs_end_transaction(trans);
10320         if (drop_inode) {
10321                 inode_dec_link_count(inode);
10322                 iput(inode);
10323         }
10324         btrfs_btree_balance_dirty(fs_info);
10325         return err;
10326
10327 out_unlock_inode:
10328         drop_inode = 1;
10329         unlock_new_inode(inode);
10330         goto out_unlock;
10331 }
10332
10333 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10334                                        u64 start, u64 num_bytes, u64 min_size,
10335                                        loff_t actual_len, u64 *alloc_hint,
10336                                        struct btrfs_trans_handle *trans)
10337 {
10338         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10339         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10340         struct extent_map *em;
10341         struct btrfs_root *root = BTRFS_I(inode)->root;
10342         struct btrfs_key ins;
10343         u64 cur_offset = start;
10344         u64 i_size;
10345         u64 cur_bytes;
10346         u64 last_alloc = (u64)-1;
10347         int ret = 0;
10348         bool own_trans = true;
10349         u64 end = start + num_bytes - 1;
10350
10351         if (trans)
10352                 own_trans = false;
10353         while (num_bytes > 0) {
10354                 if (own_trans) {
10355                         trans = btrfs_start_transaction(root, 3);
10356                         if (IS_ERR(trans)) {
10357                                 ret = PTR_ERR(trans);
10358                                 break;
10359                         }
10360                 }
10361
10362                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10363                 cur_bytes = max(cur_bytes, min_size);
10364                 /*
10365                  * If we are severely fragmented we could end up with really
10366                  * small allocations, so if the allocator is returning small
10367                  * chunks lets make its job easier by only searching for those
10368                  * sized chunks.
10369                  */
10370                 cur_bytes = min(cur_bytes, last_alloc);
10371                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10372                                 min_size, 0, *alloc_hint, &ins, 1, 0);
10373                 if (ret) {
10374                         if (own_trans)
10375                                 btrfs_end_transaction(trans);
10376                         break;
10377                 }
10378                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10379
10380                 last_alloc = ins.offset;
10381                 ret = insert_reserved_file_extent(trans, inode,
10382                                                   cur_offset, ins.objectid,
10383                                                   ins.offset, ins.offset,
10384                                                   ins.offset, 0, 0, 0,
10385                                                   BTRFS_FILE_EXTENT_PREALLOC);
10386                 if (ret) {
10387                         btrfs_free_reserved_extent(fs_info, ins.objectid,
10388                                                    ins.offset, 0);
10389                         btrfs_abort_transaction(trans, ret);
10390                         if (own_trans)
10391                                 btrfs_end_transaction(trans);
10392                         break;
10393                 }
10394
10395                 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10396                                         cur_offset + ins.offset -1, 0);
10397
10398                 em = alloc_extent_map();
10399                 if (!em) {
10400                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10401                                 &BTRFS_I(inode)->runtime_flags);
10402                         goto next;
10403                 }
10404
10405                 em->start = cur_offset;
10406                 em->orig_start = cur_offset;
10407                 em->len = ins.offset;
10408                 em->block_start = ins.objectid;
10409                 em->block_len = ins.offset;
10410                 em->orig_block_len = ins.offset;
10411                 em->ram_bytes = ins.offset;
10412                 em->bdev = fs_info->fs_devices->latest_bdev;
10413                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10414                 em->generation = trans->transid;
10415
10416                 while (1) {
10417                         write_lock(&em_tree->lock);
10418                         ret = add_extent_mapping(em_tree, em, 1);
10419                         write_unlock(&em_tree->lock);
10420                         if (ret != -EEXIST)
10421                                 break;
10422                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10423                                                 cur_offset + ins.offset - 1,
10424                                                 0);
10425                 }
10426                 free_extent_map(em);
10427 next:
10428                 num_bytes -= ins.offset;
10429                 cur_offset += ins.offset;
10430                 *alloc_hint = ins.objectid + ins.offset;
10431
10432                 inode_inc_iversion(inode);
10433                 inode->i_ctime = current_time(inode);
10434                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10435                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10436                     (actual_len > inode->i_size) &&
10437                     (cur_offset > inode->i_size)) {
10438                         if (cur_offset > actual_len)
10439                                 i_size = actual_len;
10440                         else
10441                                 i_size = cur_offset;
10442                         i_size_write(inode, i_size);
10443                         btrfs_ordered_update_i_size(inode, i_size, NULL);
10444                 }
10445
10446                 ret = btrfs_update_inode(trans, root, inode);
10447
10448                 if (ret) {
10449                         btrfs_abort_transaction(trans, ret);
10450                         if (own_trans)
10451                                 btrfs_end_transaction(trans);
10452                         break;
10453                 }
10454
10455                 if (own_trans)
10456                         btrfs_end_transaction(trans);
10457         }
10458         if (cur_offset < end)
10459                 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10460                         end - cur_offset + 1);
10461         return ret;
10462 }
10463
10464 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10465                               u64 start, u64 num_bytes, u64 min_size,
10466                               loff_t actual_len, u64 *alloc_hint)
10467 {
10468         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10469                                            min_size, actual_len, alloc_hint,
10470                                            NULL);
10471 }
10472
10473 int btrfs_prealloc_file_range_trans(struct inode *inode,
10474                                     struct btrfs_trans_handle *trans, int mode,
10475                                     u64 start, u64 num_bytes, u64 min_size,
10476                                     loff_t actual_len, u64 *alloc_hint)
10477 {
10478         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10479                                            min_size, actual_len, alloc_hint, trans);
10480 }
10481
10482 static int btrfs_set_page_dirty(struct page *page)
10483 {
10484         return __set_page_dirty_nobuffers(page);
10485 }
10486
10487 static int btrfs_permission(struct inode *inode, int mask)
10488 {
10489         struct btrfs_root *root = BTRFS_I(inode)->root;
10490         umode_t mode = inode->i_mode;
10491
10492         if (mask & MAY_WRITE &&
10493             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10494                 if (btrfs_root_readonly(root))
10495                         return -EROFS;
10496                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10497                         return -EACCES;
10498         }
10499         return generic_permission(inode, mask);
10500 }
10501
10502 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10503 {
10504         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10505         struct btrfs_trans_handle *trans;
10506         struct btrfs_root *root = BTRFS_I(dir)->root;
10507         struct inode *inode = NULL;
10508         u64 objectid;
10509         u64 index;
10510         int ret = 0;
10511
10512         /*
10513          * 5 units required for adding orphan entry
10514          */
10515         trans = btrfs_start_transaction(root, 5);
10516         if (IS_ERR(trans))
10517                 return PTR_ERR(trans);
10518
10519         ret = btrfs_find_free_ino(root, &objectid);
10520         if (ret)
10521                 goto out;
10522
10523         inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10524                         btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10525         if (IS_ERR(inode)) {
10526                 ret = PTR_ERR(inode);
10527                 inode = NULL;
10528                 goto out;
10529         }
10530
10531         inode->i_fop = &btrfs_file_operations;
10532         inode->i_op = &btrfs_file_inode_operations;
10533
10534         inode->i_mapping->a_ops = &btrfs_aops;
10535         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10536
10537         ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10538         if (ret)
10539                 goto out_inode;
10540
10541         ret = btrfs_update_inode(trans, root, inode);
10542         if (ret)
10543                 goto out_inode;
10544         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10545         if (ret)
10546                 goto out_inode;
10547
10548         /*
10549          * We set number of links to 0 in btrfs_new_inode(), and here we set
10550          * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10551          * through:
10552          *
10553          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10554          */
10555         set_nlink(inode, 1);
10556         unlock_new_inode(inode);
10557         d_tmpfile(dentry, inode);
10558         mark_inode_dirty(inode);
10559
10560 out:
10561         btrfs_end_transaction(trans);
10562         if (ret)
10563                 iput(inode);
10564         btrfs_btree_balance_dirty(fs_info);
10565         return ret;
10566
10567 out_inode:
10568         unlock_new_inode(inode);
10569         goto out;
10570
10571 }
10572
10573 __attribute__((const))
10574 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10575 {
10576         return -EAGAIN;
10577 }
10578
10579 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10580 {
10581         struct inode *inode = private_data;
10582         return btrfs_sb(inode->i_sb);
10583 }
10584
10585 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10586                                         u64 start, u64 end)
10587 {
10588         struct inode *inode = private_data;
10589         u64 isize;
10590
10591         isize = i_size_read(inode);
10592         if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10593                 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10594                     "%s: ino %llu isize %llu odd range [%llu,%llu]",
10595                         caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10596         }
10597 }
10598
10599 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10600 {
10601         struct inode *inode = private_data;
10602         unsigned long index = start >> PAGE_SHIFT;
10603         unsigned long end_index = end >> PAGE_SHIFT;
10604         struct page *page;
10605
10606         while (index <= end_index) {
10607                 page = find_get_page(inode->i_mapping, index);
10608                 ASSERT(page); /* Pages should be in the extent_io_tree */
10609                 set_page_writeback(page);
10610                 put_page(page);
10611                 index++;
10612         }
10613 }
10614
10615 static const struct inode_operations btrfs_dir_inode_operations = {
10616         .getattr        = btrfs_getattr,
10617         .lookup         = btrfs_lookup,
10618         .create         = btrfs_create,
10619         .unlink         = btrfs_unlink,
10620         .link           = btrfs_link,
10621         .mkdir          = btrfs_mkdir,
10622         .rmdir          = btrfs_rmdir,
10623         .rename         = btrfs_rename2,
10624         .symlink        = btrfs_symlink,
10625         .setattr        = btrfs_setattr,
10626         .mknod          = btrfs_mknod,
10627         .listxattr      = btrfs_listxattr,
10628         .permission     = btrfs_permission,
10629         .get_acl        = btrfs_get_acl,
10630         .set_acl        = btrfs_set_acl,
10631         .update_time    = btrfs_update_time,
10632         .tmpfile        = btrfs_tmpfile,
10633 };
10634 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10635         .lookup         = btrfs_lookup,
10636         .permission     = btrfs_permission,
10637         .update_time    = btrfs_update_time,
10638 };
10639
10640 static const struct file_operations btrfs_dir_file_operations = {
10641         .llseek         = generic_file_llseek,
10642         .read           = generic_read_dir,
10643         .iterate_shared = btrfs_real_readdir,
10644         .open           = btrfs_opendir,
10645         .unlocked_ioctl = btrfs_ioctl,
10646 #ifdef CONFIG_COMPAT
10647         .compat_ioctl   = btrfs_compat_ioctl,
10648 #endif
10649         .release        = btrfs_release_file,
10650         .fsync          = btrfs_sync_file,
10651 };
10652
10653 static const struct extent_io_ops btrfs_extent_io_ops = {
10654         /* mandatory callbacks */
10655         .submit_bio_hook = btrfs_submit_bio_hook,
10656         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10657         .merge_bio_hook = btrfs_merge_bio_hook,
10658         .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10659         .tree_fs_info = iotree_fs_info,
10660         .set_range_writeback = btrfs_set_range_writeback,
10661
10662         /* optional callbacks */
10663         .fill_delalloc = run_delalloc_range,
10664         .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10665         .writepage_start_hook = btrfs_writepage_start_hook,
10666         .set_bit_hook = btrfs_set_bit_hook,
10667         .clear_bit_hook = btrfs_clear_bit_hook,
10668         .merge_extent_hook = btrfs_merge_extent_hook,
10669         .split_extent_hook = btrfs_split_extent_hook,
10670         .check_extent_io_range = btrfs_check_extent_io_range,
10671 };
10672
10673 /*
10674  * btrfs doesn't support the bmap operation because swapfiles
10675  * use bmap to make a mapping of extents in the file.  They assume
10676  * these extents won't change over the life of the file and they
10677  * use the bmap result to do IO directly to the drive.
10678  *
10679  * the btrfs bmap call would return logical addresses that aren't
10680  * suitable for IO and they also will change frequently as COW
10681  * operations happen.  So, swapfile + btrfs == corruption.
10682  *
10683  * For now we're avoiding this by dropping bmap.
10684  */
10685 static const struct address_space_operations btrfs_aops = {
10686         .readpage       = btrfs_readpage,
10687         .writepage      = btrfs_writepage,
10688         .writepages     = btrfs_writepages,
10689         .readpages      = btrfs_readpages,
10690         .direct_IO      = btrfs_direct_IO,
10691         .invalidatepage = btrfs_invalidatepage,
10692         .releasepage    = btrfs_releasepage,
10693         .set_page_dirty = btrfs_set_page_dirty,
10694         .error_remove_page = generic_error_remove_page,
10695 };
10696
10697 static const struct address_space_operations btrfs_symlink_aops = {
10698         .readpage       = btrfs_readpage,
10699         .writepage      = btrfs_writepage,
10700         .invalidatepage = btrfs_invalidatepage,
10701         .releasepage    = btrfs_releasepage,
10702 };
10703
10704 static const struct inode_operations btrfs_file_inode_operations = {
10705         .getattr        = btrfs_getattr,
10706         .setattr        = btrfs_setattr,
10707         .listxattr      = btrfs_listxattr,
10708         .permission     = btrfs_permission,
10709         .fiemap         = btrfs_fiemap,
10710         .get_acl        = btrfs_get_acl,
10711         .set_acl        = btrfs_set_acl,
10712         .update_time    = btrfs_update_time,
10713 };
10714 static const struct inode_operations btrfs_special_inode_operations = {
10715         .getattr        = btrfs_getattr,
10716         .setattr        = btrfs_setattr,
10717         .permission     = btrfs_permission,
10718         .listxattr      = btrfs_listxattr,
10719         .get_acl        = btrfs_get_acl,
10720         .set_acl        = btrfs_set_acl,
10721         .update_time    = btrfs_update_time,
10722 };
10723 static const struct inode_operations btrfs_symlink_inode_operations = {
10724         .get_link       = page_get_link,
10725         .getattr        = btrfs_getattr,
10726         .setattr        = btrfs_setattr,
10727         .permission     = btrfs_permission,
10728         .listxattr      = btrfs_listxattr,
10729         .update_time    = btrfs_update_time,
10730 };
10731
10732 const struct dentry_operations btrfs_dentry_operations = {
10733         .d_delete       = btrfs_dentry_delete,
10734 };