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