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