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