2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/aio.h>
36 #include <linux/bit_spinlock.h>
37 #include <linux/xattr.h>
38 #include <linux/posix_acl.h>
39 #include <linux/falloc.h>
40 #include <linux/slab.h>
41 #include <linux/ratelimit.h>
42 #include <linux/mount.h>
43 #include <linux/btrfs.h>
44 #include <linux/blkdev.h>
45 #include <linux/posix_acl_xattr.h>
49 #include "transaction.h"
50 #include "btrfs_inode.h"
51 #include "print-tree.h"
52 #include "ordered-data.h"
56 #include "compression.h"
58 #include "free-space-cache.h"
59 #include "inode-map.h"
63 struct btrfs_iget_args {
65 struct btrfs_root *root;
68 static const struct inode_operations btrfs_dir_inode_operations;
69 static const struct inode_operations btrfs_symlink_inode_operations;
70 static const struct inode_operations btrfs_dir_ro_inode_operations;
71 static const struct inode_operations btrfs_special_inode_operations;
72 static const struct inode_operations btrfs_file_inode_operations;
73 static const struct address_space_operations btrfs_aops;
74 static const struct address_space_operations btrfs_symlink_aops;
75 static const struct file_operations btrfs_dir_file_operations;
76 static struct extent_io_ops btrfs_extent_io_ops;
78 static struct kmem_cache *btrfs_inode_cachep;
79 static struct kmem_cache *btrfs_delalloc_work_cachep;
80 struct kmem_cache *btrfs_trans_handle_cachep;
81 struct kmem_cache *btrfs_transaction_cachep;
82 struct kmem_cache *btrfs_path_cachep;
83 struct kmem_cache *btrfs_free_space_cachep;
86 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
87 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
88 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
89 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
90 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
91 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
92 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
93 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
96 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
97 static int btrfs_truncate(struct inode *inode);
98 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
99 static noinline int cow_file_range(struct inode *inode,
100 struct page *locked_page,
101 u64 start, u64 end, int *page_started,
102 unsigned long *nr_written, int unlock);
103 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
104 u64 len, u64 orig_start,
105 u64 block_start, u64 block_len,
106 u64 orig_block_len, u64 ram_bytes,
109 static int btrfs_dirty_inode(struct inode *inode);
111 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
112 struct inode *inode, struct inode *dir,
113 const struct qstr *qstr)
117 err = btrfs_init_acl(trans, inode, dir);
119 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
124 * this does all the hard work for inserting an inline extent into
125 * the btree. The caller should have done a btrfs_drop_extents so that
126 * no overlapping inline items exist in the btree
128 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
129 struct btrfs_root *root, struct inode *inode,
130 u64 start, size_t size, size_t compressed_size,
132 struct page **compressed_pages)
134 struct btrfs_key key;
135 struct btrfs_path *path;
136 struct extent_buffer *leaf;
137 struct page *page = NULL;
140 struct btrfs_file_extent_item *ei;
143 size_t cur_size = size;
145 unsigned long offset;
147 if (compressed_size && compressed_pages)
148 cur_size = compressed_size;
150 path = btrfs_alloc_path();
154 path->leave_spinning = 1;
156 key.objectid = btrfs_ino(inode);
158 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
159 datasize = btrfs_file_extent_calc_inline_size(cur_size);
161 inode_add_bytes(inode, size);
162 ret = btrfs_insert_empty_item(trans, root, path, &key,
168 leaf = path->nodes[0];
169 ei = btrfs_item_ptr(leaf, path->slots[0],
170 struct btrfs_file_extent_item);
171 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
172 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
173 btrfs_set_file_extent_encryption(leaf, ei, 0);
174 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
175 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
176 ptr = btrfs_file_extent_inline_start(ei);
178 if (compress_type != BTRFS_COMPRESS_NONE) {
181 while (compressed_size > 0) {
182 cpage = compressed_pages[i];
183 cur_size = min_t(unsigned long, compressed_size,
186 kaddr = kmap_atomic(cpage);
187 write_extent_buffer(leaf, kaddr, ptr, cur_size);
188 kunmap_atomic(kaddr);
192 compressed_size -= cur_size;
194 btrfs_set_file_extent_compression(leaf, ei,
197 page = find_get_page(inode->i_mapping,
198 start >> PAGE_CACHE_SHIFT);
199 btrfs_set_file_extent_compression(leaf, ei, 0);
200 kaddr = kmap_atomic(page);
201 offset = start & (PAGE_CACHE_SIZE - 1);
202 write_extent_buffer(leaf, kaddr + offset, ptr, size);
203 kunmap_atomic(kaddr);
204 page_cache_release(page);
206 btrfs_mark_buffer_dirty(leaf);
207 btrfs_free_path(path);
210 * we're an inline extent, so nobody can
211 * extend the file past i_size without locking
212 * a page we already have locked.
214 * We must do any isize and inode updates
215 * before we unlock the pages. Otherwise we
216 * could end up racing with unlink.
218 BTRFS_I(inode)->disk_i_size = inode->i_size;
219 ret = btrfs_update_inode(trans, root, inode);
223 btrfs_free_path(path);
229 * conditionally insert an inline extent into the file. This
230 * does the checks required to make sure the data is small enough
231 * to fit as an inline extent.
233 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
234 struct btrfs_root *root,
235 struct inode *inode, u64 start, u64 end,
236 size_t compressed_size, int compress_type,
237 struct page **compressed_pages)
239 u64 isize = i_size_read(inode);
240 u64 actual_end = min(end + 1, isize);
241 u64 inline_len = actual_end - start;
242 u64 aligned_end = ALIGN(end, root->sectorsize);
243 u64 data_len = inline_len;
247 data_len = compressed_size;
250 actual_end >= PAGE_CACHE_SIZE ||
251 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
253 (actual_end & (root->sectorsize - 1)) == 0) ||
255 data_len > root->fs_info->max_inline) {
259 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
263 if (isize > actual_end)
264 inline_len = min_t(u64, isize, actual_end);
265 ret = insert_inline_extent(trans, root, inode, start,
266 inline_len, compressed_size,
267 compress_type, compressed_pages);
268 if (ret && ret != -ENOSPC) {
269 btrfs_abort_transaction(trans, root, ret);
271 } else if (ret == -ENOSPC) {
275 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
276 btrfs_delalloc_release_metadata(inode, end + 1 - start);
277 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
281 struct async_extent {
286 unsigned long nr_pages;
288 struct list_head list;
293 struct btrfs_root *root;
294 struct page *locked_page;
297 struct list_head extents;
298 struct btrfs_work work;
301 static noinline int add_async_extent(struct async_cow *cow,
302 u64 start, u64 ram_size,
305 unsigned long nr_pages,
308 struct async_extent *async_extent;
310 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
311 BUG_ON(!async_extent); /* -ENOMEM */
312 async_extent->start = start;
313 async_extent->ram_size = ram_size;
314 async_extent->compressed_size = compressed_size;
315 async_extent->pages = pages;
316 async_extent->nr_pages = nr_pages;
317 async_extent->compress_type = compress_type;
318 list_add_tail(&async_extent->list, &cow->extents);
323 * we create compressed extents in two phases. The first
324 * phase compresses a range of pages that have already been
325 * locked (both pages and state bits are locked).
327 * This is done inside an ordered work queue, and the compression
328 * is spread across many cpus. The actual IO submission is step
329 * two, and the ordered work queue takes care of making sure that
330 * happens in the same order things were put onto the queue by
331 * writepages and friends.
333 * If this code finds it can't get good compression, it puts an
334 * entry onto the work queue to write the uncompressed bytes. This
335 * makes sure that both compressed inodes and uncompressed inodes
336 * are written in the same order that the flusher thread sent them
339 static noinline int compress_file_range(struct inode *inode,
340 struct page *locked_page,
342 struct async_cow *async_cow,
345 struct btrfs_root *root = BTRFS_I(inode)->root;
346 struct btrfs_trans_handle *trans;
348 u64 blocksize = root->sectorsize;
350 u64 isize = i_size_read(inode);
352 struct page **pages = NULL;
353 unsigned long nr_pages;
354 unsigned long nr_pages_ret = 0;
355 unsigned long total_compressed = 0;
356 unsigned long total_in = 0;
357 unsigned long max_compressed = 128 * 1024;
358 unsigned long max_uncompressed = 128 * 1024;
361 int compress_type = root->fs_info->compress_type;
364 /* if this is a small write inside eof, kick off a defrag */
365 if ((end - start + 1) < 16 * 1024 &&
366 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
367 btrfs_add_inode_defrag(NULL, inode);
369 actual_end = min_t(u64, isize, end + 1);
372 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
373 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
376 * we don't want to send crud past the end of i_size through
377 * compression, that's just a waste of CPU time. So, if the
378 * end of the file is before the start of our current
379 * requested range of bytes, we bail out to the uncompressed
380 * cleanup code that can deal with all of this.
382 * It isn't really the fastest way to fix things, but this is a
383 * very uncommon corner.
385 if (actual_end <= start)
386 goto cleanup_and_bail_uncompressed;
388 total_compressed = actual_end - start;
390 /* we want to make sure that amount of ram required to uncompress
391 * an extent is reasonable, so we limit the total size in ram
392 * of a compressed extent to 128k. This is a crucial number
393 * because it also controls how easily we can spread reads across
394 * cpus for decompression.
396 * We also want to make sure the amount of IO required to do
397 * a random read is reasonably small, so we limit the size of
398 * a compressed extent to 128k.
400 total_compressed = min(total_compressed, max_uncompressed);
401 num_bytes = ALIGN(end - start + 1, blocksize);
402 num_bytes = max(blocksize, num_bytes);
407 * we do compression for mount -o compress and when the
408 * inode has not been flagged as nocompress. This flag can
409 * change at any time if we discover bad compression ratios.
411 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
412 (btrfs_test_opt(root, COMPRESS) ||
413 (BTRFS_I(inode)->force_compress) ||
414 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
416 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
418 /* just bail out to the uncompressed code */
422 if (BTRFS_I(inode)->force_compress)
423 compress_type = BTRFS_I(inode)->force_compress;
426 * we need to call clear_page_dirty_for_io on each
427 * page in the range. Otherwise applications with the file
428 * mmap'd can wander in and change the page contents while
429 * we are compressing them.
431 * If the compression fails for any reason, we set the pages
432 * dirty again later on.
434 extent_range_clear_dirty_for_io(inode, start, end);
436 ret = btrfs_compress_pages(compress_type,
437 inode->i_mapping, start,
438 total_compressed, pages,
439 nr_pages, &nr_pages_ret,
445 unsigned long offset = total_compressed &
446 (PAGE_CACHE_SIZE - 1);
447 struct page *page = pages[nr_pages_ret - 1];
450 /* zero the tail end of the last page, we might be
451 * sending it down to disk
454 kaddr = kmap_atomic(page);
455 memset(kaddr + offset, 0,
456 PAGE_CACHE_SIZE - offset);
457 kunmap_atomic(kaddr);
464 trans = btrfs_join_transaction(root);
466 ret = PTR_ERR(trans);
468 goto cleanup_and_out;
470 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
472 /* lets try to make an inline extent */
473 if (ret || total_in < (actual_end - start)) {
474 /* we didn't compress the entire range, try
475 * to make an uncompressed inline extent.
477 ret = cow_file_range_inline(trans, root, inode,
478 start, end, 0, 0, NULL);
480 /* try making a compressed inline extent */
481 ret = cow_file_range_inline(trans, root, inode,
484 compress_type, pages);
488 * inline extent creation worked or returned error,
489 * we don't need to create any more async work items.
490 * Unlock and free up our temp pages.
492 extent_clear_unlock_delalloc(inode, start, end, NULL,
499 btrfs_end_transaction(trans, root);
502 btrfs_end_transaction(trans, root);
507 * we aren't doing an inline extent round the compressed size
508 * up to a block size boundary so the allocator does sane
511 total_compressed = ALIGN(total_compressed, blocksize);
514 * one last check to make sure the compression is really a
515 * win, compare the page count read with the blocks on disk
517 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
518 if (total_compressed >= total_in) {
521 num_bytes = total_in;
524 if (!will_compress && pages) {
526 * the compression code ran but failed to make things smaller,
527 * free any pages it allocated and our page pointer array
529 for (i = 0; i < nr_pages_ret; i++) {
530 WARN_ON(pages[i]->mapping);
531 page_cache_release(pages[i]);
535 total_compressed = 0;
538 /* flag the file so we don't compress in the future */
539 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
540 !(BTRFS_I(inode)->force_compress)) {
541 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
547 /* the async work queues will take care of doing actual
548 * allocation on disk for these compressed pages,
549 * and will submit them to the elevator.
551 add_async_extent(async_cow, start, num_bytes,
552 total_compressed, pages, nr_pages_ret,
555 if (start + num_bytes < end) {
562 cleanup_and_bail_uncompressed:
564 * No compression, but we still need to write the pages in
565 * the file we've been given so far. redirty the locked
566 * page if it corresponds to our extent and set things up
567 * for the async work queue to run cow_file_range to do
568 * the normal delalloc dance
570 if (page_offset(locked_page) >= start &&
571 page_offset(locked_page) <= end) {
572 __set_page_dirty_nobuffers(locked_page);
573 /* unlocked later on in the async handlers */
576 extent_range_redirty_for_io(inode, start, end);
577 add_async_extent(async_cow, start, end - start + 1,
578 0, NULL, 0, BTRFS_COMPRESS_NONE);
586 for (i = 0; i < nr_pages_ret; i++) {
587 WARN_ON(pages[i]->mapping);
588 page_cache_release(pages[i]);
595 extent_clear_unlock_delalloc(inode, start, end, NULL,
596 EXTENT_DIRTY | EXTENT_DELALLOC,
597 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
598 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
599 if (!trans || IS_ERR(trans))
600 btrfs_error(root->fs_info, ret, "Failed to join transaction");
602 btrfs_abort_transaction(trans, root, ret);
607 * phase two of compressed writeback. This is the ordered portion
608 * of the code, which only gets called in the order the work was
609 * queued. We walk all the async extents created by compress_file_range
610 * and send them down to the disk.
612 static noinline int submit_compressed_extents(struct inode *inode,
613 struct async_cow *async_cow)
615 struct async_extent *async_extent;
617 struct btrfs_trans_handle *trans;
618 struct btrfs_key ins;
619 struct extent_map *em;
620 struct btrfs_root *root = BTRFS_I(inode)->root;
621 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
622 struct extent_io_tree *io_tree;
625 if (list_empty(&async_cow->extents))
629 while (!list_empty(&async_cow->extents)) {
630 async_extent = list_entry(async_cow->extents.next,
631 struct async_extent, list);
632 list_del(&async_extent->list);
634 io_tree = &BTRFS_I(inode)->io_tree;
637 /* did the compression code fall back to uncompressed IO? */
638 if (!async_extent->pages) {
639 int page_started = 0;
640 unsigned long nr_written = 0;
642 lock_extent(io_tree, async_extent->start,
643 async_extent->start +
644 async_extent->ram_size - 1);
646 /* allocate blocks */
647 ret = cow_file_range(inode, async_cow->locked_page,
649 async_extent->start +
650 async_extent->ram_size - 1,
651 &page_started, &nr_written, 0);
656 * if page_started, cow_file_range inserted an
657 * inline extent and took care of all the unlocking
658 * and IO for us. Otherwise, we need to submit
659 * all those pages down to the drive.
661 if (!page_started && !ret)
662 extent_write_locked_range(io_tree,
663 inode, async_extent->start,
664 async_extent->start +
665 async_extent->ram_size - 1,
669 unlock_page(async_cow->locked_page);
675 lock_extent(io_tree, async_extent->start,
676 async_extent->start + async_extent->ram_size - 1);
678 trans = btrfs_join_transaction(root);
680 ret = PTR_ERR(trans);
682 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
683 ret = btrfs_reserve_extent(trans, root,
684 async_extent->compressed_size,
685 async_extent->compressed_size,
686 0, alloc_hint, &ins, 1);
687 if (ret && ret != -ENOSPC)
688 btrfs_abort_transaction(trans, root, ret);
689 btrfs_end_transaction(trans, root);
695 for (i = 0; i < async_extent->nr_pages; i++) {
696 WARN_ON(async_extent->pages[i]->mapping);
697 page_cache_release(async_extent->pages[i]);
699 kfree(async_extent->pages);
700 async_extent->nr_pages = 0;
701 async_extent->pages = NULL;
703 if (ret == -ENOSPC) {
704 unlock_extent(io_tree, async_extent->start,
705 async_extent->start +
706 async_extent->ram_size - 1);
713 * here we're doing allocation and writeback of the
716 btrfs_drop_extent_cache(inode, async_extent->start,
717 async_extent->start +
718 async_extent->ram_size - 1, 0);
720 em = alloc_extent_map();
723 goto out_free_reserve;
725 em->start = async_extent->start;
726 em->len = async_extent->ram_size;
727 em->orig_start = em->start;
728 em->mod_start = em->start;
729 em->mod_len = em->len;
731 em->block_start = ins.objectid;
732 em->block_len = ins.offset;
733 em->orig_block_len = ins.offset;
734 em->ram_bytes = async_extent->ram_size;
735 em->bdev = root->fs_info->fs_devices->latest_bdev;
736 em->compress_type = async_extent->compress_type;
737 set_bit(EXTENT_FLAG_PINNED, &em->flags);
738 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
742 write_lock(&em_tree->lock);
743 ret = add_extent_mapping(em_tree, em, 1);
744 write_unlock(&em_tree->lock);
745 if (ret != -EEXIST) {
749 btrfs_drop_extent_cache(inode, async_extent->start,
750 async_extent->start +
751 async_extent->ram_size - 1, 0);
755 goto out_free_reserve;
757 ret = btrfs_add_ordered_extent_compress(inode,
760 async_extent->ram_size,
762 BTRFS_ORDERED_COMPRESSED,
763 async_extent->compress_type);
765 goto out_free_reserve;
768 * clear dirty, set writeback and unlock the pages.
770 extent_clear_unlock_delalloc(inode, async_extent->start,
771 async_extent->start +
772 async_extent->ram_size - 1,
773 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
774 EXTENT_DIRTY, PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
776 ret = btrfs_submit_compressed_write(inode,
778 async_extent->ram_size,
780 ins.offset, async_extent->pages,
781 async_extent->nr_pages);
782 alloc_hint = ins.objectid + ins.offset;
792 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
794 extent_clear_unlock_delalloc(inode, async_extent->start,
795 async_extent->start +
796 async_extent->ram_size - 1,
797 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
798 EXTENT_DIRTY, PAGE_UNLOCK |
799 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
805 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
808 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
809 struct extent_map *em;
812 read_lock(&em_tree->lock);
813 em = search_extent_mapping(em_tree, start, num_bytes);
816 * if block start isn't an actual block number then find the
817 * first block in this inode and use that as a hint. If that
818 * block is also bogus then just don't worry about it.
820 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
822 em = search_extent_mapping(em_tree, 0, 0);
823 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
824 alloc_hint = em->block_start;
828 alloc_hint = em->block_start;
832 read_unlock(&em_tree->lock);
838 * when extent_io.c finds a delayed allocation range in the file,
839 * the call backs end up in this code. The basic idea is to
840 * allocate extents on disk for the range, and create ordered data structs
841 * in ram to track those extents.
843 * locked_page is the page that writepage had locked already. We use
844 * it to make sure we don't do extra locks or unlocks.
846 * *page_started is set to one if we unlock locked_page and do everything
847 * required to start IO on it. It may be clean and already done with
850 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
852 struct btrfs_root *root,
853 struct page *locked_page,
854 u64 start, u64 end, int *page_started,
855 unsigned long *nr_written,
860 unsigned long ram_size;
863 u64 blocksize = root->sectorsize;
864 struct btrfs_key ins;
865 struct extent_map *em;
866 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
869 BUG_ON(btrfs_is_free_space_inode(inode));
871 num_bytes = ALIGN(end - start + 1, blocksize);
872 num_bytes = max(blocksize, num_bytes);
873 disk_num_bytes = num_bytes;
875 /* if this is a small write inside eof, kick off defrag */
876 if (num_bytes < 64 * 1024 &&
877 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
878 btrfs_add_inode_defrag(trans, inode);
881 /* lets try to make an inline extent */
882 ret = cow_file_range_inline(trans, root, inode,
883 start, end, 0, 0, NULL);
885 extent_clear_unlock_delalloc(inode, start, end, NULL,
886 EXTENT_LOCKED | EXTENT_DELALLOC |
887 EXTENT_DIRTY, PAGE_UNLOCK |
888 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
891 *nr_written = *nr_written +
892 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
895 } else if (ret < 0) {
896 btrfs_abort_transaction(trans, root, ret);
901 BUG_ON(disk_num_bytes >
902 btrfs_super_total_bytes(root->fs_info->super_copy));
904 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
905 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
907 while (disk_num_bytes > 0) {
910 cur_alloc_size = disk_num_bytes;
911 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
912 root->sectorsize, 0, alloc_hint,
915 btrfs_abort_transaction(trans, root, ret);
919 em = alloc_extent_map();
925 em->orig_start = em->start;
926 ram_size = ins.offset;
927 em->len = ins.offset;
928 em->mod_start = em->start;
929 em->mod_len = em->len;
931 em->block_start = ins.objectid;
932 em->block_len = ins.offset;
933 em->orig_block_len = ins.offset;
934 em->ram_bytes = ram_size;
935 em->bdev = root->fs_info->fs_devices->latest_bdev;
936 set_bit(EXTENT_FLAG_PINNED, &em->flags);
940 write_lock(&em_tree->lock);
941 ret = add_extent_mapping(em_tree, em, 1);
942 write_unlock(&em_tree->lock);
943 if (ret != -EEXIST) {
947 btrfs_drop_extent_cache(inode, start,
948 start + ram_size - 1, 0);
953 cur_alloc_size = ins.offset;
954 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
955 ram_size, cur_alloc_size, 0);
959 if (root->root_key.objectid ==
960 BTRFS_DATA_RELOC_TREE_OBJECTID) {
961 ret = btrfs_reloc_clone_csums(inode, start,
964 btrfs_abort_transaction(trans, root, ret);
969 if (disk_num_bytes < cur_alloc_size)
972 /* we're not doing compressed IO, don't unlock the first
973 * page (which the caller expects to stay locked), don't
974 * clear any dirty bits and don't set any writeback bits
976 * Do set the Private2 bit so we know this page was properly
977 * setup for writepage
979 op = unlock ? PAGE_UNLOCK : 0;
980 op |= PAGE_SET_PRIVATE2;
982 extent_clear_unlock_delalloc(inode, start,
983 start + ram_size - 1, locked_page,
984 EXTENT_LOCKED | EXTENT_DELALLOC,
986 disk_num_bytes -= cur_alloc_size;
987 num_bytes -= cur_alloc_size;
988 alloc_hint = ins.objectid + ins.offset;
989 start += cur_alloc_size;
995 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
997 extent_clear_unlock_delalloc(inode, start, end, locked_page,
998 EXTENT_LOCKED | EXTENT_DIRTY |
999 EXTENT_DELALLOC, PAGE_UNLOCK |
1000 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1001 PAGE_END_WRITEBACK);
1005 static noinline int cow_file_range(struct inode *inode,
1006 struct page *locked_page,
1007 u64 start, u64 end, int *page_started,
1008 unsigned long *nr_written,
1011 struct btrfs_trans_handle *trans;
1012 struct btrfs_root *root = BTRFS_I(inode)->root;
1015 trans = btrfs_join_transaction(root);
1016 if (IS_ERR(trans)) {
1017 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1018 EXTENT_LOCKED | EXTENT_DELALLOC |
1019 EXTENT_DIRTY, PAGE_UNLOCK |
1021 PAGE_SET_WRITEBACK |
1022 PAGE_END_WRITEBACK);
1023 return PTR_ERR(trans);
1025 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1027 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1028 page_started, nr_written, unlock);
1030 btrfs_end_transaction(trans, root);
1036 * work queue call back to started compression on a file and pages
1038 static noinline void async_cow_start(struct btrfs_work *work)
1040 struct async_cow *async_cow;
1042 async_cow = container_of(work, struct async_cow, work);
1044 compress_file_range(async_cow->inode, async_cow->locked_page,
1045 async_cow->start, async_cow->end, async_cow,
1047 if (num_added == 0) {
1048 btrfs_add_delayed_iput(async_cow->inode);
1049 async_cow->inode = NULL;
1054 * work queue call back to submit previously compressed pages
1056 static noinline void async_cow_submit(struct btrfs_work *work)
1058 struct async_cow *async_cow;
1059 struct btrfs_root *root;
1060 unsigned long nr_pages;
1062 async_cow = container_of(work, struct async_cow, work);
1064 root = async_cow->root;
1065 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1068 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1070 waitqueue_active(&root->fs_info->async_submit_wait))
1071 wake_up(&root->fs_info->async_submit_wait);
1073 if (async_cow->inode)
1074 submit_compressed_extents(async_cow->inode, async_cow);
1077 static noinline void async_cow_free(struct btrfs_work *work)
1079 struct async_cow *async_cow;
1080 async_cow = container_of(work, struct async_cow, work);
1081 if (async_cow->inode)
1082 btrfs_add_delayed_iput(async_cow->inode);
1086 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1087 u64 start, u64 end, int *page_started,
1088 unsigned long *nr_written)
1090 struct async_cow *async_cow;
1091 struct btrfs_root *root = BTRFS_I(inode)->root;
1092 unsigned long nr_pages;
1094 int limit = 10 * 1024 * 1024;
1096 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1097 1, 0, NULL, GFP_NOFS);
1098 while (start < end) {
1099 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1100 BUG_ON(!async_cow); /* -ENOMEM */
1101 async_cow->inode = igrab(inode);
1102 async_cow->root = root;
1103 async_cow->locked_page = locked_page;
1104 async_cow->start = start;
1106 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1109 cur_end = min(end, start + 512 * 1024 - 1);
1111 async_cow->end = cur_end;
1112 INIT_LIST_HEAD(&async_cow->extents);
1114 async_cow->work.func = async_cow_start;
1115 async_cow->work.ordered_func = async_cow_submit;
1116 async_cow->work.ordered_free = async_cow_free;
1117 async_cow->work.flags = 0;
1119 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1121 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1123 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1126 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1127 wait_event(root->fs_info->async_submit_wait,
1128 (atomic_read(&root->fs_info->async_delalloc_pages) <
1132 while (atomic_read(&root->fs_info->async_submit_draining) &&
1133 atomic_read(&root->fs_info->async_delalloc_pages)) {
1134 wait_event(root->fs_info->async_submit_wait,
1135 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1139 *nr_written += nr_pages;
1140 start = cur_end + 1;
1146 static noinline int csum_exist_in_range(struct btrfs_root *root,
1147 u64 bytenr, u64 num_bytes)
1150 struct btrfs_ordered_sum *sums;
1153 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1154 bytenr + num_bytes - 1, &list, 0);
1155 if (ret == 0 && list_empty(&list))
1158 while (!list_empty(&list)) {
1159 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1160 list_del(&sums->list);
1167 * when nowcow writeback call back. This checks for snapshots or COW copies
1168 * of the extents that exist in the file, and COWs the file as required.
1170 * If no cow copies or snapshots exist, we write directly to the existing
1173 static noinline int run_delalloc_nocow(struct inode *inode,
1174 struct page *locked_page,
1175 u64 start, u64 end, int *page_started, int force,
1176 unsigned long *nr_written)
1178 struct btrfs_root *root = BTRFS_I(inode)->root;
1179 struct btrfs_trans_handle *trans;
1180 struct extent_buffer *leaf;
1181 struct btrfs_path *path;
1182 struct btrfs_file_extent_item *fi;
1183 struct btrfs_key found_key;
1198 u64 ino = btrfs_ino(inode);
1200 path = btrfs_alloc_path();
1202 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1203 EXTENT_LOCKED | EXTENT_DELALLOC |
1204 EXTENT_DIRTY, PAGE_UNLOCK |
1206 PAGE_SET_WRITEBACK |
1207 PAGE_END_WRITEBACK);
1211 nolock = btrfs_is_free_space_inode(inode);
1214 trans = btrfs_join_transaction_nolock(root);
1216 trans = btrfs_join_transaction(root);
1218 if (IS_ERR(trans)) {
1219 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1220 EXTENT_LOCKED | EXTENT_DELALLOC |
1221 EXTENT_DIRTY, PAGE_UNLOCK |
1223 PAGE_SET_WRITEBACK |
1224 PAGE_END_WRITEBACK);
1225 btrfs_free_path(path);
1226 return PTR_ERR(trans);
1229 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1231 cow_start = (u64)-1;
1234 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1237 btrfs_abort_transaction(trans, root, ret);
1240 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1241 leaf = path->nodes[0];
1242 btrfs_item_key_to_cpu(leaf, &found_key,
1243 path->slots[0] - 1);
1244 if (found_key.objectid == ino &&
1245 found_key.type == BTRFS_EXTENT_DATA_KEY)
1250 leaf = path->nodes[0];
1251 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1252 ret = btrfs_next_leaf(root, path);
1254 btrfs_abort_transaction(trans, root, ret);
1259 leaf = path->nodes[0];
1265 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1267 if (found_key.objectid > ino ||
1268 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1269 found_key.offset > end)
1272 if (found_key.offset > cur_offset) {
1273 extent_end = found_key.offset;
1278 fi = btrfs_item_ptr(leaf, path->slots[0],
1279 struct btrfs_file_extent_item);
1280 extent_type = btrfs_file_extent_type(leaf, fi);
1282 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1283 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1284 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1285 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1286 extent_offset = btrfs_file_extent_offset(leaf, fi);
1287 extent_end = found_key.offset +
1288 btrfs_file_extent_num_bytes(leaf, fi);
1290 btrfs_file_extent_disk_num_bytes(leaf, fi);
1291 if (extent_end <= start) {
1295 if (disk_bytenr == 0)
1297 if (btrfs_file_extent_compression(leaf, fi) ||
1298 btrfs_file_extent_encryption(leaf, fi) ||
1299 btrfs_file_extent_other_encoding(leaf, fi))
1301 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1303 if (btrfs_extent_readonly(root, disk_bytenr))
1305 if (btrfs_cross_ref_exist(trans, root, ino,
1307 extent_offset, disk_bytenr))
1309 disk_bytenr += extent_offset;
1310 disk_bytenr += cur_offset - found_key.offset;
1311 num_bytes = min(end + 1, extent_end) - cur_offset;
1313 * force cow if csum exists in the range.
1314 * this ensure that csum for a given extent are
1315 * either valid or do not exist.
1317 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1320 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1321 extent_end = found_key.offset +
1322 btrfs_file_extent_inline_len(leaf, fi);
1323 extent_end = ALIGN(extent_end, root->sectorsize);
1328 if (extent_end <= start) {
1333 if (cow_start == (u64)-1)
1334 cow_start = cur_offset;
1335 cur_offset = extent_end;
1336 if (cur_offset > end)
1342 btrfs_release_path(path);
1343 if (cow_start != (u64)-1) {
1344 ret = __cow_file_range(trans, inode, root, locked_page,
1345 cow_start, found_key.offset - 1,
1346 page_started, nr_written, 1);
1348 btrfs_abort_transaction(trans, root, ret);
1351 cow_start = (u64)-1;
1354 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1355 struct extent_map *em;
1356 struct extent_map_tree *em_tree;
1357 em_tree = &BTRFS_I(inode)->extent_tree;
1358 em = alloc_extent_map();
1359 BUG_ON(!em); /* -ENOMEM */
1360 em->start = cur_offset;
1361 em->orig_start = found_key.offset - extent_offset;
1362 em->len = num_bytes;
1363 em->block_len = num_bytes;
1364 em->block_start = disk_bytenr;
1365 em->orig_block_len = disk_num_bytes;
1366 em->ram_bytes = ram_bytes;
1367 em->bdev = root->fs_info->fs_devices->latest_bdev;
1368 em->mod_start = em->start;
1369 em->mod_len = em->len;
1370 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1371 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1372 em->generation = -1;
1374 write_lock(&em_tree->lock);
1375 ret = add_extent_mapping(em_tree, em, 1);
1376 write_unlock(&em_tree->lock);
1377 if (ret != -EEXIST) {
1378 free_extent_map(em);
1381 btrfs_drop_extent_cache(inode, em->start,
1382 em->start + em->len - 1, 0);
1384 type = BTRFS_ORDERED_PREALLOC;
1386 type = BTRFS_ORDERED_NOCOW;
1389 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1390 num_bytes, num_bytes, type);
1391 BUG_ON(ret); /* -ENOMEM */
1393 if (root->root_key.objectid ==
1394 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1395 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1398 btrfs_abort_transaction(trans, root, ret);
1403 extent_clear_unlock_delalloc(inode, cur_offset,
1404 cur_offset + num_bytes - 1,
1405 locked_page, EXTENT_LOCKED |
1406 EXTENT_DELALLOC, PAGE_UNLOCK |
1408 cur_offset = extent_end;
1409 if (cur_offset > end)
1412 btrfs_release_path(path);
1414 if (cur_offset <= end && cow_start == (u64)-1) {
1415 cow_start = cur_offset;
1419 if (cow_start != (u64)-1) {
1420 ret = __cow_file_range(trans, inode, root, locked_page,
1422 page_started, nr_written, 1);
1424 btrfs_abort_transaction(trans, root, ret);
1430 err = btrfs_end_transaction(trans, root);
1434 if (ret && cur_offset < end)
1435 extent_clear_unlock_delalloc(inode, cur_offset, end,
1436 locked_page, EXTENT_LOCKED |
1437 EXTENT_DELALLOC | EXTENT_DIRTY,
1438 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1439 PAGE_SET_WRITEBACK |
1440 PAGE_END_WRITEBACK);
1441 btrfs_free_path(path);
1446 * extent_io.c call back to do delayed allocation processing
1448 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1449 u64 start, u64 end, int *page_started,
1450 unsigned long *nr_written)
1453 struct btrfs_root *root = BTRFS_I(inode)->root;
1455 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1456 ret = run_delalloc_nocow(inode, locked_page, start, end,
1457 page_started, 1, nr_written);
1458 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1459 ret = run_delalloc_nocow(inode, locked_page, start, end,
1460 page_started, 0, nr_written);
1461 } else if (!btrfs_test_opt(root, COMPRESS) &&
1462 !(BTRFS_I(inode)->force_compress) &&
1463 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1464 ret = cow_file_range(inode, locked_page, start, end,
1465 page_started, nr_written, 1);
1467 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1468 &BTRFS_I(inode)->runtime_flags);
1469 ret = cow_file_range_async(inode, locked_page, start, end,
1470 page_started, nr_written);
1475 static void btrfs_split_extent_hook(struct inode *inode,
1476 struct extent_state *orig, u64 split)
1478 /* not delalloc, ignore it */
1479 if (!(orig->state & EXTENT_DELALLOC))
1482 spin_lock(&BTRFS_I(inode)->lock);
1483 BTRFS_I(inode)->outstanding_extents++;
1484 spin_unlock(&BTRFS_I(inode)->lock);
1488 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1489 * extents so we can keep track of new extents that are just merged onto old
1490 * extents, such as when we are doing sequential writes, so we can properly
1491 * account for the metadata space we'll need.
1493 static void btrfs_merge_extent_hook(struct inode *inode,
1494 struct extent_state *new,
1495 struct extent_state *other)
1497 /* not delalloc, ignore it */
1498 if (!(other->state & EXTENT_DELALLOC))
1501 spin_lock(&BTRFS_I(inode)->lock);
1502 BTRFS_I(inode)->outstanding_extents--;
1503 spin_unlock(&BTRFS_I(inode)->lock);
1506 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1507 struct inode *inode)
1509 spin_lock(&root->delalloc_lock);
1510 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1511 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1512 &root->delalloc_inodes);
1513 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1514 &BTRFS_I(inode)->runtime_flags);
1515 root->nr_delalloc_inodes++;
1516 if (root->nr_delalloc_inodes == 1) {
1517 spin_lock(&root->fs_info->delalloc_root_lock);
1518 BUG_ON(!list_empty(&root->delalloc_root));
1519 list_add_tail(&root->delalloc_root,
1520 &root->fs_info->delalloc_roots);
1521 spin_unlock(&root->fs_info->delalloc_root_lock);
1524 spin_unlock(&root->delalloc_lock);
1527 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1528 struct inode *inode)
1530 spin_lock(&root->delalloc_lock);
1531 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1532 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1533 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1534 &BTRFS_I(inode)->runtime_flags);
1535 root->nr_delalloc_inodes--;
1536 if (!root->nr_delalloc_inodes) {
1537 spin_lock(&root->fs_info->delalloc_root_lock);
1538 BUG_ON(list_empty(&root->delalloc_root));
1539 list_del_init(&root->delalloc_root);
1540 spin_unlock(&root->fs_info->delalloc_root_lock);
1543 spin_unlock(&root->delalloc_lock);
1547 * extent_io.c set_bit_hook, used to track delayed allocation
1548 * bytes in this file, and to maintain the list of inodes that
1549 * have pending delalloc work to be done.
1551 static void btrfs_set_bit_hook(struct inode *inode,
1552 struct extent_state *state, unsigned long *bits)
1556 * set_bit and clear bit hooks normally require _irqsave/restore
1557 * but in this case, we are only testing for the DELALLOC
1558 * bit, which is only set or cleared with irqs on
1560 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1561 struct btrfs_root *root = BTRFS_I(inode)->root;
1562 u64 len = state->end + 1 - state->start;
1563 bool do_list = !btrfs_is_free_space_inode(inode);
1565 if (*bits & EXTENT_FIRST_DELALLOC) {
1566 *bits &= ~EXTENT_FIRST_DELALLOC;
1568 spin_lock(&BTRFS_I(inode)->lock);
1569 BTRFS_I(inode)->outstanding_extents++;
1570 spin_unlock(&BTRFS_I(inode)->lock);
1573 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1574 root->fs_info->delalloc_batch);
1575 spin_lock(&BTRFS_I(inode)->lock);
1576 BTRFS_I(inode)->delalloc_bytes += len;
1577 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1578 &BTRFS_I(inode)->runtime_flags))
1579 btrfs_add_delalloc_inodes(root, inode);
1580 spin_unlock(&BTRFS_I(inode)->lock);
1585 * extent_io.c clear_bit_hook, see set_bit_hook for why
1587 static void btrfs_clear_bit_hook(struct inode *inode,
1588 struct extent_state *state,
1589 unsigned long *bits)
1592 * set_bit and clear bit hooks normally require _irqsave/restore
1593 * but in this case, we are only testing for the DELALLOC
1594 * bit, which is only set or cleared with irqs on
1596 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1597 struct btrfs_root *root = BTRFS_I(inode)->root;
1598 u64 len = state->end + 1 - state->start;
1599 bool do_list = !btrfs_is_free_space_inode(inode);
1601 if (*bits & EXTENT_FIRST_DELALLOC) {
1602 *bits &= ~EXTENT_FIRST_DELALLOC;
1603 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1604 spin_lock(&BTRFS_I(inode)->lock);
1605 BTRFS_I(inode)->outstanding_extents--;
1606 spin_unlock(&BTRFS_I(inode)->lock);
1609 if (*bits & EXTENT_DO_ACCOUNTING)
1610 btrfs_delalloc_release_metadata(inode, len);
1612 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1613 && do_list && !(state->state & EXTENT_NORESERVE))
1614 btrfs_free_reserved_data_space(inode, len);
1616 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1617 root->fs_info->delalloc_batch);
1618 spin_lock(&BTRFS_I(inode)->lock);
1619 BTRFS_I(inode)->delalloc_bytes -= len;
1620 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1621 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1622 &BTRFS_I(inode)->runtime_flags))
1623 btrfs_del_delalloc_inode(root, inode);
1624 spin_unlock(&BTRFS_I(inode)->lock);
1629 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1630 * we don't create bios that span stripes or chunks
1632 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1633 size_t size, struct bio *bio,
1634 unsigned long bio_flags)
1636 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1637 u64 logical = (u64)bio->bi_sector << 9;
1642 if (bio_flags & EXTENT_BIO_COMPRESSED)
1645 length = bio->bi_size;
1646 map_length = length;
1647 ret = btrfs_map_block(root->fs_info, rw, logical,
1648 &map_length, NULL, 0);
1649 /* Will always return 0 with map_multi == NULL */
1651 if (map_length < length + size)
1657 * in order to insert checksums into the metadata in large chunks,
1658 * we wait until bio submission time. All the pages in the bio are
1659 * checksummed and sums are attached onto the ordered extent record.
1661 * At IO completion time the cums attached on the ordered extent record
1662 * are inserted into the btree
1664 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1665 struct bio *bio, int mirror_num,
1666 unsigned long bio_flags,
1669 struct btrfs_root *root = BTRFS_I(inode)->root;
1672 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1673 BUG_ON(ret); /* -ENOMEM */
1678 * in order to insert checksums into the metadata in large chunks,
1679 * we wait until bio submission time. All the pages in the bio are
1680 * checksummed and sums are attached onto the ordered extent record.
1682 * At IO completion time the cums attached on the ordered extent record
1683 * are inserted into the btree
1685 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1686 int mirror_num, unsigned long bio_flags,
1689 struct btrfs_root *root = BTRFS_I(inode)->root;
1692 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1694 bio_endio(bio, ret);
1699 * extent_io.c submission hook. This does the right thing for csum calculation
1700 * on write, or reading the csums from the tree before a read
1702 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1703 int mirror_num, unsigned long bio_flags,
1706 struct btrfs_root *root = BTRFS_I(inode)->root;
1710 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1712 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1714 if (btrfs_is_free_space_inode(inode))
1717 if (!(rw & REQ_WRITE)) {
1718 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1722 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1723 ret = btrfs_submit_compressed_read(inode, bio,
1727 } else if (!skip_sum) {
1728 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1733 } else if (async && !skip_sum) {
1734 /* csum items have already been cloned */
1735 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1737 /* we're doing a write, do the async checksumming */
1738 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1739 inode, rw, bio, mirror_num,
1740 bio_flags, bio_offset,
1741 __btrfs_submit_bio_start,
1742 __btrfs_submit_bio_done);
1744 } else if (!skip_sum) {
1745 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1751 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1755 bio_endio(bio, ret);
1760 * given a list of ordered sums record them in the inode. This happens
1761 * at IO completion time based on sums calculated at bio submission time.
1763 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1764 struct inode *inode, u64 file_offset,
1765 struct list_head *list)
1767 struct btrfs_ordered_sum *sum;
1769 list_for_each_entry(sum, list, list) {
1770 trans->adding_csums = 1;
1771 btrfs_csum_file_blocks(trans,
1772 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1773 trans->adding_csums = 0;
1778 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1779 struct extent_state **cached_state)
1781 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1782 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1783 cached_state, GFP_NOFS);
1786 /* see btrfs_writepage_start_hook for details on why this is required */
1787 struct btrfs_writepage_fixup {
1789 struct btrfs_work work;
1792 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1794 struct btrfs_writepage_fixup *fixup;
1795 struct btrfs_ordered_extent *ordered;
1796 struct extent_state *cached_state = NULL;
1798 struct inode *inode;
1803 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1807 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1808 ClearPageChecked(page);
1812 inode = page->mapping->host;
1813 page_start = page_offset(page);
1814 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1816 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1819 /* already ordered? We're done */
1820 if (PagePrivate2(page))
1823 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1825 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1826 page_end, &cached_state, GFP_NOFS);
1828 btrfs_start_ordered_extent(inode, ordered, 1);
1829 btrfs_put_ordered_extent(ordered);
1833 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1835 mapping_set_error(page->mapping, ret);
1836 end_extent_writepage(page, ret, page_start, page_end);
1837 ClearPageChecked(page);
1841 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1842 ClearPageChecked(page);
1843 set_page_dirty(page);
1845 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1846 &cached_state, GFP_NOFS);
1849 page_cache_release(page);
1854 * There are a few paths in the higher layers of the kernel that directly
1855 * set the page dirty bit without asking the filesystem if it is a
1856 * good idea. This causes problems because we want to make sure COW
1857 * properly happens and the data=ordered rules are followed.
1859 * In our case any range that doesn't have the ORDERED bit set
1860 * hasn't been properly setup for IO. We kick off an async process
1861 * to fix it up. The async helper will wait for ordered extents, set
1862 * the delalloc bit and make it safe to write the page.
1864 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1866 struct inode *inode = page->mapping->host;
1867 struct btrfs_writepage_fixup *fixup;
1868 struct btrfs_root *root = BTRFS_I(inode)->root;
1870 /* this page is properly in the ordered list */
1871 if (TestClearPagePrivate2(page))
1874 if (PageChecked(page))
1877 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1881 SetPageChecked(page);
1882 page_cache_get(page);
1883 fixup->work.func = btrfs_writepage_fixup_worker;
1885 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1889 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1890 struct inode *inode, u64 file_pos,
1891 u64 disk_bytenr, u64 disk_num_bytes,
1892 u64 num_bytes, u64 ram_bytes,
1893 u8 compression, u8 encryption,
1894 u16 other_encoding, int extent_type)
1896 struct btrfs_root *root = BTRFS_I(inode)->root;
1897 struct btrfs_file_extent_item *fi;
1898 struct btrfs_path *path;
1899 struct extent_buffer *leaf;
1900 struct btrfs_key ins;
1903 path = btrfs_alloc_path();
1907 path->leave_spinning = 1;
1910 * we may be replacing one extent in the tree with another.
1911 * The new extent is pinned in the extent map, and we don't want
1912 * to drop it from the cache until it is completely in the btree.
1914 * So, tell btrfs_drop_extents to leave this extent in the cache.
1915 * the caller is expected to unpin it and allow it to be merged
1918 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1919 file_pos + num_bytes, 0);
1923 ins.objectid = btrfs_ino(inode);
1924 ins.offset = file_pos;
1925 ins.type = BTRFS_EXTENT_DATA_KEY;
1926 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1929 leaf = path->nodes[0];
1930 fi = btrfs_item_ptr(leaf, path->slots[0],
1931 struct btrfs_file_extent_item);
1932 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1933 btrfs_set_file_extent_type(leaf, fi, extent_type);
1934 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1935 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1936 btrfs_set_file_extent_offset(leaf, fi, 0);
1937 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1938 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1939 btrfs_set_file_extent_compression(leaf, fi, compression);
1940 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1941 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1943 btrfs_mark_buffer_dirty(leaf);
1944 btrfs_release_path(path);
1946 inode_add_bytes(inode, num_bytes);
1948 ins.objectid = disk_bytenr;
1949 ins.offset = disk_num_bytes;
1950 ins.type = BTRFS_EXTENT_ITEM_KEY;
1951 ret = btrfs_alloc_reserved_file_extent(trans, root,
1952 root->root_key.objectid,
1953 btrfs_ino(inode), file_pos, &ins);
1955 btrfs_free_path(path);
1960 /* snapshot-aware defrag */
1961 struct sa_defrag_extent_backref {
1962 struct rb_node node;
1963 struct old_sa_defrag_extent *old;
1972 struct old_sa_defrag_extent {
1973 struct list_head list;
1974 struct new_sa_defrag_extent *new;
1983 struct new_sa_defrag_extent {
1984 struct rb_root root;
1985 struct list_head head;
1986 struct btrfs_path *path;
1987 struct inode *inode;
1995 static int backref_comp(struct sa_defrag_extent_backref *b1,
1996 struct sa_defrag_extent_backref *b2)
1998 if (b1->root_id < b2->root_id)
2000 else if (b1->root_id > b2->root_id)
2003 if (b1->inum < b2->inum)
2005 else if (b1->inum > b2->inum)
2008 if (b1->file_pos < b2->file_pos)
2010 else if (b1->file_pos > b2->file_pos)
2014 * [------------------------------] ===> (a range of space)
2015 * |<--->| |<---->| =============> (fs/file tree A)
2016 * |<---------------------------->| ===> (fs/file tree B)
2018 * A range of space can refer to two file extents in one tree while
2019 * refer to only one file extent in another tree.
2021 * So we may process a disk offset more than one time(two extents in A)
2022 * and locate at the same extent(one extent in B), then insert two same
2023 * backrefs(both refer to the extent in B).
2028 static void backref_insert(struct rb_root *root,
2029 struct sa_defrag_extent_backref *backref)
2031 struct rb_node **p = &root->rb_node;
2032 struct rb_node *parent = NULL;
2033 struct sa_defrag_extent_backref *entry;
2038 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2040 ret = backref_comp(backref, entry);
2044 p = &(*p)->rb_right;
2047 rb_link_node(&backref->node, parent, p);
2048 rb_insert_color(&backref->node, root);
2052 * Note the backref might has changed, and in this case we just return 0.
2054 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2057 struct btrfs_file_extent_item *extent;
2058 struct btrfs_fs_info *fs_info;
2059 struct old_sa_defrag_extent *old = ctx;
2060 struct new_sa_defrag_extent *new = old->new;
2061 struct btrfs_path *path = new->path;
2062 struct btrfs_key key;
2063 struct btrfs_root *root;
2064 struct sa_defrag_extent_backref *backref;
2065 struct extent_buffer *leaf;
2066 struct inode *inode = new->inode;
2072 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2073 inum == btrfs_ino(inode))
2076 key.objectid = root_id;
2077 key.type = BTRFS_ROOT_ITEM_KEY;
2078 key.offset = (u64)-1;
2080 fs_info = BTRFS_I(inode)->root->fs_info;
2081 root = btrfs_read_fs_root_no_name(fs_info, &key);
2083 if (PTR_ERR(root) == -ENOENT)
2086 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2087 inum, offset, root_id);
2088 return PTR_ERR(root);
2091 key.objectid = inum;
2092 key.type = BTRFS_EXTENT_DATA_KEY;
2093 if (offset > (u64)-1 << 32)
2096 key.offset = offset;
2098 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2108 leaf = path->nodes[0];
2109 slot = path->slots[0];
2111 if (slot >= btrfs_header_nritems(leaf)) {
2112 ret = btrfs_next_leaf(root, path);
2115 } else if (ret > 0) {
2124 btrfs_item_key_to_cpu(leaf, &key, slot);
2126 if (key.objectid > inum)
2129 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2132 extent = btrfs_item_ptr(leaf, slot,
2133 struct btrfs_file_extent_item);
2135 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2139 * 'offset' refers to the exact key.offset,
2140 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2141 * (key.offset - extent_offset).
2143 if (key.offset != offset)
2146 extent_offset = btrfs_file_extent_offset(leaf, extent);
2147 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2149 if (extent_offset >= old->extent_offset + old->offset +
2150 old->len || extent_offset + num_bytes <=
2151 old->extent_offset + old->offset)
2156 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2162 backref->root_id = root_id;
2163 backref->inum = inum;
2164 backref->file_pos = offset;
2165 backref->num_bytes = num_bytes;
2166 backref->extent_offset = extent_offset;
2167 backref->generation = btrfs_file_extent_generation(leaf, extent);
2169 backref_insert(&new->root, backref);
2172 btrfs_release_path(path);
2177 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2178 struct new_sa_defrag_extent *new)
2180 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2181 struct old_sa_defrag_extent *old, *tmp;
2186 list_for_each_entry_safe(old, tmp, &new->head, list) {
2187 ret = iterate_inodes_from_logical(old->bytenr +
2188 old->extent_offset, fs_info,
2189 path, record_one_backref,
2191 BUG_ON(ret < 0 && ret != -ENOENT);
2193 /* no backref to be processed for this extent */
2195 list_del(&old->list);
2200 if (list_empty(&new->head))
2206 static int relink_is_mergable(struct extent_buffer *leaf,
2207 struct btrfs_file_extent_item *fi,
2210 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2213 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2216 if (btrfs_file_extent_compression(leaf, fi) ||
2217 btrfs_file_extent_encryption(leaf, fi) ||
2218 btrfs_file_extent_other_encoding(leaf, fi))
2225 * Note the backref might has changed, and in this case we just return 0.
2227 static noinline int relink_extent_backref(struct btrfs_path *path,
2228 struct sa_defrag_extent_backref *prev,
2229 struct sa_defrag_extent_backref *backref)
2231 struct btrfs_file_extent_item *extent;
2232 struct btrfs_file_extent_item *item;
2233 struct btrfs_ordered_extent *ordered;
2234 struct btrfs_trans_handle *trans;
2235 struct btrfs_fs_info *fs_info;
2236 struct btrfs_root *root;
2237 struct btrfs_key key;
2238 struct extent_buffer *leaf;
2239 struct old_sa_defrag_extent *old = backref->old;
2240 struct new_sa_defrag_extent *new = old->new;
2241 struct inode *src_inode = new->inode;
2242 struct inode *inode;
2243 struct extent_state *cached = NULL;
2252 if (prev && prev->root_id == backref->root_id &&
2253 prev->inum == backref->inum &&
2254 prev->file_pos + prev->num_bytes == backref->file_pos)
2257 /* step 1: get root */
2258 key.objectid = backref->root_id;
2259 key.type = BTRFS_ROOT_ITEM_KEY;
2260 key.offset = (u64)-1;
2262 fs_info = BTRFS_I(src_inode)->root->fs_info;
2263 index = srcu_read_lock(&fs_info->subvol_srcu);
2265 root = btrfs_read_fs_root_no_name(fs_info, &key);
2267 srcu_read_unlock(&fs_info->subvol_srcu, index);
2268 if (PTR_ERR(root) == -ENOENT)
2270 return PTR_ERR(root);
2273 /* step 2: get inode */
2274 key.objectid = backref->inum;
2275 key.type = BTRFS_INODE_ITEM_KEY;
2278 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2279 if (IS_ERR(inode)) {
2280 srcu_read_unlock(&fs_info->subvol_srcu, index);
2284 srcu_read_unlock(&fs_info->subvol_srcu, index);
2286 /* step 3: relink backref */
2287 lock_start = backref->file_pos;
2288 lock_end = backref->file_pos + backref->num_bytes - 1;
2289 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2292 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2294 btrfs_put_ordered_extent(ordered);
2298 trans = btrfs_join_transaction(root);
2299 if (IS_ERR(trans)) {
2300 ret = PTR_ERR(trans);
2304 key.objectid = backref->inum;
2305 key.type = BTRFS_EXTENT_DATA_KEY;
2306 key.offset = backref->file_pos;
2308 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2311 } else if (ret > 0) {
2316 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2317 struct btrfs_file_extent_item);
2319 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2320 backref->generation)
2323 btrfs_release_path(path);
2325 start = backref->file_pos;
2326 if (backref->extent_offset < old->extent_offset + old->offset)
2327 start += old->extent_offset + old->offset -
2328 backref->extent_offset;
2330 len = min(backref->extent_offset + backref->num_bytes,
2331 old->extent_offset + old->offset + old->len);
2332 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2334 ret = btrfs_drop_extents(trans, root, inode, start,
2339 key.objectid = btrfs_ino(inode);
2340 key.type = BTRFS_EXTENT_DATA_KEY;
2343 path->leave_spinning = 1;
2345 struct btrfs_file_extent_item *fi;
2347 struct btrfs_key found_key;
2349 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2354 leaf = path->nodes[0];
2355 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2357 fi = btrfs_item_ptr(leaf, path->slots[0],
2358 struct btrfs_file_extent_item);
2359 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2361 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2362 extent_len + found_key.offset == start) {
2363 btrfs_set_file_extent_num_bytes(leaf, fi,
2365 btrfs_mark_buffer_dirty(leaf);
2366 inode_add_bytes(inode, len);
2372 btrfs_release_path(path);
2377 ret = btrfs_insert_empty_item(trans, root, path, &key,
2380 btrfs_abort_transaction(trans, root, ret);
2384 leaf = path->nodes[0];
2385 item = btrfs_item_ptr(leaf, path->slots[0],
2386 struct btrfs_file_extent_item);
2387 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2388 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2389 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2390 btrfs_set_file_extent_num_bytes(leaf, item, len);
2391 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2392 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2393 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2394 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2395 btrfs_set_file_extent_encryption(leaf, item, 0);
2396 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2398 btrfs_mark_buffer_dirty(leaf);
2399 inode_add_bytes(inode, len);
2400 btrfs_release_path(path);
2402 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2404 backref->root_id, backref->inum,
2405 new->file_pos, 0); /* start - extent_offset */
2407 btrfs_abort_transaction(trans, root, ret);
2413 btrfs_release_path(path);
2414 path->leave_spinning = 0;
2415 btrfs_end_transaction(trans, root);
2417 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2423 static void relink_file_extents(struct new_sa_defrag_extent *new)
2425 struct btrfs_path *path;
2426 struct old_sa_defrag_extent *old, *tmp;
2427 struct sa_defrag_extent_backref *backref;
2428 struct sa_defrag_extent_backref *prev = NULL;
2429 struct inode *inode;
2430 struct btrfs_root *root;
2431 struct rb_node *node;
2435 root = BTRFS_I(inode)->root;
2437 path = btrfs_alloc_path();
2441 if (!record_extent_backrefs(path, new)) {
2442 btrfs_free_path(path);
2445 btrfs_release_path(path);
2448 node = rb_first(&new->root);
2451 rb_erase(node, &new->root);
2453 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2455 ret = relink_extent_backref(path, prev, backref);
2468 btrfs_free_path(path);
2470 list_for_each_entry_safe(old, tmp, &new->head, list) {
2471 list_del(&old->list);
2475 atomic_dec(&root->fs_info->defrag_running);
2476 wake_up(&root->fs_info->transaction_wait);
2481 static struct new_sa_defrag_extent *
2482 record_old_file_extents(struct inode *inode,
2483 struct btrfs_ordered_extent *ordered)
2485 struct btrfs_root *root = BTRFS_I(inode)->root;
2486 struct btrfs_path *path;
2487 struct btrfs_key key;
2488 struct old_sa_defrag_extent *old, *tmp;
2489 struct new_sa_defrag_extent *new;
2492 new = kmalloc(sizeof(*new), GFP_NOFS);
2497 new->file_pos = ordered->file_offset;
2498 new->len = ordered->len;
2499 new->bytenr = ordered->start;
2500 new->disk_len = ordered->disk_len;
2501 new->compress_type = ordered->compress_type;
2502 new->root = RB_ROOT;
2503 INIT_LIST_HEAD(&new->head);
2505 path = btrfs_alloc_path();
2509 key.objectid = btrfs_ino(inode);
2510 key.type = BTRFS_EXTENT_DATA_KEY;
2511 key.offset = new->file_pos;
2513 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2516 if (ret > 0 && path->slots[0] > 0)
2519 /* find out all the old extents for the file range */
2521 struct btrfs_file_extent_item *extent;
2522 struct extent_buffer *l;
2531 slot = path->slots[0];
2533 if (slot >= btrfs_header_nritems(l)) {
2534 ret = btrfs_next_leaf(root, path);
2542 btrfs_item_key_to_cpu(l, &key, slot);
2544 if (key.objectid != btrfs_ino(inode))
2546 if (key.type != BTRFS_EXTENT_DATA_KEY)
2548 if (key.offset >= new->file_pos + new->len)
2551 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2553 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2554 if (key.offset + num_bytes < new->file_pos)
2557 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2561 extent_offset = btrfs_file_extent_offset(l, extent);
2563 old = kmalloc(sizeof(*old), GFP_NOFS);
2567 offset = max(new->file_pos, key.offset);
2568 end = min(new->file_pos + new->len, key.offset + num_bytes);
2570 old->bytenr = disk_bytenr;
2571 old->extent_offset = extent_offset;
2572 old->offset = offset - key.offset;
2573 old->len = end - offset;
2576 list_add_tail(&old->list, &new->head);
2582 btrfs_free_path(path);
2583 atomic_inc(&root->fs_info->defrag_running);
2588 list_for_each_entry_safe(old, tmp, &new->head, list) {
2589 list_del(&old->list);
2593 btrfs_free_path(path);
2600 * helper function for btrfs_finish_ordered_io, this
2601 * just reads in some of the csum leaves to prime them into ram
2602 * before we start the transaction. It limits the amount of btree
2603 * reads required while inside the transaction.
2605 /* as ordered data IO finishes, this gets called so we can finish
2606 * an ordered extent if the range of bytes in the file it covers are
2609 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2611 struct inode *inode = ordered_extent->inode;
2612 struct btrfs_root *root = BTRFS_I(inode)->root;
2613 struct btrfs_trans_handle *trans = NULL;
2614 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2615 struct extent_state *cached_state = NULL;
2616 struct new_sa_defrag_extent *new = NULL;
2617 int compress_type = 0;
2621 nolock = btrfs_is_free_space_inode(inode);
2623 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2628 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2629 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2630 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2632 trans = btrfs_join_transaction_nolock(root);
2634 trans = btrfs_join_transaction(root);
2635 if (IS_ERR(trans)) {
2636 ret = PTR_ERR(trans);
2640 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2641 ret = btrfs_update_inode_fallback(trans, root, inode);
2642 if (ret) /* -ENOMEM or corruption */
2643 btrfs_abort_transaction(trans, root, ret);
2647 lock_extent_bits(io_tree, ordered_extent->file_offset,
2648 ordered_extent->file_offset + ordered_extent->len - 1,
2651 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2652 ordered_extent->file_offset + ordered_extent->len - 1,
2653 EXTENT_DEFRAG, 1, cached_state);
2655 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2656 if (last_snapshot >= BTRFS_I(inode)->generation)
2657 /* the inode is shared */
2658 new = record_old_file_extents(inode, ordered_extent);
2660 clear_extent_bit(io_tree, ordered_extent->file_offset,
2661 ordered_extent->file_offset + ordered_extent->len - 1,
2662 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2666 trans = btrfs_join_transaction_nolock(root);
2668 trans = btrfs_join_transaction(root);
2669 if (IS_ERR(trans)) {
2670 ret = PTR_ERR(trans);
2674 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2676 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2677 compress_type = ordered_extent->compress_type;
2678 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2679 BUG_ON(compress_type);
2680 ret = btrfs_mark_extent_written(trans, inode,
2681 ordered_extent->file_offset,
2682 ordered_extent->file_offset +
2683 ordered_extent->len);
2685 BUG_ON(root == root->fs_info->tree_root);
2686 ret = insert_reserved_file_extent(trans, inode,
2687 ordered_extent->file_offset,
2688 ordered_extent->start,
2689 ordered_extent->disk_len,
2690 ordered_extent->len,
2691 ordered_extent->len,
2692 compress_type, 0, 0,
2693 BTRFS_FILE_EXTENT_REG);
2695 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2696 ordered_extent->file_offset, ordered_extent->len,
2699 btrfs_abort_transaction(trans, root, ret);
2703 add_pending_csums(trans, inode, ordered_extent->file_offset,
2704 &ordered_extent->list);
2706 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2707 ret = btrfs_update_inode_fallback(trans, root, inode);
2708 if (ret) { /* -ENOMEM or corruption */
2709 btrfs_abort_transaction(trans, root, ret);
2714 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2715 ordered_extent->file_offset +
2716 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2718 if (root != root->fs_info->tree_root)
2719 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2721 btrfs_end_transaction(trans, root);
2724 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2725 ordered_extent->file_offset +
2726 ordered_extent->len - 1, NULL, GFP_NOFS);
2729 * If the ordered extent had an IOERR or something else went
2730 * wrong we need to return the space for this ordered extent
2731 * back to the allocator.
2733 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2734 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2735 btrfs_free_reserved_extent(root, ordered_extent->start,
2736 ordered_extent->disk_len);
2741 * This needs to be done to make sure anybody waiting knows we are done
2742 * updating everything for this ordered extent.
2744 btrfs_remove_ordered_extent(inode, ordered_extent);
2746 /* for snapshot-aware defrag */
2748 relink_file_extents(new);
2751 btrfs_put_ordered_extent(ordered_extent);
2752 /* once for the tree */
2753 btrfs_put_ordered_extent(ordered_extent);
2758 static void finish_ordered_fn(struct btrfs_work *work)
2760 struct btrfs_ordered_extent *ordered_extent;
2761 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2762 btrfs_finish_ordered_io(ordered_extent);
2765 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2766 struct extent_state *state, int uptodate)
2768 struct inode *inode = page->mapping->host;
2769 struct btrfs_root *root = BTRFS_I(inode)->root;
2770 struct btrfs_ordered_extent *ordered_extent = NULL;
2771 struct btrfs_workers *workers;
2773 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2775 ClearPagePrivate2(page);
2776 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2777 end - start + 1, uptodate))
2780 ordered_extent->work.func = finish_ordered_fn;
2781 ordered_extent->work.flags = 0;
2783 if (btrfs_is_free_space_inode(inode))
2784 workers = &root->fs_info->endio_freespace_worker;
2786 workers = &root->fs_info->endio_write_workers;
2787 btrfs_queue_worker(workers, &ordered_extent->work);
2793 * when reads are done, we need to check csums to verify the data is correct
2794 * if there's a match, we allow the bio to finish. If not, the code in
2795 * extent_io.c will try to find good copies for us.
2797 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2798 u64 phy_offset, struct page *page,
2799 u64 start, u64 end, int mirror)
2801 size_t offset = start - page_offset(page);
2802 struct inode *inode = page->mapping->host;
2803 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2805 struct btrfs_root *root = BTRFS_I(inode)->root;
2808 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2809 DEFAULT_RATELIMIT_BURST);
2811 if (PageChecked(page)) {
2812 ClearPageChecked(page);
2816 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2819 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2820 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2821 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2826 phy_offset >>= inode->i_sb->s_blocksize_bits;
2827 csum_expected = *(((u32 *)io_bio->csum) + phy_offset);
2829 kaddr = kmap_atomic(page);
2830 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2831 btrfs_csum_final(csum, (char *)&csum);
2832 if (csum != csum_expected)
2835 kunmap_atomic(kaddr);
2840 if (__ratelimit(&_rs))
2841 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
2842 (unsigned long long)btrfs_ino(page->mapping->host),
2843 (unsigned long long)start, csum, csum_expected);
2844 memset(kaddr + offset, 1, end - start + 1);
2845 flush_dcache_page(page);
2846 kunmap_atomic(kaddr);
2847 if (csum_expected == 0)
2852 struct delayed_iput {
2853 struct list_head list;
2854 struct inode *inode;
2857 /* JDM: If this is fs-wide, why can't we add a pointer to
2858 * btrfs_inode instead and avoid the allocation? */
2859 void btrfs_add_delayed_iput(struct inode *inode)
2861 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2862 struct delayed_iput *delayed;
2864 if (atomic_add_unless(&inode->i_count, -1, 1))
2867 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2868 delayed->inode = inode;
2870 spin_lock(&fs_info->delayed_iput_lock);
2871 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2872 spin_unlock(&fs_info->delayed_iput_lock);
2875 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2878 struct btrfs_fs_info *fs_info = root->fs_info;
2879 struct delayed_iput *delayed;
2882 spin_lock(&fs_info->delayed_iput_lock);
2883 empty = list_empty(&fs_info->delayed_iputs);
2884 spin_unlock(&fs_info->delayed_iput_lock);
2888 spin_lock(&fs_info->delayed_iput_lock);
2889 list_splice_init(&fs_info->delayed_iputs, &list);
2890 spin_unlock(&fs_info->delayed_iput_lock);
2892 while (!list_empty(&list)) {
2893 delayed = list_entry(list.next, struct delayed_iput, list);
2894 list_del(&delayed->list);
2895 iput(delayed->inode);
2901 * This is called in transaction commit time. If there are no orphan
2902 * files in the subvolume, it removes orphan item and frees block_rsv
2905 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2906 struct btrfs_root *root)
2908 struct btrfs_block_rsv *block_rsv;
2911 if (atomic_read(&root->orphan_inodes) ||
2912 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2915 spin_lock(&root->orphan_lock);
2916 if (atomic_read(&root->orphan_inodes)) {
2917 spin_unlock(&root->orphan_lock);
2921 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2922 spin_unlock(&root->orphan_lock);
2926 block_rsv = root->orphan_block_rsv;
2927 root->orphan_block_rsv = NULL;
2928 spin_unlock(&root->orphan_lock);
2930 if (root->orphan_item_inserted &&
2931 btrfs_root_refs(&root->root_item) > 0) {
2932 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2933 root->root_key.objectid);
2935 root->orphan_item_inserted = 0;
2939 WARN_ON(block_rsv->size > 0);
2940 btrfs_free_block_rsv(root, block_rsv);
2945 * This creates an orphan entry for the given inode in case something goes
2946 * wrong in the middle of an unlink/truncate.
2948 * NOTE: caller of this function should reserve 5 units of metadata for
2951 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2953 struct btrfs_root *root = BTRFS_I(inode)->root;
2954 struct btrfs_block_rsv *block_rsv = NULL;
2959 if (!root->orphan_block_rsv) {
2960 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2965 spin_lock(&root->orphan_lock);
2966 if (!root->orphan_block_rsv) {
2967 root->orphan_block_rsv = block_rsv;
2968 } else if (block_rsv) {
2969 btrfs_free_block_rsv(root, block_rsv);
2973 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2974 &BTRFS_I(inode)->runtime_flags)) {
2977 * For proper ENOSPC handling, we should do orphan
2978 * cleanup when mounting. But this introduces backward
2979 * compatibility issue.
2981 if (!xchg(&root->orphan_item_inserted, 1))
2987 atomic_inc(&root->orphan_inodes);
2990 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2991 &BTRFS_I(inode)->runtime_flags))
2993 spin_unlock(&root->orphan_lock);
2995 /* grab metadata reservation from transaction handle */
2997 ret = btrfs_orphan_reserve_metadata(trans, inode);
2998 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3001 /* insert an orphan item to track this unlinked/truncated file */
3003 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3004 if (ret && ret != -EEXIST) {
3005 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3006 &BTRFS_I(inode)->runtime_flags);
3007 btrfs_abort_transaction(trans, root, ret);
3013 /* insert an orphan item to track subvolume contains orphan files */
3015 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3016 root->root_key.objectid);
3017 if (ret && ret != -EEXIST) {
3018 btrfs_abort_transaction(trans, root, ret);
3026 * We have done the truncate/delete so we can go ahead and remove the orphan
3027 * item for this particular inode.
3029 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3030 struct inode *inode)
3032 struct btrfs_root *root = BTRFS_I(inode)->root;
3033 int delete_item = 0;
3034 int release_rsv = 0;
3037 spin_lock(&root->orphan_lock);
3038 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3039 &BTRFS_I(inode)->runtime_flags))
3042 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3043 &BTRFS_I(inode)->runtime_flags))
3045 spin_unlock(&root->orphan_lock);
3047 if (trans && delete_item) {
3048 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3049 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3053 btrfs_orphan_release_metadata(inode);
3054 atomic_dec(&root->orphan_inodes);
3061 * this cleans up any orphans that may be left on the list from the last use
3064 int btrfs_orphan_cleanup(struct btrfs_root *root)
3066 struct btrfs_path *path;
3067 struct extent_buffer *leaf;
3068 struct btrfs_key key, found_key;
3069 struct btrfs_trans_handle *trans;
3070 struct inode *inode;
3071 u64 last_objectid = 0;
3072 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3074 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3077 path = btrfs_alloc_path();
3084 key.objectid = BTRFS_ORPHAN_OBJECTID;
3085 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3086 key.offset = (u64)-1;
3089 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3094 * if ret == 0 means we found what we were searching for, which
3095 * is weird, but possible, so only screw with path if we didn't
3096 * find the key and see if we have stuff that matches
3100 if (path->slots[0] == 0)
3105 /* pull out the item */
3106 leaf = path->nodes[0];
3107 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3109 /* make sure the item matches what we want */
3110 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3112 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3115 /* release the path since we're done with it */
3116 btrfs_release_path(path);
3119 * this is where we are basically btrfs_lookup, without the
3120 * crossing root thing. we store the inode number in the
3121 * offset of the orphan item.
3124 if (found_key.offset == last_objectid) {
3125 btrfs_err(root->fs_info,
3126 "Error removing orphan entry, stopping orphan cleanup");
3131 last_objectid = found_key.offset;
3133 found_key.objectid = found_key.offset;
3134 found_key.type = BTRFS_INODE_ITEM_KEY;
3135 found_key.offset = 0;
3136 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3137 ret = PTR_RET(inode);
3138 if (ret && ret != -ESTALE)
3141 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3142 struct btrfs_root *dead_root;
3143 struct btrfs_fs_info *fs_info = root->fs_info;
3144 int is_dead_root = 0;
3147 * this is an orphan in the tree root. Currently these
3148 * could come from 2 sources:
3149 * a) a snapshot deletion in progress
3150 * b) a free space cache inode
3151 * We need to distinguish those two, as the snapshot
3152 * orphan must not get deleted.
3153 * find_dead_roots already ran before us, so if this
3154 * is a snapshot deletion, we should find the root
3155 * in the dead_roots list
3157 spin_lock(&fs_info->trans_lock);
3158 list_for_each_entry(dead_root, &fs_info->dead_roots,
3160 if (dead_root->root_key.objectid ==
3161 found_key.objectid) {
3166 spin_unlock(&fs_info->trans_lock);
3168 /* prevent this orphan from being found again */
3169 key.offset = found_key.objectid - 1;
3174 * Inode is already gone but the orphan item is still there,
3175 * kill the orphan item.
3177 if (ret == -ESTALE) {
3178 trans = btrfs_start_transaction(root, 1);
3179 if (IS_ERR(trans)) {
3180 ret = PTR_ERR(trans);
3183 btrfs_debug(root->fs_info, "auto deleting %Lu",
3184 found_key.objectid);
3185 ret = btrfs_del_orphan_item(trans, root,
3186 found_key.objectid);
3187 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3188 btrfs_end_transaction(trans, root);
3193 * add this inode to the orphan list so btrfs_orphan_del does
3194 * the proper thing when we hit it
3196 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3197 &BTRFS_I(inode)->runtime_flags);
3198 atomic_inc(&root->orphan_inodes);
3200 /* if we have links, this was a truncate, lets do that */
3201 if (inode->i_nlink) {
3202 if (!S_ISREG(inode->i_mode)) {
3209 /* 1 for the orphan item deletion. */
3210 trans = btrfs_start_transaction(root, 1);
3211 if (IS_ERR(trans)) {
3213 ret = PTR_ERR(trans);
3216 ret = btrfs_orphan_add(trans, inode);
3217 btrfs_end_transaction(trans, root);
3223 ret = btrfs_truncate(inode);
3225 btrfs_orphan_del(NULL, inode);
3230 /* this will do delete_inode and everything for us */
3235 /* release the path since we're done with it */
3236 btrfs_release_path(path);
3238 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3240 if (root->orphan_block_rsv)
3241 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3244 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3245 trans = btrfs_join_transaction(root);
3247 btrfs_end_transaction(trans, root);
3251 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3253 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3257 btrfs_crit(root->fs_info,
3258 "could not do orphan cleanup %d", ret);
3259 btrfs_free_path(path);
3264 * very simple check to peek ahead in the leaf looking for xattrs. If we
3265 * don't find any xattrs, we know there can't be any acls.
3267 * slot is the slot the inode is in, objectid is the objectid of the inode
3269 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3270 int slot, u64 objectid)
3272 u32 nritems = btrfs_header_nritems(leaf);
3273 struct btrfs_key found_key;
3274 static u64 xattr_access = 0;
3275 static u64 xattr_default = 0;
3278 if (!xattr_access) {
3279 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3280 strlen(POSIX_ACL_XATTR_ACCESS));
3281 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3282 strlen(POSIX_ACL_XATTR_DEFAULT));
3286 while (slot < nritems) {
3287 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3289 /* we found a different objectid, there must not be acls */
3290 if (found_key.objectid != objectid)
3293 /* we found an xattr, assume we've got an acl */
3294 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3295 if (found_key.offset == xattr_access ||
3296 found_key.offset == xattr_default)
3301 * we found a key greater than an xattr key, there can't
3302 * be any acls later on
3304 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3311 * it goes inode, inode backrefs, xattrs, extents,
3312 * so if there are a ton of hard links to an inode there can
3313 * be a lot of backrefs. Don't waste time searching too hard,
3314 * this is just an optimization
3319 /* we hit the end of the leaf before we found an xattr or
3320 * something larger than an xattr. We have to assume the inode
3327 * read an inode from the btree into the in-memory inode
3329 static void btrfs_read_locked_inode(struct inode *inode)
3331 struct btrfs_path *path;
3332 struct extent_buffer *leaf;
3333 struct btrfs_inode_item *inode_item;
3334 struct btrfs_timespec *tspec;
3335 struct btrfs_root *root = BTRFS_I(inode)->root;
3336 struct btrfs_key location;
3340 bool filled = false;
3342 ret = btrfs_fill_inode(inode, &rdev);
3346 path = btrfs_alloc_path();
3350 path->leave_spinning = 1;
3351 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3353 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3357 leaf = path->nodes[0];
3362 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3363 struct btrfs_inode_item);
3364 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3365 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3366 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3367 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3368 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3370 tspec = btrfs_inode_atime(inode_item);
3371 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3372 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3374 tspec = btrfs_inode_mtime(inode_item);
3375 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3376 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3378 tspec = btrfs_inode_ctime(inode_item);
3379 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3380 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3382 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3383 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3384 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3387 * If we were modified in the current generation and evicted from memory
3388 * and then re-read we need to do a full sync since we don't have any
3389 * idea about which extents were modified before we were evicted from
3392 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3393 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3394 &BTRFS_I(inode)->runtime_flags);
3396 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3397 inode->i_generation = BTRFS_I(inode)->generation;
3399 rdev = btrfs_inode_rdev(leaf, inode_item);
3401 BTRFS_I(inode)->index_cnt = (u64)-1;
3402 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3405 * try to precache a NULL acl entry for files that don't have
3406 * any xattrs or acls
3408 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3411 cache_no_acl(inode);
3413 btrfs_free_path(path);
3415 switch (inode->i_mode & S_IFMT) {
3417 inode->i_mapping->a_ops = &btrfs_aops;
3418 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3419 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3420 inode->i_fop = &btrfs_file_operations;
3421 inode->i_op = &btrfs_file_inode_operations;
3424 inode->i_fop = &btrfs_dir_file_operations;
3425 if (root == root->fs_info->tree_root)
3426 inode->i_op = &btrfs_dir_ro_inode_operations;
3428 inode->i_op = &btrfs_dir_inode_operations;
3431 inode->i_op = &btrfs_symlink_inode_operations;
3432 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3433 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3436 inode->i_op = &btrfs_special_inode_operations;
3437 init_special_inode(inode, inode->i_mode, rdev);
3441 btrfs_update_iflags(inode);
3445 btrfs_free_path(path);
3446 make_bad_inode(inode);
3450 * given a leaf and an inode, copy the inode fields into the leaf
3452 static void fill_inode_item(struct btrfs_trans_handle *trans,
3453 struct extent_buffer *leaf,
3454 struct btrfs_inode_item *item,
3455 struct inode *inode)
3457 struct btrfs_map_token token;
3459 btrfs_init_map_token(&token);
3461 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3462 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3463 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3465 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3466 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3468 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3469 inode->i_atime.tv_sec, &token);
3470 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3471 inode->i_atime.tv_nsec, &token);
3473 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3474 inode->i_mtime.tv_sec, &token);
3475 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3476 inode->i_mtime.tv_nsec, &token);
3478 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3479 inode->i_ctime.tv_sec, &token);
3480 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3481 inode->i_ctime.tv_nsec, &token);
3483 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3485 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3487 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3488 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3489 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3490 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3491 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3495 * copy everything in the in-memory inode into the btree.
3497 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3498 struct btrfs_root *root, struct inode *inode)
3500 struct btrfs_inode_item *inode_item;
3501 struct btrfs_path *path;
3502 struct extent_buffer *leaf;
3505 path = btrfs_alloc_path();
3509 path->leave_spinning = 1;
3510 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3518 btrfs_unlock_up_safe(path, 1);
3519 leaf = path->nodes[0];
3520 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3521 struct btrfs_inode_item);
3523 fill_inode_item(trans, leaf, inode_item, inode);
3524 btrfs_mark_buffer_dirty(leaf);
3525 btrfs_set_inode_last_trans(trans, inode);
3528 btrfs_free_path(path);
3533 * copy everything in the in-memory inode into the btree.
3535 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3536 struct btrfs_root *root, struct inode *inode)
3541 * If the inode is a free space inode, we can deadlock during commit
3542 * if we put it into the delayed code.
3544 * The data relocation inode should also be directly updated
3547 if (!btrfs_is_free_space_inode(inode)
3548 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3549 btrfs_update_root_times(trans, root);
3551 ret = btrfs_delayed_update_inode(trans, root, inode);
3553 btrfs_set_inode_last_trans(trans, inode);
3557 return btrfs_update_inode_item(trans, root, inode);
3560 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3561 struct btrfs_root *root,
3562 struct inode *inode)
3566 ret = btrfs_update_inode(trans, root, inode);
3568 return btrfs_update_inode_item(trans, root, inode);
3573 * unlink helper that gets used here in inode.c and in the tree logging
3574 * recovery code. It remove a link in a directory with a given name, and
3575 * also drops the back refs in the inode to the directory
3577 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3578 struct btrfs_root *root,
3579 struct inode *dir, struct inode *inode,
3580 const char *name, int name_len)
3582 struct btrfs_path *path;
3584 struct extent_buffer *leaf;
3585 struct btrfs_dir_item *di;
3586 struct btrfs_key key;
3588 u64 ino = btrfs_ino(inode);
3589 u64 dir_ino = btrfs_ino(dir);
3591 path = btrfs_alloc_path();
3597 path->leave_spinning = 1;
3598 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3599 name, name_len, -1);
3608 leaf = path->nodes[0];
3609 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3610 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3613 btrfs_release_path(path);
3615 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3618 btrfs_info(root->fs_info,
3619 "failed to delete reference to %.*s, inode %llu parent %llu",
3621 (unsigned long long)ino, (unsigned long long)dir_ino);
3622 btrfs_abort_transaction(trans, root, ret);
3626 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3628 btrfs_abort_transaction(trans, root, ret);
3632 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3634 if (ret != 0 && ret != -ENOENT) {
3635 btrfs_abort_transaction(trans, root, ret);
3639 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3644 btrfs_abort_transaction(trans, root, ret);
3646 btrfs_free_path(path);
3650 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3651 inode_inc_iversion(inode);
3652 inode_inc_iversion(dir);
3653 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3654 ret = btrfs_update_inode(trans, root, dir);
3659 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3660 struct btrfs_root *root,
3661 struct inode *dir, struct inode *inode,
3662 const char *name, int name_len)
3665 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3667 btrfs_drop_nlink(inode);
3668 ret = btrfs_update_inode(trans, root, inode);
3674 * helper to start transaction for unlink and rmdir.
3676 * unlink and rmdir are special in btrfs, they do not always free space, so
3677 * if we cannot make our reservations the normal way try and see if there is
3678 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3679 * allow the unlink to occur.
3681 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3683 struct btrfs_trans_handle *trans;
3684 struct btrfs_root *root = BTRFS_I(dir)->root;
3688 * 1 for the possible orphan item
3689 * 1 for the dir item
3690 * 1 for the dir index
3691 * 1 for the inode ref
3694 trans = btrfs_start_transaction(root, 5);
3695 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3698 if (PTR_ERR(trans) == -ENOSPC) {
3699 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3701 trans = btrfs_start_transaction(root, 0);
3704 ret = btrfs_cond_migrate_bytes(root->fs_info,
3705 &root->fs_info->trans_block_rsv,
3708 btrfs_end_transaction(trans, root);
3709 return ERR_PTR(ret);
3711 trans->block_rsv = &root->fs_info->trans_block_rsv;
3712 trans->bytes_reserved = num_bytes;
3717 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3719 struct btrfs_root *root = BTRFS_I(dir)->root;
3720 struct btrfs_trans_handle *trans;
3721 struct inode *inode = dentry->d_inode;
3724 trans = __unlink_start_trans(dir);
3726 return PTR_ERR(trans);
3728 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3730 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3731 dentry->d_name.name, dentry->d_name.len);
3735 if (inode->i_nlink == 0) {
3736 ret = btrfs_orphan_add(trans, inode);
3742 btrfs_end_transaction(trans, root);
3743 btrfs_btree_balance_dirty(root);
3747 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3748 struct btrfs_root *root,
3749 struct inode *dir, u64 objectid,
3750 const char *name, int name_len)
3752 struct btrfs_path *path;
3753 struct extent_buffer *leaf;
3754 struct btrfs_dir_item *di;
3755 struct btrfs_key key;
3758 u64 dir_ino = btrfs_ino(dir);
3760 path = btrfs_alloc_path();
3764 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3765 name, name_len, -1);
3766 if (IS_ERR_OR_NULL(di)) {
3774 leaf = path->nodes[0];
3775 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3776 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3777 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3779 btrfs_abort_transaction(trans, root, ret);
3782 btrfs_release_path(path);
3784 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3785 objectid, root->root_key.objectid,
3786 dir_ino, &index, name, name_len);
3788 if (ret != -ENOENT) {
3789 btrfs_abort_transaction(trans, root, ret);
3792 di = btrfs_search_dir_index_item(root, path, dir_ino,
3794 if (IS_ERR_OR_NULL(di)) {
3799 btrfs_abort_transaction(trans, root, ret);
3803 leaf = path->nodes[0];
3804 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3805 btrfs_release_path(path);
3808 btrfs_release_path(path);
3810 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3812 btrfs_abort_transaction(trans, root, ret);
3816 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3817 inode_inc_iversion(dir);
3818 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3819 ret = btrfs_update_inode_fallback(trans, root, dir);
3821 btrfs_abort_transaction(trans, root, ret);
3823 btrfs_free_path(path);
3827 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3829 struct inode *inode = dentry->d_inode;
3831 struct btrfs_root *root = BTRFS_I(dir)->root;
3832 struct btrfs_trans_handle *trans;
3834 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3836 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3839 trans = __unlink_start_trans(dir);
3841 return PTR_ERR(trans);
3843 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3844 err = btrfs_unlink_subvol(trans, root, dir,
3845 BTRFS_I(inode)->location.objectid,
3846 dentry->d_name.name,
3847 dentry->d_name.len);
3851 err = btrfs_orphan_add(trans, inode);
3855 /* now the directory is empty */
3856 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3857 dentry->d_name.name, dentry->d_name.len);
3859 btrfs_i_size_write(inode, 0);
3861 btrfs_end_transaction(trans, root);
3862 btrfs_btree_balance_dirty(root);
3868 * this can truncate away extent items, csum items and directory items.
3869 * It starts at a high offset and removes keys until it can't find
3870 * any higher than new_size
3872 * csum items that cross the new i_size are truncated to the new size
3875 * min_type is the minimum key type to truncate down to. If set to 0, this
3876 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3878 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3879 struct btrfs_root *root,
3880 struct inode *inode,
3881 u64 new_size, u32 min_type)
3883 struct btrfs_path *path;
3884 struct extent_buffer *leaf;
3885 struct btrfs_file_extent_item *fi;
3886 struct btrfs_key key;
3887 struct btrfs_key found_key;
3888 u64 extent_start = 0;
3889 u64 extent_num_bytes = 0;
3890 u64 extent_offset = 0;
3892 u32 found_type = (u8)-1;
3895 int pending_del_nr = 0;
3896 int pending_del_slot = 0;
3897 int extent_type = -1;
3900 u64 ino = btrfs_ino(inode);
3902 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3904 path = btrfs_alloc_path();
3910 * We want to drop from the next block forward in case this new size is
3911 * not block aligned since we will be keeping the last block of the
3912 * extent just the way it is.
3914 if (root->ref_cows || root == root->fs_info->tree_root)
3915 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3916 root->sectorsize), (u64)-1, 0);
3919 * This function is also used to drop the items in the log tree before
3920 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3921 * it is used to drop the loged items. So we shouldn't kill the delayed
3924 if (min_type == 0 && root == BTRFS_I(inode)->root)
3925 btrfs_kill_delayed_inode_items(inode);
3928 key.offset = (u64)-1;
3932 path->leave_spinning = 1;
3933 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3940 /* there are no items in the tree for us to truncate, we're
3943 if (path->slots[0] == 0)
3950 leaf = path->nodes[0];
3951 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3952 found_type = btrfs_key_type(&found_key);
3954 if (found_key.objectid != ino)
3957 if (found_type < min_type)
3960 item_end = found_key.offset;
3961 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3962 fi = btrfs_item_ptr(leaf, path->slots[0],
3963 struct btrfs_file_extent_item);
3964 extent_type = btrfs_file_extent_type(leaf, fi);
3965 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3967 btrfs_file_extent_num_bytes(leaf, fi);
3968 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3969 item_end += btrfs_file_extent_inline_len(leaf,
3974 if (found_type > min_type) {
3977 if (item_end < new_size)
3979 if (found_key.offset >= new_size)
3985 /* FIXME, shrink the extent if the ref count is only 1 */
3986 if (found_type != BTRFS_EXTENT_DATA_KEY)
3989 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3991 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3993 u64 orig_num_bytes =
3994 btrfs_file_extent_num_bytes(leaf, fi);
3995 extent_num_bytes = ALIGN(new_size -
3998 btrfs_set_file_extent_num_bytes(leaf, fi,
4000 num_dec = (orig_num_bytes -
4002 if (root->ref_cows && extent_start != 0)
4003 inode_sub_bytes(inode, num_dec);
4004 btrfs_mark_buffer_dirty(leaf);
4007 btrfs_file_extent_disk_num_bytes(leaf,
4009 extent_offset = found_key.offset -
4010 btrfs_file_extent_offset(leaf, fi);
4012 /* FIXME blocksize != 4096 */
4013 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4014 if (extent_start != 0) {
4017 inode_sub_bytes(inode, num_dec);
4020 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4022 * we can't truncate inline items that have had
4026 btrfs_file_extent_compression(leaf, fi) == 0 &&
4027 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4028 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4029 u32 size = new_size - found_key.offset;
4031 if (root->ref_cows) {
4032 inode_sub_bytes(inode, item_end + 1 -
4036 btrfs_file_extent_calc_inline_size(size);
4037 btrfs_truncate_item(root, path, size, 1);
4038 } else if (root->ref_cows) {
4039 inode_sub_bytes(inode, item_end + 1 -
4045 if (!pending_del_nr) {
4046 /* no pending yet, add ourselves */
4047 pending_del_slot = path->slots[0];
4049 } else if (pending_del_nr &&
4050 path->slots[0] + 1 == pending_del_slot) {
4051 /* hop on the pending chunk */
4053 pending_del_slot = path->slots[0];
4060 if (found_extent && (root->ref_cows ||
4061 root == root->fs_info->tree_root)) {
4062 btrfs_set_path_blocking(path);
4063 ret = btrfs_free_extent(trans, root, extent_start,
4064 extent_num_bytes, 0,
4065 btrfs_header_owner(leaf),
4066 ino, extent_offset, 0);
4070 if (found_type == BTRFS_INODE_ITEM_KEY)
4073 if (path->slots[0] == 0 ||
4074 path->slots[0] != pending_del_slot) {
4075 if (pending_del_nr) {
4076 ret = btrfs_del_items(trans, root, path,
4080 btrfs_abort_transaction(trans,
4086 btrfs_release_path(path);
4093 if (pending_del_nr) {
4094 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4097 btrfs_abort_transaction(trans, root, ret);
4100 btrfs_free_path(path);
4105 * btrfs_truncate_page - read, zero a chunk and write a page
4106 * @inode - inode that we're zeroing
4107 * @from - the offset to start zeroing
4108 * @len - the length to zero, 0 to zero the entire range respective to the
4110 * @front - zero up to the offset instead of from the offset on
4112 * This will find the page for the "from" offset and cow the page and zero the
4113 * part we want to zero. This is used with truncate and hole punching.
4115 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4118 struct address_space *mapping = inode->i_mapping;
4119 struct btrfs_root *root = BTRFS_I(inode)->root;
4120 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4121 struct btrfs_ordered_extent *ordered;
4122 struct extent_state *cached_state = NULL;
4124 u32 blocksize = root->sectorsize;
4125 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4126 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4128 gfp_t mask = btrfs_alloc_write_mask(mapping);
4133 if ((offset & (blocksize - 1)) == 0 &&
4134 (!len || ((len & (blocksize - 1)) == 0)))
4136 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4141 page = find_or_create_page(mapping, index, mask);
4143 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4148 page_start = page_offset(page);
4149 page_end = page_start + PAGE_CACHE_SIZE - 1;
4151 if (!PageUptodate(page)) {
4152 ret = btrfs_readpage(NULL, page);
4154 if (page->mapping != mapping) {
4156 page_cache_release(page);
4159 if (!PageUptodate(page)) {
4164 wait_on_page_writeback(page);
4166 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4167 set_page_extent_mapped(page);
4169 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4171 unlock_extent_cached(io_tree, page_start, page_end,
4172 &cached_state, GFP_NOFS);
4174 page_cache_release(page);
4175 btrfs_start_ordered_extent(inode, ordered, 1);
4176 btrfs_put_ordered_extent(ordered);
4180 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4181 EXTENT_DIRTY | EXTENT_DELALLOC |
4182 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4183 0, 0, &cached_state, GFP_NOFS);
4185 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4188 unlock_extent_cached(io_tree, page_start, page_end,
4189 &cached_state, GFP_NOFS);
4193 if (offset != PAGE_CACHE_SIZE) {
4195 len = PAGE_CACHE_SIZE - offset;
4198 memset(kaddr, 0, offset);
4200 memset(kaddr + offset, 0, len);
4201 flush_dcache_page(page);
4204 ClearPageChecked(page);
4205 set_page_dirty(page);
4206 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4211 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4213 page_cache_release(page);
4219 * This function puts in dummy file extents for the area we're creating a hole
4220 * for. So if we are truncating this file to a larger size we need to insert
4221 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4222 * the range between oldsize and size
4224 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4226 struct btrfs_trans_handle *trans;
4227 struct btrfs_root *root = BTRFS_I(inode)->root;
4228 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4229 struct extent_map *em = NULL;
4230 struct extent_state *cached_state = NULL;
4231 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4232 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4233 u64 block_end = ALIGN(size, root->sectorsize);
4240 * If our size started in the middle of a page we need to zero out the
4241 * rest of the page before we expand the i_size, otherwise we could
4242 * expose stale data.
4244 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4248 if (size <= hole_start)
4252 struct btrfs_ordered_extent *ordered;
4253 btrfs_wait_ordered_range(inode, hole_start,
4254 block_end - hole_start);
4255 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4257 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4260 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4261 &cached_state, GFP_NOFS);
4262 btrfs_put_ordered_extent(ordered);
4265 cur_offset = hole_start;
4267 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4268 block_end - cur_offset, 0);
4274 last_byte = min(extent_map_end(em), block_end);
4275 last_byte = ALIGN(last_byte , root->sectorsize);
4276 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4277 struct extent_map *hole_em;
4278 hole_size = last_byte - cur_offset;
4280 trans = btrfs_start_transaction(root, 3);
4281 if (IS_ERR(trans)) {
4282 err = PTR_ERR(trans);
4286 err = btrfs_drop_extents(trans, root, inode,
4288 cur_offset + hole_size, 1);
4290 btrfs_abort_transaction(trans, root, err);
4291 btrfs_end_transaction(trans, root);
4295 err = btrfs_insert_file_extent(trans, root,
4296 btrfs_ino(inode), cur_offset, 0,
4297 0, hole_size, 0, hole_size,
4300 btrfs_abort_transaction(trans, root, err);
4301 btrfs_end_transaction(trans, root);
4305 btrfs_drop_extent_cache(inode, cur_offset,
4306 cur_offset + hole_size - 1, 0);
4307 hole_em = alloc_extent_map();
4309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4310 &BTRFS_I(inode)->runtime_flags);
4313 hole_em->start = cur_offset;
4314 hole_em->len = hole_size;
4315 hole_em->orig_start = cur_offset;
4317 hole_em->block_start = EXTENT_MAP_HOLE;
4318 hole_em->block_len = 0;
4319 hole_em->orig_block_len = 0;
4320 hole_em->ram_bytes = hole_size;
4321 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4322 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4323 hole_em->generation = trans->transid;
4326 write_lock(&em_tree->lock);
4327 err = add_extent_mapping(em_tree, hole_em, 1);
4328 write_unlock(&em_tree->lock);
4331 btrfs_drop_extent_cache(inode, cur_offset,
4335 free_extent_map(hole_em);
4337 btrfs_update_inode(trans, root, inode);
4338 btrfs_end_transaction(trans, root);
4340 free_extent_map(em);
4342 cur_offset = last_byte;
4343 if (cur_offset >= block_end)
4347 free_extent_map(em);
4348 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4353 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4355 struct btrfs_root *root = BTRFS_I(inode)->root;
4356 struct btrfs_trans_handle *trans;
4357 loff_t oldsize = i_size_read(inode);
4358 loff_t newsize = attr->ia_size;
4359 int mask = attr->ia_valid;
4363 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4364 * special case where we need to update the times despite not having
4365 * these flags set. For all other operations the VFS set these flags
4366 * explicitly if it wants a timestamp update.
4368 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4369 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4371 if (newsize > oldsize) {
4372 truncate_pagecache(inode, oldsize, newsize);
4373 ret = btrfs_cont_expand(inode, oldsize, newsize);
4377 trans = btrfs_start_transaction(root, 1);
4379 return PTR_ERR(trans);
4381 i_size_write(inode, newsize);
4382 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4383 ret = btrfs_update_inode(trans, root, inode);
4384 btrfs_end_transaction(trans, root);
4388 * We're truncating a file that used to have good data down to
4389 * zero. Make sure it gets into the ordered flush list so that
4390 * any new writes get down to disk quickly.
4393 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4394 &BTRFS_I(inode)->runtime_flags);
4397 * 1 for the orphan item we're going to add
4398 * 1 for the orphan item deletion.
4400 trans = btrfs_start_transaction(root, 2);
4402 return PTR_ERR(trans);
4405 * We need to do this in case we fail at _any_ point during the
4406 * actual truncate. Once we do the truncate_setsize we could
4407 * invalidate pages which forces any outstanding ordered io to
4408 * be instantly completed which will give us extents that need
4409 * to be truncated. If we fail to get an orphan inode down we
4410 * could have left over extents that were never meant to live,
4411 * so we need to garuntee from this point on that everything
4412 * will be consistent.
4414 ret = btrfs_orphan_add(trans, inode);
4415 btrfs_end_transaction(trans, root);
4419 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4420 truncate_setsize(inode, newsize);
4422 /* Disable nonlocked read DIO to avoid the end less truncate */
4423 btrfs_inode_block_unlocked_dio(inode);
4424 inode_dio_wait(inode);
4425 btrfs_inode_resume_unlocked_dio(inode);
4427 ret = btrfs_truncate(inode);
4428 if (ret && inode->i_nlink)
4429 btrfs_orphan_del(NULL, inode);
4435 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4437 struct inode *inode = dentry->d_inode;
4438 struct btrfs_root *root = BTRFS_I(inode)->root;
4441 if (btrfs_root_readonly(root))
4444 err = inode_change_ok(inode, attr);
4448 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4449 err = btrfs_setsize(inode, attr);
4454 if (attr->ia_valid) {
4455 setattr_copy(inode, attr);
4456 inode_inc_iversion(inode);
4457 err = btrfs_dirty_inode(inode);
4459 if (!err && attr->ia_valid & ATTR_MODE)
4460 err = btrfs_acl_chmod(inode);
4466 void btrfs_evict_inode(struct inode *inode)
4468 struct btrfs_trans_handle *trans;
4469 struct btrfs_root *root = BTRFS_I(inode)->root;
4470 struct btrfs_block_rsv *rsv, *global_rsv;
4471 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4474 trace_btrfs_inode_evict(inode);
4476 truncate_inode_pages(&inode->i_data, 0);
4477 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4478 btrfs_is_free_space_inode(inode)))
4481 if (is_bad_inode(inode)) {
4482 btrfs_orphan_del(NULL, inode);
4485 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4486 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4488 if (root->fs_info->log_root_recovering) {
4489 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4490 &BTRFS_I(inode)->runtime_flags));
4494 if (inode->i_nlink > 0) {
4495 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4499 ret = btrfs_commit_inode_delayed_inode(inode);
4501 btrfs_orphan_del(NULL, inode);
4505 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4507 btrfs_orphan_del(NULL, inode);
4510 rsv->size = min_size;
4512 global_rsv = &root->fs_info->global_block_rsv;
4514 btrfs_i_size_write(inode, 0);
4517 * This is a bit simpler than btrfs_truncate since we've already
4518 * reserved our space for our orphan item in the unlink, so we just
4519 * need to reserve some slack space in case we add bytes and update
4520 * inode item when doing the truncate.
4523 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4524 BTRFS_RESERVE_FLUSH_LIMIT);
4527 * Try and steal from the global reserve since we will
4528 * likely not use this space anyway, we want to try as
4529 * hard as possible to get this to work.
4532 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4535 btrfs_warn(root->fs_info,
4536 "Could not get space for a delete, will truncate on mount %d",
4538 btrfs_orphan_del(NULL, inode);
4539 btrfs_free_block_rsv(root, rsv);
4543 trans = btrfs_join_transaction(root);
4544 if (IS_ERR(trans)) {
4545 btrfs_orphan_del(NULL, inode);
4546 btrfs_free_block_rsv(root, rsv);
4550 trans->block_rsv = rsv;
4552 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4556 trans->block_rsv = &root->fs_info->trans_block_rsv;
4557 btrfs_end_transaction(trans, root);
4559 btrfs_btree_balance_dirty(root);
4562 btrfs_free_block_rsv(root, rsv);
4565 trans->block_rsv = root->orphan_block_rsv;
4566 ret = btrfs_orphan_del(trans, inode);
4570 trans->block_rsv = &root->fs_info->trans_block_rsv;
4571 if (!(root == root->fs_info->tree_root ||
4572 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4573 btrfs_return_ino(root, btrfs_ino(inode));
4575 btrfs_end_transaction(trans, root);
4576 btrfs_btree_balance_dirty(root);
4578 btrfs_remove_delayed_node(inode);
4584 * this returns the key found in the dir entry in the location pointer.
4585 * If no dir entries were found, location->objectid is 0.
4587 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4588 struct btrfs_key *location)
4590 const char *name = dentry->d_name.name;
4591 int namelen = dentry->d_name.len;
4592 struct btrfs_dir_item *di;
4593 struct btrfs_path *path;
4594 struct btrfs_root *root = BTRFS_I(dir)->root;
4597 path = btrfs_alloc_path();
4601 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4606 if (IS_ERR_OR_NULL(di))
4609 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4611 btrfs_free_path(path);
4614 location->objectid = 0;
4619 * when we hit a tree root in a directory, the btrfs part of the inode
4620 * needs to be changed to reflect the root directory of the tree root. This
4621 * is kind of like crossing a mount point.
4623 static int fixup_tree_root_location(struct btrfs_root *root,
4625 struct dentry *dentry,
4626 struct btrfs_key *location,
4627 struct btrfs_root **sub_root)
4629 struct btrfs_path *path;
4630 struct btrfs_root *new_root;
4631 struct btrfs_root_ref *ref;
4632 struct extent_buffer *leaf;
4636 path = btrfs_alloc_path();
4643 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4644 BTRFS_I(dir)->root->root_key.objectid,
4645 location->objectid);
4652 leaf = path->nodes[0];
4653 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4654 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4655 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4658 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4659 (unsigned long)(ref + 1),
4660 dentry->d_name.len);
4664 btrfs_release_path(path);
4666 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4667 if (IS_ERR(new_root)) {
4668 err = PTR_ERR(new_root);
4672 *sub_root = new_root;
4673 location->objectid = btrfs_root_dirid(&new_root->root_item);
4674 location->type = BTRFS_INODE_ITEM_KEY;
4675 location->offset = 0;
4678 btrfs_free_path(path);
4682 static void inode_tree_add(struct inode *inode)
4684 struct btrfs_root *root = BTRFS_I(inode)->root;
4685 struct btrfs_inode *entry;
4687 struct rb_node *parent;
4688 u64 ino = btrfs_ino(inode);
4690 if (inode_unhashed(inode))
4694 spin_lock(&root->inode_lock);
4695 p = &root->inode_tree.rb_node;
4698 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4700 if (ino < btrfs_ino(&entry->vfs_inode))
4701 p = &parent->rb_left;
4702 else if (ino > btrfs_ino(&entry->vfs_inode))
4703 p = &parent->rb_right;
4705 WARN_ON(!(entry->vfs_inode.i_state &
4706 (I_WILL_FREE | I_FREEING)));
4707 rb_erase(parent, &root->inode_tree);
4708 RB_CLEAR_NODE(parent);
4709 spin_unlock(&root->inode_lock);
4713 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4714 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4715 spin_unlock(&root->inode_lock);
4718 static void inode_tree_del(struct inode *inode)
4720 struct btrfs_root *root = BTRFS_I(inode)->root;
4723 spin_lock(&root->inode_lock);
4724 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4725 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4726 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4727 empty = RB_EMPTY_ROOT(&root->inode_tree);
4729 spin_unlock(&root->inode_lock);
4732 * Free space cache has inodes in the tree root, but the tree root has a
4733 * root_refs of 0, so this could end up dropping the tree root as a
4734 * snapshot, so we need the extra !root->fs_info->tree_root check to
4735 * make sure we don't drop it.
4737 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4738 root != root->fs_info->tree_root) {
4739 synchronize_srcu(&root->fs_info->subvol_srcu);
4740 spin_lock(&root->inode_lock);
4741 empty = RB_EMPTY_ROOT(&root->inode_tree);
4742 spin_unlock(&root->inode_lock);
4744 btrfs_add_dead_root(root);
4748 void btrfs_invalidate_inodes(struct btrfs_root *root)
4750 struct rb_node *node;
4751 struct rb_node *prev;
4752 struct btrfs_inode *entry;
4753 struct inode *inode;
4756 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4758 spin_lock(&root->inode_lock);
4760 node = root->inode_tree.rb_node;
4764 entry = rb_entry(node, struct btrfs_inode, rb_node);
4766 if (objectid < btrfs_ino(&entry->vfs_inode))
4767 node = node->rb_left;
4768 else if (objectid > btrfs_ino(&entry->vfs_inode))
4769 node = node->rb_right;
4775 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4776 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4780 prev = rb_next(prev);
4784 entry = rb_entry(node, struct btrfs_inode, rb_node);
4785 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4786 inode = igrab(&entry->vfs_inode);
4788 spin_unlock(&root->inode_lock);
4789 if (atomic_read(&inode->i_count) > 1)
4790 d_prune_aliases(inode);
4792 * btrfs_drop_inode will have it removed from
4793 * the inode cache when its usage count
4798 spin_lock(&root->inode_lock);
4802 if (cond_resched_lock(&root->inode_lock))
4805 node = rb_next(node);
4807 spin_unlock(&root->inode_lock);
4810 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4812 struct btrfs_iget_args *args = p;
4813 inode->i_ino = args->ino;
4814 BTRFS_I(inode)->root = args->root;
4818 static int btrfs_find_actor(struct inode *inode, void *opaque)
4820 struct btrfs_iget_args *args = opaque;
4821 return args->ino == btrfs_ino(inode) &&
4822 args->root == BTRFS_I(inode)->root;
4825 static struct inode *btrfs_iget_locked(struct super_block *s,
4827 struct btrfs_root *root)
4829 struct inode *inode;
4830 struct btrfs_iget_args args;
4831 args.ino = objectid;
4834 inode = iget5_locked(s, objectid, btrfs_find_actor,
4835 btrfs_init_locked_inode,
4840 /* Get an inode object given its location and corresponding root.
4841 * Returns in *is_new if the inode was read from disk
4843 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4844 struct btrfs_root *root, int *new)
4846 struct inode *inode;
4848 inode = btrfs_iget_locked(s, location->objectid, root);
4850 return ERR_PTR(-ENOMEM);
4852 if (inode->i_state & I_NEW) {
4853 BTRFS_I(inode)->root = root;
4854 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4855 btrfs_read_locked_inode(inode);
4856 if (!is_bad_inode(inode)) {
4857 inode_tree_add(inode);
4858 unlock_new_inode(inode);
4862 unlock_new_inode(inode);
4864 inode = ERR_PTR(-ESTALE);
4871 static struct inode *new_simple_dir(struct super_block *s,
4872 struct btrfs_key *key,
4873 struct btrfs_root *root)
4875 struct inode *inode = new_inode(s);
4878 return ERR_PTR(-ENOMEM);
4880 BTRFS_I(inode)->root = root;
4881 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4882 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4884 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4885 inode->i_op = &btrfs_dir_ro_inode_operations;
4886 inode->i_fop = &simple_dir_operations;
4887 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4888 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4893 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4895 struct inode *inode;
4896 struct btrfs_root *root = BTRFS_I(dir)->root;
4897 struct btrfs_root *sub_root = root;
4898 struct btrfs_key location;
4902 if (dentry->d_name.len > BTRFS_NAME_LEN)
4903 return ERR_PTR(-ENAMETOOLONG);
4905 ret = btrfs_inode_by_name(dir, dentry, &location);
4907 return ERR_PTR(ret);
4909 if (location.objectid == 0)
4912 if (location.type == BTRFS_INODE_ITEM_KEY) {
4913 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4917 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4919 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4920 ret = fixup_tree_root_location(root, dir, dentry,
4921 &location, &sub_root);
4924 inode = ERR_PTR(ret);
4926 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4928 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4930 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4932 if (!IS_ERR(inode) && root != sub_root) {
4933 down_read(&root->fs_info->cleanup_work_sem);
4934 if (!(inode->i_sb->s_flags & MS_RDONLY))
4935 ret = btrfs_orphan_cleanup(sub_root);
4936 up_read(&root->fs_info->cleanup_work_sem);
4939 inode = ERR_PTR(ret);
4946 static int btrfs_dentry_delete(const struct dentry *dentry)
4948 struct btrfs_root *root;
4949 struct inode *inode = dentry->d_inode;
4951 if (!inode && !IS_ROOT(dentry))
4952 inode = dentry->d_parent->d_inode;
4955 root = BTRFS_I(inode)->root;
4956 if (btrfs_root_refs(&root->root_item) == 0)
4959 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4965 static void btrfs_dentry_release(struct dentry *dentry)
4967 if (dentry->d_fsdata)
4968 kfree(dentry->d_fsdata);
4971 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4976 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4980 unsigned char btrfs_filetype_table[] = {
4981 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4984 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
4986 struct inode *inode = file_inode(file);
4987 struct btrfs_root *root = BTRFS_I(inode)->root;
4988 struct btrfs_item *item;
4989 struct btrfs_dir_item *di;
4990 struct btrfs_key key;
4991 struct btrfs_key found_key;
4992 struct btrfs_path *path;
4993 struct list_head ins_list;
4994 struct list_head del_list;
4996 struct extent_buffer *leaf;
4998 unsigned char d_type;
5003 int key_type = BTRFS_DIR_INDEX_KEY;
5007 int is_curr = 0; /* ctx->pos points to the current index? */
5009 /* FIXME, use a real flag for deciding about the key type */
5010 if (root->fs_info->tree_root == root)
5011 key_type = BTRFS_DIR_ITEM_KEY;
5013 if (!dir_emit_dots(file, ctx))
5016 path = btrfs_alloc_path();
5022 if (key_type == BTRFS_DIR_INDEX_KEY) {
5023 INIT_LIST_HEAD(&ins_list);
5024 INIT_LIST_HEAD(&del_list);
5025 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5028 btrfs_set_key_type(&key, key_type);
5029 key.offset = ctx->pos;
5030 key.objectid = btrfs_ino(inode);
5032 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5037 leaf = path->nodes[0];
5038 slot = path->slots[0];
5039 if (slot >= btrfs_header_nritems(leaf)) {
5040 ret = btrfs_next_leaf(root, path);
5048 item = btrfs_item_nr(leaf, slot);
5049 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5051 if (found_key.objectid != key.objectid)
5053 if (btrfs_key_type(&found_key) != key_type)
5055 if (found_key.offset < ctx->pos)
5057 if (key_type == BTRFS_DIR_INDEX_KEY &&
5058 btrfs_should_delete_dir_index(&del_list,
5062 ctx->pos = found_key.offset;
5065 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5067 di_total = btrfs_item_size(leaf, item);
5069 while (di_cur < di_total) {
5070 struct btrfs_key location;
5072 if (verify_dir_item(root, leaf, di))
5075 name_len = btrfs_dir_name_len(leaf, di);
5076 if (name_len <= sizeof(tmp_name)) {
5077 name_ptr = tmp_name;
5079 name_ptr = kmalloc(name_len, GFP_NOFS);
5085 read_extent_buffer(leaf, name_ptr,
5086 (unsigned long)(di + 1), name_len);
5088 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5089 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5092 /* is this a reference to our own snapshot? If so
5095 * In contrast to old kernels, we insert the snapshot's
5096 * dir item and dir index after it has been created, so
5097 * we won't find a reference to our own snapshot. We
5098 * still keep the following code for backward
5101 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5102 location.objectid == root->root_key.objectid) {
5106 over = !dir_emit(ctx, name_ptr, name_len,
5107 location.objectid, d_type);
5110 if (name_ptr != tmp_name)
5115 di_len = btrfs_dir_name_len(leaf, di) +
5116 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5118 di = (struct btrfs_dir_item *)((char *)di + di_len);
5124 if (key_type == BTRFS_DIR_INDEX_KEY) {
5127 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5132 /* Reached end of directory/root. Bump pos past the last item. */
5136 * Stop new entries from being returned after we return the last
5139 * New directory entries are assigned a strictly increasing
5140 * offset. This means that new entries created during readdir
5141 * are *guaranteed* to be seen in the future by that readdir.
5142 * This has broken buggy programs which operate on names as
5143 * they're returned by readdir. Until we re-use freed offsets
5144 * we have this hack to stop new entries from being returned
5145 * under the assumption that they'll never reach this huge
5148 * This is being careful not to overflow 32bit loff_t unless the
5149 * last entry requires it because doing so has broken 32bit apps
5152 if (key_type == BTRFS_DIR_INDEX_KEY) {
5153 if (ctx->pos >= INT_MAX)
5154 ctx->pos = LLONG_MAX;
5161 if (key_type == BTRFS_DIR_INDEX_KEY)
5162 btrfs_put_delayed_items(&ins_list, &del_list);
5163 btrfs_free_path(path);
5167 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5169 struct btrfs_root *root = BTRFS_I(inode)->root;
5170 struct btrfs_trans_handle *trans;
5172 bool nolock = false;
5174 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5177 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5180 if (wbc->sync_mode == WB_SYNC_ALL) {
5182 trans = btrfs_join_transaction_nolock(root);
5184 trans = btrfs_join_transaction(root);
5186 return PTR_ERR(trans);
5187 ret = btrfs_commit_transaction(trans, root);
5193 * This is somewhat expensive, updating the tree every time the
5194 * inode changes. But, it is most likely to find the inode in cache.
5195 * FIXME, needs more benchmarking...there are no reasons other than performance
5196 * to keep or drop this code.
5198 static int btrfs_dirty_inode(struct inode *inode)
5200 struct btrfs_root *root = BTRFS_I(inode)->root;
5201 struct btrfs_trans_handle *trans;
5204 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5207 trans = btrfs_join_transaction(root);
5209 return PTR_ERR(trans);
5211 ret = btrfs_update_inode(trans, root, inode);
5212 if (ret && ret == -ENOSPC) {
5213 /* whoops, lets try again with the full transaction */
5214 btrfs_end_transaction(trans, root);
5215 trans = btrfs_start_transaction(root, 1);
5217 return PTR_ERR(trans);
5219 ret = btrfs_update_inode(trans, root, inode);
5221 btrfs_end_transaction(trans, root);
5222 if (BTRFS_I(inode)->delayed_node)
5223 btrfs_balance_delayed_items(root);
5229 * This is a copy of file_update_time. We need this so we can return error on
5230 * ENOSPC for updating the inode in the case of file write and mmap writes.
5232 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5235 struct btrfs_root *root = BTRFS_I(inode)->root;
5237 if (btrfs_root_readonly(root))
5240 if (flags & S_VERSION)
5241 inode_inc_iversion(inode);
5242 if (flags & S_CTIME)
5243 inode->i_ctime = *now;
5244 if (flags & S_MTIME)
5245 inode->i_mtime = *now;
5246 if (flags & S_ATIME)
5247 inode->i_atime = *now;
5248 return btrfs_dirty_inode(inode);
5252 * find the highest existing sequence number in a directory
5253 * and then set the in-memory index_cnt variable to reflect
5254 * free sequence numbers
5256 static int btrfs_set_inode_index_count(struct inode *inode)
5258 struct btrfs_root *root = BTRFS_I(inode)->root;
5259 struct btrfs_key key, found_key;
5260 struct btrfs_path *path;
5261 struct extent_buffer *leaf;
5264 key.objectid = btrfs_ino(inode);
5265 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5266 key.offset = (u64)-1;
5268 path = btrfs_alloc_path();
5272 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5275 /* FIXME: we should be able to handle this */
5281 * MAGIC NUMBER EXPLANATION:
5282 * since we search a directory based on f_pos we have to start at 2
5283 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5284 * else has to start at 2
5286 if (path->slots[0] == 0) {
5287 BTRFS_I(inode)->index_cnt = 2;
5293 leaf = path->nodes[0];
5294 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5296 if (found_key.objectid != btrfs_ino(inode) ||
5297 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5298 BTRFS_I(inode)->index_cnt = 2;
5302 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5304 btrfs_free_path(path);
5309 * helper to find a free sequence number in a given directory. This current
5310 * code is very simple, later versions will do smarter things in the btree
5312 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5316 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5317 ret = btrfs_inode_delayed_dir_index_count(dir);
5319 ret = btrfs_set_inode_index_count(dir);
5325 *index = BTRFS_I(dir)->index_cnt;
5326 BTRFS_I(dir)->index_cnt++;
5331 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5332 struct btrfs_root *root,
5334 const char *name, int name_len,
5335 u64 ref_objectid, u64 objectid,
5336 umode_t mode, u64 *index)
5338 struct inode *inode;
5339 struct btrfs_inode_item *inode_item;
5340 struct btrfs_key *location;
5341 struct btrfs_path *path;
5342 struct btrfs_inode_ref *ref;
5343 struct btrfs_key key[2];
5349 path = btrfs_alloc_path();
5351 return ERR_PTR(-ENOMEM);
5353 inode = new_inode(root->fs_info->sb);
5355 btrfs_free_path(path);
5356 return ERR_PTR(-ENOMEM);
5360 * we have to initialize this early, so we can reclaim the inode
5361 * number if we fail afterwards in this function.
5363 inode->i_ino = objectid;
5366 trace_btrfs_inode_request(dir);
5368 ret = btrfs_set_inode_index(dir, index);
5370 btrfs_free_path(path);
5372 return ERR_PTR(ret);
5376 * index_cnt is ignored for everything but a dir,
5377 * btrfs_get_inode_index_count has an explanation for the magic
5380 BTRFS_I(inode)->index_cnt = 2;
5381 BTRFS_I(inode)->root = root;
5382 BTRFS_I(inode)->generation = trans->transid;
5383 inode->i_generation = BTRFS_I(inode)->generation;
5386 * We could have gotten an inode number from somebody who was fsynced
5387 * and then removed in this same transaction, so let's just set full
5388 * sync since it will be a full sync anyway and this will blow away the
5389 * old info in the log.
5391 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5398 key[0].objectid = objectid;
5399 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5403 * Start new inodes with an inode_ref. This is slightly more
5404 * efficient for small numbers of hard links since they will
5405 * be packed into one item. Extended refs will kick in if we
5406 * add more hard links than can fit in the ref item.
5408 key[1].objectid = objectid;
5409 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5410 key[1].offset = ref_objectid;
5412 sizes[0] = sizeof(struct btrfs_inode_item);
5413 sizes[1] = name_len + sizeof(*ref);
5415 path->leave_spinning = 1;
5416 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5420 inode_init_owner(inode, dir, mode);
5421 inode_set_bytes(inode, 0);
5422 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5423 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5424 struct btrfs_inode_item);
5425 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5426 sizeof(*inode_item));
5427 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5429 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5430 struct btrfs_inode_ref);
5431 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5432 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5433 ptr = (unsigned long)(ref + 1);
5434 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5436 btrfs_mark_buffer_dirty(path->nodes[0]);
5437 btrfs_free_path(path);
5439 location = &BTRFS_I(inode)->location;
5440 location->objectid = objectid;
5441 location->offset = 0;
5442 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5444 btrfs_inherit_iflags(inode, dir);
5446 if (S_ISREG(mode)) {
5447 if (btrfs_test_opt(root, NODATASUM))
5448 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5449 if (btrfs_test_opt(root, NODATACOW))
5450 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5451 BTRFS_INODE_NODATASUM;
5454 insert_inode_hash(inode);
5455 inode_tree_add(inode);
5457 trace_btrfs_inode_new(inode);
5458 btrfs_set_inode_last_trans(trans, inode);
5460 btrfs_update_root_times(trans, root);
5465 BTRFS_I(dir)->index_cnt--;
5466 btrfs_free_path(path);
5468 return ERR_PTR(ret);
5471 static inline u8 btrfs_inode_type(struct inode *inode)
5473 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5477 * utility function to add 'inode' into 'parent_inode' with
5478 * a give name and a given sequence number.
5479 * if 'add_backref' is true, also insert a backref from the
5480 * inode to the parent directory.
5482 int btrfs_add_link(struct btrfs_trans_handle *trans,
5483 struct inode *parent_inode, struct inode *inode,
5484 const char *name, int name_len, int add_backref, u64 index)
5487 struct btrfs_key key;
5488 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5489 u64 ino = btrfs_ino(inode);
5490 u64 parent_ino = btrfs_ino(parent_inode);
5492 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5493 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5496 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5500 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5501 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5502 key.objectid, root->root_key.objectid,
5503 parent_ino, index, name, name_len);
5504 } else if (add_backref) {
5505 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5509 /* Nothing to clean up yet */
5513 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5515 btrfs_inode_type(inode), index);
5516 if (ret == -EEXIST || ret == -EOVERFLOW)
5519 btrfs_abort_transaction(trans, root, ret);
5523 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5525 inode_inc_iversion(parent_inode);
5526 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5527 ret = btrfs_update_inode(trans, root, parent_inode);
5529 btrfs_abort_transaction(trans, root, ret);
5533 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5536 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5537 key.objectid, root->root_key.objectid,
5538 parent_ino, &local_index, name, name_len);
5540 } else if (add_backref) {
5544 err = btrfs_del_inode_ref(trans, root, name, name_len,
5545 ino, parent_ino, &local_index);
5550 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5551 struct inode *dir, struct dentry *dentry,
5552 struct inode *inode, int backref, u64 index)
5554 int err = btrfs_add_link(trans, dir, inode,
5555 dentry->d_name.name, dentry->d_name.len,
5562 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5563 umode_t mode, dev_t rdev)
5565 struct btrfs_trans_handle *trans;
5566 struct btrfs_root *root = BTRFS_I(dir)->root;
5567 struct inode *inode = NULL;
5573 if (!new_valid_dev(rdev))
5577 * 2 for inode item and ref
5579 * 1 for xattr if selinux is on
5581 trans = btrfs_start_transaction(root, 5);
5583 return PTR_ERR(trans);
5585 err = btrfs_find_free_ino(root, &objectid);
5589 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5590 dentry->d_name.len, btrfs_ino(dir), objectid,
5592 if (IS_ERR(inode)) {
5593 err = PTR_ERR(inode);
5597 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5604 * If the active LSM wants to access the inode during
5605 * d_instantiate it needs these. Smack checks to see
5606 * if the filesystem supports xattrs by looking at the
5610 inode->i_op = &btrfs_special_inode_operations;
5611 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5615 init_special_inode(inode, inode->i_mode, rdev);
5616 btrfs_update_inode(trans, root, inode);
5617 d_instantiate(dentry, inode);
5620 btrfs_end_transaction(trans, root);
5621 btrfs_btree_balance_dirty(root);
5623 inode_dec_link_count(inode);
5629 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5630 umode_t mode, bool excl)
5632 struct btrfs_trans_handle *trans;
5633 struct btrfs_root *root = BTRFS_I(dir)->root;
5634 struct inode *inode = NULL;
5635 int drop_inode_on_err = 0;
5641 * 2 for inode item and ref
5643 * 1 for xattr if selinux is on
5645 trans = btrfs_start_transaction(root, 5);
5647 return PTR_ERR(trans);
5649 err = btrfs_find_free_ino(root, &objectid);
5653 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5654 dentry->d_name.len, btrfs_ino(dir), objectid,
5656 if (IS_ERR(inode)) {
5657 err = PTR_ERR(inode);
5660 drop_inode_on_err = 1;
5662 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5666 err = btrfs_update_inode(trans, root, inode);
5671 * If the active LSM wants to access the inode during
5672 * d_instantiate it needs these. Smack checks to see
5673 * if the filesystem supports xattrs by looking at the
5676 inode->i_fop = &btrfs_file_operations;
5677 inode->i_op = &btrfs_file_inode_operations;
5679 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5683 inode->i_mapping->a_ops = &btrfs_aops;
5684 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5685 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5686 d_instantiate(dentry, inode);
5689 btrfs_end_transaction(trans, root);
5690 if (err && drop_inode_on_err) {
5691 inode_dec_link_count(inode);
5694 btrfs_btree_balance_dirty(root);
5698 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5699 struct dentry *dentry)
5701 struct btrfs_trans_handle *trans;
5702 struct btrfs_root *root = BTRFS_I(dir)->root;
5703 struct inode *inode = old_dentry->d_inode;
5708 /* do not allow sys_link's with other subvols of the same device */
5709 if (root->objectid != BTRFS_I(inode)->root->objectid)
5712 if (inode->i_nlink >= BTRFS_LINK_MAX)
5715 err = btrfs_set_inode_index(dir, &index);
5720 * 2 items for inode and inode ref
5721 * 2 items for dir items
5722 * 1 item for parent inode
5724 trans = btrfs_start_transaction(root, 5);
5725 if (IS_ERR(trans)) {
5726 err = PTR_ERR(trans);
5730 btrfs_inc_nlink(inode);
5731 inode_inc_iversion(inode);
5732 inode->i_ctime = CURRENT_TIME;
5734 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5736 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5741 struct dentry *parent = dentry->d_parent;
5742 err = btrfs_update_inode(trans, root, inode);
5745 d_instantiate(dentry, inode);
5746 btrfs_log_new_name(trans, inode, NULL, parent);
5749 btrfs_end_transaction(trans, root);
5752 inode_dec_link_count(inode);
5755 btrfs_btree_balance_dirty(root);
5759 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5761 struct inode *inode = NULL;
5762 struct btrfs_trans_handle *trans;
5763 struct btrfs_root *root = BTRFS_I(dir)->root;
5765 int drop_on_err = 0;
5770 * 2 items for inode and ref
5771 * 2 items for dir items
5772 * 1 for xattr if selinux is on
5774 trans = btrfs_start_transaction(root, 5);
5776 return PTR_ERR(trans);
5778 err = btrfs_find_free_ino(root, &objectid);
5782 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5783 dentry->d_name.len, btrfs_ino(dir), objectid,
5784 S_IFDIR | mode, &index);
5785 if (IS_ERR(inode)) {
5786 err = PTR_ERR(inode);
5792 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5796 inode->i_op = &btrfs_dir_inode_operations;
5797 inode->i_fop = &btrfs_dir_file_operations;
5799 btrfs_i_size_write(inode, 0);
5800 err = btrfs_update_inode(trans, root, inode);
5804 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5805 dentry->d_name.len, 0, index);
5809 d_instantiate(dentry, inode);
5813 btrfs_end_transaction(trans, root);
5816 btrfs_btree_balance_dirty(root);
5820 /* helper for btfs_get_extent. Given an existing extent in the tree,
5821 * and an extent that you want to insert, deal with overlap and insert
5822 * the new extent into the tree.
5824 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5825 struct extent_map *existing,
5826 struct extent_map *em,
5827 u64 map_start, u64 map_len)
5831 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5832 start_diff = map_start - em->start;
5833 em->start = map_start;
5835 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5836 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5837 em->block_start += start_diff;
5838 em->block_len -= start_diff;
5840 return add_extent_mapping(em_tree, em, 0);
5843 static noinline int uncompress_inline(struct btrfs_path *path,
5844 struct inode *inode, struct page *page,
5845 size_t pg_offset, u64 extent_offset,
5846 struct btrfs_file_extent_item *item)
5849 struct extent_buffer *leaf = path->nodes[0];
5852 unsigned long inline_size;
5856 WARN_ON(pg_offset != 0);
5857 compress_type = btrfs_file_extent_compression(leaf, item);
5858 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5859 inline_size = btrfs_file_extent_inline_item_len(leaf,
5860 btrfs_item_nr(leaf, path->slots[0]));
5861 tmp = kmalloc(inline_size, GFP_NOFS);
5864 ptr = btrfs_file_extent_inline_start(item);
5866 read_extent_buffer(leaf, tmp, ptr, inline_size);
5868 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5869 ret = btrfs_decompress(compress_type, tmp, page,
5870 extent_offset, inline_size, max_size);
5872 char *kaddr = kmap_atomic(page);
5873 unsigned long copy_size = min_t(u64,
5874 PAGE_CACHE_SIZE - pg_offset,
5875 max_size - extent_offset);
5876 memset(kaddr + pg_offset, 0, copy_size);
5877 kunmap_atomic(kaddr);
5884 * a bit scary, this does extent mapping from logical file offset to the disk.
5885 * the ugly parts come from merging extents from the disk with the in-ram
5886 * representation. This gets more complex because of the data=ordered code,
5887 * where the in-ram extents might be locked pending data=ordered completion.
5889 * This also copies inline extents directly into the page.
5892 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5893 size_t pg_offset, u64 start, u64 len,
5899 u64 extent_start = 0;
5901 u64 objectid = btrfs_ino(inode);
5903 struct btrfs_path *path = NULL;
5904 struct btrfs_root *root = BTRFS_I(inode)->root;
5905 struct btrfs_file_extent_item *item;
5906 struct extent_buffer *leaf;
5907 struct btrfs_key found_key;
5908 struct extent_map *em = NULL;
5909 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5910 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5911 struct btrfs_trans_handle *trans = NULL;
5915 read_lock(&em_tree->lock);
5916 em = lookup_extent_mapping(em_tree, start, len);
5918 em->bdev = root->fs_info->fs_devices->latest_bdev;
5919 read_unlock(&em_tree->lock);
5922 if (em->start > start || em->start + em->len <= start)
5923 free_extent_map(em);
5924 else if (em->block_start == EXTENT_MAP_INLINE && page)
5925 free_extent_map(em);
5929 em = alloc_extent_map();
5934 em->bdev = root->fs_info->fs_devices->latest_bdev;
5935 em->start = EXTENT_MAP_HOLE;
5936 em->orig_start = EXTENT_MAP_HOLE;
5938 em->block_len = (u64)-1;
5941 path = btrfs_alloc_path();
5947 * Chances are we'll be called again, so go ahead and do
5953 ret = btrfs_lookup_file_extent(trans, root, path,
5954 objectid, start, trans != NULL);
5961 if (path->slots[0] == 0)
5966 leaf = path->nodes[0];
5967 item = btrfs_item_ptr(leaf, path->slots[0],
5968 struct btrfs_file_extent_item);
5969 /* are we inside the extent that was found? */
5970 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5971 found_type = btrfs_key_type(&found_key);
5972 if (found_key.objectid != objectid ||
5973 found_type != BTRFS_EXTENT_DATA_KEY) {
5977 found_type = btrfs_file_extent_type(leaf, item);
5978 extent_start = found_key.offset;
5979 compress_type = btrfs_file_extent_compression(leaf, item);
5980 if (found_type == BTRFS_FILE_EXTENT_REG ||
5981 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5982 extent_end = extent_start +
5983 btrfs_file_extent_num_bytes(leaf, item);
5984 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5986 size = btrfs_file_extent_inline_len(leaf, item);
5987 extent_end = ALIGN(extent_start + size, root->sectorsize);
5990 if (start >= extent_end) {
5992 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5993 ret = btrfs_next_leaf(root, path);
6000 leaf = path->nodes[0];
6002 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6003 if (found_key.objectid != objectid ||
6004 found_key.type != BTRFS_EXTENT_DATA_KEY)
6006 if (start + len <= found_key.offset)
6009 em->orig_start = start;
6010 em->len = found_key.offset - start;
6014 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6015 if (found_type == BTRFS_FILE_EXTENT_REG ||
6016 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6017 em->start = extent_start;
6018 em->len = extent_end - extent_start;
6019 em->orig_start = extent_start -
6020 btrfs_file_extent_offset(leaf, item);
6021 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6023 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6025 em->block_start = EXTENT_MAP_HOLE;
6028 if (compress_type != BTRFS_COMPRESS_NONE) {
6029 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6030 em->compress_type = compress_type;
6031 em->block_start = bytenr;
6032 em->block_len = em->orig_block_len;
6034 bytenr += btrfs_file_extent_offset(leaf, item);
6035 em->block_start = bytenr;
6036 em->block_len = em->len;
6037 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6038 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6041 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6045 size_t extent_offset;
6048 em->block_start = EXTENT_MAP_INLINE;
6049 if (!page || create) {
6050 em->start = extent_start;
6051 em->len = extent_end - extent_start;
6055 size = btrfs_file_extent_inline_len(leaf, item);
6056 extent_offset = page_offset(page) + pg_offset - extent_start;
6057 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6058 size - extent_offset);
6059 em->start = extent_start + extent_offset;
6060 em->len = ALIGN(copy_size, root->sectorsize);
6061 em->orig_block_len = em->len;
6062 em->orig_start = em->start;
6063 if (compress_type) {
6064 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6065 em->compress_type = compress_type;
6067 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6068 if (create == 0 && !PageUptodate(page)) {
6069 if (btrfs_file_extent_compression(leaf, item) !=
6070 BTRFS_COMPRESS_NONE) {
6071 ret = uncompress_inline(path, inode, page,
6073 extent_offset, item);
6074 BUG_ON(ret); /* -ENOMEM */
6077 read_extent_buffer(leaf, map + pg_offset, ptr,
6079 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6080 memset(map + pg_offset + copy_size, 0,
6081 PAGE_CACHE_SIZE - pg_offset -
6086 flush_dcache_page(page);
6087 } else if (create && PageUptodate(page)) {
6091 free_extent_map(em);
6094 btrfs_release_path(path);
6095 trans = btrfs_join_transaction(root);
6098 return ERR_CAST(trans);
6102 write_extent_buffer(leaf, map + pg_offset, ptr,
6105 btrfs_mark_buffer_dirty(leaf);
6107 set_extent_uptodate(io_tree, em->start,
6108 extent_map_end(em) - 1, NULL, GFP_NOFS);
6111 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6115 em->orig_start = start;
6118 em->block_start = EXTENT_MAP_HOLE;
6119 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6121 btrfs_release_path(path);
6122 if (em->start > start || extent_map_end(em) <= start) {
6123 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6124 (unsigned long long)em->start,
6125 (unsigned long long)em->len,
6126 (unsigned long long)start,
6127 (unsigned long long)len);
6133 write_lock(&em_tree->lock);
6134 ret = add_extent_mapping(em_tree, em, 0);
6135 /* it is possible that someone inserted the extent into the tree
6136 * while we had the lock dropped. It is also possible that
6137 * an overlapping map exists in the tree
6139 if (ret == -EEXIST) {
6140 struct extent_map *existing;
6144 existing = lookup_extent_mapping(em_tree, start, len);
6145 if (existing && (existing->start > start ||
6146 existing->start + existing->len <= start)) {
6147 free_extent_map(existing);
6151 existing = lookup_extent_mapping(em_tree, em->start,
6154 err = merge_extent_mapping(em_tree, existing,
6157 free_extent_map(existing);
6159 free_extent_map(em);
6164 free_extent_map(em);
6168 free_extent_map(em);
6173 write_unlock(&em_tree->lock);
6177 trace_btrfs_get_extent(root, em);
6180 btrfs_free_path(path);
6182 ret = btrfs_end_transaction(trans, root);
6187 free_extent_map(em);
6188 return ERR_PTR(err);
6190 BUG_ON(!em); /* Error is always set */
6194 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6195 size_t pg_offset, u64 start, u64 len,
6198 struct extent_map *em;
6199 struct extent_map *hole_em = NULL;
6200 u64 range_start = start;
6206 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6213 * - a pre-alloc extent,
6214 * there might actually be delalloc bytes behind it.
6216 if (em->block_start != EXTENT_MAP_HOLE &&
6217 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6223 /* check to see if we've wrapped (len == -1 or similar) */
6232 /* ok, we didn't find anything, lets look for delalloc */
6233 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6234 end, len, EXTENT_DELALLOC, 1);
6235 found_end = range_start + found;
6236 if (found_end < range_start)
6237 found_end = (u64)-1;
6240 * we didn't find anything useful, return
6241 * the original results from get_extent()
6243 if (range_start > end || found_end <= start) {
6249 /* adjust the range_start to make sure it doesn't
6250 * go backwards from the start they passed in
6252 range_start = max(start,range_start);
6253 found = found_end - range_start;
6256 u64 hole_start = start;
6259 em = alloc_extent_map();
6265 * when btrfs_get_extent can't find anything it
6266 * returns one huge hole
6268 * make sure what it found really fits our range, and
6269 * adjust to make sure it is based on the start from
6273 u64 calc_end = extent_map_end(hole_em);
6275 if (calc_end <= start || (hole_em->start > end)) {
6276 free_extent_map(hole_em);
6279 hole_start = max(hole_em->start, start);
6280 hole_len = calc_end - hole_start;
6284 if (hole_em && range_start > hole_start) {
6285 /* our hole starts before our delalloc, so we
6286 * have to return just the parts of the hole
6287 * that go until the delalloc starts
6289 em->len = min(hole_len,
6290 range_start - hole_start);
6291 em->start = hole_start;
6292 em->orig_start = hole_start;
6294 * don't adjust block start at all,
6295 * it is fixed at EXTENT_MAP_HOLE
6297 em->block_start = hole_em->block_start;
6298 em->block_len = hole_len;
6299 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6300 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6302 em->start = range_start;
6304 em->orig_start = range_start;
6305 em->block_start = EXTENT_MAP_DELALLOC;
6306 em->block_len = found;
6308 } else if (hole_em) {
6313 free_extent_map(hole_em);
6315 free_extent_map(em);
6316 return ERR_PTR(err);
6321 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6324 struct btrfs_root *root = BTRFS_I(inode)->root;
6325 struct btrfs_trans_handle *trans;
6326 struct extent_map *em;
6327 struct btrfs_key ins;
6331 trans = btrfs_join_transaction(root);
6333 return ERR_CAST(trans);
6335 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6337 alloc_hint = get_extent_allocation_hint(inode, start, len);
6338 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6339 alloc_hint, &ins, 1);
6345 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6346 ins.offset, ins.offset, ins.offset, 0);
6350 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6351 ins.offset, ins.offset, 0);
6353 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6357 btrfs_end_transaction(trans, root);
6362 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6363 * block must be cow'd
6365 noinline int can_nocow_extent(struct btrfs_trans_handle *trans,
6366 struct inode *inode, u64 offset, u64 *len,
6367 u64 *orig_start, u64 *orig_block_len,
6370 struct btrfs_path *path;
6372 struct extent_buffer *leaf;
6373 struct btrfs_root *root = BTRFS_I(inode)->root;
6374 struct btrfs_file_extent_item *fi;
6375 struct btrfs_key key;
6382 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6383 path = btrfs_alloc_path();
6387 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6392 slot = path->slots[0];
6395 /* can't find the item, must cow */
6402 leaf = path->nodes[0];
6403 btrfs_item_key_to_cpu(leaf, &key, slot);
6404 if (key.objectid != btrfs_ino(inode) ||
6405 key.type != BTRFS_EXTENT_DATA_KEY) {
6406 /* not our file or wrong item type, must cow */
6410 if (key.offset > offset) {
6411 /* Wrong offset, must cow */
6415 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6416 found_type = btrfs_file_extent_type(leaf, fi);
6417 if (found_type != BTRFS_FILE_EXTENT_REG &&
6418 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6419 /* not a regular extent, must cow */
6423 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6426 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6427 if (disk_bytenr == 0)
6430 if (btrfs_file_extent_compression(leaf, fi) ||
6431 btrfs_file_extent_encryption(leaf, fi) ||
6432 btrfs_file_extent_other_encoding(leaf, fi))
6435 backref_offset = btrfs_file_extent_offset(leaf, fi);
6438 *orig_start = key.offset - backref_offset;
6439 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6440 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6443 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6445 if (btrfs_extent_readonly(root, disk_bytenr))
6449 * look for other files referencing this extent, if we
6450 * find any we must cow
6452 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6453 key.offset - backref_offset, disk_bytenr))
6457 * adjust disk_bytenr and num_bytes to cover just the bytes
6458 * in this extent we are about to write. If there
6459 * are any csums in that range we have to cow in order
6460 * to keep the csums correct
6462 disk_bytenr += backref_offset;
6463 disk_bytenr += offset - key.offset;
6464 num_bytes = min(offset + *len, extent_end) - offset;
6465 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6468 * all of the above have passed, it is safe to overwrite this extent
6474 btrfs_free_path(path);
6478 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6479 struct extent_state **cached_state, int writing)
6481 struct btrfs_ordered_extent *ordered;
6485 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6488 * We're concerned with the entire range that we're going to be
6489 * doing DIO to, so we need to make sure theres no ordered
6490 * extents in this range.
6492 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6493 lockend - lockstart + 1);
6496 * We need to make sure there are no buffered pages in this
6497 * range either, we could have raced between the invalidate in
6498 * generic_file_direct_write and locking the extent. The
6499 * invalidate needs to happen so that reads after a write do not
6502 if (!ordered && (!writing ||
6503 !test_range_bit(&BTRFS_I(inode)->io_tree,
6504 lockstart, lockend, EXTENT_UPTODATE, 0,
6508 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6509 cached_state, GFP_NOFS);
6512 btrfs_start_ordered_extent(inode, ordered, 1);
6513 btrfs_put_ordered_extent(ordered);
6515 /* Screw you mmap */
6516 ret = filemap_write_and_wait_range(inode->i_mapping,
6523 * If we found a page that couldn't be invalidated just
6524 * fall back to buffered.
6526 ret = invalidate_inode_pages2_range(inode->i_mapping,
6527 lockstart >> PAGE_CACHE_SHIFT,
6528 lockend >> PAGE_CACHE_SHIFT);
6539 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6540 u64 len, u64 orig_start,
6541 u64 block_start, u64 block_len,
6542 u64 orig_block_len, u64 ram_bytes,
6545 struct extent_map_tree *em_tree;
6546 struct extent_map *em;
6547 struct btrfs_root *root = BTRFS_I(inode)->root;
6550 em_tree = &BTRFS_I(inode)->extent_tree;
6551 em = alloc_extent_map();
6553 return ERR_PTR(-ENOMEM);
6556 em->orig_start = orig_start;
6557 em->mod_start = start;
6560 em->block_len = block_len;
6561 em->block_start = block_start;
6562 em->bdev = root->fs_info->fs_devices->latest_bdev;
6563 em->orig_block_len = orig_block_len;
6564 em->ram_bytes = ram_bytes;
6565 em->generation = -1;
6566 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6567 if (type == BTRFS_ORDERED_PREALLOC)
6568 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6571 btrfs_drop_extent_cache(inode, em->start,
6572 em->start + em->len - 1, 0);
6573 write_lock(&em_tree->lock);
6574 ret = add_extent_mapping(em_tree, em, 1);
6575 write_unlock(&em_tree->lock);
6576 } while (ret == -EEXIST);
6579 free_extent_map(em);
6580 return ERR_PTR(ret);
6587 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6588 struct buffer_head *bh_result, int create)
6590 struct extent_map *em;
6591 struct btrfs_root *root = BTRFS_I(inode)->root;
6592 struct extent_state *cached_state = NULL;
6593 u64 start = iblock << inode->i_blkbits;
6594 u64 lockstart, lockend;
6595 u64 len = bh_result->b_size;
6596 struct btrfs_trans_handle *trans;
6597 int unlock_bits = EXTENT_LOCKED;
6601 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6603 len = min_t(u64, len, root->sectorsize);
6606 lockend = start + len - 1;
6609 * If this errors out it's because we couldn't invalidate pagecache for
6610 * this range and we need to fallback to buffered.
6612 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6615 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6622 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6623 * io. INLINE is special, and we could probably kludge it in here, but
6624 * it's still buffered so for safety lets just fall back to the generic
6627 * For COMPRESSED we _have_ to read the entire extent in so we can
6628 * decompress it, so there will be buffering required no matter what we
6629 * do, so go ahead and fallback to buffered.
6631 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6632 * to buffered IO. Don't blame me, this is the price we pay for using
6635 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6636 em->block_start == EXTENT_MAP_INLINE) {
6637 free_extent_map(em);
6642 /* Just a good old fashioned hole, return */
6643 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6644 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6645 free_extent_map(em);
6650 * We don't allocate a new extent in the following cases
6652 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6654 * 2) The extent is marked as PREALLOC. We're good to go here and can
6655 * just use the extent.
6659 len = min(len, em->len - (start - em->start));
6660 lockstart = start + len;
6664 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6665 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6666 em->block_start != EXTENT_MAP_HOLE)) {
6669 u64 block_start, orig_start, orig_block_len, ram_bytes;
6671 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6672 type = BTRFS_ORDERED_PREALLOC;
6674 type = BTRFS_ORDERED_NOCOW;
6675 len = min(len, em->len - (start - em->start));
6676 block_start = em->block_start + (start - em->start);
6679 * we're not going to log anything, but we do need
6680 * to make sure the current transaction stays open
6681 * while we look for nocow cross refs
6683 trans = btrfs_join_transaction(root);
6687 if (can_nocow_extent(trans, inode, start, &len, &orig_start,
6688 &orig_block_len, &ram_bytes) == 1) {
6689 if (type == BTRFS_ORDERED_PREALLOC) {
6690 free_extent_map(em);
6691 em = create_pinned_em(inode, start, len,
6697 btrfs_end_transaction(trans, root);
6702 ret = btrfs_add_ordered_extent_dio(inode, start,
6703 block_start, len, len, type);
6704 btrfs_end_transaction(trans, root);
6706 free_extent_map(em);
6711 btrfs_end_transaction(trans, root);
6715 * this will cow the extent, reset the len in case we changed
6718 len = bh_result->b_size;
6719 free_extent_map(em);
6720 em = btrfs_new_extent_direct(inode, start, len);
6725 len = min(len, em->len - (start - em->start));
6727 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6729 bh_result->b_size = len;
6730 bh_result->b_bdev = em->bdev;
6731 set_buffer_mapped(bh_result);
6733 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6734 set_buffer_new(bh_result);
6737 * Need to update the i_size under the extent lock so buffered
6738 * readers will get the updated i_size when we unlock.
6740 if (start + len > i_size_read(inode))
6741 i_size_write(inode, start + len);
6743 spin_lock(&BTRFS_I(inode)->lock);
6744 BTRFS_I(inode)->outstanding_extents++;
6745 spin_unlock(&BTRFS_I(inode)->lock);
6747 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6748 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6749 &cached_state, GFP_NOFS);
6754 * In the case of write we need to clear and unlock the entire range,
6755 * in the case of read we need to unlock only the end area that we
6756 * aren't using if there is any left over space.
6758 if (lockstart < lockend) {
6759 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6760 lockend, unlock_bits, 1, 0,
6761 &cached_state, GFP_NOFS);
6763 free_extent_state(cached_state);
6766 free_extent_map(em);
6771 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6772 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6776 static void btrfs_endio_direct_read(struct bio *bio, int err)
6778 struct btrfs_dio_private *dip = bio->bi_private;
6779 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6780 struct bio_vec *bvec = bio->bi_io_vec;
6781 struct inode *inode = dip->inode;
6782 struct btrfs_root *root = BTRFS_I(inode)->root;
6783 struct bio *dio_bio;
6784 u32 *csums = (u32 *)dip->csum;
6788 start = dip->logical_offset;
6790 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6791 struct page *page = bvec->bv_page;
6794 unsigned long flags;
6796 local_irq_save(flags);
6797 kaddr = kmap_atomic(page);
6798 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6799 csum, bvec->bv_len);
6800 btrfs_csum_final(csum, (char *)&csum);
6801 kunmap_atomic(kaddr);
6802 local_irq_restore(flags);
6804 flush_dcache_page(bvec->bv_page);
6805 if (csum != csums[index]) {
6806 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u expected csum %u",
6807 (unsigned long long)btrfs_ino(inode),
6808 (unsigned long long)start,
6809 csum, csums[index]);
6814 start += bvec->bv_len;
6817 } while (bvec <= bvec_end);
6819 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6820 dip->logical_offset + dip->bytes - 1);
6821 dio_bio = dip->dio_bio;
6825 /* If we had a csum failure make sure to clear the uptodate flag */
6827 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6828 dio_end_io(dio_bio, err);
6832 static void btrfs_endio_direct_write(struct bio *bio, int err)
6834 struct btrfs_dio_private *dip = bio->bi_private;
6835 struct inode *inode = dip->inode;
6836 struct btrfs_root *root = BTRFS_I(inode)->root;
6837 struct btrfs_ordered_extent *ordered = NULL;
6838 u64 ordered_offset = dip->logical_offset;
6839 u64 ordered_bytes = dip->bytes;
6840 struct bio *dio_bio;
6846 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6848 ordered_bytes, !err);
6852 ordered->work.func = finish_ordered_fn;
6853 ordered->work.flags = 0;
6854 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6858 * our bio might span multiple ordered extents. If we haven't
6859 * completed the accounting for the whole dio, go back and try again
6861 if (ordered_offset < dip->logical_offset + dip->bytes) {
6862 ordered_bytes = dip->logical_offset + dip->bytes -
6868 dio_bio = dip->dio_bio;
6872 /* If we had an error make sure to clear the uptodate flag */
6874 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6875 dio_end_io(dio_bio, err);
6879 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6880 struct bio *bio, int mirror_num,
6881 unsigned long bio_flags, u64 offset)
6884 struct btrfs_root *root = BTRFS_I(inode)->root;
6885 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6886 BUG_ON(ret); /* -ENOMEM */
6890 static void btrfs_end_dio_bio(struct bio *bio, int err)
6892 struct btrfs_dio_private *dip = bio->bi_private;
6895 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6896 "sector %#Lx len %u err no %d\n",
6897 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6898 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6902 * before atomic variable goto zero, we must make sure
6903 * dip->errors is perceived to be set.
6905 smp_mb__before_atomic_dec();
6908 /* if there are more bios still pending for this dio, just exit */
6909 if (!atomic_dec_and_test(&dip->pending_bios))
6913 bio_io_error(dip->orig_bio);
6915 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
6916 bio_endio(dip->orig_bio, 0);
6922 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6923 u64 first_sector, gfp_t gfp_flags)
6925 int nr_vecs = bio_get_nr_vecs(bdev);
6926 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6929 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6930 int rw, u64 file_offset, int skip_sum,
6933 struct btrfs_dio_private *dip = bio->bi_private;
6934 int write = rw & REQ_WRITE;
6935 struct btrfs_root *root = BTRFS_I(inode)->root;
6939 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6944 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6952 if (write && async_submit) {
6953 ret = btrfs_wq_submit_bio(root->fs_info,
6954 inode, rw, bio, 0, 0,
6956 __btrfs_submit_bio_start_direct_io,
6957 __btrfs_submit_bio_done);
6961 * If we aren't doing async submit, calculate the csum of the
6964 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6967 } else if (!skip_sum) {
6968 ret = btrfs_lookup_bio_sums_dio(root, inode, dip, bio,
6975 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6981 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6984 struct inode *inode = dip->inode;
6985 struct btrfs_root *root = BTRFS_I(inode)->root;
6987 struct bio *orig_bio = dip->orig_bio;
6988 struct bio_vec *bvec = orig_bio->bi_io_vec;
6989 u64 start_sector = orig_bio->bi_sector;
6990 u64 file_offset = dip->logical_offset;
6995 int async_submit = 0;
6997 map_length = orig_bio->bi_size;
6998 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
6999 &map_length, NULL, 0);
7005 if (map_length >= orig_bio->bi_size) {
7010 /* async crcs make it difficult to collect full stripe writes. */
7011 if (btrfs_get_alloc_profile(root, 1) &
7012 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7017 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7020 bio->bi_private = dip;
7021 bio->bi_end_io = btrfs_end_dio_bio;
7022 atomic_inc(&dip->pending_bios);
7024 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7025 if (unlikely(map_length < submit_len + bvec->bv_len ||
7026 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7027 bvec->bv_offset) < bvec->bv_len)) {
7029 * inc the count before we submit the bio so
7030 * we know the end IO handler won't happen before
7031 * we inc the count. Otherwise, the dip might get freed
7032 * before we're done setting it up
7034 atomic_inc(&dip->pending_bios);
7035 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7036 file_offset, skip_sum,
7040 atomic_dec(&dip->pending_bios);
7044 start_sector += submit_len >> 9;
7045 file_offset += submit_len;
7050 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7051 start_sector, GFP_NOFS);
7054 bio->bi_private = dip;
7055 bio->bi_end_io = btrfs_end_dio_bio;
7057 map_length = orig_bio->bi_size;
7058 ret = btrfs_map_block(root->fs_info, rw,
7060 &map_length, NULL, 0);
7066 submit_len += bvec->bv_len;
7073 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7082 * before atomic variable goto zero, we must
7083 * make sure dip->errors is perceived to be set.
7085 smp_mb__before_atomic_dec();
7086 if (atomic_dec_and_test(&dip->pending_bios))
7087 bio_io_error(dip->orig_bio);
7089 /* bio_end_io() will handle error, so we needn't return it */
7093 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7094 struct inode *inode, loff_t file_offset)
7096 struct btrfs_root *root = BTRFS_I(inode)->root;
7097 struct btrfs_dio_private *dip;
7101 int write = rw & REQ_WRITE;
7105 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7107 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7113 if (!skip_sum && !write) {
7114 csum_size = btrfs_super_csum_size(root->fs_info->super_copy);
7115 sum_len = dio_bio->bi_size >> inode->i_sb->s_blocksize_bits;
7116 sum_len *= csum_size;
7121 dip = kmalloc(sizeof(*dip) + sum_len, GFP_NOFS);
7127 dip->private = dio_bio->bi_private;
7129 dip->logical_offset = file_offset;
7130 dip->bytes = dio_bio->bi_size;
7131 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7132 io_bio->bi_private = dip;
7134 dip->orig_bio = io_bio;
7135 dip->dio_bio = dio_bio;
7136 atomic_set(&dip->pending_bios, 0);
7139 io_bio->bi_end_io = btrfs_endio_direct_write;
7141 io_bio->bi_end_io = btrfs_endio_direct_read;
7143 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7152 * If this is a write, we need to clean up the reserved space and kill
7153 * the ordered extent.
7156 struct btrfs_ordered_extent *ordered;
7157 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7158 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7159 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7160 btrfs_free_reserved_extent(root, ordered->start,
7162 btrfs_put_ordered_extent(ordered);
7163 btrfs_put_ordered_extent(ordered);
7165 bio_endio(dio_bio, ret);
7168 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7169 const struct iovec *iov, loff_t offset,
7170 unsigned long nr_segs)
7176 unsigned blocksize_mask = root->sectorsize - 1;
7177 ssize_t retval = -EINVAL;
7178 loff_t end = offset;
7180 if (offset & blocksize_mask)
7183 /* Check the memory alignment. Blocks cannot straddle pages */
7184 for (seg = 0; seg < nr_segs; seg++) {
7185 addr = (unsigned long)iov[seg].iov_base;
7186 size = iov[seg].iov_len;
7188 if ((addr & blocksize_mask) || (size & blocksize_mask))
7191 /* If this is a write we don't need to check anymore */
7196 * Check to make sure we don't have duplicate iov_base's in this
7197 * iovec, if so return EINVAL, otherwise we'll get csum errors
7198 * when reading back.
7200 for (i = seg + 1; i < nr_segs; i++) {
7201 if (iov[seg].iov_base == iov[i].iov_base)
7210 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7211 const struct iovec *iov, loff_t offset,
7212 unsigned long nr_segs)
7214 struct file *file = iocb->ki_filp;
7215 struct inode *inode = file->f_mapping->host;
7219 bool relock = false;
7222 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7226 atomic_inc(&inode->i_dio_count);
7227 smp_mb__after_atomic_inc();
7230 * The generic stuff only does filemap_write_and_wait_range, which isn't
7231 * enough if we've written compressed pages to this area, so we need to
7232 * call btrfs_wait_ordered_range to make absolutely sure that any
7233 * outstanding dirty pages are on disk.
7235 count = iov_length(iov, nr_segs);
7236 btrfs_wait_ordered_range(inode, offset, count);
7240 * If the write DIO is beyond the EOF, we need update
7241 * the isize, but it is protected by i_mutex. So we can
7242 * not unlock the i_mutex at this case.
7244 if (offset + count <= inode->i_size) {
7245 mutex_unlock(&inode->i_mutex);
7248 ret = btrfs_delalloc_reserve_space(inode, count);
7251 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7252 &BTRFS_I(inode)->runtime_flags))) {
7253 inode_dio_done(inode);
7254 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7258 ret = __blockdev_direct_IO(rw, iocb, inode,
7259 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7260 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7261 btrfs_submit_direct, flags);
7263 if (ret < 0 && ret != -EIOCBQUEUED)
7264 btrfs_delalloc_release_space(inode, count);
7265 else if (ret >= 0 && (size_t)ret < count)
7266 btrfs_delalloc_release_space(inode,
7267 count - (size_t)ret);
7269 btrfs_delalloc_release_metadata(inode, 0);
7273 inode_dio_done(inode);
7275 mutex_lock(&inode->i_mutex);
7280 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7282 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7283 __u64 start, __u64 len)
7287 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7291 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7294 int btrfs_readpage(struct file *file, struct page *page)
7296 struct extent_io_tree *tree;
7297 tree = &BTRFS_I(page->mapping->host)->io_tree;
7298 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7301 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7303 struct extent_io_tree *tree;
7306 if (current->flags & PF_MEMALLOC) {
7307 redirty_page_for_writepage(wbc, page);
7311 tree = &BTRFS_I(page->mapping->host)->io_tree;
7312 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7315 static int btrfs_writepages(struct address_space *mapping,
7316 struct writeback_control *wbc)
7318 struct extent_io_tree *tree;
7320 tree = &BTRFS_I(mapping->host)->io_tree;
7321 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7325 btrfs_readpages(struct file *file, struct address_space *mapping,
7326 struct list_head *pages, unsigned nr_pages)
7328 struct extent_io_tree *tree;
7329 tree = &BTRFS_I(mapping->host)->io_tree;
7330 return extent_readpages(tree, mapping, pages, nr_pages,
7333 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7335 struct extent_io_tree *tree;
7336 struct extent_map_tree *map;
7339 tree = &BTRFS_I(page->mapping->host)->io_tree;
7340 map = &BTRFS_I(page->mapping->host)->extent_tree;
7341 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7343 ClearPagePrivate(page);
7344 set_page_private(page, 0);
7345 page_cache_release(page);
7350 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7352 if (PageWriteback(page) || PageDirty(page))
7354 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7357 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
7358 unsigned int length)
7360 struct inode *inode = page->mapping->host;
7361 struct extent_io_tree *tree;
7362 struct btrfs_ordered_extent *ordered;
7363 struct extent_state *cached_state = NULL;
7364 u64 page_start = page_offset(page);
7365 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7368 * we have the page locked, so new writeback can't start,
7369 * and the dirty bit won't be cleared while we are here.
7371 * Wait for IO on this page so that we can safely clear
7372 * the PagePrivate2 bit and do ordered accounting
7374 wait_on_page_writeback(page);
7376 tree = &BTRFS_I(inode)->io_tree;
7378 btrfs_releasepage(page, GFP_NOFS);
7381 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7382 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7385 * IO on this page will never be started, so we need
7386 * to account for any ordered extents now
7388 clear_extent_bit(tree, page_start, page_end,
7389 EXTENT_DIRTY | EXTENT_DELALLOC |
7390 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7391 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7393 * whoever cleared the private bit is responsible
7394 * for the finish_ordered_io
7396 if (TestClearPagePrivate2(page) &&
7397 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7398 PAGE_CACHE_SIZE, 1)) {
7399 btrfs_finish_ordered_io(ordered);
7401 btrfs_put_ordered_extent(ordered);
7402 cached_state = NULL;
7403 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7405 clear_extent_bit(tree, page_start, page_end,
7406 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7407 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7408 &cached_state, GFP_NOFS);
7409 __btrfs_releasepage(page, GFP_NOFS);
7411 ClearPageChecked(page);
7412 if (PagePrivate(page)) {
7413 ClearPagePrivate(page);
7414 set_page_private(page, 0);
7415 page_cache_release(page);
7420 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7421 * called from a page fault handler when a page is first dirtied. Hence we must
7422 * be careful to check for EOF conditions here. We set the page up correctly
7423 * for a written page which means we get ENOSPC checking when writing into
7424 * holes and correct delalloc and unwritten extent mapping on filesystems that
7425 * support these features.
7427 * We are not allowed to take the i_mutex here so we have to play games to
7428 * protect against truncate races as the page could now be beyond EOF. Because
7429 * vmtruncate() writes the inode size before removing pages, once we have the
7430 * page lock we can determine safely if the page is beyond EOF. If it is not
7431 * beyond EOF, then the page is guaranteed safe against truncation until we
7434 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7436 struct page *page = vmf->page;
7437 struct inode *inode = file_inode(vma->vm_file);
7438 struct btrfs_root *root = BTRFS_I(inode)->root;
7439 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7440 struct btrfs_ordered_extent *ordered;
7441 struct extent_state *cached_state = NULL;
7443 unsigned long zero_start;
7450 sb_start_pagefault(inode->i_sb);
7451 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7453 ret = file_update_time(vma->vm_file);
7459 else /* -ENOSPC, -EIO, etc */
7460 ret = VM_FAULT_SIGBUS;
7466 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7469 size = i_size_read(inode);
7470 page_start = page_offset(page);
7471 page_end = page_start + PAGE_CACHE_SIZE - 1;
7473 if ((page->mapping != inode->i_mapping) ||
7474 (page_start >= size)) {
7475 /* page got truncated out from underneath us */
7478 wait_on_page_writeback(page);
7480 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7481 set_page_extent_mapped(page);
7484 * we can't set the delalloc bits if there are pending ordered
7485 * extents. Drop our locks and wait for them to finish
7487 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7489 unlock_extent_cached(io_tree, page_start, page_end,
7490 &cached_state, GFP_NOFS);
7492 btrfs_start_ordered_extent(inode, ordered, 1);
7493 btrfs_put_ordered_extent(ordered);
7498 * XXX - page_mkwrite gets called every time the page is dirtied, even
7499 * if it was already dirty, so for space accounting reasons we need to
7500 * clear any delalloc bits for the range we are fixing to save. There
7501 * is probably a better way to do this, but for now keep consistent with
7502 * prepare_pages in the normal write path.
7504 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7505 EXTENT_DIRTY | EXTENT_DELALLOC |
7506 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7507 0, 0, &cached_state, GFP_NOFS);
7509 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7512 unlock_extent_cached(io_tree, page_start, page_end,
7513 &cached_state, GFP_NOFS);
7514 ret = VM_FAULT_SIGBUS;
7519 /* page is wholly or partially inside EOF */
7520 if (page_start + PAGE_CACHE_SIZE > size)
7521 zero_start = size & ~PAGE_CACHE_MASK;
7523 zero_start = PAGE_CACHE_SIZE;
7525 if (zero_start != PAGE_CACHE_SIZE) {
7527 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7528 flush_dcache_page(page);
7531 ClearPageChecked(page);
7532 set_page_dirty(page);
7533 SetPageUptodate(page);
7535 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7536 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7537 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7539 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7543 sb_end_pagefault(inode->i_sb);
7544 return VM_FAULT_LOCKED;
7548 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7550 sb_end_pagefault(inode->i_sb);
7554 static int btrfs_truncate(struct inode *inode)
7556 struct btrfs_root *root = BTRFS_I(inode)->root;
7557 struct btrfs_block_rsv *rsv;
7560 struct btrfs_trans_handle *trans;
7561 u64 mask = root->sectorsize - 1;
7562 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7564 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7565 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7568 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7569 * 3 things going on here
7571 * 1) We need to reserve space for our orphan item and the space to
7572 * delete our orphan item. Lord knows we don't want to have a dangling
7573 * orphan item because we didn't reserve space to remove it.
7575 * 2) We need to reserve space to update our inode.
7577 * 3) We need to have something to cache all the space that is going to
7578 * be free'd up by the truncate operation, but also have some slack
7579 * space reserved in case it uses space during the truncate (thank you
7580 * very much snapshotting).
7582 * And we need these to all be seperate. The fact is we can use alot of
7583 * space doing the truncate, and we have no earthly idea how much space
7584 * we will use, so we need the truncate reservation to be seperate so it
7585 * doesn't end up using space reserved for updating the inode or
7586 * removing the orphan item. We also need to be able to stop the
7587 * transaction and start a new one, which means we need to be able to
7588 * update the inode several times, and we have no idea of knowing how
7589 * many times that will be, so we can't just reserve 1 item for the
7590 * entirety of the opration, so that has to be done seperately as well.
7591 * Then there is the orphan item, which does indeed need to be held on
7592 * to for the whole operation, and we need nobody to touch this reserved
7593 * space except the orphan code.
7595 * So that leaves us with
7597 * 1) root->orphan_block_rsv - for the orphan deletion.
7598 * 2) rsv - for the truncate reservation, which we will steal from the
7599 * transaction reservation.
7600 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7601 * updating the inode.
7603 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7606 rsv->size = min_size;
7610 * 1 for the truncate slack space
7611 * 1 for updating the inode.
7613 trans = btrfs_start_transaction(root, 2);
7614 if (IS_ERR(trans)) {
7615 err = PTR_ERR(trans);
7619 /* Migrate the slack space for the truncate to our reserve */
7620 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7625 * setattr is responsible for setting the ordered_data_close flag,
7626 * but that is only tested during the last file release. That
7627 * could happen well after the next commit, leaving a great big
7628 * window where new writes may get lost if someone chooses to write
7629 * to this file after truncating to zero
7631 * The inode doesn't have any dirty data here, and so if we commit
7632 * this is a noop. If someone immediately starts writing to the inode
7633 * it is very likely we'll catch some of their writes in this
7634 * transaction, and the commit will find this file on the ordered
7635 * data list with good things to send down.
7637 * This is a best effort solution, there is still a window where
7638 * using truncate to replace the contents of the file will
7639 * end up with a zero length file after a crash.
7641 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7642 &BTRFS_I(inode)->runtime_flags))
7643 btrfs_add_ordered_operation(trans, root, inode);
7646 * So if we truncate and then write and fsync we normally would just
7647 * write the extents that changed, which is a problem if we need to
7648 * first truncate that entire inode. So set this flag so we write out
7649 * all of the extents in the inode to the sync log so we're completely
7652 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7653 trans->block_rsv = rsv;
7656 ret = btrfs_truncate_inode_items(trans, root, inode,
7658 BTRFS_EXTENT_DATA_KEY);
7659 if (ret != -ENOSPC) {
7664 trans->block_rsv = &root->fs_info->trans_block_rsv;
7665 ret = btrfs_update_inode(trans, root, inode);
7671 btrfs_end_transaction(trans, root);
7672 btrfs_btree_balance_dirty(root);
7674 trans = btrfs_start_transaction(root, 2);
7675 if (IS_ERR(trans)) {
7676 ret = err = PTR_ERR(trans);
7681 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7683 BUG_ON(ret); /* shouldn't happen */
7684 trans->block_rsv = rsv;
7687 if (ret == 0 && inode->i_nlink > 0) {
7688 trans->block_rsv = root->orphan_block_rsv;
7689 ret = btrfs_orphan_del(trans, inode);
7695 trans->block_rsv = &root->fs_info->trans_block_rsv;
7696 ret = btrfs_update_inode(trans, root, inode);
7700 ret = btrfs_end_transaction(trans, root);
7701 btrfs_btree_balance_dirty(root);
7705 btrfs_free_block_rsv(root, rsv);
7714 * create a new subvolume directory/inode (helper for the ioctl).
7716 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7717 struct btrfs_root *new_root, u64 new_dirid)
7719 struct inode *inode;
7723 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7724 new_dirid, new_dirid,
7725 S_IFDIR | (~current_umask() & S_IRWXUGO),
7728 return PTR_ERR(inode);
7729 inode->i_op = &btrfs_dir_inode_operations;
7730 inode->i_fop = &btrfs_dir_file_operations;
7732 set_nlink(inode, 1);
7733 btrfs_i_size_write(inode, 0);
7735 err = btrfs_update_inode(trans, new_root, inode);
7741 struct inode *btrfs_alloc_inode(struct super_block *sb)
7743 struct btrfs_inode *ei;
7744 struct inode *inode;
7746 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7753 ei->last_sub_trans = 0;
7754 ei->logged_trans = 0;
7755 ei->delalloc_bytes = 0;
7756 ei->disk_i_size = 0;
7759 ei->index_cnt = (u64)-1;
7760 ei->last_unlink_trans = 0;
7761 ei->last_log_commit = 0;
7763 spin_lock_init(&ei->lock);
7764 ei->outstanding_extents = 0;
7765 ei->reserved_extents = 0;
7767 ei->runtime_flags = 0;
7768 ei->force_compress = BTRFS_COMPRESS_NONE;
7770 ei->delayed_node = NULL;
7772 inode = &ei->vfs_inode;
7773 extent_map_tree_init(&ei->extent_tree);
7774 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7775 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7776 ei->io_tree.track_uptodate = 1;
7777 ei->io_failure_tree.track_uptodate = 1;
7778 atomic_set(&ei->sync_writers, 0);
7779 mutex_init(&ei->log_mutex);
7780 mutex_init(&ei->delalloc_mutex);
7781 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7782 INIT_LIST_HEAD(&ei->delalloc_inodes);
7783 INIT_LIST_HEAD(&ei->ordered_operations);
7784 RB_CLEAR_NODE(&ei->rb_node);
7789 static void btrfs_i_callback(struct rcu_head *head)
7791 struct inode *inode = container_of(head, struct inode, i_rcu);
7792 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7795 void btrfs_destroy_inode(struct inode *inode)
7797 struct btrfs_ordered_extent *ordered;
7798 struct btrfs_root *root = BTRFS_I(inode)->root;
7800 WARN_ON(!hlist_empty(&inode->i_dentry));
7801 WARN_ON(inode->i_data.nrpages);
7802 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7803 WARN_ON(BTRFS_I(inode)->reserved_extents);
7804 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7805 WARN_ON(BTRFS_I(inode)->csum_bytes);
7808 * This can happen where we create an inode, but somebody else also
7809 * created the same inode and we need to destroy the one we already
7816 * Make sure we're properly removed from the ordered operation
7820 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7821 spin_lock(&root->fs_info->ordered_root_lock);
7822 list_del_init(&BTRFS_I(inode)->ordered_operations);
7823 spin_unlock(&root->fs_info->ordered_root_lock);
7826 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7827 &BTRFS_I(inode)->runtime_flags)) {
7828 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7829 (unsigned long long)btrfs_ino(inode));
7830 atomic_dec(&root->orphan_inodes);
7834 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7838 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7839 (unsigned long long)ordered->file_offset,
7840 (unsigned long long)ordered->len);
7841 btrfs_remove_ordered_extent(inode, ordered);
7842 btrfs_put_ordered_extent(ordered);
7843 btrfs_put_ordered_extent(ordered);
7846 inode_tree_del(inode);
7847 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7849 call_rcu(&inode->i_rcu, btrfs_i_callback);
7852 int btrfs_drop_inode(struct inode *inode)
7854 struct btrfs_root *root = BTRFS_I(inode)->root;
7859 /* the snap/subvol tree is on deleting */
7860 if (btrfs_root_refs(&root->root_item) == 0 &&
7861 root != root->fs_info->tree_root)
7864 return generic_drop_inode(inode);
7867 static void init_once(void *foo)
7869 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7871 inode_init_once(&ei->vfs_inode);
7874 void btrfs_destroy_cachep(void)
7877 * Make sure all delayed rcu free inodes are flushed before we
7881 if (btrfs_inode_cachep)
7882 kmem_cache_destroy(btrfs_inode_cachep);
7883 if (btrfs_trans_handle_cachep)
7884 kmem_cache_destroy(btrfs_trans_handle_cachep);
7885 if (btrfs_transaction_cachep)
7886 kmem_cache_destroy(btrfs_transaction_cachep);
7887 if (btrfs_path_cachep)
7888 kmem_cache_destroy(btrfs_path_cachep);
7889 if (btrfs_free_space_cachep)
7890 kmem_cache_destroy(btrfs_free_space_cachep);
7891 if (btrfs_delalloc_work_cachep)
7892 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7895 int btrfs_init_cachep(void)
7897 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7898 sizeof(struct btrfs_inode), 0,
7899 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7900 if (!btrfs_inode_cachep)
7903 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7904 sizeof(struct btrfs_trans_handle), 0,
7905 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7906 if (!btrfs_trans_handle_cachep)
7909 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7910 sizeof(struct btrfs_transaction), 0,
7911 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7912 if (!btrfs_transaction_cachep)
7915 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7916 sizeof(struct btrfs_path), 0,
7917 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7918 if (!btrfs_path_cachep)
7921 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7922 sizeof(struct btrfs_free_space), 0,
7923 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7924 if (!btrfs_free_space_cachep)
7927 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7928 sizeof(struct btrfs_delalloc_work), 0,
7929 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7931 if (!btrfs_delalloc_work_cachep)
7936 btrfs_destroy_cachep();
7940 static int btrfs_getattr(struct vfsmount *mnt,
7941 struct dentry *dentry, struct kstat *stat)
7944 struct inode *inode = dentry->d_inode;
7945 u32 blocksize = inode->i_sb->s_blocksize;
7947 generic_fillattr(inode, stat);
7948 stat->dev = BTRFS_I(inode)->root->anon_dev;
7949 stat->blksize = PAGE_CACHE_SIZE;
7951 spin_lock(&BTRFS_I(inode)->lock);
7952 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
7953 spin_unlock(&BTRFS_I(inode)->lock);
7954 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7955 ALIGN(delalloc_bytes, blocksize)) >> 9;
7959 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7960 struct inode *new_dir, struct dentry *new_dentry)
7962 struct btrfs_trans_handle *trans;
7963 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7964 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7965 struct inode *new_inode = new_dentry->d_inode;
7966 struct inode *old_inode = old_dentry->d_inode;
7967 struct timespec ctime = CURRENT_TIME;
7971 u64 old_ino = btrfs_ino(old_inode);
7973 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7976 /* we only allow rename subvolume link between subvolumes */
7977 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7980 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7981 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7984 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7985 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7989 /* check for collisions, even if the name isn't there */
7990 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
7991 new_dentry->d_name.name,
7992 new_dentry->d_name.len);
7995 if (ret == -EEXIST) {
7997 * eexist without a new_inode */
8003 /* maybe -EOVERFLOW */
8010 * we're using rename to replace one file with another.
8011 * and the replacement file is large. Start IO on it now so
8012 * we don't add too much work to the end of the transaction
8014 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8015 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8016 filemap_flush(old_inode->i_mapping);
8018 /* close the racy window with snapshot create/destroy ioctl */
8019 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8020 down_read(&root->fs_info->subvol_sem);
8022 * We want to reserve the absolute worst case amount of items. So if
8023 * both inodes are subvols and we need to unlink them then that would
8024 * require 4 item modifications, but if they are both normal inodes it
8025 * would require 5 item modifications, so we'll assume their normal
8026 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8027 * should cover the worst case number of items we'll modify.
8029 trans = btrfs_start_transaction(root, 11);
8030 if (IS_ERR(trans)) {
8031 ret = PTR_ERR(trans);
8036 btrfs_record_root_in_trans(trans, dest);
8038 ret = btrfs_set_inode_index(new_dir, &index);
8042 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8043 /* force full log commit if subvolume involved. */
8044 root->fs_info->last_trans_log_full_commit = trans->transid;
8046 ret = btrfs_insert_inode_ref(trans, dest,
8047 new_dentry->d_name.name,
8048 new_dentry->d_name.len,
8050 btrfs_ino(new_dir), index);
8054 * this is an ugly little race, but the rename is required
8055 * to make sure that if we crash, the inode is either at the
8056 * old name or the new one. pinning the log transaction lets
8057 * us make sure we don't allow a log commit to come in after
8058 * we unlink the name but before we add the new name back in.
8060 btrfs_pin_log_trans(root);
8063 * make sure the inode gets flushed if it is replacing
8066 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8067 btrfs_add_ordered_operation(trans, root, old_inode);
8069 inode_inc_iversion(old_dir);
8070 inode_inc_iversion(new_dir);
8071 inode_inc_iversion(old_inode);
8072 old_dir->i_ctime = old_dir->i_mtime = ctime;
8073 new_dir->i_ctime = new_dir->i_mtime = ctime;
8074 old_inode->i_ctime = ctime;
8076 if (old_dentry->d_parent != new_dentry->d_parent)
8077 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8079 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8080 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8081 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8082 old_dentry->d_name.name,
8083 old_dentry->d_name.len);
8085 ret = __btrfs_unlink_inode(trans, root, old_dir,
8086 old_dentry->d_inode,
8087 old_dentry->d_name.name,
8088 old_dentry->d_name.len);
8090 ret = btrfs_update_inode(trans, root, old_inode);
8093 btrfs_abort_transaction(trans, root, ret);
8098 inode_inc_iversion(new_inode);
8099 new_inode->i_ctime = CURRENT_TIME;
8100 if (unlikely(btrfs_ino(new_inode) ==
8101 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8102 root_objectid = BTRFS_I(new_inode)->location.objectid;
8103 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8105 new_dentry->d_name.name,
8106 new_dentry->d_name.len);
8107 BUG_ON(new_inode->i_nlink == 0);
8109 ret = btrfs_unlink_inode(trans, dest, new_dir,
8110 new_dentry->d_inode,
8111 new_dentry->d_name.name,
8112 new_dentry->d_name.len);
8114 if (!ret && new_inode->i_nlink == 0) {
8115 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8119 btrfs_abort_transaction(trans, root, ret);
8124 ret = btrfs_add_link(trans, new_dir, old_inode,
8125 new_dentry->d_name.name,
8126 new_dentry->d_name.len, 0, index);
8128 btrfs_abort_transaction(trans, root, ret);
8132 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8133 struct dentry *parent = new_dentry->d_parent;
8134 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8135 btrfs_end_log_trans(root);
8138 btrfs_end_transaction(trans, root);
8140 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8141 up_read(&root->fs_info->subvol_sem);
8146 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8148 struct btrfs_delalloc_work *delalloc_work;
8150 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8152 if (delalloc_work->wait)
8153 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8155 filemap_flush(delalloc_work->inode->i_mapping);
8157 if (delalloc_work->delay_iput)
8158 btrfs_add_delayed_iput(delalloc_work->inode);
8160 iput(delalloc_work->inode);
8161 complete(&delalloc_work->completion);
8164 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8165 int wait, int delay_iput)
8167 struct btrfs_delalloc_work *work;
8169 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8173 init_completion(&work->completion);
8174 INIT_LIST_HEAD(&work->list);
8175 work->inode = inode;
8177 work->delay_iput = delay_iput;
8178 work->work.func = btrfs_run_delalloc_work;
8183 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8185 wait_for_completion(&work->completion);
8186 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8190 * some fairly slow code that needs optimization. This walks the list
8191 * of all the inodes with pending delalloc and forces them to disk.
8193 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8195 struct btrfs_inode *binode;
8196 struct inode *inode;
8197 struct btrfs_delalloc_work *work, *next;
8198 struct list_head works;
8199 struct list_head splice;
8202 INIT_LIST_HEAD(&works);
8203 INIT_LIST_HEAD(&splice);
8205 spin_lock(&root->delalloc_lock);
8206 list_splice_init(&root->delalloc_inodes, &splice);
8207 while (!list_empty(&splice)) {
8208 binode = list_entry(splice.next, struct btrfs_inode,
8211 list_move_tail(&binode->delalloc_inodes,
8212 &root->delalloc_inodes);
8213 inode = igrab(&binode->vfs_inode);
8215 cond_resched_lock(&root->delalloc_lock);
8218 spin_unlock(&root->delalloc_lock);
8220 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8221 if (unlikely(!work)) {
8225 list_add_tail(&work->list, &works);
8226 btrfs_queue_worker(&root->fs_info->flush_workers,
8230 spin_lock(&root->delalloc_lock);
8232 spin_unlock(&root->delalloc_lock);
8234 list_for_each_entry_safe(work, next, &works, list) {
8235 list_del_init(&work->list);
8236 btrfs_wait_and_free_delalloc_work(work);
8240 list_for_each_entry_safe(work, next, &works, list) {
8241 list_del_init(&work->list);
8242 btrfs_wait_and_free_delalloc_work(work);
8245 if (!list_empty_careful(&splice)) {
8246 spin_lock(&root->delalloc_lock);
8247 list_splice_tail(&splice, &root->delalloc_inodes);
8248 spin_unlock(&root->delalloc_lock);
8253 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8257 if (root->fs_info->sb->s_flags & MS_RDONLY)
8260 ret = __start_delalloc_inodes(root, delay_iput);
8262 * the filemap_flush will queue IO into the worker threads, but
8263 * we have to make sure the IO is actually started and that
8264 * ordered extents get created before we return
8266 atomic_inc(&root->fs_info->async_submit_draining);
8267 while (atomic_read(&root->fs_info->nr_async_submits) ||
8268 atomic_read(&root->fs_info->async_delalloc_pages)) {
8269 wait_event(root->fs_info->async_submit_wait,
8270 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8271 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8273 atomic_dec(&root->fs_info->async_submit_draining);
8277 int btrfs_start_all_delalloc_inodes(struct btrfs_fs_info *fs_info,
8280 struct btrfs_root *root;
8281 struct list_head splice;
8284 if (fs_info->sb->s_flags & MS_RDONLY)
8287 INIT_LIST_HEAD(&splice);
8289 spin_lock(&fs_info->delalloc_root_lock);
8290 list_splice_init(&fs_info->delalloc_roots, &splice);
8291 while (!list_empty(&splice)) {
8292 root = list_first_entry(&splice, struct btrfs_root,
8294 root = btrfs_grab_fs_root(root);
8296 list_move_tail(&root->delalloc_root,
8297 &fs_info->delalloc_roots);
8298 spin_unlock(&fs_info->delalloc_root_lock);
8300 ret = __start_delalloc_inodes(root, delay_iput);
8301 btrfs_put_fs_root(root);
8305 spin_lock(&fs_info->delalloc_root_lock);
8307 spin_unlock(&fs_info->delalloc_root_lock);
8309 atomic_inc(&fs_info->async_submit_draining);
8310 while (atomic_read(&fs_info->nr_async_submits) ||
8311 atomic_read(&fs_info->async_delalloc_pages)) {
8312 wait_event(fs_info->async_submit_wait,
8313 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8314 atomic_read(&fs_info->async_delalloc_pages) == 0));
8316 atomic_dec(&fs_info->async_submit_draining);
8319 if (!list_empty_careful(&splice)) {
8320 spin_lock(&fs_info->delalloc_root_lock);
8321 list_splice_tail(&splice, &fs_info->delalloc_roots);
8322 spin_unlock(&fs_info->delalloc_root_lock);
8327 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8328 const char *symname)
8330 struct btrfs_trans_handle *trans;
8331 struct btrfs_root *root = BTRFS_I(dir)->root;
8332 struct btrfs_path *path;
8333 struct btrfs_key key;
8334 struct inode *inode = NULL;
8342 struct btrfs_file_extent_item *ei;
8343 struct extent_buffer *leaf;
8345 name_len = strlen(symname) + 1;
8346 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8347 return -ENAMETOOLONG;
8350 * 2 items for inode item and ref
8351 * 2 items for dir items
8352 * 1 item for xattr if selinux is on
8354 trans = btrfs_start_transaction(root, 5);
8356 return PTR_ERR(trans);
8358 err = btrfs_find_free_ino(root, &objectid);
8362 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8363 dentry->d_name.len, btrfs_ino(dir), objectid,
8364 S_IFLNK|S_IRWXUGO, &index);
8365 if (IS_ERR(inode)) {
8366 err = PTR_ERR(inode);
8370 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8377 * If the active LSM wants to access the inode during
8378 * d_instantiate it needs these. Smack checks to see
8379 * if the filesystem supports xattrs by looking at the
8382 inode->i_fop = &btrfs_file_operations;
8383 inode->i_op = &btrfs_file_inode_operations;
8385 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8389 inode->i_mapping->a_ops = &btrfs_aops;
8390 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8391 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8396 path = btrfs_alloc_path();
8402 key.objectid = btrfs_ino(inode);
8404 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8405 datasize = btrfs_file_extent_calc_inline_size(name_len);
8406 err = btrfs_insert_empty_item(trans, root, path, &key,
8410 btrfs_free_path(path);
8413 leaf = path->nodes[0];
8414 ei = btrfs_item_ptr(leaf, path->slots[0],
8415 struct btrfs_file_extent_item);
8416 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8417 btrfs_set_file_extent_type(leaf, ei,
8418 BTRFS_FILE_EXTENT_INLINE);
8419 btrfs_set_file_extent_encryption(leaf, ei, 0);
8420 btrfs_set_file_extent_compression(leaf, ei, 0);
8421 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8422 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8424 ptr = btrfs_file_extent_inline_start(ei);
8425 write_extent_buffer(leaf, symname, ptr, name_len);
8426 btrfs_mark_buffer_dirty(leaf);
8427 btrfs_free_path(path);
8429 inode->i_op = &btrfs_symlink_inode_operations;
8430 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8431 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8432 inode_set_bytes(inode, name_len);
8433 btrfs_i_size_write(inode, name_len - 1);
8434 err = btrfs_update_inode(trans, root, inode);
8440 d_instantiate(dentry, inode);
8441 btrfs_end_transaction(trans, root);
8443 inode_dec_link_count(inode);
8446 btrfs_btree_balance_dirty(root);
8450 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8451 u64 start, u64 num_bytes, u64 min_size,
8452 loff_t actual_len, u64 *alloc_hint,
8453 struct btrfs_trans_handle *trans)
8455 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8456 struct extent_map *em;
8457 struct btrfs_root *root = BTRFS_I(inode)->root;
8458 struct btrfs_key ins;
8459 u64 cur_offset = start;
8463 bool own_trans = true;
8467 while (num_bytes > 0) {
8469 trans = btrfs_start_transaction(root, 3);
8470 if (IS_ERR(trans)) {
8471 ret = PTR_ERR(trans);
8476 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8477 cur_bytes = max(cur_bytes, min_size);
8478 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8479 min_size, 0, *alloc_hint, &ins, 1);
8482 btrfs_end_transaction(trans, root);
8486 ret = insert_reserved_file_extent(trans, inode,
8487 cur_offset, ins.objectid,
8488 ins.offset, ins.offset,
8489 ins.offset, 0, 0, 0,
8490 BTRFS_FILE_EXTENT_PREALLOC);
8492 btrfs_abort_transaction(trans, root, ret);
8494 btrfs_end_transaction(trans, root);
8497 btrfs_drop_extent_cache(inode, cur_offset,
8498 cur_offset + ins.offset -1, 0);
8500 em = alloc_extent_map();
8502 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8503 &BTRFS_I(inode)->runtime_flags);
8507 em->start = cur_offset;
8508 em->orig_start = cur_offset;
8509 em->len = ins.offset;
8510 em->block_start = ins.objectid;
8511 em->block_len = ins.offset;
8512 em->orig_block_len = ins.offset;
8513 em->ram_bytes = ins.offset;
8514 em->bdev = root->fs_info->fs_devices->latest_bdev;
8515 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8516 em->generation = trans->transid;
8519 write_lock(&em_tree->lock);
8520 ret = add_extent_mapping(em_tree, em, 1);
8521 write_unlock(&em_tree->lock);
8524 btrfs_drop_extent_cache(inode, cur_offset,
8525 cur_offset + ins.offset - 1,
8528 free_extent_map(em);
8530 num_bytes -= ins.offset;
8531 cur_offset += ins.offset;
8532 *alloc_hint = ins.objectid + ins.offset;
8534 inode_inc_iversion(inode);
8535 inode->i_ctime = CURRENT_TIME;
8536 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8537 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8538 (actual_len > inode->i_size) &&
8539 (cur_offset > inode->i_size)) {
8540 if (cur_offset > actual_len)
8541 i_size = actual_len;
8543 i_size = cur_offset;
8544 i_size_write(inode, i_size);
8545 btrfs_ordered_update_i_size(inode, i_size, NULL);
8548 ret = btrfs_update_inode(trans, root, inode);
8551 btrfs_abort_transaction(trans, root, ret);
8553 btrfs_end_transaction(trans, root);
8558 btrfs_end_transaction(trans, root);
8563 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8564 u64 start, u64 num_bytes, u64 min_size,
8565 loff_t actual_len, u64 *alloc_hint)
8567 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8568 min_size, actual_len, alloc_hint,
8572 int btrfs_prealloc_file_range_trans(struct inode *inode,
8573 struct btrfs_trans_handle *trans, int mode,
8574 u64 start, u64 num_bytes, u64 min_size,
8575 loff_t actual_len, u64 *alloc_hint)
8577 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8578 min_size, actual_len, alloc_hint, trans);
8581 static int btrfs_set_page_dirty(struct page *page)
8583 return __set_page_dirty_nobuffers(page);
8586 static int btrfs_permission(struct inode *inode, int mask)
8588 struct btrfs_root *root = BTRFS_I(inode)->root;
8589 umode_t mode = inode->i_mode;
8591 if (mask & MAY_WRITE &&
8592 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8593 if (btrfs_root_readonly(root))
8595 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8598 return generic_permission(inode, mask);
8601 static const struct inode_operations btrfs_dir_inode_operations = {
8602 .getattr = btrfs_getattr,
8603 .lookup = btrfs_lookup,
8604 .create = btrfs_create,
8605 .unlink = btrfs_unlink,
8607 .mkdir = btrfs_mkdir,
8608 .rmdir = btrfs_rmdir,
8609 .rename = btrfs_rename,
8610 .symlink = btrfs_symlink,
8611 .setattr = btrfs_setattr,
8612 .mknod = btrfs_mknod,
8613 .setxattr = btrfs_setxattr,
8614 .getxattr = btrfs_getxattr,
8615 .listxattr = btrfs_listxattr,
8616 .removexattr = btrfs_removexattr,
8617 .permission = btrfs_permission,
8618 .get_acl = btrfs_get_acl,
8620 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8621 .lookup = btrfs_lookup,
8622 .permission = btrfs_permission,
8623 .get_acl = btrfs_get_acl,
8626 static const struct file_operations btrfs_dir_file_operations = {
8627 .llseek = generic_file_llseek,
8628 .read = generic_read_dir,
8629 .iterate = btrfs_real_readdir,
8630 .unlocked_ioctl = btrfs_ioctl,
8631 #ifdef CONFIG_COMPAT
8632 .compat_ioctl = btrfs_ioctl,
8634 .release = btrfs_release_file,
8635 .fsync = btrfs_sync_file,
8638 static struct extent_io_ops btrfs_extent_io_ops = {
8639 .fill_delalloc = run_delalloc_range,
8640 .submit_bio_hook = btrfs_submit_bio_hook,
8641 .merge_bio_hook = btrfs_merge_bio_hook,
8642 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8643 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8644 .writepage_start_hook = btrfs_writepage_start_hook,
8645 .set_bit_hook = btrfs_set_bit_hook,
8646 .clear_bit_hook = btrfs_clear_bit_hook,
8647 .merge_extent_hook = btrfs_merge_extent_hook,
8648 .split_extent_hook = btrfs_split_extent_hook,
8652 * btrfs doesn't support the bmap operation because swapfiles
8653 * use bmap to make a mapping of extents in the file. They assume
8654 * these extents won't change over the life of the file and they
8655 * use the bmap result to do IO directly to the drive.
8657 * the btrfs bmap call would return logical addresses that aren't
8658 * suitable for IO and they also will change frequently as COW
8659 * operations happen. So, swapfile + btrfs == corruption.
8661 * For now we're avoiding this by dropping bmap.
8663 static const struct address_space_operations btrfs_aops = {
8664 .readpage = btrfs_readpage,
8665 .writepage = btrfs_writepage,
8666 .writepages = btrfs_writepages,
8667 .readpages = btrfs_readpages,
8668 .direct_IO = btrfs_direct_IO,
8669 .invalidatepage = btrfs_invalidatepage,
8670 .releasepage = btrfs_releasepage,
8671 .set_page_dirty = btrfs_set_page_dirty,
8672 .error_remove_page = generic_error_remove_page,
8675 static const struct address_space_operations btrfs_symlink_aops = {
8676 .readpage = btrfs_readpage,
8677 .writepage = btrfs_writepage,
8678 .invalidatepage = btrfs_invalidatepage,
8679 .releasepage = btrfs_releasepage,
8682 static const struct inode_operations btrfs_file_inode_operations = {
8683 .getattr = btrfs_getattr,
8684 .setattr = btrfs_setattr,
8685 .setxattr = btrfs_setxattr,
8686 .getxattr = btrfs_getxattr,
8687 .listxattr = btrfs_listxattr,
8688 .removexattr = btrfs_removexattr,
8689 .permission = btrfs_permission,
8690 .fiemap = btrfs_fiemap,
8691 .get_acl = btrfs_get_acl,
8692 .update_time = btrfs_update_time,
8694 static const struct inode_operations btrfs_special_inode_operations = {
8695 .getattr = btrfs_getattr,
8696 .setattr = btrfs_setattr,
8697 .permission = btrfs_permission,
8698 .setxattr = btrfs_setxattr,
8699 .getxattr = btrfs_getxattr,
8700 .listxattr = btrfs_listxattr,
8701 .removexattr = btrfs_removexattr,
8702 .get_acl = btrfs_get_acl,
8703 .update_time = btrfs_update_time,
8705 static const struct inode_operations btrfs_symlink_inode_operations = {
8706 .readlink = generic_readlink,
8707 .follow_link = page_follow_link_light,
8708 .put_link = page_put_link,
8709 .getattr = btrfs_getattr,
8710 .setattr = btrfs_setattr,
8711 .permission = btrfs_permission,
8712 .setxattr = btrfs_setxattr,
8713 .getxattr = btrfs_getxattr,
8714 .listxattr = btrfs_listxattr,
8715 .removexattr = btrfs_removexattr,
8716 .get_acl = btrfs_get_acl,
8717 .update_time = btrfs_update_time,
8720 const struct dentry_operations btrfs_dentry_operations = {
8721 .d_delete = btrfs_dentry_delete,
8722 .d_release = btrfs_dentry_release,