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