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