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>
46 #include <linux/uio.h>
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "ordered-data.h"
56 #include "compression.h"
58 #include "free-space-cache.h"
59 #include "inode-map.h"
65 struct btrfs_iget_args {
66 struct btrfs_key *location;
67 struct btrfs_root *root;
70 static const struct inode_operations btrfs_dir_inode_operations;
71 static const struct inode_operations btrfs_symlink_inode_operations;
72 static const struct inode_operations btrfs_dir_ro_inode_operations;
73 static const struct inode_operations btrfs_special_inode_operations;
74 static const struct inode_operations btrfs_file_inode_operations;
75 static const struct address_space_operations btrfs_aops;
76 static const struct address_space_operations btrfs_symlink_aops;
77 static const struct file_operations btrfs_dir_file_operations;
78 static struct extent_io_ops btrfs_extent_io_ops;
80 static struct kmem_cache *btrfs_inode_cachep;
81 static struct kmem_cache *btrfs_delalloc_work_cachep;
82 struct kmem_cache *btrfs_trans_handle_cachep;
83 struct kmem_cache *btrfs_transaction_cachep;
84 struct kmem_cache *btrfs_path_cachep;
85 struct kmem_cache *btrfs_free_space_cachep;
88 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
89 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
90 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
91 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
92 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
93 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
94 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
95 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
98 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
99 static int btrfs_truncate(struct inode *inode);
100 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
101 static noinline int cow_file_range(struct inode *inode,
102 struct page *locked_page,
103 u64 start, u64 end, int *page_started,
104 unsigned long *nr_written, int unlock);
105 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
106 u64 len, u64 orig_start,
107 u64 block_start, u64 block_len,
108 u64 orig_block_len, u64 ram_bytes,
111 static int btrfs_dirty_inode(struct inode *inode);
113 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
114 void btrfs_test_inode_set_ops(struct inode *inode)
116 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
120 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
121 struct inode *inode, struct inode *dir,
122 const struct qstr *qstr)
126 err = btrfs_init_acl(trans, inode, dir);
128 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
133 * this does all the hard work for inserting an inline extent into
134 * the btree. The caller should have done a btrfs_drop_extents so that
135 * no overlapping inline items exist in the btree
137 static int insert_inline_extent(struct btrfs_trans_handle *trans,
138 struct btrfs_path *path, int extent_inserted,
139 struct btrfs_root *root, struct inode *inode,
140 u64 start, size_t size, size_t compressed_size,
142 struct page **compressed_pages)
144 struct extent_buffer *leaf;
145 struct page *page = NULL;
148 struct btrfs_file_extent_item *ei;
151 size_t cur_size = size;
152 unsigned long offset;
154 if (compressed_size && compressed_pages)
155 cur_size = compressed_size;
157 inode_add_bytes(inode, size);
159 if (!extent_inserted) {
160 struct btrfs_key key;
163 key.objectid = btrfs_ino(inode);
165 key.type = BTRFS_EXTENT_DATA_KEY;
167 datasize = btrfs_file_extent_calc_inline_size(cur_size);
168 path->leave_spinning = 1;
169 ret = btrfs_insert_empty_item(trans, root, path, &key,
176 leaf = path->nodes[0];
177 ei = btrfs_item_ptr(leaf, path->slots[0],
178 struct btrfs_file_extent_item);
179 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
180 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
181 btrfs_set_file_extent_encryption(leaf, ei, 0);
182 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
183 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
184 ptr = btrfs_file_extent_inline_start(ei);
186 if (compress_type != BTRFS_COMPRESS_NONE) {
189 while (compressed_size > 0) {
190 cpage = compressed_pages[i];
191 cur_size = min_t(unsigned long, compressed_size,
194 kaddr = kmap_atomic(cpage);
195 write_extent_buffer(leaf, kaddr, ptr, cur_size);
196 kunmap_atomic(kaddr);
200 compressed_size -= cur_size;
202 btrfs_set_file_extent_compression(leaf, ei,
205 page = find_get_page(inode->i_mapping,
206 start >> PAGE_CACHE_SHIFT);
207 btrfs_set_file_extent_compression(leaf, ei, 0);
208 kaddr = kmap_atomic(page);
209 offset = start & (PAGE_CACHE_SIZE - 1);
210 write_extent_buffer(leaf, kaddr + offset, ptr, size);
211 kunmap_atomic(kaddr);
212 page_cache_release(page);
214 btrfs_mark_buffer_dirty(leaf);
215 btrfs_release_path(path);
218 * we're an inline extent, so nobody can
219 * extend the file past i_size without locking
220 * a page we already have locked.
222 * We must do any isize and inode updates
223 * before we unlock the pages. Otherwise we
224 * could end up racing with unlink.
226 BTRFS_I(inode)->disk_i_size = inode->i_size;
227 ret = btrfs_update_inode(trans, root, inode);
236 * conditionally insert an inline extent into the file. This
237 * does the checks required to make sure the data is small enough
238 * to fit as an inline extent.
240 static noinline int cow_file_range_inline(struct btrfs_root *root,
241 struct inode *inode, u64 start,
242 u64 end, size_t compressed_size,
244 struct page **compressed_pages)
246 struct btrfs_trans_handle *trans;
247 u64 isize = i_size_read(inode);
248 u64 actual_end = min(end + 1, isize);
249 u64 inline_len = actual_end - start;
250 u64 aligned_end = ALIGN(end, root->sectorsize);
251 u64 data_len = inline_len;
253 struct btrfs_path *path;
254 int extent_inserted = 0;
255 u32 extent_item_size;
258 data_len = compressed_size;
261 actual_end > PAGE_CACHE_SIZE ||
262 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
264 (actual_end & (root->sectorsize - 1)) == 0) ||
266 data_len > root->fs_info->max_inline) {
270 path = btrfs_alloc_path();
274 trans = btrfs_join_transaction(root);
276 btrfs_free_path(path);
277 return PTR_ERR(trans);
279 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
281 if (compressed_size && compressed_pages)
282 extent_item_size = btrfs_file_extent_calc_inline_size(
285 extent_item_size = btrfs_file_extent_calc_inline_size(
288 ret = __btrfs_drop_extents(trans, root, inode, path,
289 start, aligned_end, NULL,
290 1, 1, extent_item_size, &extent_inserted);
292 btrfs_abort_transaction(trans, root, ret);
296 if (isize > actual_end)
297 inline_len = min_t(u64, isize, actual_end);
298 ret = insert_inline_extent(trans, path, extent_inserted,
300 inline_len, compressed_size,
301 compress_type, compressed_pages);
302 if (ret && ret != -ENOSPC) {
303 btrfs_abort_transaction(trans, root, ret);
305 } else if (ret == -ENOSPC) {
310 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
311 btrfs_delalloc_release_metadata(inode, end + 1 - start);
312 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
314 btrfs_free_path(path);
315 btrfs_end_transaction(trans, root);
319 struct async_extent {
324 unsigned long nr_pages;
326 struct list_head list;
331 struct btrfs_root *root;
332 struct page *locked_page;
335 struct list_head extents;
336 struct btrfs_work work;
339 static noinline int add_async_extent(struct async_cow *cow,
340 u64 start, u64 ram_size,
343 unsigned long nr_pages,
346 struct async_extent *async_extent;
348 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
349 BUG_ON(!async_extent); /* -ENOMEM */
350 async_extent->start = start;
351 async_extent->ram_size = ram_size;
352 async_extent->compressed_size = compressed_size;
353 async_extent->pages = pages;
354 async_extent->nr_pages = nr_pages;
355 async_extent->compress_type = compress_type;
356 list_add_tail(&async_extent->list, &cow->extents);
360 static inline int inode_need_compress(struct inode *inode)
362 struct btrfs_root *root = BTRFS_I(inode)->root;
365 if (btrfs_test_opt(root, FORCE_COMPRESS))
367 /* bad compression ratios */
368 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
370 if (btrfs_test_opt(root, COMPRESS) ||
371 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
372 BTRFS_I(inode)->force_compress)
378 * we create compressed extents in two phases. The first
379 * phase compresses a range of pages that have already been
380 * locked (both pages and state bits are locked).
382 * This is done inside an ordered work queue, and the compression
383 * is spread across many cpus. The actual IO submission is step
384 * two, and the ordered work queue takes care of making sure that
385 * happens in the same order things were put onto the queue by
386 * writepages and friends.
388 * If this code finds it can't get good compression, it puts an
389 * entry onto the work queue to write the uncompressed bytes. This
390 * makes sure that both compressed inodes and uncompressed inodes
391 * are written in the same order that the flusher thread sent them
394 static noinline void compress_file_range(struct inode *inode,
395 struct page *locked_page,
397 struct async_cow *async_cow,
400 struct btrfs_root *root = BTRFS_I(inode)->root;
402 u64 blocksize = root->sectorsize;
404 u64 isize = i_size_read(inode);
406 struct page **pages = NULL;
407 unsigned long nr_pages;
408 unsigned long nr_pages_ret = 0;
409 unsigned long total_compressed = 0;
410 unsigned long total_in = 0;
411 unsigned long max_compressed = 128 * 1024;
412 unsigned long max_uncompressed = 128 * 1024;
415 int compress_type = root->fs_info->compress_type;
418 /* if this is a small write inside eof, kick off a defrag */
419 if ((end - start + 1) < 16 * 1024 &&
420 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
421 btrfs_add_inode_defrag(NULL, inode);
423 actual_end = min_t(u64, isize, end + 1);
426 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
427 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
430 * we don't want to send crud past the end of i_size through
431 * compression, that's just a waste of CPU time. So, if the
432 * end of the file is before the start of our current
433 * requested range of bytes, we bail out to the uncompressed
434 * cleanup code that can deal with all of this.
436 * It isn't really the fastest way to fix things, but this is a
437 * very uncommon corner.
439 if (actual_end <= start)
440 goto cleanup_and_bail_uncompressed;
442 total_compressed = actual_end - start;
445 * skip compression for a small file range(<=blocksize) that
446 * isn't an inline extent, since it dosen't save disk space at all.
448 if (total_compressed <= blocksize &&
449 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
450 goto cleanup_and_bail_uncompressed;
452 /* we want to make sure that amount of ram required to uncompress
453 * an extent is reasonable, so we limit the total size in ram
454 * of a compressed extent to 128k. This is a crucial number
455 * because it also controls how easily we can spread reads across
456 * cpus for decompression.
458 * We also want to make sure the amount of IO required to do
459 * a random read is reasonably small, so we limit the size of
460 * a compressed extent to 128k.
462 total_compressed = min(total_compressed, max_uncompressed);
463 num_bytes = ALIGN(end - start + 1, blocksize);
464 num_bytes = max(blocksize, num_bytes);
469 * we do compression for mount -o compress and when the
470 * inode has not been flagged as nocompress. This flag can
471 * change at any time if we discover bad compression ratios.
473 if (inode_need_compress(inode)) {
475 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
477 /* just bail out to the uncompressed code */
481 if (BTRFS_I(inode)->force_compress)
482 compress_type = BTRFS_I(inode)->force_compress;
485 * we need to call clear_page_dirty_for_io on each
486 * page in the range. Otherwise applications with the file
487 * mmap'd can wander in and change the page contents while
488 * we are compressing them.
490 * If the compression fails for any reason, we set the pages
491 * dirty again later on.
493 extent_range_clear_dirty_for_io(inode, start, end);
495 ret = btrfs_compress_pages(compress_type,
496 inode->i_mapping, start,
497 total_compressed, pages,
498 nr_pages, &nr_pages_ret,
504 unsigned long offset = total_compressed &
505 (PAGE_CACHE_SIZE - 1);
506 struct page *page = pages[nr_pages_ret - 1];
509 /* zero the tail end of the last page, we might be
510 * sending it down to disk
513 kaddr = kmap_atomic(page);
514 memset(kaddr + offset, 0,
515 PAGE_CACHE_SIZE - offset);
516 kunmap_atomic(kaddr);
523 /* lets try to make an inline extent */
524 if (ret || total_in < (actual_end - start)) {
525 /* we didn't compress the entire range, try
526 * to make an uncompressed inline extent.
528 ret = cow_file_range_inline(root, inode, start, end,
531 /* try making a compressed inline extent */
532 ret = cow_file_range_inline(root, inode, start, end,
534 compress_type, pages);
537 unsigned long clear_flags = EXTENT_DELALLOC |
539 unsigned long page_error_op;
541 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
542 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
545 * inline extent creation worked or returned error,
546 * we don't need to create any more async work items.
547 * Unlock and free up our temp pages.
549 extent_clear_unlock_delalloc(inode, start, end, NULL,
550 clear_flags, PAGE_UNLOCK |
561 * we aren't doing an inline extent round the compressed size
562 * up to a block size boundary so the allocator does sane
565 total_compressed = ALIGN(total_compressed, blocksize);
568 * one last check to make sure the compression is really a
569 * win, compare the page count read with the blocks on disk
571 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
572 if (total_compressed >= total_in) {
575 num_bytes = total_in;
578 if (!will_compress && pages) {
580 * the compression code ran but failed to make things smaller,
581 * free any pages it allocated and our page pointer array
583 for (i = 0; i < nr_pages_ret; i++) {
584 WARN_ON(pages[i]->mapping);
585 page_cache_release(pages[i]);
589 total_compressed = 0;
592 /* flag the file so we don't compress in the future */
593 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
594 !(BTRFS_I(inode)->force_compress)) {
595 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
601 /* the async work queues will take care of doing actual
602 * allocation on disk for these compressed pages,
603 * and will submit them to the elevator.
605 add_async_extent(async_cow, start, num_bytes,
606 total_compressed, pages, nr_pages_ret,
609 if (start + num_bytes < end) {
616 cleanup_and_bail_uncompressed:
618 * No compression, but we still need to write the pages in
619 * the file we've been given so far. redirty the locked
620 * page if it corresponds to our extent and set things up
621 * for the async work queue to run cow_file_range to do
622 * the normal delalloc dance
624 if (page_offset(locked_page) >= start &&
625 page_offset(locked_page) <= end) {
626 __set_page_dirty_nobuffers(locked_page);
627 /* unlocked later on in the async handlers */
630 extent_range_redirty_for_io(inode, start, end);
631 add_async_extent(async_cow, start, end - start + 1,
632 0, NULL, 0, BTRFS_COMPRESS_NONE);
639 for (i = 0; i < nr_pages_ret; i++) {
640 WARN_ON(pages[i]->mapping);
641 page_cache_release(pages[i]);
646 static void free_async_extent_pages(struct async_extent *async_extent)
650 if (!async_extent->pages)
653 for (i = 0; i < async_extent->nr_pages; i++) {
654 WARN_ON(async_extent->pages[i]->mapping);
655 page_cache_release(async_extent->pages[i]);
657 kfree(async_extent->pages);
658 async_extent->nr_pages = 0;
659 async_extent->pages = NULL;
663 * phase two of compressed writeback. This is the ordered portion
664 * of the code, which only gets called in the order the work was
665 * queued. We walk all the async extents created by compress_file_range
666 * and send them down to the disk.
668 static noinline void submit_compressed_extents(struct inode *inode,
669 struct async_cow *async_cow)
671 struct async_extent *async_extent;
673 struct btrfs_key ins;
674 struct extent_map *em;
675 struct btrfs_root *root = BTRFS_I(inode)->root;
676 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
677 struct extent_io_tree *io_tree;
681 while (!list_empty(&async_cow->extents)) {
682 async_extent = list_entry(async_cow->extents.next,
683 struct async_extent, list);
684 list_del(&async_extent->list);
686 io_tree = &BTRFS_I(inode)->io_tree;
689 /* did the compression code fall back to uncompressed IO? */
690 if (!async_extent->pages) {
691 int page_started = 0;
692 unsigned long nr_written = 0;
694 lock_extent(io_tree, async_extent->start,
695 async_extent->start +
696 async_extent->ram_size - 1);
698 /* allocate blocks */
699 ret = cow_file_range(inode, async_cow->locked_page,
701 async_extent->start +
702 async_extent->ram_size - 1,
703 &page_started, &nr_written, 0);
708 * if page_started, cow_file_range inserted an
709 * inline extent and took care of all the unlocking
710 * and IO for us. Otherwise, we need to submit
711 * all those pages down to the drive.
713 if (!page_started && !ret)
714 extent_write_locked_range(io_tree,
715 inode, async_extent->start,
716 async_extent->start +
717 async_extent->ram_size - 1,
721 unlock_page(async_cow->locked_page);
727 lock_extent(io_tree, async_extent->start,
728 async_extent->start + async_extent->ram_size - 1);
730 ret = btrfs_reserve_extent(root,
731 async_extent->compressed_size,
732 async_extent->compressed_size,
733 0, alloc_hint, &ins, 1, 1);
735 free_async_extent_pages(async_extent);
737 if (ret == -ENOSPC) {
738 unlock_extent(io_tree, async_extent->start,
739 async_extent->start +
740 async_extent->ram_size - 1);
743 * we need to redirty the pages if we decide to
744 * fallback to uncompressed IO, otherwise we
745 * will not submit these pages down to lower
748 extent_range_redirty_for_io(inode,
750 async_extent->start +
751 async_extent->ram_size - 1);
758 * here we're doing allocation and writeback of the
761 btrfs_drop_extent_cache(inode, async_extent->start,
762 async_extent->start +
763 async_extent->ram_size - 1, 0);
765 em = alloc_extent_map();
768 goto out_free_reserve;
770 em->start = async_extent->start;
771 em->len = async_extent->ram_size;
772 em->orig_start = em->start;
773 em->mod_start = em->start;
774 em->mod_len = em->len;
776 em->block_start = ins.objectid;
777 em->block_len = ins.offset;
778 em->orig_block_len = ins.offset;
779 em->ram_bytes = async_extent->ram_size;
780 em->bdev = root->fs_info->fs_devices->latest_bdev;
781 em->compress_type = async_extent->compress_type;
782 set_bit(EXTENT_FLAG_PINNED, &em->flags);
783 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
787 write_lock(&em_tree->lock);
788 ret = add_extent_mapping(em_tree, em, 1);
789 write_unlock(&em_tree->lock);
790 if (ret != -EEXIST) {
794 btrfs_drop_extent_cache(inode, async_extent->start,
795 async_extent->start +
796 async_extent->ram_size - 1, 0);
800 goto out_free_reserve;
802 ret = btrfs_add_ordered_extent_compress(inode,
805 async_extent->ram_size,
807 BTRFS_ORDERED_COMPRESSED,
808 async_extent->compress_type);
810 btrfs_drop_extent_cache(inode, async_extent->start,
811 async_extent->start +
812 async_extent->ram_size - 1, 0);
813 goto out_free_reserve;
817 * clear dirty, set writeback and unlock the pages.
819 extent_clear_unlock_delalloc(inode, async_extent->start,
820 async_extent->start +
821 async_extent->ram_size - 1,
822 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
823 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
825 ret = btrfs_submit_compressed_write(inode,
827 async_extent->ram_size,
829 ins.offset, async_extent->pages,
830 async_extent->nr_pages);
832 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
833 struct page *p = async_extent->pages[0];
834 const u64 start = async_extent->start;
835 const u64 end = start + async_extent->ram_size - 1;
837 p->mapping = inode->i_mapping;
838 tree->ops->writepage_end_io_hook(p, start, end,
841 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
844 free_async_extent_pages(async_extent);
846 alloc_hint = ins.objectid + ins.offset;
852 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
854 extent_clear_unlock_delalloc(inode, async_extent->start,
855 async_extent->start +
856 async_extent->ram_size - 1,
857 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
858 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
859 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
860 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
862 free_async_extent_pages(async_extent);
867 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
870 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
871 struct extent_map *em;
874 read_lock(&em_tree->lock);
875 em = search_extent_mapping(em_tree, start, num_bytes);
878 * if block start isn't an actual block number then find the
879 * first block in this inode and use that as a hint. If that
880 * block is also bogus then just don't worry about it.
882 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
884 em = search_extent_mapping(em_tree, 0, 0);
885 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
886 alloc_hint = em->block_start;
890 alloc_hint = em->block_start;
894 read_unlock(&em_tree->lock);
900 * when extent_io.c finds a delayed allocation range in the file,
901 * the call backs end up in this code. The basic idea is to
902 * allocate extents on disk for the range, and create ordered data structs
903 * in ram to track those extents.
905 * locked_page is the page that writepage had locked already. We use
906 * it to make sure we don't do extra locks or unlocks.
908 * *page_started is set to one if we unlock locked_page and do everything
909 * required to start IO on it. It may be clean and already done with
912 static noinline int cow_file_range(struct inode *inode,
913 struct page *locked_page,
914 u64 start, u64 end, int *page_started,
915 unsigned long *nr_written,
918 struct btrfs_root *root = BTRFS_I(inode)->root;
921 unsigned long ram_size;
924 u64 blocksize = root->sectorsize;
925 struct btrfs_key ins;
926 struct extent_map *em;
927 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
930 if (btrfs_is_free_space_inode(inode)) {
936 num_bytes = ALIGN(end - start + 1, blocksize);
937 num_bytes = max(blocksize, num_bytes);
938 disk_num_bytes = num_bytes;
940 /* if this is a small write inside eof, kick off defrag */
941 if (num_bytes < 64 * 1024 &&
942 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
943 btrfs_add_inode_defrag(NULL, inode);
946 /* lets try to make an inline extent */
947 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
950 extent_clear_unlock_delalloc(inode, start, end, NULL,
951 EXTENT_LOCKED | EXTENT_DELALLOC |
952 EXTENT_DEFRAG, PAGE_UNLOCK |
953 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
956 *nr_written = *nr_written +
957 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
960 } else if (ret < 0) {
965 BUG_ON(disk_num_bytes >
966 btrfs_super_total_bytes(root->fs_info->super_copy));
968 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
969 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
971 while (disk_num_bytes > 0) {
974 cur_alloc_size = disk_num_bytes;
975 ret = btrfs_reserve_extent(root, cur_alloc_size,
976 root->sectorsize, 0, alloc_hint,
981 em = alloc_extent_map();
987 em->orig_start = em->start;
988 ram_size = ins.offset;
989 em->len = ins.offset;
990 em->mod_start = em->start;
991 em->mod_len = em->len;
993 em->block_start = ins.objectid;
994 em->block_len = ins.offset;
995 em->orig_block_len = ins.offset;
996 em->ram_bytes = ram_size;
997 em->bdev = root->fs_info->fs_devices->latest_bdev;
998 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1002 write_lock(&em_tree->lock);
1003 ret = add_extent_mapping(em_tree, em, 1);
1004 write_unlock(&em_tree->lock);
1005 if (ret != -EEXIST) {
1006 free_extent_map(em);
1009 btrfs_drop_extent_cache(inode, start,
1010 start + ram_size - 1, 0);
1015 cur_alloc_size = ins.offset;
1016 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1017 ram_size, cur_alloc_size, 0);
1019 goto out_drop_extent_cache;
1021 if (root->root_key.objectid ==
1022 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1023 ret = btrfs_reloc_clone_csums(inode, start,
1026 goto out_drop_extent_cache;
1029 if (disk_num_bytes < cur_alloc_size)
1032 /* we're not doing compressed IO, don't unlock the first
1033 * page (which the caller expects to stay locked), don't
1034 * clear any dirty bits and don't set any writeback bits
1036 * Do set the Private2 bit so we know this page was properly
1037 * setup for writepage
1039 op = unlock ? PAGE_UNLOCK : 0;
1040 op |= PAGE_SET_PRIVATE2;
1042 extent_clear_unlock_delalloc(inode, start,
1043 start + ram_size - 1, locked_page,
1044 EXTENT_LOCKED | EXTENT_DELALLOC,
1046 disk_num_bytes -= cur_alloc_size;
1047 num_bytes -= cur_alloc_size;
1048 alloc_hint = ins.objectid + ins.offset;
1049 start += cur_alloc_size;
1054 out_drop_extent_cache:
1055 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1057 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1059 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1060 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1061 EXTENT_DELALLOC | EXTENT_DEFRAG,
1062 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1063 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1068 * work queue call back to started compression on a file and pages
1070 static noinline void async_cow_start(struct btrfs_work *work)
1072 struct async_cow *async_cow;
1074 async_cow = container_of(work, struct async_cow, work);
1076 compress_file_range(async_cow->inode, async_cow->locked_page,
1077 async_cow->start, async_cow->end, async_cow,
1079 if (num_added == 0) {
1080 btrfs_add_delayed_iput(async_cow->inode);
1081 async_cow->inode = NULL;
1086 * work queue call back to submit previously compressed pages
1088 static noinline void async_cow_submit(struct btrfs_work *work)
1090 struct async_cow *async_cow;
1091 struct btrfs_root *root;
1092 unsigned long nr_pages;
1094 async_cow = container_of(work, struct async_cow, work);
1096 root = async_cow->root;
1097 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1100 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1102 waitqueue_active(&root->fs_info->async_submit_wait))
1103 wake_up(&root->fs_info->async_submit_wait);
1105 if (async_cow->inode)
1106 submit_compressed_extents(async_cow->inode, async_cow);
1109 static noinline void async_cow_free(struct btrfs_work *work)
1111 struct async_cow *async_cow;
1112 async_cow = container_of(work, struct async_cow, work);
1113 if (async_cow->inode)
1114 btrfs_add_delayed_iput(async_cow->inode);
1118 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1119 u64 start, u64 end, int *page_started,
1120 unsigned long *nr_written)
1122 struct async_cow *async_cow;
1123 struct btrfs_root *root = BTRFS_I(inode)->root;
1124 unsigned long nr_pages;
1126 int limit = 10 * 1024 * 1024;
1128 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1129 1, 0, NULL, GFP_NOFS);
1130 while (start < end) {
1131 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1132 BUG_ON(!async_cow); /* -ENOMEM */
1133 async_cow->inode = igrab(inode);
1134 async_cow->root = root;
1135 async_cow->locked_page = locked_page;
1136 async_cow->start = start;
1138 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1139 !btrfs_test_opt(root, FORCE_COMPRESS))
1142 cur_end = min(end, start + 512 * 1024 - 1);
1144 async_cow->end = cur_end;
1145 INIT_LIST_HEAD(&async_cow->extents);
1147 btrfs_init_work(&async_cow->work,
1148 btrfs_delalloc_helper,
1149 async_cow_start, async_cow_submit,
1152 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1154 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1156 btrfs_queue_work(root->fs_info->delalloc_workers,
1159 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1160 wait_event(root->fs_info->async_submit_wait,
1161 (atomic_read(&root->fs_info->async_delalloc_pages) <
1165 while (atomic_read(&root->fs_info->async_submit_draining) &&
1166 atomic_read(&root->fs_info->async_delalloc_pages)) {
1167 wait_event(root->fs_info->async_submit_wait,
1168 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1172 *nr_written += nr_pages;
1173 start = cur_end + 1;
1179 static noinline int csum_exist_in_range(struct btrfs_root *root,
1180 u64 bytenr, u64 num_bytes)
1183 struct btrfs_ordered_sum *sums;
1186 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1187 bytenr + num_bytes - 1, &list, 0);
1188 if (ret == 0 && list_empty(&list))
1191 while (!list_empty(&list)) {
1192 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1193 list_del(&sums->list);
1200 * when nowcow writeback call back. This checks for snapshots or COW copies
1201 * of the extents that exist in the file, and COWs the file as required.
1203 * If no cow copies or snapshots exist, we write directly to the existing
1206 static noinline int run_delalloc_nocow(struct inode *inode,
1207 struct page *locked_page,
1208 u64 start, u64 end, int *page_started, int force,
1209 unsigned long *nr_written)
1211 struct btrfs_root *root = BTRFS_I(inode)->root;
1212 struct btrfs_trans_handle *trans;
1213 struct extent_buffer *leaf;
1214 struct btrfs_path *path;
1215 struct btrfs_file_extent_item *fi;
1216 struct btrfs_key found_key;
1231 u64 ino = btrfs_ino(inode);
1233 path = btrfs_alloc_path();
1235 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1236 EXTENT_LOCKED | EXTENT_DELALLOC |
1237 EXTENT_DO_ACCOUNTING |
1238 EXTENT_DEFRAG, PAGE_UNLOCK |
1240 PAGE_SET_WRITEBACK |
1241 PAGE_END_WRITEBACK);
1245 nolock = btrfs_is_free_space_inode(inode);
1248 trans = btrfs_join_transaction_nolock(root);
1250 trans = btrfs_join_transaction(root);
1252 if (IS_ERR(trans)) {
1253 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1254 EXTENT_LOCKED | EXTENT_DELALLOC |
1255 EXTENT_DO_ACCOUNTING |
1256 EXTENT_DEFRAG, PAGE_UNLOCK |
1258 PAGE_SET_WRITEBACK |
1259 PAGE_END_WRITEBACK);
1260 btrfs_free_path(path);
1261 return PTR_ERR(trans);
1264 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1266 cow_start = (u64)-1;
1269 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1273 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1274 leaf = path->nodes[0];
1275 btrfs_item_key_to_cpu(leaf, &found_key,
1276 path->slots[0] - 1);
1277 if (found_key.objectid == ino &&
1278 found_key.type == BTRFS_EXTENT_DATA_KEY)
1283 leaf = path->nodes[0];
1284 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1285 ret = btrfs_next_leaf(root, path);
1290 leaf = path->nodes[0];
1296 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1298 if (found_key.objectid > ino ||
1299 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1300 found_key.offset > end)
1303 if (found_key.offset > cur_offset) {
1304 extent_end = found_key.offset;
1309 fi = btrfs_item_ptr(leaf, path->slots[0],
1310 struct btrfs_file_extent_item);
1311 extent_type = btrfs_file_extent_type(leaf, fi);
1313 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1314 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1315 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1316 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1317 extent_offset = btrfs_file_extent_offset(leaf, fi);
1318 extent_end = found_key.offset +
1319 btrfs_file_extent_num_bytes(leaf, fi);
1321 btrfs_file_extent_disk_num_bytes(leaf, fi);
1322 if (extent_end <= start) {
1326 if (disk_bytenr == 0)
1328 if (btrfs_file_extent_compression(leaf, fi) ||
1329 btrfs_file_extent_encryption(leaf, fi) ||
1330 btrfs_file_extent_other_encoding(leaf, fi))
1332 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1334 if (btrfs_extent_readonly(root, disk_bytenr))
1336 if (btrfs_cross_ref_exist(trans, root, ino,
1338 extent_offset, disk_bytenr))
1340 disk_bytenr += extent_offset;
1341 disk_bytenr += cur_offset - found_key.offset;
1342 num_bytes = min(end + 1, extent_end) - cur_offset;
1344 * if there are pending snapshots for this root,
1345 * we fall into common COW way.
1348 err = btrfs_start_write_no_snapshoting(root);
1353 * force cow if csum exists in the range.
1354 * this ensure that csum for a given extent are
1355 * either valid or do not exist.
1357 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1360 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1361 extent_end = found_key.offset +
1362 btrfs_file_extent_inline_len(leaf,
1363 path->slots[0], fi);
1364 extent_end = ALIGN(extent_end, root->sectorsize);
1369 if (extent_end <= start) {
1371 if (!nolock && nocow)
1372 btrfs_end_write_no_snapshoting(root);
1376 if (cow_start == (u64)-1)
1377 cow_start = cur_offset;
1378 cur_offset = extent_end;
1379 if (cur_offset > end)
1385 btrfs_release_path(path);
1386 if (cow_start != (u64)-1) {
1387 ret = cow_file_range(inode, locked_page,
1388 cow_start, found_key.offset - 1,
1389 page_started, nr_written, 1);
1391 if (!nolock && nocow)
1392 btrfs_end_write_no_snapshoting(root);
1395 cow_start = (u64)-1;
1398 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1399 struct extent_map *em;
1400 struct extent_map_tree *em_tree;
1401 em_tree = &BTRFS_I(inode)->extent_tree;
1402 em = alloc_extent_map();
1403 BUG_ON(!em); /* -ENOMEM */
1404 em->start = cur_offset;
1405 em->orig_start = found_key.offset - extent_offset;
1406 em->len = num_bytes;
1407 em->block_len = num_bytes;
1408 em->block_start = disk_bytenr;
1409 em->orig_block_len = disk_num_bytes;
1410 em->ram_bytes = ram_bytes;
1411 em->bdev = root->fs_info->fs_devices->latest_bdev;
1412 em->mod_start = em->start;
1413 em->mod_len = em->len;
1414 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1415 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1416 em->generation = -1;
1418 write_lock(&em_tree->lock);
1419 ret = add_extent_mapping(em_tree, em, 1);
1420 write_unlock(&em_tree->lock);
1421 if (ret != -EEXIST) {
1422 free_extent_map(em);
1425 btrfs_drop_extent_cache(inode, em->start,
1426 em->start + em->len - 1, 0);
1428 type = BTRFS_ORDERED_PREALLOC;
1430 type = BTRFS_ORDERED_NOCOW;
1433 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1434 num_bytes, num_bytes, type);
1435 BUG_ON(ret); /* -ENOMEM */
1437 if (root->root_key.objectid ==
1438 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1439 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1442 if (!nolock && nocow)
1443 btrfs_end_write_no_snapshoting(root);
1448 extent_clear_unlock_delalloc(inode, cur_offset,
1449 cur_offset + num_bytes - 1,
1450 locked_page, EXTENT_LOCKED |
1451 EXTENT_DELALLOC, PAGE_UNLOCK |
1453 if (!nolock && nocow)
1454 btrfs_end_write_no_snapshoting(root);
1455 cur_offset = extent_end;
1456 if (cur_offset > end)
1459 btrfs_release_path(path);
1461 if (cur_offset <= end && cow_start == (u64)-1) {
1462 cow_start = cur_offset;
1466 if (cow_start != (u64)-1) {
1467 ret = cow_file_range(inode, locked_page, cow_start, end,
1468 page_started, nr_written, 1);
1474 err = btrfs_end_transaction(trans, root);
1478 if (ret && cur_offset < end)
1479 extent_clear_unlock_delalloc(inode, cur_offset, end,
1480 locked_page, EXTENT_LOCKED |
1481 EXTENT_DELALLOC | EXTENT_DEFRAG |
1482 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1484 PAGE_SET_WRITEBACK |
1485 PAGE_END_WRITEBACK);
1486 btrfs_free_path(path);
1490 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1493 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1494 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1498 * @defrag_bytes is a hint value, no spinlock held here,
1499 * if is not zero, it means the file is defragging.
1500 * Force cow if given extent needs to be defragged.
1502 if (BTRFS_I(inode)->defrag_bytes &&
1503 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1504 EXTENT_DEFRAG, 0, NULL))
1511 * extent_io.c call back to do delayed allocation processing
1513 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1514 u64 start, u64 end, int *page_started,
1515 unsigned long *nr_written)
1518 int force_cow = need_force_cow(inode, start, end);
1520 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1521 ret = run_delalloc_nocow(inode, locked_page, start, end,
1522 page_started, 1, nr_written);
1523 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1524 ret = run_delalloc_nocow(inode, locked_page, start, end,
1525 page_started, 0, nr_written);
1526 } else if (!inode_need_compress(inode)) {
1527 ret = cow_file_range(inode, locked_page, start, end,
1528 page_started, nr_written, 1);
1530 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1531 &BTRFS_I(inode)->runtime_flags);
1532 ret = cow_file_range_async(inode, locked_page, start, end,
1533 page_started, nr_written);
1538 static void btrfs_split_extent_hook(struct inode *inode,
1539 struct extent_state *orig, u64 split)
1543 /* not delalloc, ignore it */
1544 if (!(orig->state & EXTENT_DELALLOC))
1547 size = orig->end - orig->start + 1;
1548 if (size > BTRFS_MAX_EXTENT_SIZE) {
1553 * See the explanation in btrfs_merge_extent_hook, the same
1554 * applies here, just in reverse.
1556 new_size = orig->end - split + 1;
1557 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1558 BTRFS_MAX_EXTENT_SIZE);
1559 new_size = split - orig->start;
1560 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1561 BTRFS_MAX_EXTENT_SIZE);
1562 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1563 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1567 spin_lock(&BTRFS_I(inode)->lock);
1568 BTRFS_I(inode)->outstanding_extents++;
1569 spin_unlock(&BTRFS_I(inode)->lock);
1573 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1574 * extents so we can keep track of new extents that are just merged onto old
1575 * extents, such as when we are doing sequential writes, so we can properly
1576 * account for the metadata space we'll need.
1578 static void btrfs_merge_extent_hook(struct inode *inode,
1579 struct extent_state *new,
1580 struct extent_state *other)
1582 u64 new_size, old_size;
1585 /* not delalloc, ignore it */
1586 if (!(other->state & EXTENT_DELALLOC))
1589 if (new->start > other->start)
1590 new_size = new->end - other->start + 1;
1592 new_size = other->end - new->start + 1;
1594 /* we're not bigger than the max, unreserve the space and go */
1595 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1596 spin_lock(&BTRFS_I(inode)->lock);
1597 BTRFS_I(inode)->outstanding_extents--;
1598 spin_unlock(&BTRFS_I(inode)->lock);
1603 * We have to add up either side to figure out how many extents were
1604 * accounted for before we merged into one big extent. If the number of
1605 * extents we accounted for is <= the amount we need for the new range
1606 * then we can return, otherwise drop. Think of it like this
1610 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1611 * need 2 outstanding extents, on one side we have 1 and the other side
1612 * we have 1 so they are == and we can return. But in this case
1614 * [MAX_SIZE+4k][MAX_SIZE+4k]
1616 * Each range on their own accounts for 2 extents, but merged together
1617 * they are only 3 extents worth of accounting, so we need to drop in
1620 old_size = other->end - other->start + 1;
1621 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1622 BTRFS_MAX_EXTENT_SIZE);
1623 old_size = new->end - new->start + 1;
1624 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1625 BTRFS_MAX_EXTENT_SIZE);
1627 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1628 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1631 spin_lock(&BTRFS_I(inode)->lock);
1632 BTRFS_I(inode)->outstanding_extents--;
1633 spin_unlock(&BTRFS_I(inode)->lock);
1636 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1637 struct inode *inode)
1639 spin_lock(&root->delalloc_lock);
1640 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1641 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1642 &root->delalloc_inodes);
1643 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1644 &BTRFS_I(inode)->runtime_flags);
1645 root->nr_delalloc_inodes++;
1646 if (root->nr_delalloc_inodes == 1) {
1647 spin_lock(&root->fs_info->delalloc_root_lock);
1648 BUG_ON(!list_empty(&root->delalloc_root));
1649 list_add_tail(&root->delalloc_root,
1650 &root->fs_info->delalloc_roots);
1651 spin_unlock(&root->fs_info->delalloc_root_lock);
1654 spin_unlock(&root->delalloc_lock);
1657 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1658 struct inode *inode)
1660 spin_lock(&root->delalloc_lock);
1661 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1662 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1663 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1664 &BTRFS_I(inode)->runtime_flags);
1665 root->nr_delalloc_inodes--;
1666 if (!root->nr_delalloc_inodes) {
1667 spin_lock(&root->fs_info->delalloc_root_lock);
1668 BUG_ON(list_empty(&root->delalloc_root));
1669 list_del_init(&root->delalloc_root);
1670 spin_unlock(&root->fs_info->delalloc_root_lock);
1673 spin_unlock(&root->delalloc_lock);
1677 * extent_io.c set_bit_hook, used to track delayed allocation
1678 * bytes in this file, and to maintain the list of inodes that
1679 * have pending delalloc work to be done.
1681 static void btrfs_set_bit_hook(struct inode *inode,
1682 struct extent_state *state, unsigned *bits)
1685 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1688 * set_bit and clear bit hooks normally require _irqsave/restore
1689 * but in this case, we are only testing for the DELALLOC
1690 * bit, which is only set or cleared with irqs on
1692 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1693 struct btrfs_root *root = BTRFS_I(inode)->root;
1694 u64 len = state->end + 1 - state->start;
1695 bool do_list = !btrfs_is_free_space_inode(inode);
1697 if (*bits & EXTENT_FIRST_DELALLOC) {
1698 *bits &= ~EXTENT_FIRST_DELALLOC;
1700 spin_lock(&BTRFS_I(inode)->lock);
1701 BTRFS_I(inode)->outstanding_extents++;
1702 spin_unlock(&BTRFS_I(inode)->lock);
1705 /* For sanity tests */
1706 if (btrfs_test_is_dummy_root(root))
1709 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1710 root->fs_info->delalloc_batch);
1711 spin_lock(&BTRFS_I(inode)->lock);
1712 BTRFS_I(inode)->delalloc_bytes += len;
1713 if (*bits & EXTENT_DEFRAG)
1714 BTRFS_I(inode)->defrag_bytes += len;
1715 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1716 &BTRFS_I(inode)->runtime_flags))
1717 btrfs_add_delalloc_inodes(root, inode);
1718 spin_unlock(&BTRFS_I(inode)->lock);
1723 * extent_io.c clear_bit_hook, see set_bit_hook for why
1725 static void btrfs_clear_bit_hook(struct inode *inode,
1726 struct extent_state *state,
1729 u64 len = state->end + 1 - state->start;
1730 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1731 BTRFS_MAX_EXTENT_SIZE);
1733 spin_lock(&BTRFS_I(inode)->lock);
1734 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1735 BTRFS_I(inode)->defrag_bytes -= len;
1736 spin_unlock(&BTRFS_I(inode)->lock);
1739 * set_bit and clear bit hooks normally require _irqsave/restore
1740 * but in this case, we are only testing for the DELALLOC
1741 * bit, which is only set or cleared with irqs on
1743 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1744 struct btrfs_root *root = BTRFS_I(inode)->root;
1745 bool do_list = !btrfs_is_free_space_inode(inode);
1747 if (*bits & EXTENT_FIRST_DELALLOC) {
1748 *bits &= ~EXTENT_FIRST_DELALLOC;
1749 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1750 spin_lock(&BTRFS_I(inode)->lock);
1751 BTRFS_I(inode)->outstanding_extents -= num_extents;
1752 spin_unlock(&BTRFS_I(inode)->lock);
1756 * We don't reserve metadata space for space cache inodes so we
1757 * don't need to call dellalloc_release_metadata if there is an
1760 if (*bits & EXTENT_DO_ACCOUNTING &&
1761 root != root->fs_info->tree_root)
1762 btrfs_delalloc_release_metadata(inode, len);
1764 /* For sanity tests. */
1765 if (btrfs_test_is_dummy_root(root))
1768 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1769 && do_list && !(state->state & EXTENT_NORESERVE))
1770 btrfs_free_reserved_data_space(inode, len);
1772 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1773 root->fs_info->delalloc_batch);
1774 spin_lock(&BTRFS_I(inode)->lock);
1775 BTRFS_I(inode)->delalloc_bytes -= len;
1776 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1777 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1778 &BTRFS_I(inode)->runtime_flags))
1779 btrfs_del_delalloc_inode(root, inode);
1780 spin_unlock(&BTRFS_I(inode)->lock);
1785 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1786 * we don't create bios that span stripes or chunks
1788 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1789 size_t size, struct bio *bio,
1790 unsigned long bio_flags)
1792 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1793 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1798 if (bio_flags & EXTENT_BIO_COMPRESSED)
1801 length = bio->bi_iter.bi_size;
1802 map_length = length;
1803 ret = btrfs_map_block(root->fs_info, rw, logical,
1804 &map_length, NULL, 0);
1805 /* Will always return 0 with map_multi == NULL */
1807 if (map_length < length + size)
1813 * in order to insert checksums into the metadata in large chunks,
1814 * we wait until bio submission time. All the pages in the bio are
1815 * checksummed and sums are attached onto the ordered extent record.
1817 * At IO completion time the cums attached on the ordered extent record
1818 * are inserted into the btree
1820 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1821 struct bio *bio, int mirror_num,
1822 unsigned long bio_flags,
1825 struct btrfs_root *root = BTRFS_I(inode)->root;
1828 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1829 BUG_ON(ret); /* -ENOMEM */
1834 * in order to insert checksums into the metadata in large chunks,
1835 * we wait until bio submission time. All the pages in the bio are
1836 * checksummed and sums are attached onto the ordered extent record.
1838 * At IO completion time the cums attached on the ordered extent record
1839 * are inserted into the btree
1841 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1842 int mirror_num, unsigned long bio_flags,
1845 struct btrfs_root *root = BTRFS_I(inode)->root;
1848 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1850 bio_endio(bio, ret);
1855 * extent_io.c submission hook. This does the right thing for csum calculation
1856 * on write, or reading the csums from the tree before a read
1858 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1859 int mirror_num, unsigned long bio_flags,
1862 struct btrfs_root *root = BTRFS_I(inode)->root;
1866 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1868 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1870 if (btrfs_is_free_space_inode(inode))
1873 if (!(rw & REQ_WRITE)) {
1874 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1878 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1879 ret = btrfs_submit_compressed_read(inode, bio,
1883 } else if (!skip_sum) {
1884 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1889 } else if (async && !skip_sum) {
1890 /* csum items have already been cloned */
1891 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1893 /* we're doing a write, do the async checksumming */
1894 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1895 inode, rw, bio, mirror_num,
1896 bio_flags, bio_offset,
1897 __btrfs_submit_bio_start,
1898 __btrfs_submit_bio_done);
1900 } else if (!skip_sum) {
1901 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1907 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1911 bio_endio(bio, ret);
1916 * given a list of ordered sums record them in the inode. This happens
1917 * at IO completion time based on sums calculated at bio submission time.
1919 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1920 struct inode *inode, u64 file_offset,
1921 struct list_head *list)
1923 struct btrfs_ordered_sum *sum;
1925 list_for_each_entry(sum, list, list) {
1926 trans->adding_csums = 1;
1927 btrfs_csum_file_blocks(trans,
1928 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1929 trans->adding_csums = 0;
1934 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1935 struct extent_state **cached_state)
1937 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1938 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1939 cached_state, GFP_NOFS);
1942 /* see btrfs_writepage_start_hook for details on why this is required */
1943 struct btrfs_writepage_fixup {
1945 struct btrfs_work work;
1948 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1950 struct btrfs_writepage_fixup *fixup;
1951 struct btrfs_ordered_extent *ordered;
1952 struct extent_state *cached_state = NULL;
1954 struct inode *inode;
1959 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1963 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1964 ClearPageChecked(page);
1968 inode = page->mapping->host;
1969 page_start = page_offset(page);
1970 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1972 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1975 /* already ordered? We're done */
1976 if (PagePrivate2(page))
1979 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1981 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1982 page_end, &cached_state, GFP_NOFS);
1984 btrfs_start_ordered_extent(inode, ordered, 1);
1985 btrfs_put_ordered_extent(ordered);
1989 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1991 mapping_set_error(page->mapping, ret);
1992 end_extent_writepage(page, ret, page_start, page_end);
1993 ClearPageChecked(page);
1997 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1998 ClearPageChecked(page);
1999 set_page_dirty(page);
2001 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2002 &cached_state, GFP_NOFS);
2005 page_cache_release(page);
2010 * There are a few paths in the higher layers of the kernel that directly
2011 * set the page dirty bit without asking the filesystem if it is a
2012 * good idea. This causes problems because we want to make sure COW
2013 * properly happens and the data=ordered rules are followed.
2015 * In our case any range that doesn't have the ORDERED bit set
2016 * hasn't been properly setup for IO. We kick off an async process
2017 * to fix it up. The async helper will wait for ordered extents, set
2018 * the delalloc bit and make it safe to write the page.
2020 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2022 struct inode *inode = page->mapping->host;
2023 struct btrfs_writepage_fixup *fixup;
2024 struct btrfs_root *root = BTRFS_I(inode)->root;
2026 /* this page is properly in the ordered list */
2027 if (TestClearPagePrivate2(page))
2030 if (PageChecked(page))
2033 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2037 SetPageChecked(page);
2038 page_cache_get(page);
2039 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2040 btrfs_writepage_fixup_worker, NULL, NULL);
2042 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2046 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2047 struct inode *inode, u64 file_pos,
2048 u64 disk_bytenr, u64 disk_num_bytes,
2049 u64 num_bytes, u64 ram_bytes,
2050 u8 compression, u8 encryption,
2051 u16 other_encoding, int extent_type)
2053 struct btrfs_root *root = BTRFS_I(inode)->root;
2054 struct btrfs_file_extent_item *fi;
2055 struct btrfs_path *path;
2056 struct extent_buffer *leaf;
2057 struct btrfs_key ins;
2058 int extent_inserted = 0;
2061 path = btrfs_alloc_path();
2066 * we may be replacing one extent in the tree with another.
2067 * The new extent is pinned in the extent map, and we don't want
2068 * to drop it from the cache until it is completely in the btree.
2070 * So, tell btrfs_drop_extents to leave this extent in the cache.
2071 * the caller is expected to unpin it and allow it to be merged
2074 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2075 file_pos + num_bytes, NULL, 0,
2076 1, sizeof(*fi), &extent_inserted);
2080 if (!extent_inserted) {
2081 ins.objectid = btrfs_ino(inode);
2082 ins.offset = file_pos;
2083 ins.type = BTRFS_EXTENT_DATA_KEY;
2085 path->leave_spinning = 1;
2086 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2091 leaf = path->nodes[0];
2092 fi = btrfs_item_ptr(leaf, path->slots[0],
2093 struct btrfs_file_extent_item);
2094 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2095 btrfs_set_file_extent_type(leaf, fi, extent_type);
2096 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2097 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2098 btrfs_set_file_extent_offset(leaf, fi, 0);
2099 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2100 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2101 btrfs_set_file_extent_compression(leaf, fi, compression);
2102 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2103 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2105 btrfs_mark_buffer_dirty(leaf);
2106 btrfs_release_path(path);
2108 inode_add_bytes(inode, num_bytes);
2110 ins.objectid = disk_bytenr;
2111 ins.offset = disk_num_bytes;
2112 ins.type = BTRFS_EXTENT_ITEM_KEY;
2113 ret = btrfs_alloc_reserved_file_extent(trans, root,
2114 root->root_key.objectid,
2115 btrfs_ino(inode), file_pos, &ins);
2117 btrfs_free_path(path);
2122 /* snapshot-aware defrag */
2123 struct sa_defrag_extent_backref {
2124 struct rb_node node;
2125 struct old_sa_defrag_extent *old;
2134 struct old_sa_defrag_extent {
2135 struct list_head list;
2136 struct new_sa_defrag_extent *new;
2145 struct new_sa_defrag_extent {
2146 struct rb_root root;
2147 struct list_head head;
2148 struct btrfs_path *path;
2149 struct inode *inode;
2157 static int backref_comp(struct sa_defrag_extent_backref *b1,
2158 struct sa_defrag_extent_backref *b2)
2160 if (b1->root_id < b2->root_id)
2162 else if (b1->root_id > b2->root_id)
2165 if (b1->inum < b2->inum)
2167 else if (b1->inum > b2->inum)
2170 if (b1->file_pos < b2->file_pos)
2172 else if (b1->file_pos > b2->file_pos)
2176 * [------------------------------] ===> (a range of space)
2177 * |<--->| |<---->| =============> (fs/file tree A)
2178 * |<---------------------------->| ===> (fs/file tree B)
2180 * A range of space can refer to two file extents in one tree while
2181 * refer to only one file extent in another tree.
2183 * So we may process a disk offset more than one time(two extents in A)
2184 * and locate at the same extent(one extent in B), then insert two same
2185 * backrefs(both refer to the extent in B).
2190 static void backref_insert(struct rb_root *root,
2191 struct sa_defrag_extent_backref *backref)
2193 struct rb_node **p = &root->rb_node;
2194 struct rb_node *parent = NULL;
2195 struct sa_defrag_extent_backref *entry;
2200 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2202 ret = backref_comp(backref, entry);
2206 p = &(*p)->rb_right;
2209 rb_link_node(&backref->node, parent, p);
2210 rb_insert_color(&backref->node, root);
2214 * Note the backref might has changed, and in this case we just return 0.
2216 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2219 struct btrfs_file_extent_item *extent;
2220 struct btrfs_fs_info *fs_info;
2221 struct old_sa_defrag_extent *old = ctx;
2222 struct new_sa_defrag_extent *new = old->new;
2223 struct btrfs_path *path = new->path;
2224 struct btrfs_key key;
2225 struct btrfs_root *root;
2226 struct sa_defrag_extent_backref *backref;
2227 struct extent_buffer *leaf;
2228 struct inode *inode = new->inode;
2234 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2235 inum == btrfs_ino(inode))
2238 key.objectid = root_id;
2239 key.type = BTRFS_ROOT_ITEM_KEY;
2240 key.offset = (u64)-1;
2242 fs_info = BTRFS_I(inode)->root->fs_info;
2243 root = btrfs_read_fs_root_no_name(fs_info, &key);
2245 if (PTR_ERR(root) == -ENOENT)
2248 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2249 inum, offset, root_id);
2250 return PTR_ERR(root);
2253 key.objectid = inum;
2254 key.type = BTRFS_EXTENT_DATA_KEY;
2255 if (offset > (u64)-1 << 32)
2258 key.offset = offset;
2260 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2261 if (WARN_ON(ret < 0))
2268 leaf = path->nodes[0];
2269 slot = path->slots[0];
2271 if (slot >= btrfs_header_nritems(leaf)) {
2272 ret = btrfs_next_leaf(root, path);
2275 } else if (ret > 0) {
2284 btrfs_item_key_to_cpu(leaf, &key, slot);
2286 if (key.objectid > inum)
2289 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2292 extent = btrfs_item_ptr(leaf, slot,
2293 struct btrfs_file_extent_item);
2295 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2299 * 'offset' refers to the exact key.offset,
2300 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2301 * (key.offset - extent_offset).
2303 if (key.offset != offset)
2306 extent_offset = btrfs_file_extent_offset(leaf, extent);
2307 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2309 if (extent_offset >= old->extent_offset + old->offset +
2310 old->len || extent_offset + num_bytes <=
2311 old->extent_offset + old->offset)
2316 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2322 backref->root_id = root_id;
2323 backref->inum = inum;
2324 backref->file_pos = offset;
2325 backref->num_bytes = num_bytes;
2326 backref->extent_offset = extent_offset;
2327 backref->generation = btrfs_file_extent_generation(leaf, extent);
2329 backref_insert(&new->root, backref);
2332 btrfs_release_path(path);
2337 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2338 struct new_sa_defrag_extent *new)
2340 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2341 struct old_sa_defrag_extent *old, *tmp;
2346 list_for_each_entry_safe(old, tmp, &new->head, list) {
2347 ret = iterate_inodes_from_logical(old->bytenr +
2348 old->extent_offset, fs_info,
2349 path, record_one_backref,
2351 if (ret < 0 && ret != -ENOENT)
2354 /* no backref to be processed for this extent */
2356 list_del(&old->list);
2361 if (list_empty(&new->head))
2367 static int relink_is_mergable(struct extent_buffer *leaf,
2368 struct btrfs_file_extent_item *fi,
2369 struct new_sa_defrag_extent *new)
2371 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2374 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2377 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2380 if (btrfs_file_extent_encryption(leaf, fi) ||
2381 btrfs_file_extent_other_encoding(leaf, fi))
2388 * Note the backref might has changed, and in this case we just return 0.
2390 static noinline int relink_extent_backref(struct btrfs_path *path,
2391 struct sa_defrag_extent_backref *prev,
2392 struct sa_defrag_extent_backref *backref)
2394 struct btrfs_file_extent_item *extent;
2395 struct btrfs_file_extent_item *item;
2396 struct btrfs_ordered_extent *ordered;
2397 struct btrfs_trans_handle *trans;
2398 struct btrfs_fs_info *fs_info;
2399 struct btrfs_root *root;
2400 struct btrfs_key key;
2401 struct extent_buffer *leaf;
2402 struct old_sa_defrag_extent *old = backref->old;
2403 struct new_sa_defrag_extent *new = old->new;
2404 struct inode *src_inode = new->inode;
2405 struct inode *inode;
2406 struct extent_state *cached = NULL;
2415 if (prev && prev->root_id == backref->root_id &&
2416 prev->inum == backref->inum &&
2417 prev->file_pos + prev->num_bytes == backref->file_pos)
2420 /* step 1: get root */
2421 key.objectid = backref->root_id;
2422 key.type = BTRFS_ROOT_ITEM_KEY;
2423 key.offset = (u64)-1;
2425 fs_info = BTRFS_I(src_inode)->root->fs_info;
2426 index = srcu_read_lock(&fs_info->subvol_srcu);
2428 root = btrfs_read_fs_root_no_name(fs_info, &key);
2430 srcu_read_unlock(&fs_info->subvol_srcu, index);
2431 if (PTR_ERR(root) == -ENOENT)
2433 return PTR_ERR(root);
2436 if (btrfs_root_readonly(root)) {
2437 srcu_read_unlock(&fs_info->subvol_srcu, index);
2441 /* step 2: get inode */
2442 key.objectid = backref->inum;
2443 key.type = BTRFS_INODE_ITEM_KEY;
2446 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2447 if (IS_ERR(inode)) {
2448 srcu_read_unlock(&fs_info->subvol_srcu, index);
2452 srcu_read_unlock(&fs_info->subvol_srcu, index);
2454 /* step 3: relink backref */
2455 lock_start = backref->file_pos;
2456 lock_end = backref->file_pos + backref->num_bytes - 1;
2457 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2460 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2462 btrfs_put_ordered_extent(ordered);
2466 trans = btrfs_join_transaction(root);
2467 if (IS_ERR(trans)) {
2468 ret = PTR_ERR(trans);
2472 key.objectid = backref->inum;
2473 key.type = BTRFS_EXTENT_DATA_KEY;
2474 key.offset = backref->file_pos;
2476 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2479 } else if (ret > 0) {
2484 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2485 struct btrfs_file_extent_item);
2487 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2488 backref->generation)
2491 btrfs_release_path(path);
2493 start = backref->file_pos;
2494 if (backref->extent_offset < old->extent_offset + old->offset)
2495 start += old->extent_offset + old->offset -
2496 backref->extent_offset;
2498 len = min(backref->extent_offset + backref->num_bytes,
2499 old->extent_offset + old->offset + old->len);
2500 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2502 ret = btrfs_drop_extents(trans, root, inode, start,
2507 key.objectid = btrfs_ino(inode);
2508 key.type = BTRFS_EXTENT_DATA_KEY;
2511 path->leave_spinning = 1;
2513 struct btrfs_file_extent_item *fi;
2515 struct btrfs_key found_key;
2517 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2522 leaf = path->nodes[0];
2523 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2525 fi = btrfs_item_ptr(leaf, path->slots[0],
2526 struct btrfs_file_extent_item);
2527 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2529 if (extent_len + found_key.offset == start &&
2530 relink_is_mergable(leaf, fi, new)) {
2531 btrfs_set_file_extent_num_bytes(leaf, fi,
2533 btrfs_mark_buffer_dirty(leaf);
2534 inode_add_bytes(inode, len);
2540 btrfs_release_path(path);
2545 ret = btrfs_insert_empty_item(trans, root, path, &key,
2548 btrfs_abort_transaction(trans, root, ret);
2552 leaf = path->nodes[0];
2553 item = btrfs_item_ptr(leaf, path->slots[0],
2554 struct btrfs_file_extent_item);
2555 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2556 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2557 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2558 btrfs_set_file_extent_num_bytes(leaf, item, len);
2559 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2560 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2561 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2562 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2563 btrfs_set_file_extent_encryption(leaf, item, 0);
2564 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2566 btrfs_mark_buffer_dirty(leaf);
2567 inode_add_bytes(inode, len);
2568 btrfs_release_path(path);
2570 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2572 backref->root_id, backref->inum,
2573 new->file_pos, 0); /* start - extent_offset */
2575 btrfs_abort_transaction(trans, root, ret);
2581 btrfs_release_path(path);
2582 path->leave_spinning = 0;
2583 btrfs_end_transaction(trans, root);
2585 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2591 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2593 struct old_sa_defrag_extent *old, *tmp;
2598 list_for_each_entry_safe(old, tmp, &new->head, list) {
2599 list_del(&old->list);
2605 static void relink_file_extents(struct new_sa_defrag_extent *new)
2607 struct btrfs_path *path;
2608 struct sa_defrag_extent_backref *backref;
2609 struct sa_defrag_extent_backref *prev = NULL;
2610 struct inode *inode;
2611 struct btrfs_root *root;
2612 struct rb_node *node;
2616 root = BTRFS_I(inode)->root;
2618 path = btrfs_alloc_path();
2622 if (!record_extent_backrefs(path, new)) {
2623 btrfs_free_path(path);
2626 btrfs_release_path(path);
2629 node = rb_first(&new->root);
2632 rb_erase(node, &new->root);
2634 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2636 ret = relink_extent_backref(path, prev, backref);
2649 btrfs_free_path(path);
2651 free_sa_defrag_extent(new);
2653 atomic_dec(&root->fs_info->defrag_running);
2654 wake_up(&root->fs_info->transaction_wait);
2657 static struct new_sa_defrag_extent *
2658 record_old_file_extents(struct inode *inode,
2659 struct btrfs_ordered_extent *ordered)
2661 struct btrfs_root *root = BTRFS_I(inode)->root;
2662 struct btrfs_path *path;
2663 struct btrfs_key key;
2664 struct old_sa_defrag_extent *old;
2665 struct new_sa_defrag_extent *new;
2668 new = kmalloc(sizeof(*new), GFP_NOFS);
2673 new->file_pos = ordered->file_offset;
2674 new->len = ordered->len;
2675 new->bytenr = ordered->start;
2676 new->disk_len = ordered->disk_len;
2677 new->compress_type = ordered->compress_type;
2678 new->root = RB_ROOT;
2679 INIT_LIST_HEAD(&new->head);
2681 path = btrfs_alloc_path();
2685 key.objectid = btrfs_ino(inode);
2686 key.type = BTRFS_EXTENT_DATA_KEY;
2687 key.offset = new->file_pos;
2689 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2692 if (ret > 0 && path->slots[0] > 0)
2695 /* find out all the old extents for the file range */
2697 struct btrfs_file_extent_item *extent;
2698 struct extent_buffer *l;
2707 slot = path->slots[0];
2709 if (slot >= btrfs_header_nritems(l)) {
2710 ret = btrfs_next_leaf(root, path);
2718 btrfs_item_key_to_cpu(l, &key, slot);
2720 if (key.objectid != btrfs_ino(inode))
2722 if (key.type != BTRFS_EXTENT_DATA_KEY)
2724 if (key.offset >= new->file_pos + new->len)
2727 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2729 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2730 if (key.offset + num_bytes < new->file_pos)
2733 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2737 extent_offset = btrfs_file_extent_offset(l, extent);
2739 old = kmalloc(sizeof(*old), GFP_NOFS);
2743 offset = max(new->file_pos, key.offset);
2744 end = min(new->file_pos + new->len, key.offset + num_bytes);
2746 old->bytenr = disk_bytenr;
2747 old->extent_offset = extent_offset;
2748 old->offset = offset - key.offset;
2749 old->len = end - offset;
2752 list_add_tail(&old->list, &new->head);
2758 btrfs_free_path(path);
2759 atomic_inc(&root->fs_info->defrag_running);
2764 btrfs_free_path(path);
2766 free_sa_defrag_extent(new);
2770 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2773 struct btrfs_block_group_cache *cache;
2775 cache = btrfs_lookup_block_group(root->fs_info, start);
2778 spin_lock(&cache->lock);
2779 cache->delalloc_bytes -= len;
2780 spin_unlock(&cache->lock);
2782 btrfs_put_block_group(cache);
2785 /* as ordered data IO finishes, this gets called so we can finish
2786 * an ordered extent if the range of bytes in the file it covers are
2789 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2791 struct inode *inode = ordered_extent->inode;
2792 struct btrfs_root *root = BTRFS_I(inode)->root;
2793 struct btrfs_trans_handle *trans = NULL;
2794 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2795 struct extent_state *cached_state = NULL;
2796 struct new_sa_defrag_extent *new = NULL;
2797 int compress_type = 0;
2799 u64 logical_len = ordered_extent->len;
2801 bool truncated = false;
2803 nolock = btrfs_is_free_space_inode(inode);
2805 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2810 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2811 ordered_extent->file_offset +
2812 ordered_extent->len - 1);
2814 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2816 logical_len = ordered_extent->truncated_len;
2817 /* Truncated the entire extent, don't bother adding */
2822 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2823 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2824 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2826 trans = btrfs_join_transaction_nolock(root);
2828 trans = btrfs_join_transaction(root);
2829 if (IS_ERR(trans)) {
2830 ret = PTR_ERR(trans);
2834 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2835 ret = btrfs_update_inode_fallback(trans, root, inode);
2836 if (ret) /* -ENOMEM or corruption */
2837 btrfs_abort_transaction(trans, root, ret);
2841 lock_extent_bits(io_tree, ordered_extent->file_offset,
2842 ordered_extent->file_offset + ordered_extent->len - 1,
2845 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2846 ordered_extent->file_offset + ordered_extent->len - 1,
2847 EXTENT_DEFRAG, 1, cached_state);
2849 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2850 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2851 /* the inode is shared */
2852 new = record_old_file_extents(inode, ordered_extent);
2854 clear_extent_bit(io_tree, ordered_extent->file_offset,
2855 ordered_extent->file_offset + ordered_extent->len - 1,
2856 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2860 trans = btrfs_join_transaction_nolock(root);
2862 trans = btrfs_join_transaction(root);
2863 if (IS_ERR(trans)) {
2864 ret = PTR_ERR(trans);
2869 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2871 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2872 compress_type = ordered_extent->compress_type;
2873 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2874 BUG_ON(compress_type);
2875 ret = btrfs_mark_extent_written(trans, inode,
2876 ordered_extent->file_offset,
2877 ordered_extent->file_offset +
2880 BUG_ON(root == root->fs_info->tree_root);
2881 ret = insert_reserved_file_extent(trans, inode,
2882 ordered_extent->file_offset,
2883 ordered_extent->start,
2884 ordered_extent->disk_len,
2885 logical_len, logical_len,
2886 compress_type, 0, 0,
2887 BTRFS_FILE_EXTENT_REG);
2889 btrfs_release_delalloc_bytes(root,
2890 ordered_extent->start,
2891 ordered_extent->disk_len);
2893 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2894 ordered_extent->file_offset, ordered_extent->len,
2897 btrfs_abort_transaction(trans, root, ret);
2901 add_pending_csums(trans, inode, ordered_extent->file_offset,
2902 &ordered_extent->list);
2904 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2905 ret = btrfs_update_inode_fallback(trans, root, inode);
2906 if (ret) { /* -ENOMEM or corruption */
2907 btrfs_abort_transaction(trans, root, ret);
2912 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2913 ordered_extent->file_offset +
2914 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2916 if (root != root->fs_info->tree_root)
2917 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2919 btrfs_end_transaction(trans, root);
2921 if (ret || truncated) {
2925 start = ordered_extent->file_offset + logical_len;
2927 start = ordered_extent->file_offset;
2928 end = ordered_extent->file_offset + ordered_extent->len - 1;
2929 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
2931 /* Drop the cache for the part of the extent we didn't write. */
2932 btrfs_drop_extent_cache(inode, start, end, 0);
2935 * If the ordered extent had an IOERR or something else went
2936 * wrong we need to return the space for this ordered extent
2937 * back to the allocator. We only free the extent in the
2938 * truncated case if we didn't write out the extent at all.
2940 if ((ret || !logical_len) &&
2941 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2942 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2943 btrfs_free_reserved_extent(root, ordered_extent->start,
2944 ordered_extent->disk_len, 1);
2949 * This needs to be done to make sure anybody waiting knows we are done
2950 * updating everything for this ordered extent.
2952 btrfs_remove_ordered_extent(inode, ordered_extent);
2954 /* for snapshot-aware defrag */
2957 free_sa_defrag_extent(new);
2958 atomic_dec(&root->fs_info->defrag_running);
2960 relink_file_extents(new);
2965 btrfs_put_ordered_extent(ordered_extent);
2966 /* once for the tree */
2967 btrfs_put_ordered_extent(ordered_extent);
2972 static void finish_ordered_fn(struct btrfs_work *work)
2974 struct btrfs_ordered_extent *ordered_extent;
2975 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2976 btrfs_finish_ordered_io(ordered_extent);
2979 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2980 struct extent_state *state, int uptodate)
2982 struct inode *inode = page->mapping->host;
2983 struct btrfs_root *root = BTRFS_I(inode)->root;
2984 struct btrfs_ordered_extent *ordered_extent = NULL;
2985 struct btrfs_workqueue *wq;
2986 btrfs_work_func_t func;
2988 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2990 ClearPagePrivate2(page);
2991 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2992 end - start + 1, uptodate))
2995 if (btrfs_is_free_space_inode(inode)) {
2996 wq = root->fs_info->endio_freespace_worker;
2997 func = btrfs_freespace_write_helper;
2999 wq = root->fs_info->endio_write_workers;
3000 func = btrfs_endio_write_helper;
3003 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3005 btrfs_queue_work(wq, &ordered_extent->work);
3010 static int __readpage_endio_check(struct inode *inode,
3011 struct btrfs_io_bio *io_bio,
3012 int icsum, struct page *page,
3013 int pgoff, u64 start, size_t len)
3018 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
3019 DEFAULT_RATELIMIT_BURST);
3021 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3023 kaddr = kmap_atomic(page);
3024 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3025 btrfs_csum_final(csum, (char *)&csum);
3026 if (csum != csum_expected)
3029 kunmap_atomic(kaddr);
3032 if (__ratelimit(&_rs))
3033 btrfs_warn(BTRFS_I(inode)->root->fs_info,
3034 "csum failed ino %llu off %llu csum %u expected csum %u",
3035 btrfs_ino(inode), start, csum, csum_expected);
3036 memset(kaddr + pgoff, 1, len);
3037 flush_dcache_page(page);
3038 kunmap_atomic(kaddr);
3039 if (csum_expected == 0)
3045 * when reads are done, we need to check csums to verify the data is correct
3046 * if there's a match, we allow the bio to finish. If not, the code in
3047 * extent_io.c will try to find good copies for us.
3049 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3050 u64 phy_offset, struct page *page,
3051 u64 start, u64 end, int mirror)
3053 size_t offset = start - page_offset(page);
3054 struct inode *inode = page->mapping->host;
3055 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3056 struct btrfs_root *root = BTRFS_I(inode)->root;
3058 if (PageChecked(page)) {
3059 ClearPageChecked(page);
3063 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3066 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3067 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3068 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3073 phy_offset >>= inode->i_sb->s_blocksize_bits;
3074 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3075 start, (size_t)(end - start + 1));
3078 struct delayed_iput {
3079 struct list_head list;
3080 struct inode *inode;
3083 /* JDM: If this is fs-wide, why can't we add a pointer to
3084 * btrfs_inode instead and avoid the allocation? */
3085 void btrfs_add_delayed_iput(struct inode *inode)
3087 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3088 struct delayed_iput *delayed;
3090 if (atomic_add_unless(&inode->i_count, -1, 1))
3093 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3094 delayed->inode = inode;
3096 spin_lock(&fs_info->delayed_iput_lock);
3097 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3098 spin_unlock(&fs_info->delayed_iput_lock);
3101 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3104 struct btrfs_fs_info *fs_info = root->fs_info;
3105 struct delayed_iput *delayed;
3108 spin_lock(&fs_info->delayed_iput_lock);
3109 empty = list_empty(&fs_info->delayed_iputs);
3110 spin_unlock(&fs_info->delayed_iput_lock);
3114 down_read(&fs_info->delayed_iput_sem);
3116 spin_lock(&fs_info->delayed_iput_lock);
3117 list_splice_init(&fs_info->delayed_iputs, &list);
3118 spin_unlock(&fs_info->delayed_iput_lock);
3120 while (!list_empty(&list)) {
3121 delayed = list_entry(list.next, struct delayed_iput, list);
3122 list_del(&delayed->list);
3123 iput(delayed->inode);
3127 up_read(&root->fs_info->delayed_iput_sem);
3131 * This is called in transaction commit time. If there are no orphan
3132 * files in the subvolume, it removes orphan item and frees block_rsv
3135 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3136 struct btrfs_root *root)
3138 struct btrfs_block_rsv *block_rsv;
3141 if (atomic_read(&root->orphan_inodes) ||
3142 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3145 spin_lock(&root->orphan_lock);
3146 if (atomic_read(&root->orphan_inodes)) {
3147 spin_unlock(&root->orphan_lock);
3151 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3152 spin_unlock(&root->orphan_lock);
3156 block_rsv = root->orphan_block_rsv;
3157 root->orphan_block_rsv = NULL;
3158 spin_unlock(&root->orphan_lock);
3160 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3161 btrfs_root_refs(&root->root_item) > 0) {
3162 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3163 root->root_key.objectid);
3165 btrfs_abort_transaction(trans, root, ret);
3167 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3172 WARN_ON(block_rsv->size > 0);
3173 btrfs_free_block_rsv(root, block_rsv);
3178 * This creates an orphan entry for the given inode in case something goes
3179 * wrong in the middle of an unlink/truncate.
3181 * NOTE: caller of this function should reserve 5 units of metadata for
3184 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3186 struct btrfs_root *root = BTRFS_I(inode)->root;
3187 struct btrfs_block_rsv *block_rsv = NULL;
3192 if (!root->orphan_block_rsv) {
3193 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3198 spin_lock(&root->orphan_lock);
3199 if (!root->orphan_block_rsv) {
3200 root->orphan_block_rsv = block_rsv;
3201 } else if (block_rsv) {
3202 btrfs_free_block_rsv(root, block_rsv);
3206 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3207 &BTRFS_I(inode)->runtime_flags)) {
3210 * For proper ENOSPC handling, we should do orphan
3211 * cleanup when mounting. But this introduces backward
3212 * compatibility issue.
3214 if (!xchg(&root->orphan_item_inserted, 1))
3220 atomic_inc(&root->orphan_inodes);
3223 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3224 &BTRFS_I(inode)->runtime_flags))
3226 spin_unlock(&root->orphan_lock);
3228 /* grab metadata reservation from transaction handle */
3230 ret = btrfs_orphan_reserve_metadata(trans, inode);
3231 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3234 /* insert an orphan item to track this unlinked/truncated file */
3236 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3238 atomic_dec(&root->orphan_inodes);
3240 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3241 &BTRFS_I(inode)->runtime_flags);
3242 btrfs_orphan_release_metadata(inode);
3244 if (ret != -EEXIST) {
3245 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3246 &BTRFS_I(inode)->runtime_flags);
3247 btrfs_abort_transaction(trans, root, ret);
3254 /* insert an orphan item to track subvolume contains orphan files */
3256 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3257 root->root_key.objectid);
3258 if (ret && ret != -EEXIST) {
3259 btrfs_abort_transaction(trans, root, ret);
3267 * We have done the truncate/delete so we can go ahead and remove the orphan
3268 * item for this particular inode.
3270 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3271 struct inode *inode)
3273 struct btrfs_root *root = BTRFS_I(inode)->root;
3274 int delete_item = 0;
3275 int release_rsv = 0;
3278 spin_lock(&root->orphan_lock);
3279 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3280 &BTRFS_I(inode)->runtime_flags))
3283 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3284 &BTRFS_I(inode)->runtime_flags))
3286 spin_unlock(&root->orphan_lock);
3289 atomic_dec(&root->orphan_inodes);
3291 ret = btrfs_del_orphan_item(trans, root,
3296 btrfs_orphan_release_metadata(inode);
3302 * this cleans up any orphans that may be left on the list from the last use
3305 int btrfs_orphan_cleanup(struct btrfs_root *root)
3307 struct btrfs_path *path;
3308 struct extent_buffer *leaf;
3309 struct btrfs_key key, found_key;
3310 struct btrfs_trans_handle *trans;
3311 struct inode *inode;
3312 u64 last_objectid = 0;
3313 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3315 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3318 path = btrfs_alloc_path();
3325 key.objectid = BTRFS_ORPHAN_OBJECTID;
3326 key.type = BTRFS_ORPHAN_ITEM_KEY;
3327 key.offset = (u64)-1;
3330 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3335 * if ret == 0 means we found what we were searching for, which
3336 * is weird, but possible, so only screw with path if we didn't
3337 * find the key and see if we have stuff that matches
3341 if (path->slots[0] == 0)
3346 /* pull out the item */
3347 leaf = path->nodes[0];
3348 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3350 /* make sure the item matches what we want */
3351 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3353 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3356 /* release the path since we're done with it */
3357 btrfs_release_path(path);
3360 * this is where we are basically btrfs_lookup, without the
3361 * crossing root thing. we store the inode number in the
3362 * offset of the orphan item.
3365 if (found_key.offset == last_objectid) {
3366 btrfs_err(root->fs_info,
3367 "Error removing orphan entry, stopping orphan cleanup");
3372 last_objectid = found_key.offset;
3374 found_key.objectid = found_key.offset;
3375 found_key.type = BTRFS_INODE_ITEM_KEY;
3376 found_key.offset = 0;
3377 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3378 ret = PTR_ERR_OR_ZERO(inode);
3379 if (ret && ret != -ESTALE)
3382 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3383 struct btrfs_root *dead_root;
3384 struct btrfs_fs_info *fs_info = root->fs_info;
3385 int is_dead_root = 0;
3388 * this is an orphan in the tree root. Currently these
3389 * could come from 2 sources:
3390 * a) a snapshot deletion in progress
3391 * b) a free space cache inode
3392 * We need to distinguish those two, as the snapshot
3393 * orphan must not get deleted.
3394 * find_dead_roots already ran before us, so if this
3395 * is a snapshot deletion, we should find the root
3396 * in the dead_roots list
3398 spin_lock(&fs_info->trans_lock);
3399 list_for_each_entry(dead_root, &fs_info->dead_roots,
3401 if (dead_root->root_key.objectid ==
3402 found_key.objectid) {
3407 spin_unlock(&fs_info->trans_lock);
3409 /* prevent this orphan from being found again */
3410 key.offset = found_key.objectid - 1;
3415 * Inode is already gone but the orphan item is still there,
3416 * kill the orphan item.
3418 if (ret == -ESTALE) {
3419 trans = btrfs_start_transaction(root, 1);
3420 if (IS_ERR(trans)) {
3421 ret = PTR_ERR(trans);
3424 btrfs_debug(root->fs_info, "auto deleting %Lu",
3425 found_key.objectid);
3426 ret = btrfs_del_orphan_item(trans, root,
3427 found_key.objectid);
3428 btrfs_end_transaction(trans, root);
3435 * add this inode to the orphan list so btrfs_orphan_del does
3436 * the proper thing when we hit it
3438 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3439 &BTRFS_I(inode)->runtime_flags);
3440 atomic_inc(&root->orphan_inodes);
3442 /* if we have links, this was a truncate, lets do that */
3443 if (inode->i_nlink) {
3444 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3450 /* 1 for the orphan item deletion. */
3451 trans = btrfs_start_transaction(root, 1);
3452 if (IS_ERR(trans)) {
3454 ret = PTR_ERR(trans);
3457 ret = btrfs_orphan_add(trans, inode);
3458 btrfs_end_transaction(trans, root);
3464 ret = btrfs_truncate(inode);
3466 btrfs_orphan_del(NULL, inode);
3471 /* this will do delete_inode and everything for us */
3476 /* release the path since we're done with it */
3477 btrfs_release_path(path);
3479 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3481 if (root->orphan_block_rsv)
3482 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3485 if (root->orphan_block_rsv ||
3486 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3487 trans = btrfs_join_transaction(root);
3489 btrfs_end_transaction(trans, root);
3493 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3495 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3499 btrfs_err(root->fs_info,
3500 "could not do orphan cleanup %d", ret);
3501 btrfs_free_path(path);
3506 * very simple check to peek ahead in the leaf looking for xattrs. If we
3507 * don't find any xattrs, we know there can't be any acls.
3509 * slot is the slot the inode is in, objectid is the objectid of the inode
3511 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3512 int slot, u64 objectid,
3513 int *first_xattr_slot)
3515 u32 nritems = btrfs_header_nritems(leaf);
3516 struct btrfs_key found_key;
3517 static u64 xattr_access = 0;
3518 static u64 xattr_default = 0;
3521 if (!xattr_access) {
3522 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3523 strlen(POSIX_ACL_XATTR_ACCESS));
3524 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3525 strlen(POSIX_ACL_XATTR_DEFAULT));
3529 *first_xattr_slot = -1;
3530 while (slot < nritems) {
3531 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3533 /* we found a different objectid, there must not be acls */
3534 if (found_key.objectid != objectid)
3537 /* we found an xattr, assume we've got an acl */
3538 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3539 if (*first_xattr_slot == -1)
3540 *first_xattr_slot = slot;
3541 if (found_key.offset == xattr_access ||
3542 found_key.offset == xattr_default)
3547 * we found a key greater than an xattr key, there can't
3548 * be any acls later on
3550 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3557 * it goes inode, inode backrefs, xattrs, extents,
3558 * so if there are a ton of hard links to an inode there can
3559 * be a lot of backrefs. Don't waste time searching too hard,
3560 * this is just an optimization
3565 /* we hit the end of the leaf before we found an xattr or
3566 * something larger than an xattr. We have to assume the inode
3569 if (*first_xattr_slot == -1)
3570 *first_xattr_slot = slot;
3575 * read an inode from the btree into the in-memory inode
3577 static void btrfs_read_locked_inode(struct inode *inode)
3579 struct btrfs_path *path;
3580 struct extent_buffer *leaf;
3581 struct btrfs_inode_item *inode_item;
3582 struct btrfs_root *root = BTRFS_I(inode)->root;
3583 struct btrfs_key location;
3588 bool filled = false;
3589 int first_xattr_slot;
3591 ret = btrfs_fill_inode(inode, &rdev);
3595 path = btrfs_alloc_path();
3599 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3601 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3605 leaf = path->nodes[0];
3610 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3611 struct btrfs_inode_item);
3612 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3613 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3614 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3615 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3616 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3618 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3619 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3621 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3622 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3624 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3625 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3627 BTRFS_I(inode)->i_otime.tv_sec =
3628 btrfs_timespec_sec(leaf, &inode_item->otime);
3629 BTRFS_I(inode)->i_otime.tv_nsec =
3630 btrfs_timespec_nsec(leaf, &inode_item->otime);
3632 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3633 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3634 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3637 * If we were modified in the current generation and evicted from memory
3638 * and then re-read we need to do a full sync since we don't have any
3639 * idea about which extents were modified before we were evicted from
3642 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3643 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3644 &BTRFS_I(inode)->runtime_flags);
3646 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3647 inode->i_generation = BTRFS_I(inode)->generation;
3649 rdev = btrfs_inode_rdev(leaf, inode_item);
3651 BTRFS_I(inode)->index_cnt = (u64)-1;
3652 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3656 if (inode->i_nlink != 1 ||
3657 path->slots[0] >= btrfs_header_nritems(leaf))
3660 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3661 if (location.objectid != btrfs_ino(inode))
3664 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3665 if (location.type == BTRFS_INODE_REF_KEY) {
3666 struct btrfs_inode_ref *ref;
3668 ref = (struct btrfs_inode_ref *)ptr;
3669 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3670 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3671 struct btrfs_inode_extref *extref;
3673 extref = (struct btrfs_inode_extref *)ptr;
3674 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3679 * try to precache a NULL acl entry for files that don't have
3680 * any xattrs or acls
3682 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3683 btrfs_ino(inode), &first_xattr_slot);
3684 if (first_xattr_slot != -1) {
3685 path->slots[0] = first_xattr_slot;
3686 ret = btrfs_load_inode_props(inode, path);
3688 btrfs_err(root->fs_info,
3689 "error loading props for ino %llu (root %llu): %d",
3691 root->root_key.objectid, ret);
3693 btrfs_free_path(path);
3696 cache_no_acl(inode);
3698 switch (inode->i_mode & S_IFMT) {
3700 inode->i_mapping->a_ops = &btrfs_aops;
3701 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3702 inode->i_fop = &btrfs_file_operations;
3703 inode->i_op = &btrfs_file_inode_operations;
3706 inode->i_fop = &btrfs_dir_file_operations;
3707 if (root == root->fs_info->tree_root)
3708 inode->i_op = &btrfs_dir_ro_inode_operations;
3710 inode->i_op = &btrfs_dir_inode_operations;
3713 inode->i_op = &btrfs_symlink_inode_operations;
3714 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3717 inode->i_op = &btrfs_special_inode_operations;
3718 init_special_inode(inode, inode->i_mode, rdev);
3722 btrfs_update_iflags(inode);
3726 btrfs_free_path(path);
3727 make_bad_inode(inode);
3731 * given a leaf and an inode, copy the inode fields into the leaf
3733 static void fill_inode_item(struct btrfs_trans_handle *trans,
3734 struct extent_buffer *leaf,
3735 struct btrfs_inode_item *item,
3736 struct inode *inode)
3738 struct btrfs_map_token token;
3740 btrfs_init_map_token(&token);
3742 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3743 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3744 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3746 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3747 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3749 btrfs_set_token_timespec_sec(leaf, &item->atime,
3750 inode->i_atime.tv_sec, &token);
3751 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3752 inode->i_atime.tv_nsec, &token);
3754 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3755 inode->i_mtime.tv_sec, &token);
3756 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3757 inode->i_mtime.tv_nsec, &token);
3759 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3760 inode->i_ctime.tv_sec, &token);
3761 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3762 inode->i_ctime.tv_nsec, &token);
3764 btrfs_set_token_timespec_sec(leaf, &item->otime,
3765 BTRFS_I(inode)->i_otime.tv_sec, &token);
3766 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3767 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3769 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3771 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3773 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3774 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3775 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3776 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3777 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3781 * copy everything in the in-memory inode into the btree.
3783 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3784 struct btrfs_root *root, struct inode *inode)
3786 struct btrfs_inode_item *inode_item;
3787 struct btrfs_path *path;
3788 struct extent_buffer *leaf;
3791 path = btrfs_alloc_path();
3795 path->leave_spinning = 1;
3796 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3804 leaf = path->nodes[0];
3805 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3806 struct btrfs_inode_item);
3808 fill_inode_item(trans, leaf, inode_item, inode);
3809 btrfs_mark_buffer_dirty(leaf);
3810 btrfs_set_inode_last_trans(trans, inode);
3813 btrfs_free_path(path);
3818 * copy everything in the in-memory inode into the btree.
3820 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3821 struct btrfs_root *root, struct inode *inode)
3826 * If the inode is a free space inode, we can deadlock during commit
3827 * if we put it into the delayed code.
3829 * The data relocation inode should also be directly updated
3832 if (!btrfs_is_free_space_inode(inode)
3833 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3834 && !root->fs_info->log_root_recovering) {
3835 btrfs_update_root_times(trans, root);
3837 ret = btrfs_delayed_update_inode(trans, root, inode);
3839 btrfs_set_inode_last_trans(trans, inode);
3843 return btrfs_update_inode_item(trans, root, inode);
3846 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3847 struct btrfs_root *root,
3848 struct inode *inode)
3852 ret = btrfs_update_inode(trans, root, inode);
3854 return btrfs_update_inode_item(trans, root, inode);
3859 * unlink helper that gets used here in inode.c and in the tree logging
3860 * recovery code. It remove a link in a directory with a given name, and
3861 * also drops the back refs in the inode to the directory
3863 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3864 struct btrfs_root *root,
3865 struct inode *dir, struct inode *inode,
3866 const char *name, int name_len)
3868 struct btrfs_path *path;
3870 struct extent_buffer *leaf;
3871 struct btrfs_dir_item *di;
3872 struct btrfs_key key;
3874 u64 ino = btrfs_ino(inode);
3875 u64 dir_ino = btrfs_ino(dir);
3877 path = btrfs_alloc_path();
3883 path->leave_spinning = 1;
3884 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3885 name, name_len, -1);
3894 leaf = path->nodes[0];
3895 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3896 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3899 btrfs_release_path(path);
3902 * If we don't have dir index, we have to get it by looking up
3903 * the inode ref, since we get the inode ref, remove it directly,
3904 * it is unnecessary to do delayed deletion.
3906 * But if we have dir index, needn't search inode ref to get it.
3907 * Since the inode ref is close to the inode item, it is better
3908 * that we delay to delete it, and just do this deletion when
3909 * we update the inode item.
3911 if (BTRFS_I(inode)->dir_index) {
3912 ret = btrfs_delayed_delete_inode_ref(inode);
3914 index = BTRFS_I(inode)->dir_index;
3919 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3922 btrfs_info(root->fs_info,
3923 "failed to delete reference to %.*s, inode %llu parent %llu",
3924 name_len, name, ino, dir_ino);
3925 btrfs_abort_transaction(trans, root, ret);
3929 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3931 btrfs_abort_transaction(trans, root, ret);
3935 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3937 if (ret != 0 && ret != -ENOENT) {
3938 btrfs_abort_transaction(trans, root, ret);
3942 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3947 btrfs_abort_transaction(trans, root, ret);
3949 btrfs_free_path(path);
3953 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3954 inode_inc_iversion(inode);
3955 inode_inc_iversion(dir);
3956 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3957 ret = btrfs_update_inode(trans, root, dir);
3962 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3963 struct btrfs_root *root,
3964 struct inode *dir, struct inode *inode,
3965 const char *name, int name_len)
3968 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3971 ret = btrfs_update_inode(trans, root, inode);
3977 * helper to start transaction for unlink and rmdir.
3979 * unlink and rmdir are special in btrfs, they do not always free space, so
3980 * if we cannot make our reservations the normal way try and see if there is
3981 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3982 * allow the unlink to occur.
3984 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3986 struct btrfs_trans_handle *trans;
3987 struct btrfs_root *root = BTRFS_I(dir)->root;
3991 * 1 for the possible orphan item
3992 * 1 for the dir item
3993 * 1 for the dir index
3994 * 1 for the inode ref
3997 trans = btrfs_start_transaction(root, 5);
3998 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
4001 if (PTR_ERR(trans) == -ENOSPC) {
4002 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
4004 trans = btrfs_start_transaction(root, 0);
4007 ret = btrfs_cond_migrate_bytes(root->fs_info,
4008 &root->fs_info->trans_block_rsv,
4011 btrfs_end_transaction(trans, root);
4012 return ERR_PTR(ret);
4014 trans->block_rsv = &root->fs_info->trans_block_rsv;
4015 trans->bytes_reserved = num_bytes;
4020 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4022 struct btrfs_root *root = BTRFS_I(dir)->root;
4023 struct btrfs_trans_handle *trans;
4024 struct inode *inode = dentry->d_inode;
4027 trans = __unlink_start_trans(dir);
4029 return PTR_ERR(trans);
4031 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
4033 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4034 dentry->d_name.name, dentry->d_name.len);
4038 if (inode->i_nlink == 0) {
4039 ret = btrfs_orphan_add(trans, inode);
4045 btrfs_end_transaction(trans, root);
4046 btrfs_btree_balance_dirty(root);
4050 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4051 struct btrfs_root *root,
4052 struct inode *dir, u64 objectid,
4053 const char *name, int name_len)
4055 struct btrfs_path *path;
4056 struct extent_buffer *leaf;
4057 struct btrfs_dir_item *di;
4058 struct btrfs_key key;
4061 u64 dir_ino = btrfs_ino(dir);
4063 path = btrfs_alloc_path();
4067 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4068 name, name_len, -1);
4069 if (IS_ERR_OR_NULL(di)) {
4077 leaf = path->nodes[0];
4078 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4079 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4080 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4082 btrfs_abort_transaction(trans, root, ret);
4085 btrfs_release_path(path);
4087 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4088 objectid, root->root_key.objectid,
4089 dir_ino, &index, name, name_len);
4091 if (ret != -ENOENT) {
4092 btrfs_abort_transaction(trans, root, ret);
4095 di = btrfs_search_dir_index_item(root, path, dir_ino,
4097 if (IS_ERR_OR_NULL(di)) {
4102 btrfs_abort_transaction(trans, root, ret);
4106 leaf = path->nodes[0];
4107 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4108 btrfs_release_path(path);
4111 btrfs_release_path(path);
4113 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4115 btrfs_abort_transaction(trans, root, ret);
4119 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4120 inode_inc_iversion(dir);
4121 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4122 ret = btrfs_update_inode_fallback(trans, root, dir);
4124 btrfs_abort_transaction(trans, root, ret);
4126 btrfs_free_path(path);
4130 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4132 struct inode *inode = dentry->d_inode;
4134 struct btrfs_root *root = BTRFS_I(dir)->root;
4135 struct btrfs_trans_handle *trans;
4137 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4139 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4142 trans = __unlink_start_trans(dir);
4144 return PTR_ERR(trans);
4146 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4147 err = btrfs_unlink_subvol(trans, root, dir,
4148 BTRFS_I(inode)->location.objectid,
4149 dentry->d_name.name,
4150 dentry->d_name.len);
4154 err = btrfs_orphan_add(trans, inode);
4158 /* now the directory is empty */
4159 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4160 dentry->d_name.name, dentry->d_name.len);
4162 btrfs_i_size_write(inode, 0);
4164 btrfs_end_transaction(trans, root);
4165 btrfs_btree_balance_dirty(root);
4170 static int truncate_space_check(struct btrfs_trans_handle *trans,
4171 struct btrfs_root *root,
4176 bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4177 ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4178 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4180 trans->bytes_reserved += bytes_deleted;
4186 * this can truncate away extent items, csum items and directory items.
4187 * It starts at a high offset and removes keys until it can't find
4188 * any higher than new_size
4190 * csum items that cross the new i_size are truncated to the new size
4193 * min_type is the minimum key type to truncate down to. If set to 0, this
4194 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4196 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4197 struct btrfs_root *root,
4198 struct inode *inode,
4199 u64 new_size, u32 min_type)
4201 struct btrfs_path *path;
4202 struct extent_buffer *leaf;
4203 struct btrfs_file_extent_item *fi;
4204 struct btrfs_key key;
4205 struct btrfs_key found_key;
4206 u64 extent_start = 0;
4207 u64 extent_num_bytes = 0;
4208 u64 extent_offset = 0;
4210 u64 last_size = (u64)-1;
4211 u32 found_type = (u8)-1;
4214 int pending_del_nr = 0;
4215 int pending_del_slot = 0;
4216 int extent_type = -1;
4219 u64 ino = btrfs_ino(inode);
4220 u64 bytes_deleted = 0;
4222 bool should_throttle = 0;
4223 bool should_end = 0;
4225 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4228 * for non-free space inodes and ref cows, we want to back off from
4231 if (!btrfs_is_free_space_inode(inode) &&
4232 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4235 path = btrfs_alloc_path();
4241 * We want to drop from the next block forward in case this new size is
4242 * not block aligned since we will be keeping the last block of the
4243 * extent just the way it is.
4245 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4246 root == root->fs_info->tree_root)
4247 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4248 root->sectorsize), (u64)-1, 0);
4251 * This function is also used to drop the items in the log tree before
4252 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4253 * it is used to drop the loged items. So we shouldn't kill the delayed
4256 if (min_type == 0 && root == BTRFS_I(inode)->root)
4257 btrfs_kill_delayed_inode_items(inode);
4260 key.offset = (u64)-1;
4265 * with a 16K leaf size and 128MB extents, you can actually queue
4266 * up a huge file in a single leaf. Most of the time that
4267 * bytes_deleted is > 0, it will be huge by the time we get here
4269 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4270 if (btrfs_should_end_transaction(trans, root)) {
4277 path->leave_spinning = 1;
4278 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4285 /* there are no items in the tree for us to truncate, we're
4288 if (path->slots[0] == 0)
4295 leaf = path->nodes[0];
4296 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4297 found_type = found_key.type;
4299 if (found_key.objectid != ino)
4302 if (found_type < min_type)
4305 item_end = found_key.offset;
4306 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4307 fi = btrfs_item_ptr(leaf, path->slots[0],
4308 struct btrfs_file_extent_item);
4309 extent_type = btrfs_file_extent_type(leaf, fi);
4310 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4312 btrfs_file_extent_num_bytes(leaf, fi);
4313 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4314 item_end += btrfs_file_extent_inline_len(leaf,
4315 path->slots[0], fi);
4319 if (found_type > min_type) {
4322 if (item_end < new_size)
4324 if (found_key.offset >= new_size)
4330 /* FIXME, shrink the extent if the ref count is only 1 */
4331 if (found_type != BTRFS_EXTENT_DATA_KEY)
4335 last_size = found_key.offset;
4337 last_size = new_size;
4339 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4341 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4343 u64 orig_num_bytes =
4344 btrfs_file_extent_num_bytes(leaf, fi);
4345 extent_num_bytes = ALIGN(new_size -
4348 btrfs_set_file_extent_num_bytes(leaf, fi,
4350 num_dec = (orig_num_bytes -
4352 if (test_bit(BTRFS_ROOT_REF_COWS,
4355 inode_sub_bytes(inode, num_dec);
4356 btrfs_mark_buffer_dirty(leaf);
4359 btrfs_file_extent_disk_num_bytes(leaf,
4361 extent_offset = found_key.offset -
4362 btrfs_file_extent_offset(leaf, fi);
4364 /* FIXME blocksize != 4096 */
4365 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4366 if (extent_start != 0) {
4368 if (test_bit(BTRFS_ROOT_REF_COWS,
4370 inode_sub_bytes(inode, num_dec);
4373 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4375 * we can't truncate inline items that have had
4379 btrfs_file_extent_compression(leaf, fi) == 0 &&
4380 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4381 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4382 u32 size = new_size - found_key.offset;
4384 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4385 inode_sub_bytes(inode, item_end + 1 -
4389 * update the ram bytes to properly reflect
4390 * the new size of our item
4392 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4394 btrfs_file_extent_calc_inline_size(size);
4395 btrfs_truncate_item(root, path, size, 1);
4396 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4398 inode_sub_bytes(inode, item_end + 1 -
4404 if (!pending_del_nr) {
4405 /* no pending yet, add ourselves */
4406 pending_del_slot = path->slots[0];
4408 } else if (pending_del_nr &&
4409 path->slots[0] + 1 == pending_del_slot) {
4410 /* hop on the pending chunk */
4412 pending_del_slot = path->slots[0];
4419 should_throttle = 0;
4422 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4423 root == root->fs_info->tree_root)) {
4424 btrfs_set_path_blocking(path);
4425 bytes_deleted += extent_num_bytes;
4426 ret = btrfs_free_extent(trans, root, extent_start,
4427 extent_num_bytes, 0,
4428 btrfs_header_owner(leaf),
4429 ino, extent_offset, 0);
4431 if (btrfs_should_throttle_delayed_refs(trans, root))
4432 btrfs_async_run_delayed_refs(root,
4433 trans->delayed_ref_updates * 2, 0);
4435 if (truncate_space_check(trans, root,
4436 extent_num_bytes)) {
4439 if (btrfs_should_throttle_delayed_refs(trans,
4441 should_throttle = 1;
4446 if (found_type == BTRFS_INODE_ITEM_KEY)
4449 if (path->slots[0] == 0 ||
4450 path->slots[0] != pending_del_slot ||
4451 should_throttle || should_end) {
4452 if (pending_del_nr) {
4453 ret = btrfs_del_items(trans, root, path,
4457 btrfs_abort_transaction(trans,
4463 btrfs_release_path(path);
4464 if (should_throttle) {
4465 unsigned long updates = trans->delayed_ref_updates;
4467 trans->delayed_ref_updates = 0;
4468 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4474 * if we failed to refill our space rsv, bail out
4475 * and let the transaction restart
4487 if (pending_del_nr) {
4488 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4491 btrfs_abort_transaction(trans, root, ret);
4494 if (last_size != (u64)-1 &&
4495 root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4496 btrfs_ordered_update_i_size(inode, last_size, NULL);
4498 btrfs_free_path(path);
4500 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4501 unsigned long updates = trans->delayed_ref_updates;
4503 trans->delayed_ref_updates = 0;
4504 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4513 * btrfs_truncate_page - read, zero a chunk and write a page
4514 * @inode - inode that we're zeroing
4515 * @from - the offset to start zeroing
4516 * @len - the length to zero, 0 to zero the entire range respective to the
4518 * @front - zero up to the offset instead of from the offset on
4520 * This will find the page for the "from" offset and cow the page and zero the
4521 * part we want to zero. This is used with truncate and hole punching.
4523 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4526 struct address_space *mapping = inode->i_mapping;
4527 struct btrfs_root *root = BTRFS_I(inode)->root;
4528 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4529 struct btrfs_ordered_extent *ordered;
4530 struct extent_state *cached_state = NULL;
4532 u32 blocksize = root->sectorsize;
4533 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4534 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4536 gfp_t mask = btrfs_alloc_write_mask(mapping);
4541 if ((offset & (blocksize - 1)) == 0 &&
4542 (!len || ((len & (blocksize - 1)) == 0)))
4544 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4549 page = find_or_create_page(mapping, index, mask);
4551 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4556 page_start = page_offset(page);
4557 page_end = page_start + PAGE_CACHE_SIZE - 1;
4559 if (!PageUptodate(page)) {
4560 ret = btrfs_readpage(NULL, page);
4562 if (page->mapping != mapping) {
4564 page_cache_release(page);
4567 if (!PageUptodate(page)) {
4572 wait_on_page_writeback(page);
4574 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4575 set_page_extent_mapped(page);
4577 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4579 unlock_extent_cached(io_tree, page_start, page_end,
4580 &cached_state, GFP_NOFS);
4582 page_cache_release(page);
4583 btrfs_start_ordered_extent(inode, ordered, 1);
4584 btrfs_put_ordered_extent(ordered);
4588 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4589 EXTENT_DIRTY | EXTENT_DELALLOC |
4590 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4591 0, 0, &cached_state, GFP_NOFS);
4593 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4596 unlock_extent_cached(io_tree, page_start, page_end,
4597 &cached_state, GFP_NOFS);
4601 if (offset != PAGE_CACHE_SIZE) {
4603 len = PAGE_CACHE_SIZE - offset;
4606 memset(kaddr, 0, offset);
4608 memset(kaddr + offset, 0, len);
4609 flush_dcache_page(page);
4612 ClearPageChecked(page);
4613 set_page_dirty(page);
4614 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4619 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4621 page_cache_release(page);
4626 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4627 u64 offset, u64 len)
4629 struct btrfs_trans_handle *trans;
4633 * Still need to make sure the inode looks like it's been updated so
4634 * that any holes get logged if we fsync.
4636 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4637 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4638 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4639 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4644 * 1 - for the one we're dropping
4645 * 1 - for the one we're adding
4646 * 1 - for updating the inode.
4648 trans = btrfs_start_transaction(root, 3);
4650 return PTR_ERR(trans);
4652 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4654 btrfs_abort_transaction(trans, root, ret);
4655 btrfs_end_transaction(trans, root);
4659 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4660 0, 0, len, 0, len, 0, 0, 0);
4662 btrfs_abort_transaction(trans, root, ret);
4664 btrfs_update_inode(trans, root, inode);
4665 btrfs_end_transaction(trans, root);
4670 * This function puts in dummy file extents for the area we're creating a hole
4671 * for. So if we are truncating this file to a larger size we need to insert
4672 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4673 * the range between oldsize and size
4675 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4677 struct btrfs_root *root = BTRFS_I(inode)->root;
4678 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4679 struct extent_map *em = NULL;
4680 struct extent_state *cached_state = NULL;
4681 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4682 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4683 u64 block_end = ALIGN(size, root->sectorsize);
4690 * If our size started in the middle of a page we need to zero out the
4691 * rest of the page before we expand the i_size, otherwise we could
4692 * expose stale data.
4694 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4698 if (size <= hole_start)
4702 struct btrfs_ordered_extent *ordered;
4704 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4706 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4707 block_end - hole_start);
4710 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4711 &cached_state, GFP_NOFS);
4712 btrfs_start_ordered_extent(inode, ordered, 1);
4713 btrfs_put_ordered_extent(ordered);
4716 cur_offset = hole_start;
4718 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4719 block_end - cur_offset, 0);
4725 last_byte = min(extent_map_end(em), block_end);
4726 last_byte = ALIGN(last_byte , root->sectorsize);
4727 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4728 struct extent_map *hole_em;
4729 hole_size = last_byte - cur_offset;
4731 err = maybe_insert_hole(root, inode, cur_offset,
4735 btrfs_drop_extent_cache(inode, cur_offset,
4736 cur_offset + hole_size - 1, 0);
4737 hole_em = alloc_extent_map();
4739 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4740 &BTRFS_I(inode)->runtime_flags);
4743 hole_em->start = cur_offset;
4744 hole_em->len = hole_size;
4745 hole_em->orig_start = cur_offset;
4747 hole_em->block_start = EXTENT_MAP_HOLE;
4748 hole_em->block_len = 0;
4749 hole_em->orig_block_len = 0;
4750 hole_em->ram_bytes = hole_size;
4751 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4752 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4753 hole_em->generation = root->fs_info->generation;
4756 write_lock(&em_tree->lock);
4757 err = add_extent_mapping(em_tree, hole_em, 1);
4758 write_unlock(&em_tree->lock);
4761 btrfs_drop_extent_cache(inode, cur_offset,
4765 free_extent_map(hole_em);
4768 free_extent_map(em);
4770 cur_offset = last_byte;
4771 if (cur_offset >= block_end)
4774 free_extent_map(em);
4775 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4780 static int wait_snapshoting_atomic_t(atomic_t *a)
4786 static void wait_for_snapshot_creation(struct btrfs_root *root)
4791 ret = btrfs_start_write_no_snapshoting(root);
4794 wait_on_atomic_t(&root->will_be_snapshoted,
4795 wait_snapshoting_atomic_t,
4796 TASK_UNINTERRUPTIBLE);
4800 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4802 struct btrfs_root *root = BTRFS_I(inode)->root;
4803 struct btrfs_trans_handle *trans;
4804 loff_t oldsize = i_size_read(inode);
4805 loff_t newsize = attr->ia_size;
4806 int mask = attr->ia_valid;
4810 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4811 * special case where we need to update the times despite not having
4812 * these flags set. For all other operations the VFS set these flags
4813 * explicitly if it wants a timestamp update.
4815 if (newsize != oldsize) {
4816 inode_inc_iversion(inode);
4817 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4818 inode->i_ctime = inode->i_mtime =
4819 current_fs_time(inode->i_sb);
4822 if (newsize > oldsize) {
4823 truncate_pagecache(inode, newsize);
4825 * Don't do an expanding truncate while snapshoting is ongoing.
4826 * This is to ensure the snapshot captures a fully consistent
4827 * state of this file - if the snapshot captures this expanding
4828 * truncation, it must capture all writes that happened before
4831 wait_for_snapshot_creation(root);
4832 ret = btrfs_cont_expand(inode, oldsize, newsize);
4834 btrfs_end_write_no_snapshoting(root);
4838 trans = btrfs_start_transaction(root, 1);
4839 if (IS_ERR(trans)) {
4840 btrfs_end_write_no_snapshoting(root);
4841 return PTR_ERR(trans);
4844 i_size_write(inode, newsize);
4845 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4846 ret = btrfs_update_inode(trans, root, inode);
4847 btrfs_end_write_no_snapshoting(root);
4848 btrfs_end_transaction(trans, root);
4852 * We're truncating a file that used to have good data down to
4853 * zero. Make sure it gets into the ordered flush list so that
4854 * any new writes get down to disk quickly.
4857 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4858 &BTRFS_I(inode)->runtime_flags);
4861 * 1 for the orphan item we're going to add
4862 * 1 for the orphan item deletion.
4864 trans = btrfs_start_transaction(root, 2);
4866 return PTR_ERR(trans);
4869 * We need to do this in case we fail at _any_ point during the
4870 * actual truncate. Once we do the truncate_setsize we could
4871 * invalidate pages which forces any outstanding ordered io to
4872 * be instantly completed which will give us extents that need
4873 * to be truncated. If we fail to get an orphan inode down we
4874 * could have left over extents that were never meant to live,
4875 * so we need to garuntee from this point on that everything
4876 * will be consistent.
4878 ret = btrfs_orphan_add(trans, inode);
4879 btrfs_end_transaction(trans, root);
4883 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4884 truncate_setsize(inode, newsize);
4886 /* Disable nonlocked read DIO to avoid the end less truncate */
4887 btrfs_inode_block_unlocked_dio(inode);
4888 inode_dio_wait(inode);
4889 btrfs_inode_resume_unlocked_dio(inode);
4891 ret = btrfs_truncate(inode);
4892 if (ret && inode->i_nlink) {
4896 * failed to truncate, disk_i_size is only adjusted down
4897 * as we remove extents, so it should represent the true
4898 * size of the inode, so reset the in memory size and
4899 * delete our orphan entry.
4901 trans = btrfs_join_transaction(root);
4902 if (IS_ERR(trans)) {
4903 btrfs_orphan_del(NULL, inode);
4906 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4907 err = btrfs_orphan_del(trans, inode);
4909 btrfs_abort_transaction(trans, root, err);
4910 btrfs_end_transaction(trans, root);
4917 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4919 struct inode *inode = dentry->d_inode;
4920 struct btrfs_root *root = BTRFS_I(inode)->root;
4923 if (btrfs_root_readonly(root))
4926 err = inode_change_ok(inode, attr);
4930 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4931 err = btrfs_setsize(inode, attr);
4936 if (attr->ia_valid) {
4937 setattr_copy(inode, attr);
4938 inode_inc_iversion(inode);
4939 err = btrfs_dirty_inode(inode);
4941 if (!err && attr->ia_valid & ATTR_MODE)
4942 err = posix_acl_chmod(inode, inode->i_mode);
4949 * While truncating the inode pages during eviction, we get the VFS calling
4950 * btrfs_invalidatepage() against each page of the inode. This is slow because
4951 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4952 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4953 * extent_state structures over and over, wasting lots of time.
4955 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4956 * those expensive operations on a per page basis and do only the ordered io
4957 * finishing, while we release here the extent_map and extent_state structures,
4958 * without the excessive merging and splitting.
4960 static void evict_inode_truncate_pages(struct inode *inode)
4962 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4963 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4964 struct rb_node *node;
4966 ASSERT(inode->i_state & I_FREEING);
4967 truncate_inode_pages_final(&inode->i_data);
4969 write_lock(&map_tree->lock);
4970 while (!RB_EMPTY_ROOT(&map_tree->map)) {
4971 struct extent_map *em;
4973 node = rb_first(&map_tree->map);
4974 em = rb_entry(node, struct extent_map, rb_node);
4975 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4976 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4977 remove_extent_mapping(map_tree, em);
4978 free_extent_map(em);
4979 if (need_resched()) {
4980 write_unlock(&map_tree->lock);
4982 write_lock(&map_tree->lock);
4985 write_unlock(&map_tree->lock);
4987 spin_lock(&io_tree->lock);
4988 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4989 struct extent_state *state;
4990 struct extent_state *cached_state = NULL;
4992 node = rb_first(&io_tree->state);
4993 state = rb_entry(node, struct extent_state, rb_node);
4994 atomic_inc(&state->refs);
4995 spin_unlock(&io_tree->lock);
4997 lock_extent_bits(io_tree, state->start, state->end,
4999 clear_extent_bit(io_tree, state->start, state->end,
5000 EXTENT_LOCKED | EXTENT_DIRTY |
5001 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5002 EXTENT_DEFRAG, 1, 1,
5003 &cached_state, GFP_NOFS);
5004 free_extent_state(state);
5007 spin_lock(&io_tree->lock);
5009 spin_unlock(&io_tree->lock);
5012 void btrfs_evict_inode(struct inode *inode)
5014 struct btrfs_trans_handle *trans;
5015 struct btrfs_root *root = BTRFS_I(inode)->root;
5016 struct btrfs_block_rsv *rsv, *global_rsv;
5017 int steal_from_global = 0;
5018 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5021 trace_btrfs_inode_evict(inode);
5023 evict_inode_truncate_pages(inode);
5025 if (inode->i_nlink &&
5026 ((btrfs_root_refs(&root->root_item) != 0 &&
5027 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5028 btrfs_is_free_space_inode(inode)))
5031 if (is_bad_inode(inode)) {
5032 btrfs_orphan_del(NULL, inode);
5035 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5036 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5038 btrfs_free_io_failure_record(inode, 0, (u64)-1);
5040 if (root->fs_info->log_root_recovering) {
5041 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5042 &BTRFS_I(inode)->runtime_flags));
5046 if (inode->i_nlink > 0) {
5047 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5048 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5052 ret = btrfs_commit_inode_delayed_inode(inode);
5054 btrfs_orphan_del(NULL, inode);
5058 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5060 btrfs_orphan_del(NULL, inode);
5063 rsv->size = min_size;
5065 global_rsv = &root->fs_info->global_block_rsv;
5067 btrfs_i_size_write(inode, 0);
5070 * This is a bit simpler than btrfs_truncate since we've already
5071 * reserved our space for our orphan item in the unlink, so we just
5072 * need to reserve some slack space in case we add bytes and update
5073 * inode item when doing the truncate.
5076 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5077 BTRFS_RESERVE_FLUSH_LIMIT);
5080 * Try and steal from the global reserve since we will
5081 * likely not use this space anyway, we want to try as
5082 * hard as possible to get this to work.
5085 steal_from_global++;
5087 steal_from_global = 0;
5091 * steal_from_global == 0: we reserved stuff, hooray!
5092 * steal_from_global == 1: we didn't reserve stuff, boo!
5093 * steal_from_global == 2: we've committed, still not a lot of
5094 * room but maybe we'll have room in the global reserve this
5096 * steal_from_global == 3: abandon all hope!
5098 if (steal_from_global > 2) {
5099 btrfs_warn(root->fs_info,
5100 "Could not get space for a delete, will truncate on mount %d",
5102 btrfs_orphan_del(NULL, inode);
5103 btrfs_free_block_rsv(root, rsv);
5107 trans = btrfs_join_transaction(root);
5108 if (IS_ERR(trans)) {
5109 btrfs_orphan_del(NULL, inode);
5110 btrfs_free_block_rsv(root, rsv);
5115 * We can't just steal from the global reserve, we need tomake
5116 * sure there is room to do it, if not we need to commit and try
5119 if (steal_from_global) {
5120 if (!btrfs_check_space_for_delayed_refs(trans, root))
5121 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5128 * Couldn't steal from the global reserve, we have too much
5129 * pending stuff built up, commit the transaction and try it
5133 ret = btrfs_commit_transaction(trans, root);
5135 btrfs_orphan_del(NULL, inode);
5136 btrfs_free_block_rsv(root, rsv);
5141 steal_from_global = 0;
5144 trans->block_rsv = rsv;
5146 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5147 if (ret != -ENOSPC && ret != -EAGAIN)
5150 trans->block_rsv = &root->fs_info->trans_block_rsv;
5151 btrfs_end_transaction(trans, root);
5153 btrfs_btree_balance_dirty(root);
5156 btrfs_free_block_rsv(root, rsv);
5159 * Errors here aren't a big deal, it just means we leave orphan items
5160 * in the tree. They will be cleaned up on the next mount.
5163 trans->block_rsv = root->orphan_block_rsv;
5164 btrfs_orphan_del(trans, inode);
5166 btrfs_orphan_del(NULL, inode);
5169 trans->block_rsv = &root->fs_info->trans_block_rsv;
5170 if (!(root == root->fs_info->tree_root ||
5171 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5172 btrfs_return_ino(root, btrfs_ino(inode));
5174 btrfs_end_transaction(trans, root);
5175 btrfs_btree_balance_dirty(root);
5177 btrfs_remove_delayed_node(inode);
5183 * this returns the key found in the dir entry in the location pointer.
5184 * If no dir entries were found, location->objectid is 0.
5186 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5187 struct btrfs_key *location)
5189 const char *name = dentry->d_name.name;
5190 int namelen = dentry->d_name.len;
5191 struct btrfs_dir_item *di;
5192 struct btrfs_path *path;
5193 struct btrfs_root *root = BTRFS_I(dir)->root;
5196 path = btrfs_alloc_path();
5200 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5205 if (IS_ERR_OR_NULL(di))
5208 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5210 btrfs_free_path(path);
5213 location->objectid = 0;
5218 * when we hit a tree root in a directory, the btrfs part of the inode
5219 * needs to be changed to reflect the root directory of the tree root. This
5220 * is kind of like crossing a mount point.
5222 static int fixup_tree_root_location(struct btrfs_root *root,
5224 struct dentry *dentry,
5225 struct btrfs_key *location,
5226 struct btrfs_root **sub_root)
5228 struct btrfs_path *path;
5229 struct btrfs_root *new_root;
5230 struct btrfs_root_ref *ref;
5231 struct extent_buffer *leaf;
5232 struct btrfs_key key;
5236 path = btrfs_alloc_path();
5243 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5244 key.type = BTRFS_ROOT_REF_KEY;
5245 key.offset = location->objectid;
5247 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5255 leaf = path->nodes[0];
5256 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5257 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5258 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5261 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5262 (unsigned long)(ref + 1),
5263 dentry->d_name.len);
5267 btrfs_release_path(path);
5269 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5270 if (IS_ERR(new_root)) {
5271 err = PTR_ERR(new_root);
5275 *sub_root = new_root;
5276 location->objectid = btrfs_root_dirid(&new_root->root_item);
5277 location->type = BTRFS_INODE_ITEM_KEY;
5278 location->offset = 0;
5281 btrfs_free_path(path);
5285 static void inode_tree_add(struct inode *inode)
5287 struct btrfs_root *root = BTRFS_I(inode)->root;
5288 struct btrfs_inode *entry;
5290 struct rb_node *parent;
5291 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5292 u64 ino = btrfs_ino(inode);
5294 if (inode_unhashed(inode))
5297 spin_lock(&root->inode_lock);
5298 p = &root->inode_tree.rb_node;
5301 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5303 if (ino < btrfs_ino(&entry->vfs_inode))
5304 p = &parent->rb_left;
5305 else if (ino > btrfs_ino(&entry->vfs_inode))
5306 p = &parent->rb_right;
5308 WARN_ON(!(entry->vfs_inode.i_state &
5309 (I_WILL_FREE | I_FREEING)));
5310 rb_replace_node(parent, new, &root->inode_tree);
5311 RB_CLEAR_NODE(parent);
5312 spin_unlock(&root->inode_lock);
5316 rb_link_node(new, parent, p);
5317 rb_insert_color(new, &root->inode_tree);
5318 spin_unlock(&root->inode_lock);
5321 static void inode_tree_del(struct inode *inode)
5323 struct btrfs_root *root = BTRFS_I(inode)->root;
5326 spin_lock(&root->inode_lock);
5327 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5328 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5329 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5330 empty = RB_EMPTY_ROOT(&root->inode_tree);
5332 spin_unlock(&root->inode_lock);
5334 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5335 synchronize_srcu(&root->fs_info->subvol_srcu);
5336 spin_lock(&root->inode_lock);
5337 empty = RB_EMPTY_ROOT(&root->inode_tree);
5338 spin_unlock(&root->inode_lock);
5340 btrfs_add_dead_root(root);
5344 void btrfs_invalidate_inodes(struct btrfs_root *root)
5346 struct rb_node *node;
5347 struct rb_node *prev;
5348 struct btrfs_inode *entry;
5349 struct inode *inode;
5352 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5353 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5355 spin_lock(&root->inode_lock);
5357 node = root->inode_tree.rb_node;
5361 entry = rb_entry(node, struct btrfs_inode, rb_node);
5363 if (objectid < btrfs_ino(&entry->vfs_inode))
5364 node = node->rb_left;
5365 else if (objectid > btrfs_ino(&entry->vfs_inode))
5366 node = node->rb_right;
5372 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5373 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5377 prev = rb_next(prev);
5381 entry = rb_entry(node, struct btrfs_inode, rb_node);
5382 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5383 inode = igrab(&entry->vfs_inode);
5385 spin_unlock(&root->inode_lock);
5386 if (atomic_read(&inode->i_count) > 1)
5387 d_prune_aliases(inode);
5389 * btrfs_drop_inode will have it removed from
5390 * the inode cache when its usage count
5395 spin_lock(&root->inode_lock);
5399 if (cond_resched_lock(&root->inode_lock))
5402 node = rb_next(node);
5404 spin_unlock(&root->inode_lock);
5407 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5409 struct btrfs_iget_args *args = p;
5410 inode->i_ino = args->location->objectid;
5411 memcpy(&BTRFS_I(inode)->location, args->location,
5412 sizeof(*args->location));
5413 BTRFS_I(inode)->root = args->root;
5417 static int btrfs_find_actor(struct inode *inode, void *opaque)
5419 struct btrfs_iget_args *args = opaque;
5420 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5421 args->root == BTRFS_I(inode)->root;
5424 static struct inode *btrfs_iget_locked(struct super_block *s,
5425 struct btrfs_key *location,
5426 struct btrfs_root *root)
5428 struct inode *inode;
5429 struct btrfs_iget_args args;
5430 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5432 args.location = location;
5435 inode = iget5_locked(s, hashval, btrfs_find_actor,
5436 btrfs_init_locked_inode,
5441 /* Get an inode object given its location and corresponding root.
5442 * Returns in *is_new if the inode was read from disk
5444 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5445 struct btrfs_root *root, int *new)
5447 struct inode *inode;
5449 inode = btrfs_iget_locked(s, location, root);
5451 return ERR_PTR(-ENOMEM);
5453 if (inode->i_state & I_NEW) {
5454 btrfs_read_locked_inode(inode);
5455 if (!is_bad_inode(inode)) {
5456 inode_tree_add(inode);
5457 unlock_new_inode(inode);
5461 unlock_new_inode(inode);
5463 inode = ERR_PTR(-ESTALE);
5470 static struct inode *new_simple_dir(struct super_block *s,
5471 struct btrfs_key *key,
5472 struct btrfs_root *root)
5474 struct inode *inode = new_inode(s);
5477 return ERR_PTR(-ENOMEM);
5479 BTRFS_I(inode)->root = root;
5480 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5481 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5483 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5484 inode->i_op = &btrfs_dir_ro_inode_operations;
5485 inode->i_fop = &simple_dir_operations;
5486 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5487 inode->i_mtime = CURRENT_TIME;
5488 inode->i_atime = inode->i_mtime;
5489 inode->i_ctime = inode->i_mtime;
5490 BTRFS_I(inode)->i_otime = inode->i_mtime;
5495 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5497 struct inode *inode;
5498 struct btrfs_root *root = BTRFS_I(dir)->root;
5499 struct btrfs_root *sub_root = root;
5500 struct btrfs_key location;
5504 if (dentry->d_name.len > BTRFS_NAME_LEN)
5505 return ERR_PTR(-ENAMETOOLONG);
5507 ret = btrfs_inode_by_name(dir, dentry, &location);
5509 return ERR_PTR(ret);
5511 if (location.objectid == 0)
5512 return ERR_PTR(-ENOENT);
5514 if (location.type == BTRFS_INODE_ITEM_KEY) {
5515 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5519 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5521 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5522 ret = fixup_tree_root_location(root, dir, dentry,
5523 &location, &sub_root);
5526 inode = ERR_PTR(ret);
5528 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5530 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5532 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5534 if (!IS_ERR(inode) && root != sub_root) {
5535 down_read(&root->fs_info->cleanup_work_sem);
5536 if (!(inode->i_sb->s_flags & MS_RDONLY))
5537 ret = btrfs_orphan_cleanup(sub_root);
5538 up_read(&root->fs_info->cleanup_work_sem);
5541 inode = ERR_PTR(ret);
5548 static int btrfs_dentry_delete(const struct dentry *dentry)
5550 struct btrfs_root *root;
5551 struct inode *inode = dentry->d_inode;
5553 if (!inode && !IS_ROOT(dentry))
5554 inode = dentry->d_parent->d_inode;
5557 root = BTRFS_I(inode)->root;
5558 if (btrfs_root_refs(&root->root_item) == 0)
5561 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5567 static void btrfs_dentry_release(struct dentry *dentry)
5569 kfree(dentry->d_fsdata);
5572 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5575 struct inode *inode;
5577 inode = btrfs_lookup_dentry(dir, dentry);
5578 if (IS_ERR(inode)) {
5579 if (PTR_ERR(inode) == -ENOENT)
5582 return ERR_CAST(inode);
5585 return d_splice_alias(inode, dentry);
5588 unsigned char btrfs_filetype_table[] = {
5589 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5592 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5594 struct inode *inode = file_inode(file);
5595 struct btrfs_root *root = BTRFS_I(inode)->root;
5596 struct btrfs_item *item;
5597 struct btrfs_dir_item *di;
5598 struct btrfs_key key;
5599 struct btrfs_key found_key;
5600 struct btrfs_path *path;
5601 struct list_head ins_list;
5602 struct list_head del_list;
5604 struct extent_buffer *leaf;
5606 unsigned char d_type;
5611 int key_type = BTRFS_DIR_INDEX_KEY;
5615 int is_curr = 0; /* ctx->pos points to the current index? */
5617 /* FIXME, use a real flag for deciding about the key type */
5618 if (root->fs_info->tree_root == root)
5619 key_type = BTRFS_DIR_ITEM_KEY;
5621 if (!dir_emit_dots(file, ctx))
5624 path = btrfs_alloc_path();
5630 if (key_type == BTRFS_DIR_INDEX_KEY) {
5631 INIT_LIST_HEAD(&ins_list);
5632 INIT_LIST_HEAD(&del_list);
5633 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5636 key.type = key_type;
5637 key.offset = ctx->pos;
5638 key.objectid = btrfs_ino(inode);
5640 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5645 leaf = path->nodes[0];
5646 slot = path->slots[0];
5647 if (slot >= btrfs_header_nritems(leaf)) {
5648 ret = btrfs_next_leaf(root, path);
5656 item = btrfs_item_nr(slot);
5657 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5659 if (found_key.objectid != key.objectid)
5661 if (found_key.type != key_type)
5663 if (found_key.offset < ctx->pos)
5665 if (key_type == BTRFS_DIR_INDEX_KEY &&
5666 btrfs_should_delete_dir_index(&del_list,
5670 ctx->pos = found_key.offset;
5673 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5675 di_total = btrfs_item_size(leaf, item);
5677 while (di_cur < di_total) {
5678 struct btrfs_key location;
5680 if (verify_dir_item(root, leaf, di))
5683 name_len = btrfs_dir_name_len(leaf, di);
5684 if (name_len <= sizeof(tmp_name)) {
5685 name_ptr = tmp_name;
5687 name_ptr = kmalloc(name_len, GFP_NOFS);
5693 read_extent_buffer(leaf, name_ptr,
5694 (unsigned long)(di + 1), name_len);
5696 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5697 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5700 /* is this a reference to our own snapshot? If so
5703 * In contrast to old kernels, we insert the snapshot's
5704 * dir item and dir index after it has been created, so
5705 * we won't find a reference to our own snapshot. We
5706 * still keep the following code for backward
5709 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5710 location.objectid == root->root_key.objectid) {
5714 over = !dir_emit(ctx, name_ptr, name_len,
5715 location.objectid, d_type);
5718 if (name_ptr != tmp_name)
5723 di_len = btrfs_dir_name_len(leaf, di) +
5724 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5726 di = (struct btrfs_dir_item *)((char *)di + di_len);
5732 if (key_type == BTRFS_DIR_INDEX_KEY) {
5735 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5740 /* Reached end of directory/root. Bump pos past the last item. */
5744 * Stop new entries from being returned after we return the last
5747 * New directory entries are assigned a strictly increasing
5748 * offset. This means that new entries created during readdir
5749 * are *guaranteed* to be seen in the future by that readdir.
5750 * This has broken buggy programs which operate on names as
5751 * they're returned by readdir. Until we re-use freed offsets
5752 * we have this hack to stop new entries from being returned
5753 * under the assumption that they'll never reach this huge
5756 * This is being careful not to overflow 32bit loff_t unless the
5757 * last entry requires it because doing so has broken 32bit apps
5760 if (key_type == BTRFS_DIR_INDEX_KEY) {
5761 if (ctx->pos >= INT_MAX)
5762 ctx->pos = LLONG_MAX;
5769 if (key_type == BTRFS_DIR_INDEX_KEY)
5770 btrfs_put_delayed_items(&ins_list, &del_list);
5771 btrfs_free_path(path);
5775 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5777 struct btrfs_root *root = BTRFS_I(inode)->root;
5778 struct btrfs_trans_handle *trans;
5780 bool nolock = false;
5782 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5785 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5788 if (wbc->sync_mode == WB_SYNC_ALL) {
5790 trans = btrfs_join_transaction_nolock(root);
5792 trans = btrfs_join_transaction(root);
5794 return PTR_ERR(trans);
5795 ret = btrfs_commit_transaction(trans, root);
5801 * This is somewhat expensive, updating the tree every time the
5802 * inode changes. But, it is most likely to find the inode in cache.
5803 * FIXME, needs more benchmarking...there are no reasons other than performance
5804 * to keep or drop this code.
5806 static int btrfs_dirty_inode(struct inode *inode)
5808 struct btrfs_root *root = BTRFS_I(inode)->root;
5809 struct btrfs_trans_handle *trans;
5812 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5815 trans = btrfs_join_transaction(root);
5817 return PTR_ERR(trans);
5819 ret = btrfs_update_inode(trans, root, inode);
5820 if (ret && ret == -ENOSPC) {
5821 /* whoops, lets try again with the full transaction */
5822 btrfs_end_transaction(trans, root);
5823 trans = btrfs_start_transaction(root, 1);
5825 return PTR_ERR(trans);
5827 ret = btrfs_update_inode(trans, root, inode);
5829 btrfs_end_transaction(trans, root);
5830 if (BTRFS_I(inode)->delayed_node)
5831 btrfs_balance_delayed_items(root);
5837 * This is a copy of file_update_time. We need this so we can return error on
5838 * ENOSPC for updating the inode in the case of file write and mmap writes.
5840 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5843 struct btrfs_root *root = BTRFS_I(inode)->root;
5845 if (btrfs_root_readonly(root))
5848 if (flags & S_VERSION)
5849 inode_inc_iversion(inode);
5850 if (flags & S_CTIME)
5851 inode->i_ctime = *now;
5852 if (flags & S_MTIME)
5853 inode->i_mtime = *now;
5854 if (flags & S_ATIME)
5855 inode->i_atime = *now;
5856 return btrfs_dirty_inode(inode);
5860 * find the highest existing sequence number in a directory
5861 * and then set the in-memory index_cnt variable to reflect
5862 * free sequence numbers
5864 static int btrfs_set_inode_index_count(struct inode *inode)
5866 struct btrfs_root *root = BTRFS_I(inode)->root;
5867 struct btrfs_key key, found_key;
5868 struct btrfs_path *path;
5869 struct extent_buffer *leaf;
5872 key.objectid = btrfs_ino(inode);
5873 key.type = BTRFS_DIR_INDEX_KEY;
5874 key.offset = (u64)-1;
5876 path = btrfs_alloc_path();
5880 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5883 /* FIXME: we should be able to handle this */
5889 * MAGIC NUMBER EXPLANATION:
5890 * since we search a directory based on f_pos we have to start at 2
5891 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5892 * else has to start at 2
5894 if (path->slots[0] == 0) {
5895 BTRFS_I(inode)->index_cnt = 2;
5901 leaf = path->nodes[0];
5902 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5904 if (found_key.objectid != btrfs_ino(inode) ||
5905 found_key.type != BTRFS_DIR_INDEX_KEY) {
5906 BTRFS_I(inode)->index_cnt = 2;
5910 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5912 btrfs_free_path(path);
5917 * helper to find a free sequence number in a given directory. This current
5918 * code is very simple, later versions will do smarter things in the btree
5920 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5924 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5925 ret = btrfs_inode_delayed_dir_index_count(dir);
5927 ret = btrfs_set_inode_index_count(dir);
5933 *index = BTRFS_I(dir)->index_cnt;
5934 BTRFS_I(dir)->index_cnt++;
5939 static int btrfs_insert_inode_locked(struct inode *inode)
5941 struct btrfs_iget_args args;
5942 args.location = &BTRFS_I(inode)->location;
5943 args.root = BTRFS_I(inode)->root;
5945 return insert_inode_locked4(inode,
5946 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5947 btrfs_find_actor, &args);
5950 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5951 struct btrfs_root *root,
5953 const char *name, int name_len,
5954 u64 ref_objectid, u64 objectid,
5955 umode_t mode, u64 *index)
5957 struct inode *inode;
5958 struct btrfs_inode_item *inode_item;
5959 struct btrfs_key *location;
5960 struct btrfs_path *path;
5961 struct btrfs_inode_ref *ref;
5962 struct btrfs_key key[2];
5964 int nitems = name ? 2 : 1;
5968 path = btrfs_alloc_path();
5970 return ERR_PTR(-ENOMEM);
5972 inode = new_inode(root->fs_info->sb);
5974 btrfs_free_path(path);
5975 return ERR_PTR(-ENOMEM);
5979 * O_TMPFILE, set link count to 0, so that after this point,
5980 * we fill in an inode item with the correct link count.
5983 set_nlink(inode, 0);
5986 * we have to initialize this early, so we can reclaim the inode
5987 * number if we fail afterwards in this function.
5989 inode->i_ino = objectid;
5992 trace_btrfs_inode_request(dir);
5994 ret = btrfs_set_inode_index(dir, index);
5996 btrfs_free_path(path);
5998 return ERR_PTR(ret);
6004 * index_cnt is ignored for everything but a dir,
6005 * btrfs_get_inode_index_count has an explanation for the magic
6008 BTRFS_I(inode)->index_cnt = 2;
6009 BTRFS_I(inode)->dir_index = *index;
6010 BTRFS_I(inode)->root = root;
6011 BTRFS_I(inode)->generation = trans->transid;
6012 inode->i_generation = BTRFS_I(inode)->generation;
6015 * We could have gotten an inode number from somebody who was fsynced
6016 * and then removed in this same transaction, so let's just set full
6017 * sync since it will be a full sync anyway and this will blow away the
6018 * old info in the log.
6020 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6022 key[0].objectid = objectid;
6023 key[0].type = BTRFS_INODE_ITEM_KEY;
6026 sizes[0] = sizeof(struct btrfs_inode_item);
6030 * Start new inodes with an inode_ref. This is slightly more
6031 * efficient for small numbers of hard links since they will
6032 * be packed into one item. Extended refs will kick in if we
6033 * add more hard links than can fit in the ref item.
6035 key[1].objectid = objectid;
6036 key[1].type = BTRFS_INODE_REF_KEY;
6037 key[1].offset = ref_objectid;
6039 sizes[1] = name_len + sizeof(*ref);
6042 location = &BTRFS_I(inode)->location;
6043 location->objectid = objectid;
6044 location->offset = 0;
6045 location->type = BTRFS_INODE_ITEM_KEY;
6047 ret = btrfs_insert_inode_locked(inode);
6051 path->leave_spinning = 1;
6052 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6056 inode_init_owner(inode, dir, mode);
6057 inode_set_bytes(inode, 0);
6059 inode->i_mtime = CURRENT_TIME;
6060 inode->i_atime = inode->i_mtime;
6061 inode->i_ctime = inode->i_mtime;
6062 BTRFS_I(inode)->i_otime = inode->i_mtime;
6064 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6065 struct btrfs_inode_item);
6066 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
6067 sizeof(*inode_item));
6068 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6071 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6072 struct btrfs_inode_ref);
6073 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6074 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6075 ptr = (unsigned long)(ref + 1);
6076 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6079 btrfs_mark_buffer_dirty(path->nodes[0]);
6080 btrfs_free_path(path);
6082 btrfs_inherit_iflags(inode, dir);
6084 if (S_ISREG(mode)) {
6085 if (btrfs_test_opt(root, NODATASUM))
6086 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6087 if (btrfs_test_opt(root, NODATACOW))
6088 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6089 BTRFS_INODE_NODATASUM;
6092 inode_tree_add(inode);
6094 trace_btrfs_inode_new(inode);
6095 btrfs_set_inode_last_trans(trans, inode);
6097 btrfs_update_root_times(trans, root);
6099 ret = btrfs_inode_inherit_props(trans, inode, dir);
6101 btrfs_err(root->fs_info,
6102 "error inheriting props for ino %llu (root %llu): %d",
6103 btrfs_ino(inode), root->root_key.objectid, ret);
6108 unlock_new_inode(inode);
6111 BTRFS_I(dir)->index_cnt--;
6112 btrfs_free_path(path);
6114 return ERR_PTR(ret);
6117 static inline u8 btrfs_inode_type(struct inode *inode)
6119 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6123 * utility function to add 'inode' into 'parent_inode' with
6124 * a give name and a given sequence number.
6125 * if 'add_backref' is true, also insert a backref from the
6126 * inode to the parent directory.
6128 int btrfs_add_link(struct btrfs_trans_handle *trans,
6129 struct inode *parent_inode, struct inode *inode,
6130 const char *name, int name_len, int add_backref, u64 index)
6133 struct btrfs_key key;
6134 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
6135 u64 ino = btrfs_ino(inode);
6136 u64 parent_ino = btrfs_ino(parent_inode);
6138 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6139 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6142 key.type = BTRFS_INODE_ITEM_KEY;
6146 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6147 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6148 key.objectid, root->root_key.objectid,
6149 parent_ino, index, name, name_len);
6150 } else if (add_backref) {
6151 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6155 /* Nothing to clean up yet */
6159 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6161 btrfs_inode_type(inode), index);
6162 if (ret == -EEXIST || ret == -EOVERFLOW)
6165 btrfs_abort_transaction(trans, root, ret);
6169 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6171 inode_inc_iversion(parent_inode);
6172 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
6173 ret = btrfs_update_inode(trans, root, parent_inode);
6175 btrfs_abort_transaction(trans, root, ret);
6179 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6182 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6183 key.objectid, root->root_key.objectid,
6184 parent_ino, &local_index, name, name_len);
6186 } else if (add_backref) {
6190 err = btrfs_del_inode_ref(trans, root, name, name_len,
6191 ino, parent_ino, &local_index);
6196 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6197 struct inode *dir, struct dentry *dentry,
6198 struct inode *inode, int backref, u64 index)
6200 int err = btrfs_add_link(trans, dir, inode,
6201 dentry->d_name.name, dentry->d_name.len,
6208 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6209 umode_t mode, dev_t rdev)
6211 struct btrfs_trans_handle *trans;
6212 struct btrfs_root *root = BTRFS_I(dir)->root;
6213 struct inode *inode = NULL;
6219 if (!new_valid_dev(rdev))
6223 * 2 for inode item and ref
6225 * 1 for xattr if selinux is on
6227 trans = btrfs_start_transaction(root, 5);
6229 return PTR_ERR(trans);
6231 err = btrfs_find_free_ino(root, &objectid);
6235 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6236 dentry->d_name.len, btrfs_ino(dir), objectid,
6238 if (IS_ERR(inode)) {
6239 err = PTR_ERR(inode);
6244 * If the active LSM wants to access the inode during
6245 * d_instantiate it needs these. Smack checks to see
6246 * if the filesystem supports xattrs by looking at the
6249 inode->i_op = &btrfs_special_inode_operations;
6250 init_special_inode(inode, inode->i_mode, rdev);
6252 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6254 goto out_unlock_inode;
6256 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6258 goto out_unlock_inode;
6260 btrfs_update_inode(trans, root, inode);
6261 unlock_new_inode(inode);
6262 d_instantiate(dentry, inode);
6266 btrfs_end_transaction(trans, root);
6267 btrfs_balance_delayed_items(root);
6268 btrfs_btree_balance_dirty(root);
6270 inode_dec_link_count(inode);
6277 unlock_new_inode(inode);
6282 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6283 umode_t mode, bool excl)
6285 struct btrfs_trans_handle *trans;
6286 struct btrfs_root *root = BTRFS_I(dir)->root;
6287 struct inode *inode = NULL;
6288 int drop_inode_on_err = 0;
6294 * 2 for inode item and ref
6296 * 1 for xattr if selinux is on
6298 trans = btrfs_start_transaction(root, 5);
6300 return PTR_ERR(trans);
6302 err = btrfs_find_free_ino(root, &objectid);
6306 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6307 dentry->d_name.len, btrfs_ino(dir), objectid,
6309 if (IS_ERR(inode)) {
6310 err = PTR_ERR(inode);
6313 drop_inode_on_err = 1;
6315 * If the active LSM wants to access the inode during
6316 * d_instantiate it needs these. Smack checks to see
6317 * if the filesystem supports xattrs by looking at the
6320 inode->i_fop = &btrfs_file_operations;
6321 inode->i_op = &btrfs_file_inode_operations;
6322 inode->i_mapping->a_ops = &btrfs_aops;
6324 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6326 goto out_unlock_inode;
6328 err = btrfs_update_inode(trans, root, inode);
6330 goto out_unlock_inode;
6332 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6334 goto out_unlock_inode;
6336 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6337 unlock_new_inode(inode);
6338 d_instantiate(dentry, inode);
6341 btrfs_end_transaction(trans, root);
6342 if (err && drop_inode_on_err) {
6343 inode_dec_link_count(inode);
6346 btrfs_balance_delayed_items(root);
6347 btrfs_btree_balance_dirty(root);
6351 unlock_new_inode(inode);
6356 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6357 struct dentry *dentry)
6359 struct btrfs_trans_handle *trans;
6360 struct btrfs_root *root = BTRFS_I(dir)->root;
6361 struct inode *inode = old_dentry->d_inode;
6366 /* do not allow sys_link's with other subvols of the same device */
6367 if (root->objectid != BTRFS_I(inode)->root->objectid)
6370 if (inode->i_nlink >= BTRFS_LINK_MAX)
6373 err = btrfs_set_inode_index(dir, &index);
6378 * 2 items for inode and inode ref
6379 * 2 items for dir items
6380 * 1 item for parent inode
6382 trans = btrfs_start_transaction(root, 5);
6383 if (IS_ERR(trans)) {
6384 err = PTR_ERR(trans);
6388 /* There are several dir indexes for this inode, clear the cache. */
6389 BTRFS_I(inode)->dir_index = 0ULL;
6391 inode_inc_iversion(inode);
6392 inode->i_ctime = CURRENT_TIME;
6394 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6396 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6401 struct dentry *parent = dentry->d_parent;
6402 err = btrfs_update_inode(trans, root, inode);
6405 if (inode->i_nlink == 1) {
6407 * If new hard link count is 1, it's a file created
6408 * with open(2) O_TMPFILE flag.
6410 err = btrfs_orphan_del(trans, inode);
6414 d_instantiate(dentry, inode);
6415 btrfs_log_new_name(trans, inode, NULL, parent);
6418 btrfs_end_transaction(trans, root);
6419 btrfs_balance_delayed_items(root);
6422 inode_dec_link_count(inode);
6425 btrfs_btree_balance_dirty(root);
6429 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6431 struct inode *inode = NULL;
6432 struct btrfs_trans_handle *trans;
6433 struct btrfs_root *root = BTRFS_I(dir)->root;
6435 int drop_on_err = 0;
6440 * 2 items for inode and ref
6441 * 2 items for dir items
6442 * 1 for xattr if selinux is on
6444 trans = btrfs_start_transaction(root, 5);
6446 return PTR_ERR(trans);
6448 err = btrfs_find_free_ino(root, &objectid);
6452 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6453 dentry->d_name.len, btrfs_ino(dir), objectid,
6454 S_IFDIR | mode, &index);
6455 if (IS_ERR(inode)) {
6456 err = PTR_ERR(inode);
6461 /* these must be set before we unlock the inode */
6462 inode->i_op = &btrfs_dir_inode_operations;
6463 inode->i_fop = &btrfs_dir_file_operations;
6465 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6467 goto out_fail_inode;
6469 btrfs_i_size_write(inode, 0);
6470 err = btrfs_update_inode(trans, root, inode);
6472 goto out_fail_inode;
6474 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6475 dentry->d_name.len, 0, index);
6477 goto out_fail_inode;
6479 d_instantiate(dentry, inode);
6481 * mkdir is special. We're unlocking after we call d_instantiate
6482 * to avoid a race with nfsd calling d_instantiate.
6484 unlock_new_inode(inode);
6488 btrfs_end_transaction(trans, root);
6490 inode_dec_link_count(inode);
6493 btrfs_balance_delayed_items(root);
6494 btrfs_btree_balance_dirty(root);
6498 unlock_new_inode(inode);
6502 /* Find next extent map of a given extent map, caller needs to ensure locks */
6503 static struct extent_map *next_extent_map(struct extent_map *em)
6505 struct rb_node *next;
6507 next = rb_next(&em->rb_node);
6510 return container_of(next, struct extent_map, rb_node);
6513 static struct extent_map *prev_extent_map(struct extent_map *em)
6515 struct rb_node *prev;
6517 prev = rb_prev(&em->rb_node);
6520 return container_of(prev, struct extent_map, rb_node);
6523 /* helper for btfs_get_extent. Given an existing extent in the tree,
6524 * the existing extent is the nearest extent to map_start,
6525 * and an extent that you want to insert, deal with overlap and insert
6526 * the best fitted new extent into the tree.
6528 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6529 struct extent_map *existing,
6530 struct extent_map *em,
6533 struct extent_map *prev;
6534 struct extent_map *next;
6539 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6541 if (existing->start > map_start) {
6543 prev = prev_extent_map(next);
6546 next = next_extent_map(prev);
6549 start = prev ? extent_map_end(prev) : em->start;
6550 start = max_t(u64, start, em->start);
6551 end = next ? next->start : extent_map_end(em);
6552 end = min_t(u64, end, extent_map_end(em));
6553 start_diff = start - em->start;
6555 em->len = end - start;
6556 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6557 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6558 em->block_start += start_diff;
6559 em->block_len -= start_diff;
6561 return add_extent_mapping(em_tree, em, 0);
6564 static noinline int uncompress_inline(struct btrfs_path *path,
6565 struct inode *inode, struct page *page,
6566 size_t pg_offset, u64 extent_offset,
6567 struct btrfs_file_extent_item *item)
6570 struct extent_buffer *leaf = path->nodes[0];
6573 unsigned long inline_size;
6577 WARN_ON(pg_offset != 0);
6578 compress_type = btrfs_file_extent_compression(leaf, item);
6579 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6580 inline_size = btrfs_file_extent_inline_item_len(leaf,
6581 btrfs_item_nr(path->slots[0]));
6582 tmp = kmalloc(inline_size, GFP_NOFS);
6585 ptr = btrfs_file_extent_inline_start(item);
6587 read_extent_buffer(leaf, tmp, ptr, inline_size);
6589 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6590 ret = btrfs_decompress(compress_type, tmp, page,
6591 extent_offset, inline_size, max_size);
6597 * a bit scary, this does extent mapping from logical file offset to the disk.
6598 * the ugly parts come from merging extents from the disk with the in-ram
6599 * representation. This gets more complex because of the data=ordered code,
6600 * where the in-ram extents might be locked pending data=ordered completion.
6602 * This also copies inline extents directly into the page.
6605 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6606 size_t pg_offset, u64 start, u64 len,
6611 u64 extent_start = 0;
6613 u64 objectid = btrfs_ino(inode);
6615 struct btrfs_path *path = NULL;
6616 struct btrfs_root *root = BTRFS_I(inode)->root;
6617 struct btrfs_file_extent_item *item;
6618 struct extent_buffer *leaf;
6619 struct btrfs_key found_key;
6620 struct extent_map *em = NULL;
6621 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6622 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6623 struct btrfs_trans_handle *trans = NULL;
6624 const bool new_inline = !page || create;
6627 read_lock(&em_tree->lock);
6628 em = lookup_extent_mapping(em_tree, start, len);
6630 em->bdev = root->fs_info->fs_devices->latest_bdev;
6631 read_unlock(&em_tree->lock);
6634 if (em->start > start || em->start + em->len <= start)
6635 free_extent_map(em);
6636 else if (em->block_start == EXTENT_MAP_INLINE && page)
6637 free_extent_map(em);
6641 em = alloc_extent_map();
6646 em->bdev = root->fs_info->fs_devices->latest_bdev;
6647 em->start = EXTENT_MAP_HOLE;
6648 em->orig_start = EXTENT_MAP_HOLE;
6650 em->block_len = (u64)-1;
6653 path = btrfs_alloc_path();
6659 * Chances are we'll be called again, so go ahead and do
6665 ret = btrfs_lookup_file_extent(trans, root, path,
6666 objectid, start, trans != NULL);
6673 if (path->slots[0] == 0)
6678 leaf = path->nodes[0];
6679 item = btrfs_item_ptr(leaf, path->slots[0],
6680 struct btrfs_file_extent_item);
6681 /* are we inside the extent that was found? */
6682 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6683 found_type = found_key.type;
6684 if (found_key.objectid != objectid ||
6685 found_type != BTRFS_EXTENT_DATA_KEY) {
6687 * If we backup past the first extent we want to move forward
6688 * and see if there is an extent in front of us, otherwise we'll
6689 * say there is a hole for our whole search range which can
6696 found_type = btrfs_file_extent_type(leaf, item);
6697 extent_start = found_key.offset;
6698 if (found_type == BTRFS_FILE_EXTENT_REG ||
6699 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6700 extent_end = extent_start +
6701 btrfs_file_extent_num_bytes(leaf, item);
6702 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6704 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6705 extent_end = ALIGN(extent_start + size, root->sectorsize);
6708 if (start >= extent_end) {
6710 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6711 ret = btrfs_next_leaf(root, path);
6718 leaf = path->nodes[0];
6720 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6721 if (found_key.objectid != objectid ||
6722 found_key.type != BTRFS_EXTENT_DATA_KEY)
6724 if (start + len <= found_key.offset)
6726 if (start > found_key.offset)
6729 em->orig_start = start;
6730 em->len = found_key.offset - start;
6734 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6736 if (found_type == BTRFS_FILE_EXTENT_REG ||
6737 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6739 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6743 size_t extent_offset;
6749 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6750 extent_offset = page_offset(page) + pg_offset - extent_start;
6751 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6752 size - extent_offset);
6753 em->start = extent_start + extent_offset;
6754 em->len = ALIGN(copy_size, root->sectorsize);
6755 em->orig_block_len = em->len;
6756 em->orig_start = em->start;
6757 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6758 if (create == 0 && !PageUptodate(page)) {
6759 if (btrfs_file_extent_compression(leaf, item) !=
6760 BTRFS_COMPRESS_NONE) {
6761 ret = uncompress_inline(path, inode, page,
6763 extent_offset, item);
6770 read_extent_buffer(leaf, map + pg_offset, ptr,
6772 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6773 memset(map + pg_offset + copy_size, 0,
6774 PAGE_CACHE_SIZE - pg_offset -
6779 flush_dcache_page(page);
6780 } else if (create && PageUptodate(page)) {
6784 free_extent_map(em);
6787 btrfs_release_path(path);
6788 trans = btrfs_join_transaction(root);
6791 return ERR_CAST(trans);
6795 write_extent_buffer(leaf, map + pg_offset, ptr,
6798 btrfs_mark_buffer_dirty(leaf);
6800 set_extent_uptodate(io_tree, em->start,
6801 extent_map_end(em) - 1, NULL, GFP_NOFS);
6806 em->orig_start = start;
6809 em->block_start = EXTENT_MAP_HOLE;
6810 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6812 btrfs_release_path(path);
6813 if (em->start > start || extent_map_end(em) <= start) {
6814 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6815 em->start, em->len, start, len);
6821 write_lock(&em_tree->lock);
6822 ret = add_extent_mapping(em_tree, em, 0);
6823 /* it is possible that someone inserted the extent into the tree
6824 * while we had the lock dropped. It is also possible that
6825 * an overlapping map exists in the tree
6827 if (ret == -EEXIST) {
6828 struct extent_map *existing;
6832 existing = search_extent_mapping(em_tree, start, len);
6834 * existing will always be non-NULL, since there must be
6835 * extent causing the -EEXIST.
6837 if (start >= extent_map_end(existing) ||
6838 start <= existing->start) {
6840 * The existing extent map is the one nearest to
6841 * the [start, start + len) range which overlaps
6843 err = merge_extent_mapping(em_tree, existing,
6845 free_extent_map(existing);
6847 free_extent_map(em);
6851 free_extent_map(em);
6856 write_unlock(&em_tree->lock);
6859 trace_btrfs_get_extent(root, em);
6862 btrfs_free_path(path);
6864 ret = btrfs_end_transaction(trans, root);
6869 free_extent_map(em);
6870 return ERR_PTR(err);
6872 BUG_ON(!em); /* Error is always set */
6876 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6877 size_t pg_offset, u64 start, u64 len,
6880 struct extent_map *em;
6881 struct extent_map *hole_em = NULL;
6882 u64 range_start = start;
6888 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6895 * - a pre-alloc extent,
6896 * there might actually be delalloc bytes behind it.
6898 if (em->block_start != EXTENT_MAP_HOLE &&
6899 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6905 /* check to see if we've wrapped (len == -1 or similar) */
6914 /* ok, we didn't find anything, lets look for delalloc */
6915 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6916 end, len, EXTENT_DELALLOC, 1);
6917 found_end = range_start + found;
6918 if (found_end < range_start)
6919 found_end = (u64)-1;
6922 * we didn't find anything useful, return
6923 * the original results from get_extent()
6925 if (range_start > end || found_end <= start) {
6931 /* adjust the range_start to make sure it doesn't
6932 * go backwards from the start they passed in
6934 range_start = max(start, range_start);
6935 found = found_end - range_start;
6938 u64 hole_start = start;
6941 em = alloc_extent_map();
6947 * when btrfs_get_extent can't find anything it
6948 * returns one huge hole
6950 * make sure what it found really fits our range, and
6951 * adjust to make sure it is based on the start from
6955 u64 calc_end = extent_map_end(hole_em);
6957 if (calc_end <= start || (hole_em->start > end)) {
6958 free_extent_map(hole_em);
6961 hole_start = max(hole_em->start, start);
6962 hole_len = calc_end - hole_start;
6966 if (hole_em && range_start > hole_start) {
6967 /* our hole starts before our delalloc, so we
6968 * have to return just the parts of the hole
6969 * that go until the delalloc starts
6971 em->len = min(hole_len,
6972 range_start - hole_start);
6973 em->start = hole_start;
6974 em->orig_start = hole_start;
6976 * don't adjust block start at all,
6977 * it is fixed at EXTENT_MAP_HOLE
6979 em->block_start = hole_em->block_start;
6980 em->block_len = hole_len;
6981 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6982 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6984 em->start = range_start;
6986 em->orig_start = range_start;
6987 em->block_start = EXTENT_MAP_DELALLOC;
6988 em->block_len = found;
6990 } else if (hole_em) {
6995 free_extent_map(hole_em);
6997 free_extent_map(em);
6998 return ERR_PTR(err);
7003 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7006 struct btrfs_root *root = BTRFS_I(inode)->root;
7007 struct extent_map *em;
7008 struct btrfs_key ins;
7012 alloc_hint = get_extent_allocation_hint(inode, start, len);
7013 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
7014 alloc_hint, &ins, 1, 1);
7016 return ERR_PTR(ret);
7018 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
7019 ins.offset, ins.offset, ins.offset, 0);
7021 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7025 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
7026 ins.offset, ins.offset, 0);
7028 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7029 free_extent_map(em);
7030 return ERR_PTR(ret);
7037 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7038 * block must be cow'd
7040 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7041 u64 *orig_start, u64 *orig_block_len,
7044 struct btrfs_trans_handle *trans;
7045 struct btrfs_path *path;
7047 struct extent_buffer *leaf;
7048 struct btrfs_root *root = BTRFS_I(inode)->root;
7049 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7050 struct btrfs_file_extent_item *fi;
7051 struct btrfs_key key;
7058 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7060 path = btrfs_alloc_path();
7064 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7069 slot = path->slots[0];
7072 /* can't find the item, must cow */
7079 leaf = path->nodes[0];
7080 btrfs_item_key_to_cpu(leaf, &key, slot);
7081 if (key.objectid != btrfs_ino(inode) ||
7082 key.type != BTRFS_EXTENT_DATA_KEY) {
7083 /* not our file or wrong item type, must cow */
7087 if (key.offset > offset) {
7088 /* Wrong offset, must cow */
7092 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7093 found_type = btrfs_file_extent_type(leaf, fi);
7094 if (found_type != BTRFS_FILE_EXTENT_REG &&
7095 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7096 /* not a regular extent, must cow */
7100 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7103 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7104 if (extent_end <= offset)
7107 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7108 if (disk_bytenr == 0)
7111 if (btrfs_file_extent_compression(leaf, fi) ||
7112 btrfs_file_extent_encryption(leaf, fi) ||
7113 btrfs_file_extent_other_encoding(leaf, fi))
7116 backref_offset = btrfs_file_extent_offset(leaf, fi);
7119 *orig_start = key.offset - backref_offset;
7120 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7121 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7124 if (btrfs_extent_readonly(root, disk_bytenr))
7127 num_bytes = min(offset + *len, extent_end) - offset;
7128 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7131 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7132 ret = test_range_bit(io_tree, offset, range_end,
7133 EXTENT_DELALLOC, 0, NULL);
7140 btrfs_release_path(path);
7143 * look for other files referencing this extent, if we
7144 * find any we must cow
7146 trans = btrfs_join_transaction(root);
7147 if (IS_ERR(trans)) {
7152 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7153 key.offset - backref_offset, disk_bytenr);
7154 btrfs_end_transaction(trans, root);
7161 * adjust disk_bytenr and num_bytes to cover just the bytes
7162 * in this extent we are about to write. If there
7163 * are any csums in that range we have to cow in order
7164 * to keep the csums correct
7166 disk_bytenr += backref_offset;
7167 disk_bytenr += offset - key.offset;
7168 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7171 * all of the above have passed, it is safe to overwrite this extent
7177 btrfs_free_path(path);
7181 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7183 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7185 void **pagep = NULL;
7186 struct page *page = NULL;
7190 start_idx = start >> PAGE_CACHE_SHIFT;
7193 * end is the last byte in the last page. end == start is legal
7195 end_idx = end >> PAGE_CACHE_SHIFT;
7199 /* Most of the code in this while loop is lifted from
7200 * find_get_page. It's been modified to begin searching from a
7201 * page and return just the first page found in that range. If the
7202 * found idx is less than or equal to the end idx then we know that
7203 * a page exists. If no pages are found or if those pages are
7204 * outside of the range then we're fine (yay!) */
7205 while (page == NULL &&
7206 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7207 page = radix_tree_deref_slot(pagep);
7208 if (unlikely(!page))
7211 if (radix_tree_exception(page)) {
7212 if (radix_tree_deref_retry(page)) {
7217 * Otherwise, shmem/tmpfs must be storing a swap entry
7218 * here as an exceptional entry: so return it without
7219 * attempting to raise page count.
7222 break; /* TODO: Is this relevant for this use case? */
7225 if (!page_cache_get_speculative(page)) {
7231 * Has the page moved?
7232 * This is part of the lockless pagecache protocol. See
7233 * include/linux/pagemap.h for details.
7235 if (unlikely(page != *pagep)) {
7236 page_cache_release(page);
7242 if (page->index <= end_idx)
7244 page_cache_release(page);
7251 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7252 struct extent_state **cached_state, int writing)
7254 struct btrfs_ordered_extent *ordered;
7258 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7261 * We're concerned with the entire range that we're going to be
7262 * doing DIO to, so we need to make sure theres no ordered
7263 * extents in this range.
7265 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7266 lockend - lockstart + 1);
7269 * We need to make sure there are no buffered pages in this
7270 * range either, we could have raced between the invalidate in
7271 * generic_file_direct_write and locking the extent. The
7272 * invalidate needs to happen so that reads after a write do not
7277 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7280 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7281 cached_state, GFP_NOFS);
7284 btrfs_start_ordered_extent(inode, ordered, 1);
7285 btrfs_put_ordered_extent(ordered);
7287 /* Screw you mmap */
7288 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
7291 ret = filemap_fdatawait_range(inode->i_mapping,
7298 * If we found a page that couldn't be invalidated just
7299 * fall back to buffered.
7301 ret = invalidate_inode_pages2_range(inode->i_mapping,
7302 lockstart >> PAGE_CACHE_SHIFT,
7303 lockend >> PAGE_CACHE_SHIFT);
7314 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7315 u64 len, u64 orig_start,
7316 u64 block_start, u64 block_len,
7317 u64 orig_block_len, u64 ram_bytes,
7320 struct extent_map_tree *em_tree;
7321 struct extent_map *em;
7322 struct btrfs_root *root = BTRFS_I(inode)->root;
7325 em_tree = &BTRFS_I(inode)->extent_tree;
7326 em = alloc_extent_map();
7328 return ERR_PTR(-ENOMEM);
7331 em->orig_start = orig_start;
7332 em->mod_start = start;
7335 em->block_len = block_len;
7336 em->block_start = block_start;
7337 em->bdev = root->fs_info->fs_devices->latest_bdev;
7338 em->orig_block_len = orig_block_len;
7339 em->ram_bytes = ram_bytes;
7340 em->generation = -1;
7341 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7342 if (type == BTRFS_ORDERED_PREALLOC)
7343 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7346 btrfs_drop_extent_cache(inode, em->start,
7347 em->start + em->len - 1, 0);
7348 write_lock(&em_tree->lock);
7349 ret = add_extent_mapping(em_tree, em, 1);
7350 write_unlock(&em_tree->lock);
7351 } while (ret == -EEXIST);
7354 free_extent_map(em);
7355 return ERR_PTR(ret);
7362 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7363 struct buffer_head *bh_result, int create)
7365 struct extent_map *em;
7366 struct btrfs_root *root = BTRFS_I(inode)->root;
7367 struct extent_state *cached_state = NULL;
7368 u64 start = iblock << inode->i_blkbits;
7369 u64 lockstart, lockend;
7370 u64 len = bh_result->b_size;
7371 u64 *outstanding_extents = NULL;
7372 int unlock_bits = EXTENT_LOCKED;
7376 unlock_bits |= EXTENT_DIRTY;
7378 len = min_t(u64, len, root->sectorsize);
7381 lockend = start + len - 1;
7383 if (current->journal_info) {
7385 * Need to pull our outstanding extents and set journal_info to NULL so
7386 * that anything that needs to check if there's a transction doesn't get
7389 outstanding_extents = current->journal_info;
7390 current->journal_info = NULL;
7394 * If this errors out it's because we couldn't invalidate pagecache for
7395 * this range and we need to fallback to buffered.
7397 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
7400 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7407 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7408 * io. INLINE is special, and we could probably kludge it in here, but
7409 * it's still buffered so for safety lets just fall back to the generic
7412 * For COMPRESSED we _have_ to read the entire extent in so we can
7413 * decompress it, so there will be buffering required no matter what we
7414 * do, so go ahead and fallback to buffered.
7416 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7417 * to buffered IO. Don't blame me, this is the price we pay for using
7420 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7421 em->block_start == EXTENT_MAP_INLINE) {
7422 free_extent_map(em);
7427 /* Just a good old fashioned hole, return */
7428 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7429 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7430 free_extent_map(em);
7435 * We don't allocate a new extent in the following cases
7437 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7439 * 2) The extent is marked as PREALLOC. We're good to go here and can
7440 * just use the extent.
7444 len = min(len, em->len - (start - em->start));
7445 lockstart = start + len;
7449 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7450 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7451 em->block_start != EXTENT_MAP_HOLE)) {
7453 u64 block_start, orig_start, orig_block_len, ram_bytes;
7455 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7456 type = BTRFS_ORDERED_PREALLOC;
7458 type = BTRFS_ORDERED_NOCOW;
7459 len = min(len, em->len - (start - em->start));
7460 block_start = em->block_start + (start - em->start);
7462 if (can_nocow_extent(inode, start, &len, &orig_start,
7463 &orig_block_len, &ram_bytes) == 1) {
7464 if (type == BTRFS_ORDERED_PREALLOC) {
7465 free_extent_map(em);
7466 em = create_pinned_em(inode, start, len,
7477 ret = btrfs_add_ordered_extent_dio(inode, start,
7478 block_start, len, len, type);
7480 free_extent_map(em);
7488 * this will cow the extent, reset the len in case we changed
7491 len = bh_result->b_size;
7492 free_extent_map(em);
7493 em = btrfs_new_extent_direct(inode, start, len);
7498 len = min(len, em->len - (start - em->start));
7500 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7502 bh_result->b_size = len;
7503 bh_result->b_bdev = em->bdev;
7504 set_buffer_mapped(bh_result);
7506 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7507 set_buffer_new(bh_result);
7510 * Need to update the i_size under the extent lock so buffered
7511 * readers will get the updated i_size when we unlock.
7513 if (start + len > i_size_read(inode))
7514 i_size_write(inode, start + len);
7517 * If we have an outstanding_extents count still set then we're
7518 * within our reservation, otherwise we need to adjust our inode
7519 * counter appropriately.
7521 if (*outstanding_extents) {
7522 (*outstanding_extents)--;
7524 spin_lock(&BTRFS_I(inode)->lock);
7525 BTRFS_I(inode)->outstanding_extents++;
7526 spin_unlock(&BTRFS_I(inode)->lock);
7529 current->journal_info = outstanding_extents;
7530 btrfs_free_reserved_data_space(inode, len);
7534 * In the case of write we need to clear and unlock the entire range,
7535 * in the case of read we need to unlock only the end area that we
7536 * aren't using if there is any left over space.
7538 if (lockstart < lockend) {
7539 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7540 lockend, unlock_bits, 1, 0,
7541 &cached_state, GFP_NOFS);
7543 free_extent_state(cached_state);
7546 free_extent_map(em);
7551 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7552 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7553 if (outstanding_extents)
7554 current->journal_info = outstanding_extents;
7558 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7559 int rw, int mirror_num)
7561 struct btrfs_root *root = BTRFS_I(inode)->root;
7564 BUG_ON(rw & REQ_WRITE);
7568 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7569 BTRFS_WQ_ENDIO_DIO_REPAIR);
7573 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7579 static int btrfs_check_dio_repairable(struct inode *inode,
7580 struct bio *failed_bio,
7581 struct io_failure_record *failrec,
7586 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7587 failrec->logical, failrec->len);
7588 if (num_copies == 1) {
7590 * we only have a single copy of the data, so don't bother with
7591 * all the retry and error correction code that follows. no
7592 * matter what the error is, it is very likely to persist.
7594 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7595 num_copies, failrec->this_mirror, failed_mirror);
7599 failrec->failed_mirror = failed_mirror;
7600 failrec->this_mirror++;
7601 if (failrec->this_mirror == failed_mirror)
7602 failrec->this_mirror++;
7604 if (failrec->this_mirror > num_copies) {
7605 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7606 num_copies, failrec->this_mirror, failed_mirror);
7613 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7614 struct page *page, u64 start, u64 end,
7615 int failed_mirror, bio_end_io_t *repair_endio,
7618 struct io_failure_record *failrec;
7624 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7626 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7630 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7633 free_io_failure(inode, failrec);
7637 if (failed_bio->bi_vcnt > 1)
7638 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7640 read_mode = READ_SYNC;
7642 isector = start - btrfs_io_bio(failed_bio)->logical;
7643 isector >>= inode->i_sb->s_blocksize_bits;
7644 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7645 0, isector, repair_endio, repair_arg);
7647 free_io_failure(inode, failrec);
7651 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7652 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7653 read_mode, failrec->this_mirror, failrec->in_validation);
7655 ret = submit_dio_repair_bio(inode, bio, read_mode,
7656 failrec->this_mirror);
7658 free_io_failure(inode, failrec);
7665 struct btrfs_retry_complete {
7666 struct completion done;
7667 struct inode *inode;
7672 static void btrfs_retry_endio_nocsum(struct bio *bio, int err)
7674 struct btrfs_retry_complete *done = bio->bi_private;
7675 struct bio_vec *bvec;
7682 bio_for_each_segment_all(bvec, bio, i)
7683 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7685 complete(&done->done);
7689 static int __btrfs_correct_data_nocsum(struct inode *inode,
7690 struct btrfs_io_bio *io_bio)
7692 struct bio_vec *bvec;
7693 struct btrfs_retry_complete done;
7698 start = io_bio->logical;
7701 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7705 init_completion(&done.done);
7707 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7708 start + bvec->bv_len - 1,
7710 btrfs_retry_endio_nocsum, &done);
7714 wait_for_completion(&done.done);
7716 if (!done.uptodate) {
7717 /* We might have another mirror, so try again */
7721 start += bvec->bv_len;
7727 static void btrfs_retry_endio(struct bio *bio, int err)
7729 struct btrfs_retry_complete *done = bio->bi_private;
7730 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7731 struct bio_vec *bvec;
7740 bio_for_each_segment_all(bvec, bio, i) {
7741 ret = __readpage_endio_check(done->inode, io_bio, i,
7743 done->start, bvec->bv_len);
7745 clean_io_failure(done->inode, done->start,
7751 done->uptodate = uptodate;
7753 complete(&done->done);
7757 static int __btrfs_subio_endio_read(struct inode *inode,
7758 struct btrfs_io_bio *io_bio, int err)
7760 struct bio_vec *bvec;
7761 struct btrfs_retry_complete done;
7768 start = io_bio->logical;
7771 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7772 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7773 0, start, bvec->bv_len);
7779 init_completion(&done.done);
7781 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7782 start + bvec->bv_len - 1,
7784 btrfs_retry_endio, &done);
7790 wait_for_completion(&done.done);
7792 if (!done.uptodate) {
7793 /* We might have another mirror, so try again */
7797 offset += bvec->bv_len;
7798 start += bvec->bv_len;
7804 static int btrfs_subio_endio_read(struct inode *inode,
7805 struct btrfs_io_bio *io_bio, int err)
7807 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7811 return __btrfs_correct_data_nocsum(inode, io_bio);
7815 return __btrfs_subio_endio_read(inode, io_bio, err);
7819 static void btrfs_endio_direct_read(struct bio *bio, int err)
7821 struct btrfs_dio_private *dip = bio->bi_private;
7822 struct inode *inode = dip->inode;
7823 struct bio *dio_bio;
7824 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7826 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7827 err = btrfs_subio_endio_read(inode, io_bio, err);
7829 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7830 dip->logical_offset + dip->bytes - 1);
7831 dio_bio = dip->dio_bio;
7835 /* If we had a csum failure make sure to clear the uptodate flag */
7837 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7838 dio_end_io(dio_bio, err);
7841 io_bio->end_io(io_bio, err);
7845 static void btrfs_endio_direct_write(struct bio *bio, int err)
7847 struct btrfs_dio_private *dip = bio->bi_private;
7848 struct inode *inode = dip->inode;
7849 struct btrfs_root *root = BTRFS_I(inode)->root;
7850 struct btrfs_ordered_extent *ordered = NULL;
7851 u64 ordered_offset = dip->logical_offset;
7852 u64 ordered_bytes = dip->bytes;
7853 struct bio *dio_bio;
7859 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7861 ordered_bytes, !err);
7865 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
7866 finish_ordered_fn, NULL, NULL);
7867 btrfs_queue_work(root->fs_info->endio_write_workers,
7871 * our bio might span multiple ordered extents. If we haven't
7872 * completed the accounting for the whole dio, go back and try again
7874 if (ordered_offset < dip->logical_offset + dip->bytes) {
7875 ordered_bytes = dip->logical_offset + dip->bytes -
7881 dio_bio = dip->dio_bio;
7885 /* If we had an error make sure to clear the uptodate flag */
7887 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7888 dio_end_io(dio_bio, err);
7892 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7893 struct bio *bio, int mirror_num,
7894 unsigned long bio_flags, u64 offset)
7897 struct btrfs_root *root = BTRFS_I(inode)->root;
7898 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7899 BUG_ON(ret); /* -ENOMEM */
7903 static void btrfs_end_dio_bio(struct bio *bio, int err)
7905 struct btrfs_dio_private *dip = bio->bi_private;
7908 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7909 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
7910 btrfs_ino(dip->inode), bio->bi_rw,
7911 (unsigned long long)bio->bi_iter.bi_sector,
7912 bio->bi_iter.bi_size, err);
7914 if (dip->subio_endio)
7915 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7921 * before atomic variable goto zero, we must make sure
7922 * dip->errors is perceived to be set.
7924 smp_mb__before_atomic();
7927 /* if there are more bios still pending for this dio, just exit */
7928 if (!atomic_dec_and_test(&dip->pending_bios))
7932 bio_io_error(dip->orig_bio);
7934 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7935 bio_endio(dip->orig_bio, 0);
7941 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7942 u64 first_sector, gfp_t gfp_flags)
7944 int nr_vecs = bio_get_nr_vecs(bdev);
7945 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7948 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
7949 struct inode *inode,
7950 struct btrfs_dio_private *dip,
7954 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7955 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7959 * We load all the csum data we need when we submit
7960 * the first bio to reduce the csum tree search and
7963 if (dip->logical_offset == file_offset) {
7964 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
7970 if (bio == dip->orig_bio)
7973 file_offset -= dip->logical_offset;
7974 file_offset >>= inode->i_sb->s_blocksize_bits;
7975 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
7980 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7981 int rw, u64 file_offset, int skip_sum,
7984 struct btrfs_dio_private *dip = bio->bi_private;
7985 int write = rw & REQ_WRITE;
7986 struct btrfs_root *root = BTRFS_I(inode)->root;
7990 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7995 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7996 BTRFS_WQ_ENDIO_DATA);
8004 if (write && async_submit) {
8005 ret = btrfs_wq_submit_bio(root->fs_info,
8006 inode, rw, bio, 0, 0,
8008 __btrfs_submit_bio_start_direct_io,
8009 __btrfs_submit_bio_done);
8013 * If we aren't doing async submit, calculate the csum of the
8016 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
8020 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
8026 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
8032 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
8035 struct inode *inode = dip->inode;
8036 struct btrfs_root *root = BTRFS_I(inode)->root;
8038 struct bio *orig_bio = dip->orig_bio;
8039 struct bio_vec *bvec = orig_bio->bi_io_vec;
8040 u64 start_sector = orig_bio->bi_iter.bi_sector;
8041 u64 file_offset = dip->logical_offset;
8046 int async_submit = 0;
8048 map_length = orig_bio->bi_iter.bi_size;
8049 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
8050 &map_length, NULL, 0);
8054 if (map_length >= orig_bio->bi_iter.bi_size) {
8056 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8060 /* async crcs make it difficult to collect full stripe writes. */
8061 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8066 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8070 bio->bi_private = dip;
8071 bio->bi_end_io = btrfs_end_dio_bio;
8072 btrfs_io_bio(bio)->logical = file_offset;
8073 atomic_inc(&dip->pending_bios);
8075 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
8076 if (map_length < submit_len + bvec->bv_len ||
8077 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
8078 bvec->bv_offset) < bvec->bv_len) {
8080 * inc the count before we submit the bio so
8081 * we know the end IO handler won't happen before
8082 * we inc the count. Otherwise, the dip might get freed
8083 * before we're done setting it up
8085 atomic_inc(&dip->pending_bios);
8086 ret = __btrfs_submit_dio_bio(bio, inode, rw,
8087 file_offset, skip_sum,
8091 atomic_dec(&dip->pending_bios);
8095 start_sector += submit_len >> 9;
8096 file_offset += submit_len;
8101 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8102 start_sector, GFP_NOFS);
8105 bio->bi_private = dip;
8106 bio->bi_end_io = btrfs_end_dio_bio;
8107 btrfs_io_bio(bio)->logical = file_offset;
8109 map_length = orig_bio->bi_iter.bi_size;
8110 ret = btrfs_map_block(root->fs_info, rw,
8112 &map_length, NULL, 0);
8118 submit_len += bvec->bv_len;
8125 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
8134 * before atomic variable goto zero, we must
8135 * make sure dip->errors is perceived to be set.
8137 smp_mb__before_atomic();
8138 if (atomic_dec_and_test(&dip->pending_bios))
8139 bio_io_error(dip->orig_bio);
8141 /* bio_end_io() will handle error, so we needn't return it */
8145 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
8146 struct inode *inode, loff_t file_offset)
8148 struct btrfs_root *root = BTRFS_I(inode)->root;
8149 struct btrfs_dio_private *dip;
8151 struct btrfs_io_bio *btrfs_bio;
8153 int write = rw & REQ_WRITE;
8156 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8158 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8164 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8170 dip->private = dio_bio->bi_private;
8172 dip->logical_offset = file_offset;
8173 dip->bytes = dio_bio->bi_iter.bi_size;
8174 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8175 io_bio->bi_private = dip;
8176 dip->orig_bio = io_bio;
8177 dip->dio_bio = dio_bio;
8178 atomic_set(&dip->pending_bios, 0);
8179 btrfs_bio = btrfs_io_bio(io_bio);
8180 btrfs_bio->logical = file_offset;
8183 io_bio->bi_end_io = btrfs_endio_direct_write;
8185 io_bio->bi_end_io = btrfs_endio_direct_read;
8186 dip->subio_endio = btrfs_subio_endio_read;
8189 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8193 if (btrfs_bio->end_io)
8194 btrfs_bio->end_io(btrfs_bio, ret);
8200 * If this is a write, we need to clean up the reserved space and kill
8201 * the ordered extent.
8204 struct btrfs_ordered_extent *ordered;
8205 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
8206 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
8207 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
8208 btrfs_free_reserved_extent(root, ordered->start,
8209 ordered->disk_len, 1);
8210 btrfs_put_ordered_extent(ordered);
8211 btrfs_put_ordered_extent(ordered);
8213 bio_endio(dio_bio, ret);
8216 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
8217 const struct iov_iter *iter, loff_t offset)
8221 unsigned blocksize_mask = root->sectorsize - 1;
8222 ssize_t retval = -EINVAL;
8224 if (offset & blocksize_mask)
8227 if (iov_iter_alignment(iter) & blocksize_mask)
8230 /* If this is a write we don't need to check anymore */
8234 * Check to make sure we don't have duplicate iov_base's in this
8235 * iovec, if so return EINVAL, otherwise we'll get csum errors
8236 * when reading back.
8238 for (seg = 0; seg < iter->nr_segs; seg++) {
8239 for (i = seg + 1; i < iter->nr_segs; i++) {
8240 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8249 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
8250 struct iov_iter *iter, loff_t offset)
8252 struct file *file = iocb->ki_filp;
8253 struct inode *inode = file->f_mapping->host;
8254 u64 outstanding_extents = 0;
8258 bool relock = false;
8261 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iter, offset))
8264 atomic_inc(&inode->i_dio_count);
8265 smp_mb__after_atomic();
8268 * The generic stuff only does filemap_write_and_wait_range, which
8269 * isn't enough if we've written compressed pages to this area, so
8270 * we need to flush the dirty pages again to make absolutely sure
8271 * that any outstanding dirty pages are on disk.
8273 count = iov_iter_count(iter);
8274 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8275 &BTRFS_I(inode)->runtime_flags))
8276 filemap_fdatawrite_range(inode->i_mapping, offset,
8277 offset + count - 1);
8281 * If the write DIO is beyond the EOF, we need update
8282 * the isize, but it is protected by i_mutex. So we can
8283 * not unlock the i_mutex at this case.
8285 if (offset + count <= inode->i_size) {
8286 mutex_unlock(&inode->i_mutex);
8289 ret = btrfs_delalloc_reserve_space(inode, count);
8292 outstanding_extents = div64_u64(count +
8293 BTRFS_MAX_EXTENT_SIZE - 1,
8294 BTRFS_MAX_EXTENT_SIZE);
8297 * We need to know how many extents we reserved so that we can
8298 * do the accounting properly if we go over the number we
8299 * originally calculated. Abuse current->journal_info for this.
8301 current->journal_info = &outstanding_extents;
8302 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8303 &BTRFS_I(inode)->runtime_flags)) {
8304 inode_dio_done(inode);
8305 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8309 ret = __blockdev_direct_IO(rw, iocb, inode,
8310 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8311 iter, offset, btrfs_get_blocks_direct, NULL,
8312 btrfs_submit_direct, flags);
8314 current->journal_info = NULL;
8315 if (ret < 0 && ret != -EIOCBQUEUED)
8316 btrfs_delalloc_release_space(inode, count);
8317 else if (ret >= 0 && (size_t)ret < count)
8318 btrfs_delalloc_release_space(inode,
8319 count - (size_t)ret);
8323 inode_dio_done(inode);
8325 mutex_lock(&inode->i_mutex);
8330 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8332 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8333 __u64 start, __u64 len)
8337 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8341 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8344 int btrfs_readpage(struct file *file, struct page *page)
8346 struct extent_io_tree *tree;
8347 tree = &BTRFS_I(page->mapping->host)->io_tree;
8348 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8351 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8353 struct extent_io_tree *tree;
8356 if (current->flags & PF_MEMALLOC) {
8357 redirty_page_for_writepage(wbc, page);
8361 tree = &BTRFS_I(page->mapping->host)->io_tree;
8362 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8365 static int btrfs_writepages(struct address_space *mapping,
8366 struct writeback_control *wbc)
8368 struct extent_io_tree *tree;
8370 tree = &BTRFS_I(mapping->host)->io_tree;
8371 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8375 btrfs_readpages(struct file *file, struct address_space *mapping,
8376 struct list_head *pages, unsigned nr_pages)
8378 struct extent_io_tree *tree;
8379 tree = &BTRFS_I(mapping->host)->io_tree;
8380 return extent_readpages(tree, mapping, pages, nr_pages,
8383 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8385 struct extent_io_tree *tree;
8386 struct extent_map_tree *map;
8389 tree = &BTRFS_I(page->mapping->host)->io_tree;
8390 map = &BTRFS_I(page->mapping->host)->extent_tree;
8391 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8393 ClearPagePrivate(page);
8394 set_page_private(page, 0);
8395 page_cache_release(page);
8400 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8402 if (PageWriteback(page) || PageDirty(page))
8404 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8407 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8408 unsigned int length)
8410 struct inode *inode = page->mapping->host;
8411 struct extent_io_tree *tree;
8412 struct btrfs_ordered_extent *ordered;
8413 struct extent_state *cached_state = NULL;
8414 u64 page_start = page_offset(page);
8415 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8416 int inode_evicting = inode->i_state & I_FREEING;
8419 * we have the page locked, so new writeback can't start,
8420 * and the dirty bit won't be cleared while we are here.
8422 * Wait for IO on this page so that we can safely clear
8423 * the PagePrivate2 bit and do ordered accounting
8425 wait_on_page_writeback(page);
8427 tree = &BTRFS_I(inode)->io_tree;
8429 btrfs_releasepage(page, GFP_NOFS);
8433 if (!inode_evicting)
8434 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8435 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8438 * IO on this page will never be started, so we need
8439 * to account for any ordered extents now
8441 if (!inode_evicting)
8442 clear_extent_bit(tree, page_start, page_end,
8443 EXTENT_DIRTY | EXTENT_DELALLOC |
8444 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8445 EXTENT_DEFRAG, 1, 0, &cached_state,
8448 * whoever cleared the private bit is responsible
8449 * for the finish_ordered_io
8451 if (TestClearPagePrivate2(page)) {
8452 struct btrfs_ordered_inode_tree *tree;
8455 tree = &BTRFS_I(inode)->ordered_tree;
8457 spin_lock_irq(&tree->lock);
8458 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8459 new_len = page_start - ordered->file_offset;
8460 if (new_len < ordered->truncated_len)
8461 ordered->truncated_len = new_len;
8462 spin_unlock_irq(&tree->lock);
8464 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8466 PAGE_CACHE_SIZE, 1))
8467 btrfs_finish_ordered_io(ordered);
8469 btrfs_put_ordered_extent(ordered);
8470 if (!inode_evicting) {
8471 cached_state = NULL;
8472 lock_extent_bits(tree, page_start, page_end, 0,
8477 if (!inode_evicting) {
8478 clear_extent_bit(tree, page_start, page_end,
8479 EXTENT_LOCKED | EXTENT_DIRTY |
8480 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8481 EXTENT_DEFRAG, 1, 1,
8482 &cached_state, GFP_NOFS);
8484 __btrfs_releasepage(page, GFP_NOFS);
8487 ClearPageChecked(page);
8488 if (PagePrivate(page)) {
8489 ClearPagePrivate(page);
8490 set_page_private(page, 0);
8491 page_cache_release(page);
8496 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8497 * called from a page fault handler when a page is first dirtied. Hence we must
8498 * be careful to check for EOF conditions here. We set the page up correctly
8499 * for a written page which means we get ENOSPC checking when writing into
8500 * holes and correct delalloc and unwritten extent mapping on filesystems that
8501 * support these features.
8503 * We are not allowed to take the i_mutex here so we have to play games to
8504 * protect against truncate races as the page could now be beyond EOF. Because
8505 * vmtruncate() writes the inode size before removing pages, once we have the
8506 * page lock we can determine safely if the page is beyond EOF. If it is not
8507 * beyond EOF, then the page is guaranteed safe against truncation until we
8510 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8512 struct page *page = vmf->page;
8513 struct inode *inode = file_inode(vma->vm_file);
8514 struct btrfs_root *root = BTRFS_I(inode)->root;
8515 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8516 struct btrfs_ordered_extent *ordered;
8517 struct extent_state *cached_state = NULL;
8519 unsigned long zero_start;
8526 sb_start_pagefault(inode->i_sb);
8527 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
8529 ret = file_update_time(vma->vm_file);
8535 else /* -ENOSPC, -EIO, etc */
8536 ret = VM_FAULT_SIGBUS;
8542 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8545 size = i_size_read(inode);
8546 page_start = page_offset(page);
8547 page_end = page_start + PAGE_CACHE_SIZE - 1;
8549 if ((page->mapping != inode->i_mapping) ||
8550 (page_start >= size)) {
8551 /* page got truncated out from underneath us */
8554 wait_on_page_writeback(page);
8556 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8557 set_page_extent_mapped(page);
8560 * we can't set the delalloc bits if there are pending ordered
8561 * extents. Drop our locks and wait for them to finish
8563 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8565 unlock_extent_cached(io_tree, page_start, page_end,
8566 &cached_state, GFP_NOFS);
8568 btrfs_start_ordered_extent(inode, ordered, 1);
8569 btrfs_put_ordered_extent(ordered);
8574 * XXX - page_mkwrite gets called every time the page is dirtied, even
8575 * if it was already dirty, so for space accounting reasons we need to
8576 * clear any delalloc bits for the range we are fixing to save. There
8577 * is probably a better way to do this, but for now keep consistent with
8578 * prepare_pages in the normal write path.
8580 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8581 EXTENT_DIRTY | EXTENT_DELALLOC |
8582 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8583 0, 0, &cached_state, GFP_NOFS);
8585 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8588 unlock_extent_cached(io_tree, page_start, page_end,
8589 &cached_state, GFP_NOFS);
8590 ret = VM_FAULT_SIGBUS;
8595 /* page is wholly or partially inside EOF */
8596 if (page_start + PAGE_CACHE_SIZE > size)
8597 zero_start = size & ~PAGE_CACHE_MASK;
8599 zero_start = PAGE_CACHE_SIZE;
8601 if (zero_start != PAGE_CACHE_SIZE) {
8603 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8604 flush_dcache_page(page);
8607 ClearPageChecked(page);
8608 set_page_dirty(page);
8609 SetPageUptodate(page);
8611 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8612 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8613 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8615 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8619 sb_end_pagefault(inode->i_sb);
8620 return VM_FAULT_LOCKED;
8624 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
8626 sb_end_pagefault(inode->i_sb);
8630 static int btrfs_truncate(struct inode *inode)
8632 struct btrfs_root *root = BTRFS_I(inode)->root;
8633 struct btrfs_block_rsv *rsv;
8636 struct btrfs_trans_handle *trans;
8637 u64 mask = root->sectorsize - 1;
8638 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8640 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8646 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8647 * 3 things going on here
8649 * 1) We need to reserve space for our orphan item and the space to
8650 * delete our orphan item. Lord knows we don't want to have a dangling
8651 * orphan item because we didn't reserve space to remove it.
8653 * 2) We need to reserve space to update our inode.
8655 * 3) We need to have something to cache all the space that is going to
8656 * be free'd up by the truncate operation, but also have some slack
8657 * space reserved in case it uses space during the truncate (thank you
8658 * very much snapshotting).
8660 * And we need these to all be seperate. The fact is we can use alot of
8661 * space doing the truncate, and we have no earthly idea how much space
8662 * we will use, so we need the truncate reservation to be seperate so it
8663 * doesn't end up using space reserved for updating the inode or
8664 * removing the orphan item. We also need to be able to stop the
8665 * transaction and start a new one, which means we need to be able to
8666 * update the inode several times, and we have no idea of knowing how
8667 * many times that will be, so we can't just reserve 1 item for the
8668 * entirety of the opration, so that has to be done seperately as well.
8669 * Then there is the orphan item, which does indeed need to be held on
8670 * to for the whole operation, and we need nobody to touch this reserved
8671 * space except the orphan code.
8673 * So that leaves us with
8675 * 1) root->orphan_block_rsv - for the orphan deletion.
8676 * 2) rsv - for the truncate reservation, which we will steal from the
8677 * transaction reservation.
8678 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8679 * updating the inode.
8681 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8684 rsv->size = min_size;
8688 * 1 for the truncate slack space
8689 * 1 for updating the inode.
8691 trans = btrfs_start_transaction(root, 2);
8692 if (IS_ERR(trans)) {
8693 err = PTR_ERR(trans);
8697 /* Migrate the slack space for the truncate to our reserve */
8698 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8703 * So if we truncate and then write and fsync we normally would just
8704 * write the extents that changed, which is a problem if we need to
8705 * first truncate that entire inode. So set this flag so we write out
8706 * all of the extents in the inode to the sync log so we're completely
8709 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8710 trans->block_rsv = rsv;
8713 ret = btrfs_truncate_inode_items(trans, root, inode,
8715 BTRFS_EXTENT_DATA_KEY);
8716 if (ret != -ENOSPC && ret != -EAGAIN) {
8721 trans->block_rsv = &root->fs_info->trans_block_rsv;
8722 ret = btrfs_update_inode(trans, root, inode);
8728 btrfs_end_transaction(trans, root);
8729 btrfs_btree_balance_dirty(root);
8731 trans = btrfs_start_transaction(root, 2);
8732 if (IS_ERR(trans)) {
8733 ret = err = PTR_ERR(trans);
8738 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
8740 BUG_ON(ret); /* shouldn't happen */
8741 trans->block_rsv = rsv;
8744 if (ret == 0 && inode->i_nlink > 0) {
8745 trans->block_rsv = root->orphan_block_rsv;
8746 ret = btrfs_orphan_del(trans, inode);
8752 trans->block_rsv = &root->fs_info->trans_block_rsv;
8753 ret = btrfs_update_inode(trans, root, inode);
8757 ret = btrfs_end_transaction(trans, root);
8758 btrfs_btree_balance_dirty(root);
8762 btrfs_free_block_rsv(root, rsv);
8771 * create a new subvolume directory/inode (helper for the ioctl).
8773 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8774 struct btrfs_root *new_root,
8775 struct btrfs_root *parent_root,
8778 struct inode *inode;
8782 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8783 new_dirid, new_dirid,
8784 S_IFDIR | (~current_umask() & S_IRWXUGO),
8787 return PTR_ERR(inode);
8788 inode->i_op = &btrfs_dir_inode_operations;
8789 inode->i_fop = &btrfs_dir_file_operations;
8791 set_nlink(inode, 1);
8792 btrfs_i_size_write(inode, 0);
8793 unlock_new_inode(inode);
8795 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8797 btrfs_err(new_root->fs_info,
8798 "error inheriting subvolume %llu properties: %d",
8799 new_root->root_key.objectid, err);
8801 err = btrfs_update_inode(trans, new_root, inode);
8807 struct inode *btrfs_alloc_inode(struct super_block *sb)
8809 struct btrfs_inode *ei;
8810 struct inode *inode;
8812 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
8819 ei->last_sub_trans = 0;
8820 ei->logged_trans = 0;
8821 ei->delalloc_bytes = 0;
8822 ei->defrag_bytes = 0;
8823 ei->disk_i_size = 0;
8826 ei->index_cnt = (u64)-1;
8828 ei->last_unlink_trans = 0;
8829 ei->last_log_commit = 0;
8831 spin_lock_init(&ei->lock);
8832 ei->outstanding_extents = 0;
8833 ei->reserved_extents = 0;
8835 ei->runtime_flags = 0;
8836 ei->force_compress = BTRFS_COMPRESS_NONE;
8838 ei->delayed_node = NULL;
8840 ei->i_otime.tv_sec = 0;
8841 ei->i_otime.tv_nsec = 0;
8843 inode = &ei->vfs_inode;
8844 extent_map_tree_init(&ei->extent_tree);
8845 extent_io_tree_init(&ei->io_tree, &inode->i_data);
8846 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
8847 ei->io_tree.track_uptodate = 1;
8848 ei->io_failure_tree.track_uptodate = 1;
8849 atomic_set(&ei->sync_writers, 0);
8850 mutex_init(&ei->log_mutex);
8851 mutex_init(&ei->delalloc_mutex);
8852 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8853 INIT_LIST_HEAD(&ei->delalloc_inodes);
8854 RB_CLEAR_NODE(&ei->rb_node);
8859 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8860 void btrfs_test_destroy_inode(struct inode *inode)
8862 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8863 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8867 static void btrfs_i_callback(struct rcu_head *head)
8869 struct inode *inode = container_of(head, struct inode, i_rcu);
8870 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8873 void btrfs_destroy_inode(struct inode *inode)
8875 struct btrfs_ordered_extent *ordered;
8876 struct btrfs_root *root = BTRFS_I(inode)->root;
8878 WARN_ON(!hlist_empty(&inode->i_dentry));
8879 WARN_ON(inode->i_data.nrpages);
8880 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8881 WARN_ON(BTRFS_I(inode)->reserved_extents);
8882 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8883 WARN_ON(BTRFS_I(inode)->csum_bytes);
8884 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8887 * This can happen where we create an inode, but somebody else also
8888 * created the same inode and we need to destroy the one we already
8894 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
8895 &BTRFS_I(inode)->runtime_flags)) {
8896 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
8898 atomic_dec(&root->orphan_inodes);
8902 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8906 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
8907 ordered->file_offset, ordered->len);
8908 btrfs_remove_ordered_extent(inode, ordered);
8909 btrfs_put_ordered_extent(ordered);
8910 btrfs_put_ordered_extent(ordered);
8913 inode_tree_del(inode);
8914 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8916 call_rcu(&inode->i_rcu, btrfs_i_callback);
8919 int btrfs_drop_inode(struct inode *inode)
8921 struct btrfs_root *root = BTRFS_I(inode)->root;
8926 /* the snap/subvol tree is on deleting */
8927 if (btrfs_root_refs(&root->root_item) == 0)
8930 return generic_drop_inode(inode);
8933 static void init_once(void *foo)
8935 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8937 inode_init_once(&ei->vfs_inode);
8940 void btrfs_destroy_cachep(void)
8943 * Make sure all delayed rcu free inodes are flushed before we
8947 if (btrfs_inode_cachep)
8948 kmem_cache_destroy(btrfs_inode_cachep);
8949 if (btrfs_trans_handle_cachep)
8950 kmem_cache_destroy(btrfs_trans_handle_cachep);
8951 if (btrfs_transaction_cachep)
8952 kmem_cache_destroy(btrfs_transaction_cachep);
8953 if (btrfs_path_cachep)
8954 kmem_cache_destroy(btrfs_path_cachep);
8955 if (btrfs_free_space_cachep)
8956 kmem_cache_destroy(btrfs_free_space_cachep);
8957 if (btrfs_delalloc_work_cachep)
8958 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8961 int btrfs_init_cachep(void)
8963 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8964 sizeof(struct btrfs_inode), 0,
8965 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8966 if (!btrfs_inode_cachep)
8969 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8970 sizeof(struct btrfs_trans_handle), 0,
8971 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8972 if (!btrfs_trans_handle_cachep)
8975 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8976 sizeof(struct btrfs_transaction), 0,
8977 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8978 if (!btrfs_transaction_cachep)
8981 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8982 sizeof(struct btrfs_path), 0,
8983 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8984 if (!btrfs_path_cachep)
8987 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8988 sizeof(struct btrfs_free_space), 0,
8989 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8990 if (!btrfs_free_space_cachep)
8993 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8994 sizeof(struct btrfs_delalloc_work), 0,
8995 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8997 if (!btrfs_delalloc_work_cachep)
9002 btrfs_destroy_cachep();
9006 static int btrfs_getattr(struct vfsmount *mnt,
9007 struct dentry *dentry, struct kstat *stat)
9010 struct inode *inode = dentry->d_inode;
9011 u32 blocksize = inode->i_sb->s_blocksize;
9013 generic_fillattr(inode, stat);
9014 stat->dev = BTRFS_I(inode)->root->anon_dev;
9015 stat->blksize = PAGE_CACHE_SIZE;
9017 spin_lock(&BTRFS_I(inode)->lock);
9018 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9019 spin_unlock(&BTRFS_I(inode)->lock);
9020 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9021 ALIGN(delalloc_bytes, blocksize)) >> 9;
9025 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9026 struct inode *new_dir, struct dentry *new_dentry)
9028 struct btrfs_trans_handle *trans;
9029 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9030 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9031 struct inode *new_inode = new_dentry->d_inode;
9032 struct inode *old_inode = old_dentry->d_inode;
9033 struct timespec ctime = CURRENT_TIME;
9037 u64 old_ino = btrfs_ino(old_inode);
9039 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9042 /* we only allow rename subvolume link between subvolumes */
9043 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9046 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9047 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
9050 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9051 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9055 /* check for collisions, even if the name isn't there */
9056 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9057 new_dentry->d_name.name,
9058 new_dentry->d_name.len);
9061 if (ret == -EEXIST) {
9063 * eexist without a new_inode */
9064 if (WARN_ON(!new_inode)) {
9068 /* maybe -EOVERFLOW */
9075 * we're using rename to replace one file with another. Start IO on it
9076 * now so we don't add too much work to the end of the transaction
9078 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9079 filemap_flush(old_inode->i_mapping);
9081 /* close the racy window with snapshot create/destroy ioctl */
9082 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9083 down_read(&root->fs_info->subvol_sem);
9085 * We want to reserve the absolute worst case amount of items. So if
9086 * both inodes are subvols and we need to unlink them then that would
9087 * require 4 item modifications, but if they are both normal inodes it
9088 * would require 5 item modifications, so we'll assume their normal
9089 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9090 * should cover the worst case number of items we'll modify.
9092 trans = btrfs_start_transaction(root, 11);
9093 if (IS_ERR(trans)) {
9094 ret = PTR_ERR(trans);
9099 btrfs_record_root_in_trans(trans, dest);
9101 ret = btrfs_set_inode_index(new_dir, &index);
9105 BTRFS_I(old_inode)->dir_index = 0ULL;
9106 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9107 /* force full log commit if subvolume involved. */
9108 btrfs_set_log_full_commit(root->fs_info, trans);
9110 ret = btrfs_insert_inode_ref(trans, dest,
9111 new_dentry->d_name.name,
9112 new_dentry->d_name.len,
9114 btrfs_ino(new_dir), index);
9118 * this is an ugly little race, but the rename is required
9119 * to make sure that if we crash, the inode is either at the
9120 * old name or the new one. pinning the log transaction lets
9121 * us make sure we don't allow a log commit to come in after
9122 * we unlink the name but before we add the new name back in.
9124 btrfs_pin_log_trans(root);
9127 inode_inc_iversion(old_dir);
9128 inode_inc_iversion(new_dir);
9129 inode_inc_iversion(old_inode);
9130 old_dir->i_ctime = old_dir->i_mtime = ctime;
9131 new_dir->i_ctime = new_dir->i_mtime = ctime;
9132 old_inode->i_ctime = ctime;
9134 if (old_dentry->d_parent != new_dentry->d_parent)
9135 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9137 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9138 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9139 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9140 old_dentry->d_name.name,
9141 old_dentry->d_name.len);
9143 ret = __btrfs_unlink_inode(trans, root, old_dir,
9144 old_dentry->d_inode,
9145 old_dentry->d_name.name,
9146 old_dentry->d_name.len);
9148 ret = btrfs_update_inode(trans, root, old_inode);
9151 btrfs_abort_transaction(trans, root, ret);
9156 inode_inc_iversion(new_inode);
9157 new_inode->i_ctime = CURRENT_TIME;
9158 if (unlikely(btrfs_ino(new_inode) ==
9159 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9160 root_objectid = BTRFS_I(new_inode)->location.objectid;
9161 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9163 new_dentry->d_name.name,
9164 new_dentry->d_name.len);
9165 BUG_ON(new_inode->i_nlink == 0);
9167 ret = btrfs_unlink_inode(trans, dest, new_dir,
9168 new_dentry->d_inode,
9169 new_dentry->d_name.name,
9170 new_dentry->d_name.len);
9172 if (!ret && new_inode->i_nlink == 0)
9173 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
9175 btrfs_abort_transaction(trans, root, ret);
9180 ret = btrfs_add_link(trans, new_dir, old_inode,
9181 new_dentry->d_name.name,
9182 new_dentry->d_name.len, 0, index);
9184 btrfs_abort_transaction(trans, root, ret);
9188 if (old_inode->i_nlink == 1)
9189 BTRFS_I(old_inode)->dir_index = index;
9191 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9192 struct dentry *parent = new_dentry->d_parent;
9193 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9194 btrfs_end_log_trans(root);
9197 btrfs_end_transaction(trans, root);
9199 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9200 up_read(&root->fs_info->subvol_sem);
9205 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9206 struct inode *new_dir, struct dentry *new_dentry,
9209 if (flags & ~RENAME_NOREPLACE)
9212 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
9215 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9217 struct btrfs_delalloc_work *delalloc_work;
9218 struct inode *inode;
9220 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9222 inode = delalloc_work->inode;
9223 if (delalloc_work->wait) {
9224 btrfs_wait_ordered_range(inode, 0, (u64)-1);
9226 filemap_flush(inode->i_mapping);
9227 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9228 &BTRFS_I(inode)->runtime_flags))
9229 filemap_flush(inode->i_mapping);
9232 if (delalloc_work->delay_iput)
9233 btrfs_add_delayed_iput(inode);
9236 complete(&delalloc_work->completion);
9239 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9240 int wait, int delay_iput)
9242 struct btrfs_delalloc_work *work;
9244 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
9248 init_completion(&work->completion);
9249 INIT_LIST_HEAD(&work->list);
9250 work->inode = inode;
9252 work->delay_iput = delay_iput;
9253 WARN_ON_ONCE(!inode);
9254 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9255 btrfs_run_delalloc_work, NULL, NULL);
9260 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9262 wait_for_completion(&work->completion);
9263 kmem_cache_free(btrfs_delalloc_work_cachep, work);
9267 * some fairly slow code that needs optimization. This walks the list
9268 * of all the inodes with pending delalloc and forces them to disk.
9270 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9273 struct btrfs_inode *binode;
9274 struct inode *inode;
9275 struct btrfs_delalloc_work *work, *next;
9276 struct list_head works;
9277 struct list_head splice;
9280 INIT_LIST_HEAD(&works);
9281 INIT_LIST_HEAD(&splice);
9283 mutex_lock(&root->delalloc_mutex);
9284 spin_lock(&root->delalloc_lock);
9285 list_splice_init(&root->delalloc_inodes, &splice);
9286 while (!list_empty(&splice)) {
9287 binode = list_entry(splice.next, struct btrfs_inode,
9290 list_move_tail(&binode->delalloc_inodes,
9291 &root->delalloc_inodes);
9292 inode = igrab(&binode->vfs_inode);
9294 cond_resched_lock(&root->delalloc_lock);
9297 spin_unlock(&root->delalloc_lock);
9299 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9302 btrfs_add_delayed_iput(inode);
9308 list_add_tail(&work->list, &works);
9309 btrfs_queue_work(root->fs_info->flush_workers,
9312 if (nr != -1 && ret >= nr)
9315 spin_lock(&root->delalloc_lock);
9317 spin_unlock(&root->delalloc_lock);
9320 list_for_each_entry_safe(work, next, &works, list) {
9321 list_del_init(&work->list);
9322 btrfs_wait_and_free_delalloc_work(work);
9325 if (!list_empty_careful(&splice)) {
9326 spin_lock(&root->delalloc_lock);
9327 list_splice_tail(&splice, &root->delalloc_inodes);
9328 spin_unlock(&root->delalloc_lock);
9330 mutex_unlock(&root->delalloc_mutex);
9334 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9338 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9341 ret = __start_delalloc_inodes(root, delay_iput, -1);
9345 * the filemap_flush will queue IO into the worker threads, but
9346 * we have to make sure the IO is actually started and that
9347 * ordered extents get created before we return
9349 atomic_inc(&root->fs_info->async_submit_draining);
9350 while (atomic_read(&root->fs_info->nr_async_submits) ||
9351 atomic_read(&root->fs_info->async_delalloc_pages)) {
9352 wait_event(root->fs_info->async_submit_wait,
9353 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9354 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9356 atomic_dec(&root->fs_info->async_submit_draining);
9360 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9363 struct btrfs_root *root;
9364 struct list_head splice;
9367 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9370 INIT_LIST_HEAD(&splice);
9372 mutex_lock(&fs_info->delalloc_root_mutex);
9373 spin_lock(&fs_info->delalloc_root_lock);
9374 list_splice_init(&fs_info->delalloc_roots, &splice);
9375 while (!list_empty(&splice) && nr) {
9376 root = list_first_entry(&splice, struct btrfs_root,
9378 root = btrfs_grab_fs_root(root);
9380 list_move_tail(&root->delalloc_root,
9381 &fs_info->delalloc_roots);
9382 spin_unlock(&fs_info->delalloc_root_lock);
9384 ret = __start_delalloc_inodes(root, delay_iput, nr);
9385 btrfs_put_fs_root(root);
9393 spin_lock(&fs_info->delalloc_root_lock);
9395 spin_unlock(&fs_info->delalloc_root_lock);
9398 atomic_inc(&fs_info->async_submit_draining);
9399 while (atomic_read(&fs_info->nr_async_submits) ||
9400 atomic_read(&fs_info->async_delalloc_pages)) {
9401 wait_event(fs_info->async_submit_wait,
9402 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9403 atomic_read(&fs_info->async_delalloc_pages) == 0));
9405 atomic_dec(&fs_info->async_submit_draining);
9407 if (!list_empty_careful(&splice)) {
9408 spin_lock(&fs_info->delalloc_root_lock);
9409 list_splice_tail(&splice, &fs_info->delalloc_roots);
9410 spin_unlock(&fs_info->delalloc_root_lock);
9412 mutex_unlock(&fs_info->delalloc_root_mutex);
9416 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9417 const char *symname)
9419 struct btrfs_trans_handle *trans;
9420 struct btrfs_root *root = BTRFS_I(dir)->root;
9421 struct btrfs_path *path;
9422 struct btrfs_key key;
9423 struct inode *inode = NULL;
9431 struct btrfs_file_extent_item *ei;
9432 struct extent_buffer *leaf;
9434 name_len = strlen(symname);
9435 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9436 return -ENAMETOOLONG;
9439 * 2 items for inode item and ref
9440 * 2 items for dir items
9441 * 1 item for xattr if selinux is on
9443 trans = btrfs_start_transaction(root, 5);
9445 return PTR_ERR(trans);
9447 err = btrfs_find_free_ino(root, &objectid);
9451 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9452 dentry->d_name.len, btrfs_ino(dir), objectid,
9453 S_IFLNK|S_IRWXUGO, &index);
9454 if (IS_ERR(inode)) {
9455 err = PTR_ERR(inode);
9460 * If the active LSM wants to access the inode during
9461 * d_instantiate it needs these. Smack checks to see
9462 * if the filesystem supports xattrs by looking at the
9465 inode->i_fop = &btrfs_file_operations;
9466 inode->i_op = &btrfs_file_inode_operations;
9467 inode->i_mapping->a_ops = &btrfs_aops;
9468 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9470 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9472 goto out_unlock_inode;
9474 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9476 goto out_unlock_inode;
9478 path = btrfs_alloc_path();
9481 goto out_unlock_inode;
9483 key.objectid = btrfs_ino(inode);
9485 key.type = BTRFS_EXTENT_DATA_KEY;
9486 datasize = btrfs_file_extent_calc_inline_size(name_len);
9487 err = btrfs_insert_empty_item(trans, root, path, &key,
9490 btrfs_free_path(path);
9491 goto out_unlock_inode;
9493 leaf = path->nodes[0];
9494 ei = btrfs_item_ptr(leaf, path->slots[0],
9495 struct btrfs_file_extent_item);
9496 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9497 btrfs_set_file_extent_type(leaf, ei,
9498 BTRFS_FILE_EXTENT_INLINE);
9499 btrfs_set_file_extent_encryption(leaf, ei, 0);
9500 btrfs_set_file_extent_compression(leaf, ei, 0);
9501 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9502 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9504 ptr = btrfs_file_extent_inline_start(ei);
9505 write_extent_buffer(leaf, symname, ptr, name_len);
9506 btrfs_mark_buffer_dirty(leaf);
9507 btrfs_free_path(path);
9509 inode->i_op = &btrfs_symlink_inode_operations;
9510 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9511 inode_set_bytes(inode, name_len);
9512 btrfs_i_size_write(inode, name_len);
9513 err = btrfs_update_inode(trans, root, inode);
9516 goto out_unlock_inode;
9519 unlock_new_inode(inode);
9520 d_instantiate(dentry, inode);
9523 btrfs_end_transaction(trans, root);
9525 inode_dec_link_count(inode);
9528 btrfs_btree_balance_dirty(root);
9533 unlock_new_inode(inode);
9537 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9538 u64 start, u64 num_bytes, u64 min_size,
9539 loff_t actual_len, u64 *alloc_hint,
9540 struct btrfs_trans_handle *trans)
9542 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9543 struct extent_map *em;
9544 struct btrfs_root *root = BTRFS_I(inode)->root;
9545 struct btrfs_key ins;
9546 u64 cur_offset = start;
9550 bool own_trans = true;
9554 while (num_bytes > 0) {
9556 trans = btrfs_start_transaction(root, 3);
9557 if (IS_ERR(trans)) {
9558 ret = PTR_ERR(trans);
9563 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9564 cur_bytes = max(cur_bytes, min_size);
9565 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9566 *alloc_hint, &ins, 1, 0);
9569 btrfs_end_transaction(trans, root);
9573 ret = insert_reserved_file_extent(trans, inode,
9574 cur_offset, ins.objectid,
9575 ins.offset, ins.offset,
9576 ins.offset, 0, 0, 0,
9577 BTRFS_FILE_EXTENT_PREALLOC);
9579 btrfs_free_reserved_extent(root, ins.objectid,
9581 btrfs_abort_transaction(trans, root, ret);
9583 btrfs_end_transaction(trans, root);
9587 btrfs_drop_extent_cache(inode, cur_offset,
9588 cur_offset + ins.offset -1, 0);
9590 em = alloc_extent_map();
9592 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9593 &BTRFS_I(inode)->runtime_flags);
9597 em->start = cur_offset;
9598 em->orig_start = cur_offset;
9599 em->len = ins.offset;
9600 em->block_start = ins.objectid;
9601 em->block_len = ins.offset;
9602 em->orig_block_len = ins.offset;
9603 em->ram_bytes = ins.offset;
9604 em->bdev = root->fs_info->fs_devices->latest_bdev;
9605 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9606 em->generation = trans->transid;
9609 write_lock(&em_tree->lock);
9610 ret = add_extent_mapping(em_tree, em, 1);
9611 write_unlock(&em_tree->lock);
9614 btrfs_drop_extent_cache(inode, cur_offset,
9615 cur_offset + ins.offset - 1,
9618 free_extent_map(em);
9620 num_bytes -= ins.offset;
9621 cur_offset += ins.offset;
9622 *alloc_hint = ins.objectid + ins.offset;
9624 inode_inc_iversion(inode);
9625 inode->i_ctime = CURRENT_TIME;
9626 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9627 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9628 (actual_len > inode->i_size) &&
9629 (cur_offset > inode->i_size)) {
9630 if (cur_offset > actual_len)
9631 i_size = actual_len;
9633 i_size = cur_offset;
9634 i_size_write(inode, i_size);
9635 btrfs_ordered_update_i_size(inode, i_size, NULL);
9638 ret = btrfs_update_inode(trans, root, inode);
9641 btrfs_abort_transaction(trans, root, ret);
9643 btrfs_end_transaction(trans, root);
9648 btrfs_end_transaction(trans, root);
9653 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9654 u64 start, u64 num_bytes, u64 min_size,
9655 loff_t actual_len, u64 *alloc_hint)
9657 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9658 min_size, actual_len, alloc_hint,
9662 int btrfs_prealloc_file_range_trans(struct inode *inode,
9663 struct btrfs_trans_handle *trans, int mode,
9664 u64 start, u64 num_bytes, u64 min_size,
9665 loff_t actual_len, u64 *alloc_hint)
9667 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9668 min_size, actual_len, alloc_hint, trans);
9671 static int btrfs_set_page_dirty(struct page *page)
9673 return __set_page_dirty_nobuffers(page);
9676 static int btrfs_permission(struct inode *inode, int mask)
9678 struct btrfs_root *root = BTRFS_I(inode)->root;
9679 umode_t mode = inode->i_mode;
9681 if (mask & MAY_WRITE &&
9682 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9683 if (btrfs_root_readonly(root))
9685 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9688 return generic_permission(inode, mask);
9691 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9693 struct btrfs_trans_handle *trans;
9694 struct btrfs_root *root = BTRFS_I(dir)->root;
9695 struct inode *inode = NULL;
9701 * 5 units required for adding orphan entry
9703 trans = btrfs_start_transaction(root, 5);
9705 return PTR_ERR(trans);
9707 ret = btrfs_find_free_ino(root, &objectid);
9711 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
9712 btrfs_ino(dir), objectid, mode, &index);
9713 if (IS_ERR(inode)) {
9714 ret = PTR_ERR(inode);
9719 inode->i_fop = &btrfs_file_operations;
9720 inode->i_op = &btrfs_file_inode_operations;
9722 inode->i_mapping->a_ops = &btrfs_aops;
9723 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9725 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
9729 ret = btrfs_update_inode(trans, root, inode);
9732 ret = btrfs_orphan_add(trans, inode);
9737 * We set number of links to 0 in btrfs_new_inode(), and here we set
9738 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
9741 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9743 set_nlink(inode, 1);
9744 unlock_new_inode(inode);
9745 d_tmpfile(dentry, inode);
9746 mark_inode_dirty(inode);
9749 btrfs_end_transaction(trans, root);
9752 btrfs_balance_delayed_items(root);
9753 btrfs_btree_balance_dirty(root);
9757 unlock_new_inode(inode);
9762 /* Inspired by filemap_check_errors() */
9763 int btrfs_inode_check_errors(struct inode *inode)
9767 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
9768 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
9770 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
9771 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
9777 static const struct inode_operations btrfs_dir_inode_operations = {
9778 .getattr = btrfs_getattr,
9779 .lookup = btrfs_lookup,
9780 .create = btrfs_create,
9781 .unlink = btrfs_unlink,
9783 .mkdir = btrfs_mkdir,
9784 .rmdir = btrfs_rmdir,
9785 .rename2 = btrfs_rename2,
9786 .symlink = btrfs_symlink,
9787 .setattr = btrfs_setattr,
9788 .mknod = btrfs_mknod,
9789 .setxattr = btrfs_setxattr,
9790 .getxattr = btrfs_getxattr,
9791 .listxattr = btrfs_listxattr,
9792 .removexattr = btrfs_removexattr,
9793 .permission = btrfs_permission,
9794 .get_acl = btrfs_get_acl,
9795 .set_acl = btrfs_set_acl,
9796 .update_time = btrfs_update_time,
9797 .tmpfile = btrfs_tmpfile,
9799 static const struct inode_operations btrfs_dir_ro_inode_operations = {
9800 .lookup = btrfs_lookup,
9801 .permission = btrfs_permission,
9802 .get_acl = btrfs_get_acl,
9803 .set_acl = btrfs_set_acl,
9804 .update_time = btrfs_update_time,
9807 static const struct file_operations btrfs_dir_file_operations = {
9808 .llseek = generic_file_llseek,
9809 .read = generic_read_dir,
9810 .iterate = btrfs_real_readdir,
9811 .unlocked_ioctl = btrfs_ioctl,
9812 #ifdef CONFIG_COMPAT
9813 .compat_ioctl = btrfs_ioctl,
9815 .release = btrfs_release_file,
9816 .fsync = btrfs_sync_file,
9819 static struct extent_io_ops btrfs_extent_io_ops = {
9820 .fill_delalloc = run_delalloc_range,
9821 .submit_bio_hook = btrfs_submit_bio_hook,
9822 .merge_bio_hook = btrfs_merge_bio_hook,
9823 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
9824 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
9825 .writepage_start_hook = btrfs_writepage_start_hook,
9826 .set_bit_hook = btrfs_set_bit_hook,
9827 .clear_bit_hook = btrfs_clear_bit_hook,
9828 .merge_extent_hook = btrfs_merge_extent_hook,
9829 .split_extent_hook = btrfs_split_extent_hook,
9833 * btrfs doesn't support the bmap operation because swapfiles
9834 * use bmap to make a mapping of extents in the file. They assume
9835 * these extents won't change over the life of the file and they
9836 * use the bmap result to do IO directly to the drive.
9838 * the btrfs bmap call would return logical addresses that aren't
9839 * suitable for IO and they also will change frequently as COW
9840 * operations happen. So, swapfile + btrfs == corruption.
9842 * For now we're avoiding this by dropping bmap.
9844 static const struct address_space_operations btrfs_aops = {
9845 .readpage = btrfs_readpage,
9846 .writepage = btrfs_writepage,
9847 .writepages = btrfs_writepages,
9848 .readpages = btrfs_readpages,
9849 .direct_IO = btrfs_direct_IO,
9850 .invalidatepage = btrfs_invalidatepage,
9851 .releasepage = btrfs_releasepage,
9852 .set_page_dirty = btrfs_set_page_dirty,
9853 .error_remove_page = generic_error_remove_page,
9856 static const struct address_space_operations btrfs_symlink_aops = {
9857 .readpage = btrfs_readpage,
9858 .writepage = btrfs_writepage,
9859 .invalidatepage = btrfs_invalidatepage,
9860 .releasepage = btrfs_releasepage,
9863 static const struct inode_operations btrfs_file_inode_operations = {
9864 .getattr = btrfs_getattr,
9865 .setattr = btrfs_setattr,
9866 .setxattr = btrfs_setxattr,
9867 .getxattr = btrfs_getxattr,
9868 .listxattr = btrfs_listxattr,
9869 .removexattr = btrfs_removexattr,
9870 .permission = btrfs_permission,
9871 .fiemap = btrfs_fiemap,
9872 .get_acl = btrfs_get_acl,
9873 .set_acl = btrfs_set_acl,
9874 .update_time = btrfs_update_time,
9876 static const struct inode_operations btrfs_special_inode_operations = {
9877 .getattr = btrfs_getattr,
9878 .setattr = btrfs_setattr,
9879 .permission = btrfs_permission,
9880 .setxattr = btrfs_setxattr,
9881 .getxattr = btrfs_getxattr,
9882 .listxattr = btrfs_listxattr,
9883 .removexattr = btrfs_removexattr,
9884 .get_acl = btrfs_get_acl,
9885 .set_acl = btrfs_set_acl,
9886 .update_time = btrfs_update_time,
9888 static const struct inode_operations btrfs_symlink_inode_operations = {
9889 .readlink = generic_readlink,
9890 .follow_link = page_follow_link_light,
9891 .put_link = page_put_link,
9892 .getattr = btrfs_getattr,
9893 .setattr = btrfs_setattr,
9894 .permission = btrfs_permission,
9895 .setxattr = btrfs_setxattr,
9896 .getxattr = btrfs_getxattr,
9897 .listxattr = btrfs_listxattr,
9898 .removexattr = btrfs_removexattr,
9899 .update_time = btrfs_update_time,
9902 const struct dentry_operations btrfs_dentry_operations = {
9903 .d_delete = btrfs_dentry_delete,
9904 .d_release = btrfs_dentry_release,