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