2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.h>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
63 struct btrfs_iget_args {
64 struct btrfs_key *location;
65 struct btrfs_root *root;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_dir_ro_inode_operations;
71 static const struct inode_operations btrfs_special_inode_operations;
72 static const struct inode_operations btrfs_file_inode_operations;
73 static const struct address_space_operations btrfs_aops;
74 static const struct address_space_operations btrfs_symlink_aops;
75 static const struct file_operations btrfs_dir_file_operations;
76 static struct extent_io_ops btrfs_extent_io_ops;
78 static struct kmem_cache *btrfs_inode_cachep;
79 static struct kmem_cache *btrfs_delalloc_work_cachep;
80 struct kmem_cache *btrfs_trans_handle_cachep;
81 struct kmem_cache *btrfs_transaction_cachep;
82 struct kmem_cache *btrfs_path_cachep;
83 struct kmem_cache *btrfs_free_space_cachep;
86 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
87 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
88 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
89 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
90 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
91 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
92 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
93 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
96 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
97 static int btrfs_truncate(struct inode *inode);
98 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
99 static noinline int cow_file_range(struct inode *inode,
100 struct page *locked_page,
101 u64 start, u64 end, int *page_started,
102 unsigned long *nr_written, int unlock);
103 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
104 u64 len, u64 orig_start,
105 u64 block_start, u64 block_len,
106 u64 orig_block_len, u64 ram_bytes,
109 static int btrfs_dirty_inode(struct inode *inode);
111 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
112 struct inode *inode, struct inode *dir,
113 const struct qstr *qstr)
117 err = btrfs_init_acl(trans, inode, dir);
119 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
124 * this does all the hard work for inserting an inline extent into
125 * the btree. The caller should have done a btrfs_drop_extents so that
126 * no overlapping inline items exist in the btree
128 static int insert_inline_extent(struct btrfs_trans_handle *trans,
129 struct btrfs_path *path, int extent_inserted,
130 struct btrfs_root *root, struct inode *inode,
131 u64 start, size_t size, size_t compressed_size,
133 struct page **compressed_pages)
135 struct extent_buffer *leaf;
136 struct page *page = NULL;
139 struct btrfs_file_extent_item *ei;
142 size_t cur_size = size;
143 unsigned long offset;
145 if (compressed_size && compressed_pages)
146 cur_size = compressed_size;
148 inode_add_bytes(inode, size);
150 if (!extent_inserted) {
151 struct btrfs_key key;
154 key.objectid = btrfs_ino(inode);
156 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
158 datasize = btrfs_file_extent_calc_inline_size(cur_size);
159 path->leave_spinning = 1;
160 ret = btrfs_insert_empty_item(trans, root, path, &key,
167 leaf = path->nodes[0];
168 ei = btrfs_item_ptr(leaf, path->slots[0],
169 struct btrfs_file_extent_item);
170 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
171 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
172 btrfs_set_file_extent_encryption(leaf, ei, 0);
173 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
174 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
175 ptr = btrfs_file_extent_inline_start(ei);
177 if (compress_type != BTRFS_COMPRESS_NONE) {
180 while (compressed_size > 0) {
181 cpage = compressed_pages[i];
182 cur_size = min_t(unsigned long, compressed_size,
185 kaddr = kmap_atomic(cpage);
186 write_extent_buffer(leaf, kaddr, ptr, cur_size);
187 kunmap_atomic(kaddr);
191 compressed_size -= cur_size;
193 btrfs_set_file_extent_compression(leaf, ei,
196 page = find_get_page(inode->i_mapping,
197 start >> PAGE_CACHE_SHIFT);
198 btrfs_set_file_extent_compression(leaf, ei, 0);
199 kaddr = kmap_atomic(page);
200 offset = start & (PAGE_CACHE_SIZE - 1);
201 write_extent_buffer(leaf, kaddr + offset, ptr, size);
202 kunmap_atomic(kaddr);
203 page_cache_release(page);
205 btrfs_mark_buffer_dirty(leaf);
206 btrfs_release_path(path);
209 * we're an inline extent, so nobody can
210 * extend the file past i_size without locking
211 * a page we already have locked.
213 * We must do any isize and inode updates
214 * before we unlock the pages. Otherwise we
215 * could end up racing with unlink.
217 BTRFS_I(inode)->disk_i_size = inode->i_size;
218 ret = btrfs_update_inode(trans, root, inode);
227 * conditionally insert an inline extent into the file. This
228 * does the checks required to make sure the data is small enough
229 * to fit as an inline extent.
231 static noinline int cow_file_range_inline(struct btrfs_root *root,
232 struct inode *inode, u64 start,
233 u64 end, size_t compressed_size,
235 struct page **compressed_pages)
237 struct btrfs_trans_handle *trans;
238 u64 isize = i_size_read(inode);
239 u64 actual_end = min(end + 1, isize);
240 u64 inline_len = actual_end - start;
241 u64 aligned_end = ALIGN(end, root->sectorsize);
242 u64 data_len = inline_len;
244 struct btrfs_path *path;
245 int extent_inserted = 0;
246 u32 extent_item_size;
249 data_len = compressed_size;
252 actual_end >= PAGE_CACHE_SIZE ||
253 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
255 (actual_end & (root->sectorsize - 1)) == 0) ||
257 data_len > root->fs_info->max_inline) {
261 path = btrfs_alloc_path();
265 trans = btrfs_join_transaction(root);
267 btrfs_free_path(path);
268 return PTR_ERR(trans);
270 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
272 if (compressed_size && compressed_pages)
273 extent_item_size = btrfs_file_extent_calc_inline_size(
276 extent_item_size = btrfs_file_extent_calc_inline_size(
279 ret = __btrfs_drop_extents(trans, root, inode, path,
280 start, aligned_end, NULL,
281 1, 1, extent_item_size, &extent_inserted);
283 btrfs_abort_transaction(trans, root, ret);
287 if (isize > actual_end)
288 inline_len = min_t(u64, isize, actual_end);
289 ret = insert_inline_extent(trans, path, extent_inserted,
291 inline_len, compressed_size,
292 compress_type, compressed_pages);
293 if (ret && ret != -ENOSPC) {
294 btrfs_abort_transaction(trans, root, ret);
296 } else if (ret == -ENOSPC) {
301 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
302 btrfs_delalloc_release_metadata(inode, end + 1 - start);
303 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
305 btrfs_free_path(path);
306 btrfs_end_transaction(trans, root);
310 struct async_extent {
315 unsigned long nr_pages;
317 struct list_head list;
322 struct btrfs_root *root;
323 struct page *locked_page;
326 struct list_head extents;
327 struct btrfs_work work;
330 static noinline int add_async_extent(struct async_cow *cow,
331 u64 start, u64 ram_size,
334 unsigned long nr_pages,
337 struct async_extent *async_extent;
339 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
340 BUG_ON(!async_extent); /* -ENOMEM */
341 async_extent->start = start;
342 async_extent->ram_size = ram_size;
343 async_extent->compressed_size = compressed_size;
344 async_extent->pages = pages;
345 async_extent->nr_pages = nr_pages;
346 async_extent->compress_type = compress_type;
347 list_add_tail(&async_extent->list, &cow->extents);
352 * we create compressed extents in two phases. The first
353 * phase compresses a range of pages that have already been
354 * locked (both pages and state bits are locked).
356 * This is done inside an ordered work queue, and the compression
357 * is spread across many cpus. The actual IO submission is step
358 * two, and the ordered work queue takes care of making sure that
359 * happens in the same order things were put onto the queue by
360 * writepages and friends.
362 * If this code finds it can't get good compression, it puts an
363 * entry onto the work queue to write the uncompressed bytes. This
364 * makes sure that both compressed inodes and uncompressed inodes
365 * are written in the same order that the flusher thread sent them
368 static noinline int compress_file_range(struct inode *inode,
369 struct page *locked_page,
371 struct async_cow *async_cow,
374 struct btrfs_root *root = BTRFS_I(inode)->root;
376 u64 blocksize = root->sectorsize;
378 u64 isize = i_size_read(inode);
380 struct page **pages = NULL;
381 unsigned long nr_pages;
382 unsigned long nr_pages_ret = 0;
383 unsigned long total_compressed = 0;
384 unsigned long total_in = 0;
385 unsigned long max_compressed = 128 * 1024;
386 unsigned long max_uncompressed = 128 * 1024;
389 int compress_type = root->fs_info->compress_type;
392 /* if this is a small write inside eof, kick off a defrag */
393 if ((end - start + 1) < 16 * 1024 &&
394 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
395 btrfs_add_inode_defrag(NULL, inode);
398 * skip compression for a small file range(<=blocksize) that
399 * isn't an inline extent, since it dosen't save disk space at all.
401 if ((end - start + 1) <= blocksize &&
402 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
403 goto cleanup_and_bail_uncompressed;
405 actual_end = min_t(u64, isize, end + 1);
408 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
409 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
412 * we don't want to send crud past the end of i_size through
413 * compression, that's just a waste of CPU time. So, if the
414 * end of the file is before the start of our current
415 * requested range of bytes, we bail out to the uncompressed
416 * cleanup code that can deal with all of this.
418 * It isn't really the fastest way to fix things, but this is a
419 * very uncommon corner.
421 if (actual_end <= start)
422 goto cleanup_and_bail_uncompressed;
424 total_compressed = actual_end - start;
426 /* we want to make sure that amount of ram required to uncompress
427 * an extent is reasonable, so we limit the total size in ram
428 * of a compressed extent to 128k. This is a crucial number
429 * because it also controls how easily we can spread reads across
430 * cpus for decompression.
432 * We also want to make sure the amount of IO required to do
433 * a random read is reasonably small, so we limit the size of
434 * a compressed extent to 128k.
436 total_compressed = min(total_compressed, max_uncompressed);
437 num_bytes = ALIGN(end - start + 1, blocksize);
438 num_bytes = max(blocksize, num_bytes);
443 * we do compression for mount -o compress and when the
444 * inode has not been flagged as nocompress. This flag can
445 * change at any time if we discover bad compression ratios.
447 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
448 (btrfs_test_opt(root, COMPRESS) ||
449 (BTRFS_I(inode)->force_compress) ||
450 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
452 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
454 /* just bail out to the uncompressed code */
458 if (BTRFS_I(inode)->force_compress)
459 compress_type = BTRFS_I(inode)->force_compress;
462 * we need to call clear_page_dirty_for_io on each
463 * page in the range. Otherwise applications with the file
464 * mmap'd can wander in and change the page contents while
465 * we are compressing them.
467 * If the compression fails for any reason, we set the pages
468 * dirty again later on.
470 extent_range_clear_dirty_for_io(inode, start, end);
472 ret = btrfs_compress_pages(compress_type,
473 inode->i_mapping, start,
474 total_compressed, pages,
475 nr_pages, &nr_pages_ret,
481 unsigned long offset = total_compressed &
482 (PAGE_CACHE_SIZE - 1);
483 struct page *page = pages[nr_pages_ret - 1];
486 /* zero the tail end of the last page, we might be
487 * sending it down to disk
490 kaddr = kmap_atomic(page);
491 memset(kaddr + offset, 0,
492 PAGE_CACHE_SIZE - offset);
493 kunmap_atomic(kaddr);
500 /* lets try to make an inline extent */
501 if (ret || total_in < (actual_end - start)) {
502 /* we didn't compress the entire range, try
503 * to make an uncompressed inline extent.
505 ret = cow_file_range_inline(root, inode, start, end,
508 /* try making a compressed inline extent */
509 ret = cow_file_range_inline(root, inode, start, end,
511 compress_type, pages);
514 unsigned long clear_flags = EXTENT_DELALLOC |
516 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
519 * inline extent creation worked or returned error,
520 * we don't need to create any more async work items.
521 * Unlock and free up our temp pages.
523 extent_clear_unlock_delalloc(inode, start, end, NULL,
524 clear_flags, PAGE_UNLOCK |
534 * we aren't doing an inline extent round the compressed size
535 * up to a block size boundary so the allocator does sane
538 total_compressed = ALIGN(total_compressed, blocksize);
541 * one last check to make sure the compression is really a
542 * win, compare the page count read with the blocks on disk
544 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
545 if (total_compressed >= total_in) {
548 num_bytes = total_in;
551 if (!will_compress && pages) {
553 * the compression code ran but failed to make things smaller,
554 * free any pages it allocated and our page pointer array
556 for (i = 0; i < nr_pages_ret; i++) {
557 WARN_ON(pages[i]->mapping);
558 page_cache_release(pages[i]);
562 total_compressed = 0;
565 /* flag the file so we don't compress in the future */
566 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
567 !(BTRFS_I(inode)->force_compress)) {
568 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
574 /* the async work queues will take care of doing actual
575 * allocation on disk for these compressed pages,
576 * and will submit them to the elevator.
578 add_async_extent(async_cow, start, num_bytes,
579 total_compressed, pages, nr_pages_ret,
582 if (start + num_bytes < end) {
589 cleanup_and_bail_uncompressed:
591 * No compression, but we still need to write the pages in
592 * the file we've been given so far. redirty the locked
593 * page if it corresponds to our extent and set things up
594 * for the async work queue to run cow_file_range to do
595 * the normal delalloc dance
597 if (page_offset(locked_page) >= start &&
598 page_offset(locked_page) <= end) {
599 __set_page_dirty_nobuffers(locked_page);
600 /* unlocked later on in the async handlers */
603 extent_range_redirty_for_io(inode, start, end);
604 add_async_extent(async_cow, start, end - start + 1,
605 0, NULL, 0, BTRFS_COMPRESS_NONE);
613 for (i = 0; i < nr_pages_ret; i++) {
614 WARN_ON(pages[i]->mapping);
615 page_cache_release(pages[i]);
623 * phase two of compressed writeback. This is the ordered portion
624 * of the code, which only gets called in the order the work was
625 * queued. We walk all the async extents created by compress_file_range
626 * and send them down to the disk.
628 static noinline int submit_compressed_extents(struct inode *inode,
629 struct async_cow *async_cow)
631 struct async_extent *async_extent;
633 struct btrfs_key ins;
634 struct extent_map *em;
635 struct btrfs_root *root = BTRFS_I(inode)->root;
636 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
637 struct extent_io_tree *io_tree;
640 if (list_empty(&async_cow->extents))
644 while (!list_empty(&async_cow->extents)) {
645 async_extent = list_entry(async_cow->extents.next,
646 struct async_extent, list);
647 list_del(&async_extent->list);
649 io_tree = &BTRFS_I(inode)->io_tree;
652 /* did the compression code fall back to uncompressed IO? */
653 if (!async_extent->pages) {
654 int page_started = 0;
655 unsigned long nr_written = 0;
657 lock_extent(io_tree, async_extent->start,
658 async_extent->start +
659 async_extent->ram_size - 1);
661 /* allocate blocks */
662 ret = cow_file_range(inode, async_cow->locked_page,
664 async_extent->start +
665 async_extent->ram_size - 1,
666 &page_started, &nr_written, 0);
671 * if page_started, cow_file_range inserted an
672 * inline extent and took care of all the unlocking
673 * and IO for us. Otherwise, we need to submit
674 * all those pages down to the drive.
676 if (!page_started && !ret)
677 extent_write_locked_range(io_tree,
678 inode, async_extent->start,
679 async_extent->start +
680 async_extent->ram_size - 1,
684 unlock_page(async_cow->locked_page);
690 lock_extent(io_tree, async_extent->start,
691 async_extent->start + async_extent->ram_size - 1);
693 ret = btrfs_reserve_extent(root,
694 async_extent->compressed_size,
695 async_extent->compressed_size,
696 0, alloc_hint, &ins, 1, 1);
700 for (i = 0; i < async_extent->nr_pages; i++) {
701 WARN_ON(async_extent->pages[i]->mapping);
702 page_cache_release(async_extent->pages[i]);
704 kfree(async_extent->pages);
705 async_extent->nr_pages = 0;
706 async_extent->pages = NULL;
708 if (ret == -ENOSPC) {
709 unlock_extent(io_tree, async_extent->start,
710 async_extent->start +
711 async_extent->ram_size - 1);
714 * we need to redirty the pages if we decide to
715 * fallback to uncompressed IO, otherwise we
716 * will not submit these pages down to lower
719 extent_range_redirty_for_io(inode,
721 async_extent->start +
722 async_extent->ram_size - 1);
730 * here we're doing allocation and writeback of the
733 btrfs_drop_extent_cache(inode, async_extent->start,
734 async_extent->start +
735 async_extent->ram_size - 1, 0);
737 em = alloc_extent_map();
740 goto out_free_reserve;
742 em->start = async_extent->start;
743 em->len = async_extent->ram_size;
744 em->orig_start = em->start;
745 em->mod_start = em->start;
746 em->mod_len = em->len;
748 em->block_start = ins.objectid;
749 em->block_len = ins.offset;
750 em->orig_block_len = ins.offset;
751 em->ram_bytes = async_extent->ram_size;
752 em->bdev = root->fs_info->fs_devices->latest_bdev;
753 em->compress_type = async_extent->compress_type;
754 set_bit(EXTENT_FLAG_PINNED, &em->flags);
755 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
759 write_lock(&em_tree->lock);
760 ret = add_extent_mapping(em_tree, em, 1);
761 write_unlock(&em_tree->lock);
762 if (ret != -EEXIST) {
766 btrfs_drop_extent_cache(inode, async_extent->start,
767 async_extent->start +
768 async_extent->ram_size - 1, 0);
772 goto out_free_reserve;
774 ret = btrfs_add_ordered_extent_compress(inode,
777 async_extent->ram_size,
779 BTRFS_ORDERED_COMPRESSED,
780 async_extent->compress_type);
782 goto out_free_reserve;
785 * clear dirty, set writeback and unlock the pages.
787 extent_clear_unlock_delalloc(inode, async_extent->start,
788 async_extent->start +
789 async_extent->ram_size - 1,
790 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
791 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
793 ret = btrfs_submit_compressed_write(inode,
795 async_extent->ram_size,
797 ins.offset, async_extent->pages,
798 async_extent->nr_pages);
799 alloc_hint = ins.objectid + ins.offset;
809 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
811 extent_clear_unlock_delalloc(inode, async_extent->start,
812 async_extent->start +
813 async_extent->ram_size - 1,
814 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
815 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
816 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
817 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
822 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
825 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
826 struct extent_map *em;
829 read_lock(&em_tree->lock);
830 em = search_extent_mapping(em_tree, start, num_bytes);
833 * if block start isn't an actual block number then find the
834 * first block in this inode and use that as a hint. If that
835 * block is also bogus then just don't worry about it.
837 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
839 em = search_extent_mapping(em_tree, 0, 0);
840 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
841 alloc_hint = em->block_start;
845 alloc_hint = em->block_start;
849 read_unlock(&em_tree->lock);
855 * when extent_io.c finds a delayed allocation range in the file,
856 * the call backs end up in this code. The basic idea is to
857 * allocate extents on disk for the range, and create ordered data structs
858 * in ram to track those extents.
860 * locked_page is the page that writepage had locked already. We use
861 * it to make sure we don't do extra locks or unlocks.
863 * *page_started is set to one if we unlock locked_page and do everything
864 * required to start IO on it. It may be clean and already done with
867 static noinline int cow_file_range(struct inode *inode,
868 struct page *locked_page,
869 u64 start, u64 end, int *page_started,
870 unsigned long *nr_written,
873 struct btrfs_root *root = BTRFS_I(inode)->root;
876 unsigned long ram_size;
879 u64 blocksize = root->sectorsize;
880 struct btrfs_key ins;
881 struct extent_map *em;
882 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
885 if (btrfs_is_free_space_inode(inode)) {
891 num_bytes = ALIGN(end - start + 1, blocksize);
892 num_bytes = max(blocksize, num_bytes);
893 disk_num_bytes = num_bytes;
895 /* if this is a small write inside eof, kick off defrag */
896 if (num_bytes < 64 * 1024 &&
897 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
898 btrfs_add_inode_defrag(NULL, inode);
901 /* lets try to make an inline extent */
902 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
905 extent_clear_unlock_delalloc(inode, start, end, NULL,
906 EXTENT_LOCKED | EXTENT_DELALLOC |
907 EXTENT_DEFRAG, PAGE_UNLOCK |
908 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
911 *nr_written = *nr_written +
912 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
915 } else if (ret < 0) {
920 BUG_ON(disk_num_bytes >
921 btrfs_super_total_bytes(root->fs_info->super_copy));
923 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
924 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
926 while (disk_num_bytes > 0) {
929 cur_alloc_size = disk_num_bytes;
930 ret = btrfs_reserve_extent(root, cur_alloc_size,
931 root->sectorsize, 0, alloc_hint,
936 em = alloc_extent_map();
942 em->orig_start = em->start;
943 ram_size = ins.offset;
944 em->len = ins.offset;
945 em->mod_start = em->start;
946 em->mod_len = em->len;
948 em->block_start = ins.objectid;
949 em->block_len = ins.offset;
950 em->orig_block_len = ins.offset;
951 em->ram_bytes = ram_size;
952 em->bdev = root->fs_info->fs_devices->latest_bdev;
953 set_bit(EXTENT_FLAG_PINNED, &em->flags);
957 write_lock(&em_tree->lock);
958 ret = add_extent_mapping(em_tree, em, 1);
959 write_unlock(&em_tree->lock);
960 if (ret != -EEXIST) {
964 btrfs_drop_extent_cache(inode, start,
965 start + ram_size - 1, 0);
970 cur_alloc_size = ins.offset;
971 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
972 ram_size, cur_alloc_size, 0);
976 if (root->root_key.objectid ==
977 BTRFS_DATA_RELOC_TREE_OBJECTID) {
978 ret = btrfs_reloc_clone_csums(inode, start,
984 if (disk_num_bytes < cur_alloc_size)
987 /* we're not doing compressed IO, don't unlock the first
988 * page (which the caller expects to stay locked), don't
989 * clear any dirty bits and don't set any writeback bits
991 * Do set the Private2 bit so we know this page was properly
992 * setup for writepage
994 op = unlock ? PAGE_UNLOCK : 0;
995 op |= PAGE_SET_PRIVATE2;
997 extent_clear_unlock_delalloc(inode, start,
998 start + ram_size - 1, locked_page,
999 EXTENT_LOCKED | EXTENT_DELALLOC,
1001 disk_num_bytes -= cur_alloc_size;
1002 num_bytes -= cur_alloc_size;
1003 alloc_hint = ins.objectid + ins.offset;
1004 start += cur_alloc_size;
1010 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1012 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1013 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1014 EXTENT_DELALLOC | EXTENT_DEFRAG,
1015 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1016 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1021 * work queue call back to started compression on a file and pages
1023 static noinline void async_cow_start(struct btrfs_work *work)
1025 struct async_cow *async_cow;
1027 async_cow = container_of(work, struct async_cow, work);
1029 compress_file_range(async_cow->inode, async_cow->locked_page,
1030 async_cow->start, async_cow->end, async_cow,
1032 if (num_added == 0) {
1033 btrfs_add_delayed_iput(async_cow->inode);
1034 async_cow->inode = NULL;
1039 * work queue call back to submit previously compressed pages
1041 static noinline void async_cow_submit(struct btrfs_work *work)
1043 struct async_cow *async_cow;
1044 struct btrfs_root *root;
1045 unsigned long nr_pages;
1047 async_cow = container_of(work, struct async_cow, work);
1049 root = async_cow->root;
1050 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1053 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1055 waitqueue_active(&root->fs_info->async_submit_wait))
1056 wake_up(&root->fs_info->async_submit_wait);
1058 if (async_cow->inode)
1059 submit_compressed_extents(async_cow->inode, async_cow);
1062 static noinline void async_cow_free(struct btrfs_work *work)
1064 struct async_cow *async_cow;
1065 async_cow = container_of(work, struct async_cow, work);
1066 if (async_cow->inode)
1067 btrfs_add_delayed_iput(async_cow->inode);
1071 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1072 u64 start, u64 end, int *page_started,
1073 unsigned long *nr_written)
1075 struct async_cow *async_cow;
1076 struct btrfs_root *root = BTRFS_I(inode)->root;
1077 unsigned long nr_pages;
1079 int limit = 10 * 1024 * 1024;
1081 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1082 1, 0, NULL, GFP_NOFS);
1083 while (start < end) {
1084 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1085 BUG_ON(!async_cow); /* -ENOMEM */
1086 async_cow->inode = igrab(inode);
1087 async_cow->root = root;
1088 async_cow->locked_page = locked_page;
1089 async_cow->start = start;
1091 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1094 cur_end = min(end, start + 512 * 1024 - 1);
1096 async_cow->end = cur_end;
1097 INIT_LIST_HEAD(&async_cow->extents);
1099 btrfs_init_work(&async_cow->work,
1100 btrfs_delalloc_helper,
1101 async_cow_start, async_cow_submit,
1104 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1106 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1108 btrfs_queue_work(root->fs_info->delalloc_workers,
1111 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1112 wait_event(root->fs_info->async_submit_wait,
1113 (atomic_read(&root->fs_info->async_delalloc_pages) <
1117 while (atomic_read(&root->fs_info->async_submit_draining) &&
1118 atomic_read(&root->fs_info->async_delalloc_pages)) {
1119 wait_event(root->fs_info->async_submit_wait,
1120 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1124 *nr_written += nr_pages;
1125 start = cur_end + 1;
1131 static noinline int csum_exist_in_range(struct btrfs_root *root,
1132 u64 bytenr, u64 num_bytes)
1135 struct btrfs_ordered_sum *sums;
1138 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1139 bytenr + num_bytes - 1, &list, 0);
1140 if (ret == 0 && list_empty(&list))
1143 while (!list_empty(&list)) {
1144 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1145 list_del(&sums->list);
1152 * when nowcow writeback call back. This checks for snapshots or COW copies
1153 * of the extents that exist in the file, and COWs the file as required.
1155 * If no cow copies or snapshots exist, we write directly to the existing
1158 static noinline int run_delalloc_nocow(struct inode *inode,
1159 struct page *locked_page,
1160 u64 start, u64 end, int *page_started, int force,
1161 unsigned long *nr_written)
1163 struct btrfs_root *root = BTRFS_I(inode)->root;
1164 struct btrfs_trans_handle *trans;
1165 struct extent_buffer *leaf;
1166 struct btrfs_path *path;
1167 struct btrfs_file_extent_item *fi;
1168 struct btrfs_key found_key;
1183 u64 ino = btrfs_ino(inode);
1185 path = btrfs_alloc_path();
1187 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1188 EXTENT_LOCKED | EXTENT_DELALLOC |
1189 EXTENT_DO_ACCOUNTING |
1190 EXTENT_DEFRAG, PAGE_UNLOCK |
1192 PAGE_SET_WRITEBACK |
1193 PAGE_END_WRITEBACK);
1197 nolock = btrfs_is_free_space_inode(inode);
1200 trans = btrfs_join_transaction_nolock(root);
1202 trans = btrfs_join_transaction(root);
1204 if (IS_ERR(trans)) {
1205 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1206 EXTENT_LOCKED | EXTENT_DELALLOC |
1207 EXTENT_DO_ACCOUNTING |
1208 EXTENT_DEFRAG, PAGE_UNLOCK |
1210 PAGE_SET_WRITEBACK |
1211 PAGE_END_WRITEBACK);
1212 btrfs_free_path(path);
1213 return PTR_ERR(trans);
1216 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1218 cow_start = (u64)-1;
1221 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1225 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1226 leaf = path->nodes[0];
1227 btrfs_item_key_to_cpu(leaf, &found_key,
1228 path->slots[0] - 1);
1229 if (found_key.objectid == ino &&
1230 found_key.type == BTRFS_EXTENT_DATA_KEY)
1235 leaf = path->nodes[0];
1236 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1237 ret = btrfs_next_leaf(root, path);
1242 leaf = path->nodes[0];
1248 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1250 if (found_key.objectid > ino ||
1251 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1252 found_key.offset > end)
1255 if (found_key.offset > cur_offset) {
1256 extent_end = found_key.offset;
1261 fi = btrfs_item_ptr(leaf, path->slots[0],
1262 struct btrfs_file_extent_item);
1263 extent_type = btrfs_file_extent_type(leaf, fi);
1265 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1266 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1267 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1268 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1269 extent_offset = btrfs_file_extent_offset(leaf, fi);
1270 extent_end = found_key.offset +
1271 btrfs_file_extent_num_bytes(leaf, fi);
1273 btrfs_file_extent_disk_num_bytes(leaf, fi);
1274 if (extent_end <= start) {
1278 if (disk_bytenr == 0)
1280 if (btrfs_file_extent_compression(leaf, fi) ||
1281 btrfs_file_extent_encryption(leaf, fi) ||
1282 btrfs_file_extent_other_encoding(leaf, fi))
1284 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1286 if (btrfs_extent_readonly(root, disk_bytenr))
1288 if (btrfs_cross_ref_exist(trans, root, ino,
1290 extent_offset, disk_bytenr))
1292 disk_bytenr += extent_offset;
1293 disk_bytenr += cur_offset - found_key.offset;
1294 num_bytes = min(end + 1, extent_end) - cur_offset;
1296 * if there are pending snapshots for this root,
1297 * we fall into common COW way.
1300 err = btrfs_start_nocow_write(root);
1305 * force cow if csum exists in the range.
1306 * this ensure that csum for a given extent are
1307 * either valid or do not exist.
1309 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1312 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1313 extent_end = found_key.offset +
1314 btrfs_file_extent_inline_len(leaf,
1315 path->slots[0], fi);
1316 extent_end = ALIGN(extent_end, root->sectorsize);
1321 if (extent_end <= start) {
1323 if (!nolock && nocow)
1324 btrfs_end_nocow_write(root);
1328 if (cow_start == (u64)-1)
1329 cow_start = cur_offset;
1330 cur_offset = extent_end;
1331 if (cur_offset > end)
1337 btrfs_release_path(path);
1338 if (cow_start != (u64)-1) {
1339 ret = cow_file_range(inode, locked_page,
1340 cow_start, found_key.offset - 1,
1341 page_started, nr_written, 1);
1343 if (!nolock && nocow)
1344 btrfs_end_nocow_write(root);
1347 cow_start = (u64)-1;
1350 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1351 struct extent_map *em;
1352 struct extent_map_tree *em_tree;
1353 em_tree = &BTRFS_I(inode)->extent_tree;
1354 em = alloc_extent_map();
1355 BUG_ON(!em); /* -ENOMEM */
1356 em->start = cur_offset;
1357 em->orig_start = found_key.offset - extent_offset;
1358 em->len = num_bytes;
1359 em->block_len = num_bytes;
1360 em->block_start = disk_bytenr;
1361 em->orig_block_len = disk_num_bytes;
1362 em->ram_bytes = ram_bytes;
1363 em->bdev = root->fs_info->fs_devices->latest_bdev;
1364 em->mod_start = em->start;
1365 em->mod_len = em->len;
1366 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1367 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1368 em->generation = -1;
1370 write_lock(&em_tree->lock);
1371 ret = add_extent_mapping(em_tree, em, 1);
1372 write_unlock(&em_tree->lock);
1373 if (ret != -EEXIST) {
1374 free_extent_map(em);
1377 btrfs_drop_extent_cache(inode, em->start,
1378 em->start + em->len - 1, 0);
1380 type = BTRFS_ORDERED_PREALLOC;
1382 type = BTRFS_ORDERED_NOCOW;
1385 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1386 num_bytes, num_bytes, type);
1387 BUG_ON(ret); /* -ENOMEM */
1389 if (root->root_key.objectid ==
1390 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1391 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1394 if (!nolock && nocow)
1395 btrfs_end_nocow_write(root);
1400 extent_clear_unlock_delalloc(inode, cur_offset,
1401 cur_offset + num_bytes - 1,
1402 locked_page, EXTENT_LOCKED |
1403 EXTENT_DELALLOC, PAGE_UNLOCK |
1405 if (!nolock && nocow)
1406 btrfs_end_nocow_write(root);
1407 cur_offset = extent_end;
1408 if (cur_offset > end)
1411 btrfs_release_path(path);
1413 if (cur_offset <= end && cow_start == (u64)-1) {
1414 cow_start = cur_offset;
1418 if (cow_start != (u64)-1) {
1419 ret = cow_file_range(inode, locked_page, cow_start, end,
1420 page_started, nr_written, 1);
1426 err = btrfs_end_transaction(trans, root);
1430 if (ret && cur_offset < end)
1431 extent_clear_unlock_delalloc(inode, cur_offset, end,
1432 locked_page, EXTENT_LOCKED |
1433 EXTENT_DELALLOC | EXTENT_DEFRAG |
1434 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1436 PAGE_SET_WRITEBACK |
1437 PAGE_END_WRITEBACK);
1438 btrfs_free_path(path);
1443 * extent_io.c call back to do delayed allocation processing
1445 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1446 u64 start, u64 end, int *page_started,
1447 unsigned long *nr_written)
1450 struct btrfs_root *root = BTRFS_I(inode)->root;
1452 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1453 ret = run_delalloc_nocow(inode, locked_page, start, end,
1454 page_started, 1, nr_written);
1455 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1456 ret = run_delalloc_nocow(inode, locked_page, start, end,
1457 page_started, 0, nr_written);
1458 } else if (!btrfs_test_opt(root, COMPRESS) &&
1459 !(BTRFS_I(inode)->force_compress) &&
1460 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1461 ret = cow_file_range(inode, locked_page, start, end,
1462 page_started, nr_written, 1);
1464 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1465 &BTRFS_I(inode)->runtime_flags);
1466 ret = cow_file_range_async(inode, locked_page, start, end,
1467 page_started, nr_written);
1472 static void btrfs_split_extent_hook(struct inode *inode,
1473 struct extent_state *orig, u64 split)
1475 /* not delalloc, ignore it */
1476 if (!(orig->state & EXTENT_DELALLOC))
1479 spin_lock(&BTRFS_I(inode)->lock);
1480 BTRFS_I(inode)->outstanding_extents++;
1481 spin_unlock(&BTRFS_I(inode)->lock);
1485 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1486 * extents so we can keep track of new extents that are just merged onto old
1487 * extents, such as when we are doing sequential writes, so we can properly
1488 * account for the metadata space we'll need.
1490 static void btrfs_merge_extent_hook(struct inode *inode,
1491 struct extent_state *new,
1492 struct extent_state *other)
1494 /* not delalloc, ignore it */
1495 if (!(other->state & EXTENT_DELALLOC))
1498 spin_lock(&BTRFS_I(inode)->lock);
1499 BTRFS_I(inode)->outstanding_extents--;
1500 spin_unlock(&BTRFS_I(inode)->lock);
1503 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1504 struct inode *inode)
1506 spin_lock(&root->delalloc_lock);
1507 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1508 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1509 &root->delalloc_inodes);
1510 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1511 &BTRFS_I(inode)->runtime_flags);
1512 root->nr_delalloc_inodes++;
1513 if (root->nr_delalloc_inodes == 1) {
1514 spin_lock(&root->fs_info->delalloc_root_lock);
1515 BUG_ON(!list_empty(&root->delalloc_root));
1516 list_add_tail(&root->delalloc_root,
1517 &root->fs_info->delalloc_roots);
1518 spin_unlock(&root->fs_info->delalloc_root_lock);
1521 spin_unlock(&root->delalloc_lock);
1524 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1525 struct inode *inode)
1527 spin_lock(&root->delalloc_lock);
1528 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1529 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1530 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1531 &BTRFS_I(inode)->runtime_flags);
1532 root->nr_delalloc_inodes--;
1533 if (!root->nr_delalloc_inodes) {
1534 spin_lock(&root->fs_info->delalloc_root_lock);
1535 BUG_ON(list_empty(&root->delalloc_root));
1536 list_del_init(&root->delalloc_root);
1537 spin_unlock(&root->fs_info->delalloc_root_lock);
1540 spin_unlock(&root->delalloc_lock);
1544 * extent_io.c set_bit_hook, used to track delayed allocation
1545 * bytes in this file, and to maintain the list of inodes that
1546 * have pending delalloc work to be done.
1548 static void btrfs_set_bit_hook(struct inode *inode,
1549 struct extent_state *state, unsigned long *bits)
1553 * set_bit and clear bit hooks normally require _irqsave/restore
1554 * but in this case, we are only testing for the DELALLOC
1555 * bit, which is only set or cleared with irqs on
1557 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1558 struct btrfs_root *root = BTRFS_I(inode)->root;
1559 u64 len = state->end + 1 - state->start;
1560 bool do_list = !btrfs_is_free_space_inode(inode);
1562 if (*bits & EXTENT_FIRST_DELALLOC) {
1563 *bits &= ~EXTENT_FIRST_DELALLOC;
1565 spin_lock(&BTRFS_I(inode)->lock);
1566 BTRFS_I(inode)->outstanding_extents++;
1567 spin_unlock(&BTRFS_I(inode)->lock);
1570 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1571 root->fs_info->delalloc_batch);
1572 spin_lock(&BTRFS_I(inode)->lock);
1573 BTRFS_I(inode)->delalloc_bytes += len;
1574 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1575 &BTRFS_I(inode)->runtime_flags))
1576 btrfs_add_delalloc_inodes(root, inode);
1577 spin_unlock(&BTRFS_I(inode)->lock);
1582 * extent_io.c clear_bit_hook, see set_bit_hook for why
1584 static void btrfs_clear_bit_hook(struct inode *inode,
1585 struct extent_state *state,
1586 unsigned long *bits)
1589 * set_bit and clear bit hooks normally require _irqsave/restore
1590 * but in this case, we are only testing for the DELALLOC
1591 * bit, which is only set or cleared with irqs on
1593 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1594 struct btrfs_root *root = BTRFS_I(inode)->root;
1595 u64 len = state->end + 1 - state->start;
1596 bool do_list = !btrfs_is_free_space_inode(inode);
1598 if (*bits & EXTENT_FIRST_DELALLOC) {
1599 *bits &= ~EXTENT_FIRST_DELALLOC;
1600 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1601 spin_lock(&BTRFS_I(inode)->lock);
1602 BTRFS_I(inode)->outstanding_extents--;
1603 spin_unlock(&BTRFS_I(inode)->lock);
1607 * We don't reserve metadata space for space cache inodes so we
1608 * don't need to call dellalloc_release_metadata if there is an
1611 if (*bits & EXTENT_DO_ACCOUNTING &&
1612 root != root->fs_info->tree_root)
1613 btrfs_delalloc_release_metadata(inode, len);
1615 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1616 && do_list && !(state->state & EXTENT_NORESERVE))
1617 btrfs_free_reserved_data_space(inode, len);
1619 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1620 root->fs_info->delalloc_batch);
1621 spin_lock(&BTRFS_I(inode)->lock);
1622 BTRFS_I(inode)->delalloc_bytes -= len;
1623 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1624 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1625 &BTRFS_I(inode)->runtime_flags))
1626 btrfs_del_delalloc_inode(root, inode);
1627 spin_unlock(&BTRFS_I(inode)->lock);
1632 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1633 * we don't create bios that span stripes or chunks
1635 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1636 size_t size, struct bio *bio,
1637 unsigned long bio_flags)
1639 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1640 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1645 if (bio_flags & EXTENT_BIO_COMPRESSED)
1648 length = bio->bi_iter.bi_size;
1649 map_length = length;
1650 ret = btrfs_map_block(root->fs_info, rw, logical,
1651 &map_length, NULL, 0);
1652 /* Will always return 0 with map_multi == NULL */
1654 if (map_length < length + size)
1660 * in order to insert checksums into the metadata in large chunks,
1661 * we wait until bio submission time. All the pages in the bio are
1662 * checksummed and sums are attached onto the ordered extent record.
1664 * At IO completion time the cums attached on the ordered extent record
1665 * are inserted into the btree
1667 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1668 struct bio *bio, int mirror_num,
1669 unsigned long bio_flags,
1672 struct btrfs_root *root = BTRFS_I(inode)->root;
1675 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1676 BUG_ON(ret); /* -ENOMEM */
1681 * in order to insert checksums into the metadata in large chunks,
1682 * we wait until bio submission time. All the pages in the bio are
1683 * checksummed and sums are attached onto the ordered extent record.
1685 * At IO completion time the cums attached on the ordered extent record
1686 * are inserted into the btree
1688 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1689 int mirror_num, unsigned long bio_flags,
1692 struct btrfs_root *root = BTRFS_I(inode)->root;
1695 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1697 bio_endio(bio, ret);
1702 * extent_io.c submission hook. This does the right thing for csum calculation
1703 * on write, or reading the csums from the tree before a read
1705 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1706 int mirror_num, unsigned long bio_flags,
1709 struct btrfs_root *root = BTRFS_I(inode)->root;
1713 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1715 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1717 if (btrfs_is_free_space_inode(inode))
1720 if (!(rw & REQ_WRITE)) {
1721 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1725 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1726 ret = btrfs_submit_compressed_read(inode, bio,
1730 } else if (!skip_sum) {
1731 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1736 } else if (async && !skip_sum) {
1737 /* csum items have already been cloned */
1738 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1740 /* we're doing a write, do the async checksumming */
1741 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1742 inode, rw, bio, mirror_num,
1743 bio_flags, bio_offset,
1744 __btrfs_submit_bio_start,
1745 __btrfs_submit_bio_done);
1747 } else if (!skip_sum) {
1748 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1754 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1758 bio_endio(bio, ret);
1763 * given a list of ordered sums record them in the inode. This happens
1764 * at IO completion time based on sums calculated at bio submission time.
1766 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1767 struct inode *inode, u64 file_offset,
1768 struct list_head *list)
1770 struct btrfs_ordered_sum *sum;
1772 list_for_each_entry(sum, list, list) {
1773 trans->adding_csums = 1;
1774 btrfs_csum_file_blocks(trans,
1775 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1776 trans->adding_csums = 0;
1781 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1782 struct extent_state **cached_state)
1784 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1785 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1786 cached_state, GFP_NOFS);
1789 /* see btrfs_writepage_start_hook for details on why this is required */
1790 struct btrfs_writepage_fixup {
1792 struct btrfs_work work;
1795 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1797 struct btrfs_writepage_fixup *fixup;
1798 struct btrfs_ordered_extent *ordered;
1799 struct extent_state *cached_state = NULL;
1801 struct inode *inode;
1806 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1810 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1811 ClearPageChecked(page);
1815 inode = page->mapping->host;
1816 page_start = page_offset(page);
1817 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1819 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1822 /* already ordered? We're done */
1823 if (PagePrivate2(page))
1826 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1828 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1829 page_end, &cached_state, GFP_NOFS);
1831 btrfs_start_ordered_extent(inode, ordered, 1);
1832 btrfs_put_ordered_extent(ordered);
1836 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1838 mapping_set_error(page->mapping, ret);
1839 end_extent_writepage(page, ret, page_start, page_end);
1840 ClearPageChecked(page);
1844 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1845 ClearPageChecked(page);
1846 set_page_dirty(page);
1848 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1849 &cached_state, GFP_NOFS);
1852 page_cache_release(page);
1857 * There are a few paths in the higher layers of the kernel that directly
1858 * set the page dirty bit without asking the filesystem if it is a
1859 * good idea. This causes problems because we want to make sure COW
1860 * properly happens and the data=ordered rules are followed.
1862 * In our case any range that doesn't have the ORDERED bit set
1863 * hasn't been properly setup for IO. We kick off an async process
1864 * to fix it up. The async helper will wait for ordered extents, set
1865 * the delalloc bit and make it safe to write the page.
1867 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1869 struct inode *inode = page->mapping->host;
1870 struct btrfs_writepage_fixup *fixup;
1871 struct btrfs_root *root = BTRFS_I(inode)->root;
1873 /* this page is properly in the ordered list */
1874 if (TestClearPagePrivate2(page))
1877 if (PageChecked(page))
1880 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1884 SetPageChecked(page);
1885 page_cache_get(page);
1886 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
1887 btrfs_writepage_fixup_worker, NULL, NULL);
1889 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1893 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1894 struct inode *inode, u64 file_pos,
1895 u64 disk_bytenr, u64 disk_num_bytes,
1896 u64 num_bytes, u64 ram_bytes,
1897 u8 compression, u8 encryption,
1898 u16 other_encoding, int extent_type)
1900 struct btrfs_root *root = BTRFS_I(inode)->root;
1901 struct btrfs_file_extent_item *fi;
1902 struct btrfs_path *path;
1903 struct extent_buffer *leaf;
1904 struct btrfs_key ins;
1905 int extent_inserted = 0;
1908 path = btrfs_alloc_path();
1913 * we may be replacing one extent in the tree with another.
1914 * The new extent is pinned in the extent map, and we don't want
1915 * to drop it from the cache until it is completely in the btree.
1917 * So, tell btrfs_drop_extents to leave this extent in the cache.
1918 * the caller is expected to unpin it and allow it to be merged
1921 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1922 file_pos + num_bytes, NULL, 0,
1923 1, sizeof(*fi), &extent_inserted);
1927 if (!extent_inserted) {
1928 ins.objectid = btrfs_ino(inode);
1929 ins.offset = file_pos;
1930 ins.type = BTRFS_EXTENT_DATA_KEY;
1932 path->leave_spinning = 1;
1933 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1938 leaf = path->nodes[0];
1939 fi = btrfs_item_ptr(leaf, path->slots[0],
1940 struct btrfs_file_extent_item);
1941 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1942 btrfs_set_file_extent_type(leaf, fi, extent_type);
1943 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1944 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1945 btrfs_set_file_extent_offset(leaf, fi, 0);
1946 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1947 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1948 btrfs_set_file_extent_compression(leaf, fi, compression);
1949 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1950 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1952 btrfs_mark_buffer_dirty(leaf);
1953 btrfs_release_path(path);
1955 inode_add_bytes(inode, num_bytes);
1957 ins.objectid = disk_bytenr;
1958 ins.offset = disk_num_bytes;
1959 ins.type = BTRFS_EXTENT_ITEM_KEY;
1960 ret = btrfs_alloc_reserved_file_extent(trans, root,
1961 root->root_key.objectid,
1962 btrfs_ino(inode), file_pos, &ins);
1964 btrfs_free_path(path);
1969 /* snapshot-aware defrag */
1970 struct sa_defrag_extent_backref {
1971 struct rb_node node;
1972 struct old_sa_defrag_extent *old;
1981 struct old_sa_defrag_extent {
1982 struct list_head list;
1983 struct new_sa_defrag_extent *new;
1992 struct new_sa_defrag_extent {
1993 struct rb_root root;
1994 struct list_head head;
1995 struct btrfs_path *path;
1996 struct inode *inode;
2004 static int backref_comp(struct sa_defrag_extent_backref *b1,
2005 struct sa_defrag_extent_backref *b2)
2007 if (b1->root_id < b2->root_id)
2009 else if (b1->root_id > b2->root_id)
2012 if (b1->inum < b2->inum)
2014 else if (b1->inum > b2->inum)
2017 if (b1->file_pos < b2->file_pos)
2019 else if (b1->file_pos > b2->file_pos)
2023 * [------------------------------] ===> (a range of space)
2024 * |<--->| |<---->| =============> (fs/file tree A)
2025 * |<---------------------------->| ===> (fs/file tree B)
2027 * A range of space can refer to two file extents in one tree while
2028 * refer to only one file extent in another tree.
2030 * So we may process a disk offset more than one time(two extents in A)
2031 * and locate at the same extent(one extent in B), then insert two same
2032 * backrefs(both refer to the extent in B).
2037 static void backref_insert(struct rb_root *root,
2038 struct sa_defrag_extent_backref *backref)
2040 struct rb_node **p = &root->rb_node;
2041 struct rb_node *parent = NULL;
2042 struct sa_defrag_extent_backref *entry;
2047 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2049 ret = backref_comp(backref, entry);
2053 p = &(*p)->rb_right;
2056 rb_link_node(&backref->node, parent, p);
2057 rb_insert_color(&backref->node, root);
2061 * Note the backref might has changed, and in this case we just return 0.
2063 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2066 struct btrfs_file_extent_item *extent;
2067 struct btrfs_fs_info *fs_info;
2068 struct old_sa_defrag_extent *old = ctx;
2069 struct new_sa_defrag_extent *new = old->new;
2070 struct btrfs_path *path = new->path;
2071 struct btrfs_key key;
2072 struct btrfs_root *root;
2073 struct sa_defrag_extent_backref *backref;
2074 struct extent_buffer *leaf;
2075 struct inode *inode = new->inode;
2081 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2082 inum == btrfs_ino(inode))
2085 key.objectid = root_id;
2086 key.type = BTRFS_ROOT_ITEM_KEY;
2087 key.offset = (u64)-1;
2089 fs_info = BTRFS_I(inode)->root->fs_info;
2090 root = btrfs_read_fs_root_no_name(fs_info, &key);
2092 if (PTR_ERR(root) == -ENOENT)
2095 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2096 inum, offset, root_id);
2097 return PTR_ERR(root);
2100 key.objectid = inum;
2101 key.type = BTRFS_EXTENT_DATA_KEY;
2102 if (offset > (u64)-1 << 32)
2105 key.offset = offset;
2107 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2108 if (WARN_ON(ret < 0))
2115 leaf = path->nodes[0];
2116 slot = path->slots[0];
2118 if (slot >= btrfs_header_nritems(leaf)) {
2119 ret = btrfs_next_leaf(root, path);
2122 } else if (ret > 0) {
2131 btrfs_item_key_to_cpu(leaf, &key, slot);
2133 if (key.objectid > inum)
2136 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2139 extent = btrfs_item_ptr(leaf, slot,
2140 struct btrfs_file_extent_item);
2142 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2146 * 'offset' refers to the exact key.offset,
2147 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2148 * (key.offset - extent_offset).
2150 if (key.offset != offset)
2153 extent_offset = btrfs_file_extent_offset(leaf, extent);
2154 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2156 if (extent_offset >= old->extent_offset + old->offset +
2157 old->len || extent_offset + num_bytes <=
2158 old->extent_offset + old->offset)
2163 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2169 backref->root_id = root_id;
2170 backref->inum = inum;
2171 backref->file_pos = offset;
2172 backref->num_bytes = num_bytes;
2173 backref->extent_offset = extent_offset;
2174 backref->generation = btrfs_file_extent_generation(leaf, extent);
2176 backref_insert(&new->root, backref);
2179 btrfs_release_path(path);
2184 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2185 struct new_sa_defrag_extent *new)
2187 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2188 struct old_sa_defrag_extent *old, *tmp;
2193 list_for_each_entry_safe(old, tmp, &new->head, list) {
2194 ret = iterate_inodes_from_logical(old->bytenr +
2195 old->extent_offset, fs_info,
2196 path, record_one_backref,
2198 if (ret < 0 && ret != -ENOENT)
2201 /* no backref to be processed for this extent */
2203 list_del(&old->list);
2208 if (list_empty(&new->head))
2214 static int relink_is_mergable(struct extent_buffer *leaf,
2215 struct btrfs_file_extent_item *fi,
2216 struct new_sa_defrag_extent *new)
2218 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2221 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2224 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2227 if (btrfs_file_extent_encryption(leaf, fi) ||
2228 btrfs_file_extent_other_encoding(leaf, fi))
2235 * Note the backref might has changed, and in this case we just return 0.
2237 static noinline int relink_extent_backref(struct btrfs_path *path,
2238 struct sa_defrag_extent_backref *prev,
2239 struct sa_defrag_extent_backref *backref)
2241 struct btrfs_file_extent_item *extent;
2242 struct btrfs_file_extent_item *item;
2243 struct btrfs_ordered_extent *ordered;
2244 struct btrfs_trans_handle *trans;
2245 struct btrfs_fs_info *fs_info;
2246 struct btrfs_root *root;
2247 struct btrfs_key key;
2248 struct extent_buffer *leaf;
2249 struct old_sa_defrag_extent *old = backref->old;
2250 struct new_sa_defrag_extent *new = old->new;
2251 struct inode *src_inode = new->inode;
2252 struct inode *inode;
2253 struct extent_state *cached = NULL;
2262 if (prev && prev->root_id == backref->root_id &&
2263 prev->inum == backref->inum &&
2264 prev->file_pos + prev->num_bytes == backref->file_pos)
2267 /* step 1: get root */
2268 key.objectid = backref->root_id;
2269 key.type = BTRFS_ROOT_ITEM_KEY;
2270 key.offset = (u64)-1;
2272 fs_info = BTRFS_I(src_inode)->root->fs_info;
2273 index = srcu_read_lock(&fs_info->subvol_srcu);
2275 root = btrfs_read_fs_root_no_name(fs_info, &key);
2277 srcu_read_unlock(&fs_info->subvol_srcu, index);
2278 if (PTR_ERR(root) == -ENOENT)
2280 return PTR_ERR(root);
2283 if (btrfs_root_readonly(root)) {
2284 srcu_read_unlock(&fs_info->subvol_srcu, index);
2288 /* step 2: get inode */
2289 key.objectid = backref->inum;
2290 key.type = BTRFS_INODE_ITEM_KEY;
2293 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2294 if (IS_ERR(inode)) {
2295 srcu_read_unlock(&fs_info->subvol_srcu, index);
2299 srcu_read_unlock(&fs_info->subvol_srcu, index);
2301 /* step 3: relink backref */
2302 lock_start = backref->file_pos;
2303 lock_end = backref->file_pos + backref->num_bytes - 1;
2304 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2307 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2309 btrfs_put_ordered_extent(ordered);
2313 trans = btrfs_join_transaction(root);
2314 if (IS_ERR(trans)) {
2315 ret = PTR_ERR(trans);
2319 key.objectid = backref->inum;
2320 key.type = BTRFS_EXTENT_DATA_KEY;
2321 key.offset = backref->file_pos;
2323 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2326 } else if (ret > 0) {
2331 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2332 struct btrfs_file_extent_item);
2334 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2335 backref->generation)
2338 btrfs_release_path(path);
2340 start = backref->file_pos;
2341 if (backref->extent_offset < old->extent_offset + old->offset)
2342 start += old->extent_offset + old->offset -
2343 backref->extent_offset;
2345 len = min(backref->extent_offset + backref->num_bytes,
2346 old->extent_offset + old->offset + old->len);
2347 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2349 ret = btrfs_drop_extents(trans, root, inode, start,
2354 key.objectid = btrfs_ino(inode);
2355 key.type = BTRFS_EXTENT_DATA_KEY;
2358 path->leave_spinning = 1;
2360 struct btrfs_file_extent_item *fi;
2362 struct btrfs_key found_key;
2364 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2369 leaf = path->nodes[0];
2370 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2372 fi = btrfs_item_ptr(leaf, path->slots[0],
2373 struct btrfs_file_extent_item);
2374 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2376 if (extent_len + found_key.offset == start &&
2377 relink_is_mergable(leaf, fi, new)) {
2378 btrfs_set_file_extent_num_bytes(leaf, fi,
2380 btrfs_mark_buffer_dirty(leaf);
2381 inode_add_bytes(inode, len);
2387 btrfs_release_path(path);
2392 ret = btrfs_insert_empty_item(trans, root, path, &key,
2395 btrfs_abort_transaction(trans, root, ret);
2399 leaf = path->nodes[0];
2400 item = btrfs_item_ptr(leaf, path->slots[0],
2401 struct btrfs_file_extent_item);
2402 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2403 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2404 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2405 btrfs_set_file_extent_num_bytes(leaf, item, len);
2406 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2407 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2408 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2409 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2410 btrfs_set_file_extent_encryption(leaf, item, 0);
2411 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2413 btrfs_mark_buffer_dirty(leaf);
2414 inode_add_bytes(inode, len);
2415 btrfs_release_path(path);
2417 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2419 backref->root_id, backref->inum,
2420 new->file_pos, 0); /* start - extent_offset */
2422 btrfs_abort_transaction(trans, root, ret);
2428 btrfs_release_path(path);
2429 path->leave_spinning = 0;
2430 btrfs_end_transaction(trans, root);
2432 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2438 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2440 struct old_sa_defrag_extent *old, *tmp;
2445 list_for_each_entry_safe(old, tmp, &new->head, list) {
2446 list_del(&old->list);
2452 static void relink_file_extents(struct new_sa_defrag_extent *new)
2454 struct btrfs_path *path;
2455 struct sa_defrag_extent_backref *backref;
2456 struct sa_defrag_extent_backref *prev = NULL;
2457 struct inode *inode;
2458 struct btrfs_root *root;
2459 struct rb_node *node;
2463 root = BTRFS_I(inode)->root;
2465 path = btrfs_alloc_path();
2469 if (!record_extent_backrefs(path, new)) {
2470 btrfs_free_path(path);
2473 btrfs_release_path(path);
2476 node = rb_first(&new->root);
2479 rb_erase(node, &new->root);
2481 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2483 ret = relink_extent_backref(path, prev, backref);
2496 btrfs_free_path(path);
2498 free_sa_defrag_extent(new);
2500 atomic_dec(&root->fs_info->defrag_running);
2501 wake_up(&root->fs_info->transaction_wait);
2504 static struct new_sa_defrag_extent *
2505 record_old_file_extents(struct inode *inode,
2506 struct btrfs_ordered_extent *ordered)
2508 struct btrfs_root *root = BTRFS_I(inode)->root;
2509 struct btrfs_path *path;
2510 struct btrfs_key key;
2511 struct old_sa_defrag_extent *old;
2512 struct new_sa_defrag_extent *new;
2515 new = kmalloc(sizeof(*new), GFP_NOFS);
2520 new->file_pos = ordered->file_offset;
2521 new->len = ordered->len;
2522 new->bytenr = ordered->start;
2523 new->disk_len = ordered->disk_len;
2524 new->compress_type = ordered->compress_type;
2525 new->root = RB_ROOT;
2526 INIT_LIST_HEAD(&new->head);
2528 path = btrfs_alloc_path();
2532 key.objectid = btrfs_ino(inode);
2533 key.type = BTRFS_EXTENT_DATA_KEY;
2534 key.offset = new->file_pos;
2536 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2539 if (ret > 0 && path->slots[0] > 0)
2542 /* find out all the old extents for the file range */
2544 struct btrfs_file_extent_item *extent;
2545 struct extent_buffer *l;
2554 slot = path->slots[0];
2556 if (slot >= btrfs_header_nritems(l)) {
2557 ret = btrfs_next_leaf(root, path);
2565 btrfs_item_key_to_cpu(l, &key, slot);
2567 if (key.objectid != btrfs_ino(inode))
2569 if (key.type != BTRFS_EXTENT_DATA_KEY)
2571 if (key.offset >= new->file_pos + new->len)
2574 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2576 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2577 if (key.offset + num_bytes < new->file_pos)
2580 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2584 extent_offset = btrfs_file_extent_offset(l, extent);
2586 old = kmalloc(sizeof(*old), GFP_NOFS);
2590 offset = max(new->file_pos, key.offset);
2591 end = min(new->file_pos + new->len, key.offset + num_bytes);
2593 old->bytenr = disk_bytenr;
2594 old->extent_offset = extent_offset;
2595 old->offset = offset - key.offset;
2596 old->len = end - offset;
2599 list_add_tail(&old->list, &new->head);
2605 btrfs_free_path(path);
2606 atomic_inc(&root->fs_info->defrag_running);
2611 btrfs_free_path(path);
2613 free_sa_defrag_extent(new);
2617 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2620 struct btrfs_block_group_cache *cache;
2622 cache = btrfs_lookup_block_group(root->fs_info, start);
2625 spin_lock(&cache->lock);
2626 cache->delalloc_bytes -= len;
2627 spin_unlock(&cache->lock);
2629 btrfs_put_block_group(cache);
2632 /* as ordered data IO finishes, this gets called so we can finish
2633 * an ordered extent if the range of bytes in the file it covers are
2636 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2638 struct inode *inode = ordered_extent->inode;
2639 struct btrfs_root *root = BTRFS_I(inode)->root;
2640 struct btrfs_trans_handle *trans = NULL;
2641 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2642 struct extent_state *cached_state = NULL;
2643 struct new_sa_defrag_extent *new = NULL;
2644 int compress_type = 0;
2646 u64 logical_len = ordered_extent->len;
2648 bool truncated = false;
2650 nolock = btrfs_is_free_space_inode(inode);
2652 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2657 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2659 logical_len = ordered_extent->truncated_len;
2660 /* Truncated the entire extent, don't bother adding */
2665 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2666 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2667 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2669 trans = btrfs_join_transaction_nolock(root);
2671 trans = btrfs_join_transaction(root);
2672 if (IS_ERR(trans)) {
2673 ret = PTR_ERR(trans);
2677 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2678 ret = btrfs_update_inode_fallback(trans, root, inode);
2679 if (ret) /* -ENOMEM or corruption */
2680 btrfs_abort_transaction(trans, root, ret);
2684 lock_extent_bits(io_tree, ordered_extent->file_offset,
2685 ordered_extent->file_offset + ordered_extent->len - 1,
2688 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2689 ordered_extent->file_offset + ordered_extent->len - 1,
2690 EXTENT_DEFRAG, 1, cached_state);
2692 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2693 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2694 /* the inode is shared */
2695 new = record_old_file_extents(inode, ordered_extent);
2697 clear_extent_bit(io_tree, ordered_extent->file_offset,
2698 ordered_extent->file_offset + ordered_extent->len - 1,
2699 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2703 trans = btrfs_join_transaction_nolock(root);
2705 trans = btrfs_join_transaction(root);
2706 if (IS_ERR(trans)) {
2707 ret = PTR_ERR(trans);
2712 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2714 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2715 compress_type = ordered_extent->compress_type;
2716 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2717 BUG_ON(compress_type);
2718 ret = btrfs_mark_extent_written(trans, inode,
2719 ordered_extent->file_offset,
2720 ordered_extent->file_offset +
2723 BUG_ON(root == root->fs_info->tree_root);
2724 ret = insert_reserved_file_extent(trans, inode,
2725 ordered_extent->file_offset,
2726 ordered_extent->start,
2727 ordered_extent->disk_len,
2728 logical_len, logical_len,
2729 compress_type, 0, 0,
2730 BTRFS_FILE_EXTENT_REG);
2732 btrfs_release_delalloc_bytes(root,
2733 ordered_extent->start,
2734 ordered_extent->disk_len);
2736 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2737 ordered_extent->file_offset, ordered_extent->len,
2740 btrfs_abort_transaction(trans, root, ret);
2744 add_pending_csums(trans, inode, ordered_extent->file_offset,
2745 &ordered_extent->list);
2747 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2748 ret = btrfs_update_inode_fallback(trans, root, inode);
2749 if (ret) { /* -ENOMEM or corruption */
2750 btrfs_abort_transaction(trans, root, ret);
2755 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2756 ordered_extent->file_offset +
2757 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2759 if (root != root->fs_info->tree_root)
2760 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2762 btrfs_end_transaction(trans, root);
2764 if (ret || truncated) {
2768 start = ordered_extent->file_offset + logical_len;
2770 start = ordered_extent->file_offset;
2771 end = ordered_extent->file_offset + ordered_extent->len - 1;
2772 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2774 /* Drop the cache for the part of the extent we didn't write. */
2775 btrfs_drop_extent_cache(inode, start, end, 0);
2778 * If the ordered extent had an IOERR or something else went
2779 * wrong we need to return the space for this ordered extent
2780 * back to the allocator. We only free the extent in the
2781 * truncated case if we didn't write out the extent at all.
2783 if ((ret || !logical_len) &&
2784 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2785 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2786 btrfs_free_reserved_extent(root, ordered_extent->start,
2787 ordered_extent->disk_len, 1);
2792 * This needs to be done to make sure anybody waiting knows we are done
2793 * updating everything for this ordered extent.
2795 btrfs_remove_ordered_extent(inode, ordered_extent);
2797 /* for snapshot-aware defrag */
2800 free_sa_defrag_extent(new);
2801 atomic_dec(&root->fs_info->defrag_running);
2803 relink_file_extents(new);
2808 btrfs_put_ordered_extent(ordered_extent);
2809 /* once for the tree */
2810 btrfs_put_ordered_extent(ordered_extent);
2815 static void finish_ordered_fn(struct btrfs_work *work)
2817 struct btrfs_ordered_extent *ordered_extent;
2818 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2819 btrfs_finish_ordered_io(ordered_extent);
2822 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2823 struct extent_state *state, int uptodate)
2825 struct inode *inode = page->mapping->host;
2826 struct btrfs_root *root = BTRFS_I(inode)->root;
2827 struct btrfs_ordered_extent *ordered_extent = NULL;
2828 struct btrfs_workqueue *wq;
2829 btrfs_work_func_t func;
2831 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2833 ClearPagePrivate2(page);
2834 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2835 end - start + 1, uptodate))
2838 if (btrfs_is_free_space_inode(inode)) {
2839 wq = root->fs_info->endio_freespace_worker;
2840 func = btrfs_freespace_write_helper;
2842 wq = root->fs_info->endio_write_workers;
2843 func = btrfs_endio_write_helper;
2846 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
2848 btrfs_queue_work(wq, &ordered_extent->work);
2854 * when reads are done, we need to check csums to verify the data is correct
2855 * if there's a match, we allow the bio to finish. If not, the code in
2856 * extent_io.c will try to find good copies for us.
2858 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2859 u64 phy_offset, struct page *page,
2860 u64 start, u64 end, int mirror)
2862 size_t offset = start - page_offset(page);
2863 struct inode *inode = page->mapping->host;
2864 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2866 struct btrfs_root *root = BTRFS_I(inode)->root;
2869 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2870 DEFAULT_RATELIMIT_BURST);
2872 if (PageChecked(page)) {
2873 ClearPageChecked(page);
2877 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2880 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2881 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2882 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2887 phy_offset >>= inode->i_sb->s_blocksize_bits;
2888 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2890 kaddr = kmap_atomic(page);
2891 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2892 btrfs_csum_final(csum, (char *)&csum);
2893 if (csum != csum_expected)
2896 kunmap_atomic(kaddr);
2901 if (__ratelimit(&_rs))
2902 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2903 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2904 memset(kaddr + offset, 1, end - start + 1);
2905 flush_dcache_page(page);
2906 kunmap_atomic(kaddr);
2907 if (csum_expected == 0)
2912 struct delayed_iput {
2913 struct list_head list;
2914 struct inode *inode;
2917 /* JDM: If this is fs-wide, why can't we add a pointer to
2918 * btrfs_inode instead and avoid the allocation? */
2919 void btrfs_add_delayed_iput(struct inode *inode)
2921 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2922 struct delayed_iput *delayed;
2924 if (atomic_add_unless(&inode->i_count, -1, 1))
2927 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2928 delayed->inode = inode;
2930 spin_lock(&fs_info->delayed_iput_lock);
2931 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2932 spin_unlock(&fs_info->delayed_iput_lock);
2935 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2938 struct btrfs_fs_info *fs_info = root->fs_info;
2939 struct delayed_iput *delayed;
2942 spin_lock(&fs_info->delayed_iput_lock);
2943 empty = list_empty(&fs_info->delayed_iputs);
2944 spin_unlock(&fs_info->delayed_iput_lock);
2948 spin_lock(&fs_info->delayed_iput_lock);
2949 list_splice_init(&fs_info->delayed_iputs, &list);
2950 spin_unlock(&fs_info->delayed_iput_lock);
2952 while (!list_empty(&list)) {
2953 delayed = list_entry(list.next, struct delayed_iput, list);
2954 list_del(&delayed->list);
2955 iput(delayed->inode);
2961 * This is called in transaction commit time. If there are no orphan
2962 * files in the subvolume, it removes orphan item and frees block_rsv
2965 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2966 struct btrfs_root *root)
2968 struct btrfs_block_rsv *block_rsv;
2971 if (atomic_read(&root->orphan_inodes) ||
2972 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2975 spin_lock(&root->orphan_lock);
2976 if (atomic_read(&root->orphan_inodes)) {
2977 spin_unlock(&root->orphan_lock);
2981 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2982 spin_unlock(&root->orphan_lock);
2986 block_rsv = root->orphan_block_rsv;
2987 root->orphan_block_rsv = NULL;
2988 spin_unlock(&root->orphan_lock);
2990 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
2991 btrfs_root_refs(&root->root_item) > 0) {
2992 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2993 root->root_key.objectid);
2995 btrfs_abort_transaction(trans, root, ret);
2997 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3002 WARN_ON(block_rsv->size > 0);
3003 btrfs_free_block_rsv(root, block_rsv);
3008 * This creates an orphan entry for the given inode in case something goes
3009 * wrong in the middle of an unlink/truncate.
3011 * NOTE: caller of this function should reserve 5 units of metadata for
3014 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3016 struct btrfs_root *root = BTRFS_I(inode)->root;
3017 struct btrfs_block_rsv *block_rsv = NULL;
3022 if (!root->orphan_block_rsv) {
3023 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3028 spin_lock(&root->orphan_lock);
3029 if (!root->orphan_block_rsv) {
3030 root->orphan_block_rsv = block_rsv;
3031 } else if (block_rsv) {
3032 btrfs_free_block_rsv(root, block_rsv);
3036 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3037 &BTRFS_I(inode)->runtime_flags)) {
3040 * For proper ENOSPC handling, we should do orphan
3041 * cleanup when mounting. But this introduces backward
3042 * compatibility issue.
3044 if (!xchg(&root->orphan_item_inserted, 1))
3050 atomic_inc(&root->orphan_inodes);
3053 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3054 &BTRFS_I(inode)->runtime_flags))
3056 spin_unlock(&root->orphan_lock);
3058 /* grab metadata reservation from transaction handle */
3060 ret = btrfs_orphan_reserve_metadata(trans, inode);
3061 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3064 /* insert an orphan item to track this unlinked/truncated file */
3066 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3068 atomic_dec(&root->orphan_inodes);
3070 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3071 &BTRFS_I(inode)->runtime_flags);
3072 btrfs_orphan_release_metadata(inode);
3074 if (ret != -EEXIST) {
3075 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3076 &BTRFS_I(inode)->runtime_flags);
3077 btrfs_abort_transaction(trans, root, ret);
3084 /* insert an orphan item to track subvolume contains orphan files */
3086 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3087 root->root_key.objectid);
3088 if (ret && ret != -EEXIST) {
3089 btrfs_abort_transaction(trans, root, ret);
3097 * We have done the truncate/delete so we can go ahead and remove the orphan
3098 * item for this particular inode.
3100 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3101 struct inode *inode)
3103 struct btrfs_root *root = BTRFS_I(inode)->root;
3104 int delete_item = 0;
3105 int release_rsv = 0;
3108 spin_lock(&root->orphan_lock);
3109 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3110 &BTRFS_I(inode)->runtime_flags))
3113 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3114 &BTRFS_I(inode)->runtime_flags))
3116 spin_unlock(&root->orphan_lock);
3119 atomic_dec(&root->orphan_inodes);
3121 ret = btrfs_del_orphan_item(trans, root,
3126 btrfs_orphan_release_metadata(inode);
3132 * this cleans up any orphans that may be left on the list from the last use
3135 int btrfs_orphan_cleanup(struct btrfs_root *root)
3137 struct btrfs_path *path;
3138 struct extent_buffer *leaf;
3139 struct btrfs_key key, found_key;
3140 struct btrfs_trans_handle *trans;
3141 struct inode *inode;
3142 u64 last_objectid = 0;
3143 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3145 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3148 path = btrfs_alloc_path();
3155 key.objectid = BTRFS_ORPHAN_OBJECTID;
3156 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3157 key.offset = (u64)-1;
3160 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3165 * if ret == 0 means we found what we were searching for, which
3166 * is weird, but possible, so only screw with path if we didn't
3167 * find the key and see if we have stuff that matches
3171 if (path->slots[0] == 0)
3176 /* pull out the item */
3177 leaf = path->nodes[0];
3178 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3180 /* make sure the item matches what we want */
3181 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3183 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3186 /* release the path since we're done with it */
3187 btrfs_release_path(path);
3190 * this is where we are basically btrfs_lookup, without the
3191 * crossing root thing. we store the inode number in the
3192 * offset of the orphan item.
3195 if (found_key.offset == last_objectid) {
3196 btrfs_err(root->fs_info,
3197 "Error removing orphan entry, stopping orphan cleanup");
3202 last_objectid = found_key.offset;
3204 found_key.objectid = found_key.offset;
3205 found_key.type = BTRFS_INODE_ITEM_KEY;
3206 found_key.offset = 0;
3207 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3208 ret = PTR_ERR_OR_ZERO(inode);
3209 if (ret && ret != -ESTALE)
3212 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3213 struct btrfs_root *dead_root;
3214 struct btrfs_fs_info *fs_info = root->fs_info;
3215 int is_dead_root = 0;
3218 * this is an orphan in the tree root. Currently these
3219 * could come from 2 sources:
3220 * a) a snapshot deletion in progress
3221 * b) a free space cache inode
3222 * We need to distinguish those two, as the snapshot
3223 * orphan must not get deleted.
3224 * find_dead_roots already ran before us, so if this
3225 * is a snapshot deletion, we should find the root
3226 * in the dead_roots list
3228 spin_lock(&fs_info->trans_lock);
3229 list_for_each_entry(dead_root, &fs_info->dead_roots,
3231 if (dead_root->root_key.objectid ==
3232 found_key.objectid) {
3237 spin_unlock(&fs_info->trans_lock);
3239 /* prevent this orphan from being found again */
3240 key.offset = found_key.objectid - 1;
3245 * Inode is already gone but the orphan item is still there,
3246 * kill the orphan item.
3248 if (ret == -ESTALE) {
3249 trans = btrfs_start_transaction(root, 1);
3250 if (IS_ERR(trans)) {
3251 ret = PTR_ERR(trans);
3254 btrfs_debug(root->fs_info, "auto deleting %Lu",
3255 found_key.objectid);
3256 ret = btrfs_del_orphan_item(trans, root,
3257 found_key.objectid);
3258 btrfs_end_transaction(trans, root);
3265 * add this inode to the orphan list so btrfs_orphan_del does
3266 * the proper thing when we hit it
3268 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3269 &BTRFS_I(inode)->runtime_flags);
3270 atomic_inc(&root->orphan_inodes);
3272 /* if we have links, this was a truncate, lets do that */
3273 if (inode->i_nlink) {
3274 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3280 /* 1 for the orphan item deletion. */
3281 trans = btrfs_start_transaction(root, 1);
3282 if (IS_ERR(trans)) {
3284 ret = PTR_ERR(trans);
3287 ret = btrfs_orphan_add(trans, inode);
3288 btrfs_end_transaction(trans, root);
3294 ret = btrfs_truncate(inode);
3296 btrfs_orphan_del(NULL, inode);
3301 /* this will do delete_inode and everything for us */
3306 /* release the path since we're done with it */
3307 btrfs_release_path(path);
3309 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3311 if (root->orphan_block_rsv)
3312 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3315 if (root->orphan_block_rsv ||
3316 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3317 trans = btrfs_join_transaction(root);
3319 btrfs_end_transaction(trans, root);
3323 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3325 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3329 btrfs_crit(root->fs_info,
3330 "could not do orphan cleanup %d", ret);
3331 btrfs_free_path(path);
3336 * very simple check to peek ahead in the leaf looking for xattrs. If we
3337 * don't find any xattrs, we know there can't be any acls.
3339 * slot is the slot the inode is in, objectid is the objectid of the inode
3341 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3342 int slot, u64 objectid,
3343 int *first_xattr_slot)
3345 u32 nritems = btrfs_header_nritems(leaf);
3346 struct btrfs_key found_key;
3347 static u64 xattr_access = 0;
3348 static u64 xattr_default = 0;
3351 if (!xattr_access) {
3352 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3353 strlen(POSIX_ACL_XATTR_ACCESS));
3354 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3355 strlen(POSIX_ACL_XATTR_DEFAULT));
3359 *first_xattr_slot = -1;
3360 while (slot < nritems) {
3361 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3363 /* we found a different objectid, there must not be acls */
3364 if (found_key.objectid != objectid)
3367 /* we found an xattr, assume we've got an acl */
3368 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3369 if (*first_xattr_slot == -1)
3370 *first_xattr_slot = slot;
3371 if (found_key.offset == xattr_access ||
3372 found_key.offset == xattr_default)
3377 * we found a key greater than an xattr key, there can't
3378 * be any acls later on
3380 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3387 * it goes inode, inode backrefs, xattrs, extents,
3388 * so if there are a ton of hard links to an inode there can
3389 * be a lot of backrefs. Don't waste time searching too hard,
3390 * this is just an optimization
3395 /* we hit the end of the leaf before we found an xattr or
3396 * something larger than an xattr. We have to assume the inode
3399 if (*first_xattr_slot == -1)
3400 *first_xattr_slot = slot;
3405 * read an inode from the btree into the in-memory inode
3407 static void btrfs_read_locked_inode(struct inode *inode)
3409 struct btrfs_path *path;
3410 struct extent_buffer *leaf;
3411 struct btrfs_inode_item *inode_item;
3412 struct btrfs_timespec *tspec;
3413 struct btrfs_root *root = BTRFS_I(inode)->root;
3414 struct btrfs_key location;
3419 bool filled = false;
3420 int first_xattr_slot;
3422 ret = btrfs_fill_inode(inode, &rdev);
3426 path = btrfs_alloc_path();
3430 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3432 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3436 leaf = path->nodes[0];
3441 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3442 struct btrfs_inode_item);
3443 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3444 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3445 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3446 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3447 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3449 tspec = btrfs_inode_atime(inode_item);
3450 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3451 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3453 tspec = btrfs_inode_mtime(inode_item);
3454 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3455 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3457 tspec = btrfs_inode_ctime(inode_item);
3458 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3459 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3461 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3462 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3463 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3466 * If we were modified in the current generation and evicted from memory
3467 * and then re-read we need to do a full sync since we don't have any
3468 * idea about which extents were modified before we were evicted from
3471 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3472 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3473 &BTRFS_I(inode)->runtime_flags);
3475 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3476 inode->i_generation = BTRFS_I(inode)->generation;
3478 rdev = btrfs_inode_rdev(leaf, inode_item);
3480 BTRFS_I(inode)->index_cnt = (u64)-1;
3481 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3485 if (inode->i_nlink != 1 ||
3486 path->slots[0] >= btrfs_header_nritems(leaf))
3489 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3490 if (location.objectid != btrfs_ino(inode))
3493 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3494 if (location.type == BTRFS_INODE_REF_KEY) {
3495 struct btrfs_inode_ref *ref;
3497 ref = (struct btrfs_inode_ref *)ptr;
3498 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3499 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3500 struct btrfs_inode_extref *extref;
3502 extref = (struct btrfs_inode_extref *)ptr;
3503 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3508 * try to precache a NULL acl entry for files that don't have
3509 * any xattrs or acls
3511 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3512 btrfs_ino(inode), &first_xattr_slot);
3513 if (first_xattr_slot != -1) {
3514 path->slots[0] = first_xattr_slot;
3515 ret = btrfs_load_inode_props(inode, path);
3517 btrfs_err(root->fs_info,
3518 "error loading props for ino %llu (root %llu): %d",
3520 root->root_key.objectid, ret);
3522 btrfs_free_path(path);
3525 cache_no_acl(inode);
3527 switch (inode->i_mode & S_IFMT) {
3529 inode->i_mapping->a_ops = &btrfs_aops;
3530 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3531 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3532 inode->i_fop = &btrfs_file_operations;
3533 inode->i_op = &btrfs_file_inode_operations;
3536 inode->i_fop = &btrfs_dir_file_operations;
3537 if (root == root->fs_info->tree_root)
3538 inode->i_op = &btrfs_dir_ro_inode_operations;
3540 inode->i_op = &btrfs_dir_inode_operations;
3543 inode->i_op = &btrfs_symlink_inode_operations;
3544 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3545 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3548 inode->i_op = &btrfs_special_inode_operations;
3549 init_special_inode(inode, inode->i_mode, rdev);
3553 btrfs_update_iflags(inode);
3557 btrfs_free_path(path);
3558 make_bad_inode(inode);
3562 * given a leaf and an inode, copy the inode fields into the leaf
3564 static void fill_inode_item(struct btrfs_trans_handle *trans,
3565 struct extent_buffer *leaf,
3566 struct btrfs_inode_item *item,
3567 struct inode *inode)
3569 struct btrfs_map_token token;
3571 btrfs_init_map_token(&token);
3573 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3574 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3575 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3577 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3578 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3580 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3581 inode->i_atime.tv_sec, &token);
3582 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3583 inode->i_atime.tv_nsec, &token);
3585 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3586 inode->i_mtime.tv_sec, &token);
3587 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3588 inode->i_mtime.tv_nsec, &token);
3590 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3591 inode->i_ctime.tv_sec, &token);
3592 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3593 inode->i_ctime.tv_nsec, &token);
3595 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3597 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3599 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3600 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3601 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3602 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3603 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3607 * copy everything in the in-memory inode into the btree.
3609 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3610 struct btrfs_root *root, struct inode *inode)
3612 struct btrfs_inode_item *inode_item;
3613 struct btrfs_path *path;
3614 struct extent_buffer *leaf;
3617 path = btrfs_alloc_path();
3621 path->leave_spinning = 1;
3622 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3630 leaf = path->nodes[0];
3631 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3632 struct btrfs_inode_item);
3634 fill_inode_item(trans, leaf, inode_item, inode);
3635 btrfs_mark_buffer_dirty(leaf);
3636 btrfs_set_inode_last_trans(trans, inode);
3639 btrfs_free_path(path);
3644 * copy everything in the in-memory inode into the btree.
3646 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3647 struct btrfs_root *root, struct inode *inode)
3652 * If the inode is a free space inode, we can deadlock during commit
3653 * if we put it into the delayed code.
3655 * The data relocation inode should also be directly updated
3658 if (!btrfs_is_free_space_inode(inode)
3659 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3660 btrfs_update_root_times(trans, root);
3662 ret = btrfs_delayed_update_inode(trans, root, inode);
3664 btrfs_set_inode_last_trans(trans, inode);
3668 return btrfs_update_inode_item(trans, root, inode);
3671 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3672 struct btrfs_root *root,
3673 struct inode *inode)
3677 ret = btrfs_update_inode(trans, root, inode);
3679 return btrfs_update_inode_item(trans, root, inode);
3684 * unlink helper that gets used here in inode.c and in the tree logging
3685 * recovery code. It remove a link in a directory with a given name, and
3686 * also drops the back refs in the inode to the directory
3688 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3689 struct btrfs_root *root,
3690 struct inode *dir, struct inode *inode,
3691 const char *name, int name_len)
3693 struct btrfs_path *path;
3695 struct extent_buffer *leaf;
3696 struct btrfs_dir_item *di;
3697 struct btrfs_key key;
3699 u64 ino = btrfs_ino(inode);
3700 u64 dir_ino = btrfs_ino(dir);
3702 path = btrfs_alloc_path();
3708 path->leave_spinning = 1;
3709 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3710 name, name_len, -1);
3719 leaf = path->nodes[0];
3720 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3721 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3724 btrfs_release_path(path);
3727 * If we don't have dir index, we have to get it by looking up
3728 * the inode ref, since we get the inode ref, remove it directly,
3729 * it is unnecessary to do delayed deletion.
3731 * But if we have dir index, needn't search inode ref to get it.
3732 * Since the inode ref is close to the inode item, it is better
3733 * that we delay to delete it, and just do this deletion when
3734 * we update the inode item.
3736 if (BTRFS_I(inode)->dir_index) {
3737 ret = btrfs_delayed_delete_inode_ref(inode);
3739 index = BTRFS_I(inode)->dir_index;
3744 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3747 btrfs_info(root->fs_info,
3748 "failed to delete reference to %.*s, inode %llu parent %llu",
3749 name_len, name, ino, dir_ino);
3750 btrfs_abort_transaction(trans, root, ret);
3754 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3756 btrfs_abort_transaction(trans, root, ret);
3760 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3762 if (ret != 0 && ret != -ENOENT) {
3763 btrfs_abort_transaction(trans, root, ret);
3767 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3772 btrfs_abort_transaction(trans, root, ret);
3774 btrfs_free_path(path);
3778 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3779 inode_inc_iversion(inode);
3780 inode_inc_iversion(dir);
3781 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3782 ret = btrfs_update_inode(trans, root, dir);
3787 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3788 struct btrfs_root *root,
3789 struct inode *dir, struct inode *inode,
3790 const char *name, int name_len)
3793 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3796 ret = btrfs_update_inode(trans, root, inode);
3802 * helper to start transaction for unlink and rmdir.
3804 * unlink and rmdir are special in btrfs, they do not always free space, so
3805 * if we cannot make our reservations the normal way try and see if there is
3806 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3807 * allow the unlink to occur.
3809 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3811 struct btrfs_trans_handle *trans;
3812 struct btrfs_root *root = BTRFS_I(dir)->root;
3816 * 1 for the possible orphan item
3817 * 1 for the dir item
3818 * 1 for the dir index
3819 * 1 for the inode ref
3822 trans = btrfs_start_transaction(root, 5);
3823 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3826 if (PTR_ERR(trans) == -ENOSPC) {
3827 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3829 trans = btrfs_start_transaction(root, 0);
3832 ret = btrfs_cond_migrate_bytes(root->fs_info,
3833 &root->fs_info->trans_block_rsv,
3836 btrfs_end_transaction(trans, root);
3837 return ERR_PTR(ret);
3839 trans->block_rsv = &root->fs_info->trans_block_rsv;
3840 trans->bytes_reserved = num_bytes;
3845 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3847 struct btrfs_root *root = BTRFS_I(dir)->root;
3848 struct btrfs_trans_handle *trans;
3849 struct inode *inode = dentry->d_inode;
3852 trans = __unlink_start_trans(dir);
3854 return PTR_ERR(trans);
3856 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3858 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3859 dentry->d_name.name, dentry->d_name.len);
3863 if (inode->i_nlink == 0) {
3864 ret = btrfs_orphan_add(trans, inode);
3870 btrfs_end_transaction(trans, root);
3871 btrfs_btree_balance_dirty(root);
3875 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3876 struct btrfs_root *root,
3877 struct inode *dir, u64 objectid,
3878 const char *name, int name_len)
3880 struct btrfs_path *path;
3881 struct extent_buffer *leaf;
3882 struct btrfs_dir_item *di;
3883 struct btrfs_key key;
3886 u64 dir_ino = btrfs_ino(dir);
3888 path = btrfs_alloc_path();
3892 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3893 name, name_len, -1);
3894 if (IS_ERR_OR_NULL(di)) {
3902 leaf = path->nodes[0];
3903 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3904 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3905 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3907 btrfs_abort_transaction(trans, root, ret);
3910 btrfs_release_path(path);
3912 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3913 objectid, root->root_key.objectid,
3914 dir_ino, &index, name, name_len);
3916 if (ret != -ENOENT) {
3917 btrfs_abort_transaction(trans, root, ret);
3920 di = btrfs_search_dir_index_item(root, path, dir_ino,
3922 if (IS_ERR_OR_NULL(di)) {
3927 btrfs_abort_transaction(trans, root, ret);
3931 leaf = path->nodes[0];
3932 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3933 btrfs_release_path(path);
3936 btrfs_release_path(path);
3938 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3940 btrfs_abort_transaction(trans, root, ret);
3944 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3945 inode_inc_iversion(dir);
3946 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3947 ret = btrfs_update_inode_fallback(trans, root, dir);
3949 btrfs_abort_transaction(trans, root, ret);
3951 btrfs_free_path(path);
3955 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3957 struct inode *inode = dentry->d_inode;
3959 struct btrfs_root *root = BTRFS_I(dir)->root;
3960 struct btrfs_trans_handle *trans;
3962 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3964 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3967 trans = __unlink_start_trans(dir);
3969 return PTR_ERR(trans);
3971 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3972 err = btrfs_unlink_subvol(trans, root, dir,
3973 BTRFS_I(inode)->location.objectid,
3974 dentry->d_name.name,
3975 dentry->d_name.len);
3979 err = btrfs_orphan_add(trans, inode);
3983 /* now the directory is empty */
3984 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3985 dentry->d_name.name, dentry->d_name.len);
3987 btrfs_i_size_write(inode, 0);
3989 btrfs_end_transaction(trans, root);
3990 btrfs_btree_balance_dirty(root);
3996 * this can truncate away extent items, csum items and directory items.
3997 * It starts at a high offset and removes keys until it can't find
3998 * any higher than new_size
4000 * csum items that cross the new i_size are truncated to the new size
4003 * min_type is the minimum key type to truncate down to. If set to 0, this
4004 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4006 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4007 struct btrfs_root *root,
4008 struct inode *inode,
4009 u64 new_size, u32 min_type)
4011 struct btrfs_path *path;
4012 struct extent_buffer *leaf;
4013 struct btrfs_file_extent_item *fi;
4014 struct btrfs_key key;
4015 struct btrfs_key found_key;
4016 u64 extent_start = 0;
4017 u64 extent_num_bytes = 0;
4018 u64 extent_offset = 0;
4020 u64 last_size = (u64)-1;
4021 u32 found_type = (u8)-1;
4024 int pending_del_nr = 0;
4025 int pending_del_slot = 0;
4026 int extent_type = -1;
4029 u64 ino = btrfs_ino(inode);
4031 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4033 path = btrfs_alloc_path();
4039 * We want to drop from the next block forward in case this new size is
4040 * not block aligned since we will be keeping the last block of the
4041 * extent just the way it is.
4043 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4044 root == root->fs_info->tree_root)
4045 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4046 root->sectorsize), (u64)-1, 0);
4049 * This function is also used to drop the items in the log tree before
4050 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4051 * it is used to drop the loged items. So we shouldn't kill the delayed
4054 if (min_type == 0 && root == BTRFS_I(inode)->root)
4055 btrfs_kill_delayed_inode_items(inode);
4058 key.offset = (u64)-1;
4062 path->leave_spinning = 1;
4063 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4070 /* there are no items in the tree for us to truncate, we're
4073 if (path->slots[0] == 0)
4080 leaf = path->nodes[0];
4081 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4082 found_type = btrfs_key_type(&found_key);
4084 if (found_key.objectid != ino)
4087 if (found_type < min_type)
4090 item_end = found_key.offset;
4091 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4092 fi = btrfs_item_ptr(leaf, path->slots[0],
4093 struct btrfs_file_extent_item);
4094 extent_type = btrfs_file_extent_type(leaf, fi);
4095 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4097 btrfs_file_extent_num_bytes(leaf, fi);
4098 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4099 item_end += btrfs_file_extent_inline_len(leaf,
4100 path->slots[0], fi);
4104 if (found_type > min_type) {
4107 if (item_end < new_size)
4109 if (found_key.offset >= new_size)
4115 /* FIXME, shrink the extent if the ref count is only 1 */
4116 if (found_type != BTRFS_EXTENT_DATA_KEY)
4120 last_size = found_key.offset;
4122 last_size = new_size;
4124 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4126 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4128 u64 orig_num_bytes =
4129 btrfs_file_extent_num_bytes(leaf, fi);
4130 extent_num_bytes = ALIGN(new_size -
4133 btrfs_set_file_extent_num_bytes(leaf, fi,
4135 num_dec = (orig_num_bytes -
4137 if (test_bit(BTRFS_ROOT_REF_COWS,
4140 inode_sub_bytes(inode, num_dec);
4141 btrfs_mark_buffer_dirty(leaf);
4144 btrfs_file_extent_disk_num_bytes(leaf,
4146 extent_offset = found_key.offset -
4147 btrfs_file_extent_offset(leaf, fi);
4149 /* FIXME blocksize != 4096 */
4150 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4151 if (extent_start != 0) {
4153 if (test_bit(BTRFS_ROOT_REF_COWS,
4155 inode_sub_bytes(inode, num_dec);
4158 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4160 * we can't truncate inline items that have had
4164 btrfs_file_extent_compression(leaf, fi) == 0 &&
4165 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4166 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4167 u32 size = new_size - found_key.offset;
4169 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4170 inode_sub_bytes(inode, item_end + 1 -
4174 * update the ram bytes to properly reflect
4175 * the new size of our item
4177 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4179 btrfs_file_extent_calc_inline_size(size);
4180 btrfs_truncate_item(root, path, size, 1);
4181 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4183 inode_sub_bytes(inode, item_end + 1 -
4189 if (!pending_del_nr) {
4190 /* no pending yet, add ourselves */
4191 pending_del_slot = path->slots[0];
4193 } else if (pending_del_nr &&
4194 path->slots[0] + 1 == pending_del_slot) {
4195 /* hop on the pending chunk */
4197 pending_del_slot = path->slots[0];
4205 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4206 root == root->fs_info->tree_root)) {
4207 btrfs_set_path_blocking(path);
4208 ret = btrfs_free_extent(trans, root, extent_start,
4209 extent_num_bytes, 0,
4210 btrfs_header_owner(leaf),
4211 ino, extent_offset, 0);
4215 if (found_type == BTRFS_INODE_ITEM_KEY)
4218 if (path->slots[0] == 0 ||
4219 path->slots[0] != pending_del_slot) {
4220 if (pending_del_nr) {
4221 ret = btrfs_del_items(trans, root, path,
4225 btrfs_abort_transaction(trans,
4231 btrfs_release_path(path);
4238 if (pending_del_nr) {
4239 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4242 btrfs_abort_transaction(trans, root, ret);
4245 if (last_size != (u64)-1)
4246 btrfs_ordered_update_i_size(inode, last_size, NULL);
4247 btrfs_free_path(path);
4252 * btrfs_truncate_page - read, zero a chunk and write a page
4253 * @inode - inode that we're zeroing
4254 * @from - the offset to start zeroing
4255 * @len - the length to zero, 0 to zero the entire range respective to the
4257 * @front - zero up to the offset instead of from the offset on
4259 * This will find the page for the "from" offset and cow the page and zero the
4260 * part we want to zero. This is used with truncate and hole punching.
4262 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4265 struct address_space *mapping = inode->i_mapping;
4266 struct btrfs_root *root = BTRFS_I(inode)->root;
4267 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4268 struct btrfs_ordered_extent *ordered;
4269 struct extent_state *cached_state = NULL;
4271 u32 blocksize = root->sectorsize;
4272 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4273 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4275 gfp_t mask = btrfs_alloc_write_mask(mapping);
4280 if ((offset & (blocksize - 1)) == 0 &&
4281 (!len || ((len & (blocksize - 1)) == 0)))
4283 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4288 page = find_or_create_page(mapping, index, mask);
4290 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4295 page_start = page_offset(page);
4296 page_end = page_start + PAGE_CACHE_SIZE - 1;
4298 if (!PageUptodate(page)) {
4299 ret = btrfs_readpage(NULL, page);
4301 if (page->mapping != mapping) {
4303 page_cache_release(page);
4306 if (!PageUptodate(page)) {
4311 wait_on_page_writeback(page);
4313 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4314 set_page_extent_mapped(page);
4316 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4318 unlock_extent_cached(io_tree, page_start, page_end,
4319 &cached_state, GFP_NOFS);
4321 page_cache_release(page);
4322 btrfs_start_ordered_extent(inode, ordered, 1);
4323 btrfs_put_ordered_extent(ordered);
4327 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4328 EXTENT_DIRTY | EXTENT_DELALLOC |
4329 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4330 0, 0, &cached_state, GFP_NOFS);
4332 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4335 unlock_extent_cached(io_tree, page_start, page_end,
4336 &cached_state, GFP_NOFS);
4340 if (offset != PAGE_CACHE_SIZE) {
4342 len = PAGE_CACHE_SIZE - offset;
4345 memset(kaddr, 0, offset);
4347 memset(kaddr + offset, 0, len);
4348 flush_dcache_page(page);
4351 ClearPageChecked(page);
4352 set_page_dirty(page);
4353 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4358 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4360 page_cache_release(page);
4365 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4366 u64 offset, u64 len)
4368 struct btrfs_trans_handle *trans;
4372 * Still need to make sure the inode looks like it's been updated so
4373 * that any holes get logged if we fsync.
4375 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4376 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4377 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4378 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4383 * 1 - for the one we're dropping
4384 * 1 - for the one we're adding
4385 * 1 - for updating the inode.
4387 trans = btrfs_start_transaction(root, 3);
4389 return PTR_ERR(trans);
4391 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4393 btrfs_abort_transaction(trans, root, ret);
4394 btrfs_end_transaction(trans, root);
4398 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4399 0, 0, len, 0, len, 0, 0, 0);
4401 btrfs_abort_transaction(trans, root, ret);
4403 btrfs_update_inode(trans, root, inode);
4404 btrfs_end_transaction(trans, root);
4409 * This function puts in dummy file extents for the area we're creating a hole
4410 * for. So if we are truncating this file to a larger size we need to insert
4411 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4412 * the range between oldsize and size
4414 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4416 struct btrfs_root *root = BTRFS_I(inode)->root;
4417 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4418 struct extent_map *em = NULL;
4419 struct extent_state *cached_state = NULL;
4420 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4421 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4422 u64 block_end = ALIGN(size, root->sectorsize);
4429 * If our size started in the middle of a page we need to zero out the
4430 * rest of the page before we expand the i_size, otherwise we could
4431 * expose stale data.
4433 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4437 if (size <= hole_start)
4441 struct btrfs_ordered_extent *ordered;
4443 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4445 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4446 block_end - hole_start);
4449 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4450 &cached_state, GFP_NOFS);
4451 btrfs_start_ordered_extent(inode, ordered, 1);
4452 btrfs_put_ordered_extent(ordered);
4455 cur_offset = hole_start;
4457 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4458 block_end - cur_offset, 0);
4464 last_byte = min(extent_map_end(em), block_end);
4465 last_byte = ALIGN(last_byte , root->sectorsize);
4466 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4467 struct extent_map *hole_em;
4468 hole_size = last_byte - cur_offset;
4470 err = maybe_insert_hole(root, inode, cur_offset,
4474 btrfs_drop_extent_cache(inode, cur_offset,
4475 cur_offset + hole_size - 1, 0);
4476 hole_em = alloc_extent_map();
4478 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4479 &BTRFS_I(inode)->runtime_flags);
4482 hole_em->start = cur_offset;
4483 hole_em->len = hole_size;
4484 hole_em->orig_start = cur_offset;
4486 hole_em->block_start = EXTENT_MAP_HOLE;
4487 hole_em->block_len = 0;
4488 hole_em->orig_block_len = 0;
4489 hole_em->ram_bytes = hole_size;
4490 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4491 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4492 hole_em->generation = root->fs_info->generation;
4495 write_lock(&em_tree->lock);
4496 err = add_extent_mapping(em_tree, hole_em, 1);
4497 write_unlock(&em_tree->lock);
4500 btrfs_drop_extent_cache(inode, cur_offset,
4504 free_extent_map(hole_em);
4507 free_extent_map(em);
4509 cur_offset = last_byte;
4510 if (cur_offset >= block_end)
4513 free_extent_map(em);
4514 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4519 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4521 struct btrfs_root *root = BTRFS_I(inode)->root;
4522 struct btrfs_trans_handle *trans;
4523 loff_t oldsize = i_size_read(inode);
4524 loff_t newsize = attr->ia_size;
4525 int mask = attr->ia_valid;
4529 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4530 * special case where we need to update the times despite not having
4531 * these flags set. For all other operations the VFS set these flags
4532 * explicitly if it wants a timestamp update.
4534 if (newsize != oldsize) {
4535 inode_inc_iversion(inode);
4536 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4537 inode->i_ctime = inode->i_mtime =
4538 current_fs_time(inode->i_sb);
4541 if (newsize > oldsize) {
4542 truncate_pagecache(inode, newsize);
4543 ret = btrfs_cont_expand(inode, oldsize, newsize);
4547 trans = btrfs_start_transaction(root, 1);
4549 return PTR_ERR(trans);
4551 i_size_write(inode, newsize);
4552 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4553 ret = btrfs_update_inode(trans, root, inode);
4554 btrfs_end_transaction(trans, root);
4558 * We're truncating a file that used to have good data down to
4559 * zero. Make sure it gets into the ordered flush list so that
4560 * any new writes get down to disk quickly.
4563 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4564 &BTRFS_I(inode)->runtime_flags);
4567 * 1 for the orphan item we're going to add
4568 * 1 for the orphan item deletion.
4570 trans = btrfs_start_transaction(root, 2);
4572 return PTR_ERR(trans);
4575 * We need to do this in case we fail at _any_ point during the
4576 * actual truncate. Once we do the truncate_setsize we could
4577 * invalidate pages which forces any outstanding ordered io to
4578 * be instantly completed which will give us extents that need
4579 * to be truncated. If we fail to get an orphan inode down we
4580 * could have left over extents that were never meant to live,
4581 * so we need to garuntee from this point on that everything
4582 * will be consistent.
4584 ret = btrfs_orphan_add(trans, inode);
4585 btrfs_end_transaction(trans, root);
4589 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4590 truncate_setsize(inode, newsize);
4592 /* Disable nonlocked read DIO to avoid the end less truncate */
4593 btrfs_inode_block_unlocked_dio(inode);
4594 inode_dio_wait(inode);
4595 btrfs_inode_resume_unlocked_dio(inode);
4597 ret = btrfs_truncate(inode);
4598 if (ret && inode->i_nlink) {
4602 * failed to truncate, disk_i_size is only adjusted down
4603 * as we remove extents, so it should represent the true
4604 * size of the inode, so reset the in memory size and
4605 * delete our orphan entry.
4607 trans = btrfs_join_transaction(root);
4608 if (IS_ERR(trans)) {
4609 btrfs_orphan_del(NULL, inode);
4612 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4613 err = btrfs_orphan_del(trans, inode);
4615 btrfs_abort_transaction(trans, root, err);
4616 btrfs_end_transaction(trans, root);
4623 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4625 struct inode *inode = dentry->d_inode;
4626 struct btrfs_root *root = BTRFS_I(inode)->root;
4629 if (btrfs_root_readonly(root))
4632 err = inode_change_ok(inode, attr);
4636 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4637 err = btrfs_setsize(inode, attr);
4642 if (attr->ia_valid) {
4643 setattr_copy(inode, attr);
4644 inode_inc_iversion(inode);
4645 err = btrfs_dirty_inode(inode);
4647 if (!err && attr->ia_valid & ATTR_MODE)
4648 err = posix_acl_chmod(inode, inode->i_mode);
4655 * While truncating the inode pages during eviction, we get the VFS calling
4656 * btrfs_invalidatepage() against each page of the inode. This is slow because
4657 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4658 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4659 * extent_state structures over and over, wasting lots of time.
4661 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4662 * those expensive operations on a per page basis and do only the ordered io
4663 * finishing, while we release here the extent_map and extent_state structures,
4664 * without the excessive merging and splitting.
4666 static void evict_inode_truncate_pages(struct inode *inode)
4668 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4669 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4670 struct rb_node *node;
4672 ASSERT(inode->i_state & I_FREEING);
4673 truncate_inode_pages_final(&inode->i_data);
4675 write_lock(&map_tree->lock);
4676 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4677 struct extent_map *em;
4679 node = rb_first(&map_tree->map);
4680 em = rb_entry(node, struct extent_map, rb_node);
4681 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4682 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4683 remove_extent_mapping(map_tree, em);
4684 free_extent_map(em);
4685 if (need_resched()) {
4686 write_unlock(&map_tree->lock);
4688 write_lock(&map_tree->lock);
4691 write_unlock(&map_tree->lock);
4693 spin_lock(&io_tree->lock);
4694 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4695 struct extent_state *state;
4696 struct extent_state *cached_state = NULL;
4698 node = rb_first(&io_tree->state);
4699 state = rb_entry(node, struct extent_state, rb_node);
4700 atomic_inc(&state->refs);
4701 spin_unlock(&io_tree->lock);
4703 lock_extent_bits(io_tree, state->start, state->end,
4705 clear_extent_bit(io_tree, state->start, state->end,
4706 EXTENT_LOCKED | EXTENT_DIRTY |
4707 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4708 EXTENT_DEFRAG, 1, 1,
4709 &cached_state, GFP_NOFS);
4710 free_extent_state(state);
4713 spin_lock(&io_tree->lock);
4715 spin_unlock(&io_tree->lock);
4718 void btrfs_evict_inode(struct inode *inode)
4720 struct btrfs_trans_handle *trans;
4721 struct btrfs_root *root = BTRFS_I(inode)->root;
4722 struct btrfs_block_rsv *rsv, *global_rsv;
4723 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4726 trace_btrfs_inode_evict(inode);
4728 evict_inode_truncate_pages(inode);
4730 if (inode->i_nlink &&
4731 ((btrfs_root_refs(&root->root_item) != 0 &&
4732 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4733 btrfs_is_free_space_inode(inode)))
4736 if (is_bad_inode(inode)) {
4737 btrfs_orphan_del(NULL, inode);
4740 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4741 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4743 if (root->fs_info->log_root_recovering) {
4744 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4745 &BTRFS_I(inode)->runtime_flags));
4749 if (inode->i_nlink > 0) {
4750 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4751 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4755 ret = btrfs_commit_inode_delayed_inode(inode);
4757 btrfs_orphan_del(NULL, inode);
4761 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4763 btrfs_orphan_del(NULL, inode);
4766 rsv->size = min_size;
4768 global_rsv = &root->fs_info->global_block_rsv;
4770 btrfs_i_size_write(inode, 0);
4773 * This is a bit simpler than btrfs_truncate since we've already
4774 * reserved our space for our orphan item in the unlink, so we just
4775 * need to reserve some slack space in case we add bytes and update
4776 * inode item when doing the truncate.
4779 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4780 BTRFS_RESERVE_FLUSH_LIMIT);
4783 * Try and steal from the global reserve since we will
4784 * likely not use this space anyway, we want to try as
4785 * hard as possible to get this to work.
4788 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4791 btrfs_warn(root->fs_info,
4792 "Could not get space for a delete, will truncate on mount %d",
4794 btrfs_orphan_del(NULL, inode);
4795 btrfs_free_block_rsv(root, rsv);
4799 trans = btrfs_join_transaction(root);
4800 if (IS_ERR(trans)) {
4801 btrfs_orphan_del(NULL, inode);
4802 btrfs_free_block_rsv(root, rsv);
4806 trans->block_rsv = rsv;
4808 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4812 trans->block_rsv = &root->fs_info->trans_block_rsv;
4813 btrfs_end_transaction(trans, root);
4815 btrfs_btree_balance_dirty(root);
4818 btrfs_free_block_rsv(root, rsv);
4821 * Errors here aren't a big deal, it just means we leave orphan items
4822 * in the tree. They will be cleaned up on the next mount.
4825 trans->block_rsv = root->orphan_block_rsv;
4826 btrfs_orphan_del(trans, inode);
4828 btrfs_orphan_del(NULL, inode);
4831 trans->block_rsv = &root->fs_info->trans_block_rsv;
4832 if (!(root == root->fs_info->tree_root ||
4833 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4834 btrfs_return_ino(root, btrfs_ino(inode));
4836 btrfs_end_transaction(trans, root);
4837 btrfs_btree_balance_dirty(root);
4839 btrfs_remove_delayed_node(inode);
4845 * this returns the key found in the dir entry in the location pointer.
4846 * If no dir entries were found, location->objectid is 0.
4848 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4849 struct btrfs_key *location)
4851 const char *name = dentry->d_name.name;
4852 int namelen = dentry->d_name.len;
4853 struct btrfs_dir_item *di;
4854 struct btrfs_path *path;
4855 struct btrfs_root *root = BTRFS_I(dir)->root;
4858 path = btrfs_alloc_path();
4862 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4867 if (IS_ERR_OR_NULL(di))
4870 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4872 btrfs_free_path(path);
4875 location->objectid = 0;
4880 * when we hit a tree root in a directory, the btrfs part of the inode
4881 * needs to be changed to reflect the root directory of the tree root. This
4882 * is kind of like crossing a mount point.
4884 static int fixup_tree_root_location(struct btrfs_root *root,
4886 struct dentry *dentry,
4887 struct btrfs_key *location,
4888 struct btrfs_root **sub_root)
4890 struct btrfs_path *path;
4891 struct btrfs_root *new_root;
4892 struct btrfs_root_ref *ref;
4893 struct extent_buffer *leaf;
4897 path = btrfs_alloc_path();
4904 ret = btrfs_find_item(root->fs_info->tree_root, path,
4905 BTRFS_I(dir)->root->root_key.objectid,
4906 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4913 leaf = path->nodes[0];
4914 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4915 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4916 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4919 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4920 (unsigned long)(ref + 1),
4921 dentry->d_name.len);
4925 btrfs_release_path(path);
4927 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4928 if (IS_ERR(new_root)) {
4929 err = PTR_ERR(new_root);
4933 *sub_root = new_root;
4934 location->objectid = btrfs_root_dirid(&new_root->root_item);
4935 location->type = BTRFS_INODE_ITEM_KEY;
4936 location->offset = 0;
4939 btrfs_free_path(path);
4943 static void inode_tree_add(struct inode *inode)
4945 struct btrfs_root *root = BTRFS_I(inode)->root;
4946 struct btrfs_inode *entry;
4948 struct rb_node *parent;
4949 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4950 u64 ino = btrfs_ino(inode);
4952 if (inode_unhashed(inode))
4955 spin_lock(&root->inode_lock);
4956 p = &root->inode_tree.rb_node;
4959 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4961 if (ino < btrfs_ino(&entry->vfs_inode))
4962 p = &parent->rb_left;
4963 else if (ino > btrfs_ino(&entry->vfs_inode))
4964 p = &parent->rb_right;
4966 WARN_ON(!(entry->vfs_inode.i_state &
4967 (I_WILL_FREE | I_FREEING)));
4968 rb_replace_node(parent, new, &root->inode_tree);
4969 RB_CLEAR_NODE(parent);
4970 spin_unlock(&root->inode_lock);
4974 rb_link_node(new, parent, p);
4975 rb_insert_color(new, &root->inode_tree);
4976 spin_unlock(&root->inode_lock);
4979 static void inode_tree_del(struct inode *inode)
4981 struct btrfs_root *root = BTRFS_I(inode)->root;
4984 spin_lock(&root->inode_lock);
4985 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4986 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4987 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4988 empty = RB_EMPTY_ROOT(&root->inode_tree);
4990 spin_unlock(&root->inode_lock);
4992 if (empty && btrfs_root_refs(&root->root_item) == 0) {
4993 synchronize_srcu(&root->fs_info->subvol_srcu);
4994 spin_lock(&root->inode_lock);
4995 empty = RB_EMPTY_ROOT(&root->inode_tree);
4996 spin_unlock(&root->inode_lock);
4998 btrfs_add_dead_root(root);
5002 void btrfs_invalidate_inodes(struct btrfs_root *root)
5004 struct rb_node *node;
5005 struct rb_node *prev;
5006 struct btrfs_inode *entry;
5007 struct inode *inode;
5010 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5011 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5013 spin_lock(&root->inode_lock);
5015 node = root->inode_tree.rb_node;
5019 entry = rb_entry(node, struct btrfs_inode, rb_node);
5021 if (objectid < btrfs_ino(&entry->vfs_inode))
5022 node = node->rb_left;
5023 else if (objectid > btrfs_ino(&entry->vfs_inode))
5024 node = node->rb_right;
5030 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5031 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5035 prev = rb_next(prev);
5039 entry = rb_entry(node, struct btrfs_inode, rb_node);
5040 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5041 inode = igrab(&entry->vfs_inode);
5043 spin_unlock(&root->inode_lock);
5044 if (atomic_read(&inode->i_count) > 1)
5045 d_prune_aliases(inode);
5047 * btrfs_drop_inode will have it removed from
5048 * the inode cache when its usage count
5053 spin_lock(&root->inode_lock);
5057 if (cond_resched_lock(&root->inode_lock))
5060 node = rb_next(node);
5062 spin_unlock(&root->inode_lock);
5065 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5067 struct btrfs_iget_args *args = p;
5068 inode->i_ino = args->location->objectid;
5069 memcpy(&BTRFS_I(inode)->location, args->location,
5070 sizeof(*args->location));
5071 BTRFS_I(inode)->root = args->root;
5075 static int btrfs_find_actor(struct inode *inode, void *opaque)
5077 struct btrfs_iget_args *args = opaque;
5078 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5079 args->root == BTRFS_I(inode)->root;
5082 static struct inode *btrfs_iget_locked(struct super_block *s,
5083 struct btrfs_key *location,
5084 struct btrfs_root *root)
5086 struct inode *inode;
5087 struct btrfs_iget_args args;
5088 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5090 args.location = location;
5093 inode = iget5_locked(s, hashval, btrfs_find_actor,
5094 btrfs_init_locked_inode,
5099 /* Get an inode object given its location and corresponding root.
5100 * Returns in *is_new if the inode was read from disk
5102 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5103 struct btrfs_root *root, int *new)
5105 struct inode *inode;
5107 inode = btrfs_iget_locked(s, location, root);
5109 return ERR_PTR(-ENOMEM);
5111 if (inode->i_state & I_NEW) {
5112 btrfs_read_locked_inode(inode);
5113 if (!is_bad_inode(inode)) {
5114 inode_tree_add(inode);
5115 unlock_new_inode(inode);
5119 unlock_new_inode(inode);
5121 inode = ERR_PTR(-ESTALE);
5128 static struct inode *new_simple_dir(struct super_block *s,
5129 struct btrfs_key *key,
5130 struct btrfs_root *root)
5132 struct inode *inode = new_inode(s);
5135 return ERR_PTR(-ENOMEM);
5137 BTRFS_I(inode)->root = root;
5138 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5139 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5141 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5142 inode->i_op = &btrfs_dir_ro_inode_operations;
5143 inode->i_fop = &simple_dir_operations;
5144 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5145 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5150 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5152 struct inode *inode;
5153 struct btrfs_root *root = BTRFS_I(dir)->root;
5154 struct btrfs_root *sub_root = root;
5155 struct btrfs_key location;
5159 if (dentry->d_name.len > BTRFS_NAME_LEN)
5160 return ERR_PTR(-ENAMETOOLONG);
5162 ret = btrfs_inode_by_name(dir, dentry, &location);
5164 return ERR_PTR(ret);
5166 if (location.objectid == 0)
5167 return ERR_PTR(-ENOENT);
5169 if (location.type == BTRFS_INODE_ITEM_KEY) {
5170 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5174 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5176 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5177 ret = fixup_tree_root_location(root, dir, dentry,
5178 &location, &sub_root);
5181 inode = ERR_PTR(ret);
5183 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5185 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5187 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5189 if (!IS_ERR(inode) && root != sub_root) {
5190 down_read(&root->fs_info->cleanup_work_sem);
5191 if (!(inode->i_sb->s_flags & MS_RDONLY))
5192 ret = btrfs_orphan_cleanup(sub_root);
5193 up_read(&root->fs_info->cleanup_work_sem);
5196 inode = ERR_PTR(ret);
5199 * If orphan cleanup did remove any orphans, it means the tree
5200 * was modified and therefore the commit root is not the same as
5201 * the current root anymore. This is a problem, because send
5202 * uses the commit root and therefore can see inode items that
5203 * don't exist in the current root anymore, and for example make
5204 * calls to btrfs_iget, which will do tree lookups based on the
5205 * current root and not on the commit root. Those lookups will
5206 * fail, returning a -ESTALE error, and making send fail with
5207 * that error. So make sure a send does not see any orphans we
5208 * have just removed, and that it will see the same inodes
5209 * regardless of whether a transaction commit happened before
5210 * it started (meaning that the commit root will be the same as
5211 * the current root) or not.
5213 if (sub_root->node != sub_root->commit_root) {
5214 u64 sub_flags = btrfs_root_flags(&sub_root->root_item);
5216 if (sub_flags & BTRFS_ROOT_SUBVOL_RDONLY) {
5217 struct extent_buffer *eb;
5220 * Assert we can't have races between dentry
5221 * lookup called through the snapshot creation
5222 * ioctl and the VFS.
5224 ASSERT(mutex_is_locked(&dir->i_mutex));
5226 down_write(&root->fs_info->commit_root_sem);
5227 eb = sub_root->commit_root;
5228 sub_root->commit_root =
5229 btrfs_root_node(sub_root);
5230 up_write(&root->fs_info->commit_root_sem);
5231 free_extent_buffer(eb);
5239 static int btrfs_dentry_delete(const struct dentry *dentry)
5241 struct btrfs_root *root;
5242 struct inode *inode = dentry->d_inode;
5244 if (!inode && !IS_ROOT(dentry))
5245 inode = dentry->d_parent->d_inode;
5248 root = BTRFS_I(inode)->root;
5249 if (btrfs_root_refs(&root->root_item) == 0)
5252 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5258 static void btrfs_dentry_release(struct dentry *dentry)
5260 kfree(dentry->d_fsdata);
5263 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5266 struct inode *inode;
5268 inode = btrfs_lookup_dentry(dir, dentry);
5269 if (IS_ERR(inode)) {
5270 if (PTR_ERR(inode) == -ENOENT)
5273 return ERR_CAST(inode);
5276 return d_materialise_unique(dentry, inode);
5279 unsigned char btrfs_filetype_table[] = {
5280 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5283 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5285 struct inode *inode = file_inode(file);
5286 struct btrfs_root *root = BTRFS_I(inode)->root;
5287 struct btrfs_item *item;
5288 struct btrfs_dir_item *di;
5289 struct btrfs_key key;
5290 struct btrfs_key found_key;
5291 struct btrfs_path *path;
5292 struct list_head ins_list;
5293 struct list_head del_list;
5295 struct extent_buffer *leaf;
5297 unsigned char d_type;
5302 int key_type = BTRFS_DIR_INDEX_KEY;
5306 int is_curr = 0; /* ctx->pos points to the current index? */
5308 /* FIXME, use a real flag for deciding about the key type */
5309 if (root->fs_info->tree_root == root)
5310 key_type = BTRFS_DIR_ITEM_KEY;
5312 if (!dir_emit_dots(file, ctx))
5315 path = btrfs_alloc_path();
5321 if (key_type == BTRFS_DIR_INDEX_KEY) {
5322 INIT_LIST_HEAD(&ins_list);
5323 INIT_LIST_HEAD(&del_list);
5324 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5327 btrfs_set_key_type(&key, key_type);
5328 key.offset = ctx->pos;
5329 key.objectid = btrfs_ino(inode);
5331 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5336 leaf = path->nodes[0];
5337 slot = path->slots[0];
5338 if (slot >= btrfs_header_nritems(leaf)) {
5339 ret = btrfs_next_leaf(root, path);
5347 item = btrfs_item_nr(slot);
5348 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5350 if (found_key.objectid != key.objectid)
5352 if (btrfs_key_type(&found_key) != key_type)
5354 if (found_key.offset < ctx->pos)
5356 if (key_type == BTRFS_DIR_INDEX_KEY &&
5357 btrfs_should_delete_dir_index(&del_list,
5361 ctx->pos = found_key.offset;
5364 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5366 di_total = btrfs_item_size(leaf, item);
5368 while (di_cur < di_total) {
5369 struct btrfs_key location;
5371 if (verify_dir_item(root, leaf, di))
5374 name_len = btrfs_dir_name_len(leaf, di);
5375 if (name_len <= sizeof(tmp_name)) {
5376 name_ptr = tmp_name;
5378 name_ptr = kmalloc(name_len, GFP_NOFS);
5384 read_extent_buffer(leaf, name_ptr,
5385 (unsigned long)(di + 1), name_len);
5387 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5388 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5391 /* is this a reference to our own snapshot? If so
5394 * In contrast to old kernels, we insert the snapshot's
5395 * dir item and dir index after it has been created, so
5396 * we won't find a reference to our own snapshot. We
5397 * still keep the following code for backward
5400 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5401 location.objectid == root->root_key.objectid) {
5405 over = !dir_emit(ctx, name_ptr, name_len,
5406 location.objectid, d_type);
5409 if (name_ptr != tmp_name)
5414 di_len = btrfs_dir_name_len(leaf, di) +
5415 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5417 di = (struct btrfs_dir_item *)((char *)di + di_len);
5423 if (key_type == BTRFS_DIR_INDEX_KEY) {
5426 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5431 /* Reached end of directory/root. Bump pos past the last item. */
5435 * Stop new entries from being returned after we return the last
5438 * New directory entries are assigned a strictly increasing
5439 * offset. This means that new entries created during readdir
5440 * are *guaranteed* to be seen in the future by that readdir.
5441 * This has broken buggy programs which operate on names as
5442 * they're returned by readdir. Until we re-use freed offsets
5443 * we have this hack to stop new entries from being returned
5444 * under the assumption that they'll never reach this huge
5447 * This is being careful not to overflow 32bit loff_t unless the
5448 * last entry requires it because doing so has broken 32bit apps
5451 if (key_type == BTRFS_DIR_INDEX_KEY) {
5452 if (ctx->pos >= INT_MAX)
5453 ctx->pos = LLONG_MAX;
5460 if (key_type == BTRFS_DIR_INDEX_KEY)
5461 btrfs_put_delayed_items(&ins_list, &del_list);
5462 btrfs_free_path(path);
5466 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5468 struct btrfs_root *root = BTRFS_I(inode)->root;
5469 struct btrfs_trans_handle *trans;
5471 bool nolock = false;
5473 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5476 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5479 if (wbc->sync_mode == WB_SYNC_ALL) {
5481 trans = btrfs_join_transaction_nolock(root);
5483 trans = btrfs_join_transaction(root);
5485 return PTR_ERR(trans);
5486 ret = btrfs_commit_transaction(trans, root);
5492 * This is somewhat expensive, updating the tree every time the
5493 * inode changes. But, it is most likely to find the inode in cache.
5494 * FIXME, needs more benchmarking...there are no reasons other than performance
5495 * to keep or drop this code.
5497 static int btrfs_dirty_inode(struct inode *inode)
5499 struct btrfs_root *root = BTRFS_I(inode)->root;
5500 struct btrfs_trans_handle *trans;
5503 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5506 trans = btrfs_join_transaction(root);
5508 return PTR_ERR(trans);
5510 ret = btrfs_update_inode(trans, root, inode);
5511 if (ret && ret == -ENOSPC) {
5512 /* whoops, lets try again with the full transaction */
5513 btrfs_end_transaction(trans, root);
5514 trans = btrfs_start_transaction(root, 1);
5516 return PTR_ERR(trans);
5518 ret = btrfs_update_inode(trans, root, inode);
5520 btrfs_end_transaction(trans, root);
5521 if (BTRFS_I(inode)->delayed_node)
5522 btrfs_balance_delayed_items(root);
5528 * This is a copy of file_update_time. We need this so we can return error on
5529 * ENOSPC for updating the inode in the case of file write and mmap writes.
5531 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5534 struct btrfs_root *root = BTRFS_I(inode)->root;
5536 if (btrfs_root_readonly(root))
5539 if (flags & S_VERSION)
5540 inode_inc_iversion(inode);
5541 if (flags & S_CTIME)
5542 inode->i_ctime = *now;
5543 if (flags & S_MTIME)
5544 inode->i_mtime = *now;
5545 if (flags & S_ATIME)
5546 inode->i_atime = *now;
5547 return btrfs_dirty_inode(inode);
5551 * find the highest existing sequence number in a directory
5552 * and then set the in-memory index_cnt variable to reflect
5553 * free sequence numbers
5555 static int btrfs_set_inode_index_count(struct inode *inode)
5557 struct btrfs_root *root = BTRFS_I(inode)->root;
5558 struct btrfs_key key, found_key;
5559 struct btrfs_path *path;
5560 struct extent_buffer *leaf;
5563 key.objectid = btrfs_ino(inode);
5564 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5565 key.offset = (u64)-1;
5567 path = btrfs_alloc_path();
5571 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5574 /* FIXME: we should be able to handle this */
5580 * MAGIC NUMBER EXPLANATION:
5581 * since we search a directory based on f_pos we have to start at 2
5582 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5583 * else has to start at 2
5585 if (path->slots[0] == 0) {
5586 BTRFS_I(inode)->index_cnt = 2;
5592 leaf = path->nodes[0];
5593 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5595 if (found_key.objectid != btrfs_ino(inode) ||
5596 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5597 BTRFS_I(inode)->index_cnt = 2;
5601 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5603 btrfs_free_path(path);
5608 * helper to find a free sequence number in a given directory. This current
5609 * code is very simple, later versions will do smarter things in the btree
5611 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5615 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5616 ret = btrfs_inode_delayed_dir_index_count(dir);
5618 ret = btrfs_set_inode_index_count(dir);
5624 *index = BTRFS_I(dir)->index_cnt;
5625 BTRFS_I(dir)->index_cnt++;
5630 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5631 struct btrfs_root *root,
5633 const char *name, int name_len,
5634 u64 ref_objectid, u64 objectid,
5635 umode_t mode, u64 *index)
5637 struct inode *inode;
5638 struct btrfs_inode_item *inode_item;
5639 struct btrfs_key *location;
5640 struct btrfs_path *path;
5641 struct btrfs_inode_ref *ref;
5642 struct btrfs_key key[2];
5644 int nitems = name ? 2 : 1;
5648 path = btrfs_alloc_path();
5650 return ERR_PTR(-ENOMEM);
5652 inode = new_inode(root->fs_info->sb);
5654 btrfs_free_path(path);
5655 return ERR_PTR(-ENOMEM);
5659 * O_TMPFILE, set link count to 0, so that after this point,
5660 * we fill in an inode item with the correct link count.
5663 set_nlink(inode, 0);
5666 * we have to initialize this early, so we can reclaim the inode
5667 * number if we fail afterwards in this function.
5669 inode->i_ino = objectid;
5672 trace_btrfs_inode_request(dir);
5674 ret = btrfs_set_inode_index(dir, index);
5676 btrfs_free_path(path);
5678 return ERR_PTR(ret);
5684 * index_cnt is ignored for everything but a dir,
5685 * btrfs_get_inode_index_count has an explanation for the magic
5688 BTRFS_I(inode)->index_cnt = 2;
5689 BTRFS_I(inode)->dir_index = *index;
5690 BTRFS_I(inode)->root = root;
5691 BTRFS_I(inode)->generation = trans->transid;
5692 inode->i_generation = BTRFS_I(inode)->generation;
5695 * We could have gotten an inode number from somebody who was fsynced
5696 * and then removed in this same transaction, so let's just set full
5697 * sync since it will be a full sync anyway and this will blow away the
5698 * old info in the log.
5700 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5702 key[0].objectid = objectid;
5703 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5706 sizes[0] = sizeof(struct btrfs_inode_item);
5710 * Start new inodes with an inode_ref. This is slightly more
5711 * efficient for small numbers of hard links since they will
5712 * be packed into one item. Extended refs will kick in if we
5713 * add more hard links than can fit in the ref item.
5715 key[1].objectid = objectid;
5716 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5717 key[1].offset = ref_objectid;
5719 sizes[1] = name_len + sizeof(*ref);
5722 path->leave_spinning = 1;
5723 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5727 inode_init_owner(inode, dir, mode);
5728 inode_set_bytes(inode, 0);
5729 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5730 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5731 struct btrfs_inode_item);
5732 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5733 sizeof(*inode_item));
5734 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5737 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5738 struct btrfs_inode_ref);
5739 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5740 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5741 ptr = (unsigned long)(ref + 1);
5742 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5745 btrfs_mark_buffer_dirty(path->nodes[0]);
5746 btrfs_free_path(path);
5748 location = &BTRFS_I(inode)->location;
5749 location->objectid = objectid;
5750 location->offset = 0;
5751 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5753 btrfs_inherit_iflags(inode, dir);
5755 if (S_ISREG(mode)) {
5756 if (btrfs_test_opt(root, NODATASUM))
5757 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5758 if (btrfs_test_opt(root, NODATACOW))
5759 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5760 BTRFS_INODE_NODATASUM;
5763 btrfs_insert_inode_hash(inode);
5764 inode_tree_add(inode);
5766 trace_btrfs_inode_new(inode);
5767 btrfs_set_inode_last_trans(trans, inode);
5769 btrfs_update_root_times(trans, root);
5771 ret = btrfs_inode_inherit_props(trans, inode, dir);
5773 btrfs_err(root->fs_info,
5774 "error inheriting props for ino %llu (root %llu): %d",
5775 btrfs_ino(inode), root->root_key.objectid, ret);
5780 BTRFS_I(dir)->index_cnt--;
5781 btrfs_free_path(path);
5783 return ERR_PTR(ret);
5786 static inline u8 btrfs_inode_type(struct inode *inode)
5788 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5792 * utility function to add 'inode' into 'parent_inode' with
5793 * a give name and a given sequence number.
5794 * if 'add_backref' is true, also insert a backref from the
5795 * inode to the parent directory.
5797 int btrfs_add_link(struct btrfs_trans_handle *trans,
5798 struct inode *parent_inode, struct inode *inode,
5799 const char *name, int name_len, int add_backref, u64 index)
5802 struct btrfs_key key;
5803 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5804 u64 ino = btrfs_ino(inode);
5805 u64 parent_ino = btrfs_ino(parent_inode);
5807 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5808 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5811 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5815 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5816 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5817 key.objectid, root->root_key.objectid,
5818 parent_ino, index, name, name_len);
5819 } else if (add_backref) {
5820 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5824 /* Nothing to clean up yet */
5828 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5830 btrfs_inode_type(inode), index);
5831 if (ret == -EEXIST || ret == -EOVERFLOW)
5834 btrfs_abort_transaction(trans, root, ret);
5838 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5840 inode_inc_iversion(parent_inode);
5841 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5842 ret = btrfs_update_inode(trans, root, parent_inode);
5844 btrfs_abort_transaction(trans, root, ret);
5848 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5851 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5852 key.objectid, root->root_key.objectid,
5853 parent_ino, &local_index, name, name_len);
5855 } else if (add_backref) {
5859 err = btrfs_del_inode_ref(trans, root, name, name_len,
5860 ino, parent_ino, &local_index);
5865 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5866 struct inode *dir, struct dentry *dentry,
5867 struct inode *inode, int backref, u64 index)
5869 int err = btrfs_add_link(trans, dir, inode,
5870 dentry->d_name.name, dentry->d_name.len,
5877 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5878 umode_t mode, dev_t rdev)
5880 struct btrfs_trans_handle *trans;
5881 struct btrfs_root *root = BTRFS_I(dir)->root;
5882 struct inode *inode = NULL;
5888 if (!new_valid_dev(rdev))
5892 * 2 for inode item and ref
5894 * 1 for xattr if selinux is on
5896 trans = btrfs_start_transaction(root, 5);
5898 return PTR_ERR(trans);
5900 err = btrfs_find_free_ino(root, &objectid);
5904 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5905 dentry->d_name.len, btrfs_ino(dir), objectid,
5907 if (IS_ERR(inode)) {
5908 err = PTR_ERR(inode);
5912 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5919 * If the active LSM wants to access the inode during
5920 * d_instantiate it needs these. Smack checks to see
5921 * if the filesystem supports xattrs by looking at the
5925 inode->i_op = &btrfs_special_inode_operations;
5926 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5930 init_special_inode(inode, inode->i_mode, rdev);
5931 btrfs_update_inode(trans, root, inode);
5932 d_instantiate(dentry, inode);
5935 btrfs_end_transaction(trans, root);
5936 btrfs_balance_delayed_items(root);
5937 btrfs_btree_balance_dirty(root);
5939 inode_dec_link_count(inode);
5945 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5946 umode_t mode, bool excl)
5948 struct btrfs_trans_handle *trans;
5949 struct btrfs_root *root = BTRFS_I(dir)->root;
5950 struct inode *inode = NULL;
5951 int drop_inode_on_err = 0;
5957 * 2 for inode item and ref
5959 * 1 for xattr if selinux is on
5961 trans = btrfs_start_transaction(root, 5);
5963 return PTR_ERR(trans);
5965 err = btrfs_find_free_ino(root, &objectid);
5969 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5970 dentry->d_name.len, btrfs_ino(dir), objectid,
5972 if (IS_ERR(inode)) {
5973 err = PTR_ERR(inode);
5976 drop_inode_on_err = 1;
5978 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5982 err = btrfs_update_inode(trans, root, inode);
5987 * If the active LSM wants to access the inode during
5988 * d_instantiate it needs these. Smack checks to see
5989 * if the filesystem supports xattrs by looking at the
5992 inode->i_fop = &btrfs_file_operations;
5993 inode->i_op = &btrfs_file_inode_operations;
5995 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5999 inode->i_mapping->a_ops = &btrfs_aops;
6000 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
6001 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6002 d_instantiate(dentry, inode);
6005 btrfs_end_transaction(trans, root);
6006 if (err && drop_inode_on_err) {
6007 inode_dec_link_count(inode);
6010 btrfs_balance_delayed_items(root);
6011 btrfs_btree_balance_dirty(root);
6015 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6016 struct dentry *dentry)
6018 struct btrfs_trans_handle *trans;
6019 struct btrfs_root *root = BTRFS_I(dir)->root;
6020 struct inode *inode = old_dentry->d_inode;
6025 /* do not allow sys_link's with other subvols of the same device */
6026 if (root->objectid != BTRFS_I(inode)->root->objectid)
6029 if (inode->i_nlink >= BTRFS_LINK_MAX)
6032 err = btrfs_set_inode_index(dir, &index);
6037 * 2 items for inode and inode ref
6038 * 2 items for dir items
6039 * 1 item for parent inode
6041 trans = btrfs_start_transaction(root, 5);
6042 if (IS_ERR(trans)) {
6043 err = PTR_ERR(trans);
6047 /* There are several dir indexes for this inode, clear the cache. */
6048 BTRFS_I(inode)->dir_index = 0ULL;
6050 inode_inc_iversion(inode);
6051 inode->i_ctime = CURRENT_TIME;
6053 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6055 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6060 struct dentry *parent = dentry->d_parent;
6061 err = btrfs_update_inode(trans, root, inode);
6064 if (inode->i_nlink == 1) {
6066 * If new hard link count is 1, it's a file created
6067 * with open(2) O_TMPFILE flag.
6069 err = btrfs_orphan_del(trans, inode);
6073 d_instantiate(dentry, inode);
6074 btrfs_log_new_name(trans, inode, NULL, parent);
6077 btrfs_end_transaction(trans, root);
6078 btrfs_balance_delayed_items(root);
6081 inode_dec_link_count(inode);
6084 btrfs_btree_balance_dirty(root);
6088 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6090 struct inode *inode = NULL;
6091 struct btrfs_trans_handle *trans;
6092 struct btrfs_root *root = BTRFS_I(dir)->root;
6094 int drop_on_err = 0;
6099 * 2 items for inode and ref
6100 * 2 items for dir items
6101 * 1 for xattr if selinux is on
6103 trans = btrfs_start_transaction(root, 5);
6105 return PTR_ERR(trans);
6107 err = btrfs_find_free_ino(root, &objectid);
6111 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6112 dentry->d_name.len, btrfs_ino(dir), objectid,
6113 S_IFDIR | mode, &index);
6114 if (IS_ERR(inode)) {
6115 err = PTR_ERR(inode);
6121 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6125 inode->i_op = &btrfs_dir_inode_operations;
6126 inode->i_fop = &btrfs_dir_file_operations;
6128 btrfs_i_size_write(inode, 0);
6129 err = btrfs_update_inode(trans, root, inode);
6133 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6134 dentry->d_name.len, 0, index);
6138 d_instantiate(dentry, inode);
6142 btrfs_end_transaction(trans, root);
6145 btrfs_balance_delayed_items(root);
6146 btrfs_btree_balance_dirty(root);
6150 /* helper for btfs_get_extent. Given an existing extent in the tree,
6151 * and an extent that you want to insert, deal with overlap and insert
6152 * the new extent into the tree.
6154 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6155 struct extent_map *existing,
6156 struct extent_map *em,
6161 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6162 start_diff = map_start - em->start;
6163 em->start = map_start;
6164 em->len = existing->start - em->start;
6165 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6166 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6167 em->block_start += start_diff;
6168 em->block_len -= start_diff;
6170 return add_extent_mapping(em_tree, em, 0);
6173 static noinline int uncompress_inline(struct btrfs_path *path,
6174 struct inode *inode, struct page *page,
6175 size_t pg_offset, u64 extent_offset,
6176 struct btrfs_file_extent_item *item)
6179 struct extent_buffer *leaf = path->nodes[0];
6182 unsigned long inline_size;
6186 WARN_ON(pg_offset != 0);
6187 compress_type = btrfs_file_extent_compression(leaf, item);
6188 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6189 inline_size = btrfs_file_extent_inline_item_len(leaf,
6190 btrfs_item_nr(path->slots[0]));
6191 tmp = kmalloc(inline_size, GFP_NOFS);
6194 ptr = btrfs_file_extent_inline_start(item);
6196 read_extent_buffer(leaf, tmp, ptr, inline_size);
6198 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6199 ret = btrfs_decompress(compress_type, tmp, page,
6200 extent_offset, inline_size, max_size);
6206 * a bit scary, this does extent mapping from logical file offset to the disk.
6207 * the ugly parts come from merging extents from the disk with the in-ram
6208 * representation. This gets more complex because of the data=ordered code,
6209 * where the in-ram extents might be locked pending data=ordered completion.
6211 * This also copies inline extents directly into the page.
6214 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6215 size_t pg_offset, u64 start, u64 len,
6220 u64 extent_start = 0;
6222 u64 objectid = btrfs_ino(inode);
6224 struct btrfs_path *path = NULL;
6225 struct btrfs_root *root = BTRFS_I(inode)->root;
6226 struct btrfs_file_extent_item *item;
6227 struct extent_buffer *leaf;
6228 struct btrfs_key found_key;
6229 struct extent_map *em = NULL;
6230 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6231 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6232 struct btrfs_trans_handle *trans = NULL;
6233 const bool new_inline = !page || create;
6236 read_lock(&em_tree->lock);
6237 em = lookup_extent_mapping(em_tree, start, len);
6239 em->bdev = root->fs_info->fs_devices->latest_bdev;
6240 read_unlock(&em_tree->lock);
6243 if (em->start > start || em->start + em->len <= start)
6244 free_extent_map(em);
6245 else if (em->block_start == EXTENT_MAP_INLINE && page)
6246 free_extent_map(em);
6250 em = alloc_extent_map();
6255 em->bdev = root->fs_info->fs_devices->latest_bdev;
6256 em->start = EXTENT_MAP_HOLE;
6257 em->orig_start = EXTENT_MAP_HOLE;
6259 em->block_len = (u64)-1;
6262 path = btrfs_alloc_path();
6268 * Chances are we'll be called again, so go ahead and do
6274 ret = btrfs_lookup_file_extent(trans, root, path,
6275 objectid, start, trans != NULL);
6282 if (path->slots[0] == 0)
6287 leaf = path->nodes[0];
6288 item = btrfs_item_ptr(leaf, path->slots[0],
6289 struct btrfs_file_extent_item);
6290 /* are we inside the extent that was found? */
6291 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6292 found_type = btrfs_key_type(&found_key);
6293 if (found_key.objectid != objectid ||
6294 found_type != BTRFS_EXTENT_DATA_KEY) {
6296 * If we backup past the first extent we want to move forward
6297 * and see if there is an extent in front of us, otherwise we'll
6298 * say there is a hole for our whole search range which can
6305 found_type = btrfs_file_extent_type(leaf, item);
6306 extent_start = found_key.offset;
6307 if (found_type == BTRFS_FILE_EXTENT_REG ||
6308 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6309 extent_end = extent_start +
6310 btrfs_file_extent_num_bytes(leaf, item);
6311 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6313 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6314 extent_end = ALIGN(extent_start + size, root->sectorsize);
6317 if (start >= extent_end) {
6319 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6320 ret = btrfs_next_leaf(root, path);
6327 leaf = path->nodes[0];
6329 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6330 if (found_key.objectid != objectid ||
6331 found_key.type != BTRFS_EXTENT_DATA_KEY)
6333 if (start + len <= found_key.offset)
6335 if (start > found_key.offset)
6338 em->orig_start = start;
6339 em->len = found_key.offset - start;
6343 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6345 if (found_type == BTRFS_FILE_EXTENT_REG ||
6346 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6348 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6352 size_t extent_offset;
6358 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6359 extent_offset = page_offset(page) + pg_offset - extent_start;
6360 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6361 size - extent_offset);
6362 em->start = extent_start + extent_offset;
6363 em->len = ALIGN(copy_size, root->sectorsize);
6364 em->orig_block_len = em->len;
6365 em->orig_start = em->start;
6366 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6367 if (create == 0 && !PageUptodate(page)) {
6368 if (btrfs_file_extent_compression(leaf, item) !=
6369 BTRFS_COMPRESS_NONE) {
6370 ret = uncompress_inline(path, inode, page,
6372 extent_offset, item);
6379 read_extent_buffer(leaf, map + pg_offset, ptr,
6381 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6382 memset(map + pg_offset + copy_size, 0,
6383 PAGE_CACHE_SIZE - pg_offset -
6388 flush_dcache_page(page);
6389 } else if (create && PageUptodate(page)) {
6393 free_extent_map(em);
6396 btrfs_release_path(path);
6397 trans = btrfs_join_transaction(root);
6400 return ERR_CAST(trans);
6404 write_extent_buffer(leaf, map + pg_offset, ptr,
6407 btrfs_mark_buffer_dirty(leaf);
6409 set_extent_uptodate(io_tree, em->start,
6410 extent_map_end(em) - 1, NULL, GFP_NOFS);
6415 em->orig_start = start;
6418 em->block_start = EXTENT_MAP_HOLE;
6419 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6421 btrfs_release_path(path);
6422 if (em->start > start || extent_map_end(em) <= start) {
6423 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6424 em->start, em->len, start, len);
6430 write_lock(&em_tree->lock);
6431 ret = add_extent_mapping(em_tree, em, 0);
6432 /* it is possible that someone inserted the extent into the tree
6433 * while we had the lock dropped. It is also possible that
6434 * an overlapping map exists in the tree
6436 if (ret == -EEXIST) {
6437 struct extent_map *existing;
6441 existing = lookup_extent_mapping(em_tree, start, len);
6442 if (existing && (existing->start > start ||
6443 existing->start + existing->len <= start)) {
6444 free_extent_map(existing);
6448 existing = lookup_extent_mapping(em_tree, em->start,
6451 err = merge_extent_mapping(em_tree, existing,
6453 free_extent_map(existing);
6455 free_extent_map(em);
6460 free_extent_map(em);
6464 free_extent_map(em);
6469 write_unlock(&em_tree->lock);
6472 trace_btrfs_get_extent(root, em);
6475 btrfs_free_path(path);
6477 ret = btrfs_end_transaction(trans, root);
6482 free_extent_map(em);
6483 return ERR_PTR(err);
6485 BUG_ON(!em); /* Error is always set */
6489 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6490 size_t pg_offset, u64 start, u64 len,
6493 struct extent_map *em;
6494 struct extent_map *hole_em = NULL;
6495 u64 range_start = start;
6501 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6508 * - a pre-alloc extent,
6509 * there might actually be delalloc bytes behind it.
6511 if (em->block_start != EXTENT_MAP_HOLE &&
6512 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6518 /* check to see if we've wrapped (len == -1 or similar) */
6527 /* ok, we didn't find anything, lets look for delalloc */
6528 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6529 end, len, EXTENT_DELALLOC, 1);
6530 found_end = range_start + found;
6531 if (found_end < range_start)
6532 found_end = (u64)-1;
6535 * we didn't find anything useful, return
6536 * the original results from get_extent()
6538 if (range_start > end || found_end <= start) {
6544 /* adjust the range_start to make sure it doesn't
6545 * go backwards from the start they passed in
6547 range_start = max(start, range_start);
6548 found = found_end - range_start;
6551 u64 hole_start = start;
6554 em = alloc_extent_map();
6560 * when btrfs_get_extent can't find anything it
6561 * returns one huge hole
6563 * make sure what it found really fits our range, and
6564 * adjust to make sure it is based on the start from
6568 u64 calc_end = extent_map_end(hole_em);
6570 if (calc_end <= start || (hole_em->start > end)) {
6571 free_extent_map(hole_em);
6574 hole_start = max(hole_em->start, start);
6575 hole_len = calc_end - hole_start;
6579 if (hole_em && range_start > hole_start) {
6580 /* our hole starts before our delalloc, so we
6581 * have to return just the parts of the hole
6582 * that go until the delalloc starts
6584 em->len = min(hole_len,
6585 range_start - hole_start);
6586 em->start = hole_start;
6587 em->orig_start = hole_start;
6589 * don't adjust block start at all,
6590 * it is fixed at EXTENT_MAP_HOLE
6592 em->block_start = hole_em->block_start;
6593 em->block_len = hole_len;
6594 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6595 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6597 em->start = range_start;
6599 em->orig_start = range_start;
6600 em->block_start = EXTENT_MAP_DELALLOC;
6601 em->block_len = found;
6603 } else if (hole_em) {
6608 free_extent_map(hole_em);
6610 free_extent_map(em);
6611 return ERR_PTR(err);
6616 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6619 struct btrfs_root *root = BTRFS_I(inode)->root;
6620 struct extent_map *em;
6621 struct btrfs_key ins;
6625 alloc_hint = get_extent_allocation_hint(inode, start, len);
6626 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6627 alloc_hint, &ins, 1, 1);
6629 return ERR_PTR(ret);
6631 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6632 ins.offset, ins.offset, ins.offset, 0);
6634 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6638 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6639 ins.offset, ins.offset, 0);
6641 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
6642 free_extent_map(em);
6643 return ERR_PTR(ret);
6650 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6651 * block must be cow'd
6653 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6654 u64 *orig_start, u64 *orig_block_len,
6657 struct btrfs_trans_handle *trans;
6658 struct btrfs_path *path;
6660 struct extent_buffer *leaf;
6661 struct btrfs_root *root = BTRFS_I(inode)->root;
6662 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6663 struct btrfs_file_extent_item *fi;
6664 struct btrfs_key key;
6671 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6673 path = btrfs_alloc_path();
6677 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6682 slot = path->slots[0];
6685 /* can't find the item, must cow */
6692 leaf = path->nodes[0];
6693 btrfs_item_key_to_cpu(leaf, &key, slot);
6694 if (key.objectid != btrfs_ino(inode) ||
6695 key.type != BTRFS_EXTENT_DATA_KEY) {
6696 /* not our file or wrong item type, must cow */
6700 if (key.offset > offset) {
6701 /* Wrong offset, must cow */
6705 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6706 found_type = btrfs_file_extent_type(leaf, fi);
6707 if (found_type != BTRFS_FILE_EXTENT_REG &&
6708 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6709 /* not a regular extent, must cow */
6713 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6716 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6717 if (extent_end <= offset)
6720 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6721 if (disk_bytenr == 0)
6724 if (btrfs_file_extent_compression(leaf, fi) ||
6725 btrfs_file_extent_encryption(leaf, fi) ||
6726 btrfs_file_extent_other_encoding(leaf, fi))
6729 backref_offset = btrfs_file_extent_offset(leaf, fi);
6732 *orig_start = key.offset - backref_offset;
6733 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6734 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6737 if (btrfs_extent_readonly(root, disk_bytenr))
6740 num_bytes = min(offset + *len, extent_end) - offset;
6741 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6744 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6745 ret = test_range_bit(io_tree, offset, range_end,
6746 EXTENT_DELALLOC, 0, NULL);
6753 btrfs_release_path(path);
6756 * look for other files referencing this extent, if we
6757 * find any we must cow
6759 trans = btrfs_join_transaction(root);
6760 if (IS_ERR(trans)) {
6765 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6766 key.offset - backref_offset, disk_bytenr);
6767 btrfs_end_transaction(trans, root);
6774 * adjust disk_bytenr and num_bytes to cover just the bytes
6775 * in this extent we are about to write. If there
6776 * are any csums in that range we have to cow in order
6777 * to keep the csums correct
6779 disk_bytenr += backref_offset;
6780 disk_bytenr += offset - key.offset;
6781 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6784 * all of the above have passed, it is safe to overwrite this extent
6790 btrfs_free_path(path);
6794 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
6796 struct radix_tree_root *root = &inode->i_mapping->page_tree;
6798 void **pagep = NULL;
6799 struct page *page = NULL;
6803 start_idx = start >> PAGE_CACHE_SHIFT;
6806 * end is the last byte in the last page. end == start is legal
6808 end_idx = end >> PAGE_CACHE_SHIFT;
6812 /* Most of the code in this while loop is lifted from
6813 * find_get_page. It's been modified to begin searching from a
6814 * page and return just the first page found in that range. If the
6815 * found idx is less than or equal to the end idx then we know that
6816 * a page exists. If no pages are found or if those pages are
6817 * outside of the range then we're fine (yay!) */
6818 while (page == NULL &&
6819 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
6820 page = radix_tree_deref_slot(pagep);
6821 if (unlikely(!page))
6824 if (radix_tree_exception(page)) {
6825 if (radix_tree_deref_retry(page)) {
6830 * Otherwise, shmem/tmpfs must be storing a swap entry
6831 * here as an exceptional entry: so return it without
6832 * attempting to raise page count.
6835 break; /* TODO: Is this relevant for this use case? */
6838 if (!page_cache_get_speculative(page)) {
6844 * Has the page moved?
6845 * This is part of the lockless pagecache protocol. See
6846 * include/linux/pagemap.h for details.
6848 if (unlikely(page != *pagep)) {
6849 page_cache_release(page);
6855 if (page->index <= end_idx)
6857 page_cache_release(page);
6864 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6865 struct extent_state **cached_state, int writing)
6867 struct btrfs_ordered_extent *ordered;
6871 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6874 * We're concerned with the entire range that we're going to be
6875 * doing DIO to, so we need to make sure theres no ordered
6876 * extents in this range.
6878 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6879 lockend - lockstart + 1);
6882 * We need to make sure there are no buffered pages in this
6883 * range either, we could have raced between the invalidate in
6884 * generic_file_direct_write and locking the extent. The
6885 * invalidate needs to happen so that reads after a write do not
6890 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
6893 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6894 cached_state, GFP_NOFS);
6897 btrfs_start_ordered_extent(inode, ordered, 1);
6898 btrfs_put_ordered_extent(ordered);
6900 /* Screw you mmap */
6901 ret = filemap_write_and_wait_range(inode->i_mapping,
6908 * If we found a page that couldn't be invalidated just
6909 * fall back to buffered.
6911 ret = invalidate_inode_pages2_range(inode->i_mapping,
6912 lockstart >> PAGE_CACHE_SHIFT,
6913 lockend >> PAGE_CACHE_SHIFT);
6924 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6925 u64 len, u64 orig_start,
6926 u64 block_start, u64 block_len,
6927 u64 orig_block_len, u64 ram_bytes,
6930 struct extent_map_tree *em_tree;
6931 struct extent_map *em;
6932 struct btrfs_root *root = BTRFS_I(inode)->root;
6935 em_tree = &BTRFS_I(inode)->extent_tree;
6936 em = alloc_extent_map();
6938 return ERR_PTR(-ENOMEM);
6941 em->orig_start = orig_start;
6942 em->mod_start = start;
6945 em->block_len = block_len;
6946 em->block_start = block_start;
6947 em->bdev = root->fs_info->fs_devices->latest_bdev;
6948 em->orig_block_len = orig_block_len;
6949 em->ram_bytes = ram_bytes;
6950 em->generation = -1;
6951 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6952 if (type == BTRFS_ORDERED_PREALLOC)
6953 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6956 btrfs_drop_extent_cache(inode, em->start,
6957 em->start + em->len - 1, 0);
6958 write_lock(&em_tree->lock);
6959 ret = add_extent_mapping(em_tree, em, 1);
6960 write_unlock(&em_tree->lock);
6961 } while (ret == -EEXIST);
6964 free_extent_map(em);
6965 return ERR_PTR(ret);
6972 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6973 struct buffer_head *bh_result, int create)
6975 struct extent_map *em;
6976 struct btrfs_root *root = BTRFS_I(inode)->root;
6977 struct extent_state *cached_state = NULL;
6978 u64 start = iblock << inode->i_blkbits;
6979 u64 lockstart, lockend;
6980 u64 len = bh_result->b_size;
6981 int unlock_bits = EXTENT_LOCKED;
6985 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6987 len = min_t(u64, len, root->sectorsize);
6990 lockend = start + len - 1;
6993 * If this errors out it's because we couldn't invalidate pagecache for
6994 * this range and we need to fallback to buffered.
6996 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6999 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7006 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7007 * io. INLINE is special, and we could probably kludge it in here, but
7008 * it's still buffered so for safety lets just fall back to the generic
7011 * For COMPRESSED we _have_ to read the entire extent in so we can
7012 * decompress it, so there will be buffering required no matter what we
7013 * do, so go ahead and fallback to buffered.
7015 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7016 * to buffered IO. Don't blame me, this is the price we pay for using
7019 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7020 em->block_start == EXTENT_MAP_INLINE) {
7021 free_extent_map(em);
7026 /* Just a good old fashioned hole, return */
7027 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7028 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7029 free_extent_map(em);
7034 * We don't allocate a new extent in the following cases
7036 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7038 * 2) The extent is marked as PREALLOC. We're good to go here and can
7039 * just use the extent.
7043 len = min(len, em->len - (start - em->start));
7044 lockstart = start + len;
7048 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7049 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7050 em->block_start != EXTENT_MAP_HOLE)) {
7053 u64 block_start, orig_start, orig_block_len, ram_bytes;
7055 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7056 type = BTRFS_ORDERED_PREALLOC;
7058 type = BTRFS_ORDERED_NOCOW;
7059 len = min(len, em->len - (start - em->start));
7060 block_start = em->block_start + (start - em->start);
7062 if (can_nocow_extent(inode, start, &len, &orig_start,
7063 &orig_block_len, &ram_bytes) == 1) {
7064 if (type == BTRFS_ORDERED_PREALLOC) {
7065 free_extent_map(em);
7066 em = create_pinned_em(inode, start, len,
7075 ret = btrfs_add_ordered_extent_dio(inode, start,
7076 block_start, len, len, type);
7078 free_extent_map(em);
7086 * this will cow the extent, reset the len in case we changed
7089 len = bh_result->b_size;
7090 free_extent_map(em);
7091 em = btrfs_new_extent_direct(inode, start, len);
7096 len = min(len, em->len - (start - em->start));
7098 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7100 bh_result->b_size = len;
7101 bh_result->b_bdev = em->bdev;
7102 set_buffer_mapped(bh_result);
7104 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7105 set_buffer_new(bh_result);
7108 * Need to update the i_size under the extent lock so buffered
7109 * readers will get the updated i_size when we unlock.
7111 if (start + len > i_size_read(inode))
7112 i_size_write(inode, start + len);
7114 spin_lock(&BTRFS_I(inode)->lock);
7115 BTRFS_I(inode)->outstanding_extents++;
7116 spin_unlock(&BTRFS_I(inode)->lock);
7118 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7119 lockstart + len - 1, EXTENT_DELALLOC, NULL,
7120 &cached_state, GFP_NOFS);
7125 * In the case of write we need to clear and unlock the entire range,
7126 * in the case of read we need to unlock only the end area that we
7127 * aren't using if there is any left over space.
7129 if (lockstart < lockend) {
7130 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7131 lockend, unlock_bits, 1, 0,
7132 &cached_state, GFP_NOFS);
7134 free_extent_state(cached_state);
7137 free_extent_map(em);
7142 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7143 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7147 static void btrfs_endio_direct_read(struct bio *bio, int err)
7149 struct btrfs_dio_private *dip = bio->bi_private;
7150 struct bio_vec *bvec;
7151 struct inode *inode = dip->inode;
7152 struct btrfs_root *root = BTRFS_I(inode)->root;
7153 struct bio *dio_bio;
7154 u32 *csums = (u32 *)dip->csum;
7158 start = dip->logical_offset;
7159 bio_for_each_segment_all(bvec, bio, i) {
7160 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
7161 struct page *page = bvec->bv_page;
7164 unsigned long flags;
7166 local_irq_save(flags);
7167 kaddr = kmap_atomic(page);
7168 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
7169 csum, bvec->bv_len);
7170 btrfs_csum_final(csum, (char *)&csum);
7171 kunmap_atomic(kaddr);
7172 local_irq_restore(flags);
7174 flush_dcache_page(bvec->bv_page);
7175 if (csum != csums[i]) {
7176 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
7177 btrfs_ino(inode), start, csum,
7183 start += bvec->bv_len;
7186 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7187 dip->logical_offset + dip->bytes - 1);
7188 dio_bio = dip->dio_bio;
7192 /* If we had a csum failure make sure to clear the uptodate flag */
7194 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7195 dio_end_io(dio_bio, err);
7199 static void btrfs_endio_direct_write(struct bio *bio, int err)
7201 struct btrfs_dio_private *dip = bio->bi_private;
7202 struct inode *inode = dip->inode;
7203 struct btrfs_root *root = BTRFS_I(inode)->root;
7204 struct btrfs_ordered_extent *ordered = NULL;
7205 u64 ordered_offset = dip->logical_offset;
7206 u64 ordered_bytes = dip->bytes;
7207 struct bio *dio_bio;
7213 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7215 ordered_bytes, !err);
7219 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7220 finish_ordered_fn, NULL, NULL);
7221 btrfs_queue_work(root->fs_info->endio_write_workers,
7225 * our bio might span multiple ordered extents. If we haven't
7226 * completed the accounting for the whole dio, go back and try again
7228 if (ordered_offset < dip->logical_offset + dip->bytes) {
7229 ordered_bytes = dip->logical_offset + dip->bytes -
7235 dio_bio = dip->dio_bio;
7239 /* If we had an error make sure to clear the uptodate flag */
7241 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7242 dio_end_io(dio_bio, err);
7246 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7247 struct bio *bio, int mirror_num,
7248 unsigned long bio_flags, u64 offset)
7251 struct btrfs_root *root = BTRFS_I(inode)->root;
7252 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7253 BUG_ON(ret); /* -ENOMEM */
7257 static void btrfs_end_dio_bio(struct bio *bio, int err)
7259 struct btrfs_dio_private *dip = bio->bi_private;
7262 btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
7263 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7264 btrfs_ino(dip->inode), bio->bi_rw,
7265 (unsigned long long)bio->bi_iter.bi_sector,
7266 bio->bi_iter.bi_size, err);
7270 * before atomic variable goto zero, we must make sure
7271 * dip->errors is perceived to be set.
7273 smp_mb__before_atomic();
7276 /* if there are more bios still pending for this dio, just exit */
7277 if (!atomic_dec_and_test(&dip->pending_bios))
7281 bio_io_error(dip->orig_bio);
7283 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7284 bio_endio(dip->orig_bio, 0);
7290 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7291 u64 first_sector, gfp_t gfp_flags)
7293 int nr_vecs = bio_get_nr_vecs(bdev);
7294 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7297 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7298 int rw, u64 file_offset, int skip_sum,
7301 struct btrfs_dio_private *dip = bio->bi_private;
7302 int write = rw & REQ_WRITE;
7303 struct btrfs_root *root = BTRFS_I(inode)->root;
7307 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7312 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7320 if (write && async_submit) {
7321 ret = btrfs_wq_submit_bio(root->fs_info,
7322 inode, rw, bio, 0, 0,
7324 __btrfs_submit_bio_start_direct_io,
7325 __btrfs_submit_bio_done);
7329 * If we aren't doing async submit, calculate the csum of the
7332 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7335 } else if (!skip_sum) {
7336 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
7343 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7349 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7352 struct inode *inode = dip->inode;
7353 struct btrfs_root *root = BTRFS_I(inode)->root;
7355 struct bio *orig_bio = dip->orig_bio;
7356 struct bio_vec *bvec = orig_bio->bi_io_vec;
7357 u64 start_sector = orig_bio->bi_iter.bi_sector;
7358 u64 file_offset = dip->logical_offset;
7363 int async_submit = 0;
7365 map_length = orig_bio->bi_iter.bi_size;
7366 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7367 &map_length, NULL, 0);
7371 if (map_length >= orig_bio->bi_iter.bi_size) {
7376 /* async crcs make it difficult to collect full stripe writes. */
7377 if (btrfs_get_alloc_profile(root, 1) &
7378 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7383 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7387 bio->bi_private = dip;
7388 bio->bi_end_io = btrfs_end_dio_bio;
7389 atomic_inc(&dip->pending_bios);
7391 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7392 if (unlikely(map_length < submit_len + bvec->bv_len ||
7393 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7394 bvec->bv_offset) < bvec->bv_len)) {
7396 * inc the count before we submit the bio so
7397 * we know the end IO handler won't happen before
7398 * we inc the count. Otherwise, the dip might get freed
7399 * before we're done setting it up
7401 atomic_inc(&dip->pending_bios);
7402 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7403 file_offset, skip_sum,
7407 atomic_dec(&dip->pending_bios);
7411 start_sector += submit_len >> 9;
7412 file_offset += submit_len;
7417 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7418 start_sector, GFP_NOFS);
7421 bio->bi_private = dip;
7422 bio->bi_end_io = btrfs_end_dio_bio;
7424 map_length = orig_bio->bi_iter.bi_size;
7425 ret = btrfs_map_block(root->fs_info, rw,
7427 &map_length, NULL, 0);
7433 submit_len += bvec->bv_len;
7440 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7449 * before atomic variable goto zero, we must
7450 * make sure dip->errors is perceived to be set.
7452 smp_mb__before_atomic();
7453 if (atomic_dec_and_test(&dip->pending_bios))
7454 bio_io_error(dip->orig_bio);
7456 /* bio_end_io() will handle error, so we needn't return it */
7460 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7461 struct inode *inode, loff_t file_offset)
7463 struct btrfs_root *root = BTRFS_I(inode)->root;
7464 struct btrfs_dio_private *dip;
7468 int write = rw & REQ_WRITE;
7472 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7474 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7480 if (!skip_sum && !write) {
7481 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7482 sum_len = dio_bio->bi_iter.bi_size >>
7483 inode->i_sb->s_blocksize_bits;
7484 sum_len *= csum_size;
7489 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7495 dip->private = dio_bio->bi_private;
7497 dip->logical_offset = file_offset;
7498 dip->bytes = dio_bio->bi_iter.bi_size;
7499 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7500 io_bio->bi_private = dip;
7502 dip->orig_bio = io_bio;
7503 dip->dio_bio = dio_bio;
7504 atomic_set(&dip->pending_bios, 0);
7507 io_bio->bi_end_io = btrfs_endio_direct_write;
7509 io_bio->bi_end_io = btrfs_endio_direct_read;
7511 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7520 * If this is a write, we need to clean up the reserved space and kill
7521 * the ordered extent.
7524 struct btrfs_ordered_extent *ordered;
7525 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7526 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7527 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7528 btrfs_free_reserved_extent(root, ordered->start,
7529 ordered->disk_len, 1);
7530 btrfs_put_ordered_extent(ordered);
7531 btrfs_put_ordered_extent(ordered);
7533 bio_endio(dio_bio, ret);
7536 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7537 const struct iov_iter *iter, loff_t offset)
7541 unsigned blocksize_mask = root->sectorsize - 1;
7542 ssize_t retval = -EINVAL;
7544 if (offset & blocksize_mask)
7547 if (iov_iter_alignment(iter) & blocksize_mask)
7550 /* If this is a write we don't need to check anymore */
7554 * Check to make sure we don't have duplicate iov_base's in this
7555 * iovec, if so return EINVAL, otherwise we'll get csum errors
7556 * when reading back.
7558 for (seg = 0; seg < iter->nr_segs; seg++) {
7559 for (i = seg + 1; i < iter->nr_segs; i++) {
7560 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
7569 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7570 struct iov_iter *iter, loff_t offset)
7572 struct file *file = iocb->ki_filp;
7573 struct inode *inode = file->f_mapping->host;
7577 bool relock = false;
7580 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
7583 atomic_inc(&inode->i_dio_count);
7584 smp_mb__after_atomic();
7587 * The generic stuff only does filemap_write_and_wait_range, which
7588 * isn't enough if we've written compressed pages to this area, so
7589 * we need to flush the dirty pages again to make absolutely sure
7590 * that any outstanding dirty pages are on disk.
7592 count = iov_iter_count(iter);
7593 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7594 &BTRFS_I(inode)->runtime_flags))
7595 filemap_fdatawrite_range(inode->i_mapping, offset,
7596 offset + count - 1);
7600 * If the write DIO is beyond the EOF, we need update
7601 * the isize, but it is protected by i_mutex. So we can
7602 * not unlock the i_mutex at this case.
7604 if (offset + count <= inode->i_size) {
7605 mutex_unlock(&inode->i_mutex);
7608 ret = btrfs_delalloc_reserve_space(inode, count);
7611 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7612 &BTRFS_I(inode)->runtime_flags))) {
7613 inode_dio_done(inode);
7614 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7618 ret = __blockdev_direct_IO(rw, iocb, inode,
7619 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7620 iter, offset, btrfs_get_blocks_direct, NULL,
7621 btrfs_submit_direct, flags);
7623 if (ret < 0 && ret != -EIOCBQUEUED)
7624 btrfs_delalloc_release_space(inode, count);
7625 else if (ret >= 0 && (size_t)ret < count)
7626 btrfs_delalloc_release_space(inode,
7627 count - (size_t)ret);
7629 btrfs_delalloc_release_metadata(inode, 0);
7633 inode_dio_done(inode);
7635 mutex_lock(&inode->i_mutex);
7640 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7642 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7643 __u64 start, __u64 len)
7647 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7651 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7654 int btrfs_readpage(struct file *file, struct page *page)
7656 struct extent_io_tree *tree;
7657 tree = &BTRFS_I(page->mapping->host)->io_tree;
7658 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7661 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7663 struct extent_io_tree *tree;
7666 if (current->flags & PF_MEMALLOC) {
7667 redirty_page_for_writepage(wbc, page);
7671 tree = &BTRFS_I(page->mapping->host)->io_tree;
7672 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7675 static int btrfs_writepages(struct address_space *mapping,
7676 struct writeback_control *wbc)
7678 struct extent_io_tree *tree;
7680 tree = &BTRFS_I(mapping->host)->io_tree;
7681 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7685 btrfs_readpages(struct file *file, struct address_space *mapping,
7686 struct list_head *pages, unsigned nr_pages)
7688 struct extent_io_tree *tree;
7689 tree = &BTRFS_I(mapping->host)->io_tree;
7690 return extent_readpages(tree, mapping, pages, nr_pages,
7693 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7695 struct extent_io_tree *tree;
7696 struct extent_map_tree *map;
7699 tree = &BTRFS_I(page->mapping->host)->io_tree;
7700 map = &BTRFS_I(page->mapping->host)->extent_tree;
7701 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7703 ClearPagePrivate(page);
7704 set_page_private(page, 0);
7705 page_cache_release(page);
7710 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7712 if (PageWriteback(page) || PageDirty(page))
7714 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7717 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7718 unsigned int length)
7720 struct inode *inode = page->mapping->host;
7721 struct extent_io_tree *tree;
7722 struct btrfs_ordered_extent *ordered;
7723 struct extent_state *cached_state = NULL;
7724 u64 page_start = page_offset(page);
7725 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7726 int inode_evicting = inode->i_state & I_FREEING;
7729 * we have the page locked, so new writeback can't start,
7730 * and the dirty bit won't be cleared while we are here.
7732 * Wait for IO on this page so that we can safely clear
7733 * the PagePrivate2 bit and do ordered accounting
7735 wait_on_page_writeback(page);
7737 tree = &BTRFS_I(inode)->io_tree;
7739 btrfs_releasepage(page, GFP_NOFS);
7743 if (!inode_evicting)
7744 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7745 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7748 * IO on this page will never be started, so we need
7749 * to account for any ordered extents now
7751 if (!inode_evicting)
7752 clear_extent_bit(tree, page_start, page_end,
7753 EXTENT_DIRTY | EXTENT_DELALLOC |
7754 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7755 EXTENT_DEFRAG, 1, 0, &cached_state,
7758 * whoever cleared the private bit is responsible
7759 * for the finish_ordered_io
7761 if (TestClearPagePrivate2(page)) {
7762 struct btrfs_ordered_inode_tree *tree;
7765 tree = &BTRFS_I(inode)->ordered_tree;
7767 spin_lock_irq(&tree->lock);
7768 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7769 new_len = page_start - ordered->file_offset;
7770 if (new_len < ordered->truncated_len)
7771 ordered->truncated_len = new_len;
7772 spin_unlock_irq(&tree->lock);
7774 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7776 PAGE_CACHE_SIZE, 1))
7777 btrfs_finish_ordered_io(ordered);
7779 btrfs_put_ordered_extent(ordered);
7780 if (!inode_evicting) {
7781 cached_state = NULL;
7782 lock_extent_bits(tree, page_start, page_end, 0,
7787 if (!inode_evicting) {
7788 clear_extent_bit(tree, page_start, page_end,
7789 EXTENT_LOCKED | EXTENT_DIRTY |
7790 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7791 EXTENT_DEFRAG, 1, 1,
7792 &cached_state, GFP_NOFS);
7794 __btrfs_releasepage(page, GFP_NOFS);
7797 ClearPageChecked(page);
7798 if (PagePrivate(page)) {
7799 ClearPagePrivate(page);
7800 set_page_private(page, 0);
7801 page_cache_release(page);
7806 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7807 * called from a page fault handler when a page is first dirtied. Hence we must
7808 * be careful to check for EOF conditions here. We set the page up correctly
7809 * for a written page which means we get ENOSPC checking when writing into
7810 * holes and correct delalloc and unwritten extent mapping on filesystems that
7811 * support these features.
7813 * We are not allowed to take the i_mutex here so we have to play games to
7814 * protect against truncate races as the page could now be beyond EOF. Because
7815 * vmtruncate() writes the inode size before removing pages, once we have the
7816 * page lock we can determine safely if the page is beyond EOF. If it is not
7817 * beyond EOF, then the page is guaranteed safe against truncation until we
7820 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7822 struct page *page = vmf->page;
7823 struct inode *inode = file_inode(vma->vm_file);
7824 struct btrfs_root *root = BTRFS_I(inode)->root;
7825 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7826 struct btrfs_ordered_extent *ordered;
7827 struct extent_state *cached_state = NULL;
7829 unsigned long zero_start;
7836 sb_start_pagefault(inode->i_sb);
7837 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7839 ret = file_update_time(vma->vm_file);
7845 else /* -ENOSPC, -EIO, etc */
7846 ret = VM_FAULT_SIGBUS;
7852 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7855 size = i_size_read(inode);
7856 page_start = page_offset(page);
7857 page_end = page_start + PAGE_CACHE_SIZE - 1;
7859 if ((page->mapping != inode->i_mapping) ||
7860 (page_start >= size)) {
7861 /* page got truncated out from underneath us */
7864 wait_on_page_writeback(page);
7866 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7867 set_page_extent_mapped(page);
7870 * we can't set the delalloc bits if there are pending ordered
7871 * extents. Drop our locks and wait for them to finish
7873 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7875 unlock_extent_cached(io_tree, page_start, page_end,
7876 &cached_state, GFP_NOFS);
7878 btrfs_start_ordered_extent(inode, ordered, 1);
7879 btrfs_put_ordered_extent(ordered);
7884 * XXX - page_mkwrite gets called every time the page is dirtied, even
7885 * if it was already dirty, so for space accounting reasons we need to
7886 * clear any delalloc bits for the range we are fixing to save. There
7887 * is probably a better way to do this, but for now keep consistent with
7888 * prepare_pages in the normal write path.
7890 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7891 EXTENT_DIRTY | EXTENT_DELALLOC |
7892 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7893 0, 0, &cached_state, GFP_NOFS);
7895 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7898 unlock_extent_cached(io_tree, page_start, page_end,
7899 &cached_state, GFP_NOFS);
7900 ret = VM_FAULT_SIGBUS;
7905 /* page is wholly or partially inside EOF */
7906 if (page_start + PAGE_CACHE_SIZE > size)
7907 zero_start = size & ~PAGE_CACHE_MASK;
7909 zero_start = PAGE_CACHE_SIZE;
7911 if (zero_start != PAGE_CACHE_SIZE) {
7913 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7914 flush_dcache_page(page);
7917 ClearPageChecked(page);
7918 set_page_dirty(page);
7919 SetPageUptodate(page);
7921 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7922 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7923 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7925 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7929 sb_end_pagefault(inode->i_sb);
7930 return VM_FAULT_LOCKED;
7934 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7936 sb_end_pagefault(inode->i_sb);
7940 static int btrfs_truncate(struct inode *inode)
7942 struct btrfs_root *root = BTRFS_I(inode)->root;
7943 struct btrfs_block_rsv *rsv;
7946 struct btrfs_trans_handle *trans;
7947 u64 mask = root->sectorsize - 1;
7948 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7950 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
7956 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7957 * 3 things going on here
7959 * 1) We need to reserve space for our orphan item and the space to
7960 * delete our orphan item. Lord knows we don't want to have a dangling
7961 * orphan item because we didn't reserve space to remove it.
7963 * 2) We need to reserve space to update our inode.
7965 * 3) We need to have something to cache all the space that is going to
7966 * be free'd up by the truncate operation, but also have some slack
7967 * space reserved in case it uses space during the truncate (thank you
7968 * very much snapshotting).
7970 * And we need these to all be seperate. The fact is we can use alot of
7971 * space doing the truncate, and we have no earthly idea how much space
7972 * we will use, so we need the truncate reservation to be seperate so it
7973 * doesn't end up using space reserved for updating the inode or
7974 * removing the orphan item. We also need to be able to stop the
7975 * transaction and start a new one, which means we need to be able to
7976 * update the inode several times, and we have no idea of knowing how
7977 * many times that will be, so we can't just reserve 1 item for the
7978 * entirety of the opration, so that has to be done seperately as well.
7979 * Then there is the orphan item, which does indeed need to be held on
7980 * to for the whole operation, and we need nobody to touch this reserved
7981 * space except the orphan code.
7983 * So that leaves us with
7985 * 1) root->orphan_block_rsv - for the orphan deletion.
7986 * 2) rsv - for the truncate reservation, which we will steal from the
7987 * transaction reservation.
7988 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7989 * updating the inode.
7991 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7994 rsv->size = min_size;
7998 * 1 for the truncate slack space
7999 * 1 for updating the inode.
8001 trans = btrfs_start_transaction(root, 2);
8002 if (IS_ERR(trans)) {
8003 err = PTR_ERR(trans);
8007 /* Migrate the slack space for the truncate to our reserve */
8008 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8013 * So if we truncate and then write and fsync we normally would just
8014 * write the extents that changed, which is a problem if we need to
8015 * first truncate that entire inode. So set this flag so we write out
8016 * all of the extents in the inode to the sync log so we're completely
8019 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8020 trans->block_rsv = rsv;
8023 ret = btrfs_truncate_inode_items(trans, root, inode,
8025 BTRFS_EXTENT_DATA_KEY);
8026 if (ret != -ENOSPC) {
8031 trans->block_rsv = &root->fs_info->trans_block_rsv;
8032 ret = btrfs_update_inode(trans, root, inode);
8038 btrfs_end_transaction(trans, root);
8039 btrfs_btree_balance_dirty(root);
8041 trans = btrfs_start_transaction(root, 2);
8042 if (IS_ERR(trans)) {
8043 ret = err = PTR_ERR(trans);
8048 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8050 BUG_ON(ret); /* shouldn't happen */
8051 trans->block_rsv = rsv;
8054 if (ret == 0 && inode->i_nlink > 0) {
8055 trans->block_rsv = root->orphan_block_rsv;
8056 ret = btrfs_orphan_del(trans, inode);
8062 trans->block_rsv = &root->fs_info->trans_block_rsv;
8063 ret = btrfs_update_inode(trans, root, inode);
8067 ret = btrfs_end_transaction(trans, root);
8068 btrfs_btree_balance_dirty(root);
8072 btrfs_free_block_rsv(root, rsv);
8081 * create a new subvolume directory/inode (helper for the ioctl).
8083 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8084 struct btrfs_root *new_root,
8085 struct btrfs_root *parent_root,
8088 struct inode *inode;
8092 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8093 new_dirid, new_dirid,
8094 S_IFDIR | (~current_umask() & S_IRWXUGO),
8097 return PTR_ERR(inode);
8098 inode->i_op = &btrfs_dir_inode_operations;
8099 inode->i_fop = &btrfs_dir_file_operations;
8101 set_nlink(inode, 1);
8102 btrfs_i_size_write(inode, 0);
8104 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8106 btrfs_err(new_root->fs_info,
8107 "error inheriting subvolume %llu properties: %d",
8108 new_root->root_key.objectid, err);
8110 err = btrfs_update_inode(trans, new_root, inode);
8116 struct inode *btrfs_alloc_inode(struct super_block *sb)
8118 struct btrfs_inode *ei;
8119 struct inode *inode;
8121 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8128 ei->last_sub_trans = 0;
8129 ei->logged_trans = 0;
8130 ei->delalloc_bytes = 0;
8131 ei->disk_i_size = 0;
8134 ei->index_cnt = (u64)-1;
8136 ei->last_unlink_trans = 0;
8137 ei->last_log_commit = 0;
8139 spin_lock_init(&ei->lock);
8140 ei->outstanding_extents = 0;
8141 ei->reserved_extents = 0;
8143 ei->runtime_flags = 0;
8144 ei->force_compress = BTRFS_COMPRESS_NONE;
8146 ei->delayed_node = NULL;
8148 inode = &ei->vfs_inode;
8149 extent_map_tree_init(&ei->extent_tree);
8150 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8151 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8152 ei->io_tree.track_uptodate = 1;
8153 ei->io_failure_tree.track_uptodate = 1;
8154 atomic_set(&ei->sync_writers, 0);
8155 mutex_init(&ei->log_mutex);
8156 mutex_init(&ei->delalloc_mutex);
8157 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8158 INIT_LIST_HEAD(&ei->delalloc_inodes);
8159 RB_CLEAR_NODE(&ei->rb_node);
8164 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8165 void btrfs_test_destroy_inode(struct inode *inode)
8167 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8168 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8172 static void btrfs_i_callback(struct rcu_head *head)
8174 struct inode *inode = container_of(head, struct inode, i_rcu);
8175 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8178 void btrfs_destroy_inode(struct inode *inode)
8180 struct btrfs_ordered_extent *ordered;
8181 struct btrfs_root *root = BTRFS_I(inode)->root;
8183 WARN_ON(!hlist_empty(&inode->i_dentry));
8184 WARN_ON(inode->i_data.nrpages);
8185 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8186 WARN_ON(BTRFS_I(inode)->reserved_extents);
8187 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8188 WARN_ON(BTRFS_I(inode)->csum_bytes);
8191 * This can happen where we create an inode, but somebody else also
8192 * created the same inode and we need to destroy the one we already
8198 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8199 &BTRFS_I(inode)->runtime_flags)) {
8200 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8202 atomic_dec(&root->orphan_inodes);
8206 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8210 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8211 ordered->file_offset, ordered->len);
8212 btrfs_remove_ordered_extent(inode, ordered);
8213 btrfs_put_ordered_extent(ordered);
8214 btrfs_put_ordered_extent(ordered);
8217 inode_tree_del(inode);
8218 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8220 call_rcu(&inode->i_rcu, btrfs_i_callback);
8223 int btrfs_drop_inode(struct inode *inode)
8225 struct btrfs_root *root = BTRFS_I(inode)->root;
8230 /* the snap/subvol tree is on deleting */
8231 if (btrfs_root_refs(&root->root_item) == 0)
8234 return generic_drop_inode(inode);
8237 static void init_once(void *foo)
8239 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8241 inode_init_once(&ei->vfs_inode);
8244 void btrfs_destroy_cachep(void)
8247 * Make sure all delayed rcu free inodes are flushed before we
8251 if (btrfs_inode_cachep)
8252 kmem_cache_destroy(btrfs_inode_cachep);
8253 if (btrfs_trans_handle_cachep)
8254 kmem_cache_destroy(btrfs_trans_handle_cachep);
8255 if (btrfs_transaction_cachep)
8256 kmem_cache_destroy(btrfs_transaction_cachep);
8257 if (btrfs_path_cachep)
8258 kmem_cache_destroy(btrfs_path_cachep);
8259 if (btrfs_free_space_cachep)
8260 kmem_cache_destroy(btrfs_free_space_cachep);
8261 if (btrfs_delalloc_work_cachep)
8262 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8265 int btrfs_init_cachep(void)
8267 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8268 sizeof(struct btrfs_inode), 0,
8269 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8270 if (!btrfs_inode_cachep)
8273 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8274 sizeof(struct btrfs_trans_handle), 0,
8275 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8276 if (!btrfs_trans_handle_cachep)
8279 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8280 sizeof(struct btrfs_transaction), 0,
8281 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8282 if (!btrfs_transaction_cachep)
8285 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8286 sizeof(struct btrfs_path), 0,
8287 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8288 if (!btrfs_path_cachep)
8291 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8292 sizeof(struct btrfs_free_space), 0,
8293 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8294 if (!btrfs_free_space_cachep)
8297 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8298 sizeof(struct btrfs_delalloc_work), 0,
8299 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8301 if (!btrfs_delalloc_work_cachep)
8306 btrfs_destroy_cachep();
8310 static int btrfs_getattr(struct vfsmount *mnt,
8311 struct dentry *dentry, struct kstat *stat)
8314 struct inode *inode = dentry->d_inode;
8315 u32 blocksize = inode->i_sb->s_blocksize;
8317 generic_fillattr(inode, stat);
8318 stat->dev = BTRFS_I(inode)->root->anon_dev;
8319 stat->blksize = PAGE_CACHE_SIZE;
8321 spin_lock(&BTRFS_I(inode)->lock);
8322 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8323 spin_unlock(&BTRFS_I(inode)->lock);
8324 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8325 ALIGN(delalloc_bytes, blocksize)) >> 9;
8329 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8330 struct inode *new_dir, struct dentry *new_dentry)
8332 struct btrfs_trans_handle *trans;
8333 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8334 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8335 struct inode *new_inode = new_dentry->d_inode;
8336 struct inode *old_inode = old_dentry->d_inode;
8337 struct timespec ctime = CURRENT_TIME;
8341 u64 old_ino = btrfs_ino(old_inode);
8343 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8346 /* we only allow rename subvolume link between subvolumes */
8347 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8350 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8351 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8354 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8355 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8359 /* check for collisions, even if the name isn't there */
8360 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8361 new_dentry->d_name.name,
8362 new_dentry->d_name.len);
8365 if (ret == -EEXIST) {
8367 * eexist without a new_inode */
8368 if (WARN_ON(!new_inode)) {
8372 /* maybe -EOVERFLOW */
8379 * we're using rename to replace one file with another. Start IO on it
8380 * now so we don't add too much work to the end of the transaction
8382 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8383 filemap_flush(old_inode->i_mapping);
8385 /* close the racy window with snapshot create/destroy ioctl */
8386 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8387 down_read(&root->fs_info->subvol_sem);
8389 * We want to reserve the absolute worst case amount of items. So if
8390 * both inodes are subvols and we need to unlink them then that would
8391 * require 4 item modifications, but if they are both normal inodes it
8392 * would require 5 item modifications, so we'll assume their normal
8393 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8394 * should cover the worst case number of items we'll modify.
8396 trans = btrfs_start_transaction(root, 11);
8397 if (IS_ERR(trans)) {
8398 ret = PTR_ERR(trans);
8403 btrfs_record_root_in_trans(trans, dest);
8405 ret = btrfs_set_inode_index(new_dir, &index);
8409 BTRFS_I(old_inode)->dir_index = 0ULL;
8410 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8411 /* force full log commit if subvolume involved. */
8412 btrfs_set_log_full_commit(root->fs_info, trans);
8414 ret = btrfs_insert_inode_ref(trans, dest,
8415 new_dentry->d_name.name,
8416 new_dentry->d_name.len,
8418 btrfs_ino(new_dir), index);
8422 * this is an ugly little race, but the rename is required
8423 * to make sure that if we crash, the inode is either at the
8424 * old name or the new one. pinning the log transaction lets
8425 * us make sure we don't allow a log commit to come in after
8426 * we unlink the name but before we add the new name back in.
8428 btrfs_pin_log_trans(root);
8431 inode_inc_iversion(old_dir);
8432 inode_inc_iversion(new_dir);
8433 inode_inc_iversion(old_inode);
8434 old_dir->i_ctime = old_dir->i_mtime = ctime;
8435 new_dir->i_ctime = new_dir->i_mtime = ctime;
8436 old_inode->i_ctime = ctime;
8438 if (old_dentry->d_parent != new_dentry->d_parent)
8439 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8441 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8442 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8443 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8444 old_dentry->d_name.name,
8445 old_dentry->d_name.len);
8447 ret = __btrfs_unlink_inode(trans, root, old_dir,
8448 old_dentry->d_inode,
8449 old_dentry->d_name.name,
8450 old_dentry->d_name.len);
8452 ret = btrfs_update_inode(trans, root, old_inode);
8455 btrfs_abort_transaction(trans, root, ret);
8460 inode_inc_iversion(new_inode);
8461 new_inode->i_ctime = CURRENT_TIME;
8462 if (unlikely(btrfs_ino(new_inode) ==
8463 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8464 root_objectid = BTRFS_I(new_inode)->location.objectid;
8465 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8467 new_dentry->d_name.name,
8468 new_dentry->d_name.len);
8469 BUG_ON(new_inode->i_nlink == 0);
8471 ret = btrfs_unlink_inode(trans, dest, new_dir,
8472 new_dentry->d_inode,
8473 new_dentry->d_name.name,
8474 new_dentry->d_name.len);
8476 if (!ret && new_inode->i_nlink == 0)
8477 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8479 btrfs_abort_transaction(trans, root, ret);
8484 ret = btrfs_add_link(trans, new_dir, old_inode,
8485 new_dentry->d_name.name,
8486 new_dentry->d_name.len, 0, index);
8488 btrfs_abort_transaction(trans, root, ret);
8492 if (old_inode->i_nlink == 1)
8493 BTRFS_I(old_inode)->dir_index = index;
8495 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8496 struct dentry *parent = new_dentry->d_parent;
8497 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8498 btrfs_end_log_trans(root);
8501 btrfs_end_transaction(trans, root);
8503 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8504 up_read(&root->fs_info->subvol_sem);
8509 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
8510 struct inode *new_dir, struct dentry *new_dentry,
8513 if (flags & ~RENAME_NOREPLACE)
8516 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
8519 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8521 struct btrfs_delalloc_work *delalloc_work;
8522 struct inode *inode;
8524 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8526 inode = delalloc_work->inode;
8527 if (delalloc_work->wait) {
8528 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8530 filemap_flush(inode->i_mapping);
8531 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8532 &BTRFS_I(inode)->runtime_flags))
8533 filemap_flush(inode->i_mapping);
8536 if (delalloc_work->delay_iput)
8537 btrfs_add_delayed_iput(inode);
8540 complete(&delalloc_work->completion);
8543 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8544 int wait, int delay_iput)
8546 struct btrfs_delalloc_work *work;
8548 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8552 init_completion(&work->completion);
8553 INIT_LIST_HEAD(&work->list);
8554 work->inode = inode;
8556 work->delay_iput = delay_iput;
8557 WARN_ON_ONCE(!inode);
8558 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
8559 btrfs_run_delalloc_work, NULL, NULL);
8564 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8566 wait_for_completion(&work->completion);
8567 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8571 * some fairly slow code that needs optimization. This walks the list
8572 * of all the inodes with pending delalloc and forces them to disk.
8574 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
8577 struct btrfs_inode *binode;
8578 struct inode *inode;
8579 struct btrfs_delalloc_work *work, *next;
8580 struct list_head works;
8581 struct list_head splice;
8584 INIT_LIST_HEAD(&works);
8585 INIT_LIST_HEAD(&splice);
8587 mutex_lock(&root->delalloc_mutex);
8588 spin_lock(&root->delalloc_lock);
8589 list_splice_init(&root->delalloc_inodes, &splice);
8590 while (!list_empty(&splice)) {
8591 binode = list_entry(splice.next, struct btrfs_inode,
8594 list_move_tail(&binode->delalloc_inodes,
8595 &root->delalloc_inodes);
8596 inode = igrab(&binode->vfs_inode);
8598 cond_resched_lock(&root->delalloc_lock);
8601 spin_unlock(&root->delalloc_lock);
8603 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8604 if (unlikely(!work)) {
8606 btrfs_add_delayed_iput(inode);
8612 list_add_tail(&work->list, &works);
8613 btrfs_queue_work(root->fs_info->flush_workers,
8616 if (nr != -1 && ret >= nr)
8619 spin_lock(&root->delalloc_lock);
8621 spin_unlock(&root->delalloc_lock);
8624 list_for_each_entry_safe(work, next, &works, list) {
8625 list_del_init(&work->list);
8626 btrfs_wait_and_free_delalloc_work(work);
8629 if (!list_empty_careful(&splice)) {
8630 spin_lock(&root->delalloc_lock);
8631 list_splice_tail(&splice, &root->delalloc_inodes);
8632 spin_unlock(&root->delalloc_lock);
8634 mutex_unlock(&root->delalloc_mutex);
8638 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8642 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
8645 ret = __start_delalloc_inodes(root, delay_iput, -1);
8649 * the filemap_flush will queue IO into the worker threads, but
8650 * we have to make sure the IO is actually started and that
8651 * ordered extents get created before we return
8653 atomic_inc(&root->fs_info->async_submit_draining);
8654 while (atomic_read(&root->fs_info->nr_async_submits) ||
8655 atomic_read(&root->fs_info->async_delalloc_pages)) {
8656 wait_event(root->fs_info->async_submit_wait,
8657 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8658 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8660 atomic_dec(&root->fs_info->async_submit_draining);
8664 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
8667 struct btrfs_root *root;
8668 struct list_head splice;
8671 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
8674 INIT_LIST_HEAD(&splice);
8676 mutex_lock(&fs_info->delalloc_root_mutex);
8677 spin_lock(&fs_info->delalloc_root_lock);
8678 list_splice_init(&fs_info->delalloc_roots, &splice);
8679 while (!list_empty(&splice) && nr) {
8680 root = list_first_entry(&splice, struct btrfs_root,
8682 root = btrfs_grab_fs_root(root);
8684 list_move_tail(&root->delalloc_root,
8685 &fs_info->delalloc_roots);
8686 spin_unlock(&fs_info->delalloc_root_lock);
8688 ret = __start_delalloc_inodes(root, delay_iput, nr);
8689 btrfs_put_fs_root(root);
8697 spin_lock(&fs_info->delalloc_root_lock);
8699 spin_unlock(&fs_info->delalloc_root_lock);
8702 atomic_inc(&fs_info->async_submit_draining);
8703 while (atomic_read(&fs_info->nr_async_submits) ||
8704 atomic_read(&fs_info->async_delalloc_pages)) {
8705 wait_event(fs_info->async_submit_wait,
8706 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8707 atomic_read(&fs_info->async_delalloc_pages) == 0));
8709 atomic_dec(&fs_info->async_submit_draining);
8711 if (!list_empty_careful(&splice)) {
8712 spin_lock(&fs_info->delalloc_root_lock);
8713 list_splice_tail(&splice, &fs_info->delalloc_roots);
8714 spin_unlock(&fs_info->delalloc_root_lock);
8716 mutex_unlock(&fs_info->delalloc_root_mutex);
8720 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8721 const char *symname)
8723 struct btrfs_trans_handle *trans;
8724 struct btrfs_root *root = BTRFS_I(dir)->root;
8725 struct btrfs_path *path;
8726 struct btrfs_key key;
8727 struct inode *inode = NULL;
8735 struct btrfs_file_extent_item *ei;
8736 struct extent_buffer *leaf;
8738 name_len = strlen(symname);
8739 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8740 return -ENAMETOOLONG;
8743 * 2 items for inode item and ref
8744 * 2 items for dir items
8745 * 1 item for xattr if selinux is on
8747 trans = btrfs_start_transaction(root, 5);
8749 return PTR_ERR(trans);
8751 err = btrfs_find_free_ino(root, &objectid);
8755 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8756 dentry->d_name.len, btrfs_ino(dir), objectid,
8757 S_IFLNK|S_IRWXUGO, &index);
8758 if (IS_ERR(inode)) {
8759 err = PTR_ERR(inode);
8763 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8770 * If the active LSM wants to access the inode during
8771 * d_instantiate it needs these. Smack checks to see
8772 * if the filesystem supports xattrs by looking at the
8775 inode->i_fop = &btrfs_file_operations;
8776 inode->i_op = &btrfs_file_inode_operations;
8778 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8782 inode->i_mapping->a_ops = &btrfs_aops;
8783 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8784 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8789 path = btrfs_alloc_path();
8795 key.objectid = btrfs_ino(inode);
8797 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8798 datasize = btrfs_file_extent_calc_inline_size(name_len);
8799 err = btrfs_insert_empty_item(trans, root, path, &key,
8803 btrfs_free_path(path);
8806 leaf = path->nodes[0];
8807 ei = btrfs_item_ptr(leaf, path->slots[0],
8808 struct btrfs_file_extent_item);
8809 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8810 btrfs_set_file_extent_type(leaf, ei,
8811 BTRFS_FILE_EXTENT_INLINE);
8812 btrfs_set_file_extent_encryption(leaf, ei, 0);
8813 btrfs_set_file_extent_compression(leaf, ei, 0);
8814 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8815 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8817 ptr = btrfs_file_extent_inline_start(ei);
8818 write_extent_buffer(leaf, symname, ptr, name_len);
8819 btrfs_mark_buffer_dirty(leaf);
8820 btrfs_free_path(path);
8822 inode->i_op = &btrfs_symlink_inode_operations;
8823 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8824 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8825 inode_set_bytes(inode, name_len);
8826 btrfs_i_size_write(inode, name_len);
8827 err = btrfs_update_inode(trans, root, inode);
8833 d_instantiate(dentry, inode);
8834 btrfs_end_transaction(trans, root);
8836 inode_dec_link_count(inode);
8839 btrfs_btree_balance_dirty(root);
8843 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8844 u64 start, u64 num_bytes, u64 min_size,
8845 loff_t actual_len, u64 *alloc_hint,
8846 struct btrfs_trans_handle *trans)
8848 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8849 struct extent_map *em;
8850 struct btrfs_root *root = BTRFS_I(inode)->root;
8851 struct btrfs_key ins;
8852 u64 cur_offset = start;
8856 bool own_trans = true;
8860 while (num_bytes > 0) {
8862 trans = btrfs_start_transaction(root, 3);
8863 if (IS_ERR(trans)) {
8864 ret = PTR_ERR(trans);
8869 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8870 cur_bytes = max(cur_bytes, min_size);
8871 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8872 *alloc_hint, &ins, 1, 0);
8875 btrfs_end_transaction(trans, root);
8879 ret = insert_reserved_file_extent(trans, inode,
8880 cur_offset, ins.objectid,
8881 ins.offset, ins.offset,
8882 ins.offset, 0, 0, 0,
8883 BTRFS_FILE_EXTENT_PREALLOC);
8885 btrfs_free_reserved_extent(root, ins.objectid,
8887 btrfs_abort_transaction(trans, root, ret);
8889 btrfs_end_transaction(trans, root);
8892 btrfs_drop_extent_cache(inode, cur_offset,
8893 cur_offset + ins.offset -1, 0);
8895 em = alloc_extent_map();
8897 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8898 &BTRFS_I(inode)->runtime_flags);
8902 em->start = cur_offset;
8903 em->orig_start = cur_offset;
8904 em->len = ins.offset;
8905 em->block_start = ins.objectid;
8906 em->block_len = ins.offset;
8907 em->orig_block_len = ins.offset;
8908 em->ram_bytes = ins.offset;
8909 em->bdev = root->fs_info->fs_devices->latest_bdev;
8910 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8911 em->generation = trans->transid;
8914 write_lock(&em_tree->lock);
8915 ret = add_extent_mapping(em_tree, em, 1);
8916 write_unlock(&em_tree->lock);
8919 btrfs_drop_extent_cache(inode, cur_offset,
8920 cur_offset + ins.offset - 1,
8923 free_extent_map(em);
8925 num_bytes -= ins.offset;
8926 cur_offset += ins.offset;
8927 *alloc_hint = ins.objectid + ins.offset;
8929 inode_inc_iversion(inode);
8930 inode->i_ctime = CURRENT_TIME;
8931 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8932 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8933 (actual_len > inode->i_size) &&
8934 (cur_offset > inode->i_size)) {
8935 if (cur_offset > actual_len)
8936 i_size = actual_len;
8938 i_size = cur_offset;
8939 i_size_write(inode, i_size);
8940 btrfs_ordered_update_i_size(inode, i_size, NULL);
8943 ret = btrfs_update_inode(trans, root, inode);
8946 btrfs_abort_transaction(trans, root, ret);
8948 btrfs_end_transaction(trans, root);
8953 btrfs_end_transaction(trans, root);
8958 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8959 u64 start, u64 num_bytes, u64 min_size,
8960 loff_t actual_len, u64 *alloc_hint)
8962 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8963 min_size, actual_len, alloc_hint,
8967 int btrfs_prealloc_file_range_trans(struct inode *inode,
8968 struct btrfs_trans_handle *trans, int mode,
8969 u64 start, u64 num_bytes, u64 min_size,
8970 loff_t actual_len, u64 *alloc_hint)
8972 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8973 min_size, actual_len, alloc_hint, trans);
8976 static int btrfs_set_page_dirty(struct page *page)
8978 return __set_page_dirty_nobuffers(page);
8981 static int btrfs_permission(struct inode *inode, int mask)
8983 struct btrfs_root *root = BTRFS_I(inode)->root;
8984 umode_t mode = inode->i_mode;
8986 if (mask & MAY_WRITE &&
8987 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8988 if (btrfs_root_readonly(root))
8990 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8993 return generic_permission(inode, mask);
8996 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
8998 struct btrfs_trans_handle *trans;
8999 struct btrfs_root *root = BTRFS_I(dir)->root;
9000 struct inode *inode = NULL;
9006 * 5 units required for adding orphan entry
9008 trans = btrfs_start_transaction(root, 5);
9010 return PTR_ERR(trans);
9012 ret = btrfs_find_free_ino(root, &objectid);
9016 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9017 btrfs_ino(dir), objectid, mode, &index);
9018 if (IS_ERR(inode)) {
9019 ret = PTR_ERR(inode);
9024 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9028 ret = btrfs_update_inode(trans, root, inode);
9032 inode->i_fop = &btrfs_file_operations;
9033 inode->i_op = &btrfs_file_inode_operations;
9035 inode->i_mapping->a_ops = &btrfs_aops;
9036 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
9037 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9039 ret = btrfs_orphan_add(trans, inode);
9044 * We set number of links to 0 in btrfs_new_inode(), and here we set
9045 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9048 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9050 set_nlink(inode, 1);
9051 d_tmpfile(dentry, inode);
9052 mark_inode_dirty(inode);
9055 btrfs_end_transaction(trans, root);
9058 btrfs_balance_delayed_items(root);
9059 btrfs_btree_balance_dirty(root);
9064 static const struct inode_operations btrfs_dir_inode_operations = {
9065 .getattr = btrfs_getattr,
9066 .lookup = btrfs_lookup,
9067 .create = btrfs_create,
9068 .unlink = btrfs_unlink,
9070 .mkdir = btrfs_mkdir,
9071 .rmdir = btrfs_rmdir,
9072 .rename2 = btrfs_rename2,
9073 .symlink = btrfs_symlink,
9074 .setattr = btrfs_setattr,
9075 .mknod = btrfs_mknod,
9076 .setxattr = btrfs_setxattr,
9077 .getxattr = btrfs_getxattr,
9078 .listxattr = btrfs_listxattr,
9079 .removexattr = btrfs_removexattr,
9080 .permission = btrfs_permission,
9081 .get_acl = btrfs_get_acl,
9082 .set_acl = btrfs_set_acl,
9083 .update_time = btrfs_update_time,
9084 .tmpfile = btrfs_tmpfile,
9086 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9087 .lookup = btrfs_lookup,
9088 .permission = btrfs_permission,
9089 .get_acl = btrfs_get_acl,
9090 .set_acl = btrfs_set_acl,
9091 .update_time = btrfs_update_time,
9094 static const struct file_operations btrfs_dir_file_operations = {
9095 .llseek = generic_file_llseek,
9096 .read = generic_read_dir,
9097 .iterate = btrfs_real_readdir,
9098 .unlocked_ioctl = btrfs_ioctl,
9099 #ifdef CONFIG_COMPAT
9100 .compat_ioctl = btrfs_ioctl,
9102 .release = btrfs_release_file,
9103 .fsync = btrfs_sync_file,
9106 static struct extent_io_ops btrfs_extent_io_ops = {
9107 .fill_delalloc = run_delalloc_range,
9108 .submit_bio_hook = btrfs_submit_bio_hook,
9109 .merge_bio_hook = btrfs_merge_bio_hook,
9110 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9111 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9112 .writepage_start_hook = btrfs_writepage_start_hook,
9113 .set_bit_hook = btrfs_set_bit_hook,
9114 .clear_bit_hook = btrfs_clear_bit_hook,
9115 .merge_extent_hook = btrfs_merge_extent_hook,
9116 .split_extent_hook = btrfs_split_extent_hook,
9120 * btrfs doesn't support the bmap operation because swapfiles
9121 * use bmap to make a mapping of extents in the file. They assume
9122 * these extents won't change over the life of the file and they
9123 * use the bmap result to do IO directly to the drive.
9125 * the btrfs bmap call would return logical addresses that aren't
9126 * suitable for IO and they also will change frequently as COW
9127 * operations happen. So, swapfile + btrfs == corruption.
9129 * For now we're avoiding this by dropping bmap.
9131 static const struct address_space_operations btrfs_aops = {
9132 .readpage = btrfs_readpage,
9133 .writepage = btrfs_writepage,
9134 .writepages = btrfs_writepages,
9135 .readpages = btrfs_readpages,
9136 .direct_IO = btrfs_direct_IO,
9137 .invalidatepage = btrfs_invalidatepage,
9138 .releasepage = btrfs_releasepage,
9139 .set_page_dirty = btrfs_set_page_dirty,
9140 .error_remove_page = generic_error_remove_page,
9143 static const struct address_space_operations btrfs_symlink_aops = {
9144 .readpage = btrfs_readpage,
9145 .writepage = btrfs_writepage,
9146 .invalidatepage = btrfs_invalidatepage,
9147 .releasepage = btrfs_releasepage,
9150 static const struct inode_operations btrfs_file_inode_operations = {
9151 .getattr = btrfs_getattr,
9152 .setattr = btrfs_setattr,
9153 .setxattr = btrfs_setxattr,
9154 .getxattr = btrfs_getxattr,
9155 .listxattr = btrfs_listxattr,
9156 .removexattr = btrfs_removexattr,
9157 .permission = btrfs_permission,
9158 .fiemap = btrfs_fiemap,
9159 .get_acl = btrfs_get_acl,
9160 .set_acl = btrfs_set_acl,
9161 .update_time = btrfs_update_time,
9163 static const struct inode_operations btrfs_special_inode_operations = {
9164 .getattr = btrfs_getattr,
9165 .setattr = btrfs_setattr,
9166 .permission = btrfs_permission,
9167 .setxattr = btrfs_setxattr,
9168 .getxattr = btrfs_getxattr,
9169 .listxattr = btrfs_listxattr,
9170 .removexattr = btrfs_removexattr,
9171 .get_acl = btrfs_get_acl,
9172 .set_acl = btrfs_set_acl,
9173 .update_time = btrfs_update_time,
9175 static const struct inode_operations btrfs_symlink_inode_operations = {
9176 .readlink = generic_readlink,
9177 .follow_link = page_follow_link_light,
9178 .put_link = page_put_link,
9179 .getattr = btrfs_getattr,
9180 .setattr = btrfs_setattr,
9181 .permission = btrfs_permission,
9182 .setxattr = btrfs_setxattr,
9183 .getxattr = btrfs_getxattr,
9184 .listxattr = btrfs_listxattr,
9185 .removexattr = btrfs_removexattr,
9186 .update_time = btrfs_update_time,
9189 const struct dentry_operations btrfs_dentry_operations = {
9190 .d_delete = btrfs_dentry_delete,
9191 .d_release = btrfs_dentry_release,