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