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>
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
55 #include "compression.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
61 struct btrfs_iget_args {
63 struct btrfs_root *root;
66 static const struct inode_operations btrfs_dir_inode_operations;
67 static const struct inode_operations btrfs_symlink_inode_operations;
68 static const struct inode_operations btrfs_dir_ro_inode_operations;
69 static const struct inode_operations btrfs_special_inode_operations;
70 static const struct inode_operations btrfs_file_inode_operations;
71 static const struct address_space_operations btrfs_aops;
72 static const struct address_space_operations btrfs_symlink_aops;
73 static const struct file_operations btrfs_dir_file_operations;
74 static struct extent_io_ops btrfs_extent_io_ops;
76 static struct kmem_cache *btrfs_inode_cachep;
77 static struct kmem_cache *btrfs_delalloc_work_cachep;
78 struct kmem_cache *btrfs_trans_handle_cachep;
79 struct kmem_cache *btrfs_transaction_cachep;
80 struct kmem_cache *btrfs_path_cachep;
81 struct kmem_cache *btrfs_free_space_cachep;
84 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
85 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
86 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
87 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
88 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
89 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
90 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
91 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
94 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
95 static int btrfs_truncate(struct inode *inode);
96 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
97 static noinline int cow_file_range(struct inode *inode,
98 struct page *locked_page,
99 u64 start, u64 end, int *page_started,
100 unsigned long *nr_written, int unlock);
101 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
102 u64 len, u64 orig_start,
103 u64 block_start, u64 block_len,
104 u64 orig_block_len, int type);
106 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
107 struct inode *inode, struct inode *dir,
108 const struct qstr *qstr)
112 err = btrfs_init_acl(trans, inode, dir);
114 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
119 * this does all the hard work for inserting an inline extent into
120 * the btree. The caller should have done a btrfs_drop_extents so that
121 * no overlapping inline items exist in the btree
123 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
124 struct btrfs_root *root, struct inode *inode,
125 u64 start, size_t size, size_t compressed_size,
127 struct page **compressed_pages)
129 struct btrfs_key key;
130 struct btrfs_path *path;
131 struct extent_buffer *leaf;
132 struct page *page = NULL;
135 struct btrfs_file_extent_item *ei;
138 size_t cur_size = size;
140 unsigned long offset;
142 if (compressed_size && compressed_pages)
143 cur_size = compressed_size;
145 path = btrfs_alloc_path();
149 path->leave_spinning = 1;
151 key.objectid = btrfs_ino(inode);
153 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
154 datasize = btrfs_file_extent_calc_inline_size(cur_size);
156 inode_add_bytes(inode, size);
157 ret = btrfs_insert_empty_item(trans, root, path, &key,
163 leaf = path->nodes[0];
164 ei = btrfs_item_ptr(leaf, path->slots[0],
165 struct btrfs_file_extent_item);
166 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
167 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
168 btrfs_set_file_extent_encryption(leaf, ei, 0);
169 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
170 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
171 ptr = btrfs_file_extent_inline_start(ei);
173 if (compress_type != BTRFS_COMPRESS_NONE) {
176 while (compressed_size > 0) {
177 cpage = compressed_pages[i];
178 cur_size = min_t(unsigned long, compressed_size,
181 kaddr = kmap_atomic(cpage);
182 write_extent_buffer(leaf, kaddr, ptr, cur_size);
183 kunmap_atomic(kaddr);
187 compressed_size -= cur_size;
189 btrfs_set_file_extent_compression(leaf, ei,
192 page = find_get_page(inode->i_mapping,
193 start >> PAGE_CACHE_SHIFT);
194 btrfs_set_file_extent_compression(leaf, ei, 0);
195 kaddr = kmap_atomic(page);
196 offset = start & (PAGE_CACHE_SIZE - 1);
197 write_extent_buffer(leaf, kaddr + offset, ptr, size);
198 kunmap_atomic(kaddr);
199 page_cache_release(page);
201 btrfs_mark_buffer_dirty(leaf);
202 btrfs_free_path(path);
205 * we're an inline extent, so nobody can
206 * extend the file past i_size without locking
207 * a page we already have locked.
209 * We must do any isize and inode updates
210 * before we unlock the pages. Otherwise we
211 * could end up racing with unlink.
213 BTRFS_I(inode)->disk_i_size = inode->i_size;
214 ret = btrfs_update_inode(trans, root, inode);
218 btrfs_free_path(path);
224 * conditionally insert an inline extent into the file. This
225 * does the checks required to make sure the data is small enough
226 * to fit as an inline extent.
228 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
229 struct btrfs_root *root,
230 struct inode *inode, u64 start, u64 end,
231 size_t compressed_size, int compress_type,
232 struct page **compressed_pages)
234 u64 isize = i_size_read(inode);
235 u64 actual_end = min(end + 1, isize);
236 u64 inline_len = actual_end - start;
237 u64 aligned_end = ALIGN(end, root->sectorsize);
238 u64 data_len = inline_len;
242 data_len = compressed_size;
245 actual_end >= PAGE_CACHE_SIZE ||
246 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
248 (actual_end & (root->sectorsize - 1)) == 0) ||
250 data_len > root->fs_info->max_inline) {
254 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
258 if (isize > actual_end)
259 inline_len = min_t(u64, isize, actual_end);
260 ret = insert_inline_extent(trans, root, inode, start,
261 inline_len, compressed_size,
262 compress_type, compressed_pages);
263 if (ret && ret != -ENOSPC) {
264 btrfs_abort_transaction(trans, root, ret);
266 } else if (ret == -ENOSPC) {
270 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
271 btrfs_delalloc_release_metadata(inode, end + 1 - start);
272 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
276 struct async_extent {
281 unsigned long nr_pages;
283 struct list_head list;
288 struct btrfs_root *root;
289 struct page *locked_page;
292 struct list_head extents;
293 struct btrfs_work work;
296 static noinline int add_async_extent(struct async_cow *cow,
297 u64 start, u64 ram_size,
300 unsigned long nr_pages,
303 struct async_extent *async_extent;
305 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
306 BUG_ON(!async_extent); /* -ENOMEM */
307 async_extent->start = start;
308 async_extent->ram_size = ram_size;
309 async_extent->compressed_size = compressed_size;
310 async_extent->pages = pages;
311 async_extent->nr_pages = nr_pages;
312 async_extent->compress_type = compress_type;
313 list_add_tail(&async_extent->list, &cow->extents);
318 * we create compressed extents in two phases. The first
319 * phase compresses a range of pages that have already been
320 * locked (both pages and state bits are locked).
322 * This is done inside an ordered work queue, and the compression
323 * is spread across many cpus. The actual IO submission is step
324 * two, and the ordered work queue takes care of making sure that
325 * happens in the same order things were put onto the queue by
326 * writepages and friends.
328 * If this code finds it can't get good compression, it puts an
329 * entry onto the work queue to write the uncompressed bytes. This
330 * makes sure that both compressed inodes and uncompressed inodes
331 * are written in the same order that the flusher thread sent them
334 static noinline int compress_file_range(struct inode *inode,
335 struct page *locked_page,
337 struct async_cow *async_cow,
340 struct btrfs_root *root = BTRFS_I(inode)->root;
341 struct btrfs_trans_handle *trans;
343 u64 blocksize = root->sectorsize;
345 u64 isize = i_size_read(inode);
347 struct page **pages = NULL;
348 unsigned long nr_pages;
349 unsigned long nr_pages_ret = 0;
350 unsigned long total_compressed = 0;
351 unsigned long total_in = 0;
352 unsigned long max_compressed = 128 * 1024;
353 unsigned long max_uncompressed = 128 * 1024;
356 int compress_type = root->fs_info->compress_type;
359 /* if this is a small write inside eof, kick off a defrag */
360 if ((end - start + 1) < 16 * 1024 &&
361 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
362 btrfs_add_inode_defrag(NULL, inode);
364 actual_end = min_t(u64, isize, end + 1);
367 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
368 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
371 * we don't want to send crud past the end of i_size through
372 * compression, that's just a waste of CPU time. So, if the
373 * end of the file is before the start of our current
374 * requested range of bytes, we bail out to the uncompressed
375 * cleanup code that can deal with all of this.
377 * It isn't really the fastest way to fix things, but this is a
378 * very uncommon corner.
380 if (actual_end <= start)
381 goto cleanup_and_bail_uncompressed;
383 total_compressed = actual_end - start;
385 /* we want to make sure that amount of ram required to uncompress
386 * an extent is reasonable, so we limit the total size in ram
387 * of a compressed extent to 128k. This is a crucial number
388 * because it also controls how easily we can spread reads across
389 * cpus for decompression.
391 * We also want to make sure the amount of IO required to do
392 * a random read is reasonably small, so we limit the size of
393 * a compressed extent to 128k.
395 total_compressed = min(total_compressed, max_uncompressed);
396 num_bytes = ALIGN(end - start + 1, blocksize);
397 num_bytes = max(blocksize, num_bytes);
402 * we do compression for mount -o compress and when the
403 * inode has not been flagged as nocompress. This flag can
404 * change at any time if we discover bad compression ratios.
406 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
407 (btrfs_test_opt(root, COMPRESS) ||
408 (BTRFS_I(inode)->force_compress) ||
409 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
411 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
413 /* just bail out to the uncompressed code */
417 if (BTRFS_I(inode)->force_compress)
418 compress_type = BTRFS_I(inode)->force_compress;
421 * we need to call clear_page_dirty_for_io on each
422 * page in the range. Otherwise applications with the file
423 * mmap'd can wander in and change the page contents while
424 * we are compressing them.
426 * If the compression fails for any reason, we set the pages
427 * dirty again later on.
429 extent_range_clear_dirty_for_io(inode, start, end);
431 ret = btrfs_compress_pages(compress_type,
432 inode->i_mapping, start,
433 total_compressed, pages,
434 nr_pages, &nr_pages_ret,
440 unsigned long offset = total_compressed &
441 (PAGE_CACHE_SIZE - 1);
442 struct page *page = pages[nr_pages_ret - 1];
445 /* zero the tail end of the last page, we might be
446 * sending it down to disk
449 kaddr = kmap_atomic(page);
450 memset(kaddr + offset, 0,
451 PAGE_CACHE_SIZE - offset);
452 kunmap_atomic(kaddr);
459 trans = btrfs_join_transaction(root);
461 ret = PTR_ERR(trans);
463 goto cleanup_and_out;
465 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
467 /* lets try to make an inline extent */
468 if (ret || total_in < (actual_end - start)) {
469 /* we didn't compress the entire range, try
470 * to make an uncompressed inline extent.
472 ret = cow_file_range_inline(trans, root, inode,
473 start, end, 0, 0, NULL);
475 /* try making a compressed inline extent */
476 ret = cow_file_range_inline(trans, root, inode,
479 compress_type, pages);
483 * inline extent creation worked or returned error,
484 * we don't need to create any more async work items.
485 * Unlock and free up our temp pages.
487 extent_clear_unlock_delalloc(inode,
488 &BTRFS_I(inode)->io_tree,
490 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
491 EXTENT_CLEAR_DELALLOC |
492 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
494 btrfs_end_transaction(trans, root);
497 btrfs_end_transaction(trans, root);
502 * we aren't doing an inline extent round the compressed size
503 * up to a block size boundary so the allocator does sane
506 total_compressed = ALIGN(total_compressed, blocksize);
509 * one last check to make sure the compression is really a
510 * win, compare the page count read with the blocks on disk
512 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
513 if (total_compressed >= total_in) {
516 num_bytes = total_in;
519 if (!will_compress && pages) {
521 * the compression code ran but failed to make things smaller,
522 * free any pages it allocated and our page pointer array
524 for (i = 0; i < nr_pages_ret; i++) {
525 WARN_ON(pages[i]->mapping);
526 page_cache_release(pages[i]);
530 total_compressed = 0;
533 /* flag the file so we don't compress in the future */
534 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
535 !(BTRFS_I(inode)->force_compress)) {
536 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
542 /* the async work queues will take care of doing actual
543 * allocation on disk for these compressed pages,
544 * and will submit them to the elevator.
546 add_async_extent(async_cow, start, num_bytes,
547 total_compressed, pages, nr_pages_ret,
550 if (start + num_bytes < end) {
557 cleanup_and_bail_uncompressed:
559 * No compression, but we still need to write the pages in
560 * the file we've been given so far. redirty the locked
561 * page if it corresponds to our extent and set things up
562 * for the async work queue to run cow_file_range to do
563 * the normal delalloc dance
565 if (page_offset(locked_page) >= start &&
566 page_offset(locked_page) <= end) {
567 __set_page_dirty_nobuffers(locked_page);
568 /* unlocked later on in the async handlers */
571 extent_range_redirty_for_io(inode, start, end);
572 add_async_extent(async_cow, start, end - start + 1,
573 0, NULL, 0, BTRFS_COMPRESS_NONE);
581 for (i = 0; i < nr_pages_ret; i++) {
582 WARN_ON(pages[i]->mapping);
583 page_cache_release(pages[i]);
590 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
592 EXTENT_CLEAR_UNLOCK_PAGE |
594 EXTENT_CLEAR_DELALLOC |
595 EXTENT_SET_WRITEBACK |
596 EXTENT_END_WRITEBACK);
597 if (!trans || IS_ERR(trans))
598 btrfs_error(root->fs_info, ret, "Failed to join transaction");
600 btrfs_abort_transaction(trans, root, ret);
605 * phase two of compressed writeback. This is the ordered portion
606 * of the code, which only gets called in the order the work was
607 * queued. We walk all the async extents created by compress_file_range
608 * and send them down to the disk.
610 static noinline int submit_compressed_extents(struct inode *inode,
611 struct async_cow *async_cow)
613 struct async_extent *async_extent;
615 struct btrfs_trans_handle *trans;
616 struct btrfs_key ins;
617 struct extent_map *em;
618 struct btrfs_root *root = BTRFS_I(inode)->root;
619 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
620 struct extent_io_tree *io_tree;
623 if (list_empty(&async_cow->extents))
627 while (!list_empty(&async_cow->extents)) {
628 async_extent = list_entry(async_cow->extents.next,
629 struct async_extent, list);
630 list_del(&async_extent->list);
632 io_tree = &BTRFS_I(inode)->io_tree;
635 /* did the compression code fall back to uncompressed IO? */
636 if (!async_extent->pages) {
637 int page_started = 0;
638 unsigned long nr_written = 0;
640 lock_extent(io_tree, async_extent->start,
641 async_extent->start +
642 async_extent->ram_size - 1);
644 /* allocate blocks */
645 ret = cow_file_range(inode, async_cow->locked_page,
647 async_extent->start +
648 async_extent->ram_size - 1,
649 &page_started, &nr_written, 0);
654 * if page_started, cow_file_range inserted an
655 * inline extent and took care of all the unlocking
656 * and IO for us. Otherwise, we need to submit
657 * all those pages down to the drive.
659 if (!page_started && !ret)
660 extent_write_locked_range(io_tree,
661 inode, async_extent->start,
662 async_extent->start +
663 async_extent->ram_size - 1,
667 unlock_page(async_cow->locked_page);
673 lock_extent(io_tree, async_extent->start,
674 async_extent->start + async_extent->ram_size - 1);
676 trans = btrfs_join_transaction(root);
678 ret = PTR_ERR(trans);
680 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
681 ret = btrfs_reserve_extent(trans, root,
682 async_extent->compressed_size,
683 async_extent->compressed_size,
684 0, alloc_hint, &ins, 1);
685 if (ret && ret != -ENOSPC)
686 btrfs_abort_transaction(trans, root, ret);
687 btrfs_end_transaction(trans, root);
693 for (i = 0; i < async_extent->nr_pages; i++) {
694 WARN_ON(async_extent->pages[i]->mapping);
695 page_cache_release(async_extent->pages[i]);
697 kfree(async_extent->pages);
698 async_extent->nr_pages = 0;
699 async_extent->pages = NULL;
707 * here we're doing allocation and writeback of the
710 btrfs_drop_extent_cache(inode, async_extent->start,
711 async_extent->start +
712 async_extent->ram_size - 1, 0);
714 em = alloc_extent_map();
716 goto out_free_reserve;
717 em->start = async_extent->start;
718 em->len = async_extent->ram_size;
719 em->orig_start = em->start;
720 em->mod_start = em->start;
721 em->mod_len = em->len;
723 em->block_start = ins.objectid;
724 em->block_len = ins.offset;
725 em->orig_block_len = ins.offset;
726 em->bdev = root->fs_info->fs_devices->latest_bdev;
727 em->compress_type = async_extent->compress_type;
728 set_bit(EXTENT_FLAG_PINNED, &em->flags);
729 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
733 write_lock(&em_tree->lock);
734 ret = add_extent_mapping(em_tree, em);
737 &em_tree->modified_extents);
738 write_unlock(&em_tree->lock);
739 if (ret != -EEXIST) {
743 btrfs_drop_extent_cache(inode, async_extent->start,
744 async_extent->start +
745 async_extent->ram_size - 1, 0);
749 goto out_free_reserve;
751 ret = btrfs_add_ordered_extent_compress(inode,
754 async_extent->ram_size,
756 BTRFS_ORDERED_COMPRESSED,
757 async_extent->compress_type);
759 goto out_free_reserve;
762 * clear dirty, set writeback and unlock the pages.
764 extent_clear_unlock_delalloc(inode,
765 &BTRFS_I(inode)->io_tree,
767 async_extent->start +
768 async_extent->ram_size - 1,
769 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
770 EXTENT_CLEAR_UNLOCK |
771 EXTENT_CLEAR_DELALLOC |
772 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
774 ret = btrfs_submit_compressed_write(inode,
776 async_extent->ram_size,
778 ins.offset, async_extent->pages,
779 async_extent->nr_pages);
780 alloc_hint = ins.objectid + ins.offset;
790 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
792 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
794 async_extent->start +
795 async_extent->ram_size - 1,
796 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
797 EXTENT_CLEAR_UNLOCK |
798 EXTENT_CLEAR_DELALLOC |
800 EXTENT_SET_WRITEBACK |
801 EXTENT_END_WRITEBACK);
806 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
809 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
810 struct extent_map *em;
813 read_lock(&em_tree->lock);
814 em = search_extent_mapping(em_tree, start, num_bytes);
817 * if block start isn't an actual block number then find the
818 * first block in this inode and use that as a hint. If that
819 * block is also bogus then just don't worry about it.
821 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
823 em = search_extent_mapping(em_tree, 0, 0);
824 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
825 alloc_hint = em->block_start;
829 alloc_hint = em->block_start;
833 read_unlock(&em_tree->lock);
839 * when extent_io.c finds a delayed allocation range in the file,
840 * the call backs end up in this code. The basic idea is to
841 * allocate extents on disk for the range, and create ordered data structs
842 * in ram to track those extents.
844 * locked_page is the page that writepage had locked already. We use
845 * it to make sure we don't do extra locks or unlocks.
847 * *page_started is set to one if we unlock locked_page and do everything
848 * required to start IO on it. It may be clean and already done with
851 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
853 struct btrfs_root *root,
854 struct page *locked_page,
855 u64 start, u64 end, int *page_started,
856 unsigned long *nr_written,
861 unsigned long ram_size;
864 u64 blocksize = root->sectorsize;
865 struct btrfs_key ins;
866 struct extent_map *em;
867 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
870 BUG_ON(btrfs_is_free_space_inode(inode));
872 num_bytes = ALIGN(end - start + 1, blocksize);
873 num_bytes = max(blocksize, num_bytes);
874 disk_num_bytes = num_bytes;
876 /* if this is a small write inside eof, kick off defrag */
877 if (num_bytes < 64 * 1024 &&
878 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
879 btrfs_add_inode_defrag(trans, inode);
882 /* lets try to make an inline extent */
883 ret = cow_file_range_inline(trans, root, inode,
884 start, end, 0, 0, NULL);
886 extent_clear_unlock_delalloc(inode,
887 &BTRFS_I(inode)->io_tree,
889 EXTENT_CLEAR_UNLOCK_PAGE |
890 EXTENT_CLEAR_UNLOCK |
891 EXTENT_CLEAR_DELALLOC |
893 EXTENT_SET_WRITEBACK |
894 EXTENT_END_WRITEBACK);
896 *nr_written = *nr_written +
897 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
900 } else if (ret < 0) {
901 btrfs_abort_transaction(trans, root, ret);
906 BUG_ON(disk_num_bytes >
907 btrfs_super_total_bytes(root->fs_info->super_copy));
909 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
910 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
912 while (disk_num_bytes > 0) {
915 cur_alloc_size = disk_num_bytes;
916 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
917 root->sectorsize, 0, alloc_hint,
920 btrfs_abort_transaction(trans, root, ret);
924 em = alloc_extent_map();
925 BUG_ON(!em); /* -ENOMEM */
927 em->orig_start = em->start;
928 ram_size = ins.offset;
929 em->len = ins.offset;
930 em->mod_start = em->start;
931 em->mod_len = em->len;
933 em->block_start = ins.objectid;
934 em->block_len = ins.offset;
935 em->orig_block_len = ins.offset;
936 em->bdev = root->fs_info->fs_devices->latest_bdev;
937 set_bit(EXTENT_FLAG_PINNED, &em->flags);
941 write_lock(&em_tree->lock);
942 ret = add_extent_mapping(em_tree, em);
945 &em_tree->modified_extents);
946 write_unlock(&em_tree->lock);
947 if (ret != -EEXIST) {
951 btrfs_drop_extent_cache(inode, start,
952 start + ram_size - 1, 0);
955 cur_alloc_size = ins.offset;
956 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
957 ram_size, cur_alloc_size, 0);
958 BUG_ON(ret); /* -ENOMEM */
960 if (root->root_key.objectid ==
961 BTRFS_DATA_RELOC_TREE_OBJECTID) {
962 ret = btrfs_reloc_clone_csums(inode, start,
965 btrfs_abort_transaction(trans, root, ret);
970 if (disk_num_bytes < cur_alloc_size)
973 /* we're not doing compressed IO, don't unlock the first
974 * page (which the caller expects to stay locked), don't
975 * clear any dirty bits and don't set any writeback bits
977 * Do set the Private2 bit so we know this page was properly
978 * setup for writepage
980 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
981 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
984 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
985 start, start + ram_size - 1,
987 disk_num_bytes -= cur_alloc_size;
988 num_bytes -= cur_alloc_size;
989 alloc_hint = ins.objectid + ins.offset;
990 start += cur_alloc_size;
996 extent_clear_unlock_delalloc(inode,
997 &BTRFS_I(inode)->io_tree,
998 start, end, locked_page,
999 EXTENT_CLEAR_UNLOCK_PAGE |
1000 EXTENT_CLEAR_UNLOCK |
1001 EXTENT_CLEAR_DELALLOC |
1002 EXTENT_CLEAR_DIRTY |
1003 EXTENT_SET_WRITEBACK |
1004 EXTENT_END_WRITEBACK);
1009 static noinline int cow_file_range(struct inode *inode,
1010 struct page *locked_page,
1011 u64 start, u64 end, int *page_started,
1012 unsigned long *nr_written,
1015 struct btrfs_trans_handle *trans;
1016 struct btrfs_root *root = BTRFS_I(inode)->root;
1019 trans = btrfs_join_transaction(root);
1020 if (IS_ERR(trans)) {
1021 extent_clear_unlock_delalloc(inode,
1022 &BTRFS_I(inode)->io_tree,
1023 start, end, locked_page,
1024 EXTENT_CLEAR_UNLOCK_PAGE |
1025 EXTENT_CLEAR_UNLOCK |
1026 EXTENT_CLEAR_DELALLOC |
1027 EXTENT_CLEAR_DIRTY |
1028 EXTENT_SET_WRITEBACK |
1029 EXTENT_END_WRITEBACK);
1030 return PTR_ERR(trans);
1032 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1034 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1035 page_started, nr_written, unlock);
1037 btrfs_end_transaction(trans, root);
1043 * work queue call back to started compression on a file and pages
1045 static noinline void async_cow_start(struct btrfs_work *work)
1047 struct async_cow *async_cow;
1049 async_cow = container_of(work, struct async_cow, work);
1051 compress_file_range(async_cow->inode, async_cow->locked_page,
1052 async_cow->start, async_cow->end, async_cow,
1054 if (num_added == 0) {
1055 btrfs_add_delayed_iput(async_cow->inode);
1056 async_cow->inode = NULL;
1061 * work queue call back to submit previously compressed pages
1063 static noinline void async_cow_submit(struct btrfs_work *work)
1065 struct async_cow *async_cow;
1066 struct btrfs_root *root;
1067 unsigned long nr_pages;
1069 async_cow = container_of(work, struct async_cow, work);
1071 root = async_cow->root;
1072 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1075 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1077 waitqueue_active(&root->fs_info->async_submit_wait))
1078 wake_up(&root->fs_info->async_submit_wait);
1080 if (async_cow->inode)
1081 submit_compressed_extents(async_cow->inode, async_cow);
1084 static noinline void async_cow_free(struct btrfs_work *work)
1086 struct async_cow *async_cow;
1087 async_cow = container_of(work, struct async_cow, work);
1088 if (async_cow->inode)
1089 btrfs_add_delayed_iput(async_cow->inode);
1093 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1094 u64 start, u64 end, int *page_started,
1095 unsigned long *nr_written)
1097 struct async_cow *async_cow;
1098 struct btrfs_root *root = BTRFS_I(inode)->root;
1099 unsigned long nr_pages;
1101 int limit = 10 * 1024 * 1024;
1103 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1104 1, 0, NULL, GFP_NOFS);
1105 while (start < end) {
1106 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1107 BUG_ON(!async_cow); /* -ENOMEM */
1108 async_cow->inode = igrab(inode);
1109 async_cow->root = root;
1110 async_cow->locked_page = locked_page;
1111 async_cow->start = start;
1113 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1116 cur_end = min(end, start + 512 * 1024 - 1);
1118 async_cow->end = cur_end;
1119 INIT_LIST_HEAD(&async_cow->extents);
1121 async_cow->work.func = async_cow_start;
1122 async_cow->work.ordered_func = async_cow_submit;
1123 async_cow->work.ordered_free = async_cow_free;
1124 async_cow->work.flags = 0;
1126 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1128 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1130 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1133 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1134 wait_event(root->fs_info->async_submit_wait,
1135 (atomic_read(&root->fs_info->async_delalloc_pages) <
1139 while (atomic_read(&root->fs_info->async_submit_draining) &&
1140 atomic_read(&root->fs_info->async_delalloc_pages)) {
1141 wait_event(root->fs_info->async_submit_wait,
1142 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1146 *nr_written += nr_pages;
1147 start = cur_end + 1;
1153 static noinline int csum_exist_in_range(struct btrfs_root *root,
1154 u64 bytenr, u64 num_bytes)
1157 struct btrfs_ordered_sum *sums;
1160 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1161 bytenr + num_bytes - 1, &list, 0);
1162 if (ret == 0 && list_empty(&list))
1165 while (!list_empty(&list)) {
1166 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1167 list_del(&sums->list);
1174 * when nowcow writeback call back. This checks for snapshots or COW copies
1175 * of the extents that exist in the file, and COWs the file as required.
1177 * If no cow copies or snapshots exist, we write directly to the existing
1180 static noinline int run_delalloc_nocow(struct inode *inode,
1181 struct page *locked_page,
1182 u64 start, u64 end, int *page_started, int force,
1183 unsigned long *nr_written)
1185 struct btrfs_root *root = BTRFS_I(inode)->root;
1186 struct btrfs_trans_handle *trans;
1187 struct extent_buffer *leaf;
1188 struct btrfs_path *path;
1189 struct btrfs_file_extent_item *fi;
1190 struct btrfs_key found_key;
1204 u64 ino = btrfs_ino(inode);
1206 path = btrfs_alloc_path();
1208 extent_clear_unlock_delalloc(inode,
1209 &BTRFS_I(inode)->io_tree,
1210 start, end, locked_page,
1211 EXTENT_CLEAR_UNLOCK_PAGE |
1212 EXTENT_CLEAR_UNLOCK |
1213 EXTENT_CLEAR_DELALLOC |
1214 EXTENT_CLEAR_DIRTY |
1215 EXTENT_SET_WRITEBACK |
1216 EXTENT_END_WRITEBACK);
1220 nolock = btrfs_is_free_space_inode(inode);
1223 trans = btrfs_join_transaction_nolock(root);
1225 trans = btrfs_join_transaction(root);
1227 if (IS_ERR(trans)) {
1228 extent_clear_unlock_delalloc(inode,
1229 &BTRFS_I(inode)->io_tree,
1230 start, end, locked_page,
1231 EXTENT_CLEAR_UNLOCK_PAGE |
1232 EXTENT_CLEAR_UNLOCK |
1233 EXTENT_CLEAR_DELALLOC |
1234 EXTENT_CLEAR_DIRTY |
1235 EXTENT_SET_WRITEBACK |
1236 EXTENT_END_WRITEBACK);
1237 btrfs_free_path(path);
1238 return PTR_ERR(trans);
1241 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1243 cow_start = (u64)-1;
1246 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1249 btrfs_abort_transaction(trans, root, ret);
1252 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1253 leaf = path->nodes[0];
1254 btrfs_item_key_to_cpu(leaf, &found_key,
1255 path->slots[0] - 1);
1256 if (found_key.objectid == ino &&
1257 found_key.type == BTRFS_EXTENT_DATA_KEY)
1262 leaf = path->nodes[0];
1263 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1264 ret = btrfs_next_leaf(root, path);
1266 btrfs_abort_transaction(trans, root, ret);
1271 leaf = path->nodes[0];
1277 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1279 if (found_key.objectid > ino ||
1280 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1281 found_key.offset > end)
1284 if (found_key.offset > cur_offset) {
1285 extent_end = found_key.offset;
1290 fi = btrfs_item_ptr(leaf, path->slots[0],
1291 struct btrfs_file_extent_item);
1292 extent_type = btrfs_file_extent_type(leaf, fi);
1294 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1295 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1296 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1297 extent_offset = btrfs_file_extent_offset(leaf, fi);
1298 extent_end = found_key.offset +
1299 btrfs_file_extent_num_bytes(leaf, fi);
1301 btrfs_file_extent_disk_num_bytes(leaf, fi);
1302 if (extent_end <= start) {
1306 if (disk_bytenr == 0)
1308 if (btrfs_file_extent_compression(leaf, fi) ||
1309 btrfs_file_extent_encryption(leaf, fi) ||
1310 btrfs_file_extent_other_encoding(leaf, fi))
1312 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1314 if (btrfs_extent_readonly(root, disk_bytenr))
1316 if (btrfs_cross_ref_exist(trans, root, ino,
1318 extent_offset, disk_bytenr))
1320 disk_bytenr += extent_offset;
1321 disk_bytenr += cur_offset - found_key.offset;
1322 num_bytes = min(end + 1, extent_end) - cur_offset;
1324 * force cow if csum exists in the range.
1325 * this ensure that csum for a given extent are
1326 * either valid or do not exist.
1328 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1331 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1332 extent_end = found_key.offset +
1333 btrfs_file_extent_inline_len(leaf, fi);
1334 extent_end = ALIGN(extent_end, root->sectorsize);
1339 if (extent_end <= start) {
1344 if (cow_start == (u64)-1)
1345 cow_start = cur_offset;
1346 cur_offset = extent_end;
1347 if (cur_offset > end)
1353 btrfs_release_path(path);
1354 if (cow_start != (u64)-1) {
1355 ret = __cow_file_range(trans, inode, root, locked_page,
1356 cow_start, found_key.offset - 1,
1357 page_started, nr_written, 1);
1359 btrfs_abort_transaction(trans, root, ret);
1362 cow_start = (u64)-1;
1365 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1366 struct extent_map *em;
1367 struct extent_map_tree *em_tree;
1368 em_tree = &BTRFS_I(inode)->extent_tree;
1369 em = alloc_extent_map();
1370 BUG_ON(!em); /* -ENOMEM */
1371 em->start = cur_offset;
1372 em->orig_start = found_key.offset - extent_offset;
1373 em->len = num_bytes;
1374 em->block_len = num_bytes;
1375 em->block_start = disk_bytenr;
1376 em->orig_block_len = disk_num_bytes;
1377 em->bdev = root->fs_info->fs_devices->latest_bdev;
1378 em->mod_start = em->start;
1379 em->mod_len = em->len;
1380 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1381 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1382 em->generation = -1;
1384 write_lock(&em_tree->lock);
1385 ret = add_extent_mapping(em_tree, em);
1387 list_move(&em->list,
1388 &em_tree->modified_extents);
1389 write_unlock(&em_tree->lock);
1390 if (ret != -EEXIST) {
1391 free_extent_map(em);
1394 btrfs_drop_extent_cache(inode, em->start,
1395 em->start + em->len - 1, 0);
1397 type = BTRFS_ORDERED_PREALLOC;
1399 type = BTRFS_ORDERED_NOCOW;
1402 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1403 num_bytes, num_bytes, type);
1404 BUG_ON(ret); /* -ENOMEM */
1406 if (root->root_key.objectid ==
1407 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1408 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1411 btrfs_abort_transaction(trans, root, ret);
1416 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1417 cur_offset, cur_offset + num_bytes - 1,
1418 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1419 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1420 EXTENT_SET_PRIVATE2);
1421 cur_offset = extent_end;
1422 if (cur_offset > end)
1425 btrfs_release_path(path);
1427 if (cur_offset <= end && cow_start == (u64)-1) {
1428 cow_start = cur_offset;
1432 if (cow_start != (u64)-1) {
1433 ret = __cow_file_range(trans, inode, root, locked_page,
1435 page_started, nr_written, 1);
1437 btrfs_abort_transaction(trans, root, ret);
1443 err = btrfs_end_transaction(trans, root);
1447 if (ret && cur_offset < end)
1448 extent_clear_unlock_delalloc(inode,
1449 &BTRFS_I(inode)->io_tree,
1450 cur_offset, end, locked_page,
1451 EXTENT_CLEAR_UNLOCK_PAGE |
1452 EXTENT_CLEAR_UNLOCK |
1453 EXTENT_CLEAR_DELALLOC |
1454 EXTENT_CLEAR_DIRTY |
1455 EXTENT_SET_WRITEBACK |
1456 EXTENT_END_WRITEBACK);
1458 btrfs_free_path(path);
1463 * extent_io.c call back to do delayed allocation processing
1465 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1466 u64 start, u64 end, int *page_started,
1467 unsigned long *nr_written)
1470 struct btrfs_root *root = BTRFS_I(inode)->root;
1472 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1473 ret = run_delalloc_nocow(inode, locked_page, start, end,
1474 page_started, 1, nr_written);
1475 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1476 ret = run_delalloc_nocow(inode, locked_page, start, end,
1477 page_started, 0, nr_written);
1478 } else if (!btrfs_test_opt(root, COMPRESS) &&
1479 !(BTRFS_I(inode)->force_compress) &&
1480 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1481 ret = cow_file_range(inode, locked_page, start, end,
1482 page_started, nr_written, 1);
1484 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1485 &BTRFS_I(inode)->runtime_flags);
1486 ret = cow_file_range_async(inode, locked_page, start, end,
1487 page_started, nr_written);
1492 static void btrfs_split_extent_hook(struct inode *inode,
1493 struct extent_state *orig, u64 split)
1495 /* not delalloc, ignore it */
1496 if (!(orig->state & EXTENT_DELALLOC))
1499 spin_lock(&BTRFS_I(inode)->lock);
1500 BTRFS_I(inode)->outstanding_extents++;
1501 spin_unlock(&BTRFS_I(inode)->lock);
1505 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1506 * extents so we can keep track of new extents that are just merged onto old
1507 * extents, such as when we are doing sequential writes, so we can properly
1508 * account for the metadata space we'll need.
1510 static void btrfs_merge_extent_hook(struct inode *inode,
1511 struct extent_state *new,
1512 struct extent_state *other)
1514 /* not delalloc, ignore it */
1515 if (!(other->state & EXTENT_DELALLOC))
1518 spin_lock(&BTRFS_I(inode)->lock);
1519 BTRFS_I(inode)->outstanding_extents--;
1520 spin_unlock(&BTRFS_I(inode)->lock);
1524 * extent_io.c set_bit_hook, used to track delayed allocation
1525 * bytes in this file, and to maintain the list of inodes that
1526 * have pending delalloc work to be done.
1528 static void btrfs_set_bit_hook(struct inode *inode,
1529 struct extent_state *state, int *bits)
1533 * set_bit and clear bit hooks normally require _irqsave/restore
1534 * but in this case, we are only testing for the DELALLOC
1535 * bit, which is only set or cleared with irqs on
1537 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1538 struct btrfs_root *root = BTRFS_I(inode)->root;
1539 u64 len = state->end + 1 - state->start;
1540 bool do_list = !btrfs_is_free_space_inode(inode);
1542 if (*bits & EXTENT_FIRST_DELALLOC) {
1543 *bits &= ~EXTENT_FIRST_DELALLOC;
1545 spin_lock(&BTRFS_I(inode)->lock);
1546 BTRFS_I(inode)->outstanding_extents++;
1547 spin_unlock(&BTRFS_I(inode)->lock);
1550 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1551 root->fs_info->delalloc_batch);
1552 spin_lock(&BTRFS_I(inode)->lock);
1553 BTRFS_I(inode)->delalloc_bytes += len;
1554 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1555 &BTRFS_I(inode)->runtime_flags)) {
1556 spin_lock(&root->fs_info->delalloc_lock);
1557 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1558 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1559 &root->fs_info->delalloc_inodes);
1560 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1561 &BTRFS_I(inode)->runtime_flags);
1563 spin_unlock(&root->fs_info->delalloc_lock);
1565 spin_unlock(&BTRFS_I(inode)->lock);
1570 * extent_io.c clear_bit_hook, see set_bit_hook for why
1572 static void btrfs_clear_bit_hook(struct inode *inode,
1573 struct extent_state *state, int *bits)
1576 * set_bit and clear bit hooks normally require _irqsave/restore
1577 * but in this case, we are only testing for the DELALLOC
1578 * bit, which is only set or cleared with irqs on
1580 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1581 struct btrfs_root *root = BTRFS_I(inode)->root;
1582 u64 len = state->end + 1 - state->start;
1583 bool do_list = !btrfs_is_free_space_inode(inode);
1585 if (*bits & EXTENT_FIRST_DELALLOC) {
1586 *bits &= ~EXTENT_FIRST_DELALLOC;
1587 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1588 spin_lock(&BTRFS_I(inode)->lock);
1589 BTRFS_I(inode)->outstanding_extents--;
1590 spin_unlock(&BTRFS_I(inode)->lock);
1593 if (*bits & EXTENT_DO_ACCOUNTING)
1594 btrfs_delalloc_release_metadata(inode, len);
1596 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1598 btrfs_free_reserved_data_space(inode, len);
1600 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1601 root->fs_info->delalloc_batch);
1602 spin_lock(&BTRFS_I(inode)->lock);
1603 BTRFS_I(inode)->delalloc_bytes -= len;
1604 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1605 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1606 &BTRFS_I(inode)->runtime_flags)) {
1607 spin_lock(&root->fs_info->delalloc_lock);
1608 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1609 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1610 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1611 &BTRFS_I(inode)->runtime_flags);
1613 spin_unlock(&root->fs_info->delalloc_lock);
1615 spin_unlock(&BTRFS_I(inode)->lock);
1620 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1621 * we don't create bios that span stripes or chunks
1623 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1624 size_t size, struct bio *bio,
1625 unsigned long bio_flags)
1627 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1628 u64 logical = (u64)bio->bi_sector << 9;
1633 if (bio_flags & EXTENT_BIO_COMPRESSED)
1636 length = bio->bi_size;
1637 map_length = length;
1638 ret = btrfs_map_block(root->fs_info, rw, logical,
1639 &map_length, NULL, 0);
1640 /* Will always return 0 with map_multi == NULL */
1642 if (map_length < length + size)
1648 * in order to insert checksums into the metadata in large chunks,
1649 * we wait until bio submission time. All the pages in the bio are
1650 * checksummed and sums are attached onto the ordered extent record.
1652 * At IO completion time the cums attached on the ordered extent record
1653 * are inserted into the btree
1655 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1656 struct bio *bio, int mirror_num,
1657 unsigned long bio_flags,
1660 struct btrfs_root *root = BTRFS_I(inode)->root;
1663 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1664 BUG_ON(ret); /* -ENOMEM */
1669 * in order to insert checksums into the metadata in large chunks,
1670 * we wait until bio submission time. All the pages in the bio are
1671 * checksummed and sums are attached onto the ordered extent record.
1673 * At IO completion time the cums attached on the ordered extent record
1674 * are inserted into the btree
1676 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1677 int mirror_num, unsigned long bio_flags,
1680 struct btrfs_root *root = BTRFS_I(inode)->root;
1683 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1685 bio_endio(bio, ret);
1690 * extent_io.c submission hook. This does the right thing for csum calculation
1691 * on write, or reading the csums from the tree before a read
1693 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1694 int mirror_num, unsigned long bio_flags,
1697 struct btrfs_root *root = BTRFS_I(inode)->root;
1701 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1703 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1705 if (btrfs_is_free_space_inode(inode))
1708 if (!(rw & REQ_WRITE)) {
1709 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1713 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1714 ret = btrfs_submit_compressed_read(inode, bio,
1718 } else if (!skip_sum) {
1719 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1724 } else if (async && !skip_sum) {
1725 /* csum items have already been cloned */
1726 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1728 /* we're doing a write, do the async checksumming */
1729 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1730 inode, rw, bio, mirror_num,
1731 bio_flags, bio_offset,
1732 __btrfs_submit_bio_start,
1733 __btrfs_submit_bio_done);
1735 } else if (!skip_sum) {
1736 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1742 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1746 bio_endio(bio, ret);
1751 * given a list of ordered sums record them in the inode. This happens
1752 * at IO completion time based on sums calculated at bio submission time.
1754 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1755 struct inode *inode, u64 file_offset,
1756 struct list_head *list)
1758 struct btrfs_ordered_sum *sum;
1760 list_for_each_entry(sum, list, list) {
1761 trans->adding_csums = 1;
1762 btrfs_csum_file_blocks(trans,
1763 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1764 trans->adding_csums = 0;
1769 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1770 struct extent_state **cached_state)
1772 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1773 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1774 cached_state, GFP_NOFS);
1777 /* see btrfs_writepage_start_hook for details on why this is required */
1778 struct btrfs_writepage_fixup {
1780 struct btrfs_work work;
1783 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1785 struct btrfs_writepage_fixup *fixup;
1786 struct btrfs_ordered_extent *ordered;
1787 struct extent_state *cached_state = NULL;
1789 struct inode *inode;
1794 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1798 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1799 ClearPageChecked(page);
1803 inode = page->mapping->host;
1804 page_start = page_offset(page);
1805 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1807 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1810 /* already ordered? We're done */
1811 if (PagePrivate2(page))
1814 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1816 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1817 page_end, &cached_state, GFP_NOFS);
1819 btrfs_start_ordered_extent(inode, ordered, 1);
1820 btrfs_put_ordered_extent(ordered);
1824 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1826 mapping_set_error(page->mapping, ret);
1827 end_extent_writepage(page, ret, page_start, page_end);
1828 ClearPageChecked(page);
1832 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1833 ClearPageChecked(page);
1834 set_page_dirty(page);
1836 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1837 &cached_state, GFP_NOFS);
1840 page_cache_release(page);
1845 * There are a few paths in the higher layers of the kernel that directly
1846 * set the page dirty bit without asking the filesystem if it is a
1847 * good idea. This causes problems because we want to make sure COW
1848 * properly happens and the data=ordered rules are followed.
1850 * In our case any range that doesn't have the ORDERED bit set
1851 * hasn't been properly setup for IO. We kick off an async process
1852 * to fix it up. The async helper will wait for ordered extents, set
1853 * the delalloc bit and make it safe to write the page.
1855 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1857 struct inode *inode = page->mapping->host;
1858 struct btrfs_writepage_fixup *fixup;
1859 struct btrfs_root *root = BTRFS_I(inode)->root;
1861 /* this page is properly in the ordered list */
1862 if (TestClearPagePrivate2(page))
1865 if (PageChecked(page))
1868 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1872 SetPageChecked(page);
1873 page_cache_get(page);
1874 fixup->work.func = btrfs_writepage_fixup_worker;
1876 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1880 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1881 struct inode *inode, u64 file_pos,
1882 u64 disk_bytenr, u64 disk_num_bytes,
1883 u64 num_bytes, u64 ram_bytes,
1884 u8 compression, u8 encryption,
1885 u16 other_encoding, int extent_type)
1887 struct btrfs_root *root = BTRFS_I(inode)->root;
1888 struct btrfs_file_extent_item *fi;
1889 struct btrfs_path *path;
1890 struct extent_buffer *leaf;
1891 struct btrfs_key ins;
1894 path = btrfs_alloc_path();
1898 path->leave_spinning = 1;
1901 * we may be replacing one extent in the tree with another.
1902 * The new extent is pinned in the extent map, and we don't want
1903 * to drop it from the cache until it is completely in the btree.
1905 * So, tell btrfs_drop_extents to leave this extent in the cache.
1906 * the caller is expected to unpin it and allow it to be merged
1909 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1910 file_pos + num_bytes, 0);
1914 ins.objectid = btrfs_ino(inode);
1915 ins.offset = file_pos;
1916 ins.type = BTRFS_EXTENT_DATA_KEY;
1917 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1920 leaf = path->nodes[0];
1921 fi = btrfs_item_ptr(leaf, path->slots[0],
1922 struct btrfs_file_extent_item);
1923 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1924 btrfs_set_file_extent_type(leaf, fi, extent_type);
1925 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1926 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1927 btrfs_set_file_extent_offset(leaf, fi, 0);
1928 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1929 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1930 btrfs_set_file_extent_compression(leaf, fi, compression);
1931 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1932 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1934 btrfs_mark_buffer_dirty(leaf);
1935 btrfs_release_path(path);
1937 inode_add_bytes(inode, num_bytes);
1939 ins.objectid = disk_bytenr;
1940 ins.offset = disk_num_bytes;
1941 ins.type = BTRFS_EXTENT_ITEM_KEY;
1942 ret = btrfs_alloc_reserved_file_extent(trans, root,
1943 root->root_key.objectid,
1944 btrfs_ino(inode), file_pos, &ins);
1946 btrfs_free_path(path);
1951 /* snapshot-aware defrag */
1952 struct sa_defrag_extent_backref {
1953 struct rb_node node;
1954 struct old_sa_defrag_extent *old;
1963 struct old_sa_defrag_extent {
1964 struct list_head list;
1965 struct new_sa_defrag_extent *new;
1974 struct new_sa_defrag_extent {
1975 struct rb_root root;
1976 struct list_head head;
1977 struct btrfs_path *path;
1978 struct inode *inode;
1986 static int backref_comp(struct sa_defrag_extent_backref *b1,
1987 struct sa_defrag_extent_backref *b2)
1989 if (b1->root_id < b2->root_id)
1991 else if (b1->root_id > b2->root_id)
1994 if (b1->inum < b2->inum)
1996 else if (b1->inum > b2->inum)
1999 if (b1->file_pos < b2->file_pos)
2001 else if (b1->file_pos > b2->file_pos)
2005 * [------------------------------] ===> (a range of space)
2006 * |<--->| |<---->| =============> (fs/file tree A)
2007 * |<---------------------------->| ===> (fs/file tree B)
2009 * A range of space can refer to two file extents in one tree while
2010 * refer to only one file extent in another tree.
2012 * So we may process a disk offset more than one time(two extents in A)
2013 * and locate at the same extent(one extent in B), then insert two same
2014 * backrefs(both refer to the extent in B).
2019 static void backref_insert(struct rb_root *root,
2020 struct sa_defrag_extent_backref *backref)
2022 struct rb_node **p = &root->rb_node;
2023 struct rb_node *parent = NULL;
2024 struct sa_defrag_extent_backref *entry;
2029 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2031 ret = backref_comp(backref, entry);
2035 p = &(*p)->rb_right;
2038 rb_link_node(&backref->node, parent, p);
2039 rb_insert_color(&backref->node, root);
2043 * Note the backref might has changed, and in this case we just return 0.
2045 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2048 struct btrfs_file_extent_item *extent;
2049 struct btrfs_fs_info *fs_info;
2050 struct old_sa_defrag_extent *old = ctx;
2051 struct new_sa_defrag_extent *new = old->new;
2052 struct btrfs_path *path = new->path;
2053 struct btrfs_key key;
2054 struct btrfs_root *root;
2055 struct sa_defrag_extent_backref *backref;
2056 struct extent_buffer *leaf;
2057 struct inode *inode = new->inode;
2063 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2064 inum == btrfs_ino(inode))
2067 key.objectid = root_id;
2068 key.type = BTRFS_ROOT_ITEM_KEY;
2069 key.offset = (u64)-1;
2071 fs_info = BTRFS_I(inode)->root->fs_info;
2072 root = btrfs_read_fs_root_no_name(fs_info, &key);
2074 if (PTR_ERR(root) == -ENOENT)
2077 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2078 inum, offset, root_id);
2079 return PTR_ERR(root);
2082 key.objectid = inum;
2083 key.type = BTRFS_EXTENT_DATA_KEY;
2084 if (offset > (u64)-1 << 32)
2087 key.offset = offset;
2089 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2098 leaf = path->nodes[0];
2099 slot = path->slots[0];
2101 if (slot >= btrfs_header_nritems(leaf)) {
2102 ret = btrfs_next_leaf(root, path);
2105 } else if (ret > 0) {
2114 btrfs_item_key_to_cpu(leaf, &key, slot);
2116 if (key.objectid > inum)
2119 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2122 extent = btrfs_item_ptr(leaf, slot,
2123 struct btrfs_file_extent_item);
2125 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2128 extent_offset = btrfs_file_extent_offset(leaf, extent);
2129 if (key.offset - extent_offset != offset)
2132 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2133 if (extent_offset >= old->extent_offset + old->offset +
2134 old->len || extent_offset + num_bytes <=
2135 old->extent_offset + old->offset)
2141 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2147 backref->root_id = root_id;
2148 backref->inum = inum;
2149 backref->file_pos = offset + extent_offset;
2150 backref->num_bytes = num_bytes;
2151 backref->extent_offset = extent_offset;
2152 backref->generation = btrfs_file_extent_generation(leaf, extent);
2154 backref_insert(&new->root, backref);
2157 btrfs_release_path(path);
2162 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2163 struct new_sa_defrag_extent *new)
2165 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2166 struct old_sa_defrag_extent *old, *tmp;
2171 list_for_each_entry_safe(old, tmp, &new->head, list) {
2172 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2173 path, record_one_backref,
2175 BUG_ON(ret < 0 && ret != -ENOENT);
2177 /* no backref to be processed for this extent */
2179 list_del(&old->list);
2184 if (list_empty(&new->head))
2190 static int relink_is_mergable(struct extent_buffer *leaf,
2191 struct btrfs_file_extent_item *fi,
2194 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2197 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2200 if (btrfs_file_extent_compression(leaf, fi) ||
2201 btrfs_file_extent_encryption(leaf, fi) ||
2202 btrfs_file_extent_other_encoding(leaf, fi))
2209 * Note the backref might has changed, and in this case we just return 0.
2211 static noinline int relink_extent_backref(struct btrfs_path *path,
2212 struct sa_defrag_extent_backref *prev,
2213 struct sa_defrag_extent_backref *backref)
2215 struct btrfs_file_extent_item *extent;
2216 struct btrfs_file_extent_item *item;
2217 struct btrfs_ordered_extent *ordered;
2218 struct btrfs_trans_handle *trans;
2219 struct btrfs_fs_info *fs_info;
2220 struct btrfs_root *root;
2221 struct btrfs_key key;
2222 struct extent_buffer *leaf;
2223 struct old_sa_defrag_extent *old = backref->old;
2224 struct new_sa_defrag_extent *new = old->new;
2225 struct inode *src_inode = new->inode;
2226 struct inode *inode;
2227 struct extent_state *cached = NULL;
2236 if (prev && prev->root_id == backref->root_id &&
2237 prev->inum == backref->inum &&
2238 prev->file_pos + prev->num_bytes == backref->file_pos)
2241 /* step 1: get root */
2242 key.objectid = backref->root_id;
2243 key.type = BTRFS_ROOT_ITEM_KEY;
2244 key.offset = (u64)-1;
2246 fs_info = BTRFS_I(src_inode)->root->fs_info;
2247 index = srcu_read_lock(&fs_info->subvol_srcu);
2249 root = btrfs_read_fs_root_no_name(fs_info, &key);
2251 srcu_read_unlock(&fs_info->subvol_srcu, index);
2252 if (PTR_ERR(root) == -ENOENT)
2254 return PTR_ERR(root);
2256 if (btrfs_root_refs(&root->root_item) == 0) {
2257 srcu_read_unlock(&fs_info->subvol_srcu, index);
2258 /* parse ENOENT to 0 */
2262 /* step 2: get inode */
2263 key.objectid = backref->inum;
2264 key.type = BTRFS_INODE_ITEM_KEY;
2267 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2268 if (IS_ERR(inode)) {
2269 srcu_read_unlock(&fs_info->subvol_srcu, index);
2273 srcu_read_unlock(&fs_info->subvol_srcu, index);
2275 /* step 3: relink backref */
2276 lock_start = backref->file_pos;
2277 lock_end = backref->file_pos + backref->num_bytes - 1;
2278 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2281 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2283 btrfs_put_ordered_extent(ordered);
2287 trans = btrfs_join_transaction(root);
2288 if (IS_ERR(trans)) {
2289 ret = PTR_ERR(trans);
2293 key.objectid = backref->inum;
2294 key.type = BTRFS_EXTENT_DATA_KEY;
2295 key.offset = backref->file_pos;
2297 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2300 } else if (ret > 0) {
2305 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2306 struct btrfs_file_extent_item);
2308 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2309 backref->generation)
2312 btrfs_release_path(path);
2314 start = backref->file_pos;
2315 if (backref->extent_offset < old->extent_offset + old->offset)
2316 start += old->extent_offset + old->offset -
2317 backref->extent_offset;
2319 len = min(backref->extent_offset + backref->num_bytes,
2320 old->extent_offset + old->offset + old->len);
2321 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2323 ret = btrfs_drop_extents(trans, root, inode, start,
2328 key.objectid = btrfs_ino(inode);
2329 key.type = BTRFS_EXTENT_DATA_KEY;
2332 path->leave_spinning = 1;
2334 struct btrfs_file_extent_item *fi;
2336 struct btrfs_key found_key;
2338 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2343 leaf = path->nodes[0];
2344 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2346 fi = btrfs_item_ptr(leaf, path->slots[0],
2347 struct btrfs_file_extent_item);
2348 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2350 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2351 extent_len + found_key.offset == start) {
2352 btrfs_set_file_extent_num_bytes(leaf, fi,
2354 btrfs_mark_buffer_dirty(leaf);
2355 inode_add_bytes(inode, len);
2361 btrfs_release_path(path);
2366 ret = btrfs_insert_empty_item(trans, root, path, &key,
2369 btrfs_abort_transaction(trans, root, ret);
2373 leaf = path->nodes[0];
2374 item = btrfs_item_ptr(leaf, path->slots[0],
2375 struct btrfs_file_extent_item);
2376 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2377 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2378 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2379 btrfs_set_file_extent_num_bytes(leaf, item, len);
2380 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2381 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2382 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2383 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2384 btrfs_set_file_extent_encryption(leaf, item, 0);
2385 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2387 btrfs_mark_buffer_dirty(leaf);
2388 inode_add_bytes(inode, len);
2389 btrfs_release_path(path);
2391 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2393 backref->root_id, backref->inum,
2394 new->file_pos, 0); /* start - extent_offset */
2396 btrfs_abort_transaction(trans, root, ret);
2402 btrfs_release_path(path);
2403 path->leave_spinning = 0;
2404 btrfs_end_transaction(trans, root);
2406 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2412 static void relink_file_extents(struct new_sa_defrag_extent *new)
2414 struct btrfs_path *path;
2415 struct old_sa_defrag_extent *old, *tmp;
2416 struct sa_defrag_extent_backref *backref;
2417 struct sa_defrag_extent_backref *prev = NULL;
2418 struct inode *inode;
2419 struct btrfs_root *root;
2420 struct rb_node *node;
2424 root = BTRFS_I(inode)->root;
2426 path = btrfs_alloc_path();
2430 if (!record_extent_backrefs(path, new)) {
2431 btrfs_free_path(path);
2434 btrfs_release_path(path);
2437 node = rb_first(&new->root);
2440 rb_erase(node, &new->root);
2442 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2444 ret = relink_extent_backref(path, prev, backref);
2457 btrfs_free_path(path);
2459 list_for_each_entry_safe(old, tmp, &new->head, list) {
2460 list_del(&old->list);
2464 atomic_dec(&root->fs_info->defrag_running);
2465 wake_up(&root->fs_info->transaction_wait);
2470 static struct new_sa_defrag_extent *
2471 record_old_file_extents(struct inode *inode,
2472 struct btrfs_ordered_extent *ordered)
2474 struct btrfs_root *root = BTRFS_I(inode)->root;
2475 struct btrfs_path *path;
2476 struct btrfs_key key;
2477 struct old_sa_defrag_extent *old, *tmp;
2478 struct new_sa_defrag_extent *new;
2481 new = kmalloc(sizeof(*new), GFP_NOFS);
2486 new->file_pos = ordered->file_offset;
2487 new->len = ordered->len;
2488 new->bytenr = ordered->start;
2489 new->disk_len = ordered->disk_len;
2490 new->compress_type = ordered->compress_type;
2491 new->root = RB_ROOT;
2492 INIT_LIST_HEAD(&new->head);
2494 path = btrfs_alloc_path();
2498 key.objectid = btrfs_ino(inode);
2499 key.type = BTRFS_EXTENT_DATA_KEY;
2500 key.offset = new->file_pos;
2502 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2505 if (ret > 0 && path->slots[0] > 0)
2508 /* find out all the old extents for the file range */
2510 struct btrfs_file_extent_item *extent;
2511 struct extent_buffer *l;
2520 slot = path->slots[0];
2522 if (slot >= btrfs_header_nritems(l)) {
2523 ret = btrfs_next_leaf(root, path);
2531 btrfs_item_key_to_cpu(l, &key, slot);
2533 if (key.objectid != btrfs_ino(inode))
2535 if (key.type != BTRFS_EXTENT_DATA_KEY)
2537 if (key.offset >= new->file_pos + new->len)
2540 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2542 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2543 if (key.offset + num_bytes < new->file_pos)
2546 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2550 extent_offset = btrfs_file_extent_offset(l, extent);
2552 old = kmalloc(sizeof(*old), GFP_NOFS);
2556 offset = max(new->file_pos, key.offset);
2557 end = min(new->file_pos + new->len, key.offset + num_bytes);
2559 old->bytenr = disk_bytenr;
2560 old->extent_offset = extent_offset;
2561 old->offset = offset - key.offset;
2562 old->len = end - offset;
2565 list_add_tail(&old->list, &new->head);
2571 btrfs_free_path(path);
2572 atomic_inc(&root->fs_info->defrag_running);
2577 list_for_each_entry_safe(old, tmp, &new->head, list) {
2578 list_del(&old->list);
2582 btrfs_free_path(path);
2589 * helper function for btrfs_finish_ordered_io, this
2590 * just reads in some of the csum leaves to prime them into ram
2591 * before we start the transaction. It limits the amount of btree
2592 * reads required while inside the transaction.
2594 /* as ordered data IO finishes, this gets called so we can finish
2595 * an ordered extent if the range of bytes in the file it covers are
2598 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2600 struct inode *inode = ordered_extent->inode;
2601 struct btrfs_root *root = BTRFS_I(inode)->root;
2602 struct btrfs_trans_handle *trans = NULL;
2603 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2604 struct extent_state *cached_state = NULL;
2605 struct new_sa_defrag_extent *new = NULL;
2606 int compress_type = 0;
2610 nolock = btrfs_is_free_space_inode(inode);
2612 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2617 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2618 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2619 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2621 trans = btrfs_join_transaction_nolock(root);
2623 trans = btrfs_join_transaction(root);
2624 if (IS_ERR(trans)) {
2625 ret = PTR_ERR(trans);
2629 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2630 ret = btrfs_update_inode_fallback(trans, root, inode);
2631 if (ret) /* -ENOMEM or corruption */
2632 btrfs_abort_transaction(trans, root, ret);
2636 lock_extent_bits(io_tree, ordered_extent->file_offset,
2637 ordered_extent->file_offset + ordered_extent->len - 1,
2640 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2641 ordered_extent->file_offset + ordered_extent->len - 1,
2642 EXTENT_DEFRAG, 1, cached_state);
2644 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2645 if (last_snapshot >= BTRFS_I(inode)->generation)
2646 /* the inode is shared */
2647 new = record_old_file_extents(inode, ordered_extent);
2649 clear_extent_bit(io_tree, ordered_extent->file_offset,
2650 ordered_extent->file_offset + ordered_extent->len - 1,
2651 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2655 trans = btrfs_join_transaction_nolock(root);
2657 trans = btrfs_join_transaction(root);
2658 if (IS_ERR(trans)) {
2659 ret = PTR_ERR(trans);
2663 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2665 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2666 compress_type = ordered_extent->compress_type;
2667 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2668 BUG_ON(compress_type);
2669 ret = btrfs_mark_extent_written(trans, inode,
2670 ordered_extent->file_offset,
2671 ordered_extent->file_offset +
2672 ordered_extent->len);
2674 BUG_ON(root == root->fs_info->tree_root);
2675 ret = insert_reserved_file_extent(trans, inode,
2676 ordered_extent->file_offset,
2677 ordered_extent->start,
2678 ordered_extent->disk_len,
2679 ordered_extent->len,
2680 ordered_extent->len,
2681 compress_type, 0, 0,
2682 BTRFS_FILE_EXTENT_REG);
2684 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2685 ordered_extent->file_offset, ordered_extent->len,
2688 btrfs_abort_transaction(trans, root, ret);
2692 add_pending_csums(trans, inode, ordered_extent->file_offset,
2693 &ordered_extent->list);
2695 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2696 ret = btrfs_update_inode_fallback(trans, root, inode);
2697 if (ret) { /* -ENOMEM or corruption */
2698 btrfs_abort_transaction(trans, root, ret);
2703 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2704 ordered_extent->file_offset +
2705 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2707 if (root != root->fs_info->tree_root)
2708 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2710 btrfs_end_transaction(trans, root);
2713 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2714 ordered_extent->file_offset +
2715 ordered_extent->len - 1, NULL, GFP_NOFS);
2718 * If the ordered extent had an IOERR or something else went
2719 * wrong we need to return the space for this ordered extent
2720 * back to the allocator.
2722 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2723 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2724 btrfs_free_reserved_extent(root, ordered_extent->start,
2725 ordered_extent->disk_len);
2730 * This needs to be done to make sure anybody waiting knows we are done
2731 * updating everything for this ordered extent.
2733 btrfs_remove_ordered_extent(inode, ordered_extent);
2735 /* for snapshot-aware defrag */
2737 relink_file_extents(new);
2740 btrfs_put_ordered_extent(ordered_extent);
2741 /* once for the tree */
2742 btrfs_put_ordered_extent(ordered_extent);
2747 static void finish_ordered_fn(struct btrfs_work *work)
2749 struct btrfs_ordered_extent *ordered_extent;
2750 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2751 btrfs_finish_ordered_io(ordered_extent);
2754 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2755 struct extent_state *state, int uptodate)
2757 struct inode *inode = page->mapping->host;
2758 struct btrfs_root *root = BTRFS_I(inode)->root;
2759 struct btrfs_ordered_extent *ordered_extent = NULL;
2760 struct btrfs_workers *workers;
2762 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2764 ClearPagePrivate2(page);
2765 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2766 end - start + 1, uptodate))
2769 ordered_extent->work.func = finish_ordered_fn;
2770 ordered_extent->work.flags = 0;
2772 if (btrfs_is_free_space_inode(inode))
2773 workers = &root->fs_info->endio_freespace_worker;
2775 workers = &root->fs_info->endio_write_workers;
2776 btrfs_queue_worker(workers, &ordered_extent->work);
2782 * when reads are done, we need to check csums to verify the data is correct
2783 * if there's a match, we allow the bio to finish. If not, the code in
2784 * extent_io.c will try to find good copies for us.
2786 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2787 struct extent_state *state, int mirror)
2789 size_t offset = start - page_offset(page);
2790 struct inode *inode = page->mapping->host;
2791 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2793 u64 private = ~(u32)0;
2795 struct btrfs_root *root = BTRFS_I(inode)->root;
2798 if (PageChecked(page)) {
2799 ClearPageChecked(page);
2803 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2806 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2807 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2808 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2813 if (state && state->start == start) {
2814 private = state->private;
2817 ret = get_state_private(io_tree, start, &private);
2819 kaddr = kmap_atomic(page);
2823 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2824 btrfs_csum_final(csum, (char *)&csum);
2825 if (csum != private)
2828 kunmap_atomic(kaddr);
2833 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2835 (unsigned long long)btrfs_ino(page->mapping->host),
2836 (unsigned long long)start, csum,
2837 (unsigned long long)private);
2838 memset(kaddr + offset, 1, end - start + 1);
2839 flush_dcache_page(page);
2840 kunmap_atomic(kaddr);
2846 struct delayed_iput {
2847 struct list_head list;
2848 struct inode *inode;
2851 /* JDM: If this is fs-wide, why can't we add a pointer to
2852 * btrfs_inode instead and avoid the allocation? */
2853 void btrfs_add_delayed_iput(struct inode *inode)
2855 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2856 struct delayed_iput *delayed;
2858 if (atomic_add_unless(&inode->i_count, -1, 1))
2861 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2862 delayed->inode = inode;
2864 spin_lock(&fs_info->delayed_iput_lock);
2865 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2866 spin_unlock(&fs_info->delayed_iput_lock);
2869 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2872 struct btrfs_fs_info *fs_info = root->fs_info;
2873 struct delayed_iput *delayed;
2876 spin_lock(&fs_info->delayed_iput_lock);
2877 empty = list_empty(&fs_info->delayed_iputs);
2878 spin_unlock(&fs_info->delayed_iput_lock);
2882 spin_lock(&fs_info->delayed_iput_lock);
2883 list_splice_init(&fs_info->delayed_iputs, &list);
2884 spin_unlock(&fs_info->delayed_iput_lock);
2886 while (!list_empty(&list)) {
2887 delayed = list_entry(list.next, struct delayed_iput, list);
2888 list_del(&delayed->list);
2889 iput(delayed->inode);
2895 * This is called in transaction commit time. If there are no orphan
2896 * files in the subvolume, it removes orphan item and frees block_rsv
2899 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2900 struct btrfs_root *root)
2902 struct btrfs_block_rsv *block_rsv;
2905 if (atomic_read(&root->orphan_inodes) ||
2906 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2909 spin_lock(&root->orphan_lock);
2910 if (atomic_read(&root->orphan_inodes)) {
2911 spin_unlock(&root->orphan_lock);
2915 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2916 spin_unlock(&root->orphan_lock);
2920 block_rsv = root->orphan_block_rsv;
2921 root->orphan_block_rsv = NULL;
2922 spin_unlock(&root->orphan_lock);
2924 if (root->orphan_item_inserted &&
2925 btrfs_root_refs(&root->root_item) > 0) {
2926 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2927 root->root_key.objectid);
2929 root->orphan_item_inserted = 0;
2933 WARN_ON(block_rsv->size > 0);
2934 btrfs_free_block_rsv(root, block_rsv);
2939 * This creates an orphan entry for the given inode in case something goes
2940 * wrong in the middle of an unlink/truncate.
2942 * NOTE: caller of this function should reserve 5 units of metadata for
2945 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2947 struct btrfs_root *root = BTRFS_I(inode)->root;
2948 struct btrfs_block_rsv *block_rsv = NULL;
2953 if (!root->orphan_block_rsv) {
2954 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2959 spin_lock(&root->orphan_lock);
2960 if (!root->orphan_block_rsv) {
2961 root->orphan_block_rsv = block_rsv;
2962 } else if (block_rsv) {
2963 btrfs_free_block_rsv(root, block_rsv);
2967 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2968 &BTRFS_I(inode)->runtime_flags)) {
2971 * For proper ENOSPC handling, we should do orphan
2972 * cleanup when mounting. But this introduces backward
2973 * compatibility issue.
2975 if (!xchg(&root->orphan_item_inserted, 1))
2981 atomic_inc(&root->orphan_inodes);
2984 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2985 &BTRFS_I(inode)->runtime_flags))
2987 spin_unlock(&root->orphan_lock);
2989 /* grab metadata reservation from transaction handle */
2991 ret = btrfs_orphan_reserve_metadata(trans, inode);
2992 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2995 /* insert an orphan item to track this unlinked/truncated file */
2997 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2998 if (ret && ret != -EEXIST) {
2999 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3000 &BTRFS_I(inode)->runtime_flags);
3001 btrfs_abort_transaction(trans, root, ret);
3007 /* insert an orphan item to track subvolume contains orphan files */
3009 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3010 root->root_key.objectid);
3011 if (ret && ret != -EEXIST) {
3012 btrfs_abort_transaction(trans, root, ret);
3020 * We have done the truncate/delete so we can go ahead and remove the orphan
3021 * item for this particular inode.
3023 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
3025 struct btrfs_root *root = BTRFS_I(inode)->root;
3026 int delete_item = 0;
3027 int release_rsv = 0;
3030 spin_lock(&root->orphan_lock);
3031 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3032 &BTRFS_I(inode)->runtime_flags))
3035 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3036 &BTRFS_I(inode)->runtime_flags))
3038 spin_unlock(&root->orphan_lock);
3040 if (trans && delete_item) {
3041 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3042 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3046 btrfs_orphan_release_metadata(inode);
3047 atomic_dec(&root->orphan_inodes);
3054 * this cleans up any orphans that may be left on the list from the last use
3057 int btrfs_orphan_cleanup(struct btrfs_root *root)
3059 struct btrfs_path *path;
3060 struct extent_buffer *leaf;
3061 struct btrfs_key key, found_key;
3062 struct btrfs_trans_handle *trans;
3063 struct inode *inode;
3064 u64 last_objectid = 0;
3065 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3067 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3070 path = btrfs_alloc_path();
3077 key.objectid = BTRFS_ORPHAN_OBJECTID;
3078 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3079 key.offset = (u64)-1;
3082 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3087 * if ret == 0 means we found what we were searching for, which
3088 * is weird, but possible, so only screw with path if we didn't
3089 * find the key and see if we have stuff that matches
3093 if (path->slots[0] == 0)
3098 /* pull out the item */
3099 leaf = path->nodes[0];
3100 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3102 /* make sure the item matches what we want */
3103 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3105 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3108 /* release the path since we're done with it */
3109 btrfs_release_path(path);
3112 * this is where we are basically btrfs_lookup, without the
3113 * crossing root thing. we store the inode number in the
3114 * offset of the orphan item.
3117 if (found_key.offset == last_objectid) {
3118 printk(KERN_ERR "btrfs: Error removing orphan entry, "
3119 "stopping orphan cleanup\n");
3124 last_objectid = found_key.offset;
3126 found_key.objectid = found_key.offset;
3127 found_key.type = BTRFS_INODE_ITEM_KEY;
3128 found_key.offset = 0;
3129 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3130 ret = PTR_RET(inode);
3131 if (ret && ret != -ESTALE)
3134 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3135 struct btrfs_root *dead_root;
3136 struct btrfs_fs_info *fs_info = root->fs_info;
3137 int is_dead_root = 0;
3140 * this is an orphan in the tree root. Currently these
3141 * could come from 2 sources:
3142 * a) a snapshot deletion in progress
3143 * b) a free space cache inode
3144 * We need to distinguish those two, as the snapshot
3145 * orphan must not get deleted.
3146 * find_dead_roots already ran before us, so if this
3147 * is a snapshot deletion, we should find the root
3148 * in the dead_roots list
3150 spin_lock(&fs_info->trans_lock);
3151 list_for_each_entry(dead_root, &fs_info->dead_roots,
3153 if (dead_root->root_key.objectid ==
3154 found_key.objectid) {
3159 spin_unlock(&fs_info->trans_lock);
3161 /* prevent this orphan from being found again */
3162 key.offset = found_key.objectid - 1;
3167 * Inode is already gone but the orphan item is still there,
3168 * kill the orphan item.
3170 if (ret == -ESTALE) {
3171 trans = btrfs_start_transaction(root, 1);
3172 if (IS_ERR(trans)) {
3173 ret = PTR_ERR(trans);
3176 printk(KERN_ERR "auto deleting %Lu\n",
3177 found_key.objectid);
3178 ret = btrfs_del_orphan_item(trans, root,
3179 found_key.objectid);
3180 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3181 btrfs_end_transaction(trans, root);
3186 * add this inode to the orphan list so btrfs_orphan_del does
3187 * the proper thing when we hit it
3189 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3190 &BTRFS_I(inode)->runtime_flags);
3191 atomic_inc(&root->orphan_inodes);
3193 /* if we have links, this was a truncate, lets do that */
3194 if (inode->i_nlink) {
3195 if (!S_ISREG(inode->i_mode)) {
3202 /* 1 for the orphan item deletion. */
3203 trans = btrfs_start_transaction(root, 1);
3204 if (IS_ERR(trans)) {
3205 ret = PTR_ERR(trans);
3208 ret = btrfs_orphan_add(trans, inode);
3209 btrfs_end_transaction(trans, root);
3213 ret = btrfs_truncate(inode);
3215 btrfs_orphan_del(NULL, inode);
3220 /* this will do delete_inode and everything for us */
3225 /* release the path since we're done with it */
3226 btrfs_release_path(path);
3228 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3230 if (root->orphan_block_rsv)
3231 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3234 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3235 trans = btrfs_join_transaction(root);
3237 btrfs_end_transaction(trans, root);
3241 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
3243 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
3247 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
3248 btrfs_free_path(path);
3253 * very simple check to peek ahead in the leaf looking for xattrs. If we
3254 * don't find any xattrs, we know there can't be any acls.
3256 * slot is the slot the inode is in, objectid is the objectid of the inode
3258 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3259 int slot, u64 objectid)
3261 u32 nritems = btrfs_header_nritems(leaf);
3262 struct btrfs_key found_key;
3266 while (slot < nritems) {
3267 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3269 /* we found a different objectid, there must not be acls */
3270 if (found_key.objectid != objectid)
3273 /* we found an xattr, assume we've got an acl */
3274 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
3278 * we found a key greater than an xattr key, there can't
3279 * be any acls later on
3281 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3288 * it goes inode, inode backrefs, xattrs, extents,
3289 * so if there are a ton of hard links to an inode there can
3290 * be a lot of backrefs. Don't waste time searching too hard,
3291 * this is just an optimization
3296 /* we hit the end of the leaf before we found an xattr or
3297 * something larger than an xattr. We have to assume the inode
3304 * read an inode from the btree into the in-memory inode
3306 static void btrfs_read_locked_inode(struct inode *inode)
3308 struct btrfs_path *path;
3309 struct extent_buffer *leaf;
3310 struct btrfs_inode_item *inode_item;
3311 struct btrfs_timespec *tspec;
3312 struct btrfs_root *root = BTRFS_I(inode)->root;
3313 struct btrfs_key location;
3317 bool filled = false;
3319 ret = btrfs_fill_inode(inode, &rdev);
3323 path = btrfs_alloc_path();
3327 path->leave_spinning = 1;
3328 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3330 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3334 leaf = path->nodes[0];
3339 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3340 struct btrfs_inode_item);
3341 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3342 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3343 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3344 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3345 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3347 tspec = btrfs_inode_atime(inode_item);
3348 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3349 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3351 tspec = btrfs_inode_mtime(inode_item);
3352 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3353 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3355 tspec = btrfs_inode_ctime(inode_item);
3356 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3357 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3359 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3360 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3361 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3364 * If we were modified in the current generation and evicted from memory
3365 * and then re-read we need to do a full sync since we don't have any
3366 * idea about which extents were modified before we were evicted from
3369 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3370 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3371 &BTRFS_I(inode)->runtime_flags);
3373 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3374 inode->i_generation = BTRFS_I(inode)->generation;
3376 rdev = btrfs_inode_rdev(leaf, inode_item);
3378 BTRFS_I(inode)->index_cnt = (u64)-1;
3379 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3382 * try to precache a NULL acl entry for files that don't have
3383 * any xattrs or acls
3385 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3388 cache_no_acl(inode);
3390 btrfs_free_path(path);
3392 switch (inode->i_mode & S_IFMT) {
3394 inode->i_mapping->a_ops = &btrfs_aops;
3395 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3396 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3397 inode->i_fop = &btrfs_file_operations;
3398 inode->i_op = &btrfs_file_inode_operations;
3401 inode->i_fop = &btrfs_dir_file_operations;
3402 if (root == root->fs_info->tree_root)
3403 inode->i_op = &btrfs_dir_ro_inode_operations;
3405 inode->i_op = &btrfs_dir_inode_operations;
3408 inode->i_op = &btrfs_symlink_inode_operations;
3409 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3410 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3413 inode->i_op = &btrfs_special_inode_operations;
3414 init_special_inode(inode, inode->i_mode, rdev);
3418 btrfs_update_iflags(inode);
3422 btrfs_free_path(path);
3423 make_bad_inode(inode);
3427 * given a leaf and an inode, copy the inode fields into the leaf
3429 static void fill_inode_item(struct btrfs_trans_handle *trans,
3430 struct extent_buffer *leaf,
3431 struct btrfs_inode_item *item,
3432 struct inode *inode)
3434 struct btrfs_map_token token;
3436 btrfs_init_map_token(&token);
3438 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3439 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3440 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3442 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3443 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3445 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3446 inode->i_atime.tv_sec, &token);
3447 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3448 inode->i_atime.tv_nsec, &token);
3450 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3451 inode->i_mtime.tv_sec, &token);
3452 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3453 inode->i_mtime.tv_nsec, &token);
3455 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3456 inode->i_ctime.tv_sec, &token);
3457 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3458 inode->i_ctime.tv_nsec, &token);
3460 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3462 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3464 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3465 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3466 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3467 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3468 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3472 * copy everything in the in-memory inode into the btree.
3474 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3475 struct btrfs_root *root, struct inode *inode)
3477 struct btrfs_inode_item *inode_item;
3478 struct btrfs_path *path;
3479 struct extent_buffer *leaf;
3482 path = btrfs_alloc_path();
3486 path->leave_spinning = 1;
3487 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3495 btrfs_unlock_up_safe(path, 1);
3496 leaf = path->nodes[0];
3497 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3498 struct btrfs_inode_item);
3500 fill_inode_item(trans, leaf, inode_item, inode);
3501 btrfs_mark_buffer_dirty(leaf);
3502 btrfs_set_inode_last_trans(trans, inode);
3505 btrfs_free_path(path);
3510 * copy everything in the in-memory inode into the btree.
3512 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3513 struct btrfs_root *root, struct inode *inode)
3518 * If the inode is a free space inode, we can deadlock during commit
3519 * if we put it into the delayed code.
3521 * The data relocation inode should also be directly updated
3524 if (!btrfs_is_free_space_inode(inode)
3525 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3526 btrfs_update_root_times(trans, root);
3528 ret = btrfs_delayed_update_inode(trans, root, inode);
3530 btrfs_set_inode_last_trans(trans, inode);
3534 return btrfs_update_inode_item(trans, root, inode);
3537 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3538 struct btrfs_root *root,
3539 struct inode *inode)
3543 ret = btrfs_update_inode(trans, root, inode);
3545 return btrfs_update_inode_item(trans, root, inode);
3550 * unlink helper that gets used here in inode.c and in the tree logging
3551 * recovery code. It remove a link in a directory with a given name, and
3552 * also drops the back refs in the inode to the directory
3554 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3555 struct btrfs_root *root,
3556 struct inode *dir, struct inode *inode,
3557 const char *name, int name_len)
3559 struct btrfs_path *path;
3561 struct extent_buffer *leaf;
3562 struct btrfs_dir_item *di;
3563 struct btrfs_key key;
3565 u64 ino = btrfs_ino(inode);
3566 u64 dir_ino = btrfs_ino(dir);
3568 path = btrfs_alloc_path();
3574 path->leave_spinning = 1;
3575 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3576 name, name_len, -1);
3585 leaf = path->nodes[0];
3586 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3587 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3590 btrfs_release_path(path);
3592 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3595 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
3596 "inode %llu parent %llu\n", name_len, name,
3597 (unsigned long long)ino, (unsigned long long)dir_ino);
3598 btrfs_abort_transaction(trans, root, ret);
3602 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3604 btrfs_abort_transaction(trans, root, ret);
3608 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3610 if (ret != 0 && ret != -ENOENT) {
3611 btrfs_abort_transaction(trans, root, ret);
3615 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3620 btrfs_free_path(path);
3624 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3625 inode_inc_iversion(inode);
3626 inode_inc_iversion(dir);
3627 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3628 ret = btrfs_update_inode(trans, root, dir);
3633 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3634 struct btrfs_root *root,
3635 struct inode *dir, struct inode *inode,
3636 const char *name, int name_len)
3639 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3641 btrfs_drop_nlink(inode);
3642 ret = btrfs_update_inode(trans, root, inode);
3648 /* helper to check if there is any shared block in the path */
3649 static int check_path_shared(struct btrfs_root *root,
3650 struct btrfs_path *path)
3652 struct extent_buffer *eb;
3656 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3659 if (!path->nodes[level])
3661 eb = path->nodes[level];
3662 if (!btrfs_block_can_be_shared(root, eb))
3664 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
3673 * helper to start transaction for unlink and rmdir.
3675 * unlink and rmdir are special in btrfs, they do not always free space.
3676 * so in enospc case, we should make sure they will free space before
3677 * allowing them to use the global metadata reservation.
3679 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
3680 struct dentry *dentry)
3682 struct btrfs_trans_handle *trans;
3683 struct btrfs_root *root = BTRFS_I(dir)->root;
3684 struct btrfs_path *path;
3685 struct btrfs_dir_item *di;
3686 struct inode *inode = dentry->d_inode;
3691 u64 ino = btrfs_ino(inode);
3692 u64 dir_ino = btrfs_ino(dir);
3695 * 1 for the possible orphan item
3696 * 1 for the dir item
3697 * 1 for the dir index
3698 * 1 for the inode ref
3701 trans = btrfs_start_transaction(root, 5);
3702 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3705 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
3706 return ERR_PTR(-ENOSPC);
3708 /* check if there is someone else holds reference */
3709 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
3710 return ERR_PTR(-ENOSPC);
3712 if (atomic_read(&inode->i_count) > 2)
3713 return ERR_PTR(-ENOSPC);
3715 if (xchg(&root->fs_info->enospc_unlink, 1))
3716 return ERR_PTR(-ENOSPC);
3718 path = btrfs_alloc_path();
3720 root->fs_info->enospc_unlink = 0;
3721 return ERR_PTR(-ENOMEM);
3724 /* 1 for the orphan item */
3725 trans = btrfs_start_transaction(root, 1);
3726 if (IS_ERR(trans)) {
3727 btrfs_free_path(path);
3728 root->fs_info->enospc_unlink = 0;
3732 path->skip_locking = 1;
3733 path->search_commit_root = 1;
3735 ret = btrfs_lookup_inode(trans, root, path,
3736 &BTRFS_I(dir)->location, 0);
3742 if (check_path_shared(root, path))
3747 btrfs_release_path(path);
3749 ret = btrfs_lookup_inode(trans, root, path,
3750 &BTRFS_I(inode)->location, 0);
3756 if (check_path_shared(root, path))
3761 btrfs_release_path(path);
3763 if (ret == 0 && S_ISREG(inode->i_mode)) {
3764 ret = btrfs_lookup_file_extent(trans, root, path,
3770 BUG_ON(ret == 0); /* Corruption */
3771 if (check_path_shared(root, path))
3773 btrfs_release_path(path);
3781 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3782 dentry->d_name.name, dentry->d_name.len, 0);
3788 if (check_path_shared(root, path))
3794 btrfs_release_path(path);
3796 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3797 dentry->d_name.len, ino, dir_ino, 0,
3804 if (check_path_shared(root, path))
3807 btrfs_release_path(path);
3810 * This is a commit root search, if we can lookup inode item and other
3811 * relative items in the commit root, it means the transaction of
3812 * dir/file creation has been committed, and the dir index item that we
3813 * delay to insert has also been inserted into the commit root. So
3814 * we needn't worry about the delayed insertion of the dir index item
3817 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3818 dentry->d_name.name, dentry->d_name.len, 0);
3823 BUG_ON(ret == -ENOENT);
3824 if (check_path_shared(root, path))
3829 btrfs_free_path(path);
3830 /* Migrate the orphan reservation over */
3832 err = btrfs_block_rsv_migrate(trans->block_rsv,
3833 &root->fs_info->global_block_rsv,
3834 trans->bytes_reserved);
3837 btrfs_end_transaction(trans, root);
3838 root->fs_info->enospc_unlink = 0;
3839 return ERR_PTR(err);
3842 trans->block_rsv = &root->fs_info->global_block_rsv;
3846 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3847 struct btrfs_root *root)
3849 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3850 btrfs_block_rsv_release(root, trans->block_rsv,
3851 trans->bytes_reserved);
3852 trans->block_rsv = &root->fs_info->trans_block_rsv;
3853 BUG_ON(!root->fs_info->enospc_unlink);
3854 root->fs_info->enospc_unlink = 0;
3856 btrfs_end_transaction(trans, root);
3859 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3861 struct btrfs_root *root = BTRFS_I(dir)->root;
3862 struct btrfs_trans_handle *trans;
3863 struct inode *inode = dentry->d_inode;
3866 trans = __unlink_start_trans(dir, dentry);
3868 return PTR_ERR(trans);
3870 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3872 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3873 dentry->d_name.name, dentry->d_name.len);
3877 if (inode->i_nlink == 0) {
3878 ret = btrfs_orphan_add(trans, inode);
3884 __unlink_end_trans(trans, root);
3885 btrfs_btree_balance_dirty(root);
3889 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3890 struct btrfs_root *root,
3891 struct inode *dir, u64 objectid,
3892 const char *name, int name_len)
3894 struct btrfs_path *path;
3895 struct extent_buffer *leaf;
3896 struct btrfs_dir_item *di;
3897 struct btrfs_key key;
3900 u64 dir_ino = btrfs_ino(dir);
3902 path = btrfs_alloc_path();
3906 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3907 name, name_len, -1);
3908 if (IS_ERR_OR_NULL(di)) {
3916 leaf = path->nodes[0];
3917 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3918 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3919 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3921 btrfs_abort_transaction(trans, root, ret);
3924 btrfs_release_path(path);
3926 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3927 objectid, root->root_key.objectid,
3928 dir_ino, &index, name, name_len);
3930 if (ret != -ENOENT) {
3931 btrfs_abort_transaction(trans, root, ret);
3934 di = btrfs_search_dir_index_item(root, path, dir_ino,
3936 if (IS_ERR_OR_NULL(di)) {
3941 btrfs_abort_transaction(trans, root, ret);
3945 leaf = path->nodes[0];
3946 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3947 btrfs_release_path(path);
3950 btrfs_release_path(path);
3952 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3954 btrfs_abort_transaction(trans, root, ret);
3958 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3959 inode_inc_iversion(dir);
3960 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3961 ret = btrfs_update_inode_fallback(trans, root, dir);
3963 btrfs_abort_transaction(trans, root, ret);
3965 btrfs_free_path(path);
3969 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3971 struct inode *inode = dentry->d_inode;
3973 struct btrfs_root *root = BTRFS_I(dir)->root;
3974 struct btrfs_trans_handle *trans;
3976 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3978 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3981 trans = __unlink_start_trans(dir, dentry);
3983 return PTR_ERR(trans);
3985 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3986 err = btrfs_unlink_subvol(trans, root, dir,
3987 BTRFS_I(inode)->location.objectid,
3988 dentry->d_name.name,
3989 dentry->d_name.len);
3993 err = btrfs_orphan_add(trans, inode);
3997 /* now the directory is empty */
3998 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3999 dentry->d_name.name, dentry->d_name.len);
4001 btrfs_i_size_write(inode, 0);
4003 __unlink_end_trans(trans, root);
4004 btrfs_btree_balance_dirty(root);
4010 * this can truncate away extent items, csum items and directory items.
4011 * It starts at a high offset and removes keys until it can't find
4012 * any higher than new_size
4014 * csum items that cross the new i_size are truncated to the new size
4017 * min_type is the minimum key type to truncate down to. If set to 0, this
4018 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4020 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4021 struct btrfs_root *root,
4022 struct inode *inode,
4023 u64 new_size, u32 min_type)
4025 struct btrfs_path *path;
4026 struct extent_buffer *leaf;
4027 struct btrfs_file_extent_item *fi;
4028 struct btrfs_key key;
4029 struct btrfs_key found_key;
4030 u64 extent_start = 0;
4031 u64 extent_num_bytes = 0;
4032 u64 extent_offset = 0;
4034 u32 found_type = (u8)-1;
4037 int pending_del_nr = 0;
4038 int pending_del_slot = 0;
4039 int extent_type = -1;
4042 u64 ino = btrfs_ino(inode);
4044 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4046 path = btrfs_alloc_path();
4052 * We want to drop from the next block forward in case this new size is
4053 * not block aligned since we will be keeping the last block of the
4054 * extent just the way it is.
4056 if (root->ref_cows || root == root->fs_info->tree_root)
4057 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4058 root->sectorsize), (u64)-1, 0);
4061 * This function is also used to drop the items in the log tree before
4062 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4063 * it is used to drop the loged items. So we shouldn't kill the delayed
4066 if (min_type == 0 && root == BTRFS_I(inode)->root)
4067 btrfs_kill_delayed_inode_items(inode);
4070 key.offset = (u64)-1;
4074 path->leave_spinning = 1;
4075 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4082 /* there are no items in the tree for us to truncate, we're
4085 if (path->slots[0] == 0)
4092 leaf = path->nodes[0];
4093 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4094 found_type = btrfs_key_type(&found_key);
4096 if (found_key.objectid != ino)
4099 if (found_type < min_type)
4102 item_end = found_key.offset;
4103 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4104 fi = btrfs_item_ptr(leaf, path->slots[0],
4105 struct btrfs_file_extent_item);
4106 extent_type = btrfs_file_extent_type(leaf, fi);
4107 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4109 btrfs_file_extent_num_bytes(leaf, fi);
4110 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4111 item_end += btrfs_file_extent_inline_len(leaf,
4116 if (found_type > min_type) {
4119 if (item_end < new_size)
4121 if (found_key.offset >= new_size)
4127 /* FIXME, shrink the extent if the ref count is only 1 */
4128 if (found_type != BTRFS_EXTENT_DATA_KEY)
4131 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4133 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4135 u64 orig_num_bytes =
4136 btrfs_file_extent_num_bytes(leaf, fi);
4137 extent_num_bytes = ALIGN(new_size -
4140 btrfs_set_file_extent_num_bytes(leaf, fi,
4142 num_dec = (orig_num_bytes -
4144 if (root->ref_cows && extent_start != 0)
4145 inode_sub_bytes(inode, num_dec);
4146 btrfs_mark_buffer_dirty(leaf);
4149 btrfs_file_extent_disk_num_bytes(leaf,
4151 extent_offset = found_key.offset -
4152 btrfs_file_extent_offset(leaf, fi);
4154 /* FIXME blocksize != 4096 */
4155 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4156 if (extent_start != 0) {
4159 inode_sub_bytes(inode, num_dec);
4162 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4164 * we can't truncate inline items that have had
4168 btrfs_file_extent_compression(leaf, fi) == 0 &&
4169 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4170 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4171 u32 size = new_size - found_key.offset;
4173 if (root->ref_cows) {
4174 inode_sub_bytes(inode, item_end + 1 -
4178 btrfs_file_extent_calc_inline_size(size);
4179 btrfs_truncate_item(trans, root, path,
4181 } else if (root->ref_cows) {
4182 inode_sub_bytes(inode, item_end + 1 -
4188 if (!pending_del_nr) {
4189 /* no pending yet, add ourselves */
4190 pending_del_slot = path->slots[0];
4192 } else if (pending_del_nr &&
4193 path->slots[0] + 1 == pending_del_slot) {
4194 /* hop on the pending chunk */
4196 pending_del_slot = path->slots[0];
4203 if (found_extent && (root->ref_cows ||
4204 root == root->fs_info->tree_root)) {
4205 btrfs_set_path_blocking(path);
4206 ret = btrfs_free_extent(trans, root, extent_start,
4207 extent_num_bytes, 0,
4208 btrfs_header_owner(leaf),
4209 ino, extent_offset, 0);
4213 if (found_type == BTRFS_INODE_ITEM_KEY)
4216 if (path->slots[0] == 0 ||
4217 path->slots[0] != pending_del_slot) {
4218 if (pending_del_nr) {
4219 ret = btrfs_del_items(trans, root, path,
4223 btrfs_abort_transaction(trans,
4229 btrfs_release_path(path);
4236 if (pending_del_nr) {
4237 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4240 btrfs_abort_transaction(trans, root, ret);
4243 btrfs_free_path(path);
4248 * btrfs_truncate_page - read, zero a chunk and write a page
4249 * @inode - inode that we're zeroing
4250 * @from - the offset to start zeroing
4251 * @len - the length to zero, 0 to zero the entire range respective to the
4253 * @front - zero up to the offset instead of from the offset on
4255 * This will find the page for the "from" offset and cow the page and zero the
4256 * part we want to zero. This is used with truncate and hole punching.
4258 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4261 struct address_space *mapping = inode->i_mapping;
4262 struct btrfs_root *root = BTRFS_I(inode)->root;
4263 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4264 struct btrfs_ordered_extent *ordered;
4265 struct extent_state *cached_state = NULL;
4267 u32 blocksize = root->sectorsize;
4268 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4269 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4271 gfp_t mask = btrfs_alloc_write_mask(mapping);
4276 if ((offset & (blocksize - 1)) == 0 &&
4277 (!len || ((len & (blocksize - 1)) == 0)))
4279 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4284 page = find_or_create_page(mapping, index, mask);
4286 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4291 page_start = page_offset(page);
4292 page_end = page_start + PAGE_CACHE_SIZE - 1;
4294 if (!PageUptodate(page)) {
4295 ret = btrfs_readpage(NULL, page);
4297 if (page->mapping != mapping) {
4299 page_cache_release(page);
4302 if (!PageUptodate(page)) {
4307 wait_on_page_writeback(page);
4309 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4310 set_page_extent_mapped(page);
4312 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4314 unlock_extent_cached(io_tree, page_start, page_end,
4315 &cached_state, GFP_NOFS);
4317 page_cache_release(page);
4318 btrfs_start_ordered_extent(inode, ordered, 1);
4319 btrfs_put_ordered_extent(ordered);
4323 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4324 EXTENT_DIRTY | EXTENT_DELALLOC |
4325 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4326 0, 0, &cached_state, GFP_NOFS);
4328 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4331 unlock_extent_cached(io_tree, page_start, page_end,
4332 &cached_state, GFP_NOFS);
4336 if (offset != PAGE_CACHE_SIZE) {
4338 len = PAGE_CACHE_SIZE - offset;
4341 memset(kaddr, 0, offset);
4343 memset(kaddr + offset, 0, len);
4344 flush_dcache_page(page);
4347 ClearPageChecked(page);
4348 set_page_dirty(page);
4349 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4354 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4356 page_cache_release(page);
4362 * This function puts in dummy file extents for the area we're creating a hole
4363 * for. So if we are truncating this file to a larger size we need to insert
4364 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4365 * the range between oldsize and size
4367 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4369 struct btrfs_trans_handle *trans;
4370 struct btrfs_root *root = BTRFS_I(inode)->root;
4371 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4372 struct extent_map *em = NULL;
4373 struct extent_state *cached_state = NULL;
4374 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4375 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4376 u64 block_end = ALIGN(size, root->sectorsize);
4382 if (size <= hole_start)
4386 struct btrfs_ordered_extent *ordered;
4387 btrfs_wait_ordered_range(inode, hole_start,
4388 block_end - hole_start);
4389 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4391 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4394 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4395 &cached_state, GFP_NOFS);
4396 btrfs_put_ordered_extent(ordered);
4399 cur_offset = hole_start;
4401 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4402 block_end - cur_offset, 0);
4408 last_byte = min(extent_map_end(em), block_end);
4409 last_byte = ALIGN(last_byte , root->sectorsize);
4410 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4411 struct extent_map *hole_em;
4412 hole_size = last_byte - cur_offset;
4414 trans = btrfs_start_transaction(root, 3);
4415 if (IS_ERR(trans)) {
4416 err = PTR_ERR(trans);
4420 err = btrfs_drop_extents(trans, root, inode,
4422 cur_offset + hole_size, 1);
4424 btrfs_abort_transaction(trans, root, err);
4425 btrfs_end_transaction(trans, root);
4429 err = btrfs_insert_file_extent(trans, root,
4430 btrfs_ino(inode), cur_offset, 0,
4431 0, hole_size, 0, hole_size,
4434 btrfs_abort_transaction(trans, root, err);
4435 btrfs_end_transaction(trans, root);
4439 btrfs_drop_extent_cache(inode, cur_offset,
4440 cur_offset + hole_size - 1, 0);
4441 hole_em = alloc_extent_map();
4443 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4444 &BTRFS_I(inode)->runtime_flags);
4447 hole_em->start = cur_offset;
4448 hole_em->len = hole_size;
4449 hole_em->orig_start = cur_offset;
4451 hole_em->block_start = EXTENT_MAP_HOLE;
4452 hole_em->block_len = 0;
4453 hole_em->orig_block_len = 0;
4454 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4455 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4456 hole_em->generation = trans->transid;
4459 write_lock(&em_tree->lock);
4460 err = add_extent_mapping(em_tree, hole_em);
4462 list_move(&hole_em->list,
4463 &em_tree->modified_extents);
4464 write_unlock(&em_tree->lock);
4467 btrfs_drop_extent_cache(inode, cur_offset,
4471 free_extent_map(hole_em);
4473 btrfs_update_inode(trans, root, inode);
4474 btrfs_end_transaction(trans, root);
4476 free_extent_map(em);
4478 cur_offset = last_byte;
4479 if (cur_offset >= block_end)
4483 free_extent_map(em);
4484 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4489 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4491 struct btrfs_root *root = BTRFS_I(inode)->root;
4492 struct btrfs_trans_handle *trans;
4493 loff_t oldsize = i_size_read(inode);
4494 loff_t newsize = attr->ia_size;
4495 int mask = attr->ia_valid;
4498 if (newsize == oldsize)
4502 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4503 * special case where we need to update the times despite not having
4504 * these flags set. For all other operations the VFS set these flags
4505 * explicitly if it wants a timestamp update.
4507 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4508 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4510 if (newsize > oldsize) {
4511 truncate_pagecache(inode, oldsize, newsize);
4512 ret = btrfs_cont_expand(inode, oldsize, newsize);
4516 trans = btrfs_start_transaction(root, 1);
4518 return PTR_ERR(trans);
4520 i_size_write(inode, newsize);
4521 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4522 ret = btrfs_update_inode(trans, root, inode);
4523 btrfs_end_transaction(trans, root);
4527 * We're truncating a file that used to have good data down to
4528 * zero. Make sure it gets into the ordered flush list so that
4529 * any new writes get down to disk quickly.
4532 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4533 &BTRFS_I(inode)->runtime_flags);
4536 * 1 for the orphan item we're going to add
4537 * 1 for the orphan item deletion.
4539 trans = btrfs_start_transaction(root, 2);
4541 return PTR_ERR(trans);
4544 * We need to do this in case we fail at _any_ point during the
4545 * actual truncate. Once we do the truncate_setsize we could
4546 * invalidate pages which forces any outstanding ordered io to
4547 * be instantly completed which will give us extents that need
4548 * to be truncated. If we fail to get an orphan inode down we
4549 * could have left over extents that were never meant to live,
4550 * so we need to garuntee from this point on that everything
4551 * will be consistent.
4553 ret = btrfs_orphan_add(trans, inode);
4554 btrfs_end_transaction(trans, root);
4558 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4559 truncate_setsize(inode, newsize);
4561 /* Disable nonlocked read DIO to avoid the end less truncate */
4562 btrfs_inode_block_unlocked_dio(inode);
4563 inode_dio_wait(inode);
4564 btrfs_inode_resume_unlocked_dio(inode);
4566 ret = btrfs_truncate(inode);
4567 if (ret && inode->i_nlink)
4568 btrfs_orphan_del(NULL, inode);
4574 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4576 struct inode *inode = dentry->d_inode;
4577 struct btrfs_root *root = BTRFS_I(inode)->root;
4580 if (btrfs_root_readonly(root))
4583 err = inode_change_ok(inode, attr);
4587 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4588 err = btrfs_setsize(inode, attr);
4593 if (attr->ia_valid) {
4594 setattr_copy(inode, attr);
4595 inode_inc_iversion(inode);
4596 err = btrfs_dirty_inode(inode);
4598 if (!err && attr->ia_valid & ATTR_MODE)
4599 err = btrfs_acl_chmod(inode);
4605 void btrfs_evict_inode(struct inode *inode)
4607 struct btrfs_trans_handle *trans;
4608 struct btrfs_root *root = BTRFS_I(inode)->root;
4609 struct btrfs_block_rsv *rsv, *global_rsv;
4610 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4613 trace_btrfs_inode_evict(inode);
4615 truncate_inode_pages(&inode->i_data, 0);
4616 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4617 btrfs_is_free_space_inode(inode)))
4620 if (is_bad_inode(inode)) {
4621 btrfs_orphan_del(NULL, inode);
4624 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4625 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4627 if (root->fs_info->log_root_recovering) {
4628 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4629 &BTRFS_I(inode)->runtime_flags));
4633 if (inode->i_nlink > 0) {
4634 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4638 ret = btrfs_commit_inode_delayed_inode(inode);
4640 btrfs_orphan_del(NULL, inode);
4644 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4646 btrfs_orphan_del(NULL, inode);
4649 rsv->size = min_size;
4651 global_rsv = &root->fs_info->global_block_rsv;
4653 btrfs_i_size_write(inode, 0);
4656 * This is a bit simpler than btrfs_truncate since we've already
4657 * reserved our space for our orphan item in the unlink, so we just
4658 * need to reserve some slack space in case we add bytes and update
4659 * inode item when doing the truncate.
4662 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4663 BTRFS_RESERVE_FLUSH_LIMIT);
4666 * Try and steal from the global reserve since we will
4667 * likely not use this space anyway, we want to try as
4668 * hard as possible to get this to work.
4671 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4674 printk(KERN_WARNING "Could not get space for a "
4675 "delete, will truncate on mount %d\n", ret);
4676 btrfs_orphan_del(NULL, inode);
4677 btrfs_free_block_rsv(root, rsv);
4681 trans = btrfs_join_transaction(root);
4682 if (IS_ERR(trans)) {
4683 btrfs_orphan_del(NULL, inode);
4684 btrfs_free_block_rsv(root, rsv);
4688 trans->block_rsv = rsv;
4690 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4694 trans->block_rsv = &root->fs_info->trans_block_rsv;
4695 btrfs_end_transaction(trans, root);
4697 btrfs_btree_balance_dirty(root);
4700 btrfs_free_block_rsv(root, rsv);
4703 trans->block_rsv = root->orphan_block_rsv;
4704 ret = btrfs_orphan_del(trans, inode);
4708 trans->block_rsv = &root->fs_info->trans_block_rsv;
4709 if (!(root == root->fs_info->tree_root ||
4710 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4711 btrfs_return_ino(root, btrfs_ino(inode));
4713 btrfs_end_transaction(trans, root);
4714 btrfs_btree_balance_dirty(root);
4721 * this returns the key found in the dir entry in the location pointer.
4722 * If no dir entries were found, location->objectid is 0.
4724 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4725 struct btrfs_key *location)
4727 const char *name = dentry->d_name.name;
4728 int namelen = dentry->d_name.len;
4729 struct btrfs_dir_item *di;
4730 struct btrfs_path *path;
4731 struct btrfs_root *root = BTRFS_I(dir)->root;
4734 path = btrfs_alloc_path();
4738 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4743 if (IS_ERR_OR_NULL(di))
4746 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4748 btrfs_free_path(path);
4751 location->objectid = 0;
4756 * when we hit a tree root in a directory, the btrfs part of the inode
4757 * needs to be changed to reflect the root directory of the tree root. This
4758 * is kind of like crossing a mount point.
4760 static int fixup_tree_root_location(struct btrfs_root *root,
4762 struct dentry *dentry,
4763 struct btrfs_key *location,
4764 struct btrfs_root **sub_root)
4766 struct btrfs_path *path;
4767 struct btrfs_root *new_root;
4768 struct btrfs_root_ref *ref;
4769 struct extent_buffer *leaf;
4773 path = btrfs_alloc_path();
4780 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4781 BTRFS_I(dir)->root->root_key.objectid,
4782 location->objectid);
4789 leaf = path->nodes[0];
4790 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4791 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4792 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4795 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4796 (unsigned long)(ref + 1),
4797 dentry->d_name.len);
4801 btrfs_release_path(path);
4803 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4804 if (IS_ERR(new_root)) {
4805 err = PTR_ERR(new_root);
4809 if (btrfs_root_refs(&new_root->root_item) == 0) {
4814 *sub_root = new_root;
4815 location->objectid = btrfs_root_dirid(&new_root->root_item);
4816 location->type = BTRFS_INODE_ITEM_KEY;
4817 location->offset = 0;
4820 btrfs_free_path(path);
4824 static void inode_tree_add(struct inode *inode)
4826 struct btrfs_root *root = BTRFS_I(inode)->root;
4827 struct btrfs_inode *entry;
4829 struct rb_node *parent;
4830 u64 ino = btrfs_ino(inode);
4832 p = &root->inode_tree.rb_node;
4835 if (inode_unhashed(inode))
4838 spin_lock(&root->inode_lock);
4841 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4843 if (ino < btrfs_ino(&entry->vfs_inode))
4844 p = &parent->rb_left;
4845 else if (ino > btrfs_ino(&entry->vfs_inode))
4846 p = &parent->rb_right;
4848 WARN_ON(!(entry->vfs_inode.i_state &
4849 (I_WILL_FREE | I_FREEING)));
4850 rb_erase(parent, &root->inode_tree);
4851 RB_CLEAR_NODE(parent);
4852 spin_unlock(&root->inode_lock);
4856 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4857 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4858 spin_unlock(&root->inode_lock);
4861 static void inode_tree_del(struct inode *inode)
4863 struct btrfs_root *root = BTRFS_I(inode)->root;
4866 spin_lock(&root->inode_lock);
4867 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4868 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4869 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4870 empty = RB_EMPTY_ROOT(&root->inode_tree);
4872 spin_unlock(&root->inode_lock);
4875 * Free space cache has inodes in the tree root, but the tree root has a
4876 * root_refs of 0, so this could end up dropping the tree root as a
4877 * snapshot, so we need the extra !root->fs_info->tree_root check to
4878 * make sure we don't drop it.
4880 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4881 root != root->fs_info->tree_root) {
4882 synchronize_srcu(&root->fs_info->subvol_srcu);
4883 spin_lock(&root->inode_lock);
4884 empty = RB_EMPTY_ROOT(&root->inode_tree);
4885 spin_unlock(&root->inode_lock);
4887 btrfs_add_dead_root(root);
4891 void btrfs_invalidate_inodes(struct btrfs_root *root)
4893 struct rb_node *node;
4894 struct rb_node *prev;
4895 struct btrfs_inode *entry;
4896 struct inode *inode;
4899 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4901 spin_lock(&root->inode_lock);
4903 node = root->inode_tree.rb_node;
4907 entry = rb_entry(node, struct btrfs_inode, rb_node);
4909 if (objectid < btrfs_ino(&entry->vfs_inode))
4910 node = node->rb_left;
4911 else if (objectid > btrfs_ino(&entry->vfs_inode))
4912 node = node->rb_right;
4918 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4919 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4923 prev = rb_next(prev);
4927 entry = rb_entry(node, struct btrfs_inode, rb_node);
4928 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4929 inode = igrab(&entry->vfs_inode);
4931 spin_unlock(&root->inode_lock);
4932 if (atomic_read(&inode->i_count) > 1)
4933 d_prune_aliases(inode);
4935 * btrfs_drop_inode will have it removed from
4936 * the inode cache when its usage count
4941 spin_lock(&root->inode_lock);
4945 if (cond_resched_lock(&root->inode_lock))
4948 node = rb_next(node);
4950 spin_unlock(&root->inode_lock);
4953 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4955 struct btrfs_iget_args *args = p;
4956 inode->i_ino = args->ino;
4957 BTRFS_I(inode)->root = args->root;
4961 static int btrfs_find_actor(struct inode *inode, void *opaque)
4963 struct btrfs_iget_args *args = opaque;
4964 return args->ino == btrfs_ino(inode) &&
4965 args->root == BTRFS_I(inode)->root;
4968 static struct inode *btrfs_iget_locked(struct super_block *s,
4970 struct btrfs_root *root)
4972 struct inode *inode;
4973 struct btrfs_iget_args args;
4974 args.ino = objectid;
4977 inode = iget5_locked(s, objectid, btrfs_find_actor,
4978 btrfs_init_locked_inode,
4983 /* Get an inode object given its location and corresponding root.
4984 * Returns in *is_new if the inode was read from disk
4986 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4987 struct btrfs_root *root, int *new)
4989 struct inode *inode;
4991 inode = btrfs_iget_locked(s, location->objectid, root);
4993 return ERR_PTR(-ENOMEM);
4995 if (inode->i_state & I_NEW) {
4996 BTRFS_I(inode)->root = root;
4997 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4998 btrfs_read_locked_inode(inode);
4999 if (!is_bad_inode(inode)) {
5000 inode_tree_add(inode);
5001 unlock_new_inode(inode);
5005 unlock_new_inode(inode);
5007 inode = ERR_PTR(-ESTALE);
5014 static struct inode *new_simple_dir(struct super_block *s,
5015 struct btrfs_key *key,
5016 struct btrfs_root *root)
5018 struct inode *inode = new_inode(s);
5021 return ERR_PTR(-ENOMEM);
5023 BTRFS_I(inode)->root = root;
5024 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5025 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5027 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5028 inode->i_op = &btrfs_dir_ro_inode_operations;
5029 inode->i_fop = &simple_dir_operations;
5030 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5031 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5036 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5038 struct inode *inode;
5039 struct btrfs_root *root = BTRFS_I(dir)->root;
5040 struct btrfs_root *sub_root = root;
5041 struct btrfs_key location;
5045 if (dentry->d_name.len > BTRFS_NAME_LEN)
5046 return ERR_PTR(-ENAMETOOLONG);
5048 ret = btrfs_inode_by_name(dir, dentry, &location);
5050 return ERR_PTR(ret);
5052 if (location.objectid == 0)
5055 if (location.type == BTRFS_INODE_ITEM_KEY) {
5056 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5060 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5062 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5063 ret = fixup_tree_root_location(root, dir, dentry,
5064 &location, &sub_root);
5067 inode = ERR_PTR(ret);
5069 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5071 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5073 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5075 if (!IS_ERR(inode) && root != sub_root) {
5076 down_read(&root->fs_info->cleanup_work_sem);
5077 if (!(inode->i_sb->s_flags & MS_RDONLY))
5078 ret = btrfs_orphan_cleanup(sub_root);
5079 up_read(&root->fs_info->cleanup_work_sem);
5081 inode = ERR_PTR(ret);
5087 static int btrfs_dentry_delete(const struct dentry *dentry)
5089 struct btrfs_root *root;
5090 struct inode *inode = dentry->d_inode;
5092 if (!inode && !IS_ROOT(dentry))
5093 inode = dentry->d_parent->d_inode;
5096 root = BTRFS_I(inode)->root;
5097 if (btrfs_root_refs(&root->root_item) == 0)
5100 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5106 static void btrfs_dentry_release(struct dentry *dentry)
5108 if (dentry->d_fsdata)
5109 kfree(dentry->d_fsdata);
5112 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5117 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5121 unsigned char btrfs_filetype_table[] = {
5122 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5125 static int btrfs_real_readdir(struct file *filp, void *dirent,
5128 struct inode *inode = file_inode(filp);
5129 struct btrfs_root *root = BTRFS_I(inode)->root;
5130 struct btrfs_item *item;
5131 struct btrfs_dir_item *di;
5132 struct btrfs_key key;
5133 struct btrfs_key found_key;
5134 struct btrfs_path *path;
5135 struct list_head ins_list;
5136 struct list_head del_list;
5138 struct extent_buffer *leaf;
5140 unsigned char d_type;
5145 int key_type = BTRFS_DIR_INDEX_KEY;
5149 int is_curr = 0; /* filp->f_pos points to the current index? */
5151 /* FIXME, use a real flag for deciding about the key type */
5152 if (root->fs_info->tree_root == root)
5153 key_type = BTRFS_DIR_ITEM_KEY;
5155 /* special case for "." */
5156 if (filp->f_pos == 0) {
5157 over = filldir(dirent, ".", 1,
5158 filp->f_pos, btrfs_ino(inode), DT_DIR);
5163 /* special case for .., just use the back ref */
5164 if (filp->f_pos == 1) {
5165 u64 pino = parent_ino(filp->f_path.dentry);
5166 over = filldir(dirent, "..", 2,
5167 filp->f_pos, pino, DT_DIR);
5172 path = btrfs_alloc_path();
5178 if (key_type == BTRFS_DIR_INDEX_KEY) {
5179 INIT_LIST_HEAD(&ins_list);
5180 INIT_LIST_HEAD(&del_list);
5181 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5184 btrfs_set_key_type(&key, key_type);
5185 key.offset = filp->f_pos;
5186 key.objectid = btrfs_ino(inode);
5188 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5193 leaf = path->nodes[0];
5194 slot = path->slots[0];
5195 if (slot >= btrfs_header_nritems(leaf)) {
5196 ret = btrfs_next_leaf(root, path);
5204 item = btrfs_item_nr(leaf, slot);
5205 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5207 if (found_key.objectid != key.objectid)
5209 if (btrfs_key_type(&found_key) != key_type)
5211 if (found_key.offset < filp->f_pos)
5213 if (key_type == BTRFS_DIR_INDEX_KEY &&
5214 btrfs_should_delete_dir_index(&del_list,
5218 filp->f_pos = found_key.offset;
5221 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5223 di_total = btrfs_item_size(leaf, item);
5225 while (di_cur < di_total) {
5226 struct btrfs_key location;
5228 if (verify_dir_item(root, leaf, di))
5231 name_len = btrfs_dir_name_len(leaf, di);
5232 if (name_len <= sizeof(tmp_name)) {
5233 name_ptr = tmp_name;
5235 name_ptr = kmalloc(name_len, GFP_NOFS);
5241 read_extent_buffer(leaf, name_ptr,
5242 (unsigned long)(di + 1), name_len);
5244 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5245 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5248 /* is this a reference to our own snapshot? If so
5251 * In contrast to old kernels, we insert the snapshot's
5252 * dir item and dir index after it has been created, so
5253 * we won't find a reference to our own snapshot. We
5254 * still keep the following code for backward
5257 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5258 location.objectid == root->root_key.objectid) {
5262 over = filldir(dirent, name_ptr, name_len,
5263 found_key.offset, location.objectid,
5267 if (name_ptr != tmp_name)
5272 di_len = btrfs_dir_name_len(leaf, di) +
5273 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5275 di = (struct btrfs_dir_item *)((char *)di + di_len);
5281 if (key_type == BTRFS_DIR_INDEX_KEY) {
5284 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5290 /* Reached end of directory/root. Bump pos past the last item. */
5291 if (key_type == BTRFS_DIR_INDEX_KEY)
5293 * 32-bit glibc will use getdents64, but then strtol -
5294 * so the last number we can serve is this.
5296 filp->f_pos = 0x7fffffff;
5302 if (key_type == BTRFS_DIR_INDEX_KEY)
5303 btrfs_put_delayed_items(&ins_list, &del_list);
5304 btrfs_free_path(path);
5308 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5310 struct btrfs_root *root = BTRFS_I(inode)->root;
5311 struct btrfs_trans_handle *trans;
5313 bool nolock = false;
5315 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5318 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5321 if (wbc->sync_mode == WB_SYNC_ALL) {
5323 trans = btrfs_join_transaction_nolock(root);
5325 trans = btrfs_join_transaction(root);
5327 return PTR_ERR(trans);
5328 ret = btrfs_commit_transaction(trans, root);
5334 * This is somewhat expensive, updating the tree every time the
5335 * inode changes. But, it is most likely to find the inode in cache.
5336 * FIXME, needs more benchmarking...there are no reasons other than performance
5337 * to keep or drop this code.
5339 int btrfs_dirty_inode(struct inode *inode)
5341 struct btrfs_root *root = BTRFS_I(inode)->root;
5342 struct btrfs_trans_handle *trans;
5345 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5348 trans = btrfs_join_transaction(root);
5350 return PTR_ERR(trans);
5352 ret = btrfs_update_inode(trans, root, inode);
5353 if (ret && ret == -ENOSPC) {
5354 /* whoops, lets try again with the full transaction */
5355 btrfs_end_transaction(trans, root);
5356 trans = btrfs_start_transaction(root, 1);
5358 return PTR_ERR(trans);
5360 ret = btrfs_update_inode(trans, root, inode);
5362 btrfs_end_transaction(trans, root);
5363 if (BTRFS_I(inode)->delayed_node)
5364 btrfs_balance_delayed_items(root);
5370 * This is a copy of file_update_time. We need this so we can return error on
5371 * ENOSPC for updating the inode in the case of file write and mmap writes.
5373 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5376 struct btrfs_root *root = BTRFS_I(inode)->root;
5378 if (btrfs_root_readonly(root))
5381 if (flags & S_VERSION)
5382 inode_inc_iversion(inode);
5383 if (flags & S_CTIME)
5384 inode->i_ctime = *now;
5385 if (flags & S_MTIME)
5386 inode->i_mtime = *now;
5387 if (flags & S_ATIME)
5388 inode->i_atime = *now;
5389 return btrfs_dirty_inode(inode);
5393 * find the highest existing sequence number in a directory
5394 * and then set the in-memory index_cnt variable to reflect
5395 * free sequence numbers
5397 static int btrfs_set_inode_index_count(struct inode *inode)
5399 struct btrfs_root *root = BTRFS_I(inode)->root;
5400 struct btrfs_key key, found_key;
5401 struct btrfs_path *path;
5402 struct extent_buffer *leaf;
5405 key.objectid = btrfs_ino(inode);
5406 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5407 key.offset = (u64)-1;
5409 path = btrfs_alloc_path();
5413 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5416 /* FIXME: we should be able to handle this */
5422 * MAGIC NUMBER EXPLANATION:
5423 * since we search a directory based on f_pos we have to start at 2
5424 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5425 * else has to start at 2
5427 if (path->slots[0] == 0) {
5428 BTRFS_I(inode)->index_cnt = 2;
5434 leaf = path->nodes[0];
5435 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5437 if (found_key.objectid != btrfs_ino(inode) ||
5438 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5439 BTRFS_I(inode)->index_cnt = 2;
5443 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5445 btrfs_free_path(path);
5450 * helper to find a free sequence number in a given directory. This current
5451 * code is very simple, later versions will do smarter things in the btree
5453 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5457 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5458 ret = btrfs_inode_delayed_dir_index_count(dir);
5460 ret = btrfs_set_inode_index_count(dir);
5466 *index = BTRFS_I(dir)->index_cnt;
5467 BTRFS_I(dir)->index_cnt++;
5472 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5473 struct btrfs_root *root,
5475 const char *name, int name_len,
5476 u64 ref_objectid, u64 objectid,
5477 umode_t mode, u64 *index)
5479 struct inode *inode;
5480 struct btrfs_inode_item *inode_item;
5481 struct btrfs_key *location;
5482 struct btrfs_path *path;
5483 struct btrfs_inode_ref *ref;
5484 struct btrfs_key key[2];
5490 path = btrfs_alloc_path();
5492 return ERR_PTR(-ENOMEM);
5494 inode = new_inode(root->fs_info->sb);
5496 btrfs_free_path(path);
5497 return ERR_PTR(-ENOMEM);
5501 * we have to initialize this early, so we can reclaim the inode
5502 * number if we fail afterwards in this function.
5504 inode->i_ino = objectid;
5507 trace_btrfs_inode_request(dir);
5509 ret = btrfs_set_inode_index(dir, index);
5511 btrfs_free_path(path);
5513 return ERR_PTR(ret);
5517 * index_cnt is ignored for everything but a dir,
5518 * btrfs_get_inode_index_count has an explanation for the magic
5521 BTRFS_I(inode)->index_cnt = 2;
5522 BTRFS_I(inode)->root = root;
5523 BTRFS_I(inode)->generation = trans->transid;
5524 inode->i_generation = BTRFS_I(inode)->generation;
5527 * We could have gotten an inode number from somebody who was fsynced
5528 * and then removed in this same transaction, so let's just set full
5529 * sync since it will be a full sync anyway and this will blow away the
5530 * old info in the log.
5532 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5539 key[0].objectid = objectid;
5540 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5544 * Start new inodes with an inode_ref. This is slightly more
5545 * efficient for small numbers of hard links since they will
5546 * be packed into one item. Extended refs will kick in if we
5547 * add more hard links than can fit in the ref item.
5549 key[1].objectid = objectid;
5550 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5551 key[1].offset = ref_objectid;
5553 sizes[0] = sizeof(struct btrfs_inode_item);
5554 sizes[1] = name_len + sizeof(*ref);
5556 path->leave_spinning = 1;
5557 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5561 inode_init_owner(inode, dir, mode);
5562 inode_set_bytes(inode, 0);
5563 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5564 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5565 struct btrfs_inode_item);
5566 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5567 sizeof(*inode_item));
5568 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5570 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5571 struct btrfs_inode_ref);
5572 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5573 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5574 ptr = (unsigned long)(ref + 1);
5575 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5577 btrfs_mark_buffer_dirty(path->nodes[0]);
5578 btrfs_free_path(path);
5580 location = &BTRFS_I(inode)->location;
5581 location->objectid = objectid;
5582 location->offset = 0;
5583 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5585 btrfs_inherit_iflags(inode, dir);
5587 if (S_ISREG(mode)) {
5588 if (btrfs_test_opt(root, NODATASUM))
5589 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5590 if (btrfs_test_opt(root, NODATACOW))
5591 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5592 BTRFS_INODE_NODATASUM;
5595 insert_inode_hash(inode);
5596 inode_tree_add(inode);
5598 trace_btrfs_inode_new(inode);
5599 btrfs_set_inode_last_trans(trans, inode);
5601 btrfs_update_root_times(trans, root);
5606 BTRFS_I(dir)->index_cnt--;
5607 btrfs_free_path(path);
5609 return ERR_PTR(ret);
5612 static inline u8 btrfs_inode_type(struct inode *inode)
5614 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5618 * utility function to add 'inode' into 'parent_inode' with
5619 * a give name and a given sequence number.
5620 * if 'add_backref' is true, also insert a backref from the
5621 * inode to the parent directory.
5623 int btrfs_add_link(struct btrfs_trans_handle *trans,
5624 struct inode *parent_inode, struct inode *inode,
5625 const char *name, int name_len, int add_backref, u64 index)
5628 struct btrfs_key key;
5629 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5630 u64 ino = btrfs_ino(inode);
5631 u64 parent_ino = btrfs_ino(parent_inode);
5633 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5634 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5637 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5641 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5642 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5643 key.objectid, root->root_key.objectid,
5644 parent_ino, index, name, name_len);
5645 } else if (add_backref) {
5646 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5650 /* Nothing to clean up yet */
5654 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5656 btrfs_inode_type(inode), index);
5657 if (ret == -EEXIST || ret == -EOVERFLOW)
5660 btrfs_abort_transaction(trans, root, ret);
5664 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5666 inode_inc_iversion(parent_inode);
5667 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5668 ret = btrfs_update_inode(trans, root, parent_inode);
5670 btrfs_abort_transaction(trans, root, ret);
5674 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5677 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5678 key.objectid, root->root_key.objectid,
5679 parent_ino, &local_index, name, name_len);
5681 } else if (add_backref) {
5685 err = btrfs_del_inode_ref(trans, root, name, name_len,
5686 ino, parent_ino, &local_index);
5691 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5692 struct inode *dir, struct dentry *dentry,
5693 struct inode *inode, int backref, u64 index)
5695 int err = btrfs_add_link(trans, dir, inode,
5696 dentry->d_name.name, dentry->d_name.len,
5703 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5704 umode_t mode, dev_t rdev)
5706 struct btrfs_trans_handle *trans;
5707 struct btrfs_root *root = BTRFS_I(dir)->root;
5708 struct inode *inode = NULL;
5714 if (!new_valid_dev(rdev))
5718 * 2 for inode item and ref
5720 * 1 for xattr if selinux is on
5722 trans = btrfs_start_transaction(root, 5);
5724 return PTR_ERR(trans);
5726 err = btrfs_find_free_ino(root, &objectid);
5730 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5731 dentry->d_name.len, btrfs_ino(dir), objectid,
5733 if (IS_ERR(inode)) {
5734 err = PTR_ERR(inode);
5738 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5745 * If the active LSM wants to access the inode during
5746 * d_instantiate it needs these. Smack checks to see
5747 * if the filesystem supports xattrs by looking at the
5751 inode->i_op = &btrfs_special_inode_operations;
5752 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5756 init_special_inode(inode, inode->i_mode, rdev);
5757 btrfs_update_inode(trans, root, inode);
5758 d_instantiate(dentry, inode);
5761 btrfs_end_transaction(trans, root);
5762 btrfs_btree_balance_dirty(root);
5764 inode_dec_link_count(inode);
5770 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5771 umode_t mode, bool excl)
5773 struct btrfs_trans_handle *trans;
5774 struct btrfs_root *root = BTRFS_I(dir)->root;
5775 struct inode *inode = NULL;
5776 int drop_inode_on_err = 0;
5782 * 2 for inode item and ref
5784 * 1 for xattr if selinux is on
5786 trans = btrfs_start_transaction(root, 5);
5788 return PTR_ERR(trans);
5790 err = btrfs_find_free_ino(root, &objectid);
5794 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5795 dentry->d_name.len, btrfs_ino(dir), objectid,
5797 if (IS_ERR(inode)) {
5798 err = PTR_ERR(inode);
5801 drop_inode_on_err = 1;
5803 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5807 err = btrfs_update_inode(trans, root, inode);
5812 * If the active LSM wants to access the inode during
5813 * d_instantiate it needs these. Smack checks to see
5814 * if the filesystem supports xattrs by looking at the
5817 inode->i_fop = &btrfs_file_operations;
5818 inode->i_op = &btrfs_file_inode_operations;
5820 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5824 inode->i_mapping->a_ops = &btrfs_aops;
5825 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5826 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5827 d_instantiate(dentry, inode);
5830 btrfs_end_transaction(trans, root);
5831 if (err && drop_inode_on_err) {
5832 inode_dec_link_count(inode);
5835 btrfs_btree_balance_dirty(root);
5839 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5840 struct dentry *dentry)
5842 struct btrfs_trans_handle *trans;
5843 struct btrfs_root *root = BTRFS_I(dir)->root;
5844 struct inode *inode = old_dentry->d_inode;
5849 /* do not allow sys_link's with other subvols of the same device */
5850 if (root->objectid != BTRFS_I(inode)->root->objectid)
5853 if (inode->i_nlink >= BTRFS_LINK_MAX)
5856 err = btrfs_set_inode_index(dir, &index);
5861 * 2 items for inode and inode ref
5862 * 2 items for dir items
5863 * 1 item for parent inode
5865 trans = btrfs_start_transaction(root, 5);
5866 if (IS_ERR(trans)) {
5867 err = PTR_ERR(trans);
5871 btrfs_inc_nlink(inode);
5872 inode_inc_iversion(inode);
5873 inode->i_ctime = CURRENT_TIME;
5875 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5877 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5882 struct dentry *parent = dentry->d_parent;
5883 err = btrfs_update_inode(trans, root, inode);
5886 d_instantiate(dentry, inode);
5887 btrfs_log_new_name(trans, inode, NULL, parent);
5890 btrfs_end_transaction(trans, root);
5893 inode_dec_link_count(inode);
5896 btrfs_btree_balance_dirty(root);
5900 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5902 struct inode *inode = NULL;
5903 struct btrfs_trans_handle *trans;
5904 struct btrfs_root *root = BTRFS_I(dir)->root;
5906 int drop_on_err = 0;
5911 * 2 items for inode and ref
5912 * 2 items for dir items
5913 * 1 for xattr if selinux is on
5915 trans = btrfs_start_transaction(root, 5);
5917 return PTR_ERR(trans);
5919 err = btrfs_find_free_ino(root, &objectid);
5923 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5924 dentry->d_name.len, btrfs_ino(dir), objectid,
5925 S_IFDIR | mode, &index);
5926 if (IS_ERR(inode)) {
5927 err = PTR_ERR(inode);
5933 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5937 inode->i_op = &btrfs_dir_inode_operations;
5938 inode->i_fop = &btrfs_dir_file_operations;
5940 btrfs_i_size_write(inode, 0);
5941 err = btrfs_update_inode(trans, root, inode);
5945 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5946 dentry->d_name.len, 0, index);
5950 d_instantiate(dentry, inode);
5954 btrfs_end_transaction(trans, root);
5957 btrfs_btree_balance_dirty(root);
5961 /* helper for btfs_get_extent. Given an existing extent in the tree,
5962 * and an extent that you want to insert, deal with overlap and insert
5963 * the new extent into the tree.
5965 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5966 struct extent_map *existing,
5967 struct extent_map *em,
5968 u64 map_start, u64 map_len)
5972 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5973 start_diff = map_start - em->start;
5974 em->start = map_start;
5976 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5977 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5978 em->block_start += start_diff;
5979 em->block_len -= start_diff;
5981 return add_extent_mapping(em_tree, em);
5984 static noinline int uncompress_inline(struct btrfs_path *path,
5985 struct inode *inode, struct page *page,
5986 size_t pg_offset, u64 extent_offset,
5987 struct btrfs_file_extent_item *item)
5990 struct extent_buffer *leaf = path->nodes[0];
5993 unsigned long inline_size;
5997 WARN_ON(pg_offset != 0);
5998 compress_type = btrfs_file_extent_compression(leaf, item);
5999 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6000 inline_size = btrfs_file_extent_inline_item_len(leaf,
6001 btrfs_item_nr(leaf, path->slots[0]));
6002 tmp = kmalloc(inline_size, GFP_NOFS);
6005 ptr = btrfs_file_extent_inline_start(item);
6007 read_extent_buffer(leaf, tmp, ptr, inline_size);
6009 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6010 ret = btrfs_decompress(compress_type, tmp, page,
6011 extent_offset, inline_size, max_size);
6013 char *kaddr = kmap_atomic(page);
6014 unsigned long copy_size = min_t(u64,
6015 PAGE_CACHE_SIZE - pg_offset,
6016 max_size - extent_offset);
6017 memset(kaddr + pg_offset, 0, copy_size);
6018 kunmap_atomic(kaddr);
6025 * a bit scary, this does extent mapping from logical file offset to the disk.
6026 * the ugly parts come from merging extents from the disk with the in-ram
6027 * representation. This gets more complex because of the data=ordered code,
6028 * where the in-ram extents might be locked pending data=ordered completion.
6030 * This also copies inline extents directly into the page.
6033 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6034 size_t pg_offset, u64 start, u64 len,
6040 u64 extent_start = 0;
6042 u64 objectid = btrfs_ino(inode);
6044 struct btrfs_path *path = NULL;
6045 struct btrfs_root *root = BTRFS_I(inode)->root;
6046 struct btrfs_file_extent_item *item;
6047 struct extent_buffer *leaf;
6048 struct btrfs_key found_key;
6049 struct extent_map *em = NULL;
6050 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6051 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6052 struct btrfs_trans_handle *trans = NULL;
6056 read_lock(&em_tree->lock);
6057 em = lookup_extent_mapping(em_tree, start, len);
6059 em->bdev = root->fs_info->fs_devices->latest_bdev;
6060 read_unlock(&em_tree->lock);
6063 if (em->start > start || em->start + em->len <= start)
6064 free_extent_map(em);
6065 else if (em->block_start == EXTENT_MAP_INLINE && page)
6066 free_extent_map(em);
6070 em = alloc_extent_map();
6075 em->bdev = root->fs_info->fs_devices->latest_bdev;
6076 em->start = EXTENT_MAP_HOLE;
6077 em->orig_start = EXTENT_MAP_HOLE;
6079 em->block_len = (u64)-1;
6082 path = btrfs_alloc_path();
6088 * Chances are we'll be called again, so go ahead and do
6094 ret = btrfs_lookup_file_extent(trans, root, path,
6095 objectid, start, trans != NULL);
6102 if (path->slots[0] == 0)
6107 leaf = path->nodes[0];
6108 item = btrfs_item_ptr(leaf, path->slots[0],
6109 struct btrfs_file_extent_item);
6110 /* are we inside the extent that was found? */
6111 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6112 found_type = btrfs_key_type(&found_key);
6113 if (found_key.objectid != objectid ||
6114 found_type != BTRFS_EXTENT_DATA_KEY) {
6118 found_type = btrfs_file_extent_type(leaf, item);
6119 extent_start = found_key.offset;
6120 compress_type = btrfs_file_extent_compression(leaf, item);
6121 if (found_type == BTRFS_FILE_EXTENT_REG ||
6122 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6123 extent_end = extent_start +
6124 btrfs_file_extent_num_bytes(leaf, item);
6125 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6127 size = btrfs_file_extent_inline_len(leaf, item);
6128 extent_end = ALIGN(extent_start + size, root->sectorsize);
6131 if (start >= extent_end) {
6133 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6134 ret = btrfs_next_leaf(root, path);
6141 leaf = path->nodes[0];
6143 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6144 if (found_key.objectid != objectid ||
6145 found_key.type != BTRFS_EXTENT_DATA_KEY)
6147 if (start + len <= found_key.offset)
6150 em->orig_start = start;
6151 em->len = found_key.offset - start;
6155 if (found_type == BTRFS_FILE_EXTENT_REG ||
6156 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6157 em->start = extent_start;
6158 em->len = extent_end - extent_start;
6159 em->orig_start = extent_start -
6160 btrfs_file_extent_offset(leaf, item);
6161 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6163 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6165 em->block_start = EXTENT_MAP_HOLE;
6168 if (compress_type != BTRFS_COMPRESS_NONE) {
6169 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6170 em->compress_type = compress_type;
6171 em->block_start = bytenr;
6172 em->block_len = em->orig_block_len;
6174 bytenr += btrfs_file_extent_offset(leaf, item);
6175 em->block_start = bytenr;
6176 em->block_len = em->len;
6177 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6178 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6181 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6185 size_t extent_offset;
6188 em->block_start = EXTENT_MAP_INLINE;
6189 if (!page || create) {
6190 em->start = extent_start;
6191 em->len = extent_end - extent_start;
6195 size = btrfs_file_extent_inline_len(leaf, item);
6196 extent_offset = page_offset(page) + pg_offset - extent_start;
6197 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6198 size - extent_offset);
6199 em->start = extent_start + extent_offset;
6200 em->len = ALIGN(copy_size, root->sectorsize);
6201 em->orig_block_len = em->len;
6202 em->orig_start = em->start;
6203 if (compress_type) {
6204 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6205 em->compress_type = compress_type;
6207 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6208 if (create == 0 && !PageUptodate(page)) {
6209 if (btrfs_file_extent_compression(leaf, item) !=
6210 BTRFS_COMPRESS_NONE) {
6211 ret = uncompress_inline(path, inode, page,
6213 extent_offset, item);
6214 BUG_ON(ret); /* -ENOMEM */
6217 read_extent_buffer(leaf, map + pg_offset, ptr,
6219 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6220 memset(map + pg_offset + copy_size, 0,
6221 PAGE_CACHE_SIZE - pg_offset -
6226 flush_dcache_page(page);
6227 } else if (create && PageUptodate(page)) {
6231 free_extent_map(em);
6234 btrfs_release_path(path);
6235 trans = btrfs_join_transaction(root);
6238 return ERR_CAST(trans);
6242 write_extent_buffer(leaf, map + pg_offset, ptr,
6245 btrfs_mark_buffer_dirty(leaf);
6247 set_extent_uptodate(io_tree, em->start,
6248 extent_map_end(em) - 1, NULL, GFP_NOFS);
6251 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6255 em->orig_start = start;
6258 em->block_start = EXTENT_MAP_HOLE;
6259 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6261 btrfs_release_path(path);
6262 if (em->start > start || extent_map_end(em) <= start) {
6263 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
6264 "[%llu %llu]\n", (unsigned long long)em->start,
6265 (unsigned long long)em->len,
6266 (unsigned long long)start,
6267 (unsigned long long)len);
6273 write_lock(&em_tree->lock);
6274 ret = add_extent_mapping(em_tree, em);
6275 /* it is possible that someone inserted the extent into the tree
6276 * while we had the lock dropped. It is also possible that
6277 * an overlapping map exists in the tree
6279 if (ret == -EEXIST) {
6280 struct extent_map *existing;
6284 existing = lookup_extent_mapping(em_tree, start, len);
6285 if (existing && (existing->start > start ||
6286 existing->start + existing->len <= start)) {
6287 free_extent_map(existing);
6291 existing = lookup_extent_mapping(em_tree, em->start,
6294 err = merge_extent_mapping(em_tree, existing,
6297 free_extent_map(existing);
6299 free_extent_map(em);
6304 free_extent_map(em);
6308 free_extent_map(em);
6313 write_unlock(&em_tree->lock);
6317 trace_btrfs_get_extent(root, em);
6320 btrfs_free_path(path);
6322 ret = btrfs_end_transaction(trans, root);
6327 free_extent_map(em);
6328 return ERR_PTR(err);
6330 BUG_ON(!em); /* Error is always set */
6334 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6335 size_t pg_offset, u64 start, u64 len,
6338 struct extent_map *em;
6339 struct extent_map *hole_em = NULL;
6340 u64 range_start = start;
6346 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6353 * - a pre-alloc extent,
6354 * there might actually be delalloc bytes behind it.
6356 if (em->block_start != EXTENT_MAP_HOLE &&
6357 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6363 /* check to see if we've wrapped (len == -1 or similar) */
6372 /* ok, we didn't find anything, lets look for delalloc */
6373 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6374 end, len, EXTENT_DELALLOC, 1);
6375 found_end = range_start + found;
6376 if (found_end < range_start)
6377 found_end = (u64)-1;
6380 * we didn't find anything useful, return
6381 * the original results from get_extent()
6383 if (range_start > end || found_end <= start) {
6389 /* adjust the range_start to make sure it doesn't
6390 * go backwards from the start they passed in
6392 range_start = max(start,range_start);
6393 found = found_end - range_start;
6396 u64 hole_start = start;
6399 em = alloc_extent_map();
6405 * when btrfs_get_extent can't find anything it
6406 * returns one huge hole
6408 * make sure what it found really fits our range, and
6409 * adjust to make sure it is based on the start from
6413 u64 calc_end = extent_map_end(hole_em);
6415 if (calc_end <= start || (hole_em->start > end)) {
6416 free_extent_map(hole_em);
6419 hole_start = max(hole_em->start, start);
6420 hole_len = calc_end - hole_start;
6424 if (hole_em && range_start > hole_start) {
6425 /* our hole starts before our delalloc, so we
6426 * have to return just the parts of the hole
6427 * that go until the delalloc starts
6429 em->len = min(hole_len,
6430 range_start - hole_start);
6431 em->start = hole_start;
6432 em->orig_start = hole_start;
6434 * don't adjust block start at all,
6435 * it is fixed at EXTENT_MAP_HOLE
6437 em->block_start = hole_em->block_start;
6438 em->block_len = hole_len;
6439 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6440 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6442 em->start = range_start;
6444 em->orig_start = range_start;
6445 em->block_start = EXTENT_MAP_DELALLOC;
6446 em->block_len = found;
6448 } else if (hole_em) {
6453 free_extent_map(hole_em);
6455 free_extent_map(em);
6456 return ERR_PTR(err);
6461 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6464 struct btrfs_root *root = BTRFS_I(inode)->root;
6465 struct btrfs_trans_handle *trans;
6466 struct extent_map *em;
6467 struct btrfs_key ins;
6471 trans = btrfs_join_transaction(root);
6473 return ERR_CAST(trans);
6475 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6477 alloc_hint = get_extent_allocation_hint(inode, start, len);
6478 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6479 alloc_hint, &ins, 1);
6485 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6486 ins.offset, ins.offset, 0);
6490 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6491 ins.offset, ins.offset, 0);
6493 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6497 btrfs_end_transaction(trans, root);
6502 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6503 * block must be cow'd
6505 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
6506 struct inode *inode, u64 offset, u64 len)
6508 struct btrfs_path *path;
6510 struct extent_buffer *leaf;
6511 struct btrfs_root *root = BTRFS_I(inode)->root;
6512 struct btrfs_file_extent_item *fi;
6513 struct btrfs_key key;
6521 path = btrfs_alloc_path();
6525 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6530 slot = path->slots[0];
6533 /* can't find the item, must cow */
6540 leaf = path->nodes[0];
6541 btrfs_item_key_to_cpu(leaf, &key, slot);
6542 if (key.objectid != btrfs_ino(inode) ||
6543 key.type != BTRFS_EXTENT_DATA_KEY) {
6544 /* not our file or wrong item type, must cow */
6548 if (key.offset > offset) {
6549 /* Wrong offset, must cow */
6553 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6554 found_type = btrfs_file_extent_type(leaf, fi);
6555 if (found_type != BTRFS_FILE_EXTENT_REG &&
6556 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6557 /* not a regular extent, must cow */
6560 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6561 backref_offset = btrfs_file_extent_offset(leaf, fi);
6563 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6564 if (extent_end < offset + len) {
6565 /* extent doesn't include our full range, must cow */
6569 if (btrfs_extent_readonly(root, disk_bytenr))
6573 * look for other files referencing this extent, if we
6574 * find any we must cow
6576 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6577 key.offset - backref_offset, disk_bytenr))
6581 * adjust disk_bytenr and num_bytes to cover just the bytes
6582 * in this extent we are about to write. If there
6583 * are any csums in that range we have to cow in order
6584 * to keep the csums correct
6586 disk_bytenr += backref_offset;
6587 disk_bytenr += offset - key.offset;
6588 num_bytes = min(offset + len, extent_end) - offset;
6589 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6592 * all of the above have passed, it is safe to overwrite this extent
6597 btrfs_free_path(path);
6601 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6602 struct extent_state **cached_state, int writing)
6604 struct btrfs_ordered_extent *ordered;
6608 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6611 * We're concerned with the entire range that we're going to be
6612 * doing DIO to, so we need to make sure theres no ordered
6613 * extents in this range.
6615 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6616 lockend - lockstart + 1);
6619 * We need to make sure there are no buffered pages in this
6620 * range either, we could have raced between the invalidate in
6621 * generic_file_direct_write and locking the extent. The
6622 * invalidate needs to happen so that reads after a write do not
6625 if (!ordered && (!writing ||
6626 !test_range_bit(&BTRFS_I(inode)->io_tree,
6627 lockstart, lockend, EXTENT_UPTODATE, 0,
6631 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6632 cached_state, GFP_NOFS);
6635 btrfs_start_ordered_extent(inode, ordered, 1);
6636 btrfs_put_ordered_extent(ordered);
6638 /* Screw you mmap */
6639 ret = filemap_write_and_wait_range(inode->i_mapping,
6646 * If we found a page that couldn't be invalidated just
6647 * fall back to buffered.
6649 ret = invalidate_inode_pages2_range(inode->i_mapping,
6650 lockstart >> PAGE_CACHE_SHIFT,
6651 lockend >> PAGE_CACHE_SHIFT);
6662 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6663 u64 len, u64 orig_start,
6664 u64 block_start, u64 block_len,
6665 u64 orig_block_len, int type)
6667 struct extent_map_tree *em_tree;
6668 struct extent_map *em;
6669 struct btrfs_root *root = BTRFS_I(inode)->root;
6672 em_tree = &BTRFS_I(inode)->extent_tree;
6673 em = alloc_extent_map();
6675 return ERR_PTR(-ENOMEM);
6678 em->orig_start = orig_start;
6679 em->mod_start = start;
6682 em->block_len = block_len;
6683 em->block_start = block_start;
6684 em->bdev = root->fs_info->fs_devices->latest_bdev;
6685 em->orig_block_len = orig_block_len;
6686 em->generation = -1;
6687 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6688 if (type == BTRFS_ORDERED_PREALLOC)
6689 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6692 btrfs_drop_extent_cache(inode, em->start,
6693 em->start + em->len - 1, 0);
6694 write_lock(&em_tree->lock);
6695 ret = add_extent_mapping(em_tree, em);
6697 list_move(&em->list,
6698 &em_tree->modified_extents);
6699 write_unlock(&em_tree->lock);
6700 } while (ret == -EEXIST);
6703 free_extent_map(em);
6704 return ERR_PTR(ret);
6711 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6712 struct buffer_head *bh_result, int create)
6714 struct extent_map *em;
6715 struct btrfs_root *root = BTRFS_I(inode)->root;
6716 struct extent_state *cached_state = NULL;
6717 u64 start = iblock << inode->i_blkbits;
6718 u64 lockstart, lockend;
6719 u64 len = bh_result->b_size;
6720 struct btrfs_trans_handle *trans;
6721 int unlock_bits = EXTENT_LOCKED;
6725 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6727 len = min_t(u64, len, root->sectorsize);
6730 lockend = start + len - 1;
6733 * If this errors out it's because we couldn't invalidate pagecache for
6734 * this range and we need to fallback to buffered.
6736 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6739 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6746 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6747 * io. INLINE is special, and we could probably kludge it in here, but
6748 * it's still buffered so for safety lets just fall back to the generic
6751 * For COMPRESSED we _have_ to read the entire extent in so we can
6752 * decompress it, so there will be buffering required no matter what we
6753 * do, so go ahead and fallback to buffered.
6755 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6756 * to buffered IO. Don't blame me, this is the price we pay for using
6759 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6760 em->block_start == EXTENT_MAP_INLINE) {
6761 free_extent_map(em);
6766 /* Just a good old fashioned hole, return */
6767 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6768 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6769 free_extent_map(em);
6774 * We don't allocate a new extent in the following cases
6776 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6778 * 2) The extent is marked as PREALLOC. We're good to go here and can
6779 * just use the extent.
6783 len = min(len, em->len - (start - em->start));
6784 lockstart = start + len;
6788 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6789 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6790 em->block_start != EXTENT_MAP_HOLE)) {
6795 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6796 type = BTRFS_ORDERED_PREALLOC;
6798 type = BTRFS_ORDERED_NOCOW;
6799 len = min(len, em->len - (start - em->start));
6800 block_start = em->block_start + (start - em->start);
6803 * we're not going to log anything, but we do need
6804 * to make sure the current transaction stays open
6805 * while we look for nocow cross refs
6807 trans = btrfs_join_transaction(root);
6811 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6812 u64 orig_start = em->orig_start;
6813 u64 orig_block_len = em->orig_block_len;
6815 if (type == BTRFS_ORDERED_PREALLOC) {
6816 free_extent_map(em);
6817 em = create_pinned_em(inode, start, len,
6820 orig_block_len, type);
6822 btrfs_end_transaction(trans, root);
6827 ret = btrfs_add_ordered_extent_dio(inode, start,
6828 block_start, len, len, type);
6829 btrfs_end_transaction(trans, root);
6831 free_extent_map(em);
6836 btrfs_end_transaction(trans, root);
6840 * this will cow the extent, reset the len in case we changed
6843 len = bh_result->b_size;
6844 free_extent_map(em);
6845 em = btrfs_new_extent_direct(inode, start, len);
6850 len = min(len, em->len - (start - em->start));
6852 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6854 bh_result->b_size = len;
6855 bh_result->b_bdev = em->bdev;
6856 set_buffer_mapped(bh_result);
6858 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6859 set_buffer_new(bh_result);
6862 * Need to update the i_size under the extent lock so buffered
6863 * readers will get the updated i_size when we unlock.
6865 if (start + len > i_size_read(inode))
6866 i_size_write(inode, start + len);
6868 spin_lock(&BTRFS_I(inode)->lock);
6869 BTRFS_I(inode)->outstanding_extents++;
6870 spin_unlock(&BTRFS_I(inode)->lock);
6872 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6873 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6874 &cached_state, GFP_NOFS);
6879 * In the case of write we need to clear and unlock the entire range,
6880 * in the case of read we need to unlock only the end area that we
6881 * aren't using if there is any left over space.
6883 if (lockstart < lockend) {
6884 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6885 lockend, unlock_bits, 1, 0,
6886 &cached_state, GFP_NOFS);
6888 free_extent_state(cached_state);
6891 free_extent_map(em);
6896 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6897 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6901 struct btrfs_dio_private {
6902 struct inode *inode;
6908 /* number of bios pending for this dio */
6909 atomic_t pending_bios;
6914 struct bio *orig_bio;
6917 static void btrfs_endio_direct_read(struct bio *bio, int err)
6919 struct btrfs_dio_private *dip = bio->bi_private;
6920 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6921 struct bio_vec *bvec = bio->bi_io_vec;
6922 struct inode *inode = dip->inode;
6923 struct btrfs_root *root = BTRFS_I(inode)->root;
6926 start = dip->logical_offset;
6928 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6929 struct page *page = bvec->bv_page;
6932 u64 private = ~(u32)0;
6933 unsigned long flags;
6935 if (get_state_private(&BTRFS_I(inode)->io_tree,
6938 local_irq_save(flags);
6939 kaddr = kmap_atomic(page);
6940 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
6941 csum, bvec->bv_len);
6942 btrfs_csum_final(csum, (char *)&csum);
6943 kunmap_atomic(kaddr);
6944 local_irq_restore(flags);
6946 flush_dcache_page(bvec->bv_page);
6947 if (csum != private) {
6949 printk(KERN_ERR "btrfs csum failed ino %llu off"
6950 " %llu csum %u private %u\n",
6951 (unsigned long long)btrfs_ino(inode),
6952 (unsigned long long)start,
6953 csum, (unsigned)private);
6958 start += bvec->bv_len;
6960 } while (bvec <= bvec_end);
6962 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6963 dip->logical_offset + dip->bytes - 1);
6964 bio->bi_private = dip->private;
6968 /* If we had a csum failure make sure to clear the uptodate flag */
6970 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6971 dio_end_io(bio, err);
6974 static void btrfs_endio_direct_write(struct bio *bio, int err)
6976 struct btrfs_dio_private *dip = bio->bi_private;
6977 struct inode *inode = dip->inode;
6978 struct btrfs_root *root = BTRFS_I(inode)->root;
6979 struct btrfs_ordered_extent *ordered = NULL;
6980 u64 ordered_offset = dip->logical_offset;
6981 u64 ordered_bytes = dip->bytes;
6987 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6989 ordered_bytes, !err);
6993 ordered->work.func = finish_ordered_fn;
6994 ordered->work.flags = 0;
6995 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6999 * our bio might span multiple ordered extents. If we haven't
7000 * completed the accounting for the whole dio, go back and try again
7002 if (ordered_offset < dip->logical_offset + dip->bytes) {
7003 ordered_bytes = dip->logical_offset + dip->bytes -
7009 bio->bi_private = dip->private;
7013 /* If we had an error make sure to clear the uptodate flag */
7015 clear_bit(BIO_UPTODATE, &bio->bi_flags);
7016 dio_end_io(bio, err);
7019 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7020 struct bio *bio, int mirror_num,
7021 unsigned long bio_flags, u64 offset)
7024 struct btrfs_root *root = BTRFS_I(inode)->root;
7025 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7026 BUG_ON(ret); /* -ENOMEM */
7030 static void btrfs_end_dio_bio(struct bio *bio, int err)
7032 struct btrfs_dio_private *dip = bio->bi_private;
7035 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
7036 "sector %#Lx len %u err no %d\n",
7037 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
7038 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7042 * before atomic variable goto zero, we must make sure
7043 * dip->errors is perceived to be set.
7045 smp_mb__before_atomic_dec();
7048 /* if there are more bios still pending for this dio, just exit */
7049 if (!atomic_dec_and_test(&dip->pending_bios))
7053 bio_io_error(dip->orig_bio);
7055 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
7056 bio_endio(dip->orig_bio, 0);
7062 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7063 u64 first_sector, gfp_t gfp_flags)
7065 int nr_vecs = bio_get_nr_vecs(bdev);
7066 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7069 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7070 int rw, u64 file_offset, int skip_sum,
7073 int write = rw & REQ_WRITE;
7074 struct btrfs_root *root = BTRFS_I(inode)->root;
7078 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7083 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7091 if (write && async_submit) {
7092 ret = btrfs_wq_submit_bio(root->fs_info,
7093 inode, rw, bio, 0, 0,
7095 __btrfs_submit_bio_start_direct_io,
7096 __btrfs_submit_bio_done);
7100 * If we aren't doing async submit, calculate the csum of the
7103 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7106 } else if (!skip_sum) {
7107 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
7113 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7119 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7122 struct inode *inode = dip->inode;
7123 struct btrfs_root *root = BTRFS_I(inode)->root;
7125 struct bio *orig_bio = dip->orig_bio;
7126 struct bio_vec *bvec = orig_bio->bi_io_vec;
7127 u64 start_sector = orig_bio->bi_sector;
7128 u64 file_offset = dip->logical_offset;
7133 int async_submit = 0;
7135 map_length = orig_bio->bi_size;
7136 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7137 &map_length, NULL, 0);
7142 if (map_length >= orig_bio->bi_size) {
7147 /* async crcs make it difficult to collect full stripe writes. */
7148 if (btrfs_get_alloc_profile(root, 1) &
7149 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7154 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7157 bio->bi_private = dip;
7158 bio->bi_end_io = btrfs_end_dio_bio;
7159 atomic_inc(&dip->pending_bios);
7161 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7162 if (unlikely(map_length < submit_len + bvec->bv_len ||
7163 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7164 bvec->bv_offset) < bvec->bv_len)) {
7166 * inc the count before we submit the bio so
7167 * we know the end IO handler won't happen before
7168 * we inc the count. Otherwise, the dip might get freed
7169 * before we're done setting it up
7171 atomic_inc(&dip->pending_bios);
7172 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7173 file_offset, skip_sum,
7177 atomic_dec(&dip->pending_bios);
7181 start_sector += submit_len >> 9;
7182 file_offset += submit_len;
7187 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7188 start_sector, GFP_NOFS);
7191 bio->bi_private = dip;
7192 bio->bi_end_io = btrfs_end_dio_bio;
7194 map_length = orig_bio->bi_size;
7195 ret = btrfs_map_block(root->fs_info, rw,
7197 &map_length, NULL, 0);
7203 submit_len += bvec->bv_len;
7210 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7219 * before atomic variable goto zero, we must
7220 * make sure dip->errors is perceived to be set.
7222 smp_mb__before_atomic_dec();
7223 if (atomic_dec_and_test(&dip->pending_bios))
7224 bio_io_error(dip->orig_bio);
7226 /* bio_end_io() will handle error, so we needn't return it */
7230 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
7233 struct btrfs_root *root = BTRFS_I(inode)->root;
7234 struct btrfs_dio_private *dip;
7235 struct bio_vec *bvec = bio->bi_io_vec;
7237 int write = rw & REQ_WRITE;
7240 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7242 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7248 dip->private = bio->bi_private;
7250 dip->logical_offset = file_offset;
7254 dip->bytes += bvec->bv_len;
7256 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
7258 dip->disk_bytenr = (u64)bio->bi_sector << 9;
7259 bio->bi_private = dip;
7261 dip->orig_bio = bio;
7262 atomic_set(&dip->pending_bios, 0);
7265 bio->bi_end_io = btrfs_endio_direct_write;
7267 bio->bi_end_io = btrfs_endio_direct_read;
7269 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7274 * If this is a write, we need to clean up the reserved space and kill
7275 * the ordered extent.
7278 struct btrfs_ordered_extent *ordered;
7279 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7280 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7281 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7282 btrfs_free_reserved_extent(root, ordered->start,
7284 btrfs_put_ordered_extent(ordered);
7285 btrfs_put_ordered_extent(ordered);
7287 bio_endio(bio, ret);
7290 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7291 const struct iovec *iov, loff_t offset,
7292 unsigned long nr_segs)
7298 unsigned blocksize_mask = root->sectorsize - 1;
7299 ssize_t retval = -EINVAL;
7300 loff_t end = offset;
7302 if (offset & blocksize_mask)
7305 /* Check the memory alignment. Blocks cannot straddle pages */
7306 for (seg = 0; seg < nr_segs; seg++) {
7307 addr = (unsigned long)iov[seg].iov_base;
7308 size = iov[seg].iov_len;
7310 if ((addr & blocksize_mask) || (size & blocksize_mask))
7313 /* If this is a write we don't need to check anymore */
7318 * Check to make sure we don't have duplicate iov_base's in this
7319 * iovec, if so return EINVAL, otherwise we'll get csum errors
7320 * when reading back.
7322 for (i = seg + 1; i < nr_segs; i++) {
7323 if (iov[seg].iov_base == iov[i].iov_base)
7332 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7333 const struct iovec *iov, loff_t offset,
7334 unsigned long nr_segs)
7336 struct file *file = iocb->ki_filp;
7337 struct inode *inode = file->f_mapping->host;
7341 bool relock = false;
7344 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7348 atomic_inc(&inode->i_dio_count);
7349 smp_mb__after_atomic_inc();
7352 count = iov_length(iov, nr_segs);
7354 * If the write DIO is beyond the EOF, we need update
7355 * the isize, but it is protected by i_mutex. So we can
7356 * not unlock the i_mutex at this case.
7358 if (offset + count <= inode->i_size) {
7359 mutex_unlock(&inode->i_mutex);
7362 ret = btrfs_delalloc_reserve_space(inode, count);
7365 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7366 &BTRFS_I(inode)->runtime_flags))) {
7367 inode_dio_done(inode);
7368 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7372 ret = __blockdev_direct_IO(rw, iocb, inode,
7373 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7374 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7375 btrfs_submit_direct, flags);
7377 if (ret < 0 && ret != -EIOCBQUEUED)
7378 btrfs_delalloc_release_space(inode, count);
7379 else if (ret >= 0 && (size_t)ret < count)
7380 btrfs_delalloc_release_space(inode,
7381 count - (size_t)ret);
7383 btrfs_delalloc_release_metadata(inode, 0);
7387 inode_dio_done(inode);
7389 mutex_lock(&inode->i_mutex);
7394 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7396 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7397 __u64 start, __u64 len)
7401 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7405 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7408 int btrfs_readpage(struct file *file, struct page *page)
7410 struct extent_io_tree *tree;
7411 tree = &BTRFS_I(page->mapping->host)->io_tree;
7412 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7415 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7417 struct extent_io_tree *tree;
7420 if (current->flags & PF_MEMALLOC) {
7421 redirty_page_for_writepage(wbc, page);
7425 tree = &BTRFS_I(page->mapping->host)->io_tree;
7426 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7429 int btrfs_writepages(struct address_space *mapping,
7430 struct writeback_control *wbc)
7432 struct extent_io_tree *tree;
7434 tree = &BTRFS_I(mapping->host)->io_tree;
7435 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7439 btrfs_readpages(struct file *file, struct address_space *mapping,
7440 struct list_head *pages, unsigned nr_pages)
7442 struct extent_io_tree *tree;
7443 tree = &BTRFS_I(mapping->host)->io_tree;
7444 return extent_readpages(tree, mapping, pages, nr_pages,
7447 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7449 struct extent_io_tree *tree;
7450 struct extent_map_tree *map;
7453 tree = &BTRFS_I(page->mapping->host)->io_tree;
7454 map = &BTRFS_I(page->mapping->host)->extent_tree;
7455 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7457 ClearPagePrivate(page);
7458 set_page_private(page, 0);
7459 page_cache_release(page);
7464 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7466 if (PageWriteback(page) || PageDirty(page))
7468 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7471 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7473 struct inode *inode = page->mapping->host;
7474 struct extent_io_tree *tree;
7475 struct btrfs_ordered_extent *ordered;
7476 struct extent_state *cached_state = NULL;
7477 u64 page_start = page_offset(page);
7478 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7481 * we have the page locked, so new writeback can't start,
7482 * and the dirty bit won't be cleared while we are here.
7484 * Wait for IO on this page so that we can safely clear
7485 * the PagePrivate2 bit and do ordered accounting
7487 wait_on_page_writeback(page);
7489 tree = &BTRFS_I(inode)->io_tree;
7491 btrfs_releasepage(page, GFP_NOFS);
7494 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7495 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7498 * IO on this page will never be started, so we need
7499 * to account for any ordered extents now
7501 clear_extent_bit(tree, page_start, page_end,
7502 EXTENT_DIRTY | EXTENT_DELALLOC |
7503 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7504 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7506 * whoever cleared the private bit is responsible
7507 * for the finish_ordered_io
7509 if (TestClearPagePrivate2(page) &&
7510 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7511 PAGE_CACHE_SIZE, 1)) {
7512 btrfs_finish_ordered_io(ordered);
7514 btrfs_put_ordered_extent(ordered);
7515 cached_state = NULL;
7516 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7518 clear_extent_bit(tree, page_start, page_end,
7519 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7520 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7521 &cached_state, GFP_NOFS);
7522 __btrfs_releasepage(page, GFP_NOFS);
7524 ClearPageChecked(page);
7525 if (PagePrivate(page)) {
7526 ClearPagePrivate(page);
7527 set_page_private(page, 0);
7528 page_cache_release(page);
7533 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7534 * called from a page fault handler when a page is first dirtied. Hence we must
7535 * be careful to check for EOF conditions here. We set the page up correctly
7536 * for a written page which means we get ENOSPC checking when writing into
7537 * holes and correct delalloc and unwritten extent mapping on filesystems that
7538 * support these features.
7540 * We are not allowed to take the i_mutex here so we have to play games to
7541 * protect against truncate races as the page could now be beyond EOF. Because
7542 * vmtruncate() writes the inode size before removing pages, once we have the
7543 * page lock we can determine safely if the page is beyond EOF. If it is not
7544 * beyond EOF, then the page is guaranteed safe against truncation until we
7547 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7549 struct page *page = vmf->page;
7550 struct inode *inode = file_inode(vma->vm_file);
7551 struct btrfs_root *root = BTRFS_I(inode)->root;
7552 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7553 struct btrfs_ordered_extent *ordered;
7554 struct extent_state *cached_state = NULL;
7556 unsigned long zero_start;
7563 sb_start_pagefault(inode->i_sb);
7564 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7566 ret = file_update_time(vma->vm_file);
7572 else /* -ENOSPC, -EIO, etc */
7573 ret = VM_FAULT_SIGBUS;
7579 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7582 size = i_size_read(inode);
7583 page_start = page_offset(page);
7584 page_end = page_start + PAGE_CACHE_SIZE - 1;
7586 if ((page->mapping != inode->i_mapping) ||
7587 (page_start >= size)) {
7588 /* page got truncated out from underneath us */
7591 wait_on_page_writeback(page);
7593 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7594 set_page_extent_mapped(page);
7597 * we can't set the delalloc bits if there are pending ordered
7598 * extents. Drop our locks and wait for them to finish
7600 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7602 unlock_extent_cached(io_tree, page_start, page_end,
7603 &cached_state, GFP_NOFS);
7605 btrfs_start_ordered_extent(inode, ordered, 1);
7606 btrfs_put_ordered_extent(ordered);
7611 * XXX - page_mkwrite gets called every time the page is dirtied, even
7612 * if it was already dirty, so for space accounting reasons we need to
7613 * clear any delalloc bits for the range we are fixing to save. There
7614 * is probably a better way to do this, but for now keep consistent with
7615 * prepare_pages in the normal write path.
7617 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7618 EXTENT_DIRTY | EXTENT_DELALLOC |
7619 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7620 0, 0, &cached_state, GFP_NOFS);
7622 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7625 unlock_extent_cached(io_tree, page_start, page_end,
7626 &cached_state, GFP_NOFS);
7627 ret = VM_FAULT_SIGBUS;
7632 /* page is wholly or partially inside EOF */
7633 if (page_start + PAGE_CACHE_SIZE > size)
7634 zero_start = size & ~PAGE_CACHE_MASK;
7636 zero_start = PAGE_CACHE_SIZE;
7638 if (zero_start != PAGE_CACHE_SIZE) {
7640 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7641 flush_dcache_page(page);
7644 ClearPageChecked(page);
7645 set_page_dirty(page);
7646 SetPageUptodate(page);
7648 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7649 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7650 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7652 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7656 sb_end_pagefault(inode->i_sb);
7657 return VM_FAULT_LOCKED;
7661 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7663 sb_end_pagefault(inode->i_sb);
7667 static int btrfs_truncate(struct inode *inode)
7669 struct btrfs_root *root = BTRFS_I(inode)->root;
7670 struct btrfs_block_rsv *rsv;
7673 struct btrfs_trans_handle *trans;
7674 u64 mask = root->sectorsize - 1;
7675 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7677 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
7681 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7682 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7685 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7686 * 3 things going on here
7688 * 1) We need to reserve space for our orphan item and the space to
7689 * delete our orphan item. Lord knows we don't want to have a dangling
7690 * orphan item because we didn't reserve space to remove it.
7692 * 2) We need to reserve space to update our inode.
7694 * 3) We need to have something to cache all the space that is going to
7695 * be free'd up by the truncate operation, but also have some slack
7696 * space reserved in case it uses space during the truncate (thank you
7697 * very much snapshotting).
7699 * And we need these to all be seperate. The fact is we can use alot of
7700 * space doing the truncate, and we have no earthly idea how much space
7701 * we will use, so we need the truncate reservation to be seperate so it
7702 * doesn't end up using space reserved for updating the inode or
7703 * removing the orphan item. We also need to be able to stop the
7704 * transaction and start a new one, which means we need to be able to
7705 * update the inode several times, and we have no idea of knowing how
7706 * many times that will be, so we can't just reserve 1 item for the
7707 * entirety of the opration, so that has to be done seperately as well.
7708 * Then there is the orphan item, which does indeed need to be held on
7709 * to for the whole operation, and we need nobody to touch this reserved
7710 * space except the orphan code.
7712 * So that leaves us with
7714 * 1) root->orphan_block_rsv - for the orphan deletion.
7715 * 2) rsv - for the truncate reservation, which we will steal from the
7716 * transaction reservation.
7717 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7718 * updating the inode.
7720 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7723 rsv->size = min_size;
7727 * 1 for the truncate slack space
7728 * 1 for updating the inode.
7730 trans = btrfs_start_transaction(root, 2);
7731 if (IS_ERR(trans)) {
7732 err = PTR_ERR(trans);
7736 /* Migrate the slack space for the truncate to our reserve */
7737 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7742 * setattr is responsible for setting the ordered_data_close flag,
7743 * but that is only tested during the last file release. That
7744 * could happen well after the next commit, leaving a great big
7745 * window where new writes may get lost if someone chooses to write
7746 * to this file after truncating to zero
7748 * The inode doesn't have any dirty data here, and so if we commit
7749 * this is a noop. If someone immediately starts writing to the inode
7750 * it is very likely we'll catch some of their writes in this
7751 * transaction, and the commit will find this file on the ordered
7752 * data list with good things to send down.
7754 * This is a best effort solution, there is still a window where
7755 * using truncate to replace the contents of the file will
7756 * end up with a zero length file after a crash.
7758 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7759 &BTRFS_I(inode)->runtime_flags))
7760 btrfs_add_ordered_operation(trans, root, inode);
7763 * So if we truncate and then write and fsync we normally would just
7764 * write the extents that changed, which is a problem if we need to
7765 * first truncate that entire inode. So set this flag so we write out
7766 * all of the extents in the inode to the sync log so we're completely
7769 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7770 trans->block_rsv = rsv;
7773 ret = btrfs_truncate_inode_items(trans, root, inode,
7775 BTRFS_EXTENT_DATA_KEY);
7776 if (ret != -ENOSPC) {
7781 trans->block_rsv = &root->fs_info->trans_block_rsv;
7782 ret = btrfs_update_inode(trans, root, inode);
7788 btrfs_end_transaction(trans, root);
7789 btrfs_btree_balance_dirty(root);
7791 trans = btrfs_start_transaction(root, 2);
7792 if (IS_ERR(trans)) {
7793 ret = err = PTR_ERR(trans);
7798 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7800 BUG_ON(ret); /* shouldn't happen */
7801 trans->block_rsv = rsv;
7804 if (ret == 0 && inode->i_nlink > 0) {
7805 trans->block_rsv = root->orphan_block_rsv;
7806 ret = btrfs_orphan_del(trans, inode);
7812 trans->block_rsv = &root->fs_info->trans_block_rsv;
7813 ret = btrfs_update_inode(trans, root, inode);
7817 ret = btrfs_end_transaction(trans, root);
7818 btrfs_btree_balance_dirty(root);
7822 btrfs_free_block_rsv(root, rsv);
7831 * create a new subvolume directory/inode (helper for the ioctl).
7833 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7834 struct btrfs_root *new_root, u64 new_dirid)
7836 struct inode *inode;
7840 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7841 new_dirid, new_dirid,
7842 S_IFDIR | (~current_umask() & S_IRWXUGO),
7845 return PTR_ERR(inode);
7846 inode->i_op = &btrfs_dir_inode_operations;
7847 inode->i_fop = &btrfs_dir_file_operations;
7849 set_nlink(inode, 1);
7850 btrfs_i_size_write(inode, 0);
7852 err = btrfs_update_inode(trans, new_root, inode);
7858 struct inode *btrfs_alloc_inode(struct super_block *sb)
7860 struct btrfs_inode *ei;
7861 struct inode *inode;
7863 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7870 ei->last_sub_trans = 0;
7871 ei->logged_trans = 0;
7872 ei->delalloc_bytes = 0;
7873 ei->disk_i_size = 0;
7876 ei->index_cnt = (u64)-1;
7877 ei->last_unlink_trans = 0;
7878 ei->last_log_commit = 0;
7880 spin_lock_init(&ei->lock);
7881 ei->outstanding_extents = 0;
7882 ei->reserved_extents = 0;
7884 ei->runtime_flags = 0;
7885 ei->force_compress = BTRFS_COMPRESS_NONE;
7887 ei->delayed_node = NULL;
7889 inode = &ei->vfs_inode;
7890 extent_map_tree_init(&ei->extent_tree);
7891 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7892 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7893 ei->io_tree.track_uptodate = 1;
7894 ei->io_failure_tree.track_uptodate = 1;
7895 atomic_set(&ei->sync_writers, 0);
7896 mutex_init(&ei->log_mutex);
7897 mutex_init(&ei->delalloc_mutex);
7898 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7899 INIT_LIST_HEAD(&ei->delalloc_inodes);
7900 INIT_LIST_HEAD(&ei->ordered_operations);
7901 RB_CLEAR_NODE(&ei->rb_node);
7906 static void btrfs_i_callback(struct rcu_head *head)
7908 struct inode *inode = container_of(head, struct inode, i_rcu);
7909 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7912 void btrfs_destroy_inode(struct inode *inode)
7914 struct btrfs_ordered_extent *ordered;
7915 struct btrfs_root *root = BTRFS_I(inode)->root;
7917 WARN_ON(!hlist_empty(&inode->i_dentry));
7918 WARN_ON(inode->i_data.nrpages);
7919 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7920 WARN_ON(BTRFS_I(inode)->reserved_extents);
7921 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7922 WARN_ON(BTRFS_I(inode)->csum_bytes);
7925 * This can happen where we create an inode, but somebody else also
7926 * created the same inode and we need to destroy the one we already
7933 * Make sure we're properly removed from the ordered operation
7937 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7938 spin_lock(&root->fs_info->ordered_extent_lock);
7939 list_del_init(&BTRFS_I(inode)->ordered_operations);
7940 spin_unlock(&root->fs_info->ordered_extent_lock);
7943 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7944 &BTRFS_I(inode)->runtime_flags)) {
7945 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
7946 (unsigned long long)btrfs_ino(inode));
7947 atomic_dec(&root->orphan_inodes);
7951 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7955 printk(KERN_ERR "btrfs found ordered "
7956 "extent %llu %llu on inode cleanup\n",
7957 (unsigned long long)ordered->file_offset,
7958 (unsigned long long)ordered->len);
7959 btrfs_remove_ordered_extent(inode, ordered);
7960 btrfs_put_ordered_extent(ordered);
7961 btrfs_put_ordered_extent(ordered);
7964 inode_tree_del(inode);
7965 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7967 btrfs_remove_delayed_node(inode);
7968 call_rcu(&inode->i_rcu, btrfs_i_callback);
7971 int btrfs_drop_inode(struct inode *inode)
7973 struct btrfs_root *root = BTRFS_I(inode)->root;
7975 /* the snap/subvol tree is on deleting */
7976 if (btrfs_root_refs(&root->root_item) == 0 &&
7977 root != root->fs_info->tree_root)
7980 return generic_drop_inode(inode);
7983 static void init_once(void *foo)
7985 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7987 inode_init_once(&ei->vfs_inode);
7990 void btrfs_destroy_cachep(void)
7993 * Make sure all delayed rcu free inodes are flushed before we
7997 if (btrfs_inode_cachep)
7998 kmem_cache_destroy(btrfs_inode_cachep);
7999 if (btrfs_trans_handle_cachep)
8000 kmem_cache_destroy(btrfs_trans_handle_cachep);
8001 if (btrfs_transaction_cachep)
8002 kmem_cache_destroy(btrfs_transaction_cachep);
8003 if (btrfs_path_cachep)
8004 kmem_cache_destroy(btrfs_path_cachep);
8005 if (btrfs_free_space_cachep)
8006 kmem_cache_destroy(btrfs_free_space_cachep);
8007 if (btrfs_delalloc_work_cachep)
8008 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8011 int btrfs_init_cachep(void)
8013 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8014 sizeof(struct btrfs_inode), 0,
8015 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8016 if (!btrfs_inode_cachep)
8019 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8020 sizeof(struct btrfs_trans_handle), 0,
8021 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8022 if (!btrfs_trans_handle_cachep)
8025 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8026 sizeof(struct btrfs_transaction), 0,
8027 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8028 if (!btrfs_transaction_cachep)
8031 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8032 sizeof(struct btrfs_path), 0,
8033 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8034 if (!btrfs_path_cachep)
8037 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8038 sizeof(struct btrfs_free_space), 0,
8039 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8040 if (!btrfs_free_space_cachep)
8043 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8044 sizeof(struct btrfs_delalloc_work), 0,
8045 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8047 if (!btrfs_delalloc_work_cachep)
8052 btrfs_destroy_cachep();
8056 static int btrfs_getattr(struct vfsmount *mnt,
8057 struct dentry *dentry, struct kstat *stat)
8060 struct inode *inode = dentry->d_inode;
8061 u32 blocksize = inode->i_sb->s_blocksize;
8063 generic_fillattr(inode, stat);
8064 stat->dev = BTRFS_I(inode)->root->anon_dev;
8065 stat->blksize = PAGE_CACHE_SIZE;
8067 spin_lock(&BTRFS_I(inode)->lock);
8068 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8069 spin_unlock(&BTRFS_I(inode)->lock);
8070 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8071 ALIGN(delalloc_bytes, blocksize)) >> 9;
8075 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8076 struct inode *new_dir, struct dentry *new_dentry)
8078 struct btrfs_trans_handle *trans;
8079 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8080 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8081 struct inode *new_inode = new_dentry->d_inode;
8082 struct inode *old_inode = old_dentry->d_inode;
8083 struct timespec ctime = CURRENT_TIME;
8087 u64 old_ino = btrfs_ino(old_inode);
8089 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8092 /* we only allow rename subvolume link between subvolumes */
8093 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8096 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8097 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8100 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8101 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8105 /* check for collisions, even if the name isn't there */
8106 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
8107 new_dentry->d_name.name,
8108 new_dentry->d_name.len);
8111 if (ret == -EEXIST) {
8113 * eexist without a new_inode */
8119 /* maybe -EOVERFLOW */
8126 * we're using rename to replace one file with another.
8127 * and the replacement file is large. Start IO on it now so
8128 * we don't add too much work to the end of the transaction
8130 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8131 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8132 filemap_flush(old_inode->i_mapping);
8134 /* close the racy window with snapshot create/destroy ioctl */
8135 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8136 down_read(&root->fs_info->subvol_sem);
8138 * We want to reserve the absolute worst case amount of items. So if
8139 * both inodes are subvols and we need to unlink them then that would
8140 * require 4 item modifications, but if they are both normal inodes it
8141 * would require 5 item modifications, so we'll assume their normal
8142 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8143 * should cover the worst case number of items we'll modify.
8145 trans = btrfs_start_transaction(root, 11);
8146 if (IS_ERR(trans)) {
8147 ret = PTR_ERR(trans);
8152 btrfs_record_root_in_trans(trans, dest);
8154 ret = btrfs_set_inode_index(new_dir, &index);
8158 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8159 /* force full log commit if subvolume involved. */
8160 root->fs_info->last_trans_log_full_commit = trans->transid;
8162 ret = btrfs_insert_inode_ref(trans, dest,
8163 new_dentry->d_name.name,
8164 new_dentry->d_name.len,
8166 btrfs_ino(new_dir), index);
8170 * this is an ugly little race, but the rename is required
8171 * to make sure that if we crash, the inode is either at the
8172 * old name or the new one. pinning the log transaction lets
8173 * us make sure we don't allow a log commit to come in after
8174 * we unlink the name but before we add the new name back in.
8176 btrfs_pin_log_trans(root);
8179 * make sure the inode gets flushed if it is replacing
8182 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8183 btrfs_add_ordered_operation(trans, root, old_inode);
8185 inode_inc_iversion(old_dir);
8186 inode_inc_iversion(new_dir);
8187 inode_inc_iversion(old_inode);
8188 old_dir->i_ctime = old_dir->i_mtime = ctime;
8189 new_dir->i_ctime = new_dir->i_mtime = ctime;
8190 old_inode->i_ctime = ctime;
8192 if (old_dentry->d_parent != new_dentry->d_parent)
8193 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8195 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8196 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8197 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8198 old_dentry->d_name.name,
8199 old_dentry->d_name.len);
8201 ret = __btrfs_unlink_inode(trans, root, old_dir,
8202 old_dentry->d_inode,
8203 old_dentry->d_name.name,
8204 old_dentry->d_name.len);
8206 ret = btrfs_update_inode(trans, root, old_inode);
8209 btrfs_abort_transaction(trans, root, ret);
8214 inode_inc_iversion(new_inode);
8215 new_inode->i_ctime = CURRENT_TIME;
8216 if (unlikely(btrfs_ino(new_inode) ==
8217 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8218 root_objectid = BTRFS_I(new_inode)->location.objectid;
8219 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8221 new_dentry->d_name.name,
8222 new_dentry->d_name.len);
8223 BUG_ON(new_inode->i_nlink == 0);
8225 ret = btrfs_unlink_inode(trans, dest, new_dir,
8226 new_dentry->d_inode,
8227 new_dentry->d_name.name,
8228 new_dentry->d_name.len);
8230 if (!ret && new_inode->i_nlink == 0) {
8231 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8235 btrfs_abort_transaction(trans, root, ret);
8240 ret = btrfs_add_link(trans, new_dir, old_inode,
8241 new_dentry->d_name.name,
8242 new_dentry->d_name.len, 0, index);
8244 btrfs_abort_transaction(trans, root, ret);
8248 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8249 struct dentry *parent = new_dentry->d_parent;
8250 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8251 btrfs_end_log_trans(root);
8254 btrfs_end_transaction(trans, root);
8256 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8257 up_read(&root->fs_info->subvol_sem);
8262 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8264 struct btrfs_delalloc_work *delalloc_work;
8266 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8268 if (delalloc_work->wait)
8269 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8271 filemap_flush(delalloc_work->inode->i_mapping);
8273 if (delalloc_work->delay_iput)
8274 btrfs_add_delayed_iput(delalloc_work->inode);
8276 iput(delalloc_work->inode);
8277 complete(&delalloc_work->completion);
8280 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8281 int wait, int delay_iput)
8283 struct btrfs_delalloc_work *work;
8285 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8289 init_completion(&work->completion);
8290 INIT_LIST_HEAD(&work->list);
8291 work->inode = inode;
8293 work->delay_iput = delay_iput;
8294 work->work.func = btrfs_run_delalloc_work;
8299 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8301 wait_for_completion(&work->completion);
8302 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8306 * some fairly slow code that needs optimization. This walks the list
8307 * of all the inodes with pending delalloc and forces them to disk.
8309 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8311 struct btrfs_inode *binode;
8312 struct inode *inode;
8313 struct btrfs_delalloc_work *work, *next;
8314 struct list_head works;
8315 struct list_head splice;
8318 if (root->fs_info->sb->s_flags & MS_RDONLY)
8321 INIT_LIST_HEAD(&works);
8322 INIT_LIST_HEAD(&splice);
8324 spin_lock(&root->fs_info->delalloc_lock);
8325 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
8326 while (!list_empty(&splice)) {
8327 binode = list_entry(splice.next, struct btrfs_inode,
8330 list_del_init(&binode->delalloc_inodes);
8332 inode = igrab(&binode->vfs_inode);
8334 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
8335 &binode->runtime_flags);
8339 list_add_tail(&binode->delalloc_inodes,
8340 &root->fs_info->delalloc_inodes);
8341 spin_unlock(&root->fs_info->delalloc_lock);
8343 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8344 if (unlikely(!work)) {
8348 list_add_tail(&work->list, &works);
8349 btrfs_queue_worker(&root->fs_info->flush_workers,
8353 spin_lock(&root->fs_info->delalloc_lock);
8355 spin_unlock(&root->fs_info->delalloc_lock);
8357 list_for_each_entry_safe(work, next, &works, list) {
8358 list_del_init(&work->list);
8359 btrfs_wait_and_free_delalloc_work(work);
8362 /* the filemap_flush will queue IO into the worker threads, but
8363 * we have to make sure the IO is actually started and that
8364 * ordered extents get created before we return
8366 atomic_inc(&root->fs_info->async_submit_draining);
8367 while (atomic_read(&root->fs_info->nr_async_submits) ||
8368 atomic_read(&root->fs_info->async_delalloc_pages)) {
8369 wait_event(root->fs_info->async_submit_wait,
8370 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8371 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8373 atomic_dec(&root->fs_info->async_submit_draining);
8376 list_for_each_entry_safe(work, next, &works, list) {
8377 list_del_init(&work->list);
8378 btrfs_wait_and_free_delalloc_work(work);
8381 if (!list_empty_careful(&splice)) {
8382 spin_lock(&root->fs_info->delalloc_lock);
8383 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
8384 spin_unlock(&root->fs_info->delalloc_lock);
8389 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8390 const char *symname)
8392 struct btrfs_trans_handle *trans;
8393 struct btrfs_root *root = BTRFS_I(dir)->root;
8394 struct btrfs_path *path;
8395 struct btrfs_key key;
8396 struct inode *inode = NULL;
8404 struct btrfs_file_extent_item *ei;
8405 struct extent_buffer *leaf;
8407 name_len = strlen(symname) + 1;
8408 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8409 return -ENAMETOOLONG;
8412 * 2 items for inode item and ref
8413 * 2 items for dir items
8414 * 1 item for xattr if selinux is on
8416 trans = btrfs_start_transaction(root, 5);
8418 return PTR_ERR(trans);
8420 err = btrfs_find_free_ino(root, &objectid);
8424 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8425 dentry->d_name.len, btrfs_ino(dir), objectid,
8426 S_IFLNK|S_IRWXUGO, &index);
8427 if (IS_ERR(inode)) {
8428 err = PTR_ERR(inode);
8432 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8439 * If the active LSM wants to access the inode during
8440 * d_instantiate it needs these. Smack checks to see
8441 * if the filesystem supports xattrs by looking at the
8444 inode->i_fop = &btrfs_file_operations;
8445 inode->i_op = &btrfs_file_inode_operations;
8447 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8451 inode->i_mapping->a_ops = &btrfs_aops;
8452 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8453 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8458 path = btrfs_alloc_path();
8464 key.objectid = btrfs_ino(inode);
8466 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8467 datasize = btrfs_file_extent_calc_inline_size(name_len);
8468 err = btrfs_insert_empty_item(trans, root, path, &key,
8472 btrfs_free_path(path);
8475 leaf = path->nodes[0];
8476 ei = btrfs_item_ptr(leaf, path->slots[0],
8477 struct btrfs_file_extent_item);
8478 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8479 btrfs_set_file_extent_type(leaf, ei,
8480 BTRFS_FILE_EXTENT_INLINE);
8481 btrfs_set_file_extent_encryption(leaf, ei, 0);
8482 btrfs_set_file_extent_compression(leaf, ei, 0);
8483 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8484 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8486 ptr = btrfs_file_extent_inline_start(ei);
8487 write_extent_buffer(leaf, symname, ptr, name_len);
8488 btrfs_mark_buffer_dirty(leaf);
8489 btrfs_free_path(path);
8491 inode->i_op = &btrfs_symlink_inode_operations;
8492 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8493 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8494 inode_set_bytes(inode, name_len);
8495 btrfs_i_size_write(inode, name_len - 1);
8496 err = btrfs_update_inode(trans, root, inode);
8502 d_instantiate(dentry, inode);
8503 btrfs_end_transaction(trans, root);
8505 inode_dec_link_count(inode);
8508 btrfs_btree_balance_dirty(root);
8512 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8513 u64 start, u64 num_bytes, u64 min_size,
8514 loff_t actual_len, u64 *alloc_hint,
8515 struct btrfs_trans_handle *trans)
8517 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8518 struct extent_map *em;
8519 struct btrfs_root *root = BTRFS_I(inode)->root;
8520 struct btrfs_key ins;
8521 u64 cur_offset = start;
8525 bool own_trans = true;
8529 while (num_bytes > 0) {
8531 trans = btrfs_start_transaction(root, 3);
8532 if (IS_ERR(trans)) {
8533 ret = PTR_ERR(trans);
8538 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8539 cur_bytes = max(cur_bytes, min_size);
8540 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8541 min_size, 0, *alloc_hint, &ins, 1);
8544 btrfs_end_transaction(trans, root);
8548 ret = insert_reserved_file_extent(trans, inode,
8549 cur_offset, ins.objectid,
8550 ins.offset, ins.offset,
8551 ins.offset, 0, 0, 0,
8552 BTRFS_FILE_EXTENT_PREALLOC);
8554 btrfs_abort_transaction(trans, root, ret);
8556 btrfs_end_transaction(trans, root);
8559 btrfs_drop_extent_cache(inode, cur_offset,
8560 cur_offset + ins.offset -1, 0);
8562 em = alloc_extent_map();
8564 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8565 &BTRFS_I(inode)->runtime_flags);
8569 em->start = cur_offset;
8570 em->orig_start = cur_offset;
8571 em->len = ins.offset;
8572 em->block_start = ins.objectid;
8573 em->block_len = ins.offset;
8574 em->orig_block_len = ins.offset;
8575 em->bdev = root->fs_info->fs_devices->latest_bdev;
8576 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8577 em->generation = trans->transid;
8580 write_lock(&em_tree->lock);
8581 ret = add_extent_mapping(em_tree, em);
8583 list_move(&em->list,
8584 &em_tree->modified_extents);
8585 write_unlock(&em_tree->lock);
8588 btrfs_drop_extent_cache(inode, cur_offset,
8589 cur_offset + ins.offset - 1,
8592 free_extent_map(em);
8594 num_bytes -= ins.offset;
8595 cur_offset += ins.offset;
8596 *alloc_hint = ins.objectid + ins.offset;
8598 inode_inc_iversion(inode);
8599 inode->i_ctime = CURRENT_TIME;
8600 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8601 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8602 (actual_len > inode->i_size) &&
8603 (cur_offset > inode->i_size)) {
8604 if (cur_offset > actual_len)
8605 i_size = actual_len;
8607 i_size = cur_offset;
8608 i_size_write(inode, i_size);
8609 btrfs_ordered_update_i_size(inode, i_size, NULL);
8612 ret = btrfs_update_inode(trans, root, inode);
8615 btrfs_abort_transaction(trans, root, ret);
8617 btrfs_end_transaction(trans, root);
8622 btrfs_end_transaction(trans, root);
8627 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8628 u64 start, u64 num_bytes, u64 min_size,
8629 loff_t actual_len, u64 *alloc_hint)
8631 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8632 min_size, actual_len, alloc_hint,
8636 int btrfs_prealloc_file_range_trans(struct inode *inode,
8637 struct btrfs_trans_handle *trans, int mode,
8638 u64 start, u64 num_bytes, u64 min_size,
8639 loff_t actual_len, u64 *alloc_hint)
8641 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8642 min_size, actual_len, alloc_hint, trans);
8645 static int btrfs_set_page_dirty(struct page *page)
8647 return __set_page_dirty_nobuffers(page);
8650 static int btrfs_permission(struct inode *inode, int mask)
8652 struct btrfs_root *root = BTRFS_I(inode)->root;
8653 umode_t mode = inode->i_mode;
8655 if (mask & MAY_WRITE &&
8656 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8657 if (btrfs_root_readonly(root))
8659 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8662 return generic_permission(inode, mask);
8665 static const struct inode_operations btrfs_dir_inode_operations = {
8666 .getattr = btrfs_getattr,
8667 .lookup = btrfs_lookup,
8668 .create = btrfs_create,
8669 .unlink = btrfs_unlink,
8671 .mkdir = btrfs_mkdir,
8672 .rmdir = btrfs_rmdir,
8673 .rename = btrfs_rename,
8674 .symlink = btrfs_symlink,
8675 .setattr = btrfs_setattr,
8676 .mknod = btrfs_mknod,
8677 .setxattr = btrfs_setxattr,
8678 .getxattr = btrfs_getxattr,
8679 .listxattr = btrfs_listxattr,
8680 .removexattr = btrfs_removexattr,
8681 .permission = btrfs_permission,
8682 .get_acl = btrfs_get_acl,
8684 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8685 .lookup = btrfs_lookup,
8686 .permission = btrfs_permission,
8687 .get_acl = btrfs_get_acl,
8690 static const struct file_operations btrfs_dir_file_operations = {
8691 .llseek = generic_file_llseek,
8692 .read = generic_read_dir,
8693 .readdir = btrfs_real_readdir,
8694 .unlocked_ioctl = btrfs_ioctl,
8695 #ifdef CONFIG_COMPAT
8696 .compat_ioctl = btrfs_ioctl,
8698 .release = btrfs_release_file,
8699 .fsync = btrfs_sync_file,
8702 static struct extent_io_ops btrfs_extent_io_ops = {
8703 .fill_delalloc = run_delalloc_range,
8704 .submit_bio_hook = btrfs_submit_bio_hook,
8705 .merge_bio_hook = btrfs_merge_bio_hook,
8706 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8707 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8708 .writepage_start_hook = btrfs_writepage_start_hook,
8709 .set_bit_hook = btrfs_set_bit_hook,
8710 .clear_bit_hook = btrfs_clear_bit_hook,
8711 .merge_extent_hook = btrfs_merge_extent_hook,
8712 .split_extent_hook = btrfs_split_extent_hook,
8716 * btrfs doesn't support the bmap operation because swapfiles
8717 * use bmap to make a mapping of extents in the file. They assume
8718 * these extents won't change over the life of the file and they
8719 * use the bmap result to do IO directly to the drive.
8721 * the btrfs bmap call would return logical addresses that aren't
8722 * suitable for IO and they also will change frequently as COW
8723 * operations happen. So, swapfile + btrfs == corruption.
8725 * For now we're avoiding this by dropping bmap.
8727 static const struct address_space_operations btrfs_aops = {
8728 .readpage = btrfs_readpage,
8729 .writepage = btrfs_writepage,
8730 .writepages = btrfs_writepages,
8731 .readpages = btrfs_readpages,
8732 .direct_IO = btrfs_direct_IO,
8733 .invalidatepage = btrfs_invalidatepage,
8734 .releasepage = btrfs_releasepage,
8735 .set_page_dirty = btrfs_set_page_dirty,
8736 .error_remove_page = generic_error_remove_page,
8739 static const struct address_space_operations btrfs_symlink_aops = {
8740 .readpage = btrfs_readpage,
8741 .writepage = btrfs_writepage,
8742 .invalidatepage = btrfs_invalidatepage,
8743 .releasepage = btrfs_releasepage,
8746 static const struct inode_operations btrfs_file_inode_operations = {
8747 .getattr = btrfs_getattr,
8748 .setattr = btrfs_setattr,
8749 .setxattr = btrfs_setxattr,
8750 .getxattr = btrfs_getxattr,
8751 .listxattr = btrfs_listxattr,
8752 .removexattr = btrfs_removexattr,
8753 .permission = btrfs_permission,
8754 .fiemap = btrfs_fiemap,
8755 .get_acl = btrfs_get_acl,
8756 .update_time = btrfs_update_time,
8758 static const struct inode_operations btrfs_special_inode_operations = {
8759 .getattr = btrfs_getattr,
8760 .setattr = btrfs_setattr,
8761 .permission = btrfs_permission,
8762 .setxattr = btrfs_setxattr,
8763 .getxattr = btrfs_getxattr,
8764 .listxattr = btrfs_listxattr,
8765 .removexattr = btrfs_removexattr,
8766 .get_acl = btrfs_get_acl,
8767 .update_time = btrfs_update_time,
8769 static const struct inode_operations btrfs_symlink_inode_operations = {
8770 .readlink = generic_readlink,
8771 .follow_link = page_follow_link_light,
8772 .put_link = page_put_link,
8773 .getattr = btrfs_getattr,
8774 .setattr = btrfs_setattr,
8775 .permission = btrfs_permission,
8776 .setxattr = btrfs_setxattr,
8777 .getxattr = btrfs_getxattr,
8778 .listxattr = btrfs_listxattr,
8779 .removexattr = btrfs_removexattr,
8780 .get_acl = btrfs_get_acl,
8781 .update_time = btrfs_update_time,
8784 const struct dentry_operations btrfs_dentry_operations = {
8785 .d_delete = btrfs_dentry_delete,
8786 .d_release = btrfs_dentry_release,