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