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/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
43 #include <linux/blkdev.h>
47 #include "transaction.h"
48 #include "btrfs_inode.h"
49 #include "print-tree.h"
50 #include "ordered-data.h"
54 #include "compression.h"
56 #include "free-space-cache.h"
57 #include "inode-map.h"
60 struct btrfs_iget_args {
62 struct btrfs_root *root;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static struct extent_io_ops btrfs_extent_io_ops;
75 static struct kmem_cache *btrfs_inode_cachep;
76 static struct kmem_cache *btrfs_delalloc_work_cachep;
77 struct kmem_cache *btrfs_trans_handle_cachep;
78 struct kmem_cache *btrfs_transaction_cachep;
79 struct kmem_cache *btrfs_path_cachep;
80 struct kmem_cache *btrfs_free_space_cachep;
83 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
84 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
85 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
86 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
87 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
88 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
89 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
90 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
93 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
94 static int btrfs_truncate(struct inode *inode);
95 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
96 static noinline int cow_file_range(struct inode *inode,
97 struct page *locked_page,
98 u64 start, u64 end, int *page_started,
99 unsigned long *nr_written, int unlock);
100 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
101 u64 len, u64 orig_start,
102 u64 block_start, u64 block_len,
103 u64 orig_block_len, u64 ram_bytes,
106 static int btrfs_dirty_inode(struct inode *inode);
108 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
109 struct inode *inode, struct inode *dir,
110 const struct qstr *qstr)
114 err = btrfs_init_acl(trans, inode, dir);
116 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
121 * this does all the hard work for inserting an inline extent into
122 * the btree. The caller should have done a btrfs_drop_extents so that
123 * no overlapping inline items exist in the btree
125 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
126 struct btrfs_root *root, struct inode *inode,
127 u64 start, size_t size, size_t compressed_size,
129 struct page **compressed_pages)
131 struct btrfs_key key;
132 struct btrfs_path *path;
133 struct extent_buffer *leaf;
134 struct page *page = NULL;
137 struct btrfs_file_extent_item *ei;
140 size_t cur_size = size;
142 unsigned long offset;
144 if (compressed_size && compressed_pages)
145 cur_size = compressed_size;
147 path = btrfs_alloc_path();
151 path->leave_spinning = 1;
153 key.objectid = btrfs_ino(inode);
155 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
156 datasize = btrfs_file_extent_calc_inline_size(cur_size);
158 inode_add_bytes(inode, size);
159 ret = btrfs_insert_empty_item(trans, root, path, &key,
165 leaf = path->nodes[0];
166 ei = btrfs_item_ptr(leaf, path->slots[0],
167 struct btrfs_file_extent_item);
168 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
169 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
170 btrfs_set_file_extent_encryption(leaf, ei, 0);
171 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
172 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
173 ptr = btrfs_file_extent_inline_start(ei);
175 if (compress_type != BTRFS_COMPRESS_NONE) {
178 while (compressed_size > 0) {
179 cpage = compressed_pages[i];
180 cur_size = min_t(unsigned long, compressed_size,
183 kaddr = kmap_atomic(cpage);
184 write_extent_buffer(leaf, kaddr, ptr, cur_size);
185 kunmap_atomic(kaddr);
189 compressed_size -= cur_size;
191 btrfs_set_file_extent_compression(leaf, ei,
194 page = find_get_page(inode->i_mapping,
195 start >> PAGE_CACHE_SHIFT);
196 btrfs_set_file_extent_compression(leaf, ei, 0);
197 kaddr = kmap_atomic(page);
198 offset = start & (PAGE_CACHE_SIZE - 1);
199 write_extent_buffer(leaf, kaddr + offset, ptr, size);
200 kunmap_atomic(kaddr);
201 page_cache_release(page);
203 btrfs_mark_buffer_dirty(leaf);
204 btrfs_free_path(path);
207 * we're an inline extent, so nobody can
208 * extend the file past i_size without locking
209 * a page we already have locked.
211 * We must do any isize and inode updates
212 * before we unlock the pages. Otherwise we
213 * could end up racing with unlink.
215 BTRFS_I(inode)->disk_i_size = inode->i_size;
216 ret = btrfs_update_inode(trans, root, inode);
220 btrfs_free_path(path);
226 * conditionally insert an inline extent into the file. This
227 * does the checks required to make sure the data is small enough
228 * to fit as an inline extent.
230 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
231 struct btrfs_root *root,
232 struct inode *inode, u64 start, u64 end,
233 size_t compressed_size, int compress_type,
234 struct page **compressed_pages)
236 u64 isize = i_size_read(inode);
237 u64 actual_end = min(end + 1, isize);
238 u64 inline_len = actual_end - start;
239 u64 aligned_end = ALIGN(end, root->sectorsize);
240 u64 data_len = inline_len;
244 data_len = compressed_size;
247 actual_end >= PAGE_CACHE_SIZE ||
248 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
250 (actual_end & (root->sectorsize - 1)) == 0) ||
252 data_len > root->fs_info->max_inline) {
256 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
260 if (isize > actual_end)
261 inline_len = min_t(u64, isize, actual_end);
262 ret = insert_inline_extent(trans, root, inode, start,
263 inline_len, compressed_size,
264 compress_type, compressed_pages);
265 if (ret && ret != -ENOSPC) {
266 btrfs_abort_transaction(trans, root, ret);
268 } else if (ret == -ENOSPC) {
272 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
273 btrfs_delalloc_release_metadata(inode, end + 1 - start);
274 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
278 struct async_extent {
283 unsigned long nr_pages;
285 struct list_head list;
290 struct btrfs_root *root;
291 struct page *locked_page;
294 struct list_head extents;
295 struct btrfs_work work;
298 static noinline int add_async_extent(struct async_cow *cow,
299 u64 start, u64 ram_size,
302 unsigned long nr_pages,
305 struct async_extent *async_extent;
307 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
308 BUG_ON(!async_extent); /* -ENOMEM */
309 async_extent->start = start;
310 async_extent->ram_size = ram_size;
311 async_extent->compressed_size = compressed_size;
312 async_extent->pages = pages;
313 async_extent->nr_pages = nr_pages;
314 async_extent->compress_type = compress_type;
315 list_add_tail(&async_extent->list, &cow->extents);
320 * we create compressed extents in two phases. The first
321 * phase compresses a range of pages that have already been
322 * locked (both pages and state bits are locked).
324 * This is done inside an ordered work queue, and the compression
325 * is spread across many cpus. The actual IO submission is step
326 * two, and the ordered work queue takes care of making sure that
327 * happens in the same order things were put onto the queue by
328 * writepages and friends.
330 * If this code finds it can't get good compression, it puts an
331 * entry onto the work queue to write the uncompressed bytes. This
332 * makes sure that both compressed inodes and uncompressed inodes
333 * are written in the same order that the flusher thread sent them
336 static noinline int compress_file_range(struct inode *inode,
337 struct page *locked_page,
339 struct async_cow *async_cow,
342 struct btrfs_root *root = BTRFS_I(inode)->root;
343 struct btrfs_trans_handle *trans;
345 u64 blocksize = root->sectorsize;
347 u64 isize = i_size_read(inode);
349 struct page **pages = NULL;
350 unsigned long nr_pages;
351 unsigned long nr_pages_ret = 0;
352 unsigned long total_compressed = 0;
353 unsigned long total_in = 0;
354 unsigned long max_compressed = 128 * 1024;
355 unsigned long max_uncompressed = 128 * 1024;
358 int compress_type = root->fs_info->compress_type;
361 /* if this is a small write inside eof, kick off a defrag */
362 if ((end - start + 1) < 16 * 1024 &&
363 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
364 btrfs_add_inode_defrag(NULL, inode);
366 actual_end = min_t(u64, isize, end + 1);
369 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
370 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
373 * we don't want to send crud past the end of i_size through
374 * compression, that's just a waste of CPU time. So, if the
375 * end of the file is before the start of our current
376 * requested range of bytes, we bail out to the uncompressed
377 * cleanup code that can deal with all of this.
379 * It isn't really the fastest way to fix things, but this is a
380 * very uncommon corner.
382 if (actual_end <= start)
383 goto cleanup_and_bail_uncompressed;
385 total_compressed = actual_end - start;
387 /* we want to make sure that amount of ram required to uncompress
388 * an extent is reasonable, so we limit the total size in ram
389 * of a compressed extent to 128k. This is a crucial number
390 * because it also controls how easily we can spread reads across
391 * cpus for decompression.
393 * We also want to make sure the amount of IO required to do
394 * a random read is reasonably small, so we limit the size of
395 * a compressed extent to 128k.
397 total_compressed = min(total_compressed, max_uncompressed);
398 num_bytes = ALIGN(end - start + 1, blocksize);
399 num_bytes = max(blocksize, num_bytes);
404 * we do compression for mount -o compress and when the
405 * inode has not been flagged as nocompress. This flag can
406 * change at any time if we discover bad compression ratios.
408 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
409 (btrfs_test_opt(root, COMPRESS) ||
410 (BTRFS_I(inode)->force_compress) ||
411 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
413 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
415 /* just bail out to the uncompressed code */
419 if (BTRFS_I(inode)->force_compress)
420 compress_type = BTRFS_I(inode)->force_compress;
423 * we need to call clear_page_dirty_for_io on each
424 * page in the range. Otherwise applications with the file
425 * mmap'd can wander in and change the page contents while
426 * we are compressing them.
428 * If the compression fails for any reason, we set the pages
429 * dirty again later on.
431 extent_range_clear_dirty_for_io(inode, start, end);
433 ret = btrfs_compress_pages(compress_type,
434 inode->i_mapping, start,
435 total_compressed, pages,
436 nr_pages, &nr_pages_ret,
442 unsigned long offset = total_compressed &
443 (PAGE_CACHE_SIZE - 1);
444 struct page *page = pages[nr_pages_ret - 1];
447 /* zero the tail end of the last page, we might be
448 * sending it down to disk
451 kaddr = kmap_atomic(page);
452 memset(kaddr + offset, 0,
453 PAGE_CACHE_SIZE - offset);
454 kunmap_atomic(kaddr);
461 trans = btrfs_join_transaction(root);
463 ret = PTR_ERR(trans);
465 goto cleanup_and_out;
467 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
469 /* lets try to make an inline extent */
470 if (ret || total_in < (actual_end - start)) {
471 /* we didn't compress the entire range, try
472 * to make an uncompressed inline extent.
474 ret = cow_file_range_inline(trans, root, inode,
475 start, end, 0, 0, NULL);
477 /* try making a compressed inline extent */
478 ret = cow_file_range_inline(trans, root, inode,
481 compress_type, pages);
485 * inline extent creation worked or returned error,
486 * we don't need to create any more async work items.
487 * Unlock and free up our temp pages.
489 extent_clear_unlock_delalloc(inode,
490 &BTRFS_I(inode)->io_tree,
492 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
493 EXTENT_CLEAR_DELALLOC |
494 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
496 btrfs_end_transaction(trans, root);
499 btrfs_end_transaction(trans, root);
504 * we aren't doing an inline extent round the compressed size
505 * up to a block size boundary so the allocator does sane
508 total_compressed = ALIGN(total_compressed, blocksize);
511 * one last check to make sure the compression is really a
512 * win, compare the page count read with the blocks on disk
514 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
515 if (total_compressed >= total_in) {
518 num_bytes = total_in;
521 if (!will_compress && pages) {
523 * the compression code ran but failed to make things smaller,
524 * free any pages it allocated and our page pointer array
526 for (i = 0; i < nr_pages_ret; i++) {
527 WARN_ON(pages[i]->mapping);
528 page_cache_release(pages[i]);
532 total_compressed = 0;
535 /* flag the file so we don't compress in the future */
536 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
537 !(BTRFS_I(inode)->force_compress)) {
538 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
544 /* the async work queues will take care of doing actual
545 * allocation on disk for these compressed pages,
546 * and will submit them to the elevator.
548 add_async_extent(async_cow, start, num_bytes,
549 total_compressed, pages, nr_pages_ret,
552 if (start + num_bytes < end) {
559 cleanup_and_bail_uncompressed:
561 * No compression, but we still need to write the pages in
562 * the file we've been given so far. redirty the locked
563 * page if it corresponds to our extent and set things up
564 * for the async work queue to run cow_file_range to do
565 * the normal delalloc dance
567 if (page_offset(locked_page) >= start &&
568 page_offset(locked_page) <= end) {
569 __set_page_dirty_nobuffers(locked_page);
570 /* unlocked later on in the async handlers */
573 extent_range_redirty_for_io(inode, start, end);
574 add_async_extent(async_cow, start, end - start + 1,
575 0, NULL, 0, BTRFS_COMPRESS_NONE);
583 for (i = 0; i < nr_pages_ret; i++) {
584 WARN_ON(pages[i]->mapping);
585 page_cache_release(pages[i]);
592 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
594 EXTENT_CLEAR_UNLOCK_PAGE |
596 EXTENT_CLEAR_DELALLOC |
597 EXTENT_SET_WRITEBACK |
598 EXTENT_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,
771 &BTRFS_I(inode)->io_tree,
773 async_extent->start +
774 async_extent->ram_size - 1,
775 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
776 EXTENT_CLEAR_UNLOCK |
777 EXTENT_CLEAR_DELALLOC |
778 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
780 ret = btrfs_submit_compressed_write(inode,
782 async_extent->ram_size,
784 ins.offset, async_extent->pages,
785 async_extent->nr_pages);
786 alloc_hint = ins.objectid + ins.offset;
796 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
798 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
800 async_extent->start +
801 async_extent->ram_size - 1,
802 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
803 EXTENT_CLEAR_UNLOCK |
804 EXTENT_CLEAR_DELALLOC |
806 EXTENT_SET_WRITEBACK |
807 EXTENT_END_WRITEBACK);
812 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
815 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
816 struct extent_map *em;
819 read_lock(&em_tree->lock);
820 em = search_extent_mapping(em_tree, start, num_bytes);
823 * if block start isn't an actual block number then find the
824 * first block in this inode and use that as a hint. If that
825 * block is also bogus then just don't worry about it.
827 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
829 em = search_extent_mapping(em_tree, 0, 0);
830 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
831 alloc_hint = em->block_start;
835 alloc_hint = em->block_start;
839 read_unlock(&em_tree->lock);
845 * when extent_io.c finds a delayed allocation range in the file,
846 * the call backs end up in this code. The basic idea is to
847 * allocate extents on disk for the range, and create ordered data structs
848 * in ram to track those extents.
850 * locked_page is the page that writepage had locked already. We use
851 * it to make sure we don't do extra locks or unlocks.
853 * *page_started is set to one if we unlock locked_page and do everything
854 * required to start IO on it. It may be clean and already done with
857 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
859 struct btrfs_root *root,
860 struct page *locked_page,
861 u64 start, u64 end, int *page_started,
862 unsigned long *nr_written,
867 unsigned long ram_size;
870 u64 blocksize = root->sectorsize;
871 struct btrfs_key ins;
872 struct extent_map *em;
873 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
876 BUG_ON(btrfs_is_free_space_inode(inode));
878 num_bytes = ALIGN(end - start + 1, blocksize);
879 num_bytes = max(blocksize, num_bytes);
880 disk_num_bytes = num_bytes;
882 /* if this is a small write inside eof, kick off defrag */
883 if (num_bytes < 64 * 1024 &&
884 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
885 btrfs_add_inode_defrag(trans, inode);
888 /* lets try to make an inline extent */
889 ret = cow_file_range_inline(trans, root, inode,
890 start, end, 0, 0, NULL);
892 extent_clear_unlock_delalloc(inode,
893 &BTRFS_I(inode)->io_tree,
895 EXTENT_CLEAR_UNLOCK_PAGE |
896 EXTENT_CLEAR_UNLOCK |
897 EXTENT_CLEAR_DELALLOC |
899 EXTENT_SET_WRITEBACK |
900 EXTENT_END_WRITEBACK);
902 *nr_written = *nr_written +
903 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
906 } else if (ret < 0) {
907 btrfs_abort_transaction(trans, root, ret);
912 BUG_ON(disk_num_bytes >
913 btrfs_super_total_bytes(root->fs_info->super_copy));
915 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
916 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
918 while (disk_num_bytes > 0) {
921 cur_alloc_size = disk_num_bytes;
922 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
923 root->sectorsize, 0, alloc_hint,
926 btrfs_abort_transaction(trans, root, ret);
930 em = alloc_extent_map();
936 em->orig_start = em->start;
937 ram_size = ins.offset;
938 em->len = ins.offset;
939 em->mod_start = em->start;
940 em->mod_len = em->len;
942 em->block_start = ins.objectid;
943 em->block_len = ins.offset;
944 em->orig_block_len = ins.offset;
945 em->ram_bytes = ram_size;
946 em->bdev = root->fs_info->fs_devices->latest_bdev;
947 set_bit(EXTENT_FLAG_PINNED, &em->flags);
951 write_lock(&em_tree->lock);
952 ret = add_extent_mapping(em_tree, em, 1);
953 write_unlock(&em_tree->lock);
954 if (ret != -EEXIST) {
958 btrfs_drop_extent_cache(inode, start,
959 start + ram_size - 1, 0);
964 cur_alloc_size = ins.offset;
965 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
966 ram_size, cur_alloc_size, 0);
970 if (root->root_key.objectid ==
971 BTRFS_DATA_RELOC_TREE_OBJECTID) {
972 ret = btrfs_reloc_clone_csums(inode, start,
975 btrfs_abort_transaction(trans, root, ret);
980 if (disk_num_bytes < cur_alloc_size)
983 /* we're not doing compressed IO, don't unlock the first
984 * page (which the caller expects to stay locked), don't
985 * clear any dirty bits and don't set any writeback bits
987 * Do set the Private2 bit so we know this page was properly
988 * setup for writepage
990 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
991 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
994 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
995 start, start + ram_size - 1,
997 disk_num_bytes -= cur_alloc_size;
998 num_bytes -= cur_alloc_size;
999 alloc_hint = ins.objectid + ins.offset;
1000 start += cur_alloc_size;
1006 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1008 extent_clear_unlock_delalloc(inode,
1009 &BTRFS_I(inode)->io_tree,
1010 start, end, locked_page,
1011 EXTENT_CLEAR_UNLOCK_PAGE |
1012 EXTENT_CLEAR_UNLOCK |
1013 EXTENT_CLEAR_DELALLOC |
1014 EXTENT_CLEAR_DIRTY |
1015 EXTENT_SET_WRITEBACK |
1016 EXTENT_END_WRITEBACK);
1021 static noinline int cow_file_range(struct inode *inode,
1022 struct page *locked_page,
1023 u64 start, u64 end, int *page_started,
1024 unsigned long *nr_written,
1027 struct btrfs_trans_handle *trans;
1028 struct btrfs_root *root = BTRFS_I(inode)->root;
1031 trans = btrfs_join_transaction(root);
1032 if (IS_ERR(trans)) {
1033 extent_clear_unlock_delalloc(inode,
1034 &BTRFS_I(inode)->io_tree,
1035 start, end, locked_page,
1036 EXTENT_CLEAR_UNLOCK_PAGE |
1037 EXTENT_CLEAR_UNLOCK |
1038 EXTENT_CLEAR_DELALLOC |
1039 EXTENT_CLEAR_DIRTY |
1040 EXTENT_SET_WRITEBACK |
1041 EXTENT_END_WRITEBACK);
1042 return PTR_ERR(trans);
1044 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1046 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1047 page_started, nr_written, unlock);
1049 btrfs_end_transaction(trans, root);
1055 * work queue call back to started compression on a file and pages
1057 static noinline void async_cow_start(struct btrfs_work *work)
1059 struct async_cow *async_cow;
1061 async_cow = container_of(work, struct async_cow, work);
1063 compress_file_range(async_cow->inode, async_cow->locked_page,
1064 async_cow->start, async_cow->end, async_cow,
1066 if (num_added == 0) {
1067 btrfs_add_delayed_iput(async_cow->inode);
1068 async_cow->inode = NULL;
1073 * work queue call back to submit previously compressed pages
1075 static noinline void async_cow_submit(struct btrfs_work *work)
1077 struct async_cow *async_cow;
1078 struct btrfs_root *root;
1079 unsigned long nr_pages;
1081 async_cow = container_of(work, struct async_cow, work);
1083 root = async_cow->root;
1084 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1087 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1089 waitqueue_active(&root->fs_info->async_submit_wait))
1090 wake_up(&root->fs_info->async_submit_wait);
1092 if (async_cow->inode)
1093 submit_compressed_extents(async_cow->inode, async_cow);
1096 static noinline void async_cow_free(struct btrfs_work *work)
1098 struct async_cow *async_cow;
1099 async_cow = container_of(work, struct async_cow, work);
1100 if (async_cow->inode)
1101 btrfs_add_delayed_iput(async_cow->inode);
1105 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1106 u64 start, u64 end, int *page_started,
1107 unsigned long *nr_written)
1109 struct async_cow *async_cow;
1110 struct btrfs_root *root = BTRFS_I(inode)->root;
1111 unsigned long nr_pages;
1113 int limit = 10 * 1024 * 1024;
1115 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1116 1, 0, NULL, GFP_NOFS);
1117 while (start < end) {
1118 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1119 BUG_ON(!async_cow); /* -ENOMEM */
1120 async_cow->inode = igrab(inode);
1121 async_cow->root = root;
1122 async_cow->locked_page = locked_page;
1123 async_cow->start = start;
1125 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1128 cur_end = min(end, start + 512 * 1024 - 1);
1130 async_cow->end = cur_end;
1131 INIT_LIST_HEAD(&async_cow->extents);
1133 async_cow->work.func = async_cow_start;
1134 async_cow->work.ordered_func = async_cow_submit;
1135 async_cow->work.ordered_free = async_cow_free;
1136 async_cow->work.flags = 0;
1138 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1140 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1142 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1145 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1146 wait_event(root->fs_info->async_submit_wait,
1147 (atomic_read(&root->fs_info->async_delalloc_pages) <
1151 while (atomic_read(&root->fs_info->async_submit_draining) &&
1152 atomic_read(&root->fs_info->async_delalloc_pages)) {
1153 wait_event(root->fs_info->async_submit_wait,
1154 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1158 *nr_written += nr_pages;
1159 start = cur_end + 1;
1165 static noinline int csum_exist_in_range(struct btrfs_root *root,
1166 u64 bytenr, u64 num_bytes)
1169 struct btrfs_ordered_sum *sums;
1172 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1173 bytenr + num_bytes - 1, &list, 0);
1174 if (ret == 0 && list_empty(&list))
1177 while (!list_empty(&list)) {
1178 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1179 list_del(&sums->list);
1186 * when nowcow writeback call back. This checks for snapshots or COW copies
1187 * of the extents that exist in the file, and COWs the file as required.
1189 * If no cow copies or snapshots exist, we write directly to the existing
1192 static noinline int run_delalloc_nocow(struct inode *inode,
1193 struct page *locked_page,
1194 u64 start, u64 end, int *page_started, int force,
1195 unsigned long *nr_written)
1197 struct btrfs_root *root = BTRFS_I(inode)->root;
1198 struct btrfs_trans_handle *trans;
1199 struct extent_buffer *leaf;
1200 struct btrfs_path *path;
1201 struct btrfs_file_extent_item *fi;
1202 struct btrfs_key found_key;
1217 u64 ino = btrfs_ino(inode);
1219 path = btrfs_alloc_path();
1221 extent_clear_unlock_delalloc(inode,
1222 &BTRFS_I(inode)->io_tree,
1223 start, end, locked_page,
1224 EXTENT_CLEAR_UNLOCK_PAGE |
1225 EXTENT_CLEAR_UNLOCK |
1226 EXTENT_CLEAR_DELALLOC |
1227 EXTENT_CLEAR_DIRTY |
1228 EXTENT_SET_WRITEBACK |
1229 EXTENT_END_WRITEBACK);
1233 nolock = btrfs_is_free_space_inode(inode);
1236 trans = btrfs_join_transaction_nolock(root);
1238 trans = btrfs_join_transaction(root);
1240 if (IS_ERR(trans)) {
1241 extent_clear_unlock_delalloc(inode,
1242 &BTRFS_I(inode)->io_tree,
1243 start, end, locked_page,
1244 EXTENT_CLEAR_UNLOCK_PAGE |
1245 EXTENT_CLEAR_UNLOCK |
1246 EXTENT_CLEAR_DELALLOC |
1247 EXTENT_CLEAR_DIRTY |
1248 EXTENT_SET_WRITEBACK |
1249 EXTENT_END_WRITEBACK);
1250 btrfs_free_path(path);
1251 return PTR_ERR(trans);
1254 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1256 cow_start = (u64)-1;
1259 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1262 btrfs_abort_transaction(trans, root, ret);
1265 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1266 leaf = path->nodes[0];
1267 btrfs_item_key_to_cpu(leaf, &found_key,
1268 path->slots[0] - 1);
1269 if (found_key.objectid == ino &&
1270 found_key.type == BTRFS_EXTENT_DATA_KEY)
1275 leaf = path->nodes[0];
1276 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1277 ret = btrfs_next_leaf(root, path);
1279 btrfs_abort_transaction(trans, root, ret);
1284 leaf = path->nodes[0];
1290 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1292 if (found_key.objectid > ino ||
1293 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1294 found_key.offset > end)
1297 if (found_key.offset > cur_offset) {
1298 extent_end = found_key.offset;
1303 fi = btrfs_item_ptr(leaf, path->slots[0],
1304 struct btrfs_file_extent_item);
1305 extent_type = btrfs_file_extent_type(leaf, fi);
1307 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1308 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1309 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1310 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1311 extent_offset = btrfs_file_extent_offset(leaf, fi);
1312 extent_end = found_key.offset +
1313 btrfs_file_extent_num_bytes(leaf, fi);
1315 btrfs_file_extent_disk_num_bytes(leaf, fi);
1316 if (extent_end <= start) {
1320 if (disk_bytenr == 0)
1322 if (btrfs_file_extent_compression(leaf, fi) ||
1323 btrfs_file_extent_encryption(leaf, fi) ||
1324 btrfs_file_extent_other_encoding(leaf, fi))
1326 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1328 if (btrfs_extent_readonly(root, disk_bytenr))
1330 if (btrfs_cross_ref_exist(trans, root, ino,
1332 extent_offset, disk_bytenr))
1334 disk_bytenr += extent_offset;
1335 disk_bytenr += cur_offset - found_key.offset;
1336 num_bytes = min(end + 1, extent_end) - cur_offset;
1338 * force cow if csum exists in the range.
1339 * this ensure that csum for a given extent are
1340 * either valid or do not exist.
1342 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1345 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1346 extent_end = found_key.offset +
1347 btrfs_file_extent_inline_len(leaf, fi);
1348 extent_end = ALIGN(extent_end, root->sectorsize);
1353 if (extent_end <= start) {
1358 if (cow_start == (u64)-1)
1359 cow_start = cur_offset;
1360 cur_offset = extent_end;
1361 if (cur_offset > end)
1367 btrfs_release_path(path);
1368 if (cow_start != (u64)-1) {
1369 ret = __cow_file_range(trans, inode, root, locked_page,
1370 cow_start, found_key.offset - 1,
1371 page_started, nr_written, 1);
1373 btrfs_abort_transaction(trans, root, ret);
1376 cow_start = (u64)-1;
1379 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1380 struct extent_map *em;
1381 struct extent_map_tree *em_tree;
1382 em_tree = &BTRFS_I(inode)->extent_tree;
1383 em = alloc_extent_map();
1384 BUG_ON(!em); /* -ENOMEM */
1385 em->start = cur_offset;
1386 em->orig_start = found_key.offset - extent_offset;
1387 em->len = num_bytes;
1388 em->block_len = num_bytes;
1389 em->block_start = disk_bytenr;
1390 em->orig_block_len = disk_num_bytes;
1391 em->ram_bytes = ram_bytes;
1392 em->bdev = root->fs_info->fs_devices->latest_bdev;
1393 em->mod_start = em->start;
1394 em->mod_len = em->len;
1395 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1396 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1397 em->generation = -1;
1399 write_lock(&em_tree->lock);
1400 ret = add_extent_mapping(em_tree, em, 1);
1401 write_unlock(&em_tree->lock);
1402 if (ret != -EEXIST) {
1403 free_extent_map(em);
1406 btrfs_drop_extent_cache(inode, em->start,
1407 em->start + em->len - 1, 0);
1409 type = BTRFS_ORDERED_PREALLOC;
1411 type = BTRFS_ORDERED_NOCOW;
1414 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1415 num_bytes, num_bytes, type);
1416 BUG_ON(ret); /* -ENOMEM */
1418 if (root->root_key.objectid ==
1419 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1420 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1423 btrfs_abort_transaction(trans, root, ret);
1428 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1429 cur_offset, cur_offset + num_bytes - 1,
1430 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1431 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1432 EXTENT_SET_PRIVATE2);
1433 cur_offset = extent_end;
1434 if (cur_offset > end)
1437 btrfs_release_path(path);
1439 if (cur_offset <= end && cow_start == (u64)-1) {
1440 cow_start = cur_offset;
1444 if (cow_start != (u64)-1) {
1445 ret = __cow_file_range(trans, inode, root, locked_page,
1447 page_started, nr_written, 1);
1449 btrfs_abort_transaction(trans, root, ret);
1455 err = btrfs_end_transaction(trans, root);
1459 if (ret && cur_offset < end)
1460 extent_clear_unlock_delalloc(inode,
1461 &BTRFS_I(inode)->io_tree,
1462 cur_offset, end, locked_page,
1463 EXTENT_CLEAR_UNLOCK_PAGE |
1464 EXTENT_CLEAR_UNLOCK |
1465 EXTENT_CLEAR_DELALLOC |
1466 EXTENT_CLEAR_DIRTY |
1467 EXTENT_SET_WRITEBACK |
1468 EXTENT_END_WRITEBACK);
1470 btrfs_free_path(path);
1475 * extent_io.c call back to do delayed allocation processing
1477 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1478 u64 start, u64 end, int *page_started,
1479 unsigned long *nr_written)
1482 struct btrfs_root *root = BTRFS_I(inode)->root;
1484 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1485 ret = run_delalloc_nocow(inode, locked_page, start, end,
1486 page_started, 1, nr_written);
1487 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1488 ret = run_delalloc_nocow(inode, locked_page, start, end,
1489 page_started, 0, nr_written);
1490 } else if (!btrfs_test_opt(root, COMPRESS) &&
1491 !(BTRFS_I(inode)->force_compress) &&
1492 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1493 ret = cow_file_range(inode, locked_page, start, end,
1494 page_started, nr_written, 1);
1496 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1497 &BTRFS_I(inode)->runtime_flags);
1498 ret = cow_file_range_async(inode, locked_page, start, end,
1499 page_started, nr_written);
1504 static void btrfs_split_extent_hook(struct inode *inode,
1505 struct extent_state *orig, u64 split)
1507 /* not delalloc, ignore it */
1508 if (!(orig->state & EXTENT_DELALLOC))
1511 spin_lock(&BTRFS_I(inode)->lock);
1512 BTRFS_I(inode)->outstanding_extents++;
1513 spin_unlock(&BTRFS_I(inode)->lock);
1517 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1518 * extents so we can keep track of new extents that are just merged onto old
1519 * extents, such as when we are doing sequential writes, so we can properly
1520 * account for the metadata space we'll need.
1522 static void btrfs_merge_extent_hook(struct inode *inode,
1523 struct extent_state *new,
1524 struct extent_state *other)
1526 /* not delalloc, ignore it */
1527 if (!(other->state & EXTENT_DELALLOC))
1530 spin_lock(&BTRFS_I(inode)->lock);
1531 BTRFS_I(inode)->outstanding_extents--;
1532 spin_unlock(&BTRFS_I(inode)->lock);
1535 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1536 struct inode *inode)
1538 spin_lock(&root->delalloc_lock);
1539 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1540 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1541 &root->delalloc_inodes);
1542 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1543 &BTRFS_I(inode)->runtime_flags);
1544 root->nr_delalloc_inodes++;
1545 if (root->nr_delalloc_inodes == 1) {
1546 spin_lock(&root->fs_info->delalloc_root_lock);
1547 BUG_ON(!list_empty(&root->delalloc_root));
1548 list_add_tail(&root->delalloc_root,
1549 &root->fs_info->delalloc_roots);
1550 spin_unlock(&root->fs_info->delalloc_root_lock);
1553 spin_unlock(&root->delalloc_lock);
1556 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1557 struct inode *inode)
1559 spin_lock(&root->delalloc_lock);
1560 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1561 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1562 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1563 &BTRFS_I(inode)->runtime_flags);
1564 root->nr_delalloc_inodes--;
1565 if (!root->nr_delalloc_inodes) {
1566 spin_lock(&root->fs_info->delalloc_root_lock);
1567 BUG_ON(list_empty(&root->delalloc_root));
1568 list_del_init(&root->delalloc_root);
1569 spin_unlock(&root->fs_info->delalloc_root_lock);
1572 spin_unlock(&root->delalloc_lock);
1576 * extent_io.c set_bit_hook, used to track delayed allocation
1577 * bytes in this file, and to maintain the list of inodes that
1578 * have pending delalloc work to be done.
1580 static void btrfs_set_bit_hook(struct inode *inode,
1581 struct extent_state *state, unsigned long *bits)
1585 * set_bit and clear bit hooks normally require _irqsave/restore
1586 * but in this case, we are only testing for the DELALLOC
1587 * bit, which is only set or cleared with irqs on
1589 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1590 struct btrfs_root *root = BTRFS_I(inode)->root;
1591 u64 len = state->end + 1 - state->start;
1592 bool do_list = !btrfs_is_free_space_inode(inode);
1594 if (*bits & EXTENT_FIRST_DELALLOC) {
1595 *bits &= ~EXTENT_FIRST_DELALLOC;
1597 spin_lock(&BTRFS_I(inode)->lock);
1598 BTRFS_I(inode)->outstanding_extents++;
1599 spin_unlock(&BTRFS_I(inode)->lock);
1602 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1603 root->fs_info->delalloc_batch);
1604 spin_lock(&BTRFS_I(inode)->lock);
1605 BTRFS_I(inode)->delalloc_bytes += len;
1606 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1607 &BTRFS_I(inode)->runtime_flags))
1608 btrfs_add_delalloc_inodes(root, inode);
1609 spin_unlock(&BTRFS_I(inode)->lock);
1614 * extent_io.c clear_bit_hook, see set_bit_hook for why
1616 static void btrfs_clear_bit_hook(struct inode *inode,
1617 struct extent_state *state,
1618 unsigned long *bits)
1621 * set_bit and clear bit hooks normally require _irqsave/restore
1622 * but in this case, we are only testing for the DELALLOC
1623 * bit, which is only set or cleared with irqs on
1625 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1626 struct btrfs_root *root = BTRFS_I(inode)->root;
1627 u64 len = state->end + 1 - state->start;
1628 bool do_list = !btrfs_is_free_space_inode(inode);
1630 if (*bits & EXTENT_FIRST_DELALLOC) {
1631 *bits &= ~EXTENT_FIRST_DELALLOC;
1632 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1633 spin_lock(&BTRFS_I(inode)->lock);
1634 BTRFS_I(inode)->outstanding_extents--;
1635 spin_unlock(&BTRFS_I(inode)->lock);
1638 if (*bits & EXTENT_DO_ACCOUNTING)
1639 btrfs_delalloc_release_metadata(inode, len);
1641 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1643 btrfs_free_reserved_data_space(inode, len);
1645 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1646 root->fs_info->delalloc_batch);
1647 spin_lock(&BTRFS_I(inode)->lock);
1648 BTRFS_I(inode)->delalloc_bytes -= len;
1649 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1650 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1651 &BTRFS_I(inode)->runtime_flags))
1652 btrfs_del_delalloc_inode(root, inode);
1653 spin_unlock(&BTRFS_I(inode)->lock);
1658 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1659 * we don't create bios that span stripes or chunks
1661 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1662 size_t size, struct bio *bio,
1663 unsigned long bio_flags)
1665 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1666 u64 logical = (u64)bio->bi_sector << 9;
1671 if (bio_flags & EXTENT_BIO_COMPRESSED)
1674 length = bio->bi_size;
1675 map_length = length;
1676 ret = btrfs_map_block(root->fs_info, rw, logical,
1677 &map_length, NULL, 0);
1678 /* Will always return 0 with map_multi == NULL */
1680 if (map_length < length + size)
1686 * in order to insert checksums into the metadata in large chunks,
1687 * we wait until bio submission time. All the pages in the bio are
1688 * checksummed and sums are attached onto the ordered extent record.
1690 * At IO completion time the cums attached on the ordered extent record
1691 * are inserted into the btree
1693 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1694 struct bio *bio, int mirror_num,
1695 unsigned long bio_flags,
1698 struct btrfs_root *root = BTRFS_I(inode)->root;
1701 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1702 BUG_ON(ret); /* -ENOMEM */
1707 * in order to insert checksums into the metadata in large chunks,
1708 * we wait until bio submission time. All the pages in the bio are
1709 * checksummed and sums are attached onto the ordered extent record.
1711 * At IO completion time the cums attached on the ordered extent record
1712 * are inserted into the btree
1714 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1715 int mirror_num, unsigned long bio_flags,
1718 struct btrfs_root *root = BTRFS_I(inode)->root;
1721 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1723 bio_endio(bio, ret);
1728 * extent_io.c submission hook. This does the right thing for csum calculation
1729 * on write, or reading the csums from the tree before a read
1731 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1732 int mirror_num, unsigned long bio_flags,
1735 struct btrfs_root *root = BTRFS_I(inode)->root;
1739 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1741 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1743 if (btrfs_is_free_space_inode(inode))
1746 if (!(rw & REQ_WRITE)) {
1747 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1751 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1752 ret = btrfs_submit_compressed_read(inode, bio,
1756 } else if (!skip_sum) {
1757 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1762 } else if (async && !skip_sum) {
1763 /* csum items have already been cloned */
1764 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1766 /* we're doing a write, do the async checksumming */
1767 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1768 inode, rw, bio, mirror_num,
1769 bio_flags, bio_offset,
1770 __btrfs_submit_bio_start,
1771 __btrfs_submit_bio_done);
1773 } else if (!skip_sum) {
1774 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1780 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1784 bio_endio(bio, ret);
1789 * given a list of ordered sums record them in the inode. This happens
1790 * at IO completion time based on sums calculated at bio submission time.
1792 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1793 struct inode *inode, u64 file_offset,
1794 struct list_head *list)
1796 struct btrfs_ordered_sum *sum;
1798 list_for_each_entry(sum, list, list) {
1799 trans->adding_csums = 1;
1800 btrfs_csum_file_blocks(trans,
1801 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1802 trans->adding_csums = 0;
1807 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1808 struct extent_state **cached_state)
1810 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1811 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1812 cached_state, GFP_NOFS);
1815 /* see btrfs_writepage_start_hook for details on why this is required */
1816 struct btrfs_writepage_fixup {
1818 struct btrfs_work work;
1821 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1823 struct btrfs_writepage_fixup *fixup;
1824 struct btrfs_ordered_extent *ordered;
1825 struct extent_state *cached_state = NULL;
1827 struct inode *inode;
1832 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1836 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1837 ClearPageChecked(page);
1841 inode = page->mapping->host;
1842 page_start = page_offset(page);
1843 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1845 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1848 /* already ordered? We're done */
1849 if (PagePrivate2(page))
1852 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1854 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1855 page_end, &cached_state, GFP_NOFS);
1857 btrfs_start_ordered_extent(inode, ordered, 1);
1858 btrfs_put_ordered_extent(ordered);
1862 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1864 mapping_set_error(page->mapping, ret);
1865 end_extent_writepage(page, ret, page_start, page_end);
1866 ClearPageChecked(page);
1870 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1871 ClearPageChecked(page);
1872 set_page_dirty(page);
1874 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1875 &cached_state, GFP_NOFS);
1878 page_cache_release(page);
1883 * There are a few paths in the higher layers of the kernel that directly
1884 * set the page dirty bit without asking the filesystem if it is a
1885 * good idea. This causes problems because we want to make sure COW
1886 * properly happens and the data=ordered rules are followed.
1888 * In our case any range that doesn't have the ORDERED bit set
1889 * hasn't been properly setup for IO. We kick off an async process
1890 * to fix it up. The async helper will wait for ordered extents, set
1891 * the delalloc bit and make it safe to write the page.
1893 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1895 struct inode *inode = page->mapping->host;
1896 struct btrfs_writepage_fixup *fixup;
1897 struct btrfs_root *root = BTRFS_I(inode)->root;
1899 /* this page is properly in the ordered list */
1900 if (TestClearPagePrivate2(page))
1903 if (PageChecked(page))
1906 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1910 SetPageChecked(page);
1911 page_cache_get(page);
1912 fixup->work.func = btrfs_writepage_fixup_worker;
1914 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1918 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1919 struct inode *inode, u64 file_pos,
1920 u64 disk_bytenr, u64 disk_num_bytes,
1921 u64 num_bytes, u64 ram_bytes,
1922 u8 compression, u8 encryption,
1923 u16 other_encoding, int extent_type)
1925 struct btrfs_root *root = BTRFS_I(inode)->root;
1926 struct btrfs_file_extent_item *fi;
1927 struct btrfs_path *path;
1928 struct extent_buffer *leaf;
1929 struct btrfs_key ins;
1932 path = btrfs_alloc_path();
1936 path->leave_spinning = 1;
1939 * we may be replacing one extent in the tree with another.
1940 * The new extent is pinned in the extent map, and we don't want
1941 * to drop it from the cache until it is completely in the btree.
1943 * So, tell btrfs_drop_extents to leave this extent in the cache.
1944 * the caller is expected to unpin it and allow it to be merged
1947 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1948 file_pos + num_bytes, 0);
1952 ins.objectid = btrfs_ino(inode);
1953 ins.offset = file_pos;
1954 ins.type = BTRFS_EXTENT_DATA_KEY;
1955 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1958 leaf = path->nodes[0];
1959 fi = btrfs_item_ptr(leaf, path->slots[0],
1960 struct btrfs_file_extent_item);
1961 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1962 btrfs_set_file_extent_type(leaf, fi, extent_type);
1963 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1964 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1965 btrfs_set_file_extent_offset(leaf, fi, 0);
1966 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1967 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1968 btrfs_set_file_extent_compression(leaf, fi, compression);
1969 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1970 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1972 btrfs_mark_buffer_dirty(leaf);
1973 btrfs_release_path(path);
1975 inode_add_bytes(inode, num_bytes);
1977 ins.objectid = disk_bytenr;
1978 ins.offset = disk_num_bytes;
1979 ins.type = BTRFS_EXTENT_ITEM_KEY;
1980 ret = btrfs_alloc_reserved_file_extent(trans, root,
1981 root->root_key.objectid,
1982 btrfs_ino(inode), file_pos, &ins);
1984 btrfs_free_path(path);
1989 /* snapshot-aware defrag */
1990 struct sa_defrag_extent_backref {
1991 struct rb_node node;
1992 struct old_sa_defrag_extent *old;
2001 struct old_sa_defrag_extent {
2002 struct list_head list;
2003 struct new_sa_defrag_extent *new;
2012 struct new_sa_defrag_extent {
2013 struct rb_root root;
2014 struct list_head head;
2015 struct btrfs_path *path;
2016 struct inode *inode;
2024 static int backref_comp(struct sa_defrag_extent_backref *b1,
2025 struct sa_defrag_extent_backref *b2)
2027 if (b1->root_id < b2->root_id)
2029 else if (b1->root_id > b2->root_id)
2032 if (b1->inum < b2->inum)
2034 else if (b1->inum > b2->inum)
2037 if (b1->file_pos < b2->file_pos)
2039 else if (b1->file_pos > b2->file_pos)
2043 * [------------------------------] ===> (a range of space)
2044 * |<--->| |<---->| =============> (fs/file tree A)
2045 * |<---------------------------->| ===> (fs/file tree B)
2047 * A range of space can refer to two file extents in one tree while
2048 * refer to only one file extent in another tree.
2050 * So we may process a disk offset more than one time(two extents in A)
2051 * and locate at the same extent(one extent in B), then insert two same
2052 * backrefs(both refer to the extent in B).
2057 static void backref_insert(struct rb_root *root,
2058 struct sa_defrag_extent_backref *backref)
2060 struct rb_node **p = &root->rb_node;
2061 struct rb_node *parent = NULL;
2062 struct sa_defrag_extent_backref *entry;
2067 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2069 ret = backref_comp(backref, entry);
2073 p = &(*p)->rb_right;
2076 rb_link_node(&backref->node, parent, p);
2077 rb_insert_color(&backref->node, root);
2081 * Note the backref might has changed, and in this case we just return 0.
2083 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2086 struct btrfs_file_extent_item *extent;
2087 struct btrfs_fs_info *fs_info;
2088 struct old_sa_defrag_extent *old = ctx;
2089 struct new_sa_defrag_extent *new = old->new;
2090 struct btrfs_path *path = new->path;
2091 struct btrfs_key key;
2092 struct btrfs_root *root;
2093 struct sa_defrag_extent_backref *backref;
2094 struct extent_buffer *leaf;
2095 struct inode *inode = new->inode;
2101 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2102 inum == btrfs_ino(inode))
2105 key.objectid = root_id;
2106 key.type = BTRFS_ROOT_ITEM_KEY;
2107 key.offset = (u64)-1;
2109 fs_info = BTRFS_I(inode)->root->fs_info;
2110 root = btrfs_read_fs_root_no_name(fs_info, &key);
2112 if (PTR_ERR(root) == -ENOENT)
2115 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2116 inum, offset, root_id);
2117 return PTR_ERR(root);
2120 key.objectid = inum;
2121 key.type = BTRFS_EXTENT_DATA_KEY;
2122 if (offset > (u64)-1 << 32)
2125 key.offset = offset;
2127 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2136 leaf = path->nodes[0];
2137 slot = path->slots[0];
2139 if (slot >= btrfs_header_nritems(leaf)) {
2140 ret = btrfs_next_leaf(root, path);
2143 } else if (ret > 0) {
2152 btrfs_item_key_to_cpu(leaf, &key, slot);
2154 if (key.objectid > inum)
2157 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2160 extent = btrfs_item_ptr(leaf, slot,
2161 struct btrfs_file_extent_item);
2163 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2166 extent_offset = btrfs_file_extent_offset(leaf, extent);
2167 if (key.offset - extent_offset != offset)
2170 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2171 if (extent_offset >= old->extent_offset + old->offset +
2172 old->len || extent_offset + num_bytes <=
2173 old->extent_offset + old->offset)
2179 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2185 backref->root_id = root_id;
2186 backref->inum = inum;
2187 backref->file_pos = offset + extent_offset;
2188 backref->num_bytes = num_bytes;
2189 backref->extent_offset = extent_offset;
2190 backref->generation = btrfs_file_extent_generation(leaf, extent);
2192 backref_insert(&new->root, backref);
2195 btrfs_release_path(path);
2200 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2201 struct new_sa_defrag_extent *new)
2203 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2204 struct old_sa_defrag_extent *old, *tmp;
2209 list_for_each_entry_safe(old, tmp, &new->head, list) {
2210 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2211 path, record_one_backref,
2213 BUG_ON(ret < 0 && ret != -ENOENT);
2215 /* no backref to be processed for this extent */
2217 list_del(&old->list);
2222 if (list_empty(&new->head))
2228 static int relink_is_mergable(struct extent_buffer *leaf,
2229 struct btrfs_file_extent_item *fi,
2232 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2235 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2238 if (btrfs_file_extent_compression(leaf, fi) ||
2239 btrfs_file_extent_encryption(leaf, fi) ||
2240 btrfs_file_extent_other_encoding(leaf, fi))
2247 * Note the backref might has changed, and in this case we just return 0.
2249 static noinline int relink_extent_backref(struct btrfs_path *path,
2250 struct sa_defrag_extent_backref *prev,
2251 struct sa_defrag_extent_backref *backref)
2253 struct btrfs_file_extent_item *extent;
2254 struct btrfs_file_extent_item *item;
2255 struct btrfs_ordered_extent *ordered;
2256 struct btrfs_trans_handle *trans;
2257 struct btrfs_fs_info *fs_info;
2258 struct btrfs_root *root;
2259 struct btrfs_key key;
2260 struct extent_buffer *leaf;
2261 struct old_sa_defrag_extent *old = backref->old;
2262 struct new_sa_defrag_extent *new = old->new;
2263 struct inode *src_inode = new->inode;
2264 struct inode *inode;
2265 struct extent_state *cached = NULL;
2274 if (prev && prev->root_id == backref->root_id &&
2275 prev->inum == backref->inum &&
2276 prev->file_pos + prev->num_bytes == backref->file_pos)
2279 /* step 1: get root */
2280 key.objectid = backref->root_id;
2281 key.type = BTRFS_ROOT_ITEM_KEY;
2282 key.offset = (u64)-1;
2284 fs_info = BTRFS_I(src_inode)->root->fs_info;
2285 index = srcu_read_lock(&fs_info->subvol_srcu);
2287 root = btrfs_read_fs_root_no_name(fs_info, &key);
2289 srcu_read_unlock(&fs_info->subvol_srcu, index);
2290 if (PTR_ERR(root) == -ENOENT)
2292 return PTR_ERR(root);
2295 /* step 2: get inode */
2296 key.objectid = backref->inum;
2297 key.type = BTRFS_INODE_ITEM_KEY;
2300 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2301 if (IS_ERR(inode)) {
2302 srcu_read_unlock(&fs_info->subvol_srcu, index);
2306 srcu_read_unlock(&fs_info->subvol_srcu, index);
2308 /* step 3: relink backref */
2309 lock_start = backref->file_pos;
2310 lock_end = backref->file_pos + backref->num_bytes - 1;
2311 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2314 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2316 btrfs_put_ordered_extent(ordered);
2320 trans = btrfs_join_transaction(root);
2321 if (IS_ERR(trans)) {
2322 ret = PTR_ERR(trans);
2326 key.objectid = backref->inum;
2327 key.type = BTRFS_EXTENT_DATA_KEY;
2328 key.offset = backref->file_pos;
2330 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2333 } else if (ret > 0) {
2338 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2339 struct btrfs_file_extent_item);
2341 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2342 backref->generation)
2345 btrfs_release_path(path);
2347 start = backref->file_pos;
2348 if (backref->extent_offset < old->extent_offset + old->offset)
2349 start += old->extent_offset + old->offset -
2350 backref->extent_offset;
2352 len = min(backref->extent_offset + backref->num_bytes,
2353 old->extent_offset + old->offset + old->len);
2354 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2356 ret = btrfs_drop_extents(trans, root, inode, start,
2361 key.objectid = btrfs_ino(inode);
2362 key.type = BTRFS_EXTENT_DATA_KEY;
2365 path->leave_spinning = 1;
2367 struct btrfs_file_extent_item *fi;
2369 struct btrfs_key found_key;
2371 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2376 leaf = path->nodes[0];
2377 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2379 fi = btrfs_item_ptr(leaf, path->slots[0],
2380 struct btrfs_file_extent_item);
2381 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2383 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2384 extent_len + found_key.offset == start) {
2385 btrfs_set_file_extent_num_bytes(leaf, fi,
2387 btrfs_mark_buffer_dirty(leaf);
2388 inode_add_bytes(inode, len);
2394 btrfs_release_path(path);
2399 ret = btrfs_insert_empty_item(trans, root, path, &key,
2402 btrfs_abort_transaction(trans, root, ret);
2406 leaf = path->nodes[0];
2407 item = btrfs_item_ptr(leaf, path->slots[0],
2408 struct btrfs_file_extent_item);
2409 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2410 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2411 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2412 btrfs_set_file_extent_num_bytes(leaf, item, len);
2413 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2414 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2415 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2416 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2417 btrfs_set_file_extent_encryption(leaf, item, 0);
2418 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2420 btrfs_mark_buffer_dirty(leaf);
2421 inode_add_bytes(inode, len);
2422 btrfs_release_path(path);
2424 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2426 backref->root_id, backref->inum,
2427 new->file_pos, 0); /* start - extent_offset */
2429 btrfs_abort_transaction(trans, root, ret);
2435 btrfs_release_path(path);
2436 path->leave_spinning = 0;
2437 btrfs_end_transaction(trans, root);
2439 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2445 static void relink_file_extents(struct new_sa_defrag_extent *new)
2447 struct btrfs_path *path;
2448 struct old_sa_defrag_extent *old, *tmp;
2449 struct sa_defrag_extent_backref *backref;
2450 struct sa_defrag_extent_backref *prev = NULL;
2451 struct inode *inode;
2452 struct btrfs_root *root;
2453 struct rb_node *node;
2457 root = BTRFS_I(inode)->root;
2459 path = btrfs_alloc_path();
2463 if (!record_extent_backrefs(path, new)) {
2464 btrfs_free_path(path);
2467 btrfs_release_path(path);
2470 node = rb_first(&new->root);
2473 rb_erase(node, &new->root);
2475 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2477 ret = relink_extent_backref(path, prev, backref);
2490 btrfs_free_path(path);
2492 list_for_each_entry_safe(old, tmp, &new->head, list) {
2493 list_del(&old->list);
2497 atomic_dec(&root->fs_info->defrag_running);
2498 wake_up(&root->fs_info->transaction_wait);
2503 static struct new_sa_defrag_extent *
2504 record_old_file_extents(struct inode *inode,
2505 struct btrfs_ordered_extent *ordered)
2507 struct btrfs_root *root = BTRFS_I(inode)->root;
2508 struct btrfs_path *path;
2509 struct btrfs_key key;
2510 struct old_sa_defrag_extent *old, *tmp;
2511 struct new_sa_defrag_extent *new;
2514 new = kmalloc(sizeof(*new), GFP_NOFS);
2519 new->file_pos = ordered->file_offset;
2520 new->len = ordered->len;
2521 new->bytenr = ordered->start;
2522 new->disk_len = ordered->disk_len;
2523 new->compress_type = ordered->compress_type;
2524 new->root = RB_ROOT;
2525 INIT_LIST_HEAD(&new->head);
2527 path = btrfs_alloc_path();
2531 key.objectid = btrfs_ino(inode);
2532 key.type = BTRFS_EXTENT_DATA_KEY;
2533 key.offset = new->file_pos;
2535 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2538 if (ret > 0 && path->slots[0] > 0)
2541 /* find out all the old extents for the file range */
2543 struct btrfs_file_extent_item *extent;
2544 struct extent_buffer *l;
2553 slot = path->slots[0];
2555 if (slot >= btrfs_header_nritems(l)) {
2556 ret = btrfs_next_leaf(root, path);
2564 btrfs_item_key_to_cpu(l, &key, slot);
2566 if (key.objectid != btrfs_ino(inode))
2568 if (key.type != BTRFS_EXTENT_DATA_KEY)
2570 if (key.offset >= new->file_pos + new->len)
2573 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2575 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2576 if (key.offset + num_bytes < new->file_pos)
2579 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2583 extent_offset = btrfs_file_extent_offset(l, extent);
2585 old = kmalloc(sizeof(*old), GFP_NOFS);
2589 offset = max(new->file_pos, key.offset);
2590 end = min(new->file_pos + new->len, key.offset + num_bytes);
2592 old->bytenr = disk_bytenr;
2593 old->extent_offset = extent_offset;
2594 old->offset = offset - key.offset;
2595 old->len = end - offset;
2598 list_add_tail(&old->list, &new->head);
2604 btrfs_free_path(path);
2605 atomic_inc(&root->fs_info->defrag_running);
2610 list_for_each_entry_safe(old, tmp, &new->head, list) {
2611 list_del(&old->list);
2615 btrfs_free_path(path);
2622 * helper function for btrfs_finish_ordered_io, this
2623 * just reads in some of the csum leaves to prime them into ram
2624 * before we start the transaction. It limits the amount of btree
2625 * reads required while inside the transaction.
2627 /* as ordered data IO finishes, this gets called so we can finish
2628 * an ordered extent if the range of bytes in the file it covers are
2631 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2633 struct inode *inode = ordered_extent->inode;
2634 struct btrfs_root *root = BTRFS_I(inode)->root;
2635 struct btrfs_trans_handle *trans = NULL;
2636 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2637 struct extent_state *cached_state = NULL;
2638 struct new_sa_defrag_extent *new = NULL;
2639 int compress_type = 0;
2643 nolock = btrfs_is_free_space_inode(inode);
2645 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2650 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2651 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2652 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2654 trans = btrfs_join_transaction_nolock(root);
2656 trans = btrfs_join_transaction(root);
2657 if (IS_ERR(trans)) {
2658 ret = PTR_ERR(trans);
2662 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2663 ret = btrfs_update_inode_fallback(trans, root, inode);
2664 if (ret) /* -ENOMEM or corruption */
2665 btrfs_abort_transaction(trans, root, ret);
2669 lock_extent_bits(io_tree, ordered_extent->file_offset,
2670 ordered_extent->file_offset + ordered_extent->len - 1,
2673 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2674 ordered_extent->file_offset + ordered_extent->len - 1,
2675 EXTENT_DEFRAG, 1, cached_state);
2677 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2678 if (last_snapshot >= BTRFS_I(inode)->generation)
2679 /* the inode is shared */
2680 new = record_old_file_extents(inode, ordered_extent);
2682 clear_extent_bit(io_tree, ordered_extent->file_offset,
2683 ordered_extent->file_offset + ordered_extent->len - 1,
2684 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2688 trans = btrfs_join_transaction_nolock(root);
2690 trans = btrfs_join_transaction(root);
2691 if (IS_ERR(trans)) {
2692 ret = PTR_ERR(trans);
2696 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2698 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2699 compress_type = ordered_extent->compress_type;
2700 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2701 BUG_ON(compress_type);
2702 ret = btrfs_mark_extent_written(trans, inode,
2703 ordered_extent->file_offset,
2704 ordered_extent->file_offset +
2705 ordered_extent->len);
2707 BUG_ON(root == root->fs_info->tree_root);
2708 ret = insert_reserved_file_extent(trans, inode,
2709 ordered_extent->file_offset,
2710 ordered_extent->start,
2711 ordered_extent->disk_len,
2712 ordered_extent->len,
2713 ordered_extent->len,
2714 compress_type, 0, 0,
2715 BTRFS_FILE_EXTENT_REG);
2717 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2718 ordered_extent->file_offset, ordered_extent->len,
2721 btrfs_abort_transaction(trans, root, ret);
2725 add_pending_csums(trans, inode, ordered_extent->file_offset,
2726 &ordered_extent->list);
2728 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2729 ret = btrfs_update_inode_fallback(trans, root, inode);
2730 if (ret) { /* -ENOMEM or corruption */
2731 btrfs_abort_transaction(trans, root, ret);
2736 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2737 ordered_extent->file_offset +
2738 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2740 if (root != root->fs_info->tree_root)
2741 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2743 btrfs_end_transaction(trans, root);
2746 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2747 ordered_extent->file_offset +
2748 ordered_extent->len - 1, NULL, GFP_NOFS);
2751 * If the ordered extent had an IOERR or something else went
2752 * wrong we need to return the space for this ordered extent
2753 * back to the allocator.
2755 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2756 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2757 btrfs_free_reserved_extent(root, ordered_extent->start,
2758 ordered_extent->disk_len);
2763 * This needs to be done to make sure anybody waiting knows we are done
2764 * updating everything for this ordered extent.
2766 btrfs_remove_ordered_extent(inode, ordered_extent);
2768 /* for snapshot-aware defrag */
2770 relink_file_extents(new);
2773 btrfs_put_ordered_extent(ordered_extent);
2774 /* once for the tree */
2775 btrfs_put_ordered_extent(ordered_extent);
2780 static void finish_ordered_fn(struct btrfs_work *work)
2782 struct btrfs_ordered_extent *ordered_extent;
2783 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2784 btrfs_finish_ordered_io(ordered_extent);
2787 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2788 struct extent_state *state, int uptodate)
2790 struct inode *inode = page->mapping->host;
2791 struct btrfs_root *root = BTRFS_I(inode)->root;
2792 struct btrfs_ordered_extent *ordered_extent = NULL;
2793 struct btrfs_workers *workers;
2795 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2797 ClearPagePrivate2(page);
2798 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2799 end - start + 1, uptodate))
2802 ordered_extent->work.func = finish_ordered_fn;
2803 ordered_extent->work.flags = 0;
2805 if (btrfs_is_free_space_inode(inode))
2806 workers = &root->fs_info->endio_freespace_worker;
2808 workers = &root->fs_info->endio_write_workers;
2809 btrfs_queue_worker(workers, &ordered_extent->work);
2815 * when reads are done, we need to check csums to verify the data is correct
2816 * if there's a match, we allow the bio to finish. If not, the code in
2817 * extent_io.c will try to find good copies for us.
2819 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2820 struct extent_state *state, int mirror)
2822 size_t offset = start - page_offset(page);
2823 struct inode *inode = page->mapping->host;
2824 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2826 u64 private = ~(u32)0;
2828 struct btrfs_root *root = BTRFS_I(inode)->root;
2830 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2831 DEFAULT_RATELIMIT_BURST);
2833 if (PageChecked(page)) {
2834 ClearPageChecked(page);
2838 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2841 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2842 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2843 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2848 if (state && state->start == start) {
2849 private = state->private;
2852 ret = get_state_private(io_tree, start, &private);
2854 kaddr = kmap_atomic(page);
2858 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2859 btrfs_csum_final(csum, (char *)&csum);
2860 if (csum != private)
2863 kunmap_atomic(kaddr);
2868 if (__ratelimit(&_rs))
2869 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u private %llu",
2870 (unsigned long long)btrfs_ino(page->mapping->host),
2871 (unsigned long long)start, csum,
2872 (unsigned long long)private);
2873 memset(kaddr + offset, 1, end - start + 1);
2874 flush_dcache_page(page);
2875 kunmap_atomic(kaddr);
2881 struct delayed_iput {
2882 struct list_head list;
2883 struct inode *inode;
2886 /* JDM: If this is fs-wide, why can't we add a pointer to
2887 * btrfs_inode instead and avoid the allocation? */
2888 void btrfs_add_delayed_iput(struct inode *inode)
2890 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2891 struct delayed_iput *delayed;
2893 if (atomic_add_unless(&inode->i_count, -1, 1))
2896 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2897 delayed->inode = inode;
2899 spin_lock(&fs_info->delayed_iput_lock);
2900 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2901 spin_unlock(&fs_info->delayed_iput_lock);
2904 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2907 struct btrfs_fs_info *fs_info = root->fs_info;
2908 struct delayed_iput *delayed;
2911 spin_lock(&fs_info->delayed_iput_lock);
2912 empty = list_empty(&fs_info->delayed_iputs);
2913 spin_unlock(&fs_info->delayed_iput_lock);
2917 spin_lock(&fs_info->delayed_iput_lock);
2918 list_splice_init(&fs_info->delayed_iputs, &list);
2919 spin_unlock(&fs_info->delayed_iput_lock);
2921 while (!list_empty(&list)) {
2922 delayed = list_entry(list.next, struct delayed_iput, list);
2923 list_del(&delayed->list);
2924 iput(delayed->inode);
2930 * This is called in transaction commit time. If there are no orphan
2931 * files in the subvolume, it removes orphan item and frees block_rsv
2934 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2935 struct btrfs_root *root)
2937 struct btrfs_block_rsv *block_rsv;
2940 if (atomic_read(&root->orphan_inodes) ||
2941 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2944 spin_lock(&root->orphan_lock);
2945 if (atomic_read(&root->orphan_inodes)) {
2946 spin_unlock(&root->orphan_lock);
2950 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2951 spin_unlock(&root->orphan_lock);
2955 block_rsv = root->orphan_block_rsv;
2956 root->orphan_block_rsv = NULL;
2957 spin_unlock(&root->orphan_lock);
2959 if (root->orphan_item_inserted &&
2960 btrfs_root_refs(&root->root_item) > 0) {
2961 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2962 root->root_key.objectid);
2964 root->orphan_item_inserted = 0;
2968 WARN_ON(block_rsv->size > 0);
2969 btrfs_free_block_rsv(root, block_rsv);
2974 * This creates an orphan entry for the given inode in case something goes
2975 * wrong in the middle of an unlink/truncate.
2977 * NOTE: caller of this function should reserve 5 units of metadata for
2980 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2982 struct btrfs_root *root = BTRFS_I(inode)->root;
2983 struct btrfs_block_rsv *block_rsv = NULL;
2988 if (!root->orphan_block_rsv) {
2989 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2994 spin_lock(&root->orphan_lock);
2995 if (!root->orphan_block_rsv) {
2996 root->orphan_block_rsv = block_rsv;
2997 } else if (block_rsv) {
2998 btrfs_free_block_rsv(root, block_rsv);
3002 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3003 &BTRFS_I(inode)->runtime_flags)) {
3006 * For proper ENOSPC handling, we should do orphan
3007 * cleanup when mounting. But this introduces backward
3008 * compatibility issue.
3010 if (!xchg(&root->orphan_item_inserted, 1))
3016 atomic_inc(&root->orphan_inodes);
3019 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3020 &BTRFS_I(inode)->runtime_flags))
3022 spin_unlock(&root->orphan_lock);
3024 /* grab metadata reservation from transaction handle */
3026 ret = btrfs_orphan_reserve_metadata(trans, inode);
3027 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3030 /* insert an orphan item to track this unlinked/truncated file */
3032 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3033 if (ret && ret != -EEXIST) {
3034 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3035 &BTRFS_I(inode)->runtime_flags);
3036 btrfs_abort_transaction(trans, root, ret);
3042 /* insert an orphan item to track subvolume contains orphan files */
3044 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3045 root->root_key.objectid);
3046 if (ret && ret != -EEXIST) {
3047 btrfs_abort_transaction(trans, root, ret);
3055 * We have done the truncate/delete so we can go ahead and remove the orphan
3056 * item for this particular inode.
3058 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3059 struct inode *inode)
3061 struct btrfs_root *root = BTRFS_I(inode)->root;
3062 int delete_item = 0;
3063 int release_rsv = 0;
3066 spin_lock(&root->orphan_lock);
3067 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3068 &BTRFS_I(inode)->runtime_flags))
3071 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3072 &BTRFS_I(inode)->runtime_flags))
3074 spin_unlock(&root->orphan_lock);
3076 if (trans && delete_item) {
3077 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3078 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3082 btrfs_orphan_release_metadata(inode);
3083 atomic_dec(&root->orphan_inodes);
3090 * this cleans up any orphans that may be left on the list from the last use
3093 int btrfs_orphan_cleanup(struct btrfs_root *root)
3095 struct btrfs_path *path;
3096 struct extent_buffer *leaf;
3097 struct btrfs_key key, found_key;
3098 struct btrfs_trans_handle *trans;
3099 struct inode *inode;
3100 u64 last_objectid = 0;
3101 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3103 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3106 path = btrfs_alloc_path();
3113 key.objectid = BTRFS_ORPHAN_OBJECTID;
3114 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3115 key.offset = (u64)-1;
3118 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3123 * if ret == 0 means we found what we were searching for, which
3124 * is weird, but possible, so only screw with path if we didn't
3125 * find the key and see if we have stuff that matches
3129 if (path->slots[0] == 0)
3134 /* pull out the item */
3135 leaf = path->nodes[0];
3136 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3138 /* make sure the item matches what we want */
3139 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3141 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3144 /* release the path since we're done with it */
3145 btrfs_release_path(path);
3148 * this is where we are basically btrfs_lookup, without the
3149 * crossing root thing. we store the inode number in the
3150 * offset of the orphan item.
3153 if (found_key.offset == last_objectid) {
3154 btrfs_err(root->fs_info,
3155 "Error removing orphan entry, stopping orphan cleanup");
3160 last_objectid = found_key.offset;
3162 found_key.objectid = found_key.offset;
3163 found_key.type = BTRFS_INODE_ITEM_KEY;
3164 found_key.offset = 0;
3165 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3166 ret = PTR_RET(inode);
3167 if (ret && ret != -ESTALE)
3170 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3171 struct btrfs_root *dead_root;
3172 struct btrfs_fs_info *fs_info = root->fs_info;
3173 int is_dead_root = 0;
3176 * this is an orphan in the tree root. Currently these
3177 * could come from 2 sources:
3178 * a) a snapshot deletion in progress
3179 * b) a free space cache inode
3180 * We need to distinguish those two, as the snapshot
3181 * orphan must not get deleted.
3182 * find_dead_roots already ran before us, so if this
3183 * is a snapshot deletion, we should find the root
3184 * in the dead_roots list
3186 spin_lock(&fs_info->trans_lock);
3187 list_for_each_entry(dead_root, &fs_info->dead_roots,
3189 if (dead_root->root_key.objectid ==
3190 found_key.objectid) {
3195 spin_unlock(&fs_info->trans_lock);
3197 /* prevent this orphan from being found again */
3198 key.offset = found_key.objectid - 1;
3203 * Inode is already gone but the orphan item is still there,
3204 * kill the orphan item.
3206 if (ret == -ESTALE) {
3207 trans = btrfs_start_transaction(root, 1);
3208 if (IS_ERR(trans)) {
3209 ret = PTR_ERR(trans);
3212 btrfs_debug(root->fs_info, "auto deleting %Lu",
3213 found_key.objectid);
3214 ret = btrfs_del_orphan_item(trans, root,
3215 found_key.objectid);
3216 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3217 btrfs_end_transaction(trans, root);
3222 * add this inode to the orphan list so btrfs_orphan_del does
3223 * the proper thing when we hit it
3225 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3226 &BTRFS_I(inode)->runtime_flags);
3227 atomic_inc(&root->orphan_inodes);
3229 /* if we have links, this was a truncate, lets do that */
3230 if (inode->i_nlink) {
3231 if (!S_ISREG(inode->i_mode)) {
3238 /* 1 for the orphan item deletion. */
3239 trans = btrfs_start_transaction(root, 1);
3240 if (IS_ERR(trans)) {
3242 ret = PTR_ERR(trans);
3245 ret = btrfs_orphan_add(trans, inode);
3246 btrfs_end_transaction(trans, root);
3252 ret = btrfs_truncate(inode);
3254 btrfs_orphan_del(NULL, inode);
3259 /* this will do delete_inode and everything for us */
3264 /* release the path since we're done with it */
3265 btrfs_release_path(path);
3267 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3269 if (root->orphan_block_rsv)
3270 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3273 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3274 trans = btrfs_join_transaction(root);
3276 btrfs_end_transaction(trans, root);
3280 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3282 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3286 btrfs_crit(root->fs_info,
3287 "could not do orphan cleanup %d", ret);
3288 btrfs_free_path(path);
3293 * very simple check to peek ahead in the leaf looking for xattrs. If we
3294 * don't find any xattrs, we know there can't be any acls.
3296 * slot is the slot the inode is in, objectid is the objectid of the inode
3298 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3299 int slot, u64 objectid)
3301 u32 nritems = btrfs_header_nritems(leaf);
3302 struct btrfs_key found_key;
3306 while (slot < nritems) {
3307 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3309 /* we found a different objectid, there must not be acls */
3310 if (found_key.objectid != objectid)
3313 /* we found an xattr, assume we've got an acl */
3314 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
3318 * we found a key greater than an xattr key, there can't
3319 * be any acls later on
3321 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3328 * it goes inode, inode backrefs, xattrs, extents,
3329 * so if there are a ton of hard links to an inode there can
3330 * be a lot of backrefs. Don't waste time searching too hard,
3331 * this is just an optimization
3336 /* we hit the end of the leaf before we found an xattr or
3337 * something larger than an xattr. We have to assume the inode
3344 * read an inode from the btree into the in-memory inode
3346 static void btrfs_read_locked_inode(struct inode *inode)
3348 struct btrfs_path *path;
3349 struct extent_buffer *leaf;
3350 struct btrfs_inode_item *inode_item;
3351 struct btrfs_timespec *tspec;
3352 struct btrfs_root *root = BTRFS_I(inode)->root;
3353 struct btrfs_key location;
3357 bool filled = false;
3359 ret = btrfs_fill_inode(inode, &rdev);
3363 path = btrfs_alloc_path();
3367 path->leave_spinning = 1;
3368 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3370 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3374 leaf = path->nodes[0];
3379 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3380 struct btrfs_inode_item);
3381 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3382 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3383 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3384 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3385 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3387 tspec = btrfs_inode_atime(inode_item);
3388 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3389 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3391 tspec = btrfs_inode_mtime(inode_item);
3392 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3393 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3395 tspec = btrfs_inode_ctime(inode_item);
3396 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3397 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3399 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3400 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3401 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3404 * If we were modified in the current generation and evicted from memory
3405 * and then re-read we need to do a full sync since we don't have any
3406 * idea about which extents were modified before we were evicted from
3409 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3410 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3411 &BTRFS_I(inode)->runtime_flags);
3413 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3414 inode->i_generation = BTRFS_I(inode)->generation;
3416 rdev = btrfs_inode_rdev(leaf, inode_item);
3418 BTRFS_I(inode)->index_cnt = (u64)-1;
3419 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3422 * try to precache a NULL acl entry for files that don't have
3423 * any xattrs or acls
3425 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3428 cache_no_acl(inode);
3430 btrfs_free_path(path);
3432 switch (inode->i_mode & S_IFMT) {
3434 inode->i_mapping->a_ops = &btrfs_aops;
3435 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3436 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3437 inode->i_fop = &btrfs_file_operations;
3438 inode->i_op = &btrfs_file_inode_operations;
3441 inode->i_fop = &btrfs_dir_file_operations;
3442 if (root == root->fs_info->tree_root)
3443 inode->i_op = &btrfs_dir_ro_inode_operations;
3445 inode->i_op = &btrfs_dir_inode_operations;
3448 inode->i_op = &btrfs_symlink_inode_operations;
3449 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3450 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3453 inode->i_op = &btrfs_special_inode_operations;
3454 init_special_inode(inode, inode->i_mode, rdev);
3458 btrfs_update_iflags(inode);
3462 btrfs_free_path(path);
3463 make_bad_inode(inode);
3467 * given a leaf and an inode, copy the inode fields into the leaf
3469 static void fill_inode_item(struct btrfs_trans_handle *trans,
3470 struct extent_buffer *leaf,
3471 struct btrfs_inode_item *item,
3472 struct inode *inode)
3474 struct btrfs_map_token token;
3476 btrfs_init_map_token(&token);
3478 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3479 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3480 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3482 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3483 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3485 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3486 inode->i_atime.tv_sec, &token);
3487 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3488 inode->i_atime.tv_nsec, &token);
3490 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3491 inode->i_mtime.tv_sec, &token);
3492 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3493 inode->i_mtime.tv_nsec, &token);
3495 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3496 inode->i_ctime.tv_sec, &token);
3497 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3498 inode->i_ctime.tv_nsec, &token);
3500 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3502 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3504 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3505 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3506 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3507 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3508 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3512 * copy everything in the in-memory inode into the btree.
3514 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3515 struct btrfs_root *root, struct inode *inode)
3517 struct btrfs_inode_item *inode_item;
3518 struct btrfs_path *path;
3519 struct extent_buffer *leaf;
3522 path = btrfs_alloc_path();
3526 path->leave_spinning = 1;
3527 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3535 btrfs_unlock_up_safe(path, 1);
3536 leaf = path->nodes[0];
3537 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3538 struct btrfs_inode_item);
3540 fill_inode_item(trans, leaf, inode_item, inode);
3541 btrfs_mark_buffer_dirty(leaf);
3542 btrfs_set_inode_last_trans(trans, inode);
3545 btrfs_free_path(path);
3550 * copy everything in the in-memory inode into the btree.
3552 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3553 struct btrfs_root *root, struct inode *inode)
3558 * If the inode is a free space inode, we can deadlock during commit
3559 * if we put it into the delayed code.
3561 * The data relocation inode should also be directly updated
3564 if (!btrfs_is_free_space_inode(inode)
3565 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3566 btrfs_update_root_times(trans, root);
3568 ret = btrfs_delayed_update_inode(trans, root, inode);
3570 btrfs_set_inode_last_trans(trans, inode);
3574 return btrfs_update_inode_item(trans, root, inode);
3577 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3578 struct btrfs_root *root,
3579 struct inode *inode)
3583 ret = btrfs_update_inode(trans, root, inode);
3585 return btrfs_update_inode_item(trans, root, inode);
3590 * unlink helper that gets used here in inode.c and in the tree logging
3591 * recovery code. It remove a link in a directory with a given name, and
3592 * also drops the back refs in the inode to the directory
3594 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3595 struct btrfs_root *root,
3596 struct inode *dir, struct inode *inode,
3597 const char *name, int name_len)
3599 struct btrfs_path *path;
3601 struct extent_buffer *leaf;
3602 struct btrfs_dir_item *di;
3603 struct btrfs_key key;
3605 u64 ino = btrfs_ino(inode);
3606 u64 dir_ino = btrfs_ino(dir);
3608 path = btrfs_alloc_path();
3614 path->leave_spinning = 1;
3615 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3616 name, name_len, -1);
3625 leaf = path->nodes[0];
3626 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3627 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3630 btrfs_release_path(path);
3632 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3635 btrfs_info(root->fs_info,
3636 "failed to delete reference to %.*s, inode %llu parent %llu",
3638 (unsigned long long)ino, (unsigned long long)dir_ino);
3639 btrfs_abort_transaction(trans, root, ret);
3643 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3645 btrfs_abort_transaction(trans, root, ret);
3649 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3651 if (ret != 0 && ret != -ENOENT) {
3652 btrfs_abort_transaction(trans, root, ret);
3656 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3661 btrfs_abort_transaction(trans, root, ret);
3663 btrfs_free_path(path);
3667 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3668 inode_inc_iversion(inode);
3669 inode_inc_iversion(dir);
3670 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3671 ret = btrfs_update_inode(trans, root, dir);
3676 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3677 struct btrfs_root *root,
3678 struct inode *dir, struct inode *inode,
3679 const char *name, int name_len)
3682 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3684 btrfs_drop_nlink(inode);
3685 ret = btrfs_update_inode(trans, root, inode);
3691 * helper to start transaction for unlink and rmdir.
3693 * unlink and rmdir are special in btrfs, they do not always free space, so
3694 * if we cannot make our reservations the normal way try and see if there is
3695 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3696 * allow the unlink to occur.
3698 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3700 struct btrfs_trans_handle *trans;
3701 struct btrfs_root *root = BTRFS_I(dir)->root;
3705 * 1 for the possible orphan item
3706 * 1 for the dir item
3707 * 1 for the dir index
3708 * 1 for the inode ref
3711 trans = btrfs_start_transaction(root, 5);
3712 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3715 if (PTR_ERR(trans) == -ENOSPC) {
3716 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3718 trans = btrfs_start_transaction(root, 0);
3721 ret = btrfs_cond_migrate_bytes(root->fs_info,
3722 &root->fs_info->trans_block_rsv,
3725 btrfs_end_transaction(trans, root);
3726 return ERR_PTR(ret);
3728 trans->block_rsv = &root->fs_info->trans_block_rsv;
3729 trans->bytes_reserved = num_bytes;
3734 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3736 struct btrfs_root *root = BTRFS_I(dir)->root;
3737 struct btrfs_trans_handle *trans;
3738 struct inode *inode = dentry->d_inode;
3741 trans = __unlink_start_trans(dir);
3743 return PTR_ERR(trans);
3745 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3747 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3748 dentry->d_name.name, dentry->d_name.len);
3752 if (inode->i_nlink == 0) {
3753 ret = btrfs_orphan_add(trans, inode);
3759 btrfs_end_transaction(trans, root);
3760 btrfs_btree_balance_dirty(root);
3764 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3765 struct btrfs_root *root,
3766 struct inode *dir, u64 objectid,
3767 const char *name, int name_len)
3769 struct btrfs_path *path;
3770 struct extent_buffer *leaf;
3771 struct btrfs_dir_item *di;
3772 struct btrfs_key key;
3775 u64 dir_ino = btrfs_ino(dir);
3777 path = btrfs_alloc_path();
3781 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3782 name, name_len, -1);
3783 if (IS_ERR_OR_NULL(di)) {
3791 leaf = path->nodes[0];
3792 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3793 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3794 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3796 btrfs_abort_transaction(trans, root, ret);
3799 btrfs_release_path(path);
3801 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3802 objectid, root->root_key.objectid,
3803 dir_ino, &index, name, name_len);
3805 if (ret != -ENOENT) {
3806 btrfs_abort_transaction(trans, root, ret);
3809 di = btrfs_search_dir_index_item(root, path, dir_ino,
3811 if (IS_ERR_OR_NULL(di)) {
3816 btrfs_abort_transaction(trans, root, ret);
3820 leaf = path->nodes[0];
3821 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3822 btrfs_release_path(path);
3825 btrfs_release_path(path);
3827 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3829 btrfs_abort_transaction(trans, root, ret);
3833 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3834 inode_inc_iversion(dir);
3835 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3836 ret = btrfs_update_inode_fallback(trans, root, dir);
3838 btrfs_abort_transaction(trans, root, ret);
3840 btrfs_free_path(path);
3844 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3846 struct inode *inode = dentry->d_inode;
3848 struct btrfs_root *root = BTRFS_I(dir)->root;
3849 struct btrfs_trans_handle *trans;
3851 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3853 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3856 trans = __unlink_start_trans(dir);
3858 return PTR_ERR(trans);
3860 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3861 err = btrfs_unlink_subvol(trans, root, dir,
3862 BTRFS_I(inode)->location.objectid,
3863 dentry->d_name.name,
3864 dentry->d_name.len);
3868 err = btrfs_orphan_add(trans, inode);
3872 /* now the directory is empty */
3873 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3874 dentry->d_name.name, dentry->d_name.len);
3876 btrfs_i_size_write(inode, 0);
3878 btrfs_end_transaction(trans, root);
3879 btrfs_btree_balance_dirty(root);
3885 * this can truncate away extent items, csum items and directory items.
3886 * It starts at a high offset and removes keys until it can't find
3887 * any higher than new_size
3889 * csum items that cross the new i_size are truncated to the new size
3892 * min_type is the minimum key type to truncate down to. If set to 0, this
3893 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3895 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3896 struct btrfs_root *root,
3897 struct inode *inode,
3898 u64 new_size, u32 min_type)
3900 struct btrfs_path *path;
3901 struct extent_buffer *leaf;
3902 struct btrfs_file_extent_item *fi;
3903 struct btrfs_key key;
3904 struct btrfs_key found_key;
3905 u64 extent_start = 0;
3906 u64 extent_num_bytes = 0;
3907 u64 extent_offset = 0;
3909 u32 found_type = (u8)-1;
3912 int pending_del_nr = 0;
3913 int pending_del_slot = 0;
3914 int extent_type = -1;
3917 u64 ino = btrfs_ino(inode);
3919 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3921 path = btrfs_alloc_path();
3927 * We want to drop from the next block forward in case this new size is
3928 * not block aligned since we will be keeping the last block of the
3929 * extent just the way it is.
3931 if (root->ref_cows || root == root->fs_info->tree_root)
3932 btrfs_drop_extent_cache(inode, ALIGN(new_size,
3933 root->sectorsize), (u64)-1, 0);
3936 * This function is also used to drop the items in the log tree before
3937 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3938 * it is used to drop the loged items. So we shouldn't kill the delayed
3941 if (min_type == 0 && root == BTRFS_I(inode)->root)
3942 btrfs_kill_delayed_inode_items(inode);
3945 key.offset = (u64)-1;
3949 path->leave_spinning = 1;
3950 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3957 /* there are no items in the tree for us to truncate, we're
3960 if (path->slots[0] == 0)
3967 leaf = path->nodes[0];
3968 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3969 found_type = btrfs_key_type(&found_key);
3971 if (found_key.objectid != ino)
3974 if (found_type < min_type)
3977 item_end = found_key.offset;
3978 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3979 fi = btrfs_item_ptr(leaf, path->slots[0],
3980 struct btrfs_file_extent_item);
3981 extent_type = btrfs_file_extent_type(leaf, fi);
3982 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3984 btrfs_file_extent_num_bytes(leaf, fi);
3985 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3986 item_end += btrfs_file_extent_inline_len(leaf,
3991 if (found_type > min_type) {
3994 if (item_end < new_size)
3996 if (found_key.offset >= new_size)
4002 /* FIXME, shrink the extent if the ref count is only 1 */
4003 if (found_type != BTRFS_EXTENT_DATA_KEY)
4006 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4008 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4010 u64 orig_num_bytes =
4011 btrfs_file_extent_num_bytes(leaf, fi);
4012 extent_num_bytes = ALIGN(new_size -
4015 btrfs_set_file_extent_num_bytes(leaf, fi,
4017 num_dec = (orig_num_bytes -
4019 if (root->ref_cows && extent_start != 0)
4020 inode_sub_bytes(inode, num_dec);
4021 btrfs_mark_buffer_dirty(leaf);
4024 btrfs_file_extent_disk_num_bytes(leaf,
4026 extent_offset = found_key.offset -
4027 btrfs_file_extent_offset(leaf, fi);
4029 /* FIXME blocksize != 4096 */
4030 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4031 if (extent_start != 0) {
4034 inode_sub_bytes(inode, num_dec);
4037 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4039 * we can't truncate inline items that have had
4043 btrfs_file_extent_compression(leaf, fi) == 0 &&
4044 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4045 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4046 u32 size = new_size - found_key.offset;
4048 if (root->ref_cows) {
4049 inode_sub_bytes(inode, item_end + 1 -
4053 btrfs_file_extent_calc_inline_size(size);
4054 btrfs_truncate_item(root, path, size, 1);
4055 } else if (root->ref_cows) {
4056 inode_sub_bytes(inode, item_end + 1 -
4062 if (!pending_del_nr) {
4063 /* no pending yet, add ourselves */
4064 pending_del_slot = path->slots[0];
4066 } else if (pending_del_nr &&
4067 path->slots[0] + 1 == pending_del_slot) {
4068 /* hop on the pending chunk */
4070 pending_del_slot = path->slots[0];
4077 if (found_extent && (root->ref_cows ||
4078 root == root->fs_info->tree_root)) {
4079 btrfs_set_path_blocking(path);
4080 ret = btrfs_free_extent(trans, root, extent_start,
4081 extent_num_bytes, 0,
4082 btrfs_header_owner(leaf),
4083 ino, extent_offset, 0);
4087 if (found_type == BTRFS_INODE_ITEM_KEY)
4090 if (path->slots[0] == 0 ||
4091 path->slots[0] != pending_del_slot) {
4092 if (pending_del_nr) {
4093 ret = btrfs_del_items(trans, root, path,
4097 btrfs_abort_transaction(trans,
4103 btrfs_release_path(path);
4110 if (pending_del_nr) {
4111 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4114 btrfs_abort_transaction(trans, root, ret);
4117 btrfs_free_path(path);
4122 * btrfs_truncate_page - read, zero a chunk and write a page
4123 * @inode - inode that we're zeroing
4124 * @from - the offset to start zeroing
4125 * @len - the length to zero, 0 to zero the entire range respective to the
4127 * @front - zero up to the offset instead of from the offset on
4129 * This will find the page for the "from" offset and cow the page and zero the
4130 * part we want to zero. This is used with truncate and hole punching.
4132 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4135 struct address_space *mapping = inode->i_mapping;
4136 struct btrfs_root *root = BTRFS_I(inode)->root;
4137 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4138 struct btrfs_ordered_extent *ordered;
4139 struct extent_state *cached_state = NULL;
4141 u32 blocksize = root->sectorsize;
4142 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4143 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4145 gfp_t mask = btrfs_alloc_write_mask(mapping);
4150 if ((offset & (blocksize - 1)) == 0 &&
4151 (!len || ((len & (blocksize - 1)) == 0)))
4153 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4158 page = find_or_create_page(mapping, index, mask);
4160 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4165 page_start = page_offset(page);
4166 page_end = page_start + PAGE_CACHE_SIZE - 1;
4168 if (!PageUptodate(page)) {
4169 ret = btrfs_readpage(NULL, page);
4171 if (page->mapping != mapping) {
4173 page_cache_release(page);
4176 if (!PageUptodate(page)) {
4181 wait_on_page_writeback(page);
4183 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4184 set_page_extent_mapped(page);
4186 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4188 unlock_extent_cached(io_tree, page_start, page_end,
4189 &cached_state, GFP_NOFS);
4191 page_cache_release(page);
4192 btrfs_start_ordered_extent(inode, ordered, 1);
4193 btrfs_put_ordered_extent(ordered);
4197 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4198 EXTENT_DIRTY | EXTENT_DELALLOC |
4199 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4200 0, 0, &cached_state, GFP_NOFS);
4202 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4205 unlock_extent_cached(io_tree, page_start, page_end,
4206 &cached_state, GFP_NOFS);
4210 if (offset != PAGE_CACHE_SIZE) {
4212 len = PAGE_CACHE_SIZE - offset;
4215 memset(kaddr, 0, offset);
4217 memset(kaddr + offset, 0, len);
4218 flush_dcache_page(page);
4221 ClearPageChecked(page);
4222 set_page_dirty(page);
4223 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4228 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4230 page_cache_release(page);
4236 * This function puts in dummy file extents for the area we're creating a hole
4237 * for. So if we are truncating this file to a larger size we need to insert
4238 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4239 * the range between oldsize and size
4241 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4243 struct btrfs_trans_handle *trans;
4244 struct btrfs_root *root = BTRFS_I(inode)->root;
4245 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4246 struct extent_map *em = NULL;
4247 struct extent_state *cached_state = NULL;
4248 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4249 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4250 u64 block_end = ALIGN(size, root->sectorsize);
4256 if (size <= hole_start)
4260 struct btrfs_ordered_extent *ordered;
4261 btrfs_wait_ordered_range(inode, hole_start,
4262 block_end - hole_start);
4263 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4265 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4268 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4269 &cached_state, GFP_NOFS);
4270 btrfs_put_ordered_extent(ordered);
4273 cur_offset = hole_start;
4275 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4276 block_end - cur_offset, 0);
4282 last_byte = min(extent_map_end(em), block_end);
4283 last_byte = ALIGN(last_byte , root->sectorsize);
4284 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4285 struct extent_map *hole_em;
4286 hole_size = last_byte - cur_offset;
4288 trans = btrfs_start_transaction(root, 3);
4289 if (IS_ERR(trans)) {
4290 err = PTR_ERR(trans);
4294 err = btrfs_drop_extents(trans, root, inode,
4296 cur_offset + hole_size, 1);
4298 btrfs_abort_transaction(trans, root, err);
4299 btrfs_end_transaction(trans, root);
4303 err = btrfs_insert_file_extent(trans, root,
4304 btrfs_ino(inode), cur_offset, 0,
4305 0, hole_size, 0, hole_size,
4308 btrfs_abort_transaction(trans, root, err);
4309 btrfs_end_transaction(trans, root);
4313 btrfs_drop_extent_cache(inode, cur_offset,
4314 cur_offset + hole_size - 1, 0);
4315 hole_em = alloc_extent_map();
4317 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4318 &BTRFS_I(inode)->runtime_flags);
4321 hole_em->start = cur_offset;
4322 hole_em->len = hole_size;
4323 hole_em->orig_start = cur_offset;
4325 hole_em->block_start = EXTENT_MAP_HOLE;
4326 hole_em->block_len = 0;
4327 hole_em->orig_block_len = 0;
4328 hole_em->ram_bytes = hole_size;
4329 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4330 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4331 hole_em->generation = trans->transid;
4334 write_lock(&em_tree->lock);
4335 err = add_extent_mapping(em_tree, hole_em, 1);
4336 write_unlock(&em_tree->lock);
4339 btrfs_drop_extent_cache(inode, cur_offset,
4343 free_extent_map(hole_em);
4345 btrfs_update_inode(trans, root, inode);
4346 btrfs_end_transaction(trans, root);
4348 free_extent_map(em);
4350 cur_offset = last_byte;
4351 if (cur_offset >= block_end)
4355 free_extent_map(em);
4356 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4361 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4363 struct btrfs_root *root = BTRFS_I(inode)->root;
4364 struct btrfs_trans_handle *trans;
4365 loff_t oldsize = i_size_read(inode);
4366 loff_t newsize = attr->ia_size;
4367 int mask = attr->ia_valid;
4370 if (newsize == oldsize)
4374 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4375 * special case where we need to update the times despite not having
4376 * these flags set. For all other operations the VFS set these flags
4377 * explicitly if it wants a timestamp update.
4379 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4380 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4382 if (newsize > oldsize) {
4383 truncate_pagecache(inode, oldsize, newsize);
4384 ret = btrfs_cont_expand(inode, oldsize, newsize);
4388 trans = btrfs_start_transaction(root, 1);
4390 return PTR_ERR(trans);
4392 i_size_write(inode, newsize);
4393 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4394 ret = btrfs_update_inode(trans, root, inode);
4395 btrfs_end_transaction(trans, root);
4399 * We're truncating a file that used to have good data down to
4400 * zero. Make sure it gets into the ordered flush list so that
4401 * any new writes get down to disk quickly.
4404 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4405 &BTRFS_I(inode)->runtime_flags);
4408 * 1 for the orphan item we're going to add
4409 * 1 for the orphan item deletion.
4411 trans = btrfs_start_transaction(root, 2);
4413 return PTR_ERR(trans);
4416 * We need to do this in case we fail at _any_ point during the
4417 * actual truncate. Once we do the truncate_setsize we could
4418 * invalidate pages which forces any outstanding ordered io to
4419 * be instantly completed which will give us extents that need
4420 * to be truncated. If we fail to get an orphan inode down we
4421 * could have left over extents that were never meant to live,
4422 * so we need to garuntee from this point on that everything
4423 * will be consistent.
4425 ret = btrfs_orphan_add(trans, inode);
4426 btrfs_end_transaction(trans, root);
4430 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4431 truncate_setsize(inode, newsize);
4433 /* Disable nonlocked read DIO to avoid the end less truncate */
4434 btrfs_inode_block_unlocked_dio(inode);
4435 inode_dio_wait(inode);
4436 btrfs_inode_resume_unlocked_dio(inode);
4438 ret = btrfs_truncate(inode);
4439 if (ret && inode->i_nlink)
4440 btrfs_orphan_del(NULL, inode);
4446 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4448 struct inode *inode = dentry->d_inode;
4449 struct btrfs_root *root = BTRFS_I(inode)->root;
4452 if (btrfs_root_readonly(root))
4455 err = inode_change_ok(inode, attr);
4459 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4460 err = btrfs_setsize(inode, attr);
4465 if (attr->ia_valid) {
4466 setattr_copy(inode, attr);
4467 inode_inc_iversion(inode);
4468 err = btrfs_dirty_inode(inode);
4470 if (!err && attr->ia_valid & ATTR_MODE)
4471 err = btrfs_acl_chmod(inode);
4477 void btrfs_evict_inode(struct inode *inode)
4479 struct btrfs_trans_handle *trans;
4480 struct btrfs_root *root = BTRFS_I(inode)->root;
4481 struct btrfs_block_rsv *rsv, *global_rsv;
4482 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4485 trace_btrfs_inode_evict(inode);
4487 truncate_inode_pages(&inode->i_data, 0);
4488 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4489 btrfs_is_free_space_inode(inode)))
4492 if (is_bad_inode(inode)) {
4493 btrfs_orphan_del(NULL, inode);
4496 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4497 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4499 if (root->fs_info->log_root_recovering) {
4500 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4501 &BTRFS_I(inode)->runtime_flags));
4505 if (inode->i_nlink > 0) {
4506 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4510 ret = btrfs_commit_inode_delayed_inode(inode);
4512 btrfs_orphan_del(NULL, inode);
4516 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4518 btrfs_orphan_del(NULL, inode);
4521 rsv->size = min_size;
4523 global_rsv = &root->fs_info->global_block_rsv;
4525 btrfs_i_size_write(inode, 0);
4528 * This is a bit simpler than btrfs_truncate since we've already
4529 * reserved our space for our orphan item in the unlink, so we just
4530 * need to reserve some slack space in case we add bytes and update
4531 * inode item when doing the truncate.
4534 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4535 BTRFS_RESERVE_FLUSH_LIMIT);
4538 * Try and steal from the global reserve since we will
4539 * likely not use this space anyway, we want to try as
4540 * hard as possible to get this to work.
4543 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4546 btrfs_warn(root->fs_info,
4547 "Could not get space for a delete, will truncate on mount %d",
4549 btrfs_orphan_del(NULL, inode);
4550 btrfs_free_block_rsv(root, rsv);
4554 trans = btrfs_join_transaction(root);
4555 if (IS_ERR(trans)) {
4556 btrfs_orphan_del(NULL, inode);
4557 btrfs_free_block_rsv(root, rsv);
4561 trans->block_rsv = rsv;
4563 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4567 trans->block_rsv = &root->fs_info->trans_block_rsv;
4568 btrfs_end_transaction(trans, root);
4570 btrfs_btree_balance_dirty(root);
4573 btrfs_free_block_rsv(root, rsv);
4576 trans->block_rsv = root->orphan_block_rsv;
4577 ret = btrfs_orphan_del(trans, inode);
4581 trans->block_rsv = &root->fs_info->trans_block_rsv;
4582 if (!(root == root->fs_info->tree_root ||
4583 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4584 btrfs_return_ino(root, btrfs_ino(inode));
4586 btrfs_end_transaction(trans, root);
4587 btrfs_btree_balance_dirty(root);
4589 btrfs_remove_delayed_node(inode);
4595 * this returns the key found in the dir entry in the location pointer.
4596 * If no dir entries were found, location->objectid is 0.
4598 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4599 struct btrfs_key *location)
4601 const char *name = dentry->d_name.name;
4602 int namelen = dentry->d_name.len;
4603 struct btrfs_dir_item *di;
4604 struct btrfs_path *path;
4605 struct btrfs_root *root = BTRFS_I(dir)->root;
4608 path = btrfs_alloc_path();
4612 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4617 if (IS_ERR_OR_NULL(di))
4620 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4622 btrfs_free_path(path);
4625 location->objectid = 0;
4630 * when we hit a tree root in a directory, the btrfs part of the inode
4631 * needs to be changed to reflect the root directory of the tree root. This
4632 * is kind of like crossing a mount point.
4634 static int fixup_tree_root_location(struct btrfs_root *root,
4636 struct dentry *dentry,
4637 struct btrfs_key *location,
4638 struct btrfs_root **sub_root)
4640 struct btrfs_path *path;
4641 struct btrfs_root *new_root;
4642 struct btrfs_root_ref *ref;
4643 struct extent_buffer *leaf;
4647 path = btrfs_alloc_path();
4654 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4655 BTRFS_I(dir)->root->root_key.objectid,
4656 location->objectid);
4663 leaf = path->nodes[0];
4664 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4665 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4666 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4669 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4670 (unsigned long)(ref + 1),
4671 dentry->d_name.len);
4675 btrfs_release_path(path);
4677 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4678 if (IS_ERR(new_root)) {
4679 err = PTR_ERR(new_root);
4683 *sub_root = new_root;
4684 location->objectid = btrfs_root_dirid(&new_root->root_item);
4685 location->type = BTRFS_INODE_ITEM_KEY;
4686 location->offset = 0;
4689 btrfs_free_path(path);
4693 static void inode_tree_add(struct inode *inode)
4695 struct btrfs_root *root = BTRFS_I(inode)->root;
4696 struct btrfs_inode *entry;
4698 struct rb_node *parent;
4699 u64 ino = btrfs_ino(inode);
4701 if (inode_unhashed(inode))
4705 spin_lock(&root->inode_lock);
4706 p = &root->inode_tree.rb_node;
4709 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4711 if (ino < btrfs_ino(&entry->vfs_inode))
4712 p = &parent->rb_left;
4713 else if (ino > btrfs_ino(&entry->vfs_inode))
4714 p = &parent->rb_right;
4716 WARN_ON(!(entry->vfs_inode.i_state &
4717 (I_WILL_FREE | I_FREEING)));
4718 rb_erase(parent, &root->inode_tree);
4719 RB_CLEAR_NODE(parent);
4720 spin_unlock(&root->inode_lock);
4724 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4725 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4726 spin_unlock(&root->inode_lock);
4729 static void inode_tree_del(struct inode *inode)
4731 struct btrfs_root *root = BTRFS_I(inode)->root;
4734 spin_lock(&root->inode_lock);
4735 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4736 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4737 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4738 empty = RB_EMPTY_ROOT(&root->inode_tree);
4740 spin_unlock(&root->inode_lock);
4743 * Free space cache has inodes in the tree root, but the tree root has a
4744 * root_refs of 0, so this could end up dropping the tree root as a
4745 * snapshot, so we need the extra !root->fs_info->tree_root check to
4746 * make sure we don't drop it.
4748 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4749 root != root->fs_info->tree_root) {
4750 synchronize_srcu(&root->fs_info->subvol_srcu);
4751 spin_lock(&root->inode_lock);
4752 empty = RB_EMPTY_ROOT(&root->inode_tree);
4753 spin_unlock(&root->inode_lock);
4755 btrfs_add_dead_root(root);
4759 void btrfs_invalidate_inodes(struct btrfs_root *root)
4761 struct rb_node *node;
4762 struct rb_node *prev;
4763 struct btrfs_inode *entry;
4764 struct inode *inode;
4767 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4769 spin_lock(&root->inode_lock);
4771 node = root->inode_tree.rb_node;
4775 entry = rb_entry(node, struct btrfs_inode, rb_node);
4777 if (objectid < btrfs_ino(&entry->vfs_inode))
4778 node = node->rb_left;
4779 else if (objectid > btrfs_ino(&entry->vfs_inode))
4780 node = node->rb_right;
4786 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4787 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4791 prev = rb_next(prev);
4795 entry = rb_entry(node, struct btrfs_inode, rb_node);
4796 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4797 inode = igrab(&entry->vfs_inode);
4799 spin_unlock(&root->inode_lock);
4800 if (atomic_read(&inode->i_count) > 1)
4801 d_prune_aliases(inode);
4803 * btrfs_drop_inode will have it removed from
4804 * the inode cache when its usage count
4809 spin_lock(&root->inode_lock);
4813 if (cond_resched_lock(&root->inode_lock))
4816 node = rb_next(node);
4818 spin_unlock(&root->inode_lock);
4821 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4823 struct btrfs_iget_args *args = p;
4824 inode->i_ino = args->ino;
4825 BTRFS_I(inode)->root = args->root;
4829 static int btrfs_find_actor(struct inode *inode, void *opaque)
4831 struct btrfs_iget_args *args = opaque;
4832 return args->ino == btrfs_ino(inode) &&
4833 args->root == BTRFS_I(inode)->root;
4836 static struct inode *btrfs_iget_locked(struct super_block *s,
4838 struct btrfs_root *root)
4840 struct inode *inode;
4841 struct btrfs_iget_args args;
4842 args.ino = objectid;
4845 inode = iget5_locked(s, objectid, btrfs_find_actor,
4846 btrfs_init_locked_inode,
4851 /* Get an inode object given its location and corresponding root.
4852 * Returns in *is_new if the inode was read from disk
4854 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4855 struct btrfs_root *root, int *new)
4857 struct inode *inode;
4859 inode = btrfs_iget_locked(s, location->objectid, root);
4861 return ERR_PTR(-ENOMEM);
4863 if (inode->i_state & I_NEW) {
4864 BTRFS_I(inode)->root = root;
4865 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4866 btrfs_read_locked_inode(inode);
4867 if (!is_bad_inode(inode)) {
4868 inode_tree_add(inode);
4869 unlock_new_inode(inode);
4873 unlock_new_inode(inode);
4875 inode = ERR_PTR(-ESTALE);
4882 static struct inode *new_simple_dir(struct super_block *s,
4883 struct btrfs_key *key,
4884 struct btrfs_root *root)
4886 struct inode *inode = new_inode(s);
4889 return ERR_PTR(-ENOMEM);
4891 BTRFS_I(inode)->root = root;
4892 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4893 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4895 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4896 inode->i_op = &btrfs_dir_ro_inode_operations;
4897 inode->i_fop = &simple_dir_operations;
4898 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4899 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4904 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4906 struct inode *inode;
4907 struct btrfs_root *root = BTRFS_I(dir)->root;
4908 struct btrfs_root *sub_root = root;
4909 struct btrfs_key location;
4913 if (dentry->d_name.len > BTRFS_NAME_LEN)
4914 return ERR_PTR(-ENAMETOOLONG);
4916 ret = btrfs_inode_by_name(dir, dentry, &location);
4918 return ERR_PTR(ret);
4920 if (location.objectid == 0)
4923 if (location.type == BTRFS_INODE_ITEM_KEY) {
4924 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4928 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4930 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4931 ret = fixup_tree_root_location(root, dir, dentry,
4932 &location, &sub_root);
4935 inode = ERR_PTR(ret);
4937 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4939 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4941 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4943 if (!IS_ERR(inode) && root != sub_root) {
4944 down_read(&root->fs_info->cleanup_work_sem);
4945 if (!(inode->i_sb->s_flags & MS_RDONLY))
4946 ret = btrfs_orphan_cleanup(sub_root);
4947 up_read(&root->fs_info->cleanup_work_sem);
4950 inode = ERR_PTR(ret);
4957 static int btrfs_dentry_delete(const struct dentry *dentry)
4959 struct btrfs_root *root;
4960 struct inode *inode = dentry->d_inode;
4962 if (!inode && !IS_ROOT(dentry))
4963 inode = dentry->d_parent->d_inode;
4966 root = BTRFS_I(inode)->root;
4967 if (btrfs_root_refs(&root->root_item) == 0)
4970 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4976 static void btrfs_dentry_release(struct dentry *dentry)
4978 if (dentry->d_fsdata)
4979 kfree(dentry->d_fsdata);
4982 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4987 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4991 unsigned char btrfs_filetype_table[] = {
4992 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4995 static int btrfs_real_readdir(struct file *filp, void *dirent,
4998 struct inode *inode = file_inode(filp);
4999 struct btrfs_root *root = BTRFS_I(inode)->root;
5000 struct btrfs_item *item;
5001 struct btrfs_dir_item *di;
5002 struct btrfs_key key;
5003 struct btrfs_key found_key;
5004 struct btrfs_path *path;
5005 struct list_head ins_list;
5006 struct list_head del_list;
5008 struct extent_buffer *leaf;
5010 unsigned char d_type;
5015 int key_type = BTRFS_DIR_INDEX_KEY;
5019 int is_curr = 0; /* filp->f_pos points to the current index? */
5021 /* FIXME, use a real flag for deciding about the key type */
5022 if (root->fs_info->tree_root == root)
5023 key_type = BTRFS_DIR_ITEM_KEY;
5025 /* special case for "." */
5026 if (filp->f_pos == 0) {
5027 over = filldir(dirent, ".", 1,
5028 filp->f_pos, btrfs_ino(inode), DT_DIR);
5033 /* special case for .., just use the back ref */
5034 if (filp->f_pos == 1) {
5035 u64 pino = parent_ino(filp->f_path.dentry);
5036 over = filldir(dirent, "..", 2,
5037 filp->f_pos, pino, DT_DIR);
5042 path = btrfs_alloc_path();
5048 if (key_type == BTRFS_DIR_INDEX_KEY) {
5049 INIT_LIST_HEAD(&ins_list);
5050 INIT_LIST_HEAD(&del_list);
5051 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5054 btrfs_set_key_type(&key, key_type);
5055 key.offset = filp->f_pos;
5056 key.objectid = btrfs_ino(inode);
5058 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5063 leaf = path->nodes[0];
5064 slot = path->slots[0];
5065 if (slot >= btrfs_header_nritems(leaf)) {
5066 ret = btrfs_next_leaf(root, path);
5074 item = btrfs_item_nr(leaf, slot);
5075 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5077 if (found_key.objectid != key.objectid)
5079 if (btrfs_key_type(&found_key) != key_type)
5081 if (found_key.offset < filp->f_pos)
5083 if (key_type == BTRFS_DIR_INDEX_KEY &&
5084 btrfs_should_delete_dir_index(&del_list,
5088 filp->f_pos = found_key.offset;
5091 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5093 di_total = btrfs_item_size(leaf, item);
5095 while (di_cur < di_total) {
5096 struct btrfs_key location;
5098 if (verify_dir_item(root, leaf, di))
5101 name_len = btrfs_dir_name_len(leaf, di);
5102 if (name_len <= sizeof(tmp_name)) {
5103 name_ptr = tmp_name;
5105 name_ptr = kmalloc(name_len, GFP_NOFS);
5111 read_extent_buffer(leaf, name_ptr,
5112 (unsigned long)(di + 1), name_len);
5114 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5115 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5118 /* is this a reference to our own snapshot? If so
5121 * In contrast to old kernels, we insert the snapshot's
5122 * dir item and dir index after it has been created, so
5123 * we won't find a reference to our own snapshot. We
5124 * still keep the following code for backward
5127 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5128 location.objectid == root->root_key.objectid) {
5132 over = filldir(dirent, name_ptr, name_len,
5133 found_key.offset, location.objectid,
5137 if (name_ptr != tmp_name)
5142 di_len = btrfs_dir_name_len(leaf, di) +
5143 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5145 di = (struct btrfs_dir_item *)((char *)di + di_len);
5151 if (key_type == BTRFS_DIR_INDEX_KEY) {
5154 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5160 /* Reached end of directory/root. Bump pos past the last item. */
5161 if (key_type == BTRFS_DIR_INDEX_KEY)
5163 * 32-bit glibc will use getdents64, but then strtol -
5164 * so the last number we can serve is this.
5166 filp->f_pos = 0x7fffffff;
5172 if (key_type == BTRFS_DIR_INDEX_KEY)
5173 btrfs_put_delayed_items(&ins_list, &del_list);
5174 btrfs_free_path(path);
5178 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5180 struct btrfs_root *root = BTRFS_I(inode)->root;
5181 struct btrfs_trans_handle *trans;
5183 bool nolock = false;
5185 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5188 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5191 if (wbc->sync_mode == WB_SYNC_ALL) {
5193 trans = btrfs_join_transaction_nolock(root);
5195 trans = btrfs_join_transaction(root);
5197 return PTR_ERR(trans);
5198 ret = btrfs_commit_transaction(trans, root);
5204 * This is somewhat expensive, updating the tree every time the
5205 * inode changes. But, it is most likely to find the inode in cache.
5206 * FIXME, needs more benchmarking...there are no reasons other than performance
5207 * to keep or drop this code.
5209 static int btrfs_dirty_inode(struct inode *inode)
5211 struct btrfs_root *root = BTRFS_I(inode)->root;
5212 struct btrfs_trans_handle *trans;
5215 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5218 trans = btrfs_join_transaction(root);
5220 return PTR_ERR(trans);
5222 ret = btrfs_update_inode(trans, root, inode);
5223 if (ret && ret == -ENOSPC) {
5224 /* whoops, lets try again with the full transaction */
5225 btrfs_end_transaction(trans, root);
5226 trans = btrfs_start_transaction(root, 1);
5228 return PTR_ERR(trans);
5230 ret = btrfs_update_inode(trans, root, inode);
5232 btrfs_end_transaction(trans, root);
5233 if (BTRFS_I(inode)->delayed_node)
5234 btrfs_balance_delayed_items(root);
5240 * This is a copy of file_update_time. We need this so we can return error on
5241 * ENOSPC for updating the inode in the case of file write and mmap writes.
5243 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5246 struct btrfs_root *root = BTRFS_I(inode)->root;
5248 if (btrfs_root_readonly(root))
5251 if (flags & S_VERSION)
5252 inode_inc_iversion(inode);
5253 if (flags & S_CTIME)
5254 inode->i_ctime = *now;
5255 if (flags & S_MTIME)
5256 inode->i_mtime = *now;
5257 if (flags & S_ATIME)
5258 inode->i_atime = *now;
5259 return btrfs_dirty_inode(inode);
5263 * find the highest existing sequence number in a directory
5264 * and then set the in-memory index_cnt variable to reflect
5265 * free sequence numbers
5267 static int btrfs_set_inode_index_count(struct inode *inode)
5269 struct btrfs_root *root = BTRFS_I(inode)->root;
5270 struct btrfs_key key, found_key;
5271 struct btrfs_path *path;
5272 struct extent_buffer *leaf;
5275 key.objectid = btrfs_ino(inode);
5276 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5277 key.offset = (u64)-1;
5279 path = btrfs_alloc_path();
5283 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5286 /* FIXME: we should be able to handle this */
5292 * MAGIC NUMBER EXPLANATION:
5293 * since we search a directory based on f_pos we have to start at 2
5294 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5295 * else has to start at 2
5297 if (path->slots[0] == 0) {
5298 BTRFS_I(inode)->index_cnt = 2;
5304 leaf = path->nodes[0];
5305 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5307 if (found_key.objectid != btrfs_ino(inode) ||
5308 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5309 BTRFS_I(inode)->index_cnt = 2;
5313 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5315 btrfs_free_path(path);
5320 * helper to find a free sequence number in a given directory. This current
5321 * code is very simple, later versions will do smarter things in the btree
5323 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5327 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5328 ret = btrfs_inode_delayed_dir_index_count(dir);
5330 ret = btrfs_set_inode_index_count(dir);
5336 *index = BTRFS_I(dir)->index_cnt;
5337 BTRFS_I(dir)->index_cnt++;
5342 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5343 struct btrfs_root *root,
5345 const char *name, int name_len,
5346 u64 ref_objectid, u64 objectid,
5347 umode_t mode, u64 *index)
5349 struct inode *inode;
5350 struct btrfs_inode_item *inode_item;
5351 struct btrfs_key *location;
5352 struct btrfs_path *path;
5353 struct btrfs_inode_ref *ref;
5354 struct btrfs_key key[2];
5360 path = btrfs_alloc_path();
5362 return ERR_PTR(-ENOMEM);
5364 inode = new_inode(root->fs_info->sb);
5366 btrfs_free_path(path);
5367 return ERR_PTR(-ENOMEM);
5371 * we have to initialize this early, so we can reclaim the inode
5372 * number if we fail afterwards in this function.
5374 inode->i_ino = objectid;
5377 trace_btrfs_inode_request(dir);
5379 ret = btrfs_set_inode_index(dir, index);
5381 btrfs_free_path(path);
5383 return ERR_PTR(ret);
5387 * index_cnt is ignored for everything but a dir,
5388 * btrfs_get_inode_index_count has an explanation for the magic
5391 BTRFS_I(inode)->index_cnt = 2;
5392 BTRFS_I(inode)->root = root;
5393 BTRFS_I(inode)->generation = trans->transid;
5394 inode->i_generation = BTRFS_I(inode)->generation;
5397 * We could have gotten an inode number from somebody who was fsynced
5398 * and then removed in this same transaction, so let's just set full
5399 * sync since it will be a full sync anyway and this will blow away the
5400 * old info in the log.
5402 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5409 key[0].objectid = objectid;
5410 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5414 * Start new inodes with an inode_ref. This is slightly more
5415 * efficient for small numbers of hard links since they will
5416 * be packed into one item. Extended refs will kick in if we
5417 * add more hard links than can fit in the ref item.
5419 key[1].objectid = objectid;
5420 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5421 key[1].offset = ref_objectid;
5423 sizes[0] = sizeof(struct btrfs_inode_item);
5424 sizes[1] = name_len + sizeof(*ref);
5426 path->leave_spinning = 1;
5427 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5431 inode_init_owner(inode, dir, mode);
5432 inode_set_bytes(inode, 0);
5433 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5434 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5435 struct btrfs_inode_item);
5436 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5437 sizeof(*inode_item));
5438 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5440 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5441 struct btrfs_inode_ref);
5442 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5443 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5444 ptr = (unsigned long)(ref + 1);
5445 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5447 btrfs_mark_buffer_dirty(path->nodes[0]);
5448 btrfs_free_path(path);
5450 location = &BTRFS_I(inode)->location;
5451 location->objectid = objectid;
5452 location->offset = 0;
5453 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5455 btrfs_inherit_iflags(inode, dir);
5457 if (S_ISREG(mode)) {
5458 if (btrfs_test_opt(root, NODATASUM))
5459 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5460 if (btrfs_test_opt(root, NODATACOW))
5461 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5462 BTRFS_INODE_NODATASUM;
5465 insert_inode_hash(inode);
5466 inode_tree_add(inode);
5468 trace_btrfs_inode_new(inode);
5469 btrfs_set_inode_last_trans(trans, inode);
5471 btrfs_update_root_times(trans, root);
5476 BTRFS_I(dir)->index_cnt--;
5477 btrfs_free_path(path);
5479 return ERR_PTR(ret);
5482 static inline u8 btrfs_inode_type(struct inode *inode)
5484 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5488 * utility function to add 'inode' into 'parent_inode' with
5489 * a give name and a given sequence number.
5490 * if 'add_backref' is true, also insert a backref from the
5491 * inode to the parent directory.
5493 int btrfs_add_link(struct btrfs_trans_handle *trans,
5494 struct inode *parent_inode, struct inode *inode,
5495 const char *name, int name_len, int add_backref, u64 index)
5498 struct btrfs_key key;
5499 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5500 u64 ino = btrfs_ino(inode);
5501 u64 parent_ino = btrfs_ino(parent_inode);
5503 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5504 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5507 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5511 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5512 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5513 key.objectid, root->root_key.objectid,
5514 parent_ino, index, name, name_len);
5515 } else if (add_backref) {
5516 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5520 /* Nothing to clean up yet */
5524 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5526 btrfs_inode_type(inode), index);
5527 if (ret == -EEXIST || ret == -EOVERFLOW)
5530 btrfs_abort_transaction(trans, root, ret);
5534 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5536 inode_inc_iversion(parent_inode);
5537 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5538 ret = btrfs_update_inode(trans, root, parent_inode);
5540 btrfs_abort_transaction(trans, root, ret);
5544 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5547 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5548 key.objectid, root->root_key.objectid,
5549 parent_ino, &local_index, name, name_len);
5551 } else if (add_backref) {
5555 err = btrfs_del_inode_ref(trans, root, name, name_len,
5556 ino, parent_ino, &local_index);
5561 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5562 struct inode *dir, struct dentry *dentry,
5563 struct inode *inode, int backref, u64 index)
5565 int err = btrfs_add_link(trans, dir, inode,
5566 dentry->d_name.name, dentry->d_name.len,
5573 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5574 umode_t mode, dev_t rdev)
5576 struct btrfs_trans_handle *trans;
5577 struct btrfs_root *root = BTRFS_I(dir)->root;
5578 struct inode *inode = NULL;
5584 if (!new_valid_dev(rdev))
5588 * 2 for inode item and ref
5590 * 1 for xattr if selinux is on
5592 trans = btrfs_start_transaction(root, 5);
5594 return PTR_ERR(trans);
5596 err = btrfs_find_free_ino(root, &objectid);
5600 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5601 dentry->d_name.len, btrfs_ino(dir), objectid,
5603 if (IS_ERR(inode)) {
5604 err = PTR_ERR(inode);
5608 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5615 * If the active LSM wants to access the inode during
5616 * d_instantiate it needs these. Smack checks to see
5617 * if the filesystem supports xattrs by looking at the
5621 inode->i_op = &btrfs_special_inode_operations;
5622 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5626 init_special_inode(inode, inode->i_mode, rdev);
5627 btrfs_update_inode(trans, root, inode);
5628 d_instantiate(dentry, inode);
5631 btrfs_end_transaction(trans, root);
5632 btrfs_btree_balance_dirty(root);
5634 inode_dec_link_count(inode);
5640 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5641 umode_t mode, bool excl)
5643 struct btrfs_trans_handle *trans;
5644 struct btrfs_root *root = BTRFS_I(dir)->root;
5645 struct inode *inode = NULL;
5646 int drop_inode_on_err = 0;
5652 * 2 for inode item and ref
5654 * 1 for xattr if selinux is on
5656 trans = btrfs_start_transaction(root, 5);
5658 return PTR_ERR(trans);
5660 err = btrfs_find_free_ino(root, &objectid);
5664 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5665 dentry->d_name.len, btrfs_ino(dir), objectid,
5667 if (IS_ERR(inode)) {
5668 err = PTR_ERR(inode);
5671 drop_inode_on_err = 1;
5673 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5677 err = btrfs_update_inode(trans, root, inode);
5682 * If the active LSM wants to access the inode during
5683 * d_instantiate it needs these. Smack checks to see
5684 * if the filesystem supports xattrs by looking at the
5687 inode->i_fop = &btrfs_file_operations;
5688 inode->i_op = &btrfs_file_inode_operations;
5690 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5694 inode->i_mapping->a_ops = &btrfs_aops;
5695 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5696 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5697 d_instantiate(dentry, inode);
5700 btrfs_end_transaction(trans, root);
5701 if (err && drop_inode_on_err) {
5702 inode_dec_link_count(inode);
5705 btrfs_btree_balance_dirty(root);
5709 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5710 struct dentry *dentry)
5712 struct btrfs_trans_handle *trans;
5713 struct btrfs_root *root = BTRFS_I(dir)->root;
5714 struct inode *inode = old_dentry->d_inode;
5719 /* do not allow sys_link's with other subvols of the same device */
5720 if (root->objectid != BTRFS_I(inode)->root->objectid)
5723 if (inode->i_nlink >= BTRFS_LINK_MAX)
5726 err = btrfs_set_inode_index(dir, &index);
5731 * 2 items for inode and inode ref
5732 * 2 items for dir items
5733 * 1 item for parent inode
5735 trans = btrfs_start_transaction(root, 5);
5736 if (IS_ERR(trans)) {
5737 err = PTR_ERR(trans);
5741 btrfs_inc_nlink(inode);
5742 inode_inc_iversion(inode);
5743 inode->i_ctime = CURRENT_TIME;
5745 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5747 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5752 struct dentry *parent = dentry->d_parent;
5753 err = btrfs_update_inode(trans, root, inode);
5756 d_instantiate(dentry, inode);
5757 btrfs_log_new_name(trans, inode, NULL, parent);
5760 btrfs_end_transaction(trans, root);
5763 inode_dec_link_count(inode);
5766 btrfs_btree_balance_dirty(root);
5770 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5772 struct inode *inode = NULL;
5773 struct btrfs_trans_handle *trans;
5774 struct btrfs_root *root = BTRFS_I(dir)->root;
5776 int drop_on_err = 0;
5781 * 2 items for inode and ref
5782 * 2 items for dir items
5783 * 1 for xattr if selinux is on
5785 trans = btrfs_start_transaction(root, 5);
5787 return PTR_ERR(trans);
5789 err = btrfs_find_free_ino(root, &objectid);
5793 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5794 dentry->d_name.len, btrfs_ino(dir), objectid,
5795 S_IFDIR | mode, &index);
5796 if (IS_ERR(inode)) {
5797 err = PTR_ERR(inode);
5803 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5807 inode->i_op = &btrfs_dir_inode_operations;
5808 inode->i_fop = &btrfs_dir_file_operations;
5810 btrfs_i_size_write(inode, 0);
5811 err = btrfs_update_inode(trans, root, inode);
5815 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5816 dentry->d_name.len, 0, index);
5820 d_instantiate(dentry, inode);
5824 btrfs_end_transaction(trans, root);
5827 btrfs_btree_balance_dirty(root);
5831 /* helper for btfs_get_extent. Given an existing extent in the tree,
5832 * and an extent that you want to insert, deal with overlap and insert
5833 * the new extent into the tree.
5835 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5836 struct extent_map *existing,
5837 struct extent_map *em,
5838 u64 map_start, u64 map_len)
5842 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5843 start_diff = map_start - em->start;
5844 em->start = map_start;
5846 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5847 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5848 em->block_start += start_diff;
5849 em->block_len -= start_diff;
5851 return add_extent_mapping(em_tree, em, 0);
5854 static noinline int uncompress_inline(struct btrfs_path *path,
5855 struct inode *inode, struct page *page,
5856 size_t pg_offset, u64 extent_offset,
5857 struct btrfs_file_extent_item *item)
5860 struct extent_buffer *leaf = path->nodes[0];
5863 unsigned long inline_size;
5867 WARN_ON(pg_offset != 0);
5868 compress_type = btrfs_file_extent_compression(leaf, item);
5869 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5870 inline_size = btrfs_file_extent_inline_item_len(leaf,
5871 btrfs_item_nr(leaf, path->slots[0]));
5872 tmp = kmalloc(inline_size, GFP_NOFS);
5875 ptr = btrfs_file_extent_inline_start(item);
5877 read_extent_buffer(leaf, tmp, ptr, inline_size);
5879 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5880 ret = btrfs_decompress(compress_type, tmp, page,
5881 extent_offset, inline_size, max_size);
5883 char *kaddr = kmap_atomic(page);
5884 unsigned long copy_size = min_t(u64,
5885 PAGE_CACHE_SIZE - pg_offset,
5886 max_size - extent_offset);
5887 memset(kaddr + pg_offset, 0, copy_size);
5888 kunmap_atomic(kaddr);
5895 * a bit scary, this does extent mapping from logical file offset to the disk.
5896 * the ugly parts come from merging extents from the disk with the in-ram
5897 * representation. This gets more complex because of the data=ordered code,
5898 * where the in-ram extents might be locked pending data=ordered completion.
5900 * This also copies inline extents directly into the page.
5903 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5904 size_t pg_offset, u64 start, u64 len,
5910 u64 extent_start = 0;
5912 u64 objectid = btrfs_ino(inode);
5914 struct btrfs_path *path = NULL;
5915 struct btrfs_root *root = BTRFS_I(inode)->root;
5916 struct btrfs_file_extent_item *item;
5917 struct extent_buffer *leaf;
5918 struct btrfs_key found_key;
5919 struct extent_map *em = NULL;
5920 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5921 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5922 struct btrfs_trans_handle *trans = NULL;
5926 read_lock(&em_tree->lock);
5927 em = lookup_extent_mapping(em_tree, start, len);
5929 em->bdev = root->fs_info->fs_devices->latest_bdev;
5930 read_unlock(&em_tree->lock);
5933 if (em->start > start || em->start + em->len <= start)
5934 free_extent_map(em);
5935 else if (em->block_start == EXTENT_MAP_INLINE && page)
5936 free_extent_map(em);
5940 em = alloc_extent_map();
5945 em->bdev = root->fs_info->fs_devices->latest_bdev;
5946 em->start = EXTENT_MAP_HOLE;
5947 em->orig_start = EXTENT_MAP_HOLE;
5949 em->block_len = (u64)-1;
5952 path = btrfs_alloc_path();
5958 * Chances are we'll be called again, so go ahead and do
5964 ret = btrfs_lookup_file_extent(trans, root, path,
5965 objectid, start, trans != NULL);
5972 if (path->slots[0] == 0)
5977 leaf = path->nodes[0];
5978 item = btrfs_item_ptr(leaf, path->slots[0],
5979 struct btrfs_file_extent_item);
5980 /* are we inside the extent that was found? */
5981 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5982 found_type = btrfs_key_type(&found_key);
5983 if (found_key.objectid != objectid ||
5984 found_type != BTRFS_EXTENT_DATA_KEY) {
5988 found_type = btrfs_file_extent_type(leaf, item);
5989 extent_start = found_key.offset;
5990 compress_type = btrfs_file_extent_compression(leaf, item);
5991 if (found_type == BTRFS_FILE_EXTENT_REG ||
5992 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5993 extent_end = extent_start +
5994 btrfs_file_extent_num_bytes(leaf, item);
5995 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5997 size = btrfs_file_extent_inline_len(leaf, item);
5998 extent_end = ALIGN(extent_start + size, root->sectorsize);
6001 if (start >= extent_end) {
6003 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6004 ret = btrfs_next_leaf(root, path);
6011 leaf = path->nodes[0];
6013 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6014 if (found_key.objectid != objectid ||
6015 found_key.type != BTRFS_EXTENT_DATA_KEY)
6017 if (start + len <= found_key.offset)
6020 em->orig_start = start;
6021 em->len = found_key.offset - start;
6025 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6026 if (found_type == BTRFS_FILE_EXTENT_REG ||
6027 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6028 em->start = extent_start;
6029 em->len = extent_end - extent_start;
6030 em->orig_start = extent_start -
6031 btrfs_file_extent_offset(leaf, item);
6032 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6034 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6036 em->block_start = EXTENT_MAP_HOLE;
6039 if (compress_type != BTRFS_COMPRESS_NONE) {
6040 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6041 em->compress_type = compress_type;
6042 em->block_start = bytenr;
6043 em->block_len = em->orig_block_len;
6045 bytenr += btrfs_file_extent_offset(leaf, item);
6046 em->block_start = bytenr;
6047 em->block_len = em->len;
6048 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6049 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6052 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6056 size_t extent_offset;
6059 em->block_start = EXTENT_MAP_INLINE;
6060 if (!page || create) {
6061 em->start = extent_start;
6062 em->len = extent_end - extent_start;
6066 size = btrfs_file_extent_inline_len(leaf, item);
6067 extent_offset = page_offset(page) + pg_offset - extent_start;
6068 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6069 size - extent_offset);
6070 em->start = extent_start + extent_offset;
6071 em->len = ALIGN(copy_size, root->sectorsize);
6072 em->orig_block_len = em->len;
6073 em->orig_start = em->start;
6074 if (compress_type) {
6075 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6076 em->compress_type = compress_type;
6078 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6079 if (create == 0 && !PageUptodate(page)) {
6080 if (btrfs_file_extent_compression(leaf, item) !=
6081 BTRFS_COMPRESS_NONE) {
6082 ret = uncompress_inline(path, inode, page,
6084 extent_offset, item);
6085 BUG_ON(ret); /* -ENOMEM */
6088 read_extent_buffer(leaf, map + pg_offset, ptr,
6090 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6091 memset(map + pg_offset + copy_size, 0,
6092 PAGE_CACHE_SIZE - pg_offset -
6097 flush_dcache_page(page);
6098 } else if (create && PageUptodate(page)) {
6102 free_extent_map(em);
6105 btrfs_release_path(path);
6106 trans = btrfs_join_transaction(root);
6109 return ERR_CAST(trans);
6113 write_extent_buffer(leaf, map + pg_offset, ptr,
6116 btrfs_mark_buffer_dirty(leaf);
6118 set_extent_uptodate(io_tree, em->start,
6119 extent_map_end(em) - 1, NULL, GFP_NOFS);
6122 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6126 em->orig_start = start;
6129 em->block_start = EXTENT_MAP_HOLE;
6130 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6132 btrfs_release_path(path);
6133 if (em->start > start || extent_map_end(em) <= start) {
6134 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6135 (unsigned long long)em->start,
6136 (unsigned long long)em->len,
6137 (unsigned long long)start,
6138 (unsigned long long)len);
6144 write_lock(&em_tree->lock);
6145 ret = add_extent_mapping(em_tree, em, 0);
6146 /* it is possible that someone inserted the extent into the tree
6147 * while we had the lock dropped. It is also possible that
6148 * an overlapping map exists in the tree
6150 if (ret == -EEXIST) {
6151 struct extent_map *existing;
6155 existing = lookup_extent_mapping(em_tree, start, len);
6156 if (existing && (existing->start > start ||
6157 existing->start + existing->len <= start)) {
6158 free_extent_map(existing);
6162 existing = lookup_extent_mapping(em_tree, em->start,
6165 err = merge_extent_mapping(em_tree, existing,
6168 free_extent_map(existing);
6170 free_extent_map(em);
6175 free_extent_map(em);
6179 free_extent_map(em);
6184 write_unlock(&em_tree->lock);
6188 trace_btrfs_get_extent(root, em);
6191 btrfs_free_path(path);
6193 ret = btrfs_end_transaction(trans, root);
6198 free_extent_map(em);
6199 return ERR_PTR(err);
6201 BUG_ON(!em); /* Error is always set */
6205 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6206 size_t pg_offset, u64 start, u64 len,
6209 struct extent_map *em;
6210 struct extent_map *hole_em = NULL;
6211 u64 range_start = start;
6217 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6224 * - a pre-alloc extent,
6225 * there might actually be delalloc bytes behind it.
6227 if (em->block_start != EXTENT_MAP_HOLE &&
6228 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6234 /* check to see if we've wrapped (len == -1 or similar) */
6243 /* ok, we didn't find anything, lets look for delalloc */
6244 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6245 end, len, EXTENT_DELALLOC, 1);
6246 found_end = range_start + found;
6247 if (found_end < range_start)
6248 found_end = (u64)-1;
6251 * we didn't find anything useful, return
6252 * the original results from get_extent()
6254 if (range_start > end || found_end <= start) {
6260 /* adjust the range_start to make sure it doesn't
6261 * go backwards from the start they passed in
6263 range_start = max(start,range_start);
6264 found = found_end - range_start;
6267 u64 hole_start = start;
6270 em = alloc_extent_map();
6276 * when btrfs_get_extent can't find anything it
6277 * returns one huge hole
6279 * make sure what it found really fits our range, and
6280 * adjust to make sure it is based on the start from
6284 u64 calc_end = extent_map_end(hole_em);
6286 if (calc_end <= start || (hole_em->start > end)) {
6287 free_extent_map(hole_em);
6290 hole_start = max(hole_em->start, start);
6291 hole_len = calc_end - hole_start;
6295 if (hole_em && range_start > hole_start) {
6296 /* our hole starts before our delalloc, so we
6297 * have to return just the parts of the hole
6298 * that go until the delalloc starts
6300 em->len = min(hole_len,
6301 range_start - hole_start);
6302 em->start = hole_start;
6303 em->orig_start = hole_start;
6305 * don't adjust block start at all,
6306 * it is fixed at EXTENT_MAP_HOLE
6308 em->block_start = hole_em->block_start;
6309 em->block_len = hole_len;
6310 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6311 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6313 em->start = range_start;
6315 em->orig_start = range_start;
6316 em->block_start = EXTENT_MAP_DELALLOC;
6317 em->block_len = found;
6319 } else if (hole_em) {
6324 free_extent_map(hole_em);
6326 free_extent_map(em);
6327 return ERR_PTR(err);
6332 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6335 struct btrfs_root *root = BTRFS_I(inode)->root;
6336 struct btrfs_trans_handle *trans;
6337 struct extent_map *em;
6338 struct btrfs_key ins;
6342 trans = btrfs_join_transaction(root);
6344 return ERR_CAST(trans);
6346 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6348 alloc_hint = get_extent_allocation_hint(inode, start, len);
6349 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6350 alloc_hint, &ins, 1);
6356 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6357 ins.offset, ins.offset, ins.offset, 0);
6361 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6362 ins.offset, ins.offset, 0);
6364 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6368 btrfs_end_transaction(trans, root);
6373 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6374 * block must be cow'd
6376 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
6377 struct inode *inode, u64 offset, u64 *len,
6378 u64 *orig_start, u64 *orig_block_len,
6381 struct btrfs_path *path;
6383 struct extent_buffer *leaf;
6384 struct btrfs_root *root = BTRFS_I(inode)->root;
6385 struct btrfs_file_extent_item *fi;
6386 struct btrfs_key key;
6394 path = btrfs_alloc_path();
6398 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6403 slot = path->slots[0];
6406 /* can't find the item, must cow */
6413 leaf = path->nodes[0];
6414 btrfs_item_key_to_cpu(leaf, &key, slot);
6415 if (key.objectid != btrfs_ino(inode) ||
6416 key.type != BTRFS_EXTENT_DATA_KEY) {
6417 /* not our file or wrong item type, must cow */
6421 if (key.offset > offset) {
6422 /* Wrong offset, must cow */
6426 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6427 found_type = btrfs_file_extent_type(leaf, fi);
6428 if (found_type != BTRFS_FILE_EXTENT_REG &&
6429 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6430 /* not a regular extent, must cow */
6433 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6434 backref_offset = btrfs_file_extent_offset(leaf, fi);
6436 *orig_start = key.offset - backref_offset;
6437 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6438 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6440 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6441 if (extent_end < offset + *len) {
6442 /* extent doesn't include our full range, must cow */
6446 if (btrfs_extent_readonly(root, disk_bytenr))
6450 * look for other files referencing this extent, if we
6451 * find any we must cow
6453 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6454 key.offset - backref_offset, disk_bytenr))
6458 * adjust disk_bytenr and num_bytes to cover just the bytes
6459 * in this extent we are about to write. If there
6460 * are any csums in that range we have to cow in order
6461 * to keep the csums correct
6463 disk_bytenr += backref_offset;
6464 disk_bytenr += offset - key.offset;
6465 num_bytes = min(offset + *len, extent_end) - offset;
6466 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6469 * all of the above have passed, it is safe to overwrite this extent
6475 btrfs_free_path(path);
6479 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6480 struct extent_state **cached_state, int writing)
6482 struct btrfs_ordered_extent *ordered;
6486 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6489 * We're concerned with the entire range that we're going to be
6490 * doing DIO to, so we need to make sure theres no ordered
6491 * extents in this range.
6493 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6494 lockend - lockstart + 1);
6497 * We need to make sure there are no buffered pages in this
6498 * range either, we could have raced between the invalidate in
6499 * generic_file_direct_write and locking the extent. The
6500 * invalidate needs to happen so that reads after a write do not
6503 if (!ordered && (!writing ||
6504 !test_range_bit(&BTRFS_I(inode)->io_tree,
6505 lockstart, lockend, EXTENT_UPTODATE, 0,
6509 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6510 cached_state, GFP_NOFS);
6513 btrfs_start_ordered_extent(inode, ordered, 1);
6514 btrfs_put_ordered_extent(ordered);
6516 /* Screw you mmap */
6517 ret = filemap_write_and_wait_range(inode->i_mapping,
6524 * If we found a page that couldn't be invalidated just
6525 * fall back to buffered.
6527 ret = invalidate_inode_pages2_range(inode->i_mapping,
6528 lockstart >> PAGE_CACHE_SHIFT,
6529 lockend >> PAGE_CACHE_SHIFT);
6540 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6541 u64 len, u64 orig_start,
6542 u64 block_start, u64 block_len,
6543 u64 orig_block_len, u64 ram_bytes,
6546 struct extent_map_tree *em_tree;
6547 struct extent_map *em;
6548 struct btrfs_root *root = BTRFS_I(inode)->root;
6551 em_tree = &BTRFS_I(inode)->extent_tree;
6552 em = alloc_extent_map();
6554 return ERR_PTR(-ENOMEM);
6557 em->orig_start = orig_start;
6558 em->mod_start = start;
6561 em->block_len = block_len;
6562 em->block_start = block_start;
6563 em->bdev = root->fs_info->fs_devices->latest_bdev;
6564 em->orig_block_len = orig_block_len;
6565 em->ram_bytes = ram_bytes;
6566 em->generation = -1;
6567 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6568 if (type == BTRFS_ORDERED_PREALLOC)
6569 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6572 btrfs_drop_extent_cache(inode, em->start,
6573 em->start + em->len - 1, 0);
6574 write_lock(&em_tree->lock);
6575 ret = add_extent_mapping(em_tree, em, 1);
6576 write_unlock(&em_tree->lock);
6577 } while (ret == -EEXIST);
6580 free_extent_map(em);
6581 return ERR_PTR(ret);
6588 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6589 struct buffer_head *bh_result, int create)
6591 struct extent_map *em;
6592 struct btrfs_root *root = BTRFS_I(inode)->root;
6593 struct extent_state *cached_state = NULL;
6594 u64 start = iblock << inode->i_blkbits;
6595 u64 lockstart, lockend;
6596 u64 len = bh_result->b_size;
6597 struct btrfs_trans_handle *trans;
6598 int unlock_bits = EXTENT_LOCKED;
6602 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6604 len = min_t(u64, len, root->sectorsize);
6607 lockend = start + len - 1;
6610 * If this errors out it's because we couldn't invalidate pagecache for
6611 * this range and we need to fallback to buffered.
6613 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6616 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6623 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6624 * io. INLINE is special, and we could probably kludge it in here, but
6625 * it's still buffered so for safety lets just fall back to the generic
6628 * For COMPRESSED we _have_ to read the entire extent in so we can
6629 * decompress it, so there will be buffering required no matter what we
6630 * do, so go ahead and fallback to buffered.
6632 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6633 * to buffered IO. Don't blame me, this is the price we pay for using
6636 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6637 em->block_start == EXTENT_MAP_INLINE) {
6638 free_extent_map(em);
6643 /* Just a good old fashioned hole, return */
6644 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6645 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6646 free_extent_map(em);
6651 * We don't allocate a new extent in the following cases
6653 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6655 * 2) The extent is marked as PREALLOC. We're good to go here and can
6656 * just use the extent.
6660 len = min(len, em->len - (start - em->start));
6661 lockstart = start + len;
6665 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6666 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6667 em->block_start != EXTENT_MAP_HOLE)) {
6670 u64 block_start, orig_start, orig_block_len, ram_bytes;
6672 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6673 type = BTRFS_ORDERED_PREALLOC;
6675 type = BTRFS_ORDERED_NOCOW;
6676 len = min(len, em->len - (start - em->start));
6677 block_start = em->block_start + (start - em->start);
6680 * we're not going to log anything, but we do need
6681 * to make sure the current transaction stays open
6682 * while we look for nocow cross refs
6684 trans = btrfs_join_transaction(root);
6688 if (can_nocow_odirect(trans, inode, start, &len, &orig_start,
6689 &orig_block_len, &ram_bytes) == 1) {
6690 if (type == BTRFS_ORDERED_PREALLOC) {
6691 free_extent_map(em);
6692 em = create_pinned_em(inode, start, len,
6698 btrfs_end_transaction(trans, root);
6703 ret = btrfs_add_ordered_extent_dio(inode, start,
6704 block_start, len, len, type);
6705 btrfs_end_transaction(trans, root);
6707 free_extent_map(em);
6712 btrfs_end_transaction(trans, root);
6716 * this will cow the extent, reset the len in case we changed
6719 len = bh_result->b_size;
6720 free_extent_map(em);
6721 em = btrfs_new_extent_direct(inode, start, len);
6726 len = min(len, em->len - (start - em->start));
6728 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6730 bh_result->b_size = len;
6731 bh_result->b_bdev = em->bdev;
6732 set_buffer_mapped(bh_result);
6734 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6735 set_buffer_new(bh_result);
6738 * Need to update the i_size under the extent lock so buffered
6739 * readers will get the updated i_size when we unlock.
6741 if (start + len > i_size_read(inode))
6742 i_size_write(inode, start + len);
6744 spin_lock(&BTRFS_I(inode)->lock);
6745 BTRFS_I(inode)->outstanding_extents++;
6746 spin_unlock(&BTRFS_I(inode)->lock);
6748 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6749 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6750 &cached_state, GFP_NOFS);
6755 * In the case of write we need to clear and unlock the entire range,
6756 * in the case of read we need to unlock only the end area that we
6757 * aren't using if there is any left over space.
6759 if (lockstart < lockend) {
6760 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6761 lockend, unlock_bits, 1, 0,
6762 &cached_state, GFP_NOFS);
6764 free_extent_state(cached_state);
6767 free_extent_map(em);
6772 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6773 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6777 struct btrfs_dio_private {
6778 struct inode *inode;
6784 /* number of bios pending for this dio */
6785 atomic_t pending_bios;
6790 /* orig_bio is our btrfs_io_bio */
6791 struct bio *orig_bio;
6793 /* dio_bio came from fs/direct-io.c */
6794 struct bio *dio_bio;
6797 static void btrfs_endio_direct_read(struct bio *bio, int err)
6799 struct btrfs_dio_private *dip = bio->bi_private;
6800 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6801 struct bio_vec *bvec = bio->bi_io_vec;
6802 struct inode *inode = dip->inode;
6803 struct btrfs_root *root = BTRFS_I(inode)->root;
6804 struct bio *dio_bio;
6807 start = dip->logical_offset;
6809 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6810 struct page *page = bvec->bv_page;
6813 u64 private = ~(u32)0;
6814 unsigned long flags;
6816 if (get_state_private(&BTRFS_I(inode)->io_tree,
6819 local_irq_save(flags);
6820 kaddr = kmap_atomic(page);
6821 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6822 csum, bvec->bv_len);
6823 btrfs_csum_final(csum, (char *)&csum);
6824 kunmap_atomic(kaddr);
6825 local_irq_restore(flags);
6827 flush_dcache_page(bvec->bv_page);
6828 if (csum != private) {
6830 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u private %u",
6831 (unsigned long long)btrfs_ino(inode),
6832 (unsigned long long)start,
6833 csum, (unsigned)private);
6838 start += bvec->bv_len;
6840 } while (bvec <= bvec_end);
6842 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6843 dip->logical_offset + dip->bytes - 1);
6844 dio_bio = dip->dio_bio;
6848 /* If we had a csum failure make sure to clear the uptodate flag */
6850 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6851 dio_end_io(dio_bio, err);
6855 static void btrfs_endio_direct_write(struct bio *bio, int err)
6857 struct btrfs_dio_private *dip = bio->bi_private;
6858 struct inode *inode = dip->inode;
6859 struct btrfs_root *root = BTRFS_I(inode)->root;
6860 struct btrfs_ordered_extent *ordered = NULL;
6861 u64 ordered_offset = dip->logical_offset;
6862 u64 ordered_bytes = dip->bytes;
6863 struct bio *dio_bio;
6869 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6871 ordered_bytes, !err);
6875 ordered->work.func = finish_ordered_fn;
6876 ordered->work.flags = 0;
6877 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6881 * our bio might span multiple ordered extents. If we haven't
6882 * completed the accounting for the whole dio, go back and try again
6884 if (ordered_offset < dip->logical_offset + dip->bytes) {
6885 ordered_bytes = dip->logical_offset + dip->bytes -
6891 dio_bio = dip->dio_bio;
6895 /* If we had an error make sure to clear the uptodate flag */
6897 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6898 dio_end_io(dio_bio, err);
6902 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6903 struct bio *bio, int mirror_num,
6904 unsigned long bio_flags, u64 offset)
6907 struct btrfs_root *root = BTRFS_I(inode)->root;
6908 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6909 BUG_ON(ret); /* -ENOMEM */
6913 static void btrfs_end_dio_bio(struct bio *bio, int err)
6915 struct btrfs_dio_private *dip = bio->bi_private;
6918 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6919 "sector %#Lx len %u err no %d\n",
6920 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6921 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6925 * before atomic variable goto zero, we must make sure
6926 * dip->errors is perceived to be set.
6928 smp_mb__before_atomic_dec();
6931 /* if there are more bios still pending for this dio, just exit */
6932 if (!atomic_dec_and_test(&dip->pending_bios))
6936 bio_io_error(dip->orig_bio);
6938 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
6939 bio_endio(dip->orig_bio, 0);
6945 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6946 u64 first_sector, gfp_t gfp_flags)
6948 int nr_vecs = bio_get_nr_vecs(bdev);
6949 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6952 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6953 int rw, u64 file_offset, int skip_sum,
6956 int write = rw & REQ_WRITE;
6957 struct btrfs_root *root = BTRFS_I(inode)->root;
6961 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6966 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6974 if (write && async_submit) {
6975 ret = btrfs_wq_submit_bio(root->fs_info,
6976 inode, rw, bio, 0, 0,
6978 __btrfs_submit_bio_start_direct_io,
6979 __btrfs_submit_bio_done);
6983 * If we aren't doing async submit, calculate the csum of the
6986 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6989 } else if (!skip_sum) {
6990 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
6996 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7002 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7005 struct inode *inode = dip->inode;
7006 struct btrfs_root *root = BTRFS_I(inode)->root;
7008 struct bio *orig_bio = dip->orig_bio;
7009 struct bio_vec *bvec = orig_bio->bi_io_vec;
7010 u64 start_sector = orig_bio->bi_sector;
7011 u64 file_offset = dip->logical_offset;
7016 int async_submit = 0;
7018 map_length = orig_bio->bi_size;
7019 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7020 &map_length, NULL, 0);
7025 if (map_length >= orig_bio->bi_size) {
7030 /* async crcs make it difficult to collect full stripe writes. */
7031 if (btrfs_get_alloc_profile(root, 1) &
7032 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7037 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7040 bio->bi_private = dip;
7041 bio->bi_end_io = btrfs_end_dio_bio;
7042 atomic_inc(&dip->pending_bios);
7044 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7045 if (unlikely(map_length < submit_len + bvec->bv_len ||
7046 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7047 bvec->bv_offset) < bvec->bv_len)) {
7049 * inc the count before we submit the bio so
7050 * we know the end IO handler won't happen before
7051 * we inc the count. Otherwise, the dip might get freed
7052 * before we're done setting it up
7054 atomic_inc(&dip->pending_bios);
7055 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7056 file_offset, skip_sum,
7060 atomic_dec(&dip->pending_bios);
7064 start_sector += submit_len >> 9;
7065 file_offset += submit_len;
7070 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7071 start_sector, GFP_NOFS);
7074 bio->bi_private = dip;
7075 bio->bi_end_io = btrfs_end_dio_bio;
7077 map_length = orig_bio->bi_size;
7078 ret = btrfs_map_block(root->fs_info, rw,
7080 &map_length, NULL, 0);
7086 submit_len += bvec->bv_len;
7093 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7102 * before atomic variable goto zero, we must
7103 * make sure dip->errors is perceived to be set.
7105 smp_mb__before_atomic_dec();
7106 if (atomic_dec_and_test(&dip->pending_bios))
7107 bio_io_error(dip->orig_bio);
7109 /* bio_end_io() will handle error, so we needn't return it */
7113 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7114 struct inode *inode, loff_t file_offset)
7116 struct btrfs_root *root = BTRFS_I(inode)->root;
7117 struct btrfs_dio_private *dip;
7118 struct bio_vec *bvec = dio_bio->bi_io_vec;
7121 int write = rw & REQ_WRITE;
7124 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7126 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7133 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7139 dip->private = dio_bio->bi_private;
7140 io_bio->bi_private = dio_bio->bi_private;
7142 dip->logical_offset = file_offset;
7146 dip->bytes += bvec->bv_len;
7148 } while (bvec <= (dio_bio->bi_io_vec + dio_bio->bi_vcnt - 1));
7150 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7151 io_bio->bi_private = dip;
7153 dip->orig_bio = io_bio;
7154 dip->dio_bio = dio_bio;
7155 atomic_set(&dip->pending_bios, 0);
7158 io_bio->bi_end_io = btrfs_endio_direct_write;
7160 io_bio->bi_end_io = btrfs_endio_direct_read;
7162 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7171 * If this is a write, we need to clean up the reserved space and kill
7172 * the ordered extent.
7175 struct btrfs_ordered_extent *ordered;
7176 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7177 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7178 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7179 btrfs_free_reserved_extent(root, ordered->start,
7181 btrfs_put_ordered_extent(ordered);
7182 btrfs_put_ordered_extent(ordered);
7184 bio_endio(dio_bio, ret);
7187 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7188 const struct iovec *iov, loff_t offset,
7189 unsigned long nr_segs)
7195 unsigned blocksize_mask = root->sectorsize - 1;
7196 ssize_t retval = -EINVAL;
7197 loff_t end = offset;
7199 if (offset & blocksize_mask)
7202 /* Check the memory alignment. Blocks cannot straddle pages */
7203 for (seg = 0; seg < nr_segs; seg++) {
7204 addr = (unsigned long)iov[seg].iov_base;
7205 size = iov[seg].iov_len;
7207 if ((addr & blocksize_mask) || (size & blocksize_mask))
7210 /* If this is a write we don't need to check anymore */
7215 * Check to make sure we don't have duplicate iov_base's in this
7216 * iovec, if so return EINVAL, otherwise we'll get csum errors
7217 * when reading back.
7219 for (i = seg + 1; i < nr_segs; i++) {
7220 if (iov[seg].iov_base == iov[i].iov_base)
7229 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7230 const struct iovec *iov, loff_t offset,
7231 unsigned long nr_segs)
7233 struct file *file = iocb->ki_filp;
7234 struct inode *inode = file->f_mapping->host;
7238 bool relock = false;
7241 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7245 atomic_inc(&inode->i_dio_count);
7246 smp_mb__after_atomic_inc();
7249 count = iov_length(iov, nr_segs);
7251 * If the write DIO is beyond the EOF, we need update
7252 * the isize, but it is protected by i_mutex. So we can
7253 * not unlock the i_mutex at this case.
7255 if (offset + count <= inode->i_size) {
7256 mutex_unlock(&inode->i_mutex);
7259 ret = btrfs_delalloc_reserve_space(inode, count);
7262 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7263 &BTRFS_I(inode)->runtime_flags))) {
7264 inode_dio_done(inode);
7265 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7269 ret = __blockdev_direct_IO(rw, iocb, inode,
7270 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7271 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7272 btrfs_submit_direct, flags);
7274 if (ret < 0 && ret != -EIOCBQUEUED)
7275 btrfs_delalloc_release_space(inode, count);
7276 else if (ret >= 0 && (size_t)ret < count)
7277 btrfs_delalloc_release_space(inode,
7278 count - (size_t)ret);
7280 btrfs_delalloc_release_metadata(inode, 0);
7284 inode_dio_done(inode);
7286 mutex_lock(&inode->i_mutex);
7291 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7293 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7294 __u64 start, __u64 len)
7298 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7302 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7305 int btrfs_readpage(struct file *file, struct page *page)
7307 struct extent_io_tree *tree;
7308 tree = &BTRFS_I(page->mapping->host)->io_tree;
7309 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7312 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7314 struct extent_io_tree *tree;
7317 if (current->flags & PF_MEMALLOC) {
7318 redirty_page_for_writepage(wbc, page);
7322 tree = &BTRFS_I(page->mapping->host)->io_tree;
7323 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7326 static int btrfs_writepages(struct address_space *mapping,
7327 struct writeback_control *wbc)
7329 struct extent_io_tree *tree;
7331 tree = &BTRFS_I(mapping->host)->io_tree;
7332 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7336 btrfs_readpages(struct file *file, struct address_space *mapping,
7337 struct list_head *pages, unsigned nr_pages)
7339 struct extent_io_tree *tree;
7340 tree = &BTRFS_I(mapping->host)->io_tree;
7341 return extent_readpages(tree, mapping, pages, nr_pages,
7344 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7346 struct extent_io_tree *tree;
7347 struct extent_map_tree *map;
7350 tree = &BTRFS_I(page->mapping->host)->io_tree;
7351 map = &BTRFS_I(page->mapping->host)->extent_tree;
7352 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7354 ClearPagePrivate(page);
7355 set_page_private(page, 0);
7356 page_cache_release(page);
7361 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7363 if (PageWriteback(page) || PageDirty(page))
7365 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7368 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7370 struct inode *inode = page->mapping->host;
7371 struct extent_io_tree *tree;
7372 struct btrfs_ordered_extent *ordered;
7373 struct extent_state *cached_state = NULL;
7374 u64 page_start = page_offset(page);
7375 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7378 * we have the page locked, so new writeback can't start,
7379 * and the dirty bit won't be cleared while we are here.
7381 * Wait for IO on this page so that we can safely clear
7382 * the PagePrivate2 bit and do ordered accounting
7384 wait_on_page_writeback(page);
7386 tree = &BTRFS_I(inode)->io_tree;
7388 btrfs_releasepage(page, GFP_NOFS);
7391 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7392 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7395 * IO on this page will never be started, so we need
7396 * to account for any ordered extents now
7398 clear_extent_bit(tree, page_start, page_end,
7399 EXTENT_DIRTY | EXTENT_DELALLOC |
7400 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7401 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7403 * whoever cleared the private bit is responsible
7404 * for the finish_ordered_io
7406 if (TestClearPagePrivate2(page) &&
7407 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7408 PAGE_CACHE_SIZE, 1)) {
7409 btrfs_finish_ordered_io(ordered);
7411 btrfs_put_ordered_extent(ordered);
7412 cached_state = NULL;
7413 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7415 clear_extent_bit(tree, page_start, page_end,
7416 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7417 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7418 &cached_state, GFP_NOFS);
7419 __btrfs_releasepage(page, GFP_NOFS);
7421 ClearPageChecked(page);
7422 if (PagePrivate(page)) {
7423 ClearPagePrivate(page);
7424 set_page_private(page, 0);
7425 page_cache_release(page);
7430 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7431 * called from a page fault handler when a page is first dirtied. Hence we must
7432 * be careful to check for EOF conditions here. We set the page up correctly
7433 * for a written page which means we get ENOSPC checking when writing into
7434 * holes and correct delalloc and unwritten extent mapping on filesystems that
7435 * support these features.
7437 * We are not allowed to take the i_mutex here so we have to play games to
7438 * protect against truncate races as the page could now be beyond EOF. Because
7439 * vmtruncate() writes the inode size before removing pages, once we have the
7440 * page lock we can determine safely if the page is beyond EOF. If it is not
7441 * beyond EOF, then the page is guaranteed safe against truncation until we
7444 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7446 struct page *page = vmf->page;
7447 struct inode *inode = file_inode(vma->vm_file);
7448 struct btrfs_root *root = BTRFS_I(inode)->root;
7449 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7450 struct btrfs_ordered_extent *ordered;
7451 struct extent_state *cached_state = NULL;
7453 unsigned long zero_start;
7460 sb_start_pagefault(inode->i_sb);
7461 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7463 ret = file_update_time(vma->vm_file);
7469 else /* -ENOSPC, -EIO, etc */
7470 ret = VM_FAULT_SIGBUS;
7476 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7479 size = i_size_read(inode);
7480 page_start = page_offset(page);
7481 page_end = page_start + PAGE_CACHE_SIZE - 1;
7483 if ((page->mapping != inode->i_mapping) ||
7484 (page_start >= size)) {
7485 /* page got truncated out from underneath us */
7488 wait_on_page_writeback(page);
7490 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7491 set_page_extent_mapped(page);
7494 * we can't set the delalloc bits if there are pending ordered
7495 * extents. Drop our locks and wait for them to finish
7497 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7499 unlock_extent_cached(io_tree, page_start, page_end,
7500 &cached_state, GFP_NOFS);
7502 btrfs_start_ordered_extent(inode, ordered, 1);
7503 btrfs_put_ordered_extent(ordered);
7508 * XXX - page_mkwrite gets called every time the page is dirtied, even
7509 * if it was already dirty, so for space accounting reasons we need to
7510 * clear any delalloc bits for the range we are fixing to save. There
7511 * is probably a better way to do this, but for now keep consistent with
7512 * prepare_pages in the normal write path.
7514 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7515 EXTENT_DIRTY | EXTENT_DELALLOC |
7516 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7517 0, 0, &cached_state, GFP_NOFS);
7519 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7522 unlock_extent_cached(io_tree, page_start, page_end,
7523 &cached_state, GFP_NOFS);
7524 ret = VM_FAULT_SIGBUS;
7529 /* page is wholly or partially inside EOF */
7530 if (page_start + PAGE_CACHE_SIZE > size)
7531 zero_start = size & ~PAGE_CACHE_MASK;
7533 zero_start = PAGE_CACHE_SIZE;
7535 if (zero_start != PAGE_CACHE_SIZE) {
7537 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7538 flush_dcache_page(page);
7541 ClearPageChecked(page);
7542 set_page_dirty(page);
7543 SetPageUptodate(page);
7545 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7546 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7547 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7549 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7553 sb_end_pagefault(inode->i_sb);
7554 return VM_FAULT_LOCKED;
7558 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7560 sb_end_pagefault(inode->i_sb);
7564 static int btrfs_truncate(struct inode *inode)
7566 struct btrfs_root *root = BTRFS_I(inode)->root;
7567 struct btrfs_block_rsv *rsv;
7570 struct btrfs_trans_handle *trans;
7571 u64 mask = root->sectorsize - 1;
7572 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7574 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
7578 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7579 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7582 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7583 * 3 things going on here
7585 * 1) We need to reserve space for our orphan item and the space to
7586 * delete our orphan item. Lord knows we don't want to have a dangling
7587 * orphan item because we didn't reserve space to remove it.
7589 * 2) We need to reserve space to update our inode.
7591 * 3) We need to have something to cache all the space that is going to
7592 * be free'd up by the truncate operation, but also have some slack
7593 * space reserved in case it uses space during the truncate (thank you
7594 * very much snapshotting).
7596 * And we need these to all be seperate. The fact is we can use alot of
7597 * space doing the truncate, and we have no earthly idea how much space
7598 * we will use, so we need the truncate reservation to be seperate so it
7599 * doesn't end up using space reserved for updating the inode or
7600 * removing the orphan item. We also need to be able to stop the
7601 * transaction and start a new one, which means we need to be able to
7602 * update the inode several times, and we have no idea of knowing how
7603 * many times that will be, so we can't just reserve 1 item for the
7604 * entirety of the opration, so that has to be done seperately as well.
7605 * Then there is the orphan item, which does indeed need to be held on
7606 * to for the whole operation, and we need nobody to touch this reserved
7607 * space except the orphan code.
7609 * So that leaves us with
7611 * 1) root->orphan_block_rsv - for the orphan deletion.
7612 * 2) rsv - for the truncate reservation, which we will steal from the
7613 * transaction reservation.
7614 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7615 * updating the inode.
7617 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7620 rsv->size = min_size;
7624 * 1 for the truncate slack space
7625 * 1 for updating the inode.
7627 trans = btrfs_start_transaction(root, 2);
7628 if (IS_ERR(trans)) {
7629 err = PTR_ERR(trans);
7633 /* Migrate the slack space for the truncate to our reserve */
7634 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7639 * setattr is responsible for setting the ordered_data_close flag,
7640 * but that is only tested during the last file release. That
7641 * could happen well after the next commit, leaving a great big
7642 * window where new writes may get lost if someone chooses to write
7643 * to this file after truncating to zero
7645 * The inode doesn't have any dirty data here, and so if we commit
7646 * this is a noop. If someone immediately starts writing to the inode
7647 * it is very likely we'll catch some of their writes in this
7648 * transaction, and the commit will find this file on the ordered
7649 * data list with good things to send down.
7651 * This is a best effort solution, there is still a window where
7652 * using truncate to replace the contents of the file will
7653 * end up with a zero length file after a crash.
7655 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7656 &BTRFS_I(inode)->runtime_flags))
7657 btrfs_add_ordered_operation(trans, root, inode);
7660 * So if we truncate and then write and fsync we normally would just
7661 * write the extents that changed, which is a problem if we need to
7662 * first truncate that entire inode. So set this flag so we write out
7663 * all of the extents in the inode to the sync log so we're completely
7666 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7667 trans->block_rsv = rsv;
7670 ret = btrfs_truncate_inode_items(trans, root, inode,
7672 BTRFS_EXTENT_DATA_KEY);
7673 if (ret != -ENOSPC) {
7678 trans->block_rsv = &root->fs_info->trans_block_rsv;
7679 ret = btrfs_update_inode(trans, root, inode);
7685 btrfs_end_transaction(trans, root);
7686 btrfs_btree_balance_dirty(root);
7688 trans = btrfs_start_transaction(root, 2);
7689 if (IS_ERR(trans)) {
7690 ret = err = PTR_ERR(trans);
7695 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7697 BUG_ON(ret); /* shouldn't happen */
7698 trans->block_rsv = rsv;
7701 if (ret == 0 && inode->i_nlink > 0) {
7702 trans->block_rsv = root->orphan_block_rsv;
7703 ret = btrfs_orphan_del(trans, inode);
7709 trans->block_rsv = &root->fs_info->trans_block_rsv;
7710 ret = btrfs_update_inode(trans, root, inode);
7714 ret = btrfs_end_transaction(trans, root);
7715 btrfs_btree_balance_dirty(root);
7719 btrfs_free_block_rsv(root, rsv);
7728 * create a new subvolume directory/inode (helper for the ioctl).
7730 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7731 struct btrfs_root *new_root, u64 new_dirid)
7733 struct inode *inode;
7737 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7738 new_dirid, new_dirid,
7739 S_IFDIR | (~current_umask() & S_IRWXUGO),
7742 return PTR_ERR(inode);
7743 inode->i_op = &btrfs_dir_inode_operations;
7744 inode->i_fop = &btrfs_dir_file_operations;
7746 set_nlink(inode, 1);
7747 btrfs_i_size_write(inode, 0);
7749 err = btrfs_update_inode(trans, new_root, inode);
7755 struct inode *btrfs_alloc_inode(struct super_block *sb)
7757 struct btrfs_inode *ei;
7758 struct inode *inode;
7760 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7767 ei->last_sub_trans = 0;
7768 ei->logged_trans = 0;
7769 ei->delalloc_bytes = 0;
7770 ei->disk_i_size = 0;
7773 ei->index_cnt = (u64)-1;
7774 ei->last_unlink_trans = 0;
7775 ei->last_log_commit = 0;
7777 spin_lock_init(&ei->lock);
7778 ei->outstanding_extents = 0;
7779 ei->reserved_extents = 0;
7781 ei->runtime_flags = 0;
7782 ei->force_compress = BTRFS_COMPRESS_NONE;
7784 ei->delayed_node = NULL;
7786 inode = &ei->vfs_inode;
7787 extent_map_tree_init(&ei->extent_tree);
7788 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7789 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7790 ei->io_tree.track_uptodate = 1;
7791 ei->io_failure_tree.track_uptodate = 1;
7792 atomic_set(&ei->sync_writers, 0);
7793 mutex_init(&ei->log_mutex);
7794 mutex_init(&ei->delalloc_mutex);
7795 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7796 INIT_LIST_HEAD(&ei->delalloc_inodes);
7797 INIT_LIST_HEAD(&ei->ordered_operations);
7798 RB_CLEAR_NODE(&ei->rb_node);
7803 static void btrfs_i_callback(struct rcu_head *head)
7805 struct inode *inode = container_of(head, struct inode, i_rcu);
7806 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7809 void btrfs_destroy_inode(struct inode *inode)
7811 struct btrfs_ordered_extent *ordered;
7812 struct btrfs_root *root = BTRFS_I(inode)->root;
7814 WARN_ON(!hlist_empty(&inode->i_dentry));
7815 WARN_ON(inode->i_data.nrpages);
7816 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7817 WARN_ON(BTRFS_I(inode)->reserved_extents);
7818 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7819 WARN_ON(BTRFS_I(inode)->csum_bytes);
7822 * This can happen where we create an inode, but somebody else also
7823 * created the same inode and we need to destroy the one we already
7830 * Make sure we're properly removed from the ordered operation
7834 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7835 spin_lock(&root->fs_info->ordered_root_lock);
7836 list_del_init(&BTRFS_I(inode)->ordered_operations);
7837 spin_unlock(&root->fs_info->ordered_root_lock);
7840 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7841 &BTRFS_I(inode)->runtime_flags)) {
7842 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7843 (unsigned long long)btrfs_ino(inode));
7844 atomic_dec(&root->orphan_inodes);
7848 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7852 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7853 (unsigned long long)ordered->file_offset,
7854 (unsigned long long)ordered->len);
7855 btrfs_remove_ordered_extent(inode, ordered);
7856 btrfs_put_ordered_extent(ordered);
7857 btrfs_put_ordered_extent(ordered);
7860 inode_tree_del(inode);
7861 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7863 call_rcu(&inode->i_rcu, btrfs_i_callback);
7866 int btrfs_drop_inode(struct inode *inode)
7868 struct btrfs_root *root = BTRFS_I(inode)->root;
7873 /* the snap/subvol tree is on deleting */
7874 if (btrfs_root_refs(&root->root_item) == 0 &&
7875 root != root->fs_info->tree_root)
7878 return generic_drop_inode(inode);
7881 static void init_once(void *foo)
7883 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7885 inode_init_once(&ei->vfs_inode);
7888 void btrfs_destroy_cachep(void)
7891 * Make sure all delayed rcu free inodes are flushed before we
7895 if (btrfs_inode_cachep)
7896 kmem_cache_destroy(btrfs_inode_cachep);
7897 if (btrfs_trans_handle_cachep)
7898 kmem_cache_destroy(btrfs_trans_handle_cachep);
7899 if (btrfs_transaction_cachep)
7900 kmem_cache_destroy(btrfs_transaction_cachep);
7901 if (btrfs_path_cachep)
7902 kmem_cache_destroy(btrfs_path_cachep);
7903 if (btrfs_free_space_cachep)
7904 kmem_cache_destroy(btrfs_free_space_cachep);
7905 if (btrfs_delalloc_work_cachep)
7906 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7909 int btrfs_init_cachep(void)
7911 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7912 sizeof(struct btrfs_inode), 0,
7913 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7914 if (!btrfs_inode_cachep)
7917 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7918 sizeof(struct btrfs_trans_handle), 0,
7919 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7920 if (!btrfs_trans_handle_cachep)
7923 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7924 sizeof(struct btrfs_transaction), 0,
7925 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7926 if (!btrfs_transaction_cachep)
7929 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7930 sizeof(struct btrfs_path), 0,
7931 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7932 if (!btrfs_path_cachep)
7935 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7936 sizeof(struct btrfs_free_space), 0,
7937 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7938 if (!btrfs_free_space_cachep)
7941 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7942 sizeof(struct btrfs_delalloc_work), 0,
7943 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7945 if (!btrfs_delalloc_work_cachep)
7950 btrfs_destroy_cachep();
7954 static int btrfs_getattr(struct vfsmount *mnt,
7955 struct dentry *dentry, struct kstat *stat)
7958 struct inode *inode = dentry->d_inode;
7959 u32 blocksize = inode->i_sb->s_blocksize;
7961 generic_fillattr(inode, stat);
7962 stat->dev = BTRFS_I(inode)->root->anon_dev;
7963 stat->blksize = PAGE_CACHE_SIZE;
7965 spin_lock(&BTRFS_I(inode)->lock);
7966 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
7967 spin_unlock(&BTRFS_I(inode)->lock);
7968 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7969 ALIGN(delalloc_bytes, blocksize)) >> 9;
7973 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7974 struct inode *new_dir, struct dentry *new_dentry)
7976 struct btrfs_trans_handle *trans;
7977 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7978 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7979 struct inode *new_inode = new_dentry->d_inode;
7980 struct inode *old_inode = old_dentry->d_inode;
7981 struct timespec ctime = CURRENT_TIME;
7985 u64 old_ino = btrfs_ino(old_inode);
7987 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7990 /* we only allow rename subvolume link between subvolumes */
7991 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7994 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7995 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7998 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7999 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8003 /* check for collisions, even if the name isn't there */
8004 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
8005 new_dentry->d_name.name,
8006 new_dentry->d_name.len);
8009 if (ret == -EEXIST) {
8011 * eexist without a new_inode */
8017 /* maybe -EOVERFLOW */
8024 * we're using rename to replace one file with another.
8025 * and the replacement file is large. Start IO on it now so
8026 * we don't add too much work to the end of the transaction
8028 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8029 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8030 filemap_flush(old_inode->i_mapping);
8032 /* close the racy window with snapshot create/destroy ioctl */
8033 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8034 down_read(&root->fs_info->subvol_sem);
8036 * We want to reserve the absolute worst case amount of items. So if
8037 * both inodes are subvols and we need to unlink them then that would
8038 * require 4 item modifications, but if they are both normal inodes it
8039 * would require 5 item modifications, so we'll assume their normal
8040 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8041 * should cover the worst case number of items we'll modify.
8043 trans = btrfs_start_transaction(root, 11);
8044 if (IS_ERR(trans)) {
8045 ret = PTR_ERR(trans);
8050 btrfs_record_root_in_trans(trans, dest);
8052 ret = btrfs_set_inode_index(new_dir, &index);
8056 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8057 /* force full log commit if subvolume involved. */
8058 root->fs_info->last_trans_log_full_commit = trans->transid;
8060 ret = btrfs_insert_inode_ref(trans, dest,
8061 new_dentry->d_name.name,
8062 new_dentry->d_name.len,
8064 btrfs_ino(new_dir), index);
8068 * this is an ugly little race, but the rename is required
8069 * to make sure that if we crash, the inode is either at the
8070 * old name or the new one. pinning the log transaction lets
8071 * us make sure we don't allow a log commit to come in after
8072 * we unlink the name but before we add the new name back in.
8074 btrfs_pin_log_trans(root);
8077 * make sure the inode gets flushed if it is replacing
8080 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8081 btrfs_add_ordered_operation(trans, root, old_inode);
8083 inode_inc_iversion(old_dir);
8084 inode_inc_iversion(new_dir);
8085 inode_inc_iversion(old_inode);
8086 old_dir->i_ctime = old_dir->i_mtime = ctime;
8087 new_dir->i_ctime = new_dir->i_mtime = ctime;
8088 old_inode->i_ctime = ctime;
8090 if (old_dentry->d_parent != new_dentry->d_parent)
8091 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8093 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8094 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8095 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8096 old_dentry->d_name.name,
8097 old_dentry->d_name.len);
8099 ret = __btrfs_unlink_inode(trans, root, old_dir,
8100 old_dentry->d_inode,
8101 old_dentry->d_name.name,
8102 old_dentry->d_name.len);
8104 ret = btrfs_update_inode(trans, root, old_inode);
8107 btrfs_abort_transaction(trans, root, ret);
8112 inode_inc_iversion(new_inode);
8113 new_inode->i_ctime = CURRENT_TIME;
8114 if (unlikely(btrfs_ino(new_inode) ==
8115 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8116 root_objectid = BTRFS_I(new_inode)->location.objectid;
8117 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8119 new_dentry->d_name.name,
8120 new_dentry->d_name.len);
8121 BUG_ON(new_inode->i_nlink == 0);
8123 ret = btrfs_unlink_inode(trans, dest, new_dir,
8124 new_dentry->d_inode,
8125 new_dentry->d_name.name,
8126 new_dentry->d_name.len);
8128 if (!ret && new_inode->i_nlink == 0) {
8129 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8133 btrfs_abort_transaction(trans, root, ret);
8138 ret = btrfs_add_link(trans, new_dir, old_inode,
8139 new_dentry->d_name.name,
8140 new_dentry->d_name.len, 0, index);
8142 btrfs_abort_transaction(trans, root, ret);
8146 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8147 struct dentry *parent = new_dentry->d_parent;
8148 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8149 btrfs_end_log_trans(root);
8152 btrfs_end_transaction(trans, root);
8154 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8155 up_read(&root->fs_info->subvol_sem);
8160 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8162 struct btrfs_delalloc_work *delalloc_work;
8164 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8166 if (delalloc_work->wait)
8167 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8169 filemap_flush(delalloc_work->inode->i_mapping);
8171 if (delalloc_work->delay_iput)
8172 btrfs_add_delayed_iput(delalloc_work->inode);
8174 iput(delalloc_work->inode);
8175 complete(&delalloc_work->completion);
8178 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8179 int wait, int delay_iput)
8181 struct btrfs_delalloc_work *work;
8183 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8187 init_completion(&work->completion);
8188 INIT_LIST_HEAD(&work->list);
8189 work->inode = inode;
8191 work->delay_iput = delay_iput;
8192 work->work.func = btrfs_run_delalloc_work;
8197 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8199 wait_for_completion(&work->completion);
8200 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8204 * some fairly slow code that needs optimization. This walks the list
8205 * of all the inodes with pending delalloc and forces them to disk.
8207 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8209 struct btrfs_inode *binode;
8210 struct inode *inode;
8211 struct btrfs_delalloc_work *work, *next;
8212 struct list_head works;
8213 struct list_head splice;
8216 INIT_LIST_HEAD(&works);
8217 INIT_LIST_HEAD(&splice);
8219 spin_lock(&root->delalloc_lock);
8220 list_splice_init(&root->delalloc_inodes, &splice);
8221 while (!list_empty(&splice)) {
8222 binode = list_entry(splice.next, struct btrfs_inode,
8225 list_move_tail(&binode->delalloc_inodes,
8226 &root->delalloc_inodes);
8227 inode = igrab(&binode->vfs_inode);
8229 cond_resched_lock(&root->delalloc_lock);
8232 spin_unlock(&root->delalloc_lock);
8234 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8235 if (unlikely(!work)) {
8239 list_add_tail(&work->list, &works);
8240 btrfs_queue_worker(&root->fs_info->flush_workers,
8244 spin_lock(&root->delalloc_lock);
8246 spin_unlock(&root->delalloc_lock);
8248 list_for_each_entry_safe(work, next, &works, list) {
8249 list_del_init(&work->list);
8250 btrfs_wait_and_free_delalloc_work(work);
8254 list_for_each_entry_safe(work, next, &works, list) {
8255 list_del_init(&work->list);
8256 btrfs_wait_and_free_delalloc_work(work);
8259 if (!list_empty_careful(&splice)) {
8260 spin_lock(&root->delalloc_lock);
8261 list_splice_tail(&splice, &root->delalloc_inodes);
8262 spin_unlock(&root->delalloc_lock);
8267 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8271 if (root->fs_info->sb->s_flags & MS_RDONLY)
8274 ret = __start_delalloc_inodes(root, delay_iput);
8276 * the filemap_flush will queue IO into the worker threads, but
8277 * we have to make sure the IO is actually started and that
8278 * ordered extents get created before we return
8280 atomic_inc(&root->fs_info->async_submit_draining);
8281 while (atomic_read(&root->fs_info->nr_async_submits) ||
8282 atomic_read(&root->fs_info->async_delalloc_pages)) {
8283 wait_event(root->fs_info->async_submit_wait,
8284 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8285 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8287 atomic_dec(&root->fs_info->async_submit_draining);
8291 int btrfs_start_all_delalloc_inodes(struct btrfs_fs_info *fs_info,
8294 struct btrfs_root *root;
8295 struct list_head splice;
8298 if (fs_info->sb->s_flags & MS_RDONLY)
8301 INIT_LIST_HEAD(&splice);
8303 spin_lock(&fs_info->delalloc_root_lock);
8304 list_splice_init(&fs_info->delalloc_roots, &splice);
8305 while (!list_empty(&splice)) {
8306 root = list_first_entry(&splice, struct btrfs_root,
8308 root = btrfs_grab_fs_root(root);
8310 list_move_tail(&root->delalloc_root,
8311 &fs_info->delalloc_roots);
8312 spin_unlock(&fs_info->delalloc_root_lock);
8314 ret = __start_delalloc_inodes(root, delay_iput);
8315 btrfs_put_fs_root(root);
8319 spin_lock(&fs_info->delalloc_root_lock);
8321 spin_unlock(&fs_info->delalloc_root_lock);
8323 atomic_inc(&fs_info->async_submit_draining);
8324 while (atomic_read(&fs_info->nr_async_submits) ||
8325 atomic_read(&fs_info->async_delalloc_pages)) {
8326 wait_event(fs_info->async_submit_wait,
8327 (atomic_read(&fs_info->nr_async_submits) == 0 &&
8328 atomic_read(&fs_info->async_delalloc_pages) == 0));
8330 atomic_dec(&fs_info->async_submit_draining);
8333 if (!list_empty_careful(&splice)) {
8334 spin_lock(&fs_info->delalloc_root_lock);
8335 list_splice_tail(&splice, &fs_info->delalloc_roots);
8336 spin_unlock(&fs_info->delalloc_root_lock);
8341 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8342 const char *symname)
8344 struct btrfs_trans_handle *trans;
8345 struct btrfs_root *root = BTRFS_I(dir)->root;
8346 struct btrfs_path *path;
8347 struct btrfs_key key;
8348 struct inode *inode = NULL;
8356 struct btrfs_file_extent_item *ei;
8357 struct extent_buffer *leaf;
8359 name_len = strlen(symname) + 1;
8360 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8361 return -ENAMETOOLONG;
8364 * 2 items for inode item and ref
8365 * 2 items for dir items
8366 * 1 item for xattr if selinux is on
8368 trans = btrfs_start_transaction(root, 5);
8370 return PTR_ERR(trans);
8372 err = btrfs_find_free_ino(root, &objectid);
8376 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8377 dentry->d_name.len, btrfs_ino(dir), objectid,
8378 S_IFLNK|S_IRWXUGO, &index);
8379 if (IS_ERR(inode)) {
8380 err = PTR_ERR(inode);
8384 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8391 * If the active LSM wants to access the inode during
8392 * d_instantiate it needs these. Smack checks to see
8393 * if the filesystem supports xattrs by looking at the
8396 inode->i_fop = &btrfs_file_operations;
8397 inode->i_op = &btrfs_file_inode_operations;
8399 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8403 inode->i_mapping->a_ops = &btrfs_aops;
8404 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8405 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8410 path = btrfs_alloc_path();
8416 key.objectid = btrfs_ino(inode);
8418 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8419 datasize = btrfs_file_extent_calc_inline_size(name_len);
8420 err = btrfs_insert_empty_item(trans, root, path, &key,
8424 btrfs_free_path(path);
8427 leaf = path->nodes[0];
8428 ei = btrfs_item_ptr(leaf, path->slots[0],
8429 struct btrfs_file_extent_item);
8430 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8431 btrfs_set_file_extent_type(leaf, ei,
8432 BTRFS_FILE_EXTENT_INLINE);
8433 btrfs_set_file_extent_encryption(leaf, ei, 0);
8434 btrfs_set_file_extent_compression(leaf, ei, 0);
8435 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8436 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8438 ptr = btrfs_file_extent_inline_start(ei);
8439 write_extent_buffer(leaf, symname, ptr, name_len);
8440 btrfs_mark_buffer_dirty(leaf);
8441 btrfs_free_path(path);
8443 inode->i_op = &btrfs_symlink_inode_operations;
8444 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8445 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8446 inode_set_bytes(inode, name_len);
8447 btrfs_i_size_write(inode, name_len - 1);
8448 err = btrfs_update_inode(trans, root, inode);
8454 d_instantiate(dentry, inode);
8455 btrfs_end_transaction(trans, root);
8457 inode_dec_link_count(inode);
8460 btrfs_btree_balance_dirty(root);
8464 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8465 u64 start, u64 num_bytes, u64 min_size,
8466 loff_t actual_len, u64 *alloc_hint,
8467 struct btrfs_trans_handle *trans)
8469 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8470 struct extent_map *em;
8471 struct btrfs_root *root = BTRFS_I(inode)->root;
8472 struct btrfs_key ins;
8473 u64 cur_offset = start;
8477 bool own_trans = true;
8481 while (num_bytes > 0) {
8483 trans = btrfs_start_transaction(root, 3);
8484 if (IS_ERR(trans)) {
8485 ret = PTR_ERR(trans);
8490 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8491 cur_bytes = max(cur_bytes, min_size);
8492 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8493 min_size, 0, *alloc_hint, &ins, 1);
8496 btrfs_end_transaction(trans, root);
8500 ret = insert_reserved_file_extent(trans, inode,
8501 cur_offset, ins.objectid,
8502 ins.offset, ins.offset,
8503 ins.offset, 0, 0, 0,
8504 BTRFS_FILE_EXTENT_PREALLOC);
8506 btrfs_abort_transaction(trans, root, ret);
8508 btrfs_end_transaction(trans, root);
8511 btrfs_drop_extent_cache(inode, cur_offset,
8512 cur_offset + ins.offset -1, 0);
8514 em = alloc_extent_map();
8516 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8517 &BTRFS_I(inode)->runtime_flags);
8521 em->start = cur_offset;
8522 em->orig_start = cur_offset;
8523 em->len = ins.offset;
8524 em->block_start = ins.objectid;
8525 em->block_len = ins.offset;
8526 em->orig_block_len = ins.offset;
8527 em->ram_bytes = ins.offset;
8528 em->bdev = root->fs_info->fs_devices->latest_bdev;
8529 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8530 em->generation = trans->transid;
8533 write_lock(&em_tree->lock);
8534 ret = add_extent_mapping(em_tree, em, 1);
8535 write_unlock(&em_tree->lock);
8538 btrfs_drop_extent_cache(inode, cur_offset,
8539 cur_offset + ins.offset - 1,
8542 free_extent_map(em);
8544 num_bytes -= ins.offset;
8545 cur_offset += ins.offset;
8546 *alloc_hint = ins.objectid + ins.offset;
8548 inode_inc_iversion(inode);
8549 inode->i_ctime = CURRENT_TIME;
8550 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8551 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8552 (actual_len > inode->i_size) &&
8553 (cur_offset > inode->i_size)) {
8554 if (cur_offset > actual_len)
8555 i_size = actual_len;
8557 i_size = cur_offset;
8558 i_size_write(inode, i_size);
8559 btrfs_ordered_update_i_size(inode, i_size, NULL);
8562 ret = btrfs_update_inode(trans, root, inode);
8565 btrfs_abort_transaction(trans, root, ret);
8567 btrfs_end_transaction(trans, root);
8572 btrfs_end_transaction(trans, root);
8577 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8578 u64 start, u64 num_bytes, u64 min_size,
8579 loff_t actual_len, u64 *alloc_hint)
8581 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8582 min_size, actual_len, alloc_hint,
8586 int btrfs_prealloc_file_range_trans(struct inode *inode,
8587 struct btrfs_trans_handle *trans, int mode,
8588 u64 start, u64 num_bytes, u64 min_size,
8589 loff_t actual_len, u64 *alloc_hint)
8591 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8592 min_size, actual_len, alloc_hint, trans);
8595 static int btrfs_set_page_dirty(struct page *page)
8597 return __set_page_dirty_nobuffers(page);
8600 static int btrfs_permission(struct inode *inode, int mask)
8602 struct btrfs_root *root = BTRFS_I(inode)->root;
8603 umode_t mode = inode->i_mode;
8605 if (mask & MAY_WRITE &&
8606 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8607 if (btrfs_root_readonly(root))
8609 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8612 return generic_permission(inode, mask);
8615 static const struct inode_operations btrfs_dir_inode_operations = {
8616 .getattr = btrfs_getattr,
8617 .lookup = btrfs_lookup,
8618 .create = btrfs_create,
8619 .unlink = btrfs_unlink,
8621 .mkdir = btrfs_mkdir,
8622 .rmdir = btrfs_rmdir,
8623 .rename = btrfs_rename,
8624 .symlink = btrfs_symlink,
8625 .setattr = btrfs_setattr,
8626 .mknod = btrfs_mknod,
8627 .setxattr = btrfs_setxattr,
8628 .getxattr = btrfs_getxattr,
8629 .listxattr = btrfs_listxattr,
8630 .removexattr = btrfs_removexattr,
8631 .permission = btrfs_permission,
8632 .get_acl = btrfs_get_acl,
8634 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8635 .lookup = btrfs_lookup,
8636 .permission = btrfs_permission,
8637 .get_acl = btrfs_get_acl,
8640 static const struct file_operations btrfs_dir_file_operations = {
8641 .llseek = generic_file_llseek,
8642 .read = generic_read_dir,
8643 .readdir = btrfs_real_readdir,
8644 .unlocked_ioctl = btrfs_ioctl,
8645 #ifdef CONFIG_COMPAT
8646 .compat_ioctl = btrfs_ioctl,
8648 .release = btrfs_release_file,
8649 .fsync = btrfs_sync_file,
8652 static struct extent_io_ops btrfs_extent_io_ops = {
8653 .fill_delalloc = run_delalloc_range,
8654 .submit_bio_hook = btrfs_submit_bio_hook,
8655 .merge_bio_hook = btrfs_merge_bio_hook,
8656 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8657 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8658 .writepage_start_hook = btrfs_writepage_start_hook,
8659 .set_bit_hook = btrfs_set_bit_hook,
8660 .clear_bit_hook = btrfs_clear_bit_hook,
8661 .merge_extent_hook = btrfs_merge_extent_hook,
8662 .split_extent_hook = btrfs_split_extent_hook,
8666 * btrfs doesn't support the bmap operation because swapfiles
8667 * use bmap to make a mapping of extents in the file. They assume
8668 * these extents won't change over the life of the file and they
8669 * use the bmap result to do IO directly to the drive.
8671 * the btrfs bmap call would return logical addresses that aren't
8672 * suitable for IO and they also will change frequently as COW
8673 * operations happen. So, swapfile + btrfs == corruption.
8675 * For now we're avoiding this by dropping bmap.
8677 static const struct address_space_operations btrfs_aops = {
8678 .readpage = btrfs_readpage,
8679 .writepage = btrfs_writepage,
8680 .writepages = btrfs_writepages,
8681 .readpages = btrfs_readpages,
8682 .direct_IO = btrfs_direct_IO,
8683 .invalidatepage = btrfs_invalidatepage,
8684 .releasepage = btrfs_releasepage,
8685 .set_page_dirty = btrfs_set_page_dirty,
8686 .error_remove_page = generic_error_remove_page,
8689 static const struct address_space_operations btrfs_symlink_aops = {
8690 .readpage = btrfs_readpage,
8691 .writepage = btrfs_writepage,
8692 .invalidatepage = btrfs_invalidatepage,
8693 .releasepage = btrfs_releasepage,
8696 static const struct inode_operations btrfs_file_inode_operations = {
8697 .getattr = btrfs_getattr,
8698 .setattr = btrfs_setattr,
8699 .setxattr = btrfs_setxattr,
8700 .getxattr = btrfs_getxattr,
8701 .listxattr = btrfs_listxattr,
8702 .removexattr = btrfs_removexattr,
8703 .permission = btrfs_permission,
8704 .fiemap = btrfs_fiemap,
8705 .get_acl = btrfs_get_acl,
8706 .update_time = btrfs_update_time,
8708 static const struct inode_operations btrfs_special_inode_operations = {
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,
8719 static const struct inode_operations btrfs_symlink_inode_operations = {
8720 .readlink = generic_readlink,
8721 .follow_link = page_follow_link_light,
8722 .put_link = page_put_link,
8723 .getattr = btrfs_getattr,
8724 .setattr = btrfs_setattr,
8725 .permission = btrfs_permission,
8726 .setxattr = btrfs_setxattr,
8727 .getxattr = btrfs_getxattr,
8728 .listxattr = btrfs_listxattr,
8729 .removexattr = btrfs_removexattr,
8730 .get_acl = btrfs_get_acl,
8731 .update_time = btrfs_update_time,
8734 const struct dentry_operations btrfs_dentry_operations = {
8735 .d_delete = btrfs_dentry_delete,
8736 .d_release = btrfs_dentry_release,