OSDN Git Service

btrfs: simplify iget helpers
[tomoyo/tomoyo-test1.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         u64 ino;
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_digest(shash, kaddr + pgoff, len, csum);
2746
2747         if (memcmp(csum, csum_expected, csum_size))
2748                 goto zeroit;
2749
2750         kunmap_atomic(kaddr);
2751         return 0;
2752 zeroit:
2753         btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2754                                     io_bio->mirror_num);
2755         memset(kaddr + pgoff, 1, len);
2756         flush_dcache_page(page);
2757         kunmap_atomic(kaddr);
2758         return -EIO;
2759 }
2760
2761 /*
2762  * when reads are done, we need to check csums to verify the data is correct
2763  * if there's a match, we allow the bio to finish.  If not, the code in
2764  * extent_io.c will try to find good copies for us.
2765  */
2766 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2767                                       u64 phy_offset, struct page *page,
2768                                       u64 start, u64 end, int mirror)
2769 {
2770         size_t offset = start - page_offset(page);
2771         struct inode *inode = page->mapping->host;
2772         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2773         struct btrfs_root *root = BTRFS_I(inode)->root;
2774
2775         if (PageChecked(page)) {
2776                 ClearPageChecked(page);
2777                 return 0;
2778         }
2779
2780         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2781                 return 0;
2782
2783         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2784             test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2785                 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2786                 return 0;
2787         }
2788
2789         phy_offset >>= inode->i_sb->s_blocksize_bits;
2790         return check_data_csum(inode, io_bio, phy_offset, page, offset, start,
2791                                (size_t)(end - start + 1));
2792 }
2793
2794 /*
2795  * btrfs_add_delayed_iput - perform a delayed iput on @inode
2796  *
2797  * @inode: The inode we want to perform iput on
2798  *
2799  * This function uses the generic vfs_inode::i_count to track whether we should
2800  * just decrement it (in case it's > 1) or if this is the last iput then link
2801  * the inode to the delayed iput machinery. Delayed iputs are processed at
2802  * transaction commit time/superblock commit/cleaner kthread.
2803  */
2804 void btrfs_add_delayed_iput(struct inode *inode)
2805 {
2806         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2807         struct btrfs_inode *binode = BTRFS_I(inode);
2808
2809         if (atomic_add_unless(&inode->i_count, -1, 1))
2810                 return;
2811
2812         atomic_inc(&fs_info->nr_delayed_iputs);
2813         spin_lock(&fs_info->delayed_iput_lock);
2814         ASSERT(list_empty(&binode->delayed_iput));
2815         list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2816         spin_unlock(&fs_info->delayed_iput_lock);
2817         if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2818                 wake_up_process(fs_info->cleaner_kthread);
2819 }
2820
2821 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2822                                     struct btrfs_inode *inode)
2823 {
2824         list_del_init(&inode->delayed_iput);
2825         spin_unlock(&fs_info->delayed_iput_lock);
2826         iput(&inode->vfs_inode);
2827         if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2828                 wake_up(&fs_info->delayed_iputs_wait);
2829         spin_lock(&fs_info->delayed_iput_lock);
2830 }
2831
2832 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2833                                    struct btrfs_inode *inode)
2834 {
2835         if (!list_empty(&inode->delayed_iput)) {
2836                 spin_lock(&fs_info->delayed_iput_lock);
2837                 if (!list_empty(&inode->delayed_iput))
2838                         run_delayed_iput_locked(fs_info, inode);
2839                 spin_unlock(&fs_info->delayed_iput_lock);
2840         }
2841 }
2842
2843 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2844 {
2845
2846         spin_lock(&fs_info->delayed_iput_lock);
2847         while (!list_empty(&fs_info->delayed_iputs)) {
2848                 struct btrfs_inode *inode;
2849
2850                 inode = list_first_entry(&fs_info->delayed_iputs,
2851                                 struct btrfs_inode, delayed_iput);
2852                 run_delayed_iput_locked(fs_info, inode);
2853         }
2854         spin_unlock(&fs_info->delayed_iput_lock);
2855 }
2856
2857 /**
2858  * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2859  * @fs_info - the fs_info for this fs
2860  * @return - EINTR if we were killed, 0 if nothing's pending
2861  *
2862  * This will wait on any delayed iputs that are currently running with KILLABLE
2863  * set.  Once they are all done running we will return, unless we are killed in
2864  * which case we return EINTR. This helps in user operations like fallocate etc
2865  * that might get blocked on the iputs.
2866  */
2867 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2868 {
2869         int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2870                         atomic_read(&fs_info->nr_delayed_iputs) == 0);
2871         if (ret)
2872                 return -EINTR;
2873         return 0;
2874 }
2875
2876 /*
2877  * This creates an orphan entry for the given inode in case something goes wrong
2878  * in the middle of an unlink.
2879  */
2880 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2881                      struct btrfs_inode *inode)
2882 {
2883         int ret;
2884
2885         ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2886         if (ret && ret != -EEXIST) {
2887                 btrfs_abort_transaction(trans, ret);
2888                 return ret;
2889         }
2890
2891         return 0;
2892 }
2893
2894 /*
2895  * We have done the delete so we can go ahead and remove the orphan item for
2896  * this particular inode.
2897  */
2898 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2899                             struct btrfs_inode *inode)
2900 {
2901         return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2902 }
2903
2904 /*
2905  * this cleans up any orphans that may be left on the list from the last use
2906  * of this root.
2907  */
2908 int btrfs_orphan_cleanup(struct btrfs_root *root)
2909 {
2910         struct btrfs_fs_info *fs_info = root->fs_info;
2911         struct btrfs_path *path;
2912         struct extent_buffer *leaf;
2913         struct btrfs_key key, found_key;
2914         struct btrfs_trans_handle *trans;
2915         struct inode *inode;
2916         u64 last_objectid = 0;
2917         int ret = 0, nr_unlink = 0;
2918
2919         if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2920                 return 0;
2921
2922         path = btrfs_alloc_path();
2923         if (!path) {
2924                 ret = -ENOMEM;
2925                 goto out;
2926         }
2927         path->reada = READA_BACK;
2928
2929         key.objectid = BTRFS_ORPHAN_OBJECTID;
2930         key.type = BTRFS_ORPHAN_ITEM_KEY;
2931         key.offset = (u64)-1;
2932
2933         while (1) {
2934                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2935                 if (ret < 0)
2936                         goto out;
2937
2938                 /*
2939                  * if ret == 0 means we found what we were searching for, which
2940                  * is weird, but possible, so only screw with path if we didn't
2941                  * find the key and see if we have stuff that matches
2942                  */
2943                 if (ret > 0) {
2944                         ret = 0;
2945                         if (path->slots[0] == 0)
2946                                 break;
2947                         path->slots[0]--;
2948                 }
2949
2950                 /* pull out the item */
2951                 leaf = path->nodes[0];
2952                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2953
2954                 /* make sure the item matches what we want */
2955                 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2956                         break;
2957                 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
2958                         break;
2959
2960                 /* release the path since we're done with it */
2961                 btrfs_release_path(path);
2962
2963                 /*
2964                  * this is where we are basically btrfs_lookup, without the
2965                  * crossing root thing.  we store the inode number in the
2966                  * offset of the orphan item.
2967                  */
2968
2969                 if (found_key.offset == last_objectid) {
2970                         btrfs_err(fs_info,
2971                                   "Error removing orphan entry, stopping orphan cleanup");
2972                         ret = -EINVAL;
2973                         goto out;
2974                 }
2975
2976                 last_objectid = found_key.offset;
2977
2978                 found_key.objectid = found_key.offset;
2979                 found_key.type = BTRFS_INODE_ITEM_KEY;
2980                 found_key.offset = 0;
2981                 inode = btrfs_iget(fs_info->sb, last_objectid, root);
2982                 ret = PTR_ERR_OR_ZERO(inode);
2983                 if (ret && ret != -ENOENT)
2984                         goto out;
2985
2986                 if (ret == -ENOENT && root == fs_info->tree_root) {
2987                         struct btrfs_root *dead_root;
2988                         struct btrfs_fs_info *fs_info = root->fs_info;
2989                         int is_dead_root = 0;
2990
2991                         /*
2992                          * this is an orphan in the tree root. Currently these
2993                          * could come from 2 sources:
2994                          *  a) a snapshot deletion in progress
2995                          *  b) a free space cache inode
2996                          * We need to distinguish those two, as the snapshot
2997                          * orphan must not get deleted.
2998                          * find_dead_roots already ran before us, so if this
2999                          * is a snapshot deletion, we should find the root
3000                          * in the fs_roots radix tree.
3001                          */
3002
3003                         spin_lock(&fs_info->fs_roots_radix_lock);
3004                         dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3005                                                          (unsigned long)found_key.objectid);
3006                         if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3007                                 is_dead_root = 1;
3008                         spin_unlock(&fs_info->fs_roots_radix_lock);
3009
3010                         if (is_dead_root) {
3011                                 /* prevent this orphan from being found again */
3012                                 key.offset = found_key.objectid - 1;
3013                                 continue;
3014                         }
3015
3016                 }
3017
3018                 /*
3019                  * If we have an inode with links, there are a couple of
3020                  * possibilities. Old kernels (before v3.12) used to create an
3021                  * orphan item for truncate indicating that there were possibly
3022                  * extent items past i_size that needed to be deleted. In v3.12,
3023                  * truncate was changed to update i_size in sync with the extent
3024                  * items, but the (useless) orphan item was still created. Since
3025                  * v4.18, we don't create the orphan item for truncate at all.
3026                  *
3027                  * So, this item could mean that we need to do a truncate, but
3028                  * only if this filesystem was last used on a pre-v3.12 kernel
3029                  * and was not cleanly unmounted. The odds of that are quite
3030                  * slim, and it's a pain to do the truncate now, so just delete
3031                  * the orphan item.
3032                  *
3033                  * It's also possible that this orphan item was supposed to be
3034                  * deleted but wasn't. The inode number may have been reused,
3035                  * but either way, we can delete the orphan item.
3036                  */
3037                 if (ret == -ENOENT || inode->i_nlink) {
3038                         if (!ret)
3039                                 iput(inode);
3040                         trans = btrfs_start_transaction(root, 1);
3041                         if (IS_ERR(trans)) {
3042                                 ret = PTR_ERR(trans);
3043                                 goto out;
3044                         }
3045                         btrfs_debug(fs_info, "auto deleting %Lu",
3046                                     found_key.objectid);
3047                         ret = btrfs_del_orphan_item(trans, root,
3048                                                     found_key.objectid);
3049                         btrfs_end_transaction(trans);
3050                         if (ret)
3051                                 goto out;
3052                         continue;
3053                 }
3054
3055                 nr_unlink++;
3056
3057                 /* this will do delete_inode and everything for us */
3058                 iput(inode);
3059         }
3060         /* release the path since we're done with it */
3061         btrfs_release_path(path);
3062
3063         root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3064
3065         if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3066                 trans = btrfs_join_transaction(root);
3067                 if (!IS_ERR(trans))
3068                         btrfs_end_transaction(trans);
3069         }
3070
3071         if (nr_unlink)
3072                 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3073
3074 out:
3075         if (ret)
3076                 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3077         btrfs_free_path(path);
3078         return ret;
3079 }
3080
3081 /*
3082  * very simple check to peek ahead in the leaf looking for xattrs.  If we
3083  * don't find any xattrs, we know there can't be any acls.
3084  *
3085  * slot is the slot the inode is in, objectid is the objectid of the inode
3086  */
3087 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3088                                           int slot, u64 objectid,
3089                                           int *first_xattr_slot)
3090 {
3091         u32 nritems = btrfs_header_nritems(leaf);
3092         struct btrfs_key found_key;
3093         static u64 xattr_access = 0;
3094         static u64 xattr_default = 0;
3095         int scanned = 0;
3096
3097         if (!xattr_access) {
3098                 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3099                                         strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3100                 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3101                                         strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3102         }
3103
3104         slot++;
3105         *first_xattr_slot = -1;
3106         while (slot < nritems) {
3107                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3108
3109                 /* we found a different objectid, there must not be acls */
3110                 if (found_key.objectid != objectid)
3111                         return 0;
3112
3113                 /* we found an xattr, assume we've got an acl */
3114                 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3115                         if (*first_xattr_slot == -1)
3116                                 *first_xattr_slot = slot;
3117                         if (found_key.offset == xattr_access ||
3118                             found_key.offset == xattr_default)
3119                                 return 1;
3120                 }
3121
3122                 /*
3123                  * we found a key greater than an xattr key, there can't
3124                  * be any acls later on
3125                  */
3126                 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3127                         return 0;
3128
3129                 slot++;
3130                 scanned++;
3131
3132                 /*
3133                  * it goes inode, inode backrefs, xattrs, extents,
3134                  * so if there are a ton of hard links to an inode there can
3135                  * be a lot of backrefs.  Don't waste time searching too hard,
3136                  * this is just an optimization
3137                  */
3138                 if (scanned >= 8)
3139                         break;
3140         }
3141         /* we hit the end of the leaf before we found an xattr or
3142          * something larger than an xattr.  We have to assume the inode
3143          * has acls
3144          */
3145         if (*first_xattr_slot == -1)
3146                 *first_xattr_slot = slot;
3147         return 1;
3148 }
3149
3150 /*
3151  * read an inode from the btree into the in-memory inode
3152  */
3153 static int btrfs_read_locked_inode(struct inode *inode,
3154                                    struct btrfs_path *in_path)
3155 {
3156         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3157         struct btrfs_path *path = in_path;
3158         struct extent_buffer *leaf;
3159         struct btrfs_inode_item *inode_item;
3160         struct btrfs_root *root = BTRFS_I(inode)->root;
3161         struct btrfs_key location;
3162         unsigned long ptr;
3163         int maybe_acls;
3164         u32 rdev;
3165         int ret;
3166         bool filled = false;
3167         int first_xattr_slot;
3168
3169         ret = btrfs_fill_inode(inode, &rdev);
3170         if (!ret)
3171                 filled = true;
3172
3173         if (!path) {
3174                 path = btrfs_alloc_path();
3175                 if (!path)
3176                         return -ENOMEM;
3177         }
3178
3179         memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3180
3181         ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3182         if (ret) {
3183                 if (path != in_path)
3184                         btrfs_free_path(path);
3185                 return ret;
3186         }
3187
3188         leaf = path->nodes[0];
3189
3190         if (filled)
3191                 goto cache_index;
3192
3193         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3194                                     struct btrfs_inode_item);
3195         inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3196         set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3197         i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3198         i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3199         btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3200         btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
3201                         round_up(i_size_read(inode), fs_info->sectorsize));
3202
3203         inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3204         inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3205
3206         inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3207         inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3208
3209         inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3210         inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3211
3212         BTRFS_I(inode)->i_otime.tv_sec =
3213                 btrfs_timespec_sec(leaf, &inode_item->otime);
3214         BTRFS_I(inode)->i_otime.tv_nsec =
3215                 btrfs_timespec_nsec(leaf, &inode_item->otime);
3216
3217         inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3218         BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3219         BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3220
3221         inode_set_iversion_queried(inode,
3222                                    btrfs_inode_sequence(leaf, inode_item));
3223         inode->i_generation = BTRFS_I(inode)->generation;
3224         inode->i_rdev = 0;
3225         rdev = btrfs_inode_rdev(leaf, inode_item);
3226
3227         BTRFS_I(inode)->index_cnt = (u64)-1;
3228         BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3229
3230 cache_index:
3231         /*
3232          * If we were modified in the current generation and evicted from memory
3233          * and then re-read we need to do a full sync since we don't have any
3234          * idea about which extents were modified before we were evicted from
3235          * cache.
3236          *
3237          * This is required for both inode re-read from disk and delayed inode
3238          * in delayed_nodes_tree.
3239          */
3240         if (BTRFS_I(inode)->last_trans == fs_info->generation)
3241                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3242                         &BTRFS_I(inode)->runtime_flags);
3243
3244         /*
3245          * We don't persist the id of the transaction where an unlink operation
3246          * against the inode was last made. So here we assume the inode might
3247          * have been evicted, and therefore the exact value of last_unlink_trans
3248          * lost, and set it to last_trans to avoid metadata inconsistencies
3249          * between the inode and its parent if the inode is fsync'ed and the log
3250          * replayed. For example, in the scenario:
3251          *
3252          * touch mydir/foo
3253          * ln mydir/foo mydir/bar
3254          * sync
3255          * unlink mydir/bar
3256          * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3257          * xfs_io -c fsync mydir/foo
3258          * <power failure>
3259          * mount fs, triggers fsync log replay
3260          *
3261          * We must make sure that when we fsync our inode foo we also log its
3262          * parent inode, otherwise after log replay the parent still has the
3263          * dentry with the "bar" name but our inode foo has a link count of 1
3264          * and doesn't have an inode ref with the name "bar" anymore.
3265          *
3266          * Setting last_unlink_trans to last_trans is a pessimistic approach,
3267          * but it guarantees correctness at the expense of occasional full
3268          * transaction commits on fsync if our inode is a directory, or if our
3269          * inode is not a directory, logging its parent unnecessarily.
3270          */
3271         BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3272
3273         path->slots[0]++;
3274         if (inode->i_nlink != 1 ||
3275             path->slots[0] >= btrfs_header_nritems(leaf))
3276                 goto cache_acl;
3277
3278         btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3279         if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3280                 goto cache_acl;
3281
3282         ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3283         if (location.type == BTRFS_INODE_REF_KEY) {
3284                 struct btrfs_inode_ref *ref;
3285
3286                 ref = (struct btrfs_inode_ref *)ptr;
3287                 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3288         } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3289                 struct btrfs_inode_extref *extref;
3290
3291                 extref = (struct btrfs_inode_extref *)ptr;
3292                 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3293                                                                      extref);
3294         }
3295 cache_acl:
3296         /*
3297          * try to precache a NULL acl entry for files that don't have
3298          * any xattrs or acls
3299          */
3300         maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3301                         btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3302         if (first_xattr_slot != -1) {
3303                 path->slots[0] = first_xattr_slot;
3304                 ret = btrfs_load_inode_props(inode, path);
3305                 if (ret)
3306                         btrfs_err(fs_info,
3307                                   "error loading props for ino %llu (root %llu): %d",
3308                                   btrfs_ino(BTRFS_I(inode)),
3309                                   root->root_key.objectid, ret);
3310         }
3311         if (path != in_path)
3312                 btrfs_free_path(path);
3313
3314         if (!maybe_acls)
3315                 cache_no_acl(inode);
3316
3317         switch (inode->i_mode & S_IFMT) {
3318         case S_IFREG:
3319                 inode->i_mapping->a_ops = &btrfs_aops;
3320                 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3321                 inode->i_fop = &btrfs_file_operations;
3322                 inode->i_op = &btrfs_file_inode_operations;
3323                 break;
3324         case S_IFDIR:
3325                 inode->i_fop = &btrfs_dir_file_operations;
3326                 inode->i_op = &btrfs_dir_inode_operations;
3327                 break;
3328         case S_IFLNK:
3329                 inode->i_op = &btrfs_symlink_inode_operations;
3330                 inode_nohighmem(inode);
3331                 inode->i_mapping->a_ops = &btrfs_aops;
3332                 break;
3333         default:
3334                 inode->i_op = &btrfs_special_inode_operations;
3335                 init_special_inode(inode, inode->i_mode, rdev);
3336                 break;
3337         }
3338
3339         btrfs_sync_inode_flags_to_i_flags(inode);
3340         return 0;
3341 }
3342
3343 /*
3344  * given a leaf and an inode, copy the inode fields into the leaf
3345  */
3346 static void fill_inode_item(struct btrfs_trans_handle *trans,
3347                             struct extent_buffer *leaf,
3348                             struct btrfs_inode_item *item,
3349                             struct inode *inode)
3350 {
3351         struct btrfs_map_token token;
3352
3353         btrfs_init_map_token(&token, leaf);
3354
3355         btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
3356         btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
3357         btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
3358         btrfs_set_token_inode_mode(&token, item, inode->i_mode);
3359         btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
3360
3361         btrfs_set_token_timespec_sec(&token, &item->atime,
3362                                      inode->i_atime.tv_sec);
3363         btrfs_set_token_timespec_nsec(&token, &item->atime,
3364                                       inode->i_atime.tv_nsec);
3365
3366         btrfs_set_token_timespec_sec(&token, &item->mtime,
3367                                      inode->i_mtime.tv_sec);
3368         btrfs_set_token_timespec_nsec(&token, &item->mtime,
3369                                       inode->i_mtime.tv_nsec);
3370
3371         btrfs_set_token_timespec_sec(&token, &item->ctime,
3372                                      inode->i_ctime.tv_sec);
3373         btrfs_set_token_timespec_nsec(&token, &item->ctime,
3374                                       inode->i_ctime.tv_nsec);
3375
3376         btrfs_set_token_timespec_sec(&token, &item->otime,
3377                                      BTRFS_I(inode)->i_otime.tv_sec);
3378         btrfs_set_token_timespec_nsec(&token, &item->otime,
3379                                       BTRFS_I(inode)->i_otime.tv_nsec);
3380
3381         btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
3382         btrfs_set_token_inode_generation(&token, item,
3383                                          BTRFS_I(inode)->generation);
3384         btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
3385         btrfs_set_token_inode_transid(&token, item, trans->transid);
3386         btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
3387         btrfs_set_token_inode_flags(&token, item, BTRFS_I(inode)->flags);
3388         btrfs_set_token_inode_block_group(&token, item, 0);
3389 }
3390
3391 /*
3392  * copy everything in the in-memory inode into the btree.
3393  */
3394 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3395                                 struct btrfs_root *root, struct inode *inode)
3396 {
3397         struct btrfs_inode_item *inode_item;
3398         struct btrfs_path *path;
3399         struct extent_buffer *leaf;
3400         int ret;
3401
3402         path = btrfs_alloc_path();
3403         if (!path)
3404                 return -ENOMEM;
3405
3406         path->leave_spinning = 1;
3407         ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3408                                  1);
3409         if (ret) {
3410                 if (ret > 0)
3411                         ret = -ENOENT;
3412                 goto failed;
3413         }
3414
3415         leaf = path->nodes[0];
3416         inode_item = btrfs_item_ptr(leaf, path->slots[0],
3417                                     struct btrfs_inode_item);
3418
3419         fill_inode_item(trans, leaf, inode_item, inode);
3420         btrfs_mark_buffer_dirty(leaf);
3421         btrfs_set_inode_last_trans(trans, inode);
3422         ret = 0;
3423 failed:
3424         btrfs_free_path(path);
3425         return ret;
3426 }
3427
3428 /*
3429  * copy everything in the in-memory inode into the btree.
3430  */
3431 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3432                                 struct btrfs_root *root, struct inode *inode)
3433 {
3434         struct btrfs_fs_info *fs_info = root->fs_info;
3435         int ret;
3436
3437         /*
3438          * If the inode is a free space inode, we can deadlock during commit
3439          * if we put it into the delayed code.
3440          *
3441          * The data relocation inode should also be directly updated
3442          * without delay
3443          */
3444         if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3445             && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3446             && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3447                 btrfs_update_root_times(trans, root);
3448
3449                 ret = btrfs_delayed_update_inode(trans, root, inode);
3450                 if (!ret)
3451                         btrfs_set_inode_last_trans(trans, inode);
3452                 return ret;
3453         }
3454
3455         return btrfs_update_inode_item(trans, root, inode);
3456 }
3457
3458 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3459                                          struct btrfs_root *root,
3460                                          struct inode *inode)
3461 {
3462         int ret;
3463
3464         ret = btrfs_update_inode(trans, root, inode);
3465         if (ret == -ENOSPC)
3466                 return btrfs_update_inode_item(trans, root, inode);
3467         return ret;
3468 }
3469
3470 /*
3471  * unlink helper that gets used here in inode.c and in the tree logging
3472  * recovery code.  It remove a link in a directory with a given name, and
3473  * also drops the back refs in the inode to the directory
3474  */
3475 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3476                                 struct btrfs_root *root,
3477                                 struct btrfs_inode *dir,
3478                                 struct btrfs_inode *inode,
3479                                 const char *name, int name_len)
3480 {
3481         struct btrfs_fs_info *fs_info = root->fs_info;
3482         struct btrfs_path *path;
3483         int ret = 0;
3484         struct btrfs_dir_item *di;
3485         u64 index;
3486         u64 ino = btrfs_ino(inode);
3487         u64 dir_ino = btrfs_ino(dir);
3488
3489         path = btrfs_alloc_path();
3490         if (!path) {
3491                 ret = -ENOMEM;
3492                 goto out;
3493         }
3494
3495         path->leave_spinning = 1;
3496         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3497                                     name, name_len, -1);
3498         if (IS_ERR_OR_NULL(di)) {
3499                 ret = di ? PTR_ERR(di) : -ENOENT;
3500                 goto err;
3501         }
3502         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3503         if (ret)
3504                 goto err;
3505         btrfs_release_path(path);
3506
3507         /*
3508          * If we don't have dir index, we have to get it by looking up
3509          * the inode ref, since we get the inode ref, remove it directly,
3510          * it is unnecessary to do delayed deletion.
3511          *
3512          * But if we have dir index, needn't search inode ref to get it.
3513          * Since the inode ref is close to the inode item, it is better
3514          * that we delay to delete it, and just do this deletion when
3515          * we update the inode item.
3516          */
3517         if (inode->dir_index) {
3518                 ret = btrfs_delayed_delete_inode_ref(inode);
3519                 if (!ret) {
3520                         index = inode->dir_index;
3521                         goto skip_backref;
3522                 }
3523         }
3524
3525         ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3526                                   dir_ino, &index);
3527         if (ret) {
3528                 btrfs_info(fs_info,
3529                         "failed to delete reference to %.*s, inode %llu parent %llu",
3530                         name_len, name, ino, dir_ino);
3531                 btrfs_abort_transaction(trans, ret);
3532                 goto err;
3533         }
3534 skip_backref:
3535         ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3536         if (ret) {
3537                 btrfs_abort_transaction(trans, ret);
3538                 goto err;
3539         }
3540
3541         ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3542                         dir_ino);
3543         if (ret != 0 && ret != -ENOENT) {
3544                 btrfs_abort_transaction(trans, ret);
3545                 goto err;
3546         }
3547
3548         ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3549                         index);
3550         if (ret == -ENOENT)
3551                 ret = 0;
3552         else if (ret)
3553                 btrfs_abort_transaction(trans, ret);
3554
3555         /*
3556          * If we have a pending delayed iput we could end up with the final iput
3557          * being run in btrfs-cleaner context.  If we have enough of these built
3558          * up we can end up burning a lot of time in btrfs-cleaner without any
3559          * way to throttle the unlinks.  Since we're currently holding a ref on
3560          * the inode we can run the delayed iput here without any issues as the
3561          * final iput won't be done until after we drop the ref we're currently
3562          * holding.
3563          */
3564         btrfs_run_delayed_iput(fs_info, inode);
3565 err:
3566         btrfs_free_path(path);
3567         if (ret)
3568                 goto out;
3569
3570         btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3571         inode_inc_iversion(&inode->vfs_inode);
3572         inode_inc_iversion(&dir->vfs_inode);
3573         inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3574                 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3575         ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3576 out:
3577         return ret;
3578 }
3579
3580 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3581                        struct btrfs_root *root,
3582                        struct btrfs_inode *dir, struct btrfs_inode *inode,
3583                        const char *name, int name_len)
3584 {
3585         int ret;
3586         ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3587         if (!ret) {
3588                 drop_nlink(&inode->vfs_inode);
3589                 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3590         }
3591         return ret;
3592 }
3593
3594 /*
3595  * helper to start transaction for unlink and rmdir.
3596  *
3597  * unlink and rmdir are special in btrfs, they do not always free space, so
3598  * if we cannot make our reservations the normal way try and see if there is
3599  * plenty of slack room in the global reserve to migrate, otherwise we cannot
3600  * allow the unlink to occur.
3601  */
3602 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3603 {
3604         struct btrfs_root *root = BTRFS_I(dir)->root;
3605
3606         /*
3607          * 1 for the possible orphan item
3608          * 1 for the dir item
3609          * 1 for the dir index
3610          * 1 for the inode ref
3611          * 1 for the inode
3612          */
3613         return btrfs_start_transaction_fallback_global_rsv(root, 5);
3614 }
3615
3616 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3617 {
3618         struct btrfs_root *root = BTRFS_I(dir)->root;
3619         struct btrfs_trans_handle *trans;
3620         struct inode *inode = d_inode(dentry);
3621         int ret;
3622
3623         trans = __unlink_start_trans(dir);
3624         if (IS_ERR(trans))
3625                 return PTR_ERR(trans);
3626
3627         btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3628                         0);
3629
3630         ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3631                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3632                         dentry->d_name.len);
3633         if (ret)
3634                 goto out;
3635
3636         if (inode->i_nlink == 0) {
3637                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3638                 if (ret)
3639                         goto out;
3640         }
3641
3642 out:
3643         btrfs_end_transaction(trans);
3644         btrfs_btree_balance_dirty(root->fs_info);
3645         return ret;
3646 }
3647
3648 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3649                                struct inode *dir, struct dentry *dentry)
3650 {
3651         struct btrfs_root *root = BTRFS_I(dir)->root;
3652         struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3653         struct btrfs_path *path;
3654         struct extent_buffer *leaf;
3655         struct btrfs_dir_item *di;
3656         struct btrfs_key key;
3657         const char *name = dentry->d_name.name;
3658         int name_len = dentry->d_name.len;
3659         u64 index;
3660         int ret;
3661         u64 objectid;
3662         u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3663
3664         if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3665                 objectid = inode->root->root_key.objectid;
3666         } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3667                 objectid = inode->location.objectid;
3668         } else {
3669                 WARN_ON(1);
3670                 return -EINVAL;
3671         }
3672
3673         path = btrfs_alloc_path();
3674         if (!path)
3675                 return -ENOMEM;
3676
3677         di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3678                                    name, name_len, -1);
3679         if (IS_ERR_OR_NULL(di)) {
3680                 ret = di ? PTR_ERR(di) : -ENOENT;
3681                 goto out;
3682         }
3683
3684         leaf = path->nodes[0];
3685         btrfs_dir_item_key_to_cpu(leaf, di, &key);
3686         WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3687         ret = btrfs_delete_one_dir_name(trans, root, path, di);
3688         if (ret) {
3689                 btrfs_abort_transaction(trans, ret);
3690                 goto out;
3691         }
3692         btrfs_release_path(path);
3693
3694         /*
3695          * This is a placeholder inode for a subvolume we didn't have a
3696          * reference to at the time of the snapshot creation.  In the meantime
3697          * we could have renamed the real subvol link into our snapshot, so
3698          * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3699          * Instead simply lookup the dir_index_item for this entry so we can
3700          * remove it.  Otherwise we know we have a ref to the root and we can
3701          * call btrfs_del_root_ref, and it _shouldn't_ fail.
3702          */
3703         if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3704                 di = btrfs_search_dir_index_item(root, path, dir_ino,
3705                                                  name, name_len);
3706                 if (IS_ERR_OR_NULL(di)) {
3707                         if (!di)
3708                                 ret = -ENOENT;
3709                         else
3710                                 ret = PTR_ERR(di);
3711                         btrfs_abort_transaction(trans, ret);
3712                         goto out;
3713                 }
3714
3715                 leaf = path->nodes[0];
3716                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3717                 index = key.offset;
3718                 btrfs_release_path(path);
3719         } else {
3720                 ret = btrfs_del_root_ref(trans, objectid,
3721                                          root->root_key.objectid, dir_ino,
3722                                          &index, name, name_len);
3723                 if (ret) {
3724                         btrfs_abort_transaction(trans, ret);
3725                         goto out;
3726                 }
3727         }
3728
3729         ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3730         if (ret) {
3731                 btrfs_abort_transaction(trans, ret);
3732                 goto out;
3733         }
3734
3735         btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3736         inode_inc_iversion(dir);
3737         dir->i_mtime = dir->i_ctime = current_time(dir);
3738         ret = btrfs_update_inode_fallback(trans, root, dir);
3739         if (ret)
3740                 btrfs_abort_transaction(trans, ret);
3741 out:
3742         btrfs_free_path(path);
3743         return ret;
3744 }
3745
3746 /*
3747  * Helper to check if the subvolume references other subvolumes or if it's
3748  * default.
3749  */
3750 static noinline int may_destroy_subvol(struct btrfs_root *root)
3751 {
3752         struct btrfs_fs_info *fs_info = root->fs_info;
3753         struct btrfs_path *path;
3754         struct btrfs_dir_item *di;
3755         struct btrfs_key key;
3756         u64 dir_id;
3757         int ret;
3758
3759         path = btrfs_alloc_path();
3760         if (!path)
3761                 return -ENOMEM;
3762
3763         /* Make sure this root isn't set as the default subvol */
3764         dir_id = btrfs_super_root_dir(fs_info->super_copy);
3765         di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3766                                    dir_id, "default", 7, 0);
3767         if (di && !IS_ERR(di)) {
3768                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3769                 if (key.objectid == root->root_key.objectid) {
3770                         ret = -EPERM;
3771                         btrfs_err(fs_info,
3772                                   "deleting default subvolume %llu is not allowed",
3773                                   key.objectid);
3774                         goto out;
3775                 }
3776                 btrfs_release_path(path);
3777         }
3778
3779         key.objectid = root->root_key.objectid;
3780         key.type = BTRFS_ROOT_REF_KEY;
3781         key.offset = (u64)-1;
3782
3783         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3784         if (ret < 0)
3785                 goto out;
3786         BUG_ON(ret == 0);
3787
3788         ret = 0;
3789         if (path->slots[0] > 0) {
3790                 path->slots[0]--;
3791                 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3792                 if (key.objectid == root->root_key.objectid &&
3793                     key.type == BTRFS_ROOT_REF_KEY)
3794                         ret = -ENOTEMPTY;
3795         }
3796 out:
3797         btrfs_free_path(path);
3798         return ret;
3799 }
3800
3801 /* Delete all dentries for inodes belonging to the root */
3802 static void btrfs_prune_dentries(struct btrfs_root *root)
3803 {
3804         struct btrfs_fs_info *fs_info = root->fs_info;
3805         struct rb_node *node;
3806         struct rb_node *prev;
3807         struct btrfs_inode *entry;
3808         struct inode *inode;
3809         u64 objectid = 0;
3810
3811         if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3812                 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3813
3814         spin_lock(&root->inode_lock);
3815 again:
3816         node = root->inode_tree.rb_node;
3817         prev = NULL;
3818         while (node) {
3819                 prev = node;
3820                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3821
3822                 if (objectid < btrfs_ino(entry))
3823                         node = node->rb_left;
3824                 else if (objectid > btrfs_ino(entry))
3825                         node = node->rb_right;
3826                 else
3827                         break;
3828         }
3829         if (!node) {
3830                 while (prev) {
3831                         entry = rb_entry(prev, struct btrfs_inode, rb_node);
3832                         if (objectid <= btrfs_ino(entry)) {
3833                                 node = prev;
3834                                 break;
3835                         }
3836                         prev = rb_next(prev);
3837                 }
3838         }
3839         while (node) {
3840                 entry = rb_entry(node, struct btrfs_inode, rb_node);
3841                 objectid = btrfs_ino(entry) + 1;
3842                 inode = igrab(&entry->vfs_inode);
3843                 if (inode) {
3844                         spin_unlock(&root->inode_lock);
3845                         if (atomic_read(&inode->i_count) > 1)
3846                                 d_prune_aliases(inode);
3847                         /*
3848                          * btrfs_drop_inode will have it removed from the inode
3849                          * cache when its usage count hits zero.
3850                          */
3851                         iput(inode);
3852                         cond_resched();
3853                         spin_lock(&root->inode_lock);
3854                         goto again;
3855                 }
3856
3857                 if (cond_resched_lock(&root->inode_lock))
3858                         goto again;
3859
3860                 node = rb_next(node);
3861         }
3862         spin_unlock(&root->inode_lock);
3863 }
3864
3865 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3866 {
3867         struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3868         struct btrfs_root *root = BTRFS_I(dir)->root;
3869         struct inode *inode = d_inode(dentry);
3870         struct btrfs_root *dest = BTRFS_I(inode)->root;
3871         struct btrfs_trans_handle *trans;
3872         struct btrfs_block_rsv block_rsv;
3873         u64 root_flags;
3874         int ret;
3875         int err;
3876
3877         /*
3878          * Don't allow to delete a subvolume with send in progress. This is
3879          * inside the inode lock so the error handling that has to drop the bit
3880          * again is not run concurrently.
3881          */
3882         spin_lock(&dest->root_item_lock);
3883         if (dest->send_in_progress) {
3884                 spin_unlock(&dest->root_item_lock);
3885                 btrfs_warn(fs_info,
3886                            "attempt to delete subvolume %llu during send",
3887                            dest->root_key.objectid);
3888                 return -EPERM;
3889         }
3890         root_flags = btrfs_root_flags(&dest->root_item);
3891         btrfs_set_root_flags(&dest->root_item,
3892                              root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3893         spin_unlock(&dest->root_item_lock);
3894
3895         down_write(&fs_info->subvol_sem);
3896
3897         err = may_destroy_subvol(dest);
3898         if (err)
3899                 goto out_up_write;
3900
3901         btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3902         /*
3903          * One for dir inode,
3904          * two for dir entries,
3905          * two for root ref/backref.
3906          */
3907         err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3908         if (err)
3909                 goto out_up_write;
3910
3911         trans = btrfs_start_transaction(root, 0);
3912         if (IS_ERR(trans)) {
3913                 err = PTR_ERR(trans);
3914                 goto out_release;
3915         }
3916         trans->block_rsv = &block_rsv;
3917         trans->bytes_reserved = block_rsv.size;
3918
3919         btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3920
3921         ret = btrfs_unlink_subvol(trans, dir, dentry);
3922         if (ret) {
3923                 err = ret;
3924                 btrfs_abort_transaction(trans, ret);
3925                 goto out_end_trans;
3926         }
3927
3928         btrfs_record_root_in_trans(trans, dest);
3929
3930         memset(&dest->root_item.drop_progress, 0,
3931                 sizeof(dest->root_item.drop_progress));
3932         dest->root_item.drop_level = 0;
3933         btrfs_set_root_refs(&dest->root_item, 0);
3934
3935         if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3936                 ret = btrfs_insert_orphan_item(trans,
3937                                         fs_info->tree_root,
3938                                         dest->root_key.objectid);
3939                 if (ret) {
3940                         btrfs_abort_transaction(trans, ret);
3941                         err = ret;
3942                         goto out_end_trans;
3943                 }
3944         }
3945
3946         ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
3947                                   BTRFS_UUID_KEY_SUBVOL,
3948                                   dest->root_key.objectid);
3949         if (ret && ret != -ENOENT) {
3950                 btrfs_abort_transaction(trans, ret);
3951                 err = ret;
3952                 goto out_end_trans;
3953         }
3954         if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
3955                 ret = btrfs_uuid_tree_remove(trans,
3956                                           dest->root_item.received_uuid,
3957                                           BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3958                                           dest->root_key.objectid);
3959                 if (ret && ret != -ENOENT) {
3960                         btrfs_abort_transaction(trans, ret);
3961                         err = ret;
3962                         goto out_end_trans;
3963                 }
3964         }
3965
3966 out_end_trans:
3967         trans->block_rsv = NULL;
3968         trans->bytes_reserved = 0;
3969         ret = btrfs_end_transaction(trans);
3970         if (ret && !err)
3971                 err = ret;
3972         inode->i_flags |= S_DEAD;
3973 out_release:
3974         btrfs_subvolume_release_metadata(fs_info, &block_rsv);
3975 out_up_write:
3976         up_write(&fs_info->subvol_sem);
3977         if (err) {
3978                 spin_lock(&dest->root_item_lock);
3979                 root_flags = btrfs_root_flags(&dest->root_item);
3980                 btrfs_set_root_flags(&dest->root_item,
3981                                 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
3982                 spin_unlock(&dest->root_item_lock);
3983         } else {
3984                 d_invalidate(dentry);
3985                 btrfs_prune_dentries(dest);
3986                 ASSERT(dest->send_in_progress == 0);
3987
3988                 /* the last ref */
3989                 if (dest->ino_cache_inode) {
3990                         iput(dest->ino_cache_inode);
3991                         dest->ino_cache_inode = NULL;
3992                 }
3993         }
3994
3995         return err;
3996 }
3997
3998 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3999 {
4000         struct inode *inode = d_inode(dentry);
4001         int err = 0;
4002         struct btrfs_root *root = BTRFS_I(dir)->root;
4003         struct btrfs_trans_handle *trans;
4004         u64 last_unlink_trans;
4005
4006         if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4007                 return -ENOTEMPTY;
4008         if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4009                 return btrfs_delete_subvolume(dir, dentry);
4010
4011         trans = __unlink_start_trans(dir);
4012         if (IS_ERR(trans))
4013                 return PTR_ERR(trans);
4014
4015         if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4016                 err = btrfs_unlink_subvol(trans, dir, dentry);
4017                 goto out;
4018         }
4019
4020         err = btrfs_orphan_add(trans, BTRFS_I(inode));
4021         if (err)
4022                 goto out;
4023
4024         last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4025
4026         /* now the directory is empty */
4027         err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4028                         BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4029                         dentry->d_name.len);
4030         if (!err) {
4031                 btrfs_i_size_write(BTRFS_I(inode), 0);
4032                 /*
4033                  * Propagate the last_unlink_trans value of the deleted dir to
4034                  * its parent directory. This is to prevent an unrecoverable
4035                  * log tree in the case we do something like this:
4036                  * 1) create dir foo
4037                  * 2) create snapshot under dir foo
4038                  * 3) delete the snapshot
4039                  * 4) rmdir foo
4040                  * 5) mkdir foo
4041                  * 6) fsync foo or some file inside foo
4042                  */
4043                 if (last_unlink_trans >= trans->transid)
4044                         BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4045         }
4046 out:
4047         btrfs_end_transaction(trans);
4048         btrfs_btree_balance_dirty(root->fs_info);
4049
4050         return err;
4051 }
4052
4053 /*
4054  * Return this if we need to call truncate_block for the last bit of the
4055  * truncate.
4056  */
4057 #define NEED_TRUNCATE_BLOCK 1
4058
4059 /*
4060  * this can truncate away extent items, csum items and directory items.
4061  * It starts at a high offset and removes keys until it can't find
4062  * any higher than new_size
4063  *
4064  * csum items that cross the new i_size are truncated to the new size
4065  * as well.
4066  *
4067  * min_type is the minimum key type to truncate down to.  If set to 0, this
4068  * will kill all the items on this inode, including the INODE_ITEM_KEY.
4069  */
4070 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4071                                struct btrfs_root *root,
4072                                struct inode *inode,
4073                                u64 new_size, u32 min_type)
4074 {
4075         struct btrfs_fs_info *fs_info = root->fs_info;
4076         struct btrfs_path *path;
4077         struct extent_buffer *leaf;
4078         struct btrfs_file_extent_item *fi;
4079         struct btrfs_key key;
4080         struct btrfs_key found_key;
4081         u64 extent_start = 0;
4082         u64 extent_num_bytes = 0;
4083         u64 extent_offset = 0;
4084         u64 item_end = 0;
4085         u64 last_size = new_size;
4086         u32 found_type = (u8)-1;
4087         int found_extent;
4088         int del_item;
4089         int pending_del_nr = 0;
4090         int pending_del_slot = 0;
4091         int extent_type = -1;
4092         int ret;
4093         u64 ino = btrfs_ino(BTRFS_I(inode));
4094         u64 bytes_deleted = 0;
4095         bool be_nice = false;
4096         bool should_throttle = false;
4097         const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4098         struct extent_state *cached_state = NULL;
4099
4100         BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4101
4102         /*
4103          * For non-free space inodes and non-shareable roots, we want to back
4104          * off from time to time.  This means all inodes in subvolume roots,
4105          * reloc roots, and data reloc roots.
4106          */
4107         if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4108             test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4109                 be_nice = true;
4110
4111         path = btrfs_alloc_path();
4112         if (!path)
4113                 return -ENOMEM;
4114         path->reada = READA_BACK;
4115
4116         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4117                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4118                                  &cached_state);
4119
4120                 /*
4121                  * We want to drop from the next block forward in case this
4122                  * new size is not block aligned since we will be keeping the
4123                  * last block of the extent just the way it is.
4124                  */
4125                 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4126                                         fs_info->sectorsize),
4127                                         (u64)-1, 0);
4128         }
4129
4130         /*
4131          * This function is also used to drop the items in the log tree before
4132          * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4133          * it is used to drop the logged items. So we shouldn't kill the delayed
4134          * items.
4135          */
4136         if (min_type == 0 && root == BTRFS_I(inode)->root)
4137                 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4138
4139         key.objectid = ino;
4140         key.offset = (u64)-1;
4141         key.type = (u8)-1;
4142
4143 search_again:
4144         /*
4145          * with a 16K leaf size and 128MB extents, you can actually queue
4146          * up a huge file in a single leaf.  Most of the time that
4147          * bytes_deleted is > 0, it will be huge by the time we get here
4148          */
4149         if (be_nice && bytes_deleted > SZ_32M &&
4150             btrfs_should_end_transaction(trans)) {
4151                 ret = -EAGAIN;
4152                 goto out;
4153         }
4154
4155         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4156         if (ret < 0)
4157                 goto out;
4158
4159         if (ret > 0) {
4160                 ret = 0;
4161                 /* there are no items in the tree for us to truncate, we're
4162                  * done
4163                  */
4164                 if (path->slots[0] == 0)
4165                         goto out;
4166                 path->slots[0]--;
4167         }
4168
4169         while (1) {
4170                 u64 clear_start = 0, clear_len = 0;
4171
4172                 fi = NULL;
4173                 leaf = path->nodes[0];
4174                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4175                 found_type = found_key.type;
4176
4177                 if (found_key.objectid != ino)
4178                         break;
4179
4180                 if (found_type < min_type)
4181                         break;
4182
4183                 item_end = found_key.offset;
4184                 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4185                         fi = btrfs_item_ptr(leaf, path->slots[0],
4186                                             struct btrfs_file_extent_item);
4187                         extent_type = btrfs_file_extent_type(leaf, fi);
4188                         if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4189                                 item_end +=
4190                                     btrfs_file_extent_num_bytes(leaf, fi);
4191
4192                                 trace_btrfs_truncate_show_fi_regular(
4193                                         BTRFS_I(inode), leaf, fi,
4194                                         found_key.offset);
4195                         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4196                                 item_end += btrfs_file_extent_ram_bytes(leaf,
4197                                                                         fi);
4198
4199                                 trace_btrfs_truncate_show_fi_inline(
4200                                         BTRFS_I(inode), leaf, fi, path->slots[0],
4201                                         found_key.offset);
4202                         }
4203                         item_end--;
4204                 }
4205                 if (found_type > min_type) {
4206                         del_item = 1;
4207                 } else {
4208                         if (item_end < new_size)
4209                                 break;
4210                         if (found_key.offset >= new_size)
4211                                 del_item = 1;
4212                         else
4213                                 del_item = 0;
4214                 }
4215                 found_extent = 0;
4216                 /* FIXME, shrink the extent if the ref count is only 1 */
4217                 if (found_type != BTRFS_EXTENT_DATA_KEY)
4218                         goto delete;
4219
4220                 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4221                         u64 num_dec;
4222
4223                         clear_start = found_key.offset;
4224                         extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4225                         if (!del_item) {
4226                                 u64 orig_num_bytes =
4227                                         btrfs_file_extent_num_bytes(leaf, fi);
4228                                 extent_num_bytes = ALIGN(new_size -
4229                                                 found_key.offset,
4230                                                 fs_info->sectorsize);
4231                                 clear_start = ALIGN(new_size, fs_info->sectorsize);
4232                                 btrfs_set_file_extent_num_bytes(leaf, fi,
4233                                                          extent_num_bytes);
4234                                 num_dec = (orig_num_bytes -
4235                                            extent_num_bytes);
4236                                 if (test_bit(BTRFS_ROOT_SHAREABLE,
4237                                              &root->state) &&
4238                                     extent_start != 0)
4239                                         inode_sub_bytes(inode, num_dec);
4240                                 btrfs_mark_buffer_dirty(leaf);
4241                         } else {
4242                                 extent_num_bytes =
4243                                         btrfs_file_extent_disk_num_bytes(leaf,
4244                                                                          fi);
4245                                 extent_offset = found_key.offset -
4246                                         btrfs_file_extent_offset(leaf, fi);
4247
4248                                 /* FIXME blocksize != 4096 */
4249                                 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4250                                 if (extent_start != 0) {
4251                                         found_extent = 1;
4252                                         if (test_bit(BTRFS_ROOT_SHAREABLE,
4253                                                      &root->state))
4254                                                 inode_sub_bytes(inode, num_dec);
4255                                 }
4256                         }
4257                         clear_len = num_dec;
4258                 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4259                         /*
4260                          * we can't truncate inline items that have had
4261                          * special encodings
4262                          */
4263                         if (!del_item &&
4264                             btrfs_file_extent_encryption(leaf, fi) == 0 &&
4265                             btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4266                             btrfs_file_extent_compression(leaf, fi) == 0) {
4267                                 u32 size = (u32)(new_size - found_key.offset);
4268
4269                                 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4270                                 size = btrfs_file_extent_calc_inline_size(size);
4271                                 btrfs_truncate_item(path, size, 1);
4272                         } else if (!del_item) {
4273                                 /*
4274                                  * We have to bail so the last_size is set to
4275                                  * just before this extent.
4276                                  */
4277                                 ret = NEED_TRUNCATE_BLOCK;
4278                                 break;
4279                         } else {
4280                                 /*
4281                                  * Inline extents are special, we just treat
4282                                  * them as a full sector worth in the file
4283                                  * extent tree just for simplicity sake.
4284                                  */
4285                                 clear_len = fs_info->sectorsize;
4286                         }
4287
4288                         if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
4289                                 inode_sub_bytes(inode, item_end + 1 - new_size);
4290                 }
4291 delete:
4292                 /*
4293                  * We use btrfs_truncate_inode_items() to clean up log trees for
4294                  * multiple fsyncs, and in this case we don't want to clear the
4295                  * file extent range because it's just the log.
4296                  */
4297                 if (root == BTRFS_I(inode)->root) {
4298                         ret = btrfs_inode_clear_file_extent_range(BTRFS_I(inode),
4299                                                   clear_start, clear_len);
4300                         if (ret) {
4301                                 btrfs_abort_transaction(trans, ret);
4302                                 break;
4303                         }
4304                 }
4305
4306                 if (del_item)
4307                         last_size = found_key.offset;
4308                 else
4309                         last_size = new_size;
4310                 if (del_item) {
4311                         if (!pending_del_nr) {
4312                                 /* no pending yet, add ourselves */
4313                                 pending_del_slot = path->slots[0];
4314                                 pending_del_nr = 1;
4315                         } else if (pending_del_nr &&
4316                                    path->slots[0] + 1 == pending_del_slot) {
4317                                 /* hop on the pending chunk */
4318                                 pending_del_nr++;
4319                                 pending_del_slot = path->slots[0];
4320                         } else {
4321                                 BUG();
4322                         }
4323                 } else {
4324                         break;
4325                 }
4326                 should_throttle = false;
4327
4328                 if (found_extent &&
4329                     root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4330                         struct btrfs_ref ref = { 0 };
4331
4332                         bytes_deleted += extent_num_bytes;
4333
4334                         btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4335                                         extent_start, extent_num_bytes, 0);
4336                         ref.real_root = root->root_key.objectid;
4337                         btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4338                                         ino, extent_offset);
4339                         ret = btrfs_free_extent(trans, &ref);
4340                         if (ret) {
4341                                 btrfs_abort_transaction(trans, ret);
4342                                 break;
4343                         }
4344                         if (be_nice) {
4345                                 if (btrfs_should_throttle_delayed_refs(trans))
4346                                         should_throttle = true;
4347                         }
4348                 }
4349
4350                 if (found_type == BTRFS_INODE_ITEM_KEY)
4351                         break;
4352
4353                 if (path->slots[0] == 0 ||
4354                     path->slots[0] != pending_del_slot ||
4355                     should_throttle) {
4356                         if (pending_del_nr) {
4357                                 ret = btrfs_del_items(trans, root, path,
4358                                                 pending_del_slot,
4359                                                 pending_del_nr);
4360                                 if (ret) {
4361                                         btrfs_abort_transaction(trans, ret);
4362                                         break;
4363                                 }
4364                                 pending_del_nr = 0;
4365                         }
4366                         btrfs_release_path(path);
4367
4368                         /*
4369                          * We can generate a lot of delayed refs, so we need to
4370                          * throttle every once and a while and make sure we're
4371                          * adding enough space to keep up with the work we are
4372                          * generating.  Since we hold a transaction here we
4373                          * can't flush, and we don't want to FLUSH_LIMIT because
4374                          * we could have generated too many delayed refs to
4375                          * actually allocate, so just bail if we're short and
4376                          * let the normal reservation dance happen higher up.
4377                          */
4378                         if (should_throttle) {
4379                                 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4380                                                         BTRFS_RESERVE_NO_FLUSH);
4381                                 if (ret) {
4382                                         ret = -EAGAIN;
4383                                         break;
4384                                 }
4385                         }
4386                         goto search_again;
4387                 } else {
4388                         path->slots[0]--;
4389                 }
4390         }
4391 out:
4392         if (ret >= 0 && pending_del_nr) {
4393                 int err;
4394
4395                 err = btrfs_del_items(trans, root, path, pending_del_slot,
4396                                       pending_del_nr);
4397                 if (err) {
4398                         btrfs_abort_transaction(trans, err);
4399                         ret = err;
4400                 }
4401         }
4402         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4403                 ASSERT(last_size >= new_size);
4404                 if (!ret && last_size > new_size)
4405                         last_size = new_size;
4406                 btrfs_inode_safe_disk_i_size_write(inode, last_size);
4407                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4408                                      (u64)-1, &cached_state);
4409         }
4410
4411         btrfs_free_path(path);
4412         return ret;
4413 }
4414
4415 /*
4416  * btrfs_truncate_block - read, zero a chunk and write a block
4417  * @inode - inode that we're zeroing
4418  * @from - the offset to start zeroing
4419  * @len - the length to zero, 0 to zero the entire range respective to the
4420  *      offset
4421  * @front - zero up to the offset instead of from the offset on
4422  *
4423  * This will find the block for the "from" offset and cow the block and zero the
4424  * part we want to zero.  This is used with truncate and hole punching.
4425  */
4426 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4427                         int front)
4428 {
4429         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4430         struct address_space *mapping = inode->i_mapping;
4431         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4432         struct btrfs_ordered_extent *ordered;
4433         struct extent_state *cached_state = NULL;
4434         struct extent_changeset *data_reserved = NULL;
4435         char *kaddr;
4436         u32 blocksize = fs_info->sectorsize;
4437         pgoff_t index = from >> PAGE_SHIFT;
4438         unsigned offset = from & (blocksize - 1);
4439         struct page *page;
4440         gfp_t mask = btrfs_alloc_write_mask(mapping);
4441         int ret = 0;
4442         u64 block_start;
4443         u64 block_end;
4444
4445         if (IS_ALIGNED(offset, blocksize) &&
4446             (!len || IS_ALIGNED(len, blocksize)))
4447                 goto out;
4448
4449         block_start = round_down(from, blocksize);
4450         block_end = block_start + blocksize - 1;
4451
4452         ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4453                                            block_start, blocksize);
4454         if (ret)
4455                 goto out;
4456
4457 again:
4458         page = find_or_create_page(mapping, index, mask);
4459         if (!page) {
4460                 btrfs_delalloc_release_space(inode, data_reserved,
4461                                              block_start, blocksize, true);
4462                 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4463                 ret = -ENOMEM;
4464                 goto out;
4465         }
4466
4467         if (!PageUptodate(page)) {
4468                 ret = btrfs_readpage(NULL, page);
4469                 lock_page(page);
4470                 if (page->mapping != mapping) {
4471                         unlock_page(page);
4472                         put_page(page);
4473                         goto again;
4474                 }
4475                 if (!PageUptodate(page)) {
4476                         ret = -EIO;
4477                         goto out_unlock;
4478                 }
4479         }
4480         wait_on_page_writeback(page);
4481
4482         lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4483         set_page_extent_mapped(page);
4484
4485         ordered = btrfs_lookup_ordered_extent(inode, block_start);
4486         if (ordered) {
4487                 unlock_extent_cached(io_tree, block_start, block_end,
4488                                      &cached_state);
4489                 unlock_page(page);
4490                 put_page(page);
4491                 btrfs_start_ordered_extent(inode, ordered, 1);
4492                 btrfs_put_ordered_extent(ordered);
4493                 goto again;
4494         }
4495
4496         clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4497                          EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4498                          0, 0, &cached_state);
4499
4500         ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4501                                         &cached_state);
4502         if (ret) {
4503                 unlock_extent_cached(io_tree, block_start, block_end,
4504                                      &cached_state);
4505                 goto out_unlock;
4506         }
4507
4508         if (offset != blocksize) {
4509                 if (!len)
4510                         len = blocksize - offset;
4511                 kaddr = kmap(page);
4512                 if (front)
4513                         memset(kaddr + (block_start - page_offset(page)),
4514                                 0, offset);
4515                 else
4516                         memset(kaddr + (block_start - page_offset(page)) +  offset,
4517                                 0, len);
4518                 flush_dcache_page(page);
4519                 kunmap(page);
4520         }
4521         ClearPageChecked(page);
4522         set_page_dirty(page);
4523         unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4524
4525 out_unlock:
4526         if (ret)
4527                 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4528                                              blocksize, true);
4529         btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4530         unlock_page(page);
4531         put_page(page);
4532 out:
4533         extent_changeset_free(data_reserved);
4534         return ret;
4535 }
4536
4537 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4538                              u64 offset, u64 len)
4539 {
4540         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4541         struct btrfs_trans_handle *trans;
4542         int ret;
4543
4544         /*
4545          * Still need to make sure the inode looks like it's been updated so
4546          * that any holes get logged if we fsync.
4547          */
4548         if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4549                 BTRFS_I(inode)->last_trans = fs_info->generation;
4550                 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4551                 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4552                 return 0;
4553         }
4554
4555         /*
4556          * 1 - for the one we're dropping
4557          * 1 - for the one we're adding
4558          * 1 - for updating the inode.
4559          */
4560         trans = btrfs_start_transaction(root, 3);
4561         if (IS_ERR(trans))
4562                 return PTR_ERR(trans);
4563
4564         ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4565         if (ret) {
4566                 btrfs_abort_transaction(trans, ret);
4567                 btrfs_end_transaction(trans);
4568                 return ret;
4569         }
4570
4571         ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4572                         offset, 0, 0, len, 0, len, 0, 0, 0);
4573         if (ret)
4574                 btrfs_abort_transaction(trans, ret);
4575         else
4576                 btrfs_update_inode(trans, root, inode);
4577         btrfs_end_transaction(trans);
4578         return ret;
4579 }
4580
4581 /*
4582  * This function puts in dummy file extents for the area we're creating a hole
4583  * for.  So if we are truncating this file to a larger size we need to insert
4584  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4585  * the range between oldsize and size
4586  */
4587 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4588 {
4589         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4590         struct btrfs_root *root = BTRFS_I(inode)->root;
4591         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4592         struct extent_map *em = NULL;
4593         struct extent_state *cached_state = NULL;
4594         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4595         u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4596         u64 block_end = ALIGN(size, fs_info->sectorsize);
4597         u64 last_byte;
4598         u64 cur_offset;
4599         u64 hole_size;
4600         int err = 0;
4601
4602         /*
4603          * If our size started in the middle of a block we need to zero out the
4604          * rest of the block before we expand the i_size, otherwise we could
4605          * expose stale data.
4606          */
4607         err = btrfs_truncate_block(inode, oldsize, 0, 0);
4608         if (err)
4609                 return err;
4610
4611         if (size <= hole_start)
4612                 return 0;
4613
4614         btrfs_lock_and_flush_ordered_range(BTRFS_I(inode), hole_start,
4615                                            block_end - 1, &cached_state);
4616         cur_offset = hole_start;
4617         while (1) {
4618                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4619                                       block_end - cur_offset);
4620                 if (IS_ERR(em)) {
4621                         err = PTR_ERR(em);
4622                         em = NULL;
4623                         break;
4624                 }
4625                 last_byte = min(extent_map_end(em), block_end);
4626                 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4627                 hole_size = last_byte - cur_offset;
4628
4629                 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4630                         struct extent_map *hole_em;
4631
4632                         err = maybe_insert_hole(root, inode, cur_offset,
4633                                                 hole_size);
4634                         if (err)
4635                                 break;
4636
4637                         err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4638                                                         cur_offset, hole_size);
4639                         if (err)
4640                                 break;
4641
4642                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4643                                                 cur_offset + hole_size - 1, 0);
4644                         hole_em = alloc_extent_map();
4645                         if (!hole_em) {
4646                                 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4647                                         &BTRFS_I(inode)->runtime_flags);
4648                                 goto next;
4649                         }
4650                         hole_em->start = cur_offset;
4651                         hole_em->len = hole_size;
4652                         hole_em->orig_start = cur_offset;
4653
4654                         hole_em->block_start = EXTENT_MAP_HOLE;
4655                         hole_em->block_len = 0;
4656                         hole_em->orig_block_len = 0;
4657                         hole_em->ram_bytes = hole_size;
4658                         hole_em->compress_type = BTRFS_COMPRESS_NONE;
4659                         hole_em->generation = fs_info->generation;
4660
4661                         while (1) {
4662                                 write_lock(&em_tree->lock);
4663                                 err = add_extent_mapping(em_tree, hole_em, 1);
4664                                 write_unlock(&em_tree->lock);
4665                                 if (err != -EEXIST)
4666                                         break;
4667                                 btrfs_drop_extent_cache(BTRFS_I(inode),
4668                                                         cur_offset,
4669                                                         cur_offset +
4670                                                         hole_size - 1, 0);
4671                         }
4672                         free_extent_map(hole_em);
4673                 } else {
4674                         err = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
4675                                                         cur_offset, hole_size);
4676                         if (err)
4677                                 break;
4678                 }
4679 next:
4680                 free_extent_map(em);
4681                 em = NULL;
4682                 cur_offset = last_byte;
4683                 if (cur_offset >= block_end)
4684                         break;
4685         }
4686         free_extent_map(em);
4687         unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4688         return err;
4689 }
4690
4691 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4692 {
4693         struct btrfs_root *root = BTRFS_I(inode)->root;
4694         struct btrfs_trans_handle *trans;
4695         loff_t oldsize = i_size_read(inode);
4696         loff_t newsize = attr->ia_size;
4697         int mask = attr->ia_valid;
4698         int ret;
4699
4700         /*
4701          * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4702          * special case where we need to update the times despite not having
4703          * these flags set.  For all other operations the VFS set these flags
4704          * explicitly if it wants a timestamp update.
4705          */
4706         if (newsize != oldsize) {
4707                 inode_inc_iversion(inode);
4708                 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4709                         inode->i_ctime = inode->i_mtime =
4710                                 current_time(inode);
4711         }
4712
4713         if (newsize > oldsize) {
4714                 /*
4715                  * Don't do an expanding truncate while snapshotting is ongoing.
4716                  * This is to ensure the snapshot captures a fully consistent
4717                  * state of this file - if the snapshot captures this expanding
4718                  * truncation, it must capture all writes that happened before
4719                  * this truncation.
4720                  */
4721                 btrfs_drew_write_lock(&root->snapshot_lock);
4722                 ret = btrfs_cont_expand(inode, oldsize, newsize);
4723                 if (ret) {
4724                         btrfs_drew_write_unlock(&root->snapshot_lock);
4725                         return ret;
4726                 }
4727
4728                 trans = btrfs_start_transaction(root, 1);
4729                 if (IS_ERR(trans)) {
4730                         btrfs_drew_write_unlock(&root->snapshot_lock);
4731                         return PTR_ERR(trans);
4732                 }
4733
4734                 i_size_write(inode, newsize);
4735                 btrfs_inode_safe_disk_i_size_write(inode, 0);
4736                 pagecache_isize_extended(inode, oldsize, newsize);
4737                 ret = btrfs_update_inode(trans, root, inode);
4738                 btrfs_drew_write_unlock(&root->snapshot_lock);
4739                 btrfs_end_transaction(trans);
4740         } else {
4741
4742                 /*
4743                  * We're truncating a file that used to have good data down to
4744                  * zero. Make sure it gets into the ordered flush list so that
4745                  * any new writes get down to disk quickly.
4746                  */
4747                 if (newsize == 0)
4748                         set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4749                                 &BTRFS_I(inode)->runtime_flags);
4750
4751                 truncate_setsize(inode, newsize);
4752
4753                 /* Disable nonlocked read DIO to avoid the endless truncate */
4754                 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4755                 inode_dio_wait(inode);
4756                 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4757
4758                 ret = btrfs_truncate(inode, newsize == oldsize);
4759                 if (ret && inode->i_nlink) {
4760                         int err;
4761
4762                         /*
4763                          * Truncate failed, so fix up the in-memory size. We
4764                          * adjusted disk_i_size down as we removed extents, so
4765                          * wait for disk_i_size to be stable and then update the
4766                          * in-memory size to match.
4767                          */
4768                         err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4769                         if (err)
4770                                 return err;
4771                         i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4772                 }
4773         }
4774
4775         return ret;
4776 }
4777
4778 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4779 {
4780         struct inode *inode = d_inode(dentry);
4781         struct btrfs_root *root = BTRFS_I(inode)->root;
4782         int err;
4783
4784         if (btrfs_root_readonly(root))
4785                 return -EROFS;
4786
4787         err = setattr_prepare(dentry, attr);
4788         if (err)
4789                 return err;
4790
4791         if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4792                 err = btrfs_setsize(inode, attr);
4793                 if (err)
4794                         return err;
4795         }
4796
4797         if (attr->ia_valid) {
4798                 setattr_copy(inode, attr);
4799                 inode_inc_iversion(inode);
4800                 err = btrfs_dirty_inode(inode);
4801
4802                 if (!err && attr->ia_valid & ATTR_MODE)
4803                         err = posix_acl_chmod(inode, inode->i_mode);
4804         }
4805
4806         return err;
4807 }
4808
4809 /*
4810  * While truncating the inode pages during eviction, we get the VFS calling
4811  * btrfs_invalidatepage() against each page of the inode. This is slow because
4812  * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4813  * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4814  * extent_state structures over and over, wasting lots of time.
4815  *
4816  * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4817  * those expensive operations on a per page basis and do only the ordered io
4818  * finishing, while we release here the extent_map and extent_state structures,
4819  * without the excessive merging and splitting.
4820  */
4821 static void evict_inode_truncate_pages(struct inode *inode)
4822 {
4823         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4824         struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4825         struct rb_node *node;
4826
4827         ASSERT(inode->i_state & I_FREEING);
4828         truncate_inode_pages_final(&inode->i_data);
4829
4830         write_lock(&map_tree->lock);
4831         while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4832                 struct extent_map *em;
4833
4834                 node = rb_first_cached(&map_tree->map);
4835                 em = rb_entry(node, struct extent_map, rb_node);
4836                 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4837                 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4838                 remove_extent_mapping(map_tree, em);
4839                 free_extent_map(em);
4840                 if (need_resched()) {
4841                         write_unlock(&map_tree->lock);
4842                         cond_resched();
4843                         write_lock(&map_tree->lock);
4844                 }
4845         }
4846         write_unlock(&map_tree->lock);
4847
4848         /*
4849          * Keep looping until we have no more ranges in the io tree.
4850          * We can have ongoing bios started by readpages (called from readahead)
4851          * that have their endio callback (extent_io.c:end_bio_extent_readpage)
4852          * still in progress (unlocked the pages in the bio but did not yet
4853          * unlocked the ranges in the io tree). Therefore this means some
4854          * ranges can still be locked and eviction started because before
4855          * submitting those bios, which are executed by a separate task (work
4856          * queue kthread), inode references (inode->i_count) were not taken
4857          * (which would be dropped in the end io callback of each bio).
4858          * Therefore here we effectively end up waiting for those bios and
4859          * anyone else holding locked ranges without having bumped the inode's
4860          * reference count - if we don't do it, when they access the inode's
4861          * io_tree to unlock a range it may be too late, leading to an
4862          * use-after-free issue.
4863          */
4864         spin_lock(&io_tree->lock);
4865         while (!RB_EMPTY_ROOT(&io_tree->state)) {
4866                 struct extent_state *state;
4867                 struct extent_state *cached_state = NULL;
4868                 u64 start;
4869                 u64 end;
4870                 unsigned state_flags;
4871
4872                 node = rb_first(&io_tree->state);
4873                 state = rb_entry(node, struct extent_state, rb_node);
4874                 start = state->start;
4875                 end = state->end;
4876                 state_flags = state->state;
4877                 spin_unlock(&io_tree->lock);
4878
4879                 lock_extent_bits(io_tree, start, end, &cached_state);
4880
4881                 /*
4882                  * If still has DELALLOC flag, the extent didn't reach disk,
4883                  * and its reserved space won't be freed by delayed_ref.
4884                  * So we need to free its reserved space here.
4885                  * (Refer to comment in btrfs_invalidatepage, case 2)
4886                  *
4887                  * Note, end is the bytenr of last byte, so we need + 1 here.
4888                  */
4889                 if (state_flags & EXTENT_DELALLOC)
4890                         btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4891
4892                 clear_extent_bit(io_tree, start, end,
4893                                  EXTENT_LOCKED | EXTENT_DELALLOC |
4894                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4895                                  &cached_state);
4896
4897                 cond_resched();
4898                 spin_lock(&io_tree->lock);
4899         }
4900         spin_unlock(&io_tree->lock);
4901 }
4902
4903 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4904                                                         struct btrfs_block_rsv *rsv)
4905 {
4906         struct btrfs_fs_info *fs_info = root->fs_info;
4907         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4908         struct btrfs_trans_handle *trans;
4909         u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4910         int ret;
4911
4912         /*
4913          * Eviction should be taking place at some place safe because of our
4914          * delayed iputs.  However the normal flushing code will run delayed
4915          * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4916          *
4917          * We reserve the delayed_refs_extra here again because we can't use
4918          * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4919          * above.  We reserve our extra bit here because we generate a ton of
4920          * delayed refs activity by truncating.
4921          *
4922          * If we cannot make our reservation we'll attempt to steal from the
4923          * global reserve, because we really want to be able to free up space.
4924          */
4925         ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4926                                      BTRFS_RESERVE_FLUSH_EVICT);
4927         if (ret) {
4928                 /*
4929                  * Try to steal from the global reserve if there is space for
4930                  * it.
4931                  */
4932                 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4933                     btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4934                         btrfs_warn(fs_info,
4935                                    "could not allocate space for delete; will truncate on mount");
4936                         return ERR_PTR(-ENOSPC);
4937                 }
4938                 delayed_refs_extra = 0;
4939         }
4940
4941         trans = btrfs_join_transaction(root);
4942         if (IS_ERR(trans))
4943                 return trans;
4944
4945         if (delayed_refs_extra) {
4946                 trans->block_rsv = &fs_info->trans_block_rsv;
4947                 trans->bytes_reserved = delayed_refs_extra;
4948                 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
4949                                         delayed_refs_extra, 1);
4950         }
4951         return trans;
4952 }
4953
4954 void btrfs_evict_inode(struct inode *inode)
4955 {
4956         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4957         struct btrfs_trans_handle *trans;
4958         struct btrfs_root *root = BTRFS_I(inode)->root;
4959         struct btrfs_block_rsv *rsv;
4960         int ret;
4961
4962         trace_btrfs_inode_evict(inode);
4963
4964         if (!root) {
4965                 clear_inode(inode);
4966                 return;
4967         }
4968
4969         evict_inode_truncate_pages(inode);
4970
4971         if (inode->i_nlink &&
4972             ((btrfs_root_refs(&root->root_item) != 0 &&
4973               root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4974              btrfs_is_free_space_inode(BTRFS_I(inode))))
4975                 goto no_delete;
4976
4977         if (is_bad_inode(inode))
4978                 goto no_delete;
4979
4980         btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
4981
4982         if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
4983                 goto no_delete;
4984
4985         if (inode->i_nlink > 0) {
4986                 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4987                        root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4988                 goto no_delete;
4989         }
4990
4991         ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
4992         if (ret)
4993                 goto no_delete;
4994
4995         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
4996         if (!rsv)
4997                 goto no_delete;
4998         rsv->size = btrfs_calc_metadata_size(fs_info, 1);
4999         rsv->failfast = 1;
5000
5001         btrfs_i_size_write(BTRFS_I(inode), 0);
5002
5003         while (1) {
5004                 trans = evict_refill_and_join(root, rsv);
5005                 if (IS_ERR(trans))
5006                         goto free_rsv;
5007
5008                 trans->block_rsv = rsv;
5009
5010                 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5011                 trans->block_rsv = &fs_info->trans_block_rsv;
5012                 btrfs_end_transaction(trans);
5013                 btrfs_btree_balance_dirty(fs_info);
5014                 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5015                         goto free_rsv;
5016                 else if (!ret)
5017                         break;
5018         }
5019
5020         /*
5021          * Errors here aren't a big deal, it just means we leave orphan items in
5022          * the tree. They will be cleaned up on the next mount. If the inode
5023          * number gets reused, cleanup deletes the orphan item without doing
5024          * anything, and unlink reuses the existing orphan item.
5025          *
5026          * If it turns out that we are dropping too many of these, we might want
5027          * to add a mechanism for retrying these after a commit.
5028          */
5029         trans = evict_refill_and_join(root, rsv);
5030         if (!IS_ERR(trans)) {
5031                 trans->block_rsv = rsv;
5032                 btrfs_orphan_del(trans, BTRFS_I(inode));
5033                 trans->block_rsv = &fs_info->trans_block_rsv;
5034                 btrfs_end_transaction(trans);
5035         }
5036
5037         if (!(root == fs_info->tree_root ||
5038               root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5039                 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5040
5041 free_rsv:
5042         btrfs_free_block_rsv(fs_info, rsv);
5043 no_delete:
5044         /*
5045          * If we didn't successfully delete, the orphan item will still be in
5046          * the tree and we'll retry on the next mount. Again, we might also want
5047          * to retry these periodically in the future.
5048          */
5049         btrfs_remove_delayed_node(BTRFS_I(inode));
5050         clear_inode(inode);
5051 }
5052
5053 /*
5054  * Return the key found in the dir entry in the location pointer, fill @type
5055  * with BTRFS_FT_*, and return 0.
5056  *
5057  * If no dir entries were found, returns -ENOENT.
5058  * If found a corrupted location in dir entry, returns -EUCLEAN.
5059  */
5060 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5061                                struct btrfs_key *location, u8 *type)
5062 {
5063         const char *name = dentry->d_name.name;
5064         int namelen = dentry->d_name.len;
5065         struct btrfs_dir_item *di;
5066         struct btrfs_path *path;
5067         struct btrfs_root *root = BTRFS_I(dir)->root;
5068         int ret = 0;
5069
5070         path = btrfs_alloc_path();
5071         if (!path)
5072                 return -ENOMEM;
5073
5074         di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5075                         name, namelen, 0);
5076         if (IS_ERR_OR_NULL(di)) {
5077                 ret = di ? PTR_ERR(di) : -ENOENT;
5078                 goto out;
5079         }
5080
5081         btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5082         if (location->type != BTRFS_INODE_ITEM_KEY &&
5083             location->type != BTRFS_ROOT_ITEM_KEY) {
5084                 ret = -EUCLEAN;
5085                 btrfs_warn(root->fs_info,
5086 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5087                            __func__, name, btrfs_ino(BTRFS_I(dir)),
5088                            location->objectid, location->type, location->offset);
5089         }
5090         if (!ret)
5091                 *type = btrfs_dir_type(path->nodes[0], di);
5092 out:
5093         btrfs_free_path(path);
5094         return ret;
5095 }
5096
5097 /*
5098  * when we hit a tree root in a directory, the btrfs part of the inode
5099  * needs to be changed to reflect the root directory of the tree root.  This
5100  * is kind of like crossing a mount point.
5101  */
5102 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5103                                     struct inode *dir,
5104                                     struct dentry *dentry,
5105                                     struct btrfs_key *location,
5106                                     struct btrfs_root **sub_root)
5107 {
5108         struct btrfs_path *path;
5109         struct btrfs_root *new_root;
5110         struct btrfs_root_ref *ref;
5111         struct extent_buffer *leaf;
5112         struct btrfs_key key;
5113         int ret;
5114         int err = 0;
5115
5116         path = btrfs_alloc_path();
5117         if (!path) {
5118                 err = -ENOMEM;
5119                 goto out;
5120         }
5121
5122         err = -ENOENT;
5123         key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5124         key.type = BTRFS_ROOT_REF_KEY;
5125         key.offset = location->objectid;
5126
5127         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5128         if (ret) {
5129                 if (ret < 0)
5130                         err = ret;
5131                 goto out;
5132         }
5133
5134         leaf = path->nodes[0];
5135         ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5136         if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5137             btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5138                 goto out;
5139
5140         ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5141                                    (unsigned long)(ref + 1),
5142                                    dentry->d_name.len);
5143         if (ret)
5144                 goto out;
5145
5146         btrfs_release_path(path);
5147
5148         new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5149         if (IS_ERR(new_root)) {
5150                 err = PTR_ERR(new_root);
5151                 goto out;
5152         }
5153
5154         *sub_root = new_root;
5155         location->objectid = btrfs_root_dirid(&new_root->root_item);
5156         location->type = BTRFS_INODE_ITEM_KEY;
5157         location->offset = 0;
5158         err = 0;
5159 out:
5160         btrfs_free_path(path);
5161         return err;
5162 }
5163
5164 static void inode_tree_add(struct inode *inode)
5165 {
5166         struct btrfs_root *root = BTRFS_I(inode)->root;
5167         struct btrfs_inode *entry;
5168         struct rb_node **p;
5169         struct rb_node *parent;
5170         struct rb_node *new = &BTRFS_I(inode)->rb_node;
5171         u64 ino = btrfs_ino(BTRFS_I(inode));
5172
5173         if (inode_unhashed(inode))
5174                 return;
5175         parent = NULL;
5176         spin_lock(&root->inode_lock);
5177         p = &root->inode_tree.rb_node;
5178         while (*p) {
5179                 parent = *p;
5180                 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5181
5182                 if (ino < btrfs_ino(entry))
5183                         p = &parent->rb_left;
5184                 else if (ino > btrfs_ino(entry))
5185                         p = &parent->rb_right;
5186                 else {
5187                         WARN_ON(!(entry->vfs_inode.i_state &
5188                                   (I_WILL_FREE | I_FREEING)));
5189                         rb_replace_node(parent, new, &root->inode_tree);
5190                         RB_CLEAR_NODE(parent);
5191                         spin_unlock(&root->inode_lock);
5192                         return;
5193                 }
5194         }
5195         rb_link_node(new, parent, p);
5196         rb_insert_color(new, &root->inode_tree);
5197         spin_unlock(&root->inode_lock);
5198 }
5199
5200 static void inode_tree_del(struct inode *inode)
5201 {
5202         struct btrfs_root *root = BTRFS_I(inode)->root;
5203         int empty = 0;
5204
5205         spin_lock(&root->inode_lock);
5206         if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5207                 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5208                 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5209                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5210         }
5211         spin_unlock(&root->inode_lock);
5212
5213         if (empty && btrfs_root_refs(&root->root_item) == 0) {
5214                 spin_lock(&root->inode_lock);
5215                 empty = RB_EMPTY_ROOT(&root->inode_tree);
5216                 spin_unlock(&root->inode_lock);
5217                 if (empty)
5218                         btrfs_add_dead_root(root);
5219         }
5220 }
5221
5222
5223 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5224 {
5225         struct btrfs_iget_args *args = p;
5226
5227         inode->i_ino = args->ino;
5228         BTRFS_I(inode)->location.objectid = args->ino;
5229         BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
5230         BTRFS_I(inode)->location.offset = 0;
5231         BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5232         BUG_ON(args->root && !BTRFS_I(inode)->root);
5233         return 0;
5234 }
5235
5236 static int btrfs_find_actor(struct inode *inode, void *opaque)
5237 {
5238         struct btrfs_iget_args *args = opaque;
5239
5240         return args->ino == BTRFS_I(inode)->location.objectid &&
5241                 args->root == BTRFS_I(inode)->root;
5242 }
5243
5244 static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
5245                                        struct btrfs_root *root)
5246 {
5247         struct inode *inode;
5248         struct btrfs_iget_args args;
5249         unsigned long hashval = btrfs_inode_hash(ino, root);
5250
5251         args.ino = ino;
5252         args.root = root;
5253
5254         inode = iget5_locked(s, hashval, btrfs_find_actor,
5255                              btrfs_init_locked_inode,
5256                              (void *)&args);
5257         return inode;
5258 }
5259
5260 /*
5261  * Get an inode object given its inode number and corresponding root.
5262  * Path can be preallocated to prevent recursing back to iget through
5263  * allocator. NULL is also valid but may require an additional allocation
5264  * later.
5265  */
5266 struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
5267                               struct btrfs_root *root, struct btrfs_path *path)
5268 {
5269         struct inode *inode;
5270
5271         inode = btrfs_iget_locked(s, ino, root);
5272         if (!inode)
5273                 return ERR_PTR(-ENOMEM);
5274
5275         if (inode->i_state & I_NEW) {
5276                 int ret;
5277
5278                 ret = btrfs_read_locked_inode(inode, path);
5279                 if (!ret) {
5280                         inode_tree_add(inode);
5281                         unlock_new_inode(inode);
5282                 } else {
5283                         iget_failed(inode);
5284                         /*
5285                          * ret > 0 can come from btrfs_search_slot called by
5286                          * btrfs_read_locked_inode, this means the inode item
5287                          * was not found.
5288                          */
5289                         if (ret > 0)
5290                                 ret = -ENOENT;
5291                         inode = ERR_PTR(ret);
5292                 }
5293         }
5294
5295         return inode;
5296 }
5297
5298 struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
5299 {
5300         return btrfs_iget_path(s, ino, root, NULL);
5301 }
5302
5303 static struct inode *new_simple_dir(struct super_block *s,
5304                                     struct btrfs_key *key,
5305                                     struct btrfs_root *root)
5306 {
5307         struct inode *inode = new_inode(s);
5308
5309         if (!inode)
5310                 return ERR_PTR(-ENOMEM);
5311
5312         BTRFS_I(inode)->root = btrfs_grab_root(root);
5313         memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5314         set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5315
5316         inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5317         /*
5318          * We only need lookup, the rest is read-only and there's no inode
5319          * associated with the dentry
5320          */
5321         inode->i_op = &simple_dir_inode_operations;
5322         inode->i_opflags &= ~IOP_XATTR;
5323         inode->i_fop = &simple_dir_operations;
5324         inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5325         inode->i_mtime = current_time(inode);
5326         inode->i_atime = inode->i_mtime;
5327         inode->i_ctime = inode->i_mtime;
5328         BTRFS_I(inode)->i_otime = inode->i_mtime;
5329
5330         return inode;
5331 }
5332
5333 static inline u8 btrfs_inode_type(struct inode *inode)
5334 {
5335         /*
5336          * Compile-time asserts that generic FT_* types still match
5337          * BTRFS_FT_* types
5338          */
5339         BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5340         BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5341         BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5342         BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5343         BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5344         BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5345         BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5346         BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5347
5348         return fs_umode_to_ftype(inode->i_mode);
5349 }
5350
5351 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5352 {
5353         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5354         struct inode *inode;
5355         struct btrfs_root *root = BTRFS_I(dir)->root;
5356         struct btrfs_root *sub_root = root;
5357         struct btrfs_key location;
5358         u8 di_type = 0;
5359         int ret = 0;
5360
5361         if (dentry->d_name.len > BTRFS_NAME_LEN)
5362                 return ERR_PTR(-ENAMETOOLONG);
5363
5364         ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5365         if (ret < 0)
5366                 return ERR_PTR(ret);
5367
5368         if (location.type == BTRFS_INODE_ITEM_KEY) {
5369                 inode = btrfs_iget(dir->i_sb, location.objectid, root);
5370                 if (IS_ERR(inode))
5371                         return inode;
5372
5373                 /* Do extra check against inode mode with di_type */
5374                 if (btrfs_inode_type(inode) != di_type) {
5375                         btrfs_crit(fs_info,
5376 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5377                                   inode->i_mode, btrfs_inode_type(inode),
5378                                   di_type);
5379                         iput(inode);
5380                         return ERR_PTR(-EUCLEAN);
5381                 }
5382                 return inode;
5383         }
5384
5385         ret = fixup_tree_root_location(fs_info, dir, dentry,
5386                                        &location, &sub_root);
5387         if (ret < 0) {
5388                 if (ret != -ENOENT)
5389                         inode = ERR_PTR(ret);
5390                 else
5391                         inode = new_simple_dir(dir->i_sb, &location, sub_root);
5392         } else {
5393                 inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
5394         }
5395         if (root != sub_root)
5396                 btrfs_put_root(sub_root);
5397
5398         if (!IS_ERR(inode) && root != sub_root) {
5399                 down_read(&fs_info->cleanup_work_sem);
5400                 if (!sb_rdonly(inode->i_sb))
5401                         ret = btrfs_orphan_cleanup(sub_root);
5402                 up_read(&fs_info->cleanup_work_sem);
5403                 if (ret) {
5404                         iput(inode);
5405                         inode = ERR_PTR(ret);
5406                 }
5407         }
5408
5409         return inode;
5410 }
5411
5412 static int btrfs_dentry_delete(const struct dentry *dentry)
5413 {
5414         struct btrfs_root *root;
5415         struct inode *inode = d_inode(dentry);
5416
5417         if (!inode && !IS_ROOT(dentry))
5418                 inode = d_inode(dentry->d_parent);
5419
5420         if (inode) {
5421                 root = BTRFS_I(inode)->root;
5422                 if (btrfs_root_refs(&root->root_item) == 0)
5423                         return 1;
5424
5425                 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5426                         return 1;
5427         }
5428         return 0;
5429 }
5430
5431 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5432                                    unsigned int flags)
5433 {
5434         struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5435
5436         if (inode == ERR_PTR(-ENOENT))
5437                 inode = NULL;
5438         return d_splice_alias(inode, dentry);
5439 }
5440
5441 /*
5442  * All this infrastructure exists because dir_emit can fault, and we are holding
5443  * the tree lock when doing readdir.  For now just allocate a buffer and copy
5444  * our information into that, and then dir_emit from the buffer.  This is
5445  * similar to what NFS does, only we don't keep the buffer around in pagecache
5446  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
5447  * copy_to_user_inatomic so we don't have to worry about page faulting under the
5448  * tree lock.
5449  */
5450 static int btrfs_opendir(struct inode *inode, struct file *file)
5451 {
5452         struct btrfs_file_private *private;
5453
5454         private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5455         if (!private)
5456                 return -ENOMEM;
5457         private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5458         if (!private->filldir_buf) {
5459                 kfree(private);
5460                 return -ENOMEM;
5461         }
5462         file->private_data = private;
5463         return 0;
5464 }
5465
5466 struct dir_entry {
5467         u64 ino;
5468         u64 offset;
5469         unsigned type;
5470         int name_len;
5471 };
5472
5473 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5474 {
5475         while (entries--) {
5476                 struct dir_entry *entry = addr;
5477                 char *name = (char *)(entry + 1);
5478
5479                 ctx->pos = get_unaligned(&entry->offset);
5480                 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5481                                          get_unaligned(&entry->ino),
5482                                          get_unaligned(&entry->type)))
5483                         return 1;
5484                 addr += sizeof(struct dir_entry) +
5485                         get_unaligned(&entry->name_len);
5486                 ctx->pos++;
5487         }
5488         return 0;
5489 }
5490
5491 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5492 {
5493         struct inode *inode = file_inode(file);
5494         struct btrfs_root *root = BTRFS_I(inode)->root;
5495         struct btrfs_file_private *private = file->private_data;
5496         struct btrfs_dir_item *di;
5497         struct btrfs_key key;
5498         struct btrfs_key found_key;
5499         struct btrfs_path *path;
5500         void *addr;
5501         struct list_head ins_list;
5502         struct list_head del_list;
5503         int ret;
5504         struct extent_buffer *leaf;
5505         int slot;
5506         char *name_ptr;
5507         int name_len;
5508         int entries = 0;
5509         int total_len = 0;
5510         bool put = false;
5511         struct btrfs_key location;
5512
5513         if (!dir_emit_dots(file, ctx))
5514                 return 0;
5515
5516         path = btrfs_alloc_path();
5517         if (!path)
5518                 return -ENOMEM;
5519
5520         addr = private->filldir_buf;
5521         path->reada = READA_FORWARD;
5522
5523         INIT_LIST_HEAD(&ins_list);
5524         INIT_LIST_HEAD(&del_list);
5525         put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5526
5527 again:
5528         key.type = BTRFS_DIR_INDEX_KEY;
5529         key.offset = ctx->pos;
5530         key.objectid = btrfs_ino(BTRFS_I(inode));
5531
5532         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5533         if (ret < 0)
5534                 goto err;
5535
5536         while (1) {
5537                 struct dir_entry *entry;
5538
5539                 leaf = path->nodes[0];
5540                 slot = path->slots[0];
5541                 if (slot >= btrfs_header_nritems(leaf)) {
5542                         ret = btrfs_next_leaf(root, path);
5543                         if (ret < 0)
5544                                 goto err;
5545                         else if (ret > 0)
5546                                 break;
5547                         continue;
5548                 }
5549
5550                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5551
5552                 if (found_key.objectid != key.objectid)
5553                         break;
5554                 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5555                         break;
5556                 if (found_key.offset < ctx->pos)
5557                         goto next;
5558                 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5559                         goto next;
5560                 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5561                 name_len = btrfs_dir_name_len(leaf, di);
5562                 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5563                     PAGE_SIZE) {
5564                         btrfs_release_path(path);
5565                         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5566                         if (ret)
5567                                 goto nopos;
5568                         addr = private->filldir_buf;
5569                         entries = 0;
5570                         total_len = 0;
5571                         goto again;
5572                 }
5573
5574                 entry = addr;
5575                 put_unaligned(name_len, &entry->name_len);
5576                 name_ptr = (char *)(entry + 1);
5577                 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5578                                    name_len);
5579                 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5580                                 &entry->type);
5581                 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5582                 put_unaligned(location.objectid, &entry->ino);
5583                 put_unaligned(found_key.offset, &entry->offset);
5584                 entries++;
5585                 addr += sizeof(struct dir_entry) + name_len;
5586                 total_len += sizeof(struct dir_entry) + name_len;
5587 next:
5588                 path->slots[0]++;
5589         }
5590         btrfs_release_path(path);
5591
5592         ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5593         if (ret)
5594                 goto nopos;
5595
5596         ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5597         if (ret)
5598                 goto nopos;
5599
5600         /*
5601          * Stop new entries from being returned after we return the last
5602          * entry.
5603          *
5604          * New directory entries are assigned a strictly increasing
5605          * offset.  This means that new entries created during readdir
5606          * are *guaranteed* to be seen in the future by that readdir.
5607          * This has broken buggy programs which operate on names as
5608          * they're returned by readdir.  Until we re-use freed offsets
5609          * we have this hack to stop new entries from being returned
5610          * under the assumption that they'll never reach this huge
5611          * offset.
5612          *
5613          * This is being careful not to overflow 32bit loff_t unless the
5614          * last entry requires it because doing so has broken 32bit apps
5615          * in the past.
5616          */
5617         if (ctx->pos >= INT_MAX)
5618                 ctx->pos = LLONG_MAX;
5619         else
5620                 ctx->pos = INT_MAX;
5621 nopos:
5622         ret = 0;
5623 err:
5624         if (put)
5625                 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5626         btrfs_free_path(path);
5627         return ret;
5628 }
5629
5630 /*
5631  * This is somewhat expensive, updating the tree every time the
5632  * inode changes.  But, it is most likely to find the inode in cache.
5633  * FIXME, needs more benchmarking...there are no reasons other than performance
5634  * to keep or drop this code.
5635  */
5636 static int btrfs_dirty_inode(struct inode *inode)
5637 {
5638         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5639         struct btrfs_root *root = BTRFS_I(inode)->root;
5640         struct btrfs_trans_handle *trans;
5641         int ret;
5642
5643         if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5644                 return 0;
5645
5646         trans = btrfs_join_transaction(root);
5647         if (IS_ERR(trans))
5648                 return PTR_ERR(trans);
5649
5650         ret = btrfs_update_inode(trans, root, inode);
5651         if (ret && ret == -ENOSPC) {
5652                 /* whoops, lets try again with the full transaction */
5653                 btrfs_end_transaction(trans);
5654                 trans = btrfs_start_transaction(root, 1);
5655                 if (IS_ERR(trans))
5656                         return PTR_ERR(trans);
5657
5658                 ret = btrfs_update_inode(trans, root, inode);
5659         }
5660         btrfs_end_transaction(trans);
5661         if (BTRFS_I(inode)->delayed_node)
5662                 btrfs_balance_delayed_items(fs_info);
5663
5664         return ret;
5665 }
5666
5667 /*
5668  * This is a copy of file_update_time.  We need this so we can return error on
5669  * ENOSPC for updating the inode in the case of file write and mmap writes.
5670  */
5671 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5672                              int flags)
5673 {
5674         struct btrfs_root *root = BTRFS_I(inode)->root;
5675         bool dirty = flags & ~S_VERSION;
5676
5677         if (btrfs_root_readonly(root))
5678                 return -EROFS;
5679
5680         if (flags & S_VERSION)
5681                 dirty |= inode_maybe_inc_iversion(inode, dirty);
5682         if (flags & S_CTIME)
5683                 inode->i_ctime = *now;
5684         if (flags & S_MTIME)
5685                 inode->i_mtime = *now;
5686         if (flags & S_ATIME)
5687                 inode->i_atime = *now;
5688         return dirty ? btrfs_dirty_inode(inode) : 0;
5689 }
5690
5691 /*
5692  * find the highest existing sequence number in a directory
5693  * and then set the in-memory index_cnt variable to reflect
5694  * free sequence numbers
5695  */
5696 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5697 {
5698         struct btrfs_root *root = inode->root;
5699         struct btrfs_key key, found_key;
5700         struct btrfs_path *path;
5701         struct extent_buffer *leaf;
5702         int ret;
5703
5704         key.objectid = btrfs_ino(inode);
5705         key.type = BTRFS_DIR_INDEX_KEY;
5706         key.offset = (u64)-1;
5707
5708         path = btrfs_alloc_path();
5709         if (!path)
5710                 return -ENOMEM;
5711
5712         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5713         if (ret < 0)
5714                 goto out;
5715         /* FIXME: we should be able to handle this */
5716         if (ret == 0)
5717                 goto out;
5718         ret = 0;
5719
5720         /*
5721          * MAGIC NUMBER EXPLANATION:
5722          * since we search a directory based on f_pos we have to start at 2
5723          * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5724          * else has to start at 2
5725          */
5726         if (path->slots[0] == 0) {
5727                 inode->index_cnt = 2;
5728                 goto out;
5729         }
5730
5731         path->slots[0]--;
5732
5733         leaf = path->nodes[0];
5734         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5735
5736         if (found_key.objectid != btrfs_ino(inode) ||
5737             found_key.type != BTRFS_DIR_INDEX_KEY) {
5738                 inode->index_cnt = 2;
5739                 goto out;
5740         }
5741
5742         inode->index_cnt = found_key.offset + 1;
5743 out:
5744         btrfs_free_path(path);
5745         return ret;
5746 }
5747
5748 /*
5749  * helper to find a free sequence number in a given directory.  This current
5750  * code is very simple, later versions will do smarter things in the btree
5751  */
5752 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5753 {
5754         int ret = 0;
5755
5756         if (dir->index_cnt == (u64)-1) {
5757                 ret = btrfs_inode_delayed_dir_index_count(dir);
5758                 if (ret) {
5759                         ret = btrfs_set_inode_index_count(dir);
5760                         if (ret)
5761                                 return ret;
5762                 }
5763         }
5764
5765         *index = dir->index_cnt;
5766         dir->index_cnt++;
5767
5768         return ret;
5769 }
5770
5771 static int btrfs_insert_inode_locked(struct inode *inode)
5772 {
5773         struct btrfs_iget_args args;
5774
5775         args.ino = BTRFS_I(inode)->location.objectid;
5776         args.root = BTRFS_I(inode)->root;
5777
5778         return insert_inode_locked4(inode,
5779                    btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5780                    btrfs_find_actor, &args);
5781 }
5782
5783 /*
5784  * Inherit flags from the parent inode.
5785  *
5786  * Currently only the compression flags and the cow flags are inherited.
5787  */
5788 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5789 {
5790         unsigned int flags;
5791
5792         if (!dir)
5793                 return;
5794
5795         flags = BTRFS_I(dir)->flags;
5796
5797         if (flags & BTRFS_INODE_NOCOMPRESS) {
5798                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5799                 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5800         } else if (flags & BTRFS_INODE_COMPRESS) {
5801                 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5802                 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5803         }
5804
5805         if (flags & BTRFS_INODE_NODATACOW) {
5806                 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5807                 if (S_ISREG(inode->i_mode))
5808                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5809         }
5810
5811         btrfs_sync_inode_flags_to_i_flags(inode);
5812 }
5813
5814 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5815                                      struct btrfs_root *root,
5816                                      struct inode *dir,
5817                                      const char *name, int name_len,
5818                                      u64 ref_objectid, u64 objectid,
5819                                      umode_t mode, u64 *index)
5820 {
5821         struct btrfs_fs_info *fs_info = root->fs_info;
5822         struct inode *inode;
5823         struct btrfs_inode_item *inode_item;
5824         struct btrfs_key *location;
5825         struct btrfs_path *path;
5826         struct btrfs_inode_ref *ref;
5827         struct btrfs_key key[2];
5828         u32 sizes[2];
5829         int nitems = name ? 2 : 1;
5830         unsigned long ptr;
5831         unsigned int nofs_flag;
5832         int ret;
5833
5834         path = btrfs_alloc_path();
5835         if (!path)
5836                 return ERR_PTR(-ENOMEM);
5837
5838         nofs_flag = memalloc_nofs_save();
5839         inode = new_inode(fs_info->sb);
5840         memalloc_nofs_restore(nofs_flag);
5841         if (!inode) {
5842                 btrfs_free_path(path);
5843                 return ERR_PTR(-ENOMEM);
5844         }
5845
5846         /*
5847          * O_TMPFILE, set link count to 0, so that after this point,
5848          * we fill in an inode item with the correct link count.
5849          */
5850         if (!name)
5851                 set_nlink(inode, 0);
5852
5853         /*
5854          * we have to initialize this early, so we can reclaim the inode
5855          * number if we fail afterwards in this function.
5856          */
5857         inode->i_ino = objectid;
5858
5859         if (dir && name) {
5860                 trace_btrfs_inode_request(dir);
5861
5862                 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5863                 if (ret) {
5864                         btrfs_free_path(path);
5865                         iput(inode);
5866                         return ERR_PTR(ret);
5867                 }
5868         } else if (dir) {
5869                 *index = 0;
5870         }
5871         /*
5872          * index_cnt is ignored for everything but a dir,
5873          * btrfs_set_inode_index_count has an explanation for the magic
5874          * number
5875          */
5876         BTRFS_I(inode)->index_cnt = 2;
5877         BTRFS_I(inode)->dir_index = *index;
5878         BTRFS_I(inode)->root = btrfs_grab_root(root);
5879         BTRFS_I(inode)->generation = trans->transid;
5880         inode->i_generation = BTRFS_I(inode)->generation;
5881
5882         /*
5883          * We could have gotten an inode number from somebody who was fsynced
5884          * and then removed in this same transaction, so let's just set full
5885          * sync since it will be a full sync anyway and this will blow away the
5886          * old info in the log.
5887          */
5888         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5889
5890         key[0].objectid = objectid;
5891         key[0].type = BTRFS_INODE_ITEM_KEY;
5892         key[0].offset = 0;
5893
5894         sizes[0] = sizeof(struct btrfs_inode_item);
5895
5896         if (name) {
5897                 /*
5898                  * Start new inodes with an inode_ref. This is slightly more
5899                  * efficient for small numbers of hard links since they will
5900                  * be packed into one item. Extended refs will kick in if we
5901                  * add more hard links than can fit in the ref item.
5902                  */
5903                 key[1].objectid = objectid;
5904                 key[1].type = BTRFS_INODE_REF_KEY;
5905                 key[1].offset = ref_objectid;
5906
5907                 sizes[1] = name_len + sizeof(*ref);
5908         }
5909
5910         location = &BTRFS_I(inode)->location;
5911         location->objectid = objectid;
5912         location->offset = 0;
5913         location->type = BTRFS_INODE_ITEM_KEY;
5914
5915         ret = btrfs_insert_inode_locked(inode);
5916         if (ret < 0) {
5917                 iput(inode);
5918                 goto fail;
5919         }
5920
5921         path->leave_spinning = 1;
5922         ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5923         if (ret != 0)
5924                 goto fail_unlock;
5925
5926         inode_init_owner(inode, dir, mode);
5927         inode_set_bytes(inode, 0);
5928
5929         inode->i_mtime = current_time(inode);
5930         inode->i_atime = inode->i_mtime;
5931         inode->i_ctime = inode->i_mtime;
5932         BTRFS_I(inode)->i_otime = inode->i_mtime;
5933
5934         inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5935                                   struct btrfs_inode_item);
5936         memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5937                              sizeof(*inode_item));
5938         fill_inode_item(trans, path->nodes[0], inode_item, inode);
5939
5940         if (name) {
5941                 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5942                                      struct btrfs_inode_ref);
5943                 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5944                 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5945                 ptr = (unsigned long)(ref + 1);
5946                 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5947         }
5948
5949         btrfs_mark_buffer_dirty(path->nodes[0]);
5950         btrfs_free_path(path);
5951
5952         btrfs_inherit_iflags(inode, dir);
5953
5954         if (S_ISREG(mode)) {
5955                 if (btrfs_test_opt(fs_info, NODATASUM))
5956                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5957                 if (btrfs_test_opt(fs_info, NODATACOW))
5958                         BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5959                                 BTRFS_INODE_NODATASUM;
5960         }
5961
5962         inode_tree_add(inode);
5963
5964         trace_btrfs_inode_new(inode);
5965         btrfs_set_inode_last_trans(trans, inode);
5966
5967         btrfs_update_root_times(trans, root);
5968
5969         ret = btrfs_inode_inherit_props(trans, inode, dir);
5970         if (ret)
5971                 btrfs_err(fs_info,
5972                           "error inheriting props for ino %llu (root %llu): %d",
5973                         btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
5974
5975         return inode;
5976
5977 fail_unlock:
5978         discard_new_inode(inode);
5979 fail:
5980         if (dir && name)
5981                 BTRFS_I(dir)->index_cnt--;
5982         btrfs_free_path(path);
5983         return ERR_PTR(ret);
5984 }
5985
5986 /*
5987  * utility function to add 'inode' into 'parent_inode' with
5988  * a give name and a given sequence number.
5989  * if 'add_backref' is true, also insert a backref from the
5990  * inode to the parent directory.
5991  */
5992 int btrfs_add_link(struct btrfs_trans_handle *trans,
5993                    struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
5994                    const char *name, int name_len, int add_backref, u64 index)
5995 {
5996         int ret = 0;
5997         struct btrfs_key key;
5998         struct btrfs_root *root = parent_inode->root;
5999         u64 ino = btrfs_ino(inode);
6000         u64 parent_ino = btrfs_ino(parent_inode);
6001
6002         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6003                 memcpy(&key, &inode->root->root_key, sizeof(key));
6004         } else {
6005                 key.objectid = ino;
6006                 key.type = BTRFS_INODE_ITEM_KEY;
6007                 key.offset = 0;
6008         }
6009
6010         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6011                 ret = btrfs_add_root_ref(trans, key.objectid,
6012                                          root->root_key.objectid, parent_ino,
6013                                          index, name, name_len);
6014         } else if (add_backref) {
6015                 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6016                                              parent_ino, index);
6017         }
6018
6019         /* Nothing to clean up yet */
6020         if (ret)
6021                 return ret;
6022
6023         ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
6024                                     btrfs_inode_type(&inode->vfs_inode), index);
6025         if (ret == -EEXIST || ret == -EOVERFLOW)
6026                 goto fail_dir_item;
6027         else if (ret) {
6028                 btrfs_abort_transaction(trans, ret);
6029                 return ret;
6030         }
6031
6032         btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6033                            name_len * 2);
6034         inode_inc_iversion(&parent_inode->vfs_inode);
6035         /*
6036          * If we are replaying a log tree, we do not want to update the mtime
6037          * and ctime of the parent directory with the current time, since the
6038          * log replay procedure is responsible for setting them to their correct
6039          * values (the ones it had when the fsync was done).
6040          */
6041         if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
6042                 struct timespec64 now = current_time(&parent_inode->vfs_inode);
6043
6044                 parent_inode->vfs_inode.i_mtime = now;
6045                 parent_inode->vfs_inode.i_ctime = now;
6046         }
6047         ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6048         if (ret)
6049                 btrfs_abort_transaction(trans, ret);
6050         return ret;
6051
6052 fail_dir_item:
6053         if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6054                 u64 local_index;
6055                 int err;
6056                 err = btrfs_del_root_ref(trans, key.objectid,
6057                                          root->root_key.objectid, parent_ino,
6058                                          &local_index, name, name_len);
6059                 if (err)
6060                         btrfs_abort_transaction(trans, err);
6061         } else if (add_backref) {
6062                 u64 local_index;
6063                 int err;
6064
6065                 err = btrfs_del_inode_ref(trans, root, name, name_len,
6066                                           ino, parent_ino, &local_index);
6067                 if (err)
6068                         btrfs_abort_transaction(trans, err);
6069         }
6070
6071         /* Return the original error code */
6072         return ret;
6073 }
6074
6075 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6076                             struct btrfs_inode *dir, struct dentry *dentry,
6077                             struct btrfs_inode *inode, int backref, u64 index)
6078 {
6079         int err = btrfs_add_link(trans, dir, inode,
6080                                  dentry->d_name.name, dentry->d_name.len,
6081                                  backref, index);
6082         if (err > 0)
6083                 err = -EEXIST;
6084         return err;
6085 }
6086
6087 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6088                         umode_t mode, dev_t rdev)
6089 {
6090         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6091         struct btrfs_trans_handle *trans;
6092         struct btrfs_root *root = BTRFS_I(dir)->root;
6093         struct inode *inode = NULL;
6094         int err;
6095         u64 objectid;
6096         u64 index = 0;
6097
6098         /*
6099          * 2 for inode item and ref
6100          * 2 for dir items
6101          * 1 for xattr if selinux is on
6102          */
6103         trans = btrfs_start_transaction(root, 5);
6104         if (IS_ERR(trans))
6105                 return PTR_ERR(trans);
6106
6107         err = btrfs_find_free_ino(root, &objectid);
6108         if (err)
6109                 goto out_unlock;
6110
6111         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6112                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6113                         mode, &index);
6114         if (IS_ERR(inode)) {
6115                 err = PTR_ERR(inode);
6116                 inode = NULL;
6117                 goto out_unlock;
6118         }
6119
6120         /*
6121         * If the active LSM wants to access the inode during
6122         * d_instantiate it needs these. Smack checks to see
6123         * if the filesystem supports xattrs by looking at the
6124         * ops vector.
6125         */
6126         inode->i_op = &btrfs_special_inode_operations;
6127         init_special_inode(inode, inode->i_mode, rdev);
6128
6129         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6130         if (err)
6131                 goto out_unlock;
6132
6133         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6134                         0, index);
6135         if (err)
6136                 goto out_unlock;
6137
6138         btrfs_update_inode(trans, root, inode);
6139         d_instantiate_new(dentry, inode);
6140
6141 out_unlock:
6142         btrfs_end_transaction(trans);
6143         btrfs_btree_balance_dirty(fs_info);
6144         if (err && inode) {
6145                 inode_dec_link_count(inode);
6146                 discard_new_inode(inode);
6147         }
6148         return err;
6149 }
6150
6151 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6152                         umode_t mode, bool excl)
6153 {
6154         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6155         struct btrfs_trans_handle *trans;
6156         struct btrfs_root *root = BTRFS_I(dir)->root;
6157         struct inode *inode = NULL;
6158         int err;
6159         u64 objectid;
6160         u64 index = 0;
6161
6162         /*
6163          * 2 for inode item and ref
6164          * 2 for dir items
6165          * 1 for xattr if selinux is on
6166          */
6167         trans = btrfs_start_transaction(root, 5);
6168         if (IS_ERR(trans))
6169                 return PTR_ERR(trans);
6170
6171         err = btrfs_find_free_ino(root, &objectid);
6172         if (err)
6173                 goto out_unlock;
6174
6175         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6176                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6177                         mode, &index);
6178         if (IS_ERR(inode)) {
6179                 err = PTR_ERR(inode);
6180                 inode = NULL;
6181                 goto out_unlock;
6182         }
6183         /*
6184         * If the active LSM wants to access the inode during
6185         * d_instantiate it needs these. Smack checks to see
6186         * if the filesystem supports xattrs by looking at the
6187         * ops vector.
6188         */
6189         inode->i_fop = &btrfs_file_operations;
6190         inode->i_op = &btrfs_file_inode_operations;
6191         inode->i_mapping->a_ops = &btrfs_aops;
6192
6193         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6194         if (err)
6195                 goto out_unlock;
6196
6197         err = btrfs_update_inode(trans, root, inode);
6198         if (err)
6199                 goto out_unlock;
6200
6201         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6202                         0, index);
6203         if (err)
6204                 goto out_unlock;
6205
6206         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6207         d_instantiate_new(dentry, inode);
6208
6209 out_unlock:
6210         btrfs_end_transaction(trans);
6211         if (err && inode) {
6212                 inode_dec_link_count(inode);
6213                 discard_new_inode(inode);
6214         }
6215         btrfs_btree_balance_dirty(fs_info);
6216         return err;
6217 }
6218
6219 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6220                       struct dentry *dentry)
6221 {
6222         struct btrfs_trans_handle *trans = NULL;
6223         struct btrfs_root *root = BTRFS_I(dir)->root;
6224         struct inode *inode = d_inode(old_dentry);
6225         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6226         u64 index;
6227         int err;
6228         int drop_inode = 0;
6229
6230         /* do not allow sys_link's with other subvols of the same device */
6231         if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6232                 return -EXDEV;
6233
6234         if (inode->i_nlink >= BTRFS_LINK_MAX)
6235                 return -EMLINK;
6236
6237         err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6238         if (err)
6239                 goto fail;
6240
6241         /*
6242          * 2 items for inode and inode ref
6243          * 2 items for dir items
6244          * 1 item for parent inode
6245          * 1 item for orphan item deletion if O_TMPFILE
6246          */
6247         trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6248         if (IS_ERR(trans)) {
6249                 err = PTR_ERR(trans);
6250                 trans = NULL;
6251                 goto fail;
6252         }
6253
6254         /* There are several dir indexes for this inode, clear the cache. */
6255         BTRFS_I(inode)->dir_index = 0ULL;
6256         inc_nlink(inode);
6257         inode_inc_iversion(inode);
6258         inode->i_ctime = current_time(inode);
6259         ihold(inode);
6260         set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6261
6262         err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6263                         1, index);
6264
6265         if (err) {
6266                 drop_inode = 1;
6267         } else {
6268                 struct dentry *parent = dentry->d_parent;
6269                 int ret;
6270
6271                 err = btrfs_update_inode(trans, root, inode);
6272                 if (err)
6273                         goto fail;
6274                 if (inode->i_nlink == 1) {
6275                         /*
6276                          * If new hard link count is 1, it's a file created
6277                          * with open(2) O_TMPFILE flag.
6278                          */
6279                         err = btrfs_orphan_del(trans, BTRFS_I(inode));
6280                         if (err)
6281                                 goto fail;
6282                 }
6283                 d_instantiate(dentry, inode);
6284                 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6285                                          true, NULL);
6286                 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6287                         err = btrfs_commit_transaction(trans);
6288                         trans = NULL;
6289                 }
6290         }
6291
6292 fail:
6293         if (trans)
6294                 btrfs_end_transaction(trans);
6295         if (drop_inode) {
6296                 inode_dec_link_count(inode);
6297                 iput(inode);
6298         }
6299         btrfs_btree_balance_dirty(fs_info);
6300         return err;
6301 }
6302
6303 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6304 {
6305         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6306         struct inode *inode = NULL;
6307         struct btrfs_trans_handle *trans;
6308         struct btrfs_root *root = BTRFS_I(dir)->root;
6309         int err = 0;
6310         u64 objectid = 0;
6311         u64 index = 0;
6312
6313         /*
6314          * 2 items for inode and ref
6315          * 2 items for dir items
6316          * 1 for xattr if selinux is on
6317          */
6318         trans = btrfs_start_transaction(root, 5);
6319         if (IS_ERR(trans))
6320                 return PTR_ERR(trans);
6321
6322         err = btrfs_find_free_ino(root, &objectid);
6323         if (err)
6324                 goto out_fail;
6325
6326         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6327                         dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6328                         S_IFDIR | mode, &index);
6329         if (IS_ERR(inode)) {
6330                 err = PTR_ERR(inode);
6331                 inode = NULL;
6332                 goto out_fail;
6333         }
6334
6335         /* these must be set before we unlock the inode */
6336         inode->i_op = &btrfs_dir_inode_operations;
6337         inode->i_fop = &btrfs_dir_file_operations;
6338
6339         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6340         if (err)
6341                 goto out_fail;
6342
6343         btrfs_i_size_write(BTRFS_I(inode), 0);
6344         err = btrfs_update_inode(trans, root, inode);
6345         if (err)
6346                 goto out_fail;
6347
6348         err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6349                         dentry->d_name.name,
6350                         dentry->d_name.len, 0, index);
6351         if (err)
6352                 goto out_fail;
6353
6354         d_instantiate_new(dentry, inode);
6355
6356 out_fail:
6357         btrfs_end_transaction(trans);
6358         if (err && inode) {
6359                 inode_dec_link_count(inode);
6360                 discard_new_inode(inode);
6361         }
6362         btrfs_btree_balance_dirty(fs_info);
6363         return err;
6364 }
6365
6366 static noinline int uncompress_inline(struct btrfs_path *path,
6367                                       struct page *page,
6368                                       size_t pg_offset, u64 extent_offset,
6369                                       struct btrfs_file_extent_item *item)
6370 {
6371         int ret;
6372         struct extent_buffer *leaf = path->nodes[0];
6373         char *tmp;
6374         size_t max_size;
6375         unsigned long inline_size;
6376         unsigned long ptr;
6377         int compress_type;
6378
6379         WARN_ON(pg_offset != 0);
6380         compress_type = btrfs_file_extent_compression(leaf, item);
6381         max_size = btrfs_file_extent_ram_bytes(leaf, item);
6382         inline_size = btrfs_file_extent_inline_item_len(leaf,
6383                                         btrfs_item_nr(path->slots[0]));
6384         tmp = kmalloc(inline_size, GFP_NOFS);
6385         if (!tmp)
6386                 return -ENOMEM;
6387         ptr = btrfs_file_extent_inline_start(item);
6388
6389         read_extent_buffer(leaf, tmp, ptr, inline_size);
6390
6391         max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6392         ret = btrfs_decompress(compress_type, tmp, page,
6393                                extent_offset, inline_size, max_size);
6394
6395         /*
6396          * decompression code contains a memset to fill in any space between the end
6397          * of the uncompressed data and the end of max_size in case the decompressed
6398          * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6399          * the end of an inline extent and the beginning of the next block, so we
6400          * cover that region here.
6401          */
6402
6403         if (max_size + pg_offset < PAGE_SIZE) {
6404                 char *map = kmap(page);
6405                 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6406                 kunmap(page);
6407         }
6408         kfree(tmp);
6409         return ret;
6410 }
6411
6412 /**
6413  * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6414  * @inode:      file to search in
6415  * @page:       page to read extent data into if the extent is inline
6416  * @pg_offset:  offset into @page to copy to
6417  * @start:      file offset
6418  * @len:        length of range starting at @start
6419  *
6420  * This returns the first &struct extent_map which overlaps with the given
6421  * range, reading it from the B-tree and caching it if necessary. Note that
6422  * there may be more extents which overlap the given range after the returned
6423  * extent_map.
6424  *
6425  * If @page is not NULL and the extent is inline, this also reads the extent
6426  * data directly into the page and marks the extent up to date in the io_tree.
6427  *
6428  * Return: ERR_PTR on error, non-NULL extent_map on success.
6429  */
6430 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6431                                     struct page *page, size_t pg_offset,
6432                                     u64 start, u64 len)
6433 {
6434         struct btrfs_fs_info *fs_info = inode->root->fs_info;
6435         int ret;
6436         int err = 0;
6437         u64 extent_start = 0;
6438         u64 extent_end = 0;
6439         u64 objectid = btrfs_ino(inode);
6440         int extent_type = -1;
6441         struct btrfs_path *path = NULL;
6442         struct btrfs_root *root = inode->root;
6443         struct btrfs_file_extent_item *item;
6444         struct extent_buffer *leaf;
6445         struct btrfs_key found_key;
6446         struct extent_map *em = NULL;
6447         struct extent_map_tree *em_tree = &inode->extent_tree;
6448         struct extent_io_tree *io_tree = &inode->io_tree;
6449
6450         read_lock(&em_tree->lock);
6451         em = lookup_extent_mapping(em_tree, start, len);
6452         read_unlock(&em_tree->lock);
6453
6454         if (em) {
6455                 if (em->start > start || em->start + em->len <= start)
6456                         free_extent_map(em);
6457                 else if (em->block_start == EXTENT_MAP_INLINE && page)
6458                         free_extent_map(em);
6459                 else
6460                         goto out;
6461         }
6462         em = alloc_extent_map();
6463         if (!em) {
6464                 err = -ENOMEM;
6465                 goto out;
6466         }
6467         em->start = EXTENT_MAP_HOLE;
6468         em->orig_start = EXTENT_MAP_HOLE;
6469         em->len = (u64)-1;
6470         em->block_len = (u64)-1;
6471
6472         path = btrfs_alloc_path();
6473         if (!path) {
6474                 err = -ENOMEM;
6475                 goto out;
6476         }
6477
6478         /* Chances are we'll be called again, so go ahead and do readahead */
6479         path->reada = READA_FORWARD;
6480
6481         /*
6482          * Unless we're going to uncompress the inline extent, no sleep would
6483          * happen.
6484          */
6485         path->leave_spinning = 1;
6486
6487         ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6488         if (ret < 0) {
6489                 err = ret;
6490                 goto out;
6491         } else if (ret > 0) {
6492                 if (path->slots[0] == 0)
6493                         goto not_found;
6494                 path->slots[0]--;
6495         }
6496
6497         leaf = path->nodes[0];
6498         item = btrfs_item_ptr(leaf, path->slots[0],
6499                               struct btrfs_file_extent_item);
6500         btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6501         if (found_key.objectid != objectid ||
6502             found_key.type != BTRFS_EXTENT_DATA_KEY) {
6503                 /*
6504                  * If we backup past the first extent we want to move forward
6505                  * and see if there is an extent in front of us, otherwise we'll
6506                  * say there is a hole for our whole search range which can
6507                  * cause problems.
6508                  */
6509                 extent_end = start;
6510                 goto next;
6511         }
6512
6513         extent_type = btrfs_file_extent_type(leaf, item);
6514         extent_start = found_key.offset;
6515         extent_end = btrfs_file_extent_end(path);
6516         if (extent_type == BTRFS_FILE_EXTENT_REG ||
6517             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6518                 /* Only regular file could have regular/prealloc extent */
6519                 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6520                         ret = -EUCLEAN;
6521                         btrfs_crit(fs_info,
6522                 "regular/prealloc extent found for non-regular inode %llu",
6523                                    btrfs_ino(inode));
6524                         goto out;
6525                 }
6526                 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6527                                                        extent_start);
6528         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6529                 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6530                                                       path->slots[0],
6531                                                       extent_start);
6532         }
6533 next:
6534         if (start >= extent_end) {
6535                 path->slots[0]++;
6536                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6537                         ret = btrfs_next_leaf(root, path);
6538                         if (ret < 0) {
6539                                 err = ret;
6540                                 goto out;
6541                         } else if (ret > 0) {
6542                                 goto not_found;
6543                         }
6544                         leaf = path->nodes[0];
6545                 }
6546                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6547                 if (found_key.objectid != objectid ||
6548                     found_key.type != BTRFS_EXTENT_DATA_KEY)
6549                         goto not_found;
6550                 if (start + len <= found_key.offset)
6551                         goto not_found;
6552                 if (start > found_key.offset)
6553                         goto next;
6554
6555                 /* New extent overlaps with existing one */
6556                 em->start = start;
6557                 em->orig_start = start;
6558                 em->len = found_key.offset - start;
6559                 em->block_start = EXTENT_MAP_HOLE;
6560                 goto insert;
6561         }
6562
6563         btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6564
6565         if (extent_type == BTRFS_FILE_EXTENT_REG ||
6566             extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6567                 goto insert;
6568         } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6569                 unsigned long ptr;
6570                 char *map;
6571                 size_t size;
6572                 size_t extent_offset;
6573                 size_t copy_size;
6574
6575                 if (!page)
6576                         goto out;
6577
6578                 size = btrfs_file_extent_ram_bytes(leaf, item);
6579                 extent_offset = page_offset(page) + pg_offset - extent_start;
6580                 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6581                                   size - extent_offset);
6582                 em->start = extent_start + extent_offset;
6583                 em->len = ALIGN(copy_size, fs_info->sectorsize);
6584                 em->orig_block_len = em->len;
6585                 em->orig_start = em->start;
6586                 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6587
6588                 btrfs_set_path_blocking(path);
6589                 if (!PageUptodate(page)) {
6590                         if (btrfs_file_extent_compression(leaf, item) !=
6591                             BTRFS_COMPRESS_NONE) {
6592                                 ret = uncompress_inline(path, page, pg_offset,
6593                                                         extent_offset, item);
6594                                 if (ret) {
6595                                         err = ret;
6596                                         goto out;
6597                                 }
6598                         } else {
6599                                 map = kmap(page);
6600                                 read_extent_buffer(leaf, map + pg_offset, ptr,
6601                                                    copy_size);
6602                                 if (pg_offset + copy_size < PAGE_SIZE) {
6603                                         memset(map + pg_offset + copy_size, 0,
6604                                                PAGE_SIZE - pg_offset -
6605                                                copy_size);
6606                                 }
6607                                 kunmap(page);
6608                         }
6609                         flush_dcache_page(page);
6610                 }
6611                 set_extent_uptodate(io_tree, em->start,
6612                                     extent_map_end(em) - 1, NULL, GFP_NOFS);
6613                 goto insert;
6614         }
6615 not_found:
6616         em->start = start;
6617         em->orig_start = start;
6618         em->len = len;
6619         em->block_start = EXTENT_MAP_HOLE;
6620 insert:
6621         btrfs_release_path(path);
6622         if (em->start > start || extent_map_end(em) <= start) {
6623                 btrfs_err(fs_info,
6624                           "bad extent! em: [%llu %llu] passed [%llu %llu]",
6625                           em->start, em->len, start, len);
6626                 err = -EIO;
6627                 goto out;
6628         }
6629
6630         err = 0;
6631         write_lock(&em_tree->lock);
6632         err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6633         write_unlock(&em_tree->lock);
6634 out:
6635         btrfs_free_path(path);
6636
6637         trace_btrfs_get_extent(root, inode, em);
6638
6639         if (err) {
6640                 free_extent_map(em);
6641                 return ERR_PTR(err);
6642         }
6643         BUG_ON(!em); /* Error is always set */
6644         return em;
6645 }
6646
6647 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6648                                            u64 start, u64 len)
6649 {
6650         struct extent_map *em;
6651         struct extent_map *hole_em = NULL;
6652         u64 delalloc_start = start;
6653         u64 end;
6654         u64 delalloc_len;
6655         u64 delalloc_end;
6656         int err = 0;
6657
6658         em = btrfs_get_extent(inode, NULL, 0, start, len);
6659         if (IS_ERR(em))
6660                 return em;
6661         /*
6662          * If our em maps to:
6663          * - a hole or
6664          * - a pre-alloc extent,
6665          * there might actually be delalloc bytes behind it.
6666          */
6667         if (em->block_start != EXTENT_MAP_HOLE &&
6668             !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6669                 return em;
6670         else
6671                 hole_em = em;
6672
6673         /* check to see if we've wrapped (len == -1 or similar) */
6674         end = start + len;
6675         if (end < start)
6676                 end = (u64)-1;
6677         else
6678                 end -= 1;
6679
6680         em = NULL;
6681
6682         /* ok, we didn't find anything, lets look for delalloc */
6683         delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6684                                  end, len, EXTENT_DELALLOC, 1);
6685         delalloc_end = delalloc_start + delalloc_len;
6686         if (delalloc_end < delalloc_start)
6687                 delalloc_end = (u64)-1;
6688
6689         /*
6690          * We didn't find anything useful, return the original results from
6691          * get_extent()
6692          */
6693         if (delalloc_start > end || delalloc_end <= start) {
6694                 em = hole_em;
6695                 hole_em = NULL;
6696                 goto out;
6697         }
6698
6699         /*
6700          * Adjust the delalloc_start to make sure it doesn't go backwards from
6701          * the start they passed in
6702          */
6703         delalloc_start = max(start, delalloc_start);
6704         delalloc_len = delalloc_end - delalloc_start;
6705
6706         if (delalloc_len > 0) {
6707                 u64 hole_start;
6708                 u64 hole_len;
6709                 const u64 hole_end = extent_map_end(hole_em);
6710
6711                 em = alloc_extent_map();
6712                 if (!em) {
6713                         err = -ENOMEM;
6714                         goto out;
6715                 }
6716
6717                 ASSERT(hole_em);
6718                 /*
6719                  * When btrfs_get_extent can't find anything it returns one
6720                  * huge hole
6721                  *
6722                  * Make sure what it found really fits our range, and adjust to
6723                  * make sure it is based on the start from the caller
6724                  */
6725                 if (hole_end <= start || hole_em->start > end) {
6726                        free_extent_map(hole_em);
6727                        hole_em = NULL;
6728                 } else {
6729                        hole_start = max(hole_em->start, start);
6730                        hole_len = hole_end - hole_start;
6731                 }
6732
6733                 if (hole_em && delalloc_start > hole_start) {
6734                         /*
6735                          * Our hole starts before our delalloc, so we have to
6736                          * return just the parts of the hole that go until the
6737                          * delalloc starts
6738                          */
6739                         em->len = min(hole_len, delalloc_start - hole_start);
6740                         em->start = hole_start;
6741                         em->orig_start = hole_start;
6742                         /*
6743                          * Don't adjust block start at all, it is fixed at
6744                          * EXTENT_MAP_HOLE
6745                          */
6746                         em->block_start = hole_em->block_start;
6747                         em->block_len = hole_len;
6748                         if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6749                                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6750                 } else {
6751                         /*
6752                          * Hole is out of passed range or it starts after
6753                          * delalloc range
6754                          */
6755                         em->start = delalloc_start;
6756                         em->len = delalloc_len;
6757                         em->orig_start = delalloc_start;
6758                         em->block_start = EXTENT_MAP_DELALLOC;
6759                         em->block_len = delalloc_len;
6760                 }
6761         } else {
6762                 return hole_em;
6763         }
6764 out:
6765
6766         free_extent_map(hole_em);
6767         if (err) {
6768                 free_extent_map(em);
6769                 return ERR_PTR(err);
6770         }
6771         return em;
6772 }
6773
6774 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6775                                                   const u64 start,
6776                                                   const u64 len,
6777                                                   const u64 orig_start,
6778                                                   const u64 block_start,
6779                                                   const u64 block_len,
6780                                                   const u64 orig_block_len,
6781                                                   const u64 ram_bytes,
6782                                                   const int type)
6783 {
6784         struct extent_map *em = NULL;
6785         int ret;
6786
6787         if (type != BTRFS_ORDERED_NOCOW) {
6788                 em = create_io_em(inode, start, len, orig_start,
6789                                   block_start, block_len, orig_block_len,
6790                                   ram_bytes,
6791                                   BTRFS_COMPRESS_NONE, /* compress_type */
6792                                   type);
6793                 if (IS_ERR(em))
6794                         goto out;
6795         }
6796         ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6797                                            len, block_len, type);
6798         if (ret) {
6799                 if (em) {
6800                         free_extent_map(em);
6801                         btrfs_drop_extent_cache(BTRFS_I(inode), start,
6802                                                 start + len - 1, 0);
6803                 }
6804                 em = ERR_PTR(ret);
6805         }
6806  out:
6807
6808         return em;
6809 }
6810
6811 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6812                                                   u64 start, u64 len)
6813 {
6814         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6815         struct btrfs_root *root = BTRFS_I(inode)->root;
6816         struct extent_map *em;
6817         struct btrfs_key ins;
6818         u64 alloc_hint;
6819         int ret;
6820
6821         alloc_hint = get_extent_allocation_hint(inode, start, len);
6822         ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6823                                    0, alloc_hint, &ins, 1, 1);
6824         if (ret)
6825                 return ERR_PTR(ret);
6826
6827         em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6828                                      ins.objectid, ins.offset, ins.offset,
6829                                      ins.offset, BTRFS_ORDERED_REGULAR);
6830         btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6831         if (IS_ERR(em))
6832                 btrfs_free_reserved_extent(fs_info, ins.objectid,
6833                                            ins.offset, 1);
6834
6835         return em;
6836 }
6837
6838 /*
6839  * returns 1 when the nocow is safe, < 1 on error, 0 if the
6840  * block must be cow'd
6841  */
6842 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6843                               u64 *orig_start, u64 *orig_block_len,
6844                               u64 *ram_bytes)
6845 {
6846         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6847         struct btrfs_path *path;
6848         int ret;
6849         struct extent_buffer *leaf;
6850         struct btrfs_root *root = BTRFS_I(inode)->root;
6851         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6852         struct btrfs_file_extent_item *fi;
6853         struct btrfs_key key;
6854         u64 disk_bytenr;
6855         u64 backref_offset;
6856         u64 extent_end;
6857         u64 num_bytes;
6858         int slot;
6859         int found_type;
6860         bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6861
6862         path = btrfs_alloc_path();
6863         if (!path)
6864                 return -ENOMEM;
6865
6866         ret = btrfs_lookup_file_extent(NULL, root, path,
6867                         btrfs_ino(BTRFS_I(inode)), offset, 0);
6868         if (ret < 0)
6869                 goto out;
6870
6871         slot = path->slots[0];
6872         if (ret == 1) {
6873                 if (slot == 0) {
6874                         /* can't find the item, must cow */
6875                         ret = 0;
6876                         goto out;
6877                 }
6878                 slot--;
6879         }
6880         ret = 0;
6881         leaf = path->nodes[0];
6882         btrfs_item_key_to_cpu(leaf, &key, slot);
6883         if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6884             key.type != BTRFS_EXTENT_DATA_KEY) {
6885                 /* not our file or wrong item type, must cow */
6886                 goto out;
6887         }
6888
6889         if (key.offset > offset) {
6890                 /* Wrong offset, must cow */
6891                 goto out;
6892         }
6893
6894         fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6895         found_type = btrfs_file_extent_type(leaf, fi);
6896         if (found_type != BTRFS_FILE_EXTENT_REG &&
6897             found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6898                 /* not a regular extent, must cow */
6899                 goto out;
6900         }
6901
6902         if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6903                 goto out;
6904
6905         extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6906         if (extent_end <= offset)
6907                 goto out;
6908
6909         disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6910         if (disk_bytenr == 0)
6911                 goto out;
6912
6913         if (btrfs_file_extent_compression(leaf, fi) ||
6914             btrfs_file_extent_encryption(leaf, fi) ||
6915             btrfs_file_extent_other_encoding(leaf, fi))
6916                 goto out;
6917
6918         /*
6919          * Do the same check as in btrfs_cross_ref_exist but without the
6920          * unnecessary search.
6921          */
6922         if (btrfs_file_extent_generation(leaf, fi) <=
6923             btrfs_root_last_snapshot(&root->root_item))
6924                 goto out;
6925
6926         backref_offset = btrfs_file_extent_offset(leaf, fi);
6927
6928         if (orig_start) {
6929                 *orig_start = key.offset - backref_offset;
6930                 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6931                 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6932         }
6933
6934         if (btrfs_extent_readonly(fs_info, disk_bytenr))
6935                 goto out;
6936
6937         num_bytes = min(offset + *len, extent_end) - offset;
6938         if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6939                 u64 range_end;
6940
6941                 range_end = round_up(offset + num_bytes,
6942                                      root->fs_info->sectorsize) - 1;
6943                 ret = test_range_bit(io_tree, offset, range_end,
6944                                      EXTENT_DELALLOC, 0, NULL);
6945                 if (ret) {
6946                         ret = -EAGAIN;
6947                         goto out;
6948                 }
6949         }
6950
6951         btrfs_release_path(path);
6952
6953         /*
6954          * look for other files referencing this extent, if we
6955          * find any we must cow
6956          */
6957
6958         ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
6959                                     key.offset - backref_offset, disk_bytenr);
6960         if (ret) {
6961                 ret = 0;
6962                 goto out;
6963         }
6964
6965         /*
6966          * adjust disk_bytenr and num_bytes to cover just the bytes
6967          * in this extent we are about to write.  If there
6968          * are any csums in that range we have to cow in order
6969          * to keep the csums correct
6970          */
6971         disk_bytenr += backref_offset;
6972         disk_bytenr += offset - key.offset;
6973         if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
6974                 goto out;
6975         /*
6976          * all of the above have passed, it is safe to overwrite this extent
6977          * without cow
6978          */
6979         *len = num_bytes;
6980         ret = 1;
6981 out:
6982         btrfs_free_path(path);
6983         return ret;
6984 }
6985
6986 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6987                               struct extent_state **cached_state, int writing)
6988 {
6989         struct btrfs_ordered_extent *ordered;
6990         int ret = 0;
6991
6992         while (1) {
6993                 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6994                                  cached_state);
6995                 /*
6996                  * We're concerned with the entire range that we're going to be
6997                  * doing DIO to, so we need to make sure there's no ordered
6998                  * extents in this range.
6999                  */
7000                 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7001                                                      lockend - lockstart + 1);
7002
7003                 /*
7004                  * We need to make sure there are no buffered pages in this
7005                  * range either, we could have raced between the invalidate in
7006                  * generic_file_direct_write and locking the extent.  The
7007                  * invalidate needs to happen so that reads after a write do not
7008                  * get stale data.
7009                  */
7010                 if (!ordered &&
7011                     (!writing || !filemap_range_has_page(inode->i_mapping,
7012                                                          lockstart, lockend)))
7013                         break;
7014
7015                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7016                                      cached_state);
7017
7018                 if (ordered) {
7019                         /*
7020                          * If we are doing a DIO read and the ordered extent we
7021                          * found is for a buffered write, we can not wait for it
7022                          * to complete and retry, because if we do so we can
7023                          * deadlock with concurrent buffered writes on page
7024                          * locks. This happens only if our DIO read covers more
7025                          * than one extent map, if at this point has already
7026                          * created an ordered extent for a previous extent map
7027                          * and locked its range in the inode's io tree, and a
7028                          * concurrent write against that previous extent map's
7029                          * range and this range started (we unlock the ranges
7030                          * in the io tree only when the bios complete and
7031                          * buffered writes always lock pages before attempting
7032                          * to lock range in the io tree).
7033                          */
7034                         if (writing ||
7035                             test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7036                                 btrfs_start_ordered_extent(inode, ordered, 1);
7037                         else
7038                                 ret = -ENOTBLK;
7039                         btrfs_put_ordered_extent(ordered);
7040                 } else {
7041                         /*
7042                          * We could trigger writeback for this range (and wait
7043                          * for it to complete) and then invalidate the pages for
7044                          * this range (through invalidate_inode_pages2_range()),
7045                          * but that can lead us to a deadlock with a concurrent
7046                          * call to readpages() (a buffered read or a defrag call
7047                          * triggered a readahead) on a page lock due to an
7048                          * ordered dio extent we created before but did not have
7049                          * yet a corresponding bio submitted (whence it can not
7050                          * complete), which makes readpages() wait for that
7051                          * ordered extent to complete while holding a lock on
7052                          * that page.
7053                          */
7054                         ret = -ENOTBLK;
7055                 }
7056
7057                 if (ret)
7058                         break;
7059
7060                 cond_resched();
7061         }
7062
7063         return ret;
7064 }
7065
7066 /* The callers of this must take lock_extent() */
7067 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7068                                        u64 orig_start, u64 block_start,
7069                                        u64 block_len, u64 orig_block_len,
7070                                        u64 ram_bytes, int compress_type,
7071                                        int type)
7072 {
7073         struct extent_map_tree *em_tree;
7074         struct extent_map *em;
7075         int ret;
7076
7077         ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7078                type == BTRFS_ORDERED_COMPRESSED ||
7079                type == BTRFS_ORDERED_NOCOW ||
7080                type == BTRFS_ORDERED_REGULAR);
7081
7082         em_tree = &BTRFS_I(inode)->extent_tree;
7083         em = alloc_extent_map();
7084         if (!em)
7085                 return ERR_PTR(-ENOMEM);
7086
7087         em->start = start;
7088         em->orig_start = orig_start;
7089         em->len = len;
7090         em->block_len = block_len;
7091         em->block_start = block_start;
7092         em->orig_block_len = orig_block_len;
7093         em->ram_bytes = ram_bytes;
7094         em->generation = -1;
7095         set_bit(EXTENT_FLAG_PINNED, &em->flags);
7096         if (type == BTRFS_ORDERED_PREALLOC) {
7097                 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7098         } else if (type == BTRFS_ORDERED_COMPRESSED) {
7099                 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7100                 em->compress_type = compress_type;
7101         }
7102
7103         do {
7104                 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7105                                 em->start + em->len - 1, 0);
7106                 write_lock(&em_tree->lock);
7107                 ret = add_extent_mapping(em_tree, em, 1);
7108                 write_unlock(&em_tree->lock);
7109                 /*
7110                  * The caller has taken lock_extent(), who could race with us
7111                  * to add em?
7112                  */
7113         } while (ret == -EEXIST);
7114
7115         if (ret) {
7116                 free_extent_map(em);
7117                 return ERR_PTR(ret);
7118         }
7119
7120         /* em got 2 refs now, callers needs to do free_extent_map once. */
7121         return em;
7122 }
7123
7124
7125 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7126                                         struct buffer_head *bh_result,
7127                                         struct inode *inode,
7128                                         u64 start, u64 len)
7129 {
7130         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7131
7132         if (em->block_start == EXTENT_MAP_HOLE ||
7133                         test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7134                 return -ENOENT;
7135
7136         len = min(len, em->len - (start - em->start));
7137
7138         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7139                 inode->i_blkbits;
7140         bh_result->b_size = len;
7141         bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7142         set_buffer_mapped(bh_result);
7143
7144         return 0;
7145 }
7146
7147 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7148                                          struct buffer_head *bh_result,
7149                                          struct inode *inode,
7150                                          struct btrfs_dio_data *dio_data,
7151                                          u64 start, u64 len)
7152 {
7153         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7154         struct extent_map *em = *map;
7155         int ret = 0;
7156
7157         /*
7158          * We don't allocate a new extent in the following cases
7159          *
7160          * 1) The inode is marked as NODATACOW. In this case we'll just use the
7161          * existing extent.
7162          * 2) The extent is marked as PREALLOC. We're good to go here and can
7163          * just use the extent.
7164          *
7165          */
7166         if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7167             ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7168              em->block_start != EXTENT_MAP_HOLE)) {
7169                 int type;
7170                 u64 block_start, orig_start, orig_block_len, ram_bytes;
7171
7172                 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7173                         type = BTRFS_ORDERED_PREALLOC;
7174                 else
7175                         type = BTRFS_ORDERED_NOCOW;
7176                 len = min(len, em->len - (start - em->start));
7177                 block_start = em->block_start + (start - em->start);
7178
7179                 if (can_nocow_extent(inode, start, &len, &orig_start,
7180                                      &orig_block_len, &ram_bytes) == 1 &&
7181                     btrfs_inc_nocow_writers(fs_info, block_start)) {
7182                         struct extent_map *em2;
7183
7184                         em2 = btrfs_create_dio_extent(inode, start, len,
7185                                                       orig_start, block_start,
7186                                                       len, orig_block_len,
7187                                                       ram_bytes, type);
7188                         btrfs_dec_nocow_writers(fs_info, block_start);
7189                         if (type == BTRFS_ORDERED_PREALLOC) {
7190                                 free_extent_map(em);
7191                                 *map = em = em2;
7192                         }
7193
7194                         if (em2 && IS_ERR(em2)) {
7195                                 ret = PTR_ERR(em2);
7196                                 goto out;
7197                         }
7198                         /*
7199                          * For inode marked NODATACOW or extent marked PREALLOC,
7200                          * use the existing or preallocated extent, so does not
7201                          * need to adjust btrfs_space_info's bytes_may_use.
7202                          */
7203                         btrfs_free_reserved_data_space_noquota(inode, start,
7204                                                                len);
7205                         goto skip_cow;
7206                 }
7207         }
7208
7209         /* this will cow the extent */
7210         len = bh_result->b_size;
7211         free_extent_map(em);
7212         *map = em = btrfs_new_extent_direct(inode, start, len);
7213         if (IS_ERR(em)) {
7214                 ret = PTR_ERR(em);
7215                 goto out;
7216         }
7217
7218         len = min(len, em->len - (start - em->start));
7219
7220 skip_cow:
7221         bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7222                 inode->i_blkbits;
7223         bh_result->b_size = len;
7224         bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7225         set_buffer_mapped(bh_result);
7226
7227         if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7228                 set_buffer_new(bh_result);
7229
7230         /*
7231          * Need to update the i_size under the extent lock so buffered
7232          * readers will get the updated i_size when we unlock.
7233          */
7234         if (!dio_data->overwrite && start + len > i_size_read(inode))
7235                 i_size_write(inode, start + len);
7236
7237         WARN_ON(dio_data->reserve < len);
7238         dio_data->reserve -= len;
7239         dio_data->unsubmitted_oe_range_end = start + len;
7240         current->journal_info = dio_data;
7241 out:
7242         return ret;
7243 }
7244
7245 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7246                                    struct buffer_head *bh_result, int create)
7247 {
7248         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7249         struct extent_map *em;
7250         struct extent_state *cached_state = NULL;
7251         struct btrfs_dio_data *dio_data = NULL;
7252         u64 start = iblock << inode->i_blkbits;
7253         u64 lockstart, lockend;
7254         u64 len = bh_result->b_size;
7255         int ret = 0;
7256
7257         if (!create)
7258                 len = min_t(u64, len, fs_info->sectorsize);
7259
7260         lockstart = start;
7261         lockend = start + len - 1;
7262
7263         if (current->journal_info) {
7264                 /*
7265                  * Need to pull our outstanding extents and set journal_info to NULL so
7266                  * that anything that needs to check if there's a transaction doesn't get
7267                  * confused.
7268                  */
7269                 dio_data = current->journal_info;
7270                 current->journal_info = NULL;
7271         }
7272
7273         /*
7274          * If this errors out it's because we couldn't invalidate pagecache for
7275          * this range and we need to fallback to buffered.
7276          */
7277         if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7278                                create)) {
7279                 ret = -ENOTBLK;
7280                 goto err;
7281         }
7282
7283         em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7284         if (IS_ERR(em)) {
7285                 ret = PTR_ERR(em);
7286                 goto unlock_err;
7287         }
7288
7289         /*
7290          * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7291          * io.  INLINE is special, and we could probably kludge it in here, but
7292          * it's still buffered so for safety lets just fall back to the generic
7293          * buffered path.
7294          *
7295          * For COMPRESSED we _have_ to read the entire extent in so we can
7296          * decompress it, so there will be buffering required no matter what we
7297          * do, so go ahead and fallback to buffered.
7298          *
7299          * We return -ENOTBLK because that's what makes DIO go ahead and go back
7300          * to buffered IO.  Don't blame me, this is the price we pay for using
7301          * the generic code.
7302          */
7303         if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7304             em->block_start == EXTENT_MAP_INLINE) {
7305                 free_extent_map(em);
7306                 ret = -ENOTBLK;
7307                 goto unlock_err;
7308         }
7309
7310         if (create) {
7311                 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7312                                                     dio_data, start, len);
7313                 if (ret < 0)
7314                         goto unlock_err;
7315
7316                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7317                                      lockend, &cached_state);
7318         } else {
7319                 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7320                                                    start, len);
7321                 /* Can be negative only if we read from a hole */
7322                 if (ret < 0) {
7323                         ret = 0;
7324                         free_extent_map(em);
7325                         goto unlock_err;
7326                 }
7327                 /*
7328                  * We need to unlock only the end area that we aren't using.
7329                  * The rest is going to be unlocked by the endio routine.
7330                  */
7331                 lockstart = start + bh_result->b_size;
7332                 if (lockstart < lockend) {
7333                         unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7334                                              lockstart, lockend, &cached_state);
7335                 } else {
7336                         free_extent_state(cached_state);
7337                 }
7338         }
7339
7340         free_extent_map(em);
7341
7342         return 0;
7343
7344 unlock_err:
7345         unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7346                              &cached_state);
7347 err:
7348         if (dio_data)
7349                 current->journal_info = dio_data;
7350         return ret;
7351 }
7352
7353 static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
7354 {
7355         /*
7356          * This implies a barrier so that stores to dio_bio->bi_status before
7357          * this and loads of dio_bio->bi_status after this are fully ordered.
7358          */
7359         if (!refcount_dec_and_test(&dip->refs))
7360                 return;
7361
7362         if (bio_op(dip->dio_bio) == REQ_OP_WRITE) {
7363                 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7364                                              dip->bytes,
7365                                              !dip->dio_bio->bi_status);
7366         } else {
7367                 unlock_extent(&BTRFS_I(dip->inode)->io_tree,
7368                               dip->logical_offset,
7369                               dip->logical_offset + dip->bytes - 1);
7370         }
7371
7372         dio_end_io(dip->dio_bio);
7373         kfree(dip);
7374 }
7375
7376 static blk_status_t submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7377                                           int mirror_num,
7378                                           unsigned long bio_flags)
7379 {
7380         struct btrfs_dio_private *dip = bio->bi_private;
7381         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7382         blk_status_t ret;
7383
7384         BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7385
7386         ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7387         if (ret)
7388                 return ret;
7389
7390         refcount_inc(&dip->refs);
7391         ret = btrfs_map_bio(fs_info, bio, mirror_num);
7392         if (ret)
7393                 refcount_dec(&dip->refs);
7394         return ret;
7395 }
7396
7397 static blk_status_t btrfs_check_read_dio_bio(struct inode *inode,
7398                                              struct btrfs_io_bio *io_bio,
7399                                              const bool uptodate)
7400 {
7401         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
7402         const u32 sectorsize = fs_info->sectorsize;
7403         struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7404         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7405         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7406         struct bio_vec bvec;
7407         struct bvec_iter iter;
7408         u64 start = io_bio->logical;
7409         int icsum = 0;
7410         blk_status_t err = BLK_STS_OK;
7411
7412         __bio_for_each_segment(bvec, &io_bio->bio, iter, io_bio->iter) {
7413                 unsigned int i, nr_sectors, pgoff;
7414
7415                 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7416                 pgoff = bvec.bv_offset;
7417                 for (i = 0; i < nr_sectors; i++) {
7418                         ASSERT(pgoff < PAGE_SIZE);
7419                         if (uptodate &&
7420                             (!csum || !check_data_csum(inode, io_bio, icsum,
7421                                                        bvec.bv_page, pgoff,
7422                                                        start, sectorsize))) {
7423                                 clean_io_failure(fs_info, failure_tree, io_tree,
7424                                                  start, bvec.bv_page,
7425                                                  btrfs_ino(BTRFS_I(inode)),
7426                                                  pgoff);
7427                         } else {
7428                                 blk_status_t status;
7429
7430                                 status = btrfs_submit_read_repair(inode,
7431                                                         &io_bio->bio,
7432                                                         start - io_bio->logical,
7433                                                         bvec.bv_page, pgoff,
7434                                                         start,
7435                                                         start + sectorsize - 1,
7436                                                         io_bio->mirror_num,
7437                                                         submit_dio_repair_bio);
7438                                 if (status)
7439                                         err = status;
7440                         }
7441                         start += sectorsize;
7442                         icsum++;
7443                         pgoff += sectorsize;
7444                 }
7445         }
7446         return err;
7447 }
7448
7449 static void __endio_write_update_ordered(struct inode *inode,
7450                                          const u64 offset, const u64 bytes,
7451                                          const bool uptodate)
7452 {
7453         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7454         struct btrfs_ordered_extent *ordered = NULL;
7455         struct btrfs_workqueue *wq;
7456         u64 ordered_offset = offset;
7457         u64 ordered_bytes = bytes;
7458         u64 last_offset;
7459
7460         if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7461                 wq = fs_info->endio_freespace_worker;
7462         else
7463                 wq = fs_info->endio_write_workers;
7464
7465         while (ordered_offset < offset + bytes) {
7466                 last_offset = ordered_offset;
7467                 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7468                                                            &ordered_offset,
7469                                                            ordered_bytes,
7470                                                            uptodate)) {
7471                         btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7472                                         NULL);
7473                         btrfs_queue_work(wq, &ordered->work);
7474                 }
7475                 /*
7476                  * If btrfs_dec_test_ordered_pending does not find any ordered
7477                  * extent in the range, we can exit.
7478                  */
7479                 if (ordered_offset == last_offset)
7480                         return;
7481                 /*
7482                  * Our bio might span multiple ordered extents. In this case
7483                  * we keep going until we have accounted the whole dio.
7484                  */
7485                 if (ordered_offset < offset + bytes) {
7486                         ordered_bytes = offset + bytes - ordered_offset;
7487                         ordered = NULL;
7488                 }
7489         }
7490 }
7491
7492 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7493                                     struct bio *bio, u64 offset)
7494 {
7495         struct inode *inode = private_data;
7496         blk_status_t ret;
7497         ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7498         BUG_ON(ret); /* -ENOMEM */
7499         return 0;
7500 }
7501
7502 static void btrfs_end_dio_bio(struct bio *bio)
7503 {
7504         struct btrfs_dio_private *dip = bio->bi_private;
7505         blk_status_t err = bio->bi_status;
7506
7507         if (err)
7508                 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7509                            "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7510                            btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7511                            bio->bi_opf,
7512                            (unsigned long long)bio->bi_iter.bi_sector,
7513                            bio->bi_iter.bi_size, err);
7514
7515         if (bio_op(bio) == REQ_OP_READ) {
7516                 err = btrfs_check_read_dio_bio(dip->inode, btrfs_io_bio(bio),
7517                                                !err);
7518         }
7519
7520         if (err)
7521                 dip->dio_bio->bi_status = err;
7522
7523         bio_put(bio);
7524         btrfs_dio_private_put(dip);
7525 }
7526
7527 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7528                 struct inode *inode, u64 file_offset, int async_submit)
7529 {
7530         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7531         struct btrfs_dio_private *dip = bio->bi_private;
7532         bool write = bio_op(bio) == REQ_OP_WRITE;
7533         blk_status_t ret;
7534
7535         /* Check btrfs_submit_bio_hook() for rules about async submit. */
7536         if (async_submit)
7537                 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7538
7539         if (!write) {
7540                 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7541                 if (ret)
7542                         goto err;
7543         }
7544
7545         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7546                 goto map;
7547
7548         if (write && async_submit) {
7549                 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7550                                           file_offset, inode,
7551                                           btrfs_submit_bio_start_direct_io);
7552                 goto err;
7553         } else if (write) {
7554                 /*
7555                  * If we aren't doing async submit, calculate the csum of the
7556                  * bio now.
7557                  */
7558                 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7559                 if (ret)
7560                         goto err;
7561         } else {
7562                 u64 csum_offset;
7563
7564                 csum_offset = file_offset - dip->logical_offset;
7565                 csum_offset >>= inode->i_sb->s_blocksize_bits;
7566                 csum_offset *= btrfs_super_csum_size(fs_info->super_copy);
7567                 btrfs_io_bio(bio)->csum = dip->csums + csum_offset;
7568         }
7569 map:
7570         ret = btrfs_map_bio(fs_info, bio, 0);
7571 err:
7572         return ret;
7573 }
7574
7575 /*
7576  * If this succeeds, the btrfs_dio_private is responsible for cleaning up locked
7577  * or ordered extents whether or not we submit any bios.
7578  */
7579 static struct btrfs_dio_private *btrfs_create_dio_private(struct bio *dio_bio,
7580                                                           struct inode *inode,
7581                                                           loff_t file_offset)
7582 {
7583         const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7584         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7585         size_t dip_size;
7586         struct btrfs_dio_private *dip;
7587
7588         dip_size = sizeof(*dip);
7589         if (!write && csum) {
7590                 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7591                 const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
7592                 size_t nblocks;
7593
7594                 nblocks = dio_bio->bi_iter.bi_size >> inode->i_sb->s_blocksize_bits;
7595                 dip_size += csum_size * nblocks;
7596         }
7597
7598         dip = kzalloc(dip_size, GFP_NOFS);
7599         if (!dip)
7600                 return NULL;
7601
7602         dip->inode = inode;
7603         dip->logical_offset = file_offset;
7604         dip->bytes = dio_bio->bi_iter.bi_size;
7605         dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7606         dip->dio_bio = dio_bio;
7607         refcount_set(&dip->refs, 1);
7608
7609         if (write) {
7610                 struct btrfs_dio_data *dio_data = current->journal_info;
7611
7612                 /*
7613                  * Setting range start and end to the same value means that
7614                  * no cleanup will happen in btrfs_direct_IO
7615                  */
7616                 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
7617                         dip->bytes;
7618                 dio_data->unsubmitted_oe_range_start =
7619                         dio_data->unsubmitted_oe_range_end;
7620         }
7621         return dip;
7622 }
7623
7624 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
7625                                 loff_t file_offset)
7626 {
7627         const bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7628         const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
7629         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7630         const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
7631                              BTRFS_BLOCK_GROUP_RAID56_MASK);
7632         struct btrfs_dio_private *dip;
7633         struct bio *bio;
7634         u64 start_sector;
7635         int async_submit = 0;
7636         u64 submit_len;
7637         int clone_offset = 0;
7638         int clone_len;
7639         int ret;
7640         blk_status_t status;
7641         struct btrfs_io_geometry geom;
7642
7643         dip = btrfs_create_dio_private(dio_bio, inode, file_offset);
7644         if (!dip) {
7645                 if (!write) {
7646                         unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
7647                                 file_offset + dio_bio->bi_iter.bi_size - 1);
7648                 }
7649                 dio_bio->bi_status = BLK_STS_RESOURCE;
7650                 dio_end_io(dio_bio);
7651                 return;
7652         }
7653
7654         if (!write && csum) {
7655                 /*
7656                  * Load the csums up front to reduce csum tree searches and
7657                  * contention when submitting bios.
7658                  */
7659                 status = btrfs_lookup_bio_sums(inode, dio_bio, file_offset,
7660                                                dip->csums);
7661                 if (status != BLK_STS_OK)
7662                         goto out_err;
7663         }
7664
7665         start_sector = dio_bio->bi_iter.bi_sector;
7666         submit_len = dio_bio->bi_iter.bi_size;
7667
7668         do {
7669                 ret = btrfs_get_io_geometry(fs_info, btrfs_op(dio_bio),
7670                                             start_sector << 9, submit_len,
7671                                             &geom);
7672                 if (ret) {
7673                         status = errno_to_blk_status(ret);
7674                         goto out_err;
7675                 }
7676                 ASSERT(geom.len <= INT_MAX);
7677
7678                 clone_len = min_t(int, submit_len, geom.len);
7679
7680                 /*
7681                  * This will never fail as it's passing GPF_NOFS and
7682                  * the allocation is backed by btrfs_bioset.
7683                  */
7684                 bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len);
7685                 bio->bi_private = dip;
7686                 bio->bi_end_io = btrfs_end_dio_bio;
7687                 btrfs_io_bio(bio)->logical = file_offset;
7688
7689                 ASSERT(submit_len >= clone_len);
7690                 submit_len -= clone_len;
7691
7692                 /*
7693                  * Increase the count before we submit the bio so we know
7694                  * the end IO handler won't happen before we increase the
7695                  * count. Otherwise, the dip might get freed before we're
7696                  * done setting it up.
7697                  *
7698                  * We transfer the initial reference to the last bio, so we
7699                  * don't need to increment the reference count for the last one.
7700                  */
7701                 if (submit_len > 0) {
7702                         refcount_inc(&dip->refs);
7703                         /*
7704                          * If we are submitting more than one bio, submit them
7705                          * all asynchronously. The exception is RAID 5 or 6, as
7706                          * asynchronous checksums make it difficult to collect
7707                          * full stripe writes.
7708                          */
7709                         if (!raid56)
7710                                 async_submit = 1;
7711                 }
7712
7713                 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7714                                                 async_submit);
7715                 if (status) {
7716                         bio_put(bio);
7717                         if (submit_len > 0)
7718                                 refcount_dec(&dip->refs);
7719                         goto out_err;
7720                 }
7721
7722                 clone_offset += clone_len;
7723                 start_sector += clone_len >> 9;
7724                 file_offset += clone_len;
7725         } while (submit_len > 0);
7726         return;
7727
7728 out_err:
7729         dip->dio_bio->bi_status = status;
7730         btrfs_dio_private_put(dip);
7731 }
7732
7733 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
7734                                const struct iov_iter *iter, loff_t offset)
7735 {
7736         int seg;
7737         int i;
7738         unsigned int blocksize_mask = fs_info->sectorsize - 1;
7739         ssize_t retval = -EINVAL;
7740
7741         if (offset & blocksize_mask)
7742                 goto out;
7743
7744         if (iov_iter_alignment(iter) & blocksize_mask)
7745                 goto out;
7746
7747         /* If this is a write we don't need to check anymore */
7748         if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
7749                 return 0;
7750         /*
7751          * Check to make sure we don't have duplicate iov_base's in this
7752          * iovec, if so return EINVAL, otherwise we'll get csum errors
7753          * when reading back.
7754          */
7755         for (seg = 0; seg < iter->nr_segs; seg++) {
7756                 for (i = seg + 1; i < iter->nr_segs; i++) {
7757                         if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7758                                 goto out;
7759                 }
7760         }
7761         retval = 0;
7762 out:
7763         return retval;
7764 }
7765
7766 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
7767 {
7768         struct file *file = iocb->ki_filp;
7769         struct inode *inode = file->f_mapping->host;
7770         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7771         struct btrfs_dio_data dio_data = { 0 };
7772         struct extent_changeset *data_reserved = NULL;
7773         loff_t offset = iocb->ki_pos;
7774         size_t count = 0;
7775         int flags = 0;
7776         bool wakeup = true;
7777         bool relock = false;
7778         ssize_t ret;
7779
7780         if (check_direct_IO(fs_info, iter, offset))
7781                 return 0;
7782
7783         inode_dio_begin(inode);
7784
7785         /*
7786          * The generic stuff only does filemap_write_and_wait_range, which
7787          * isn't enough if we've written compressed pages to this area, so
7788          * we need to flush the dirty pages again to make absolutely sure
7789          * that any outstanding dirty pages are on disk.
7790          */
7791         count = iov_iter_count(iter);
7792         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7793                      &BTRFS_I(inode)->runtime_flags))
7794                 filemap_fdatawrite_range(inode->i_mapping, offset,
7795                                          offset + count - 1);
7796
7797         if (iov_iter_rw(iter) == WRITE) {
7798                 /*
7799                  * If the write DIO is beyond the EOF, we need update
7800                  * the isize, but it is protected by i_mutex. So we can
7801                  * not unlock the i_mutex at this case.
7802                  */
7803                 if (offset + count <= inode->i_size) {
7804                         dio_data.overwrite = 1;
7805                         inode_unlock(inode);
7806                         relock = true;
7807                 } else if (iocb->ki_flags & IOCB_NOWAIT) {
7808                         ret = -EAGAIN;
7809                         goto out;
7810                 }
7811                 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
7812                                                    offset, count);
7813                 if (ret)
7814                         goto out;
7815
7816                 /*
7817                  * We need to know how many extents we reserved so that we can
7818                  * do the accounting properly if we go over the number we
7819                  * originally calculated.  Abuse current->journal_info for this.
7820                  */
7821                 dio_data.reserve = round_up(count,
7822                                             fs_info->sectorsize);
7823                 dio_data.unsubmitted_oe_range_start = (u64)offset;
7824                 dio_data.unsubmitted_oe_range_end = (u64)offset;
7825                 current->journal_info = &dio_data;
7826                 down_read(&BTRFS_I(inode)->dio_sem);
7827         } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7828                                      &BTRFS_I(inode)->runtime_flags)) {
7829                 inode_dio_end(inode);
7830                 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7831                 wakeup = false;
7832         }
7833
7834         ret = __blockdev_direct_IO(iocb, inode,
7835                                    fs_info->fs_devices->latest_bdev,
7836                                    iter, btrfs_get_blocks_direct, NULL,
7837                                    btrfs_submit_direct, flags);
7838         if (iov_iter_rw(iter) == WRITE) {
7839                 up_read(&BTRFS_I(inode)->dio_sem);
7840                 current->journal_info = NULL;
7841                 if (ret < 0 && ret != -EIOCBQUEUED) {
7842                         if (dio_data.reserve)
7843                                 btrfs_delalloc_release_space(inode, data_reserved,
7844                                         offset, dio_data.reserve, true);
7845                         /*
7846                          * On error we might have left some ordered extents
7847                          * without submitting corresponding bios for them, so
7848                          * cleanup them up to avoid other tasks getting them
7849                          * and waiting for them to complete forever.
7850                          */
7851                         if (dio_data.unsubmitted_oe_range_start <
7852                             dio_data.unsubmitted_oe_range_end)
7853                                 __endio_write_update_ordered(inode,
7854                                         dio_data.unsubmitted_oe_range_start,
7855                                         dio_data.unsubmitted_oe_range_end -
7856                                         dio_data.unsubmitted_oe_range_start,
7857                                         false);
7858                 } else if (ret >= 0 && (size_t)ret < count)
7859                         btrfs_delalloc_release_space(inode, data_reserved,
7860                                         offset, count - (size_t)ret, true);
7861                 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
7862         }
7863 out:
7864         if (wakeup)
7865                 inode_dio_end(inode);
7866         if (relock)
7867                 inode_lock(inode);
7868
7869         extent_changeset_free(data_reserved);
7870         return ret;
7871 }
7872
7873 #define BTRFS_FIEMAP_FLAGS      (FIEMAP_FLAG_SYNC)
7874
7875 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7876                 __u64 start, __u64 len)
7877 {
7878         int     ret;
7879
7880         ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7881         if (ret)
7882                 return ret;
7883
7884         return extent_fiemap(inode, fieinfo, start, len);
7885 }
7886
7887 int btrfs_readpage(struct file *file, struct page *page)
7888 {
7889         return extent_read_full_page(page, btrfs_get_extent, 0);
7890 }
7891
7892 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7893 {
7894         struct inode *inode = page->mapping->host;
7895         int ret;
7896
7897         if (current->flags & PF_MEMALLOC) {
7898                 redirty_page_for_writepage(wbc, page);
7899                 unlock_page(page);
7900                 return 0;
7901         }
7902
7903         /*
7904          * If we are under memory pressure we will call this directly from the
7905          * VM, we need to make sure we have the inode referenced for the ordered
7906          * extent.  If not just return like we didn't do anything.
7907          */
7908         if (!igrab(inode)) {
7909                 redirty_page_for_writepage(wbc, page);
7910                 return AOP_WRITEPAGE_ACTIVATE;
7911         }
7912         ret = extent_write_full_page(page, wbc);
7913         btrfs_add_delayed_iput(inode);
7914         return ret;
7915 }
7916
7917 static int btrfs_writepages(struct address_space *mapping,
7918                             struct writeback_control *wbc)
7919 {
7920         return extent_writepages(mapping, wbc);
7921 }
7922
7923 static int
7924 btrfs_readpages(struct file *file, struct address_space *mapping,
7925                 struct list_head *pages, unsigned nr_pages)
7926 {
7927         return extent_readpages(mapping, pages, nr_pages);
7928 }
7929
7930 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7931 {
7932         int ret = try_release_extent_mapping(page, gfp_flags);
7933         if (ret == 1) {
7934                 ClearPagePrivate(page);
7935                 set_page_private(page, 0);
7936                 put_page(page);
7937         }
7938         return ret;
7939 }
7940
7941 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7942 {
7943         if (PageWriteback(page) || PageDirty(page))
7944                 return 0;
7945         return __btrfs_releasepage(page, gfp_flags);
7946 }
7947
7948 #ifdef CONFIG_MIGRATION
7949 static int btrfs_migratepage(struct address_space *mapping,
7950                              struct page *newpage, struct page *page,
7951                              enum migrate_mode mode)
7952 {
7953         int ret;
7954
7955         ret = migrate_page_move_mapping(mapping, newpage, page, 0);
7956         if (ret != MIGRATEPAGE_SUCCESS)
7957                 return ret;
7958
7959         if (page_has_private(page)) {
7960                 ClearPagePrivate(page);
7961                 get_page(newpage);
7962                 set_page_private(newpage, page_private(page));
7963                 set_page_private(page, 0);
7964                 put_page(page);
7965                 SetPagePrivate(newpage);
7966         }
7967
7968         if (PagePrivate2(page)) {
7969                 ClearPagePrivate2(page);
7970                 SetPagePrivate2(newpage);
7971         }
7972
7973         if (mode != MIGRATE_SYNC_NO_COPY)
7974                 migrate_page_copy(newpage, page);
7975         else
7976                 migrate_page_states(newpage, page);
7977         return MIGRATEPAGE_SUCCESS;
7978 }
7979 #endif
7980
7981 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7982                                  unsigned int length)
7983 {
7984         struct inode *inode = page->mapping->host;
7985         struct extent_io_tree *tree;
7986         struct btrfs_ordered_extent *ordered;
7987         struct extent_state *cached_state = NULL;
7988         u64 page_start = page_offset(page);
7989         u64 page_end = page_start + PAGE_SIZE - 1;
7990         u64 start;
7991         u64 end;
7992         int inode_evicting = inode->i_state & I_FREEING;
7993
7994         /*
7995          * we have the page locked, so new writeback can't start,
7996          * and the dirty bit won't be cleared while we are here.
7997          *
7998          * Wait for IO on this page so that we can safely clear
7999          * the PagePrivate2 bit and do ordered accounting
8000          */
8001         wait_on_page_writeback(page);
8002
8003         tree = &BTRFS_I(inode)->io_tree;
8004         if (offset) {
8005                 btrfs_releasepage(page, GFP_NOFS);
8006                 return;
8007         }
8008
8009         if (!inode_evicting)
8010                 lock_extent_bits(tree, page_start, page_end, &cached_state);
8011 again:
8012         start = page_start;
8013         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8014                                         page_end - start + 1);
8015         if (ordered) {
8016                 end = min(page_end,
8017                           ordered->file_offset + ordered->num_bytes - 1);
8018                 /*
8019                  * IO on this page will never be started, so we need
8020                  * to account for any ordered extents now
8021                  */
8022                 if (!inode_evicting)
8023                         clear_extent_bit(tree, start, end,
8024                                          EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8025                                          EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8026                                          EXTENT_DEFRAG, 1, 0, &cached_state);
8027                 /*
8028                  * whoever cleared the private bit is responsible
8029                  * for the finish_ordered_io
8030                  */
8031                 if (TestClearPagePrivate2(page)) {
8032                         struct btrfs_ordered_inode_tree *tree;
8033                         u64 new_len;
8034
8035                         tree = &BTRFS_I(inode)->ordered_tree;
8036
8037                         spin_lock_irq(&tree->lock);
8038                         set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8039                         new_len = start - ordered->file_offset;
8040                         if (new_len < ordered->truncated_len)
8041                                 ordered->truncated_len = new_len;
8042                         spin_unlock_irq(&tree->lock);
8043
8044                         if (btrfs_dec_test_ordered_pending(inode, &ordered,
8045                                                            start,
8046                                                            end - start + 1, 1))
8047                                 btrfs_finish_ordered_io(ordered);
8048                 }
8049                 btrfs_put_ordered_extent(ordered);
8050                 if (!inode_evicting) {
8051                         cached_state = NULL;
8052                         lock_extent_bits(tree, start, end,
8053                                          &cached_state);
8054                 }
8055
8056                 start = end + 1;
8057                 if (start < page_end)
8058                         goto again;
8059         }
8060
8061         /*
8062          * Qgroup reserved space handler
8063          * Page here will be either
8064          * 1) Already written to disk
8065          *    In this case, its reserved space is released from data rsv map
8066          *    and will be freed by delayed_ref handler finally.
8067          *    So even we call qgroup_free_data(), it won't decrease reserved
8068          *    space.
8069          * 2) Not written to disk
8070          *    This means the reserved space should be freed here. However,
8071          *    if a truncate invalidates the page (by clearing PageDirty)
8072          *    and the page is accounted for while allocating extent
8073          *    in btrfs_check_data_free_space() we let delayed_ref to
8074          *    free the entire extent.
8075          */
8076         if (PageDirty(page))
8077                 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8078         if (!inode_evicting) {
8079                 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8080                                  EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8081                                  EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8082                                  &cached_state);
8083
8084                 __btrfs_releasepage(page, GFP_NOFS);
8085         }
8086
8087         ClearPageChecked(page);
8088         if (PagePrivate(page)) {
8089                 ClearPagePrivate(page);
8090                 set_page_private(page, 0);
8091                 put_page(page);
8092         }
8093 }
8094
8095 /*
8096  * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8097  * called from a page fault handler when a page is first dirtied. Hence we must
8098  * be careful to check for EOF conditions here. We set the page up correctly
8099  * for a written page which means we get ENOSPC checking when writing into
8100  * holes and correct delalloc and unwritten extent mapping on filesystems that
8101  * support these features.
8102  *
8103  * We are not allowed to take the i_mutex here so we have to play games to
8104  * protect against truncate races as the page could now be beyond EOF.  Because
8105  * truncate_setsize() writes the inode size before removing pages, once we have
8106  * the page lock we can determine safely if the page is beyond EOF. If it is not
8107  * beyond EOF, then the page is guaranteed safe against truncation until we
8108  * unlock the page.
8109  */
8110 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8111 {
8112         struct page *page = vmf->page;
8113         struct inode *inode = file_inode(vmf->vma->vm_file);
8114         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8115         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8116         struct btrfs_ordered_extent *ordered;
8117         struct extent_state *cached_state = NULL;
8118         struct extent_changeset *data_reserved = NULL;
8119         char *kaddr;
8120         unsigned long zero_start;
8121         loff_t size;
8122         vm_fault_t ret;
8123         int ret2;
8124         int reserved = 0;
8125         u64 reserved_space;
8126         u64 page_start;
8127         u64 page_end;
8128         u64 end;
8129
8130         reserved_space = PAGE_SIZE;
8131
8132         sb_start_pagefault(inode->i_sb);
8133         page_start = page_offset(page);
8134         page_end = page_start + PAGE_SIZE - 1;
8135         end = page_end;
8136
8137         /*
8138          * Reserving delalloc space after obtaining the page lock can lead to
8139          * deadlock. For example, if a dirty page is locked by this function
8140          * and the call to btrfs_delalloc_reserve_space() ends up triggering
8141          * dirty page write out, then the btrfs_writepage() function could
8142          * end up waiting indefinitely to get a lock on the page currently
8143          * being processed by btrfs_page_mkwrite() function.
8144          */
8145         ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8146                                            reserved_space);
8147         if (!ret2) {
8148                 ret2 = file_update_time(vmf->vma->vm_file);
8149                 reserved = 1;
8150         }
8151         if (ret2) {
8152                 ret = vmf_error(ret2);
8153                 if (reserved)
8154                         goto out;
8155                 goto out_noreserve;
8156         }
8157
8158         ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8159 again:
8160         lock_page(page);
8161         size = i_size_read(inode);
8162
8163         if ((page->mapping != inode->i_mapping) ||
8164             (page_start >= size)) {
8165                 /* page got truncated out from underneath us */
8166                 goto out_unlock;
8167         }
8168         wait_on_page_writeback(page);
8169
8170         lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8171         set_page_extent_mapped(page);
8172
8173         /*
8174          * we can't set the delalloc bits if there are pending ordered
8175          * extents.  Drop our locks and wait for them to finish
8176          */
8177         ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8178                         PAGE_SIZE);
8179         if (ordered) {
8180                 unlock_extent_cached(io_tree, page_start, page_end,
8181                                      &cached_state);
8182                 unlock_page(page);
8183                 btrfs_start_ordered_extent(inode, ordered, 1);
8184                 btrfs_put_ordered_extent(ordered);
8185                 goto again;
8186         }
8187
8188         if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8189                 reserved_space = round_up(size - page_start,
8190                                           fs_info->sectorsize);
8191                 if (reserved_space < PAGE_SIZE) {
8192                         end = page_start + reserved_space - 1;
8193                         btrfs_delalloc_release_space(inode, data_reserved,
8194                                         page_start, PAGE_SIZE - reserved_space,
8195                                         true);
8196                 }
8197         }
8198
8199         /*
8200          * page_mkwrite gets called when the page is firstly dirtied after it's
8201          * faulted in, but write(2) could also dirty a page and set delalloc
8202          * bits, thus in this case for space account reason, we still need to
8203          * clear any delalloc bits within this page range since we have to
8204          * reserve data&meta space before lock_page() (see above comments).
8205          */
8206         clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8207                           EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8208                           EXTENT_DEFRAG, 0, 0, &cached_state);
8209
8210         ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8211                                         &cached_state);
8212         if (ret2) {
8213                 unlock_extent_cached(io_tree, page_start, page_end,
8214                                      &cached_state);
8215                 ret = VM_FAULT_SIGBUS;
8216                 goto out_unlock;
8217         }
8218
8219         /* page is wholly or partially inside EOF */
8220         if (page_start + PAGE_SIZE > size)
8221                 zero_start = offset_in_page(size);
8222         else
8223                 zero_start = PAGE_SIZE;
8224
8225         if (zero_start != PAGE_SIZE) {
8226                 kaddr = kmap(page);
8227                 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8228                 flush_dcache_page(page);
8229                 kunmap(page);
8230         }
8231         ClearPageChecked(page);
8232         set_page_dirty(page);
8233         SetPageUptodate(page);
8234
8235         BTRFS_I(inode)->last_trans = fs_info->generation;
8236         BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8237         BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8238
8239         unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8240
8241         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8242         sb_end_pagefault(inode->i_sb);
8243         extent_changeset_free(data_reserved);
8244         return VM_FAULT_LOCKED;
8245
8246 out_unlock:
8247         unlock_page(page);
8248 out:
8249         btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8250         btrfs_delalloc_release_space(inode, data_reserved, page_start,
8251                                      reserved_space, (ret != 0));
8252 out_noreserve:
8253         sb_end_pagefault(inode->i_sb);
8254         extent_changeset_free(data_reserved);
8255         return ret;
8256 }
8257
8258 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8259 {
8260         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8261         struct btrfs_root *root = BTRFS_I(inode)->root;
8262         struct btrfs_block_rsv *rsv;
8263         int ret;
8264         struct btrfs_trans_handle *trans;
8265         u64 mask = fs_info->sectorsize - 1;
8266         u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8267
8268         if (!skip_writeback) {
8269                 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8270                                                (u64)-1);
8271                 if (ret)
8272                         return ret;
8273         }
8274
8275         /*
8276          * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
8277          * things going on here:
8278          *
8279          * 1) We need to reserve space to update our inode.
8280          *
8281          * 2) We need to have something to cache all the space that is going to
8282          * be free'd up by the truncate operation, but also have some slack
8283          * space reserved in case it uses space during the truncate (thank you
8284          * very much snapshotting).
8285          *
8286          * And we need these to be separate.  The fact is we can use a lot of
8287          * space doing the truncate, and we have no earthly idea how much space
8288          * we will use, so we need the truncate reservation to be separate so it
8289          * doesn't end up using space reserved for updating the inode.  We also
8290          * need to be able to stop the transaction and start a new one, which
8291          * means we need to be able to update the inode several times, and we
8292          * have no idea of knowing how many times that will be, so we can't just
8293          * reserve 1 item for the entirety of the operation, so that has to be
8294          * done separately as well.
8295          *
8296          * So that leaves us with
8297          *
8298          * 1) rsv - for the truncate reservation, which we will steal from the
8299          * transaction reservation.
8300          * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8301          * updating the inode.
8302          */
8303         rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8304         if (!rsv)
8305                 return -ENOMEM;
8306         rsv->size = min_size;
8307         rsv->failfast = 1;
8308
8309         /*
8310          * 1 for the truncate slack space
8311          * 1 for updating the inode.
8312          */
8313         trans = btrfs_start_transaction(root, 2);
8314         if (IS_ERR(trans)) {
8315                 ret = PTR_ERR(trans);
8316                 goto out;
8317         }
8318
8319         /* Migrate the slack space for the truncate to our reserve */
8320         ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8321                                       min_size, false);
8322         BUG_ON(ret);
8323
8324         /*
8325          * So if we truncate and then write and fsync we normally would just
8326          * write the extents that changed, which is a problem if we need to
8327          * first truncate that entire inode.  So set this flag so we write out
8328          * all of the extents in the inode to the sync log so we're completely
8329          * safe.
8330          */
8331         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8332         trans->block_rsv = rsv;
8333
8334         while (1) {
8335                 ret = btrfs_truncate_inode_items(trans, root, inode,
8336                                                  inode->i_size,
8337                                                  BTRFS_EXTENT_DATA_KEY);
8338                 trans->block_rsv = &fs_info->trans_block_rsv;
8339                 if (ret != -ENOSPC && ret != -EAGAIN)
8340                         break;
8341
8342                 ret = btrfs_update_inode(trans, root, inode);
8343                 if (ret)
8344                         break;
8345
8346                 btrfs_end_transaction(trans);
8347                 btrfs_btree_balance_dirty(fs_info);
8348
8349                 trans = btrfs_start_transaction(root, 2);
8350                 if (IS_ERR(trans)) {
8351                         ret = PTR_ERR(trans);
8352                         trans = NULL;
8353                         break;
8354                 }
8355
8356                 btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
8357                 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8358                                               rsv, min_size, false);
8359                 BUG_ON(ret);    /* shouldn't happen */
8360                 trans->block_rsv = rsv;
8361         }
8362
8363         /*
8364          * We can't call btrfs_truncate_block inside a trans handle as we could
8365          * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8366          * we've truncated everything except the last little bit, and can do
8367          * btrfs_truncate_block and then update the disk_i_size.
8368          */
8369         if (ret == NEED_TRUNCATE_BLOCK) {
8370                 btrfs_end_transaction(trans);
8371                 btrfs_btree_balance_dirty(fs_info);
8372
8373                 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8374                 if (ret)
8375                         goto out;
8376                 trans = btrfs_start_transaction(root, 1);
8377                 if (IS_ERR(trans)) {
8378                         ret = PTR_ERR(trans);
8379                         goto out;
8380                 }
8381                 btrfs_inode_safe_disk_i_size_write(inode, 0);
8382         }
8383
8384         if (trans) {
8385                 int ret2;
8386
8387                 trans->block_rsv = &fs_info->trans_block_rsv;
8388                 ret2 = btrfs_update_inode(trans, root, inode);
8389                 if (ret2 && !ret)
8390                         ret = ret2;
8391
8392                 ret2 = btrfs_end_transaction(trans);
8393                 if (ret2 && !ret)
8394                         ret = ret2;
8395                 btrfs_btree_balance_dirty(fs_info);
8396         }
8397 out:
8398         btrfs_free_block_rsv(fs_info, rsv);
8399
8400         return ret;
8401 }
8402
8403 /*
8404  * create a new subvolume directory/inode (helper for the ioctl).
8405  */
8406 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8407                              struct btrfs_root *new_root,
8408                              struct btrfs_root *parent_root,
8409                              u64 new_dirid)
8410 {
8411         struct inode *inode;
8412         int err;
8413         u64 index = 0;
8414
8415         inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8416                                 new_dirid, new_dirid,
8417                                 S_IFDIR | (~current_umask() & S_IRWXUGO),
8418                                 &index);
8419         if (IS_ERR(inode))
8420                 return PTR_ERR(inode);
8421         inode->i_op = &btrfs_dir_inode_operations;
8422         inode->i_fop = &btrfs_dir_file_operations;
8423
8424         set_nlink(inode, 1);
8425         btrfs_i_size_write(BTRFS_I(inode), 0);
8426         unlock_new_inode(inode);
8427
8428         err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8429         if (err)
8430                 btrfs_err(new_root->fs_info,
8431                           "error inheriting subvolume %llu properties: %d",
8432                           new_root->root_key.objectid, err);
8433
8434         err = btrfs_update_inode(trans, new_root, inode);
8435
8436         iput(inode);
8437         return err;
8438 }
8439
8440 struct inode *btrfs_alloc_inode(struct super_block *sb)
8441 {
8442         struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8443         struct btrfs_inode *ei;
8444         struct inode *inode;
8445
8446         ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8447         if (!ei)
8448                 return NULL;
8449
8450         ei->root = NULL;
8451         ei->generation = 0;
8452         ei->last_trans = 0;
8453         ei->last_sub_trans = 0;
8454         ei->logged_trans = 0;
8455         ei->delalloc_bytes = 0;
8456         ei->new_delalloc_bytes = 0;
8457         ei->defrag_bytes = 0;
8458         ei->disk_i_size = 0;
8459         ei->flags = 0;
8460         ei->csum_bytes = 0;
8461         ei->index_cnt = (u64)-1;
8462         ei->dir_index = 0;
8463         ei->last_unlink_trans = 0;
8464         ei->last_log_commit = 0;
8465
8466         spin_lock_init(&ei->lock);
8467         ei->outstanding_extents = 0;
8468         if (sb->s_magic != BTRFS_TEST_MAGIC)
8469                 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8470                                               BTRFS_BLOCK_RSV_DELALLOC);
8471         ei->runtime_flags = 0;
8472         ei->prop_compress = BTRFS_COMPRESS_NONE;
8473         ei->defrag_compress = BTRFS_COMPRESS_NONE;
8474
8475         ei->delayed_node = NULL;
8476
8477         ei->i_otime.tv_sec = 0;
8478         ei->i_otime.tv_nsec = 0;
8479
8480         inode = &ei->vfs_inode;
8481         extent_map_tree_init(&ei->extent_tree);
8482         extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8483         extent_io_tree_init(fs_info, &ei->io_failure_tree,
8484                             IO_TREE_INODE_IO_FAILURE, inode);
8485         extent_io_tree_init(fs_info, &ei->file_extent_tree,
8486                             IO_TREE_INODE_FILE_EXTENT, inode);
8487         ei->io_tree.track_uptodate = true;
8488         ei->io_failure_tree.track_uptodate = true;
8489         atomic_set(&ei->sync_writers, 0);
8490         mutex_init(&ei->log_mutex);
8491         btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8492         INIT_LIST_HEAD(&ei->delalloc_inodes);
8493         INIT_LIST_HEAD(&ei->delayed_iput);
8494         RB_CLEAR_NODE(&ei->rb_node);
8495         init_rwsem(&ei->dio_sem);
8496
8497         return inode;
8498 }
8499
8500 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8501 void btrfs_test_destroy_inode(struct inode *inode)
8502 {
8503         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8504         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8505 }
8506 #endif
8507
8508 void btrfs_free_inode(struct inode *inode)
8509 {
8510         kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8511 }
8512
8513 void btrfs_destroy_inode(struct inode *inode)
8514 {
8515         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8516         struct btrfs_ordered_extent *ordered;
8517         struct btrfs_root *root = BTRFS_I(inode)->root;
8518
8519         WARN_ON(!hlist_empty(&inode->i_dentry));
8520         WARN_ON(inode->i_data.nrpages);
8521         WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8522         WARN_ON(BTRFS_I(inode)->block_rsv.size);
8523         WARN_ON(BTRFS_I(inode)->outstanding_extents);
8524         WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8525         WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8526         WARN_ON(BTRFS_I(inode)->csum_bytes);
8527         WARN_ON(BTRFS_I(inode)->defrag_bytes);
8528
8529         /*
8530          * This can happen where we create an inode, but somebody else also
8531          * created the same inode and we need to destroy the one we already
8532          * created.
8533          */
8534         if (!root)
8535                 return;
8536
8537         while (1) {
8538                 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8539                 if (!ordered)
8540                         break;
8541                 else {
8542                         btrfs_err(fs_info,
8543                                   "found ordered extent %llu %llu on inode cleanup",
8544                                   ordered->file_offset, ordered->num_bytes);
8545                         btrfs_remove_ordered_extent(inode, ordered);
8546                         btrfs_put_ordered_extent(ordered);
8547                         btrfs_put_ordered_extent(ordered);
8548                 }
8549         }
8550         btrfs_qgroup_check_reserved_leak(inode);
8551         inode_tree_del(inode);
8552         btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8553         btrfs_inode_clear_file_extent_range(BTRFS_I(inode), 0, (u64)-1);
8554         btrfs_put_root(BTRFS_I(inode)->root);
8555 }
8556
8557 int btrfs_drop_inode(struct inode *inode)
8558 {
8559         struct btrfs_root *root = BTRFS_I(inode)->root;
8560
8561         if (root == NULL)
8562                 return 1;
8563
8564         /* the snap/subvol tree is on deleting */
8565         if (btrfs_root_refs(&root->root_item) == 0)
8566                 return 1;
8567         else
8568                 return generic_drop_inode(inode);
8569 }
8570
8571 static void init_once(void *foo)
8572 {
8573         struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8574
8575         inode_init_once(&ei->vfs_inode);
8576 }
8577
8578 void __cold btrfs_destroy_cachep(void)
8579 {
8580         /*
8581          * Make sure all delayed rcu free inodes are flushed before we
8582          * destroy cache.
8583          */
8584         rcu_barrier();
8585         kmem_cache_destroy(btrfs_inode_cachep);
8586         kmem_cache_destroy(btrfs_trans_handle_cachep);
8587         kmem_cache_destroy(btrfs_path_cachep);
8588         kmem_cache_destroy(btrfs_free_space_cachep);
8589         kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8590 }
8591
8592 int __init btrfs_init_cachep(void)
8593 {
8594         btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8595                         sizeof(struct btrfs_inode), 0,
8596                         SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8597                         init_once);
8598         if (!btrfs_inode_cachep)
8599                 goto fail;
8600
8601         btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8602                         sizeof(struct btrfs_trans_handle), 0,
8603                         SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8604         if (!btrfs_trans_handle_cachep)
8605                 goto fail;
8606
8607         btrfs_path_cachep = kmem_cache_create("btrfs_path",
8608                         sizeof(struct btrfs_path), 0,
8609                         SLAB_MEM_SPREAD, NULL);
8610         if (!btrfs_path_cachep)
8611                 goto fail;
8612
8613         btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8614                         sizeof(struct btrfs_free_space), 0,
8615                         SLAB_MEM_SPREAD, NULL);
8616         if (!btrfs_free_space_cachep)
8617                 goto fail;
8618
8619         btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8620                                                         PAGE_SIZE, PAGE_SIZE,
8621                                                         SLAB_RED_ZONE, NULL);
8622         if (!btrfs_free_space_bitmap_cachep)
8623                 goto fail;
8624
8625         return 0;
8626 fail:
8627         btrfs_destroy_cachep();
8628         return -ENOMEM;
8629 }
8630
8631 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8632                          u32 request_mask, unsigned int flags)
8633 {
8634         u64 delalloc_bytes;
8635         struct inode *inode = d_inode(path->dentry);
8636         u32 blocksize = inode->i_sb->s_blocksize;
8637         u32 bi_flags = BTRFS_I(inode)->flags;
8638
8639         stat->result_mask |= STATX_BTIME;
8640         stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8641         stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8642         if (bi_flags & BTRFS_INODE_APPEND)
8643                 stat->attributes |= STATX_ATTR_APPEND;
8644         if (bi_flags & BTRFS_INODE_COMPRESS)
8645                 stat->attributes |= STATX_ATTR_COMPRESSED;
8646         if (bi_flags & BTRFS_INODE_IMMUTABLE)
8647                 stat->attributes |= STATX_ATTR_IMMUTABLE;
8648         if (bi_flags & BTRFS_INODE_NODUMP)
8649                 stat->attributes |= STATX_ATTR_NODUMP;
8650
8651         stat->attributes_mask |= (STATX_ATTR_APPEND |
8652                                   STATX_ATTR_COMPRESSED |
8653                                   STATX_ATTR_IMMUTABLE |
8654                                   STATX_ATTR_NODUMP);
8655
8656         generic_fillattr(inode, stat);
8657         stat->dev = BTRFS_I(inode)->root->anon_dev;
8658
8659         spin_lock(&BTRFS_I(inode)->lock);
8660         delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8661         spin_unlock(&BTRFS_I(inode)->lock);
8662         stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8663                         ALIGN(delalloc_bytes, blocksize)) >> 9;
8664         return 0;
8665 }
8666
8667 static int btrfs_rename_exchange(struct inode *old_dir,
8668                               struct dentry *old_dentry,
8669                               struct inode *new_dir,
8670                               struct dentry *new_dentry)
8671 {
8672         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8673         struct btrfs_trans_handle *trans;
8674         struct btrfs_root *root = BTRFS_I(old_dir)->root;
8675         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8676         struct inode *new_inode = new_dentry->d_inode;
8677         struct inode *old_inode = old_dentry->d_inode;
8678         struct timespec64 ctime = current_time(old_inode);
8679         struct dentry *parent;
8680         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8681         u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8682         u64 old_idx = 0;
8683         u64 new_idx = 0;
8684         int ret;
8685         bool root_log_pinned = false;
8686         bool dest_log_pinned = false;
8687         struct btrfs_log_ctx ctx_root;
8688         struct btrfs_log_ctx ctx_dest;
8689         bool sync_log_root = false;
8690         bool sync_log_dest = false;
8691         bool commit_transaction = false;
8692
8693         /* we only allow rename subvolume link between subvolumes */
8694         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8695                 return -EXDEV;
8696
8697         btrfs_init_log_ctx(&ctx_root, old_inode);
8698         btrfs_init_log_ctx(&ctx_dest, new_inode);
8699
8700         /* close the race window with snapshot create/destroy ioctl */
8701         if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8702             new_ino == BTRFS_FIRST_FREE_OBJECTID)
8703                 down_read(&fs_info->subvol_sem);
8704
8705         /*
8706          * We want to reserve the absolute worst case amount of items.  So if
8707          * both inodes are subvols and we need to unlink them then that would
8708          * require 4 item modifications, but if they are both normal inodes it
8709          * would require 5 item modifications, so we'll assume their normal
8710          * inodes.  So 5 * 2 is 10, plus 2 for the new links, so 12 total items
8711          * should cover the worst case number of items we'll modify.
8712          */
8713         trans = btrfs_start_transaction(root, 12);
8714         if (IS_ERR(trans)) {
8715                 ret = PTR_ERR(trans);
8716                 goto out_notrans;
8717         }
8718
8719         if (dest != root)
8720                 btrfs_record_root_in_trans(trans, dest);
8721
8722         /*
8723          * We need to find a free sequence number both in the source and
8724          * in the destination directory for the exchange.
8725          */
8726         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8727         if (ret)
8728                 goto out_fail;
8729         ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8730         if (ret)
8731                 goto out_fail;
8732
8733         BTRFS_I(old_inode)->dir_index = 0ULL;
8734         BTRFS_I(new_inode)->dir_index = 0ULL;
8735
8736         /* Reference for the source. */
8737         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8738                 /* force full log commit if subvolume involved. */
8739                 btrfs_set_log_full_commit(trans);
8740         } else {
8741                 btrfs_pin_log_trans(root);
8742                 root_log_pinned = true;
8743                 ret = btrfs_insert_inode_ref(trans, dest,
8744                                              new_dentry->d_name.name,
8745                                              new_dentry->d_name.len,
8746                                              old_ino,
8747                                              btrfs_ino(BTRFS_I(new_dir)),
8748                                              old_idx);
8749                 if (ret)
8750                         goto out_fail;
8751         }
8752
8753         /* And now for the dest. */
8754         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8755                 /* force full log commit if subvolume involved. */
8756                 btrfs_set_log_full_commit(trans);
8757         } else {
8758                 btrfs_pin_log_trans(dest);
8759                 dest_log_pinned = true;
8760                 ret = btrfs_insert_inode_ref(trans, root,
8761                                              old_dentry->d_name.name,
8762                                              old_dentry->d_name.len,
8763                                              new_ino,
8764                                              btrfs_ino(BTRFS_I(old_dir)),
8765                                              new_idx);
8766                 if (ret)
8767                         goto out_fail;
8768         }
8769
8770         /* Update inode version and ctime/mtime. */
8771         inode_inc_iversion(old_dir);
8772         inode_inc_iversion(new_dir);
8773         inode_inc_iversion(old_inode);
8774         inode_inc_iversion(new_inode);
8775         old_dir->i_ctime = old_dir->i_mtime = ctime;
8776         new_dir->i_ctime = new_dir->i_mtime = ctime;
8777         old_inode->i_ctime = ctime;
8778         new_inode->i_ctime = ctime;
8779
8780         if (old_dentry->d_parent != new_dentry->d_parent) {
8781                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8782                                 BTRFS_I(old_inode), 1);
8783                 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8784                                 BTRFS_I(new_inode), 1);
8785         }
8786
8787         /* src is a subvolume */
8788         if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8789                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
8790         } else { /* src is an inode */
8791                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
8792                                            BTRFS_I(old_dentry->d_inode),
8793                                            old_dentry->d_name.name,
8794                                            old_dentry->d_name.len);
8795                 if (!ret)
8796                         ret = btrfs_update_inode(trans, root, old_inode);
8797         }
8798         if (ret) {
8799                 btrfs_abort_transaction(trans, ret);
8800                 goto out_fail;
8801         }
8802
8803         /* dest is a subvolume */
8804         if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8805                 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
8806         } else { /* dest is an inode */
8807                 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
8808                                            BTRFS_I(new_dentry->d_inode),
8809                                            new_dentry->d_name.name,
8810                                            new_dentry->d_name.len);
8811                 if (!ret)
8812                         ret = btrfs_update_inode(trans, dest, new_inode);
8813         }
8814         if (ret) {
8815                 btrfs_abort_transaction(trans, ret);
8816                 goto out_fail;
8817         }
8818
8819         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8820                              new_dentry->d_name.name,
8821                              new_dentry->d_name.len, 0, old_idx);
8822         if (ret) {
8823                 btrfs_abort_transaction(trans, ret);
8824                 goto out_fail;
8825         }
8826
8827         ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8828                              old_dentry->d_name.name,
8829                              old_dentry->d_name.len, 0, new_idx);
8830         if (ret) {
8831                 btrfs_abort_transaction(trans, ret);
8832                 goto out_fail;
8833         }
8834
8835         if (old_inode->i_nlink == 1)
8836                 BTRFS_I(old_inode)->dir_index = old_idx;
8837         if (new_inode->i_nlink == 1)
8838                 BTRFS_I(new_inode)->dir_index = new_idx;
8839
8840         if (root_log_pinned) {
8841                 parent = new_dentry->d_parent;
8842                 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
8843                                          BTRFS_I(old_dir), parent,
8844                                          false, &ctx_root);
8845                 if (ret == BTRFS_NEED_LOG_SYNC)
8846                         sync_log_root = true;
8847                 else if (ret == BTRFS_NEED_TRANS_COMMIT)
8848                         commit_transaction = true;
8849                 ret = 0;
8850                 btrfs_end_log_trans(root);
8851                 root_log_pinned = false;
8852         }
8853         if (dest_log_pinned) {
8854                 if (!commit_transaction) {
8855                         parent = old_dentry->d_parent;
8856                         ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
8857                                                  BTRFS_I(new_dir), parent,
8858                                                  false, &ctx_dest);
8859                         if (ret == BTRFS_NEED_LOG_SYNC)
8860                                 sync_log_dest = true;
8861                         else if (ret == BTRFS_NEED_TRANS_COMMIT)
8862                                 commit_transaction = true;
8863                         ret = 0;
8864                 }
8865                 btrfs_end_log_trans(dest);
8866                 dest_log_pinned = false;
8867         }
8868 out_fail:
8869         /*
8870          * If we have pinned a log and an error happened, we unpin tasks
8871          * trying to sync the log and force them to fallback to a transaction
8872          * commit if the log currently contains any of the inodes involved in
8873          * this rename operation (to ensure we do not persist a log with an
8874          * inconsistent state for any of these inodes or leading to any
8875          * inconsistencies when replayed). If the transaction was aborted, the
8876          * abortion reason is propagated to userspace when attempting to commit
8877          * the transaction. If the log does not contain any of these inodes, we
8878          * allow the tasks to sync it.
8879          */
8880         if (ret && (root_log_pinned || dest_log_pinned)) {
8881                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
8882                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
8883                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
8884                     (new_inode &&
8885                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
8886                         btrfs_set_log_full_commit(trans);
8887
8888                 if (root_log_pinned) {
8889                         btrfs_end_log_trans(root);
8890                         root_log_pinned = false;
8891                 }
8892                 if (dest_log_pinned) {
8893                         btrfs_end_log_trans(dest);
8894                         dest_log_pinned = false;
8895                 }
8896         }
8897         if (!ret && sync_log_root && !commit_transaction) {
8898                 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
8899                                      &ctx_root);
8900                 if (ret)
8901                         commit_transaction = true;
8902         }
8903         if (!ret && sync_log_dest && !commit_transaction) {
8904                 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
8905                                      &ctx_dest);
8906                 if (ret)
8907                         commit_transaction = true;
8908         }
8909         if (commit_transaction) {
8910                 /*
8911                  * We may have set commit_transaction when logging the new name
8912                  * in the destination root, in which case we left the source
8913                  * root context in the list of log contextes. So make sure we
8914                  * remove it to avoid invalid memory accesses, since the context
8915                  * was allocated in our stack frame.
8916                  */
8917                 if (sync_log_root) {
8918                         mutex_lock(&root->log_mutex);
8919                         list_del_init(&ctx_root.list);
8920                         mutex_unlock(&root->log_mutex);
8921                 }
8922                 ret = btrfs_commit_transaction(trans);
8923         } else {
8924                 int ret2;
8925
8926                 ret2 = btrfs_end_transaction(trans);
8927                 ret = ret ? ret : ret2;
8928         }
8929 out_notrans:
8930         if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8931             old_ino == BTRFS_FIRST_FREE_OBJECTID)
8932                 up_read(&fs_info->subvol_sem);
8933
8934         ASSERT(list_empty(&ctx_root.list));
8935         ASSERT(list_empty(&ctx_dest.list));
8936
8937         return ret;
8938 }
8939
8940 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
8941                                      struct btrfs_root *root,
8942                                      struct inode *dir,
8943                                      struct dentry *dentry)
8944 {
8945         int ret;
8946         struct inode *inode;
8947         u64 objectid;
8948         u64 index;
8949
8950         ret = btrfs_find_free_ino(root, &objectid);
8951         if (ret)
8952                 return ret;
8953
8954         inode = btrfs_new_inode(trans, root, dir,
8955                                 dentry->d_name.name,
8956                                 dentry->d_name.len,
8957                                 btrfs_ino(BTRFS_I(dir)),
8958                                 objectid,
8959                                 S_IFCHR | WHITEOUT_MODE,
8960                                 &index);
8961
8962         if (IS_ERR(inode)) {
8963                 ret = PTR_ERR(inode);
8964                 return ret;
8965         }
8966
8967         inode->i_op = &btrfs_special_inode_operations;
8968         init_special_inode(inode, inode->i_mode,
8969                 WHITEOUT_DEV);
8970
8971         ret = btrfs_init_inode_security(trans, inode, dir,
8972                                 &dentry->d_name);
8973         if (ret)
8974                 goto out;
8975
8976         ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
8977                                 BTRFS_I(inode), 0, index);
8978         if (ret)
8979                 goto out;
8980
8981         ret = btrfs_update_inode(trans, root, inode);
8982 out:
8983         unlock_new_inode(inode);
8984         if (ret)
8985                 inode_dec_link_count(inode);
8986         iput(inode);
8987
8988         return ret;
8989 }
8990
8991 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8992                            struct inode *new_dir, struct dentry *new_dentry,
8993                            unsigned int flags)
8994 {
8995         struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8996         struct btrfs_trans_handle *trans;
8997         unsigned int trans_num_items;
8998         struct btrfs_root *root = BTRFS_I(old_dir)->root;
8999         struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9000         struct inode *new_inode = d_inode(new_dentry);
9001         struct inode *old_inode = d_inode(old_dentry);
9002         u64 index = 0;
9003         int ret;
9004         u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9005         bool log_pinned = false;
9006         struct btrfs_log_ctx ctx;
9007         bool sync_log = false;
9008         bool commit_transaction = false;
9009
9010         if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9011                 return -EPERM;
9012
9013         /* we only allow rename subvolume link between subvolumes */
9014         if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9015                 return -EXDEV;
9016
9017         if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9018             (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9019                 return -ENOTEMPTY;
9020
9021         if (S_ISDIR(old_inode->i_mode) && new_inode &&
9022             new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9023                 return -ENOTEMPTY;
9024
9025
9026         /* check for collisions, even if the  name isn't there */
9027         ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9028                              new_dentry->d_name.name,
9029                              new_dentry->d_name.len);
9030
9031         if (ret) {
9032                 if (ret == -EEXIST) {
9033                         /* we shouldn't get
9034                          * eexist without a new_inode */
9035                         if (WARN_ON(!new_inode)) {
9036                                 return ret;
9037                         }
9038                 } else {
9039                         /* maybe -EOVERFLOW */
9040                         return ret;
9041                 }
9042         }
9043         ret = 0;
9044
9045         /*
9046          * we're using rename to replace one file with another.  Start IO on it
9047          * now so  we don't add too much work to the end of the transaction
9048          */
9049         if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9050                 filemap_flush(old_inode->i_mapping);
9051
9052         /* close the racy window with snapshot create/destroy ioctl */
9053         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9054                 down_read(&fs_info->subvol_sem);
9055         /*
9056          * We want to reserve the absolute worst case amount of items.  So if
9057          * both inodes are subvols and we need to unlink them then that would
9058          * require 4 item modifications, but if they are both normal inodes it
9059          * would require 5 item modifications, so we'll assume they are normal
9060          * inodes.  So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9061          * should cover the worst case number of items we'll modify.
9062          * If our rename has the whiteout flag, we need more 5 units for the
9063          * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9064          * when selinux is enabled).
9065          */
9066         trans_num_items = 11;
9067         if (flags & RENAME_WHITEOUT)
9068                 trans_num_items += 5;
9069         trans = btrfs_start_transaction(root, trans_num_items);
9070         if (IS_ERR(trans)) {
9071                 ret = PTR_ERR(trans);
9072                 goto out_notrans;
9073         }
9074
9075         if (dest != root)
9076                 btrfs_record_root_in_trans(trans, dest);
9077
9078         ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9079         if (ret)
9080                 goto out_fail;
9081
9082         BTRFS_I(old_inode)->dir_index = 0ULL;
9083         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9084                 /* force full log commit if subvolume involved. */
9085                 btrfs_set_log_full_commit(trans);
9086         } else {
9087                 btrfs_pin_log_trans(root);
9088                 log_pinned = true;
9089                 ret = btrfs_insert_inode_ref(trans, dest,
9090                                              new_dentry->d_name.name,
9091                                              new_dentry->d_name.len,
9092                                              old_ino,
9093                                              btrfs_ino(BTRFS_I(new_dir)), index);
9094                 if (ret)
9095                         goto out_fail;
9096         }
9097
9098         inode_inc_iversion(old_dir);
9099         inode_inc_iversion(new_dir);
9100         inode_inc_iversion(old_inode);
9101         old_dir->i_ctime = old_dir->i_mtime =
9102         new_dir->i_ctime = new_dir->i_mtime =
9103         old_inode->i_ctime = current_time(old_dir);
9104
9105         if (old_dentry->d_parent != new_dentry->d_parent)
9106                 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9107                                 BTRFS_I(old_inode), 1);
9108
9109         if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9110                 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9111         } else {
9112                 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9113                                         BTRFS_I(d_inode(old_dentry)),
9114                                         old_dentry->d_name.name,
9115                                         old_dentry->d_name.len);
9116                 if (!ret)
9117                         ret = btrfs_update_inode(trans, root, old_inode);
9118         }
9119         if (ret) {
9120                 btrfs_abort_transaction(trans, ret);
9121                 goto out_fail;
9122         }
9123
9124         if (new_inode) {
9125                 inode_inc_iversion(new_inode);
9126                 new_inode->i_ctime = current_time(new_inode);
9127                 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9128                              BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9129                         ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9130                         BUG_ON(new_inode->i_nlink == 0);
9131                 } else {
9132                         ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9133                                                  BTRFS_I(d_inode(new_dentry)),
9134                                                  new_dentry->d_name.name,
9135                                                  new_dentry->d_name.len);
9136                 }
9137                 if (!ret && new_inode->i_nlink == 0)
9138                         ret = btrfs_orphan_add(trans,
9139                                         BTRFS_I(d_inode(new_dentry)));
9140                 if (ret) {
9141                         btrfs_abort_transaction(trans, ret);
9142                         goto out_fail;
9143                 }
9144         }
9145
9146         ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9147                              new_dentry->d_name.name,
9148                              new_dentry->d_name.len, 0, index);
9149         if (ret) {
9150                 btrfs_abort_transaction(trans, ret);
9151                 goto out_fail;
9152         }
9153
9154         if (old_inode->i_nlink == 1)
9155                 BTRFS_I(old_inode)->dir_index = index;
9156
9157         if (log_pinned) {
9158                 struct dentry *parent = new_dentry->d_parent;
9159
9160                 btrfs_init_log_ctx(&ctx, old_inode);
9161                 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9162                                          BTRFS_I(old_dir), parent,
9163                                          false, &ctx);
9164                 if (ret == BTRFS_NEED_LOG_SYNC)
9165                         sync_log = true;
9166                 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9167                         commit_transaction = true;
9168                 ret = 0;
9169                 btrfs_end_log_trans(root);
9170                 log_pinned = false;
9171         }
9172
9173         if (flags & RENAME_WHITEOUT) {
9174                 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9175                                                 old_dentry);
9176
9177                 if (ret) {
9178                         btrfs_abort_transaction(trans, ret);
9179                         goto out_fail;
9180                 }
9181         }
9182 out_fail:
9183         /*
9184          * If we have pinned the log and an error happened, we unpin tasks
9185          * trying to sync the log and force them to fallback to a transaction
9186          * commit if the log currently contains any of the inodes involved in
9187          * this rename operation (to ensure we do not persist a log with an
9188          * inconsistent state for any of these inodes or leading to any
9189          * inconsistencies when replayed). If the transaction was aborted, the
9190          * abortion reason is propagated to userspace when attempting to commit
9191          * the transaction. If the log does not contain any of these inodes, we
9192          * allow the tasks to sync it.
9193          */
9194         if (ret && log_pinned) {
9195                 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9196                     btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9197                     btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9198                     (new_inode &&
9199                      btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9200                         btrfs_set_log_full_commit(trans);
9201
9202                 btrfs_end_log_trans(root);
9203                 log_pinned = false;
9204         }
9205         if (!ret && sync_log) {
9206                 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9207                 if (ret)
9208                         commit_transaction = true;
9209         } else if (sync_log) {
9210                 mutex_lock(&root->log_mutex);
9211                 list_del(&ctx.list);
9212                 mutex_unlock(&root->log_mutex);
9213         }
9214         if (commit_transaction) {
9215                 ret = btrfs_commit_transaction(trans);
9216         } else {
9217                 int ret2;
9218
9219                 ret2 = btrfs_end_transaction(trans);
9220                 ret = ret ? ret : ret2;
9221         }
9222 out_notrans:
9223         if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9224                 up_read(&fs_info->subvol_sem);
9225
9226         return ret;
9227 }
9228
9229 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9230                          struct inode *new_dir, struct dentry *new_dentry,
9231                          unsigned int flags)
9232 {
9233         if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9234                 return -EINVAL;
9235
9236         if (flags & RENAME_EXCHANGE)
9237                 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9238                                           new_dentry);
9239
9240         return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9241 }
9242
9243 struct btrfs_delalloc_work {
9244         struct inode *inode;
9245         struct completion completion;
9246         struct list_head list;
9247         struct btrfs_work work;
9248 };
9249
9250 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9251 {
9252         struct btrfs_delalloc_work *delalloc_work;
9253         struct inode *inode;
9254
9255         delalloc_work = container_of(work, struct btrfs_delalloc_work,
9256                                      work);
9257         inode = delalloc_work->inode;
9258         filemap_flush(inode->i_mapping);
9259         if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9260                                 &BTRFS_I(inode)->runtime_flags))
9261                 filemap_flush(inode->i_mapping);
9262
9263         iput(inode);
9264         complete(&delalloc_work->completion);
9265 }
9266
9267 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9268 {
9269         struct btrfs_delalloc_work *work;
9270
9271         work = kmalloc(sizeof(*work), GFP_NOFS);
9272         if (!work)
9273                 return NULL;
9274
9275         init_completion(&work->completion);
9276         INIT_LIST_HEAD(&work->list);
9277         work->inode = inode;
9278         btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9279
9280         return work;
9281 }
9282
9283 /*
9284  * some fairly slow code that needs optimization. This walks the list
9285  * of all the inodes with pending delalloc and forces them to disk.
9286  */
9287 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9288 {
9289         struct btrfs_inode *binode;
9290         struct inode *inode;
9291         struct btrfs_delalloc_work *work, *next;
9292         struct list_head works;
9293         struct list_head splice;
9294         int ret = 0;
9295
9296         INIT_LIST_HEAD(&works);
9297         INIT_LIST_HEAD(&splice);
9298
9299         mutex_lock(&root->delalloc_mutex);
9300         spin_lock(&root->delalloc_lock);
9301         list_splice_init(&root->delalloc_inodes, &splice);
9302         while (!list_empty(&splice)) {
9303                 binode = list_entry(splice.next, struct btrfs_inode,
9304                                     delalloc_inodes);
9305
9306                 list_move_tail(&binode->delalloc_inodes,
9307                                &root->delalloc_inodes);
9308                 inode = igrab(&binode->vfs_inode);
9309                 if (!inode) {
9310                         cond_resched_lock(&root->delalloc_lock);
9311                         continue;
9312                 }
9313                 spin_unlock(&root->delalloc_lock);
9314
9315                 if (snapshot)
9316                         set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9317                                 &binode->runtime_flags);
9318                 work = btrfs_alloc_delalloc_work(inode);
9319                 if (!work) {
9320                         iput(inode);
9321                         ret = -ENOMEM;
9322                         goto out;
9323                 }
9324                 list_add_tail(&work->list, &works);
9325                 btrfs_queue_work(root->fs_info->flush_workers,
9326                                  &work->work);
9327                 ret++;
9328                 if (nr != -1 && ret >= nr)
9329                         goto out;
9330                 cond_resched();
9331                 spin_lock(&root->delalloc_lock);
9332         }
9333         spin_unlock(&root->delalloc_lock);
9334
9335 out:
9336         list_for_each_entry_safe(work, next, &works, list) {
9337                 list_del_init(&work->list);
9338                 wait_for_completion(&work->completion);
9339                 kfree(work);
9340         }
9341
9342         if (!list_empty(&splice)) {
9343                 spin_lock(&root->delalloc_lock);
9344                 list_splice_tail(&splice, &root->delalloc_inodes);
9345                 spin_unlock(&root->delalloc_lock);
9346         }
9347         mutex_unlock(&root->delalloc_mutex);
9348         return ret;
9349 }
9350
9351 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9352 {
9353         struct btrfs_fs_info *fs_info = root->fs_info;
9354         int ret;
9355
9356         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9357                 return -EROFS;
9358
9359         ret = start_delalloc_inodes(root, -1, true);
9360         if (ret > 0)
9361                 ret = 0;
9362         return ret;
9363 }
9364
9365 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9366 {
9367         struct btrfs_root *root;
9368         struct list_head splice;
9369         int ret;
9370
9371         if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9372                 return -EROFS;
9373
9374         INIT_LIST_HEAD(&splice);
9375
9376         mutex_lock(&fs_info->delalloc_root_mutex);
9377         spin_lock(&fs_info->delalloc_root_lock);
9378         list_splice_init(&fs_info->delalloc_roots, &splice);
9379         while (!list_empty(&splice) && nr) {
9380                 root = list_first_entry(&splice, struct btrfs_root,
9381                                         delalloc_root);
9382                 root = btrfs_grab_root(root);
9383                 BUG_ON(!root);
9384                 list_move_tail(&root->delalloc_root,
9385                                &fs_info->delalloc_roots);
9386                 spin_unlock(&fs_info->delalloc_root_lock);
9387
9388                 ret = start_delalloc_inodes(root, nr, false);
9389                 btrfs_put_root(root);
9390                 if (ret < 0)
9391                         goto out;
9392
9393                 if (nr != -1) {
9394                         nr -= ret;
9395                         WARN_ON(nr < 0);
9396                 }
9397                 spin_lock(&fs_info->delalloc_root_lock);
9398         }
9399         spin_unlock(&fs_info->delalloc_root_lock);
9400
9401         ret = 0;
9402 out:
9403         if (!list_empty(&splice)) {
9404                 spin_lock(&fs_info->delalloc_root_lock);
9405                 list_splice_tail(&splice, &fs_info->delalloc_roots);
9406                 spin_unlock(&fs_info->delalloc_root_lock);
9407         }
9408         mutex_unlock(&fs_info->delalloc_root_mutex);
9409         return ret;
9410 }
9411
9412 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9413                          const char *symname)
9414 {
9415         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9416         struct btrfs_trans_handle *trans;
9417         struct btrfs_root *root = BTRFS_I(dir)->root;
9418         struct btrfs_path *path;
9419         struct btrfs_key key;
9420         struct inode *inode = NULL;
9421         int err;
9422         u64 objectid;
9423         u64 index = 0;
9424         int name_len;
9425         int datasize;
9426         unsigned long ptr;
9427         struct btrfs_file_extent_item *ei;
9428         struct extent_buffer *leaf;
9429
9430         name_len = strlen(symname);
9431         if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9432                 return -ENAMETOOLONG;
9433
9434         /*
9435          * 2 items for inode item and ref
9436          * 2 items for dir items
9437          * 1 item for updating parent inode item
9438          * 1 item for the inline extent item
9439          * 1 item for xattr if selinux is on
9440          */
9441         trans = btrfs_start_transaction(root, 7);
9442         if (IS_ERR(trans))
9443                 return PTR_ERR(trans);
9444
9445         err = btrfs_find_free_ino(root, &objectid);
9446         if (err)
9447                 goto out_unlock;
9448
9449         inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9450                                 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9451                                 objectid, S_IFLNK|S_IRWXUGO, &index);
9452         if (IS_ERR(inode)) {
9453                 err = PTR_ERR(inode);
9454                 inode = NULL;
9455                 goto out_unlock;
9456         }
9457
9458         /*
9459         * If the active LSM wants to access the inode during
9460         * d_instantiate it needs these. Smack checks to see
9461         * if the filesystem supports xattrs by looking at the
9462         * ops vector.
9463         */
9464         inode->i_fop = &btrfs_file_operations;
9465         inode->i_op = &btrfs_file_inode_operations;
9466         inode->i_mapping->a_ops = &btrfs_aops;
9467         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9468
9469         err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9470         if (err)
9471                 goto out_unlock;
9472
9473         path = btrfs_alloc_path();
9474         if (!path) {
9475                 err = -ENOMEM;
9476                 goto out_unlock;
9477         }
9478         key.objectid = btrfs_ino(BTRFS_I(inode));
9479         key.offset = 0;
9480         key.type = BTRFS_EXTENT_DATA_KEY;
9481         datasize = btrfs_file_extent_calc_inline_size(name_len);
9482         err = btrfs_insert_empty_item(trans, root, path, &key,
9483                                       datasize);
9484         if (err) {
9485                 btrfs_free_path(path);
9486                 goto out_unlock;
9487         }
9488         leaf = path->nodes[0];
9489         ei = btrfs_item_ptr(leaf, path->slots[0],
9490                             struct btrfs_file_extent_item);
9491         btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9492         btrfs_set_file_extent_type(leaf, ei,
9493                                    BTRFS_FILE_EXTENT_INLINE);
9494         btrfs_set_file_extent_encryption(leaf, ei, 0);
9495         btrfs_set_file_extent_compression(leaf, ei, 0);
9496         btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9497         btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9498
9499         ptr = btrfs_file_extent_inline_start(ei);
9500         write_extent_buffer(leaf, symname, ptr, name_len);
9501         btrfs_mark_buffer_dirty(leaf);
9502         btrfs_free_path(path);
9503
9504         inode->i_op = &btrfs_symlink_inode_operations;
9505         inode_nohighmem(inode);
9506         inode_set_bytes(inode, name_len);
9507         btrfs_i_size_write(BTRFS_I(inode), name_len);
9508         err = btrfs_update_inode(trans, root, inode);
9509         /*
9510          * Last step, add directory indexes for our symlink inode. This is the
9511          * last step to avoid extra cleanup of these indexes if an error happens
9512          * elsewhere above.
9513          */
9514         if (!err)
9515                 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9516                                 BTRFS_I(inode), 0, index);
9517         if (err)
9518                 goto out_unlock;
9519
9520         d_instantiate_new(dentry, inode);
9521
9522 out_unlock:
9523         btrfs_end_transaction(trans);
9524         if (err && inode) {
9525                 inode_dec_link_count(inode);
9526                 discard_new_inode(inode);
9527         }
9528         btrfs_btree_balance_dirty(fs_info);
9529         return err;
9530 }
9531
9532 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9533                                        u64 start, u64 num_bytes, u64 min_size,
9534                                        loff_t actual_len, u64 *alloc_hint,
9535                                        struct btrfs_trans_handle *trans)
9536 {
9537         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9538         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9539         struct extent_map *em;
9540         struct btrfs_root *root = BTRFS_I(inode)->root;
9541         struct btrfs_key ins;
9542         u64 cur_offset = start;
9543         u64 clear_offset = start;
9544         u64 i_size;
9545         u64 cur_bytes;
9546         u64 last_alloc = (u64)-1;
9547         int ret = 0;
9548         bool own_trans = true;
9549         u64 end = start + num_bytes - 1;
9550
9551         if (trans)
9552                 own_trans = false;
9553         while (num_bytes > 0) {
9554                 if (own_trans) {
9555                         trans = btrfs_start_transaction(root, 3);
9556                         if (IS_ERR(trans)) {
9557                                 ret = PTR_ERR(trans);
9558                                 break;
9559                         }
9560                 }
9561
9562                 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9563                 cur_bytes = max(cur_bytes, min_size);
9564                 /*
9565                  * If we are severely fragmented we could end up with really
9566                  * small allocations, so if the allocator is returning small
9567                  * chunks lets make its job easier by only searching for those
9568                  * sized chunks.
9569                  */
9570                 cur_bytes = min(cur_bytes, last_alloc);
9571                 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9572                                 min_size, 0, *alloc_hint, &ins, 1, 0);
9573                 if (ret) {
9574                         if (own_trans)
9575                                 btrfs_end_transaction(trans);
9576                         break;
9577                 }
9578
9579                 /*
9580                  * We've reserved this space, and thus converted it from
9581                  * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9582                  * from here on out we will only need to clear our reservation
9583                  * for the remaining unreserved area, so advance our
9584                  * clear_offset by our extent size.
9585                  */
9586                 clear_offset += ins.offset;
9587                 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9588
9589                 last_alloc = ins.offset;
9590                 ret = insert_reserved_file_extent(trans, inode,
9591                                                   cur_offset, ins.objectid,
9592                                                   ins.offset, ins.offset,
9593                                                   ins.offset, 0, 0, 0,
9594                                                   BTRFS_FILE_EXTENT_PREALLOC);
9595                 if (ret) {
9596                         btrfs_free_reserved_extent(fs_info, ins.objectid,
9597                                                    ins.offset, 0);
9598                         btrfs_abort_transaction(trans, ret);
9599                         if (own_trans)
9600                                 btrfs_end_transaction(trans);
9601                         break;
9602                 }
9603
9604                 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9605                                         cur_offset + ins.offset -1, 0);
9606
9607                 em = alloc_extent_map();
9608                 if (!em) {
9609                         set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9610                                 &BTRFS_I(inode)->runtime_flags);
9611                         goto next;
9612                 }
9613
9614                 em->start = cur_offset;
9615                 em->orig_start = cur_offset;
9616                 em->len = ins.offset;
9617                 em->block_start = ins.objectid;
9618                 em->block_len = ins.offset;
9619                 em->orig_block_len = ins.offset;
9620                 em->ram_bytes = ins.offset;
9621                 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9622                 em->generation = trans->transid;
9623
9624                 while (1) {
9625                         write_lock(&em_tree->lock);
9626                         ret = add_extent_mapping(em_tree, em, 1);
9627                         write_unlock(&em_tree->lock);
9628                         if (ret != -EEXIST)
9629                                 break;
9630                         btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9631                                                 cur_offset + ins.offset - 1,
9632                                                 0);
9633                 }
9634                 free_extent_map(em);
9635 next:
9636                 num_bytes -= ins.offset;
9637                 cur_offset += ins.offset;
9638                 *alloc_hint = ins.objectid + ins.offset;
9639
9640                 inode_inc_iversion(inode);
9641                 inode->i_ctime = current_time(inode);
9642                 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9643                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9644                     (actual_len > inode->i_size) &&
9645                     (cur_offset > inode->i_size)) {
9646                         if (cur_offset > actual_len)
9647                                 i_size = actual_len;
9648                         else
9649                                 i_size = cur_offset;
9650                         i_size_write(inode, i_size);
9651                         btrfs_inode_safe_disk_i_size_write(inode, 0);
9652                 }
9653
9654                 ret = btrfs_update_inode(trans, root, inode);
9655
9656                 if (ret) {
9657                         btrfs_abort_transaction(trans, ret);
9658                         if (own_trans)
9659                                 btrfs_end_transaction(trans);
9660                         break;
9661                 }
9662
9663                 if (own_trans)
9664                         btrfs_end_transaction(trans);
9665         }
9666         if (clear_offset < end)
9667                 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9668                         end - clear_offset + 1);
9669         return ret;
9670 }
9671
9672 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9673                               u64 start, u64 num_bytes, u64 min_size,
9674                               loff_t actual_len, u64 *alloc_hint)
9675 {
9676         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9677                                            min_size, actual_len, alloc_hint,
9678                                            NULL);
9679 }
9680
9681 int btrfs_prealloc_file_range_trans(struct inode *inode,
9682                                     struct btrfs_trans_handle *trans, int mode,
9683                                     u64 start, u64 num_bytes, u64 min_size,
9684                                     loff_t actual_len, u64 *alloc_hint)
9685 {
9686         return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9687                                            min_size, actual_len, alloc_hint, trans);
9688 }
9689
9690 static int btrfs_set_page_dirty(struct page *page)
9691 {
9692         return __set_page_dirty_nobuffers(page);
9693 }
9694
9695 static int btrfs_permission(struct inode *inode, int mask)
9696 {
9697         struct btrfs_root *root = BTRFS_I(inode)->root;
9698         umode_t mode = inode->i_mode;
9699
9700         if (mask & MAY_WRITE &&
9701             (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9702                 if (btrfs_root_readonly(root))
9703                         return -EROFS;
9704                 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9705                         return -EACCES;
9706         }
9707         return generic_permission(inode, mask);
9708 }
9709
9710 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9711 {
9712         struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9713         struct btrfs_trans_handle *trans;
9714         struct btrfs_root *root = BTRFS_I(dir)->root;
9715         struct inode *inode = NULL;
9716         u64 objectid;
9717         u64 index;
9718         int ret = 0;
9719
9720         /*
9721          * 5 units required for adding orphan entry
9722          */
9723         trans = btrfs_start_transaction(root, 5);
9724         if (IS_ERR(trans))
9725                 return PTR_ERR(trans);
9726
9727         ret = btrfs_find_free_ino(root, &objectid);
9728         if (ret)
9729                 goto out;
9730
9731         inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9732                         btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
9733         if (IS_ERR(inode)) {
9734                 ret = PTR_ERR(inode);
9735                 inode = NULL;
9736                 goto out;
9737         }
9738
9739         inode->i_fop = &btrfs_file_operations;
9740         inode->i_op = &btrfs_file_inode_operations;
9741
9742         inode->i_mapping->a_ops = &btrfs_aops;
9743         BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9744
9745         ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9746         if (ret)
9747                 goto out;
9748
9749         ret = btrfs_update_inode(trans, root, inode);
9750         if (ret)
9751                 goto out;
9752         ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9753         if (ret)
9754                 goto out;
9755
9756         /*
9757          * We set number of links to 0 in btrfs_new_inode(), and here we set
9758          * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9759          * through:
9760          *
9761          *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9762          */
9763         set_nlink(inode, 1);
9764         d_tmpfile(dentry, inode);
9765         unlock_new_inode(inode);
9766         mark_inode_dirty(inode);
9767 out:
9768         btrfs_end_transaction(trans);
9769         if (ret && inode)
9770                 discard_new_inode(inode);
9771         btrfs_btree_balance_dirty(fs_info);
9772         return ret;
9773 }
9774
9775 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
9776 {
9777         struct inode *inode = tree->private_data;
9778         unsigned long index = start >> PAGE_SHIFT;
9779         unsigned long end_index = end >> PAGE_SHIFT;
9780         struct page *page;
9781
9782         while (index <= end_index) {
9783                 page = find_get_page(inode->i_mapping, index);
9784                 ASSERT(page); /* Pages should be in the extent_io_tree */
9785                 set_page_writeback(page);
9786                 put_page(page);
9787                 index++;
9788         }
9789 }
9790
9791 #ifdef CONFIG_SWAP
9792 /*
9793  * Add an entry indicating a block group or device which is pinned by a
9794  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9795  * negative errno on failure.
9796  */
9797 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9798                                   bool is_block_group)
9799 {
9800         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9801         struct btrfs_swapfile_pin *sp, *entry;
9802         struct rb_node **p;
9803         struct rb_node *parent = NULL;
9804
9805         sp = kmalloc(sizeof(*sp), GFP_NOFS);
9806         if (!sp)
9807                 return -ENOMEM;
9808         sp->ptr = ptr;
9809         sp->inode = inode;
9810         sp->is_block_group = is_block_group;
9811
9812         spin_lock(&fs_info->swapfile_pins_lock);
9813         p = &fs_info->swapfile_pins.rb_node;
9814         while (*p) {
9815                 parent = *p;
9816                 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9817                 if (sp->ptr < entry->ptr ||
9818                     (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9819                         p = &(*p)->rb_left;
9820                 } else if (sp->ptr > entry->ptr ||
9821                            (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9822                         p = &(*p)->rb_right;
9823                 } else {
9824                         spin_unlock(&fs_info->swapfile_pins_lock);
9825                         kfree(sp);
9826                         return 1;
9827                 }
9828         }
9829         rb_link_node(&sp->node, parent, p);
9830         rb_insert_color(&sp->node, &fs_info->swapfile_pins);
9831         spin_unlock(&fs_info->swapfile_pins_lock);
9832         return 0;
9833 }
9834
9835 /* Free all of the entries pinned by this swapfile. */
9836 static void btrfs_free_swapfile_pins(struct inode *inode)
9837 {
9838         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9839         struct btrfs_swapfile_pin *sp;
9840         struct rb_node *node, *next;
9841
9842         spin_lock(&fs_info->swapfile_pins_lock);
9843         node = rb_first(&fs_info->swapfile_pins);
9844         while (node) {
9845                 next = rb_next(node);
9846                 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
9847                 if (sp->inode == inode) {
9848                         rb_erase(&sp->node, &fs_info->swapfile_pins);
9849                         if (sp->is_block_group)
9850                                 btrfs_put_block_group(sp->ptr);
9851                         kfree(sp);
9852                 }
9853                 node = next;
9854         }
9855         spin_unlock(&fs_info->swapfile_pins_lock);
9856 }
9857
9858 struct btrfs_swap_info {
9859         u64 start;
9860         u64 block_start;
9861         u64 block_len;
9862         u64 lowest_ppage;
9863         u64 highest_ppage;
9864         unsigned long nr_pages;
9865         int nr_extents;
9866 };
9867
9868 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
9869                                  struct btrfs_swap_info *bsi)
9870 {
9871         unsigned long nr_pages;
9872         u64 first_ppage, first_ppage_reported, next_ppage;
9873         int ret;
9874
9875         first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
9876         next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
9877                                 PAGE_SIZE) >> PAGE_SHIFT;
9878
9879         if (first_ppage >= next_ppage)
9880                 return 0;
9881         nr_pages = next_ppage - first_ppage;
9882
9883         first_ppage_reported = first_ppage;
9884         if (bsi->start == 0)
9885                 first_ppage_reported++;
9886         if (bsi->lowest_ppage > first_ppage_reported)
9887                 bsi->lowest_ppage = first_ppage_reported;
9888         if (bsi->highest_ppage < (next_ppage - 1))
9889                 bsi->highest_ppage = next_ppage - 1;
9890
9891         ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
9892         if (ret < 0)
9893                 return ret;
9894         bsi->nr_extents += ret;
9895         bsi->nr_pages += nr_pages;
9896         return 0;
9897 }
9898
9899 static void btrfs_swap_deactivate(struct file *file)
9900 {
9901         struct inode *inode = file_inode(file);
9902
9903         btrfs_free_swapfile_pins(inode);
9904         atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
9905 }
9906
9907 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
9908                                sector_t *span)
9909 {
9910         struct inode *inode = file_inode(file);
9911         struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9912         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
9913         struct extent_state *cached_state = NULL;
9914         struct extent_map *em = NULL;
9915         struct btrfs_device *device = NULL;
9916         struct btrfs_swap_info bsi = {
9917                 .lowest_ppage = (sector_t)-1ULL,
9918         };
9919         int ret = 0;
9920         u64 isize;
9921         u64 start;
9922
9923         /*
9924          * If the swap file was just created, make sure delalloc is done. If the
9925          * file changes again after this, the user is doing something stupid and
9926          * we don't really care.
9927          */
9928         ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
9929         if (ret)
9930                 return ret;
9931
9932         /*
9933          * The inode is locked, so these flags won't change after we check them.
9934          */
9935         if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
9936                 btrfs_warn(fs_info, "swapfile must not be compressed");
9937                 return -EINVAL;
9938         }
9939         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
9940                 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
9941                 return -EINVAL;
9942         }
9943         if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
9944                 btrfs_warn(fs_info, "swapfile must not be checksummed");
9945                 return -EINVAL;
9946         }
9947
9948         /*
9949          * Balance or device remove/replace/resize can move stuff around from
9950          * under us. The EXCL_OP flag makes sure they aren't running/won't run
9951          * concurrently while we are mapping the swap extents, and
9952          * fs_info->swapfile_pins prevents them from running while the swap file
9953          * is active and moving the extents. Note that this also prevents a
9954          * concurrent device add which isn't actually necessary, but it's not
9955          * really worth the trouble to allow it.
9956          */
9957         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
9958                 btrfs_warn(fs_info,
9959            "cannot activate swapfile while exclusive operation is running");
9960                 return -EBUSY;
9961         }
9962         /*
9963          * Snapshots can create extents which require COW even if NODATACOW is
9964          * set. We use this counter to prevent snapshots. We must increment it
9965          * before walking the extents because we don't want a concurrent
9966          * snapshot to run after we've already checked the extents.
9967          */
9968         atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
9969
9970         isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
9971
9972         lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
9973         start = 0;
9974         while (start < isize) {
9975                 u64 logical_block_start, physical_block_start;
9976                 struct btrfs_block_group *bg;
9977                 u64 len = isize - start;
9978
9979                 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
9980                 if (IS_ERR(em)) {
9981                         ret = PTR_ERR(em);
9982                         goto out;
9983                 }
9984
9985                 if (em->block_start == EXTENT_MAP_HOLE) {
9986                         btrfs_warn(fs_info, "swapfile must not have holes");
9987                         ret = -EINVAL;
9988                         goto out;
9989                 }
9990                 if (em->block_start == EXTENT_MAP_INLINE) {
9991                         /*
9992                          * It's unlikely we'll ever actually find ourselves
9993                          * here, as a file small enough to fit inline won't be
9994                          * big enough to store more than the swap header, but in
9995                          * case something changes in the future, let's catch it
9996                          * here rather than later.
9997                          */
9998                         btrfs_warn(fs_info, "swapfile must not be inline");
9999                         ret = -EINVAL;
10000                         goto out;
10001                 }
10002                 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10003                         btrfs_warn(fs_info, "swapfile must not be compressed");
10004                         ret = -EINVAL;
10005                         goto out;
10006                 }
10007
10008                 logical_block_start = em->block_start + (start - em->start);
10009                 len = min(len, em->len - (start - em->start));
10010                 free_extent_map(em);
10011                 em = NULL;
10012
10013                 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10014                 if (ret < 0) {
10015                         goto out;
10016                 } else if (ret) {
10017                         ret = 0;
10018                 } else {
10019                         btrfs_warn(fs_info,
10020                                    "swapfile must not be copy-on-write");
10021                         ret = -EINVAL;
10022                         goto out;
10023                 }
10024
10025                 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10026                 if (IS_ERR(em)) {
10027                         ret = PTR_ERR(em);
10028                         goto out;
10029                 }
10030
10031                 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10032                         btrfs_warn(fs_info,
10033                                    "swapfile must have single data profile");
10034                         ret = -EINVAL;
10035                         goto out;
10036                 }
10037
10038                 if (device == NULL) {
10039                         device = em->map_lookup->stripes[0].dev;
10040                         ret = btrfs_add_swapfile_pin(inode, device, false);
10041                         if (ret == 1)
10042                                 ret = 0;
10043                         else if (ret)
10044                                 goto out;
10045                 } else if (device != em->map_lookup->stripes[0].dev) {
10046                         btrfs_warn(fs_info, "swapfile must be on one device");
10047                         ret = -EINVAL;
10048                         goto out;
10049                 }
10050
10051                 physical_block_start = (em->map_lookup->stripes[0].physical +
10052                                         (logical_block_start - em->start));
10053                 len = min(len, em->len - (logical_block_start - em->start));
10054                 free_extent_map(em);
10055                 em = NULL;
10056
10057                 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10058                 if (!bg) {
10059                         btrfs_warn(fs_info,
10060                            "could not find block group containing swapfile");
10061                         ret = -EINVAL;
10062                         goto out;
10063                 }
10064
10065                 ret = btrfs_add_swapfile_pin(inode, bg, true);
10066                 if (ret) {
10067                         btrfs_put_block_group(bg);
10068                         if (ret == 1)
10069                                 ret = 0;
10070                         else
10071                                 goto out;
10072                 }
10073
10074                 if (bsi.block_len &&
10075                     bsi.block_start + bsi.block_len == physical_block_start) {
10076                         bsi.block_len += len;
10077                 } else {
10078                         if (bsi.block_len) {
10079                                 ret = btrfs_add_swap_extent(sis, &bsi);
10080                                 if (ret)
10081                                         goto out;
10082                         }
10083                         bsi.start = start;
10084                         bsi.block_start = physical_block_start;
10085                         bsi.block_len = len;
10086                 }
10087
10088                 start += len;
10089         }
10090
10091         if (bsi.block_len)
10092                 ret = btrfs_add_swap_extent(sis, &bsi);
10093
10094 out:
10095         if (!IS_ERR_OR_NULL(em))
10096                 free_extent_map(em);
10097
10098         unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10099
10100         if (ret)
10101                 btrfs_swap_deactivate(file);
10102
10103         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10104
10105         if (ret)
10106                 return ret;
10107
10108         if (device)
10109                 sis->bdev = device->bdev;
10110         *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10111         sis->max = bsi.nr_pages;
10112         sis->pages = bsi.nr_pages - 1;
10113         sis->highest_bit = bsi.nr_pages - 1;
10114         return bsi.nr_extents;
10115 }
10116 #else
10117 static void btrfs_swap_deactivate(struct file *file)
10118 {
10119 }
10120
10121 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10122                                sector_t *span)
10123 {
10124         return -EOPNOTSUPP;
10125 }
10126 #endif
10127
10128 static const struct inode_operations btrfs_dir_inode_operations = {
10129         .getattr        = btrfs_getattr,
10130         .lookup         = btrfs_lookup,
10131         .create         = btrfs_create,
10132         .unlink         = btrfs_unlink,
10133         .link           = btrfs_link,
10134         .mkdir          = btrfs_mkdir,
10135         .rmdir          = btrfs_rmdir,
10136         .rename         = btrfs_rename2,
10137         .symlink        = btrfs_symlink,
10138         .setattr        = btrfs_setattr,
10139         .mknod          = btrfs_mknod,
10140         .listxattr      = btrfs_listxattr,
10141         .permission     = btrfs_permission,
10142         .get_acl        = btrfs_get_acl,
10143         .set_acl        = btrfs_set_acl,
10144         .update_time    = btrfs_update_time,
10145         .tmpfile        = btrfs_tmpfile,
10146 };
10147
10148 static const struct file_operations btrfs_dir_file_operations = {
10149         .llseek         = generic_file_llseek,
10150         .read           = generic_read_dir,
10151         .iterate_shared = btrfs_real_readdir,
10152         .open           = btrfs_opendir,
10153         .unlocked_ioctl = btrfs_ioctl,
10154 #ifdef CONFIG_COMPAT
10155         .compat_ioctl   = btrfs_compat_ioctl,
10156 #endif
10157         .release        = btrfs_release_file,
10158         .fsync          = btrfs_sync_file,
10159 };
10160
10161 static const struct extent_io_ops btrfs_extent_io_ops = {
10162         /* mandatory callbacks */
10163         .submit_bio_hook = btrfs_submit_bio_hook,
10164         .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10165 };
10166
10167 /*
10168  * btrfs doesn't support the bmap operation because swapfiles
10169  * use bmap to make a mapping of extents in the file.  They assume
10170  * these extents won't change over the life of the file and they
10171  * use the bmap result to do IO directly to the drive.
10172  *
10173  * the btrfs bmap call would return logical addresses that aren't
10174  * suitable for IO and they also will change frequently as COW
10175  * operations happen.  So, swapfile + btrfs == corruption.
10176  *
10177  * For now we're avoiding this by dropping bmap.
10178  */
10179 static const struct address_space_operations btrfs_aops = {
10180         .readpage       = btrfs_readpage,
10181         .writepage      = btrfs_writepage,
10182         .writepages     = btrfs_writepages,
10183         .readpages      = btrfs_readpages,
10184         .direct_IO      = btrfs_direct_IO,
10185         .invalidatepage = btrfs_invalidatepage,
10186         .releasepage    = btrfs_releasepage,
10187 #ifdef CONFIG_MIGRATION
10188         .migratepage    = btrfs_migratepage,
10189 #endif
10190         .set_page_dirty = btrfs_set_page_dirty,
10191         .error_remove_page = generic_error_remove_page,
10192         .swap_activate  = btrfs_swap_activate,
10193         .swap_deactivate = btrfs_swap_deactivate,
10194 };
10195
10196 static const struct inode_operations btrfs_file_inode_operations = {
10197         .getattr        = btrfs_getattr,
10198         .setattr        = btrfs_setattr,
10199         .listxattr      = btrfs_listxattr,
10200         .permission     = btrfs_permission,
10201         .fiemap         = btrfs_fiemap,
10202         .get_acl        = btrfs_get_acl,
10203         .set_acl        = btrfs_set_acl,
10204         .update_time    = btrfs_update_time,
10205 };
10206 static const struct inode_operations btrfs_special_inode_operations = {
10207         .getattr        = btrfs_getattr,
10208         .setattr        = btrfs_setattr,
10209         .permission     = btrfs_permission,
10210         .listxattr      = btrfs_listxattr,
10211         .get_acl        = btrfs_get_acl,
10212         .set_acl        = btrfs_set_acl,
10213         .update_time    = btrfs_update_time,
10214 };
10215 static const struct inode_operations btrfs_symlink_inode_operations = {
10216         .get_link       = page_get_link,
10217         .getattr        = btrfs_getattr,
10218         .setattr        = btrfs_setattr,
10219         .permission     = btrfs_permission,
10220         .listxattr      = btrfs_listxattr,
10221         .update_time    = btrfs_update_time,
10222 };
10223
10224 const struct dentry_operations btrfs_dentry_operations = {
10225         .d_delete       = btrfs_dentry_delete,
10226 };