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