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