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