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