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