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