Mention branches and keyring.
[releases.git] / 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, NULL);
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                 /*
3368                  * Drop extent maps for the part of the extent we didn't write.
3369                  *
3370                  * We have an exception here for the free_space_inode, this is
3371                  * because when we do btrfs_get_extent() on the free space inode
3372                  * we will search the commit root.  If this is a new block group
3373                  * we won't find anything, and we will trip over the assert in
3374                  * writepage where we do ASSERT(em->block_start !=
3375                  * EXTENT_MAP_HOLE).
3376                  *
3377                  * Theoretically we could also skip this for any NOCOW extent as
3378                  * we don't mess with the extent map tree in the NOCOW case, but
3379                  * for now simply skip this if we are the free space inode.
3380                  */
3381                 if (!btrfs_is_free_space_inode(inode))
3382                         btrfs_drop_extent_map_range(inode, unwritten_start,
3383                                                     end, false);
3384
3385                 /*
3386                  * If the ordered extent had an IOERR or something else went
3387                  * wrong we need to return the space for this ordered extent
3388                  * back to the allocator.  We only free the extent in the
3389                  * truncated case if we didn't write out the extent at all.
3390                  *
3391                  * If we made it past insert_reserved_file_extent before we
3392                  * errored out then we don't need to do this as the accounting
3393                  * has already been done.
3394                  */
3395                 if ((ret || !logical_len) &&
3396                     clear_reserved_extent &&
3397                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3398                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3399                         /*
3400                          * Discard the range before returning it back to the
3401                          * free space pool
3402                          */
3403                         if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3404                                 btrfs_discard_extent(fs_info,
3405                                                 ordered_extent->disk_bytenr,
3406                                                 ordered_extent->disk_num_bytes,
3407                                                 NULL);
3408                         btrfs_free_reserved_extent(fs_info,
3409                                         ordered_extent->disk_bytenr,
3410                                         ordered_extent->disk_num_bytes, 1);
3411                         /*
3412                          * Actually free the qgroup rsv which was released when
3413                          * the ordered extent was created.
3414                          */
3415                         btrfs_qgroup_free_refroot(fs_info, inode->root->root_key.objectid,
3416                                                   ordered_extent->qgroup_rsv,
3417                                                   BTRFS_QGROUP_RSV_DATA);
3418                 }
3419         }
3420
3421         /*
3422          * This needs to be done to make sure anybody waiting knows we are done
3423          * updating everything for this ordered extent.
3424          */
3425         btrfs_remove_ordered_extent(inode, ordered_extent);
3426
3427         /* once for us */
3428         btrfs_put_ordered_extent(ordered_extent);
3429         /* once for the tree */
3430         btrfs_put_ordered_extent(ordered_extent);
3431
3432         return ret;
3433 }
3434
3435 void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
3436                                           struct page *page, u64 start,
3437                                           u64 end, bool uptodate)
3438 {
3439         trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
3440
3441         btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start, uptodate);
3442 }
3443
3444 /*
3445  * Verify the checksum for a single sector without any extra action that depend
3446  * on the type of I/O.
3447  */
3448 int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
3449                             u32 pgoff, u8 *csum, const u8 * const csum_expected)
3450 {
3451         SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3452         char *kaddr;
3453
3454         ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
3455
3456         shash->tfm = fs_info->csum_shash;
3457
3458         kaddr = kmap_local_page(page) + pgoff;
3459         crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
3460         kunmap_local(kaddr);
3461
3462         if (memcmp(csum, csum_expected, fs_info->csum_size))
3463                 return -EIO;
3464         return 0;
3465 }
3466
3467 static u8 *btrfs_csum_ptr(const struct btrfs_fs_info *fs_info, u8 *csums, u64 offset)
3468 {
3469         u64 offset_in_sectors = offset >> fs_info->sectorsize_bits;
3470
3471         return csums + offset_in_sectors * fs_info->csum_size;
3472 }
3473
3474 /*
3475  * check_data_csum - verify checksum of one sector of uncompressed data
3476  * @inode:      inode
3477  * @bbio:       btrfs_bio which contains the csum
3478  * @bio_offset: offset to the beginning of the bio (in bytes)
3479  * @page:       page where is the data to be verified
3480  * @pgoff:      offset inside the page
3481  *
3482  * The length of such check is always one sector size.
3483  *
3484  * When csum mismatch is detected, we will also report the error and fill the
3485  * corrupted range with zero. (Thus it needs the extra parameters)
3486  */
3487 int btrfs_check_data_csum(struct inode *inode, struct btrfs_bio *bbio,
3488                           u32 bio_offset, struct page *page, u32 pgoff)
3489 {
3490         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3491         u32 len = fs_info->sectorsize;
3492         u8 *csum_expected;
3493         u8 csum[BTRFS_CSUM_SIZE];
3494
3495         ASSERT(pgoff + len <= PAGE_SIZE);
3496
3497         csum_expected = btrfs_csum_ptr(fs_info, bbio->csum, bio_offset);
3498
3499         if (btrfs_check_sector_csum(fs_info, page, pgoff, csum, csum_expected))
3500                 goto zeroit;
3501         return 0;
3502
3503 zeroit:
3504         btrfs_print_data_csum_error(BTRFS_I(inode),
3505                                     bbio->file_offset + bio_offset,
3506                                     csum, csum_expected, bbio->mirror_num);
3507         if (bbio->device)
3508                 btrfs_dev_stat_inc_and_print(bbio->device,
3509                                              BTRFS_DEV_STAT_CORRUPTION_ERRS);
3510         memzero_page(page, pgoff, len);
3511         return -EIO;
3512 }
3513
3514 /*
3515  * When reads are done, we need to check csums to verify the data is correct.
3516  * if there's a match, we allow the bio to finish.  If not, the code in
3517  * extent_io.c will try to find good copies for us.
3518  *
3519  * @bio_offset: offset to the beginning of the bio (in bytes)
3520  * @start:      file offset of the range start
3521  * @end:        file offset of the range end (inclusive)
3522  *
3523  * Return a bitmap where bit set means a csum mismatch, and bit not set means
3524  * csum match.
3525  */
3526 unsigned int btrfs_verify_data_csum(struct btrfs_bio *bbio,
3527                                     u32 bio_offset, struct page *page,
3528                                     u64 start, u64 end)
3529 {
3530         struct inode *inode = page->mapping->host;
3531         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3532         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3533         struct btrfs_root *root = BTRFS_I(inode)->root;
3534         const u32 sectorsize = root->fs_info->sectorsize;
3535         u32 pg_off;
3536         unsigned int result = 0;
3537
3538         /*
3539          * This only happens for NODATASUM or compressed read.
3540          * Normally this should be covered by above check for compressed read
3541          * or the next check for NODATASUM.  Just do a quicker exit here.
3542          */
3543         if (bbio->csum == NULL)
3544                 return 0;
3545
3546         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3547                 return 0;
3548
3549         if (unlikely(test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state)))
3550                 return 0;
3551
3552         ASSERT(page_offset(page) <= start &&
3553                end <= page_offset(page) + PAGE_SIZE - 1);
3554         for (pg_off = offset_in_page(start);
3555              pg_off < offset_in_page(end);
3556              pg_off += sectorsize, bio_offset += sectorsize) {
3557                 u64 file_offset = pg_off + page_offset(page);
3558                 int ret;
3559
3560                 if (btrfs_is_data_reloc_root(root) &&
3561                     test_range_bit(io_tree, file_offset,
3562                                    file_offset + sectorsize - 1,
3563                                    EXTENT_NODATASUM, 1, NULL)) {
3564                         /* Skip the range without csum for data reloc inode */
3565                         clear_extent_bits(io_tree, file_offset,
3566                                           file_offset + sectorsize - 1,
3567                                           EXTENT_NODATASUM);
3568                         continue;
3569                 }
3570                 ret = btrfs_check_data_csum(inode, bbio, bio_offset, page, pg_off);
3571                 if (ret < 0) {
3572                         const int nr_bit = (pg_off - offset_in_page(start)) >>
3573                                      root->fs_info->sectorsize_bits;
3574
3575                         result |= (1U << nr_bit);
3576                 }
3577         }
3578         return result;
3579 }
3580
3581 /*
3582  * btrfs_add_delayed_iput - perform a delayed iput on @inode
3583  *
3584  * @inode: The inode we want to perform iput on
3585  *
3586  * This function uses the generic vfs_inode::i_count to track whether we should
3587  * just decrement it (in case it's > 1) or if this is the last iput then link
3588  * the inode to the delayed iput machinery. Delayed iputs are processed at
3589  * transaction commit time/superblock commit/cleaner kthread.
3590  */
3591 void btrfs_add_delayed_iput(struct inode *inode)
3592 {
3593         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3594         struct btrfs_inode *binode = BTRFS_I(inode);
3595
3596         if (atomic_add_unless(&inode->i_count, -1, 1))
3597                 return;
3598
3599         atomic_inc(&fs_info->nr_delayed_iputs);
3600         spin_lock(&fs_info->delayed_iput_lock);
3601         ASSERT(list_empty(&binode->delayed_iput));
3602         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3603         spin_unlock(&fs_info->delayed_iput_lock);
3604         if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3605                 wake_up_process(fs_info->cleaner_kthread);
3606 }
3607
3608 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3609                                     struct btrfs_inode *inode)
3610 {
3611         list_del_init(&inode->delayed_iput);
3612         spin_unlock(&fs_info->delayed_iput_lock);
3613         iput(&inode->vfs_inode);
3614         if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3615                 wake_up(&fs_info->delayed_iputs_wait);
3616         spin_lock(&fs_info->delayed_iput_lock);
3617 }
3618
3619 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3620                                    struct btrfs_inode *inode)
3621 {
3622         if (!list_empty(&inode->delayed_iput)) {
3623                 spin_lock(&fs_info->delayed_iput_lock);
3624                 if (!list_empty(&inode->delayed_iput))
3625                         run_delayed_iput_locked(fs_info, inode);
3626                 spin_unlock(&fs_info->delayed_iput_lock);
3627         }
3628 }
3629
3630 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3631 {
3632
3633         spin_lock(&fs_info->delayed_iput_lock);
3634         while (!list_empty(&fs_info->delayed_iputs)) {
3635                 struct btrfs_inode *inode;
3636
3637                 inode = list_first_entry(&fs_info->delayed_iputs,
3638                                 struct btrfs_inode, delayed_iput);
3639                 run_delayed_iput_locked(fs_info, inode);
3640                 cond_resched_lock(&fs_info->delayed_iput_lock);
3641         }
3642         spin_unlock(&fs_info->delayed_iput_lock);
3643 }
3644
3645 /*
3646  * Wait for flushing all delayed iputs
3647  *
3648  * @fs_info:  the filesystem
3649  *
3650  * This will wait on any delayed iputs that are currently running with KILLABLE
3651  * set.  Once they are all done running we will return, unless we are killed in
3652  * which case we return EINTR. This helps in user operations like fallocate etc
3653  * that might get blocked on the iputs.
3654  *
3655  * Return EINTR if we were killed, 0 if nothing's pending
3656  */
3657 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3658 {
3659         int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3660                         atomic_read(&fs_info->nr_delayed_iputs) == 0);
3661         if (ret)
3662                 return -EINTR;
3663         return 0;
3664 }
3665
3666 /*
3667  * This creates an orphan entry for the given inode in case something goes wrong
3668  * in the middle of an unlink.
3669  */
3670 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3671                      struct btrfs_inode *inode)
3672 {
3673         int ret;
3674
3675         ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3676         if (ret && ret != -EEXIST) {
3677                 btrfs_abort_transaction(trans, ret);
3678                 return ret;
3679         }
3680
3681         return 0;
3682 }
3683
3684 /*
3685  * We have done the delete so we can go ahead and remove the orphan item for
3686  * this particular inode.
3687  */
3688 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3689                             struct btrfs_inode *inode)
3690 {
3691         return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3692 }
3693
3694 /*
3695  * this cleans up any orphans that may be left on the list from the last use
3696  * of this root.
3697  */
3698 int btrfs_orphan_cleanup(struct btrfs_root *root)
3699 {
3700         struct btrfs_fs_info *fs_info = root->fs_info;
3701         struct btrfs_path *path;
3702         struct extent_buffer *leaf;
3703         struct btrfs_key key, found_key;
3704         struct btrfs_trans_handle *trans;
3705         struct inode *inode;
3706         u64 last_objectid = 0;
3707         int ret = 0, nr_unlink = 0;
3708
3709         if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3710                 return 0;
3711
3712         path = btrfs_alloc_path();
3713         if (!path) {
3714                 ret = -ENOMEM;
3715                 goto out;
3716         }
3717         path->reada = READA_BACK;
3718
3719         key.objectid = BTRFS_ORPHAN_OBJECTID;
3720         key.type = BTRFS_ORPHAN_ITEM_KEY;
3721         key.offset = (u64)-1;
3722
3723         while (1) {
3724                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3725                 if (ret < 0)
3726                         goto out;
3727
3728                 /*
3729                  * if ret == 0 means we found what we were searching for, which
3730                  * is weird, but possible, so only screw with path if we didn't
3731                  * find the key and see if we have stuff that matches
3732                  */
3733                 if (ret > 0) {
3734                         ret = 0;
3735                         if (path->slots[0] == 0)
3736                                 break;
3737                         path->slots[0]--;
3738                 }
3739
3740                 /* pull out the item */
3741                 leaf = path->nodes[0];
3742                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3743
3744                 /* make sure the item matches what we want */
3745                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3746                         break;
3747                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3748                         break;
3749
3750                 /* release the path since we're done with it */
3751                 btrfs_release_path(path);
3752
3753                 /*
3754                  * this is where we are basically btrfs_lookup, without the
3755                  * crossing root thing.  we store the inode number in the
3756                  * offset of the orphan item.
3757                  */
3758
3759                 if (found_key.offset == last_objectid) {
3760                         btrfs_err(fs_info,
3761                                   "Error removing orphan entry, stopping orphan cleanup");
3762                         ret = -EINVAL;
3763                         goto out;
3764                 }
3765
3766                 last_objectid = found_key.offset;
3767
3768                 found_key.objectid = found_key.offset;
3769                 found_key.type = BTRFS_INODE_ITEM_KEY;
3770                 found_key.offset = 0;
3771                 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3772                 ret = PTR_ERR_OR_ZERO(inode);
3773                 if (ret && ret != -ENOENT)
3774                         goto out;
3775
3776                 if (ret == -ENOENT && root == fs_info->tree_root) {
3777                         struct btrfs_root *dead_root;
3778                         int is_dead_root = 0;
3779
3780                         /*
3781                          * This is an orphan in the tree root. Currently these
3782                          * could come from 2 sources:
3783                          *  a) a root (snapshot/subvolume) deletion in progress
3784                          *  b) a free space cache inode
3785                          * We need to distinguish those two, as the orphan item
3786                          * for a root must not get deleted before the deletion
3787                          * of the snapshot/subvolume's tree completes.
3788                          *
3789                          * btrfs_find_orphan_roots() ran before us, which has
3790                          * found all deleted roots and loaded them into
3791                          * fs_info->fs_roots_radix. So here we can find if an
3792                          * orphan item corresponds to a deleted root by looking
3793                          * up the root from that radix tree.
3794                          */
3795
3796                         spin_lock(&fs_info->fs_roots_radix_lock);
3797                         dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3798                                                          (unsigned long)found_key.objectid);
3799                         if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3800                                 is_dead_root = 1;
3801                         spin_unlock(&fs_info->fs_roots_radix_lock);
3802
3803                         if (is_dead_root) {
3804                                 /* prevent this orphan from being found again */
3805                                 key.offset = found_key.objectid - 1;
3806                                 continue;
3807                         }
3808
3809                 }
3810
3811                 /*
3812                  * If we have an inode with links, there are a couple of
3813                  * possibilities:
3814                  *
3815                  * 1. We were halfway through creating fsverity metadata for the
3816                  * file. In that case, the orphan item represents incomplete
3817                  * fsverity metadata which must be cleaned up with
3818                  * btrfs_drop_verity_items and deleting the orphan item.
3819
3820                  * 2. Old kernels (before v3.12) used to create an
3821                  * orphan item for truncate indicating that there were possibly
3822                  * extent items past i_size that needed to be deleted. In v3.12,
3823                  * truncate was changed to update i_size in sync with the extent
3824                  * items, but the (useless) orphan item was still created. Since
3825                  * v4.18, we don't create the orphan item for truncate at all.
3826                  *
3827                  * So, this item could mean that we need to do a truncate, but
3828                  * only if this filesystem was last used on a pre-v3.12 kernel
3829                  * and was not cleanly unmounted. The odds of that are quite
3830                  * slim, and it's a pain to do the truncate now, so just delete
3831                  * the orphan item.
3832                  *
3833                  * It's also possible that this orphan item was supposed to be
3834                  * deleted but wasn't. The inode number may have been reused,
3835                  * but either way, we can delete the orphan item.
3836                  */
3837                 if (ret == -ENOENT || inode->i_nlink) {
3838                         if (!ret) {
3839                                 ret = btrfs_drop_verity_items(BTRFS_I(inode));
3840                                 iput(inode);
3841                                 if (ret)
3842                                         goto out;
3843                         }
3844                         trans = btrfs_start_transaction(root, 1);
3845                         if (IS_ERR(trans)) {
3846                                 ret = PTR_ERR(trans);
3847                                 goto out;
3848                         }
3849                         btrfs_debug(fs_info, "auto deleting %Lu",
3850                                     found_key.objectid);
3851                         ret = btrfs_del_orphan_item(trans, root,
3852                                                     found_key.objectid);
3853                         btrfs_end_transaction(trans);
3854                         if (ret)
3855                                 goto out;
3856                         continue;
3857                 }
3858
3859                 nr_unlink++;
3860
3861                 /* this will do delete_inode and everything for us */
3862                 iput(inode);
3863         }
3864         /* release the path since we're done with it */
3865         btrfs_release_path(path);
3866
3867         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3868                 trans = btrfs_join_transaction(root);
3869                 if (!IS_ERR(trans))
3870                         btrfs_end_transaction(trans);
3871         }
3872
3873         if (nr_unlink)
3874                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3875
3876 out:
3877         if (ret)
3878                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3879         btrfs_free_path(path);
3880         return ret;
3881 }
3882
3883 /*
3884  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3885  * don't find any xattrs, we know there can't be any acls.
3886  *
3887  * slot is the slot the inode is in, objectid is the objectid of the inode
3888  */
3889 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3890                                           int slot, u64 objectid,
3891                                           int *first_xattr_slot)
3892 {
3893         u32 nritems = btrfs_header_nritems(leaf);
3894         struct btrfs_key found_key;
3895         static u64 xattr_access = 0;
3896         static u64 xattr_default = 0;
3897         int scanned = 0;
3898
3899         if (!xattr_access) {
3900                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3901                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3902                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3903                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3904         }
3905
3906         slot++;
3907         *first_xattr_slot = -1;
3908         while (slot < nritems) {
3909                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3910
3911                 /* we found a different objectid, there must not be acls */
3912                 if (found_key.objectid != objectid)
3913                         return 0;
3914
3915                 /* we found an xattr, assume we've got an acl */
3916                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3917                         if (*first_xattr_slot == -1)
3918                                 *first_xattr_slot = slot;
3919                         if (found_key.offset == xattr_access ||
3920                             found_key.offset == xattr_default)
3921                                 return 1;
3922                 }
3923
3924                 /*
3925                  * we found a key greater than an xattr key, there can't
3926                  * be any acls later on
3927                  */
3928                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3929                         return 0;
3930
3931                 slot++;
3932                 scanned++;
3933
3934                 /*
3935                  * it goes inode, inode backrefs, xattrs, extents,
3936                  * so if there are a ton of hard links to an inode there can
3937                  * be a lot of backrefs.  Don't waste time searching too hard,
3938                  * this is just an optimization
3939                  */
3940                 if (scanned >= 8)
3941                         break;
3942         }
3943         /* we hit the end of the leaf before we found an xattr or
3944          * something larger than an xattr.  We have to assume the inode
3945          * has acls
3946          */
3947         if (*first_xattr_slot == -1)
3948                 *first_xattr_slot = slot;
3949         return 1;
3950 }
3951
3952 /*
3953  * read an inode from the btree into the in-memory inode
3954  */
3955 static int btrfs_read_locked_inode(struct inode *inode,
3956                                    struct btrfs_path *in_path)
3957 {
3958         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3959         struct btrfs_path *path = in_path;
3960         struct extent_buffer *leaf;
3961         struct btrfs_inode_item *inode_item;
3962         struct btrfs_root *root = BTRFS_I(inode)->root;
3963         struct btrfs_key location;
3964         unsigned long ptr;
3965         int maybe_acls;
3966         u32 rdev;
3967         int ret;
3968         bool filled = false;
3969         int first_xattr_slot;
3970
3971         ret = btrfs_fill_inode(inode, &rdev);
3972         if (!ret)
3973                 filled = true;
3974
3975         if (!path) {
3976                 path = btrfs_alloc_path();
3977                 if (!path)
3978                         return -ENOMEM;
3979         }
3980
3981         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3982
3983         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3984         if (ret) {
3985                 if (path != in_path)
3986                         btrfs_free_path(path);
3987                 return ret;
3988         }
3989
3990         leaf = path->nodes[0];
3991
3992         if (filled)
3993                 goto cache_index;
3994
3995         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3996                                     struct btrfs_inode_item);
3997         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3998         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3999         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
4000         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
4001         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
4002         btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
4003                         round_up(i_size_read(inode), fs_info->sectorsize));
4004
4005         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
4006         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
4007
4008         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
4009         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
4010
4011         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
4012         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
4013
4014         BTRFS_I(inode)->i_otime.tv_sec =
4015                 btrfs_timespec_sec(leaf, &inode_item->otime);
4016         BTRFS_I(inode)->i_otime.tv_nsec =
4017                 btrfs_timespec_nsec(leaf, &inode_item->otime);
4018
4019         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
4020         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
4021         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
4022
4023         inode_set_iversion_queried(inode,
4024                                    btrfs_inode_sequence(leaf, inode_item));
4025         inode->i_generation = BTRFS_I(inode)->generation;
4026         inode->i_rdev = 0;
4027         rdev = btrfs_inode_rdev(leaf, inode_item);
4028
4029         BTRFS_I(inode)->index_cnt = (u64)-1;
4030         btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
4031                                 &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
4032
4033 cache_index:
4034         /*
4035          * If we were modified in the current generation and evicted from memory
4036          * and then re-read we need to do a full sync since we don't have any
4037          * idea about which extents were modified before we were evicted from
4038          * cache.
4039          *
4040          * This is required for both inode re-read from disk and delayed inode
4041          * in delayed_nodes_tree.
4042          */
4043         if (BTRFS_I(inode)->last_trans == fs_info->generation)
4044                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4045                         &BTRFS_I(inode)->runtime_flags);
4046
4047         /*
4048          * We don't persist the id of the transaction where an unlink operation
4049          * against the inode was last made. So here we assume the inode might
4050          * have been evicted, and therefore the exact value of last_unlink_trans
4051          * lost, and set it to last_trans to avoid metadata inconsistencies
4052          * between the inode and its parent if the inode is fsync'ed and the log
4053          * replayed. For example, in the scenario:
4054          *
4055          * touch mydir/foo
4056          * ln mydir/foo mydir/bar
4057          * sync
4058          * unlink mydir/bar
4059          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
4060          * xfs_io -c fsync mydir/foo
4061          * <power failure>
4062          * mount fs, triggers fsync log replay
4063          *
4064          * We must make sure that when we fsync our inode foo we also log its
4065          * parent inode, otherwise after log replay the parent still has the
4066          * dentry with the "bar" name but our inode foo has a link count of 1
4067          * and doesn't have an inode ref with the name "bar" anymore.
4068          *
4069          * Setting last_unlink_trans to last_trans is a pessimistic approach,
4070          * but it guarantees correctness at the expense of occasional full
4071          * transaction commits on fsync if our inode is a directory, or if our
4072          * inode is not a directory, logging its parent unnecessarily.
4073          */
4074         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
4075
4076         /*
4077          * Same logic as for last_unlink_trans. We don't persist the generation
4078          * of the last transaction where this inode was used for a reflink
4079          * operation, so after eviction and reloading the inode we must be
4080          * pessimistic and assume the last transaction that modified the inode.
4081          */
4082         BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
4083
4084         path->slots[0]++;
4085         if (inode->i_nlink != 1 ||
4086             path->slots[0] >= btrfs_header_nritems(leaf))
4087                 goto cache_acl;
4088
4089         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4090         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
4091                 goto cache_acl;
4092
4093         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4094         if (location.type == BTRFS_INODE_REF_KEY) {
4095                 struct btrfs_inode_ref *ref;
4096
4097                 ref = (struct btrfs_inode_ref *)ptr;
4098                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
4099         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4100                 struct btrfs_inode_extref *extref;
4101
4102                 extref = (struct btrfs_inode_extref *)ptr;
4103                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
4104                                                                      extref);
4105         }
4106 cache_acl:
4107         /*
4108          * try to precache a NULL acl entry for files that don't have
4109          * any xattrs or acls
4110          */
4111         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4112                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
4113         if (first_xattr_slot != -1) {
4114                 path->slots[0] = first_xattr_slot;
4115                 ret = btrfs_load_inode_props(inode, path);
4116                 if (ret)
4117                         btrfs_err(fs_info,
4118                                   "error loading props for ino %llu (root %llu): %d",
4119                                   btrfs_ino(BTRFS_I(inode)),
4120                                   root->root_key.objectid, ret);
4121         }
4122         if (path != in_path)
4123                 btrfs_free_path(path);
4124
4125         if (!maybe_acls)
4126                 cache_no_acl(inode);
4127
4128         switch (inode->i_mode & S_IFMT) {
4129         case S_IFREG:
4130                 inode->i_mapping->a_ops = &btrfs_aops;
4131                 inode->i_fop = &btrfs_file_operations;
4132                 inode->i_op = &btrfs_file_inode_operations;
4133                 break;
4134         case S_IFDIR:
4135                 inode->i_fop = &btrfs_dir_file_operations;
4136                 inode->i_op = &btrfs_dir_inode_operations;
4137                 break;
4138         case S_IFLNK:
4139                 inode->i_op = &btrfs_symlink_inode_operations;
4140                 inode_nohighmem(inode);
4141                 inode->i_mapping->a_ops = &btrfs_aops;
4142                 break;
4143         default:
4144                 inode->i_op = &btrfs_special_inode_operations;
4145                 init_special_inode(inode, inode->i_mode, rdev);
4146                 break;
4147         }
4148
4149         btrfs_sync_inode_flags_to_i_flags(inode);
4150         return 0;
4151 }
4152
4153 /*
4154  * given a leaf and an inode, copy the inode fields into the leaf
4155  */
4156 static void fill_inode_item(struct btrfs_trans_handle *trans,
4157                             struct extent_buffer *leaf,
4158                             struct btrfs_inode_item *item,
4159                             struct inode *inode)
4160 {
4161         struct btrfs_map_token token;
4162         u64 flags;
4163
4164         btrfs_init_map_token(&token, leaf);
4165
4166         btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
4167         btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
4168         btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
4169         btrfs_set_token_inode_mode(&token, item, inode->i_mode);
4170         btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
4171
4172         btrfs_set_token_timespec_sec(&token, &item->atime,
4173                                      inode->i_atime.tv_sec);
4174         btrfs_set_token_timespec_nsec(&token, &item->atime,
4175                                       inode->i_atime.tv_nsec);
4176
4177         btrfs_set_token_timespec_sec(&token, &item->mtime,
4178                                      inode->i_mtime.tv_sec);
4179         btrfs_set_token_timespec_nsec(&token, &item->mtime,
4180                                       inode->i_mtime.tv_nsec);
4181
4182         btrfs_set_token_timespec_sec(&token, &item->ctime,
4183                                      inode->i_ctime.tv_sec);
4184         btrfs_set_token_timespec_nsec(&token, &item->ctime,
4185                                       inode->i_ctime.tv_nsec);
4186
4187         btrfs_set_token_timespec_sec(&token, &item->otime,
4188                                      BTRFS_I(inode)->i_otime.tv_sec);
4189         btrfs_set_token_timespec_nsec(&token, &item->otime,
4190                                       BTRFS_I(inode)->i_otime.tv_nsec);
4191
4192         btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
4193         btrfs_set_token_inode_generation(&token, item,
4194                                          BTRFS_I(inode)->generation);
4195         btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
4196         btrfs_set_token_inode_transid(&token, item, trans->transid);
4197         btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
4198         flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4199                                           BTRFS_I(inode)->ro_flags);
4200         btrfs_set_token_inode_flags(&token, item, flags);
4201         btrfs_set_token_inode_block_group(&token, item, 0);
4202 }
4203
4204 /*
4205  * copy everything in the in-memory inode into the btree.
4206  */
4207 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4208                                 struct btrfs_root *root,
4209                                 struct btrfs_inode *inode)
4210 {
4211         struct btrfs_inode_item *inode_item;
4212         struct btrfs_path *path;
4213         struct extent_buffer *leaf;
4214         int ret;
4215
4216         path = btrfs_alloc_path();
4217         if (!path)
4218                 return -ENOMEM;
4219
4220         ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
4221         if (ret) {
4222                 if (ret > 0)
4223                         ret = -ENOENT;
4224                 goto failed;
4225         }
4226
4227         leaf = path->nodes[0];
4228         inode_item = btrfs_item_ptr(leaf, path->slots[0],
4229                                     struct btrfs_inode_item);
4230
4231         fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4232         btrfs_mark_buffer_dirty(leaf);
4233         btrfs_set_inode_last_trans(trans, inode);
4234         ret = 0;
4235 failed:
4236         btrfs_free_path(path);
4237         return ret;
4238 }
4239
4240 /*
4241  * copy everything in the in-memory inode into the btree.
4242  */
4243 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
4244                                 struct btrfs_root *root,
4245                                 struct btrfs_inode *inode)
4246 {
4247         struct btrfs_fs_info *fs_info = root->fs_info;
4248         int ret;
4249
4250         /*
4251          * If the inode is a free space inode, we can deadlock during commit
4252          * if we put it into the delayed code.
4253          *
4254          * The data relocation inode should also be directly updated
4255          * without delay
4256          */
4257         if (!btrfs_is_free_space_inode(inode)
4258             && !btrfs_is_data_reloc_root(root)
4259             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4260                 btrfs_update_root_times(trans, root);
4261
4262                 ret = btrfs_delayed_update_inode(trans, root, inode);
4263                 if (!ret)
4264                         btrfs_set_inode_last_trans(trans, inode);
4265                 return ret;
4266         }
4267
4268         return btrfs_update_inode_item(trans, root, inode);
4269 }
4270
4271 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4272                                 struct btrfs_root *root, struct btrfs_inode *inode)
4273 {
4274         int ret;
4275
4276         ret = btrfs_update_inode(trans, root, inode);
4277         if (ret == -ENOSPC)
4278                 return btrfs_update_inode_item(trans, root, inode);
4279         return ret;
4280 }
4281
4282 /*
4283  * unlink helper that gets used here in inode.c and in the tree logging
4284  * recovery code.  It remove a link in a directory with a given name, and
4285  * also drops the back refs in the inode to the directory
4286  */
4287 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4288                                 struct btrfs_inode *dir,
4289                                 struct btrfs_inode *inode,
4290                                 const struct fscrypt_str *name,
4291                                 struct btrfs_rename_ctx *rename_ctx)
4292 {
4293         struct btrfs_root *root = dir->root;
4294         struct btrfs_fs_info *fs_info = root->fs_info;
4295         struct btrfs_path *path;
4296         int ret = 0;
4297         struct btrfs_dir_item *di;
4298         u64 index;
4299         u64 ino = btrfs_ino(inode);
4300         u64 dir_ino = btrfs_ino(dir);
4301
4302         path = btrfs_alloc_path();
4303         if (!path) {
4304                 ret = -ENOMEM;
4305                 goto out;
4306         }
4307
4308         di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4309         if (IS_ERR_OR_NULL(di)) {
4310                 ret = di ? PTR_ERR(di) : -ENOENT;
4311                 goto err;
4312         }
4313         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4314         if (ret)
4315                 goto err;
4316         btrfs_release_path(path);
4317
4318         /*
4319          * If we don't have dir index, we have to get it by looking up
4320          * the inode ref, since we get the inode ref, remove it directly,
4321          * it is unnecessary to do delayed deletion.
4322          *
4323          * But if we have dir index, needn't search inode ref to get it.
4324          * Since the inode ref is close to the inode item, it is better
4325          * that we delay to delete it, and just do this deletion when
4326          * we update the inode item.
4327          */
4328         if (inode->dir_index) {
4329                 ret = btrfs_delayed_delete_inode_ref(inode);
4330                 if (!ret) {
4331                         index = inode->dir_index;
4332                         goto skip_backref;
4333                 }
4334         }
4335
4336         ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4337         if (ret) {
4338                 btrfs_info(fs_info,
4339                         "failed to delete reference to %.*s, inode %llu parent %llu",
4340                         name->len, name->name, ino, dir_ino);
4341                 btrfs_abort_transaction(trans, ret);
4342                 goto err;
4343         }
4344 skip_backref:
4345         if (rename_ctx)
4346                 rename_ctx->index = index;
4347
4348         ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4349         if (ret) {
4350                 btrfs_abort_transaction(trans, ret);
4351                 goto err;
4352         }
4353
4354         /*
4355          * If we are in a rename context, we don't need to update anything in the
4356          * log. That will be done later during the rename by btrfs_log_new_name().
4357          * Besides that, doing it here would only cause extra unnecessary btree
4358          * operations on the log tree, increasing latency for applications.
4359          */
4360         if (!rename_ctx) {
4361                 btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
4362                 btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
4363         }
4364
4365         /*
4366          * If we have a pending delayed iput we could end up with the final iput
4367          * being run in btrfs-cleaner context.  If we have enough of these built
4368          * up we can end up burning a lot of time in btrfs-cleaner without any
4369          * way to throttle the unlinks.  Since we're currently holding a ref on
4370          * the inode we can run the delayed iput here without any issues as the
4371          * final iput won't be done until after we drop the ref we're currently
4372          * holding.
4373          */
4374         btrfs_run_delayed_iput(fs_info, inode);
4375 err:
4376         btrfs_free_path(path);
4377         if (ret)
4378                 goto out;
4379
4380         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4381         inode_inc_iversion(&inode->vfs_inode);
4382         inode_inc_iversion(&dir->vfs_inode);
4383         inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4384         dir->vfs_inode.i_mtime = inode->vfs_inode.i_ctime;
4385         dir->vfs_inode.i_ctime = inode->vfs_inode.i_ctime;
4386         ret = btrfs_update_inode(trans, root, dir);
4387 out:
4388         return ret;
4389 }
4390
4391 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4392                        struct btrfs_inode *dir, struct btrfs_inode *inode,
4393                        const struct fscrypt_str *name)
4394 {
4395         int ret;
4396
4397         ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4398         if (!ret) {
4399                 drop_nlink(&inode->vfs_inode);
4400                 ret = btrfs_update_inode(trans, inode->root, inode);
4401         }
4402         return ret;
4403 }
4404
4405 /*
4406  * helper to start transaction for unlink and rmdir.
4407  *
4408  * unlink and rmdir are special in btrfs, they do not always free space, so
4409  * if we cannot make our reservations the normal way try and see if there is
4410  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4411  * allow the unlink to occur.
4412  */
4413 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4414 {
4415         struct btrfs_root *root = BTRFS_I(dir)->root;
4416
4417         /*
4418          * 1 for the possible orphan item
4419          * 1 for the dir item
4420          * 1 for the dir index
4421          * 1 for the inode ref
4422          * 1 for the inode
4423          * 1 for the parent inode
4424          */
4425         return btrfs_start_transaction_fallback_global_rsv(root, 6);
4426 }
4427
4428 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4429 {
4430         struct btrfs_trans_handle *trans;
4431         struct inode *inode = d_inode(dentry);
4432         int ret;
4433         struct fscrypt_name fname;
4434
4435         ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4436         if (ret)
4437                 return ret;
4438
4439         /* This needs to handle no-key deletions later on */
4440
4441         trans = __unlink_start_trans(dir);
4442         if (IS_ERR(trans)) {
4443                 ret = PTR_ERR(trans);
4444                 goto fscrypt_free;
4445         }
4446
4447         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4448                         0);
4449
4450         ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4451                                  &fname.disk_name);
4452         if (ret)
4453                 goto end_trans;
4454
4455         if (inode->i_nlink == 0) {
4456                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4457                 if (ret)
4458                         goto end_trans;
4459         }
4460
4461 end_trans:
4462         btrfs_end_transaction(trans);
4463         btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4464 fscrypt_free:
4465         fscrypt_free_filename(&fname);
4466         return ret;
4467 }
4468
4469 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4470                                struct inode *dir, struct dentry *dentry)
4471 {
4472         struct btrfs_root *root = BTRFS_I(dir)->root;
4473         struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4474         struct btrfs_path *path;
4475         struct extent_buffer *leaf;
4476         struct btrfs_dir_item *di;
4477         struct btrfs_key key;
4478         u64 index;
4479         int ret;
4480         u64 objectid;
4481         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4482         struct fscrypt_name fname;
4483
4484         ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4485         if (ret)
4486                 return ret;
4487
4488         /* This needs to handle no-key deletions later on */
4489
4490         if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4491                 objectid = inode->root->root_key.objectid;
4492         } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4493                 objectid = inode->location.objectid;
4494         } else {
4495                 WARN_ON(1);
4496                 fscrypt_free_filename(&fname);
4497                 return -EINVAL;
4498         }
4499
4500         path = btrfs_alloc_path();
4501         if (!path) {
4502                 ret = -ENOMEM;
4503                 goto out;
4504         }
4505
4506         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4507                                    &fname.disk_name, -1);
4508         if (IS_ERR_OR_NULL(di)) {
4509                 ret = di ? PTR_ERR(di) : -ENOENT;
4510                 goto out;
4511         }
4512
4513         leaf = path->nodes[0];
4514         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4515         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4516         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4517         if (ret) {
4518                 btrfs_abort_transaction(trans, ret);
4519                 goto out;
4520         }
4521         btrfs_release_path(path);
4522
4523         /*
4524          * This is a placeholder inode for a subvolume we didn't have a
4525          * reference to at the time of the snapshot creation.  In the meantime
4526          * we could have renamed the real subvol link into our snapshot, so
4527          * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4528          * Instead simply lookup the dir_index_item for this entry so we can
4529          * remove it.  Otherwise we know we have a ref to the root and we can
4530          * call btrfs_del_root_ref, and it _shouldn't_ fail.
4531          */
4532         if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4533                 di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4534                 if (IS_ERR_OR_NULL(di)) {
4535                         if (!di)
4536                                 ret = -ENOENT;
4537                         else
4538                                 ret = PTR_ERR(di);
4539                         btrfs_abort_transaction(trans, ret);
4540                         goto out;
4541                 }
4542
4543                 leaf = path->nodes[0];
4544                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4545                 index = key.offset;
4546                 btrfs_release_path(path);
4547         } else {
4548                 ret = btrfs_del_root_ref(trans, objectid,
4549                                          root->root_key.objectid, dir_ino,
4550                                          &index, &fname.disk_name);
4551                 if (ret) {
4552                         btrfs_abort_transaction(trans, ret);
4553                         goto out;
4554                 }
4555         }
4556
4557         ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4558         if (ret) {
4559                 btrfs_abort_transaction(trans, ret);
4560                 goto out;
4561         }
4562
4563         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - fname.disk_name.len * 2);
4564         inode_inc_iversion(dir);
4565         dir->i_mtime = current_time(dir);
4566         dir->i_ctime = dir->i_mtime;
4567         ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4568         if (ret)
4569                 btrfs_abort_transaction(trans, ret);
4570 out:
4571         btrfs_free_path(path);
4572         fscrypt_free_filename(&fname);
4573         return ret;
4574 }
4575
4576 /*
4577  * Helper to check if the subvolume references other subvolumes or if it's
4578  * default.
4579  */
4580 static noinline int may_destroy_subvol(struct btrfs_root *root)
4581 {
4582         struct btrfs_fs_info *fs_info = root->fs_info;
4583         struct btrfs_path *path;
4584         struct btrfs_dir_item *di;
4585         struct btrfs_key key;
4586         struct fscrypt_str name = FSTR_INIT("default", 7);
4587         u64 dir_id;
4588         int ret;
4589
4590         path = btrfs_alloc_path();
4591         if (!path)
4592                 return -ENOMEM;
4593
4594         /* Make sure this root isn't set as the default subvol */
4595         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4596         di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4597                                    dir_id, &name, 0);
4598         if (di && !IS_ERR(di)) {
4599                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4600                 if (key.objectid == root->root_key.objectid) {
4601                         ret = -EPERM;
4602                         btrfs_err(fs_info,
4603                                   "deleting default subvolume %llu is not allowed",
4604                                   key.objectid);
4605                         goto out;
4606                 }
4607                 btrfs_release_path(path);
4608         }
4609
4610         key.objectid = root->root_key.objectid;
4611         key.type = BTRFS_ROOT_REF_KEY;
4612         key.offset = (u64)-1;
4613
4614         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4615         if (ret < 0)
4616                 goto out;
4617         BUG_ON(ret == 0);
4618
4619         ret = 0;
4620         if (path->slots[0] > 0) {
4621                 path->slots[0]--;
4622                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4623                 if (key.objectid == root->root_key.objectid &&
4624                     key.type == BTRFS_ROOT_REF_KEY)
4625                         ret = -ENOTEMPTY;
4626         }
4627 out:
4628         btrfs_free_path(path);
4629         return ret;
4630 }
4631
4632 /* Delete all dentries for inodes belonging to the root */
4633 static void btrfs_prune_dentries(struct btrfs_root *root)
4634 {
4635         struct btrfs_fs_info *fs_info = root->fs_info;
4636         struct rb_node *node;
4637         struct rb_node *prev;
4638         struct btrfs_inode *entry;
4639         struct inode *inode;
4640         u64 objectid = 0;
4641
4642         if (!BTRFS_FS_ERROR(fs_info))
4643                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4644
4645         spin_lock(&root->inode_lock);
4646 again:
4647         node = root->inode_tree.rb_node;
4648         prev = NULL;
4649         while (node) {
4650                 prev = node;
4651                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4652
4653                 if (objectid < btrfs_ino(entry))
4654                         node = node->rb_left;
4655                 else if (objectid > btrfs_ino(entry))
4656                         node = node->rb_right;
4657                 else
4658                         break;
4659         }
4660         if (!node) {
4661                 while (prev) {
4662                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4663                         if (objectid <= btrfs_ino(entry)) {
4664                                 node = prev;
4665                                 break;
4666                         }
4667                         prev = rb_next(prev);
4668                 }
4669         }
4670         while (node) {
4671                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4672                 objectid = btrfs_ino(entry) + 1;
4673                 inode = igrab(&entry->vfs_inode);
4674                 if (inode) {
4675                         spin_unlock(&root->inode_lock);
4676                         if (atomic_read(&inode->i_count) > 1)
4677                                 d_prune_aliases(inode);
4678                         /*
4679                          * btrfs_drop_inode will have it removed from the inode
4680                          * cache when its usage count hits zero.
4681                          */
4682                         iput(inode);
4683                         cond_resched();
4684                         spin_lock(&root->inode_lock);
4685                         goto again;
4686                 }
4687
4688                 if (cond_resched_lock(&root->inode_lock))
4689                         goto again;
4690
4691                 node = rb_next(node);
4692         }
4693         spin_unlock(&root->inode_lock);
4694 }
4695
4696 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4697 {
4698         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4699         struct btrfs_root *root = BTRFS_I(dir)->root;
4700         struct inode *inode = d_inode(dentry);
4701         struct btrfs_root *dest = BTRFS_I(inode)->root;
4702         struct btrfs_trans_handle *trans;
4703         struct btrfs_block_rsv block_rsv;
4704         u64 root_flags;
4705         int ret;
4706
4707         down_write(&fs_info->subvol_sem);
4708
4709         /*
4710          * Don't allow to delete a subvolume with send in progress. This is
4711          * inside the inode lock so the error handling that has to drop the bit
4712          * again is not run concurrently.
4713          */
4714         spin_lock(&dest->root_item_lock);
4715         if (dest->send_in_progress) {
4716                 spin_unlock(&dest->root_item_lock);
4717                 btrfs_warn(fs_info,
4718                            "attempt to delete subvolume %llu during send",
4719                            dest->root_key.objectid);
4720                 ret = -EPERM;
4721                 goto out_up_write;
4722         }
4723         if (atomic_read(&dest->nr_swapfiles)) {
4724                 spin_unlock(&dest->root_item_lock);
4725                 btrfs_warn(fs_info,
4726                            "attempt to delete subvolume %llu with active swapfile",
4727                            root->root_key.objectid);
4728                 ret = -EPERM;
4729                 goto out_up_write;
4730         }
4731         root_flags = btrfs_root_flags(&dest->root_item);
4732         btrfs_set_root_flags(&dest->root_item,
4733                              root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4734         spin_unlock(&dest->root_item_lock);
4735
4736         ret = may_destroy_subvol(dest);
4737         if (ret)
4738                 goto out_undead;
4739
4740         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4741         /*
4742          * One for dir inode,
4743          * two for dir entries,
4744          * two for root ref/backref.
4745          */
4746         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4747         if (ret)
4748                 goto out_undead;
4749
4750         trans = btrfs_start_transaction(root, 0);
4751         if (IS_ERR(trans)) {
4752                 ret = PTR_ERR(trans);
4753                 goto out_release;
4754         }
4755         trans->block_rsv = &block_rsv;
4756         trans->bytes_reserved = block_rsv.size;
4757
4758         btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4759
4760         ret = btrfs_unlink_subvol(trans, dir, dentry);
4761         if (ret) {
4762                 btrfs_abort_transaction(trans, ret);
4763                 goto out_end_trans;
4764         }
4765
4766         ret = btrfs_record_root_in_trans(trans, dest);
4767         if (ret) {
4768                 btrfs_abort_transaction(trans, ret);
4769                 goto out_end_trans;
4770         }
4771
4772         memset(&dest->root_item.drop_progress, 0,
4773                 sizeof(dest->root_item.drop_progress));
4774         btrfs_set_root_drop_level(&dest->root_item, 0);
4775         btrfs_set_root_refs(&dest->root_item, 0);
4776
4777         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4778                 ret = btrfs_insert_orphan_item(trans,
4779                                         fs_info->tree_root,
4780                                         dest->root_key.objectid);
4781                 if (ret) {
4782                         btrfs_abort_transaction(trans, ret);
4783                         goto out_end_trans;
4784                 }
4785         }
4786
4787         ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4788                                   BTRFS_UUID_KEY_SUBVOL,
4789                                   dest->root_key.objectid);
4790         if (ret && ret != -ENOENT) {
4791                 btrfs_abort_transaction(trans, ret);
4792                 goto out_end_trans;
4793         }
4794         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4795                 ret = btrfs_uuid_tree_remove(trans,
4796                                           dest->root_item.received_uuid,
4797                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4798                                           dest->root_key.objectid);
4799                 if (ret && ret != -ENOENT) {
4800                         btrfs_abort_transaction(trans, ret);
4801                         goto out_end_trans;
4802                 }
4803         }
4804
4805         free_anon_bdev(dest->anon_dev);
4806         dest->anon_dev = 0;
4807 out_end_trans:
4808         trans->block_rsv = NULL;
4809         trans->bytes_reserved = 0;
4810         ret = btrfs_end_transaction(trans);
4811         inode->i_flags |= S_DEAD;
4812 out_release:
4813         btrfs_subvolume_release_metadata(root, &block_rsv);
4814 out_undead:
4815         if (ret) {
4816                 spin_lock(&dest->root_item_lock);
4817                 root_flags = btrfs_root_flags(&dest->root_item);
4818                 btrfs_set_root_flags(&dest->root_item,
4819                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4820                 spin_unlock(&dest->root_item_lock);
4821         }
4822 out_up_write:
4823         up_write(&fs_info->subvol_sem);
4824         if (!ret) {
4825                 d_invalidate(dentry);
4826                 btrfs_prune_dentries(dest);
4827                 ASSERT(dest->send_in_progress == 0);
4828         }
4829
4830         return ret;
4831 }
4832
4833 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4834 {
4835         struct inode *inode = d_inode(dentry);
4836         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
4837         int err = 0;
4838         struct btrfs_trans_handle *trans;
4839         u64 last_unlink_trans;
4840         struct fscrypt_name fname;
4841
4842         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4843                 return -ENOTEMPTY;
4844         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
4845                 if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4846                         btrfs_err(fs_info,
4847                         "extent tree v2 doesn't support snapshot deletion yet");
4848                         return -EOPNOTSUPP;
4849                 }
4850                 return btrfs_delete_subvolume(dir, dentry);
4851         }
4852
4853         err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4854         if (err)
4855                 return err;
4856
4857         /* This needs to handle no-key deletions later on */
4858
4859         trans = __unlink_start_trans(dir);
4860         if (IS_ERR(trans)) {
4861                 err = PTR_ERR(trans);
4862                 goto out_notrans;
4863         }
4864
4865         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4866                 err = btrfs_unlink_subvol(trans, dir, dentry);
4867                 goto out;
4868         }
4869
4870         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4871         if (err)
4872                 goto out;
4873
4874         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4875
4876         /* now the directory is empty */
4877         err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4878                                  &fname.disk_name);
4879         if (!err) {
4880                 btrfs_i_size_write(BTRFS_I(inode), 0);
4881                 /*
4882                  * Propagate the last_unlink_trans value of the deleted dir to
4883                  * its parent directory. This is to prevent an unrecoverable
4884                  * log tree in the case we do something like this:
4885                  * 1) create dir foo
4886                  * 2) create snapshot under dir foo
4887                  * 3) delete the snapshot
4888                  * 4) rmdir foo
4889                  * 5) mkdir foo
4890                  * 6) fsync foo or some file inside foo
4891                  */
4892                 if (last_unlink_trans >= trans->transid)
4893                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4894         }
4895 out:
4896         btrfs_end_transaction(trans);
4897 out_notrans:
4898         btrfs_btree_balance_dirty(fs_info);
4899         fscrypt_free_filename(&fname);
4900
4901         return err;
4902 }
4903
4904 /*
4905  * btrfs_truncate_block - read, zero a chunk and write a block
4906  * @inode - inode that we're zeroing
4907  * @from - the offset to start zeroing
4908  * @len - the length to zero, 0 to zero the entire range respective to the
4909  *      offset
4910  * @front - zero up to the offset instead of from the offset on
4911  *
4912  * This will find the block for the "from" offset and cow the block and zero the
4913  * part we want to zero.  This is used with truncate and hole punching.
4914  */
4915 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4916                          int front)
4917 {
4918         struct btrfs_fs_info *fs_info = inode->root->fs_info;
4919         struct address_space *mapping = inode->vfs_inode.i_mapping;
4920         struct extent_io_tree *io_tree = &inode->io_tree;
4921         struct btrfs_ordered_extent *ordered;
4922         struct extent_state *cached_state = NULL;
4923         struct extent_changeset *data_reserved = NULL;
4924         bool only_release_metadata = false;
4925         u32 blocksize = fs_info->sectorsize;
4926         pgoff_t index = from >> PAGE_SHIFT;
4927         unsigned offset = from & (blocksize - 1);
4928         struct page *page;
4929         gfp_t mask = btrfs_alloc_write_mask(mapping);
4930         size_t write_bytes = blocksize;
4931         int ret = 0;
4932         u64 block_start;
4933         u64 block_end;
4934
4935         if (IS_ALIGNED(offset, blocksize) &&
4936             (!len || IS_ALIGNED(len, blocksize)))
4937                 goto out;
4938
4939         block_start = round_down(from, blocksize);
4940         block_end = block_start + blocksize - 1;
4941
4942         ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4943                                           blocksize, false);
4944         if (ret < 0) {
4945                 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4946                         /* For nocow case, no need to reserve data space */
4947                         only_release_metadata = true;
4948                 } else {
4949                         goto out;
4950                 }
4951         }
4952         ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4953         if (ret < 0) {
4954                 if (!only_release_metadata)
4955                         btrfs_free_reserved_data_space(inode, data_reserved,
4956                                                        block_start, blocksize);
4957                 goto out;
4958         }
4959 again:
4960         page = find_or_create_page(mapping, index, mask);
4961         if (!page) {
4962                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4963                                              blocksize, true);
4964                 btrfs_delalloc_release_extents(inode, blocksize);
4965                 ret = -ENOMEM;
4966                 goto out;
4967         }
4968
4969         if (!PageUptodate(page)) {
4970                 ret = btrfs_read_folio(NULL, page_folio(page));
4971                 lock_page(page);
4972                 if (page->mapping != mapping) {
4973                         unlock_page(page);
4974                         put_page(page);
4975                         goto again;
4976                 }
4977                 if (!PageUptodate(page)) {
4978                         ret = -EIO;
4979                         goto out_unlock;
4980                 }
4981         }
4982
4983         /*
4984          * We unlock the page after the io is completed and then re-lock it
4985          * above.  release_folio() could have come in between that and cleared
4986          * PagePrivate(), but left the page in the mapping.  Set the page mapped
4987          * here to make sure it's properly set for the subpage stuff.
4988          */
4989         ret = set_page_extent_mapped(page);
4990         if (ret < 0)
4991                 goto out_unlock;
4992
4993         wait_on_page_writeback(page);
4994
4995         lock_extent(io_tree, block_start, block_end, &cached_state);
4996
4997         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4998         if (ordered) {
4999                 unlock_extent(io_tree, block_start, block_end, &cached_state);
5000                 unlock_page(page);
5001                 put_page(page);
5002                 btrfs_start_ordered_extent(ordered, 1);
5003                 btrfs_put_ordered_extent(ordered);
5004                 goto again;
5005         }
5006
5007         clear_extent_bit(&inode->io_tree, block_start, block_end,
5008                          EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
5009                          &cached_state);
5010
5011         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
5012                                         &cached_state);
5013         if (ret) {
5014                 unlock_extent(io_tree, block_start, block_end, &cached_state);
5015                 goto out_unlock;
5016         }
5017
5018         if (offset != blocksize) {
5019                 if (!len)
5020                         len = blocksize - offset;
5021                 if (front)
5022                         memzero_page(page, (block_start - page_offset(page)),
5023                                      offset);
5024                 else
5025                         memzero_page(page, (block_start - page_offset(page)) + offset,
5026                                      len);
5027         }
5028         btrfs_page_clear_checked(fs_info, page, block_start,
5029                                  block_end + 1 - block_start);
5030         btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
5031         unlock_extent(io_tree, block_start, block_end, &cached_state);
5032
5033         if (only_release_metadata)
5034                 set_extent_bit(&inode->io_tree, block_start, block_end,
5035                                EXTENT_NORESERVE, NULL, GFP_NOFS);
5036
5037 out_unlock:
5038         if (ret) {
5039                 if (only_release_metadata)
5040                         btrfs_delalloc_release_metadata(inode, blocksize, true);
5041                 else
5042                         btrfs_delalloc_release_space(inode, data_reserved,
5043                                         block_start, blocksize, true);
5044         }
5045         btrfs_delalloc_release_extents(inode, blocksize);
5046         unlock_page(page);
5047         put_page(page);
5048 out:
5049         if (only_release_metadata)
5050                 btrfs_check_nocow_unlock(inode);
5051         extent_changeset_free(data_reserved);
5052         return ret;
5053 }
5054
5055 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
5056                              u64 offset, u64 len)
5057 {
5058         struct btrfs_fs_info *fs_info = root->fs_info;
5059         struct btrfs_trans_handle *trans;
5060         struct btrfs_drop_extents_args drop_args = { 0 };
5061         int ret;
5062
5063         /*
5064          * If NO_HOLES is enabled, we don't need to do anything.
5065          * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5066          * or btrfs_update_inode() will be called, which guarantee that the next
5067          * fsync will know this inode was changed and needs to be logged.
5068          */
5069         if (btrfs_fs_incompat(fs_info, NO_HOLES))
5070                 return 0;
5071
5072         /*
5073          * 1 - for the one we're dropping
5074          * 1 - for the one we're adding
5075          * 1 - for updating the inode.
5076          */
5077         trans = btrfs_start_transaction(root, 3);
5078         if (IS_ERR(trans))
5079                 return PTR_ERR(trans);
5080
5081         drop_args.start = offset;
5082         drop_args.end = offset + len;
5083         drop_args.drop_cache = true;
5084
5085         ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5086         if (ret) {
5087                 btrfs_abort_transaction(trans, ret);
5088                 btrfs_end_transaction(trans);
5089                 return ret;
5090         }
5091
5092         ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5093         if (ret) {
5094                 btrfs_abort_transaction(trans, ret);
5095         } else {
5096                 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5097                 btrfs_update_inode(trans, root, inode);
5098         }
5099         btrfs_end_transaction(trans);
5100         return ret;
5101 }
5102
5103 /*
5104  * This function puts in dummy file extents for the area we're creating a hole
5105  * for.  So if we are truncating this file to a larger size we need to insert
5106  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5107  * the range between oldsize and size
5108  */
5109 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5110 {
5111         struct btrfs_root *root = inode->root;
5112         struct btrfs_fs_info *fs_info = root->fs_info;
5113         struct extent_io_tree *io_tree = &inode->io_tree;
5114         struct extent_map *em = NULL;
5115         struct extent_state *cached_state = NULL;
5116         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5117         u64 block_end = ALIGN(size, fs_info->sectorsize);
5118         u64 last_byte;
5119         u64 cur_offset;
5120         u64 hole_size;
5121         int err = 0;
5122
5123         /*
5124          * If our size started in the middle of a block we need to zero out the
5125          * rest of the block before we expand the i_size, otherwise we could
5126          * expose stale data.
5127          */
5128         err = btrfs_truncate_block(inode, oldsize, 0, 0);
5129         if (err)
5130                 return err;
5131
5132         if (size <= hole_start)
5133                 return 0;
5134
5135         btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5136                                            &cached_state);
5137         cur_offset = hole_start;
5138         while (1) {
5139                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5140                                       block_end - cur_offset);
5141                 if (IS_ERR(em)) {
5142                         err = PTR_ERR(em);
5143                         em = NULL;
5144                         break;
5145                 }
5146                 last_byte = min(extent_map_end(em), block_end);
5147                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5148                 hole_size = last_byte - cur_offset;
5149
5150                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5151                         struct extent_map *hole_em;
5152
5153                         err = maybe_insert_hole(root, inode, cur_offset,
5154                                                 hole_size);
5155                         if (err)
5156                                 break;
5157
5158                         err = btrfs_inode_set_file_extent_range(inode,
5159                                                         cur_offset, hole_size);
5160                         if (err)
5161                                 break;
5162
5163                         hole_em = alloc_extent_map();
5164                         if (!hole_em) {
5165                                 btrfs_drop_extent_map_range(inode, cur_offset,
5166                                                     cur_offset + hole_size - 1,
5167                                                     false);
5168                                 btrfs_set_inode_full_sync(inode);
5169                                 goto next;
5170                         }
5171                         hole_em->start = cur_offset;
5172                         hole_em->len = hole_size;
5173                         hole_em->orig_start = cur_offset;
5174
5175                         hole_em->block_start = EXTENT_MAP_HOLE;
5176                         hole_em->block_len = 0;
5177                         hole_em->orig_block_len = 0;
5178                         hole_em->ram_bytes = hole_size;
5179                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
5180                         hole_em->generation = fs_info->generation;
5181
5182                         err = btrfs_replace_extent_map_range(inode, hole_em, true);
5183                         free_extent_map(hole_em);
5184                 } else {
5185                         err = btrfs_inode_set_file_extent_range(inode,
5186                                                         cur_offset, hole_size);
5187                         if (err)
5188                                 break;
5189                 }
5190 next:
5191                 free_extent_map(em);
5192                 em = NULL;
5193                 cur_offset = last_byte;
5194                 if (cur_offset >= block_end)
5195                         break;
5196         }
5197         free_extent_map(em);
5198         unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5199         return err;
5200 }
5201
5202 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5203 {
5204         struct btrfs_root *root = BTRFS_I(inode)->root;
5205         struct btrfs_trans_handle *trans;
5206         loff_t oldsize = i_size_read(inode);
5207         loff_t newsize = attr->ia_size;
5208         int mask = attr->ia_valid;
5209         int ret;
5210
5211         /*
5212          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5213          * special case where we need to update the times despite not having
5214          * these flags set.  For all other operations the VFS set these flags
5215          * explicitly if it wants a timestamp update.
5216          */
5217         if (newsize != oldsize) {
5218                 inode_inc_iversion(inode);
5219                 if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5220                         inode->i_mtime = current_time(inode);
5221                         inode->i_ctime = inode->i_mtime;
5222                 }
5223         }
5224
5225         if (newsize > oldsize) {
5226                 /*
5227                  * Don't do an expanding truncate while snapshotting is ongoing.
5228                  * This is to ensure the snapshot captures a fully consistent
5229                  * state of this file - if the snapshot captures this expanding
5230                  * truncation, it must capture all writes that happened before
5231                  * this truncation.
5232                  */
5233                 btrfs_drew_write_lock(&root->snapshot_lock);
5234                 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5235                 if (ret) {
5236                         btrfs_drew_write_unlock(&root->snapshot_lock);
5237                         return ret;
5238                 }
5239
5240                 trans = btrfs_start_transaction(root, 1);
5241                 if (IS_ERR(trans)) {
5242                         btrfs_drew_write_unlock(&root->snapshot_lock);
5243                         return PTR_ERR(trans);
5244                 }
5245
5246                 i_size_write(inode, newsize);
5247                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5248                 pagecache_isize_extended(inode, oldsize, newsize);
5249                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5250                 btrfs_drew_write_unlock(&root->snapshot_lock);
5251                 btrfs_end_transaction(trans);
5252         } else {
5253                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5254
5255                 if (btrfs_is_zoned(fs_info)) {
5256                         ret = btrfs_wait_ordered_range(inode,
5257                                         ALIGN(newsize, fs_info->sectorsize),
5258                                         (u64)-1);
5259                         if (ret)
5260                                 return ret;
5261                 }
5262
5263                 /*
5264                  * We're truncating a file that used to have good data down to
5265                  * zero. Make sure any new writes to the file get on disk
5266                  * on close.
5267                  */
5268                 if (newsize == 0)
5269                         set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5270                                 &BTRFS_I(inode)->runtime_flags);
5271
5272                 truncate_setsize(inode, newsize);
5273
5274                 inode_dio_wait(inode);
5275
5276                 ret = btrfs_truncate(inode, newsize == oldsize);
5277                 if (ret && inode->i_nlink) {
5278                         int err;
5279
5280                         /*
5281                          * Truncate failed, so fix up the in-memory size. We
5282                          * adjusted disk_i_size down as we removed extents, so
5283                          * wait for disk_i_size to be stable and then update the
5284                          * in-memory size to match.
5285                          */
5286                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5287                         if (err)
5288                                 return err;
5289                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5290                 }
5291         }
5292
5293         return ret;
5294 }
5295
5296 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5297                          struct iattr *attr)
5298 {
5299         struct inode *inode = d_inode(dentry);
5300         struct btrfs_root *root = BTRFS_I(inode)->root;
5301         int err;
5302
5303         if (btrfs_root_readonly(root))
5304                 return -EROFS;
5305
5306         err = setattr_prepare(mnt_userns, dentry, attr);
5307         if (err)
5308                 return err;
5309
5310         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5311                 err = btrfs_setsize(inode, attr);
5312                 if (err)
5313                         return err;
5314         }
5315
5316         if (attr->ia_valid) {
5317                 setattr_copy(mnt_userns, inode, attr);
5318                 inode_inc_iversion(inode);
5319                 err = btrfs_dirty_inode(inode);
5320
5321                 if (!err && attr->ia_valid & ATTR_MODE)
5322                         err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
5323         }
5324
5325         return err;
5326 }
5327
5328 /*
5329  * While truncating the inode pages during eviction, we get the VFS
5330  * calling btrfs_invalidate_folio() against each folio of the inode. This
5331  * is slow because the calls to btrfs_invalidate_folio() result in a
5332  * huge amount of calls to lock_extent() and clear_extent_bit(),
5333  * which keep merging and splitting extent_state structures over and over,
5334  * wasting lots of time.
5335  *
5336  * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5337  * skip all those expensive operations on a per folio basis and do only
5338  * the ordered io finishing, while we release here the extent_map and
5339  * extent_state structures, without the excessive merging and splitting.
5340  */
5341 static void evict_inode_truncate_pages(struct inode *inode)
5342 {
5343         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5344         struct rb_node *node;
5345
5346         ASSERT(inode->i_state & I_FREEING);
5347         truncate_inode_pages_final(&inode->i_data);
5348
5349         btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5350
5351         /*
5352          * Keep looping until we have no more ranges in the io tree.
5353          * We can have ongoing bios started by readahead that have
5354          * their endio callback (extent_io.c:end_bio_extent_readpage)
5355          * still in progress (unlocked the pages in the bio but did not yet
5356          * unlocked the ranges in the io tree). Therefore this means some
5357          * ranges can still be locked and eviction started because before
5358          * submitting those bios, which are executed by a separate task (work
5359          * queue kthread), inode references (inode->i_count) were not taken
5360          * (which would be dropped in the end io callback of each bio).
5361          * Therefore here we effectively end up waiting for those bios and
5362          * anyone else holding locked ranges without having bumped the inode's
5363          * reference count - if we don't do it, when they access the inode's
5364          * io_tree to unlock a range it may be too late, leading to an
5365          * use-after-free issue.
5366          */
5367         spin_lock(&io_tree->lock);
5368         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5369                 struct extent_state *state;
5370                 struct extent_state *cached_state = NULL;
5371                 u64 start;
5372                 u64 end;
5373                 unsigned state_flags;
5374
5375                 node = rb_first(&io_tree->state);
5376                 state = rb_entry(node, struct extent_state, rb_node);
5377                 start = state->start;
5378                 end = state->end;
5379                 state_flags = state->state;
5380                 spin_unlock(&io_tree->lock);
5381
5382                 lock_extent(io_tree, start, end, &cached_state);
5383
5384                 /*
5385                  * If still has DELALLOC flag, the extent didn't reach disk,
5386                  * and its reserved space won't be freed by delayed_ref.
5387                  * So we need to free its reserved space here.
5388                  * (Refer to comment in btrfs_invalidate_folio, case 2)
5389                  *
5390                  * Note, end is the bytenr of last byte, so we need + 1 here.
5391                  */
5392                 if (state_flags & EXTENT_DELALLOC)
5393                         btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5394                                                end - start + 1, NULL);
5395
5396                 clear_extent_bit(io_tree, start, end,
5397                                  EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5398                                  &cached_state);
5399
5400                 cond_resched();
5401                 spin_lock(&io_tree->lock);
5402         }
5403         spin_unlock(&io_tree->lock);
5404 }
5405
5406 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5407                                                         struct btrfs_block_rsv *rsv)
5408 {
5409         struct btrfs_fs_info *fs_info = root->fs_info;
5410         struct btrfs_trans_handle *trans;
5411         u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5412         int ret;
5413
5414         /*
5415          * Eviction should be taking place at some place safe because of our
5416          * delayed iputs.  However the normal flushing code will run delayed
5417          * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5418          *
5419          * We reserve the delayed_refs_extra here again because we can't use
5420          * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5421          * above.  We reserve our extra bit here because we generate a ton of
5422          * delayed refs activity by truncating.
5423          *
5424          * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5425          * if we fail to make this reservation we can re-try without the
5426          * delayed_refs_extra so we can make some forward progress.
5427          */
5428         ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5429                                      BTRFS_RESERVE_FLUSH_EVICT);
5430         if (ret) {
5431                 ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5432                                              BTRFS_RESERVE_FLUSH_EVICT);
5433                 if (ret) {
5434                         btrfs_warn(fs_info,
5435                                    "could not allocate space for delete; will truncate on mount");
5436                         return ERR_PTR(-ENOSPC);
5437                 }
5438                 delayed_refs_extra = 0;
5439         }
5440
5441         trans = btrfs_join_transaction(root);
5442         if (IS_ERR(trans))
5443                 return trans;
5444
5445         if (delayed_refs_extra) {
5446                 trans->block_rsv = &fs_info->trans_block_rsv;
5447                 trans->bytes_reserved = delayed_refs_extra;
5448                 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5449                                         delayed_refs_extra, 1);
5450         }
5451         return trans;
5452 }
5453
5454 void btrfs_evict_inode(struct inode *inode)
5455 {
5456         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5457         struct btrfs_trans_handle *trans;
5458         struct btrfs_root *root = BTRFS_I(inode)->root;
5459         struct btrfs_block_rsv *rsv;
5460         int ret;
5461
5462         trace_btrfs_inode_evict(inode);
5463
5464         if (!root) {
5465                 fsverity_cleanup_inode(inode);
5466                 clear_inode(inode);
5467                 return;
5468         }
5469
5470         evict_inode_truncate_pages(inode);
5471
5472         if (inode->i_nlink &&
5473             ((btrfs_root_refs(&root->root_item) != 0 &&
5474               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5475              btrfs_is_free_space_inode(BTRFS_I(inode))))
5476                 goto no_delete;
5477
5478         if (is_bad_inode(inode))
5479                 goto no_delete;
5480
5481         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5482
5483         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5484                 goto no_delete;
5485
5486         if (inode->i_nlink > 0) {
5487                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5488                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5489                 goto no_delete;
5490         }
5491
5492         /*
5493          * This makes sure the inode item in tree is uptodate and the space for
5494          * the inode update is released.
5495          */
5496         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5497         if (ret)
5498                 goto no_delete;
5499
5500         /*
5501          * This drops any pending insert or delete operations we have for this
5502          * inode.  We could have a delayed dir index deletion queued up, but
5503          * we're removing the inode completely so that'll be taken care of in
5504          * the truncate.
5505          */
5506         btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5507
5508         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5509         if (!rsv)
5510                 goto no_delete;
5511         rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5512         rsv->failfast = true;
5513
5514         btrfs_i_size_write(BTRFS_I(inode), 0);
5515
5516         while (1) {
5517                 struct btrfs_truncate_control control = {
5518                         .inode = BTRFS_I(inode),
5519                         .ino = btrfs_ino(BTRFS_I(inode)),
5520                         .new_size = 0,
5521                         .min_type = 0,
5522                 };
5523
5524                 trans = evict_refill_and_join(root, rsv);
5525                 if (IS_ERR(trans))
5526                         goto free_rsv;
5527
5528                 trans->block_rsv = rsv;
5529
5530                 ret = btrfs_truncate_inode_items(trans, root, &control);
5531                 trans->block_rsv = &fs_info->trans_block_rsv;
5532                 btrfs_end_transaction(trans);
5533                 btrfs_btree_balance_dirty(fs_info);
5534                 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5535                         goto free_rsv;
5536                 else if (!ret)
5537                         break;
5538         }
5539
5540         /*
5541          * Errors here aren't a big deal, it just means we leave orphan items in
5542          * the tree. They will be cleaned up on the next mount. If the inode
5543          * number gets reused, cleanup deletes the orphan item without doing
5544          * anything, and unlink reuses the existing orphan item.
5545          *
5546          * If it turns out that we are dropping too many of these, we might want
5547          * to add a mechanism for retrying these after a commit.
5548          */
5549         trans = evict_refill_and_join(root, rsv);
5550         if (!IS_ERR(trans)) {
5551                 trans->block_rsv = rsv;
5552                 btrfs_orphan_del(trans, BTRFS_I(inode));
5553                 trans->block_rsv = &fs_info->trans_block_rsv;
5554                 btrfs_end_transaction(trans);
5555         }
5556
5557 free_rsv:
5558         btrfs_free_block_rsv(fs_info, rsv);
5559 no_delete:
5560         /*
5561          * If we didn't successfully delete, the orphan item will still be in
5562          * the tree and we'll retry on the next mount. Again, we might also want
5563          * to retry these periodically in the future.
5564          */
5565         btrfs_remove_delayed_node(BTRFS_I(inode));
5566         fsverity_cleanup_inode(inode);
5567         clear_inode(inode);
5568 }
5569
5570 /*
5571  * Return the key found in the dir entry in the location pointer, fill @type
5572  * with BTRFS_FT_*, and return 0.
5573  *
5574  * If no dir entries were found, returns -ENOENT.
5575  * If found a corrupted location in dir entry, returns -EUCLEAN.
5576  */
5577 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5578                                struct btrfs_key *location, u8 *type)
5579 {
5580         struct btrfs_dir_item *di;
5581         struct btrfs_path *path;
5582         struct btrfs_root *root = BTRFS_I(dir)->root;
5583         int ret = 0;
5584         struct fscrypt_name fname;
5585
5586         path = btrfs_alloc_path();
5587         if (!path)
5588                 return -ENOMEM;
5589
5590         ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
5591         if (ret)
5592                 goto out;
5593
5594         /* This needs to handle no-key deletions later on */
5595
5596         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5597                                    &fname.disk_name, 0);
5598         if (IS_ERR_OR_NULL(di)) {
5599                 ret = di ? PTR_ERR(di) : -ENOENT;
5600                 goto out;
5601         }
5602
5603         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5604         if (location->type != BTRFS_INODE_ITEM_KEY &&
5605             location->type != BTRFS_ROOT_ITEM_KEY) {
5606                 ret = -EUCLEAN;
5607                 btrfs_warn(root->fs_info,
5608 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5609                            __func__, fname.disk_name.name, btrfs_ino(BTRFS_I(dir)),
5610                            location->objectid, location->type, location->offset);
5611         }
5612         if (!ret)
5613                 *type = btrfs_dir_type(path->nodes[0], di);
5614 out:
5615         fscrypt_free_filename(&fname);
5616         btrfs_free_path(path);
5617         return ret;
5618 }
5619
5620 /*
5621  * when we hit a tree root in a directory, the btrfs part of the inode
5622  * needs to be changed to reflect the root directory of the tree root.  This
5623  * is kind of like crossing a mount point.
5624  */
5625 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5626                                     struct inode *dir,
5627                                     struct dentry *dentry,
5628                                     struct btrfs_key *location,
5629                                     struct btrfs_root **sub_root)
5630 {
5631         struct btrfs_path *path;
5632         struct btrfs_root *new_root;
5633         struct btrfs_root_ref *ref;
5634         struct extent_buffer *leaf;
5635         struct btrfs_key key;
5636         int ret;
5637         int err = 0;
5638         struct fscrypt_name fname;
5639
5640         ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
5641         if (ret)
5642                 return ret;
5643
5644         path = btrfs_alloc_path();
5645         if (!path) {
5646                 err = -ENOMEM;
5647                 goto out;
5648         }
5649
5650         err = -ENOENT;
5651         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5652         key.type = BTRFS_ROOT_REF_KEY;
5653         key.offset = location->objectid;
5654
5655         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5656         if (ret) {
5657                 if (ret < 0)
5658                         err = ret;
5659                 goto out;
5660         }
5661
5662         leaf = path->nodes[0];
5663         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5664         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5665             btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5666                 goto out;
5667
5668         ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5669                                    (unsigned long)(ref + 1), fname.disk_name.len);
5670         if (ret)
5671                 goto out;
5672
5673         btrfs_release_path(path);
5674
5675         new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5676         if (IS_ERR(new_root)) {
5677                 err = PTR_ERR(new_root);
5678                 goto out;
5679         }
5680
5681         *sub_root = new_root;
5682         location->objectid = btrfs_root_dirid(&new_root->root_item);
5683         location->type = BTRFS_INODE_ITEM_KEY;
5684         location->offset = 0;
5685         err = 0;
5686 out:
5687         btrfs_free_path(path);
5688         fscrypt_free_filename(&fname);
5689         return err;
5690 }
5691
5692 static void inode_tree_add(struct inode *inode)
5693 {
5694         struct btrfs_root *root = BTRFS_I(inode)->root;
5695         struct btrfs_inode *entry;
5696         struct rb_node **p;
5697         struct rb_node *parent;
5698         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5699         u64 ino = btrfs_ino(BTRFS_I(inode));
5700
5701         if (inode_unhashed(inode))
5702                 return;
5703         parent = NULL;
5704         spin_lock(&root->inode_lock);
5705         p = &root->inode_tree.rb_node;
5706         while (*p) {
5707                 parent = *p;
5708                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5709
5710                 if (ino < btrfs_ino(entry))
5711                         p = &parent->rb_left;
5712                 else if (ino > btrfs_ino(entry))
5713                         p = &parent->rb_right;
5714                 else {
5715                         WARN_ON(!(entry->vfs_inode.i_state &
5716                                   (I_WILL_FREE | I_FREEING)));
5717                         rb_replace_node(parent, new, &root->inode_tree);
5718                         RB_CLEAR_NODE(parent);
5719                         spin_unlock(&root->inode_lock);
5720                         return;
5721                 }
5722         }
5723         rb_link_node(new, parent, p);
5724         rb_insert_color(new, &root->inode_tree);
5725         spin_unlock(&root->inode_lock);
5726 }
5727
5728 static void inode_tree_del(struct btrfs_inode *inode)
5729 {
5730         struct btrfs_root *root = inode->root;
5731         int empty = 0;
5732
5733         spin_lock(&root->inode_lock);
5734         if (!RB_EMPTY_NODE(&inode->rb_node)) {
5735                 rb_erase(&inode->rb_node, &root->inode_tree);
5736                 RB_CLEAR_NODE(&inode->rb_node);
5737                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5738         }
5739         spin_unlock(&root->inode_lock);
5740
5741         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5742                 spin_lock(&root->inode_lock);
5743                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5744                 spin_unlock(&root->inode_lock);
5745                 if (empty)
5746                         btrfs_add_dead_root(root);
5747         }
5748 }
5749
5750
5751 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5752 {
5753         struct btrfs_iget_args *args = p;
5754
5755         inode->i_ino = args->ino;
5756         BTRFS_I(inode)->location.objectid = args->ino;
5757         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5758         BTRFS_I(inode)->location.offset = 0;
5759         BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5760         BUG_ON(args->root && !BTRFS_I(inode)->root);
5761
5762         if (args->root && args->root == args->root->fs_info->tree_root &&
5763             args->ino != BTRFS_BTREE_INODE_OBJECTID)
5764                 set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5765                         &BTRFS_I(inode)->runtime_flags);
5766         return 0;
5767 }
5768
5769 static int btrfs_find_actor(struct inode *inode, void *opaque)
5770 {
5771         struct btrfs_iget_args *args = opaque;
5772
5773         return args->ino == BTRFS_I(inode)->location.objectid &&
5774                 args->root == BTRFS_I(inode)->root;
5775 }
5776
5777 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5778                                        struct btrfs_root *root)
5779 {
5780         struct inode *inode;
5781         struct btrfs_iget_args args;
5782         unsigned long hashval = btrfs_inode_hash(ino, root);
5783
5784         args.ino = ino;
5785         args.root = root;
5786
5787         inode = iget5_locked(s, hashval, btrfs_find_actor,
5788                              btrfs_init_locked_inode,
5789                              (void *)&args);
5790         return inode;
5791 }
5792
5793 /*
5794  * Get an inode object given its inode number and corresponding root.
5795  * Path can be preallocated to prevent recursing back to iget through
5796  * allocator. NULL is also valid but may require an additional allocation
5797  * later.
5798  */
5799 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5800                               struct btrfs_root *root, struct btrfs_path *path)
5801 {
5802         struct inode *inode;
5803
5804         inode = btrfs_iget_locked(s, ino, root);
5805         if (!inode)
5806                 return ERR_PTR(-ENOMEM);
5807
5808         if (inode->i_state & I_NEW) {
5809                 int ret;
5810
5811                 ret = btrfs_read_locked_inode(inode, path);
5812                 if (!ret) {
5813                         inode_tree_add(inode);
5814                         unlock_new_inode(inode);
5815                 } else {
5816                         iget_failed(inode);
5817                         /*
5818                          * ret > 0 can come from btrfs_search_slot called by
5819                          * btrfs_read_locked_inode, this means the inode item
5820                          * was not found.
5821                          */
5822                         if (ret > 0)
5823                                 ret = -ENOENT;
5824                         inode = ERR_PTR(ret);
5825                 }
5826         }
5827
5828         return inode;
5829 }
5830
5831 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5832 {
5833         return btrfs_iget_path(s, ino, root, NULL);
5834 }
5835
5836 static struct inode *new_simple_dir(struct super_block *s,
5837                                     struct btrfs_key *key,
5838                                     struct btrfs_root *root)
5839 {
5840         struct inode *inode = new_inode(s);
5841
5842         if (!inode)
5843                 return ERR_PTR(-ENOMEM);
5844
5845         BTRFS_I(inode)->root = btrfs_grab_root(root);
5846         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5847         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5848
5849         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5850         /*
5851          * We only need lookup, the rest is read-only and there's no inode
5852          * associated with the dentry
5853          */
5854         inode->i_op = &simple_dir_inode_operations;
5855         inode->i_opflags &= ~IOP_XATTR;
5856         inode->i_fop = &simple_dir_operations;
5857         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5858         inode->i_mtime = current_time(inode);
5859         inode->i_atime = inode->i_mtime;
5860         inode->i_ctime = inode->i_mtime;
5861         BTRFS_I(inode)->i_otime = inode->i_mtime;
5862
5863         return inode;
5864 }
5865
5866 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5867 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5868 static_assert(BTRFS_FT_DIR == FT_DIR);
5869 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5870 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5871 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5872 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5873 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5874
5875 static inline u8 btrfs_inode_type(struct inode *inode)
5876 {
5877         return fs_umode_to_ftype(inode->i_mode);
5878 }
5879
5880 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5881 {
5882         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5883         struct inode *inode;
5884         struct btrfs_root *root = BTRFS_I(dir)->root;
5885         struct btrfs_root *sub_root = root;
5886         struct btrfs_key location;
5887         u8 di_type = 0;
5888         int ret = 0;
5889
5890         if (dentry->d_name.len > BTRFS_NAME_LEN)
5891                 return ERR_PTR(-ENAMETOOLONG);
5892
5893         ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5894         if (ret < 0)
5895                 return ERR_PTR(ret);
5896
5897         if (location.type == BTRFS_INODE_ITEM_KEY) {
5898                 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5899                 if (IS_ERR(inode))
5900                         return inode;
5901
5902                 /* Do extra check against inode mode with di_type */
5903                 if (btrfs_inode_type(inode) != di_type) {
5904                         btrfs_crit(fs_info,
5905 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5906                                   inode->i_mode, btrfs_inode_type(inode),
5907                                   di_type);
5908                         iput(inode);
5909                         return ERR_PTR(-EUCLEAN);
5910                 }
5911                 return inode;
5912         }
5913
5914         ret = fixup_tree_root_location(fs_info, dir, dentry,
5915                                        &location, &sub_root);
5916         if (ret < 0) {
5917                 if (ret != -ENOENT)
5918                         inode = ERR_PTR(ret);
5919                 else
5920                         inode = new_simple_dir(dir->i_sb, &location, root);
5921         } else {
5922                 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5923                 btrfs_put_root(sub_root);
5924
5925                 if (IS_ERR(inode))
5926                         return inode;
5927
5928                 down_read(&fs_info->cleanup_work_sem);
5929                 if (!sb_rdonly(inode->i_sb))
5930                         ret = btrfs_orphan_cleanup(sub_root);
5931                 up_read(&fs_info->cleanup_work_sem);
5932                 if (ret) {
5933                         iput(inode);
5934                         inode = ERR_PTR(ret);
5935                 }
5936         }
5937
5938         return inode;
5939 }
5940
5941 static int btrfs_dentry_delete(const struct dentry *dentry)
5942 {
5943         struct btrfs_root *root;
5944         struct inode *inode = d_inode(dentry);
5945
5946         if (!inode && !IS_ROOT(dentry))
5947                 inode = d_inode(dentry->d_parent);
5948
5949         if (inode) {
5950                 root = BTRFS_I(inode)->root;
5951                 if (btrfs_root_refs(&root->root_item) == 0)
5952                         return 1;
5953
5954                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5955                         return 1;
5956         }
5957         return 0;
5958 }
5959
5960 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5961                                    unsigned int flags)
5962 {
5963         struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5964
5965         if (inode == ERR_PTR(-ENOENT))
5966                 inode = NULL;
5967         return d_splice_alias(inode, dentry);
5968 }
5969
5970 /*
5971  * Find the highest existing sequence number in a directory and then set the
5972  * in-memory index_cnt variable to the first free sequence number.
5973  */
5974 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5975 {
5976         struct btrfs_root *root = inode->root;
5977         struct btrfs_key key, found_key;
5978         struct btrfs_path *path;
5979         struct extent_buffer *leaf;
5980         int ret;
5981
5982         key.objectid = btrfs_ino(inode);
5983         key.type = BTRFS_DIR_INDEX_KEY;
5984         key.offset = (u64)-1;
5985
5986         path = btrfs_alloc_path();
5987         if (!path)
5988                 return -ENOMEM;
5989
5990         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5991         if (ret < 0)
5992                 goto out;
5993         /* FIXME: we should be able to handle this */
5994         if (ret == 0)
5995                 goto out;
5996         ret = 0;
5997
5998         if (path->slots[0] == 0) {
5999                 inode->index_cnt = BTRFS_DIR_START_INDEX;
6000                 goto out;
6001         }
6002
6003         path->slots[0]--;
6004
6005         leaf = path->nodes[0];
6006         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6007
6008         if (found_key.objectid != btrfs_ino(inode) ||
6009             found_key.type != BTRFS_DIR_INDEX_KEY) {
6010                 inode->index_cnt = BTRFS_DIR_START_INDEX;
6011                 goto out;
6012         }
6013
6014         inode->index_cnt = found_key.offset + 1;
6015 out:
6016         btrfs_free_path(path);
6017         return ret;
6018 }
6019
6020 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
6021 {
6022         int ret = 0;
6023
6024         btrfs_inode_lock(&dir->vfs_inode, 0);
6025         if (dir->index_cnt == (u64)-1) {
6026                 ret = btrfs_inode_delayed_dir_index_count(dir);
6027                 if (ret) {
6028                         ret = btrfs_set_inode_index_count(dir);
6029                         if (ret)
6030                                 goto out;
6031                 }
6032         }
6033
6034         /* index_cnt is the index number of next new entry, so decrement it. */
6035         *index = dir->index_cnt - 1;
6036 out:
6037         btrfs_inode_unlock(&dir->vfs_inode, 0);
6038
6039         return ret;
6040 }
6041
6042 /*
6043  * All this infrastructure exists because dir_emit can fault, and we are holding
6044  * the tree lock when doing readdir.  For now just allocate a buffer and copy
6045  * our information into that, and then dir_emit from the buffer.  This is
6046  * similar to what NFS does, only we don't keep the buffer around in pagecache
6047  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
6048  * copy_to_user_inatomic so we don't have to worry about page faulting under the
6049  * tree lock.
6050  */
6051 static int btrfs_opendir(struct inode *inode, struct file *file)
6052 {
6053         struct btrfs_file_private *private;
6054         u64 last_index;
6055         int ret;
6056
6057         ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
6058         if (ret)
6059                 return ret;
6060
6061         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
6062         if (!private)
6063                 return -ENOMEM;
6064         private->last_index = last_index;
6065         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6066         if (!private->filldir_buf) {
6067                 kfree(private);
6068                 return -ENOMEM;
6069         }
6070         file->private_data = private;
6071         return 0;
6072 }
6073
6074 static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
6075 {
6076         struct btrfs_file_private *private = file->private_data;
6077         int ret;
6078
6079         ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
6080                                        &private->last_index);
6081         if (ret)
6082                 return ret;
6083
6084         return generic_file_llseek(file, offset, whence);
6085 }
6086
6087 struct dir_entry {
6088         u64 ino;
6089         u64 offset;
6090         unsigned type;
6091         int name_len;
6092 };
6093
6094 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6095 {
6096         while (entries--) {
6097                 struct dir_entry *entry = addr;
6098                 char *name = (char *)(entry + 1);
6099
6100                 ctx->pos = get_unaligned(&entry->offset);
6101                 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6102                                          get_unaligned(&entry->ino),
6103                                          get_unaligned(&entry->type)))
6104                         return 1;
6105                 addr += sizeof(struct dir_entry) +
6106                         get_unaligned(&entry->name_len);
6107                 ctx->pos++;
6108         }
6109         return 0;
6110 }
6111
6112 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6113 {
6114         struct inode *inode = file_inode(file);
6115         struct btrfs_root *root = BTRFS_I(inode)->root;
6116         struct btrfs_file_private *private = file->private_data;
6117         struct btrfs_dir_item *di;
6118         struct btrfs_key key;
6119         struct btrfs_key found_key;
6120         struct btrfs_path *path;
6121         void *addr;
6122         struct list_head ins_list;
6123         struct list_head del_list;
6124         int ret;
6125         char *name_ptr;
6126         int name_len;
6127         int entries = 0;
6128         int total_len = 0;
6129         bool put = false;
6130         struct btrfs_key location;
6131
6132         if (!dir_emit_dots(file, ctx))
6133                 return 0;
6134
6135         path = btrfs_alloc_path();
6136         if (!path)
6137                 return -ENOMEM;
6138
6139         addr = private->filldir_buf;
6140         path->reada = READA_FORWARD;
6141
6142         INIT_LIST_HEAD(&ins_list);
6143         INIT_LIST_HEAD(&del_list);
6144         put = btrfs_readdir_get_delayed_items(inode, private->last_index,
6145                                               &ins_list, &del_list);
6146
6147 again:
6148         key.type = BTRFS_DIR_INDEX_KEY;
6149         key.offset = ctx->pos;
6150         key.objectid = btrfs_ino(BTRFS_I(inode));
6151
6152         btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6153                 struct dir_entry *entry;
6154                 struct extent_buffer *leaf = path->nodes[0];
6155
6156                 if (found_key.objectid != key.objectid)
6157                         break;
6158                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
6159                         break;
6160                 if (found_key.offset < ctx->pos)
6161                         continue;
6162                 if (found_key.offset > private->last_index)
6163                         break;
6164                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6165                         continue;
6166                 di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6167                 name_len = btrfs_dir_name_len(leaf, di);
6168                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
6169                     PAGE_SIZE) {
6170                         btrfs_release_path(path);
6171                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6172                         if (ret)
6173                                 goto nopos;
6174                         addr = private->filldir_buf;
6175                         entries = 0;
6176                         total_len = 0;
6177                         goto again;
6178                 }
6179
6180                 entry = addr;
6181                 put_unaligned(name_len, &entry->name_len);
6182                 name_ptr = (char *)(entry + 1);
6183                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6184                                    name_len);
6185                 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6186                                 &entry->type);
6187                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6188                 put_unaligned(location.objectid, &entry->ino);
6189                 put_unaligned(found_key.offset, &entry->offset);
6190                 entries++;
6191                 addr += sizeof(struct dir_entry) + name_len;
6192                 total_len += sizeof(struct dir_entry) + name_len;
6193         }
6194         /* Catch error encountered during iteration */
6195         if (ret < 0)
6196                 goto err;
6197
6198         btrfs_release_path(path);
6199
6200         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6201         if (ret)
6202                 goto nopos;
6203
6204         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6205         if (ret)
6206                 goto nopos;
6207
6208         /*
6209          * Stop new entries from being returned after we return the last
6210          * entry.
6211          *
6212          * New directory entries are assigned a strictly increasing
6213          * offset.  This means that new entries created during readdir
6214          * are *guaranteed* to be seen in the future by that readdir.
6215          * This has broken buggy programs which operate on names as
6216          * they're returned by readdir.  Until we re-use freed offsets
6217          * we have this hack to stop new entries from being returned
6218          * under the assumption that they'll never reach this huge
6219          * offset.
6220          *
6221          * This is being careful not to overflow 32bit loff_t unless the
6222          * last entry requires it because doing so has broken 32bit apps
6223          * in the past.
6224          */
6225         if (ctx->pos >= INT_MAX)
6226                 ctx->pos = LLONG_MAX;
6227         else
6228                 ctx->pos = INT_MAX;
6229 nopos:
6230         ret = 0;
6231 err:
6232         if (put)
6233                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6234         btrfs_free_path(path);
6235         return ret;
6236 }
6237
6238 /*
6239  * This is somewhat expensive, updating the tree every time the
6240  * inode changes.  But, it is most likely to find the inode in cache.
6241  * FIXME, needs more benchmarking...there are no reasons other than performance
6242  * to keep or drop this code.
6243  */
6244 static int btrfs_dirty_inode(struct inode *inode)
6245 {
6246         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6247         struct btrfs_root *root = BTRFS_I(inode)->root;
6248         struct btrfs_trans_handle *trans;
6249         int ret;
6250
6251         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6252                 return 0;
6253
6254         trans = btrfs_join_transaction(root);
6255         if (IS_ERR(trans))
6256                 return PTR_ERR(trans);
6257
6258         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6259         if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6260                 /* whoops, lets try again with the full transaction */
6261                 btrfs_end_transaction(trans);
6262                 trans = btrfs_start_transaction(root, 1);
6263                 if (IS_ERR(trans))
6264                         return PTR_ERR(trans);
6265
6266                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6267         }
6268         btrfs_end_transaction(trans);
6269         if (BTRFS_I(inode)->delayed_node)
6270                 btrfs_balance_delayed_items(fs_info);
6271
6272         return ret;
6273 }
6274
6275 /*
6276  * This is a copy of file_update_time.  We need this so we can return error on
6277  * ENOSPC for updating the inode in the case of file write and mmap writes.
6278  */
6279 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6280                              int flags)
6281 {
6282         struct btrfs_root *root = BTRFS_I(inode)->root;
6283         bool dirty = flags & ~S_VERSION;
6284
6285         if (btrfs_root_readonly(root))
6286                 return -EROFS;
6287
6288         if (flags & S_VERSION)
6289                 dirty |= inode_maybe_inc_iversion(inode, dirty);
6290         if (flags & S_CTIME)
6291                 inode->i_ctime = *now;
6292         if (flags & S_MTIME)
6293                 inode->i_mtime = *now;
6294         if (flags & S_ATIME)
6295                 inode->i_atime = *now;
6296         return dirty ? btrfs_dirty_inode(inode) : 0;
6297 }
6298
6299 /*
6300  * helper to find a free sequence number in a given directory.  This current
6301  * code is very simple, later versions will do smarter things in the btree
6302  */
6303 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6304 {
6305         int ret = 0;
6306
6307         if (dir->index_cnt == (u64)-1) {
6308                 ret = btrfs_inode_delayed_dir_index_count(dir);
6309                 if (ret) {
6310                         ret = btrfs_set_inode_index_count(dir);
6311                         if (ret)
6312                                 return ret;
6313                 }
6314         }
6315
6316         *index = dir->index_cnt;
6317         dir->index_cnt++;
6318
6319         return ret;
6320 }
6321
6322 static int btrfs_insert_inode_locked(struct inode *inode)
6323 {
6324         struct btrfs_iget_args args;
6325
6326         args.ino = BTRFS_I(inode)->location.objectid;
6327         args.root = BTRFS_I(inode)->root;
6328
6329         return insert_inode_locked4(inode,
6330                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6331                    btrfs_find_actor, &args);
6332 }
6333
6334 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6335                             unsigned int *trans_num_items)
6336 {
6337         struct inode *dir = args->dir;
6338         struct inode *inode = args->inode;
6339         int ret;
6340
6341         if (!args->orphan) {
6342                 ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6343                                              &args->fname);
6344                 if (ret)
6345                         return ret;
6346         }
6347
6348         ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6349         if (ret) {
6350                 fscrypt_free_filename(&args->fname);
6351                 return ret;
6352         }
6353
6354         /* 1 to add inode item */
6355         *trans_num_items = 1;
6356         /* 1 to add compression property */
6357         if (BTRFS_I(dir)->prop_compress)
6358                 (*trans_num_items)++;
6359         /* 1 to add default ACL xattr */
6360         if (args->default_acl)
6361                 (*trans_num_items)++;
6362         /* 1 to add access ACL xattr */
6363         if (args->acl)
6364                 (*trans_num_items)++;
6365 #ifdef CONFIG_SECURITY
6366         /* 1 to add LSM xattr */
6367         if (dir->i_security)
6368                 (*trans_num_items)++;
6369 #endif
6370         if (args->orphan) {
6371                 /* 1 to add orphan item */
6372                 (*trans_num_items)++;
6373         } else {
6374                 /*
6375                  * 1 to add dir item
6376                  * 1 to add dir index
6377                  * 1 to update parent inode item
6378                  *
6379                  * No need for 1 unit for the inode ref item because it is
6380                  * inserted in a batch together with the inode item at
6381                  * btrfs_create_new_inode().
6382                  */
6383                 *trans_num_items += 3;
6384         }
6385         return 0;
6386 }
6387
6388 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6389 {
6390         posix_acl_release(args->acl);
6391         posix_acl_release(args->default_acl);
6392         fscrypt_free_filename(&args->fname);
6393 }
6394
6395 /*
6396  * Inherit flags from the parent inode.
6397  *
6398  * Currently only the compression flags and the cow flags are inherited.
6399  */
6400 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6401 {
6402         unsigned int flags;
6403
6404         flags = BTRFS_I(dir)->flags;
6405
6406         if (flags & BTRFS_INODE_NOCOMPRESS) {
6407                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6408                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6409         } else if (flags & BTRFS_INODE_COMPRESS) {
6410                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6411                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6412         }
6413
6414         if (flags & BTRFS_INODE_NODATACOW) {
6415                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6416                 if (S_ISREG(inode->i_mode))
6417                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6418         }
6419
6420         btrfs_sync_inode_flags_to_i_flags(inode);
6421 }
6422
6423 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6424                            struct btrfs_new_inode_args *args)
6425 {
6426         struct inode *dir = args->dir;
6427         struct inode *inode = args->inode;
6428         const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6429         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6430         struct btrfs_root *root;
6431         struct btrfs_inode_item *inode_item;
6432         struct btrfs_key *location;
6433         struct btrfs_path *path;
6434         u64 objectid;
6435         struct btrfs_inode_ref *ref;
6436         struct btrfs_key key[2];
6437         u32 sizes[2];
6438         struct btrfs_item_batch batch;
6439         unsigned long ptr;
6440         int ret;
6441
6442         path = btrfs_alloc_path();
6443         if (!path)
6444                 return -ENOMEM;
6445
6446         if (!args->subvol)
6447                 BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6448         root = BTRFS_I(inode)->root;
6449
6450         ret = btrfs_get_free_objectid(root, &objectid);
6451         if (ret)
6452                 goto out;
6453         inode->i_ino = objectid;
6454
6455         if (args->orphan) {
6456                 /*
6457                  * O_TMPFILE, set link count to 0, so that after this point, we
6458                  * fill in an inode item with the correct link count.
6459                  */
6460                 set_nlink(inode, 0);
6461         } else {
6462                 trace_btrfs_inode_request(dir);
6463
6464                 ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6465                 if (ret)
6466                         goto out;
6467         }
6468         /* index_cnt is ignored for everything but a dir. */
6469         BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6470         BTRFS_I(inode)->generation = trans->transid;
6471         inode->i_generation = BTRFS_I(inode)->generation;
6472
6473         /*
6474          * Subvolumes don't inherit flags from their parent directory.
6475          * Originally this was probably by accident, but we probably can't
6476          * change it now without compatibility issues.
6477          */
6478         if (!args->subvol)
6479                 btrfs_inherit_iflags(inode, dir);
6480
6481         if (S_ISREG(inode->i_mode)) {
6482                 if (btrfs_test_opt(fs_info, NODATASUM))
6483                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6484                 if (btrfs_test_opt(fs_info, NODATACOW))
6485                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6486                                 BTRFS_INODE_NODATASUM;
6487         }
6488
6489         location = &BTRFS_I(inode)->location;
6490         location->objectid = objectid;
6491         location->offset = 0;
6492         location->type = BTRFS_INODE_ITEM_KEY;
6493
6494         ret = btrfs_insert_inode_locked(inode);
6495         if (ret < 0) {
6496                 if (!args->orphan)
6497                         BTRFS_I(dir)->index_cnt--;
6498                 goto out;
6499         }
6500
6501         /*
6502          * We could have gotten an inode number from somebody who was fsynced
6503          * and then removed in this same transaction, so let's just set full
6504          * sync since it will be a full sync anyway and this will blow away the
6505          * old info in the log.
6506          */
6507         btrfs_set_inode_full_sync(BTRFS_I(inode));
6508
6509         key[0].objectid = objectid;
6510         key[0].type = BTRFS_INODE_ITEM_KEY;
6511         key[0].offset = 0;
6512
6513         sizes[0] = sizeof(struct btrfs_inode_item);
6514
6515         if (!args->orphan) {
6516                 /*
6517                  * Start new inodes with an inode_ref. This is slightly more
6518                  * efficient for small numbers of hard links since they will
6519                  * be packed into one item. Extended refs will kick in if we
6520                  * add more hard links than can fit in the ref item.
6521                  */
6522                 key[1].objectid = objectid;
6523                 key[1].type = BTRFS_INODE_REF_KEY;
6524                 if (args->subvol) {
6525                         key[1].offset = objectid;
6526                         sizes[1] = 2 + sizeof(*ref);
6527                 } else {
6528                         key[1].offset = btrfs_ino(BTRFS_I(dir));
6529                         sizes[1] = name->len + sizeof(*ref);
6530                 }
6531         }
6532
6533         batch.keys = &key[0];
6534         batch.data_sizes = &sizes[0];
6535         batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6536         batch.nr = args->orphan ? 1 : 2;
6537         ret = btrfs_insert_empty_items(trans, root, path, &batch);
6538         if (ret != 0) {
6539                 btrfs_abort_transaction(trans, ret);
6540                 goto discard;
6541         }
6542
6543         inode->i_mtime = current_time(inode);
6544         inode->i_atime = inode->i_mtime;
6545         inode->i_ctime = inode->i_mtime;
6546         BTRFS_I(inode)->i_otime = inode->i_mtime;
6547
6548         /*
6549          * We're going to fill the inode item now, so at this point the inode
6550          * must be fully initialized.
6551          */
6552
6553         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6554                                   struct btrfs_inode_item);
6555         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6556                              sizeof(*inode_item));
6557         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6558
6559         if (!args->orphan) {
6560                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6561                                      struct btrfs_inode_ref);
6562                 ptr = (unsigned long)(ref + 1);
6563                 if (args->subvol) {
6564                         btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6565                         btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6566                         write_extent_buffer(path->nodes[0], "..", ptr, 2);
6567                 } else {
6568                         btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6569                                                      name->len);
6570                         btrfs_set_inode_ref_index(path->nodes[0], ref,
6571                                                   BTRFS_I(inode)->dir_index);
6572                         write_extent_buffer(path->nodes[0], name->name, ptr,
6573                                             name->len);
6574                 }
6575         }
6576
6577         btrfs_mark_buffer_dirty(path->nodes[0]);
6578         /*
6579          * We don't need the path anymore, plus inheriting properties, adding
6580          * ACLs, security xattrs, orphan item or adding the link, will result in
6581          * allocating yet another path. So just free our path.
6582          */
6583         btrfs_free_path(path);
6584         path = NULL;
6585
6586         if (args->subvol) {
6587                 struct inode *parent;
6588
6589                 /*
6590                  * Subvolumes inherit properties from their parent subvolume,
6591                  * not the directory they were created in.
6592                  */
6593                 parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
6594                                     BTRFS_I(dir)->root);
6595                 if (IS_ERR(parent)) {
6596                         ret = PTR_ERR(parent);
6597                 } else {
6598                         ret = btrfs_inode_inherit_props(trans, inode, parent);
6599                         iput(parent);
6600                 }
6601         } else {
6602                 ret = btrfs_inode_inherit_props(trans, inode, dir);
6603         }
6604         if (ret) {
6605                 btrfs_err(fs_info,
6606                           "error inheriting props for ino %llu (root %llu): %d",
6607                           btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
6608                           ret);
6609         }
6610
6611         /*
6612          * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6613          * probably a bug.
6614          */
6615         if (!args->subvol) {
6616                 ret = btrfs_init_inode_security(trans, args);
6617                 if (ret) {
6618                         btrfs_abort_transaction(trans, ret);
6619                         goto discard;
6620                 }
6621         }
6622
6623         inode_tree_add(inode);
6624
6625         trace_btrfs_inode_new(inode);
6626         btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6627
6628         btrfs_update_root_times(trans, root);
6629
6630         if (args->orphan) {
6631                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6632         } else {
6633                 ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6634                                      0, BTRFS_I(inode)->dir_index);
6635         }
6636         if (ret) {
6637                 btrfs_abort_transaction(trans, ret);
6638                 goto discard;
6639         }
6640
6641         return 0;
6642
6643 discard:
6644         /*
6645          * discard_new_inode() calls iput(), but the caller owns the reference
6646          * to the inode.
6647          */
6648         ihold(inode);
6649         discard_new_inode(inode);
6650 out:
6651         btrfs_free_path(path);
6652         return ret;
6653 }
6654
6655 /*
6656  * utility function to add 'inode' into 'parent_inode' with
6657  * a give name and a given sequence number.
6658  * if 'add_backref' is true, also insert a backref from the
6659  * inode to the parent directory.
6660  */
6661 int btrfs_add_link(struct btrfs_trans_handle *trans,
6662                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6663                    const struct fscrypt_str *name, int add_backref, u64 index)
6664 {
6665         int ret = 0;
6666         struct btrfs_key key;
6667         struct btrfs_root *root = parent_inode->root;
6668         u64 ino = btrfs_ino(inode);
6669         u64 parent_ino = btrfs_ino(parent_inode);
6670
6671         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6672                 memcpy(&key, &inode->root->root_key, sizeof(key));
6673         } else {
6674                 key.objectid = ino;
6675                 key.type = BTRFS_INODE_ITEM_KEY;
6676                 key.offset = 0;
6677         }
6678
6679         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6680                 ret = btrfs_add_root_ref(trans, key.objectid,
6681                                          root->root_key.objectid, parent_ino,
6682                                          index, name);
6683         } else if (add_backref) {
6684                 ret = btrfs_insert_inode_ref(trans, root, name,
6685                                              ino, parent_ino, index);
6686         }
6687
6688         /* Nothing to clean up yet */
6689         if (ret)
6690                 return ret;
6691
6692         ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6693                                     btrfs_inode_type(&inode->vfs_inode), index);
6694         if (ret == -EEXIST || ret == -EOVERFLOW)
6695                 goto fail_dir_item;
6696         else if (ret) {
6697                 btrfs_abort_transaction(trans, ret);
6698                 return ret;
6699         }
6700
6701         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6702                            name->len * 2);
6703         inode_inc_iversion(&parent_inode->vfs_inode);
6704         /*
6705          * If we are replaying a log tree, we do not want to update the mtime
6706          * and ctime of the parent directory with the current time, since the
6707          * log replay procedure is responsible for setting them to their correct
6708          * values (the ones it had when the fsync was done).
6709          */
6710         if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6711                 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6712
6713                 parent_inode->vfs_inode.i_mtime = now;
6714                 parent_inode->vfs_inode.i_ctime = now;
6715         }
6716         ret = btrfs_update_inode(trans, root, parent_inode);
6717         if (ret)
6718                 btrfs_abort_transaction(trans, ret);
6719         return ret;
6720
6721 fail_dir_item:
6722         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6723                 u64 local_index;
6724                 int err;
6725                 err = btrfs_del_root_ref(trans, key.objectid,
6726                                          root->root_key.objectid, parent_ino,
6727                                          &local_index, name);
6728                 if (err)
6729                         btrfs_abort_transaction(trans, err);
6730         } else if (add_backref) {
6731                 u64 local_index;
6732                 int err;
6733
6734                 err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
6735                                           &local_index);
6736                 if (err)
6737                         btrfs_abort_transaction(trans, err);
6738         }
6739
6740         /* Return the original error code */
6741         return ret;
6742 }
6743
6744 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6745                                struct inode *inode)
6746 {
6747         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6748         struct btrfs_root *root = BTRFS_I(dir)->root;
6749         struct btrfs_new_inode_args new_inode_args = {
6750                 .dir = dir,
6751                 .dentry = dentry,
6752                 .inode = inode,
6753         };
6754         unsigned int trans_num_items;
6755         struct btrfs_trans_handle *trans;
6756         int err;
6757
6758         err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6759         if (err)
6760                 goto out_inode;
6761
6762         trans = btrfs_start_transaction(root, trans_num_items);
6763         if (IS_ERR(trans)) {
6764                 err = PTR_ERR(trans);
6765                 goto out_new_inode_args;
6766         }
6767
6768         err = btrfs_create_new_inode(trans, &new_inode_args);
6769         if (!err)
6770                 d_instantiate_new(dentry, inode);
6771
6772         btrfs_end_transaction(trans);
6773         btrfs_btree_balance_dirty(fs_info);
6774 out_new_inode_args:
6775         btrfs_new_inode_args_destroy(&new_inode_args);
6776 out_inode:
6777         if (err)
6778                 iput(inode);
6779         return err;
6780 }
6781
6782 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6783                        struct dentry *dentry, umode_t mode, dev_t rdev)
6784 {
6785         struct inode *inode;
6786
6787         inode = new_inode(dir->i_sb);
6788         if (!inode)
6789                 return -ENOMEM;
6790         inode_init_owner(mnt_userns, inode, dir, mode);
6791         inode->i_op = &btrfs_special_inode_operations;
6792         init_special_inode(inode, inode->i_mode, rdev);
6793         return btrfs_create_common(dir, dentry, inode);
6794 }
6795
6796 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6797                         struct dentry *dentry, umode_t mode, bool excl)
6798 {
6799         struct inode *inode;
6800
6801         inode = new_inode(dir->i_sb);
6802         if (!inode)
6803                 return -ENOMEM;
6804         inode_init_owner(mnt_userns, inode, dir, mode);
6805         inode->i_fop = &btrfs_file_operations;
6806         inode->i_op = &btrfs_file_inode_operations;
6807         inode->i_mapping->a_ops = &btrfs_aops;
6808         return btrfs_create_common(dir, dentry, inode);
6809 }
6810
6811 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6812                       struct dentry *dentry)
6813 {
6814         struct btrfs_trans_handle *trans = NULL;
6815         struct btrfs_root *root = BTRFS_I(dir)->root;
6816         struct inode *inode = d_inode(old_dentry);
6817         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6818         struct fscrypt_name fname;
6819         u64 index;
6820         int err;
6821         int drop_inode = 0;
6822
6823         /* do not allow sys_link's with other subvols of the same device */
6824         if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6825                 return -EXDEV;
6826
6827         if (inode->i_nlink >= BTRFS_LINK_MAX)
6828                 return -EMLINK;
6829
6830         err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6831         if (err)
6832                 goto fail;
6833
6834         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6835         if (err)
6836                 goto fail;
6837
6838         /*
6839          * 2 items for inode and inode ref
6840          * 2 items for dir items
6841          * 1 item for parent inode
6842          * 1 item for orphan item deletion if O_TMPFILE
6843          */
6844         trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6845         if (IS_ERR(trans)) {
6846                 err = PTR_ERR(trans);
6847                 trans = NULL;
6848                 goto fail;
6849         }
6850
6851         /* There are several dir indexes for this inode, clear the cache. */
6852         BTRFS_I(inode)->dir_index = 0ULL;
6853         inc_nlink(inode);
6854         inode_inc_iversion(inode);
6855         inode->i_ctime = current_time(inode);
6856         ihold(inode);
6857         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6858
6859         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6860                              &fname.disk_name, 1, index);
6861
6862         if (err) {
6863                 drop_inode = 1;
6864         } else {
6865                 struct dentry *parent = dentry->d_parent;
6866
6867                 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6868                 if (err)
6869                         goto fail;
6870                 if (inode->i_nlink == 1) {
6871                         /*
6872                          * If new hard link count is 1, it's a file created
6873                          * with open(2) O_TMPFILE flag.
6874                          */
6875                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6876                         if (err)
6877                                 goto fail;
6878                 }
6879                 d_instantiate(dentry, inode);
6880                 btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
6881         }
6882
6883 fail:
6884         fscrypt_free_filename(&fname);
6885         if (trans)
6886                 btrfs_end_transaction(trans);
6887         if (drop_inode) {
6888                 inode_dec_link_count(inode);
6889                 iput(inode);
6890         }
6891         btrfs_btree_balance_dirty(fs_info);
6892         return err;
6893 }
6894
6895 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6896                        struct dentry *dentry, umode_t mode)
6897 {
6898         struct inode *inode;
6899
6900         inode = new_inode(dir->i_sb);
6901         if (!inode)
6902                 return -ENOMEM;
6903         inode_init_owner(mnt_userns, inode, dir, S_IFDIR | mode);
6904         inode->i_op = &btrfs_dir_inode_operations;
6905         inode->i_fop = &btrfs_dir_file_operations;
6906         return btrfs_create_common(dir, dentry, inode);
6907 }
6908
6909 static noinline int uncompress_inline(struct btrfs_path *path,
6910                                       struct page *page,
6911                                       size_t pg_offset, u64 extent_offset,
6912                                       struct btrfs_file_extent_item *item)
6913 {
6914         int ret;
6915         struct extent_buffer *leaf = path->nodes[0];
6916         char *tmp;
6917         size_t max_size;
6918         unsigned long inline_size;
6919         unsigned long ptr;
6920         int compress_type;
6921
6922         WARN_ON(pg_offset != 0);
6923         compress_type = btrfs_file_extent_compression(leaf, item);
6924         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6925         inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6926         tmp = kmalloc(inline_size, GFP_NOFS);
6927         if (!tmp)
6928                 return -ENOMEM;
6929         ptr = btrfs_file_extent_inline_start(item);
6930
6931         read_extent_buffer(leaf, tmp, ptr, inline_size);
6932
6933         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6934         ret = btrfs_decompress(compress_type, tmp, page,
6935                                extent_offset, inline_size, max_size);
6936
6937         /*
6938          * decompression code contains a memset to fill in any space between the end
6939          * of the uncompressed data and the end of max_size in case the decompressed
6940          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6941          * the end of an inline extent and the beginning of the next block, so we
6942          * cover that region here.
6943          */
6944
6945         if (max_size + pg_offset < PAGE_SIZE)
6946                 memzero_page(page,  pg_offset + max_size,
6947                              PAGE_SIZE - max_size - pg_offset);
6948         kfree(tmp);
6949         return ret;
6950 }
6951
6952 /**
6953  * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6954  * @inode:      file to search in
6955  * @page:       page to read extent data into if the extent is inline
6956  * @pg_offset:  offset into @page to copy to
6957  * @start:      file offset
6958  * @len:        length of range starting at @start
6959  *
6960  * This returns the first &struct extent_map which overlaps with the given
6961  * range, reading it from the B-tree and caching it if necessary. Note that
6962  * there may be more extents which overlap the given range after the returned
6963  * extent_map.
6964  *
6965  * If @page is not NULL and the extent is inline, this also reads the extent
6966  * data directly into the page and marks the extent up to date in the io_tree.
6967  *
6968  * Return: ERR_PTR on error, non-NULL extent_map on success.
6969  */
6970 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6971                                     struct page *page, size_t pg_offset,
6972                                     u64 start, u64 len)
6973 {
6974         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6975         int ret = 0;
6976         u64 extent_start = 0;
6977         u64 extent_end = 0;
6978         u64 objectid = btrfs_ino(inode);
6979         int extent_type = -1;
6980         struct btrfs_path *path = NULL;
6981         struct btrfs_root *root = inode->root;
6982         struct btrfs_file_extent_item *item;
6983         struct extent_buffer *leaf;
6984         struct btrfs_key found_key;
6985         struct extent_map *em = NULL;
6986         struct extent_map_tree *em_tree = &inode->extent_tree;
6987
6988         read_lock(&em_tree->lock);
6989         em = lookup_extent_mapping(em_tree, start, len);
6990         read_unlock(&em_tree->lock);
6991
6992         if (em) {
6993                 if (em->start > start || em->start + em->len <= start)
6994                         free_extent_map(em);
6995                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6996                         free_extent_map(em);
6997                 else
6998                         goto out;
6999         }
7000         em = alloc_extent_map();
7001         if (!em) {
7002                 ret = -ENOMEM;
7003                 goto out;
7004         }
7005         em->start = EXTENT_MAP_HOLE;
7006         em->orig_start = EXTENT_MAP_HOLE;
7007         em->len = (u64)-1;
7008         em->block_len = (u64)-1;
7009
7010         path = btrfs_alloc_path();
7011         if (!path) {
7012                 ret = -ENOMEM;
7013                 goto out;
7014         }
7015
7016         /* Chances are we'll be called again, so go ahead and do readahead */
7017         path->reada = READA_FORWARD;
7018
7019         /*
7020          * The same explanation in load_free_space_cache applies here as well,
7021          * we only read when we're loading the free space cache, and at that
7022          * point the commit_root has everything we need.
7023          */
7024         if (btrfs_is_free_space_inode(inode)) {
7025                 path->search_commit_root = 1;
7026                 path->skip_locking = 1;
7027         }
7028
7029         ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7030         if (ret < 0) {
7031                 goto out;
7032         } else if (ret > 0) {
7033                 if (path->slots[0] == 0)
7034                         goto not_found;
7035                 path->slots[0]--;
7036                 ret = 0;
7037         }
7038
7039         leaf = path->nodes[0];
7040         item = btrfs_item_ptr(leaf, path->slots[0],
7041                               struct btrfs_file_extent_item);
7042         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7043         if (found_key.objectid != objectid ||
7044             found_key.type != BTRFS_EXTENT_DATA_KEY) {
7045                 /*
7046                  * If we backup past the first extent we want to move forward
7047                  * and see if there is an extent in front of us, otherwise we'll
7048                  * say there is a hole for our whole search range which can
7049                  * cause problems.
7050                  */
7051                 extent_end = start;
7052                 goto next;
7053         }
7054
7055         extent_type = btrfs_file_extent_type(leaf, item);
7056         extent_start = found_key.offset;
7057         extent_end = btrfs_file_extent_end(path);
7058         if (extent_type == BTRFS_FILE_EXTENT_REG ||
7059             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7060                 /* Only regular file could have regular/prealloc extent */
7061                 if (!S_ISREG(inode->vfs_inode.i_mode)) {
7062                         ret = -EUCLEAN;
7063                         btrfs_crit(fs_info,
7064                 "regular/prealloc extent found for non-regular inode %llu",
7065                                    btrfs_ino(inode));
7066                         goto out;
7067                 }
7068                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7069                                                        extent_start);
7070         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7071                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7072                                                       path->slots[0],
7073                                                       extent_start);
7074         }
7075 next:
7076         if (start >= extent_end) {
7077                 path->slots[0]++;
7078                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7079                         ret = btrfs_next_leaf(root, path);
7080                         if (ret < 0)
7081                                 goto out;
7082                         else if (ret > 0)
7083                                 goto not_found;
7084
7085                         leaf = path->nodes[0];
7086                 }
7087                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7088                 if (found_key.objectid != objectid ||
7089                     found_key.type != BTRFS_EXTENT_DATA_KEY)
7090                         goto not_found;
7091                 if (start + len <= found_key.offset)
7092                         goto not_found;
7093                 if (start > found_key.offset)
7094                         goto next;
7095
7096                 /* New extent overlaps with existing one */
7097                 em->start = start;
7098                 em->orig_start = start;
7099                 em->len = found_key.offset - start;
7100                 em->block_start = EXTENT_MAP_HOLE;
7101                 goto insert;
7102         }
7103
7104         btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
7105
7106         if (extent_type == BTRFS_FILE_EXTENT_REG ||
7107             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7108                 goto insert;
7109         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7110                 unsigned long ptr;
7111                 char *map;
7112                 size_t size;
7113                 size_t extent_offset;
7114                 size_t copy_size;
7115
7116                 if (!page)
7117                         goto out;
7118
7119                 size = btrfs_file_extent_ram_bytes(leaf, item);
7120                 extent_offset = page_offset(page) + pg_offset - extent_start;
7121                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7122                                   size - extent_offset);
7123                 em->start = extent_start + extent_offset;
7124                 em->len = ALIGN(copy_size, fs_info->sectorsize);
7125                 em->orig_block_len = em->len;
7126                 em->orig_start = em->start;
7127                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7128
7129                 if (!PageUptodate(page)) {
7130                         if (btrfs_file_extent_compression(leaf, item) !=
7131                             BTRFS_COMPRESS_NONE) {
7132                                 ret = uncompress_inline(path, page, pg_offset,
7133                                                         extent_offset, item);
7134                                 if (ret)
7135                                         goto out;
7136                         } else {
7137                                 map = kmap_local_page(page);
7138                                 read_extent_buffer(leaf, map + pg_offset, ptr,
7139                                                    copy_size);
7140                                 if (pg_offset + copy_size < PAGE_SIZE) {
7141                                         memset(map + pg_offset + copy_size, 0,
7142                                                PAGE_SIZE - pg_offset -
7143                                                copy_size);
7144                                 }
7145                                 kunmap_local(map);
7146                         }
7147                         flush_dcache_page(page);
7148                 }
7149                 goto insert;
7150         }
7151 not_found:
7152         em->start = start;
7153         em->orig_start = start;
7154         em->len = len;
7155         em->block_start = EXTENT_MAP_HOLE;
7156 insert:
7157         ret = 0;
7158         btrfs_release_path(path);
7159         if (em->start > start || extent_map_end(em) <= start) {
7160                 btrfs_err(fs_info,
7161                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7162                           em->start, em->len, start, len);
7163                 ret = -EIO;
7164                 goto out;
7165         }
7166
7167         write_lock(&em_tree->lock);
7168         ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7169         write_unlock(&em_tree->lock);
7170 out:
7171         btrfs_free_path(path);
7172
7173         trace_btrfs_get_extent(root, inode, em);
7174
7175         if (ret) {
7176                 free_extent_map(em);
7177                 return ERR_PTR(ret);
7178         }
7179         return em;
7180 }
7181
7182 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7183                                                   const u64 start,
7184                                                   const u64 len,
7185                                                   const u64 orig_start,
7186                                                   const u64 block_start,
7187                                                   const u64 block_len,
7188                                                   const u64 orig_block_len,
7189                                                   const u64 ram_bytes,
7190                                                   const int type)
7191 {
7192         struct extent_map *em = NULL;
7193         int ret;
7194
7195         if (type != BTRFS_ORDERED_NOCOW) {
7196                 em = create_io_em(inode, start, len, orig_start, block_start,
7197                                   block_len, orig_block_len, ram_bytes,
7198                                   BTRFS_COMPRESS_NONE, /* compress_type */
7199                                   type);
7200                 if (IS_ERR(em))
7201                         goto out;
7202         }
7203         ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
7204                                        block_len, 0,
7205                                        (1 << type) |
7206                                        (1 << BTRFS_ORDERED_DIRECT),
7207                                        BTRFS_COMPRESS_NONE);
7208         if (ret) {
7209                 if (em) {
7210                         free_extent_map(em);
7211                         btrfs_drop_extent_map_range(inode, start,
7212                                                     start + len - 1, false);
7213                 }
7214                 em = ERR_PTR(ret);
7215         }
7216  out:
7217
7218         return em;
7219 }
7220
7221 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7222                                                   u64 start, u64 len)
7223 {
7224         struct btrfs_root *root = inode->root;
7225         struct btrfs_fs_info *fs_info = root->fs_info;
7226         struct extent_map *em;
7227         struct btrfs_key ins;
7228         u64 alloc_hint;
7229         int ret;
7230
7231         alloc_hint = get_extent_allocation_hint(inode, start, len);
7232 again:
7233         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7234                                    0, alloc_hint, &ins, 1, 1);
7235         if (ret == -EAGAIN) {
7236                 ASSERT(btrfs_is_zoned(fs_info));
7237                 wait_on_bit_io(&inode->root->fs_info->flags, BTRFS_FS_NEED_ZONE_FINISH,
7238                                TASK_UNINTERRUPTIBLE);
7239                 goto again;
7240         }
7241         if (ret)
7242                 return ERR_PTR(ret);
7243
7244         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7245                                      ins.objectid, ins.offset, ins.offset,
7246                                      ins.offset, BTRFS_ORDERED_REGULAR);
7247         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7248         if (IS_ERR(em))
7249                 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7250                                            1);
7251
7252         return em;
7253 }
7254
7255 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7256 {
7257         struct btrfs_block_group *block_group;
7258         bool readonly = false;
7259
7260         block_group = btrfs_lookup_block_group(fs_info, bytenr);
7261         if (!block_group || block_group->ro)
7262                 readonly = true;
7263         if (block_group)
7264                 btrfs_put_block_group(block_group);
7265         return readonly;
7266 }
7267
7268 /*
7269  * Check if we can do nocow write into the range [@offset, @offset + @len)
7270  *
7271  * @offset:     File offset
7272  * @len:        The length to write, will be updated to the nocow writeable
7273  *              range
7274  * @orig_start: (optional) Return the original file offset of the file extent
7275  * @orig_len:   (optional) Return the original on-disk length of the file extent
7276  * @ram_bytes:  (optional) Return the ram_bytes of the file extent
7277  * @strict:     if true, omit optimizations that might force us into unnecessary
7278  *              cow. e.g., don't trust generation number.
7279  *
7280  * Return:
7281  * >0   and update @len if we can do nocow write
7282  *  0   if we can't do nocow write
7283  * <0   if error happened
7284  *
7285  * NOTE: This only checks the file extents, caller is responsible to wait for
7286  *       any ordered extents.
7287  */
7288 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7289                               u64 *orig_start, u64 *orig_block_len,
7290                               u64 *ram_bytes, bool nowait, bool strict)
7291 {
7292         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7293         struct can_nocow_file_extent_args nocow_args = { 0 };
7294         struct btrfs_path *path;
7295         int ret;
7296         struct extent_buffer *leaf;
7297         struct btrfs_root *root = BTRFS_I(inode)->root;
7298         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7299         struct btrfs_file_extent_item *fi;
7300         struct btrfs_key key;
7301         int found_type;
7302
7303         path = btrfs_alloc_path();
7304         if (!path)
7305                 return -ENOMEM;
7306         path->nowait = nowait;
7307
7308         ret = btrfs_lookup_file_extent(NULL, root, path,
7309                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7310         if (ret < 0)
7311                 goto out;
7312
7313         if (ret == 1) {
7314                 if (path->slots[0] == 0) {
7315                         /* can't find the item, must cow */
7316                         ret = 0;
7317                         goto out;
7318                 }
7319                 path->slots[0]--;
7320         }
7321         ret = 0;
7322         leaf = path->nodes[0];
7323         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7324         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7325             key.type != BTRFS_EXTENT_DATA_KEY) {
7326                 /* not our file or wrong item type, must cow */
7327                 goto out;
7328         }
7329
7330         if (key.offset > offset) {
7331                 /* Wrong offset, must cow */
7332                 goto out;
7333         }
7334
7335         if (btrfs_file_extent_end(path) <= offset)
7336                 goto out;
7337
7338         fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7339         found_type = btrfs_file_extent_type(leaf, fi);
7340         if (ram_bytes)
7341                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7342
7343         nocow_args.start = offset;
7344         nocow_args.end = offset + *len - 1;
7345         nocow_args.strict = strict;
7346         nocow_args.free_path = true;
7347
7348         ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
7349         /* can_nocow_file_extent() has freed the path. */
7350         path = NULL;
7351
7352         if (ret != 1) {
7353                 /* Treat errors as not being able to NOCOW. */
7354                 ret = 0;
7355                 goto out;
7356         }
7357
7358         ret = 0;
7359         if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
7360                 goto out;
7361
7362         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7363             found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7364                 u64 range_end;
7365
7366                 range_end = round_up(offset + nocow_args.num_bytes,
7367                                      root->fs_info->sectorsize) - 1;
7368                 ret = test_range_bit(io_tree, offset, range_end,
7369                                      EXTENT_DELALLOC, 0, NULL);
7370                 if (ret) {
7371                         ret = -EAGAIN;
7372                         goto out;
7373                 }
7374         }
7375
7376         if (orig_start)
7377                 *orig_start = key.offset - nocow_args.extent_offset;
7378         if (orig_block_len)
7379                 *orig_block_len = nocow_args.disk_num_bytes;
7380
7381         *len = nocow_args.num_bytes;
7382         ret = 1;
7383 out:
7384         btrfs_free_path(path);
7385         return ret;
7386 }
7387
7388 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7389                               struct extent_state **cached_state,
7390                               unsigned int iomap_flags)
7391 {
7392         const bool writing = (iomap_flags & IOMAP_WRITE);
7393         const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7394         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7395         struct btrfs_ordered_extent *ordered;
7396         int ret = 0;
7397
7398         while (1) {
7399                 if (nowait) {
7400                         if (!try_lock_extent(io_tree, lockstart, lockend))
7401                                 return -EAGAIN;
7402                 } else {
7403                         lock_extent(io_tree, lockstart, lockend, cached_state);
7404                 }
7405                 /*
7406                  * We're concerned with the entire range that we're going to be
7407                  * doing DIO to, so we need to make sure there's no ordered
7408                  * extents in this range.
7409                  */
7410                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7411                                                      lockend - lockstart + 1);
7412
7413                 /*
7414                  * We need to make sure there are no buffered pages in this
7415                  * range either, we could have raced between the invalidate in
7416                  * generic_file_direct_write and locking the extent.  The
7417                  * invalidate needs to happen so that reads after a write do not
7418                  * get stale data.
7419                  */
7420                 if (!ordered &&
7421                     (!writing || !filemap_range_has_page(inode->i_mapping,
7422                                                          lockstart, lockend)))
7423                         break;
7424
7425                 unlock_extent(io_tree, lockstart, lockend, cached_state);
7426
7427                 if (ordered) {
7428                         if (nowait) {
7429                                 btrfs_put_ordered_extent(ordered);
7430                                 ret = -EAGAIN;
7431                                 break;
7432                         }
7433                         /*
7434                          * If we are doing a DIO read and the ordered extent we
7435                          * found is for a buffered write, we can not wait for it
7436                          * to complete and retry, because if we do so we can
7437                          * deadlock with concurrent buffered writes on page
7438                          * locks. This happens only if our DIO read covers more
7439                          * than one extent map, if at this point has already
7440                          * created an ordered extent for a previous extent map
7441                          * and locked its range in the inode's io tree, and a
7442                          * concurrent write against that previous extent map's
7443                          * range and this range started (we unlock the ranges
7444                          * in the io tree only when the bios complete and
7445                          * buffered writes always lock pages before attempting
7446                          * to lock range in the io tree).
7447                          */
7448                         if (writing ||
7449                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7450                                 btrfs_start_ordered_extent(ordered, 1);
7451                         else
7452                                 ret = nowait ? -EAGAIN : -ENOTBLK;
7453                         btrfs_put_ordered_extent(ordered);
7454                 } else {
7455                         /*
7456                          * We could trigger writeback for this range (and wait
7457                          * for it to complete) and then invalidate the pages for
7458                          * this range (through invalidate_inode_pages2_range()),
7459                          * but that can lead us to a deadlock with a concurrent
7460                          * call to readahead (a buffered read or a defrag call
7461                          * triggered a readahead) on a page lock due to an
7462                          * ordered dio extent we created before but did not have
7463                          * yet a corresponding bio submitted (whence it can not
7464                          * complete), which makes readahead wait for that
7465                          * ordered extent to complete while holding a lock on
7466                          * that page.
7467                          */
7468                         ret = nowait ? -EAGAIN : -ENOTBLK;
7469                 }
7470
7471                 if (ret)
7472                         break;
7473
7474                 cond_resched();
7475         }
7476
7477         return ret;
7478 }
7479
7480 /* The callers of this must take lock_extent() */
7481 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7482                                        u64 len, u64 orig_start, u64 block_start,
7483                                        u64 block_len, u64 orig_block_len,
7484                                        u64 ram_bytes, int compress_type,
7485                                        int type)
7486 {
7487         struct extent_map *em;
7488         int ret;
7489
7490         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7491                type == BTRFS_ORDERED_COMPRESSED ||
7492                type == BTRFS_ORDERED_NOCOW ||
7493                type == BTRFS_ORDERED_REGULAR);
7494
7495         em = alloc_extent_map();
7496         if (!em)
7497                 return ERR_PTR(-ENOMEM);
7498
7499         em->start = start;
7500         em->orig_start = orig_start;
7501         em->len = len;
7502         em->block_len = block_len;
7503         em->block_start = block_start;
7504         em->orig_block_len = orig_block_len;
7505         em->ram_bytes = ram_bytes;
7506         em->generation = -1;
7507         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7508         if (type == BTRFS_ORDERED_PREALLOC) {
7509                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7510         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7511                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7512                 em->compress_type = compress_type;
7513         }
7514
7515         ret = btrfs_replace_extent_map_range(inode, em, true);
7516         if (ret) {
7517                 free_extent_map(em);
7518                 return ERR_PTR(ret);
7519         }
7520
7521         /* em got 2 refs now, callers needs to do free_extent_map once. */
7522         return em;
7523 }
7524
7525
7526 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7527                                          struct inode *inode,
7528                                          struct btrfs_dio_data *dio_data,
7529                                          u64 start, u64 *lenp,
7530                                          unsigned int iomap_flags)
7531 {
7532         const bool nowait = (iomap_flags & IOMAP_NOWAIT);
7533         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7534         struct extent_map *em = *map;
7535         int type;
7536         u64 block_start, orig_start, orig_block_len, ram_bytes;
7537         struct btrfs_block_group *bg;
7538         bool can_nocow = false;
7539         bool space_reserved = false;
7540         u64 len = *lenp;
7541         u64 prev_len;
7542         int ret = 0;
7543
7544         /*
7545          * We don't allocate a new extent in the following cases
7546          *
7547          * 1) The inode is marked as NODATACOW. In this case we'll just use the
7548          * existing extent.
7549          * 2) The extent is marked as PREALLOC. We're good to go here and can
7550          * just use the extent.
7551          *
7552          */
7553         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7554             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7555              em->block_start != EXTENT_MAP_HOLE)) {
7556                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7557                         type = BTRFS_ORDERED_PREALLOC;
7558                 else
7559                         type = BTRFS_ORDERED_NOCOW;
7560                 len = min(len, em->len - (start - em->start));
7561                 block_start = em->block_start + (start - em->start);
7562
7563                 if (can_nocow_extent(inode, start, &len, &orig_start,
7564                                      &orig_block_len, &ram_bytes, false, false) == 1) {
7565                         bg = btrfs_inc_nocow_writers(fs_info, block_start);
7566                         if (bg)
7567                                 can_nocow = true;
7568                 }
7569         }
7570
7571         prev_len = len;
7572         if (can_nocow) {
7573                 struct extent_map *em2;
7574
7575                 /* We can NOCOW, so only need to reserve metadata space. */
7576                 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7577                                                       nowait);
7578                 if (ret < 0) {
7579                         /* Our caller expects us to free the input extent map. */
7580                         free_extent_map(em);
7581                         *map = NULL;
7582                         btrfs_dec_nocow_writers(bg);
7583                         if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
7584                                 ret = -EAGAIN;
7585                         goto out;
7586                 }
7587                 space_reserved = true;
7588
7589                 em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7590                                               orig_start, block_start,
7591                                               len, orig_block_len,
7592                                               ram_bytes, type);
7593                 btrfs_dec_nocow_writers(bg);
7594                 if (type == BTRFS_ORDERED_PREALLOC) {
7595                         free_extent_map(em);
7596                         *map = em2;
7597                         em = em2;
7598                 }
7599
7600                 if (IS_ERR(em2)) {
7601                         ret = PTR_ERR(em2);
7602                         goto out;
7603                 }
7604
7605                 dio_data->nocow_done = true;
7606         } else {
7607                 /* Our caller expects us to free the input extent map. */
7608                 free_extent_map(em);
7609                 *map = NULL;
7610
7611                 if (nowait) {
7612                         ret = -EAGAIN;
7613                         goto out;
7614                 }
7615
7616                 /*
7617                  * If we could not allocate data space before locking the file
7618                  * range and we can't do a NOCOW write, then we have to fail.
7619                  */
7620                 if (!dio_data->data_space_reserved) {
7621                         ret = -ENOSPC;
7622                         goto out;
7623                 }
7624
7625                 /*
7626                  * We have to COW and we have already reserved data space before,
7627                  * so now we reserve only metadata.
7628                  */
7629                 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
7630                                                       false);
7631                 if (ret < 0)
7632                         goto out;
7633                 space_reserved = true;
7634
7635                 em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7636                 if (IS_ERR(em)) {
7637                         ret = PTR_ERR(em);
7638                         goto out;
7639                 }
7640                 *map = em;
7641                 len = min(len, em->len - (start - em->start));
7642                 if (len < prev_len)
7643                         btrfs_delalloc_release_metadata(BTRFS_I(inode),
7644                                                         prev_len - len, true);
7645         }
7646
7647         /*
7648          * We have created our ordered extent, so we can now release our reservation
7649          * for an outstanding extent.
7650          */
7651         btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
7652
7653         /*
7654          * Need to update the i_size under the extent lock so buffered
7655          * readers will get the updated i_size when we unlock.
7656          */
7657         if (start + len > i_size_read(inode))
7658                 i_size_write(inode, start + len);
7659 out:
7660         if (ret && space_reserved) {
7661                 btrfs_delalloc_release_extents(BTRFS_I(inode), len);
7662                 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
7663         }
7664         *lenp = len;
7665         return ret;
7666 }
7667
7668 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7669                 loff_t length, unsigned int flags, struct iomap *iomap,
7670                 struct iomap *srcmap)
7671 {
7672         struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7673         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7674         struct extent_map *em;
7675         struct extent_state *cached_state = NULL;
7676         struct btrfs_dio_data *dio_data = iter->private;
7677         u64 lockstart, lockend;
7678         const bool write = !!(flags & IOMAP_WRITE);
7679         int ret = 0;
7680         u64 len = length;
7681         const u64 data_alloc_len = length;
7682         bool unlock_extents = false;
7683
7684         /*
7685          * We could potentially fault if we have a buffer > PAGE_SIZE, and if
7686          * we're NOWAIT we may submit a bio for a partial range and return
7687          * EIOCBQUEUED, which would result in an errant short read.
7688          *
7689          * The best way to handle this would be to allow for partial completions
7690          * of iocb's, so we could submit the partial bio, return and fault in
7691          * the rest of the pages, and then submit the io for the rest of the
7692          * range.  However we don't have that currently, so simply return
7693          * -EAGAIN at this point so that the normal path is used.
7694          */
7695         if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
7696                 return -EAGAIN;
7697
7698         /*
7699          * Cap the size of reads to that usually seen in buffered I/O as we need
7700          * to allocate a contiguous array for the checksums.
7701          */
7702         if (!write)
7703                 len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
7704
7705         lockstart = start;
7706         lockend = start + len - 1;
7707
7708         /*
7709          * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
7710          * enough if we've written compressed pages to this area, so we need to
7711          * flush the dirty pages again to make absolutely sure that any
7712          * outstanding dirty pages are on disk - the first flush only starts
7713          * compression on the data, while keeping the pages locked, so by the
7714          * time the second flush returns we know bios for the compressed pages
7715          * were submitted and finished, and the pages no longer under writeback.
7716          *
7717          * If we have a NOWAIT request and we have any pages in the range that
7718          * are locked, likely due to compression still in progress, we don't want
7719          * to block on page locks. We also don't want to block on pages marked as
7720          * dirty or under writeback (same as for the non-compression case).
7721          * iomap_dio_rw() did the same check, but after that and before we got
7722          * here, mmap'ed writes may have happened or buffered reads started
7723          * (readpage() and readahead(), which lock pages), as we haven't locked
7724          * the file range yet.
7725          */
7726         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7727                      &BTRFS_I(inode)->runtime_flags)) {
7728                 if (flags & IOMAP_NOWAIT) {
7729                         if (filemap_range_needs_writeback(inode->i_mapping,
7730                                                           lockstart, lockend))
7731                                 return -EAGAIN;
7732                 } else {
7733                         ret = filemap_fdatawrite_range(inode->i_mapping, start,
7734                                                        start + length - 1);
7735                         if (ret)
7736                                 return ret;
7737                 }
7738         }
7739
7740         memset(dio_data, 0, sizeof(*dio_data));
7741
7742         /*
7743          * We always try to allocate data space and must do it before locking
7744          * the file range, to avoid deadlocks with concurrent writes to the same
7745          * range if the range has several extents and the writes don't expand the
7746          * current i_size (the inode lock is taken in shared mode). If we fail to
7747          * allocate data space here we continue and later, after locking the
7748          * file range, we fail with ENOSPC only if we figure out we can not do a
7749          * NOCOW write.
7750          */
7751         if (write && !(flags & IOMAP_NOWAIT)) {
7752                 ret = btrfs_check_data_free_space(BTRFS_I(inode),
7753                                                   &dio_data->data_reserved,
7754                                                   start, data_alloc_len, false);
7755                 if (!ret)
7756                         dio_data->data_space_reserved = true;
7757                 else if (ret && !(BTRFS_I(inode)->flags &
7758                                   (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
7759                         goto err;
7760         }
7761
7762         /*
7763          * If this errors out it's because we couldn't invalidate pagecache for
7764          * this range and we need to fallback to buffered IO, or we are doing a
7765          * NOWAIT read/write and we need to block.
7766          */
7767         ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
7768         if (ret < 0)
7769                 goto err;
7770
7771         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7772         if (IS_ERR(em)) {
7773                 ret = PTR_ERR(em);
7774                 goto unlock_err;
7775         }
7776
7777         /*
7778          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7779          * io.  INLINE is special, and we could probably kludge it in here, but
7780          * it's still buffered so for safety lets just fall back to the generic
7781          * buffered path.
7782          *
7783          * For COMPRESSED we _have_ to read the entire extent in so we can
7784          * decompress it, so there will be buffering required no matter what we
7785          * do, so go ahead and fallback to buffered.
7786          *
7787          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7788          * to buffered IO.  Don't blame me, this is the price we pay for using
7789          * the generic code.
7790          */
7791         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7792             em->block_start == EXTENT_MAP_INLINE) {
7793                 free_extent_map(em);
7794                 /*
7795                  * If we are in a NOWAIT context, return -EAGAIN in order to
7796                  * fallback to buffered IO. This is not only because we can
7797                  * block with buffered IO (no support for NOWAIT semantics at
7798                  * the moment) but also to avoid returning short reads to user
7799                  * space - this happens if we were able to read some data from
7800                  * previous non-compressed extents and then when we fallback to
7801                  * buffered IO, at btrfs_file_read_iter() by calling
7802                  * filemap_read(), we fail to fault in pages for the read buffer,
7803                  * in which case filemap_read() returns a short read (the number
7804                  * of bytes previously read is > 0, so it does not return -EFAULT).
7805                  */
7806                 ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
7807                 goto unlock_err;
7808         }
7809
7810         len = min(len, em->len - (start - em->start));
7811
7812         /*
7813          * If we have a NOWAIT request and the range contains multiple extents
7814          * (or a mix of extents and holes), then we return -EAGAIN to make the
7815          * caller fallback to a context where it can do a blocking (without
7816          * NOWAIT) request. This way we avoid doing partial IO and returning
7817          * success to the caller, which is not optimal for writes and for reads
7818          * it can result in unexpected behaviour for an application.
7819          *
7820          * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
7821          * iomap_dio_rw(), we can end up returning less data then what the caller
7822          * asked for, resulting in an unexpected, and incorrect, short read.
7823          * That is, the caller asked to read N bytes and we return less than that,
7824          * which is wrong unless we are crossing EOF. This happens if we get a
7825          * page fault error when trying to fault in pages for the buffer that is
7826          * associated to the struct iov_iter passed to iomap_dio_rw(), and we
7827          * have previously submitted bios for other extents in the range, in
7828          * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
7829          * those bios have completed by the time we get the page fault error,
7830          * which we return back to our caller - we should only return EIOCBQUEUED
7831          * after we have submitted bios for all the extents in the range.
7832          */
7833         if ((flags & IOMAP_NOWAIT) && len < length) {
7834                 free_extent_map(em);
7835                 ret = -EAGAIN;
7836                 goto unlock_err;
7837         }
7838
7839         if (write) {
7840                 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7841                                                     start, &len, flags);
7842                 if (ret < 0)
7843                         goto unlock_err;
7844                 unlock_extents = true;
7845                 /* Recalc len in case the new em is smaller than requested */
7846                 len = min(len, em->len - (start - em->start));
7847                 if (dio_data->data_space_reserved) {
7848                         u64 release_offset;
7849                         u64 release_len = 0;
7850
7851                         if (dio_data->nocow_done) {
7852                                 release_offset = start;
7853                                 release_len = data_alloc_len;
7854                         } else if (len < data_alloc_len) {
7855                                 release_offset = start + len;
7856                                 release_len = data_alloc_len - len;
7857                         }
7858
7859                         if (release_len > 0)
7860                                 btrfs_free_reserved_data_space(BTRFS_I(inode),
7861                                                                dio_data->data_reserved,
7862                                                                release_offset,
7863                                                                release_len);
7864                 }
7865         } else {
7866                 /*
7867                  * We need to unlock only the end area that we aren't using.
7868                  * The rest is going to be unlocked by the endio routine.
7869                  */
7870                 lockstart = start + len;
7871                 if (lockstart < lockend)
7872                         unlock_extents = true;
7873         }
7874
7875         if (unlock_extents)
7876                 unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7877                               &cached_state);
7878         else
7879                 free_extent_state(cached_state);
7880
7881         /*
7882          * Translate extent map information to iomap.
7883          * We trim the extents (and move the addr) even though iomap code does
7884          * that, since we have locked only the parts we are performing I/O in.
7885          */
7886         if ((em->block_start == EXTENT_MAP_HOLE) ||
7887             (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7888                 iomap->addr = IOMAP_NULL_ADDR;
7889                 iomap->type = IOMAP_HOLE;
7890         } else {
7891                 iomap->addr = em->block_start + (start - em->start);
7892                 iomap->type = IOMAP_MAPPED;
7893         }
7894         iomap->offset = start;
7895         iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
7896         iomap->length = len;
7897
7898         if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
7899                 iomap->flags |= IOMAP_F_ZONE_APPEND;
7900
7901         free_extent_map(em);
7902
7903         return 0;
7904
7905 unlock_err:
7906         unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7907                       &cached_state);
7908 err:
7909         if (dio_data->data_space_reserved) {
7910                 btrfs_free_reserved_data_space(BTRFS_I(inode),
7911                                                dio_data->data_reserved,
7912                                                start, data_alloc_len);
7913                 extent_changeset_free(dio_data->data_reserved);
7914         }
7915
7916         return ret;
7917 }
7918
7919 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7920                 ssize_t written, unsigned int flags, struct iomap *iomap)
7921 {
7922         struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
7923         struct btrfs_dio_data *dio_data = iter->private;
7924         size_t submitted = dio_data->submitted;
7925         const bool write = !!(flags & IOMAP_WRITE);
7926         int ret = 0;
7927
7928         if (!write && (iomap->type == IOMAP_HOLE)) {
7929                 /* If reading from a hole, unlock and return */
7930                 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
7931                               NULL);
7932                 return 0;
7933         }
7934
7935         if (submitted < length) {
7936                 pos += submitted;
7937                 length -= submitted;
7938                 if (write)
7939                         btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
7940                                                        pos, length, false);
7941                 else
7942                         unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7943                                       pos + length - 1, NULL);
7944                 ret = -ENOTBLK;
7945         }
7946
7947         if (write)
7948                 extent_changeset_free(dio_data->data_reserved);
7949         return ret;
7950 }
7951
7952 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7953 {
7954         /*
7955          * This implies a barrier so that stores to dio_bio->bi_status before
7956          * this and loads of dio_bio->bi_status after this are fully ordered.
7957          */
7958         if (!refcount_dec_and_test(&dip->refs))
7959                 return;
7960
7961         if (btrfs_op(&dip->bio) == BTRFS_MAP_WRITE) {
7962                 btrfs_mark_ordered_io_finished(BTRFS_I(dip->inode), NULL,
7963                                                dip->file_offset, dip->bytes,
7964                                                !dip->bio.bi_status);
7965         } else {
7966                 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7967                               dip->file_offset,
7968                               dip->file_offset + dip->bytes - 1, NULL);
7969         }
7970
7971         kfree(dip->csums);
7972         bio_endio(&dip->bio);
7973 }
7974
7975 static void submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7976                                   int mirror_num,
7977                                   enum btrfs_compression_type compress_type)
7978 {
7979         struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
7980         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7981
7982         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7983
7984         refcount_inc(&dip->refs);
7985         btrfs_submit_bio(fs_info, bio, mirror_num);
7986 }
7987
7988 static blk_status_t btrfs_check_read_dio_bio(struct btrfs_dio_private *dip,
7989                                              struct btrfs_bio *bbio,
7990                                              const bool uptodate)
7991 {
7992         struct inode *inode = dip->inode;
7993         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7994         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7995         blk_status_t err = BLK_STS_OK;
7996         struct bvec_iter iter;
7997         struct bio_vec bv;
7998         u32 offset;
7999
8000         btrfs_bio_for_each_sector(fs_info, bv, bbio, iter, offset) {
8001                 u64 start = bbio->file_offset + offset;
8002
8003                 if (uptodate &&
8004                     (!csum || !btrfs_check_data_csum(inode, bbio, offset, bv.bv_page,
8005                                                bv.bv_offset))) {
8006                         btrfs_clean_io_failure(BTRFS_I(inode), start,
8007                                                bv.bv_page, bv.bv_offset);
8008                 } else {
8009                         int ret;
8010
8011                         ret = btrfs_repair_one_sector(inode, bbio, offset,
8012                                         bv.bv_page, bv.bv_offset,
8013                                         submit_dio_repair_bio);
8014                         if (ret)
8015                                 err = errno_to_blk_status(ret);
8016                 }
8017         }
8018
8019         return err;
8020 }
8021
8022 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
8023                                                      struct bio *bio,
8024                                                      u64 dio_file_offset)
8025 {
8026         return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, false);
8027 }
8028
8029 static void btrfs_end_dio_bio(struct btrfs_bio *bbio)
8030 {
8031         struct btrfs_dio_private *dip = bbio->private;
8032         struct bio *bio = &bbio->bio;
8033         blk_status_t err = bio->bi_status;
8034
8035         if (err)
8036                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8037                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8038                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8039                            bio->bi_opf, bio->bi_iter.bi_sector,
8040                            bio->bi_iter.bi_size, err);
8041
8042         if (bio_op(bio) == REQ_OP_READ)
8043                 err = btrfs_check_read_dio_bio(dip, bbio, !err);
8044
8045         if (err)
8046                 dip->bio.bi_status = err;
8047
8048         btrfs_record_physical_zoned(dip->inode, bbio->file_offset, bio);
8049
8050         bio_put(bio);
8051         btrfs_dio_private_put(dip);
8052 }
8053
8054 static void btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8055                                  u64 file_offset, int async_submit)
8056 {
8057         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8058         struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
8059         blk_status_t ret;
8060
8061         /* Save the original iter for read repair */
8062         if (btrfs_op(bio) == BTRFS_MAP_READ)
8063                 btrfs_bio(bio)->iter = bio->bi_iter;
8064
8065         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8066                 goto map;
8067
8068         if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
8069                 /* Check btrfs_submit_data_write_bio() for async submit rules */
8070                 if (async_submit && !atomic_read(&BTRFS_I(inode)->sync_writers) &&
8071                     btrfs_wq_submit_bio(inode, bio, 0, file_offset,
8072                                         btrfs_submit_bio_start_direct_io))
8073                         return;
8074
8075                 /*
8076                  * If we aren't doing async submit, calculate the csum of the
8077                  * bio now.
8078                  */
8079                 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, false);
8080                 if (ret) {
8081                         btrfs_bio_end_io(btrfs_bio(bio), ret);
8082                         return;
8083                 }
8084         } else {
8085                 btrfs_bio(bio)->csum = btrfs_csum_ptr(fs_info, dip->csums,
8086                                                       file_offset - dip->file_offset);
8087         }
8088 map:
8089         btrfs_submit_bio(fs_info, bio, 0);
8090 }
8091
8092 static void btrfs_submit_direct(const struct iomap_iter *iter,
8093                 struct bio *dio_bio, loff_t file_offset)
8094 {
8095         struct btrfs_dio_private *dip =
8096                 container_of(dio_bio, struct btrfs_dio_private, bio);
8097         struct inode *inode = iter->inode;
8098         const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8099         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8100         const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8101                              BTRFS_BLOCK_GROUP_RAID56_MASK);
8102         struct bio *bio;
8103         u64 start_sector;
8104         int async_submit = 0;
8105         u64 submit_len;
8106         u64 clone_offset = 0;
8107         u64 clone_len;
8108         u64 logical;
8109         int ret;
8110         blk_status_t status;
8111         struct btrfs_io_geometry geom;
8112         struct btrfs_dio_data *dio_data = iter->private;
8113         struct extent_map *em = NULL;
8114
8115         dip->inode = inode;
8116         dip->file_offset = file_offset;
8117         dip->bytes = dio_bio->bi_iter.bi_size;
8118         refcount_set(&dip->refs, 1);
8119         dip->csums = NULL;
8120
8121         if (!write && !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
8122                 unsigned int nr_sectors =
8123                         (dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits);
8124
8125                 /*
8126                  * Load the csums up front to reduce csum tree searches and
8127                  * contention when submitting bios.
8128                  */
8129                 status = BLK_STS_RESOURCE;
8130                 dip->csums = kcalloc(nr_sectors, fs_info->csum_size, GFP_NOFS);
8131                 if (!dip->csums)
8132                         goto out_err;
8133
8134                 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8135                 if (status != BLK_STS_OK)
8136                         goto out_err;
8137         }
8138
8139         start_sector = dio_bio->bi_iter.bi_sector;
8140         submit_len = dio_bio->bi_iter.bi_size;
8141
8142         do {
8143                 logical = start_sector << 9;
8144                 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8145                 if (IS_ERR(em)) {
8146                         status = errno_to_blk_status(PTR_ERR(em));
8147                         em = NULL;
8148                         goto out_err_em;
8149                 }
8150                 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8151                                             logical, &geom);
8152                 if (ret) {
8153                         status = errno_to_blk_status(ret);
8154                         goto out_err_em;
8155                 }
8156
8157                 clone_len = min(submit_len, geom.len);
8158                 ASSERT(clone_len <= UINT_MAX);
8159
8160                 /*
8161                  * This will never fail as it's passing GPF_NOFS and
8162                  * the allocation is backed by btrfs_bioset.
8163                  */
8164                 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len,
8165                                               btrfs_end_dio_bio, dip);
8166                 btrfs_bio(bio)->file_offset = file_offset;
8167
8168                 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8169                         status = extract_ordered_extent(BTRFS_I(inode), bio,
8170                                                         file_offset);
8171                         if (status) {
8172                                 bio_put(bio);
8173                                 goto out_err;
8174                         }
8175                 }
8176
8177                 ASSERT(submit_len >= clone_len);
8178                 submit_len -= clone_len;
8179
8180                 /*
8181                  * Increase the count before we submit the bio so we know
8182                  * the end IO handler won't happen before we increase the
8183                  * count. Otherwise, the dip might get freed before we're
8184                  * done setting it up.
8185                  *
8186                  * We transfer the initial reference to the last bio, so we
8187                  * don't need to increment the reference count for the last one.
8188                  */
8189                 if (submit_len > 0) {
8190                         refcount_inc(&dip->refs);
8191                         /*
8192                          * If we are submitting more than one bio, submit them
8193                          * all asynchronously. The exception is RAID 5 or 6, as
8194                          * asynchronous checksums make it difficult to collect
8195                          * full stripe writes.
8196                          */
8197                         if (!raid56)
8198                                 async_submit = 1;
8199                 }
8200
8201                 btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8202
8203                 dio_data->submitted += clone_len;
8204                 clone_offset += clone_len;
8205                 start_sector += clone_len >> 9;
8206                 file_offset += clone_len;
8207
8208                 free_extent_map(em);
8209         } while (submit_len > 0);
8210         return;
8211
8212 out_err_em:
8213         free_extent_map(em);
8214 out_err:
8215         dio_bio->bi_status = status;
8216         btrfs_dio_private_put(dip);
8217 }
8218
8219 static const struct iomap_ops btrfs_dio_iomap_ops = {
8220         .iomap_begin            = btrfs_dio_iomap_begin,
8221         .iomap_end              = btrfs_dio_iomap_end,
8222 };
8223
8224 static const struct iomap_dio_ops btrfs_dio_ops = {
8225         .submit_io              = btrfs_submit_direct,
8226         .bio_set                = &btrfs_dio_bioset,
8227 };
8228
8229 ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
8230 {
8231         struct btrfs_dio_data data;
8232
8233         return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
8234                             IOMAP_DIO_PARTIAL, &data, done_before);
8235 }
8236
8237 struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
8238                                   size_t done_before)
8239 {
8240         struct btrfs_dio_data data;
8241
8242         return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
8243                             IOMAP_DIO_PARTIAL, &data, done_before);
8244 }
8245
8246 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8247                         u64 start, u64 len)
8248 {
8249         int     ret;
8250
8251         ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8252         if (ret)
8253                 return ret;
8254
8255         /*
8256          * fiemap_prep() called filemap_write_and_wait() for the whole possible
8257          * file range (0 to LLONG_MAX), but that is not enough if we have
8258          * compression enabled. The first filemap_fdatawrite_range() only kicks
8259          * in the compression of data (in an async thread) and will return
8260          * before the compression is done and writeback is started. A second
8261          * filemap_fdatawrite_range() is needed to wait for the compression to
8262          * complete and writeback to start. We also need to wait for ordered
8263          * extents to complete, because our fiemap implementation uses mainly
8264          * file extent items to list the extents, searching for extent maps
8265          * only for file ranges with holes or prealloc extents to figure out
8266          * if we have delalloc in those ranges.
8267          */
8268         if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
8269                 ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
8270                 if (ret)
8271                         return ret;
8272         }
8273
8274         return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8275 }
8276
8277 static int btrfs_writepages(struct address_space *mapping,
8278                             struct writeback_control *wbc)
8279 {
8280         return extent_writepages(mapping, wbc);
8281 }
8282
8283 static void btrfs_readahead(struct readahead_control *rac)
8284 {
8285         extent_readahead(rac);
8286 }
8287
8288 /*
8289  * For release_folio() and invalidate_folio() we have a race window where
8290  * folio_end_writeback() is called but the subpage spinlock is not yet released.
8291  * If we continue to release/invalidate the page, we could cause use-after-free
8292  * for subpage spinlock.  So this function is to spin and wait for subpage
8293  * spinlock.
8294  */
8295 static void wait_subpage_spinlock(struct page *page)
8296 {
8297         struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
8298         struct btrfs_subpage *subpage;
8299
8300         if (!btrfs_is_subpage(fs_info, page))
8301                 return;
8302
8303         ASSERT(PagePrivate(page) && page->private);
8304         subpage = (struct btrfs_subpage *)page->private;
8305
8306         /*
8307          * This may look insane as we just acquire the spinlock and release it,
8308          * without doing anything.  But we just want to make sure no one is
8309          * still holding the subpage spinlock.
8310          * And since the page is not dirty nor writeback, and we have page
8311          * locked, the only possible way to hold a spinlock is from the endio
8312          * function to clear page writeback.
8313          *
8314          * Here we just acquire the spinlock so that all existing callers
8315          * should exit and we're safe to release/invalidate the page.
8316          */
8317         spin_lock_irq(&subpage->lock);
8318         spin_unlock_irq(&subpage->lock);
8319 }
8320
8321 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8322 {
8323         int ret = try_release_extent_mapping(&folio->page, gfp_flags);
8324
8325         if (ret == 1) {
8326                 wait_subpage_spinlock(&folio->page);
8327                 clear_page_extent_mapped(&folio->page);
8328         }
8329         return ret;
8330 }
8331
8332 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
8333 {
8334         if (folio_test_writeback(folio) || folio_test_dirty(folio))
8335                 return false;
8336         return __btrfs_release_folio(folio, gfp_flags);
8337 }
8338
8339 #ifdef CONFIG_MIGRATION
8340 static int btrfs_migrate_folio(struct address_space *mapping,
8341                              struct folio *dst, struct folio *src,
8342                              enum migrate_mode mode)
8343 {
8344         int ret = filemap_migrate_folio(mapping, dst, src, mode);
8345
8346         if (ret != MIGRATEPAGE_SUCCESS)
8347                 return ret;
8348
8349         if (folio_test_ordered(src)) {
8350                 folio_clear_ordered(src);
8351                 folio_set_ordered(dst);
8352         }
8353
8354         return MIGRATEPAGE_SUCCESS;
8355 }
8356 #else
8357 #define btrfs_migrate_folio NULL
8358 #endif
8359
8360 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
8361                                  size_t length)
8362 {
8363         struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
8364         struct btrfs_fs_info *fs_info = inode->root->fs_info;
8365         struct extent_io_tree *tree = &inode->io_tree;
8366         struct extent_state *cached_state = NULL;
8367         u64 page_start = folio_pos(folio);
8368         u64 page_end = page_start + folio_size(folio) - 1;
8369         u64 cur;
8370         int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8371
8372         /*
8373          * We have folio locked so no new ordered extent can be created on this
8374          * page, nor bio can be submitted for this folio.
8375          *
8376          * But already submitted bio can still be finished on this folio.
8377          * Furthermore, endio function won't skip folio which has Ordered
8378          * (Private2) already cleared, so it's possible for endio and
8379          * invalidate_folio to do the same ordered extent accounting twice
8380          * on one folio.
8381          *
8382          * So here we wait for any submitted bios to finish, so that we won't
8383          * do double ordered extent accounting on the same folio.
8384          */
8385         folio_wait_writeback(folio);
8386         wait_subpage_spinlock(&folio->page);
8387
8388         /*
8389          * For subpage case, we have call sites like
8390          * btrfs_punch_hole_lock_range() which passes range not aligned to
8391          * sectorsize.
8392          * If the range doesn't cover the full folio, we don't need to and
8393          * shouldn't clear page extent mapped, as folio->private can still
8394          * record subpage dirty bits for other part of the range.
8395          *
8396          * For cases that invalidate the full folio even the range doesn't
8397          * cover the full folio, like invalidating the last folio, we're
8398          * still safe to wait for ordered extent to finish.
8399          */
8400         if (!(offset == 0 && length == folio_size(folio))) {
8401                 btrfs_release_folio(folio, GFP_NOFS);
8402                 return;
8403         }
8404
8405         if (!inode_evicting)
8406                 lock_extent(tree, page_start, page_end, &cached_state);
8407
8408         cur = page_start;
8409         while (cur < page_end) {
8410                 struct btrfs_ordered_extent *ordered;
8411                 u64 range_end;
8412                 u32 range_len;
8413                 u32 extra_flags = 0;
8414
8415                 ordered = btrfs_lookup_first_ordered_range(inode, cur,
8416                                                            page_end + 1 - cur);
8417                 if (!ordered) {
8418                         range_end = page_end;
8419                         /*
8420                          * No ordered extent covering this range, we are safe
8421                          * to delete all extent states in the range.
8422                          */
8423                         extra_flags = EXTENT_CLEAR_ALL_BITS;
8424                         goto next;
8425                 }
8426                 if (ordered->file_offset > cur) {
8427                         /*
8428                          * There is a range between [cur, oe->file_offset) not
8429                          * covered by any ordered extent.
8430                          * We are safe to delete all extent states, and handle
8431                          * the ordered extent in the next iteration.
8432                          */
8433                         range_end = ordered->file_offset - 1;
8434                         extra_flags = EXTENT_CLEAR_ALL_BITS;
8435                         goto next;
8436                 }
8437
8438                 range_end = min(ordered->file_offset + ordered->num_bytes - 1,
8439                                 page_end);
8440                 ASSERT(range_end + 1 - cur < U32_MAX);
8441                 range_len = range_end + 1 - cur;
8442                 if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
8443                         /*
8444                          * If Ordered (Private2) is cleared, it means endio has
8445                          * already been executed for the range.
8446                          * We can't delete the extent states as
8447                          * btrfs_finish_ordered_io() may still use some of them.
8448                          */
8449                         goto next;
8450                 }
8451                 btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
8452
8453                 /*
8454                  * IO on this page will never be started, so we need to account
8455                  * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8456                  * here, must leave that up for the ordered extent completion.
8457                  *
8458                  * This will also unlock the range for incoming
8459                  * btrfs_finish_ordered_io().
8460                  */
8461                 if (!inode_evicting)
8462                         clear_extent_bit(tree, cur, range_end,
8463                                          EXTENT_DELALLOC |
8464                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8465                                          EXTENT_DEFRAG, &cached_state);
8466
8467                 spin_lock_irq(&inode->ordered_tree.lock);
8468                 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8469                 ordered->truncated_len = min(ordered->truncated_len,
8470                                              cur - ordered->file_offset);
8471                 spin_unlock_irq(&inode->ordered_tree.lock);
8472
8473                 /*
8474                  * If the ordered extent has finished, we're safe to delete all
8475                  * the extent states of the range, otherwise
8476                  * btrfs_finish_ordered_io() will get executed by endio for
8477                  * other pages, so we can't delete extent states.
8478                  */
8479                 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8480                                                    cur, range_end + 1 - cur)) {
8481                         btrfs_finish_ordered_io(ordered);
8482                         /*
8483                          * The ordered extent has finished, now we're again
8484                          * safe to delete all extent states of the range.
8485                          */
8486                         extra_flags = EXTENT_CLEAR_ALL_BITS;
8487                 }
8488 next:
8489                 if (ordered)
8490                         btrfs_put_ordered_extent(ordered);
8491                 /*
8492                  * Qgroup reserved space handler
8493                  * Sector(s) here will be either:
8494                  *
8495                  * 1) Already written to disk or bio already finished
8496                  *    Then its QGROUP_RESERVED bit in io_tree is already cleared.
8497                  *    Qgroup will be handled by its qgroup_record then.
8498                  *    btrfs_qgroup_free_data() call will do nothing here.
8499                  *
8500                  * 2) Not written to disk yet
8501                  *    Then btrfs_qgroup_free_data() call will clear the
8502                  *    QGROUP_RESERVED bit of its io_tree, and free the qgroup
8503                  *    reserved data space.
8504                  *    Since the IO will never happen for this page.
8505                  */
8506                 btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
8507                 if (!inode_evicting) {
8508                         clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
8509                                  EXTENT_DELALLOC | EXTENT_UPTODATE |
8510                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
8511                                  extra_flags, &cached_state);
8512                 }
8513                 cur = range_end + 1;
8514         }
8515         /*
8516          * We have iterated through all ordered extents of the page, the page
8517          * should not have Ordered (Private2) anymore, or the above iteration
8518          * did something wrong.
8519          */
8520         ASSERT(!folio_test_ordered(folio));
8521         btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
8522         if (!inode_evicting)
8523                 __btrfs_release_folio(folio, GFP_NOFS);
8524         clear_page_extent_mapped(&folio->page);
8525 }
8526
8527 /*
8528  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8529  * called from a page fault handler when a page is first dirtied. Hence we must
8530  * be careful to check for EOF conditions here. We set the page up correctly
8531  * for a written page which means we get ENOSPC checking when writing into
8532  * holes and correct delalloc and unwritten extent mapping on filesystems that
8533  * support these features.
8534  *
8535  * We are not allowed to take the i_mutex here so we have to play games to
8536  * protect against truncate races as the page could now be beyond EOF.  Because
8537  * truncate_setsize() writes the inode size before removing pages, once we have
8538  * the page lock we can determine safely if the page is beyond EOF. If it is not
8539  * beyond EOF, then the page is guaranteed safe against truncation until we
8540  * unlock the page.
8541  */
8542 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8543 {
8544         struct page *page = vmf->page;
8545         struct inode *inode = file_inode(vmf->vma->vm_file);
8546         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8547         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8548         struct btrfs_ordered_extent *ordered;
8549         struct extent_state *cached_state = NULL;
8550         struct extent_changeset *data_reserved = NULL;
8551         unsigned long zero_start;
8552         loff_t size;
8553         vm_fault_t ret;
8554         int ret2;
8555         int reserved = 0;
8556         u64 reserved_space;
8557         u64 page_start;
8558         u64 page_end;
8559         u64 end;
8560
8561         reserved_space = PAGE_SIZE;
8562
8563         sb_start_pagefault(inode->i_sb);
8564         page_start = page_offset(page);
8565         page_end = page_start + PAGE_SIZE - 1;
8566         end = page_end;
8567
8568         /*
8569          * Reserving delalloc space after obtaining the page lock can lead to
8570          * deadlock. For example, if a dirty page is locked by this function
8571          * and the call to btrfs_delalloc_reserve_space() ends up triggering
8572          * dirty page write out, then the btrfs_writepages() function could
8573          * end up waiting indefinitely to get a lock on the page currently
8574          * being processed by btrfs_page_mkwrite() function.
8575          */
8576         ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8577                                             page_start, reserved_space);
8578         if (!ret2) {
8579                 ret2 = file_update_time(vmf->vma->vm_file);
8580                 reserved = 1;
8581         }
8582         if (ret2) {
8583                 ret = vmf_error(ret2);
8584                 if (reserved)
8585                         goto out;
8586                 goto out_noreserve;
8587         }
8588
8589         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8590 again:
8591         down_read(&BTRFS_I(inode)->i_mmap_lock);
8592         lock_page(page);
8593         size = i_size_read(inode);
8594
8595         if ((page->mapping != inode->i_mapping) ||
8596             (page_start >= size)) {
8597                 /* page got truncated out from underneath us */
8598                 goto out_unlock;
8599         }
8600         wait_on_page_writeback(page);
8601
8602         lock_extent(io_tree, page_start, page_end, &cached_state);
8603         ret2 = set_page_extent_mapped(page);
8604         if (ret2 < 0) {
8605                 ret = vmf_error(ret2);
8606                 unlock_extent(io_tree, page_start, page_end, &cached_state);
8607                 goto out_unlock;
8608         }
8609
8610         /*
8611          * we can't set the delalloc bits if there are pending ordered
8612          * extents.  Drop our locks and wait for them to finish
8613          */
8614         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8615                         PAGE_SIZE);
8616         if (ordered) {
8617                 unlock_extent(io_tree, page_start, page_end, &cached_state);
8618                 unlock_page(page);
8619                 up_read(&BTRFS_I(inode)->i_mmap_lock);
8620                 btrfs_start_ordered_extent(ordered, 1);
8621                 btrfs_put_ordered_extent(ordered);
8622                 goto again;
8623         }
8624
8625         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8626                 reserved_space = round_up(size - page_start,
8627                                           fs_info->sectorsize);
8628                 if (reserved_space < PAGE_SIZE) {
8629                         end = page_start + reserved_space - 1;
8630                         btrfs_delalloc_release_space(BTRFS_I(inode),
8631                                         data_reserved, page_start,
8632                                         PAGE_SIZE - reserved_space, true);
8633                 }
8634         }
8635
8636         /*
8637          * page_mkwrite gets called when the page is firstly dirtied after it's
8638          * faulted in, but write(2) could also dirty a page and set delalloc
8639          * bits, thus in this case for space account reason, we still need to
8640          * clear any delalloc bits within this page range since we have to
8641          * reserve data&meta space before lock_page() (see above comments).
8642          */
8643         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8644                           EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8645                           EXTENT_DEFRAG, &cached_state);
8646
8647         ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8648                                         &cached_state);
8649         if (ret2) {
8650                 unlock_extent(io_tree, page_start, page_end, &cached_state);
8651                 ret = VM_FAULT_SIGBUS;
8652                 goto out_unlock;
8653         }
8654
8655         /* page is wholly or partially inside EOF */
8656         if (page_start + PAGE_SIZE > size)
8657                 zero_start = offset_in_page(size);
8658         else
8659                 zero_start = PAGE_SIZE;
8660
8661         if (zero_start != PAGE_SIZE)
8662                 memzero_page(page, zero_start, PAGE_SIZE - zero_start);
8663
8664         btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
8665         btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
8666         btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
8667
8668         btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8669
8670         unlock_extent(io_tree, page_start, page_end, &cached_state);
8671         up_read(&BTRFS_I(inode)->i_mmap_lock);
8672
8673         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8674         sb_end_pagefault(inode->i_sb);
8675         extent_changeset_free(data_reserved);
8676         return VM_FAULT_LOCKED;
8677
8678 out_unlock:
8679         unlock_page(page);
8680         up_read(&BTRFS_I(inode)->i_mmap_lock);
8681 out:
8682         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8683         btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8684                                      reserved_space, (ret != 0));
8685 out_noreserve:
8686         sb_end_pagefault(inode->i_sb);
8687         extent_changeset_free(data_reserved);
8688         return ret;
8689 }
8690
8691 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8692 {
8693         struct btrfs_truncate_control control = {
8694                 .inode = BTRFS_I(inode),
8695                 .ino = btrfs_ino(BTRFS_I(inode)),
8696                 .min_type = BTRFS_EXTENT_DATA_KEY,
8697                 .clear_extent_range = true,
8698         };
8699         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8700         struct btrfs_root *root = BTRFS_I(inode)->root;
8701         struct btrfs_block_rsv *rsv;
8702         int ret;
8703         struct btrfs_trans_handle *trans;
8704         u64 mask = fs_info->sectorsize - 1;
8705         u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8706
8707         if (!skip_writeback) {
8708                 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8709                                                (u64)-1);
8710                 if (ret)
8711                         return ret;
8712         }
8713
8714         /*
8715          * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
8716          * things going on here:
8717          *
8718          * 1) We need to reserve space to update our inode.
8719          *
8720          * 2) We need to have something to cache all the space that is going to
8721          * be free'd up by the truncate operation, but also have some slack
8722          * space reserved in case it uses space during the truncate (thank you
8723          * very much snapshotting).
8724          *
8725          * And we need these to be separate.  The fact is we can use a lot of
8726          * space doing the truncate, and we have no earthly idea how much space
8727          * we will use, so we need the truncate reservation to be separate so it
8728          * doesn't end up using space reserved for updating the inode.  We also
8729          * need to be able to stop the transaction and start a new one, which
8730          * means we need to be able to update the inode several times, and we
8731          * have no idea of knowing how many times that will be, so we can't just
8732          * reserve 1 item for the entirety of the operation, so that has to be
8733          * done separately as well.
8734          *
8735          * So that leaves us with
8736          *
8737          * 1) rsv - for the truncate reservation, which we will steal from the
8738          * transaction reservation.
8739          * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8740          * updating the inode.
8741          */
8742         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8743         if (!rsv)
8744                 return -ENOMEM;
8745         rsv->size = min_size;
8746         rsv->failfast = true;
8747
8748         /*
8749          * 1 for the truncate slack space
8750          * 1 for updating the inode.
8751          */
8752         trans = btrfs_start_transaction(root, 2);
8753         if (IS_ERR(trans)) {
8754                 ret = PTR_ERR(trans);
8755                 goto out;
8756         }
8757
8758         /* Migrate the slack space for the truncate to our reserve */
8759         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8760                                       min_size, false);
8761         BUG_ON(ret);
8762
8763         trans->block_rsv = rsv;
8764
8765         while (1) {
8766                 struct extent_state *cached_state = NULL;
8767                 const u64 new_size = inode->i_size;
8768                 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
8769
8770                 control.new_size = new_size;
8771                 lock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8772                                  &cached_state);
8773                 /*
8774                  * We want to drop from the next block forward in case this new
8775                  * size is not block aligned since we will be keeping the last
8776                  * block of the extent just the way it is.
8777                  */
8778                 btrfs_drop_extent_map_range(BTRFS_I(inode),
8779                                             ALIGN(new_size, fs_info->sectorsize),
8780                                             (u64)-1, false);
8781
8782                 ret = btrfs_truncate_inode_items(trans, root, &control);
8783
8784                 inode_sub_bytes(inode, control.sub_bytes);
8785                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), control.last_size);
8786
8787                 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
8788                               &cached_state);
8789
8790                 trans->block_rsv = &fs_info->trans_block_rsv;
8791                 if (ret != -ENOSPC && ret != -EAGAIN)
8792                         break;
8793
8794                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8795                 if (ret)
8796                         break;
8797
8798                 btrfs_end_transaction(trans);
8799                 btrfs_btree_balance_dirty(fs_info);
8800
8801                 trans = btrfs_start_transaction(root, 2);
8802                 if (IS_ERR(trans)) {
8803                         ret = PTR_ERR(trans);
8804                         trans = NULL;
8805                         break;
8806                 }
8807
8808                 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8809                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8810                                               rsv, min_size, false);
8811                 BUG_ON(ret);    /* shouldn't happen */
8812                 trans->block_rsv = rsv;
8813         }
8814
8815         /*
8816          * We can't call btrfs_truncate_block inside a trans handle as we could
8817          * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
8818          * know we've truncated everything except the last little bit, and can
8819          * do btrfs_truncate_block and then update the disk_i_size.
8820          */
8821         if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
8822                 btrfs_end_transaction(trans);
8823                 btrfs_btree_balance_dirty(fs_info);
8824
8825                 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8826                 if (ret)
8827                         goto out;
8828                 trans = btrfs_start_transaction(root, 1);
8829                 if (IS_ERR(trans)) {
8830                         ret = PTR_ERR(trans);
8831                         goto out;
8832                 }
8833                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8834         }
8835
8836         if (trans) {
8837                 int ret2;
8838
8839                 trans->block_rsv = &fs_info->trans_block_rsv;
8840                 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8841                 if (ret2 && !ret)
8842                         ret = ret2;
8843
8844                 ret2 = btrfs_end_transaction(trans);
8845                 if (ret2 && !ret)
8846                         ret = ret2;
8847                 btrfs_btree_balance_dirty(fs_info);
8848         }
8849 out:
8850         btrfs_free_block_rsv(fs_info, rsv);
8851         /*
8852          * So if we truncate and then write and fsync we normally would just
8853          * write the extents that changed, which is a problem if we need to
8854          * first truncate that entire inode.  So set this flag so we write out
8855          * all of the extents in the inode to the sync log so we're completely
8856          * safe.
8857          *
8858          * If no extents were dropped or trimmed we don't need to force the next
8859          * fsync to truncate all the inode's items from the log and re-log them
8860          * all. This means the truncate operation did not change the file size,
8861          * or changed it to a smaller size but there was only an implicit hole
8862          * between the old i_size and the new i_size, and there were no prealloc
8863          * extents beyond i_size to drop.
8864          */
8865         if (control.extents_found > 0)
8866                 btrfs_set_inode_full_sync(BTRFS_I(inode));
8867
8868         return ret;
8869 }
8870
8871 struct inode *btrfs_new_subvol_inode(struct user_namespace *mnt_userns,
8872                                      struct inode *dir)
8873 {
8874         struct inode *inode;
8875
8876         inode = new_inode(dir->i_sb);
8877         if (inode) {
8878                 /*
8879                  * Subvolumes don't inherit the sgid bit or the parent's gid if
8880                  * the parent's sgid bit is set. This is probably a bug.
8881                  */
8882                 inode_init_owner(mnt_userns, inode, NULL,
8883                                  S_IFDIR | (~current_umask() & S_IRWXUGO));
8884                 inode->i_op = &btrfs_dir_inode_operations;
8885                 inode->i_fop = &btrfs_dir_file_operations;
8886         }
8887         return inode;
8888 }
8889
8890 struct inode *btrfs_alloc_inode(struct super_block *sb)
8891 {
8892         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8893         struct btrfs_inode *ei;
8894         struct inode *inode;
8895
8896         ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8897         if (!ei)
8898                 return NULL;
8899
8900         ei->root = NULL;
8901         ei->generation = 0;
8902         ei->last_trans = 0;
8903         ei->last_sub_trans = 0;
8904         ei->logged_trans = 0;
8905         ei->delalloc_bytes = 0;
8906         ei->new_delalloc_bytes = 0;
8907         ei->defrag_bytes = 0;
8908         ei->disk_i_size = 0;
8909         ei->flags = 0;
8910         ei->ro_flags = 0;
8911         ei->csum_bytes = 0;
8912         ei->index_cnt = (u64)-1;
8913         ei->dir_index = 0;
8914         ei->last_unlink_trans = 0;
8915         ei->last_reflink_trans = 0;
8916         ei->last_log_commit = 0;
8917
8918         spin_lock_init(&ei->lock);
8919         spin_lock_init(&ei->io_failure_lock);
8920         ei->outstanding_extents = 0;
8921         if (sb->s_magic != BTRFS_TEST_MAGIC)
8922                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8923                                               BTRFS_BLOCK_RSV_DELALLOC);
8924         ei->runtime_flags = 0;
8925         ei->prop_compress = BTRFS_COMPRESS_NONE;
8926         ei->defrag_compress = BTRFS_COMPRESS_NONE;
8927
8928         ei->delayed_node = NULL;
8929
8930         ei->i_otime.tv_sec = 0;
8931         ei->i_otime.tv_nsec = 0;
8932
8933         inode = &ei->vfs_inode;
8934         extent_map_tree_init(&ei->extent_tree);
8935         extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8936         extent_io_tree_init(fs_info, &ei->file_extent_tree,
8937                             IO_TREE_INODE_FILE_EXTENT, NULL);
8938         ei->io_failure_tree = RB_ROOT;
8939         atomic_set(&ei->sync_writers, 0);
8940         mutex_init(&ei->log_mutex);
8941         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8942         INIT_LIST_HEAD(&ei->delalloc_inodes);
8943         INIT_LIST_HEAD(&ei->delayed_iput);
8944         RB_CLEAR_NODE(&ei->rb_node);
8945         init_rwsem(&ei->i_mmap_lock);
8946
8947         return inode;
8948 }
8949
8950 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8951 void btrfs_test_destroy_inode(struct inode *inode)
8952 {
8953         btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8954         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8955 }
8956 #endif
8957
8958 void btrfs_free_inode(struct inode *inode)
8959 {
8960         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8961 }
8962
8963 void btrfs_destroy_inode(struct inode *vfs_inode)
8964 {
8965         struct btrfs_ordered_extent *ordered;
8966         struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8967         struct btrfs_root *root = inode->root;
8968         bool freespace_inode;
8969
8970         WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8971         WARN_ON(vfs_inode->i_data.nrpages);
8972         WARN_ON(inode->block_rsv.reserved);
8973         WARN_ON(inode->block_rsv.size);
8974         WARN_ON(inode->outstanding_extents);
8975         if (!S_ISDIR(vfs_inode->i_mode)) {
8976                 WARN_ON(inode->delalloc_bytes);
8977                 WARN_ON(inode->new_delalloc_bytes);
8978         }
8979         WARN_ON(inode->csum_bytes);
8980         WARN_ON(inode->defrag_bytes);
8981
8982         /*
8983          * This can happen where we create an inode, but somebody else also
8984          * created the same inode and we need to destroy the one we already
8985          * created.
8986          */
8987         if (!root)
8988                 return;
8989
8990         /*
8991          * If this is a free space inode do not take the ordered extents lockdep
8992          * map.
8993          */
8994         freespace_inode = btrfs_is_free_space_inode(inode);
8995
8996         while (1) {
8997                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8998                 if (!ordered)
8999                         break;
9000                 else {
9001                         btrfs_err(root->fs_info,
9002                                   "found ordered extent %llu %llu on inode cleanup",
9003                                   ordered->file_offset, ordered->num_bytes);
9004
9005                         if (!freespace_inode)
9006                                 btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
9007
9008                         btrfs_remove_ordered_extent(inode, ordered);
9009                         btrfs_put_ordered_extent(ordered);
9010                         btrfs_put_ordered_extent(ordered);
9011                 }
9012         }
9013         btrfs_qgroup_check_reserved_leak(inode);
9014         inode_tree_del(inode);
9015         btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
9016         btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
9017         btrfs_put_root(inode->root);
9018 }
9019
9020 int btrfs_drop_inode(struct inode *inode)
9021 {
9022         struct btrfs_root *root = BTRFS_I(inode)->root;
9023
9024         if (root == NULL)
9025                 return 1;
9026
9027         /* the snap/subvol tree is on deleting */
9028         if (btrfs_root_refs(&root->root_item) == 0)
9029                 return 1;
9030         else
9031                 return generic_drop_inode(inode);
9032 }
9033
9034 static void init_once(void *foo)
9035 {
9036         struct btrfs_inode *ei = foo;
9037
9038         inode_init_once(&ei->vfs_inode);
9039 }
9040
9041 void __cold btrfs_destroy_cachep(void)
9042 {
9043         /*
9044          * Make sure all delayed rcu free inodes are flushed before we
9045          * destroy cache.
9046          */
9047         rcu_barrier();
9048         bioset_exit(&btrfs_dio_bioset);
9049         kmem_cache_destroy(btrfs_inode_cachep);
9050         kmem_cache_destroy(btrfs_trans_handle_cachep);
9051         kmem_cache_destroy(btrfs_path_cachep);
9052         kmem_cache_destroy(btrfs_free_space_cachep);
9053         kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
9054 }
9055
9056 int __init btrfs_init_cachep(void)
9057 {
9058         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9059                         sizeof(struct btrfs_inode), 0,
9060                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9061                         init_once);
9062         if (!btrfs_inode_cachep)
9063                 goto fail;
9064
9065         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9066                         sizeof(struct btrfs_trans_handle), 0,
9067                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9068         if (!btrfs_trans_handle_cachep)
9069                 goto fail;
9070
9071         btrfs_path_cachep = kmem_cache_create("btrfs_path",
9072                         sizeof(struct btrfs_path), 0,
9073                         SLAB_MEM_SPREAD, NULL);
9074         if (!btrfs_path_cachep)
9075                 goto fail;
9076
9077         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9078                         sizeof(struct btrfs_free_space), 0,
9079                         SLAB_MEM_SPREAD, NULL);
9080         if (!btrfs_free_space_cachep)
9081                 goto fail;
9082
9083         btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9084                                                         PAGE_SIZE, PAGE_SIZE,
9085                                                         SLAB_MEM_SPREAD, NULL);
9086         if (!btrfs_free_space_bitmap_cachep)
9087                 goto fail;
9088
9089         if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
9090                         offsetof(struct btrfs_dio_private, bio),
9091                         BIOSET_NEED_BVECS))
9092                 goto fail;
9093
9094         return 0;
9095 fail:
9096         btrfs_destroy_cachep();
9097         return -ENOMEM;
9098 }
9099
9100 static int btrfs_getattr(struct user_namespace *mnt_userns,
9101                          const struct path *path, struct kstat *stat,
9102                          u32 request_mask, unsigned int flags)
9103 {
9104         u64 delalloc_bytes;
9105         u64 inode_bytes;
9106         struct inode *inode = d_inode(path->dentry);
9107         u32 blocksize = inode->i_sb->s_blocksize;
9108         u32 bi_flags = BTRFS_I(inode)->flags;
9109         u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
9110
9111         stat->result_mask |= STATX_BTIME;
9112         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9113         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9114         if (bi_flags & BTRFS_INODE_APPEND)
9115                 stat->attributes |= STATX_ATTR_APPEND;
9116         if (bi_flags & BTRFS_INODE_COMPRESS)
9117                 stat->attributes |= STATX_ATTR_COMPRESSED;
9118         if (bi_flags & BTRFS_INODE_IMMUTABLE)
9119                 stat->attributes |= STATX_ATTR_IMMUTABLE;
9120         if (bi_flags & BTRFS_INODE_NODUMP)
9121                 stat->attributes |= STATX_ATTR_NODUMP;
9122         if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
9123                 stat->attributes |= STATX_ATTR_VERITY;
9124
9125         stat->attributes_mask |= (STATX_ATTR_APPEND |
9126                                   STATX_ATTR_COMPRESSED |
9127                                   STATX_ATTR_IMMUTABLE |
9128                                   STATX_ATTR_NODUMP);
9129
9130         generic_fillattr(mnt_userns, inode, stat);
9131         stat->dev = BTRFS_I(inode)->root->anon_dev;
9132
9133         spin_lock(&BTRFS_I(inode)->lock);
9134         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9135         inode_bytes = inode_get_bytes(inode);
9136         spin_unlock(&BTRFS_I(inode)->lock);
9137         stat->blocks = (ALIGN(inode_bytes, blocksize) +
9138                         ALIGN(delalloc_bytes, blocksize)) >> 9;
9139         return 0;
9140 }
9141
9142 static int btrfs_rename_exchange(struct inode *old_dir,
9143                               struct dentry *old_dentry,
9144                               struct inode *new_dir,
9145                               struct dentry *new_dentry)
9146 {
9147         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9148         struct btrfs_trans_handle *trans;
9149         unsigned int trans_num_items;
9150         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9151         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9152         struct inode *new_inode = new_dentry->d_inode;
9153         struct inode *old_inode = old_dentry->d_inode;
9154         struct timespec64 ctime = current_time(old_inode);
9155         struct btrfs_rename_ctx old_rename_ctx;
9156         struct btrfs_rename_ctx new_rename_ctx;
9157         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9158         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9159         u64 old_idx = 0;
9160         u64 new_idx = 0;
9161         int ret;
9162         int ret2;
9163         bool need_abort = false;
9164         struct fscrypt_name old_fname, new_fname;
9165         struct fscrypt_str *old_name, *new_name;
9166
9167         /*
9168          * For non-subvolumes allow exchange only within one subvolume, in the
9169          * same inode namespace. Two subvolumes (represented as directory) can
9170          * be exchanged as they're a logical link and have a fixed inode number.
9171          */
9172         if (root != dest &&
9173             (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
9174              new_ino != BTRFS_FIRST_FREE_OBJECTID))
9175                 return -EXDEV;
9176
9177         ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
9178         if (ret)
9179                 return ret;
9180
9181         ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
9182         if (ret) {
9183                 fscrypt_free_filename(&old_fname);
9184                 return ret;
9185         }
9186
9187         old_name = &old_fname.disk_name;
9188         new_name = &new_fname.disk_name;
9189
9190         /* close the race window with snapshot create/destroy ioctl */
9191         if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9192             new_ino == BTRFS_FIRST_FREE_OBJECTID)
9193                 down_read(&fs_info->subvol_sem);
9194
9195         /*
9196          * For each inode:
9197          * 1 to remove old dir item
9198          * 1 to remove old dir index
9199          * 1 to add new dir item
9200          * 1 to add new dir index
9201          * 1 to update parent inode
9202          *
9203          * If the parents are the same, we only need to account for one
9204          */
9205         trans_num_items = (old_dir == new_dir ? 9 : 10);
9206         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9207                 /*
9208                  * 1 to remove old root ref
9209                  * 1 to remove old root backref
9210                  * 1 to add new root ref
9211                  * 1 to add new root backref
9212                  */
9213                 trans_num_items += 4;
9214         } else {
9215                 /*
9216                  * 1 to update inode item
9217                  * 1 to remove old inode ref
9218                  * 1 to add new inode ref
9219                  */
9220                 trans_num_items += 3;
9221         }
9222         if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9223                 trans_num_items += 4;
9224         else
9225                 trans_num_items += 3;
9226         trans = btrfs_start_transaction(root, trans_num_items);
9227         if (IS_ERR(trans)) {
9228                 ret = PTR_ERR(trans);
9229                 goto out_notrans;
9230         }
9231
9232         if (dest != root) {
9233                 ret = btrfs_record_root_in_trans(trans, dest);
9234                 if (ret)
9235                         goto out_fail;
9236         }
9237
9238         /*
9239          * We need to find a free sequence number both in the source and
9240          * in the destination directory for the exchange.
9241          */
9242         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9243         if (ret)
9244                 goto out_fail;
9245         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9246         if (ret)
9247                 goto out_fail;
9248
9249         BTRFS_I(old_inode)->dir_index = 0ULL;
9250         BTRFS_I(new_inode)->dir_index = 0ULL;
9251
9252         /* Reference for the source. */
9253         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9254                 /* force full log commit if subvolume involved. */
9255                 btrfs_set_log_full_commit(trans);
9256         } else {
9257                 ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
9258                                              btrfs_ino(BTRFS_I(new_dir)),
9259                                              old_idx);
9260                 if (ret)
9261                         goto out_fail;
9262                 need_abort = true;
9263         }
9264
9265         /* And now for the dest. */
9266         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9267                 /* force full log commit if subvolume involved. */
9268                 btrfs_set_log_full_commit(trans);
9269         } else {
9270                 ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
9271                                              btrfs_ino(BTRFS_I(old_dir)),
9272                                              new_idx);
9273                 if (ret) {
9274                         if (need_abort)
9275                                 btrfs_abort_transaction(trans, ret);
9276                         goto out_fail;
9277                 }
9278         }
9279
9280         /* Update inode version and ctime/mtime. */
9281         inode_inc_iversion(old_dir);
9282         inode_inc_iversion(new_dir);
9283         inode_inc_iversion(old_inode);
9284         inode_inc_iversion(new_inode);
9285         old_dir->i_mtime = ctime;
9286         old_dir->i_ctime = ctime;
9287         new_dir->i_mtime = ctime;
9288         new_dir->i_ctime = ctime;
9289         old_inode->i_ctime = ctime;
9290         new_inode->i_ctime = ctime;
9291
9292         if (old_dentry->d_parent != new_dentry->d_parent) {
9293                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9294                                 BTRFS_I(old_inode), 1);
9295                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9296                                 BTRFS_I(new_inode), 1);
9297         }
9298
9299         /* src is a subvolume */
9300         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9301                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9302         } else { /* src is an inode */
9303                 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9304                                            BTRFS_I(old_dentry->d_inode),
9305                                            old_name, &old_rename_ctx);
9306                 if (!ret)
9307                         ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9308         }
9309         if (ret) {
9310                 btrfs_abort_transaction(trans, ret);
9311                 goto out_fail;
9312         }
9313
9314         /* dest is a subvolume */
9315         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9316                 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9317         } else { /* dest is an inode */
9318                 ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9319                                            BTRFS_I(new_dentry->d_inode),
9320                                            new_name, &new_rename_ctx);
9321                 if (!ret)
9322                         ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9323         }
9324         if (ret) {
9325                 btrfs_abort_transaction(trans, ret);
9326                 goto out_fail;
9327         }
9328
9329         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9330                              new_name, 0, old_idx);
9331         if (ret) {
9332                 btrfs_abort_transaction(trans, ret);
9333                 goto out_fail;
9334         }
9335
9336         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9337                              old_name, 0, new_idx);
9338         if (ret) {
9339                 btrfs_abort_transaction(trans, ret);
9340                 goto out_fail;
9341         }
9342
9343         if (old_inode->i_nlink == 1)
9344                 BTRFS_I(old_inode)->dir_index = old_idx;
9345         if (new_inode->i_nlink == 1)
9346                 BTRFS_I(new_inode)->dir_index = new_idx;
9347
9348         /*
9349          * Now pin the logs of the roots. We do it to ensure that no other task
9350          * can sync the logs while we are in progress with the rename, because
9351          * that could result in an inconsistency in case any of the inodes that
9352          * are part of this rename operation were logged before.
9353          */
9354         if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9355                 btrfs_pin_log_trans(root);
9356         if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9357                 btrfs_pin_log_trans(dest);
9358
9359         /* Do the log updates for all inodes. */
9360         if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9361                 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9362                                    old_rename_ctx.index, new_dentry->d_parent);
9363         if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9364                 btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
9365                                    new_rename_ctx.index, old_dentry->d_parent);
9366
9367         /* Now unpin the logs. */
9368         if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9369                 btrfs_end_log_trans(root);
9370         if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
9371                 btrfs_end_log_trans(dest);
9372 out_fail:
9373         ret2 = btrfs_end_transaction(trans);
9374         ret = ret ? ret : ret2;
9375 out_notrans:
9376         if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9377             old_ino == BTRFS_FIRST_FREE_OBJECTID)
9378                 up_read(&fs_info->subvol_sem);
9379
9380         fscrypt_free_filename(&new_fname);
9381         fscrypt_free_filename(&old_fname);
9382         return ret;
9383 }
9384
9385 static struct inode *new_whiteout_inode(struct user_namespace *mnt_userns,
9386                                         struct inode *dir)
9387 {
9388         struct inode *inode;
9389
9390         inode = new_inode(dir->i_sb);
9391         if (inode) {
9392                 inode_init_owner(mnt_userns, inode, dir,
9393                                  S_IFCHR | WHITEOUT_MODE);
9394                 inode->i_op = &btrfs_special_inode_operations;
9395                 init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
9396         }
9397         return inode;
9398 }
9399
9400 static int btrfs_rename(struct user_namespace *mnt_userns,
9401                         struct inode *old_dir, struct dentry *old_dentry,
9402                         struct inode *new_dir, struct dentry *new_dentry,
9403                         unsigned int flags)
9404 {
9405         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9406         struct btrfs_new_inode_args whiteout_args = {
9407                 .dir = old_dir,
9408                 .dentry = old_dentry,
9409         };
9410         struct btrfs_trans_handle *trans;
9411         unsigned int trans_num_items;
9412         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9413         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9414         struct inode *new_inode = d_inode(new_dentry);
9415         struct inode *old_inode = d_inode(old_dentry);
9416         struct btrfs_rename_ctx rename_ctx;
9417         u64 index = 0;
9418         int ret;
9419         int ret2;
9420         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9421         struct fscrypt_name old_fname, new_fname;
9422
9423         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9424                 return -EPERM;
9425
9426         /* we only allow rename subvolume link between subvolumes */
9427         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9428                 return -EXDEV;
9429
9430         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9431             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9432                 return -ENOTEMPTY;
9433
9434         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9435             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9436                 return -ENOTEMPTY;
9437
9438         ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
9439         if (ret)
9440                 return ret;
9441
9442         ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
9443         if (ret) {
9444                 fscrypt_free_filename(&old_fname);
9445                 return ret;
9446         }
9447
9448         /* check for collisions, even if the  name isn't there */
9449         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
9450         if (ret) {
9451                 if (ret == -EEXIST) {
9452                         /* we shouldn't get
9453                          * eexist without a new_inode */
9454                         if (WARN_ON(!new_inode)) {
9455                                 goto out_fscrypt_names;
9456                         }
9457                 } else {
9458                         /* maybe -EOVERFLOW */
9459                         goto out_fscrypt_names;
9460                 }
9461         }
9462         ret = 0;
9463
9464         /*
9465          * we're using rename to replace one file with another.  Start IO on it
9466          * now so  we don't add too much work to the end of the transaction
9467          */
9468         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9469                 filemap_flush(old_inode->i_mapping);
9470
9471         if (flags & RENAME_WHITEOUT) {
9472                 whiteout_args.inode = new_whiteout_inode(mnt_userns, old_dir);
9473                 if (!whiteout_args.inode) {
9474                         ret = -ENOMEM;
9475                         goto out_fscrypt_names;
9476                 }
9477                 ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
9478                 if (ret)
9479                         goto out_whiteout_inode;
9480         } else {
9481                 /* 1 to update the old parent inode. */
9482                 trans_num_items = 1;
9483         }
9484
9485         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9486                 /* Close the race window with snapshot create/destroy ioctl */
9487                 down_read(&fs_info->subvol_sem);
9488                 /*
9489                  * 1 to remove old root ref
9490                  * 1 to remove old root backref
9491                  * 1 to add new root ref
9492                  * 1 to add new root backref
9493                  */
9494                 trans_num_items += 4;
9495         } else {
9496                 /*
9497                  * 1 to update inode
9498                  * 1 to remove old inode ref
9499                  * 1 to add new inode ref
9500                  */
9501                 trans_num_items += 3;
9502         }
9503         /*
9504          * 1 to remove old dir item
9505          * 1 to remove old dir index
9506          * 1 to add new dir item
9507          * 1 to add new dir index
9508          */
9509         trans_num_items += 4;
9510         /* 1 to update new parent inode if it's not the same as the old parent */
9511         if (new_dir != old_dir)
9512                 trans_num_items++;
9513         if (new_inode) {
9514                 /*
9515                  * 1 to update inode
9516                  * 1 to remove inode ref
9517                  * 1 to remove dir item
9518                  * 1 to remove dir index
9519                  * 1 to possibly add orphan item
9520                  */
9521                 trans_num_items += 5;
9522         }
9523         trans = btrfs_start_transaction(root, trans_num_items);
9524         if (IS_ERR(trans)) {
9525                 ret = PTR_ERR(trans);
9526                 goto out_notrans;
9527         }
9528
9529         if (dest != root) {
9530                 ret = btrfs_record_root_in_trans(trans, dest);
9531                 if (ret)
9532                         goto out_fail;
9533         }
9534
9535         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9536         if (ret)
9537                 goto out_fail;
9538
9539         BTRFS_I(old_inode)->dir_index = 0ULL;
9540         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9541                 /* force full log commit if subvolume involved. */
9542                 btrfs_set_log_full_commit(trans);
9543         } else {
9544                 ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
9545                                              old_ino, btrfs_ino(BTRFS_I(new_dir)),
9546                                              index);
9547                 if (ret)
9548                         goto out_fail;
9549         }
9550
9551         inode_inc_iversion(old_dir);
9552         inode_inc_iversion(new_dir);
9553         inode_inc_iversion(old_inode);
9554         old_dir->i_mtime = current_time(old_dir);
9555         old_dir->i_ctime = old_dir->i_mtime;
9556         new_dir->i_mtime = old_dir->i_mtime;
9557         new_dir->i_ctime = old_dir->i_mtime;
9558         old_inode->i_ctime = old_dir->i_mtime;
9559
9560         if (old_dentry->d_parent != new_dentry->d_parent)
9561                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9562                                 BTRFS_I(old_inode), 1);
9563
9564         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9565                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9566         } else {
9567                 ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
9568                                            BTRFS_I(d_inode(old_dentry)),
9569                                            &old_fname.disk_name, &rename_ctx);
9570                 if (!ret)
9571                         ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9572         }
9573         if (ret) {
9574                 btrfs_abort_transaction(trans, ret);
9575                 goto out_fail;
9576         }
9577
9578         if (new_inode) {
9579                 inode_inc_iversion(new_inode);
9580                 new_inode->i_ctime = current_time(new_inode);
9581                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9582                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9583                         ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9584                         BUG_ON(new_inode->i_nlink == 0);
9585                 } else {
9586                         ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
9587                                                  BTRFS_I(d_inode(new_dentry)),
9588                                                  &new_fname.disk_name);
9589                 }
9590                 if (!ret && new_inode->i_nlink == 0)
9591                         ret = btrfs_orphan_add(trans,
9592                                         BTRFS_I(d_inode(new_dentry)));
9593                 if (ret) {
9594                         btrfs_abort_transaction(trans, ret);
9595                         goto out_fail;
9596                 }
9597         }
9598
9599         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9600                              &new_fname.disk_name, 0, index);
9601         if (ret) {
9602                 btrfs_abort_transaction(trans, ret);
9603                 goto out_fail;
9604         }
9605
9606         if (old_inode->i_nlink == 1)
9607                 BTRFS_I(old_inode)->dir_index = index;
9608
9609         if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
9610                 btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
9611                                    rename_ctx.index, new_dentry->d_parent);
9612
9613         if (flags & RENAME_WHITEOUT) {
9614                 ret = btrfs_create_new_inode(trans, &whiteout_args);
9615                 if (ret) {
9616                         btrfs_abort_transaction(trans, ret);
9617                         goto out_fail;
9618                 } else {
9619                         unlock_new_inode(whiteout_args.inode);
9620                         iput(whiteout_args.inode);
9621                         whiteout_args.inode = NULL;
9622                 }
9623         }
9624 out_fail:
9625         ret2 = btrfs_end_transaction(trans);
9626         ret = ret ? ret : ret2;
9627 out_notrans:
9628         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9629                 up_read(&fs_info->subvol_sem);
9630         if (flags & RENAME_WHITEOUT)
9631                 btrfs_new_inode_args_destroy(&whiteout_args);
9632 out_whiteout_inode:
9633         if (flags & RENAME_WHITEOUT)
9634                 iput(whiteout_args.inode);
9635 out_fscrypt_names:
9636         fscrypt_free_filename(&old_fname);
9637         fscrypt_free_filename(&new_fname);
9638         return ret;
9639 }
9640
9641 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9642                          struct dentry *old_dentry, struct inode *new_dir,
9643                          struct dentry *new_dentry, unsigned int flags)
9644 {
9645         int ret;
9646
9647         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9648                 return -EINVAL;
9649
9650         if (flags & RENAME_EXCHANGE)
9651                 ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9652                                             new_dentry);
9653         else
9654                 ret = btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
9655                                    new_dentry, flags);
9656
9657         btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
9658
9659         return ret;
9660 }
9661
9662 struct btrfs_delalloc_work {
9663         struct inode *inode;
9664         struct completion completion;
9665         struct list_head list;
9666         struct btrfs_work work;
9667 };
9668
9669 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9670 {
9671         struct btrfs_delalloc_work *delalloc_work;
9672         struct inode *inode;
9673
9674         delalloc_work = container_of(work, struct btrfs_delalloc_work,
9675                                      work);
9676         inode = delalloc_work->inode;
9677         filemap_flush(inode->i_mapping);
9678         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9679                                 &BTRFS_I(inode)->runtime_flags))
9680                 filemap_flush(inode->i_mapping);
9681
9682         iput(inode);
9683         complete(&delalloc_work->completion);
9684 }
9685
9686 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9687 {
9688         struct btrfs_delalloc_work *work;
9689
9690         work = kmalloc(sizeof(*work), GFP_NOFS);
9691         if (!work)
9692                 return NULL;
9693
9694         init_completion(&work->completion);
9695         INIT_LIST_HEAD(&work->list);
9696         work->inode = inode;
9697         btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9698
9699         return work;
9700 }
9701
9702 /*
9703  * some fairly slow code that needs optimization. This walks the list
9704  * of all the inodes with pending delalloc and forces them to disk.
9705  */
9706 static int start_delalloc_inodes(struct btrfs_root *root,
9707                                  struct writeback_control *wbc, bool snapshot,
9708                                  bool in_reclaim_context)
9709 {
9710         struct btrfs_inode *binode;
9711         struct inode *inode;
9712         struct btrfs_delalloc_work *work, *next;
9713         struct list_head works;
9714         struct list_head splice;
9715         int ret = 0;
9716         bool full_flush = wbc->nr_to_write == LONG_MAX;
9717
9718         INIT_LIST_HEAD(&works);
9719         INIT_LIST_HEAD(&splice);
9720
9721         mutex_lock(&root->delalloc_mutex);
9722         spin_lock(&root->delalloc_lock);
9723         list_splice_init(&root->delalloc_inodes, &splice);
9724         while (!list_empty(&splice)) {
9725                 binode = list_entry(splice.next, struct btrfs_inode,
9726                                     delalloc_inodes);
9727
9728                 list_move_tail(&binode->delalloc_inodes,
9729                                &root->delalloc_inodes);
9730
9731                 if (in_reclaim_context &&
9732                     test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9733                         continue;
9734
9735                 inode = igrab(&binode->vfs_inode);
9736                 if (!inode) {
9737                         cond_resched_lock(&root->delalloc_lock);
9738                         continue;
9739                 }
9740                 spin_unlock(&root->delalloc_lock);
9741
9742                 if (snapshot)
9743                         set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9744                                 &binode->runtime_flags);
9745                 if (full_flush) {
9746                         work = btrfs_alloc_delalloc_work(inode);
9747                         if (!work) {
9748                                 iput(inode);
9749                                 ret = -ENOMEM;
9750                                 goto out;
9751                         }
9752                         list_add_tail(&work->list, &works);
9753                         btrfs_queue_work(root->fs_info->flush_workers,
9754                                          &work->work);
9755                 } else {
9756                         ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
9757                         btrfs_add_delayed_iput(inode);
9758                         if (ret || wbc->nr_to_write <= 0)
9759                                 goto out;
9760                 }
9761                 cond_resched();
9762                 spin_lock(&root->delalloc_lock);
9763         }
9764         spin_unlock(&root->delalloc_lock);
9765
9766 out:
9767         list_for_each_entry_safe(work, next, &works, list) {
9768                 list_del_init(&work->list);
9769                 wait_for_completion(&work->completion);
9770                 kfree(work);
9771         }
9772
9773         if (!list_empty(&splice)) {
9774                 spin_lock(&root->delalloc_lock);
9775                 list_splice_tail(&splice, &root->delalloc_inodes);
9776                 spin_unlock(&root->delalloc_lock);
9777         }
9778         mutex_unlock(&root->delalloc_mutex);
9779         return ret;
9780 }
9781
9782 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
9783 {
9784         struct writeback_control wbc = {
9785                 .nr_to_write = LONG_MAX,
9786                 .sync_mode = WB_SYNC_NONE,
9787                 .range_start = 0,
9788                 .range_end = LLONG_MAX,
9789         };
9790         struct btrfs_fs_info *fs_info = root->fs_info;
9791
9792         if (BTRFS_FS_ERROR(fs_info))
9793                 return -EROFS;
9794
9795         return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
9796 }
9797
9798 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9799                                bool in_reclaim_context)
9800 {
9801         struct writeback_control wbc = {
9802                 .nr_to_write = nr,
9803                 .sync_mode = WB_SYNC_NONE,
9804                 .range_start = 0,
9805                 .range_end = LLONG_MAX,
9806         };
9807         struct btrfs_root *root;
9808         struct list_head splice;
9809         int ret;
9810
9811         if (BTRFS_FS_ERROR(fs_info))
9812                 return -EROFS;
9813
9814         INIT_LIST_HEAD(&splice);
9815
9816         mutex_lock(&fs_info->delalloc_root_mutex);
9817         spin_lock(&fs_info->delalloc_root_lock);
9818         list_splice_init(&fs_info->delalloc_roots, &splice);
9819         while (!list_empty(&splice)) {
9820                 /*
9821                  * Reset nr_to_write here so we know that we're doing a full
9822                  * flush.
9823                  */
9824                 if (nr == LONG_MAX)
9825                         wbc.nr_to_write = LONG_MAX;
9826
9827                 root = list_first_entry(&splice, struct btrfs_root,
9828                                         delalloc_root);
9829                 root = btrfs_grab_root(root);
9830                 BUG_ON(!root);
9831                 list_move_tail(&root->delalloc_root,
9832                                &fs_info->delalloc_roots);
9833                 spin_unlock(&fs_info->delalloc_root_lock);
9834
9835                 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9836                 btrfs_put_root(root);
9837                 if (ret < 0 || wbc.nr_to_write <= 0)
9838                         goto out;
9839                 spin_lock(&fs_info->delalloc_root_lock);
9840         }
9841         spin_unlock(&fs_info->delalloc_root_lock);
9842
9843         ret = 0;
9844 out:
9845         if (!list_empty(&splice)) {
9846                 spin_lock(&fs_info->delalloc_root_lock);
9847                 list_splice_tail(&splice, &fs_info->delalloc_roots);
9848                 spin_unlock(&fs_info->delalloc_root_lock);
9849         }
9850         mutex_unlock(&fs_info->delalloc_root_mutex);
9851         return ret;
9852 }
9853
9854 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9855                          struct dentry *dentry, const char *symname)
9856 {
9857         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9858         struct btrfs_trans_handle *trans;
9859         struct btrfs_root *root = BTRFS_I(dir)->root;
9860         struct btrfs_path *path;
9861         struct btrfs_key key;
9862         struct inode *inode;
9863         struct btrfs_new_inode_args new_inode_args = {
9864                 .dir = dir,
9865                 .dentry = dentry,
9866         };
9867         unsigned int trans_num_items;
9868         int err;
9869         int name_len;
9870         int datasize;
9871         unsigned long ptr;
9872         struct btrfs_file_extent_item *ei;
9873         struct extent_buffer *leaf;
9874
9875         name_len = strlen(symname);
9876         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9877                 return -ENAMETOOLONG;
9878
9879         inode = new_inode(dir->i_sb);
9880         if (!inode)
9881                 return -ENOMEM;
9882         inode_init_owner(mnt_userns, inode, dir, S_IFLNK | S_IRWXUGO);
9883         inode->i_op = &btrfs_symlink_inode_operations;
9884         inode_nohighmem(inode);
9885         inode->i_mapping->a_ops = &btrfs_aops;
9886         btrfs_i_size_write(BTRFS_I(inode), name_len);
9887         inode_set_bytes(inode, name_len);
9888
9889         new_inode_args.inode = inode;
9890         err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9891         if (err)
9892                 goto out_inode;
9893         /* 1 additional item for the inline extent */
9894         trans_num_items++;
9895
9896         trans = btrfs_start_transaction(root, trans_num_items);
9897         if (IS_ERR(trans)) {
9898                 err = PTR_ERR(trans);
9899                 goto out_new_inode_args;
9900         }
9901
9902         err = btrfs_create_new_inode(trans, &new_inode_args);
9903         if (err)
9904                 goto out;
9905
9906         path = btrfs_alloc_path();
9907         if (!path) {
9908                 err = -ENOMEM;
9909                 btrfs_abort_transaction(trans, err);
9910                 discard_new_inode(inode);
9911                 inode = NULL;
9912                 goto out;
9913         }
9914         key.objectid = btrfs_ino(BTRFS_I(inode));
9915         key.offset = 0;
9916         key.type = BTRFS_EXTENT_DATA_KEY;
9917         datasize = btrfs_file_extent_calc_inline_size(name_len);
9918         err = btrfs_insert_empty_item(trans, root, path, &key,
9919                                       datasize);
9920         if (err) {
9921                 btrfs_abort_transaction(trans, err);
9922                 btrfs_free_path(path);
9923                 discard_new_inode(inode);
9924                 inode = NULL;
9925                 goto out;
9926         }
9927         leaf = path->nodes[0];
9928         ei = btrfs_item_ptr(leaf, path->slots[0],
9929                             struct btrfs_file_extent_item);
9930         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9931         btrfs_set_file_extent_type(leaf, ei,
9932                                    BTRFS_FILE_EXTENT_INLINE);
9933         btrfs_set_file_extent_encryption(leaf, ei, 0);
9934         btrfs_set_file_extent_compression(leaf, ei, 0);
9935         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9936         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9937
9938         ptr = btrfs_file_extent_inline_start(ei);
9939         write_extent_buffer(leaf, symname, ptr, name_len);
9940         btrfs_mark_buffer_dirty(leaf);
9941         btrfs_free_path(path);
9942
9943         d_instantiate_new(dentry, inode);
9944         err = 0;
9945 out:
9946         btrfs_end_transaction(trans);
9947         btrfs_btree_balance_dirty(fs_info);
9948 out_new_inode_args:
9949         btrfs_new_inode_args_destroy(&new_inode_args);
9950 out_inode:
9951         if (err)
9952                 iput(inode);
9953         return err;
9954 }
9955
9956 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9957                                        struct btrfs_trans_handle *trans_in,
9958                                        struct btrfs_inode *inode,
9959                                        struct btrfs_key *ins,
9960                                        u64 file_offset)
9961 {
9962         struct btrfs_file_extent_item stack_fi;
9963         struct btrfs_replace_extent_info extent_info;
9964         struct btrfs_trans_handle *trans = trans_in;
9965         struct btrfs_path *path;
9966         u64 start = ins->objectid;
9967         u64 len = ins->offset;
9968         u64 qgroup_released = 0;
9969         int ret;
9970
9971         memset(&stack_fi, 0, sizeof(stack_fi));
9972
9973         btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9974         btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9975         btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9976         btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9977         btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9978         btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9979         /* Encryption and other encoding is reserved and all 0 */
9980
9981         ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
9982         if (ret < 0)
9983                 return ERR_PTR(ret);
9984
9985         if (trans) {
9986                 ret = insert_reserved_file_extent(trans, inode,
9987                                                   file_offset, &stack_fi,
9988                                                   true, qgroup_released);
9989                 if (ret)
9990                         goto free_qgroup;
9991                 return trans;
9992         }
9993
9994         extent_info.disk_offset = start;
9995         extent_info.disk_len = len;
9996         extent_info.data_offset = 0;
9997         extent_info.data_len = len;
9998         extent_info.file_offset = file_offset;
9999         extent_info.extent_buf = (char *)&stack_fi;
10000         extent_info.is_new_extent = true;
10001         extent_info.update_times = true;
10002         extent_info.qgroup_reserved = qgroup_released;
10003         extent_info.insertions = 0;
10004
10005         path = btrfs_alloc_path();
10006         if (!path) {
10007                 ret = -ENOMEM;
10008                 goto free_qgroup;
10009         }
10010
10011         ret = btrfs_replace_file_extents(inode, path, file_offset,
10012                                      file_offset + len - 1, &extent_info,
10013                                      &trans);
10014         btrfs_free_path(path);
10015         if (ret)
10016                 goto free_qgroup;
10017         return trans;
10018
10019 free_qgroup:
10020         /*
10021          * We have released qgroup data range at the beginning of the function,
10022          * and normally qgroup_released bytes will be freed when committing
10023          * transaction.
10024          * But if we error out early, we have to free what we have released
10025          * or we leak qgroup data reservation.
10026          */
10027         btrfs_qgroup_free_refroot(inode->root->fs_info,
10028                         inode->root->root_key.objectid, qgroup_released,
10029                         BTRFS_QGROUP_RSV_DATA);
10030         return ERR_PTR(ret);
10031 }
10032
10033 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10034                                        u64 start, u64 num_bytes, u64 min_size,
10035                                        loff_t actual_len, u64 *alloc_hint,
10036                                        struct btrfs_trans_handle *trans)
10037 {
10038         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10039         struct extent_map *em;
10040         struct btrfs_root *root = BTRFS_I(inode)->root;
10041         struct btrfs_key ins;
10042         u64 cur_offset = start;
10043         u64 clear_offset = start;
10044         u64 i_size;
10045         u64 cur_bytes;
10046         u64 last_alloc = (u64)-1;
10047         int ret = 0;
10048         bool own_trans = true;
10049         u64 end = start + num_bytes - 1;
10050
10051         if (trans)
10052                 own_trans = false;
10053         while (num_bytes > 0) {
10054                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10055                 cur_bytes = max(cur_bytes, min_size);
10056                 /*
10057                  * If we are severely fragmented we could end up with really
10058                  * small allocations, so if the allocator is returning small
10059                  * chunks lets make its job easier by only searching for those
10060                  * sized chunks.
10061                  */
10062                 cur_bytes = min(cur_bytes, last_alloc);
10063                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10064                                 min_size, 0, *alloc_hint, &ins, 1, 0);
10065                 if (ret)
10066                         break;
10067
10068                 /*
10069                  * We've reserved this space, and thus converted it from
10070                  * ->bytes_may_use to ->bytes_reserved.  Any error that happens
10071                  * from here on out we will only need to clear our reservation
10072                  * for the remaining unreserved area, so advance our
10073                  * clear_offset by our extent size.
10074                  */
10075                 clear_offset += ins.offset;
10076
10077                 last_alloc = ins.offset;
10078                 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
10079                                                     &ins, cur_offset);
10080                 /*
10081                  * Now that we inserted the prealloc extent we can finally
10082                  * decrement the number of reservations in the block group.
10083                  * If we did it before, we could race with relocation and have
10084                  * relocation miss the reserved extent, making it fail later.
10085                  */
10086                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10087                 if (IS_ERR(trans)) {
10088                         ret = PTR_ERR(trans);
10089                         btrfs_free_reserved_extent(fs_info, ins.objectid,
10090                                                    ins.offset, 0);
10091                         break;
10092                 }
10093
10094                 em = alloc_extent_map();
10095                 if (!em) {
10096                         btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
10097                                             cur_offset + ins.offset - 1, false);
10098                         btrfs_set_inode_full_sync(BTRFS_I(inode));
10099                         goto next;
10100                 }
10101
10102                 em->start = cur_offset;
10103                 em->orig_start = cur_offset;
10104                 em->len = ins.offset;
10105                 em->block_start = ins.objectid;
10106                 em->block_len = ins.offset;
10107                 em->orig_block_len = ins.offset;
10108                 em->ram_bytes = ins.offset;
10109                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10110                 em->generation = trans->transid;
10111
10112                 ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
10113                 free_extent_map(em);
10114 next:
10115                 num_bytes -= ins.offset;
10116                 cur_offset += ins.offset;
10117                 *alloc_hint = ins.objectid + ins.offset;
10118
10119                 inode_inc_iversion(inode);
10120                 inode->i_ctime = current_time(inode);
10121                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10122                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10123                     (actual_len > inode->i_size) &&
10124                     (cur_offset > inode->i_size)) {
10125                         if (cur_offset > actual_len)
10126                                 i_size = actual_len;
10127                         else
10128                                 i_size = cur_offset;
10129                         i_size_write(inode, i_size);
10130                         btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10131                 }
10132
10133                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10134
10135                 if (ret) {
10136                         btrfs_abort_transaction(trans, ret);
10137                         if (own_trans)
10138                                 btrfs_end_transaction(trans);
10139                         break;
10140                 }
10141
10142                 if (own_trans) {
10143                         btrfs_end_transaction(trans);
10144                         trans = NULL;
10145                 }
10146         }
10147         if (clear_offset < end)
10148                 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10149                         end - clear_offset + 1);
10150         return ret;
10151 }
10152
10153 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10154                               u64 start, u64 num_bytes, u64 min_size,
10155                               loff_t actual_len, u64 *alloc_hint)
10156 {
10157         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10158                                            min_size, actual_len, alloc_hint,
10159                                            NULL);
10160 }
10161
10162 int btrfs_prealloc_file_range_trans(struct inode *inode,
10163                                     struct btrfs_trans_handle *trans, int mode,
10164                                     u64 start, u64 num_bytes, u64 min_size,
10165                                     loff_t actual_len, u64 *alloc_hint)
10166 {
10167         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10168                                            min_size, actual_len, alloc_hint, trans);
10169 }
10170
10171 static int btrfs_permission(struct user_namespace *mnt_userns,
10172                             struct inode *inode, int mask)
10173 {
10174         struct btrfs_root *root = BTRFS_I(inode)->root;
10175         umode_t mode = inode->i_mode;
10176
10177         if (mask & MAY_WRITE &&
10178             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10179                 if (btrfs_root_readonly(root))
10180                         return -EROFS;
10181                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10182                         return -EACCES;
10183         }
10184         return generic_permission(mnt_userns, inode, mask);
10185 }
10186
10187 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10188                          struct file *file, umode_t mode)
10189 {
10190         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10191         struct btrfs_trans_handle *trans;
10192         struct btrfs_root *root = BTRFS_I(dir)->root;
10193         struct inode *inode;
10194         struct btrfs_new_inode_args new_inode_args = {
10195                 .dir = dir,
10196                 .dentry = file->f_path.dentry,
10197                 .orphan = true,
10198         };
10199         unsigned int trans_num_items;
10200         int ret;
10201
10202         inode = new_inode(dir->i_sb);
10203         if (!inode)
10204                 return -ENOMEM;
10205         inode_init_owner(mnt_userns, inode, dir, mode);
10206         inode->i_fop = &btrfs_file_operations;
10207         inode->i_op = &btrfs_file_inode_operations;
10208         inode->i_mapping->a_ops = &btrfs_aops;
10209
10210         new_inode_args.inode = inode;
10211         ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
10212         if (ret)
10213                 goto out_inode;
10214
10215         trans = btrfs_start_transaction(root, trans_num_items);
10216         if (IS_ERR(trans)) {
10217                 ret = PTR_ERR(trans);
10218                 goto out_new_inode_args;
10219         }
10220
10221         ret = btrfs_create_new_inode(trans, &new_inode_args);
10222
10223         /*
10224          * We set number of links to 0 in btrfs_create_new_inode(), and here we
10225          * set it to 1 because d_tmpfile() will issue a warning if the count is
10226          * 0, through:
10227          *
10228          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10229          */
10230         set_nlink(inode, 1);
10231
10232         if (!ret) {
10233                 d_tmpfile(file, inode);
10234                 unlock_new_inode(inode);
10235                 mark_inode_dirty(inode);
10236         }
10237
10238         btrfs_end_transaction(trans);
10239         btrfs_btree_balance_dirty(fs_info);
10240 out_new_inode_args:
10241         btrfs_new_inode_args_destroy(&new_inode_args);
10242 out_inode:
10243         if (ret)
10244                 iput(inode);
10245         return finish_open_simple(file, ret);
10246 }
10247
10248 void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
10249 {
10250         struct btrfs_fs_info *fs_info = inode->root->fs_info;
10251         unsigned long index = start >> PAGE_SHIFT;
10252         unsigned long end_index = end >> PAGE_SHIFT;
10253         struct page *page;
10254         u32 len;
10255
10256         ASSERT(end + 1 - start <= U32_MAX);
10257         len = end + 1 - start;
10258         while (index <= end_index) {
10259                 page = find_get_page(inode->vfs_inode.i_mapping, index);
10260                 ASSERT(page); /* Pages should be in the extent_io_tree */
10261
10262                 btrfs_page_set_writeback(fs_info, page, start, len);
10263                 put_page(page);
10264                 index++;
10265         }
10266 }
10267
10268 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
10269                                              int compress_type)
10270 {
10271         switch (compress_type) {
10272         case BTRFS_COMPRESS_NONE:
10273                 return BTRFS_ENCODED_IO_COMPRESSION_NONE;
10274         case BTRFS_COMPRESS_ZLIB:
10275                 return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
10276         case BTRFS_COMPRESS_LZO:
10277                 /*
10278                  * The LZO format depends on the sector size. 64K is the maximum
10279                  * sector size that we support.
10280                  */
10281                 if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
10282                         return -EINVAL;
10283                 return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
10284                        (fs_info->sectorsize_bits - 12);
10285         case BTRFS_COMPRESS_ZSTD:
10286                 return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
10287         default:
10288                 return -EUCLEAN;
10289         }
10290 }
10291
10292 static ssize_t btrfs_encoded_read_inline(
10293                                 struct kiocb *iocb,
10294                                 struct iov_iter *iter, u64 start,
10295                                 u64 lockend,
10296                                 struct extent_state **cached_state,
10297                                 u64 extent_start, size_t count,
10298                                 struct btrfs_ioctl_encoded_io_args *encoded,
10299                                 bool *unlocked)
10300 {
10301         struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10302         struct btrfs_root *root = inode->root;
10303         struct btrfs_fs_info *fs_info = root->fs_info;
10304         struct extent_io_tree *io_tree = &inode->io_tree;
10305         struct btrfs_path *path;
10306         struct extent_buffer *leaf;
10307         struct btrfs_file_extent_item *item;
10308         u64 ram_bytes;
10309         unsigned long ptr;
10310         void *tmp;
10311         ssize_t ret;
10312
10313         path = btrfs_alloc_path();
10314         if (!path) {
10315                 ret = -ENOMEM;
10316                 goto out;
10317         }
10318         ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
10319                                        extent_start, 0);
10320         if (ret) {
10321                 if (ret > 0) {
10322                         /* The extent item disappeared? */
10323                         ret = -EIO;
10324                 }
10325                 goto out;
10326         }
10327         leaf = path->nodes[0];
10328         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10329
10330         ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
10331         ptr = btrfs_file_extent_inline_start(item);
10332
10333         encoded->len = min_t(u64, extent_start + ram_bytes,
10334                              inode->vfs_inode.i_size) - iocb->ki_pos;
10335         ret = btrfs_encoded_io_compression_from_extent(fs_info,
10336                                  btrfs_file_extent_compression(leaf, item));
10337         if (ret < 0)
10338                 goto out;
10339         encoded->compression = ret;
10340         if (encoded->compression) {
10341                 size_t inline_size;
10342
10343                 inline_size = btrfs_file_extent_inline_item_len(leaf,
10344                                                                 path->slots[0]);
10345                 if (inline_size > count) {
10346                         ret = -ENOBUFS;
10347                         goto out;
10348                 }
10349                 count = inline_size;
10350                 encoded->unencoded_len = ram_bytes;
10351                 encoded->unencoded_offset = iocb->ki_pos - extent_start;
10352         } else {
10353                 count = min_t(u64, count, encoded->len);
10354                 encoded->len = count;
10355                 encoded->unencoded_len = count;
10356                 ptr += iocb->ki_pos - extent_start;
10357         }
10358
10359         tmp = kmalloc(count, GFP_NOFS);
10360         if (!tmp) {
10361                 ret = -ENOMEM;
10362                 goto out;
10363         }
10364         read_extent_buffer(leaf, tmp, ptr, count);
10365         btrfs_release_path(path);
10366         unlock_extent(io_tree, start, lockend, cached_state);
10367         btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10368         *unlocked = true;
10369
10370         ret = copy_to_iter(tmp, count, iter);
10371         if (ret != count)
10372                 ret = -EFAULT;
10373         kfree(tmp);
10374 out:
10375         btrfs_free_path(path);
10376         return ret;
10377 }
10378
10379 struct btrfs_encoded_read_private {
10380         struct btrfs_inode *inode;
10381         u64 file_offset;
10382         wait_queue_head_t wait;
10383         atomic_t pending;
10384         blk_status_t status;
10385         bool skip_csum;
10386 };
10387
10388 static blk_status_t submit_encoded_read_bio(struct btrfs_inode *inode,
10389                                             struct bio *bio, int mirror_num)
10390 {
10391         struct btrfs_encoded_read_private *priv = btrfs_bio(bio)->private;
10392         struct btrfs_fs_info *fs_info = inode->root->fs_info;
10393         blk_status_t ret;
10394
10395         if (!priv->skip_csum) {
10396                 ret = btrfs_lookup_bio_sums(&inode->vfs_inode, bio, NULL);
10397                 if (ret)
10398                         return ret;
10399         }
10400
10401         atomic_inc(&priv->pending);
10402         btrfs_submit_bio(fs_info, bio, mirror_num);
10403         return BLK_STS_OK;
10404 }
10405
10406 static blk_status_t btrfs_encoded_read_verify_csum(struct btrfs_bio *bbio)
10407 {
10408         const bool uptodate = (bbio->bio.bi_status == BLK_STS_OK);
10409         struct btrfs_encoded_read_private *priv = bbio->private;
10410         struct btrfs_inode *inode = priv->inode;
10411         struct btrfs_fs_info *fs_info = inode->root->fs_info;
10412         u32 sectorsize = fs_info->sectorsize;
10413         struct bio_vec *bvec;
10414         struct bvec_iter_all iter_all;
10415         u32 bio_offset = 0;
10416
10417         if (priv->skip_csum || !uptodate)
10418                 return bbio->bio.bi_status;
10419
10420         bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
10421                 unsigned int i, nr_sectors, pgoff;
10422
10423                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
10424                 pgoff = bvec->bv_offset;
10425                 for (i = 0; i < nr_sectors; i++) {
10426                         ASSERT(pgoff < PAGE_SIZE);
10427                         if (btrfs_check_data_csum(&inode->vfs_inode, bbio, bio_offset,
10428                                             bvec->bv_page, pgoff))
10429                                 return BLK_STS_IOERR;
10430                         bio_offset += sectorsize;
10431                         pgoff += sectorsize;
10432                 }
10433         }
10434         return BLK_STS_OK;
10435 }
10436
10437 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
10438 {
10439         struct btrfs_encoded_read_private *priv = bbio->private;
10440         blk_status_t status;
10441
10442         status = btrfs_encoded_read_verify_csum(bbio);
10443         if (status) {
10444                 /*
10445                  * The memory barrier implied by the atomic_dec_return() here
10446                  * pairs with the memory barrier implied by the
10447                  * atomic_dec_return() or io_wait_event() in
10448                  * btrfs_encoded_read_regular_fill_pages() to ensure that this
10449                  * write is observed before the load of status in
10450                  * btrfs_encoded_read_regular_fill_pages().
10451                  */
10452                 WRITE_ONCE(priv->status, status);
10453         }
10454         if (!atomic_dec_return(&priv->pending))
10455                 wake_up(&priv->wait);
10456         btrfs_bio_free_csum(bbio);
10457         bio_put(&bbio->bio);
10458 }
10459
10460 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
10461                                           u64 file_offset, u64 disk_bytenr,
10462                                           u64 disk_io_size, struct page **pages)
10463 {
10464         struct btrfs_fs_info *fs_info = inode->root->fs_info;
10465         struct btrfs_encoded_read_private priv = {
10466                 .inode = inode,
10467                 .file_offset = file_offset,
10468                 .pending = ATOMIC_INIT(1),
10469                 .skip_csum = (inode->flags & BTRFS_INODE_NODATASUM),
10470         };
10471         unsigned long i = 0;
10472         u64 cur = 0;
10473         int ret;
10474
10475         init_waitqueue_head(&priv.wait);
10476         /*
10477          * Submit bios for the extent, splitting due to bio or stripe limits as
10478          * necessary.
10479          */
10480         while (cur < disk_io_size) {
10481                 struct extent_map *em;
10482                 struct btrfs_io_geometry geom;
10483                 struct bio *bio = NULL;
10484                 u64 remaining;
10485
10486                 em = btrfs_get_chunk_map(fs_info, disk_bytenr + cur,
10487                                          disk_io_size - cur);
10488                 if (IS_ERR(em)) {
10489                         ret = PTR_ERR(em);
10490                 } else {
10491                         ret = btrfs_get_io_geometry(fs_info, em, BTRFS_MAP_READ,
10492                                                     disk_bytenr + cur, &geom);
10493                         free_extent_map(em);
10494                 }
10495                 if (ret) {
10496                         WRITE_ONCE(priv.status, errno_to_blk_status(ret));
10497                         break;
10498                 }
10499                 remaining = min(geom.len, disk_io_size - cur);
10500                 while (bio || remaining) {
10501                         size_t bytes = min_t(u64, remaining, PAGE_SIZE);
10502
10503                         if (!bio) {
10504                                 bio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ,
10505                                                       btrfs_encoded_read_endio,
10506                                                       &priv);
10507                                 bio->bi_iter.bi_sector =
10508                                         (disk_bytenr + cur) >> SECTOR_SHIFT;
10509                         }
10510
10511                         if (!bytes ||
10512                             bio_add_page(bio, pages[i], bytes, 0) < bytes) {
10513                                 blk_status_t status;
10514
10515                                 status = submit_encoded_read_bio(inode, bio, 0);
10516                                 if (status) {
10517                                         WRITE_ONCE(priv.status, status);
10518                                         bio_put(bio);
10519                                         goto out;
10520                                 }
10521                                 bio = NULL;
10522                                 continue;
10523                         }
10524
10525                         i++;
10526                         cur += bytes;
10527                         remaining -= bytes;
10528                 }
10529         }
10530
10531 out:
10532         if (atomic_dec_return(&priv.pending))
10533                 io_wait_event(priv.wait, !atomic_read(&priv.pending));
10534         /* See btrfs_encoded_read_endio() for ordering. */
10535         return blk_status_to_errno(READ_ONCE(priv.status));
10536 }
10537
10538 static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
10539                                           struct iov_iter *iter,
10540                                           u64 start, u64 lockend,
10541                                           struct extent_state **cached_state,
10542                                           u64 disk_bytenr, u64 disk_io_size,
10543                                           size_t count, bool compressed,
10544                                           bool *unlocked)
10545 {
10546         struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10547         struct extent_io_tree *io_tree = &inode->io_tree;
10548         struct page **pages;
10549         unsigned long nr_pages, i;
10550         u64 cur;
10551         size_t page_offset;
10552         ssize_t ret;
10553
10554         nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
10555         pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
10556         if (!pages)
10557                 return -ENOMEM;
10558         ret = btrfs_alloc_page_array(nr_pages, pages);
10559         if (ret) {
10560                 ret = -ENOMEM;
10561                 goto out;
10562                 }
10563
10564         ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
10565                                                     disk_io_size, pages);
10566         if (ret)
10567                 goto out;
10568
10569         unlock_extent(io_tree, start, lockend, cached_state);
10570         btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10571         *unlocked = true;
10572
10573         if (compressed) {
10574                 i = 0;
10575                 page_offset = 0;
10576         } else {
10577                 i = (iocb->ki_pos - start) >> PAGE_SHIFT;
10578                 page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
10579         }
10580         cur = 0;
10581         while (cur < count) {
10582                 size_t bytes = min_t(size_t, count - cur,
10583                                      PAGE_SIZE - page_offset);
10584
10585                 if (copy_page_to_iter(pages[i], page_offset, bytes,
10586                                       iter) != bytes) {
10587                         ret = -EFAULT;
10588                         goto out;
10589                 }
10590                 i++;
10591                 cur += bytes;
10592                 page_offset = 0;
10593         }
10594         ret = count;
10595 out:
10596         for (i = 0; i < nr_pages; i++) {
10597                 if (pages[i])
10598                         __free_page(pages[i]);
10599         }
10600         kfree(pages);
10601         return ret;
10602 }
10603
10604 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
10605                            struct btrfs_ioctl_encoded_io_args *encoded)
10606 {
10607         struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10608         struct btrfs_fs_info *fs_info = inode->root->fs_info;
10609         struct extent_io_tree *io_tree = &inode->io_tree;
10610         ssize_t ret;
10611         size_t count = iov_iter_count(iter);
10612         u64 start, lockend, disk_bytenr, disk_io_size;
10613         struct extent_state *cached_state = NULL;
10614         struct extent_map *em;
10615         bool unlocked = false;
10616
10617         file_accessed(iocb->ki_filp);
10618
10619         btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10620
10621         if (iocb->ki_pos >= inode->vfs_inode.i_size) {
10622                 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10623                 return 0;
10624         }
10625         start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
10626         /*
10627          * We don't know how long the extent containing iocb->ki_pos is, but if
10628          * it's compressed we know that it won't be longer than this.
10629          */
10630         lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
10631
10632         for (;;) {
10633                 struct btrfs_ordered_extent *ordered;
10634
10635                 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
10636                                                lockend - start + 1);
10637                 if (ret)
10638                         goto out_unlock_inode;
10639                 lock_extent(io_tree, start, lockend, &cached_state);
10640                 ordered = btrfs_lookup_ordered_range(inode, start,
10641                                                      lockend - start + 1);
10642                 if (!ordered)
10643                         break;
10644                 btrfs_put_ordered_extent(ordered);
10645                 unlock_extent(io_tree, start, lockend, &cached_state);
10646                 cond_resched();
10647         }
10648
10649         em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
10650         if (IS_ERR(em)) {
10651                 ret = PTR_ERR(em);
10652                 goto out_unlock_extent;
10653         }
10654
10655         if (em->block_start == EXTENT_MAP_INLINE) {
10656                 u64 extent_start = em->start;
10657
10658                 /*
10659                  * For inline extents we get everything we need out of the
10660                  * extent item.
10661                  */
10662                 free_extent_map(em);
10663                 em = NULL;
10664                 ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
10665                                                 &cached_state, extent_start,
10666                                                 count, encoded, &unlocked);
10667                 goto out;
10668         }
10669
10670         /*
10671          * We only want to return up to EOF even if the extent extends beyond
10672          * that.
10673          */
10674         encoded->len = min_t(u64, extent_map_end(em),
10675                              inode->vfs_inode.i_size) - iocb->ki_pos;
10676         if (em->block_start == EXTENT_MAP_HOLE ||
10677             test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
10678                 disk_bytenr = EXTENT_MAP_HOLE;
10679                 count = min_t(u64, count, encoded->len);
10680                 encoded->len = count;
10681                 encoded->unencoded_len = count;
10682         } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10683                 disk_bytenr = em->block_start;
10684                 /*
10685                  * Bail if the buffer isn't large enough to return the whole
10686                  * compressed extent.
10687                  */
10688                 if (em->block_len > count) {
10689                         ret = -ENOBUFS;
10690                         goto out_em;
10691                 }
10692                 disk_io_size = em->block_len;
10693                 count = em->block_len;
10694                 encoded->unencoded_len = em->ram_bytes;
10695                 encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
10696                 ret = btrfs_encoded_io_compression_from_extent(fs_info,
10697                                                              em->compress_type);
10698                 if (ret < 0)
10699                         goto out_em;
10700                 encoded->compression = ret;
10701         } else {
10702                 disk_bytenr = em->block_start + (start - em->start);
10703                 if (encoded->len > count)
10704                         encoded->len = count;
10705                 /*
10706                  * Don't read beyond what we locked. This also limits the page
10707                  * allocations that we'll do.
10708                  */
10709                 disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
10710                 count = start + disk_io_size - iocb->ki_pos;
10711                 encoded->len = count;
10712                 encoded->unencoded_len = count;
10713                 disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
10714         }
10715         free_extent_map(em);
10716         em = NULL;
10717
10718         if (disk_bytenr == EXTENT_MAP_HOLE) {
10719                 unlock_extent(io_tree, start, lockend, &cached_state);
10720                 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10721                 unlocked = true;
10722                 ret = iov_iter_zero(count, iter);
10723                 if (ret != count)
10724                         ret = -EFAULT;
10725         } else {
10726                 ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
10727                                                  &cached_state, disk_bytenr,
10728                                                  disk_io_size, count,
10729                                                  encoded->compression,
10730                                                  &unlocked);
10731         }
10732
10733 out:
10734         if (ret >= 0)
10735                 iocb->ki_pos += encoded->len;
10736 out_em:
10737         free_extent_map(em);
10738 out_unlock_extent:
10739         if (!unlocked)
10740                 unlock_extent(io_tree, start, lockend, &cached_state);
10741 out_unlock_inode:
10742         if (!unlocked)
10743                 btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
10744         return ret;
10745 }
10746
10747 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
10748                                const struct btrfs_ioctl_encoded_io_args *encoded)
10749 {
10750         struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
10751         struct btrfs_root *root = inode->root;
10752         struct btrfs_fs_info *fs_info = root->fs_info;
10753         struct extent_io_tree *io_tree = &inode->io_tree;
10754         struct extent_changeset *data_reserved = NULL;
10755         struct extent_state *cached_state = NULL;
10756         int compression;
10757         size_t orig_count;
10758         u64 start, end;
10759         u64 num_bytes, ram_bytes, disk_num_bytes;
10760         unsigned long nr_pages, i;
10761         struct page **pages;
10762         struct btrfs_key ins;
10763         bool extent_reserved = false;
10764         struct extent_map *em;
10765         ssize_t ret;
10766
10767         switch (encoded->compression) {
10768         case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
10769                 compression = BTRFS_COMPRESS_ZLIB;
10770                 break;
10771         case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
10772                 compression = BTRFS_COMPRESS_ZSTD;
10773                 break;
10774         case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
10775         case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
10776         case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
10777         case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
10778         case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
10779                 /* The sector size must match for LZO. */
10780                 if (encoded->compression -
10781                     BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
10782                     fs_info->sectorsize_bits)
10783                         return -EINVAL;
10784                 compression = BTRFS_COMPRESS_LZO;
10785                 break;
10786         default:
10787                 return -EINVAL;
10788         }
10789         if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
10790                 return -EINVAL;
10791
10792         /*
10793          * Compressed extents should always have checksums, so error out if we
10794          * have a NOCOW file or inode was created while mounted with NODATASUM.
10795          */
10796         if (inode->flags & BTRFS_INODE_NODATASUM)
10797                 return -EINVAL;
10798
10799         orig_count = iov_iter_count(from);
10800
10801         /* The extent size must be sane. */
10802         if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
10803             orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
10804                 return -EINVAL;
10805
10806         /*
10807          * The compressed data must be smaller than the decompressed data.
10808          *
10809          * It's of course possible for data to compress to larger or the same
10810          * size, but the buffered I/O path falls back to no compression for such
10811          * data, and we don't want to break any assumptions by creating these
10812          * extents.
10813          *
10814          * Note that this is less strict than the current check we have that the
10815          * compressed data must be at least one sector smaller than the
10816          * decompressed data. We only want to enforce the weaker requirement
10817          * from old kernels that it is at least one byte smaller.
10818          */
10819         if (orig_count >= encoded->unencoded_len)
10820                 return -EINVAL;
10821
10822         /* The extent must start on a sector boundary. */
10823         start = iocb->ki_pos;
10824         if (!IS_ALIGNED(start, fs_info->sectorsize))
10825                 return -EINVAL;
10826
10827         /*
10828          * The extent must end on a sector boundary. However, we allow a write
10829          * which ends at or extends i_size to have an unaligned length; we round
10830          * up the extent size and set i_size to the unaligned end.
10831          */
10832         if (start + encoded->len < inode->vfs_inode.i_size &&
10833             !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
10834                 return -EINVAL;
10835
10836         /* Finally, the offset in the unencoded data must be sector-aligned. */
10837         if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
10838                 return -EINVAL;
10839
10840         num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
10841         ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
10842         end = start + num_bytes - 1;
10843
10844         /*
10845          * If the extent cannot be inline, the compressed data on disk must be
10846          * sector-aligned. For convenience, we extend it with zeroes if it
10847          * isn't.
10848          */
10849         disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
10850         nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
10851         pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
10852         if (!pages)
10853                 return -ENOMEM;
10854         for (i = 0; i < nr_pages; i++) {
10855                 size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
10856                 char *kaddr;
10857
10858                 pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
10859                 if (!pages[i]) {
10860                         ret = -ENOMEM;
10861                         goto out_pages;
10862                 }
10863                 kaddr = kmap_local_page(pages[i]);
10864                 if (copy_from_iter(kaddr, bytes, from) != bytes) {
10865                         kunmap_local(kaddr);
10866                         ret = -EFAULT;
10867                         goto out_pages;
10868                 }
10869                 if (bytes < PAGE_SIZE)
10870                         memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
10871                 kunmap_local(kaddr);
10872         }
10873
10874         for (;;) {
10875                 struct btrfs_ordered_extent *ordered;
10876
10877                 ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
10878                 if (ret)
10879                         goto out_pages;
10880                 ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10881                                                     start >> PAGE_SHIFT,
10882                                                     end >> PAGE_SHIFT);
10883                 if (ret)
10884                         goto out_pages;
10885                 lock_extent(io_tree, start, end, &cached_state);
10886                 ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10887                 if (!ordered &&
10888                     !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10889                         break;
10890                 if (ordered)
10891                         btrfs_put_ordered_extent(ordered);
10892                 unlock_extent(io_tree, start, end, &cached_state);
10893                 cond_resched();
10894         }
10895
10896         /*
10897          * We don't use the higher-level delalloc space functions because our
10898          * num_bytes and disk_num_bytes are different.
10899          */
10900         ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10901         if (ret)
10902                 goto out_unlock;
10903         ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10904         if (ret)
10905                 goto out_free_data_space;
10906         ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10907                                               false);
10908         if (ret)
10909                 goto out_qgroup_free_data;
10910
10911         /* Try an inline extent first. */
10912         if (start == 0 && encoded->unencoded_len == encoded->len &&
10913             encoded->unencoded_offset == 0) {
10914                 ret = cow_file_range_inline(inode, encoded->len, orig_count,
10915                                             compression, pages, true);
10916                 if (ret <= 0) {
10917                         if (ret == 0)
10918                                 ret = orig_count;
10919                         goto out_delalloc_release;
10920                 }
10921         }
10922
10923         ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10924                                    disk_num_bytes, 0, 0, &ins, 1, 1);
10925         if (ret)
10926                 goto out_delalloc_release;
10927         extent_reserved = true;
10928
10929         em = create_io_em(inode, start, num_bytes,
10930                           start - encoded->unencoded_offset, ins.objectid,
10931                           ins.offset, ins.offset, ram_bytes, compression,
10932                           BTRFS_ORDERED_COMPRESSED);
10933         if (IS_ERR(em)) {
10934                 ret = PTR_ERR(em);
10935                 goto out_free_reserved;
10936         }
10937         free_extent_map(em);
10938
10939         ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
10940                                        ins.objectid, ins.offset,
10941                                        encoded->unencoded_offset,
10942                                        (1 << BTRFS_ORDERED_ENCODED) |
10943                                        (1 << BTRFS_ORDERED_COMPRESSED),
10944                                        compression);
10945         if (ret) {
10946                 btrfs_drop_extent_map_range(inode, start, end, false);
10947                 goto out_free_reserved;
10948         }
10949         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10950
10951         if (start + encoded->len > inode->vfs_inode.i_size)
10952                 i_size_write(&inode->vfs_inode, start + encoded->len);
10953
10954         unlock_extent(io_tree, start, end, &cached_state);
10955
10956         btrfs_delalloc_release_extents(inode, num_bytes);
10957
10958         if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
10959                                           ins.offset, pages, nr_pages, 0, NULL,
10960                                           false)) {
10961                 btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
10962                 ret = -EIO;
10963                 goto out_pages;
10964         }
10965         ret = orig_count;
10966         goto out;
10967
10968 out_free_reserved:
10969         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10970         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
10971 out_delalloc_release:
10972         btrfs_delalloc_release_extents(inode, num_bytes);
10973         btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10974 out_qgroup_free_data:
10975         if (ret < 0)
10976                 btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
10977 out_free_data_space:
10978         /*
10979          * If btrfs_reserve_extent() succeeded, then we already decremented
10980          * bytes_may_use.
10981          */
10982         if (!extent_reserved)
10983                 btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
10984 out_unlock:
10985         unlock_extent(io_tree, start, end, &cached_state);
10986 out_pages:
10987         for (i = 0; i < nr_pages; i++) {
10988                 if (pages[i])
10989                         __free_page(pages[i]);
10990         }
10991         kvfree(pages);
10992 out:
10993         if (ret >= 0)
10994                 iocb->ki_pos += encoded->len;
10995         return ret;
10996 }
10997
10998 #ifdef CONFIG_SWAP
10999 /*
11000  * Add an entry indicating a block group or device which is pinned by a
11001  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
11002  * negative errno on failure.
11003  */
11004 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
11005                                   bool is_block_group)
11006 {
11007         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
11008         struct btrfs_swapfile_pin *sp, *entry;
11009         struct rb_node **p;
11010         struct rb_node *parent = NULL;
11011
11012         sp = kmalloc(sizeof(*sp), GFP_NOFS);
11013         if (!sp)
11014                 return -ENOMEM;
11015         sp->ptr = ptr;
11016         sp->inode = inode;
11017         sp->is_block_group = is_block_group;
11018         sp->bg_extent_count = 1;
11019
11020         spin_lock(&fs_info->swapfile_pins_lock);
11021         p = &fs_info->swapfile_pins.rb_node;
11022         while (*p) {
11023                 parent = *p;
11024                 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
11025                 if (sp->ptr < entry->ptr ||
11026                     (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
11027                         p = &(*p)->rb_left;
11028                 } else if (sp->ptr > entry->ptr ||
11029                            (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
11030                         p = &(*p)->rb_right;
11031                 } else {
11032                         if (is_block_group)
11033                                 entry->bg_extent_count++;
11034                         spin_unlock(&fs_info->swapfile_pins_lock);
11035                         kfree(sp);
11036                         return 1;
11037                 }
11038         }
11039         rb_link_node(&sp->node, parent, p);
11040         rb_insert_color(&sp->node, &fs_info->swapfile_pins);
11041         spin_unlock(&fs_info->swapfile_pins_lock);
11042         return 0;
11043 }
11044
11045 /* Free all of the entries pinned by this swapfile. */
11046 static void btrfs_free_swapfile_pins(struct inode *inode)
11047 {
11048         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
11049         struct btrfs_swapfile_pin *sp;
11050         struct rb_node *node, *next;
11051
11052         spin_lock(&fs_info->swapfile_pins_lock);
11053         node = rb_first(&fs_info->swapfile_pins);
11054         while (node) {
11055                 next = rb_next(node);
11056                 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
11057                 if (sp->inode == inode) {
11058                         rb_erase(&sp->node, &fs_info->swapfile_pins);
11059                         if (sp->is_block_group) {
11060                                 btrfs_dec_block_group_swap_extents(sp->ptr,
11061                                                            sp->bg_extent_count);
11062                                 btrfs_put_block_group(sp->ptr);
11063                         }
11064                         kfree(sp);
11065                 }
11066                 node = next;
11067         }
11068         spin_unlock(&fs_info->swapfile_pins_lock);
11069 }
11070
11071 struct btrfs_swap_info {
11072         u64 start;
11073         u64 block_start;
11074         u64 block_len;
11075         u64 lowest_ppage;
11076         u64 highest_ppage;
11077         unsigned long nr_pages;
11078         int nr_extents;
11079 };
11080
11081 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
11082                                  struct btrfs_swap_info *bsi)
11083 {
11084         unsigned long nr_pages;
11085         unsigned long max_pages;
11086         u64 first_ppage, first_ppage_reported, next_ppage;
11087         int ret;
11088
11089         /*
11090          * Our swapfile may have had its size extended after the swap header was
11091          * written. In that case activating the swapfile should not go beyond
11092          * the max size set in the swap header.
11093          */
11094         if (bsi->nr_pages >= sis->max)
11095                 return 0;
11096
11097         max_pages = sis->max - bsi->nr_pages;
11098         first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
11099         next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
11100                                 PAGE_SIZE) >> PAGE_SHIFT;
11101
11102         if (first_ppage >= next_ppage)
11103                 return 0;
11104         nr_pages = next_ppage - first_ppage;
11105         nr_pages = min(nr_pages, max_pages);
11106
11107         first_ppage_reported = first_ppage;
11108         if (bsi->start == 0)
11109                 first_ppage_reported++;
11110         if (bsi->lowest_ppage > first_ppage_reported)
11111                 bsi->lowest_ppage = first_ppage_reported;
11112         if (bsi->highest_ppage < (next_ppage - 1))
11113                 bsi->highest_ppage = next_ppage - 1;
11114
11115         ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
11116         if (ret < 0)
11117                 return ret;
11118         bsi->nr_extents += ret;
11119         bsi->nr_pages += nr_pages;
11120         return 0;
11121 }
11122
11123 static void btrfs_swap_deactivate(struct file *file)
11124 {
11125         struct inode *inode = file_inode(file);
11126
11127         btrfs_free_swapfile_pins(inode);
11128         atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
11129 }
11130
11131 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11132                                sector_t *span)
11133 {
11134         struct inode *inode = file_inode(file);
11135         struct btrfs_root *root = BTRFS_I(inode)->root;
11136         struct btrfs_fs_info *fs_info = root->fs_info;
11137         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
11138         struct extent_state *cached_state = NULL;
11139         struct extent_map *em = NULL;
11140         struct btrfs_device *device = NULL;
11141         struct btrfs_swap_info bsi = {
11142                 .lowest_ppage = (sector_t)-1ULL,
11143         };
11144         int ret = 0;
11145         u64 isize;
11146         u64 start;
11147
11148         /*
11149          * If the swap file was just created, make sure delalloc is done. If the
11150          * file changes again after this, the user is doing something stupid and
11151          * we don't really care.
11152          */
11153         ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
11154         if (ret)
11155                 return ret;
11156
11157         /*
11158          * The inode is locked, so these flags won't change after we check them.
11159          */
11160         if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
11161                 btrfs_warn(fs_info, "swapfile must not be compressed");
11162                 return -EINVAL;
11163         }
11164         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
11165                 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
11166                 return -EINVAL;
11167         }
11168         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
11169                 btrfs_warn(fs_info, "swapfile must not be checksummed");
11170                 return -EINVAL;
11171         }
11172
11173         /*
11174          * Balance or device remove/replace/resize can move stuff around from
11175          * under us. The exclop protection makes sure they aren't running/won't
11176          * run concurrently while we are mapping the swap extents, and
11177          * fs_info->swapfile_pins prevents them from running while the swap
11178          * file is active and moving the extents. Note that this also prevents
11179          * a concurrent device add which isn't actually necessary, but it's not
11180          * really worth the trouble to allow it.
11181          */
11182         if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
11183                 btrfs_warn(fs_info,
11184            "cannot activate swapfile while exclusive operation is running");
11185                 return -EBUSY;
11186         }
11187
11188         /*
11189          * Prevent snapshot creation while we are activating the swap file.
11190          * We do not want to race with snapshot creation. If snapshot creation
11191          * already started before we bumped nr_swapfiles from 0 to 1 and
11192          * completes before the first write into the swap file after it is
11193          * activated, than that write would fallback to COW.
11194          */
11195         if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
11196                 btrfs_exclop_finish(fs_info);
11197                 btrfs_warn(fs_info,
11198            "cannot activate swapfile because snapshot creation is in progress");
11199                 return -EINVAL;
11200         }
11201         /*
11202          * Snapshots can create extents which require COW even if NODATACOW is
11203          * set. We use this counter to prevent snapshots. We must increment it
11204          * before walking the extents because we don't want a concurrent
11205          * snapshot to run after we've already checked the extents.
11206          *
11207          * It is possible that subvolume is marked for deletion but still not
11208          * removed yet. To prevent this race, we check the root status before
11209          * activating the swapfile.
11210          */
11211         spin_lock(&root->root_item_lock);
11212         if (btrfs_root_dead(root)) {
11213                 spin_unlock(&root->root_item_lock);
11214
11215                 btrfs_exclop_finish(fs_info);
11216                 btrfs_warn(fs_info,
11217                 "cannot activate swapfile because subvolume %llu is being deleted",
11218                         root->root_key.objectid);
11219                 return -EPERM;
11220         }
11221         atomic_inc(&root->nr_swapfiles);
11222         spin_unlock(&root->root_item_lock);
11223
11224         isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
11225
11226         lock_extent(io_tree, 0, isize - 1, &cached_state);
11227         start = 0;
11228         while (start < isize) {
11229                 u64 logical_block_start, physical_block_start;
11230                 struct btrfs_block_group *bg;
11231                 u64 len = isize - start;
11232
11233                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
11234                 if (IS_ERR(em)) {
11235                         ret = PTR_ERR(em);
11236                         goto out;
11237                 }
11238
11239                 if (em->block_start == EXTENT_MAP_HOLE) {
11240                         btrfs_warn(fs_info, "swapfile must not have holes");
11241                         ret = -EINVAL;
11242                         goto out;
11243                 }
11244                 if (em->block_start == EXTENT_MAP_INLINE) {
11245                         /*
11246                          * It's unlikely we'll ever actually find ourselves
11247                          * here, as a file small enough to fit inline won't be
11248                          * big enough to store more than the swap header, but in
11249                          * case something changes in the future, let's catch it
11250                          * here rather than later.
11251                          */
11252                         btrfs_warn(fs_info, "swapfile must not be inline");
11253                         ret = -EINVAL;
11254                         goto out;
11255                 }
11256                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
11257                         btrfs_warn(fs_info, "swapfile must not be compressed");
11258                         ret = -EINVAL;
11259                         goto out;
11260                 }
11261
11262                 logical_block_start = em->block_start + (start - em->start);
11263                 len = min(len, em->len - (start - em->start));
11264                 free_extent_map(em);
11265                 em = NULL;
11266
11267                 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
11268                 if (ret < 0) {
11269                         goto out;
11270                 } else if (ret) {
11271                         ret = 0;
11272                 } else {
11273                         btrfs_warn(fs_info,
11274                                    "swapfile must not be copy-on-write");
11275                         ret = -EINVAL;
11276                         goto out;
11277                 }
11278
11279                 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
11280                 if (IS_ERR(em)) {
11281                         ret = PTR_ERR(em);
11282                         goto out;
11283                 }
11284
11285                 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
11286                         btrfs_warn(fs_info,
11287                                    "swapfile must have single data profile");
11288                         ret = -EINVAL;
11289                         goto out;
11290                 }
11291
11292                 if (device == NULL) {
11293                         device = em->map_lookup->stripes[0].dev;
11294                         ret = btrfs_add_swapfile_pin(inode, device, false);
11295                         if (ret == 1)
11296                                 ret = 0;
11297                         else if (ret)
11298                                 goto out;
11299                 } else if (device != em->map_lookup->stripes[0].dev) {
11300                         btrfs_warn(fs_info, "swapfile must be on one device");
11301                         ret = -EINVAL;
11302                         goto out;
11303                 }
11304
11305                 physical_block_start = (em->map_lookup->stripes[0].physical +
11306                                         (logical_block_start - em->start));
11307                 len = min(len, em->len - (logical_block_start - em->start));
11308                 free_extent_map(em);
11309                 em = NULL;
11310
11311                 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
11312                 if (!bg) {
11313                         btrfs_warn(fs_info,
11314                            "could not find block group containing swapfile");
11315                         ret = -EINVAL;
11316                         goto out;
11317                 }
11318
11319                 if (!btrfs_inc_block_group_swap_extents(bg)) {
11320                         btrfs_warn(fs_info,
11321                            "block group for swapfile at %llu is read-only%s",
11322                            bg->start,
11323                            atomic_read(&fs_info->scrubs_running) ?
11324                                        " (scrub running)" : "");
11325                         btrfs_put_block_group(bg);
11326                         ret = -EINVAL;
11327                         goto out;
11328                 }
11329
11330                 ret = btrfs_add_swapfile_pin(inode, bg, true);
11331                 if (ret) {
11332                         btrfs_put_block_group(bg);
11333                         if (ret == 1)
11334                                 ret = 0;
11335                         else
11336                                 goto out;
11337                 }
11338
11339                 if (bsi.block_len &&
11340                     bsi.block_start + bsi.block_len == physical_block_start) {
11341                         bsi.block_len += len;
11342                 } else {
11343                         if (bsi.block_len) {
11344                                 ret = btrfs_add_swap_extent(sis, &bsi);
11345                                 if (ret)
11346                                         goto out;
11347                         }
11348                         bsi.start = start;
11349                         bsi.block_start = physical_block_start;
11350                         bsi.block_len = len;
11351                 }
11352
11353                 start += len;
11354         }
11355
11356         if (bsi.block_len)
11357                 ret = btrfs_add_swap_extent(sis, &bsi);
11358
11359 out:
11360         if (!IS_ERR_OR_NULL(em))
11361                 free_extent_map(em);
11362
11363         unlock_extent(io_tree, 0, isize - 1, &cached_state);
11364
11365         if (ret)
11366                 btrfs_swap_deactivate(file);
11367
11368         btrfs_drew_write_unlock(&root->snapshot_lock);
11369
11370         btrfs_exclop_finish(fs_info);
11371
11372         if (ret)
11373                 return ret;
11374
11375         if (device)
11376                 sis->bdev = device->bdev;
11377         *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
11378         sis->max = bsi.nr_pages;
11379         sis->pages = bsi.nr_pages - 1;
11380         sis->highest_bit = bsi.nr_pages - 1;
11381         return bsi.nr_extents;
11382 }
11383 #else
11384 static void btrfs_swap_deactivate(struct file *file)
11385 {
11386 }
11387
11388 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
11389                                sector_t *span)
11390 {
11391         return -EOPNOTSUPP;
11392 }
11393 #endif
11394
11395 /*
11396  * Update the number of bytes used in the VFS' inode. When we replace extents in
11397  * a range (clone, dedupe, fallocate's zero range), we must update the number of
11398  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
11399  * always get a correct value.
11400  */
11401 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
11402                               const u64 add_bytes,
11403                               const u64 del_bytes)
11404 {
11405         if (add_bytes == del_bytes)
11406                 return;
11407
11408         spin_lock(&inode->lock);
11409         if (del_bytes > 0)
11410                 inode_sub_bytes(&inode->vfs_inode, del_bytes);
11411         if (add_bytes > 0)
11412                 inode_add_bytes(&inode->vfs_inode, add_bytes);
11413         spin_unlock(&inode->lock);
11414 }
11415
11416 /**
11417  * Verify that there are no ordered extents for a given file range.
11418  *
11419  * @inode:   The target inode.
11420  * @start:   Start offset of the file range, should be sector size aligned.
11421  * @end:     End offset (inclusive) of the file range, its value +1 should be
11422  *           sector size aligned.
11423  *
11424  * This should typically be used for cases where we locked an inode's VFS lock in
11425  * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
11426  * we have flushed all delalloc in the range, we have waited for all ordered
11427  * extents in the range to complete and finally we have locked the file range in
11428  * the inode's io_tree.
11429  */
11430 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
11431 {
11432         struct btrfs_root *root = inode->root;
11433         struct btrfs_ordered_extent *ordered;
11434
11435         if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
11436                 return;
11437
11438         ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
11439         if (ordered) {
11440                 btrfs_err(root->fs_info,
11441 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
11442                           start, end, btrfs_ino(inode), root->root_key.objectid,
11443                           ordered->file_offset,
11444                           ordered->file_offset + ordered->num_bytes - 1);
11445                 btrfs_put_ordered_extent(ordered);
11446         }
11447
11448         ASSERT(ordered == NULL);
11449 }
11450
11451 static const struct inode_operations btrfs_dir_inode_operations = {
11452         .getattr        = btrfs_getattr,
11453         .lookup         = btrfs_lookup,
11454         .create         = btrfs_create,
11455         .unlink         = btrfs_unlink,
11456         .link           = btrfs_link,
11457         .mkdir          = btrfs_mkdir,
11458         .rmdir          = btrfs_rmdir,
11459         .rename         = btrfs_rename2,
11460         .symlink        = btrfs_symlink,
11461         .setattr        = btrfs_setattr,
11462         .mknod          = btrfs_mknod,
11463         .listxattr      = btrfs_listxattr,
11464         .permission     = btrfs_permission,
11465         .get_acl        = btrfs_get_acl,
11466         .set_acl        = btrfs_set_acl,
11467         .update_time    = btrfs_update_time,
11468         .tmpfile        = btrfs_tmpfile,
11469         .fileattr_get   = btrfs_fileattr_get,
11470         .fileattr_set   = btrfs_fileattr_set,
11471 };
11472
11473 static const struct file_operations btrfs_dir_file_operations = {
11474         .llseek         = btrfs_dir_llseek,
11475         .read           = generic_read_dir,
11476         .iterate_shared = btrfs_real_readdir,
11477         .open           = btrfs_opendir,
11478         .unlocked_ioctl = btrfs_ioctl,
11479 #ifdef CONFIG_COMPAT
11480         .compat_ioctl   = btrfs_compat_ioctl,
11481 #endif
11482         .release        = btrfs_release_file,
11483         .fsync          = btrfs_sync_file,
11484 };
11485
11486 /*
11487  * btrfs doesn't support the bmap operation because swapfiles
11488  * use bmap to make a mapping of extents in the file.  They assume
11489  * these extents won't change over the life of the file and they
11490  * use the bmap result to do IO directly to the drive.
11491  *
11492  * the btrfs bmap call would return logical addresses that aren't
11493  * suitable for IO and they also will change frequently as COW
11494  * operations happen.  So, swapfile + btrfs == corruption.
11495  *
11496  * For now we're avoiding this by dropping bmap.
11497  */
11498 static const struct address_space_operations btrfs_aops = {
11499         .read_folio     = btrfs_read_folio,
11500         .writepages     = btrfs_writepages,
11501         .readahead      = btrfs_readahead,
11502         .direct_IO      = noop_direct_IO,
11503         .invalidate_folio = btrfs_invalidate_folio,
11504         .release_folio  = btrfs_release_folio,
11505         .migrate_folio  = btrfs_migrate_folio,
11506         .dirty_folio    = filemap_dirty_folio,
11507         .error_remove_page = generic_error_remove_page,
11508         .swap_activate  = btrfs_swap_activate,
11509         .swap_deactivate = btrfs_swap_deactivate,
11510 };
11511
11512 static const struct inode_operations btrfs_file_inode_operations = {
11513         .getattr        = btrfs_getattr,
11514         .setattr        = btrfs_setattr,
11515         .listxattr      = btrfs_listxattr,
11516         .permission     = btrfs_permission,
11517         .fiemap         = btrfs_fiemap,
11518         .get_acl        = btrfs_get_acl,
11519         .set_acl        = btrfs_set_acl,
11520         .update_time    = btrfs_update_time,
11521         .fileattr_get   = btrfs_fileattr_get,
11522         .fileattr_set   = btrfs_fileattr_set,
11523 };
11524 static const struct inode_operations btrfs_special_inode_operations = {
11525         .getattr        = btrfs_getattr,
11526         .setattr        = btrfs_setattr,
11527         .permission     = btrfs_permission,
11528         .listxattr      = btrfs_listxattr,
11529         .get_acl        = btrfs_get_acl,
11530         .set_acl        = btrfs_set_acl,
11531         .update_time    = btrfs_update_time,
11532 };
11533 static const struct inode_operations btrfs_symlink_inode_operations = {
11534         .get_link       = page_get_link,
11535         .getattr        = btrfs_getattr,
11536         .setattr        = btrfs_setattr,
11537         .permission     = btrfs_permission,
11538         .listxattr      = btrfs_listxattr,
11539         .update_time    = btrfs_update_time,
11540 };
11541
11542 const struct dentry_operations btrfs_dentry_operations = {
11543         .d_delete       = btrfs_dentry_delete,
11544 };