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 noinline 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);
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);
718 * here we're doing allocation and writeback of the
721 btrfs_drop_extent_cache(inode, async_extent->start,
722 async_extent->start +
723 async_extent->ram_size - 1, 0);
725 em = alloc_extent_map();
728 goto out_free_reserve;
730 em->start = async_extent->start;
731 em->len = async_extent->ram_size;
732 em->orig_start = em->start;
733 em->mod_start = em->start;
734 em->mod_len = em->len;
736 em->block_start = ins.objectid;
737 em->block_len = ins.offset;
738 em->orig_block_len = ins.offset;
739 em->ram_bytes = async_extent->ram_size;
740 em->bdev = root->fs_info->fs_devices->latest_bdev;
741 em->compress_type = async_extent->compress_type;
742 set_bit(EXTENT_FLAG_PINNED, &em->flags);
743 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
747 write_lock(&em_tree->lock);
748 ret = add_extent_mapping(em_tree, em, 1);
749 write_unlock(&em_tree->lock);
750 if (ret != -EEXIST) {
754 btrfs_drop_extent_cache(inode, async_extent->start,
755 async_extent->start +
756 async_extent->ram_size - 1, 0);
760 goto out_free_reserve;
762 ret = btrfs_add_ordered_extent_compress(inode,
765 async_extent->ram_size,
767 BTRFS_ORDERED_COMPRESSED,
768 async_extent->compress_type);
770 goto out_free_reserve;
773 * clear dirty, set writeback and unlock the pages.
775 extent_clear_unlock_delalloc(inode, async_extent->start,
776 async_extent->start +
777 async_extent->ram_size - 1,
778 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
779 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
781 ret = btrfs_submit_compressed_write(inode,
783 async_extent->ram_size,
785 ins.offset, async_extent->pages,
786 async_extent->nr_pages);
787 alloc_hint = ins.objectid + ins.offset;
797 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
799 extent_clear_unlock_delalloc(inode, async_extent->start,
800 async_extent->start +
801 async_extent->ram_size - 1,
802 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
803 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
804 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
805 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
810 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
813 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
814 struct extent_map *em;
817 read_lock(&em_tree->lock);
818 em = search_extent_mapping(em_tree, start, num_bytes);
821 * if block start isn't an actual block number then find the
822 * first block in this inode and use that as a hint. If that
823 * block is also bogus then just don't worry about it.
825 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
827 em = search_extent_mapping(em_tree, 0, 0);
828 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
829 alloc_hint = em->block_start;
833 alloc_hint = em->block_start;
837 read_unlock(&em_tree->lock);
843 * when extent_io.c finds a delayed allocation range in the file,
844 * the call backs end up in this code. The basic idea is to
845 * allocate extents on disk for the range, and create ordered data structs
846 * in ram to track those extents.
848 * locked_page is the page that writepage had locked already. We use
849 * it to make sure we don't do extra locks or unlocks.
851 * *page_started is set to one if we unlock locked_page and do everything
852 * required to start IO on it. It may be clean and already done with
855 static noinline int cow_file_range(struct inode *inode,
856 struct page *locked_page,
857 u64 start, u64 end, int *page_started,
858 unsigned long *nr_written,
861 struct btrfs_root *root = BTRFS_I(inode)->root;
864 unsigned long ram_size;
867 u64 blocksize = root->sectorsize;
868 struct btrfs_key ins;
869 struct extent_map *em;
870 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
873 if (btrfs_is_free_space_inode(inode)) {
879 num_bytes = ALIGN(end - start + 1, blocksize);
880 num_bytes = max(blocksize, num_bytes);
881 disk_num_bytes = num_bytes;
883 /* if this is a small write inside eof, kick off defrag */
884 if (num_bytes < 64 * 1024 &&
885 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
886 btrfs_add_inode_defrag(NULL, inode);
889 /* lets try to make an inline extent */
890 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
893 extent_clear_unlock_delalloc(inode, start, end, NULL,
894 EXTENT_LOCKED | EXTENT_DELALLOC |
895 EXTENT_DEFRAG, PAGE_UNLOCK |
896 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
899 *nr_written = *nr_written +
900 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
903 } else if (ret < 0) {
908 BUG_ON(disk_num_bytes >
909 btrfs_super_total_bytes(root->fs_info->super_copy));
911 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
912 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
914 while (disk_num_bytes > 0) {
917 cur_alloc_size = disk_num_bytes;
918 ret = btrfs_reserve_extent(root, cur_alloc_size,
919 root->sectorsize, 0, alloc_hint,
924 em = alloc_extent_map();
930 em->orig_start = em->start;
931 ram_size = ins.offset;
932 em->len = ins.offset;
933 em->mod_start = em->start;
934 em->mod_len = em->len;
936 em->block_start = ins.objectid;
937 em->block_len = ins.offset;
938 em->orig_block_len = ins.offset;
939 em->ram_bytes = ram_size;
940 em->bdev = root->fs_info->fs_devices->latest_bdev;
941 set_bit(EXTENT_FLAG_PINNED, &em->flags);
945 write_lock(&em_tree->lock);
946 ret = add_extent_mapping(em_tree, em, 1);
947 write_unlock(&em_tree->lock);
948 if (ret != -EEXIST) {
952 btrfs_drop_extent_cache(inode, start,
953 start + ram_size - 1, 0);
958 cur_alloc_size = ins.offset;
959 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
960 ram_size, cur_alloc_size, 0);
964 if (root->root_key.objectid ==
965 BTRFS_DATA_RELOC_TREE_OBJECTID) {
966 ret = btrfs_reloc_clone_csums(inode, start,
972 if (disk_num_bytes < cur_alloc_size)
975 /* we're not doing compressed IO, don't unlock the first
976 * page (which the caller expects to stay locked), don't
977 * clear any dirty bits and don't set any writeback bits
979 * Do set the Private2 bit so we know this page was properly
980 * setup for writepage
982 op = unlock ? PAGE_UNLOCK : 0;
983 op |= PAGE_SET_PRIVATE2;
985 extent_clear_unlock_delalloc(inode, start,
986 start + ram_size - 1, locked_page,
987 EXTENT_LOCKED | EXTENT_DELALLOC,
989 disk_num_bytes -= cur_alloc_size;
990 num_bytes -= cur_alloc_size;
991 alloc_hint = ins.objectid + ins.offset;
992 start += cur_alloc_size;
998 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1000 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1001 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1002 EXTENT_DELALLOC | EXTENT_DEFRAG,
1003 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1004 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1009 * work queue call back to started compression on a file and pages
1011 static noinline void async_cow_start(struct btrfs_work *work)
1013 struct async_cow *async_cow;
1015 async_cow = container_of(work, struct async_cow, work);
1017 compress_file_range(async_cow->inode, async_cow->locked_page,
1018 async_cow->start, async_cow->end, async_cow,
1020 if (num_added == 0) {
1021 btrfs_add_delayed_iput(async_cow->inode);
1022 async_cow->inode = NULL;
1027 * work queue call back to submit previously compressed pages
1029 static noinline void async_cow_submit(struct btrfs_work *work)
1031 struct async_cow *async_cow;
1032 struct btrfs_root *root;
1033 unsigned long nr_pages;
1035 async_cow = container_of(work, struct async_cow, work);
1037 root = async_cow->root;
1038 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1041 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1043 waitqueue_active(&root->fs_info->async_submit_wait))
1044 wake_up(&root->fs_info->async_submit_wait);
1046 if (async_cow->inode)
1047 submit_compressed_extents(async_cow->inode, async_cow);
1050 static noinline void async_cow_free(struct btrfs_work *work)
1052 struct async_cow *async_cow;
1053 async_cow = container_of(work, struct async_cow, work);
1054 if (async_cow->inode)
1055 btrfs_add_delayed_iput(async_cow->inode);
1059 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1060 u64 start, u64 end, int *page_started,
1061 unsigned long *nr_written)
1063 struct async_cow *async_cow;
1064 struct btrfs_root *root = BTRFS_I(inode)->root;
1065 unsigned long nr_pages;
1067 int limit = 10 * 1024 * 1024;
1069 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1070 1, 0, NULL, GFP_NOFS);
1071 while (start < end) {
1072 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1073 BUG_ON(!async_cow); /* -ENOMEM */
1074 async_cow->inode = igrab(inode);
1075 async_cow->root = root;
1076 async_cow->locked_page = locked_page;
1077 async_cow->start = start;
1079 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1082 cur_end = min(end, start + 512 * 1024 - 1);
1084 async_cow->end = cur_end;
1085 INIT_LIST_HEAD(&async_cow->extents);
1087 btrfs_init_work(&async_cow->work, async_cow_start,
1088 async_cow_submit, async_cow_free);
1090 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1092 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1094 btrfs_queue_work(root->fs_info->delalloc_workers,
1097 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1098 wait_event(root->fs_info->async_submit_wait,
1099 (atomic_read(&root->fs_info->async_delalloc_pages) <
1103 while (atomic_read(&root->fs_info->async_submit_draining) &&
1104 atomic_read(&root->fs_info->async_delalloc_pages)) {
1105 wait_event(root->fs_info->async_submit_wait,
1106 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1110 *nr_written += nr_pages;
1111 start = cur_end + 1;
1117 static noinline int csum_exist_in_range(struct btrfs_root *root,
1118 u64 bytenr, u64 num_bytes)
1121 struct btrfs_ordered_sum *sums;
1124 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1125 bytenr + num_bytes - 1, &list, 0);
1126 if (ret == 0 && list_empty(&list))
1129 while (!list_empty(&list)) {
1130 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1131 list_del(&sums->list);
1138 * when nowcow writeback call back. This checks for snapshots or COW copies
1139 * of the extents that exist in the file, and COWs the file as required.
1141 * If no cow copies or snapshots exist, we write directly to the existing
1144 static noinline int run_delalloc_nocow(struct inode *inode,
1145 struct page *locked_page,
1146 u64 start, u64 end, int *page_started, int force,
1147 unsigned long *nr_written)
1149 struct btrfs_root *root = BTRFS_I(inode)->root;
1150 struct btrfs_trans_handle *trans;
1151 struct extent_buffer *leaf;
1152 struct btrfs_path *path;
1153 struct btrfs_file_extent_item *fi;
1154 struct btrfs_key found_key;
1169 u64 ino = btrfs_ino(inode);
1171 path = btrfs_alloc_path();
1173 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1174 EXTENT_LOCKED | EXTENT_DELALLOC |
1175 EXTENT_DO_ACCOUNTING |
1176 EXTENT_DEFRAG, PAGE_UNLOCK |
1178 PAGE_SET_WRITEBACK |
1179 PAGE_END_WRITEBACK);
1183 nolock = btrfs_is_free_space_inode(inode);
1186 trans = btrfs_join_transaction_nolock(root);
1188 trans = btrfs_join_transaction(root);
1190 if (IS_ERR(trans)) {
1191 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1192 EXTENT_LOCKED | EXTENT_DELALLOC |
1193 EXTENT_DO_ACCOUNTING |
1194 EXTENT_DEFRAG, PAGE_UNLOCK |
1196 PAGE_SET_WRITEBACK |
1197 PAGE_END_WRITEBACK);
1198 btrfs_free_path(path);
1199 return PTR_ERR(trans);
1202 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1204 cow_start = (u64)-1;
1207 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1211 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1212 leaf = path->nodes[0];
1213 btrfs_item_key_to_cpu(leaf, &found_key,
1214 path->slots[0] - 1);
1215 if (found_key.objectid == ino &&
1216 found_key.type == BTRFS_EXTENT_DATA_KEY)
1221 leaf = path->nodes[0];
1222 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1223 ret = btrfs_next_leaf(root, path);
1228 leaf = path->nodes[0];
1234 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1236 if (found_key.objectid > ino ||
1237 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1238 found_key.offset > end)
1241 if (found_key.offset > cur_offset) {
1242 extent_end = found_key.offset;
1247 fi = btrfs_item_ptr(leaf, path->slots[0],
1248 struct btrfs_file_extent_item);
1249 extent_type = btrfs_file_extent_type(leaf, fi);
1251 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1252 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1253 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1254 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1255 extent_offset = btrfs_file_extent_offset(leaf, fi);
1256 extent_end = found_key.offset +
1257 btrfs_file_extent_num_bytes(leaf, fi);
1259 btrfs_file_extent_disk_num_bytes(leaf, fi);
1260 if (extent_end <= start) {
1264 if (disk_bytenr == 0)
1266 if (btrfs_file_extent_compression(leaf, fi) ||
1267 btrfs_file_extent_encryption(leaf, fi) ||
1268 btrfs_file_extent_other_encoding(leaf, fi))
1270 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1272 if (btrfs_extent_readonly(root, disk_bytenr))
1274 if (btrfs_cross_ref_exist(trans, root, ino,
1276 extent_offset, disk_bytenr))
1278 disk_bytenr += extent_offset;
1279 disk_bytenr += cur_offset - found_key.offset;
1280 num_bytes = min(end + 1, extent_end) - cur_offset;
1282 * if there are pending snapshots for this root,
1283 * we fall into common COW way.
1286 err = btrfs_start_nocow_write(root);
1291 * force cow if csum exists in the range.
1292 * this ensure that csum for a given extent are
1293 * either valid or do not exist.
1295 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1298 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1299 extent_end = found_key.offset +
1300 btrfs_file_extent_inline_len(leaf,
1301 path->slots[0], fi);
1302 extent_end = ALIGN(extent_end, root->sectorsize);
1307 if (extent_end <= start) {
1309 if (!nolock && nocow)
1310 btrfs_end_nocow_write(root);
1314 if (cow_start == (u64)-1)
1315 cow_start = cur_offset;
1316 cur_offset = extent_end;
1317 if (cur_offset > end)
1323 btrfs_release_path(path);
1324 if (cow_start != (u64)-1) {
1325 ret = cow_file_range(inode, locked_page,
1326 cow_start, found_key.offset - 1,
1327 page_started, nr_written, 1);
1329 if (!nolock && nocow)
1330 btrfs_end_nocow_write(root);
1333 cow_start = (u64)-1;
1336 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1337 struct extent_map *em;
1338 struct extent_map_tree *em_tree;
1339 em_tree = &BTRFS_I(inode)->extent_tree;
1340 em = alloc_extent_map();
1341 BUG_ON(!em); /* -ENOMEM */
1342 em->start = cur_offset;
1343 em->orig_start = found_key.offset - extent_offset;
1344 em->len = num_bytes;
1345 em->block_len = num_bytes;
1346 em->block_start = disk_bytenr;
1347 em->orig_block_len = disk_num_bytes;
1348 em->ram_bytes = ram_bytes;
1349 em->bdev = root->fs_info->fs_devices->latest_bdev;
1350 em->mod_start = em->start;
1351 em->mod_len = em->len;
1352 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1353 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1354 em->generation = -1;
1356 write_lock(&em_tree->lock);
1357 ret = add_extent_mapping(em_tree, em, 1);
1358 write_unlock(&em_tree->lock);
1359 if (ret != -EEXIST) {
1360 free_extent_map(em);
1363 btrfs_drop_extent_cache(inode, em->start,
1364 em->start + em->len - 1, 0);
1366 type = BTRFS_ORDERED_PREALLOC;
1368 type = BTRFS_ORDERED_NOCOW;
1371 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1372 num_bytes, num_bytes, type);
1373 BUG_ON(ret); /* -ENOMEM */
1375 if (root->root_key.objectid ==
1376 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1377 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1380 if (!nolock && nocow)
1381 btrfs_end_nocow_write(root);
1386 extent_clear_unlock_delalloc(inode, cur_offset,
1387 cur_offset + num_bytes - 1,
1388 locked_page, EXTENT_LOCKED |
1389 EXTENT_DELALLOC, PAGE_UNLOCK |
1391 if (!nolock && nocow)
1392 btrfs_end_nocow_write(root);
1393 cur_offset = extent_end;
1394 if (cur_offset > end)
1397 btrfs_release_path(path);
1399 if (cur_offset <= end && cow_start == (u64)-1) {
1400 cow_start = cur_offset;
1404 if (cow_start != (u64)-1) {
1405 ret = cow_file_range(inode, locked_page, cow_start, end,
1406 page_started, nr_written, 1);
1412 err = btrfs_end_transaction(trans, root);
1416 if (ret && cur_offset < end)
1417 extent_clear_unlock_delalloc(inode, cur_offset, end,
1418 locked_page, EXTENT_LOCKED |
1419 EXTENT_DELALLOC | EXTENT_DEFRAG |
1420 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1422 PAGE_SET_WRITEBACK |
1423 PAGE_END_WRITEBACK);
1424 btrfs_free_path(path);
1429 * extent_io.c call back to do delayed allocation processing
1431 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1432 u64 start, u64 end, int *page_started,
1433 unsigned long *nr_written)
1436 struct btrfs_root *root = BTRFS_I(inode)->root;
1438 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1439 ret = run_delalloc_nocow(inode, locked_page, start, end,
1440 page_started, 1, nr_written);
1441 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1442 ret = run_delalloc_nocow(inode, locked_page, start, end,
1443 page_started, 0, nr_written);
1444 } else if (!btrfs_test_opt(root, COMPRESS) &&
1445 !(BTRFS_I(inode)->force_compress) &&
1446 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1447 ret = cow_file_range(inode, locked_page, start, end,
1448 page_started, nr_written, 1);
1450 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1451 &BTRFS_I(inode)->runtime_flags);
1452 ret = cow_file_range_async(inode, locked_page, start, end,
1453 page_started, nr_written);
1458 static void btrfs_split_extent_hook(struct inode *inode,
1459 struct extent_state *orig, u64 split)
1461 /* not delalloc, ignore it */
1462 if (!(orig->state & EXTENT_DELALLOC))
1465 spin_lock(&BTRFS_I(inode)->lock);
1466 BTRFS_I(inode)->outstanding_extents++;
1467 spin_unlock(&BTRFS_I(inode)->lock);
1471 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1472 * extents so we can keep track of new extents that are just merged onto old
1473 * extents, such as when we are doing sequential writes, so we can properly
1474 * account for the metadata space we'll need.
1476 static void btrfs_merge_extent_hook(struct inode *inode,
1477 struct extent_state *new,
1478 struct extent_state *other)
1480 /* not delalloc, ignore it */
1481 if (!(other->state & EXTENT_DELALLOC))
1484 spin_lock(&BTRFS_I(inode)->lock);
1485 BTRFS_I(inode)->outstanding_extents--;
1486 spin_unlock(&BTRFS_I(inode)->lock);
1489 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1490 struct inode *inode)
1492 spin_lock(&root->delalloc_lock);
1493 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1494 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1495 &root->delalloc_inodes);
1496 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1497 &BTRFS_I(inode)->runtime_flags);
1498 root->nr_delalloc_inodes++;
1499 if (root->nr_delalloc_inodes == 1) {
1500 spin_lock(&root->fs_info->delalloc_root_lock);
1501 BUG_ON(!list_empty(&root->delalloc_root));
1502 list_add_tail(&root->delalloc_root,
1503 &root->fs_info->delalloc_roots);
1504 spin_unlock(&root->fs_info->delalloc_root_lock);
1507 spin_unlock(&root->delalloc_lock);
1510 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1511 struct inode *inode)
1513 spin_lock(&root->delalloc_lock);
1514 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1515 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1516 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1517 &BTRFS_I(inode)->runtime_flags);
1518 root->nr_delalloc_inodes--;
1519 if (!root->nr_delalloc_inodes) {
1520 spin_lock(&root->fs_info->delalloc_root_lock);
1521 BUG_ON(list_empty(&root->delalloc_root));
1522 list_del_init(&root->delalloc_root);
1523 spin_unlock(&root->fs_info->delalloc_root_lock);
1526 spin_unlock(&root->delalloc_lock);
1530 * extent_io.c set_bit_hook, used to track delayed allocation
1531 * bytes in this file, and to maintain the list of inodes that
1532 * have pending delalloc work to be done.
1534 static void btrfs_set_bit_hook(struct inode *inode,
1535 struct extent_state *state, unsigned long *bits)
1539 * set_bit and clear bit hooks normally require _irqsave/restore
1540 * but in this case, we are only testing for the DELALLOC
1541 * bit, which is only set or cleared with irqs on
1543 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1544 struct btrfs_root *root = BTRFS_I(inode)->root;
1545 u64 len = state->end + 1 - state->start;
1546 bool do_list = !btrfs_is_free_space_inode(inode);
1548 if (*bits & EXTENT_FIRST_DELALLOC) {
1549 *bits &= ~EXTENT_FIRST_DELALLOC;
1551 spin_lock(&BTRFS_I(inode)->lock);
1552 BTRFS_I(inode)->outstanding_extents++;
1553 spin_unlock(&BTRFS_I(inode)->lock);
1556 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1557 root->fs_info->delalloc_batch);
1558 spin_lock(&BTRFS_I(inode)->lock);
1559 BTRFS_I(inode)->delalloc_bytes += len;
1560 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1561 &BTRFS_I(inode)->runtime_flags))
1562 btrfs_add_delalloc_inodes(root, inode);
1563 spin_unlock(&BTRFS_I(inode)->lock);
1568 * extent_io.c clear_bit_hook, see set_bit_hook for why
1570 static void btrfs_clear_bit_hook(struct inode *inode,
1571 struct extent_state *state,
1572 unsigned long *bits)
1575 * set_bit and clear bit hooks normally require _irqsave/restore
1576 * but in this case, we are only testing for the DELALLOC
1577 * bit, which is only set or cleared with irqs on
1579 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1580 struct btrfs_root *root = BTRFS_I(inode)->root;
1581 u64 len = state->end + 1 - state->start;
1582 bool do_list = !btrfs_is_free_space_inode(inode);
1584 if (*bits & EXTENT_FIRST_DELALLOC) {
1585 *bits &= ~EXTENT_FIRST_DELALLOC;
1586 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1587 spin_lock(&BTRFS_I(inode)->lock);
1588 BTRFS_I(inode)->outstanding_extents--;
1589 spin_unlock(&BTRFS_I(inode)->lock);
1593 * We don't reserve metadata space for space cache inodes so we
1594 * don't need to call dellalloc_release_metadata if there is an
1597 if (*bits & EXTENT_DO_ACCOUNTING &&
1598 root != root->fs_info->tree_root)
1599 btrfs_delalloc_release_metadata(inode, len);
1601 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1602 && do_list && !(state->state & EXTENT_NORESERVE))
1603 btrfs_free_reserved_data_space(inode, len);
1605 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1606 root->fs_info->delalloc_batch);
1607 spin_lock(&BTRFS_I(inode)->lock);
1608 BTRFS_I(inode)->delalloc_bytes -= len;
1609 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1610 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1611 &BTRFS_I(inode)->runtime_flags))
1612 btrfs_del_delalloc_inode(root, inode);
1613 spin_unlock(&BTRFS_I(inode)->lock);
1618 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1619 * we don't create bios that span stripes or chunks
1621 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1622 size_t size, struct bio *bio,
1623 unsigned long bio_flags)
1625 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1626 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1631 if (bio_flags & EXTENT_BIO_COMPRESSED)
1634 length = bio->bi_iter.bi_size;
1635 map_length = length;
1636 ret = btrfs_map_block(root->fs_info, rw, logical,
1637 &map_length, NULL, 0);
1638 /* Will always return 0 with map_multi == NULL */
1640 if (map_length < length + size)
1646 * in order to insert checksums into the metadata in large chunks,
1647 * we wait until bio submission time. All the pages in the bio are
1648 * checksummed and sums are attached onto the ordered extent record.
1650 * At IO completion time the cums attached on the ordered extent record
1651 * are inserted into the btree
1653 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1654 struct bio *bio, int mirror_num,
1655 unsigned long bio_flags,
1658 struct btrfs_root *root = BTRFS_I(inode)->root;
1661 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1662 BUG_ON(ret); /* -ENOMEM */
1667 * in order to insert checksums into the metadata in large chunks,
1668 * we wait until bio submission time. All the pages in the bio are
1669 * checksummed and sums are attached onto the ordered extent record.
1671 * At IO completion time the cums attached on the ordered extent record
1672 * are inserted into the btree
1674 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1675 int mirror_num, unsigned long bio_flags,
1678 struct btrfs_root *root = BTRFS_I(inode)->root;
1681 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1683 bio_endio(bio, ret);
1688 * extent_io.c submission hook. This does the right thing for csum calculation
1689 * on write, or reading the csums from the tree before a read
1691 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1692 int mirror_num, unsigned long bio_flags,
1695 struct btrfs_root *root = BTRFS_I(inode)->root;
1699 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1701 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1703 if (btrfs_is_free_space_inode(inode))
1706 if (!(rw & REQ_WRITE)) {
1707 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1711 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1712 ret = btrfs_submit_compressed_read(inode, bio,
1716 } else if (!skip_sum) {
1717 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1722 } else if (async && !skip_sum) {
1723 /* csum items have already been cloned */
1724 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1726 /* we're doing a write, do the async checksumming */
1727 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1728 inode, rw, bio, mirror_num,
1729 bio_flags, bio_offset,
1730 __btrfs_submit_bio_start,
1731 __btrfs_submit_bio_done);
1733 } else if (!skip_sum) {
1734 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1740 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1744 bio_endio(bio, ret);
1749 * given a list of ordered sums record them in the inode. This happens
1750 * at IO completion time based on sums calculated at bio submission time.
1752 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1753 struct inode *inode, u64 file_offset,
1754 struct list_head *list)
1756 struct btrfs_ordered_sum *sum;
1758 list_for_each_entry(sum, list, list) {
1759 trans->adding_csums = 1;
1760 btrfs_csum_file_blocks(trans,
1761 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1762 trans->adding_csums = 0;
1767 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1768 struct extent_state **cached_state)
1770 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1771 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1772 cached_state, GFP_NOFS);
1775 /* see btrfs_writepage_start_hook for details on why this is required */
1776 struct btrfs_writepage_fixup {
1778 struct btrfs_work work;
1781 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1783 struct btrfs_writepage_fixup *fixup;
1784 struct btrfs_ordered_extent *ordered;
1785 struct extent_state *cached_state = NULL;
1787 struct inode *inode;
1792 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1796 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1797 ClearPageChecked(page);
1801 inode = page->mapping->host;
1802 page_start = page_offset(page);
1803 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1805 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1808 /* already ordered? We're done */
1809 if (PagePrivate2(page))
1812 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1814 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1815 page_end, &cached_state, GFP_NOFS);
1817 btrfs_start_ordered_extent(inode, ordered, 1);
1818 btrfs_put_ordered_extent(ordered);
1822 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1824 mapping_set_error(page->mapping, ret);
1825 end_extent_writepage(page, ret, page_start, page_end);
1826 ClearPageChecked(page);
1830 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1831 ClearPageChecked(page);
1832 set_page_dirty(page);
1834 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1835 &cached_state, GFP_NOFS);
1838 page_cache_release(page);
1843 * There are a few paths in the higher layers of the kernel that directly
1844 * set the page dirty bit without asking the filesystem if it is a
1845 * good idea. This causes problems because we want to make sure COW
1846 * properly happens and the data=ordered rules are followed.
1848 * In our case any range that doesn't have the ORDERED bit set
1849 * hasn't been properly setup for IO. We kick off an async process
1850 * to fix it up. The async helper will wait for ordered extents, set
1851 * the delalloc bit and make it safe to write the page.
1853 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1855 struct inode *inode = page->mapping->host;
1856 struct btrfs_writepage_fixup *fixup;
1857 struct btrfs_root *root = BTRFS_I(inode)->root;
1859 /* this page is properly in the ordered list */
1860 if (TestClearPagePrivate2(page))
1863 if (PageChecked(page))
1866 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1870 SetPageChecked(page);
1871 page_cache_get(page);
1872 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
1874 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
1878 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1879 struct inode *inode, u64 file_pos,
1880 u64 disk_bytenr, u64 disk_num_bytes,
1881 u64 num_bytes, u64 ram_bytes,
1882 u8 compression, u8 encryption,
1883 u16 other_encoding, int extent_type)
1885 struct btrfs_root *root = BTRFS_I(inode)->root;
1886 struct btrfs_file_extent_item *fi;
1887 struct btrfs_path *path;
1888 struct extent_buffer *leaf;
1889 struct btrfs_key ins;
1890 int extent_inserted = 0;
1893 path = btrfs_alloc_path();
1898 * we may be replacing one extent in the tree with another.
1899 * The new extent is pinned in the extent map, and we don't want
1900 * to drop it from the cache until it is completely in the btree.
1902 * So, tell btrfs_drop_extents to leave this extent in the cache.
1903 * the caller is expected to unpin it and allow it to be merged
1906 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
1907 file_pos + num_bytes, NULL, 0,
1908 1, sizeof(*fi), &extent_inserted);
1912 if (!extent_inserted) {
1913 ins.objectid = btrfs_ino(inode);
1914 ins.offset = file_pos;
1915 ins.type = BTRFS_EXTENT_DATA_KEY;
1917 path->leave_spinning = 1;
1918 ret = btrfs_insert_empty_item(trans, root, path, &ins,
1923 leaf = path->nodes[0];
1924 fi = btrfs_item_ptr(leaf, path->slots[0],
1925 struct btrfs_file_extent_item);
1926 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1927 btrfs_set_file_extent_type(leaf, fi, extent_type);
1928 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1929 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1930 btrfs_set_file_extent_offset(leaf, fi, 0);
1931 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1932 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1933 btrfs_set_file_extent_compression(leaf, fi, compression);
1934 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1935 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1937 btrfs_mark_buffer_dirty(leaf);
1938 btrfs_release_path(path);
1940 inode_add_bytes(inode, num_bytes);
1942 ins.objectid = disk_bytenr;
1943 ins.offset = disk_num_bytes;
1944 ins.type = BTRFS_EXTENT_ITEM_KEY;
1945 ret = btrfs_alloc_reserved_file_extent(trans, root,
1946 root->root_key.objectid,
1947 btrfs_ino(inode), file_pos, &ins);
1949 btrfs_free_path(path);
1954 /* snapshot-aware defrag */
1955 struct sa_defrag_extent_backref {
1956 struct rb_node node;
1957 struct old_sa_defrag_extent *old;
1966 struct old_sa_defrag_extent {
1967 struct list_head list;
1968 struct new_sa_defrag_extent *new;
1977 struct new_sa_defrag_extent {
1978 struct rb_root root;
1979 struct list_head head;
1980 struct btrfs_path *path;
1981 struct inode *inode;
1989 static int backref_comp(struct sa_defrag_extent_backref *b1,
1990 struct sa_defrag_extent_backref *b2)
1992 if (b1->root_id < b2->root_id)
1994 else if (b1->root_id > b2->root_id)
1997 if (b1->inum < b2->inum)
1999 else if (b1->inum > b2->inum)
2002 if (b1->file_pos < b2->file_pos)
2004 else if (b1->file_pos > b2->file_pos)
2008 * [------------------------------] ===> (a range of space)
2009 * |<--->| |<---->| =============> (fs/file tree A)
2010 * |<---------------------------->| ===> (fs/file tree B)
2012 * A range of space can refer to two file extents in one tree while
2013 * refer to only one file extent in another tree.
2015 * So we may process a disk offset more than one time(two extents in A)
2016 * and locate at the same extent(one extent in B), then insert two same
2017 * backrefs(both refer to the extent in B).
2022 static void backref_insert(struct rb_root *root,
2023 struct sa_defrag_extent_backref *backref)
2025 struct rb_node **p = &root->rb_node;
2026 struct rb_node *parent = NULL;
2027 struct sa_defrag_extent_backref *entry;
2032 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2034 ret = backref_comp(backref, entry);
2038 p = &(*p)->rb_right;
2041 rb_link_node(&backref->node, parent, p);
2042 rb_insert_color(&backref->node, root);
2046 * Note the backref might has changed, and in this case we just return 0.
2048 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2051 struct btrfs_file_extent_item *extent;
2052 struct btrfs_fs_info *fs_info;
2053 struct old_sa_defrag_extent *old = ctx;
2054 struct new_sa_defrag_extent *new = old->new;
2055 struct btrfs_path *path = new->path;
2056 struct btrfs_key key;
2057 struct btrfs_root *root;
2058 struct sa_defrag_extent_backref *backref;
2059 struct extent_buffer *leaf;
2060 struct inode *inode = new->inode;
2066 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2067 inum == btrfs_ino(inode))
2070 key.objectid = root_id;
2071 key.type = BTRFS_ROOT_ITEM_KEY;
2072 key.offset = (u64)-1;
2074 fs_info = BTRFS_I(inode)->root->fs_info;
2075 root = btrfs_read_fs_root_no_name(fs_info, &key);
2077 if (PTR_ERR(root) == -ENOENT)
2080 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2081 inum, offset, root_id);
2082 return PTR_ERR(root);
2085 key.objectid = inum;
2086 key.type = BTRFS_EXTENT_DATA_KEY;
2087 if (offset > (u64)-1 << 32)
2090 key.offset = offset;
2092 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2093 if (WARN_ON(ret < 0))
2100 leaf = path->nodes[0];
2101 slot = path->slots[0];
2103 if (slot >= btrfs_header_nritems(leaf)) {
2104 ret = btrfs_next_leaf(root, path);
2107 } else if (ret > 0) {
2116 btrfs_item_key_to_cpu(leaf, &key, slot);
2118 if (key.objectid > inum)
2121 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2124 extent = btrfs_item_ptr(leaf, slot,
2125 struct btrfs_file_extent_item);
2127 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2131 * 'offset' refers to the exact key.offset,
2132 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2133 * (key.offset - extent_offset).
2135 if (key.offset != offset)
2138 extent_offset = btrfs_file_extent_offset(leaf, extent);
2139 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2141 if (extent_offset >= old->extent_offset + old->offset +
2142 old->len || extent_offset + num_bytes <=
2143 old->extent_offset + old->offset)
2148 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2154 backref->root_id = root_id;
2155 backref->inum = inum;
2156 backref->file_pos = offset;
2157 backref->num_bytes = num_bytes;
2158 backref->extent_offset = extent_offset;
2159 backref->generation = btrfs_file_extent_generation(leaf, extent);
2161 backref_insert(&new->root, backref);
2164 btrfs_release_path(path);
2169 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2170 struct new_sa_defrag_extent *new)
2172 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2173 struct old_sa_defrag_extent *old, *tmp;
2178 list_for_each_entry_safe(old, tmp, &new->head, list) {
2179 ret = iterate_inodes_from_logical(old->bytenr +
2180 old->extent_offset, fs_info,
2181 path, record_one_backref,
2183 if (ret < 0 && ret != -ENOENT)
2186 /* no backref to be processed for this extent */
2188 list_del(&old->list);
2193 if (list_empty(&new->head))
2199 static int relink_is_mergable(struct extent_buffer *leaf,
2200 struct btrfs_file_extent_item *fi,
2201 struct new_sa_defrag_extent *new)
2203 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2206 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2209 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2212 if (btrfs_file_extent_encryption(leaf, fi) ||
2213 btrfs_file_extent_other_encoding(leaf, fi))
2220 * Note the backref might has changed, and in this case we just return 0.
2222 static noinline int relink_extent_backref(struct btrfs_path *path,
2223 struct sa_defrag_extent_backref *prev,
2224 struct sa_defrag_extent_backref *backref)
2226 struct btrfs_file_extent_item *extent;
2227 struct btrfs_file_extent_item *item;
2228 struct btrfs_ordered_extent *ordered;
2229 struct btrfs_trans_handle *trans;
2230 struct btrfs_fs_info *fs_info;
2231 struct btrfs_root *root;
2232 struct btrfs_key key;
2233 struct extent_buffer *leaf;
2234 struct old_sa_defrag_extent *old = backref->old;
2235 struct new_sa_defrag_extent *new = old->new;
2236 struct inode *src_inode = new->inode;
2237 struct inode *inode;
2238 struct extent_state *cached = NULL;
2247 if (prev && prev->root_id == backref->root_id &&
2248 prev->inum == backref->inum &&
2249 prev->file_pos + prev->num_bytes == backref->file_pos)
2252 /* step 1: get root */
2253 key.objectid = backref->root_id;
2254 key.type = BTRFS_ROOT_ITEM_KEY;
2255 key.offset = (u64)-1;
2257 fs_info = BTRFS_I(src_inode)->root->fs_info;
2258 index = srcu_read_lock(&fs_info->subvol_srcu);
2260 root = btrfs_read_fs_root_no_name(fs_info, &key);
2262 srcu_read_unlock(&fs_info->subvol_srcu, index);
2263 if (PTR_ERR(root) == -ENOENT)
2265 return PTR_ERR(root);
2268 if (btrfs_root_readonly(root)) {
2269 srcu_read_unlock(&fs_info->subvol_srcu, index);
2273 /* step 2: get inode */
2274 key.objectid = backref->inum;
2275 key.type = BTRFS_INODE_ITEM_KEY;
2278 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2279 if (IS_ERR(inode)) {
2280 srcu_read_unlock(&fs_info->subvol_srcu, index);
2284 srcu_read_unlock(&fs_info->subvol_srcu, index);
2286 /* step 3: relink backref */
2287 lock_start = backref->file_pos;
2288 lock_end = backref->file_pos + backref->num_bytes - 1;
2289 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2292 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2294 btrfs_put_ordered_extent(ordered);
2298 trans = btrfs_join_transaction(root);
2299 if (IS_ERR(trans)) {
2300 ret = PTR_ERR(trans);
2304 key.objectid = backref->inum;
2305 key.type = BTRFS_EXTENT_DATA_KEY;
2306 key.offset = backref->file_pos;
2308 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2311 } else if (ret > 0) {
2316 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2317 struct btrfs_file_extent_item);
2319 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2320 backref->generation)
2323 btrfs_release_path(path);
2325 start = backref->file_pos;
2326 if (backref->extent_offset < old->extent_offset + old->offset)
2327 start += old->extent_offset + old->offset -
2328 backref->extent_offset;
2330 len = min(backref->extent_offset + backref->num_bytes,
2331 old->extent_offset + old->offset + old->len);
2332 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2334 ret = btrfs_drop_extents(trans, root, inode, start,
2339 key.objectid = btrfs_ino(inode);
2340 key.type = BTRFS_EXTENT_DATA_KEY;
2343 path->leave_spinning = 1;
2345 struct btrfs_file_extent_item *fi;
2347 struct btrfs_key found_key;
2349 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2354 leaf = path->nodes[0];
2355 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2357 fi = btrfs_item_ptr(leaf, path->slots[0],
2358 struct btrfs_file_extent_item);
2359 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2361 if (extent_len + found_key.offset == start &&
2362 relink_is_mergable(leaf, fi, new)) {
2363 btrfs_set_file_extent_num_bytes(leaf, fi,
2365 btrfs_mark_buffer_dirty(leaf);
2366 inode_add_bytes(inode, len);
2372 btrfs_release_path(path);
2377 ret = btrfs_insert_empty_item(trans, root, path, &key,
2380 btrfs_abort_transaction(trans, root, ret);
2384 leaf = path->nodes[0];
2385 item = btrfs_item_ptr(leaf, path->slots[0],
2386 struct btrfs_file_extent_item);
2387 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2388 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2389 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2390 btrfs_set_file_extent_num_bytes(leaf, item, len);
2391 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2392 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2393 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2394 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2395 btrfs_set_file_extent_encryption(leaf, item, 0);
2396 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2398 btrfs_mark_buffer_dirty(leaf);
2399 inode_add_bytes(inode, len);
2400 btrfs_release_path(path);
2402 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2404 backref->root_id, backref->inum,
2405 new->file_pos, 0); /* start - extent_offset */
2407 btrfs_abort_transaction(trans, root, ret);
2413 btrfs_release_path(path);
2414 path->leave_spinning = 0;
2415 btrfs_end_transaction(trans, root);
2417 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2423 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2425 struct old_sa_defrag_extent *old, *tmp;
2430 list_for_each_entry_safe(old, tmp, &new->head, list) {
2431 list_del(&old->list);
2437 static void relink_file_extents(struct new_sa_defrag_extent *new)
2439 struct btrfs_path *path;
2440 struct sa_defrag_extent_backref *backref;
2441 struct sa_defrag_extent_backref *prev = NULL;
2442 struct inode *inode;
2443 struct btrfs_root *root;
2444 struct rb_node *node;
2448 root = BTRFS_I(inode)->root;
2450 path = btrfs_alloc_path();
2454 if (!record_extent_backrefs(path, new)) {
2455 btrfs_free_path(path);
2458 btrfs_release_path(path);
2461 node = rb_first(&new->root);
2464 rb_erase(node, &new->root);
2466 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2468 ret = relink_extent_backref(path, prev, backref);
2481 btrfs_free_path(path);
2483 free_sa_defrag_extent(new);
2485 atomic_dec(&root->fs_info->defrag_running);
2486 wake_up(&root->fs_info->transaction_wait);
2489 static struct new_sa_defrag_extent *
2490 record_old_file_extents(struct inode *inode,
2491 struct btrfs_ordered_extent *ordered)
2493 struct btrfs_root *root = BTRFS_I(inode)->root;
2494 struct btrfs_path *path;
2495 struct btrfs_key key;
2496 struct old_sa_defrag_extent *old;
2497 struct new_sa_defrag_extent *new;
2500 new = kmalloc(sizeof(*new), GFP_NOFS);
2505 new->file_pos = ordered->file_offset;
2506 new->len = ordered->len;
2507 new->bytenr = ordered->start;
2508 new->disk_len = ordered->disk_len;
2509 new->compress_type = ordered->compress_type;
2510 new->root = RB_ROOT;
2511 INIT_LIST_HEAD(&new->head);
2513 path = btrfs_alloc_path();
2517 key.objectid = btrfs_ino(inode);
2518 key.type = BTRFS_EXTENT_DATA_KEY;
2519 key.offset = new->file_pos;
2521 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2524 if (ret > 0 && path->slots[0] > 0)
2527 /* find out all the old extents for the file range */
2529 struct btrfs_file_extent_item *extent;
2530 struct extent_buffer *l;
2539 slot = path->slots[0];
2541 if (slot >= btrfs_header_nritems(l)) {
2542 ret = btrfs_next_leaf(root, path);
2550 btrfs_item_key_to_cpu(l, &key, slot);
2552 if (key.objectid != btrfs_ino(inode))
2554 if (key.type != BTRFS_EXTENT_DATA_KEY)
2556 if (key.offset >= new->file_pos + new->len)
2559 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2561 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2562 if (key.offset + num_bytes < new->file_pos)
2565 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2569 extent_offset = btrfs_file_extent_offset(l, extent);
2571 old = kmalloc(sizeof(*old), GFP_NOFS);
2575 offset = max(new->file_pos, key.offset);
2576 end = min(new->file_pos + new->len, key.offset + num_bytes);
2578 old->bytenr = disk_bytenr;
2579 old->extent_offset = extent_offset;
2580 old->offset = offset - key.offset;
2581 old->len = end - offset;
2584 list_add_tail(&old->list, &new->head);
2590 btrfs_free_path(path);
2591 atomic_inc(&root->fs_info->defrag_running);
2596 btrfs_free_path(path);
2598 free_sa_defrag_extent(new);
2602 /* as ordered data IO finishes, this gets called so we can finish
2603 * an ordered extent if the range of bytes in the file it covers are
2606 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2608 struct inode *inode = ordered_extent->inode;
2609 struct btrfs_root *root = BTRFS_I(inode)->root;
2610 struct btrfs_trans_handle *trans = NULL;
2611 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2612 struct extent_state *cached_state = NULL;
2613 struct new_sa_defrag_extent *new = NULL;
2614 int compress_type = 0;
2616 u64 logical_len = ordered_extent->len;
2618 bool truncated = false;
2620 nolock = btrfs_is_free_space_inode(inode);
2622 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2627 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2629 logical_len = ordered_extent->truncated_len;
2630 /* Truncated the entire extent, don't bother adding */
2635 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2636 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2637 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2639 trans = btrfs_join_transaction_nolock(root);
2641 trans = btrfs_join_transaction(root);
2642 if (IS_ERR(trans)) {
2643 ret = PTR_ERR(trans);
2647 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2648 ret = btrfs_update_inode_fallback(trans, root, inode);
2649 if (ret) /* -ENOMEM or corruption */
2650 btrfs_abort_transaction(trans, root, ret);
2654 lock_extent_bits(io_tree, ordered_extent->file_offset,
2655 ordered_extent->file_offset + ordered_extent->len - 1,
2658 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2659 ordered_extent->file_offset + ordered_extent->len - 1,
2660 EXTENT_DEFRAG, 1, cached_state);
2662 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2663 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2664 /* the inode is shared */
2665 new = record_old_file_extents(inode, ordered_extent);
2667 clear_extent_bit(io_tree, ordered_extent->file_offset,
2668 ordered_extent->file_offset + ordered_extent->len - 1,
2669 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2673 trans = btrfs_join_transaction_nolock(root);
2675 trans = btrfs_join_transaction(root);
2676 if (IS_ERR(trans)) {
2677 ret = PTR_ERR(trans);
2681 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2683 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2684 compress_type = ordered_extent->compress_type;
2685 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2686 BUG_ON(compress_type);
2687 ret = btrfs_mark_extent_written(trans, inode,
2688 ordered_extent->file_offset,
2689 ordered_extent->file_offset +
2692 BUG_ON(root == root->fs_info->tree_root);
2693 ret = insert_reserved_file_extent(trans, inode,
2694 ordered_extent->file_offset,
2695 ordered_extent->start,
2696 ordered_extent->disk_len,
2697 logical_len, logical_len,
2698 compress_type, 0, 0,
2699 BTRFS_FILE_EXTENT_REG);
2701 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2702 ordered_extent->file_offset, ordered_extent->len,
2705 btrfs_abort_transaction(trans, root, ret);
2709 add_pending_csums(trans, inode, ordered_extent->file_offset,
2710 &ordered_extent->list);
2712 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2713 ret = btrfs_update_inode_fallback(trans, root, inode);
2714 if (ret) { /* -ENOMEM or corruption */
2715 btrfs_abort_transaction(trans, root, ret);
2720 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2721 ordered_extent->file_offset +
2722 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2724 if (root != root->fs_info->tree_root)
2725 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2727 btrfs_end_transaction(trans, root);
2729 if (ret || truncated) {
2733 start = ordered_extent->file_offset + logical_len;
2735 start = ordered_extent->file_offset;
2736 end = ordered_extent->file_offset + ordered_extent->len - 1;
2737 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2739 /* Drop the cache for the part of the extent we didn't write. */
2740 btrfs_drop_extent_cache(inode, start, end, 0);
2743 * If the ordered extent had an IOERR or something else went
2744 * wrong we need to return the space for this ordered extent
2745 * back to the allocator. We only free the extent in the
2746 * truncated case if we didn't write out the extent at all.
2748 if ((ret || !logical_len) &&
2749 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2750 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2751 btrfs_free_reserved_extent(root, ordered_extent->start,
2752 ordered_extent->disk_len);
2757 * This needs to be done to make sure anybody waiting knows we are done
2758 * updating everything for this ordered extent.
2760 btrfs_remove_ordered_extent(inode, ordered_extent);
2762 /* for snapshot-aware defrag */
2765 free_sa_defrag_extent(new);
2766 atomic_dec(&root->fs_info->defrag_running);
2768 relink_file_extents(new);
2773 btrfs_put_ordered_extent(ordered_extent);
2774 /* once for the tree */
2775 btrfs_put_ordered_extent(ordered_extent);
2780 static void finish_ordered_fn(struct btrfs_work *work)
2782 struct btrfs_ordered_extent *ordered_extent;
2783 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2784 btrfs_finish_ordered_io(ordered_extent);
2787 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2788 struct extent_state *state, int uptodate)
2790 struct inode *inode = page->mapping->host;
2791 struct btrfs_root *root = BTRFS_I(inode)->root;
2792 struct btrfs_ordered_extent *ordered_extent = NULL;
2793 struct btrfs_workqueue *workers;
2795 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2797 ClearPagePrivate2(page);
2798 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2799 end - start + 1, uptodate))
2802 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2804 if (btrfs_is_free_space_inode(inode))
2805 workers = root->fs_info->endio_freespace_worker;
2807 workers = root->fs_info->endio_write_workers;
2808 btrfs_queue_work(workers, &ordered_extent->work);
2814 * when reads are done, we need to check csums to verify the data is correct
2815 * if there's a match, we allow the bio to finish. If not, the code in
2816 * extent_io.c will try to find good copies for us.
2818 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2819 u64 phy_offset, struct page *page,
2820 u64 start, u64 end, int mirror)
2822 size_t offset = start - page_offset(page);
2823 struct inode *inode = page->mapping->host;
2824 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2826 struct btrfs_root *root = BTRFS_I(inode)->root;
2829 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2830 DEFAULT_RATELIMIT_BURST);
2832 if (PageChecked(page)) {
2833 ClearPageChecked(page);
2837 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2840 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2841 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2842 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2847 phy_offset >>= inode->i_sb->s_blocksize_bits;
2848 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2850 kaddr = kmap_atomic(page);
2851 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2852 btrfs_csum_final(csum, (char *)&csum);
2853 if (csum != csum_expected)
2856 kunmap_atomic(kaddr);
2861 if (__ratelimit(&_rs))
2862 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2863 btrfs_ino(page->mapping->host), start, csum, csum_expected);
2864 memset(kaddr + offset, 1, end - start + 1);
2865 flush_dcache_page(page);
2866 kunmap_atomic(kaddr);
2867 if (csum_expected == 0)
2872 struct delayed_iput {
2873 struct list_head list;
2874 struct inode *inode;
2877 /* JDM: If this is fs-wide, why can't we add a pointer to
2878 * btrfs_inode instead and avoid the allocation? */
2879 void btrfs_add_delayed_iput(struct inode *inode)
2881 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2882 struct delayed_iput *delayed;
2884 if (atomic_add_unless(&inode->i_count, -1, 1))
2887 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2888 delayed->inode = inode;
2890 spin_lock(&fs_info->delayed_iput_lock);
2891 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2892 spin_unlock(&fs_info->delayed_iput_lock);
2895 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2898 struct btrfs_fs_info *fs_info = root->fs_info;
2899 struct delayed_iput *delayed;
2902 spin_lock(&fs_info->delayed_iput_lock);
2903 empty = list_empty(&fs_info->delayed_iputs);
2904 spin_unlock(&fs_info->delayed_iput_lock);
2908 spin_lock(&fs_info->delayed_iput_lock);
2909 list_splice_init(&fs_info->delayed_iputs, &list);
2910 spin_unlock(&fs_info->delayed_iput_lock);
2912 while (!list_empty(&list)) {
2913 delayed = list_entry(list.next, struct delayed_iput, list);
2914 list_del(&delayed->list);
2915 iput(delayed->inode);
2921 * This is called in transaction commit time. If there are no orphan
2922 * files in the subvolume, it removes orphan item and frees block_rsv
2925 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2926 struct btrfs_root *root)
2928 struct btrfs_block_rsv *block_rsv;
2931 if (atomic_read(&root->orphan_inodes) ||
2932 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2935 spin_lock(&root->orphan_lock);
2936 if (atomic_read(&root->orphan_inodes)) {
2937 spin_unlock(&root->orphan_lock);
2941 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2942 spin_unlock(&root->orphan_lock);
2946 block_rsv = root->orphan_block_rsv;
2947 root->orphan_block_rsv = NULL;
2948 spin_unlock(&root->orphan_lock);
2950 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
2951 btrfs_root_refs(&root->root_item) > 0) {
2952 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2953 root->root_key.objectid);
2955 btrfs_abort_transaction(trans, root, ret);
2957 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
2962 WARN_ON(block_rsv->size > 0);
2963 btrfs_free_block_rsv(root, block_rsv);
2968 * This creates an orphan entry for the given inode in case something goes
2969 * wrong in the middle of an unlink/truncate.
2971 * NOTE: caller of this function should reserve 5 units of metadata for
2974 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2976 struct btrfs_root *root = BTRFS_I(inode)->root;
2977 struct btrfs_block_rsv *block_rsv = NULL;
2982 if (!root->orphan_block_rsv) {
2983 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2988 spin_lock(&root->orphan_lock);
2989 if (!root->orphan_block_rsv) {
2990 root->orphan_block_rsv = block_rsv;
2991 } else if (block_rsv) {
2992 btrfs_free_block_rsv(root, block_rsv);
2996 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2997 &BTRFS_I(inode)->runtime_flags)) {
3000 * For proper ENOSPC handling, we should do orphan
3001 * cleanup when mounting. But this introduces backward
3002 * compatibility issue.
3004 if (!xchg(&root->orphan_item_inserted, 1))
3010 atomic_inc(&root->orphan_inodes);
3013 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3014 &BTRFS_I(inode)->runtime_flags))
3016 spin_unlock(&root->orphan_lock);
3018 /* grab metadata reservation from transaction handle */
3020 ret = btrfs_orphan_reserve_metadata(trans, inode);
3021 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3024 /* insert an orphan item to track this unlinked/truncated file */
3026 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3028 atomic_dec(&root->orphan_inodes);
3030 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3031 &BTRFS_I(inode)->runtime_flags);
3032 btrfs_orphan_release_metadata(inode);
3034 if (ret != -EEXIST) {
3035 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3036 &BTRFS_I(inode)->runtime_flags);
3037 btrfs_abort_transaction(trans, root, ret);
3044 /* insert an orphan item to track subvolume contains orphan files */
3046 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3047 root->root_key.objectid);
3048 if (ret && ret != -EEXIST) {
3049 btrfs_abort_transaction(trans, root, ret);
3057 * We have done the truncate/delete so we can go ahead and remove the orphan
3058 * item for this particular inode.
3060 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3061 struct inode *inode)
3063 struct btrfs_root *root = BTRFS_I(inode)->root;
3064 int delete_item = 0;
3065 int release_rsv = 0;
3068 spin_lock(&root->orphan_lock);
3069 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3070 &BTRFS_I(inode)->runtime_flags))
3073 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3074 &BTRFS_I(inode)->runtime_flags))
3076 spin_unlock(&root->orphan_lock);
3079 atomic_dec(&root->orphan_inodes);
3081 ret = btrfs_del_orphan_item(trans, root,
3086 btrfs_orphan_release_metadata(inode);
3092 * this cleans up any orphans that may be left on the list from the last use
3095 int btrfs_orphan_cleanup(struct btrfs_root *root)
3097 struct btrfs_path *path;
3098 struct extent_buffer *leaf;
3099 struct btrfs_key key, found_key;
3100 struct btrfs_trans_handle *trans;
3101 struct inode *inode;
3102 u64 last_objectid = 0;
3103 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3105 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3108 path = btrfs_alloc_path();
3115 key.objectid = BTRFS_ORPHAN_OBJECTID;
3116 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3117 key.offset = (u64)-1;
3120 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3125 * if ret == 0 means we found what we were searching for, which
3126 * is weird, but possible, so only screw with path if we didn't
3127 * find the key and see if we have stuff that matches
3131 if (path->slots[0] == 0)
3136 /* pull out the item */
3137 leaf = path->nodes[0];
3138 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3140 /* make sure the item matches what we want */
3141 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3143 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3146 /* release the path since we're done with it */
3147 btrfs_release_path(path);
3150 * this is where we are basically btrfs_lookup, without the
3151 * crossing root thing. we store the inode number in the
3152 * offset of the orphan item.
3155 if (found_key.offset == last_objectid) {
3156 btrfs_err(root->fs_info,
3157 "Error removing orphan entry, stopping orphan cleanup");
3162 last_objectid = found_key.offset;
3164 found_key.objectid = found_key.offset;
3165 found_key.type = BTRFS_INODE_ITEM_KEY;
3166 found_key.offset = 0;
3167 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3168 ret = PTR_ERR_OR_ZERO(inode);
3169 if (ret && ret != -ESTALE)
3172 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3173 struct btrfs_root *dead_root;
3174 struct btrfs_fs_info *fs_info = root->fs_info;
3175 int is_dead_root = 0;
3178 * this is an orphan in the tree root. Currently these
3179 * could come from 2 sources:
3180 * a) a snapshot deletion in progress
3181 * b) a free space cache inode
3182 * We need to distinguish those two, as the snapshot
3183 * orphan must not get deleted.
3184 * find_dead_roots already ran before us, so if this
3185 * is a snapshot deletion, we should find the root
3186 * in the dead_roots list
3188 spin_lock(&fs_info->trans_lock);
3189 list_for_each_entry(dead_root, &fs_info->dead_roots,
3191 if (dead_root->root_key.objectid ==
3192 found_key.objectid) {
3197 spin_unlock(&fs_info->trans_lock);
3199 /* prevent this orphan from being found again */
3200 key.offset = found_key.objectid - 1;
3205 * Inode is already gone but the orphan item is still there,
3206 * kill the orphan item.
3208 if (ret == -ESTALE) {
3209 trans = btrfs_start_transaction(root, 1);
3210 if (IS_ERR(trans)) {
3211 ret = PTR_ERR(trans);
3214 btrfs_debug(root->fs_info, "auto deleting %Lu",
3215 found_key.objectid);
3216 ret = btrfs_del_orphan_item(trans, root,
3217 found_key.objectid);
3218 btrfs_end_transaction(trans, root);
3225 * add this inode to the orphan list so btrfs_orphan_del does
3226 * the proper thing when we hit it
3228 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3229 &BTRFS_I(inode)->runtime_flags);
3230 atomic_inc(&root->orphan_inodes);
3232 /* if we have links, this was a truncate, lets do that */
3233 if (inode->i_nlink) {
3234 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3240 /* 1 for the orphan item deletion. */
3241 trans = btrfs_start_transaction(root, 1);
3242 if (IS_ERR(trans)) {
3244 ret = PTR_ERR(trans);
3247 ret = btrfs_orphan_add(trans, inode);
3248 btrfs_end_transaction(trans, root);
3254 ret = btrfs_truncate(inode);
3256 btrfs_orphan_del(NULL, inode);
3261 /* this will do delete_inode and everything for us */
3266 /* release the path since we're done with it */
3267 btrfs_release_path(path);
3269 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3271 if (root->orphan_block_rsv)
3272 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3275 if (root->orphan_block_rsv ||
3276 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3277 trans = btrfs_join_transaction(root);
3279 btrfs_end_transaction(trans, root);
3283 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3285 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3289 btrfs_crit(root->fs_info,
3290 "could not do orphan cleanup %d", ret);
3291 btrfs_free_path(path);
3296 * very simple check to peek ahead in the leaf looking for xattrs. If we
3297 * don't find any xattrs, we know there can't be any acls.
3299 * slot is the slot the inode is in, objectid is the objectid of the inode
3301 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3302 int slot, u64 objectid,
3303 int *first_xattr_slot)
3305 u32 nritems = btrfs_header_nritems(leaf);
3306 struct btrfs_key found_key;
3307 static u64 xattr_access = 0;
3308 static u64 xattr_default = 0;
3311 if (!xattr_access) {
3312 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3313 strlen(POSIX_ACL_XATTR_ACCESS));
3314 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3315 strlen(POSIX_ACL_XATTR_DEFAULT));
3319 *first_xattr_slot = -1;
3320 while (slot < nritems) {
3321 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3323 /* we found a different objectid, there must not be acls */
3324 if (found_key.objectid != objectid)
3327 /* we found an xattr, assume we've got an acl */
3328 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3329 if (*first_xattr_slot == -1)
3330 *first_xattr_slot = slot;
3331 if (found_key.offset == xattr_access ||
3332 found_key.offset == xattr_default)
3337 * we found a key greater than an xattr key, there can't
3338 * be any acls later on
3340 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3347 * it goes inode, inode backrefs, xattrs, extents,
3348 * so if there are a ton of hard links to an inode there can
3349 * be a lot of backrefs. Don't waste time searching too hard,
3350 * this is just an optimization
3355 /* we hit the end of the leaf before we found an xattr or
3356 * something larger than an xattr. We have to assume the inode
3359 if (*first_xattr_slot == -1)
3360 *first_xattr_slot = slot;
3365 * read an inode from the btree into the in-memory inode
3367 static void btrfs_read_locked_inode(struct inode *inode)
3369 struct btrfs_path *path;
3370 struct extent_buffer *leaf;
3371 struct btrfs_inode_item *inode_item;
3372 struct btrfs_timespec *tspec;
3373 struct btrfs_root *root = BTRFS_I(inode)->root;
3374 struct btrfs_key location;
3379 bool filled = false;
3380 int first_xattr_slot;
3382 ret = btrfs_fill_inode(inode, &rdev);
3386 path = btrfs_alloc_path();
3390 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3392 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3396 leaf = path->nodes[0];
3401 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3402 struct btrfs_inode_item);
3403 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3404 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3405 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3406 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3407 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3409 tspec = btrfs_inode_atime(inode_item);
3410 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3411 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3413 tspec = btrfs_inode_mtime(inode_item);
3414 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3415 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3417 tspec = btrfs_inode_ctime(inode_item);
3418 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3419 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3421 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3422 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3423 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3426 * If we were modified in the current generation and evicted from memory
3427 * and then re-read we need to do a full sync since we don't have any
3428 * idea about which extents were modified before we were evicted from
3431 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3432 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3433 &BTRFS_I(inode)->runtime_flags);
3435 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3436 inode->i_generation = BTRFS_I(inode)->generation;
3438 rdev = btrfs_inode_rdev(leaf, inode_item);
3440 BTRFS_I(inode)->index_cnt = (u64)-1;
3441 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3445 if (inode->i_nlink != 1 ||
3446 path->slots[0] >= btrfs_header_nritems(leaf))
3449 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3450 if (location.objectid != btrfs_ino(inode))
3453 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3454 if (location.type == BTRFS_INODE_REF_KEY) {
3455 struct btrfs_inode_ref *ref;
3457 ref = (struct btrfs_inode_ref *)ptr;
3458 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3459 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3460 struct btrfs_inode_extref *extref;
3462 extref = (struct btrfs_inode_extref *)ptr;
3463 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3468 * try to precache a NULL acl entry for files that don't have
3469 * any xattrs or acls
3471 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3472 btrfs_ino(inode), &first_xattr_slot);
3473 if (first_xattr_slot != -1) {
3474 path->slots[0] = first_xattr_slot;
3475 ret = btrfs_load_inode_props(inode, path);
3477 btrfs_err(root->fs_info,
3478 "error loading props for ino %llu (root %llu): %d\n",
3480 root->root_key.objectid, ret);
3482 btrfs_free_path(path);
3485 cache_no_acl(inode);
3487 switch (inode->i_mode & S_IFMT) {
3489 inode->i_mapping->a_ops = &btrfs_aops;
3490 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3491 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3492 inode->i_fop = &btrfs_file_operations;
3493 inode->i_op = &btrfs_file_inode_operations;
3496 inode->i_fop = &btrfs_dir_file_operations;
3497 if (root == root->fs_info->tree_root)
3498 inode->i_op = &btrfs_dir_ro_inode_operations;
3500 inode->i_op = &btrfs_dir_inode_operations;
3503 inode->i_op = &btrfs_symlink_inode_operations;
3504 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3505 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3508 inode->i_op = &btrfs_special_inode_operations;
3509 init_special_inode(inode, inode->i_mode, rdev);
3513 btrfs_update_iflags(inode);
3517 btrfs_free_path(path);
3518 make_bad_inode(inode);
3522 * given a leaf and an inode, copy the inode fields into the leaf
3524 static void fill_inode_item(struct btrfs_trans_handle *trans,
3525 struct extent_buffer *leaf,
3526 struct btrfs_inode_item *item,
3527 struct inode *inode)
3529 struct btrfs_map_token token;
3531 btrfs_init_map_token(&token);
3533 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3534 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3535 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3537 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3538 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3540 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3541 inode->i_atime.tv_sec, &token);
3542 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3543 inode->i_atime.tv_nsec, &token);
3545 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3546 inode->i_mtime.tv_sec, &token);
3547 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3548 inode->i_mtime.tv_nsec, &token);
3550 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3551 inode->i_ctime.tv_sec, &token);
3552 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3553 inode->i_ctime.tv_nsec, &token);
3555 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3557 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3559 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3560 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3561 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3562 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3563 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3567 * copy everything in the in-memory inode into the btree.
3569 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3570 struct btrfs_root *root, struct inode *inode)
3572 struct btrfs_inode_item *inode_item;
3573 struct btrfs_path *path;
3574 struct extent_buffer *leaf;
3577 path = btrfs_alloc_path();
3581 path->leave_spinning = 1;
3582 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3590 leaf = path->nodes[0];
3591 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3592 struct btrfs_inode_item);
3594 fill_inode_item(trans, leaf, inode_item, inode);
3595 btrfs_mark_buffer_dirty(leaf);
3596 btrfs_set_inode_last_trans(trans, inode);
3599 btrfs_free_path(path);
3604 * copy everything in the in-memory inode into the btree.
3606 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3607 struct btrfs_root *root, struct inode *inode)
3612 * If the inode is a free space inode, we can deadlock during commit
3613 * if we put it into the delayed code.
3615 * The data relocation inode should also be directly updated
3618 if (!btrfs_is_free_space_inode(inode)
3619 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3620 btrfs_update_root_times(trans, root);
3622 ret = btrfs_delayed_update_inode(trans, root, inode);
3624 btrfs_set_inode_last_trans(trans, inode);
3628 return btrfs_update_inode_item(trans, root, inode);
3631 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3632 struct btrfs_root *root,
3633 struct inode *inode)
3637 ret = btrfs_update_inode(trans, root, inode);
3639 return btrfs_update_inode_item(trans, root, inode);
3644 * unlink helper that gets used here in inode.c and in the tree logging
3645 * recovery code. It remove a link in a directory with a given name, and
3646 * also drops the back refs in the inode to the directory
3648 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3649 struct btrfs_root *root,
3650 struct inode *dir, struct inode *inode,
3651 const char *name, int name_len)
3653 struct btrfs_path *path;
3655 struct extent_buffer *leaf;
3656 struct btrfs_dir_item *di;
3657 struct btrfs_key key;
3659 u64 ino = btrfs_ino(inode);
3660 u64 dir_ino = btrfs_ino(dir);
3662 path = btrfs_alloc_path();
3668 path->leave_spinning = 1;
3669 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3670 name, name_len, -1);
3679 leaf = path->nodes[0];
3680 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3681 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3684 btrfs_release_path(path);
3687 * If we don't have dir index, we have to get it by looking up
3688 * the inode ref, since we get the inode ref, remove it directly,
3689 * it is unnecessary to do delayed deletion.
3691 * But if we have dir index, needn't search inode ref to get it.
3692 * Since the inode ref is close to the inode item, it is better
3693 * that we delay to delete it, and just do this deletion when
3694 * we update the inode item.
3696 if (BTRFS_I(inode)->dir_index) {
3697 ret = btrfs_delayed_delete_inode_ref(inode);
3699 index = BTRFS_I(inode)->dir_index;
3704 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3707 btrfs_info(root->fs_info,
3708 "failed to delete reference to %.*s, inode %llu parent %llu",
3709 name_len, name, ino, dir_ino);
3710 btrfs_abort_transaction(trans, root, ret);
3714 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3716 btrfs_abort_transaction(trans, root, ret);
3720 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3722 if (ret != 0 && ret != -ENOENT) {
3723 btrfs_abort_transaction(trans, root, ret);
3727 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3732 btrfs_abort_transaction(trans, root, ret);
3734 btrfs_free_path(path);
3738 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3739 inode_inc_iversion(inode);
3740 inode_inc_iversion(dir);
3741 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3742 ret = btrfs_update_inode(trans, root, dir);
3747 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3748 struct btrfs_root *root,
3749 struct inode *dir, struct inode *inode,
3750 const char *name, int name_len)
3753 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3756 ret = btrfs_update_inode(trans, root, inode);
3762 * helper to start transaction for unlink and rmdir.
3764 * unlink and rmdir are special in btrfs, they do not always free space, so
3765 * if we cannot make our reservations the normal way try and see if there is
3766 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3767 * allow the unlink to occur.
3769 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3771 struct btrfs_trans_handle *trans;
3772 struct btrfs_root *root = BTRFS_I(dir)->root;
3776 * 1 for the possible orphan item
3777 * 1 for the dir item
3778 * 1 for the dir index
3779 * 1 for the inode ref
3782 trans = btrfs_start_transaction(root, 5);
3783 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3786 if (PTR_ERR(trans) == -ENOSPC) {
3787 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3789 trans = btrfs_start_transaction(root, 0);
3792 ret = btrfs_cond_migrate_bytes(root->fs_info,
3793 &root->fs_info->trans_block_rsv,
3796 btrfs_end_transaction(trans, root);
3797 return ERR_PTR(ret);
3799 trans->block_rsv = &root->fs_info->trans_block_rsv;
3800 trans->bytes_reserved = num_bytes;
3805 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3807 struct btrfs_root *root = BTRFS_I(dir)->root;
3808 struct btrfs_trans_handle *trans;
3809 struct inode *inode = dentry->d_inode;
3812 trans = __unlink_start_trans(dir);
3814 return PTR_ERR(trans);
3816 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3818 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3819 dentry->d_name.name, dentry->d_name.len);
3823 if (inode->i_nlink == 0) {
3824 ret = btrfs_orphan_add(trans, inode);
3830 btrfs_end_transaction(trans, root);
3831 btrfs_btree_balance_dirty(root);
3835 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3836 struct btrfs_root *root,
3837 struct inode *dir, u64 objectid,
3838 const char *name, int name_len)
3840 struct btrfs_path *path;
3841 struct extent_buffer *leaf;
3842 struct btrfs_dir_item *di;
3843 struct btrfs_key key;
3846 u64 dir_ino = btrfs_ino(dir);
3848 path = btrfs_alloc_path();
3852 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3853 name, name_len, -1);
3854 if (IS_ERR_OR_NULL(di)) {
3862 leaf = path->nodes[0];
3863 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3864 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3865 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3867 btrfs_abort_transaction(trans, root, ret);
3870 btrfs_release_path(path);
3872 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3873 objectid, root->root_key.objectid,
3874 dir_ino, &index, name, name_len);
3876 if (ret != -ENOENT) {
3877 btrfs_abort_transaction(trans, root, ret);
3880 di = btrfs_search_dir_index_item(root, path, dir_ino,
3882 if (IS_ERR_OR_NULL(di)) {
3887 btrfs_abort_transaction(trans, root, ret);
3891 leaf = path->nodes[0];
3892 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3893 btrfs_release_path(path);
3896 btrfs_release_path(path);
3898 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3900 btrfs_abort_transaction(trans, root, ret);
3904 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3905 inode_inc_iversion(dir);
3906 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3907 ret = btrfs_update_inode_fallback(trans, root, dir);
3909 btrfs_abort_transaction(trans, root, ret);
3911 btrfs_free_path(path);
3915 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3917 struct inode *inode = dentry->d_inode;
3919 struct btrfs_root *root = BTRFS_I(dir)->root;
3920 struct btrfs_trans_handle *trans;
3922 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3924 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3927 trans = __unlink_start_trans(dir);
3929 return PTR_ERR(trans);
3931 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3932 err = btrfs_unlink_subvol(trans, root, dir,
3933 BTRFS_I(inode)->location.objectid,
3934 dentry->d_name.name,
3935 dentry->d_name.len);
3939 err = btrfs_orphan_add(trans, inode);
3943 /* now the directory is empty */
3944 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3945 dentry->d_name.name, dentry->d_name.len);
3947 btrfs_i_size_write(inode, 0);
3949 btrfs_end_transaction(trans, root);
3950 btrfs_btree_balance_dirty(root);
3956 * this can truncate away extent items, csum items and directory items.
3957 * It starts at a high offset and removes keys until it can't find
3958 * any higher than new_size
3960 * csum items that cross the new i_size are truncated to the new size
3963 * min_type is the minimum key type to truncate down to. If set to 0, this
3964 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3966 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3967 struct btrfs_root *root,
3968 struct inode *inode,
3969 u64 new_size, u32 min_type)
3971 struct btrfs_path *path;
3972 struct extent_buffer *leaf;
3973 struct btrfs_file_extent_item *fi;
3974 struct btrfs_key key;
3975 struct btrfs_key found_key;
3976 u64 extent_start = 0;
3977 u64 extent_num_bytes = 0;
3978 u64 extent_offset = 0;
3980 u64 last_size = (u64)-1;
3981 u32 found_type = (u8)-1;
3984 int pending_del_nr = 0;
3985 int pending_del_slot = 0;
3986 int extent_type = -1;
3989 u64 ino = btrfs_ino(inode);
3991 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3993 path = btrfs_alloc_path();
3999 * We want to drop from the next block forward in case this new size is
4000 * not block aligned since we will be keeping the last block of the
4001 * extent just the way it is.
4003 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4004 root == root->fs_info->tree_root)
4005 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4006 root->sectorsize), (u64)-1, 0);
4009 * This function is also used to drop the items in the log tree before
4010 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4011 * it is used to drop the loged items. So we shouldn't kill the delayed
4014 if (min_type == 0 && root == BTRFS_I(inode)->root)
4015 btrfs_kill_delayed_inode_items(inode);
4018 key.offset = (u64)-1;
4022 path->leave_spinning = 1;
4023 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4030 /* there are no items in the tree for us to truncate, we're
4033 if (path->slots[0] == 0)
4040 leaf = path->nodes[0];
4041 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4042 found_type = btrfs_key_type(&found_key);
4044 if (found_key.objectid != ino)
4047 if (found_type < min_type)
4050 item_end = found_key.offset;
4051 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4052 fi = btrfs_item_ptr(leaf, path->slots[0],
4053 struct btrfs_file_extent_item);
4054 extent_type = btrfs_file_extent_type(leaf, fi);
4055 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4057 btrfs_file_extent_num_bytes(leaf, fi);
4058 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4059 item_end += btrfs_file_extent_inline_len(leaf,
4060 path->slots[0], fi);
4064 if (found_type > min_type) {
4067 if (item_end < new_size)
4069 if (found_key.offset >= new_size)
4075 /* FIXME, shrink the extent if the ref count is only 1 */
4076 if (found_type != BTRFS_EXTENT_DATA_KEY)
4080 last_size = found_key.offset;
4082 last_size = new_size;
4084 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4086 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4088 u64 orig_num_bytes =
4089 btrfs_file_extent_num_bytes(leaf, fi);
4090 extent_num_bytes = ALIGN(new_size -
4093 btrfs_set_file_extent_num_bytes(leaf, fi,
4095 num_dec = (orig_num_bytes -
4097 if (test_bit(BTRFS_ROOT_REF_COWS,
4100 inode_sub_bytes(inode, num_dec);
4101 btrfs_mark_buffer_dirty(leaf);
4104 btrfs_file_extent_disk_num_bytes(leaf,
4106 extent_offset = found_key.offset -
4107 btrfs_file_extent_offset(leaf, fi);
4109 /* FIXME blocksize != 4096 */
4110 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4111 if (extent_start != 0) {
4113 if (test_bit(BTRFS_ROOT_REF_COWS,
4115 inode_sub_bytes(inode, num_dec);
4118 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4120 * we can't truncate inline items that have had
4124 btrfs_file_extent_compression(leaf, fi) == 0 &&
4125 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4126 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4127 u32 size = new_size - found_key.offset;
4129 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4130 inode_sub_bytes(inode, item_end + 1 -
4134 * update the ram bytes to properly reflect
4135 * the new size of our item
4137 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4139 btrfs_file_extent_calc_inline_size(size);
4140 btrfs_truncate_item(root, path, size, 1);
4141 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4143 inode_sub_bytes(inode, item_end + 1 -
4149 if (!pending_del_nr) {
4150 /* no pending yet, add ourselves */
4151 pending_del_slot = path->slots[0];
4153 } else if (pending_del_nr &&
4154 path->slots[0] + 1 == pending_del_slot) {
4155 /* hop on the pending chunk */
4157 pending_del_slot = path->slots[0];
4165 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4166 root == root->fs_info->tree_root)) {
4167 btrfs_set_path_blocking(path);
4168 ret = btrfs_free_extent(trans, root, extent_start,
4169 extent_num_bytes, 0,
4170 btrfs_header_owner(leaf),
4171 ino, extent_offset, 0);
4175 if (found_type == BTRFS_INODE_ITEM_KEY)
4178 if (path->slots[0] == 0 ||
4179 path->slots[0] != pending_del_slot) {
4180 if (pending_del_nr) {
4181 ret = btrfs_del_items(trans, root, path,
4185 btrfs_abort_transaction(trans,
4191 btrfs_release_path(path);
4198 if (pending_del_nr) {
4199 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4202 btrfs_abort_transaction(trans, root, ret);
4205 if (last_size != (u64)-1)
4206 btrfs_ordered_update_i_size(inode, last_size, NULL);
4207 btrfs_free_path(path);
4212 * btrfs_truncate_page - read, zero a chunk and write a page
4213 * @inode - inode that we're zeroing
4214 * @from - the offset to start zeroing
4215 * @len - the length to zero, 0 to zero the entire range respective to the
4217 * @front - zero up to the offset instead of from the offset on
4219 * This will find the page for the "from" offset and cow the page and zero the
4220 * part we want to zero. This is used with truncate and hole punching.
4222 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4225 struct address_space *mapping = inode->i_mapping;
4226 struct btrfs_root *root = BTRFS_I(inode)->root;
4227 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4228 struct btrfs_ordered_extent *ordered;
4229 struct extent_state *cached_state = NULL;
4231 u32 blocksize = root->sectorsize;
4232 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4233 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4235 gfp_t mask = btrfs_alloc_write_mask(mapping);
4240 if ((offset & (blocksize - 1)) == 0 &&
4241 (!len || ((len & (blocksize - 1)) == 0)))
4243 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4248 page = find_or_create_page(mapping, index, mask);
4250 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4255 page_start = page_offset(page);
4256 page_end = page_start + PAGE_CACHE_SIZE - 1;
4258 if (!PageUptodate(page)) {
4259 ret = btrfs_readpage(NULL, page);
4261 if (page->mapping != mapping) {
4263 page_cache_release(page);
4266 if (!PageUptodate(page)) {
4271 wait_on_page_writeback(page);
4273 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4274 set_page_extent_mapped(page);
4276 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4278 unlock_extent_cached(io_tree, page_start, page_end,
4279 &cached_state, GFP_NOFS);
4281 page_cache_release(page);
4282 btrfs_start_ordered_extent(inode, ordered, 1);
4283 btrfs_put_ordered_extent(ordered);
4287 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4288 EXTENT_DIRTY | EXTENT_DELALLOC |
4289 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4290 0, 0, &cached_state, GFP_NOFS);
4292 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4295 unlock_extent_cached(io_tree, page_start, page_end,
4296 &cached_state, GFP_NOFS);
4300 if (offset != PAGE_CACHE_SIZE) {
4302 len = PAGE_CACHE_SIZE - offset;
4305 memset(kaddr, 0, offset);
4307 memset(kaddr + offset, 0, len);
4308 flush_dcache_page(page);
4311 ClearPageChecked(page);
4312 set_page_dirty(page);
4313 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4318 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4320 page_cache_release(page);
4325 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4326 u64 offset, u64 len)
4328 struct btrfs_trans_handle *trans;
4332 * Still need to make sure the inode looks like it's been updated so
4333 * that any holes get logged if we fsync.
4335 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4336 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4337 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4338 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4343 * 1 - for the one we're dropping
4344 * 1 - for the one we're adding
4345 * 1 - for updating the inode.
4347 trans = btrfs_start_transaction(root, 3);
4349 return PTR_ERR(trans);
4351 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4353 btrfs_abort_transaction(trans, root, ret);
4354 btrfs_end_transaction(trans, root);
4358 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4359 0, 0, len, 0, len, 0, 0, 0);
4361 btrfs_abort_transaction(trans, root, ret);
4363 btrfs_update_inode(trans, root, inode);
4364 btrfs_end_transaction(trans, root);
4369 * This function puts in dummy file extents for the area we're creating a hole
4370 * for. So if we are truncating this file to a larger size we need to insert
4371 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4372 * the range between oldsize and size
4374 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4376 struct btrfs_root *root = BTRFS_I(inode)->root;
4377 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4378 struct extent_map *em = NULL;
4379 struct extent_state *cached_state = NULL;
4380 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4381 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4382 u64 block_end = ALIGN(size, root->sectorsize);
4389 * If our size started in the middle of a page we need to zero out the
4390 * rest of the page before we expand the i_size, otherwise we could
4391 * expose stale data.
4393 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4397 if (size <= hole_start)
4401 struct btrfs_ordered_extent *ordered;
4403 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4405 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4406 block_end - hole_start);
4409 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4410 &cached_state, GFP_NOFS);
4411 btrfs_start_ordered_extent(inode, ordered, 1);
4412 btrfs_put_ordered_extent(ordered);
4415 cur_offset = hole_start;
4417 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4418 block_end - cur_offset, 0);
4424 last_byte = min(extent_map_end(em), block_end);
4425 last_byte = ALIGN(last_byte , root->sectorsize);
4426 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4427 struct extent_map *hole_em;
4428 hole_size = last_byte - cur_offset;
4430 err = maybe_insert_hole(root, inode, cur_offset,
4434 btrfs_drop_extent_cache(inode, cur_offset,
4435 cur_offset + hole_size - 1, 0);
4436 hole_em = alloc_extent_map();
4438 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4439 &BTRFS_I(inode)->runtime_flags);
4442 hole_em->start = cur_offset;
4443 hole_em->len = hole_size;
4444 hole_em->orig_start = cur_offset;
4446 hole_em->block_start = EXTENT_MAP_HOLE;
4447 hole_em->block_len = 0;
4448 hole_em->orig_block_len = 0;
4449 hole_em->ram_bytes = hole_size;
4450 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4451 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4452 hole_em->generation = root->fs_info->generation;
4455 write_lock(&em_tree->lock);
4456 err = add_extent_mapping(em_tree, hole_em, 1);
4457 write_unlock(&em_tree->lock);
4460 btrfs_drop_extent_cache(inode, cur_offset,
4464 free_extent_map(hole_em);
4467 free_extent_map(em);
4469 cur_offset = last_byte;
4470 if (cur_offset >= block_end)
4473 free_extent_map(em);
4474 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4479 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4481 struct btrfs_root *root = BTRFS_I(inode)->root;
4482 struct btrfs_trans_handle *trans;
4483 loff_t oldsize = i_size_read(inode);
4484 loff_t newsize = attr->ia_size;
4485 int mask = attr->ia_valid;
4489 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4490 * special case where we need to update the times despite not having
4491 * these flags set. For all other operations the VFS set these flags
4492 * explicitly if it wants a timestamp update.
4494 if (newsize != oldsize) {
4495 inode_inc_iversion(inode);
4496 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4497 inode->i_ctime = inode->i_mtime =
4498 current_fs_time(inode->i_sb);
4501 if (newsize > oldsize) {
4502 truncate_pagecache(inode, newsize);
4503 ret = btrfs_cont_expand(inode, oldsize, newsize);
4507 trans = btrfs_start_transaction(root, 1);
4509 return PTR_ERR(trans);
4511 i_size_write(inode, newsize);
4512 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4513 ret = btrfs_update_inode(trans, root, inode);
4514 btrfs_end_transaction(trans, root);
4518 * We're truncating a file that used to have good data down to
4519 * zero. Make sure it gets into the ordered flush list so that
4520 * any new writes get down to disk quickly.
4523 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4524 &BTRFS_I(inode)->runtime_flags);
4527 * 1 for the orphan item we're going to add
4528 * 1 for the orphan item deletion.
4530 trans = btrfs_start_transaction(root, 2);
4532 return PTR_ERR(trans);
4535 * We need to do this in case we fail at _any_ point during the
4536 * actual truncate. Once we do the truncate_setsize we could
4537 * invalidate pages which forces any outstanding ordered io to
4538 * be instantly completed which will give us extents that need
4539 * to be truncated. If we fail to get an orphan inode down we
4540 * could have left over extents that were never meant to live,
4541 * so we need to garuntee from this point on that everything
4542 * will be consistent.
4544 ret = btrfs_orphan_add(trans, inode);
4545 btrfs_end_transaction(trans, root);
4549 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4550 truncate_setsize(inode, newsize);
4552 /* Disable nonlocked read DIO to avoid the end less truncate */
4553 btrfs_inode_block_unlocked_dio(inode);
4554 inode_dio_wait(inode);
4555 btrfs_inode_resume_unlocked_dio(inode);
4557 ret = btrfs_truncate(inode);
4558 if (ret && inode->i_nlink) {
4562 * failed to truncate, disk_i_size is only adjusted down
4563 * as we remove extents, so it should represent the true
4564 * size of the inode, so reset the in memory size and
4565 * delete our orphan entry.
4567 trans = btrfs_join_transaction(root);
4568 if (IS_ERR(trans)) {
4569 btrfs_orphan_del(NULL, inode);
4572 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4573 err = btrfs_orphan_del(trans, inode);
4575 btrfs_abort_transaction(trans, root, err);
4576 btrfs_end_transaction(trans, root);
4583 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4585 struct inode *inode = dentry->d_inode;
4586 struct btrfs_root *root = BTRFS_I(inode)->root;
4589 if (btrfs_root_readonly(root))
4592 err = inode_change_ok(inode, attr);
4596 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4597 err = btrfs_setsize(inode, attr);
4602 if (attr->ia_valid) {
4603 setattr_copy(inode, attr);
4604 inode_inc_iversion(inode);
4605 err = btrfs_dirty_inode(inode);
4607 if (!err && attr->ia_valid & ATTR_MODE)
4608 err = posix_acl_chmod(inode, inode->i_mode);
4615 * While truncating the inode pages during eviction, we get the VFS calling
4616 * btrfs_invalidatepage() against each page of the inode. This is slow because
4617 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4618 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4619 * extent_state structures over and over, wasting lots of time.
4621 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4622 * those expensive operations on a per page basis and do only the ordered io
4623 * finishing, while we release here the extent_map and extent_state structures,
4624 * without the excessive merging and splitting.
4626 static void evict_inode_truncate_pages(struct inode *inode)
4628 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4629 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4630 struct rb_node *node;
4632 ASSERT(inode->i_state & I_FREEING);
4633 truncate_inode_pages_final(&inode->i_data);
4635 write_lock(&map_tree->lock);
4636 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4637 struct extent_map *em;
4639 node = rb_first(&map_tree->map);
4640 em = rb_entry(node, struct extent_map, rb_node);
4641 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4642 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4643 remove_extent_mapping(map_tree, em);
4644 free_extent_map(em);
4646 write_unlock(&map_tree->lock);
4648 spin_lock(&io_tree->lock);
4649 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4650 struct extent_state *state;
4651 struct extent_state *cached_state = NULL;
4653 node = rb_first(&io_tree->state);
4654 state = rb_entry(node, struct extent_state, rb_node);
4655 atomic_inc(&state->refs);
4656 spin_unlock(&io_tree->lock);
4658 lock_extent_bits(io_tree, state->start, state->end,
4660 clear_extent_bit(io_tree, state->start, state->end,
4661 EXTENT_LOCKED | EXTENT_DIRTY |
4662 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
4663 EXTENT_DEFRAG, 1, 1,
4664 &cached_state, GFP_NOFS);
4665 free_extent_state(state);
4667 spin_lock(&io_tree->lock);
4669 spin_unlock(&io_tree->lock);
4672 void btrfs_evict_inode(struct inode *inode)
4674 struct btrfs_trans_handle *trans;
4675 struct btrfs_root *root = BTRFS_I(inode)->root;
4676 struct btrfs_block_rsv *rsv, *global_rsv;
4677 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4680 trace_btrfs_inode_evict(inode);
4682 evict_inode_truncate_pages(inode);
4684 if (inode->i_nlink &&
4685 ((btrfs_root_refs(&root->root_item) != 0 &&
4686 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4687 btrfs_is_free_space_inode(inode)))
4690 if (is_bad_inode(inode)) {
4691 btrfs_orphan_del(NULL, inode);
4694 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4695 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4697 if (root->fs_info->log_root_recovering) {
4698 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4699 &BTRFS_I(inode)->runtime_flags));
4703 if (inode->i_nlink > 0) {
4704 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4705 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4709 ret = btrfs_commit_inode_delayed_inode(inode);
4711 btrfs_orphan_del(NULL, inode);
4715 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4717 btrfs_orphan_del(NULL, inode);
4720 rsv->size = min_size;
4722 global_rsv = &root->fs_info->global_block_rsv;
4724 btrfs_i_size_write(inode, 0);
4727 * This is a bit simpler than btrfs_truncate since we've already
4728 * reserved our space for our orphan item in the unlink, so we just
4729 * need to reserve some slack space in case we add bytes and update
4730 * inode item when doing the truncate.
4733 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4734 BTRFS_RESERVE_FLUSH_LIMIT);
4737 * Try and steal from the global reserve since we will
4738 * likely not use this space anyway, we want to try as
4739 * hard as possible to get this to work.
4742 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4745 btrfs_warn(root->fs_info,
4746 "Could not get space for a delete, will truncate on mount %d",
4748 btrfs_orphan_del(NULL, inode);
4749 btrfs_free_block_rsv(root, rsv);
4753 trans = btrfs_join_transaction(root);
4754 if (IS_ERR(trans)) {
4755 btrfs_orphan_del(NULL, inode);
4756 btrfs_free_block_rsv(root, rsv);
4760 trans->block_rsv = rsv;
4762 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4766 trans->block_rsv = &root->fs_info->trans_block_rsv;
4767 btrfs_end_transaction(trans, root);
4769 btrfs_btree_balance_dirty(root);
4772 btrfs_free_block_rsv(root, rsv);
4775 * Errors here aren't a big deal, it just means we leave orphan items
4776 * in the tree. They will be cleaned up on the next mount.
4779 trans->block_rsv = root->orphan_block_rsv;
4780 btrfs_orphan_del(trans, inode);
4782 btrfs_orphan_del(NULL, inode);
4785 trans->block_rsv = &root->fs_info->trans_block_rsv;
4786 if (!(root == root->fs_info->tree_root ||
4787 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4788 btrfs_return_ino(root, btrfs_ino(inode));
4790 btrfs_end_transaction(trans, root);
4791 btrfs_btree_balance_dirty(root);
4793 btrfs_remove_delayed_node(inode);
4799 * this returns the key found in the dir entry in the location pointer.
4800 * If no dir entries were found, location->objectid is 0.
4802 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4803 struct btrfs_key *location)
4805 const char *name = dentry->d_name.name;
4806 int namelen = dentry->d_name.len;
4807 struct btrfs_dir_item *di;
4808 struct btrfs_path *path;
4809 struct btrfs_root *root = BTRFS_I(dir)->root;
4812 path = btrfs_alloc_path();
4816 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4821 if (IS_ERR_OR_NULL(di))
4824 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4826 btrfs_free_path(path);
4829 location->objectid = 0;
4834 * when we hit a tree root in a directory, the btrfs part of the inode
4835 * needs to be changed to reflect the root directory of the tree root. This
4836 * is kind of like crossing a mount point.
4838 static int fixup_tree_root_location(struct btrfs_root *root,
4840 struct dentry *dentry,
4841 struct btrfs_key *location,
4842 struct btrfs_root **sub_root)
4844 struct btrfs_path *path;
4845 struct btrfs_root *new_root;
4846 struct btrfs_root_ref *ref;
4847 struct extent_buffer *leaf;
4851 path = btrfs_alloc_path();
4858 ret = btrfs_find_item(root->fs_info->tree_root, path,
4859 BTRFS_I(dir)->root->root_key.objectid,
4860 location->objectid, BTRFS_ROOT_REF_KEY, NULL);
4867 leaf = path->nodes[0];
4868 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4869 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4870 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4873 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4874 (unsigned long)(ref + 1),
4875 dentry->d_name.len);
4879 btrfs_release_path(path);
4881 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4882 if (IS_ERR(new_root)) {
4883 err = PTR_ERR(new_root);
4887 *sub_root = new_root;
4888 location->objectid = btrfs_root_dirid(&new_root->root_item);
4889 location->type = BTRFS_INODE_ITEM_KEY;
4890 location->offset = 0;
4893 btrfs_free_path(path);
4897 static void inode_tree_add(struct inode *inode)
4899 struct btrfs_root *root = BTRFS_I(inode)->root;
4900 struct btrfs_inode *entry;
4902 struct rb_node *parent;
4903 struct rb_node *new = &BTRFS_I(inode)->rb_node;
4904 u64 ino = btrfs_ino(inode);
4906 if (inode_unhashed(inode))
4909 spin_lock(&root->inode_lock);
4910 p = &root->inode_tree.rb_node;
4913 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4915 if (ino < btrfs_ino(&entry->vfs_inode))
4916 p = &parent->rb_left;
4917 else if (ino > btrfs_ino(&entry->vfs_inode))
4918 p = &parent->rb_right;
4920 WARN_ON(!(entry->vfs_inode.i_state &
4921 (I_WILL_FREE | I_FREEING)));
4922 rb_replace_node(parent, new, &root->inode_tree);
4923 RB_CLEAR_NODE(parent);
4924 spin_unlock(&root->inode_lock);
4928 rb_link_node(new, parent, p);
4929 rb_insert_color(new, &root->inode_tree);
4930 spin_unlock(&root->inode_lock);
4933 static void inode_tree_del(struct inode *inode)
4935 struct btrfs_root *root = BTRFS_I(inode)->root;
4938 spin_lock(&root->inode_lock);
4939 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4940 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4941 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4942 empty = RB_EMPTY_ROOT(&root->inode_tree);
4944 spin_unlock(&root->inode_lock);
4946 if (empty && btrfs_root_refs(&root->root_item) == 0) {
4947 synchronize_srcu(&root->fs_info->subvol_srcu);
4948 spin_lock(&root->inode_lock);
4949 empty = RB_EMPTY_ROOT(&root->inode_tree);
4950 spin_unlock(&root->inode_lock);
4952 btrfs_add_dead_root(root);
4956 void btrfs_invalidate_inodes(struct btrfs_root *root)
4958 struct rb_node *node;
4959 struct rb_node *prev;
4960 struct btrfs_inode *entry;
4961 struct inode *inode;
4964 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
4965 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4967 spin_lock(&root->inode_lock);
4969 node = root->inode_tree.rb_node;
4973 entry = rb_entry(node, struct btrfs_inode, rb_node);
4975 if (objectid < btrfs_ino(&entry->vfs_inode))
4976 node = node->rb_left;
4977 else if (objectid > btrfs_ino(&entry->vfs_inode))
4978 node = node->rb_right;
4984 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4985 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4989 prev = rb_next(prev);
4993 entry = rb_entry(node, struct btrfs_inode, rb_node);
4994 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4995 inode = igrab(&entry->vfs_inode);
4997 spin_unlock(&root->inode_lock);
4998 if (atomic_read(&inode->i_count) > 1)
4999 d_prune_aliases(inode);
5001 * btrfs_drop_inode will have it removed from
5002 * the inode cache when its usage count
5007 spin_lock(&root->inode_lock);
5011 if (cond_resched_lock(&root->inode_lock))
5014 node = rb_next(node);
5016 spin_unlock(&root->inode_lock);
5019 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5021 struct btrfs_iget_args *args = p;
5022 inode->i_ino = args->location->objectid;
5023 memcpy(&BTRFS_I(inode)->location, args->location,
5024 sizeof(*args->location));
5025 BTRFS_I(inode)->root = args->root;
5029 static int btrfs_find_actor(struct inode *inode, void *opaque)
5031 struct btrfs_iget_args *args = opaque;
5032 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5033 args->root == BTRFS_I(inode)->root;
5036 static struct inode *btrfs_iget_locked(struct super_block *s,
5037 struct btrfs_key *location,
5038 struct btrfs_root *root)
5040 struct inode *inode;
5041 struct btrfs_iget_args args;
5042 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5044 args.location = location;
5047 inode = iget5_locked(s, hashval, btrfs_find_actor,
5048 btrfs_init_locked_inode,
5053 /* Get an inode object given its location and corresponding root.
5054 * Returns in *is_new if the inode was read from disk
5056 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5057 struct btrfs_root *root, int *new)
5059 struct inode *inode;
5061 inode = btrfs_iget_locked(s, location, root);
5063 return ERR_PTR(-ENOMEM);
5065 if (inode->i_state & I_NEW) {
5066 btrfs_read_locked_inode(inode);
5067 if (!is_bad_inode(inode)) {
5068 inode_tree_add(inode);
5069 unlock_new_inode(inode);
5073 unlock_new_inode(inode);
5075 inode = ERR_PTR(-ESTALE);
5082 static struct inode *new_simple_dir(struct super_block *s,
5083 struct btrfs_key *key,
5084 struct btrfs_root *root)
5086 struct inode *inode = new_inode(s);
5089 return ERR_PTR(-ENOMEM);
5091 BTRFS_I(inode)->root = root;
5092 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5093 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5095 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5096 inode->i_op = &btrfs_dir_ro_inode_operations;
5097 inode->i_fop = &simple_dir_operations;
5098 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5099 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5104 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5106 struct inode *inode;
5107 struct btrfs_root *root = BTRFS_I(dir)->root;
5108 struct btrfs_root *sub_root = root;
5109 struct btrfs_key location;
5113 if (dentry->d_name.len > BTRFS_NAME_LEN)
5114 return ERR_PTR(-ENAMETOOLONG);
5116 ret = btrfs_inode_by_name(dir, dentry, &location);
5118 return ERR_PTR(ret);
5120 if (location.objectid == 0)
5121 return ERR_PTR(-ENOENT);
5123 if (location.type == BTRFS_INODE_ITEM_KEY) {
5124 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5128 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5130 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5131 ret = fixup_tree_root_location(root, dir, dentry,
5132 &location, &sub_root);
5135 inode = ERR_PTR(ret);
5137 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5139 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5141 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5143 if (!IS_ERR(inode) && root != sub_root) {
5144 down_read(&root->fs_info->cleanup_work_sem);
5145 if (!(inode->i_sb->s_flags & MS_RDONLY))
5146 ret = btrfs_orphan_cleanup(sub_root);
5147 up_read(&root->fs_info->cleanup_work_sem);
5150 inode = ERR_PTR(ret);
5157 static int btrfs_dentry_delete(const struct dentry *dentry)
5159 struct btrfs_root *root;
5160 struct inode *inode = dentry->d_inode;
5162 if (!inode && !IS_ROOT(dentry))
5163 inode = dentry->d_parent->d_inode;
5166 root = BTRFS_I(inode)->root;
5167 if (btrfs_root_refs(&root->root_item) == 0)
5170 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5176 static void btrfs_dentry_release(struct dentry *dentry)
5178 kfree(dentry->d_fsdata);
5181 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5184 struct inode *inode;
5186 inode = btrfs_lookup_dentry(dir, dentry);
5187 if (IS_ERR(inode)) {
5188 if (PTR_ERR(inode) == -ENOENT)
5191 return ERR_CAST(inode);
5194 return d_materialise_unique(dentry, inode);
5197 unsigned char btrfs_filetype_table[] = {
5198 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5201 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5203 struct inode *inode = file_inode(file);
5204 struct btrfs_root *root = BTRFS_I(inode)->root;
5205 struct btrfs_item *item;
5206 struct btrfs_dir_item *di;
5207 struct btrfs_key key;
5208 struct btrfs_key found_key;
5209 struct btrfs_path *path;
5210 struct list_head ins_list;
5211 struct list_head del_list;
5213 struct extent_buffer *leaf;
5215 unsigned char d_type;
5220 int key_type = BTRFS_DIR_INDEX_KEY;
5224 int is_curr = 0; /* ctx->pos points to the current index? */
5226 /* FIXME, use a real flag for deciding about the key type */
5227 if (root->fs_info->tree_root == root)
5228 key_type = BTRFS_DIR_ITEM_KEY;
5230 if (!dir_emit_dots(file, ctx))
5233 path = btrfs_alloc_path();
5239 if (key_type == BTRFS_DIR_INDEX_KEY) {
5240 INIT_LIST_HEAD(&ins_list);
5241 INIT_LIST_HEAD(&del_list);
5242 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5245 btrfs_set_key_type(&key, key_type);
5246 key.offset = ctx->pos;
5247 key.objectid = btrfs_ino(inode);
5249 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5254 leaf = path->nodes[0];
5255 slot = path->slots[0];
5256 if (slot >= btrfs_header_nritems(leaf)) {
5257 ret = btrfs_next_leaf(root, path);
5265 item = btrfs_item_nr(slot);
5266 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5268 if (found_key.objectid != key.objectid)
5270 if (btrfs_key_type(&found_key) != key_type)
5272 if (found_key.offset < ctx->pos)
5274 if (key_type == BTRFS_DIR_INDEX_KEY &&
5275 btrfs_should_delete_dir_index(&del_list,
5279 ctx->pos = found_key.offset;
5282 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5284 di_total = btrfs_item_size(leaf, item);
5286 while (di_cur < di_total) {
5287 struct btrfs_key location;
5289 if (verify_dir_item(root, leaf, di))
5292 name_len = btrfs_dir_name_len(leaf, di);
5293 if (name_len <= sizeof(tmp_name)) {
5294 name_ptr = tmp_name;
5296 name_ptr = kmalloc(name_len, GFP_NOFS);
5302 read_extent_buffer(leaf, name_ptr,
5303 (unsigned long)(di + 1), name_len);
5305 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5306 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5309 /* is this a reference to our own snapshot? If so
5312 * In contrast to old kernels, we insert the snapshot's
5313 * dir item and dir index after it has been created, so
5314 * we won't find a reference to our own snapshot. We
5315 * still keep the following code for backward
5318 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5319 location.objectid == root->root_key.objectid) {
5323 over = !dir_emit(ctx, name_ptr, name_len,
5324 location.objectid, d_type);
5327 if (name_ptr != tmp_name)
5332 di_len = btrfs_dir_name_len(leaf, di) +
5333 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5335 di = (struct btrfs_dir_item *)((char *)di + di_len);
5341 if (key_type == BTRFS_DIR_INDEX_KEY) {
5344 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5349 /* Reached end of directory/root. Bump pos past the last item. */
5353 * Stop new entries from being returned after we return the last
5356 * New directory entries are assigned a strictly increasing
5357 * offset. This means that new entries created during readdir
5358 * are *guaranteed* to be seen in the future by that readdir.
5359 * This has broken buggy programs which operate on names as
5360 * they're returned by readdir. Until we re-use freed offsets
5361 * we have this hack to stop new entries from being returned
5362 * under the assumption that they'll never reach this huge
5365 * This is being careful not to overflow 32bit loff_t unless the
5366 * last entry requires it because doing so has broken 32bit apps
5369 if (key_type == BTRFS_DIR_INDEX_KEY) {
5370 if (ctx->pos >= INT_MAX)
5371 ctx->pos = LLONG_MAX;
5378 if (key_type == BTRFS_DIR_INDEX_KEY)
5379 btrfs_put_delayed_items(&ins_list, &del_list);
5380 btrfs_free_path(path);
5384 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5386 struct btrfs_root *root = BTRFS_I(inode)->root;
5387 struct btrfs_trans_handle *trans;
5389 bool nolock = false;
5391 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5394 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5397 if (wbc->sync_mode == WB_SYNC_ALL) {
5399 trans = btrfs_join_transaction_nolock(root);
5401 trans = btrfs_join_transaction(root);
5403 return PTR_ERR(trans);
5404 ret = btrfs_commit_transaction(trans, root);
5410 * This is somewhat expensive, updating the tree every time the
5411 * inode changes. But, it is most likely to find the inode in cache.
5412 * FIXME, needs more benchmarking...there are no reasons other than performance
5413 * to keep or drop this code.
5415 static int btrfs_dirty_inode(struct inode *inode)
5417 struct btrfs_root *root = BTRFS_I(inode)->root;
5418 struct btrfs_trans_handle *trans;
5421 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5424 trans = btrfs_join_transaction(root);
5426 return PTR_ERR(trans);
5428 ret = btrfs_update_inode(trans, root, inode);
5429 if (ret && ret == -ENOSPC) {
5430 /* whoops, lets try again with the full transaction */
5431 btrfs_end_transaction(trans, root);
5432 trans = btrfs_start_transaction(root, 1);
5434 return PTR_ERR(trans);
5436 ret = btrfs_update_inode(trans, root, inode);
5438 btrfs_end_transaction(trans, root);
5439 if (BTRFS_I(inode)->delayed_node)
5440 btrfs_balance_delayed_items(root);
5446 * This is a copy of file_update_time. We need this so we can return error on
5447 * ENOSPC for updating the inode in the case of file write and mmap writes.
5449 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5452 struct btrfs_root *root = BTRFS_I(inode)->root;
5454 if (btrfs_root_readonly(root))
5457 if (flags & S_VERSION)
5458 inode_inc_iversion(inode);
5459 if (flags & S_CTIME)
5460 inode->i_ctime = *now;
5461 if (flags & S_MTIME)
5462 inode->i_mtime = *now;
5463 if (flags & S_ATIME)
5464 inode->i_atime = *now;
5465 return btrfs_dirty_inode(inode);
5469 * find the highest existing sequence number in a directory
5470 * and then set the in-memory index_cnt variable to reflect
5471 * free sequence numbers
5473 static int btrfs_set_inode_index_count(struct inode *inode)
5475 struct btrfs_root *root = BTRFS_I(inode)->root;
5476 struct btrfs_key key, found_key;
5477 struct btrfs_path *path;
5478 struct extent_buffer *leaf;
5481 key.objectid = btrfs_ino(inode);
5482 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5483 key.offset = (u64)-1;
5485 path = btrfs_alloc_path();
5489 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5492 /* FIXME: we should be able to handle this */
5498 * MAGIC NUMBER EXPLANATION:
5499 * since we search a directory based on f_pos we have to start at 2
5500 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5501 * else has to start at 2
5503 if (path->slots[0] == 0) {
5504 BTRFS_I(inode)->index_cnt = 2;
5510 leaf = path->nodes[0];
5511 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5513 if (found_key.objectid != btrfs_ino(inode) ||
5514 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5515 BTRFS_I(inode)->index_cnt = 2;
5519 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5521 btrfs_free_path(path);
5526 * helper to find a free sequence number in a given directory. This current
5527 * code is very simple, later versions will do smarter things in the btree
5529 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5533 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5534 ret = btrfs_inode_delayed_dir_index_count(dir);
5536 ret = btrfs_set_inode_index_count(dir);
5542 *index = BTRFS_I(dir)->index_cnt;
5543 BTRFS_I(dir)->index_cnt++;
5548 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5549 struct btrfs_root *root,
5551 const char *name, int name_len,
5552 u64 ref_objectid, u64 objectid,
5553 umode_t mode, u64 *index)
5555 struct inode *inode;
5556 struct btrfs_inode_item *inode_item;
5557 struct btrfs_key *location;
5558 struct btrfs_path *path;
5559 struct btrfs_inode_ref *ref;
5560 struct btrfs_key key[2];
5562 int nitems = name ? 2 : 1;
5566 path = btrfs_alloc_path();
5568 return ERR_PTR(-ENOMEM);
5570 inode = new_inode(root->fs_info->sb);
5572 btrfs_free_path(path);
5573 return ERR_PTR(-ENOMEM);
5577 * we have to initialize this early, so we can reclaim the inode
5578 * number if we fail afterwards in this function.
5580 inode->i_ino = objectid;
5583 trace_btrfs_inode_request(dir);
5585 ret = btrfs_set_inode_index(dir, index);
5587 btrfs_free_path(path);
5589 return ERR_PTR(ret);
5595 * index_cnt is ignored for everything but a dir,
5596 * btrfs_get_inode_index_count has an explanation for the magic
5599 BTRFS_I(inode)->index_cnt = 2;
5600 BTRFS_I(inode)->dir_index = *index;
5601 BTRFS_I(inode)->root = root;
5602 BTRFS_I(inode)->generation = trans->transid;
5603 inode->i_generation = BTRFS_I(inode)->generation;
5606 * We could have gotten an inode number from somebody who was fsynced
5607 * and then removed in this same transaction, so let's just set full
5608 * sync since it will be a full sync anyway and this will blow away the
5609 * old info in the log.
5611 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5613 key[0].objectid = objectid;
5614 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5617 sizes[0] = sizeof(struct btrfs_inode_item);
5621 * Start new inodes with an inode_ref. This is slightly more
5622 * efficient for small numbers of hard links since they will
5623 * be packed into one item. Extended refs will kick in if we
5624 * add more hard links than can fit in the ref item.
5626 key[1].objectid = objectid;
5627 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5628 key[1].offset = ref_objectid;
5630 sizes[1] = name_len + sizeof(*ref);
5633 path->leave_spinning = 1;
5634 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5638 inode_init_owner(inode, dir, mode);
5639 inode_set_bytes(inode, 0);
5640 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5641 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5642 struct btrfs_inode_item);
5643 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5644 sizeof(*inode_item));
5645 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5648 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5649 struct btrfs_inode_ref);
5650 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5651 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5652 ptr = (unsigned long)(ref + 1);
5653 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5656 btrfs_mark_buffer_dirty(path->nodes[0]);
5657 btrfs_free_path(path);
5659 location = &BTRFS_I(inode)->location;
5660 location->objectid = objectid;
5661 location->offset = 0;
5662 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5664 btrfs_inherit_iflags(inode, dir);
5666 if (S_ISREG(mode)) {
5667 if (btrfs_test_opt(root, NODATASUM))
5668 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5669 if (btrfs_test_opt(root, NODATACOW))
5670 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5671 BTRFS_INODE_NODATASUM;
5674 btrfs_insert_inode_hash(inode);
5675 inode_tree_add(inode);
5677 trace_btrfs_inode_new(inode);
5678 btrfs_set_inode_last_trans(trans, inode);
5680 btrfs_update_root_times(trans, root);
5682 ret = btrfs_inode_inherit_props(trans, inode, dir);
5684 btrfs_err(root->fs_info,
5685 "error inheriting props for ino %llu (root %llu): %d",
5686 btrfs_ino(inode), root->root_key.objectid, ret);
5691 BTRFS_I(dir)->index_cnt--;
5692 btrfs_free_path(path);
5694 return ERR_PTR(ret);
5697 static inline u8 btrfs_inode_type(struct inode *inode)
5699 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5703 * utility function to add 'inode' into 'parent_inode' with
5704 * a give name and a given sequence number.
5705 * if 'add_backref' is true, also insert a backref from the
5706 * inode to the parent directory.
5708 int btrfs_add_link(struct btrfs_trans_handle *trans,
5709 struct inode *parent_inode, struct inode *inode,
5710 const char *name, int name_len, int add_backref, u64 index)
5713 struct btrfs_key key;
5714 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5715 u64 ino = btrfs_ino(inode);
5716 u64 parent_ino = btrfs_ino(parent_inode);
5718 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5719 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5722 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5726 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5727 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5728 key.objectid, root->root_key.objectid,
5729 parent_ino, index, name, name_len);
5730 } else if (add_backref) {
5731 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5735 /* Nothing to clean up yet */
5739 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5741 btrfs_inode_type(inode), index);
5742 if (ret == -EEXIST || ret == -EOVERFLOW)
5745 btrfs_abort_transaction(trans, root, ret);
5749 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5751 inode_inc_iversion(parent_inode);
5752 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5753 ret = btrfs_update_inode(trans, root, parent_inode);
5755 btrfs_abort_transaction(trans, root, ret);
5759 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5762 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5763 key.objectid, root->root_key.objectid,
5764 parent_ino, &local_index, name, name_len);
5766 } else if (add_backref) {
5770 err = btrfs_del_inode_ref(trans, root, name, name_len,
5771 ino, parent_ino, &local_index);
5776 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5777 struct inode *dir, struct dentry *dentry,
5778 struct inode *inode, int backref, u64 index)
5780 int err = btrfs_add_link(trans, dir, inode,
5781 dentry->d_name.name, dentry->d_name.len,
5788 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5789 umode_t mode, dev_t rdev)
5791 struct btrfs_trans_handle *trans;
5792 struct btrfs_root *root = BTRFS_I(dir)->root;
5793 struct inode *inode = NULL;
5799 if (!new_valid_dev(rdev))
5803 * 2 for inode item and ref
5805 * 1 for xattr if selinux is on
5807 trans = btrfs_start_transaction(root, 5);
5809 return PTR_ERR(trans);
5811 err = btrfs_find_free_ino(root, &objectid);
5815 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5816 dentry->d_name.len, btrfs_ino(dir), objectid,
5818 if (IS_ERR(inode)) {
5819 err = PTR_ERR(inode);
5823 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5830 * If the active LSM wants to access the inode during
5831 * d_instantiate it needs these. Smack checks to see
5832 * if the filesystem supports xattrs by looking at the
5836 inode->i_op = &btrfs_special_inode_operations;
5837 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5841 init_special_inode(inode, inode->i_mode, rdev);
5842 btrfs_update_inode(trans, root, inode);
5843 d_instantiate(dentry, inode);
5846 btrfs_end_transaction(trans, root);
5847 btrfs_balance_delayed_items(root);
5848 btrfs_btree_balance_dirty(root);
5850 inode_dec_link_count(inode);
5856 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5857 umode_t mode, bool excl)
5859 struct btrfs_trans_handle *trans;
5860 struct btrfs_root *root = BTRFS_I(dir)->root;
5861 struct inode *inode = NULL;
5862 int drop_inode_on_err = 0;
5868 * 2 for inode item and ref
5870 * 1 for xattr if selinux is on
5872 trans = btrfs_start_transaction(root, 5);
5874 return PTR_ERR(trans);
5876 err = btrfs_find_free_ino(root, &objectid);
5880 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5881 dentry->d_name.len, btrfs_ino(dir), objectid,
5883 if (IS_ERR(inode)) {
5884 err = PTR_ERR(inode);
5887 drop_inode_on_err = 1;
5889 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5893 err = btrfs_update_inode(trans, root, inode);
5898 * If the active LSM wants to access the inode during
5899 * d_instantiate it needs these. Smack checks to see
5900 * if the filesystem supports xattrs by looking at the
5903 inode->i_fop = &btrfs_file_operations;
5904 inode->i_op = &btrfs_file_inode_operations;
5906 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5910 inode->i_mapping->a_ops = &btrfs_aops;
5911 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5912 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5913 d_instantiate(dentry, inode);
5916 btrfs_end_transaction(trans, root);
5917 if (err && drop_inode_on_err) {
5918 inode_dec_link_count(inode);
5921 btrfs_balance_delayed_items(root);
5922 btrfs_btree_balance_dirty(root);
5926 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5927 struct dentry *dentry)
5929 struct btrfs_trans_handle *trans;
5930 struct btrfs_root *root = BTRFS_I(dir)->root;
5931 struct inode *inode = old_dentry->d_inode;
5936 /* do not allow sys_link's with other subvols of the same device */
5937 if (root->objectid != BTRFS_I(inode)->root->objectid)
5940 if (inode->i_nlink >= BTRFS_LINK_MAX)
5943 err = btrfs_set_inode_index(dir, &index);
5948 * 2 items for inode and inode ref
5949 * 2 items for dir items
5950 * 1 item for parent inode
5952 trans = btrfs_start_transaction(root, 5);
5953 if (IS_ERR(trans)) {
5954 err = PTR_ERR(trans);
5958 /* There are several dir indexes for this inode, clear the cache. */
5959 BTRFS_I(inode)->dir_index = 0ULL;
5961 inode_inc_iversion(inode);
5962 inode->i_ctime = CURRENT_TIME;
5964 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5966 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5971 struct dentry *parent = dentry->d_parent;
5972 err = btrfs_update_inode(trans, root, inode);
5975 if (inode->i_nlink == 1) {
5977 * If new hard link count is 1, it's a file created
5978 * with open(2) O_TMPFILE flag.
5980 err = btrfs_orphan_del(trans, inode);
5984 d_instantiate(dentry, inode);
5985 btrfs_log_new_name(trans, inode, NULL, parent);
5988 btrfs_end_transaction(trans, root);
5989 btrfs_balance_delayed_items(root);
5992 inode_dec_link_count(inode);
5995 btrfs_btree_balance_dirty(root);
5999 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6001 struct inode *inode = NULL;
6002 struct btrfs_trans_handle *trans;
6003 struct btrfs_root *root = BTRFS_I(dir)->root;
6005 int drop_on_err = 0;
6010 * 2 items for inode and ref
6011 * 2 items for dir items
6012 * 1 for xattr if selinux is on
6014 trans = btrfs_start_transaction(root, 5);
6016 return PTR_ERR(trans);
6018 err = btrfs_find_free_ino(root, &objectid);
6022 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6023 dentry->d_name.len, btrfs_ino(dir), objectid,
6024 S_IFDIR | mode, &index);
6025 if (IS_ERR(inode)) {
6026 err = PTR_ERR(inode);
6032 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6036 inode->i_op = &btrfs_dir_inode_operations;
6037 inode->i_fop = &btrfs_dir_file_operations;
6039 btrfs_i_size_write(inode, 0);
6040 err = btrfs_update_inode(trans, root, inode);
6044 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6045 dentry->d_name.len, 0, index);
6049 d_instantiate(dentry, inode);
6053 btrfs_end_transaction(trans, root);
6056 btrfs_balance_delayed_items(root);
6057 btrfs_btree_balance_dirty(root);
6061 /* helper for btfs_get_extent. Given an existing extent in the tree,
6062 * and an extent that you want to insert, deal with overlap and insert
6063 * the new extent into the tree.
6065 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6066 struct extent_map *existing,
6067 struct extent_map *em,
6068 u64 map_start, u64 map_len)
6072 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6073 start_diff = map_start - em->start;
6074 em->start = map_start;
6076 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6077 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6078 em->block_start += start_diff;
6079 em->block_len -= start_diff;
6081 return add_extent_mapping(em_tree, em, 0);
6084 static noinline int uncompress_inline(struct btrfs_path *path,
6085 struct inode *inode, struct page *page,
6086 size_t pg_offset, u64 extent_offset,
6087 struct btrfs_file_extent_item *item)
6090 struct extent_buffer *leaf = path->nodes[0];
6093 unsigned long inline_size;
6097 WARN_ON(pg_offset != 0);
6098 compress_type = btrfs_file_extent_compression(leaf, item);
6099 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6100 inline_size = btrfs_file_extent_inline_item_len(leaf,
6101 btrfs_item_nr(path->slots[0]));
6102 tmp = kmalloc(inline_size, GFP_NOFS);
6105 ptr = btrfs_file_extent_inline_start(item);
6107 read_extent_buffer(leaf, tmp, ptr, inline_size);
6109 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6110 ret = btrfs_decompress(compress_type, tmp, page,
6111 extent_offset, inline_size, max_size);
6117 * a bit scary, this does extent mapping from logical file offset to the disk.
6118 * the ugly parts come from merging extents from the disk with the in-ram
6119 * representation. This gets more complex because of the data=ordered code,
6120 * where the in-ram extents might be locked pending data=ordered completion.
6122 * This also copies inline extents directly into the page.
6125 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6126 size_t pg_offset, u64 start, u64 len,
6132 u64 extent_start = 0;
6134 u64 objectid = btrfs_ino(inode);
6136 struct btrfs_path *path = NULL;
6137 struct btrfs_root *root = BTRFS_I(inode)->root;
6138 struct btrfs_file_extent_item *item;
6139 struct extent_buffer *leaf;
6140 struct btrfs_key found_key;
6141 struct extent_map *em = NULL;
6142 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6143 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6144 struct btrfs_trans_handle *trans = NULL;
6148 read_lock(&em_tree->lock);
6149 em = lookup_extent_mapping(em_tree, start, len);
6151 em->bdev = root->fs_info->fs_devices->latest_bdev;
6152 read_unlock(&em_tree->lock);
6155 if (em->start > start || em->start + em->len <= start)
6156 free_extent_map(em);
6157 else if (em->block_start == EXTENT_MAP_INLINE && page)
6158 free_extent_map(em);
6162 em = alloc_extent_map();
6167 em->bdev = root->fs_info->fs_devices->latest_bdev;
6168 em->start = EXTENT_MAP_HOLE;
6169 em->orig_start = EXTENT_MAP_HOLE;
6171 em->block_len = (u64)-1;
6174 path = btrfs_alloc_path();
6180 * Chances are we'll be called again, so go ahead and do
6186 ret = btrfs_lookup_file_extent(trans, root, path,
6187 objectid, start, trans != NULL);
6194 if (path->slots[0] == 0)
6199 leaf = path->nodes[0];
6200 item = btrfs_item_ptr(leaf, path->slots[0],
6201 struct btrfs_file_extent_item);
6202 /* are we inside the extent that was found? */
6203 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6204 found_type = btrfs_key_type(&found_key);
6205 if (found_key.objectid != objectid ||
6206 found_type != BTRFS_EXTENT_DATA_KEY) {
6208 * If we backup past the first extent we want to move forward
6209 * and see if there is an extent in front of us, otherwise we'll
6210 * say there is a hole for our whole search range which can
6217 found_type = btrfs_file_extent_type(leaf, item);
6218 extent_start = found_key.offset;
6219 compress_type = btrfs_file_extent_compression(leaf, item);
6220 if (found_type == BTRFS_FILE_EXTENT_REG ||
6221 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6222 extent_end = extent_start +
6223 btrfs_file_extent_num_bytes(leaf, item);
6224 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6226 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6227 extent_end = ALIGN(extent_start + size, root->sectorsize);
6230 if (start >= extent_end) {
6232 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6233 ret = btrfs_next_leaf(root, path);
6240 leaf = path->nodes[0];
6242 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6243 if (found_key.objectid != objectid ||
6244 found_key.type != BTRFS_EXTENT_DATA_KEY)
6246 if (start + len <= found_key.offset)
6249 em->orig_start = start;
6250 em->len = found_key.offset - start;
6254 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6255 if (found_type == BTRFS_FILE_EXTENT_REG ||
6256 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6257 em->start = extent_start;
6258 em->len = extent_end - extent_start;
6259 em->orig_start = extent_start -
6260 btrfs_file_extent_offset(leaf, item);
6261 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6263 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6265 em->block_start = EXTENT_MAP_HOLE;
6268 if (compress_type != BTRFS_COMPRESS_NONE) {
6269 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6270 em->compress_type = compress_type;
6271 em->block_start = bytenr;
6272 em->block_len = em->orig_block_len;
6274 bytenr += btrfs_file_extent_offset(leaf, item);
6275 em->block_start = bytenr;
6276 em->block_len = em->len;
6277 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6278 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6281 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6285 size_t extent_offset;
6288 em->block_start = EXTENT_MAP_INLINE;
6289 if (!page || create) {
6290 em->start = extent_start;
6291 em->len = extent_end - extent_start;
6295 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6296 extent_offset = page_offset(page) + pg_offset - extent_start;
6297 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6298 size - extent_offset);
6299 em->start = extent_start + extent_offset;
6300 em->len = ALIGN(copy_size, root->sectorsize);
6301 em->orig_block_len = em->len;
6302 em->orig_start = em->start;
6303 if (compress_type) {
6304 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6305 em->compress_type = compress_type;
6307 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6308 if (create == 0 && !PageUptodate(page)) {
6309 if (btrfs_file_extent_compression(leaf, item) !=
6310 BTRFS_COMPRESS_NONE) {
6311 ret = uncompress_inline(path, inode, page,
6313 extent_offset, item);
6320 read_extent_buffer(leaf, map + pg_offset, ptr,
6322 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6323 memset(map + pg_offset + copy_size, 0,
6324 PAGE_CACHE_SIZE - pg_offset -
6329 flush_dcache_page(page);
6330 } else if (create && PageUptodate(page)) {
6334 free_extent_map(em);
6337 btrfs_release_path(path);
6338 trans = btrfs_join_transaction(root);
6341 return ERR_CAST(trans);
6345 write_extent_buffer(leaf, map + pg_offset, ptr,
6348 btrfs_mark_buffer_dirty(leaf);
6350 set_extent_uptodate(io_tree, em->start,
6351 extent_map_end(em) - 1, NULL, GFP_NOFS);
6354 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6358 em->orig_start = start;
6361 em->block_start = EXTENT_MAP_HOLE;
6362 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6364 btrfs_release_path(path);
6365 if (em->start > start || extent_map_end(em) <= start) {
6366 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6367 em->start, em->len, start, len);
6373 write_lock(&em_tree->lock);
6374 ret = add_extent_mapping(em_tree, em, 0);
6375 /* it is possible that someone inserted the extent into the tree
6376 * while we had the lock dropped. It is also possible that
6377 * an overlapping map exists in the tree
6379 if (ret == -EEXIST) {
6380 struct extent_map *existing;
6384 existing = lookup_extent_mapping(em_tree, start, len);
6385 if (existing && (existing->start > start ||
6386 existing->start + existing->len <= start)) {
6387 free_extent_map(existing);
6391 existing = lookup_extent_mapping(em_tree, em->start,
6394 err = merge_extent_mapping(em_tree, existing,
6397 free_extent_map(existing);
6399 free_extent_map(em);
6404 free_extent_map(em);
6408 free_extent_map(em);
6413 write_unlock(&em_tree->lock);
6416 trace_btrfs_get_extent(root, em);
6419 btrfs_free_path(path);
6421 ret = btrfs_end_transaction(trans, root);
6426 free_extent_map(em);
6427 return ERR_PTR(err);
6429 BUG_ON(!em); /* Error is always set */
6433 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6434 size_t pg_offset, u64 start, u64 len,
6437 struct extent_map *em;
6438 struct extent_map *hole_em = NULL;
6439 u64 range_start = start;
6445 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6452 * - a pre-alloc extent,
6453 * there might actually be delalloc bytes behind it.
6455 if (em->block_start != EXTENT_MAP_HOLE &&
6456 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6462 /* check to see if we've wrapped (len == -1 or similar) */
6471 /* ok, we didn't find anything, lets look for delalloc */
6472 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6473 end, len, EXTENT_DELALLOC, 1);
6474 found_end = range_start + found;
6475 if (found_end < range_start)
6476 found_end = (u64)-1;
6479 * we didn't find anything useful, return
6480 * the original results from get_extent()
6482 if (range_start > end || found_end <= start) {
6488 /* adjust the range_start to make sure it doesn't
6489 * go backwards from the start they passed in
6491 range_start = max(start, range_start);
6492 found = found_end - range_start;
6495 u64 hole_start = start;
6498 em = alloc_extent_map();
6504 * when btrfs_get_extent can't find anything it
6505 * returns one huge hole
6507 * make sure what it found really fits our range, and
6508 * adjust to make sure it is based on the start from
6512 u64 calc_end = extent_map_end(hole_em);
6514 if (calc_end <= start || (hole_em->start > end)) {
6515 free_extent_map(hole_em);
6518 hole_start = max(hole_em->start, start);
6519 hole_len = calc_end - hole_start;
6523 if (hole_em && range_start > hole_start) {
6524 /* our hole starts before our delalloc, so we
6525 * have to return just the parts of the hole
6526 * that go until the delalloc starts
6528 em->len = min(hole_len,
6529 range_start - hole_start);
6530 em->start = hole_start;
6531 em->orig_start = hole_start;
6533 * don't adjust block start at all,
6534 * it is fixed at EXTENT_MAP_HOLE
6536 em->block_start = hole_em->block_start;
6537 em->block_len = hole_len;
6538 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6539 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6541 em->start = range_start;
6543 em->orig_start = range_start;
6544 em->block_start = EXTENT_MAP_DELALLOC;
6545 em->block_len = found;
6547 } else if (hole_em) {
6552 free_extent_map(hole_em);
6554 free_extent_map(em);
6555 return ERR_PTR(err);
6560 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6563 struct btrfs_root *root = BTRFS_I(inode)->root;
6564 struct extent_map *em;
6565 struct btrfs_key ins;
6569 alloc_hint = get_extent_allocation_hint(inode, start, len);
6570 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
6571 alloc_hint, &ins, 1);
6573 return ERR_PTR(ret);
6575 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6576 ins.offset, ins.offset, ins.offset, 0);
6578 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6582 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6583 ins.offset, ins.offset, 0);
6585 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6586 free_extent_map(em);
6587 return ERR_PTR(ret);
6594 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6595 * block must be cow'd
6597 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6598 u64 *orig_start, u64 *orig_block_len,
6601 struct btrfs_trans_handle *trans;
6602 struct btrfs_path *path;
6604 struct extent_buffer *leaf;
6605 struct btrfs_root *root = BTRFS_I(inode)->root;
6606 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6607 struct btrfs_file_extent_item *fi;
6608 struct btrfs_key key;
6615 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6617 path = btrfs_alloc_path();
6621 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
6626 slot = path->slots[0];
6629 /* can't find the item, must cow */
6636 leaf = path->nodes[0];
6637 btrfs_item_key_to_cpu(leaf, &key, slot);
6638 if (key.objectid != btrfs_ino(inode) ||
6639 key.type != BTRFS_EXTENT_DATA_KEY) {
6640 /* not our file or wrong item type, must cow */
6644 if (key.offset > offset) {
6645 /* Wrong offset, must cow */
6649 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6650 found_type = btrfs_file_extent_type(leaf, fi);
6651 if (found_type != BTRFS_FILE_EXTENT_REG &&
6652 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6653 /* not a regular extent, must cow */
6657 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6660 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6661 if (extent_end <= offset)
6664 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6665 if (disk_bytenr == 0)
6668 if (btrfs_file_extent_compression(leaf, fi) ||
6669 btrfs_file_extent_encryption(leaf, fi) ||
6670 btrfs_file_extent_other_encoding(leaf, fi))
6673 backref_offset = btrfs_file_extent_offset(leaf, fi);
6676 *orig_start = key.offset - backref_offset;
6677 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6678 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6681 if (btrfs_extent_readonly(root, disk_bytenr))
6684 num_bytes = min(offset + *len, extent_end) - offset;
6685 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6688 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
6689 ret = test_range_bit(io_tree, offset, range_end,
6690 EXTENT_DELALLOC, 0, NULL);
6697 btrfs_release_path(path);
6700 * look for other files referencing this extent, if we
6701 * find any we must cow
6703 trans = btrfs_join_transaction(root);
6704 if (IS_ERR(trans)) {
6709 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6710 key.offset - backref_offset, disk_bytenr);
6711 btrfs_end_transaction(trans, root);
6718 * adjust disk_bytenr and num_bytes to cover just the bytes
6719 * in this extent we are about to write. If there
6720 * are any csums in that range we have to cow in order
6721 * to keep the csums correct
6723 disk_bytenr += backref_offset;
6724 disk_bytenr += offset - key.offset;
6725 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6728 * all of the above have passed, it is safe to overwrite this extent
6734 btrfs_free_path(path);
6738 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6739 struct extent_state **cached_state, int writing)
6741 struct btrfs_ordered_extent *ordered;
6745 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6748 * We're concerned with the entire range that we're going to be
6749 * doing DIO to, so we need to make sure theres no ordered
6750 * extents in this range.
6752 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6753 lockend - lockstart + 1);
6756 * We need to make sure there are no buffered pages in this
6757 * range either, we could have raced between the invalidate in
6758 * generic_file_direct_write and locking the extent. The
6759 * invalidate needs to happen so that reads after a write do not
6762 if (!ordered && (!writing ||
6763 !test_range_bit(&BTRFS_I(inode)->io_tree,
6764 lockstart, lockend, EXTENT_UPTODATE, 0,
6768 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6769 cached_state, GFP_NOFS);
6772 btrfs_start_ordered_extent(inode, ordered, 1);
6773 btrfs_put_ordered_extent(ordered);
6775 /* Screw you mmap */
6776 ret = filemap_write_and_wait_range(inode->i_mapping,
6783 * If we found a page that couldn't be invalidated just
6784 * fall back to buffered.
6786 ret = invalidate_inode_pages2_range(inode->i_mapping,
6787 lockstart >> PAGE_CACHE_SHIFT,
6788 lockend >> PAGE_CACHE_SHIFT);
6799 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6800 u64 len, u64 orig_start,
6801 u64 block_start, u64 block_len,
6802 u64 orig_block_len, u64 ram_bytes,
6805 struct extent_map_tree *em_tree;
6806 struct extent_map *em;
6807 struct btrfs_root *root = BTRFS_I(inode)->root;
6810 em_tree = &BTRFS_I(inode)->extent_tree;
6811 em = alloc_extent_map();
6813 return ERR_PTR(-ENOMEM);
6816 em->orig_start = orig_start;
6817 em->mod_start = start;
6820 em->block_len = block_len;
6821 em->block_start = block_start;
6822 em->bdev = root->fs_info->fs_devices->latest_bdev;
6823 em->orig_block_len = orig_block_len;
6824 em->ram_bytes = ram_bytes;
6825 em->generation = -1;
6826 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6827 if (type == BTRFS_ORDERED_PREALLOC)
6828 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6831 btrfs_drop_extent_cache(inode, em->start,
6832 em->start + em->len - 1, 0);
6833 write_lock(&em_tree->lock);
6834 ret = add_extent_mapping(em_tree, em, 1);
6835 write_unlock(&em_tree->lock);
6836 } while (ret == -EEXIST);
6839 free_extent_map(em);
6840 return ERR_PTR(ret);
6847 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6848 struct buffer_head *bh_result, int create)
6850 struct extent_map *em;
6851 struct btrfs_root *root = BTRFS_I(inode)->root;
6852 struct extent_state *cached_state = NULL;
6853 u64 start = iblock << inode->i_blkbits;
6854 u64 lockstart, lockend;
6855 u64 len = bh_result->b_size;
6856 int unlock_bits = EXTENT_LOCKED;
6860 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6862 len = min_t(u64, len, root->sectorsize);
6865 lockend = start + len - 1;
6868 * If this errors out it's because we couldn't invalidate pagecache for
6869 * this range and we need to fallback to buffered.
6871 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6874 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6881 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6882 * io. INLINE is special, and we could probably kludge it in here, but
6883 * it's still buffered so for safety lets just fall back to the generic
6886 * For COMPRESSED we _have_ to read the entire extent in so we can
6887 * decompress it, so there will be buffering required no matter what we
6888 * do, so go ahead and fallback to buffered.
6890 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6891 * to buffered IO. Don't blame me, this is the price we pay for using
6894 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6895 em->block_start == EXTENT_MAP_INLINE) {
6896 free_extent_map(em);
6901 /* Just a good old fashioned hole, return */
6902 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6903 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6904 free_extent_map(em);
6909 * We don't allocate a new extent in the following cases
6911 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6913 * 2) The extent is marked as PREALLOC. We're good to go here and can
6914 * just use the extent.
6918 len = min(len, em->len - (start - em->start));
6919 lockstart = start + len;
6923 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6924 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6925 em->block_start != EXTENT_MAP_HOLE)) {
6928 u64 block_start, orig_start, orig_block_len, ram_bytes;
6930 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6931 type = BTRFS_ORDERED_PREALLOC;
6933 type = BTRFS_ORDERED_NOCOW;
6934 len = min(len, em->len - (start - em->start));
6935 block_start = em->block_start + (start - em->start);
6937 if (can_nocow_extent(inode, start, &len, &orig_start,
6938 &orig_block_len, &ram_bytes) == 1) {
6939 if (type == BTRFS_ORDERED_PREALLOC) {
6940 free_extent_map(em);
6941 em = create_pinned_em(inode, start, len,
6950 ret = btrfs_add_ordered_extent_dio(inode, start,
6951 block_start, len, len, type);
6953 free_extent_map(em);
6961 * this will cow the extent, reset the len in case we changed
6964 len = bh_result->b_size;
6965 free_extent_map(em);
6966 em = btrfs_new_extent_direct(inode, start, len);
6971 len = min(len, em->len - (start - em->start));
6973 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6975 bh_result->b_size = len;
6976 bh_result->b_bdev = em->bdev;
6977 set_buffer_mapped(bh_result);
6979 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6980 set_buffer_new(bh_result);
6983 * Need to update the i_size under the extent lock so buffered
6984 * readers will get the updated i_size when we unlock.
6986 if (start + len > i_size_read(inode))
6987 i_size_write(inode, start + len);
6989 spin_lock(&BTRFS_I(inode)->lock);
6990 BTRFS_I(inode)->outstanding_extents++;
6991 spin_unlock(&BTRFS_I(inode)->lock);
6993 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6994 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6995 &cached_state, GFP_NOFS);
7000 * In the case of write we need to clear and unlock the entire range,
7001 * in the case of read we need to unlock only the end area that we
7002 * aren't using if there is any left over space.
7004 if (lockstart < lockend) {
7005 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7006 lockend, unlock_bits, 1, 0,
7007 &cached_state, GFP_NOFS);
7009 free_extent_state(cached_state);
7012 free_extent_map(em);
7017 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7018 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7022 static void btrfs_endio_direct_read(struct bio *bio, int err)
7024 struct btrfs_dio_private *dip = bio->bi_private;
7025 struct bio_vec *bvec;
7026 struct inode *inode = dip->inode;
7027 struct btrfs_root *root = BTRFS_I(inode)->root;
7028 struct bio *dio_bio;
7029 u32 *csums = (u32 *)dip->csum;
7033 start = dip->logical_offset;
7034 bio_for_each_segment_all(bvec, bio, i) {
7035 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
7036 struct page *page = bvec->bv_page;
7039 unsigned long flags;
7041 local_irq_save(flags);
7042 kaddr = kmap_atomic(page);
7043 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
7044 csum, bvec->bv_len);
7045 btrfs_csum_final(csum, (char *)&csum);
7046 kunmap_atomic(kaddr);
7047 local_irq_restore(flags);
7049 flush_dcache_page(bvec->bv_page);
7050 if (csum != csums[i]) {
7051 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
7052 btrfs_ino(inode), start, csum,
7058 start += bvec->bv_len;
7061 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7062 dip->logical_offset + dip->bytes - 1);
7063 dio_bio = dip->dio_bio;
7067 /* If we had a csum failure make sure to clear the uptodate flag */
7069 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7070 dio_end_io(dio_bio, err);
7074 static void btrfs_endio_direct_write(struct bio *bio, int err)
7076 struct btrfs_dio_private *dip = bio->bi_private;
7077 struct inode *inode = dip->inode;
7078 struct btrfs_root *root = BTRFS_I(inode)->root;
7079 struct btrfs_ordered_extent *ordered = NULL;
7080 u64 ordered_offset = dip->logical_offset;
7081 u64 ordered_bytes = dip->bytes;
7082 struct bio *dio_bio;
7088 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7090 ordered_bytes, !err);
7094 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL, NULL);
7095 btrfs_queue_work(root->fs_info->endio_write_workers,
7099 * our bio might span multiple ordered extents. If we haven't
7100 * completed the accounting for the whole dio, go back and try again
7102 if (ordered_offset < dip->logical_offset + dip->bytes) {
7103 ordered_bytes = dip->logical_offset + dip->bytes -
7109 dio_bio = dip->dio_bio;
7113 /* If we had an error make sure to clear the uptodate flag */
7115 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7116 dio_end_io(dio_bio, err);
7120 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7121 struct bio *bio, int mirror_num,
7122 unsigned long bio_flags, u64 offset)
7125 struct btrfs_root *root = BTRFS_I(inode)->root;
7126 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7127 BUG_ON(ret); /* -ENOMEM */
7131 static void btrfs_end_dio_bio(struct bio *bio, int err)
7133 struct btrfs_dio_private *dip = bio->bi_private;
7136 btrfs_err(BTRFS_I(dip->inode)->root->fs_info,
7137 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7138 btrfs_ino(dip->inode), bio->bi_rw,
7139 (unsigned long long)bio->bi_iter.bi_sector,
7140 bio->bi_iter.bi_size, err);
7144 * before atomic variable goto zero, we must make sure
7145 * dip->errors is perceived to be set.
7147 smp_mb__before_atomic_dec();
7150 /* if there are more bios still pending for this dio, just exit */
7151 if (!atomic_dec_and_test(&dip->pending_bios))
7155 bio_io_error(dip->orig_bio);
7157 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7158 bio_endio(dip->orig_bio, 0);
7164 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7165 u64 first_sector, gfp_t gfp_flags)
7167 int nr_vecs = bio_get_nr_vecs(bdev);
7168 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7171 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7172 int rw, u64 file_offset, int skip_sum,
7175 struct btrfs_dio_private *dip = bio->bi_private;
7176 int write = rw & REQ_WRITE;
7177 struct btrfs_root *root = BTRFS_I(inode)->root;
7181 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7186 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7194 if (write && async_submit) {
7195 ret = btrfs_wq_submit_bio(root->fs_info,
7196 inode, rw, bio, 0, 0,
7198 __btrfs_submit_bio_start_direct_io,
7199 __btrfs_submit_bio_done);
7203 * If we aren't doing async submit, calculate the csum of the
7206 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7209 } else if (!skip_sum) {
7210 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
7217 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7223 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7226 struct inode *inode = dip->inode;
7227 struct btrfs_root *root = BTRFS_I(inode)->root;
7229 struct bio *orig_bio = dip->orig_bio;
7230 struct bio_vec *bvec = orig_bio->bi_io_vec;
7231 u64 start_sector = orig_bio->bi_iter.bi_sector;
7232 u64 file_offset = dip->logical_offset;
7237 int async_submit = 0;
7239 map_length = orig_bio->bi_iter.bi_size;
7240 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7241 &map_length, NULL, 0);
7247 if (map_length >= orig_bio->bi_iter.bi_size) {
7252 /* async crcs make it difficult to collect full stripe writes. */
7253 if (btrfs_get_alloc_profile(root, 1) &
7254 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7259 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7262 bio->bi_private = dip;
7263 bio->bi_end_io = btrfs_end_dio_bio;
7264 atomic_inc(&dip->pending_bios);
7266 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7267 if (unlikely(map_length < submit_len + bvec->bv_len ||
7268 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7269 bvec->bv_offset) < bvec->bv_len)) {
7271 * inc the count before we submit the bio so
7272 * we know the end IO handler won't happen before
7273 * we inc the count. Otherwise, the dip might get freed
7274 * before we're done setting it up
7276 atomic_inc(&dip->pending_bios);
7277 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7278 file_offset, skip_sum,
7282 atomic_dec(&dip->pending_bios);
7286 start_sector += submit_len >> 9;
7287 file_offset += submit_len;
7292 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7293 start_sector, GFP_NOFS);
7296 bio->bi_private = dip;
7297 bio->bi_end_io = btrfs_end_dio_bio;
7299 map_length = orig_bio->bi_iter.bi_size;
7300 ret = btrfs_map_block(root->fs_info, rw,
7302 &map_length, NULL, 0);
7308 submit_len += bvec->bv_len;
7315 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7324 * before atomic variable goto zero, we must
7325 * make sure dip->errors is perceived to be set.
7327 smp_mb__before_atomic_dec();
7328 if (atomic_dec_and_test(&dip->pending_bios))
7329 bio_io_error(dip->orig_bio);
7331 /* bio_end_io() will handle error, so we needn't return it */
7335 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7336 struct inode *inode, loff_t file_offset)
7338 struct btrfs_root *root = BTRFS_I(inode)->root;
7339 struct btrfs_dio_private *dip;
7343 int write = rw & REQ_WRITE;
7347 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7349 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7355 if (!skip_sum && !write) {
7356 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7357 sum_len = dio_bio->bi_iter.bi_size >>
7358 inode->i_sb->s_blocksize_bits;
7359 sum_len *= csum_size;
7364 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7370 dip->private = dio_bio->bi_private;
7372 dip->logical_offset = file_offset;
7373 dip->bytes = dio_bio->bi_iter.bi_size;
7374 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7375 io_bio->bi_private = dip;
7377 dip->orig_bio = io_bio;
7378 dip->dio_bio = dio_bio;
7379 atomic_set(&dip->pending_bios, 0);
7382 io_bio->bi_end_io = btrfs_endio_direct_write;
7384 io_bio->bi_end_io = btrfs_endio_direct_read;
7386 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7395 * If this is a write, we need to clean up the reserved space and kill
7396 * the ordered extent.
7399 struct btrfs_ordered_extent *ordered;
7400 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7401 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7402 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7403 btrfs_free_reserved_extent(root, ordered->start,
7405 btrfs_put_ordered_extent(ordered);
7406 btrfs_put_ordered_extent(ordered);
7408 bio_endio(dio_bio, ret);
7411 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7412 const struct iovec *iov, loff_t offset,
7413 unsigned long nr_segs)
7419 unsigned blocksize_mask = root->sectorsize - 1;
7420 ssize_t retval = -EINVAL;
7421 loff_t end = offset;
7423 if (offset & blocksize_mask)
7426 /* Check the memory alignment. Blocks cannot straddle pages */
7427 for (seg = 0; seg < nr_segs; seg++) {
7428 addr = (unsigned long)iov[seg].iov_base;
7429 size = iov[seg].iov_len;
7431 if ((addr & blocksize_mask) || (size & blocksize_mask))
7434 /* If this is a write we don't need to check anymore */
7439 * Check to make sure we don't have duplicate iov_base's in this
7440 * iovec, if so return EINVAL, otherwise we'll get csum errors
7441 * when reading back.
7443 for (i = seg + 1; i < nr_segs; i++) {
7444 if (iov[seg].iov_base == iov[i].iov_base)
7453 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7454 const struct iovec *iov, loff_t offset,
7455 unsigned long nr_segs)
7457 struct file *file = iocb->ki_filp;
7458 struct inode *inode = file->f_mapping->host;
7462 bool relock = false;
7465 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7469 atomic_inc(&inode->i_dio_count);
7470 smp_mb__after_atomic_inc();
7473 * The generic stuff only does filemap_write_and_wait_range, which
7474 * isn't enough if we've written compressed pages to this area, so
7475 * we need to flush the dirty pages again to make absolutely sure
7476 * that any outstanding dirty pages are on disk.
7478 count = iov_length(iov, nr_segs);
7479 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
7480 &BTRFS_I(inode)->runtime_flags))
7481 filemap_fdatawrite_range(inode->i_mapping, offset, count);
7485 * If the write DIO is beyond the EOF, we need update
7486 * the isize, but it is protected by i_mutex. So we can
7487 * not unlock the i_mutex at this case.
7489 if (offset + count <= inode->i_size) {
7490 mutex_unlock(&inode->i_mutex);
7493 ret = btrfs_delalloc_reserve_space(inode, count);
7496 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7497 &BTRFS_I(inode)->runtime_flags))) {
7498 inode_dio_done(inode);
7499 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7503 ret = __blockdev_direct_IO(rw, iocb, inode,
7504 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7505 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7506 btrfs_submit_direct, flags);
7508 if (ret < 0 && ret != -EIOCBQUEUED)
7509 btrfs_delalloc_release_space(inode, count);
7510 else if (ret >= 0 && (size_t)ret < count)
7511 btrfs_delalloc_release_space(inode,
7512 count - (size_t)ret);
7514 btrfs_delalloc_release_metadata(inode, 0);
7518 inode_dio_done(inode);
7520 mutex_lock(&inode->i_mutex);
7525 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7527 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7528 __u64 start, __u64 len)
7532 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7536 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7539 int btrfs_readpage(struct file *file, struct page *page)
7541 struct extent_io_tree *tree;
7542 tree = &BTRFS_I(page->mapping->host)->io_tree;
7543 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7546 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7548 struct extent_io_tree *tree;
7551 if (current->flags & PF_MEMALLOC) {
7552 redirty_page_for_writepage(wbc, page);
7556 tree = &BTRFS_I(page->mapping->host)->io_tree;
7557 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7560 static int btrfs_writepages(struct address_space *mapping,
7561 struct writeback_control *wbc)
7563 struct extent_io_tree *tree;
7565 tree = &BTRFS_I(mapping->host)->io_tree;
7566 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7570 btrfs_readpages(struct file *file, struct address_space *mapping,
7571 struct list_head *pages, unsigned nr_pages)
7573 struct extent_io_tree *tree;
7574 tree = &BTRFS_I(mapping->host)->io_tree;
7575 return extent_readpages(tree, mapping, pages, nr_pages,
7578 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7580 struct extent_io_tree *tree;
7581 struct extent_map_tree *map;
7584 tree = &BTRFS_I(page->mapping->host)->io_tree;
7585 map = &BTRFS_I(page->mapping->host)->extent_tree;
7586 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7588 ClearPagePrivate(page);
7589 set_page_private(page, 0);
7590 page_cache_release(page);
7595 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7597 if (PageWriteback(page) || PageDirty(page))
7599 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7602 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7603 unsigned int length)
7605 struct inode *inode = page->mapping->host;
7606 struct extent_io_tree *tree;
7607 struct btrfs_ordered_extent *ordered;
7608 struct extent_state *cached_state = NULL;
7609 u64 page_start = page_offset(page);
7610 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7611 int inode_evicting = inode->i_state & I_FREEING;
7614 * we have the page locked, so new writeback can't start,
7615 * and the dirty bit won't be cleared while we are here.
7617 * Wait for IO on this page so that we can safely clear
7618 * the PagePrivate2 bit and do ordered accounting
7620 wait_on_page_writeback(page);
7622 tree = &BTRFS_I(inode)->io_tree;
7624 btrfs_releasepage(page, GFP_NOFS);
7628 if (!inode_evicting)
7629 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7630 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7633 * IO on this page will never be started, so we need
7634 * to account for any ordered extents now
7636 if (!inode_evicting)
7637 clear_extent_bit(tree, page_start, page_end,
7638 EXTENT_DIRTY | EXTENT_DELALLOC |
7639 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7640 EXTENT_DEFRAG, 1, 0, &cached_state,
7643 * whoever cleared the private bit is responsible
7644 * for the finish_ordered_io
7646 if (TestClearPagePrivate2(page)) {
7647 struct btrfs_ordered_inode_tree *tree;
7650 tree = &BTRFS_I(inode)->ordered_tree;
7652 spin_lock_irq(&tree->lock);
7653 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
7654 new_len = page_start - ordered->file_offset;
7655 if (new_len < ordered->truncated_len)
7656 ordered->truncated_len = new_len;
7657 spin_unlock_irq(&tree->lock);
7659 if (btrfs_dec_test_ordered_pending(inode, &ordered,
7661 PAGE_CACHE_SIZE, 1))
7662 btrfs_finish_ordered_io(ordered);
7664 btrfs_put_ordered_extent(ordered);
7665 if (!inode_evicting) {
7666 cached_state = NULL;
7667 lock_extent_bits(tree, page_start, page_end, 0,
7672 if (!inode_evicting) {
7673 clear_extent_bit(tree, page_start, page_end,
7674 EXTENT_LOCKED | EXTENT_DIRTY |
7675 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7676 EXTENT_DEFRAG, 1, 1,
7677 &cached_state, GFP_NOFS);
7679 __btrfs_releasepage(page, GFP_NOFS);
7682 ClearPageChecked(page);
7683 if (PagePrivate(page)) {
7684 ClearPagePrivate(page);
7685 set_page_private(page, 0);
7686 page_cache_release(page);
7691 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7692 * called from a page fault handler when a page is first dirtied. Hence we must
7693 * be careful to check for EOF conditions here. We set the page up correctly
7694 * for a written page which means we get ENOSPC checking when writing into
7695 * holes and correct delalloc and unwritten extent mapping on filesystems that
7696 * support these features.
7698 * We are not allowed to take the i_mutex here so we have to play games to
7699 * protect against truncate races as the page could now be beyond EOF. Because
7700 * vmtruncate() writes the inode size before removing pages, once we have the
7701 * page lock we can determine safely if the page is beyond EOF. If it is not
7702 * beyond EOF, then the page is guaranteed safe against truncation until we
7705 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7707 struct page *page = vmf->page;
7708 struct inode *inode = file_inode(vma->vm_file);
7709 struct btrfs_root *root = BTRFS_I(inode)->root;
7710 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7711 struct btrfs_ordered_extent *ordered;
7712 struct extent_state *cached_state = NULL;
7714 unsigned long zero_start;
7721 sb_start_pagefault(inode->i_sb);
7722 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7724 ret = file_update_time(vma->vm_file);
7730 else /* -ENOSPC, -EIO, etc */
7731 ret = VM_FAULT_SIGBUS;
7737 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7740 size = i_size_read(inode);
7741 page_start = page_offset(page);
7742 page_end = page_start + PAGE_CACHE_SIZE - 1;
7744 if ((page->mapping != inode->i_mapping) ||
7745 (page_start >= size)) {
7746 /* page got truncated out from underneath us */
7749 wait_on_page_writeback(page);
7751 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7752 set_page_extent_mapped(page);
7755 * we can't set the delalloc bits if there are pending ordered
7756 * extents. Drop our locks and wait for them to finish
7758 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7760 unlock_extent_cached(io_tree, page_start, page_end,
7761 &cached_state, GFP_NOFS);
7763 btrfs_start_ordered_extent(inode, ordered, 1);
7764 btrfs_put_ordered_extent(ordered);
7769 * XXX - page_mkwrite gets called every time the page is dirtied, even
7770 * if it was already dirty, so for space accounting reasons we need to
7771 * clear any delalloc bits for the range we are fixing to save. There
7772 * is probably a better way to do this, but for now keep consistent with
7773 * prepare_pages in the normal write path.
7775 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7776 EXTENT_DIRTY | EXTENT_DELALLOC |
7777 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7778 0, 0, &cached_state, GFP_NOFS);
7780 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7783 unlock_extent_cached(io_tree, page_start, page_end,
7784 &cached_state, GFP_NOFS);
7785 ret = VM_FAULT_SIGBUS;
7790 /* page is wholly or partially inside EOF */
7791 if (page_start + PAGE_CACHE_SIZE > size)
7792 zero_start = size & ~PAGE_CACHE_MASK;
7794 zero_start = PAGE_CACHE_SIZE;
7796 if (zero_start != PAGE_CACHE_SIZE) {
7798 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7799 flush_dcache_page(page);
7802 ClearPageChecked(page);
7803 set_page_dirty(page);
7804 SetPageUptodate(page);
7806 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7807 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7808 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7810 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7814 sb_end_pagefault(inode->i_sb);
7815 return VM_FAULT_LOCKED;
7819 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7821 sb_end_pagefault(inode->i_sb);
7825 static int btrfs_truncate(struct inode *inode)
7827 struct btrfs_root *root = BTRFS_I(inode)->root;
7828 struct btrfs_block_rsv *rsv;
7831 struct btrfs_trans_handle *trans;
7832 u64 mask = root->sectorsize - 1;
7833 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7835 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
7841 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7842 * 3 things going on here
7844 * 1) We need to reserve space for our orphan item and the space to
7845 * delete our orphan item. Lord knows we don't want to have a dangling
7846 * orphan item because we didn't reserve space to remove it.
7848 * 2) We need to reserve space to update our inode.
7850 * 3) We need to have something to cache all the space that is going to
7851 * be free'd up by the truncate operation, but also have some slack
7852 * space reserved in case it uses space during the truncate (thank you
7853 * very much snapshotting).
7855 * And we need these to all be seperate. The fact is we can use alot of
7856 * space doing the truncate, and we have no earthly idea how much space
7857 * we will use, so we need the truncate reservation to be seperate so it
7858 * doesn't end up using space reserved for updating the inode or
7859 * removing the orphan item. We also need to be able to stop the
7860 * transaction and start a new one, which means we need to be able to
7861 * update the inode several times, and we have no idea of knowing how
7862 * many times that will be, so we can't just reserve 1 item for the
7863 * entirety of the opration, so that has to be done seperately as well.
7864 * Then there is the orphan item, which does indeed need to be held on
7865 * to for the whole operation, and we need nobody to touch this reserved
7866 * space except the orphan code.
7868 * So that leaves us with
7870 * 1) root->orphan_block_rsv - for the orphan deletion.
7871 * 2) rsv - for the truncate reservation, which we will steal from the
7872 * transaction reservation.
7873 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7874 * updating the inode.
7876 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7879 rsv->size = min_size;
7883 * 1 for the truncate slack space
7884 * 1 for updating the inode.
7886 trans = btrfs_start_transaction(root, 2);
7887 if (IS_ERR(trans)) {
7888 err = PTR_ERR(trans);
7892 /* Migrate the slack space for the truncate to our reserve */
7893 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7898 * setattr is responsible for setting the ordered_data_close flag,
7899 * but that is only tested during the last file release. That
7900 * could happen well after the next commit, leaving a great big
7901 * window where new writes may get lost if someone chooses to write
7902 * to this file after truncating to zero
7904 * The inode doesn't have any dirty data here, and so if we commit
7905 * this is a noop. If someone immediately starts writing to the inode
7906 * it is very likely we'll catch some of their writes in this
7907 * transaction, and the commit will find this file on the ordered
7908 * data list with good things to send down.
7910 * This is a best effort solution, there is still a window where
7911 * using truncate to replace the contents of the file will
7912 * end up with a zero length file after a crash.
7914 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7915 &BTRFS_I(inode)->runtime_flags))
7916 btrfs_add_ordered_operation(trans, root, inode);
7919 * So if we truncate and then write and fsync we normally would just
7920 * write the extents that changed, which is a problem if we need to
7921 * first truncate that entire inode. So set this flag so we write out
7922 * all of the extents in the inode to the sync log so we're completely
7925 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7926 trans->block_rsv = rsv;
7929 ret = btrfs_truncate_inode_items(trans, root, inode,
7931 BTRFS_EXTENT_DATA_KEY);
7932 if (ret != -ENOSPC) {
7937 trans->block_rsv = &root->fs_info->trans_block_rsv;
7938 ret = btrfs_update_inode(trans, root, inode);
7944 btrfs_end_transaction(trans, root);
7945 btrfs_btree_balance_dirty(root);
7947 trans = btrfs_start_transaction(root, 2);
7948 if (IS_ERR(trans)) {
7949 ret = err = PTR_ERR(trans);
7954 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7956 BUG_ON(ret); /* shouldn't happen */
7957 trans->block_rsv = rsv;
7960 if (ret == 0 && inode->i_nlink > 0) {
7961 trans->block_rsv = root->orphan_block_rsv;
7962 ret = btrfs_orphan_del(trans, inode);
7968 trans->block_rsv = &root->fs_info->trans_block_rsv;
7969 ret = btrfs_update_inode(trans, root, inode);
7973 ret = btrfs_end_transaction(trans, root);
7974 btrfs_btree_balance_dirty(root);
7978 btrfs_free_block_rsv(root, rsv);
7987 * create a new subvolume directory/inode (helper for the ioctl).
7989 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7990 struct btrfs_root *new_root,
7991 struct btrfs_root *parent_root,
7994 struct inode *inode;
7998 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7999 new_dirid, new_dirid,
8000 S_IFDIR | (~current_umask() & S_IRWXUGO),
8003 return PTR_ERR(inode);
8004 inode->i_op = &btrfs_dir_inode_operations;
8005 inode->i_fop = &btrfs_dir_file_operations;
8007 set_nlink(inode, 1);
8008 btrfs_i_size_write(inode, 0);
8010 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8012 btrfs_err(new_root->fs_info,
8013 "error inheriting subvolume %llu properties: %d\n",
8014 new_root->root_key.objectid, err);
8016 err = btrfs_update_inode(trans, new_root, inode);
8022 struct inode *btrfs_alloc_inode(struct super_block *sb)
8024 struct btrfs_inode *ei;
8025 struct inode *inode;
8027 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8034 ei->last_sub_trans = 0;
8035 ei->logged_trans = 0;
8036 ei->delalloc_bytes = 0;
8037 ei->disk_i_size = 0;
8040 ei->index_cnt = (u64)-1;
8042 ei->last_unlink_trans = 0;
8043 ei->last_log_commit = 0;
8045 spin_lock_init(&ei->lock);
8046 ei->outstanding_extents = 0;
8047 ei->reserved_extents = 0;
8049 ei->runtime_flags = 0;
8050 ei->force_compress = BTRFS_COMPRESS_NONE;
8052 ei->delayed_node = NULL;
8054 inode = &ei->vfs_inode;
8055 extent_map_tree_init(&ei->extent_tree);
8056 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8057 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8058 ei->io_tree.track_uptodate = 1;
8059 ei->io_failure_tree.track_uptodate = 1;
8060 atomic_set(&ei->sync_writers, 0);
8061 mutex_init(&ei->log_mutex);
8062 mutex_init(&ei->delalloc_mutex);
8063 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8064 INIT_LIST_HEAD(&ei->delalloc_inodes);
8065 INIT_LIST_HEAD(&ei->ordered_operations);
8066 RB_CLEAR_NODE(&ei->rb_node);
8071 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8072 void btrfs_test_destroy_inode(struct inode *inode)
8074 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8075 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8079 static void btrfs_i_callback(struct rcu_head *head)
8081 struct inode *inode = container_of(head, struct inode, i_rcu);
8082 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8085 void btrfs_destroy_inode(struct inode *inode)
8087 struct btrfs_ordered_extent *ordered;
8088 struct btrfs_root *root = BTRFS_I(inode)->root;
8090 WARN_ON(!hlist_empty(&inode->i_dentry));
8091 WARN_ON(inode->i_data.nrpages);
8092 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8093 WARN_ON(BTRFS_I(inode)->reserved_extents);
8094 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8095 WARN_ON(BTRFS_I(inode)->csum_bytes);
8098 * This can happen where we create an inode, but somebody else also
8099 * created the same inode and we need to destroy the one we already
8106 * Make sure we're properly removed from the ordered operation
8110 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
8111 spin_lock(&root->fs_info->ordered_root_lock);
8112 list_del_init(&BTRFS_I(inode)->ordered_operations);
8113 spin_unlock(&root->fs_info->ordered_root_lock);
8116 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8117 &BTRFS_I(inode)->runtime_flags)) {
8118 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8120 atomic_dec(&root->orphan_inodes);
8124 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8128 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8129 ordered->file_offset, ordered->len);
8130 btrfs_remove_ordered_extent(inode, ordered);
8131 btrfs_put_ordered_extent(ordered);
8132 btrfs_put_ordered_extent(ordered);
8135 inode_tree_del(inode);
8136 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8138 call_rcu(&inode->i_rcu, btrfs_i_callback);
8141 int btrfs_drop_inode(struct inode *inode)
8143 struct btrfs_root *root = BTRFS_I(inode)->root;
8148 /* the snap/subvol tree is on deleting */
8149 if (btrfs_root_refs(&root->root_item) == 0)
8152 return generic_drop_inode(inode);
8155 static void init_once(void *foo)
8157 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8159 inode_init_once(&ei->vfs_inode);
8162 void btrfs_destroy_cachep(void)
8165 * Make sure all delayed rcu free inodes are flushed before we
8169 if (btrfs_inode_cachep)
8170 kmem_cache_destroy(btrfs_inode_cachep);
8171 if (btrfs_trans_handle_cachep)
8172 kmem_cache_destroy(btrfs_trans_handle_cachep);
8173 if (btrfs_transaction_cachep)
8174 kmem_cache_destroy(btrfs_transaction_cachep);
8175 if (btrfs_path_cachep)
8176 kmem_cache_destroy(btrfs_path_cachep);
8177 if (btrfs_free_space_cachep)
8178 kmem_cache_destroy(btrfs_free_space_cachep);
8179 if (btrfs_delalloc_work_cachep)
8180 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8183 int btrfs_init_cachep(void)
8185 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8186 sizeof(struct btrfs_inode), 0,
8187 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8188 if (!btrfs_inode_cachep)
8191 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8192 sizeof(struct btrfs_trans_handle), 0,
8193 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8194 if (!btrfs_trans_handle_cachep)
8197 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8198 sizeof(struct btrfs_transaction), 0,
8199 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8200 if (!btrfs_transaction_cachep)
8203 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8204 sizeof(struct btrfs_path), 0,
8205 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8206 if (!btrfs_path_cachep)
8209 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8210 sizeof(struct btrfs_free_space), 0,
8211 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8212 if (!btrfs_free_space_cachep)
8215 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8216 sizeof(struct btrfs_delalloc_work), 0,
8217 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8219 if (!btrfs_delalloc_work_cachep)
8224 btrfs_destroy_cachep();
8228 static int btrfs_getattr(struct vfsmount *mnt,
8229 struct dentry *dentry, struct kstat *stat)
8232 struct inode *inode = dentry->d_inode;
8233 u32 blocksize = inode->i_sb->s_blocksize;
8235 generic_fillattr(inode, stat);
8236 stat->dev = BTRFS_I(inode)->root->anon_dev;
8237 stat->blksize = PAGE_CACHE_SIZE;
8239 spin_lock(&BTRFS_I(inode)->lock);
8240 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8241 spin_unlock(&BTRFS_I(inode)->lock);
8242 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8243 ALIGN(delalloc_bytes, blocksize)) >> 9;
8247 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8248 struct inode *new_dir, struct dentry *new_dentry)
8250 struct btrfs_trans_handle *trans;
8251 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8252 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8253 struct inode *new_inode = new_dentry->d_inode;
8254 struct inode *old_inode = old_dentry->d_inode;
8255 struct timespec ctime = CURRENT_TIME;
8259 u64 old_ino = btrfs_ino(old_inode);
8261 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8264 /* we only allow rename subvolume link between subvolumes */
8265 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8268 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8269 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8272 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8273 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8277 /* check for collisions, even if the name isn't there */
8278 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
8279 new_dentry->d_name.name,
8280 new_dentry->d_name.len);
8283 if (ret == -EEXIST) {
8285 * eexist without a new_inode */
8286 if (WARN_ON(!new_inode)) {
8290 /* maybe -EOVERFLOW */
8297 * we're using rename to replace one file with another.
8298 * and the replacement file is large. Start IO on it now so
8299 * we don't add too much work to the end of the transaction
8301 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8302 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8303 filemap_flush(old_inode->i_mapping);
8305 /* close the racy window with snapshot create/destroy ioctl */
8306 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8307 down_read(&root->fs_info->subvol_sem);
8309 * We want to reserve the absolute worst case amount of items. So if
8310 * both inodes are subvols and we need to unlink them then that would
8311 * require 4 item modifications, but if they are both normal inodes it
8312 * would require 5 item modifications, so we'll assume their normal
8313 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8314 * should cover the worst case number of items we'll modify.
8316 trans = btrfs_start_transaction(root, 11);
8317 if (IS_ERR(trans)) {
8318 ret = PTR_ERR(trans);
8323 btrfs_record_root_in_trans(trans, dest);
8325 ret = btrfs_set_inode_index(new_dir, &index);
8329 BTRFS_I(old_inode)->dir_index = 0ULL;
8330 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8331 /* force full log commit if subvolume involved. */
8332 btrfs_set_log_full_commit(root->fs_info, trans);
8334 ret = btrfs_insert_inode_ref(trans, dest,
8335 new_dentry->d_name.name,
8336 new_dentry->d_name.len,
8338 btrfs_ino(new_dir), index);
8342 * this is an ugly little race, but the rename is required
8343 * to make sure that if we crash, the inode is either at the
8344 * old name or the new one. pinning the log transaction lets
8345 * us make sure we don't allow a log commit to come in after
8346 * we unlink the name but before we add the new name back in.
8348 btrfs_pin_log_trans(root);
8351 * make sure the inode gets flushed if it is replacing
8354 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8355 btrfs_add_ordered_operation(trans, root, old_inode);
8357 inode_inc_iversion(old_dir);
8358 inode_inc_iversion(new_dir);
8359 inode_inc_iversion(old_inode);
8360 old_dir->i_ctime = old_dir->i_mtime = ctime;
8361 new_dir->i_ctime = new_dir->i_mtime = ctime;
8362 old_inode->i_ctime = ctime;
8364 if (old_dentry->d_parent != new_dentry->d_parent)
8365 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8367 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8368 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8369 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8370 old_dentry->d_name.name,
8371 old_dentry->d_name.len);
8373 ret = __btrfs_unlink_inode(trans, root, old_dir,
8374 old_dentry->d_inode,
8375 old_dentry->d_name.name,
8376 old_dentry->d_name.len);
8378 ret = btrfs_update_inode(trans, root, old_inode);
8381 btrfs_abort_transaction(trans, root, ret);
8386 inode_inc_iversion(new_inode);
8387 new_inode->i_ctime = CURRENT_TIME;
8388 if (unlikely(btrfs_ino(new_inode) ==
8389 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8390 root_objectid = BTRFS_I(new_inode)->location.objectid;
8391 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8393 new_dentry->d_name.name,
8394 new_dentry->d_name.len);
8395 BUG_ON(new_inode->i_nlink == 0);
8397 ret = btrfs_unlink_inode(trans, dest, new_dir,
8398 new_dentry->d_inode,
8399 new_dentry->d_name.name,
8400 new_dentry->d_name.len);
8402 if (!ret && new_inode->i_nlink == 0)
8403 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8405 btrfs_abort_transaction(trans, root, ret);
8410 ret = btrfs_add_link(trans, new_dir, old_inode,
8411 new_dentry->d_name.name,
8412 new_dentry->d_name.len, 0, index);
8414 btrfs_abort_transaction(trans, root, ret);
8418 if (old_inode->i_nlink == 1)
8419 BTRFS_I(old_inode)->dir_index = index;
8421 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8422 struct dentry *parent = new_dentry->d_parent;
8423 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8424 btrfs_end_log_trans(root);
8427 btrfs_end_transaction(trans, root);
8429 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8430 up_read(&root->fs_info->subvol_sem);
8435 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8437 struct btrfs_delalloc_work *delalloc_work;
8438 struct inode *inode;
8440 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8442 inode = delalloc_work->inode;
8443 if (delalloc_work->wait) {
8444 btrfs_wait_ordered_range(inode, 0, (u64)-1);
8446 filemap_flush(inode->i_mapping);
8447 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8448 &BTRFS_I(inode)->runtime_flags))
8449 filemap_flush(inode->i_mapping);
8452 if (delalloc_work->delay_iput)
8453 btrfs_add_delayed_iput(inode);
8456 complete(&delalloc_work->completion);
8459 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8460 int wait, int delay_iput)
8462 struct btrfs_delalloc_work *work;
8464 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8468 init_completion(&work->completion);
8469 INIT_LIST_HEAD(&work->list);
8470 work->inode = inode;
8472 work->delay_iput = delay_iput;
8473 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
8478 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8480 wait_for_completion(&work->completion);
8481 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8485 * some fairly slow code that needs optimization. This walks the list
8486 * of all the inodes with pending delalloc and forces them to disk.
8488 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
8491 struct btrfs_inode *binode;
8492 struct inode *inode;
8493 struct btrfs_delalloc_work *work, *next;
8494 struct list_head works;
8495 struct list_head splice;
8498 INIT_LIST_HEAD(&works);
8499 INIT_LIST_HEAD(&splice);
8501 mutex_lock(&root->delalloc_mutex);
8502 spin_lock(&root->delalloc_lock);
8503 list_splice_init(&root->delalloc_inodes, &splice);
8504 while (!list_empty(&splice)) {
8505 binode = list_entry(splice.next, struct btrfs_inode,
8508 list_move_tail(&binode->delalloc_inodes,
8509 &root->delalloc_inodes);
8510 inode = igrab(&binode->vfs_inode);
8512 cond_resched_lock(&root->delalloc_lock);
8515 spin_unlock(&root->delalloc_lock);
8517 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8518 if (unlikely(!work)) {
8520 btrfs_add_delayed_iput(inode);
8526 list_add_tail(&work->list, &works);
8527 btrfs_queue_work(root->fs_info->flush_workers,
8530 if (nr != -1 && ret >= nr)
8533 spin_lock(&root->delalloc_lock);
8535 spin_unlock(&root->delalloc_lock);
8538 list_for_each_entry_safe(work, next, &works, list) {
8539 list_del_init(&work->list);
8540 btrfs_wait_and_free_delalloc_work(work);
8543 if (!list_empty_careful(&splice)) {
8544 spin_lock(&root->delalloc_lock);
8545 list_splice_tail(&splice, &root->delalloc_inodes);
8546 spin_unlock(&root->delalloc_lock);
8548 mutex_unlock(&root->delalloc_mutex);
8552 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8556 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
8559 ret = __start_delalloc_inodes(root, delay_iput, -1);
8563 * the filemap_flush will queue IO into the worker threads, but
8564 * we have to make sure the IO is actually started and that
8565 * ordered extents get created before we return
8567 atomic_inc(&root->fs_info->async_submit_draining);
8568 while (atomic_read(&root->fs_info->nr_async_submits) ||
8569 atomic_read(&root->fs_info->async_delalloc_pages)) {
8570 wait_event(root->fs_info->async_submit_wait,
8571 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8572 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8574 atomic_dec(&root->fs_info->async_submit_draining);
8578 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
8581 struct btrfs_root *root;
8582 struct list_head splice;
8585 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
8588 INIT_LIST_HEAD(&splice);
8590 mutex_lock(&fs_info->delalloc_root_mutex);
8591 spin_lock(&fs_info->delalloc_root_lock);
8592 list_splice_init(&fs_info->delalloc_roots, &splice);
8593 while (!list_empty(&splice) && nr) {
8594 root = list_first_entry(&splice, struct btrfs_root,
8596 root = btrfs_grab_fs_root(root);
8598 list_move_tail(&root->delalloc_root,
8599 &fs_info->delalloc_roots);
8600 spin_unlock(&fs_info->delalloc_root_lock);
8602 ret = __start_delalloc_inodes(root, delay_iput, nr);
8603 btrfs_put_fs_root(root);
8611 spin_lock(&fs_info->delalloc_root_lock);
8613 spin_unlock(&fs_info->delalloc_root_lock);
8616 atomic_inc(&fs_info->async_submit_draining);
8617 while (atomic_read(&fs_info->nr_async_submits) ||
8618 atomic_read(&fs_info->async_delalloc_pages)) {
8619 wait_event(fs_info->async_submit_wait,
8620 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8621 atomic_read(&fs_info->async_delalloc_pages) == 0));
8623 atomic_dec(&fs_info->async_submit_draining);
8625 if (!list_empty_careful(&splice)) {
8626 spin_lock(&fs_info->delalloc_root_lock);
8627 list_splice_tail(&splice, &fs_info->delalloc_roots);
8628 spin_unlock(&fs_info->delalloc_root_lock);
8630 mutex_unlock(&fs_info->delalloc_root_mutex);
8634 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8635 const char *symname)
8637 struct btrfs_trans_handle *trans;
8638 struct btrfs_root *root = BTRFS_I(dir)->root;
8639 struct btrfs_path *path;
8640 struct btrfs_key key;
8641 struct inode *inode = NULL;
8649 struct btrfs_file_extent_item *ei;
8650 struct extent_buffer *leaf;
8652 name_len = strlen(symname);
8653 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8654 return -ENAMETOOLONG;
8657 * 2 items for inode item and ref
8658 * 2 items for dir items
8659 * 1 item for xattr if selinux is on
8661 trans = btrfs_start_transaction(root, 5);
8663 return PTR_ERR(trans);
8665 err = btrfs_find_free_ino(root, &objectid);
8669 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8670 dentry->d_name.len, btrfs_ino(dir), objectid,
8671 S_IFLNK|S_IRWXUGO, &index);
8672 if (IS_ERR(inode)) {
8673 err = PTR_ERR(inode);
8677 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8684 * If the active LSM wants to access the inode during
8685 * d_instantiate it needs these. Smack checks to see
8686 * if the filesystem supports xattrs by looking at the
8689 inode->i_fop = &btrfs_file_operations;
8690 inode->i_op = &btrfs_file_inode_operations;
8692 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8696 inode->i_mapping->a_ops = &btrfs_aops;
8697 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8698 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8703 path = btrfs_alloc_path();
8709 key.objectid = btrfs_ino(inode);
8711 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8712 datasize = btrfs_file_extent_calc_inline_size(name_len);
8713 err = btrfs_insert_empty_item(trans, root, path, &key,
8717 btrfs_free_path(path);
8720 leaf = path->nodes[0];
8721 ei = btrfs_item_ptr(leaf, path->slots[0],
8722 struct btrfs_file_extent_item);
8723 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8724 btrfs_set_file_extent_type(leaf, ei,
8725 BTRFS_FILE_EXTENT_INLINE);
8726 btrfs_set_file_extent_encryption(leaf, ei, 0);
8727 btrfs_set_file_extent_compression(leaf, ei, 0);
8728 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8729 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8731 ptr = btrfs_file_extent_inline_start(ei);
8732 write_extent_buffer(leaf, symname, ptr, name_len);
8733 btrfs_mark_buffer_dirty(leaf);
8734 btrfs_free_path(path);
8736 inode->i_op = &btrfs_symlink_inode_operations;
8737 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8738 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8739 inode_set_bytes(inode, name_len);
8740 btrfs_i_size_write(inode, name_len);
8741 err = btrfs_update_inode(trans, root, inode);
8747 d_instantiate(dentry, inode);
8748 btrfs_end_transaction(trans, root);
8750 inode_dec_link_count(inode);
8753 btrfs_btree_balance_dirty(root);
8757 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8758 u64 start, u64 num_bytes, u64 min_size,
8759 loff_t actual_len, u64 *alloc_hint,
8760 struct btrfs_trans_handle *trans)
8762 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8763 struct extent_map *em;
8764 struct btrfs_root *root = BTRFS_I(inode)->root;
8765 struct btrfs_key ins;
8766 u64 cur_offset = start;
8770 bool own_trans = true;
8774 while (num_bytes > 0) {
8776 trans = btrfs_start_transaction(root, 3);
8777 if (IS_ERR(trans)) {
8778 ret = PTR_ERR(trans);
8783 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8784 cur_bytes = max(cur_bytes, min_size);
8785 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
8786 *alloc_hint, &ins, 1);
8789 btrfs_end_transaction(trans, root);
8793 ret = insert_reserved_file_extent(trans, inode,
8794 cur_offset, ins.objectid,
8795 ins.offset, ins.offset,
8796 ins.offset, 0, 0, 0,
8797 BTRFS_FILE_EXTENT_PREALLOC);
8799 btrfs_free_reserved_extent(root, ins.objectid,
8801 btrfs_abort_transaction(trans, root, ret);
8803 btrfs_end_transaction(trans, root);
8806 btrfs_drop_extent_cache(inode, cur_offset,
8807 cur_offset + ins.offset -1, 0);
8809 em = alloc_extent_map();
8811 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8812 &BTRFS_I(inode)->runtime_flags);
8816 em->start = cur_offset;
8817 em->orig_start = cur_offset;
8818 em->len = ins.offset;
8819 em->block_start = ins.objectid;
8820 em->block_len = ins.offset;
8821 em->orig_block_len = ins.offset;
8822 em->ram_bytes = ins.offset;
8823 em->bdev = root->fs_info->fs_devices->latest_bdev;
8824 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8825 em->generation = trans->transid;
8828 write_lock(&em_tree->lock);
8829 ret = add_extent_mapping(em_tree, em, 1);
8830 write_unlock(&em_tree->lock);
8833 btrfs_drop_extent_cache(inode, cur_offset,
8834 cur_offset + ins.offset - 1,
8837 free_extent_map(em);
8839 num_bytes -= ins.offset;
8840 cur_offset += ins.offset;
8841 *alloc_hint = ins.objectid + ins.offset;
8843 inode_inc_iversion(inode);
8844 inode->i_ctime = CURRENT_TIME;
8845 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8846 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8847 (actual_len > inode->i_size) &&
8848 (cur_offset > inode->i_size)) {
8849 if (cur_offset > actual_len)
8850 i_size = actual_len;
8852 i_size = cur_offset;
8853 i_size_write(inode, i_size);
8854 btrfs_ordered_update_i_size(inode, i_size, NULL);
8857 ret = btrfs_update_inode(trans, root, inode);
8860 btrfs_abort_transaction(trans, root, ret);
8862 btrfs_end_transaction(trans, root);
8867 btrfs_end_transaction(trans, root);
8872 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8873 u64 start, u64 num_bytes, u64 min_size,
8874 loff_t actual_len, u64 *alloc_hint)
8876 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8877 min_size, actual_len, alloc_hint,
8881 int btrfs_prealloc_file_range_trans(struct inode *inode,
8882 struct btrfs_trans_handle *trans, int mode,
8883 u64 start, u64 num_bytes, u64 min_size,
8884 loff_t actual_len, u64 *alloc_hint)
8886 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8887 min_size, actual_len, alloc_hint, trans);
8890 static int btrfs_set_page_dirty(struct page *page)
8892 return __set_page_dirty_nobuffers(page);
8895 static int btrfs_permission(struct inode *inode, int mask)
8897 struct btrfs_root *root = BTRFS_I(inode)->root;
8898 umode_t mode = inode->i_mode;
8900 if (mask & MAY_WRITE &&
8901 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8902 if (btrfs_root_readonly(root))
8904 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8907 return generic_permission(inode, mask);
8910 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
8912 struct btrfs_trans_handle *trans;
8913 struct btrfs_root *root = BTRFS_I(dir)->root;
8914 struct inode *inode = NULL;
8920 * 5 units required for adding orphan entry
8922 trans = btrfs_start_transaction(root, 5);
8924 return PTR_ERR(trans);
8926 ret = btrfs_find_free_ino(root, &objectid);
8930 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
8931 btrfs_ino(dir), objectid, mode, &index);
8932 if (IS_ERR(inode)) {
8933 ret = PTR_ERR(inode);
8938 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
8942 ret = btrfs_update_inode(trans, root, inode);
8946 inode->i_fop = &btrfs_file_operations;
8947 inode->i_op = &btrfs_file_inode_operations;
8949 inode->i_mapping->a_ops = &btrfs_aops;
8950 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8951 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8953 ret = btrfs_orphan_add(trans, inode);
8957 d_tmpfile(dentry, inode);
8958 mark_inode_dirty(inode);
8961 btrfs_end_transaction(trans, root);
8964 btrfs_balance_delayed_items(root);
8965 btrfs_btree_balance_dirty(root);
8970 static const struct inode_operations btrfs_dir_inode_operations = {
8971 .getattr = btrfs_getattr,
8972 .lookup = btrfs_lookup,
8973 .create = btrfs_create,
8974 .unlink = btrfs_unlink,
8976 .mkdir = btrfs_mkdir,
8977 .rmdir = btrfs_rmdir,
8978 .rename = btrfs_rename,
8979 .symlink = btrfs_symlink,
8980 .setattr = btrfs_setattr,
8981 .mknod = btrfs_mknod,
8982 .setxattr = btrfs_setxattr,
8983 .getxattr = btrfs_getxattr,
8984 .listxattr = btrfs_listxattr,
8985 .removexattr = btrfs_removexattr,
8986 .permission = btrfs_permission,
8987 .get_acl = btrfs_get_acl,
8988 .set_acl = btrfs_set_acl,
8989 .update_time = btrfs_update_time,
8990 .tmpfile = btrfs_tmpfile,
8992 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8993 .lookup = btrfs_lookup,
8994 .permission = btrfs_permission,
8995 .get_acl = btrfs_get_acl,
8996 .set_acl = btrfs_set_acl,
8997 .update_time = btrfs_update_time,
9000 static const struct file_operations btrfs_dir_file_operations = {
9001 .llseek = generic_file_llseek,
9002 .read = generic_read_dir,
9003 .iterate = btrfs_real_readdir,
9004 .unlocked_ioctl = btrfs_ioctl,
9005 #ifdef CONFIG_COMPAT
9006 .compat_ioctl = btrfs_ioctl,
9008 .release = btrfs_release_file,
9009 .fsync = btrfs_sync_file,
9012 static struct extent_io_ops btrfs_extent_io_ops = {
9013 .fill_delalloc = run_delalloc_range,
9014 .submit_bio_hook = btrfs_submit_bio_hook,
9015 .merge_bio_hook = btrfs_merge_bio_hook,
9016 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9017 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9018 .writepage_start_hook = btrfs_writepage_start_hook,
9019 .set_bit_hook = btrfs_set_bit_hook,
9020 .clear_bit_hook = btrfs_clear_bit_hook,
9021 .merge_extent_hook = btrfs_merge_extent_hook,
9022 .split_extent_hook = btrfs_split_extent_hook,
9026 * btrfs doesn't support the bmap operation because swapfiles
9027 * use bmap to make a mapping of extents in the file. They assume
9028 * these extents won't change over the life of the file and they
9029 * use the bmap result to do IO directly to the drive.
9031 * the btrfs bmap call would return logical addresses that aren't
9032 * suitable for IO and they also will change frequently as COW
9033 * operations happen. So, swapfile + btrfs == corruption.
9035 * For now we're avoiding this by dropping bmap.
9037 static const struct address_space_operations btrfs_aops = {
9038 .readpage = btrfs_readpage,
9039 .writepage = btrfs_writepage,
9040 .writepages = btrfs_writepages,
9041 .readpages = btrfs_readpages,
9042 .direct_IO = btrfs_direct_IO,
9043 .invalidatepage = btrfs_invalidatepage,
9044 .releasepage = btrfs_releasepage,
9045 .set_page_dirty = btrfs_set_page_dirty,
9046 .error_remove_page = generic_error_remove_page,
9049 static const struct address_space_operations btrfs_symlink_aops = {
9050 .readpage = btrfs_readpage,
9051 .writepage = btrfs_writepage,
9052 .invalidatepage = btrfs_invalidatepage,
9053 .releasepage = btrfs_releasepage,
9056 static const struct inode_operations btrfs_file_inode_operations = {
9057 .getattr = btrfs_getattr,
9058 .setattr = btrfs_setattr,
9059 .setxattr = btrfs_setxattr,
9060 .getxattr = btrfs_getxattr,
9061 .listxattr = btrfs_listxattr,
9062 .removexattr = btrfs_removexattr,
9063 .permission = btrfs_permission,
9064 .fiemap = btrfs_fiemap,
9065 .get_acl = btrfs_get_acl,
9066 .set_acl = btrfs_set_acl,
9067 .update_time = btrfs_update_time,
9069 static const struct inode_operations btrfs_special_inode_operations = {
9070 .getattr = btrfs_getattr,
9071 .setattr = btrfs_setattr,
9072 .permission = btrfs_permission,
9073 .setxattr = btrfs_setxattr,
9074 .getxattr = btrfs_getxattr,
9075 .listxattr = btrfs_listxattr,
9076 .removexattr = btrfs_removexattr,
9077 .get_acl = btrfs_get_acl,
9078 .set_acl = btrfs_set_acl,
9079 .update_time = btrfs_update_time,
9081 static const struct inode_operations btrfs_symlink_inode_operations = {
9082 .readlink = generic_readlink,
9083 .follow_link = page_follow_link_light,
9084 .put_link = page_put_link,
9085 .getattr = btrfs_getattr,
9086 .setattr = btrfs_setattr,
9087 .permission = btrfs_permission,
9088 .setxattr = btrfs_setxattr,
9089 .getxattr = btrfs_getxattr,
9090 .listxattr = btrfs_listxattr,
9091 .removexattr = btrfs_removexattr,
9092 .update_time = btrfs_update_time,
9095 const struct dentry_operations btrfs_dentry_operations = {
9096 .d_delete = btrfs_dentry_delete,
9097 .d_release = btrfs_dentry_release,