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