8f21036bcc99ae85d750fb3e2c93c08fae30bf60
[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                 if (truncated)
3009                         unwritten_start += logical_len;
3010                 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
3011
3012                 /* Drop the cache for the part of the extent we didn't write. */
3013                 btrfs_drop_extent_cache(inode, unwritten_start, end, 0);
3014
3015                 /*
3016                  * If the ordered extent had an IOERR or something else went
3017                  * wrong we need to return the space for this ordered extent
3018                  * back to the allocator.  We only free the extent in the
3019                  * truncated case if we didn't write out the extent at all.
3020                  *
3021                  * If we made it past insert_reserved_file_extent before we
3022                  * errored out then we don't need to do this as the accounting
3023                  * has already been done.
3024                  */
3025                 if ((ret || !logical_len) &&
3026                     clear_reserved_extent &&
3027                     !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3028                     !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3029                         /*
3030                          * Discard the range before returning it back to the
3031                          * free space pool
3032                          */
3033                         if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3034                                 btrfs_discard_extent(fs_info,
3035                                                 ordered_extent->disk_bytenr,
3036                                                 ordered_extent->disk_num_bytes,
3037                                                 NULL);
3038                         btrfs_free_reserved_extent(fs_info,
3039                                         ordered_extent->disk_bytenr,
3040                                         ordered_extent->disk_num_bytes, 1);
3041                 }
3042         }
3043
3044         /*
3045          * This needs to be done to make sure anybody waiting knows we are done
3046          * updating everything for this ordered extent.
3047          */
3048         btrfs_remove_ordered_extent(inode, ordered_extent);
3049
3050         /* once for us */
3051         btrfs_put_ordered_extent(ordered_extent);
3052         /* once for the tree */
3053         btrfs_put_ordered_extent(ordered_extent);
3054
3055         return ret;
3056 }
3057
3058 static void finish_ordered_fn(struct btrfs_work *work)
3059 {
3060         struct btrfs_ordered_extent *ordered_extent;
3061         ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3062         btrfs_finish_ordered_io(ordered_extent);
3063 }
3064
3065 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
3066                                           u64 end, int uptodate)
3067 {
3068         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
3069         struct btrfs_fs_info *fs_info = inode->root->fs_info;
3070         struct btrfs_ordered_extent *ordered_extent = NULL;
3071         struct btrfs_workqueue *wq;
3072
3073         trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3074
3075         ClearPagePrivate2(page);
3076         if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3077                                             end - start + 1, uptodate))
3078                 return;
3079
3080         if (btrfs_is_free_space_inode(inode))
3081                 wq = fs_info->endio_freespace_worker;
3082         else
3083                 wq = fs_info->endio_write_workers;
3084
3085         btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
3086         btrfs_queue_work(wq, &ordered_extent->work);
3087 }
3088
3089 /*
3090  * check_data_csum - verify checksum of one sector of uncompressed data
3091  * @inode:      inode
3092  * @io_bio:     btrfs_io_bio which contains the csum
3093  * @bio_offset: offset to the beginning of the bio (in bytes)
3094  * @page:       page where is the data to be verified
3095  * @pgoff:      offset inside the page
3096  * @start:      logical offset in the file
3097  *
3098  * The length of such check is always one sector size.
3099  */
3100 static int check_data_csum(struct inode *inode, struct btrfs_io_bio *io_bio,
3101                            u32 bio_offset, struct page *page, u32 pgoff,
3102                            u64 start)
3103 {
3104         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3105         SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
3106         char *kaddr;
3107         u32 len = fs_info->sectorsize;
3108         const u32 csum_size = fs_info->csum_size;
3109         unsigned int offset_sectors;
3110         u8 *csum_expected;
3111         u8 csum[BTRFS_CSUM_SIZE];
3112
3113         ASSERT(pgoff + len <= PAGE_SIZE);
3114
3115         offset_sectors = bio_offset >> fs_info->sectorsize_bits;
3116         csum_expected = ((u8 *)io_bio->csum) + offset_sectors * csum_size;
3117
3118         kaddr = kmap_atomic(page);
3119         shash->tfm = fs_info->csum_shash;
3120
3121         crypto_shash_digest(shash, kaddr + pgoff, len, csum);
3122
3123         if (memcmp(csum, csum_expected, csum_size))
3124                 goto zeroit;
3125
3126         kunmap_atomic(kaddr);
3127         return 0;
3128 zeroit:
3129         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3130                                     io_bio->mirror_num);
3131         if (io_bio->device)
3132                 btrfs_dev_stat_inc_and_print(io_bio->device,
3133                                              BTRFS_DEV_STAT_CORRUPTION_ERRS);
3134         memset(kaddr + pgoff, 1, len);
3135         flush_dcache_page(page);
3136         kunmap_atomic(kaddr);
3137         return -EIO;
3138 }
3139
3140 /*
3141  * When reads are done, we need to check csums to verify the data is correct.
3142  * if there's a match, we allow the bio to finish.  If not, the code in
3143  * extent_io.c will try to find good copies for us.
3144  *
3145  * @bio_offset: offset to the beginning of the bio (in bytes)
3146  * @start:      file offset of the range start
3147  * @end:        file offset of the range end (inclusive)
3148  */
3149 int btrfs_verify_data_csum(struct btrfs_io_bio *io_bio, u32 bio_offset,
3150                            struct page *page, u64 start, u64 end)
3151 {
3152         struct inode *inode = page->mapping->host;
3153         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3154         struct btrfs_root *root = BTRFS_I(inode)->root;
3155         const u32 sectorsize = root->fs_info->sectorsize;
3156         u32 pg_off;
3157
3158         if (PageChecked(page)) {
3159                 ClearPageChecked(page);
3160                 return 0;
3161         }
3162
3163         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3164                 return 0;
3165
3166         if (!root->fs_info->csum_root)
3167                 return 0;
3168
3169         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3170             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3171                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3172                 return 0;
3173         }
3174
3175         ASSERT(page_offset(page) <= start &&
3176                end <= page_offset(page) + PAGE_SIZE - 1);
3177         for (pg_off = offset_in_page(start);
3178              pg_off < offset_in_page(end);
3179              pg_off += sectorsize, bio_offset += sectorsize) {
3180                 int ret;
3181
3182                 ret = check_data_csum(inode, io_bio, bio_offset, page, pg_off,
3183                                       page_offset(page) + pg_off);
3184                 if (ret < 0)
3185                         return -EIO;
3186         }
3187         return 0;
3188 }
3189
3190 /*
3191  * btrfs_add_delayed_iput - perform a delayed iput on @inode
3192  *
3193  * @inode: The inode we want to perform iput on
3194  *
3195  * This function uses the generic vfs_inode::i_count to track whether we should
3196  * just decrement it (in case it's > 1) or if this is the last iput then link
3197  * the inode to the delayed iput machinery. Delayed iputs are processed at
3198  * transaction commit time/superblock commit/cleaner kthread.
3199  */
3200 void btrfs_add_delayed_iput(struct inode *inode)
3201 {
3202         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3203         struct btrfs_inode *binode = BTRFS_I(inode);
3204
3205         if (atomic_add_unless(&inode->i_count, -1, 1))
3206                 return;
3207
3208         atomic_inc(&fs_info->nr_delayed_iputs);
3209         spin_lock(&fs_info->delayed_iput_lock);
3210         ASSERT(list_empty(&binode->delayed_iput));
3211         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3212         spin_unlock(&fs_info->delayed_iput_lock);
3213         if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3214                 wake_up_process(fs_info->cleaner_kthread);
3215 }
3216
3217 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3218                                     struct btrfs_inode *inode)
3219 {
3220         list_del_init(&inode->delayed_iput);
3221         spin_unlock(&fs_info->delayed_iput_lock);
3222         iput(&inode->vfs_inode);
3223         if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3224                 wake_up(&fs_info->delayed_iputs_wait);
3225         spin_lock(&fs_info->delayed_iput_lock);
3226 }
3227
3228 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3229                                    struct btrfs_inode *inode)
3230 {
3231         if (!list_empty(&inode->delayed_iput)) {
3232                 spin_lock(&fs_info->delayed_iput_lock);
3233                 if (!list_empty(&inode->delayed_iput))
3234                         run_delayed_iput_locked(fs_info, inode);
3235                 spin_unlock(&fs_info->delayed_iput_lock);
3236         }
3237 }
3238
3239 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3240 {
3241
3242         spin_lock(&fs_info->delayed_iput_lock);
3243         while (!list_empty(&fs_info->delayed_iputs)) {
3244                 struct btrfs_inode *inode;
3245
3246                 inode = list_first_entry(&fs_info->delayed_iputs,
3247                                 struct btrfs_inode, delayed_iput);
3248                 run_delayed_iput_locked(fs_info, inode);
3249         }
3250         spin_unlock(&fs_info->delayed_iput_lock);
3251 }
3252
3253 /**
3254  * Wait for flushing all delayed iputs
3255  *
3256  * @fs_info:  the filesystem
3257  *
3258  * This will wait on any delayed iputs that are currently running with KILLABLE
3259  * set.  Once they are all done running we will return, unless we are killed in
3260  * which case we return EINTR. This helps in user operations like fallocate etc
3261  * that might get blocked on the iputs.
3262  *
3263  * Return EINTR if we were killed, 0 if nothing's pending
3264  */
3265 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3266 {
3267         int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3268                         atomic_read(&fs_info->nr_delayed_iputs) == 0);
3269         if (ret)
3270                 return -EINTR;
3271         return 0;
3272 }
3273
3274 /*
3275  * This creates an orphan entry for the given inode in case something goes wrong
3276  * in the middle of an unlink.
3277  */
3278 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3279                      struct btrfs_inode *inode)
3280 {
3281         int ret;
3282
3283         ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3284         if (ret && ret != -EEXIST) {
3285                 btrfs_abort_transaction(trans, ret);
3286                 return ret;
3287         }
3288
3289         return 0;
3290 }
3291
3292 /*
3293  * We have done the delete so we can go ahead and remove the orphan item for
3294  * this particular inode.
3295  */
3296 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3297                             struct btrfs_inode *inode)
3298 {
3299         return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3300 }
3301
3302 /*
3303  * this cleans up any orphans that may be left on the list from the last use
3304  * of this root.
3305  */
3306 int btrfs_orphan_cleanup(struct btrfs_root *root)
3307 {
3308         struct btrfs_fs_info *fs_info = root->fs_info;
3309         struct btrfs_path *path;
3310         struct extent_buffer *leaf;
3311         struct btrfs_key key, found_key;
3312         struct btrfs_trans_handle *trans;
3313         struct inode *inode;
3314         u64 last_objectid = 0;
3315         int ret = 0, nr_unlink = 0;
3316
3317         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3318                 return 0;
3319
3320         path = btrfs_alloc_path();
3321         if (!path) {
3322                 ret = -ENOMEM;
3323                 goto out;
3324         }
3325         path->reada = READA_BACK;
3326
3327         key.objectid = BTRFS_ORPHAN_OBJECTID;
3328         key.type = BTRFS_ORPHAN_ITEM_KEY;
3329         key.offset = (u64)-1;
3330
3331         while (1) {
3332                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3333                 if (ret < 0)
3334                         goto out;
3335
3336                 /*
3337                  * if ret == 0 means we found what we were searching for, which
3338                  * is weird, but possible, so only screw with path if we didn't
3339                  * find the key and see if we have stuff that matches
3340                  */
3341                 if (ret > 0) {
3342                         ret = 0;
3343                         if (path->slots[0] == 0)
3344                                 break;
3345                         path->slots[0]--;
3346                 }
3347
3348                 /* pull out the item */
3349                 leaf = path->nodes[0];
3350                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3351
3352                 /* make sure the item matches what we want */
3353                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3354                         break;
3355                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3356                         break;
3357
3358                 /* release the path since we're done with it */
3359                 btrfs_release_path(path);
3360
3361                 /*
3362                  * this is where we are basically btrfs_lookup, without the
3363                  * crossing root thing.  we store the inode number in the
3364                  * offset of the orphan item.
3365                  */
3366
3367                 if (found_key.offset == last_objectid) {
3368                         btrfs_err(fs_info,
3369                                   "Error removing orphan entry, stopping orphan cleanup");
3370                         ret = -EINVAL;
3371                         goto out;
3372                 }
3373
3374                 last_objectid = found_key.offset;
3375
3376                 found_key.objectid = found_key.offset;
3377                 found_key.type = BTRFS_INODE_ITEM_KEY;
3378                 found_key.offset = 0;
3379                 inode = btrfs_iget(fs_info->sb, last_objectid, root);
3380                 ret = PTR_ERR_OR_ZERO(inode);
3381                 if (ret && ret != -ENOENT)
3382                         goto out;
3383
3384                 if (ret == -ENOENT && root == fs_info->tree_root) {
3385                         struct btrfs_root *dead_root;
3386                         int is_dead_root = 0;
3387
3388                         /*
3389                          * this is an orphan in the tree root. Currently these
3390                          * could come from 2 sources:
3391                          *  a) a snapshot deletion in progress
3392                          *  b) a free space cache inode
3393                          * We need to distinguish those two, as the snapshot
3394                          * orphan must not get deleted.
3395                          * find_dead_roots already ran before us, so if this
3396                          * is a snapshot deletion, we should find the root
3397                          * in the fs_roots radix tree.
3398                          */
3399
3400                         spin_lock(&fs_info->fs_roots_radix_lock);
3401                         dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3402                                                          (unsigned long)found_key.objectid);
3403                         if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3404                                 is_dead_root = 1;
3405                         spin_unlock(&fs_info->fs_roots_radix_lock);
3406
3407                         if (is_dead_root) {
3408                                 /* prevent this orphan from being found again */
3409                                 key.offset = found_key.objectid - 1;
3410                                 continue;
3411                         }
3412
3413                 }
3414
3415                 /*
3416                  * If we have an inode with links, there are a couple of
3417                  * possibilities. Old kernels (before v3.12) used to create an
3418                  * orphan item for truncate indicating that there were possibly
3419                  * extent items past i_size that needed to be deleted. In v3.12,
3420                  * truncate was changed to update i_size in sync with the extent
3421                  * items, but the (useless) orphan item was still created. Since
3422                  * v4.18, we don't create the orphan item for truncate at all.
3423                  *
3424                  * So, this item could mean that we need to do a truncate, but
3425                  * only if this filesystem was last used on a pre-v3.12 kernel
3426                  * and was not cleanly unmounted. The odds of that are quite
3427                  * slim, and it's a pain to do the truncate now, so just delete
3428                  * the orphan item.
3429                  *
3430                  * It's also possible that this orphan item was supposed to be
3431                  * deleted but wasn't. The inode number may have been reused,
3432                  * but either way, we can delete the orphan item.
3433                  */
3434                 if (ret == -ENOENT || inode->i_nlink) {
3435                         if (!ret)
3436                                 iput(inode);
3437                         trans = btrfs_start_transaction(root, 1);
3438                         if (IS_ERR(trans)) {
3439                                 ret = PTR_ERR(trans);
3440                                 goto out;
3441                         }
3442                         btrfs_debug(fs_info, "auto deleting %Lu",
3443                                     found_key.objectid);
3444                         ret = btrfs_del_orphan_item(trans, root,
3445                                                     found_key.objectid);
3446                         btrfs_end_transaction(trans);
3447                         if (ret)
3448                                 goto out;
3449                         continue;
3450                 }
3451
3452                 nr_unlink++;
3453
3454                 /* this will do delete_inode and everything for us */
3455                 iput(inode);
3456         }
3457         /* release the path since we're done with it */
3458         btrfs_release_path(path);
3459
3460         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3461
3462         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3463                 trans = btrfs_join_transaction(root);
3464                 if (!IS_ERR(trans))
3465                         btrfs_end_transaction(trans);
3466         }
3467
3468         if (nr_unlink)
3469                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3470
3471 out:
3472         if (ret)
3473                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3474         btrfs_free_path(path);
3475         return ret;
3476 }
3477
3478 /*
3479  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3480  * don't find any xattrs, we know there can't be any acls.
3481  *
3482  * slot is the slot the inode is in, objectid is the objectid of the inode
3483  */
3484 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3485                                           int slot, u64 objectid,
3486                                           int *first_xattr_slot)
3487 {
3488         u32 nritems = btrfs_header_nritems(leaf);
3489         struct btrfs_key found_key;
3490         static u64 xattr_access = 0;
3491         static u64 xattr_default = 0;
3492         int scanned = 0;
3493
3494         if (!xattr_access) {
3495                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3496                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3497                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3498                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3499         }
3500
3501         slot++;
3502         *first_xattr_slot = -1;
3503         while (slot < nritems) {
3504                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3505
3506                 /* we found a different objectid, there must not be acls */
3507                 if (found_key.objectid != objectid)
3508                         return 0;
3509
3510                 /* we found an xattr, assume we've got an acl */
3511                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3512                         if (*first_xattr_slot == -1)
3513                                 *first_xattr_slot = slot;
3514                         if (found_key.offset == xattr_access ||
3515                             found_key.offset == xattr_default)
3516                                 return 1;
3517                 }
3518
3519                 /*
3520                  * we found a key greater than an xattr key, there can't
3521                  * be any acls later on
3522                  */
3523                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3524                         return 0;
3525
3526                 slot++;
3527                 scanned++;
3528
3529                 /*
3530                  * it goes inode, inode backrefs, xattrs, extents,
3531                  * so if there are a ton of hard links to an inode there can
3532                  * be a lot of backrefs.  Don't waste time searching too hard,
3533                  * this is just an optimization
3534                  */
3535                 if (scanned >= 8)
3536                         break;
3537         }
3538         /* we hit the end of the leaf before we found an xattr or
3539          * something larger than an xattr.  We have to assume the inode
3540          * has acls
3541          */
3542         if (*first_xattr_slot == -1)
3543                 *first_xattr_slot = slot;
3544         return 1;
3545 }
3546
3547 /*
3548  * read an inode from the btree into the in-memory inode
3549  */
3550 static int btrfs_read_locked_inode(struct inode *inode,
3551                                    struct btrfs_path *in_path)
3552 {
3553         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3554         struct btrfs_path *path = in_path;
3555         struct extent_buffer *leaf;
3556         struct btrfs_inode_item *inode_item;
3557         struct btrfs_root *root = BTRFS_I(inode)->root;
3558         struct btrfs_key location;
3559         unsigned long ptr;
3560         int maybe_acls;
3561         u32 rdev;
3562         int ret;
3563         bool filled = false;
3564         int first_xattr_slot;
3565
3566         ret = btrfs_fill_inode(inode, &rdev);
3567         if (!ret)
3568                 filled = true;
3569
3570         if (!path) {
3571                 path = btrfs_alloc_path();
3572                 if (!path)
3573                         return -ENOMEM;
3574         }
3575
3576         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3577
3578         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3579         if (ret) {
3580                 if (path != in_path)
3581                         btrfs_free_path(path);
3582                 return ret;
3583         }
3584
3585         leaf = path->nodes[0];
3586
3587         if (filled)
3588                 goto cache_index;
3589
3590         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3591                                     struct btrfs_inode_item);
3592         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3593         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3594         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3595         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3596         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3597         btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3598                         round_up(i_size_read(inode), fs_info->sectorsize));
3599
3600         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3601         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3602
3603         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3604         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3605
3606         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3607         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3608
3609         BTRFS_I(inode)->i_otime.tv_sec =
3610                 btrfs_timespec_sec(leaf, &inode_item->otime);
3611         BTRFS_I(inode)->i_otime.tv_nsec =
3612                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3613
3614         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3615         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3616         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3617
3618         inode_set_iversion_queried(inode,
3619                                    btrfs_inode_sequence(leaf, inode_item));
3620         inode->i_generation = BTRFS_I(inode)->generation;
3621         inode->i_rdev = 0;
3622         rdev = btrfs_inode_rdev(leaf, inode_item);
3623
3624         BTRFS_I(inode)->index_cnt = (u64)-1;
3625         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3626
3627 cache_index:
3628         /*
3629          * If we were modified in the current generation and evicted from memory
3630          * and then re-read we need to do a full sync since we don't have any
3631          * idea about which extents were modified before we were evicted from
3632          * cache.
3633          *
3634          * This is required for both inode re-read from disk and delayed inode
3635          * in delayed_nodes_tree.
3636          */
3637         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3638                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3639                         &BTRFS_I(inode)->runtime_flags);
3640
3641         /*
3642          * We don't persist the id of the transaction where an unlink operation
3643          * against the inode was last made. So here we assume the inode might
3644          * have been evicted, and therefore the exact value of last_unlink_trans
3645          * lost, and set it to last_trans to avoid metadata inconsistencies
3646          * between the inode and its parent if the inode is fsync'ed and the log
3647          * replayed. For example, in the scenario:
3648          *
3649          * touch mydir/foo
3650          * ln mydir/foo mydir/bar
3651          * sync
3652          * unlink mydir/bar
3653          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3654          * xfs_io -c fsync mydir/foo
3655          * <power failure>
3656          * mount fs, triggers fsync log replay
3657          *
3658          * We must make sure that when we fsync our inode foo we also log its
3659          * parent inode, otherwise after log replay the parent still has the
3660          * dentry with the "bar" name but our inode foo has a link count of 1
3661          * and doesn't have an inode ref with the name "bar" anymore.
3662          *
3663          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3664          * but it guarantees correctness at the expense of occasional full
3665          * transaction commits on fsync if our inode is a directory, or if our
3666          * inode is not a directory, logging its parent unnecessarily.
3667          */
3668         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3669
3670         /*
3671          * Same logic as for last_unlink_trans. We don't persist the generation
3672          * of the last transaction where this inode was used for a reflink
3673          * operation, so after eviction and reloading the inode we must be
3674          * pessimistic and assume the last transaction that modified the inode.
3675          */
3676         BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
3677
3678         path->slots[0]++;
3679         if (inode->i_nlink != 1 ||
3680             path->slots[0] >= btrfs_header_nritems(leaf))
3681                 goto cache_acl;
3682
3683         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3684         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3685                 goto cache_acl;
3686
3687         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3688         if (location.type == BTRFS_INODE_REF_KEY) {
3689                 struct btrfs_inode_ref *ref;
3690
3691                 ref = (struct btrfs_inode_ref *)ptr;
3692                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3693         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3694                 struct btrfs_inode_extref *extref;
3695
3696                 extref = (struct btrfs_inode_extref *)ptr;
3697                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3698                                                                      extref);
3699         }
3700 cache_acl:
3701         /*
3702          * try to precache a NULL acl entry for files that don't have
3703          * any xattrs or acls
3704          */
3705         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3706                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3707         if (first_xattr_slot != -1) {
3708                 path->slots[0] = first_xattr_slot;
3709                 ret = btrfs_load_inode_props(inode, path);
3710                 if (ret)
3711                         btrfs_err(fs_info,
3712                                   "error loading props for ino %llu (root %llu): %d",
3713                                   btrfs_ino(BTRFS_I(inode)),
3714                                   root->root_key.objectid, ret);
3715         }
3716         if (path != in_path)
3717                 btrfs_free_path(path);
3718
3719         if (!maybe_acls)
3720                 cache_no_acl(inode);
3721
3722         switch (inode->i_mode & S_IFMT) {
3723         case S_IFREG:
3724                 inode->i_mapping->a_ops = &btrfs_aops;
3725                 inode->i_fop = &btrfs_file_operations;
3726                 inode->i_op = &btrfs_file_inode_operations;
3727                 break;
3728         case S_IFDIR:
3729                 inode->i_fop = &btrfs_dir_file_operations;
3730                 inode->i_op = &btrfs_dir_inode_operations;
3731                 break;
3732         case S_IFLNK:
3733                 inode->i_op = &btrfs_symlink_inode_operations;
3734                 inode_nohighmem(inode);
3735                 inode->i_mapping->a_ops = &btrfs_aops;
3736                 break;
3737         default:
3738                 inode->i_op = &btrfs_special_inode_operations;
3739                 init_special_inode(inode, inode->i_mode, rdev);
3740                 break;
3741         }
3742
3743         btrfs_sync_inode_flags_to_i_flags(inode);
3744         return 0;
3745 }
3746
3747 /*
3748  * given a leaf and an inode, copy the inode fields into the leaf
3749  */
3750 static void fill_inode_item(struct btrfs_trans_handle *trans,
3751                             struct extent_buffer *leaf,
3752                             struct btrfs_inode_item *item,
3753                             struct inode *inode)
3754 {
3755         struct btrfs_map_token token;
3756
3757         btrfs_init_map_token(&token, leaf);
3758
3759         btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3760         btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3761         btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3762         btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3763         btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3764
3765         btrfs_set_token_timespec_sec(&token, &item->atime,
3766                                      inode->i_atime.tv_sec);
3767         btrfs_set_token_timespec_nsec(&token, &item->atime,
3768                                       inode->i_atime.tv_nsec);
3769
3770         btrfs_set_token_timespec_sec(&token, &item->mtime,
3771                                      inode->i_mtime.tv_sec);
3772         btrfs_set_token_timespec_nsec(&token, &item->mtime,
3773                                       inode->i_mtime.tv_nsec);
3774
3775         btrfs_set_token_timespec_sec(&token, &item->ctime,
3776                                      inode->i_ctime.tv_sec);
3777         btrfs_set_token_timespec_nsec(&token, &item->ctime,
3778                                       inode->i_ctime.tv_nsec);
3779
3780         btrfs_set_token_timespec_sec(&token, &item->otime,
3781                                      BTRFS_I(inode)->i_otime.tv_sec);
3782         btrfs_set_token_timespec_nsec(&token, &item->otime,
3783                                       BTRFS_I(inode)->i_otime.tv_nsec);
3784
3785         btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3786         btrfs_set_token_inode_generation(&token, item,
3787                                          BTRFS_I(inode)->generation);
3788         btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3789         btrfs_set_token_inode_transid(&token, item, trans->transid);
3790         btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3791         btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3792         btrfs_set_token_inode_block_group(&token, item, 0);
3793 }
3794
3795 /*
3796  * copy everything in the in-memory inode into the btree.
3797  */
3798 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3799                                 struct btrfs_root *root,
3800                                 struct btrfs_inode *inode)
3801 {
3802         struct btrfs_inode_item *inode_item;
3803         struct btrfs_path *path;
3804         struct extent_buffer *leaf;
3805         int ret;
3806
3807         path = btrfs_alloc_path();
3808         if (!path)
3809                 return -ENOMEM;
3810
3811         ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
3812         if (ret) {
3813                 if (ret > 0)
3814                         ret = -ENOENT;
3815                 goto failed;
3816         }
3817
3818         leaf = path->nodes[0];
3819         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3820                                     struct btrfs_inode_item);
3821
3822         fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
3823         btrfs_mark_buffer_dirty(leaf);
3824         btrfs_set_inode_last_trans(trans, inode);
3825         ret = 0;
3826 failed:
3827         btrfs_free_path(path);
3828         return ret;
3829 }
3830
3831 /*
3832  * copy everything in the in-memory inode into the btree.
3833  */
3834 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3835                                 struct btrfs_root *root,
3836                                 struct btrfs_inode *inode)
3837 {
3838         struct btrfs_fs_info *fs_info = root->fs_info;
3839         int ret;
3840
3841         /*
3842          * If the inode is a free space inode, we can deadlock during commit
3843          * if we put it into the delayed code.
3844          *
3845          * The data relocation inode should also be directly updated
3846          * without delay
3847          */
3848         if (!btrfs_is_free_space_inode(inode)
3849             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3850             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3851                 btrfs_update_root_times(trans, root);
3852
3853                 ret = btrfs_delayed_update_inode(trans, root, inode);
3854                 if (!ret)
3855                         btrfs_set_inode_last_trans(trans, inode);
3856                 return ret;
3857         }
3858
3859         return btrfs_update_inode_item(trans, root, inode);
3860 }
3861
3862 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3863                                 struct btrfs_root *root, struct btrfs_inode *inode)
3864 {
3865         int ret;
3866
3867         ret = btrfs_update_inode(trans, root, inode);
3868         if (ret == -ENOSPC)
3869                 return btrfs_update_inode_item(trans, root, inode);
3870         return ret;
3871 }
3872
3873 /*
3874  * unlink helper that gets used here in inode.c and in the tree logging
3875  * recovery code.  It remove a link in a directory with a given name, and
3876  * also drops the back refs in the inode to the directory
3877  */
3878 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3879                                 struct btrfs_root *root,
3880                                 struct btrfs_inode *dir,
3881                                 struct btrfs_inode *inode,
3882                                 const char *name, int name_len)
3883 {
3884         struct btrfs_fs_info *fs_info = root->fs_info;
3885         struct btrfs_path *path;
3886         int ret = 0;
3887         struct btrfs_dir_item *di;
3888         u64 index;
3889         u64 ino = btrfs_ino(inode);
3890         u64 dir_ino = btrfs_ino(dir);
3891
3892         path = btrfs_alloc_path();
3893         if (!path) {
3894                 ret = -ENOMEM;
3895                 goto out;
3896         }
3897
3898         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3899                                     name, name_len, -1);
3900         if (IS_ERR_OR_NULL(di)) {
3901                 ret = di ? PTR_ERR(di) : -ENOENT;
3902                 goto err;
3903         }
3904         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3905         if (ret)
3906                 goto err;
3907         btrfs_release_path(path);
3908
3909         /*
3910          * If we don't have dir index, we have to get it by looking up
3911          * the inode ref, since we get the inode ref, remove it directly,
3912          * it is unnecessary to do delayed deletion.
3913          *
3914          * But if we have dir index, needn't search inode ref to get it.
3915          * Since the inode ref is close to the inode item, it is better
3916          * that we delay to delete it, and just do this deletion when
3917          * we update the inode item.
3918          */
3919         if (inode->dir_index) {
3920                 ret = btrfs_delayed_delete_inode_ref(inode);
3921                 if (!ret) {
3922                         index = inode->dir_index;
3923                         goto skip_backref;
3924                 }
3925         }
3926
3927         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3928                                   dir_ino, &index);
3929         if (ret) {
3930                 btrfs_info(fs_info,
3931                         "failed to delete reference to %.*s, inode %llu parent %llu",
3932                         name_len, name, ino, dir_ino);
3933                 btrfs_abort_transaction(trans, ret);
3934                 goto err;
3935         }
3936 skip_backref:
3937         ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3938         if (ret) {
3939                 btrfs_abort_transaction(trans, ret);
3940                 goto err;
3941         }
3942
3943         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3944                         dir_ino);
3945         if (ret != 0 && ret != -ENOENT) {
3946                 btrfs_abort_transaction(trans, ret);
3947                 goto err;
3948         }
3949
3950         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3951                         index);
3952         if (ret == -ENOENT)
3953                 ret = 0;
3954         else if (ret)
3955                 btrfs_abort_transaction(trans, ret);
3956
3957         /*
3958          * If we have a pending delayed iput we could end up with the final iput
3959          * being run in btrfs-cleaner context.  If we have enough of these built
3960          * up we can end up burning a lot of time in btrfs-cleaner without any
3961          * way to throttle the unlinks.  Since we're currently holding a ref on
3962          * the inode we can run the delayed iput here without any issues as the
3963          * final iput won't be done until after we drop the ref we're currently
3964          * holding.
3965          */
3966         btrfs_run_delayed_iput(fs_info, inode);
3967 err:
3968         btrfs_free_path(path);
3969         if (ret)
3970                 goto out;
3971
3972         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3973         inode_inc_iversion(&inode->vfs_inode);
3974         inode_inc_iversion(&dir->vfs_inode);
3975         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3976                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3977         ret = btrfs_update_inode(trans, root, dir);
3978 out:
3979         return ret;
3980 }
3981
3982 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3983                        struct btrfs_root *root,
3984                        struct btrfs_inode *dir, struct btrfs_inode *inode,
3985                        const char *name, int name_len)
3986 {
3987         int ret;
3988         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3989         if (!ret) {
3990                 drop_nlink(&inode->vfs_inode);
3991                 ret = btrfs_update_inode(trans, root, inode);
3992         }
3993         return ret;
3994 }
3995
3996 /*
3997  * helper to start transaction for unlink and rmdir.
3998  *
3999  * unlink and rmdir are special in btrfs, they do not always free space, so
4000  * if we cannot make our reservations the normal way try and see if there is
4001  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4002  * allow the unlink to occur.
4003  */
4004 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4005 {
4006         struct btrfs_root *root = BTRFS_I(dir)->root;
4007
4008         /*
4009          * 1 for the possible orphan item
4010          * 1 for the dir item
4011          * 1 for the dir index
4012          * 1 for the inode ref
4013          * 1 for the inode
4014          */
4015         return btrfs_start_transaction_fallback_global_rsv(root, 5);
4016 }
4017
4018 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4019 {
4020         struct btrfs_root *root = BTRFS_I(dir)->root;
4021         struct btrfs_trans_handle *trans;
4022         struct inode *inode = d_inode(dentry);
4023         int ret;
4024
4025         trans = __unlink_start_trans(dir);
4026         if (IS_ERR(trans))
4027                 return PTR_ERR(trans);
4028
4029         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4030                         0);
4031
4032         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4033                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4034                         dentry->d_name.len);
4035         if (ret)
4036                 goto out;
4037
4038         if (inode->i_nlink == 0) {
4039                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4040                 if (ret)
4041                         goto out;
4042         }
4043
4044 out:
4045         btrfs_end_transaction(trans);
4046         btrfs_btree_balance_dirty(root->fs_info);
4047         return ret;
4048 }
4049
4050 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4051                                struct inode *dir, struct dentry *dentry)
4052 {
4053         struct btrfs_root *root = BTRFS_I(dir)->root;
4054         struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4055         struct btrfs_path *path;
4056         struct extent_buffer *leaf;
4057         struct btrfs_dir_item *di;
4058         struct btrfs_key key;
4059         const char *name = dentry->d_name.name;
4060         int name_len = dentry->d_name.len;
4061         u64 index;
4062         int ret;
4063         u64 objectid;
4064         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4065
4066         if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4067                 objectid = inode->root->root_key.objectid;
4068         } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4069                 objectid = inode->location.objectid;
4070         } else {
4071                 WARN_ON(1);
4072                 return -EINVAL;
4073         }
4074
4075         path = btrfs_alloc_path();
4076         if (!path)
4077                 return -ENOMEM;
4078
4079         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4080                                    name, name_len, -1);
4081         if (IS_ERR_OR_NULL(di)) {
4082                 ret = di ? PTR_ERR(di) : -ENOENT;
4083                 goto out;
4084         }
4085
4086         leaf = path->nodes[0];
4087         btrfs_dir_item_key_to_cpu(leaf, di, &key);
4088         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4089         ret = btrfs_delete_one_dir_name(trans, root, path, di);
4090         if (ret) {
4091                 btrfs_abort_transaction(trans, ret);
4092                 goto out;
4093         }
4094         btrfs_release_path(path);
4095
4096         /*
4097          * This is a placeholder inode for a subvolume we didn't have a
4098          * reference to at the time of the snapshot creation.  In the meantime
4099          * we could have renamed the real subvol link into our snapshot, so
4100          * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
4101          * Instead simply lookup the dir_index_item for this entry so we can
4102          * remove it.  Otherwise we know we have a ref to the root and we can
4103          * call btrfs_del_root_ref, and it _shouldn't_ fail.
4104          */
4105         if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4106                 di = btrfs_search_dir_index_item(root, path, dir_ino,
4107                                                  name, name_len);
4108                 if (IS_ERR_OR_NULL(di)) {
4109                         if (!di)
4110                                 ret = -ENOENT;
4111                         else
4112                                 ret = PTR_ERR(di);
4113                         btrfs_abort_transaction(trans, ret);
4114                         goto out;
4115                 }
4116
4117                 leaf = path->nodes[0];
4118                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4119                 index = key.offset;
4120                 btrfs_release_path(path);
4121         } else {
4122                 ret = btrfs_del_root_ref(trans, objectid,
4123                                          root->root_key.objectid, dir_ino,
4124                                          &index, name, name_len);
4125                 if (ret) {
4126                         btrfs_abort_transaction(trans, ret);
4127                         goto out;
4128                 }
4129         }
4130
4131         ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
4132         if (ret) {
4133                 btrfs_abort_transaction(trans, ret);
4134                 goto out;
4135         }
4136
4137         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4138         inode_inc_iversion(dir);
4139         dir->i_mtime = dir->i_ctime = current_time(dir);
4140         ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
4141         if (ret)
4142                 btrfs_abort_transaction(trans, ret);
4143 out:
4144         btrfs_free_path(path);
4145         return ret;
4146 }
4147
4148 /*
4149  * Helper to check if the subvolume references other subvolumes or if it's
4150  * default.
4151  */
4152 static noinline int may_destroy_subvol(struct btrfs_root *root)
4153 {
4154         struct btrfs_fs_info *fs_info = root->fs_info;
4155         struct btrfs_path *path;
4156         struct btrfs_dir_item *di;
4157         struct btrfs_key key;
4158         u64 dir_id;
4159         int ret;
4160
4161         path = btrfs_alloc_path();
4162         if (!path)
4163                 return -ENOMEM;
4164
4165         /* Make sure this root isn't set as the default subvol */
4166         dir_id = btrfs_super_root_dir(fs_info->super_copy);
4167         di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4168                                    dir_id, "default", 7, 0);
4169         if (di && !IS_ERR(di)) {
4170                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4171                 if (key.objectid == root->root_key.objectid) {
4172                         ret = -EPERM;
4173                         btrfs_err(fs_info,
4174                                   "deleting default subvolume %llu is not allowed",
4175                                   key.objectid);
4176                         goto out;
4177                 }
4178                 btrfs_release_path(path);
4179         }
4180
4181         key.objectid = root->root_key.objectid;
4182         key.type = BTRFS_ROOT_REF_KEY;
4183         key.offset = (u64)-1;
4184
4185         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4186         if (ret < 0)
4187                 goto out;
4188         BUG_ON(ret == 0);
4189
4190         ret = 0;
4191         if (path->slots[0] > 0) {
4192                 path->slots[0]--;
4193                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4194                 if (key.objectid == root->root_key.objectid &&
4195                     key.type == BTRFS_ROOT_REF_KEY)
4196                         ret = -ENOTEMPTY;
4197         }
4198 out:
4199         btrfs_free_path(path);
4200         return ret;
4201 }
4202
4203 /* Delete all dentries for inodes belonging to the root */
4204 static void btrfs_prune_dentries(struct btrfs_root *root)
4205 {
4206         struct btrfs_fs_info *fs_info = root->fs_info;
4207         struct rb_node *node;
4208         struct rb_node *prev;
4209         struct btrfs_inode *entry;
4210         struct inode *inode;
4211         u64 objectid = 0;
4212
4213         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4214                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4215
4216         spin_lock(&root->inode_lock);
4217 again:
4218         node = root->inode_tree.rb_node;
4219         prev = NULL;
4220         while (node) {
4221                 prev = node;
4222                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4223
4224                 if (objectid < btrfs_ino(entry))
4225                         node = node->rb_left;
4226                 else if (objectid > btrfs_ino(entry))
4227                         node = node->rb_right;
4228                 else
4229                         break;
4230         }
4231         if (!node) {
4232                 while (prev) {
4233                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
4234                         if (objectid <= btrfs_ino(entry)) {
4235                                 node = prev;
4236                                 break;
4237                         }
4238                         prev = rb_next(prev);
4239                 }
4240         }
4241         while (node) {
4242                 entry = rb_entry(node, struct btrfs_inode, rb_node);
4243                 objectid = btrfs_ino(entry) + 1;
4244                 inode = igrab(&entry->vfs_inode);
4245                 if (inode) {
4246                         spin_unlock(&root->inode_lock);
4247                         if (atomic_read(&inode->i_count) > 1)
4248                                 d_prune_aliases(inode);
4249                         /*
4250                          * btrfs_drop_inode will have it removed from the inode
4251                          * cache when its usage count hits zero.
4252                          */
4253                         iput(inode);
4254                         cond_resched();
4255                         spin_lock(&root->inode_lock);
4256                         goto again;
4257                 }
4258
4259                 if (cond_resched_lock(&root->inode_lock))
4260                         goto again;
4261
4262                 node = rb_next(node);
4263         }
4264         spin_unlock(&root->inode_lock);
4265 }
4266
4267 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4268 {
4269         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4270         struct btrfs_root *root = BTRFS_I(dir)->root;
4271         struct inode *inode = d_inode(dentry);
4272         struct btrfs_root *dest = BTRFS_I(inode)->root;
4273         struct btrfs_trans_handle *trans;
4274         struct btrfs_block_rsv block_rsv;
4275         u64 root_flags;
4276         int ret;
4277
4278         /*
4279          * Don't allow to delete a subvolume with send in progress. This is
4280          * inside the inode lock so the error handling that has to drop the bit
4281          * again is not run concurrently.
4282          */
4283         spin_lock(&dest->root_item_lock);
4284         if (dest->send_in_progress) {
4285                 spin_unlock(&dest->root_item_lock);
4286                 btrfs_warn(fs_info,
4287                            "attempt to delete subvolume %llu during send",
4288                            dest->root_key.objectid);
4289                 return -EPERM;
4290         }
4291         root_flags = btrfs_root_flags(&dest->root_item);
4292         btrfs_set_root_flags(&dest->root_item,
4293                              root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4294         spin_unlock(&dest->root_item_lock);
4295
4296         down_write(&fs_info->subvol_sem);
4297
4298         ret = may_destroy_subvol(dest);
4299         if (ret)
4300                 goto out_up_write;
4301
4302         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4303         /*
4304          * One for dir inode,
4305          * two for dir entries,
4306          * two for root ref/backref.
4307          */
4308         ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4309         if (ret)
4310                 goto out_up_write;
4311
4312         trans = btrfs_start_transaction(root, 0);
4313         if (IS_ERR(trans)) {
4314                 ret = PTR_ERR(trans);
4315                 goto out_release;
4316         }
4317         trans->block_rsv = &block_rsv;
4318         trans->bytes_reserved = block_rsv.size;
4319
4320         btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4321
4322         ret = btrfs_unlink_subvol(trans, dir, dentry);
4323         if (ret) {
4324                 btrfs_abort_transaction(trans, ret);
4325                 goto out_end_trans;
4326         }
4327
4328         btrfs_record_root_in_trans(trans, dest);
4329
4330         memset(&dest->root_item.drop_progress, 0,
4331                 sizeof(dest->root_item.drop_progress));
4332         btrfs_set_root_drop_level(&dest->root_item, 0);
4333         btrfs_set_root_refs(&dest->root_item, 0);
4334
4335         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4336                 ret = btrfs_insert_orphan_item(trans,
4337                                         fs_info->tree_root,
4338                                         dest->root_key.objectid);
4339                 if (ret) {
4340                         btrfs_abort_transaction(trans, ret);
4341                         goto out_end_trans;
4342                 }
4343         }
4344
4345         ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4346                                   BTRFS_UUID_KEY_SUBVOL,
4347                                   dest->root_key.objectid);
4348         if (ret && ret != -ENOENT) {
4349                 btrfs_abort_transaction(trans, ret);
4350                 goto out_end_trans;
4351         }
4352         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4353                 ret = btrfs_uuid_tree_remove(trans,
4354                                           dest->root_item.received_uuid,
4355                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4356                                           dest->root_key.objectid);
4357                 if (ret && ret != -ENOENT) {
4358                         btrfs_abort_transaction(trans, ret);
4359                         goto out_end_trans;
4360                 }
4361         }
4362
4363         free_anon_bdev(dest->anon_dev);
4364         dest->anon_dev = 0;
4365 out_end_trans:
4366         trans->block_rsv = NULL;
4367         trans->bytes_reserved = 0;
4368         ret = btrfs_end_transaction(trans);
4369         inode->i_flags |= S_DEAD;
4370 out_release:
4371         btrfs_subvolume_release_metadata(root, &block_rsv);
4372 out_up_write:
4373         up_write(&fs_info->subvol_sem);
4374         if (ret) {
4375                 spin_lock(&dest->root_item_lock);
4376                 root_flags = btrfs_root_flags(&dest->root_item);
4377                 btrfs_set_root_flags(&dest->root_item,
4378                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4379                 spin_unlock(&dest->root_item_lock);
4380         } else {
4381                 d_invalidate(dentry);
4382                 btrfs_prune_dentries(dest);
4383                 ASSERT(dest->send_in_progress == 0);
4384         }
4385
4386         return ret;
4387 }
4388
4389 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4390 {
4391         struct inode *inode = d_inode(dentry);
4392         int err = 0;
4393         struct btrfs_root *root = BTRFS_I(dir)->root;
4394         struct btrfs_trans_handle *trans;
4395         u64 last_unlink_trans;
4396
4397         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4398                 return -ENOTEMPTY;
4399         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4400                 return btrfs_delete_subvolume(dir, dentry);
4401
4402         trans = __unlink_start_trans(dir);
4403         if (IS_ERR(trans))
4404                 return PTR_ERR(trans);
4405
4406         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4407                 err = btrfs_unlink_subvol(trans, dir, dentry);
4408                 goto out;
4409         }
4410
4411         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4412         if (err)
4413                 goto out;
4414
4415         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4416
4417         /* now the directory is empty */
4418         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4419                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4420                         dentry->d_name.len);
4421         if (!err) {
4422                 btrfs_i_size_write(BTRFS_I(inode), 0);
4423                 /*
4424                  * Propagate the last_unlink_trans value of the deleted dir to
4425                  * its parent directory. This is to prevent an unrecoverable
4426                  * log tree in the case we do something like this:
4427                  * 1) create dir foo
4428                  * 2) create snapshot under dir foo
4429                  * 3) delete the snapshot
4430                  * 4) rmdir foo
4431                  * 5) mkdir foo
4432                  * 6) fsync foo or some file inside foo
4433                  */
4434                 if (last_unlink_trans >= trans->transid)
4435                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4436         }
4437 out:
4438         btrfs_end_transaction(trans);
4439         btrfs_btree_balance_dirty(root->fs_info);
4440
4441         return err;
4442 }
4443
4444 /*
4445  * Return this if we need to call truncate_block for the last bit of the
4446  * truncate.
4447  */
4448 #define NEED_TRUNCATE_BLOCK 1
4449
4450 /*
4451  * this can truncate away extent items, csum items and directory items.
4452  * It starts at a high offset and removes keys until it can't find
4453  * any higher than new_size
4454  *
4455  * csum items that cross the new i_size are truncated to the new size
4456  * as well.
4457  *
4458  * min_type is the minimum key type to truncate down to.  If set to 0, this
4459  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4460  */
4461 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4462                                struct btrfs_root *root,
4463                                struct btrfs_inode *inode,
4464                                u64 new_size, u32 min_type)
4465 {
4466         struct btrfs_fs_info *fs_info = root->fs_info;
4467         struct btrfs_path *path;
4468         struct extent_buffer *leaf;
4469         struct btrfs_file_extent_item *fi;
4470         struct btrfs_key key;
4471         struct btrfs_key found_key;
4472         u64 extent_start = 0;
4473         u64 extent_num_bytes = 0;
4474         u64 extent_offset = 0;
4475         u64 item_end = 0;
4476         u64 last_size = new_size;
4477         u32 found_type = (u8)-1;
4478         int found_extent;
4479         int del_item;
4480         int pending_del_nr = 0;
4481         int pending_del_slot = 0;
4482         int extent_type = -1;
4483         int ret;
4484         u64 ino = btrfs_ino(inode);
4485         u64 bytes_deleted = 0;
4486         bool be_nice = false;
4487         bool should_throttle = false;
4488         const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4489         struct extent_state *cached_state = NULL;
4490
4491         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4492
4493         /*
4494          * For non-free space inodes and non-shareable roots, we want to back
4495          * off from time to time.  This means all inodes in subvolume roots,
4496          * reloc roots, and data reloc roots.
4497          */
4498         if (!btrfs_is_free_space_inode(inode) &&
4499             test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4500                 be_nice = true;
4501
4502         path = btrfs_alloc_path();
4503         if (!path)
4504                 return -ENOMEM;
4505         path->reada = READA_BACK;
4506
4507         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4508                 lock_extent_bits(&inode->io_tree, lock_start, (u64)-1,
4509                                  &cached_state);
4510
4511                 /*
4512                  * We want to drop from the next block forward in case this
4513                  * new size is not block aligned since we will be keeping the
4514                  * last block of the extent just the way it is.
4515                  */
4516                 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4517                                         fs_info->sectorsize),
4518                                         (u64)-1, 0);
4519         }
4520
4521         /*
4522          * This function is also used to drop the items in the log tree before
4523          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4524          * it is used to drop the logged items. So we shouldn't kill the delayed
4525          * items.
4526          */
4527         if (min_type == 0 && root == inode->root)
4528                 btrfs_kill_delayed_inode_items(inode);
4529
4530         key.objectid = ino;
4531         key.offset = (u64)-1;
4532         key.type = (u8)-1;
4533
4534 search_again:
4535         /*
4536          * with a 16K leaf size and 128MB extents, you can actually queue
4537          * up a huge file in a single leaf.  Most of the time that
4538          * bytes_deleted is > 0, it will be huge by the time we get here
4539          */
4540         if (be_nice && bytes_deleted > SZ_32M &&
4541             btrfs_should_end_transaction(trans)) {
4542                 ret = -EAGAIN;
4543                 goto out;
4544         }
4545
4546         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4547         if (ret < 0)
4548                 goto out;
4549
4550         if (ret > 0) {
4551                 ret = 0;
4552                 /* there are no items in the tree for us to truncate, we're
4553                  * done
4554                  */
4555                 if (path->slots[0] == 0)
4556                         goto out;
4557                 path->slots[0]--;
4558         }
4559
4560         while (1) {
4561                 u64 clear_start = 0, clear_len = 0;
4562
4563                 fi = NULL;
4564                 leaf = path->nodes[0];
4565                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4566                 found_type = found_key.type;
4567
4568                 if (found_key.objectid != ino)
4569                         break;
4570
4571                 if (found_type < min_type)
4572                         break;
4573
4574                 item_end = found_key.offset;
4575                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4576                         fi = btrfs_item_ptr(leaf, path->slots[0],
4577                                             struct btrfs_file_extent_item);
4578                         extent_type = btrfs_file_extent_type(leaf, fi);
4579                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4580                                 item_end +=
4581                                     btrfs_file_extent_num_bytes(leaf, fi);
4582
4583                                 trace_btrfs_truncate_show_fi_regular(
4584                                         inode, leaf, fi, found_key.offset);
4585                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4586                                 item_end += btrfs_file_extent_ram_bytes(leaf,
4587                                                                         fi);
4588
4589                                 trace_btrfs_truncate_show_fi_inline(
4590                                         inode, leaf, fi, path->slots[0],
4591                                         found_key.offset);
4592                         }
4593                         item_end--;
4594                 }
4595                 if (found_type > min_type) {
4596                         del_item = 1;
4597                 } else {
4598                         if (item_end < new_size)
4599                                 break;
4600                         if (found_key.offset >= new_size)
4601                                 del_item = 1;
4602                         else
4603                                 del_item = 0;
4604                 }
4605                 found_extent = 0;
4606                 /* FIXME, shrink the extent if the ref count is only 1 */
4607                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4608                         goto delete;
4609
4610                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4611                         u64 num_dec;
4612
4613                         clear_start = found_key.offset;
4614                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4615                         if (!del_item) {
4616                                 u64 orig_num_bytes =
4617                                         btrfs_file_extent_num_bytes(leaf, fi);
4618                                 extent_num_bytes = ALIGN(new_size -
4619                                                 found_key.offset,
4620                                                 fs_info->sectorsize);
4621                                 clear_start = ALIGN(new_size, fs_info->sectorsize);
4622                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4623                                                          extent_num_bytes);
4624                                 num_dec = (orig_num_bytes -
4625                                            extent_num_bytes);
4626                                 if (test_bit(BTRFS_ROOT_SHAREABLE,
4627                                              &root->state) &&
4628                                     extent_start != 0)
4629                                         inode_sub_bytes(&inode->vfs_inode,
4630                                                         num_dec);
4631                                 btrfs_mark_buffer_dirty(leaf);
4632                         } else {
4633                                 extent_num_bytes =
4634                                         btrfs_file_extent_disk_num_bytes(leaf,
4635                                                                          fi);
4636                                 extent_offset = found_key.offset -
4637                                         btrfs_file_extent_offset(leaf, fi);
4638
4639                                 /* FIXME blocksize != 4096 */
4640                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4641                                 if (extent_start != 0) {
4642                                         found_extent = 1;
4643                                         if (test_bit(BTRFS_ROOT_SHAREABLE,
4644                                                      &root->state))
4645                                                 inode_sub_bytes(&inode->vfs_inode,
4646                                                                 num_dec);
4647                                 }
4648                         }
4649                         clear_len = num_dec;
4650                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4651                         /*
4652                          * we can't truncate inline items that have had
4653                          * special encodings
4654                          */
4655                         if (!del_item &&
4656                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4657                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4658                             btrfs_file_extent_compression(leaf, fi) == 0) {
4659                                 u32 size = (u32)(new_size - found_key.offset);
4660
4661                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4662                                 size = btrfs_file_extent_calc_inline_size(size);
4663                                 btrfs_truncate_item(path, size, 1);
4664                         } else if (!del_item) {
4665                                 /*
4666                                  * We have to bail so the last_size is set to
4667                                  * just before this extent.
4668                                  */
4669                                 ret = NEED_TRUNCATE_BLOCK;
4670                                 break;
4671                         } else {
4672                                 /*
4673                                  * Inline extents are special, we just treat
4674                                  * them as a full sector worth in the file
4675                                  * extent tree just for simplicity sake.
4676                                  */
4677                                 clear_len = fs_info->sectorsize;
4678                         }
4679
4680                         if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4681                                 inode_sub_bytes(&inode->vfs_inode,
4682                                                 item_end + 1 - new_size);
4683                 }
4684 delete:
4685                 /*
4686                  * We use btrfs_truncate_inode_items() to clean up log trees for
4687                  * multiple fsyncs, and in this case we don't want to clear the
4688                  * file extent range because it's just the log.
4689                  */
4690                 if (root == inode->root) {
4691                         ret = btrfs_inode_clear_file_extent_range(inode,
4692                                                   clear_start, clear_len);
4693                         if (ret) {
4694                                 btrfs_abort_transaction(trans, ret);
4695                                 break;
4696                         }
4697                 }
4698
4699                 if (del_item)
4700                         last_size = found_key.offset;
4701                 else
4702                         last_size = new_size;
4703                 if (del_item) {
4704                         if (!pending_del_nr) {
4705                                 /* no pending yet, add ourselves */
4706                                 pending_del_slot = path->slots[0];
4707                                 pending_del_nr = 1;
4708                         } else if (pending_del_nr &&
4709                                    path->slots[0] + 1 == pending_del_slot) {
4710                                 /* hop on the pending chunk */
4711                                 pending_del_nr++;
4712                                 pending_del_slot = path->slots[0];
4713                         } else {
4714                                 BUG();
4715                         }
4716                 } else {
4717                         break;
4718                 }
4719                 should_throttle = false;
4720
4721                 if (found_extent &&
4722                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4723                         struct btrfs_ref ref = { 0 };
4724
4725                         bytes_deleted += extent_num_bytes;
4726
4727                         btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4728                                         extent_start, extent_num_bytes, 0);
4729                         ref.real_root = root->root_key.objectid;
4730                         btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4731                                         ino, extent_offset);
4732                         ret = btrfs_free_extent(trans, &ref);
4733                         if (ret) {
4734                                 btrfs_abort_transaction(trans, ret);
4735                                 break;
4736                         }
4737                         if (be_nice) {
4738                                 if (btrfs_should_throttle_delayed_refs(trans))
4739                                         should_throttle = true;
4740                         }
4741                 }
4742
4743                 if (found_type == BTRFS_INODE_ITEM_KEY)
4744                         break;
4745
4746                 if (path->slots[0] == 0 ||
4747                     path->slots[0] != pending_del_slot ||
4748                     should_throttle) {
4749                         if (pending_del_nr) {
4750                                 ret = btrfs_del_items(trans, root, path,
4751                                                 pending_del_slot,
4752                                                 pending_del_nr);
4753                                 if (ret) {
4754                                         btrfs_abort_transaction(trans, ret);
4755                                         break;
4756                                 }
4757                                 pending_del_nr = 0;
4758                         }
4759                         btrfs_release_path(path);
4760
4761                         /*
4762                          * We can generate a lot of delayed refs, so we need to
4763                          * throttle every once and a while and make sure we're
4764                          * adding enough space to keep up with the work we are
4765                          * generating.  Since we hold a transaction here we
4766                          * can't flush, and we don't want to FLUSH_LIMIT because
4767                          * we could have generated too many delayed refs to
4768                          * actually allocate, so just bail if we're short and
4769                          * let the normal reservation dance happen higher up.
4770                          */
4771                         if (should_throttle) {
4772                                 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4773                                                         BTRFS_RESERVE_NO_FLUSH);
4774                                 if (ret) {
4775                                         ret = -EAGAIN;
4776                                         break;
4777                                 }
4778                         }
4779                         goto search_again;
4780                 } else {
4781                         path->slots[0]--;
4782                 }
4783         }
4784 out:
4785         if (ret >= 0 && pending_del_nr) {
4786                 int err;
4787
4788                 err = btrfs_del_items(trans, root, path, pending_del_slot,
4789                                       pending_del_nr);
4790                 if (err) {
4791                         btrfs_abort_transaction(trans, err);
4792                         ret = err;
4793                 }
4794         }
4795         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4796                 ASSERT(last_size >= new_size);
4797                 if (!ret && last_size > new_size)
4798                         last_size = new_size;
4799                 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4800                 unlock_extent_cached(&inode->io_tree, lock_start, (u64)-1,
4801                                      &cached_state);
4802         }
4803
4804         btrfs_free_path(path);
4805         return ret;
4806 }
4807
4808 /*
4809  * btrfs_truncate_block - read, zero a chunk and write a block
4810  * @inode - inode that we're zeroing
4811  * @from - the offset to start zeroing
4812  * @len - the length to zero, 0 to zero the entire range respective to the
4813  *      offset
4814  * @front - zero up to the offset instead of from the offset on
4815  *
4816  * This will find the block for the "from" offset and cow the block and zero the
4817  * part we want to zero.  This is used with truncate and hole punching.
4818  */
4819 int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
4820                          int front)
4821 {
4822         struct btrfs_fs_info *fs_info = inode->root->fs_info;
4823         struct address_space *mapping = inode->vfs_inode.i_mapping;
4824         struct extent_io_tree *io_tree = &inode->io_tree;
4825         struct btrfs_ordered_extent *ordered;
4826         struct extent_state *cached_state = NULL;
4827         struct extent_changeset *data_reserved = NULL;
4828         char *kaddr;
4829         bool only_release_metadata = false;
4830         u32 blocksize = fs_info->sectorsize;
4831         pgoff_t index = from >> PAGE_SHIFT;
4832         unsigned offset = from & (blocksize - 1);
4833         struct page *page;
4834         gfp_t mask = btrfs_alloc_write_mask(mapping);
4835         size_t write_bytes = blocksize;
4836         int ret = 0;
4837         u64 block_start;
4838         u64 block_end;
4839
4840         if (IS_ALIGNED(offset, blocksize) &&
4841             (!len || IS_ALIGNED(len, blocksize)))
4842                 goto out;
4843
4844         block_start = round_down(from, blocksize);
4845         block_end = block_start + blocksize - 1;
4846
4847         ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4848                                           blocksize);
4849         if (ret < 0) {
4850                 if (btrfs_check_nocow_lock(inode, block_start, &write_bytes) > 0) {
4851                         /* For nocow case, no need to reserve data space */
4852                         only_release_metadata = true;
4853                 } else {
4854                         goto out;
4855                 }
4856         }
4857         ret = btrfs_delalloc_reserve_metadata(inode, blocksize);
4858         if (ret < 0) {
4859                 if (!only_release_metadata)
4860                         btrfs_free_reserved_data_space(inode, data_reserved,
4861                                                        block_start, blocksize);
4862                 goto out;
4863         }
4864 again:
4865         page = find_or_create_page(mapping, index, mask);
4866         if (!page) {
4867                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4868                                              blocksize, true);
4869                 btrfs_delalloc_release_extents(inode, blocksize);
4870                 ret = -ENOMEM;
4871                 goto out;
4872         }
4873         ret = set_page_extent_mapped(page);
4874         if (ret < 0)
4875                 goto out_unlock;
4876
4877         if (!PageUptodate(page)) {
4878                 ret = btrfs_readpage(NULL, page);
4879                 lock_page(page);
4880                 if (page->mapping != mapping) {
4881                         unlock_page(page);
4882                         put_page(page);
4883                         goto again;
4884                 }
4885                 if (!PageUptodate(page)) {
4886                         ret = -EIO;
4887                         goto out_unlock;
4888                 }
4889         }
4890         wait_on_page_writeback(page);
4891
4892         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4893
4894         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4895         if (ordered) {
4896                 unlock_extent_cached(io_tree, block_start, block_end,
4897                                      &cached_state);
4898                 unlock_page(page);
4899                 put_page(page);
4900                 btrfs_start_ordered_extent(ordered, 1);
4901                 btrfs_put_ordered_extent(ordered);
4902                 goto again;
4903         }
4904
4905         clear_extent_bit(&inode->io_tree, block_start, block_end,
4906                          EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4907                          0, 0, &cached_state);
4908
4909         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4910                                         &cached_state);
4911         if (ret) {
4912                 unlock_extent_cached(io_tree, block_start, block_end,
4913                                      &cached_state);
4914                 goto out_unlock;
4915         }
4916
4917         if (offset != blocksize) {
4918                 if (!len)
4919                         len = blocksize - offset;
4920                 kaddr = kmap(page);
4921                 if (front)
4922                         memset(kaddr + (block_start - page_offset(page)),
4923                                 0, offset);
4924                 else
4925                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4926                                 0, len);
4927                 flush_dcache_page(page);
4928                 kunmap(page);
4929         }
4930         ClearPageChecked(page);
4931         set_page_dirty(page);
4932         unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4933
4934         if (only_release_metadata)
4935                 set_extent_bit(&inode->io_tree, block_start, block_end,
4936                                EXTENT_NORESERVE, 0, NULL, NULL, GFP_NOFS, NULL);
4937
4938 out_unlock:
4939         if (ret) {
4940                 if (only_release_metadata)
4941                         btrfs_delalloc_release_metadata(inode, blocksize, true);
4942                 else
4943                         btrfs_delalloc_release_space(inode, data_reserved,
4944                                         block_start, blocksize, true);
4945         }
4946         btrfs_delalloc_release_extents(inode, blocksize);
4947         unlock_page(page);
4948         put_page(page);
4949 out:
4950         if (only_release_metadata)
4951                 btrfs_check_nocow_unlock(inode);
4952         extent_changeset_free(data_reserved);
4953         return ret;
4954 }
4955
4956 static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
4957                              u64 offset, u64 len)
4958 {
4959         struct btrfs_fs_info *fs_info = root->fs_info;
4960         struct btrfs_trans_handle *trans;
4961         struct btrfs_drop_extents_args drop_args = { 0 };
4962         int ret;
4963
4964         /*
4965          * Still need to make sure the inode looks like it's been updated so
4966          * that any holes get logged if we fsync.
4967          */
4968         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4969                 inode->last_trans = fs_info->generation;
4970                 inode->last_sub_trans = root->log_transid;
4971                 inode->last_log_commit = root->last_log_commit;
4972                 return 0;
4973         }
4974
4975         /*
4976          * 1 - for the one we're dropping
4977          * 1 - for the one we're adding
4978          * 1 - for updating the inode.
4979          */
4980         trans = btrfs_start_transaction(root, 3);
4981         if (IS_ERR(trans))
4982                 return PTR_ERR(trans);
4983
4984         drop_args.start = offset;
4985         drop_args.end = offset + len;
4986         drop_args.drop_cache = true;
4987
4988         ret = btrfs_drop_extents(trans, root, inode, &drop_args);
4989         if (ret) {
4990                 btrfs_abort_transaction(trans, ret);
4991                 btrfs_end_transaction(trans);
4992                 return ret;
4993         }
4994
4995         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode),
4996                         offset, 0, 0, len, 0, len, 0, 0, 0);
4997         if (ret) {
4998                 btrfs_abort_transaction(trans, ret);
4999         } else {
5000                 btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5001                 btrfs_update_inode(trans, root, inode);
5002         }
5003         btrfs_end_transaction(trans);
5004         return ret;
5005 }
5006
5007 /*
5008  * This function puts in dummy file extents for the area we're creating a hole
5009  * for.  So if we are truncating this file to a larger size we need to insert
5010  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5011  * the range between oldsize and size
5012  */
5013 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5014 {
5015         struct btrfs_root *root = inode->root;
5016         struct btrfs_fs_info *fs_info = root->fs_info;
5017         struct extent_io_tree *io_tree = &inode->io_tree;
5018         struct extent_map *em = NULL;
5019         struct extent_state *cached_state = NULL;
5020         struct extent_map_tree *em_tree = &inode->extent_tree;
5021         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5022         u64 block_end = ALIGN(size, fs_info->sectorsize);
5023         u64 last_byte;
5024         u64 cur_offset;
5025         u64 hole_size;
5026         int err = 0;
5027
5028         /*
5029          * If our size started in the middle of a block we need to zero out the
5030          * rest of the block before we expand the i_size, otherwise we could
5031          * expose stale data.
5032          */
5033         err = btrfs_truncate_block(inode, oldsize, 0, 0);
5034         if (err)
5035                 return err;
5036
5037         if (size <= hole_start)
5038                 return 0;
5039
5040         btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5041                                            &cached_state);
5042         cur_offset = hole_start;
5043         while (1) {
5044                 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
5045                                       block_end - cur_offset);
5046                 if (IS_ERR(em)) {
5047                         err = PTR_ERR(em);
5048                         em = NULL;
5049                         break;
5050                 }
5051                 last_byte = min(extent_map_end(em), block_end);
5052                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5053                 hole_size = last_byte - cur_offset;
5054
5055                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5056                         struct extent_map *hole_em;
5057
5058                         err = maybe_insert_hole(root, inode, cur_offset,
5059                                                 hole_size);
5060                         if (err)
5061                                 break;
5062
5063                         err = btrfs_inode_set_file_extent_range(inode,
5064                                                         cur_offset, hole_size);
5065                         if (err)
5066                                 break;
5067
5068                         btrfs_drop_extent_cache(inode, cur_offset,
5069                                                 cur_offset + hole_size - 1, 0);
5070                         hole_em = alloc_extent_map();
5071                         if (!hole_em) {
5072                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5073                                         &inode->runtime_flags);
5074                                 goto next;
5075                         }
5076                         hole_em->start = cur_offset;
5077                         hole_em->len = hole_size;
5078                         hole_em->orig_start = cur_offset;
5079
5080                         hole_em->block_start = EXTENT_MAP_HOLE;
5081                         hole_em->block_len = 0;
5082                         hole_em->orig_block_len = 0;
5083                         hole_em->ram_bytes = hole_size;
5084                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
5085                         hole_em->generation = fs_info->generation;
5086
5087                         while (1) {
5088                                 write_lock(&em_tree->lock);
5089                                 err = add_extent_mapping(em_tree, hole_em, 1);
5090                                 write_unlock(&em_tree->lock);
5091                                 if (err != -EEXIST)
5092                                         break;
5093                                 btrfs_drop_extent_cache(inode, cur_offset,
5094                                                         cur_offset +
5095                                                         hole_size - 1, 0);
5096                         }
5097                         free_extent_map(hole_em);
5098                 } else {
5099                         err = btrfs_inode_set_file_extent_range(inode,
5100                                                         cur_offset, hole_size);
5101                         if (err)
5102                                 break;
5103                 }
5104 next:
5105                 free_extent_map(em);
5106                 em = NULL;
5107                 cur_offset = last_byte;
5108                 if (cur_offset >= block_end)
5109                         break;
5110         }
5111         free_extent_map(em);
5112         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5113         return err;
5114 }
5115
5116 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5117 {
5118         struct btrfs_root *root = BTRFS_I(inode)->root;
5119         struct btrfs_trans_handle *trans;
5120         loff_t oldsize = i_size_read(inode);
5121         loff_t newsize = attr->ia_size;
5122         int mask = attr->ia_valid;
5123         int ret;
5124
5125         /*
5126          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5127          * special case where we need to update the times despite not having
5128          * these flags set.  For all other operations the VFS set these flags
5129          * explicitly if it wants a timestamp update.
5130          */
5131         if (newsize != oldsize) {
5132                 inode_inc_iversion(inode);
5133                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5134                         inode->i_ctime = inode->i_mtime =
5135                                 current_time(inode);
5136         }
5137
5138         if (newsize > oldsize) {
5139                 /*
5140                  * Don't do an expanding truncate while snapshotting is ongoing.
5141                  * This is to ensure the snapshot captures a fully consistent
5142                  * state of this file - if the snapshot captures this expanding
5143                  * truncation, it must capture all writes that happened before
5144                  * this truncation.
5145                  */
5146                 btrfs_drew_write_lock(&root->snapshot_lock);
5147                 ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5148                 if (ret) {
5149                         btrfs_drew_write_unlock(&root->snapshot_lock);
5150                         return ret;
5151                 }
5152
5153                 trans = btrfs_start_transaction(root, 1);
5154                 if (IS_ERR(trans)) {
5155                         btrfs_drew_write_unlock(&root->snapshot_lock);
5156                         return PTR_ERR(trans);
5157                 }
5158
5159                 i_size_write(inode, newsize);
5160                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5161                 pagecache_isize_extended(inode, oldsize, newsize);
5162                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
5163                 btrfs_drew_write_unlock(&root->snapshot_lock);
5164                 btrfs_end_transaction(trans);
5165         } else {
5166                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5167
5168                 if (btrfs_is_zoned(fs_info)) {
5169                         ret = btrfs_wait_ordered_range(inode,
5170                                         ALIGN(newsize, fs_info->sectorsize),
5171                                         (u64)-1);
5172                         if (ret)
5173                                 return ret;
5174                 }
5175
5176                 /*
5177                  * We're truncating a file that used to have good data down to
5178                  * zero. Make sure any new writes to the file get on disk
5179                  * on close.
5180                  */
5181                 if (newsize == 0)
5182                         set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5183                                 &BTRFS_I(inode)->runtime_flags);
5184
5185                 truncate_setsize(inode, newsize);
5186
5187                 inode_dio_wait(inode);
5188
5189                 ret = btrfs_truncate(inode, newsize == oldsize);
5190                 if (ret && inode->i_nlink) {
5191                         int err;
5192
5193                         /*
5194                          * Truncate failed, so fix up the in-memory size. We
5195                          * adjusted disk_i_size down as we removed extents, so
5196                          * wait for disk_i_size to be stable and then update the
5197                          * in-memory size to match.
5198                          */
5199                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5200                         if (err)
5201                                 return err;
5202                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5203                 }
5204         }
5205
5206         return ret;
5207 }
5208
5209 static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
5210                          struct iattr *attr)
5211 {
5212         struct inode *inode = d_inode(dentry);
5213         struct btrfs_root *root = BTRFS_I(inode)->root;
5214         int err;
5215
5216         if (btrfs_root_readonly(root))
5217                 return -EROFS;
5218
5219         err = setattr_prepare(&init_user_ns, dentry, attr);
5220         if (err)
5221                 return err;
5222
5223         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5224                 err = btrfs_setsize(inode, attr);
5225                 if (err)
5226                         return err;
5227         }
5228
5229         if (attr->ia_valid) {
5230                 setattr_copy(&init_user_ns, inode, attr);
5231                 inode_inc_iversion(inode);
5232                 err = btrfs_dirty_inode(inode);
5233
5234                 if (!err && attr->ia_valid & ATTR_MODE)
5235                         err = posix_acl_chmod(&init_user_ns, inode,
5236                                               inode->i_mode);
5237         }
5238
5239         return err;
5240 }
5241
5242 /*
5243  * While truncating the inode pages during eviction, we get the VFS calling
5244  * btrfs_invalidatepage() against each page of the inode. This is slow because
5245  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5246  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5247  * extent_state structures over and over, wasting lots of time.
5248  *
5249  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5250  * those expensive operations on a per page basis and do only the ordered io
5251  * finishing, while we release here the extent_map and extent_state structures,
5252  * without the excessive merging and splitting.
5253  */
5254 static void evict_inode_truncate_pages(struct inode *inode)
5255 {
5256         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5257         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5258         struct rb_node *node;
5259
5260         ASSERT(inode->i_state & I_FREEING);
5261         truncate_inode_pages_final(&inode->i_data);
5262
5263         write_lock(&map_tree->lock);
5264         while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
5265                 struct extent_map *em;
5266
5267                 node = rb_first_cached(&map_tree->map);
5268                 em = rb_entry(node, struct extent_map, rb_node);
5269                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5270                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5271                 remove_extent_mapping(map_tree, em);
5272                 free_extent_map(em);
5273                 if (need_resched()) {
5274                         write_unlock(&map_tree->lock);
5275                         cond_resched();
5276                         write_lock(&map_tree->lock);
5277                 }
5278         }
5279         write_unlock(&map_tree->lock);
5280
5281         /*
5282          * Keep looping until we have no more ranges in the io tree.
5283          * We can have ongoing bios started by readahead that have
5284          * their endio callback (extent_io.c:end_bio_extent_readpage)
5285          * still in progress (unlocked the pages in the bio but did not yet
5286          * unlocked the ranges in the io tree). Therefore this means some
5287          * ranges can still be locked and eviction started because before
5288          * submitting those bios, which are executed by a separate task (work
5289          * queue kthread), inode references (inode->i_count) were not taken
5290          * (which would be dropped in the end io callback of each bio).
5291          * Therefore here we effectively end up waiting for those bios and
5292          * anyone else holding locked ranges without having bumped the inode's
5293          * reference count - if we don't do it, when they access the inode's
5294          * io_tree to unlock a range it may be too late, leading to an
5295          * use-after-free issue.
5296          */
5297         spin_lock(&io_tree->lock);
5298         while (!RB_EMPTY_ROOT(&io_tree->state)) {
5299                 struct extent_state *state;
5300                 struct extent_state *cached_state = NULL;
5301                 u64 start;
5302                 u64 end;
5303                 unsigned state_flags;
5304
5305                 node = rb_first(&io_tree->state);
5306                 state = rb_entry(node, struct extent_state, rb_node);
5307                 start = state->start;
5308                 end = state->end;
5309                 state_flags = state->state;
5310                 spin_unlock(&io_tree->lock);
5311
5312                 lock_extent_bits(io_tree, start, end, &cached_state);
5313
5314                 /*
5315                  * If still has DELALLOC flag, the extent didn't reach disk,
5316                  * and its reserved space won't be freed by delayed_ref.
5317                  * So we need to free its reserved space here.
5318                  * (Refer to comment in btrfs_invalidatepage, case 2)
5319                  *
5320                  * Note, end is the bytenr of last byte, so we need + 1 here.
5321                  */
5322                 if (state_flags & EXTENT_DELALLOC)
5323                         btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5324                                                end - start + 1);
5325
5326                 clear_extent_bit(io_tree, start, end,
5327                                  EXTENT_LOCKED | EXTENT_DELALLOC |
5328                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
5329                                  &cached_state);
5330
5331                 cond_resched();
5332                 spin_lock(&io_tree->lock);
5333         }
5334         spin_unlock(&io_tree->lock);
5335 }
5336
5337 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5338                                                         struct btrfs_block_rsv *rsv)
5339 {
5340         struct btrfs_fs_info *fs_info = root->fs_info;
5341         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5342         struct btrfs_trans_handle *trans;
5343         u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
5344         int ret;
5345
5346         /*
5347          * Eviction should be taking place at some place safe because of our
5348          * delayed iputs.  However the normal flushing code will run delayed
5349          * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5350          *
5351          * We reserve the delayed_refs_extra here again because we can't use
5352          * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5353          * above.  We reserve our extra bit here because we generate a ton of
5354          * delayed refs activity by truncating.
5355          *
5356          * If we cannot make our reservation we'll attempt to steal from the
5357          * global reserve, because we really want to be able to free up space.
5358          */
5359         ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
5360                                      BTRFS_RESERVE_FLUSH_EVICT);
5361         if (ret) {
5362                 /*
5363                  * Try to steal from the global reserve if there is space for
5364                  * it.
5365                  */
5366                 if (btrfs_check_space_for_delayed_refs(fs_info) ||
5367                     btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
5368                         btrfs_warn(fs_info,
5369                                    "could not allocate space for delete; will truncate on mount");
5370                         return ERR_PTR(-ENOSPC);
5371                 }
5372                 delayed_refs_extra = 0;
5373         }
5374
5375         trans = btrfs_join_transaction(root);
5376         if (IS_ERR(trans))
5377                 return trans;
5378
5379         if (delayed_refs_extra) {
5380                 trans->block_rsv = &fs_info->trans_block_rsv;
5381                 trans->bytes_reserved = delayed_refs_extra;
5382                 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5383                                         delayed_refs_extra, 1);
5384         }
5385         return trans;
5386 }
5387
5388 void btrfs_evict_inode(struct inode *inode)
5389 {
5390         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5391         struct btrfs_trans_handle *trans;
5392         struct btrfs_root *root = BTRFS_I(inode)->root;
5393         struct btrfs_block_rsv *rsv;
5394         int ret;
5395
5396         trace_btrfs_inode_evict(inode);
5397
5398         if (!root) {
5399                 clear_inode(inode);
5400                 return;
5401         }
5402
5403         evict_inode_truncate_pages(inode);
5404
5405         if (inode->i_nlink &&
5406             ((btrfs_root_refs(&root->root_item) != 0 &&
5407               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5408              btrfs_is_free_space_inode(BTRFS_I(inode))))
5409                 goto no_delete;
5410
5411         if (is_bad_inode(inode))
5412                 goto no_delete;
5413
5414         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5415
5416         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5417                 goto no_delete;
5418
5419         if (inode->i_nlink > 0) {
5420                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5421                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5422                 goto no_delete;
5423         }
5424
5425         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5426         if (ret)
5427                 goto no_delete;
5428
5429         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5430         if (!rsv)
5431                 goto no_delete;
5432         rsv->size = btrfs_calc_metadata_size(fs_info, 1);
5433         rsv->failfast = 1;
5434
5435         btrfs_i_size_write(BTRFS_I(inode), 0);
5436
5437         while (1) {
5438                 trans = evict_refill_and_join(root, rsv);
5439                 if (IS_ERR(trans))
5440                         goto free_rsv;
5441
5442                 trans->block_rsv = rsv;
5443
5444                 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
5445                                                  0, 0);
5446                 trans->block_rsv = &fs_info->trans_block_rsv;
5447                 btrfs_end_transaction(trans);
5448                 btrfs_btree_balance_dirty(fs_info);
5449                 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5450                         goto free_rsv;
5451                 else if (!ret)
5452                         break;
5453         }
5454
5455         /*
5456          * Errors here aren't a big deal, it just means we leave orphan items in
5457          * the tree. They will be cleaned up on the next mount. If the inode
5458          * number gets reused, cleanup deletes the orphan item without doing
5459          * anything, and unlink reuses the existing orphan item.
5460          *
5461          * If it turns out that we are dropping too many of these, we might want
5462          * to add a mechanism for retrying these after a commit.
5463          */
5464         trans = evict_refill_and_join(root, rsv);
5465         if (!IS_ERR(trans)) {
5466                 trans->block_rsv = rsv;
5467                 btrfs_orphan_del(trans, BTRFS_I(inode));
5468                 trans->block_rsv = &fs_info->trans_block_rsv;
5469                 btrfs_end_transaction(trans);
5470         }
5471
5472 free_rsv:
5473         btrfs_free_block_rsv(fs_info, rsv);
5474 no_delete:
5475         /*
5476          * If we didn't successfully delete, the orphan item will still be in
5477          * the tree and we'll retry on the next mount. Again, we might also want
5478          * to retry these periodically in the future.
5479          */
5480         btrfs_remove_delayed_node(BTRFS_I(inode));
5481         clear_inode(inode);
5482 }
5483
5484 /*
5485  * Return the key found in the dir entry in the location pointer, fill @type
5486  * with BTRFS_FT_*, and return 0.
5487  *
5488  * If no dir entries were found, returns -ENOENT.
5489  * If found a corrupted location in dir entry, returns -EUCLEAN.
5490  */
5491 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5492                                struct btrfs_key *location, u8 *type)
5493 {
5494         const char *name = dentry->d_name.name;
5495         int namelen = dentry->d_name.len;
5496         struct btrfs_dir_item *di;
5497         struct btrfs_path *path;
5498         struct btrfs_root *root = BTRFS_I(dir)->root;
5499         int ret = 0;
5500
5501         path = btrfs_alloc_path();
5502         if (!path)
5503                 return -ENOMEM;
5504
5505         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5506                         name, namelen, 0);
5507         if (IS_ERR_OR_NULL(di)) {
5508                 ret = di ? PTR_ERR(di) : -ENOENT;
5509                 goto out;
5510         }
5511
5512         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5513         if (location->type != BTRFS_INODE_ITEM_KEY &&
5514             location->type != BTRFS_ROOT_ITEM_KEY) {
5515                 ret = -EUCLEAN;
5516                 btrfs_warn(root->fs_info,
5517 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5518                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5519                            location->objectid, location->type, location->offset);
5520         }
5521         if (!ret)
5522                 *type = btrfs_dir_type(path->nodes[0], di);
5523 out:
5524         btrfs_free_path(path);
5525         return ret;
5526 }
5527
5528 /*
5529  * when we hit a tree root in a directory, the btrfs part of the inode
5530  * needs to be changed to reflect the root directory of the tree root.  This
5531  * is kind of like crossing a mount point.
5532  */
5533 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5534                                     struct inode *dir,
5535                                     struct dentry *dentry,
5536                                     struct btrfs_key *location,
5537                                     struct btrfs_root **sub_root)
5538 {
5539         struct btrfs_path *path;
5540         struct btrfs_root *new_root;
5541         struct btrfs_root_ref *ref;
5542         struct extent_buffer *leaf;
5543         struct btrfs_key key;
5544         int ret;
5545         int err = 0;
5546
5547         path = btrfs_alloc_path();
5548         if (!path) {
5549                 err = -ENOMEM;
5550                 goto out;
5551         }
5552
5553         err = -ENOENT;
5554         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5555         key.type = BTRFS_ROOT_REF_KEY;
5556         key.offset = location->objectid;
5557
5558         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5559         if (ret) {
5560                 if (ret < 0)
5561                         err = ret;
5562                 goto out;
5563         }
5564
5565         leaf = path->nodes[0];
5566         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5567         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5568             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5569                 goto out;
5570
5571         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5572                                    (unsigned long)(ref + 1),
5573                                    dentry->d_name.len);
5574         if (ret)
5575                 goto out;
5576
5577         btrfs_release_path(path);
5578
5579         new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5580         if (IS_ERR(new_root)) {
5581                 err = PTR_ERR(new_root);
5582                 goto out;
5583         }
5584
5585         *sub_root = new_root;
5586         location->objectid = btrfs_root_dirid(&new_root->root_item);
5587         location->type = BTRFS_INODE_ITEM_KEY;
5588         location->offset = 0;
5589         err = 0;
5590 out:
5591         btrfs_free_path(path);
5592         return err;
5593 }
5594
5595 static void inode_tree_add(struct inode *inode)
5596 {
5597         struct btrfs_root *root = BTRFS_I(inode)->root;
5598         struct btrfs_inode *entry;
5599         struct rb_node **p;
5600         struct rb_node *parent;
5601         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5602         u64 ino = btrfs_ino(BTRFS_I(inode));
5603
5604         if (inode_unhashed(inode))
5605                 return;
5606         parent = NULL;
5607         spin_lock(&root->inode_lock);
5608         p = &root->inode_tree.rb_node;
5609         while (*p) {
5610                 parent = *p;
5611                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5612
5613                 if (ino < btrfs_ino(entry))
5614                         p = &parent->rb_left;
5615                 else if (ino > btrfs_ino(entry))
5616                         p = &parent->rb_right;
5617                 else {
5618                         WARN_ON(!(entry->vfs_inode.i_state &
5619                                   (I_WILL_FREE | I_FREEING)));
5620                         rb_replace_node(parent, new, &root->inode_tree);
5621                         RB_CLEAR_NODE(parent);
5622                         spin_unlock(&root->inode_lock);
5623                         return;
5624                 }
5625         }
5626         rb_link_node(new, parent, p);
5627         rb_insert_color(new, &root->inode_tree);
5628         spin_unlock(&root->inode_lock);
5629 }
5630
5631 static void inode_tree_del(struct btrfs_inode *inode)
5632 {
5633         struct btrfs_root *root = inode->root;
5634         int empty = 0;
5635
5636         spin_lock(&root->inode_lock);
5637         if (!RB_EMPTY_NODE(&inode->rb_node)) {
5638                 rb_erase(&inode->rb_node, &root->inode_tree);
5639                 RB_CLEAR_NODE(&inode->rb_node);
5640                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5641         }
5642         spin_unlock(&root->inode_lock);
5643
5644         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5645                 spin_lock(&root->inode_lock);
5646                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5647                 spin_unlock(&root->inode_lock);
5648                 if (empty)
5649                         btrfs_add_dead_root(root);
5650         }
5651 }
5652
5653
5654 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5655 {
5656         struct btrfs_iget_args *args = p;
5657
5658         inode->i_ino = args->ino;
5659         BTRFS_I(inode)->location.objectid = args->ino;
5660         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5661         BTRFS_I(inode)->location.offset = 0;
5662         BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5663         BUG_ON(args->root && !BTRFS_I(inode)->root);
5664         return 0;
5665 }
5666
5667 static int btrfs_find_actor(struct inode *inode, void *opaque)
5668 {
5669         struct btrfs_iget_args *args = opaque;
5670
5671         return args->ino == BTRFS_I(inode)->location.objectid &&
5672                 args->root == BTRFS_I(inode)->root;
5673 }
5674
5675 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5676                                        struct btrfs_root *root)
5677 {
5678         struct inode *inode;
5679         struct btrfs_iget_args args;
5680         unsigned long hashval = btrfs_inode_hash(ino, root);
5681
5682         args.ino = ino;
5683         args.root = root;
5684
5685         inode = iget5_locked(s, hashval, btrfs_find_actor,
5686                              btrfs_init_locked_inode,
5687                              (void *)&args);
5688         return inode;
5689 }
5690
5691 /*
5692  * Get an inode object given its inode number and corresponding root.
5693  * Path can be preallocated to prevent recursing back to iget through
5694  * allocator. NULL is also valid but may require an additional allocation
5695  * later.
5696  */
5697 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5698                               struct btrfs_root *root, struct btrfs_path *path)
5699 {
5700         struct inode *inode;
5701
5702         inode = btrfs_iget_locked(s, ino, root);
5703         if (!inode)
5704                 return ERR_PTR(-ENOMEM);
5705
5706         if (inode->i_state & I_NEW) {
5707                 int ret;
5708
5709                 ret = btrfs_read_locked_inode(inode, path);
5710                 if (!ret) {
5711                         inode_tree_add(inode);
5712                         unlock_new_inode(inode);
5713                 } else {
5714                         iget_failed(inode);
5715                         /*
5716                          * ret > 0 can come from btrfs_search_slot called by
5717                          * btrfs_read_locked_inode, this means the inode item
5718                          * was not found.
5719                          */
5720                         if (ret > 0)
5721                                 ret = -ENOENT;
5722                         inode = ERR_PTR(ret);
5723                 }
5724         }
5725
5726         return inode;
5727 }
5728
5729 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5730 {
5731         return btrfs_iget_path(s, ino, root, NULL);
5732 }
5733
5734 static struct inode *new_simple_dir(struct super_block *s,
5735                                     struct btrfs_key *key,
5736                                     struct btrfs_root *root)
5737 {
5738         struct inode *inode = new_inode(s);
5739
5740         if (!inode)
5741                 return ERR_PTR(-ENOMEM);
5742
5743         BTRFS_I(inode)->root = btrfs_grab_root(root);
5744         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5745         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5746
5747         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5748         /*
5749          * We only need lookup, the rest is read-only and there's no inode
5750          * associated with the dentry
5751          */
5752         inode->i_op = &simple_dir_inode_operations;
5753         inode->i_opflags &= ~IOP_XATTR;
5754         inode->i_fop = &simple_dir_operations;
5755         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5756         inode->i_mtime = current_time(inode);
5757         inode->i_atime = inode->i_mtime;
5758         inode->i_ctime = inode->i_mtime;
5759         BTRFS_I(inode)->i_otime = inode->i_mtime;
5760
5761         return inode;
5762 }
5763
5764 static inline u8 btrfs_inode_type(struct inode *inode)
5765 {
5766         /*
5767          * Compile-time asserts that generic FT_* types still match
5768          * BTRFS_FT_* types
5769          */
5770         BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5771         BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5772         BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5773         BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5774         BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5775         BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5776         BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5777         BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5778
5779         return fs_umode_to_ftype(inode->i_mode);
5780 }
5781
5782 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5783 {
5784         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5785         struct inode *inode;
5786         struct btrfs_root *root = BTRFS_I(dir)->root;
5787         struct btrfs_root *sub_root = root;
5788         struct btrfs_key location;
5789         u8 di_type = 0;
5790         int ret = 0;
5791
5792         if (dentry->d_name.len > BTRFS_NAME_LEN)
5793                 return ERR_PTR(-ENAMETOOLONG);
5794
5795         ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5796         if (ret < 0)
5797                 return ERR_PTR(ret);
5798
5799         if (location.type == BTRFS_INODE_ITEM_KEY) {
5800                 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5801                 if (IS_ERR(inode))
5802                         return inode;
5803
5804                 /* Do extra check against inode mode with di_type */
5805                 if (btrfs_inode_type(inode) != di_type) {
5806                         btrfs_crit(fs_info,
5807 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5808                                   inode->i_mode, btrfs_inode_type(inode),
5809                                   di_type);
5810                         iput(inode);
5811                         return ERR_PTR(-EUCLEAN);
5812                 }
5813                 return inode;
5814         }
5815
5816         ret = fixup_tree_root_location(fs_info, dir, dentry,
5817                                        &location, &sub_root);
5818         if (ret < 0) {
5819                 if (ret != -ENOENT)
5820                         inode = ERR_PTR(ret);
5821                 else
5822                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5823         } else {
5824                 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5825         }
5826         if (root != sub_root)
5827                 btrfs_put_root(sub_root);
5828
5829         if (!IS_ERR(inode) && root != sub_root) {
5830                 down_read(&fs_info->cleanup_work_sem);
5831                 if (!sb_rdonly(inode->i_sb))
5832                         ret = btrfs_orphan_cleanup(sub_root);
5833                 up_read(&fs_info->cleanup_work_sem);
5834                 if (ret) {
5835                         iput(inode);
5836                         inode = ERR_PTR(ret);
5837                 }
5838         }
5839
5840         return inode;
5841 }
5842
5843 static int btrfs_dentry_delete(const struct dentry *dentry)
5844 {
5845         struct btrfs_root *root;
5846         struct inode *inode = d_inode(dentry);
5847
5848         if (!inode && !IS_ROOT(dentry))
5849                 inode = d_inode(dentry->d_parent);
5850
5851         if (inode) {
5852                 root = BTRFS_I(inode)->root;
5853                 if (btrfs_root_refs(&root->root_item) == 0)
5854                         return 1;
5855
5856                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5857                         return 1;
5858         }
5859         return 0;
5860 }
5861
5862 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5863                                    unsigned int flags)
5864 {
5865         struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5866
5867         if (inode == ERR_PTR(-ENOENT))
5868                 inode = NULL;
5869         return d_splice_alias(inode, dentry);
5870 }
5871
5872 /*
5873  * All this infrastructure exists because dir_emit can fault, and we are holding
5874  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5875  * our information into that, and then dir_emit from the buffer.  This is
5876  * similar to what NFS does, only we don't keep the buffer around in pagecache
5877  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5878  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5879  * tree lock.
5880  */
5881 static int btrfs_opendir(struct inode *inode, struct file *file)
5882 {
5883         struct btrfs_file_private *private;
5884
5885         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5886         if (!private)
5887                 return -ENOMEM;
5888         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5889         if (!private->filldir_buf) {
5890                 kfree(private);
5891                 return -ENOMEM;
5892         }
5893         file->private_data = private;
5894         return 0;
5895 }
5896
5897 struct dir_entry {
5898         u64 ino;
5899         u64 offset;
5900         unsigned type;
5901         int name_len;
5902 };
5903
5904 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5905 {
5906         while (entries--) {
5907                 struct dir_entry *entry = addr;
5908                 char *name = (char *)(entry + 1);
5909
5910                 ctx->pos = get_unaligned(&entry->offset);
5911                 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5912                                          get_unaligned(&entry->ino),
5913                                          get_unaligned(&entry->type)))
5914                         return 1;
5915                 addr += sizeof(struct dir_entry) +
5916                         get_unaligned(&entry->name_len);
5917                 ctx->pos++;
5918         }
5919         return 0;
5920 }
5921
5922 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5923 {
5924         struct inode *inode = file_inode(file);
5925         struct btrfs_root *root = BTRFS_I(inode)->root;
5926         struct btrfs_file_private *private = file->private_data;
5927         struct btrfs_dir_item *di;
5928         struct btrfs_key key;
5929         struct btrfs_key found_key;
5930         struct btrfs_path *path;
5931         void *addr;
5932         struct list_head ins_list;
5933         struct list_head del_list;
5934         int ret;
5935         struct extent_buffer *leaf;
5936         int slot;
5937         char *name_ptr;
5938         int name_len;
5939         int entries = 0;
5940         int total_len = 0;
5941         bool put = false;
5942         struct btrfs_key location;
5943
5944         if (!dir_emit_dots(file, ctx))
5945                 return 0;
5946
5947         path = btrfs_alloc_path();
5948         if (!path)
5949                 return -ENOMEM;
5950
5951         addr = private->filldir_buf;
5952         path->reada = READA_FORWARD;
5953
5954         INIT_LIST_HEAD(&ins_list);
5955         INIT_LIST_HEAD(&del_list);
5956         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5957
5958 again:
5959         key.type = BTRFS_DIR_INDEX_KEY;
5960         key.offset = ctx->pos;
5961         key.objectid = btrfs_ino(BTRFS_I(inode));
5962
5963         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5964         if (ret < 0)
5965                 goto err;
5966
5967         while (1) {
5968                 struct dir_entry *entry;
5969
5970                 leaf = path->nodes[0];
5971                 slot = path->slots[0];
5972                 if (slot >= btrfs_header_nritems(leaf)) {
5973                         ret = btrfs_next_leaf(root, path);
5974                         if (ret < 0)
5975                                 goto err;
5976                         else if (ret > 0)
5977                                 break;
5978                         continue;
5979                 }
5980
5981                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5982
5983                 if (found_key.objectid != key.objectid)
5984                         break;
5985                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5986                         break;
5987                 if (found_key.offset < ctx->pos)
5988                         goto next;
5989                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5990                         goto next;
5991                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5992                 name_len = btrfs_dir_name_len(leaf, di);
5993                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5994                     PAGE_SIZE) {
5995                         btrfs_release_path(path);
5996                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5997                         if (ret)
5998                                 goto nopos;
5999                         addr = private->filldir_buf;
6000                         entries = 0;
6001                         total_len = 0;
6002                         goto again;
6003                 }
6004
6005                 entry = addr;
6006                 put_unaligned(name_len, &entry->name_len);
6007                 name_ptr = (char *)(entry + 1);
6008                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
6009                                    name_len);
6010                 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
6011                                 &entry->type);
6012                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
6013                 put_unaligned(location.objectid, &entry->ino);
6014                 put_unaligned(found_key.offset, &entry->offset);
6015                 entries++;
6016                 addr += sizeof(struct dir_entry) + name_len;
6017                 total_len += sizeof(struct dir_entry) + name_len;
6018 next:
6019                 path->slots[0]++;
6020         }
6021         btrfs_release_path(path);
6022
6023         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6024         if (ret)
6025                 goto nopos;
6026
6027         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
6028         if (ret)
6029                 goto nopos;
6030
6031         /*
6032          * Stop new entries from being returned after we return the last
6033          * entry.
6034          *
6035          * New directory entries are assigned a strictly increasing
6036          * offset.  This means that new entries created during readdir
6037          * are *guaranteed* to be seen in the future by that readdir.
6038          * This has broken buggy programs which operate on names as
6039          * they're returned by readdir.  Until we re-use freed offsets
6040          * we have this hack to stop new entries from being returned
6041          * under the assumption that they'll never reach this huge
6042          * offset.
6043          *
6044          * This is being careful not to overflow 32bit loff_t unless the
6045          * last entry requires it because doing so has broken 32bit apps
6046          * in the past.
6047          */
6048         if (ctx->pos >= INT_MAX)
6049                 ctx->pos = LLONG_MAX;
6050         else
6051                 ctx->pos = INT_MAX;
6052 nopos:
6053         ret = 0;
6054 err:
6055         if (put)
6056                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6057         btrfs_free_path(path);
6058         return ret;
6059 }
6060
6061 /*
6062  * This is somewhat expensive, updating the tree every time the
6063  * inode changes.  But, it is most likely to find the inode in cache.
6064  * FIXME, needs more benchmarking...there are no reasons other than performance
6065  * to keep or drop this code.
6066  */
6067 static int btrfs_dirty_inode(struct inode *inode)
6068 {
6069         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6070         struct btrfs_root *root = BTRFS_I(inode)->root;
6071         struct btrfs_trans_handle *trans;
6072         int ret;
6073
6074         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6075                 return 0;
6076
6077         trans = btrfs_join_transaction(root);
6078         if (IS_ERR(trans))
6079                 return PTR_ERR(trans);
6080
6081         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6082         if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
6083                 /* whoops, lets try again with the full transaction */
6084                 btrfs_end_transaction(trans);
6085                 trans = btrfs_start_transaction(root, 1);
6086                 if (IS_ERR(trans))
6087                         return PTR_ERR(trans);
6088
6089                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
6090         }
6091         btrfs_end_transaction(trans);
6092         if (BTRFS_I(inode)->delayed_node)
6093                 btrfs_balance_delayed_items(fs_info);
6094
6095         return ret;
6096 }
6097
6098 /*
6099  * This is a copy of file_update_time.  We need this so we can return error on
6100  * ENOSPC for updating the inode in the case of file write and mmap writes.
6101  */
6102 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6103                              int flags)
6104 {
6105         struct btrfs_root *root = BTRFS_I(inode)->root;
6106         bool dirty = flags & ~S_VERSION;
6107
6108         if (btrfs_root_readonly(root))
6109                 return -EROFS;
6110
6111         if (flags & S_VERSION)
6112                 dirty |= inode_maybe_inc_iversion(inode, dirty);
6113         if (flags & S_CTIME)
6114                 inode->i_ctime = *now;
6115         if (flags & S_MTIME)
6116                 inode->i_mtime = *now;
6117         if (flags & S_ATIME)
6118                 inode->i_atime = *now;
6119         return dirty ? btrfs_dirty_inode(inode) : 0;
6120 }
6121
6122 /*
6123  * find the highest existing sequence number in a directory
6124  * and then set the in-memory index_cnt variable to reflect
6125  * free sequence numbers
6126  */
6127 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6128 {
6129         struct btrfs_root *root = inode->root;
6130         struct btrfs_key key, found_key;
6131         struct btrfs_path *path;
6132         struct extent_buffer *leaf;
6133         int ret;
6134
6135         key.objectid = btrfs_ino(inode);
6136         key.type = BTRFS_DIR_INDEX_KEY;
6137         key.offset = (u64)-1;
6138
6139         path = btrfs_alloc_path();
6140         if (!path)
6141                 return -ENOMEM;
6142
6143         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6144         if (ret < 0)
6145                 goto out;
6146         /* FIXME: we should be able to handle this */
6147         if (ret == 0)
6148                 goto out;
6149         ret = 0;
6150
6151         /*
6152          * MAGIC NUMBER EXPLANATION:
6153          * since we search a directory based on f_pos we have to start at 2
6154          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6155          * else has to start at 2
6156          */
6157         if (path->slots[0] == 0) {
6158                 inode->index_cnt = 2;
6159                 goto out;
6160         }
6161
6162         path->slots[0]--;
6163
6164         leaf = path->nodes[0];
6165         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6166
6167         if (found_key.objectid != btrfs_ino(inode) ||
6168             found_key.type != BTRFS_DIR_INDEX_KEY) {
6169                 inode->index_cnt = 2;
6170                 goto out;
6171         }
6172
6173         inode->index_cnt = found_key.offset + 1;
6174 out:
6175         btrfs_free_path(path);
6176         return ret;
6177 }
6178
6179 /*
6180  * helper to find a free sequence number in a given directory.  This current
6181  * code is very simple, later versions will do smarter things in the btree
6182  */
6183 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6184 {
6185         int ret = 0;
6186
6187         if (dir->index_cnt == (u64)-1) {
6188                 ret = btrfs_inode_delayed_dir_index_count(dir);
6189                 if (ret) {
6190                         ret = btrfs_set_inode_index_count(dir);
6191                         if (ret)
6192                                 return ret;
6193                 }
6194         }
6195
6196         *index = dir->index_cnt;
6197         dir->index_cnt++;
6198
6199         return ret;
6200 }
6201
6202 static int btrfs_insert_inode_locked(struct inode *inode)
6203 {
6204         struct btrfs_iget_args args;
6205
6206         args.ino = BTRFS_I(inode)->location.objectid;
6207         args.root = BTRFS_I(inode)->root;
6208
6209         return insert_inode_locked4(inode,
6210                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6211                    btrfs_find_actor, &args);
6212 }
6213
6214 /*
6215  * Inherit flags from the parent inode.
6216  *
6217  * Currently only the compression flags and the cow flags are inherited.
6218  */
6219 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6220 {
6221         unsigned int flags;
6222
6223         if (!dir)
6224                 return;
6225
6226         flags = BTRFS_I(dir)->flags;
6227
6228         if (flags & BTRFS_INODE_NOCOMPRESS) {
6229                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6230                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6231         } else if (flags & BTRFS_INODE_COMPRESS) {
6232                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6233                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6234         }
6235
6236         if (flags & BTRFS_INODE_NODATACOW) {
6237                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6238                 if (S_ISREG(inode->i_mode))
6239                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6240         }
6241
6242         btrfs_sync_inode_flags_to_i_flags(inode);
6243 }
6244
6245 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6246                                      struct btrfs_root *root,
6247                                      struct inode *dir,
6248                                      const char *name, int name_len,
6249                                      u64 ref_objectid, u64 objectid,
6250                                      umode_t mode, u64 *index)
6251 {
6252         struct btrfs_fs_info *fs_info = root->fs_info;
6253         struct inode *inode;
6254         struct btrfs_inode_item *inode_item;
6255         struct btrfs_key *location;
6256         struct btrfs_path *path;
6257         struct btrfs_inode_ref *ref;
6258         struct btrfs_key key[2];
6259         u32 sizes[2];
6260         int nitems = name ? 2 : 1;
6261         unsigned long ptr;
6262         unsigned int nofs_flag;
6263         int ret;
6264
6265         path = btrfs_alloc_path();
6266         if (!path)
6267                 return ERR_PTR(-ENOMEM);
6268
6269         nofs_flag = memalloc_nofs_save();
6270         inode = new_inode(fs_info->sb);
6271         memalloc_nofs_restore(nofs_flag);
6272         if (!inode) {
6273                 btrfs_free_path(path);
6274                 return ERR_PTR(-ENOMEM);
6275         }
6276
6277         /*
6278          * O_TMPFILE, set link count to 0, so that after this point,
6279          * we fill in an inode item with the correct link count.
6280          */
6281         if (!name)
6282                 set_nlink(inode, 0);
6283
6284         /*
6285          * we have to initialize this early, so we can reclaim the inode
6286          * number if we fail afterwards in this function.
6287          */
6288         inode->i_ino = objectid;
6289
6290         if (dir && name) {
6291                 trace_btrfs_inode_request(dir);
6292
6293                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6294                 if (ret) {
6295                         btrfs_free_path(path);
6296                         iput(inode);
6297                         return ERR_PTR(ret);
6298                 }
6299         } else if (dir) {
6300                 *index = 0;
6301         }
6302         /*
6303          * index_cnt is ignored for everything but a dir,
6304          * btrfs_set_inode_index_count has an explanation for the magic
6305          * number
6306          */
6307         BTRFS_I(inode)->index_cnt = 2;
6308         BTRFS_I(inode)->dir_index = *index;
6309         BTRFS_I(inode)->root = btrfs_grab_root(root);
6310         BTRFS_I(inode)->generation = trans->transid;
6311         inode->i_generation = BTRFS_I(inode)->generation;
6312
6313         /*
6314          * We could have gotten an inode number from somebody who was fsynced
6315          * and then removed in this same transaction, so let's just set full
6316          * sync since it will be a full sync anyway and this will blow away the
6317          * old info in the log.
6318          */
6319         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6320
6321         key[0].objectid = objectid;
6322         key[0].type = BTRFS_INODE_ITEM_KEY;
6323         key[0].offset = 0;
6324
6325         sizes[0] = sizeof(struct btrfs_inode_item);
6326
6327         if (name) {
6328                 /*
6329                  * Start new inodes with an inode_ref. This is slightly more
6330                  * efficient for small numbers of hard links since they will
6331                  * be packed into one item. Extended refs will kick in if we
6332                  * add more hard links than can fit in the ref item.
6333                  */
6334                 key[1].objectid = objectid;
6335                 key[1].type = BTRFS_INODE_REF_KEY;
6336                 key[1].offset = ref_objectid;
6337
6338                 sizes[1] = name_len + sizeof(*ref);
6339         }
6340
6341         location = &BTRFS_I(inode)->location;
6342         location->objectid = objectid;
6343         location->offset = 0;
6344         location->type = BTRFS_INODE_ITEM_KEY;
6345
6346         ret = btrfs_insert_inode_locked(inode);
6347         if (ret < 0) {
6348                 iput(inode);
6349                 goto fail;
6350         }
6351
6352         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6353         if (ret != 0)
6354                 goto fail_unlock;
6355
6356         inode_init_owner(&init_user_ns, inode, dir, mode);
6357         inode_set_bytes(inode, 0);
6358
6359         inode->i_mtime = current_time(inode);
6360         inode->i_atime = inode->i_mtime;
6361         inode->i_ctime = inode->i_mtime;
6362         BTRFS_I(inode)->i_otime = inode->i_mtime;
6363
6364         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6365                                   struct btrfs_inode_item);
6366         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6367                              sizeof(*inode_item));
6368         fill_inode_item(trans, path->nodes[0], inode_item, inode);
6369
6370         if (name) {
6371                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6372                                      struct btrfs_inode_ref);
6373                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6374                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6375                 ptr = (unsigned long)(ref + 1);
6376                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6377         }
6378
6379         btrfs_mark_buffer_dirty(path->nodes[0]);
6380         btrfs_free_path(path);
6381
6382         btrfs_inherit_iflags(inode, dir);
6383
6384         if (S_ISREG(mode)) {
6385                 if (btrfs_test_opt(fs_info, NODATASUM))
6386                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6387                 if (btrfs_test_opt(fs_info, NODATACOW))
6388                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6389                                 BTRFS_INODE_NODATASUM;
6390         }
6391
6392         inode_tree_add(inode);
6393
6394         trace_btrfs_inode_new(inode);
6395         btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6396
6397         btrfs_update_root_times(trans, root);
6398
6399         ret = btrfs_inode_inherit_props(trans, inode, dir);
6400         if (ret)
6401                 btrfs_err(fs_info,
6402                           "error inheriting props for ino %llu (root %llu): %d",
6403                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6404
6405         return inode;
6406
6407 fail_unlock:
6408         discard_new_inode(inode);
6409 fail:
6410         if (dir && name)
6411                 BTRFS_I(dir)->index_cnt--;
6412         btrfs_free_path(path);
6413         return ERR_PTR(ret);
6414 }
6415
6416 /*
6417  * utility function to add 'inode' into 'parent_inode' with
6418  * a give name and a given sequence number.
6419  * if 'add_backref' is true, also insert a backref from the
6420  * inode to the parent directory.
6421  */
6422 int btrfs_add_link(struct btrfs_trans_handle *trans,
6423                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6424                    const char *name, int name_len, int add_backref, u64 index)
6425 {
6426         int ret = 0;
6427         struct btrfs_key key;
6428         struct btrfs_root *root = parent_inode->root;
6429         u64 ino = btrfs_ino(inode);
6430         u64 parent_ino = btrfs_ino(parent_inode);
6431
6432         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6433                 memcpy(&key, &inode->root->root_key, sizeof(key));
6434         } else {
6435                 key.objectid = ino;
6436                 key.type = BTRFS_INODE_ITEM_KEY;
6437                 key.offset = 0;
6438         }
6439
6440         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6441                 ret = btrfs_add_root_ref(trans, key.objectid,
6442                                          root->root_key.objectid, parent_ino,
6443                                          index, name, name_len);
6444         } else if (add_backref) {
6445                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6446                                              parent_ino, index);
6447         }
6448
6449         /* Nothing to clean up yet */
6450         if (ret)
6451                 return ret;
6452
6453         ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6454                                     btrfs_inode_type(&inode->vfs_inode), index);
6455         if (ret == -EEXIST || ret == -EOVERFLOW)
6456                 goto fail_dir_item;
6457         else if (ret) {
6458                 btrfs_abort_transaction(trans, ret);
6459                 return ret;
6460         }
6461
6462         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6463                            name_len * 2);
6464         inode_inc_iversion(&parent_inode->vfs_inode);
6465         /*
6466          * If we are replaying a log tree, we do not want to update the mtime
6467          * and ctime of the parent directory with the current time, since the
6468          * log replay procedure is responsible for setting them to their correct
6469          * values (the ones it had when the fsync was done).
6470          */
6471         if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6472                 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6473
6474                 parent_inode->vfs_inode.i_mtime = now;
6475                 parent_inode->vfs_inode.i_ctime = now;
6476         }
6477         ret = btrfs_update_inode(trans, root, parent_inode);
6478         if (ret)
6479                 btrfs_abort_transaction(trans, ret);
6480         return ret;
6481
6482 fail_dir_item:
6483         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6484                 u64 local_index;
6485                 int err;
6486                 err = btrfs_del_root_ref(trans, key.objectid,
6487                                          root->root_key.objectid, parent_ino,
6488                                          &local_index, name, name_len);
6489                 if (err)
6490                         btrfs_abort_transaction(trans, err);
6491         } else if (add_backref) {
6492                 u64 local_index;
6493                 int err;
6494
6495                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6496                                           ino, parent_ino, &local_index);
6497                 if (err)
6498                         btrfs_abort_transaction(trans, err);
6499         }
6500
6501         /* Return the original error code */
6502         return ret;
6503 }
6504
6505 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6506                             struct btrfs_inode *dir, struct dentry *dentry,
6507                             struct btrfs_inode *inode, int backref, u64 index)
6508 {
6509         int err = btrfs_add_link(trans, dir, inode,
6510                                  dentry->d_name.name, dentry->d_name.len,
6511                                  backref, index);
6512         if (err > 0)
6513                 err = -EEXIST;
6514         return err;
6515 }
6516
6517 static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
6518                        struct dentry *dentry, umode_t mode, dev_t rdev)
6519 {
6520         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6521         struct btrfs_trans_handle *trans;
6522         struct btrfs_root *root = BTRFS_I(dir)->root;
6523         struct inode *inode = NULL;
6524         int err;
6525         u64 objectid;
6526         u64 index = 0;
6527
6528         /*
6529          * 2 for inode item and ref
6530          * 2 for dir items
6531          * 1 for xattr if selinux is on
6532          */
6533         trans = btrfs_start_transaction(root, 5);
6534         if (IS_ERR(trans))
6535                 return PTR_ERR(trans);
6536
6537         err = btrfs_get_free_objectid(root, &objectid);
6538         if (err)
6539                 goto out_unlock;
6540
6541         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6542                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6543                         mode, &index);
6544         if (IS_ERR(inode)) {
6545                 err = PTR_ERR(inode);
6546                 inode = NULL;
6547                 goto out_unlock;
6548         }
6549
6550         /*
6551         * If the active LSM wants to access the inode during
6552         * d_instantiate it needs these. Smack checks to see
6553         * if the filesystem supports xattrs by looking at the
6554         * ops vector.
6555         */
6556         inode->i_op = &btrfs_special_inode_operations;
6557         init_special_inode(inode, inode->i_mode, rdev);
6558
6559         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6560         if (err)
6561                 goto out_unlock;
6562
6563         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6564                         0, index);
6565         if (err)
6566                 goto out_unlock;
6567
6568         btrfs_update_inode(trans, root, BTRFS_I(inode));
6569         d_instantiate_new(dentry, inode);
6570
6571 out_unlock:
6572         btrfs_end_transaction(trans);
6573         btrfs_btree_balance_dirty(fs_info);
6574         if (err && inode) {
6575                 inode_dec_link_count(inode);
6576                 discard_new_inode(inode);
6577         }
6578         return err;
6579 }
6580
6581 static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
6582                         struct dentry *dentry, umode_t mode, bool excl)
6583 {
6584         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6585         struct btrfs_trans_handle *trans;
6586         struct btrfs_root *root = BTRFS_I(dir)->root;
6587         struct inode *inode = NULL;
6588         int err;
6589         u64 objectid;
6590         u64 index = 0;
6591
6592         /*
6593          * 2 for inode item and ref
6594          * 2 for dir items
6595          * 1 for xattr if selinux is on
6596          */
6597         trans = btrfs_start_transaction(root, 5);
6598         if (IS_ERR(trans))
6599                 return PTR_ERR(trans);
6600
6601         err = btrfs_get_free_objectid(root, &objectid);
6602         if (err)
6603                 goto out_unlock;
6604
6605         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6606                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6607                         mode, &index);
6608         if (IS_ERR(inode)) {
6609                 err = PTR_ERR(inode);
6610                 inode = NULL;
6611                 goto out_unlock;
6612         }
6613         /*
6614         * If the active LSM wants to access the inode during
6615         * d_instantiate it needs these. Smack checks to see
6616         * if the filesystem supports xattrs by looking at the
6617         * ops vector.
6618         */
6619         inode->i_fop = &btrfs_file_operations;
6620         inode->i_op = &btrfs_file_inode_operations;
6621         inode->i_mapping->a_ops = &btrfs_aops;
6622
6623         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6624         if (err)
6625                 goto out_unlock;
6626
6627         err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6628         if (err)
6629                 goto out_unlock;
6630
6631         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6632                         0, index);
6633         if (err)
6634                 goto out_unlock;
6635
6636         d_instantiate_new(dentry, inode);
6637
6638 out_unlock:
6639         btrfs_end_transaction(trans);
6640         if (err && inode) {
6641                 inode_dec_link_count(inode);
6642                 discard_new_inode(inode);
6643         }
6644         btrfs_btree_balance_dirty(fs_info);
6645         return err;
6646 }
6647
6648 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6649                       struct dentry *dentry)
6650 {
6651         struct btrfs_trans_handle *trans = NULL;
6652         struct btrfs_root *root = BTRFS_I(dir)->root;
6653         struct inode *inode = d_inode(old_dentry);
6654         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6655         u64 index;
6656         int err;
6657         int drop_inode = 0;
6658
6659         /* do not allow sys_link's with other subvols of the same device */
6660         if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6661                 return -EXDEV;
6662
6663         if (inode->i_nlink >= BTRFS_LINK_MAX)
6664                 return -EMLINK;
6665
6666         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6667         if (err)
6668                 goto fail;
6669
6670         /*
6671          * 2 items for inode and inode ref
6672          * 2 items for dir items
6673          * 1 item for parent inode
6674          * 1 item for orphan item deletion if O_TMPFILE
6675          */
6676         trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6677         if (IS_ERR(trans)) {
6678                 err = PTR_ERR(trans);
6679                 trans = NULL;
6680                 goto fail;
6681         }
6682
6683         /* There are several dir indexes for this inode, clear the cache. */
6684         BTRFS_I(inode)->dir_index = 0ULL;
6685         inc_nlink(inode);
6686         inode_inc_iversion(inode);
6687         inode->i_ctime = current_time(inode);
6688         ihold(inode);
6689         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6690
6691         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6692                         1, index);
6693
6694         if (err) {
6695                 drop_inode = 1;
6696         } else {
6697                 struct dentry *parent = dentry->d_parent;
6698
6699                 err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6700                 if (err)
6701                         goto fail;
6702                 if (inode->i_nlink == 1) {
6703                         /*
6704                          * If new hard link count is 1, it's a file created
6705                          * with open(2) O_TMPFILE flag.
6706                          */
6707                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6708                         if (err)
6709                                 goto fail;
6710                 }
6711                 d_instantiate(dentry, inode);
6712                 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6713         }
6714
6715 fail:
6716         if (trans)
6717                 btrfs_end_transaction(trans);
6718         if (drop_inode) {
6719                 inode_dec_link_count(inode);
6720                 iput(inode);
6721         }
6722         btrfs_btree_balance_dirty(fs_info);
6723         return err;
6724 }
6725
6726 static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
6727                        struct dentry *dentry, umode_t mode)
6728 {
6729         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6730         struct inode *inode = NULL;
6731         struct btrfs_trans_handle *trans;
6732         struct btrfs_root *root = BTRFS_I(dir)->root;
6733         int err = 0;
6734         u64 objectid = 0;
6735         u64 index = 0;
6736
6737         /*
6738          * 2 items for inode and ref
6739          * 2 items for dir items
6740          * 1 for xattr if selinux is on
6741          */
6742         trans = btrfs_start_transaction(root, 5);
6743         if (IS_ERR(trans))
6744                 return PTR_ERR(trans);
6745
6746         err = btrfs_get_free_objectid(root, &objectid);
6747         if (err)
6748                 goto out_fail;
6749
6750         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6751                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6752                         S_IFDIR | mode, &index);
6753         if (IS_ERR(inode)) {
6754                 err = PTR_ERR(inode);
6755                 inode = NULL;
6756                 goto out_fail;
6757         }
6758
6759         /* these must be set before we unlock the inode */
6760         inode->i_op = &btrfs_dir_inode_operations;
6761         inode->i_fop = &btrfs_dir_file_operations;
6762
6763         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6764         if (err)
6765                 goto out_fail;
6766
6767         btrfs_i_size_write(BTRFS_I(inode), 0);
6768         err = btrfs_update_inode(trans, root, BTRFS_I(inode));
6769         if (err)
6770                 goto out_fail;
6771
6772         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6773                         dentry->d_name.name,
6774                         dentry->d_name.len, 0, index);
6775         if (err)
6776                 goto out_fail;
6777
6778         d_instantiate_new(dentry, inode);
6779
6780 out_fail:
6781         btrfs_end_transaction(trans);
6782         if (err && inode) {
6783                 inode_dec_link_count(inode);
6784                 discard_new_inode(inode);
6785         }
6786         btrfs_btree_balance_dirty(fs_info);
6787         return err;
6788 }
6789
6790 static noinline int uncompress_inline(struct btrfs_path *path,
6791                                       struct page *page,
6792                                       size_t pg_offset, u64 extent_offset,
6793                                       struct btrfs_file_extent_item *item)
6794 {
6795         int ret;
6796         struct extent_buffer *leaf = path->nodes[0];
6797         char *tmp;
6798         size_t max_size;
6799         unsigned long inline_size;
6800         unsigned long ptr;
6801         int compress_type;
6802
6803         WARN_ON(pg_offset != 0);
6804         compress_type = btrfs_file_extent_compression(leaf, item);
6805         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6806         inline_size = btrfs_file_extent_inline_item_len(leaf,
6807                                         btrfs_item_nr(path->slots[0]));
6808         tmp = kmalloc(inline_size, GFP_NOFS);
6809         if (!tmp)
6810                 return -ENOMEM;
6811         ptr = btrfs_file_extent_inline_start(item);
6812
6813         read_extent_buffer(leaf, tmp, ptr, inline_size);
6814
6815         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6816         ret = btrfs_decompress(compress_type, tmp, page,
6817                                extent_offset, inline_size, max_size);
6818
6819         /*
6820          * decompression code contains a memset to fill in any space between the end
6821          * of the uncompressed data and the end of max_size in case the decompressed
6822          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6823          * the end of an inline extent and the beginning of the next block, so we
6824          * cover that region here.
6825          */
6826
6827         if (max_size + pg_offset < PAGE_SIZE) {
6828                 char *map = kmap(page);
6829                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6830                 kunmap(page);
6831         }
6832         kfree(tmp);
6833         return ret;
6834 }
6835
6836 /**
6837  * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6838  * @inode:      file to search in
6839  * @page:       page to read extent data into if the extent is inline
6840  * @pg_offset:  offset into @page to copy to
6841  * @start:      file offset
6842  * @len:        length of range starting at @start
6843  *
6844  * This returns the first &struct extent_map which overlaps with the given
6845  * range, reading it from the B-tree and caching it if necessary. Note that
6846  * there may be more extents which overlap the given range after the returned
6847  * extent_map.
6848  *
6849  * If @page is not NULL and the extent is inline, this also reads the extent
6850  * data directly into the page and marks the extent up to date in the io_tree.
6851  *
6852  * Return: ERR_PTR on error, non-NULL extent_map on success.
6853  */
6854 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6855                                     struct page *page, size_t pg_offset,
6856                                     u64 start, u64 len)
6857 {
6858         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6859         int ret = 0;
6860         u64 extent_start = 0;
6861         u64 extent_end = 0;
6862         u64 objectid = btrfs_ino(inode);
6863         int extent_type = -1;
6864         struct btrfs_path *path = NULL;
6865         struct btrfs_root *root = inode->root;
6866         struct btrfs_file_extent_item *item;
6867         struct extent_buffer *leaf;
6868         struct btrfs_key found_key;
6869         struct extent_map *em = NULL;
6870         struct extent_map_tree *em_tree = &inode->extent_tree;
6871         struct extent_io_tree *io_tree = &inode->io_tree;
6872
6873         read_lock(&em_tree->lock);
6874         em = lookup_extent_mapping(em_tree, start, len);
6875         read_unlock(&em_tree->lock);
6876
6877         if (em) {
6878                 if (em->start > start || em->start + em->len <= start)
6879                         free_extent_map(em);
6880                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6881                         free_extent_map(em);
6882                 else
6883                         goto out;
6884         }
6885         em = alloc_extent_map();
6886         if (!em) {
6887                 ret = -ENOMEM;
6888                 goto out;
6889         }
6890         em->start = EXTENT_MAP_HOLE;
6891         em->orig_start = EXTENT_MAP_HOLE;
6892         em->len = (u64)-1;
6893         em->block_len = (u64)-1;
6894
6895         path = btrfs_alloc_path();
6896         if (!path) {
6897                 ret = -ENOMEM;
6898                 goto out;
6899         }
6900
6901         /* Chances are we'll be called again, so go ahead and do readahead */
6902         path->reada = READA_FORWARD;
6903
6904         /*
6905          * The same explanation in load_free_space_cache applies here as well,
6906          * we only read when we're loading the free space cache, and at that
6907          * point the commit_root has everything we need.
6908          */
6909         if (btrfs_is_free_space_inode(inode)) {
6910                 path->search_commit_root = 1;
6911                 path->skip_locking = 1;
6912         }
6913
6914         ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6915         if (ret < 0) {
6916                 goto out;
6917         } else if (ret > 0) {
6918                 if (path->slots[0] == 0)
6919                         goto not_found;
6920                 path->slots[0]--;
6921                 ret = 0;
6922         }
6923
6924         leaf = path->nodes[0];
6925         item = btrfs_item_ptr(leaf, path->slots[0],
6926                               struct btrfs_file_extent_item);
6927         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6928         if (found_key.objectid != objectid ||
6929             found_key.type != BTRFS_EXTENT_DATA_KEY) {
6930                 /*
6931                  * If we backup past the first extent we want to move forward
6932                  * and see if there is an extent in front of us, otherwise we'll
6933                  * say there is a hole for our whole search range which can
6934                  * cause problems.
6935                  */
6936                 extent_end = start;
6937                 goto next;
6938         }
6939
6940         extent_type = btrfs_file_extent_type(leaf, item);
6941         extent_start = found_key.offset;
6942         extent_end = btrfs_file_extent_end(path);
6943         if (extent_type == BTRFS_FILE_EXTENT_REG ||
6944             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6945                 /* Only regular file could have regular/prealloc extent */
6946                 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6947                         ret = -EUCLEAN;
6948                         btrfs_crit(fs_info,
6949                 "regular/prealloc extent found for non-regular inode %llu",
6950                                    btrfs_ino(inode));
6951                         goto out;
6952                 }
6953                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6954                                                        extent_start);
6955         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6956                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6957                                                       path->slots[0],
6958                                                       extent_start);
6959         }
6960 next:
6961         if (start >= extent_end) {
6962                 path->slots[0]++;
6963                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6964                         ret = btrfs_next_leaf(root, path);
6965                         if (ret < 0)
6966                                 goto out;
6967                         else if (ret > 0)
6968                                 goto not_found;
6969
6970                         leaf = path->nodes[0];
6971                 }
6972                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6973                 if (found_key.objectid != objectid ||
6974                     found_key.type != BTRFS_EXTENT_DATA_KEY)
6975                         goto not_found;
6976                 if (start + len <= found_key.offset)
6977                         goto not_found;
6978                 if (start > found_key.offset)
6979                         goto next;
6980
6981                 /* New extent overlaps with existing one */
6982                 em->start = start;
6983                 em->orig_start = start;
6984                 em->len = found_key.offset - start;
6985                 em->block_start = EXTENT_MAP_HOLE;
6986                 goto insert;
6987         }
6988
6989         btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6990
6991         if (extent_type == BTRFS_FILE_EXTENT_REG ||
6992             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6993                 goto insert;
6994         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6995                 unsigned long ptr;
6996                 char *map;
6997                 size_t size;
6998                 size_t extent_offset;
6999                 size_t copy_size;
7000
7001                 if (!page)
7002                         goto out;
7003
7004                 size = btrfs_file_extent_ram_bytes(leaf, item);
7005                 extent_offset = page_offset(page) + pg_offset - extent_start;
7006                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
7007                                   size - extent_offset);
7008                 em->start = extent_start + extent_offset;
7009                 em->len = ALIGN(copy_size, fs_info->sectorsize);
7010                 em->orig_block_len = em->len;
7011                 em->orig_start = em->start;
7012                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
7013
7014                 if (!PageUptodate(page)) {
7015                         if (btrfs_file_extent_compression(leaf, item) !=
7016                             BTRFS_COMPRESS_NONE) {
7017                                 ret = uncompress_inline(path, page, pg_offset,
7018                                                         extent_offset, item);
7019                                 if (ret)
7020                                         goto out;
7021                         } else {
7022                                 map = kmap_local_page(page);
7023                                 read_extent_buffer(leaf, map + pg_offset, ptr,
7024                                                    copy_size);
7025                                 if (pg_offset + copy_size < PAGE_SIZE) {
7026                                         memset(map + pg_offset + copy_size, 0,
7027                                                PAGE_SIZE - pg_offset -
7028                                                copy_size);
7029                                 }
7030                                 kunmap_local(map);
7031                         }
7032                         flush_dcache_page(page);
7033                 }
7034                 set_extent_uptodate(io_tree, em->start,
7035                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
7036                 goto insert;
7037         }
7038 not_found:
7039         em->start = start;
7040         em->orig_start = start;
7041         em->len = len;
7042         em->block_start = EXTENT_MAP_HOLE;
7043 insert:
7044         ret = 0;
7045         btrfs_release_path(path);
7046         if (em->start > start || extent_map_end(em) <= start) {
7047                 btrfs_err(fs_info,
7048                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
7049                           em->start, em->len, start, len);
7050                 ret = -EIO;
7051                 goto out;
7052         }
7053
7054         write_lock(&em_tree->lock);
7055         ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7056         write_unlock(&em_tree->lock);
7057 out:
7058         btrfs_free_path(path);
7059
7060         trace_btrfs_get_extent(root, inode, em);
7061
7062         if (ret) {
7063                 free_extent_map(em);
7064                 return ERR_PTR(ret);
7065         }
7066         return em;
7067 }
7068
7069 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7070                                            u64 start, u64 len)
7071 {
7072         struct extent_map *em;
7073         struct extent_map *hole_em = NULL;
7074         u64 delalloc_start = start;
7075         u64 end;
7076         u64 delalloc_len;
7077         u64 delalloc_end;
7078         int err = 0;
7079
7080         em = btrfs_get_extent(inode, NULL, 0, start, len);
7081         if (IS_ERR(em))
7082                 return em;
7083         /*
7084          * If our em maps to:
7085          * - a hole or
7086          * - a pre-alloc extent,
7087          * there might actually be delalloc bytes behind it.
7088          */
7089         if (em->block_start != EXTENT_MAP_HOLE &&
7090             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7091                 return em;
7092         else
7093                 hole_em = em;
7094
7095         /* check to see if we've wrapped (len == -1 or similar) */
7096         end = start + len;
7097         if (end < start)
7098                 end = (u64)-1;
7099         else
7100                 end -= 1;
7101
7102         em = NULL;
7103
7104         /* ok, we didn't find anything, lets look for delalloc */
7105         delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
7106                                  end, len, EXTENT_DELALLOC, 1);
7107         delalloc_end = delalloc_start + delalloc_len;
7108         if (delalloc_end < delalloc_start)
7109                 delalloc_end = (u64)-1;
7110
7111         /*
7112          * We didn't find anything useful, return the original results from
7113          * get_extent()
7114          */
7115         if (delalloc_start > end || delalloc_end <= start) {
7116                 em = hole_em;
7117                 hole_em = NULL;
7118                 goto out;
7119         }
7120
7121         /*
7122          * Adjust the delalloc_start to make sure it doesn't go backwards from
7123          * the start they passed in
7124          */
7125         delalloc_start = max(start, delalloc_start);
7126         delalloc_len = delalloc_end - delalloc_start;
7127
7128         if (delalloc_len > 0) {
7129                 u64 hole_start;
7130                 u64 hole_len;
7131                 const u64 hole_end = extent_map_end(hole_em);
7132
7133                 em = alloc_extent_map();
7134                 if (!em) {
7135                         err = -ENOMEM;
7136                         goto out;
7137                 }
7138
7139                 ASSERT(hole_em);
7140                 /*
7141                  * When btrfs_get_extent can't find anything it returns one
7142                  * huge hole
7143                  *
7144                  * Make sure what it found really fits our range, and adjust to
7145                  * make sure it is based on the start from the caller
7146                  */
7147                 if (hole_end <= start || hole_em->start > end) {
7148                        free_extent_map(hole_em);
7149                        hole_em = NULL;
7150                 } else {
7151                        hole_start = max(hole_em->start, start);
7152                        hole_len = hole_end - hole_start;
7153                 }
7154
7155                 if (hole_em && delalloc_start > hole_start) {
7156                         /*
7157                          * Our hole starts before our delalloc, so we have to
7158                          * return just the parts of the hole that go until the
7159                          * delalloc starts
7160                          */
7161                         em->len = min(hole_len, delalloc_start - hole_start);
7162                         em->start = hole_start;
7163                         em->orig_start = hole_start;
7164                         /*
7165                          * Don't adjust block start at all, it is fixed at
7166                          * EXTENT_MAP_HOLE
7167                          */
7168                         em->block_start = hole_em->block_start;
7169                         em->block_len = hole_len;
7170                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7171                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7172                 } else {
7173                         /*
7174                          * Hole is out of passed range or it starts after
7175                          * delalloc range
7176                          */
7177                         em->start = delalloc_start;
7178                         em->len = delalloc_len;
7179                         em->orig_start = delalloc_start;
7180                         em->block_start = EXTENT_MAP_DELALLOC;
7181                         em->block_len = delalloc_len;
7182                 }
7183         } else {
7184                 return hole_em;
7185         }
7186 out:
7187
7188         free_extent_map(hole_em);
7189         if (err) {
7190                 free_extent_map(em);
7191                 return ERR_PTR(err);
7192         }
7193         return em;
7194 }
7195
7196 static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
7197                                                   const u64 start,
7198                                                   const u64 len,
7199                                                   const u64 orig_start,
7200                                                   const u64 block_start,
7201                                                   const u64 block_len,
7202                                                   const u64 orig_block_len,
7203                                                   const u64 ram_bytes,
7204                                                   const int type)
7205 {
7206         struct extent_map *em = NULL;
7207         int ret;
7208
7209         if (type != BTRFS_ORDERED_NOCOW) {
7210                 em = create_io_em(inode, start, len, orig_start, block_start,
7211                                   block_len, orig_block_len, ram_bytes,
7212                                   BTRFS_COMPRESS_NONE, /* compress_type */
7213                                   type);
7214                 if (IS_ERR(em))
7215                         goto out;
7216         }
7217         ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len,
7218                                            block_len, type);
7219         if (ret) {
7220                 if (em) {
7221                         free_extent_map(em);
7222                         btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
7223                 }
7224                 em = ERR_PTR(ret);
7225         }
7226  out:
7227
7228         return em;
7229 }
7230
7231 static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
7232                                                   u64 start, u64 len)
7233 {
7234         struct btrfs_root *root = inode->root;
7235         struct btrfs_fs_info *fs_info = root->fs_info;
7236         struct extent_map *em;
7237         struct btrfs_key ins;
7238         u64 alloc_hint;
7239         int ret;
7240
7241         alloc_hint = get_extent_allocation_hint(inode, start, len);
7242         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7243                                    0, alloc_hint, &ins, 1, 1);
7244         if (ret)
7245                 return ERR_PTR(ret);
7246
7247         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7248                                      ins.objectid, ins.offset, ins.offset,
7249                                      ins.offset, BTRFS_ORDERED_REGULAR);
7250         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7251         if (IS_ERR(em))
7252                 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
7253                                            1);
7254
7255         return em;
7256 }
7257
7258 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7259 {
7260         struct btrfs_block_group *block_group;
7261         bool readonly = false;
7262
7263         block_group = btrfs_lookup_block_group(fs_info, bytenr);
7264         if (!block_group || block_group->ro)
7265                 readonly = true;
7266         if (block_group)
7267                 btrfs_put_block_group(block_group);
7268         return readonly;
7269 }
7270
7271 /*
7272  * Check if we can do nocow write into the range [@offset, @offset + @len)
7273  *
7274  * @offset:     File offset
7275  * @len:        The length to write, will be updated to the nocow writeable
7276  *              range
7277  * @orig_start: (optional) Return the original file offset of the file extent
7278  * @orig_len:   (optional) Return the original on-disk length of the file extent
7279  * @ram_bytes:  (optional) Return the ram_bytes of the file extent
7280  * @strict:     if true, omit optimizations that might force us into unnecessary
7281  *              cow. e.g., don't trust generation number.
7282  *
7283  * Return:
7284  * >0   and update @len if we can do nocow write
7285  *  0   if we can't do nocow write
7286  * <0   if error happened
7287  *
7288  * NOTE: This only checks the file extents, caller is responsible to wait for
7289  *       any ordered extents.
7290  */
7291 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7292                               u64 *orig_start, u64 *orig_block_len,
7293                               u64 *ram_bytes, bool strict)
7294 {
7295         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7296         struct btrfs_path *path;
7297         int ret;
7298         struct extent_buffer *leaf;
7299         struct btrfs_root *root = BTRFS_I(inode)->root;
7300         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7301         struct btrfs_file_extent_item *fi;
7302         struct btrfs_key key;
7303         u64 disk_bytenr;
7304         u64 backref_offset;
7305         u64 extent_end;
7306         u64 num_bytes;
7307         int slot;
7308         int found_type;
7309         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7310
7311         path = btrfs_alloc_path();
7312         if (!path)
7313                 return -ENOMEM;
7314
7315         ret = btrfs_lookup_file_extent(NULL, root, path,
7316                         btrfs_ino(BTRFS_I(inode)), offset, 0);
7317         if (ret < 0)
7318                 goto out;
7319
7320         slot = path->slots[0];
7321         if (ret == 1) {
7322                 if (slot == 0) {
7323                         /* can't find the item, must cow */
7324                         ret = 0;
7325                         goto out;
7326                 }
7327                 slot--;
7328         }
7329         ret = 0;
7330         leaf = path->nodes[0];
7331         btrfs_item_key_to_cpu(leaf, &key, slot);
7332         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7333             key.type != BTRFS_EXTENT_DATA_KEY) {
7334                 /* not our file or wrong item type, must cow */
7335                 goto out;
7336         }
7337
7338         if (key.offset > offset) {
7339                 /* Wrong offset, must cow */
7340                 goto out;
7341         }
7342
7343         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7344         found_type = btrfs_file_extent_type(leaf, fi);
7345         if (found_type != BTRFS_FILE_EXTENT_REG &&
7346             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7347                 /* not a regular extent, must cow */
7348                 goto out;
7349         }
7350
7351         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7352                 goto out;
7353
7354         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7355         if (extent_end <= offset)
7356                 goto out;
7357
7358         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7359         if (disk_bytenr == 0)
7360                 goto out;
7361
7362         if (btrfs_file_extent_compression(leaf, fi) ||
7363             btrfs_file_extent_encryption(leaf, fi) ||
7364             btrfs_file_extent_other_encoding(leaf, fi))
7365                 goto out;
7366
7367         /*
7368          * Do the same check as in btrfs_cross_ref_exist but without the
7369          * unnecessary search.
7370          */
7371         if (!strict &&
7372             (btrfs_file_extent_generation(leaf, fi) <=
7373              btrfs_root_last_snapshot(&root->root_item)))
7374                 goto out;
7375
7376         backref_offset = btrfs_file_extent_offset(leaf, fi);
7377
7378         if (orig_start) {
7379                 *orig_start = key.offset - backref_offset;
7380                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7381                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7382         }
7383
7384         if (btrfs_extent_readonly(fs_info, disk_bytenr))
7385                 goto out;
7386
7387         num_bytes = min(offset + *len, extent_end) - offset;
7388         if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7389                 u64 range_end;
7390
7391                 range_end = round_up(offset + num_bytes,
7392                                      root->fs_info->sectorsize) - 1;
7393                 ret = test_range_bit(io_tree, offset, range_end,
7394                                      EXTENT_DELALLOC, 0, NULL);
7395                 if (ret) {
7396                         ret = -EAGAIN;
7397                         goto out;
7398                 }
7399         }
7400
7401         btrfs_release_path(path);
7402
7403         /*
7404          * look for other files referencing this extent, if we
7405          * find any we must cow
7406          */
7407
7408         ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7409                                     key.offset - backref_offset, disk_bytenr,
7410                                     strict);
7411         if (ret) {
7412                 ret = 0;
7413                 goto out;
7414         }
7415
7416         /*
7417          * adjust disk_bytenr and num_bytes to cover just the bytes
7418          * in this extent we are about to write.  If there
7419          * are any csums in that range we have to cow in order
7420          * to keep the csums correct
7421          */
7422         disk_bytenr += backref_offset;
7423         disk_bytenr += offset - key.offset;
7424         if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7425                 goto out;
7426         /*
7427          * all of the above have passed, it is safe to overwrite this extent
7428          * without cow
7429          */
7430         *len = num_bytes;
7431         ret = 1;
7432 out:
7433         btrfs_free_path(path);
7434         return ret;
7435 }
7436
7437 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7438                               struct extent_state **cached_state, bool writing)
7439 {
7440         struct btrfs_ordered_extent *ordered;
7441         int ret = 0;
7442
7443         while (1) {
7444                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7445                                  cached_state);
7446                 /*
7447                  * We're concerned with the entire range that we're going to be
7448                  * doing DIO to, so we need to make sure there's no ordered
7449                  * extents in this range.
7450                  */
7451                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7452                                                      lockend - lockstart + 1);
7453
7454                 /*
7455                  * We need to make sure there are no buffered pages in this
7456                  * range either, we could have raced between the invalidate in
7457                  * generic_file_direct_write and locking the extent.  The
7458                  * invalidate needs to happen so that reads after a write do not
7459                  * get stale data.
7460                  */
7461                 if (!ordered &&
7462                     (!writing || !filemap_range_has_page(inode->i_mapping,
7463                                                          lockstart, lockend)))
7464                         break;
7465
7466                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7467                                      cached_state);
7468
7469                 if (ordered) {
7470                         /*
7471                          * If we are doing a DIO read and the ordered extent we
7472                          * found is for a buffered write, we can not wait for it
7473                          * to complete and retry, because if we do so we can
7474                          * deadlock with concurrent buffered writes on page
7475                          * locks. This happens only if our DIO read covers more
7476                          * than one extent map, if at this point has already
7477                          * created an ordered extent for a previous extent map
7478                          * and locked its range in the inode's io tree, and a
7479                          * concurrent write against that previous extent map's
7480                          * range and this range started (we unlock the ranges
7481                          * in the io tree only when the bios complete and
7482                          * buffered writes always lock pages before attempting
7483                          * to lock range in the io tree).
7484                          */
7485                         if (writing ||
7486                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7487                                 btrfs_start_ordered_extent(ordered, 1);
7488                         else
7489                                 ret = -ENOTBLK;
7490                         btrfs_put_ordered_extent(ordered);
7491                 } else {
7492                         /*
7493                          * We could trigger writeback for this range (and wait
7494                          * for it to complete) and then invalidate the pages for
7495                          * this range (through invalidate_inode_pages2_range()),
7496                          * but that can lead us to a deadlock with a concurrent
7497                          * call to readahead (a buffered read or a defrag call
7498                          * triggered a readahead) on a page lock due to an
7499                          * ordered dio extent we created before but did not have
7500                          * yet a corresponding bio submitted (whence it can not
7501                          * complete), which makes readahead wait for that
7502                          * ordered extent to complete while holding a lock on
7503                          * that page.
7504                          */
7505                         ret = -ENOTBLK;
7506                 }
7507
7508                 if (ret)
7509                         break;
7510
7511                 cond_resched();
7512         }
7513
7514         return ret;
7515 }
7516
7517 /* The callers of this must take lock_extent() */
7518 static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
7519                                        u64 len, u64 orig_start, u64 block_start,
7520                                        u64 block_len, u64 orig_block_len,
7521                                        u64 ram_bytes, int compress_type,
7522                                        int type)
7523 {
7524         struct extent_map_tree *em_tree;
7525         struct extent_map *em;
7526         int ret;
7527
7528         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7529                type == BTRFS_ORDERED_COMPRESSED ||
7530                type == BTRFS_ORDERED_NOCOW ||
7531                type == BTRFS_ORDERED_REGULAR);
7532
7533         em_tree = &inode->extent_tree;
7534         em = alloc_extent_map();
7535         if (!em)
7536                 return ERR_PTR(-ENOMEM);
7537
7538         em->start = start;
7539         em->orig_start = orig_start;
7540         em->len = len;
7541         em->block_len = block_len;
7542         em->block_start = block_start;
7543         em->orig_block_len = orig_block_len;
7544         em->ram_bytes = ram_bytes;
7545         em->generation = -1;
7546         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7547         if (type == BTRFS_ORDERED_PREALLOC) {
7548                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7549         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7550                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7551                 em->compress_type = compress_type;
7552         }
7553
7554         do {
7555                 btrfs_drop_extent_cache(inode, em->start,
7556                                         em->start + em->len - 1, 0);
7557                 write_lock(&em_tree->lock);
7558                 ret = add_extent_mapping(em_tree, em, 1);
7559                 write_unlock(&em_tree->lock);
7560                 /*
7561                  * The caller has taken lock_extent(), who could race with us
7562                  * to add em?
7563                  */
7564         } while (ret == -EEXIST);
7565
7566         if (ret) {
7567                 free_extent_map(em);
7568                 return ERR_PTR(ret);
7569         }
7570
7571         /* em got 2 refs now, callers needs to do free_extent_map once. */
7572         return em;
7573 }
7574
7575
7576 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7577                                          struct inode *inode,
7578                                          struct btrfs_dio_data *dio_data,
7579                                          u64 start, u64 len)
7580 {
7581         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7582         struct extent_map *em = *map;
7583         int ret = 0;
7584
7585         /*
7586          * We don't allocate a new extent in the following cases
7587          *
7588          * 1) The inode is marked as NODATACOW. In this case we'll just use the
7589          * existing extent.
7590          * 2) The extent is marked as PREALLOC. We're good to go here and can
7591          * just use the extent.
7592          *
7593          */
7594         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7595             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7596              em->block_start != EXTENT_MAP_HOLE)) {
7597                 int type;
7598                 u64 block_start, orig_start, orig_block_len, ram_bytes;
7599
7600                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7601                         type = BTRFS_ORDERED_PREALLOC;
7602                 else
7603                         type = BTRFS_ORDERED_NOCOW;
7604                 len = min(len, em->len - (start - em->start));
7605                 block_start = em->block_start + (start - em->start);
7606
7607                 if (can_nocow_extent(inode, start, &len, &orig_start,
7608                                      &orig_block_len, &ram_bytes, false) == 1 &&
7609                     btrfs_inc_nocow_writers(fs_info, block_start)) {
7610                         struct extent_map *em2;
7611
7612                         em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
7613                                                       orig_start, block_start,
7614                                                       len, orig_block_len,
7615                                                       ram_bytes, type);
7616                         btrfs_dec_nocow_writers(fs_info, block_start);
7617                         if (type == BTRFS_ORDERED_PREALLOC) {
7618                                 free_extent_map(em);
7619                                 *map = em = em2;
7620                         }
7621
7622                         if (em2 && IS_ERR(em2)) {
7623                                 ret = PTR_ERR(em2);
7624                                 goto out;
7625                         }
7626                         /*
7627                          * For inode marked NODATACOW or extent marked PREALLOC,
7628                          * use the existing or preallocated extent, so does not
7629                          * need to adjust btrfs_space_info's bytes_may_use.
7630                          */
7631                         btrfs_free_reserved_data_space_noquota(fs_info, len);
7632                         goto skip_cow;
7633                 }
7634         }
7635
7636         /* this will cow the extent */
7637         free_extent_map(em);
7638         *map = em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
7639         if (IS_ERR(em)) {
7640                 ret = PTR_ERR(em);
7641                 goto out;
7642         }
7643
7644         len = min(len, em->len - (start - em->start));
7645
7646 skip_cow:
7647         /*
7648          * Need to update the i_size under the extent lock so buffered
7649          * readers will get the updated i_size when we unlock.
7650          */
7651         if (start + len > i_size_read(inode))
7652                 i_size_write(inode, start + len);
7653
7654         dio_data->reserve -= len;
7655 out:
7656         return ret;
7657 }
7658
7659 static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
7660                 loff_t length, unsigned int flags, struct iomap *iomap,
7661                 struct iomap *srcmap)
7662 {
7663         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7664         struct extent_map *em;
7665         struct extent_state *cached_state = NULL;
7666         struct btrfs_dio_data *dio_data = NULL;
7667         u64 lockstart, lockend;
7668         const bool write = !!(flags & IOMAP_WRITE);
7669         int ret = 0;
7670         u64 len = length;
7671         bool unlock_extents = false;
7672
7673         if (!write)
7674                 len = min_t(u64, len, fs_info->sectorsize);
7675
7676         lockstart = start;
7677         lockend = start + len - 1;
7678
7679         /*
7680          * The generic stuff only does filemap_write_and_wait_range, which
7681          * isn't enough if we've written compressed pages to this area, so we
7682          * need to flush the dirty pages again to make absolutely sure that any
7683          * outstanding dirty pages are on disk.
7684          */
7685         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7686                      &BTRFS_I(inode)->runtime_flags)) {
7687                 ret = filemap_fdatawrite_range(inode->i_mapping, start,
7688                                                start + length - 1);
7689                 if (ret)
7690                         return ret;
7691         }
7692
7693         dio_data = kzalloc(sizeof(*dio_data), GFP_NOFS);
7694         if (!dio_data)
7695                 return -ENOMEM;
7696
7697         dio_data->length = length;
7698         if (write) {
7699                 dio_data->reserve = round_up(length, fs_info->sectorsize);
7700                 ret = btrfs_delalloc_reserve_space(BTRFS_I(inode),
7701                                 &dio_data->data_reserved,
7702                                 start, dio_data->reserve);
7703                 if (ret) {
7704                         extent_changeset_free(dio_data->data_reserved);
7705                         kfree(dio_data);
7706                         return ret;
7707                 }
7708         }
7709         iomap->private = dio_data;
7710
7711
7712         /*
7713          * If this errors out it's because we couldn't invalidate pagecache for
7714          * this range and we need to fallback to buffered.
7715          */
7716         if (lock_extent_direct(inode, lockstart, lockend, &cached_state, write)) {
7717                 ret = -ENOTBLK;
7718                 goto err;
7719         }
7720
7721         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7722         if (IS_ERR(em)) {
7723                 ret = PTR_ERR(em);
7724                 goto unlock_err;
7725         }
7726
7727         /*
7728          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7729          * io.  INLINE is special, and we could probably kludge it in here, but
7730          * it's still buffered so for safety lets just fall back to the generic
7731          * buffered path.
7732          *
7733          * For COMPRESSED we _have_ to read the entire extent in so we can
7734          * decompress it, so there will be buffering required no matter what we
7735          * do, so go ahead and fallback to buffered.
7736          *
7737          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7738          * to buffered IO.  Don't blame me, this is the price we pay for using
7739          * the generic code.
7740          */
7741         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7742             em->block_start == EXTENT_MAP_INLINE) {
7743                 free_extent_map(em);
7744                 ret = -ENOTBLK;
7745                 goto unlock_err;
7746         }
7747
7748         len = min(len, em->len - (start - em->start));
7749         if (write) {
7750                 ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
7751                                                     start, len);
7752                 if (ret < 0)
7753                         goto unlock_err;
7754                 unlock_extents = true;
7755                 /* Recalc len in case the new em is smaller than requested */
7756                 len = min(len, em->len - (start - em->start));
7757         } else {
7758                 /*
7759                  * We need to unlock only the end area that we aren't using.
7760                  * The rest is going to be unlocked by the endio routine.
7761                  */
7762                 lockstart = start + len;
7763                 if (lockstart < lockend)
7764                         unlock_extents = true;
7765         }
7766
7767         if (unlock_extents)
7768                 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7769                                      lockstart, lockend, &cached_state);
7770         else
7771                 free_extent_state(cached_state);
7772
7773         /*
7774          * Translate extent map information to iomap.
7775          * We trim the extents (and move the addr) even though iomap code does
7776          * that, since we have locked only the parts we are performing I/O in.
7777          */
7778         if ((em->block_start == EXTENT_MAP_HOLE) ||
7779             (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
7780                 iomap->addr = IOMAP_NULL_ADDR;
7781                 iomap->type = IOMAP_HOLE;
7782         } else {
7783                 iomap->addr = em->block_start + (start - em->start);
7784                 iomap->type = IOMAP_MAPPED;
7785         }
7786         iomap->offset = start;
7787         iomap->bdev = fs_info->fs_devices->latest_bdev;
7788         iomap->length = len;
7789
7790         if (write && btrfs_use_zone_append(BTRFS_I(inode), em))
7791                 iomap->flags |= IOMAP_F_ZONE_APPEND;
7792
7793         free_extent_map(em);
7794
7795         return 0;
7796
7797 unlock_err:
7798         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7799                              &cached_state);
7800 err:
7801         if (dio_data) {
7802                 btrfs_delalloc_release_space(BTRFS_I(inode),
7803                                 dio_data->data_reserved, start,
7804                                 dio_data->reserve, true);
7805                 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->reserve);
7806                 extent_changeset_free(dio_data->data_reserved);
7807                 kfree(dio_data);
7808         }
7809         return ret;
7810 }
7811
7812 static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
7813                 ssize_t written, unsigned int flags, struct iomap *iomap)
7814 {
7815         int ret = 0;
7816         struct btrfs_dio_data *dio_data = iomap->private;
7817         size_t submitted = dio_data->submitted;
7818         const bool write = !!(flags & IOMAP_WRITE);
7819
7820         if (!write && (iomap->type == IOMAP_HOLE)) {
7821                 /* If reading from a hole, unlock and return */
7822                 unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1);
7823                 goto out;
7824         }
7825
7826         if (submitted < length) {
7827                 pos += submitted;
7828                 length -= submitted;
7829                 if (write)
7830                         __endio_write_update_ordered(BTRFS_I(inode), pos,
7831                                         length, false);
7832                 else
7833                         unlock_extent(&BTRFS_I(inode)->io_tree, pos,
7834                                       pos + length - 1);
7835                 ret = -ENOTBLK;
7836         }
7837
7838         if (write) {
7839                 if (dio_data->reserve)
7840                         btrfs_delalloc_release_space(BTRFS_I(inode),
7841                                         dio_data->data_reserved, pos,
7842                                         dio_data->reserve, true);
7843                 btrfs_delalloc_release_extents(BTRFS_I(inode), dio_data->length);
7844                 extent_changeset_free(dio_data->data_reserved);
7845         }
7846 out:
7847         kfree(dio_data);
7848         iomap->private = NULL;
7849
7850         return ret;
7851 }
7852
7853 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7854 {
7855         /*
7856          * This implies a barrier so that stores to dio_bio->bi_status before
7857          * this and loads of dio_bio->bi_status after this are fully ordered.
7858          */
7859         if (!refcount_dec_and_test(&dip->refs))
7860                 return;
7861
7862         if (btrfs_op(dip->dio_bio) == BTRFS_MAP_WRITE) {
7863                 __endio_write_update_ordered(BTRFS_I(dip->inode),
7864                                              dip->logical_offset,
7865                                              dip->bytes,
7866                                              !dip->dio_bio->bi_status);
7867         } else {
7868                 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7869                               dip->logical_offset,
7870                               dip->logical_offset + dip->bytes - 1);
7871         }
7872
7873         bio_endio(dip->dio_bio);
7874         kfree(dip);
7875 }
7876
7877 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7878                                           int mirror_num,
7879                                           unsigned long bio_flags)
7880 {
7881         struct btrfs_dio_private *dip = bio->bi_private;
7882         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7883         blk_status_t ret;
7884
7885         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7886
7887         ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7888         if (ret)
7889                 return ret;
7890
7891         refcount_inc(&dip->refs);
7892         ret = btrfs_map_bio(fs_info, bio, mirror_num);
7893         if (ret)
7894                 refcount_dec(&dip->refs);
7895         return ret;
7896 }
7897
7898 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7899                                              struct btrfs_io_bio *io_bio,
7900                                              const bool uptodate)
7901 {
7902         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7903         const u32 sectorsize = fs_info->sectorsize;
7904         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7905         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7906         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7907         struct bio_vec bvec;
7908         struct bvec_iter iter;
7909         u64 start = io_bio->logical;
7910         u32 bio_offset = 0;
7911         blk_status_t err = BLK_STS_OK;
7912
7913         __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7914                 unsigned int i, nr_sectors, pgoff;
7915
7916                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7917                 pgoff = bvec.bv_offset;
7918                 for (i = 0; i < nr_sectors; i++) {
7919                         ASSERT(pgoff < PAGE_SIZE);
7920                         if (uptodate &&
7921                             (!csum || !check_data_csum(inode, io_bio,
7922                                                        bio_offset, bvec.bv_page,
7923                                                        pgoff, start))) {
7924                                 clean_io_failure(fs_info, failure_tree, io_tree,
7925                                                  start, bvec.bv_page,
7926                                                  btrfs_ino(BTRFS_I(inode)),
7927                                                  pgoff);
7928                         } else {
7929                                 blk_status_t status;
7930
7931                                 ASSERT((start - io_bio->logical) < UINT_MAX);
7932                                 status = btrfs_submit_read_repair(inode,
7933                                                         &io_bio->bio,
7934                                                         start - io_bio->logical,
7935                                                         bvec.bv_page, pgoff,
7936                                                         start,
7937                                                         start + sectorsize - 1,
7938                                                         io_bio->mirror_num,
7939                                                         submit_dio_repair_bio);
7940                                 if (status)
7941                                         err = status;
7942                         }
7943                         start += sectorsize;
7944                         ASSERT(bio_offset + sectorsize > bio_offset);
7945                         bio_offset += sectorsize;
7946                         pgoff += sectorsize;
7947                 }
7948         }
7949         return err;
7950 }
7951
7952 static void __endio_write_update_ordered(struct btrfs_inode *inode,
7953                                          const u64 offset, const u64 bytes,
7954                                          const bool uptodate)
7955 {
7956         struct btrfs_fs_info *fs_info = inode->root->fs_info;
7957         struct btrfs_ordered_extent *ordered = NULL;
7958         struct btrfs_workqueue *wq;
7959         u64 ordered_offset = offset;
7960         u64 ordered_bytes = bytes;
7961         u64 last_offset;
7962
7963         if (btrfs_is_free_space_inode(inode))
7964                 wq = fs_info->endio_freespace_worker;
7965         else
7966                 wq = fs_info->endio_write_workers;
7967
7968         while (ordered_offset < offset + bytes) {
7969                 last_offset = ordered_offset;
7970                 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7971                                                          &ordered_offset,
7972                                                          ordered_bytes,
7973                                                          uptodate)) {
7974                         btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7975                                         NULL);
7976                         btrfs_queue_work(wq, &ordered->work);
7977                 }
7978
7979                 /* No ordered extent found in the range, exit */
7980                 if (ordered_offset == last_offset)
7981                         return;
7982                 /*
7983                  * Our bio might span multiple ordered extents. In this case
7984                  * we keep going until we have accounted the whole dio.
7985                  */
7986                 if (ordered_offset < offset + bytes) {
7987                         ordered_bytes = offset + bytes - ordered_offset;
7988                         ordered = NULL;
7989                 }
7990         }
7991 }
7992
7993 static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
7994                                                      struct bio *bio,
7995                                                      u64 dio_file_offset)
7996 {
7997         return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, 1);
7998 }
7999
8000 static void btrfs_end_dio_bio(struct bio *bio)
8001 {
8002         struct btrfs_dio_private *dip = bio->bi_private;
8003         blk_status_t err = bio->bi_status;
8004
8005         if (err)
8006                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8007                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8008                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8009                            bio->bi_opf, bio->bi_iter.bi_sector,
8010                            bio->bi_iter.bi_size, err);
8011
8012         if (bio_op(bio) == REQ_OP_READ) {
8013                 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
8014                                                !err);
8015         }
8016
8017         if (err)
8018                 dip->dio_bio->bi_status = err;
8019
8020         btrfs_record_physical_zoned(dip->inode, dip->logical_offset, bio);
8021
8022         bio_put(bio);
8023         btrfs_dio_private_put(dip);
8024 }
8025
8026 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8027                 struct inode *inode, u64 file_offset, int async_submit)
8028 {
8029         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8030         struct btrfs_dio_private *dip = bio->bi_private;
8031         bool write = btrfs_op(bio) == BTRFS_MAP_WRITE;
8032         blk_status_t ret;
8033
8034         /* Check btrfs_submit_bio_hook() for rules about async submit. */
8035         if (async_submit)
8036                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8037
8038         if (!write) {
8039                 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8040                 if (ret)
8041                         goto err;
8042         }
8043
8044         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8045                 goto map;
8046
8047         if (write && async_submit) {
8048                 ret = btrfs_wq_submit_bio(inode, bio, 0, 0, file_offset,
8049                                           btrfs_submit_bio_start_direct_io);
8050                 goto err;
8051         } else if (write) {
8052                 /*
8053                  * If we aren't doing async submit, calculate the csum of the
8054                  * bio now.
8055                  */
8056                 ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, 1);
8057                 if (ret)
8058                         goto err;
8059         } else {
8060                 u64 csum_offset;
8061
8062                 csum_offset = file_offset - dip->logical_offset;
8063                 csum_offset >>= fs_info->sectorsize_bits;
8064                 csum_offset *= fs_info->csum_size;
8065                 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
8066         }
8067 map:
8068         ret = btrfs_map_bio(fs_info, bio, 0);
8069 err:
8070         return ret;
8071 }
8072
8073 /*
8074  * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
8075  * or ordered extents whether or not we submit any bios.
8076  */
8077 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
8078                                                           struct inode *inode,
8079                                                           loff_t file_offset)
8080 {
8081         const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8082         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
8083         size_t dip_size;
8084         struct btrfs_dio_private *dip;
8085
8086         dip_size = sizeof(*dip);
8087         if (!write && csum) {
8088                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8089                 size_t nblocks;
8090
8091                 nblocks = dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits;
8092                 dip_size += fs_info->csum_size * nblocks;
8093         }
8094
8095         dip = kzalloc(dip_size, GFP_NOFS);
8096         if (!dip)
8097                 return NULL;
8098
8099         dip->inode = inode;
8100         dip->logical_offset = file_offset;
8101         dip->bytes = dio_bio->bi_iter.bi_size;
8102         dip->disk_bytenr = dio_bio->bi_iter.bi_sector << 9;
8103         dip->dio_bio = dio_bio;
8104         refcount_set(&dip->refs, 1);
8105         return dip;
8106 }
8107
8108 static blk_qc_t btrfs_submit_direct(struct inode *inode, struct iomap *iomap,
8109                 struct bio *dio_bio, loff_t file_offset)
8110 {
8111         const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
8112         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8113         const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
8114                              BTRFS_BLOCK_GROUP_RAID56_MASK);
8115         struct btrfs_dio_private *dip;
8116         struct bio *bio;
8117         u64 start_sector;
8118         int async_submit = 0;
8119         u64 submit_len;
8120         int clone_offset = 0;
8121         int clone_len;
8122         u64 logical;
8123         int ret;
8124         blk_status_t status;
8125         struct btrfs_io_geometry geom;
8126         struct btrfs_dio_data *dio_data = iomap->private;
8127         struct extent_map *em = NULL;
8128
8129         dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
8130         if (!dip) {
8131                 if (!write) {
8132                         unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8133                                 file_offset + dio_bio->bi_iter.bi_size - 1);
8134                 }
8135                 dio_bio->bi_status = BLK_STS_RESOURCE;
8136                 bio_endio(dio_bio);
8137                 return BLK_QC_T_NONE;
8138         }
8139
8140         if (!write) {
8141                 /*
8142                  * Load the csums up front to reduce csum tree searches and
8143                  * contention when submitting bios.
8144                  *
8145                  * If we have csums disabled this will do nothing.
8146                  */
8147                 status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
8148                 if (status != BLK_STS_OK)
8149                         goto out_err;
8150         }
8151
8152         start_sector = dio_bio->bi_iter.bi_sector;
8153         submit_len = dio_bio->bi_iter.bi_size;
8154
8155         do {
8156                 logical = start_sector << 9;
8157                 em = btrfs_get_chunk_map(fs_info, logical, submit_len);
8158                 if (IS_ERR(em)) {
8159                         status = errno_to_blk_status(PTR_ERR(em));
8160                         em = NULL;
8161                         goto out_err_em;
8162                 }
8163                 ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
8164                                             logical, submit_len, &geom);
8165                 if (ret) {
8166                         status = errno_to_blk_status(ret);
8167                         goto out_err_em;
8168                 }
8169                 ASSERT(geom.len <= INT_MAX);
8170
8171                 clone_len = min_t(int, submit_len, geom.len);
8172
8173                 /*
8174                  * This will never fail as it's passing GPF_NOFS and
8175                  * the allocation is backed by btrfs_bioset.
8176                  */
8177                 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
8178                 bio->bi_private = dip;
8179                 bio->bi_end_io = btrfs_end_dio_bio;
8180                 btrfs_io_bio(bio)->logical = file_offset;
8181
8182                 if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
8183                         status = extract_ordered_extent(BTRFS_I(inode), bio,
8184                                                         file_offset);
8185                         if (status) {
8186                                 bio_put(bio);
8187                                 goto out_err;
8188                         }
8189                 }
8190
8191                 ASSERT(submit_len >= clone_len);
8192                 submit_len -= clone_len;
8193
8194                 /*
8195                  * Increase the count before we submit the bio so we know
8196                  * the end IO handler won't happen before we increase the
8197                  * count. Otherwise, the dip might get freed before we're
8198                  * done setting it up.
8199                  *
8200                  * We transfer the initial reference to the last bio, so we
8201                  * don't need to increment the reference count for the last one.
8202                  */
8203                 if (submit_len > 0) {
8204                         refcount_inc(&dip->refs);
8205                         /*
8206                          * If we are submitting more than one bio, submit them
8207                          * all asynchronously. The exception is RAID 5 or 6, as
8208                          * asynchronous checksums make it difficult to collect
8209                          * full stripe writes.
8210                          */
8211                         if (!raid56)
8212                                 async_submit = 1;
8213                 }
8214
8215                 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8216                                                 async_submit);
8217                 if (status) {
8218                         bio_put(bio);
8219                         if (submit_len > 0)
8220                                 refcount_dec(&dip->refs);
8221                         goto out_err_em;
8222                 }
8223
8224                 dio_data->submitted += clone_len;
8225                 clone_offset += clone_len;
8226                 start_sector += clone_len >> 9;
8227                 file_offset += clone_len;
8228
8229                 free_extent_map(em);
8230         } while (submit_len > 0);
8231         return BLK_QC_T_NONE;
8232
8233 out_err_em:
8234         free_extent_map(em);
8235 out_err:
8236         dip->dio_bio->bi_status = status;
8237         btrfs_dio_private_put(dip);
8238
8239         return BLK_QC_T_NONE;
8240 }
8241
8242 const struct iomap_ops btrfs_dio_iomap_ops = {
8243         .iomap_begin            = btrfs_dio_iomap_begin,
8244         .iomap_end              = btrfs_dio_iomap_end,
8245 };
8246
8247 const struct iomap_dio_ops btrfs_dio_ops = {
8248         .submit_io              = btrfs_submit_direct,
8249 };
8250
8251 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8252                         u64 start, u64 len)
8253 {
8254         int     ret;
8255
8256         ret = fiemap_prep(inode, fieinfo, start, &len, 0);
8257         if (ret)
8258                 return ret;
8259
8260         return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
8261 }
8262
8263 int btrfs_readpage(struct file *file, struct page *page)
8264 {
8265         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8266         u64 start = page_offset(page);
8267         u64 end = start + PAGE_SIZE - 1;
8268         unsigned long bio_flags = 0;
8269         struct bio *bio = NULL;
8270         int ret;
8271
8272         btrfs_lock_and_flush_ordered_range(inode, start, end, NULL);
8273
8274         ret = btrfs_do_readpage(page, NULL, &bio, &bio_flags, 0, NULL);
8275         if (bio)
8276                 ret = submit_one_bio(bio, 0, bio_flags);
8277         return ret;
8278 }
8279
8280 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8281 {
8282         struct inode *inode = page->mapping->host;
8283         int ret;
8284
8285         if (current->flags & PF_MEMALLOC) {
8286                 redirty_page_for_writepage(wbc, page);
8287                 unlock_page(page);
8288                 return 0;
8289         }
8290
8291         /*
8292          * If we are under memory pressure we will call this directly from the
8293          * VM, we need to make sure we have the inode referenced for the ordered
8294          * extent.  If not just return like we didn't do anything.
8295          */
8296         if (!igrab(inode)) {
8297                 redirty_page_for_writepage(wbc, page);
8298                 return AOP_WRITEPAGE_ACTIVATE;
8299         }
8300         ret = extent_write_full_page(page, wbc);
8301         btrfs_add_delayed_iput(inode);
8302         return ret;
8303 }
8304
8305 static int btrfs_writepages(struct address_space *mapping,
8306                             struct writeback_control *wbc)
8307 {
8308         return extent_writepages(mapping, wbc);
8309 }
8310
8311 static void btrfs_readahead(struct readahead_control *rac)
8312 {
8313         extent_readahead(rac);
8314 }
8315
8316 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8317 {
8318         int ret = try_release_extent_mapping(page, gfp_flags);
8319         if (ret == 1)
8320                 clear_page_extent_mapped(page);
8321         return ret;
8322 }
8323
8324 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8325 {
8326         if (PageWriteback(page) || PageDirty(page))
8327                 return 0;
8328         return __btrfs_releasepage(page, gfp_flags);
8329 }
8330
8331 #ifdef CONFIG_MIGRATION
8332 static int btrfs_migratepage(struct address_space *mapping,
8333                              struct page *newpage, struct page *page,
8334                              enum migrate_mode mode)
8335 {
8336         int ret;
8337
8338         ret = migrate_page_move_mapping(mapping, newpage, page, 0);
8339         if (ret != MIGRATEPAGE_SUCCESS)
8340                 return ret;
8341
8342         if (page_has_private(page))
8343                 attach_page_private(newpage, detach_page_private(page));
8344
8345         if (PagePrivate2(page)) {
8346                 ClearPagePrivate2(page);
8347                 SetPagePrivate2(newpage);
8348         }
8349
8350         if (mode != MIGRATE_SYNC_NO_COPY)
8351                 migrate_page_copy(newpage, page);
8352         else
8353                 migrate_page_states(newpage, page);
8354         return MIGRATEPAGE_SUCCESS;
8355 }
8356 #endif
8357
8358 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8359                                  unsigned int length)
8360 {
8361         struct btrfs_inode *inode = BTRFS_I(page->mapping->host);
8362         struct extent_io_tree *tree = &inode->io_tree;
8363         struct btrfs_ordered_extent *ordered;
8364         struct extent_state *cached_state = NULL;
8365         u64 page_start = page_offset(page);
8366         u64 page_end = page_start + PAGE_SIZE - 1;
8367         u64 start;
8368         u64 end;
8369         int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
8370         bool found_ordered = false;
8371         bool completed_ordered = false;
8372
8373         /*
8374          * we have the page locked, so new writeback can't start,
8375          * and the dirty bit won't be cleared while we are here.
8376          *
8377          * Wait for IO on this page so that we can safely clear
8378          * the PagePrivate2 bit and do ordered accounting
8379          */
8380         wait_on_page_writeback(page);
8381
8382         if (offset) {
8383                 btrfs_releasepage(page, GFP_NOFS);
8384                 return;
8385         }
8386
8387         if (!inode_evicting)
8388                 lock_extent_bits(tree, page_start, page_end, &cached_state);
8389
8390         start = page_start;
8391 again:
8392         ordered = btrfs_lookup_ordered_range(inode, start, page_end - start + 1);
8393         if (ordered) {
8394                 found_ordered = true;
8395                 end = min(page_end,
8396                           ordered->file_offset + ordered->num_bytes - 1);
8397                 /*
8398                  * IO on this page will never be started, so we need to account
8399                  * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
8400                  * here, must leave that up for the ordered extent completion.
8401                  */
8402                 if (!inode_evicting)
8403                         clear_extent_bit(tree, start, end,
8404                                          EXTENT_DELALLOC |
8405                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8406                                          EXTENT_DEFRAG, 1, 0, &cached_state);
8407                 /*
8408                  * whoever cleared the private bit is responsible
8409                  * for the finish_ordered_io
8410                  */
8411                 if (TestClearPagePrivate2(page)) {
8412                         struct btrfs_ordered_inode_tree *tree;
8413                         u64 new_len;
8414
8415                         tree = &inode->ordered_tree;
8416
8417                         spin_lock_irq(&tree->lock);
8418                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8419                         new_len = start - ordered->file_offset;
8420                         if (new_len < ordered->truncated_len)
8421                                 ordered->truncated_len = new_len;
8422                         spin_unlock_irq(&tree->lock);
8423
8424                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
8425                                                            start,
8426                                                            end - start + 1, 1)) {
8427                                 btrfs_finish_ordered_io(ordered);
8428                                 completed_ordered = true;
8429                         }
8430                 }
8431                 btrfs_put_ordered_extent(ordered);
8432                 if (!inode_evicting) {
8433                         cached_state = NULL;
8434                         lock_extent_bits(tree, start, end,
8435                                          &cached_state);
8436                 }
8437
8438                 start = end + 1;
8439                 if (start < page_end)
8440                         goto again;
8441         }
8442
8443         /*
8444          * Qgroup reserved space handler
8445          * Page here will be either
8446          * 1) Already written to disk or ordered extent already submitted
8447          *    Then its QGROUP_RESERVED bit in io_tree is already cleaned.
8448          *    Qgroup will be handled by its qgroup_record then.
8449          *    btrfs_qgroup_free_data() call will do nothing here.
8450          *
8451          * 2) Not written to disk yet
8452          *    Then btrfs_qgroup_free_data() call will clear the QGROUP_RESERVED
8453          *    bit of its io_tree, and free the qgroup reserved data space.
8454          *    Since the IO will never happen for this page.
8455          */
8456         btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8457         if (!inode_evicting) {
8458                 bool delete = true;
8459
8460                 /*
8461                  * If there's an ordered extent for this range and we have not
8462                  * finished it ourselves, we must leave EXTENT_DELALLOC_NEW set
8463                  * in the range for the ordered extent completion. We must also
8464                  * not delete the range, otherwise we would lose that bit (and
8465                  * any other bits set in the range). Make sure EXTENT_UPTODATE
8466                  * is cleared if we don't delete, otherwise it can lead to
8467                  * corruptions if the i_size is extented later.
8468                  */
8469                 if (found_ordered && !completed_ordered)
8470                         delete = false;
8471                 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8472                                  EXTENT_DELALLOC | EXTENT_UPTODATE |
8473                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1,
8474                                  delete, &cached_state);
8475
8476                 __btrfs_releasepage(page, GFP_NOFS);
8477         }
8478
8479         ClearPageChecked(page);
8480         clear_page_extent_mapped(page);
8481 }
8482
8483 /*
8484  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8485  * called from a page fault handler when a page is first dirtied. Hence we must
8486  * be careful to check for EOF conditions here. We set the page up correctly
8487  * for a written page which means we get ENOSPC checking when writing into
8488  * holes and correct delalloc and unwritten extent mapping on filesystems that
8489  * support these features.
8490  *
8491  * We are not allowed to take the i_mutex here so we have to play games to
8492  * protect against truncate races as the page could now be beyond EOF.  Because
8493  * truncate_setsize() writes the inode size before removing pages, once we have
8494  * the page lock we can determine safely if the page is beyond EOF. If it is not
8495  * beyond EOF, then the page is guaranteed safe against truncation until we
8496  * unlock the page.
8497  */
8498 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8499 {
8500         struct page *page = vmf->page;
8501         struct inode *inode = file_inode(vmf->vma->vm_file);
8502         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8503         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8504         struct btrfs_ordered_extent *ordered;
8505         struct extent_state *cached_state = NULL;
8506         struct extent_changeset *data_reserved = NULL;
8507         char *kaddr;
8508         unsigned long zero_start;
8509         loff_t size;
8510         vm_fault_t ret;
8511         int ret2;
8512         int reserved = 0;
8513         u64 reserved_space;
8514         u64 page_start;
8515         u64 page_end;
8516         u64 end;
8517
8518         reserved_space = PAGE_SIZE;
8519
8520         sb_start_pagefault(inode->i_sb);
8521         page_start = page_offset(page);
8522         page_end = page_start + PAGE_SIZE - 1;
8523         end = page_end;
8524
8525         /*
8526          * Reserving delalloc space after obtaining the page lock can lead to
8527          * deadlock. For example, if a dirty page is locked by this function
8528          * and the call to btrfs_delalloc_reserve_space() ends up triggering
8529          * dirty page write out, then the btrfs_writepage() function could
8530          * end up waiting indefinitely to get a lock on the page currently
8531          * being processed by btrfs_page_mkwrite() function.
8532          */
8533         ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
8534                                             page_start, reserved_space);
8535         if (!ret2) {
8536                 ret2 = file_update_time(vmf->vma->vm_file);
8537                 reserved = 1;
8538         }
8539         if (ret2) {
8540                 ret = vmf_error(ret2);
8541                 if (reserved)
8542                         goto out;
8543                 goto out_noreserve;
8544         }
8545
8546         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8547 again:
8548         down_read(&BTRFS_I(inode)->i_mmap_lock);
8549         lock_page(page);
8550         size = i_size_read(inode);
8551
8552         if ((page->mapping != inode->i_mapping) ||
8553             (page_start >= size)) {
8554                 /* page got truncated out from underneath us */
8555                 goto out_unlock;
8556         }
8557         wait_on_page_writeback(page);
8558
8559         lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8560         ret2 = set_page_extent_mapped(page);
8561         if (ret2 < 0) {
8562                 ret = vmf_error(ret2);
8563                 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8564                 goto out_unlock;
8565         }
8566
8567         /*
8568          * we can't set the delalloc bits if there are pending ordered
8569          * extents.  Drop our locks and wait for them to finish
8570          */
8571         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8572                         PAGE_SIZE);
8573         if (ordered) {
8574                 unlock_extent_cached(io_tree, page_start, page_end,
8575                                      &cached_state);
8576                 unlock_page(page);
8577                 up_read(&BTRFS_I(inode)->i_mmap_lock);
8578                 btrfs_start_ordered_extent(ordered, 1);
8579                 btrfs_put_ordered_extent(ordered);
8580                 goto again;
8581         }
8582
8583         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8584                 reserved_space = round_up(size - page_start,
8585                                           fs_info->sectorsize);
8586                 if (reserved_space < PAGE_SIZE) {
8587                         end = page_start + reserved_space - 1;
8588                         btrfs_delalloc_release_space(BTRFS_I(inode),
8589                                         data_reserved, page_start,
8590                                         PAGE_SIZE - reserved_space, true);
8591                 }
8592         }
8593
8594         /*
8595          * page_mkwrite gets called when the page is firstly dirtied after it's
8596          * faulted in, but write(2) could also dirty a page and set delalloc
8597          * bits, thus in this case for space account reason, we still need to
8598          * clear any delalloc bits within this page range since we have to
8599          * reserve data&meta space before lock_page() (see above comments).
8600          */
8601         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8602                           EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8603                           EXTENT_DEFRAG, 0, 0, &cached_state);
8604
8605         ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
8606                                         &cached_state);
8607         if (ret2) {
8608                 unlock_extent_cached(io_tree, page_start, page_end,
8609                                      &cached_state);
8610                 ret = VM_FAULT_SIGBUS;
8611                 goto out_unlock;
8612         }
8613
8614         /* page is wholly or partially inside EOF */
8615         if (page_start + PAGE_SIZE > size)
8616                 zero_start = offset_in_page(size);
8617         else
8618                 zero_start = PAGE_SIZE;
8619
8620         if (zero_start != PAGE_SIZE) {
8621                 kaddr = kmap(page);
8622                 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8623                 flush_dcache_page(page);
8624                 kunmap(page);
8625         }
8626         ClearPageChecked(page);
8627         set_page_dirty(page);
8628         SetPageUptodate(page);
8629
8630         btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
8631
8632         unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8633         up_read(&BTRFS_I(inode)->i_mmap_lock);
8634
8635         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8636         sb_end_pagefault(inode->i_sb);
8637         extent_changeset_free(data_reserved);
8638         return VM_FAULT_LOCKED;
8639
8640 out_unlock:
8641         unlock_page(page);
8642         up_read(&BTRFS_I(inode)->i_mmap_lock);
8643 out:
8644         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8645         btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
8646                                      reserved_space, (ret != 0));
8647 out_noreserve:
8648         sb_end_pagefault(inode->i_sb);
8649         extent_changeset_free(data_reserved);
8650         return ret;
8651 }
8652
8653 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8654 {
8655         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8656         struct btrfs_root *root = BTRFS_I(inode)->root;
8657         struct btrfs_block_rsv *rsv;
8658         int ret;
8659         struct btrfs_trans_handle *trans;
8660         u64 mask = fs_info->sectorsize - 1;
8661         u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8662
8663         if (!skip_writeback) {
8664                 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8665                                                (u64)-1);
8666                 if (ret)
8667                         return ret;
8668         }
8669
8670         /*
8671          * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
8672          * things going on here:
8673          *
8674          * 1) We need to reserve space to update our inode.
8675          *
8676          * 2) We need to have something to cache all the space that is going to
8677          * be free'd up by the truncate operation, but also have some slack
8678          * space reserved in case it uses space during the truncate (thank you
8679          * very much snapshotting).
8680          *
8681          * And we need these to be separate.  The fact is we can use a lot of
8682          * space doing the truncate, and we have no earthly idea how much space
8683          * we will use, so we need the truncate reservation to be separate so it
8684          * doesn't end up using space reserved for updating the inode.  We also
8685          * need to be able to stop the transaction and start a new one, which
8686          * means we need to be able to update the inode several times, and we
8687          * have no idea of knowing how many times that will be, so we can't just
8688          * reserve 1 item for the entirety of the operation, so that has to be
8689          * done separately as well.
8690          *
8691          * So that leaves us with
8692          *
8693          * 1) rsv - for the truncate reservation, which we will steal from the
8694          * transaction reservation.
8695          * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8696          * updating the inode.
8697          */
8698         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8699         if (!rsv)
8700                 return -ENOMEM;
8701         rsv->size = min_size;
8702         rsv->failfast = 1;
8703
8704         /*
8705          * 1 for the truncate slack space
8706          * 1 for updating the inode.
8707          */
8708         trans = btrfs_start_transaction(root, 2);
8709         if (IS_ERR(trans)) {
8710                 ret = PTR_ERR(trans);
8711                 goto out;
8712         }
8713
8714         /* Migrate the slack space for the truncate to our reserve */
8715         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8716                                       min_size, false);
8717         BUG_ON(ret);
8718
8719         /*
8720          * So if we truncate and then write and fsync we normally would just
8721          * write the extents that changed, which is a problem if we need to
8722          * first truncate that entire inode.  So set this flag so we write out
8723          * all of the extents in the inode to the sync log so we're completely
8724          * safe.
8725          */
8726         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8727         trans->block_rsv = rsv;
8728
8729         while (1) {
8730                 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
8731                                                  inode->i_size,
8732                                                  BTRFS_EXTENT_DATA_KEY);
8733                 trans->block_rsv = &fs_info->trans_block_rsv;
8734                 if (ret != -ENOSPC && ret != -EAGAIN)
8735                         break;
8736
8737                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
8738                 if (ret)
8739                         break;
8740
8741                 btrfs_end_transaction(trans);
8742                 btrfs_btree_balance_dirty(fs_info);
8743
8744                 trans = btrfs_start_transaction(root, 2);
8745                 if (IS_ERR(trans)) {
8746                         ret = PTR_ERR(trans);
8747                         trans = NULL;
8748                         break;
8749                 }
8750
8751                 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8752                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8753                                               rsv, min_size, false);
8754                 BUG_ON(ret);    /* shouldn't happen */
8755                 trans->block_rsv = rsv;
8756         }
8757
8758         /*
8759          * We can't call btrfs_truncate_block inside a trans handle as we could
8760          * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8761          * we've truncated everything except the last little bit, and can do
8762          * btrfs_truncate_block and then update the disk_i_size.
8763          */
8764         if (ret == NEED_TRUNCATE_BLOCK) {
8765                 btrfs_end_transaction(trans);
8766                 btrfs_btree_balance_dirty(fs_info);
8767
8768                 ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
8769                 if (ret)
8770                         goto out;
8771                 trans = btrfs_start_transaction(root, 1);
8772                 if (IS_ERR(trans)) {
8773                         ret = PTR_ERR(trans);
8774                         goto out;
8775                 }
8776                 btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
8777         }
8778
8779         if (trans) {
8780                 int ret2;
8781
8782                 trans->block_rsv = &fs_info->trans_block_rsv;
8783                 ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
8784                 if (ret2 && !ret)
8785                         ret = ret2;
8786
8787                 ret2 = btrfs_end_transaction(trans);
8788                 if (ret2 && !ret)
8789                         ret = ret2;
8790                 btrfs_btree_balance_dirty(fs_info);
8791         }
8792 out:
8793         btrfs_free_block_rsv(fs_info, rsv);
8794
8795         return ret;
8796 }
8797
8798 /*
8799  * create a new subvolume directory/inode (helper for the ioctl).
8800  */
8801 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8802                              struct btrfs_root *new_root,
8803                              struct btrfs_root *parent_root)
8804 {
8805         struct inode *inode;
8806         int err;
8807         u64 index = 0;
8808         u64 ino;
8809
8810         err = btrfs_get_free_objectid(new_root, &ino);
8811         if (err < 0)
8812                 return err;
8813
8814         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, ino, ino,
8815                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
8816                                 &index);
8817         if (IS_ERR(inode))
8818                 return PTR_ERR(inode);
8819         inode->i_op = &btrfs_dir_inode_operations;
8820         inode->i_fop = &btrfs_dir_file_operations;
8821
8822         set_nlink(inode, 1);
8823         btrfs_i_size_write(BTRFS_I(inode), 0);
8824         unlock_new_inode(inode);
8825
8826         err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8827         if (err)
8828                 btrfs_err(new_root->fs_info,
8829                           "error inheriting subvolume %llu properties: %d",
8830                           new_root->root_key.objectid, err);
8831
8832         err = btrfs_update_inode(trans, new_root, BTRFS_I(inode));
8833
8834         iput(inode);
8835         return err;
8836 }
8837
8838 struct inode *btrfs_alloc_inode(struct super_block *sb)
8839 {
8840         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8841         struct btrfs_inode *ei;
8842         struct inode *inode;
8843
8844         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8845         if (!ei)
8846                 return NULL;
8847
8848         ei->root = NULL;
8849         ei->generation = 0;
8850         ei->last_trans = 0;
8851         ei->last_sub_trans = 0;
8852         ei->logged_trans = 0;
8853         ei->delalloc_bytes = 0;
8854         ei->new_delalloc_bytes = 0;
8855         ei->defrag_bytes = 0;
8856         ei->disk_i_size = 0;
8857         ei->flags = 0;
8858         ei->csum_bytes = 0;
8859         ei->index_cnt = (u64)-1;
8860         ei->dir_index = 0;
8861         ei->last_unlink_trans = 0;
8862         ei->last_reflink_trans = 0;
8863         ei->last_log_commit = 0;
8864
8865         spin_lock_init(&ei->lock);
8866         ei->outstanding_extents = 0;
8867         if (sb->s_magic != BTRFS_TEST_MAGIC)
8868                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8869                                               BTRFS_BLOCK_RSV_DELALLOC);
8870         ei->runtime_flags = 0;
8871         ei->prop_compress = BTRFS_COMPRESS_NONE;
8872         ei->defrag_compress = BTRFS_COMPRESS_NONE;
8873
8874         ei->delayed_node = NULL;
8875
8876         ei->i_otime.tv_sec = 0;
8877         ei->i_otime.tv_nsec = 0;
8878
8879         inode = &ei->vfs_inode;
8880         extent_map_tree_init(&ei->extent_tree);
8881         extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8882         extent_io_tree_init(fs_info, &ei->io_failure_tree,
8883                             IO_TREE_INODE_IO_FAILURE, inode);
8884         extent_io_tree_init(fs_info, &ei->file_extent_tree,
8885                             IO_TREE_INODE_FILE_EXTENT, inode);
8886         ei->io_tree.track_uptodate = true;
8887         ei->io_failure_tree.track_uptodate = true;
8888         atomic_set(&ei->sync_writers, 0);
8889         mutex_init(&ei->log_mutex);
8890         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8891         INIT_LIST_HEAD(&ei->delalloc_inodes);
8892         INIT_LIST_HEAD(&ei->delayed_iput);
8893         RB_CLEAR_NODE(&ei->rb_node);
8894         init_rwsem(&ei->i_mmap_lock);
8895
8896         return inode;
8897 }
8898
8899 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8900 void btrfs_test_destroy_inode(struct inode *inode)
8901 {
8902         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8903         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8904 }
8905 #endif
8906
8907 void btrfs_free_inode(struct inode *inode)
8908 {
8909         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8910 }
8911
8912 void btrfs_destroy_inode(struct inode *vfs_inode)
8913 {
8914         struct btrfs_ordered_extent *ordered;
8915         struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8916         struct btrfs_root *root = inode->root;
8917
8918         WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8919         WARN_ON(vfs_inode->i_data.nrpages);
8920         WARN_ON(inode->block_rsv.reserved);
8921         WARN_ON(inode->block_rsv.size);
8922         WARN_ON(inode->outstanding_extents);
8923         WARN_ON(inode->delalloc_bytes);
8924         WARN_ON(inode->new_delalloc_bytes);
8925         WARN_ON(inode->csum_bytes);
8926         WARN_ON(inode->defrag_bytes);
8927
8928         /*
8929          * This can happen where we create an inode, but somebody else also
8930          * created the same inode and we need to destroy the one we already
8931          * created.
8932          */
8933         if (!root)
8934                 return;
8935
8936         while (1) {
8937                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8938                 if (!ordered)
8939                         break;
8940                 else {
8941                         btrfs_err(root->fs_info,
8942                                   "found ordered extent %llu %llu on inode cleanup",
8943                                   ordered->file_offset, ordered->num_bytes);
8944                         btrfs_remove_ordered_extent(inode, ordered);
8945                         btrfs_put_ordered_extent(ordered);
8946                         btrfs_put_ordered_extent(ordered);
8947                 }
8948         }
8949         btrfs_qgroup_check_reserved_leak(inode);
8950         inode_tree_del(inode);
8951         btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8952         btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8953         btrfs_put_root(inode->root);
8954 }
8955
8956 int btrfs_drop_inode(struct inode *inode)
8957 {
8958         struct btrfs_root *root = BTRFS_I(inode)->root;
8959
8960         if (root == NULL)
8961                 return 1;
8962
8963         /* the snap/subvol tree is on deleting */
8964         if (btrfs_root_refs(&root->root_item) == 0)
8965                 return 1;
8966         else
8967                 return generic_drop_inode(inode);
8968 }
8969
8970 static void init_once(void *foo)
8971 {
8972         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8973
8974         inode_init_once(&ei->vfs_inode);
8975 }
8976
8977 void __cold btrfs_destroy_cachep(void)
8978 {
8979         /*
8980          * Make sure all delayed rcu free inodes are flushed before we
8981          * destroy cache.
8982          */
8983         rcu_barrier();
8984         kmem_cache_destroy(btrfs_inode_cachep);
8985         kmem_cache_destroy(btrfs_trans_handle_cachep);
8986         kmem_cache_destroy(btrfs_path_cachep);
8987         kmem_cache_destroy(btrfs_free_space_cachep);
8988         kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8989 }
8990
8991 int __init btrfs_init_cachep(void)
8992 {
8993         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8994                         sizeof(struct btrfs_inode), 0,
8995                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8996                         init_once);
8997         if (!btrfs_inode_cachep)
8998                 goto fail;
8999
9000         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9001                         sizeof(struct btrfs_trans_handle), 0,
9002                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9003         if (!btrfs_trans_handle_cachep)
9004                 goto fail;
9005
9006         btrfs_path_cachep = kmem_cache_create("btrfs_path",
9007                         sizeof(struct btrfs_path), 0,
9008                         SLAB_MEM_SPREAD, NULL);
9009         if (!btrfs_path_cachep)
9010                 goto fail;
9011
9012         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9013                         sizeof(struct btrfs_free_space), 0,
9014                         SLAB_MEM_SPREAD, NULL);
9015         if (!btrfs_free_space_cachep)
9016                 goto fail;
9017
9018         btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
9019                                                         PAGE_SIZE, PAGE_SIZE,
9020                                                         SLAB_MEM_SPREAD, NULL);
9021         if (!btrfs_free_space_bitmap_cachep)
9022                 goto fail;
9023
9024         return 0;
9025 fail:
9026         btrfs_destroy_cachep();
9027         return -ENOMEM;
9028 }
9029
9030 static int btrfs_getattr(struct user_namespace *mnt_userns,
9031                          const struct path *path, struct kstat *stat,
9032                          u32 request_mask, unsigned int flags)
9033 {
9034         u64 delalloc_bytes;
9035         u64 inode_bytes;
9036         struct inode *inode = d_inode(path->dentry);
9037         u32 blocksize = inode->i_sb->s_blocksize;
9038         u32 bi_flags = BTRFS_I(inode)->flags;
9039
9040         stat->result_mask |= STATX_BTIME;
9041         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9042         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9043         if (bi_flags & BTRFS_INODE_APPEND)
9044                 stat->attributes |= STATX_ATTR_APPEND;
9045         if (bi_flags & BTRFS_INODE_COMPRESS)
9046                 stat->attributes |= STATX_ATTR_COMPRESSED;
9047         if (bi_flags & BTRFS_INODE_IMMUTABLE)
9048                 stat->attributes |= STATX_ATTR_IMMUTABLE;
9049         if (bi_flags & BTRFS_INODE_NODUMP)
9050                 stat->attributes |= STATX_ATTR_NODUMP;
9051
9052         stat->attributes_mask |= (STATX_ATTR_APPEND |
9053                                   STATX_ATTR_COMPRESSED |
9054                                   STATX_ATTR_IMMUTABLE |
9055                                   STATX_ATTR_NODUMP);
9056
9057         generic_fillattr(&init_user_ns, inode, stat);
9058         stat->dev = BTRFS_I(inode)->root->anon_dev;
9059
9060         spin_lock(&BTRFS_I(inode)->lock);
9061         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9062         inode_bytes = inode_get_bytes(inode);
9063         spin_unlock(&BTRFS_I(inode)->lock);
9064         stat->blocks = (ALIGN(inode_bytes, blocksize) +
9065                         ALIGN(delalloc_bytes, blocksize)) >> 9;
9066         return 0;
9067 }
9068
9069 static int btrfs_rename_exchange(struct inode *old_dir,
9070                               struct dentry *old_dentry,
9071                               struct inode *new_dir,
9072                               struct dentry *new_dentry)
9073 {
9074         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9075         struct btrfs_trans_handle *trans;
9076         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9077         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9078         struct inode *new_inode = new_dentry->d_inode;
9079         struct inode *old_inode = old_dentry->d_inode;
9080         struct timespec64 ctime = current_time(old_inode);
9081         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9082         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9083         u64 old_idx = 0;
9084         u64 new_idx = 0;
9085         int ret;
9086         int ret2;
9087         bool root_log_pinned = false;
9088         bool dest_log_pinned = false;
9089
9090         /* we only allow rename subvolume link between subvolumes */
9091         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9092                 return -EXDEV;
9093
9094         /* close the race window with snapshot create/destroy ioctl */
9095         if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
9096             new_ino == BTRFS_FIRST_FREE_OBJECTID)
9097                 down_read(&fs_info->subvol_sem);
9098
9099         /*
9100          * We want to reserve the absolute worst case amount of items.  So if
9101          * both inodes are subvols and we need to unlink them then that would
9102          * require 4 item modifications, but if they are both normal inodes it
9103          * would require 5 item modifications, so we'll assume their normal
9104          * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9105          * should cover the worst case number of items we'll modify.
9106          */
9107         trans = btrfs_start_transaction(root, 12);
9108         if (IS_ERR(trans)) {
9109                 ret = PTR_ERR(trans);
9110                 goto out_notrans;
9111         }
9112
9113         if (dest != root)
9114                 btrfs_record_root_in_trans(trans, dest);
9115
9116         /*
9117          * We need to find a free sequence number both in the source and
9118          * in the destination directory for the exchange.
9119          */
9120         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9121         if (ret)
9122                 goto out_fail;
9123         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9124         if (ret)
9125                 goto out_fail;
9126
9127         BTRFS_I(old_inode)->dir_index = 0ULL;
9128         BTRFS_I(new_inode)->dir_index = 0ULL;
9129
9130         /* Reference for the source. */
9131         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9132                 /* force full log commit if subvolume involved. */
9133                 btrfs_set_log_full_commit(trans);
9134         } else {
9135                 btrfs_pin_log_trans(root);
9136                 root_log_pinned = true;
9137                 ret = btrfs_insert_inode_ref(trans, dest,
9138                                              new_dentry->d_name.name,
9139                                              new_dentry->d_name.len,
9140                                              old_ino,
9141                                              btrfs_ino(BTRFS_I(new_dir)),
9142                                              old_idx);
9143                 if (ret)
9144                         goto out_fail;
9145         }
9146
9147         /* And now for the dest. */
9148         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9149                 /* force full log commit if subvolume involved. */
9150                 btrfs_set_log_full_commit(trans);
9151         } else {
9152                 btrfs_pin_log_trans(dest);
9153                 dest_log_pinned = true;
9154                 ret = btrfs_insert_inode_ref(trans, root,
9155                                              old_dentry->d_name.name,
9156                                              old_dentry->d_name.len,
9157                                              new_ino,
9158                                              btrfs_ino(BTRFS_I(old_dir)),
9159                                              new_idx);
9160                 if (ret)
9161                         goto out_fail;
9162         }
9163
9164         /* Update inode version and ctime/mtime. */
9165         inode_inc_iversion(old_dir);
9166         inode_inc_iversion(new_dir);
9167         inode_inc_iversion(old_inode);
9168         inode_inc_iversion(new_inode);
9169         old_dir->i_ctime = old_dir->i_mtime = ctime;
9170         new_dir->i_ctime = new_dir->i_mtime = ctime;
9171         old_inode->i_ctime = ctime;
9172         new_inode->i_ctime = ctime;
9173
9174         if (old_dentry->d_parent != new_dentry->d_parent) {
9175                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9176                                 BTRFS_I(old_inode), 1);
9177                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9178                                 BTRFS_I(new_inode), 1);
9179         }
9180
9181         /* src is a subvolume */
9182         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9183                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9184         } else { /* src is an inode */
9185                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9186                                            BTRFS_I(old_dentry->d_inode),
9187                                            old_dentry->d_name.name,
9188                                            old_dentry->d_name.len);
9189                 if (!ret)
9190                         ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9191         }
9192         if (ret) {
9193                 btrfs_abort_transaction(trans, ret);
9194                 goto out_fail;
9195         }
9196
9197         /* dest is a subvolume */
9198         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9199                 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9200         } else { /* dest is an inode */
9201                 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9202                                            BTRFS_I(new_dentry->d_inode),
9203                                            new_dentry->d_name.name,
9204                                            new_dentry->d_name.len);
9205                 if (!ret)
9206                         ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
9207         }
9208         if (ret) {
9209                 btrfs_abort_transaction(trans, ret);
9210                 goto out_fail;
9211         }
9212
9213         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9214                              new_dentry->d_name.name,
9215                              new_dentry->d_name.len, 0, old_idx);
9216         if (ret) {
9217                 btrfs_abort_transaction(trans, ret);
9218                 goto out_fail;
9219         }
9220
9221         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9222                              old_dentry->d_name.name,
9223                              old_dentry->d_name.len, 0, new_idx);
9224         if (ret) {
9225                 btrfs_abort_transaction(trans, ret);
9226                 goto out_fail;
9227         }
9228
9229         if (old_inode->i_nlink == 1)
9230                 BTRFS_I(old_inode)->dir_index = old_idx;
9231         if (new_inode->i_nlink == 1)
9232                 BTRFS_I(new_inode)->dir_index = new_idx;
9233
9234         if (root_log_pinned) {
9235                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9236                                    new_dentry->d_parent);
9237                 btrfs_end_log_trans(root);
9238                 root_log_pinned = false;
9239         }
9240         if (dest_log_pinned) {
9241                 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9242                                    old_dentry->d_parent);
9243                 btrfs_end_log_trans(dest);
9244                 dest_log_pinned = false;
9245         }
9246 out_fail:
9247         /*
9248          * If we have pinned a log and an error happened, we unpin tasks
9249          * trying to sync the log and force them to fallback to a transaction
9250          * commit if the log currently contains any of the inodes involved in
9251          * this rename operation (to ensure we do not persist a log with an
9252          * inconsistent state for any of these inodes or leading to any
9253          * inconsistencies when replayed). If the transaction was aborted, the
9254          * abortion reason is propagated to userspace when attempting to commit
9255          * the transaction. If the log does not contain any of these inodes, we
9256          * allow the tasks to sync it.
9257          */
9258         if (ret && (root_log_pinned || dest_log_pinned)) {
9259                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9260                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9261                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9262                     (new_inode &&
9263                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9264                         btrfs_set_log_full_commit(trans);
9265
9266                 if (root_log_pinned) {
9267                         btrfs_end_log_trans(root);
9268                         root_log_pinned = false;
9269                 }
9270                 if (dest_log_pinned) {
9271                         btrfs_end_log_trans(dest);
9272                         dest_log_pinned = false;
9273                 }
9274         }
9275         ret2 = btrfs_end_transaction(trans);
9276         ret = ret ? ret : ret2;
9277 out_notrans:
9278         if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9279             old_ino == BTRFS_FIRST_FREE_OBJECTID)
9280                 up_read(&fs_info->subvol_sem);
9281
9282         return ret;
9283 }
9284
9285 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9286                                      struct btrfs_root *root,
9287                                      struct inode *dir,
9288                                      struct dentry *dentry)
9289 {
9290         int ret;
9291         struct inode *inode;
9292         u64 objectid;
9293         u64 index;
9294
9295         ret = btrfs_get_free_objectid(root, &objectid);
9296         if (ret)
9297                 return ret;
9298
9299         inode = btrfs_new_inode(trans, root, dir,
9300                                 dentry->d_name.name,
9301                                 dentry->d_name.len,
9302                                 btrfs_ino(BTRFS_I(dir)),
9303                                 objectid,
9304                                 S_IFCHR | WHITEOUT_MODE,
9305                                 &index);
9306
9307         if (IS_ERR(inode)) {
9308                 ret = PTR_ERR(inode);
9309                 return ret;
9310         }
9311
9312         inode->i_op = &btrfs_special_inode_operations;
9313         init_special_inode(inode, inode->i_mode,
9314                 WHITEOUT_DEV);
9315
9316         ret = btrfs_init_inode_security(trans, inode, dir,
9317                                 &dentry->d_name);
9318         if (ret)
9319                 goto out;
9320
9321         ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9322                                 BTRFS_I(inode), 0, index);
9323         if (ret)
9324                 goto out;
9325
9326         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
9327 out:
9328         unlock_new_inode(inode);
9329         if (ret)
9330                 inode_dec_link_count(inode);
9331         iput(inode);
9332
9333         return ret;
9334 }
9335
9336 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9337                            struct inode *new_dir, struct dentry *new_dentry,
9338                            unsigned int flags)
9339 {
9340         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9341         struct btrfs_trans_handle *trans;
9342         unsigned int trans_num_items;
9343         struct btrfs_root *root = BTRFS_I(old_dir)->root;
9344         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9345         struct inode *new_inode = d_inode(new_dentry);
9346         struct inode *old_inode = d_inode(old_dentry);
9347         u64 index = 0;
9348         int ret;
9349         int ret2;
9350         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9351         bool log_pinned = false;
9352
9353         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9354                 return -EPERM;
9355
9356         /* we only allow rename subvolume link between subvolumes */
9357         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9358                 return -EXDEV;
9359
9360         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9361             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9362                 return -ENOTEMPTY;
9363
9364         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9365             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9366                 return -ENOTEMPTY;
9367
9368
9369         /* check for collisions, even if the  name isn't there */
9370         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9371                              new_dentry->d_name.name,
9372                              new_dentry->d_name.len);
9373
9374         if (ret) {
9375                 if (ret == -EEXIST) {
9376                         /* we shouldn't get
9377                          * eexist without a new_inode */
9378                         if (WARN_ON(!new_inode)) {
9379                                 return ret;
9380                         }
9381                 } else {
9382                         /* maybe -EOVERFLOW */
9383                         return ret;
9384                 }
9385         }
9386         ret = 0;
9387
9388         /*
9389          * we're using rename to replace one file with another.  Start IO on it
9390          * now so  we don't add too much work to the end of the transaction
9391          */
9392         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9393                 filemap_flush(old_inode->i_mapping);
9394
9395         /* close the racy window with snapshot create/destroy ioctl */
9396         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9397                 down_read(&fs_info->subvol_sem);
9398         /*
9399          * We want to reserve the absolute worst case amount of items.  So if
9400          * both inodes are subvols and we need to unlink them then that would
9401          * require 4 item modifications, but if they are both normal inodes it
9402          * would require 5 item modifications, so we'll assume they are normal
9403          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9404          * should cover the worst case number of items we'll modify.
9405          * If our rename has the whiteout flag, we need more 5 units for the
9406          * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9407          * when selinux is enabled).
9408          */
9409         trans_num_items = 11;
9410         if (flags & RENAME_WHITEOUT)
9411                 trans_num_items += 5;
9412         trans = btrfs_start_transaction(root, trans_num_items);
9413         if (IS_ERR(trans)) {
9414                 ret = PTR_ERR(trans);
9415                 goto out_notrans;
9416         }
9417
9418         if (dest != root)
9419                 btrfs_record_root_in_trans(trans, dest);
9420
9421         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9422         if (ret)
9423                 goto out_fail;
9424
9425         BTRFS_I(old_inode)->dir_index = 0ULL;
9426         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9427                 /* force full log commit if subvolume involved. */
9428                 btrfs_set_log_full_commit(trans);
9429         } else {
9430                 btrfs_pin_log_trans(root);
9431                 log_pinned = true;
9432                 ret = btrfs_insert_inode_ref(trans, dest,
9433                                              new_dentry->d_name.name,
9434                                              new_dentry->d_name.len,
9435                                              old_ino,
9436                                              btrfs_ino(BTRFS_I(new_dir)), index);
9437                 if (ret)
9438                         goto out_fail;
9439         }
9440
9441         inode_inc_iversion(old_dir);
9442         inode_inc_iversion(new_dir);
9443         inode_inc_iversion(old_inode);
9444         old_dir->i_ctime = old_dir->i_mtime =
9445         new_dir->i_ctime = new_dir->i_mtime =
9446         old_inode->i_ctime = current_time(old_dir);
9447
9448         if (old_dentry->d_parent != new_dentry->d_parent)
9449                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9450                                 BTRFS_I(old_inode), 1);
9451
9452         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9453                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9454         } else {
9455                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9456                                         BTRFS_I(d_inode(old_dentry)),
9457                                         old_dentry->d_name.name,
9458                                         old_dentry->d_name.len);
9459                 if (!ret)
9460                         ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
9461         }
9462         if (ret) {
9463                 btrfs_abort_transaction(trans, ret);
9464                 goto out_fail;
9465         }
9466
9467         if (new_inode) {
9468                 inode_inc_iversion(new_inode);
9469                 new_inode->i_ctime = current_time(new_inode);
9470                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9471                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9472                         ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9473                         BUG_ON(new_inode->i_nlink == 0);
9474                 } else {
9475                         ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9476                                                  BTRFS_I(d_inode(new_dentry)),
9477                                                  new_dentry->d_name.name,
9478                                                  new_dentry->d_name.len);
9479                 }
9480                 if (!ret && new_inode->i_nlink == 0)
9481                         ret = btrfs_orphan_add(trans,
9482                                         BTRFS_I(d_inode(new_dentry)));
9483                 if (ret) {
9484                         btrfs_abort_transaction(trans, ret);
9485                         goto out_fail;
9486                 }
9487         }
9488
9489         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9490                              new_dentry->d_name.name,
9491                              new_dentry->d_name.len, 0, index);
9492         if (ret) {
9493                 btrfs_abort_transaction(trans, ret);
9494                 goto out_fail;
9495         }
9496
9497         if (old_inode->i_nlink == 1)
9498                 BTRFS_I(old_inode)->dir_index = index;
9499
9500         if (log_pinned) {
9501                 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9502                                    new_dentry->d_parent);
9503                 btrfs_end_log_trans(root);
9504                 log_pinned = false;
9505         }
9506
9507         if (flags & RENAME_WHITEOUT) {
9508                 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9509                                                 old_dentry);
9510
9511                 if (ret) {
9512                         btrfs_abort_transaction(trans, ret);
9513                         goto out_fail;
9514                 }
9515         }
9516 out_fail:
9517         /*
9518          * If we have pinned the log and an error happened, we unpin tasks
9519          * trying to sync the log and force them to fallback to a transaction
9520          * commit if the log currently contains any of the inodes involved in
9521          * this rename operation (to ensure we do not persist a log with an
9522          * inconsistent state for any of these inodes or leading to any
9523          * inconsistencies when replayed). If the transaction was aborted, the
9524          * abortion reason is propagated to userspace when attempting to commit
9525          * the transaction. If the log does not contain any of these inodes, we
9526          * allow the tasks to sync it.
9527          */
9528         if (ret && log_pinned) {
9529                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9530                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9531                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9532                     (new_inode &&
9533                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9534                         btrfs_set_log_full_commit(trans);
9535
9536                 btrfs_end_log_trans(root);
9537                 log_pinned = false;
9538         }
9539         ret2 = btrfs_end_transaction(trans);
9540         ret = ret ? ret : ret2;
9541 out_notrans:
9542         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9543                 up_read(&fs_info->subvol_sem);
9544
9545         return ret;
9546 }
9547
9548 static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
9549                          struct dentry *old_dentry, struct inode *new_dir,
9550                          struct dentry *new_dentry, unsigned int flags)
9551 {
9552         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9553                 return -EINVAL;
9554
9555         if (flags & RENAME_EXCHANGE)
9556                 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9557                                           new_dentry);
9558
9559         return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9560 }
9561
9562 struct btrfs_delalloc_work {
9563         struct inode *inode;
9564         struct completion completion;
9565         struct list_head list;
9566         struct btrfs_work work;
9567 };
9568
9569 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9570 {
9571         struct btrfs_delalloc_work *delalloc_work;
9572         struct inode *inode;
9573
9574         delalloc_work = container_of(work, struct btrfs_delalloc_work,
9575                                      work);
9576         inode = delalloc_work->inode;
9577         filemap_flush(inode->i_mapping);
9578         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9579                                 &BTRFS_I(inode)->runtime_flags))
9580                 filemap_flush(inode->i_mapping);
9581
9582         iput(inode);
9583         complete(&delalloc_work->completion);
9584 }
9585
9586 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9587 {
9588         struct btrfs_delalloc_work *work;
9589
9590         work = kmalloc(sizeof(*work), GFP_NOFS);
9591         if (!work)
9592                 return NULL;
9593
9594         init_completion(&work->completion);
9595         INIT_LIST_HEAD(&work->list);
9596         work->inode = inode;
9597         btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9598
9599         return work;
9600 }
9601
9602 /*
9603  * some fairly slow code that needs optimization. This walks the list
9604  * of all the inodes with pending delalloc and forces them to disk.
9605  */
9606 static int start_delalloc_inodes(struct btrfs_root *root,
9607                                  struct writeback_control *wbc, bool snapshot,
9608                                  bool in_reclaim_context)
9609 {
9610         struct btrfs_inode *binode;
9611         struct inode *inode;
9612         struct btrfs_delalloc_work *work, *next;
9613         struct list_head works;
9614         struct list_head splice;
9615         int ret = 0;
9616         bool full_flush = wbc->nr_to_write == LONG_MAX;
9617
9618         INIT_LIST_HEAD(&works);
9619         INIT_LIST_HEAD(&splice);
9620
9621         mutex_lock(&root->delalloc_mutex);
9622         spin_lock(&root->delalloc_lock);
9623         list_splice_init(&root->delalloc_inodes, &splice);
9624         while (!list_empty(&splice)) {
9625                 binode = list_entry(splice.next, struct btrfs_inode,
9626                                     delalloc_inodes);
9627
9628                 list_move_tail(&binode->delalloc_inodes,
9629                                &root->delalloc_inodes);
9630
9631                 if (in_reclaim_context &&
9632                     test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
9633                         continue;
9634
9635                 inode = igrab(&binode->vfs_inode);
9636                 if (!inode) {
9637                         cond_resched_lock(&root->delalloc_lock);
9638                         continue;
9639                 }
9640                 spin_unlock(&root->delalloc_lock);
9641
9642                 if (snapshot)
9643                         set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9644                                 &binode->runtime_flags);
9645                 if (full_flush) {
9646                         work = btrfs_alloc_delalloc_work(inode);
9647                         if (!work) {
9648                                 iput(inode);
9649                                 ret = -ENOMEM;
9650                                 goto out;
9651                         }
9652                         list_add_tail(&work->list, &works);
9653                         btrfs_queue_work(root->fs_info->flush_workers,
9654                                          &work->work);
9655                 } else {
9656                         ret = sync_inode(inode, wbc);
9657                         if (!ret &&
9658                             test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9659                                      &BTRFS_I(inode)->runtime_flags))
9660                                 ret = sync_inode(inode, wbc);
9661                         btrfs_add_delayed_iput(inode);
9662                         if (ret || wbc->nr_to_write <= 0)
9663                                 goto out;
9664                 }
9665                 cond_resched();
9666                 spin_lock(&root->delalloc_lock);
9667         }
9668         spin_unlock(&root->delalloc_lock);
9669
9670 out:
9671         list_for_each_entry_safe(work, next, &works, list) {
9672                 list_del_init(&work->list);
9673                 wait_for_completion(&work->completion);
9674                 kfree(work);
9675         }
9676
9677         if (!list_empty(&splice)) {
9678                 spin_lock(&root->delalloc_lock);
9679                 list_splice_tail(&splice, &root->delalloc_inodes);
9680                 spin_unlock(&root->delalloc_lock);
9681         }
9682         mutex_unlock(&root->delalloc_mutex);
9683         return ret;
9684 }
9685
9686 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9687 {
9688         struct writeback_control wbc = {
9689                 .nr_to_write = LONG_MAX,
9690                 .sync_mode = WB_SYNC_NONE,
9691                 .range_start = 0,
9692                 .range_end = LLONG_MAX,
9693         };
9694         struct btrfs_fs_info *fs_info = root->fs_info;
9695
9696         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9697                 return -EROFS;
9698
9699         return start_delalloc_inodes(root, &wbc, true, false);
9700 }
9701
9702 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
9703                                bool in_reclaim_context)
9704 {
9705         struct writeback_control wbc = {
9706                 .nr_to_write = nr,
9707                 .sync_mode = WB_SYNC_NONE,
9708                 .range_start = 0,
9709                 .range_end = LLONG_MAX,
9710         };
9711         struct btrfs_root *root;
9712         struct list_head splice;
9713         int ret;
9714
9715         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9716                 return -EROFS;
9717
9718         INIT_LIST_HEAD(&splice);
9719
9720         mutex_lock(&fs_info->delalloc_root_mutex);
9721         spin_lock(&fs_info->delalloc_root_lock);
9722         list_splice_init(&fs_info->delalloc_roots, &splice);
9723         while (!list_empty(&splice)) {
9724                 /*
9725                  * Reset nr_to_write here so we know that we're doing a full
9726                  * flush.
9727                  */
9728                 if (nr == LONG_MAX)
9729                         wbc.nr_to_write = LONG_MAX;
9730
9731                 root = list_first_entry(&splice, struct btrfs_root,
9732                                         delalloc_root);
9733                 root = btrfs_grab_root(root);
9734                 BUG_ON(!root);
9735                 list_move_tail(&root->delalloc_root,
9736                                &fs_info->delalloc_roots);
9737                 spin_unlock(&fs_info->delalloc_root_lock);
9738
9739                 ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
9740                 btrfs_put_root(root);
9741                 if (ret < 0 || wbc.nr_to_write <= 0)
9742                         goto out;
9743                 spin_lock(&fs_info->delalloc_root_lock);
9744         }
9745         spin_unlock(&fs_info->delalloc_root_lock);
9746
9747         ret = 0;
9748 out:
9749         if (!list_empty(&splice)) {
9750                 spin_lock(&fs_info->delalloc_root_lock);
9751                 list_splice_tail(&splice, &fs_info->delalloc_roots);
9752                 spin_unlock(&fs_info->delalloc_root_lock);
9753         }
9754         mutex_unlock(&fs_info->delalloc_root_mutex);
9755         return ret;
9756 }
9757
9758 static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
9759                          struct dentry *dentry, const char *symname)
9760 {
9761         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9762         struct btrfs_trans_handle *trans;
9763         struct btrfs_root *root = BTRFS_I(dir)->root;
9764         struct btrfs_path *path;
9765         struct btrfs_key key;
9766         struct inode *inode = NULL;
9767         int err;
9768         u64 objectid;
9769         u64 index = 0;
9770         int name_len;
9771         int datasize;
9772         unsigned long ptr;
9773         struct btrfs_file_extent_item *ei;
9774         struct extent_buffer *leaf;
9775
9776         name_len = strlen(symname);
9777         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9778                 return -ENAMETOOLONG;
9779
9780         /*
9781          * 2 items for inode item and ref
9782          * 2 items for dir items
9783          * 1 item for updating parent inode item
9784          * 1 item for the inline extent item
9785          * 1 item for xattr if selinux is on
9786          */
9787         trans = btrfs_start_transaction(root, 7);
9788         if (IS_ERR(trans))
9789                 return PTR_ERR(trans);
9790
9791         err = btrfs_get_free_objectid(root, &objectid);
9792         if (err)
9793                 goto out_unlock;
9794
9795         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9796                                 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9797                                 objectid, S_IFLNK|S_IRWXUGO, &index);
9798         if (IS_ERR(inode)) {
9799                 err = PTR_ERR(inode);
9800                 inode = NULL;
9801                 goto out_unlock;
9802         }
9803
9804         /*
9805         * If the active LSM wants to access the inode during
9806         * d_instantiate it needs these. Smack checks to see
9807         * if the filesystem supports xattrs by looking at the
9808         * ops vector.
9809         */
9810         inode->i_fop = &btrfs_file_operations;
9811         inode->i_op = &btrfs_file_inode_operations;
9812         inode->i_mapping->a_ops = &btrfs_aops;
9813
9814         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9815         if (err)
9816                 goto out_unlock;
9817
9818         path = btrfs_alloc_path();
9819         if (!path) {
9820                 err = -ENOMEM;
9821                 goto out_unlock;
9822         }
9823         key.objectid = btrfs_ino(BTRFS_I(inode));
9824         key.offset = 0;
9825         key.type = BTRFS_EXTENT_DATA_KEY;
9826         datasize = btrfs_file_extent_calc_inline_size(name_len);
9827         err = btrfs_insert_empty_item(trans, root, path, &key,
9828                                       datasize);
9829         if (err) {
9830                 btrfs_free_path(path);
9831                 goto out_unlock;
9832         }
9833         leaf = path->nodes[0];
9834         ei = btrfs_item_ptr(leaf, path->slots[0],
9835                             struct btrfs_file_extent_item);
9836         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9837         btrfs_set_file_extent_type(leaf, ei,
9838                                    BTRFS_FILE_EXTENT_INLINE);
9839         btrfs_set_file_extent_encryption(leaf, ei, 0);
9840         btrfs_set_file_extent_compression(leaf, ei, 0);
9841         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9842         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9843
9844         ptr = btrfs_file_extent_inline_start(ei);
9845         write_extent_buffer(leaf, symname, ptr, name_len);
9846         btrfs_mark_buffer_dirty(leaf);
9847         btrfs_free_path(path);
9848
9849         inode->i_op = &btrfs_symlink_inode_operations;
9850         inode_nohighmem(inode);
9851         inode_set_bytes(inode, name_len);
9852         btrfs_i_size_write(BTRFS_I(inode), name_len);
9853         err = btrfs_update_inode(trans, root, BTRFS_I(inode));
9854         /*
9855          * Last step, add directory indexes for our symlink inode. This is the
9856          * last step to avoid extra cleanup of these indexes if an error happens
9857          * elsewhere above.
9858          */
9859         if (!err)
9860                 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9861                                 BTRFS_I(inode), 0, index);
9862         if (err)
9863                 goto out_unlock;
9864
9865         d_instantiate_new(dentry, inode);
9866
9867 out_unlock:
9868         btrfs_end_transaction(trans);
9869         if (err && inode) {
9870                 inode_dec_link_count(inode);
9871                 discard_new_inode(inode);
9872         }
9873         btrfs_btree_balance_dirty(fs_info);
9874         return err;
9875 }
9876
9877 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9878                                        struct btrfs_trans_handle *trans_in,
9879                                        struct btrfs_inode *inode,
9880                                        struct btrfs_key *ins,
9881                                        u64 file_offset)
9882 {
9883         struct btrfs_file_extent_item stack_fi;
9884         struct btrfs_replace_extent_info extent_info;
9885         struct btrfs_trans_handle *trans = trans_in;
9886         struct btrfs_path *path;
9887         u64 start = ins->objectid;
9888         u64 len = ins->offset;
9889         int qgroup_released;
9890         int ret;
9891
9892         memset(&stack_fi, 0, sizeof(stack_fi));
9893
9894         btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9895         btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9896         btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9897         btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9898         btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9899         btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9900         /* Encryption and other encoding is reserved and all 0 */
9901
9902         qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
9903         if (qgroup_released < 0)
9904                 return ERR_PTR(qgroup_released);
9905
9906         if (trans) {
9907                 ret = insert_reserved_file_extent(trans, inode,
9908                                                   file_offset, &stack_fi,
9909                                                   true, qgroup_released);
9910                 if (ret)
9911                         goto free_qgroup;
9912                 return trans;
9913         }
9914
9915         extent_info.disk_offset = start;
9916         extent_info.disk_len = len;
9917         extent_info.data_offset = 0;
9918         extent_info.data_len = len;
9919         extent_info.file_offset = file_offset;
9920         extent_info.extent_buf = (char *)&stack_fi;
9921         extent_info.is_new_extent = true;
9922         extent_info.qgroup_reserved = qgroup_released;
9923         extent_info.insertions = 0;
9924
9925         path = btrfs_alloc_path();
9926         if (!path) {
9927                 ret = -ENOMEM;
9928                 goto free_qgroup;
9929         }
9930
9931         ret = btrfs_replace_file_extents(inode, path, file_offset,
9932                                      file_offset + len - 1, &extent_info,
9933                                      &trans);
9934         btrfs_free_path(path);
9935         if (ret)
9936                 goto free_qgroup;
9937         return trans;
9938
9939 free_qgroup:
9940         /*
9941          * We have released qgroup data range at the beginning of the function,
9942          * and normally qgroup_released bytes will be freed when committing
9943          * transaction.
9944          * But if we error out early, we have to free what we have released
9945          * or we leak qgroup data reservation.
9946          */
9947         btrfs_qgroup_free_refroot(inode->root->fs_info,
9948                         inode->root->root_key.objectid, qgroup_released,
9949                         BTRFS_QGROUP_RSV_DATA);
9950         return ERR_PTR(ret);
9951 }
9952
9953 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9954                                        u64 start, u64 num_bytes, u64 min_size,
9955                                        loff_t actual_len, u64 *alloc_hint,
9956                                        struct btrfs_trans_handle *trans)
9957 {
9958         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9959         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9960         struct extent_map *em;
9961         struct btrfs_root *root = BTRFS_I(inode)->root;
9962         struct btrfs_key ins;
9963         u64 cur_offset = start;
9964         u64 clear_offset = start;
9965         u64 i_size;
9966         u64 cur_bytes;
9967         u64 last_alloc = (u64)-1;
9968         int ret = 0;
9969         bool own_trans = true;
9970         u64 end = start + num_bytes - 1;
9971
9972         if (trans)
9973                 own_trans = false;
9974         while (num_bytes > 0) {
9975                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9976                 cur_bytes = max(cur_bytes, min_size);
9977                 /*
9978                  * If we are severely fragmented we could end up with really
9979                  * small allocations, so if the allocator is returning small
9980                  * chunks lets make its job easier by only searching for those
9981                  * sized chunks.
9982                  */
9983                 cur_bytes = min(cur_bytes, last_alloc);
9984                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9985                                 min_size, 0, *alloc_hint, &ins, 1, 0);
9986                 if (ret)
9987                         break;
9988
9989                 /*
9990                  * We've reserved this space, and thus converted it from
9991                  * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9992                  * from here on out we will only need to clear our reservation
9993                  * for the remaining unreserved area, so advance our
9994                  * clear_offset by our extent size.
9995                  */
9996                 clear_offset += ins.offset;
9997
9998                 last_alloc = ins.offset;
9999                 trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
10000                                                     &ins, cur_offset);
10001                 /*
10002                  * Now that we inserted the prealloc extent we can finally
10003                  * decrement the number of reservations in the block group.
10004                  * If we did it before, we could race with relocation and have
10005                  * relocation miss the reserved extent, making it fail later.
10006                  */
10007                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10008                 if (IS_ERR(trans)) {
10009                         ret = PTR_ERR(trans);
10010                         btrfs_free_reserved_extent(fs_info, ins.objectid,
10011                                                    ins.offset, 0);
10012                         break;
10013                 }
10014
10015                 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10016                                         cur_offset + ins.offset -1, 0);
10017
10018                 em = alloc_extent_map();
10019                 if (!em) {
10020                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10021                                 &BTRFS_I(inode)->runtime_flags);
10022                         goto next;
10023                 }
10024
10025                 em->start = cur_offset;
10026                 em->orig_start = cur_offset;
10027                 em->len = ins.offset;
10028                 em->block_start = ins.objectid;
10029                 em->block_len = ins.offset;
10030                 em->orig_block_len = ins.offset;
10031                 em->ram_bytes = ins.offset;
10032                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10033                 em->generation = trans->transid;
10034
10035                 while (1) {
10036                         write_lock(&em_tree->lock);
10037                         ret = add_extent_mapping(em_tree, em, 1);
10038                         write_unlock(&em_tree->lock);
10039                         if (ret != -EEXIST)
10040                                 break;
10041                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10042                                                 cur_offset + ins.offset - 1,
10043                                                 0);
10044                 }
10045                 free_extent_map(em);
10046 next:
10047                 num_bytes -= ins.offset;
10048                 cur_offset += ins.offset;
10049                 *alloc_hint = ins.objectid + ins.offset;
10050
10051                 inode_inc_iversion(inode);
10052                 inode->i_ctime = current_time(inode);
10053                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10054                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10055                     (actual_len > inode->i_size) &&
10056                     (cur_offset > inode->i_size)) {
10057                         if (cur_offset > actual_len)
10058                                 i_size = actual_len;
10059                         else
10060                                 i_size = cur_offset;
10061                         i_size_write(inode, i_size);
10062                         btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
10063                 }
10064
10065                 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10066
10067                 if (ret) {
10068                         btrfs_abort_transaction(trans, ret);
10069                         if (own_trans)
10070                                 btrfs_end_transaction(trans);
10071                         break;
10072                 }
10073
10074                 if (own_trans) {
10075                         btrfs_end_transaction(trans);
10076                         trans = NULL;
10077                 }
10078         }
10079         if (clear_offset < end)
10080                 btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
10081                         end - clear_offset + 1);
10082         return ret;
10083 }
10084
10085 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10086                               u64 start, u64 num_bytes, u64 min_size,
10087                               loff_t actual_len, u64 *alloc_hint)
10088 {
10089         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10090                                            min_size, actual_len, alloc_hint,
10091                                            NULL);
10092 }
10093
10094 int btrfs_prealloc_file_range_trans(struct inode *inode,
10095                                     struct btrfs_trans_handle *trans, int mode,
10096                                     u64 start, u64 num_bytes, u64 min_size,
10097                                     loff_t actual_len, u64 *alloc_hint)
10098 {
10099         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10100                                            min_size, actual_len, alloc_hint, trans);
10101 }
10102
10103 static int btrfs_set_page_dirty(struct page *page)
10104 {
10105         return __set_page_dirty_nobuffers(page);
10106 }
10107
10108 static int btrfs_permission(struct user_namespace *mnt_userns,
10109                             struct inode *inode, int mask)
10110 {
10111         struct btrfs_root *root = BTRFS_I(inode)->root;
10112         umode_t mode = inode->i_mode;
10113
10114         if (mask & MAY_WRITE &&
10115             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10116                 if (btrfs_root_readonly(root))
10117                         return -EROFS;
10118                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10119                         return -EACCES;
10120         }
10121         return generic_permission(&init_user_ns, inode, mask);
10122 }
10123
10124 static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
10125                          struct dentry *dentry, umode_t mode)
10126 {
10127         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10128         struct btrfs_trans_handle *trans;
10129         struct btrfs_root *root = BTRFS_I(dir)->root;
10130         struct inode *inode = NULL;
10131         u64 objectid;
10132         u64 index;
10133         int ret = 0;
10134
10135         /*
10136          * 5 units required for adding orphan entry
10137          */
10138         trans = btrfs_start_transaction(root, 5);
10139         if (IS_ERR(trans))
10140                 return PTR_ERR(trans);
10141
10142         ret = btrfs_get_free_objectid(root, &objectid);
10143         if (ret)
10144                 goto out;
10145
10146         inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10147                         btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10148         if (IS_ERR(inode)) {
10149                 ret = PTR_ERR(inode);
10150                 inode = NULL;
10151                 goto out;
10152         }
10153
10154         inode->i_fop = &btrfs_file_operations;
10155         inode->i_op = &btrfs_file_inode_operations;
10156
10157         inode->i_mapping->a_ops = &btrfs_aops;
10158
10159         ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10160         if (ret)
10161                 goto out;
10162
10163         ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
10164         if (ret)
10165                 goto out;
10166         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10167         if (ret)
10168                 goto out;
10169
10170         /*
10171          * We set number of links to 0 in btrfs_new_inode(), and here we set
10172          * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10173          * through:
10174          *
10175          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10176          */
10177         set_nlink(inode, 1);
10178         d_tmpfile(dentry, inode);
10179         unlock_new_inode(inode);
10180         mark_inode_dirty(inode);
10181 out:
10182         btrfs_end_transaction(trans);
10183         if (ret && inode)
10184                 discard_new_inode(inode);
10185         btrfs_btree_balance_dirty(fs_info);
10186         return ret;
10187 }
10188
10189 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10190 {
10191         struct inode *inode = tree->private_data;
10192         unsigned long index = start >> PAGE_SHIFT;
10193         unsigned long end_index = end >> PAGE_SHIFT;
10194         struct page *page;
10195
10196         while (index <= end_index) {
10197                 page = find_get_page(inode->i_mapping, index);
10198                 ASSERT(page); /* Pages should be in the extent_io_tree */
10199                 set_page_writeback(page);
10200                 put_page(page);
10201                 index++;
10202         }
10203 }
10204
10205 #ifdef CONFIG_SWAP
10206 /*
10207  * Add an entry indicating a block group or device which is pinned by a
10208  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10209  * negative errno on failure.
10210  */
10211 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10212                                   bool is_block_group)
10213 {
10214         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10215         struct btrfs_swapfile_pin *sp, *entry;
10216         struct rb_node **p;
10217         struct rb_node *parent = NULL;
10218
10219         sp = kmalloc(sizeof(*sp), GFP_NOFS);
10220         if (!sp)
10221                 return -ENOMEM;
10222         sp->ptr = ptr;
10223         sp->inode = inode;
10224         sp->is_block_group = is_block_group;
10225         sp->bg_extent_count = 1;
10226
10227         spin_lock(&fs_info->swapfile_pins_lock);
10228         p = &fs_info->swapfile_pins.rb_node;
10229         while (*p) {
10230                 parent = *p;
10231                 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10232                 if (sp->ptr < entry->ptr ||
10233                     (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10234                         p = &(*p)->rb_left;
10235                 } else if (sp->ptr > entry->ptr ||
10236                            (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10237                         p = &(*p)->rb_right;
10238                 } else {
10239                         if (is_block_group)
10240                                 entry->bg_extent_count++;
10241                         spin_unlock(&fs_info->swapfile_pins_lock);
10242                         kfree(sp);
10243                         return 1;
10244                 }
10245         }
10246         rb_link_node(&sp->node, parent, p);
10247         rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10248         spin_unlock(&fs_info->swapfile_pins_lock);
10249         return 0;
10250 }
10251
10252 /* Free all of the entries pinned by this swapfile. */
10253 static void btrfs_free_swapfile_pins(struct inode *inode)
10254 {
10255         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10256         struct btrfs_swapfile_pin *sp;
10257         struct rb_node *node, *next;
10258
10259         spin_lock(&fs_info->swapfile_pins_lock);
10260         node = rb_first(&fs_info->swapfile_pins);
10261         while (node) {
10262                 next = rb_next(node);
10263                 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10264                 if (sp->inode == inode) {
10265                         rb_erase(&sp->node, &fs_info->swapfile_pins);
10266                         if (sp->is_block_group) {
10267                                 btrfs_dec_block_group_swap_extents(sp->ptr,
10268                                                            sp->bg_extent_count);
10269                                 btrfs_put_block_group(sp->ptr);
10270                         }
10271                         kfree(sp);
10272                 }
10273                 node = next;
10274         }
10275         spin_unlock(&fs_info->swapfile_pins_lock);
10276 }
10277
10278 struct btrfs_swap_info {
10279         u64 start;
10280         u64 block_start;
10281         u64 block_len;
10282         u64 lowest_ppage;
10283         u64 highest_ppage;
10284         unsigned long nr_pages;
10285         int nr_extents;
10286 };
10287
10288 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10289                                  struct btrfs_swap_info *bsi)
10290 {
10291         unsigned long nr_pages;
10292         u64 first_ppage, first_ppage_reported, next_ppage;
10293         int ret;
10294
10295         first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10296         next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10297                                 PAGE_SIZE) >> PAGE_SHIFT;
10298
10299         if (first_ppage >= next_ppage)
10300                 return 0;
10301         nr_pages = next_ppage - first_ppage;
10302
10303         first_ppage_reported = first_ppage;
10304         if (bsi->start == 0)
10305                 first_ppage_reported++;
10306         if (bsi->lowest_ppage > first_ppage_reported)
10307                 bsi->lowest_ppage = first_ppage_reported;
10308         if (bsi->highest_ppage < (next_ppage - 1))
10309                 bsi->highest_ppage = next_ppage - 1;
10310
10311         ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10312         if (ret < 0)
10313                 return ret;
10314         bsi->nr_extents += ret;
10315         bsi->nr_pages += nr_pages;
10316         return 0;
10317 }
10318
10319 static void btrfs_swap_deactivate(struct file *file)
10320 {
10321         struct inode *inode = file_inode(file);
10322
10323         btrfs_free_swapfile_pins(inode);
10324         atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10325 }
10326
10327 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10328                                sector_t *span)
10329 {
10330         struct inode *inode = file_inode(file);
10331         struct btrfs_root *root = BTRFS_I(inode)->root;
10332         struct btrfs_fs_info *fs_info = root->fs_info;
10333         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10334         struct extent_state *cached_state = NULL;
10335         struct extent_map *em = NULL;
10336         struct btrfs_device *device = NULL;
10337         struct btrfs_swap_info bsi = {
10338                 .lowest_ppage = (sector_t)-1ULL,
10339         };
10340         int ret = 0;
10341         u64 isize;
10342         u64 start;
10343
10344         /*
10345          * If the swap file was just created, make sure delalloc is done. If the
10346          * file changes again after this, the user is doing something stupid and
10347          * we don't really care.
10348          */
10349         ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10350         if (ret)
10351                 return ret;
10352
10353         /*
10354          * The inode is locked, so these flags won't change after we check them.
10355          */
10356         if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10357                 btrfs_warn(fs_info, "swapfile must not be compressed");
10358                 return -EINVAL;
10359         }
10360         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10361                 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10362                 return -EINVAL;
10363         }
10364         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10365                 btrfs_warn(fs_info, "swapfile must not be checksummed");
10366                 return -EINVAL;
10367         }
10368
10369         /*
10370          * Balance or device remove/replace/resize can move stuff around from
10371          * under us. The exclop protection makes sure they aren't running/won't
10372          * run concurrently while we are mapping the swap extents, and
10373          * fs_info->swapfile_pins prevents them from running while the swap
10374          * file is active and moving the extents. Note that this also prevents
10375          * a concurrent device add which isn't actually necessary, but it's not
10376          * really worth the trouble to allow it.
10377          */
10378         if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10379                 btrfs_warn(fs_info,
10380            "cannot activate swapfile while exclusive operation is running");
10381                 return -EBUSY;
10382         }
10383
10384         /*
10385          * Prevent snapshot creation while we are activating the swap file.
10386          * We do not want to race with snapshot creation. If snapshot creation
10387          * already started before we bumped nr_swapfiles from 0 to 1 and
10388          * completes before the first write into the swap file after it is
10389          * activated, than that write would fallback to COW.
10390          */
10391         if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10392                 btrfs_exclop_finish(fs_info);
10393                 btrfs_warn(fs_info,
10394            "cannot activate swapfile because snapshot creation is in progress");
10395                 return -EINVAL;
10396         }
10397         /*
10398          * Snapshots can create extents which require COW even if NODATACOW is
10399          * set. We use this counter to prevent snapshots. We must increment it
10400          * before walking the extents because we don't want a concurrent
10401          * snapshot to run after we've already checked the extents.
10402          */
10403         atomic_inc(&root->nr_swapfiles);
10404
10405         isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10406
10407         lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10408         start = 0;
10409         while (start < isize) {
10410                 u64 logical_block_start, physical_block_start;
10411                 struct btrfs_block_group *bg;
10412                 u64 len = isize - start;
10413
10414                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10415                 if (IS_ERR(em)) {
10416                         ret = PTR_ERR(em);
10417                         goto out;
10418                 }
10419
10420                 if (em->block_start == EXTENT_MAP_HOLE) {
10421                         btrfs_warn(fs_info, "swapfile must not have holes");
10422                         ret = -EINVAL;
10423                         goto out;
10424                 }
10425                 if (em->block_start == EXTENT_MAP_INLINE) {
10426                         /*
10427                          * It's unlikely we'll ever actually find ourselves
10428                          * here, as a file small enough to fit inline won't be
10429                          * big enough to store more than the swap header, but in
10430                          * case something changes in the future, let's catch it
10431                          * here rather than later.
10432                          */
10433                         btrfs_warn(fs_info, "swapfile must not be inline");
10434                         ret = -EINVAL;
10435                         goto out;
10436                 }
10437                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10438                         btrfs_warn(fs_info, "swapfile must not be compressed");
10439                         ret = -EINVAL;
10440                         goto out;
10441                 }
10442
10443                 logical_block_start = em->block_start + (start - em->start);
10444                 len = min(len, em->len - (start - em->start));
10445                 free_extent_map(em);
10446                 em = NULL;
10447
10448                 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, true);
10449                 if (ret < 0) {
10450                         goto out;
10451                 } else if (ret) {
10452                         ret = 0;
10453                 } else {
10454                         btrfs_warn(fs_info,
10455                                    "swapfile must not be copy-on-write");
10456                         ret = -EINVAL;
10457                         goto out;
10458                 }
10459
10460                 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10461                 if (IS_ERR(em)) {
10462                         ret = PTR_ERR(em);
10463                         goto out;
10464                 }
10465
10466                 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10467                         btrfs_warn(fs_info,
10468                                    "swapfile must have single data profile");
10469                         ret = -EINVAL;
10470                         goto out;
10471                 }
10472
10473                 if (device == NULL) {
10474                         device = em->map_lookup->stripes[0].dev;
10475                         ret = btrfs_add_swapfile_pin(inode, device, false);
10476                         if (ret == 1)
10477                                 ret = 0;
10478                         else if (ret)
10479                                 goto out;
10480                 } else if (device != em->map_lookup->stripes[0].dev) {
10481                         btrfs_warn(fs_info, "swapfile must be on one device");
10482                         ret = -EINVAL;
10483                         goto out;
10484                 }
10485
10486                 physical_block_start = (em->map_lookup->stripes[0].physical +
10487                                         (logical_block_start - em->start));
10488                 len = min(len, em->len - (logical_block_start - em->start));
10489                 free_extent_map(em);
10490                 em = NULL;
10491
10492                 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10493                 if (!bg) {
10494                         btrfs_warn(fs_info,
10495                            "could not find block group containing swapfile");
10496                         ret = -EINVAL;
10497                         goto out;
10498                 }
10499
10500                 if (!btrfs_inc_block_group_swap_extents(bg)) {
10501                         btrfs_warn(fs_info,
10502                            "block group for swapfile at %llu is read-only%s",
10503                            bg->start,
10504                            atomic_read(&fs_info->scrubs_running) ?
10505                                        " (scrub running)" : "");
10506                         btrfs_put_block_group(bg);
10507                         ret = -EINVAL;
10508                         goto out;
10509                 }
10510
10511                 ret = btrfs_add_swapfile_pin(inode, bg, true);
10512                 if (ret) {
10513                         btrfs_put_block_group(bg);
10514                         if (ret == 1)
10515                                 ret = 0;
10516                         else
10517                                 goto out;
10518                 }
10519
10520                 if (bsi.block_len &&
10521                     bsi.block_start + bsi.block_len == physical_block_start) {
10522                         bsi.block_len += len;
10523                 } else {
10524                         if (bsi.block_len) {
10525                                 ret = btrfs_add_swap_extent(sis, &bsi);
10526                                 if (ret)
10527                                         goto out;
10528                         }
10529                         bsi.start = start;
10530                         bsi.block_start = physical_block_start;
10531                         bsi.block_len = len;
10532                 }
10533
10534                 start += len;
10535         }
10536
10537         if (bsi.block_len)
10538                 ret = btrfs_add_swap_extent(sis, &bsi);
10539
10540 out:
10541         if (!IS_ERR_OR_NULL(em))
10542                 free_extent_map(em);
10543
10544         unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10545
10546         if (ret)
10547                 btrfs_swap_deactivate(file);
10548
10549         btrfs_drew_write_unlock(&root->snapshot_lock);
10550
10551         btrfs_exclop_finish(fs_info);
10552
10553         if (ret)
10554                 return ret;
10555
10556         if (device)
10557                 sis->bdev = device->bdev;
10558         *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10559         sis->max = bsi.nr_pages;
10560         sis->pages = bsi.nr_pages - 1;
10561         sis->highest_bit = bsi.nr_pages - 1;
10562         return bsi.nr_extents;
10563 }
10564 #else
10565 static void btrfs_swap_deactivate(struct file *file)
10566 {
10567 }
10568
10569 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10570                                sector_t *span)
10571 {
10572         return -EOPNOTSUPP;
10573 }
10574 #endif
10575
10576 /*
10577  * Update the number of bytes used in the VFS' inode. When we replace extents in
10578  * a range (clone, dedupe, fallocate's zero range), we must update the number of
10579  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10580  * always get a correct value.
10581  */
10582 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10583                               const u64 add_bytes,
10584                               const u64 del_bytes)
10585 {
10586         if (add_bytes == del_bytes)
10587                 return;
10588
10589         spin_lock(&inode->lock);
10590         if (del_bytes > 0)
10591                 inode_sub_bytes(&inode->vfs_inode, del_bytes);
10592         if (add_bytes > 0)
10593                 inode_add_bytes(&inode->vfs_inode, add_bytes);
10594         spin_unlock(&inode->lock);
10595 }
10596
10597 static const struct inode_operations btrfs_dir_inode_operations = {
10598         .getattr        = btrfs_getattr,
10599         .lookup         = btrfs_lookup,
10600         .create         = btrfs_create,
10601         .unlink         = btrfs_unlink,
10602         .link           = btrfs_link,
10603         .mkdir          = btrfs_mkdir,
10604         .rmdir          = btrfs_rmdir,
10605         .rename         = btrfs_rename2,
10606         .symlink        = btrfs_symlink,
10607         .setattr        = btrfs_setattr,
10608         .mknod          = btrfs_mknod,
10609         .listxattr      = btrfs_listxattr,
10610         .permission     = btrfs_permission,
10611         .get_acl        = btrfs_get_acl,
10612         .set_acl        = btrfs_set_acl,
10613         .update_time    = btrfs_update_time,
10614         .tmpfile        = btrfs_tmpfile,
10615 };
10616
10617 static const struct file_operations btrfs_dir_file_operations = {
10618         .llseek         = generic_file_llseek,
10619         .read           = generic_read_dir,
10620         .iterate_shared = btrfs_real_readdir,
10621         .open           = btrfs_opendir,
10622         .unlocked_ioctl = btrfs_ioctl,
10623 #ifdef CONFIG_COMPAT
10624         .compat_ioctl   = btrfs_compat_ioctl,
10625 #endif
10626         .release        = btrfs_release_file,
10627         .fsync          = btrfs_sync_file,
10628 };
10629
10630 /*
10631  * btrfs doesn't support the bmap operation because swapfiles
10632  * use bmap to make a mapping of extents in the file.  They assume
10633  * these extents won't change over the life of the file and they
10634  * use the bmap result to do IO directly to the drive.
10635  *
10636  * the btrfs bmap call would return logical addresses that aren't
10637  * suitable for IO and they also will change frequently as COW
10638  * operations happen.  So, swapfile + btrfs == corruption.
10639  *
10640  * For now we're avoiding this by dropping bmap.
10641  */
10642 static const struct address_space_operations btrfs_aops = {
10643         .readpage       = btrfs_readpage,
10644         .writepage      = btrfs_writepage,
10645         .writepages     = btrfs_writepages,
10646         .readahead      = btrfs_readahead,
10647         .direct_IO      = noop_direct_IO,
10648         .invalidatepage = btrfs_invalidatepage,
10649         .releasepage    = btrfs_releasepage,
10650 #ifdef CONFIG_MIGRATION
10651         .migratepage    = btrfs_migratepage,
10652 #endif
10653         .set_page_dirty = btrfs_set_page_dirty,
10654         .error_remove_page = generic_error_remove_page,
10655         .swap_activate  = btrfs_swap_activate,
10656         .swap_deactivate = btrfs_swap_deactivate,
10657 };
10658
10659 static const struct inode_operations btrfs_file_inode_operations = {
10660         .getattr        = btrfs_getattr,
10661         .setattr        = btrfs_setattr,
10662         .listxattr      = btrfs_listxattr,
10663         .permission     = btrfs_permission,
10664         .fiemap         = btrfs_fiemap,
10665         .get_acl        = btrfs_get_acl,
10666         .set_acl        = btrfs_set_acl,
10667         .update_time    = btrfs_update_time,
10668 };
10669 static const struct inode_operations btrfs_special_inode_operations = {
10670         .getattr        = btrfs_getattr,
10671         .setattr        = btrfs_setattr,
10672         .permission     = btrfs_permission,
10673         .listxattr      = btrfs_listxattr,
10674         .get_acl        = btrfs_get_acl,
10675         .set_acl        = btrfs_set_acl,
10676         .update_time    = btrfs_update_time,
10677 };
10678 static const struct inode_operations btrfs_symlink_inode_operations = {
10679         .get_link       = page_get_link,
10680         .getattr        = btrfs_getattr,
10681         .setattr        = btrfs_setattr,
10682         .permission     = btrfs_permission,
10683         .listxattr      = btrfs_listxattr,
10684         .update_time    = btrfs_update_time,
10685 };
10686
10687 const struct dentry_operations btrfs_dentry_operations = {
10688         .d_delete       = btrfs_dentry_delete,
10689 };