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