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