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