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