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