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