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