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