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