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