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