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