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