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