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