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