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