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