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