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