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;
709 * here we're doing allocation and writeback of the
712 btrfs_drop_extent_cache(inode, async_extent->start,
713 async_extent->start +
714 async_extent->ram_size - 1, 0);
716 em = alloc_extent_map();
718 goto out_free_reserve;
719 em->start = async_extent->start;
720 em->len = async_extent->ram_size;
721 em->orig_start = em->start;
722 em->mod_start = em->start;
723 em->mod_len = em->len;
725 em->block_start = ins.objectid;
726 em->block_len = ins.offset;
727 em->orig_block_len = ins.offset;
728 em->ram_bytes = async_extent->ram_size;
729 em->bdev = root->fs_info->fs_devices->latest_bdev;
730 em->compress_type = async_extent->compress_type;
731 set_bit(EXTENT_FLAG_PINNED, &em->flags);
732 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
736 write_lock(&em_tree->lock);
737 ret = add_extent_mapping(em_tree, em, 1);
738 write_unlock(&em_tree->lock);
739 if (ret != -EEXIST) {
743 btrfs_drop_extent_cache(inode, async_extent->start,
744 async_extent->start +
745 async_extent->ram_size - 1, 0);
749 goto out_free_reserve;
751 ret = btrfs_add_ordered_extent_compress(inode,
754 async_extent->ram_size,
756 BTRFS_ORDERED_COMPRESSED,
757 async_extent->compress_type);
759 goto out_free_reserve;
762 * clear dirty, set writeback and unlock the pages.
764 extent_clear_unlock_delalloc(inode,
765 &BTRFS_I(inode)->io_tree,
767 async_extent->start +
768 async_extent->ram_size - 1,
769 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
770 EXTENT_CLEAR_UNLOCK |
771 EXTENT_CLEAR_DELALLOC |
772 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
774 ret = btrfs_submit_compressed_write(inode,
776 async_extent->ram_size,
778 ins.offset, async_extent->pages,
779 async_extent->nr_pages);
780 alloc_hint = ins.objectid + ins.offset;
790 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
792 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
794 async_extent->start +
795 async_extent->ram_size - 1,
796 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
797 EXTENT_CLEAR_UNLOCK |
798 EXTENT_CLEAR_DELALLOC |
800 EXTENT_SET_WRITEBACK |
801 EXTENT_END_WRITEBACK);
806 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
809 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
810 struct extent_map *em;
813 read_lock(&em_tree->lock);
814 em = search_extent_mapping(em_tree, start, num_bytes);
817 * if block start isn't an actual block number then find the
818 * first block in this inode and use that as a hint. If that
819 * block is also bogus then just don't worry about it.
821 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
823 em = search_extent_mapping(em_tree, 0, 0);
824 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
825 alloc_hint = em->block_start;
829 alloc_hint = em->block_start;
833 read_unlock(&em_tree->lock);
839 * when extent_io.c finds a delayed allocation range in the file,
840 * the call backs end up in this code. The basic idea is to
841 * allocate extents on disk for the range, and create ordered data structs
842 * in ram to track those extents.
844 * locked_page is the page that writepage had locked already. We use
845 * it to make sure we don't do extra locks or unlocks.
847 * *page_started is set to one if we unlock locked_page and do everything
848 * required to start IO on it. It may be clean and already done with
851 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
853 struct btrfs_root *root,
854 struct page *locked_page,
855 u64 start, u64 end, int *page_started,
856 unsigned long *nr_written,
861 unsigned long ram_size;
864 u64 blocksize = root->sectorsize;
865 struct btrfs_key ins;
866 struct extent_map *em;
867 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
870 BUG_ON(btrfs_is_free_space_inode(inode));
872 num_bytes = ALIGN(end - start + 1, blocksize);
873 num_bytes = max(blocksize, num_bytes);
874 disk_num_bytes = num_bytes;
876 /* if this is a small write inside eof, kick off defrag */
877 if (num_bytes < 64 * 1024 &&
878 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
879 btrfs_add_inode_defrag(trans, inode);
882 /* lets try to make an inline extent */
883 ret = cow_file_range_inline(trans, root, inode,
884 start, end, 0, 0, NULL);
886 extent_clear_unlock_delalloc(inode,
887 &BTRFS_I(inode)->io_tree,
889 EXTENT_CLEAR_UNLOCK_PAGE |
890 EXTENT_CLEAR_UNLOCK |
891 EXTENT_CLEAR_DELALLOC |
893 EXTENT_SET_WRITEBACK |
894 EXTENT_END_WRITEBACK);
896 *nr_written = *nr_written +
897 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
900 } else if (ret < 0) {
901 btrfs_abort_transaction(trans, root, ret);
906 BUG_ON(disk_num_bytes >
907 btrfs_super_total_bytes(root->fs_info->super_copy));
909 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
910 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
912 while (disk_num_bytes > 0) {
915 cur_alloc_size = disk_num_bytes;
916 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
917 root->sectorsize, 0, alloc_hint,
920 btrfs_abort_transaction(trans, root, ret);
924 em = alloc_extent_map();
928 em->orig_start = em->start;
929 ram_size = ins.offset;
930 em->len = ins.offset;
931 em->mod_start = em->start;
932 em->mod_len = em->len;
934 em->block_start = ins.objectid;
935 em->block_len = ins.offset;
936 em->orig_block_len = ins.offset;
937 em->ram_bytes = ram_size;
938 em->bdev = root->fs_info->fs_devices->latest_bdev;
939 set_bit(EXTENT_FLAG_PINNED, &em->flags);
943 write_lock(&em_tree->lock);
944 ret = add_extent_mapping(em_tree, em, 1);
945 write_unlock(&em_tree->lock);
946 if (ret != -EEXIST) {
950 btrfs_drop_extent_cache(inode, start,
951 start + ram_size - 1, 0);
956 cur_alloc_size = ins.offset;
957 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
958 ram_size, cur_alloc_size, 0);
962 if (root->root_key.objectid ==
963 BTRFS_DATA_RELOC_TREE_OBJECTID) {
964 ret = btrfs_reloc_clone_csums(inode, start,
967 btrfs_abort_transaction(trans, root, ret);
972 if (disk_num_bytes < cur_alloc_size)
975 /* we're not doing compressed IO, don't unlock the first
976 * page (which the caller expects to stay locked), don't
977 * clear any dirty bits and don't set any writeback bits
979 * Do set the Private2 bit so we know this page was properly
980 * setup for writepage
982 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
983 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
986 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
987 start, start + ram_size - 1,
989 disk_num_bytes -= cur_alloc_size;
990 num_bytes -= cur_alloc_size;
991 alloc_hint = ins.objectid + ins.offset;
992 start += cur_alloc_size;
998 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
1000 extent_clear_unlock_delalloc(inode,
1001 &BTRFS_I(inode)->io_tree,
1002 start, end, locked_page,
1003 EXTENT_CLEAR_UNLOCK_PAGE |
1004 EXTENT_CLEAR_UNLOCK |
1005 EXTENT_CLEAR_DELALLOC |
1006 EXTENT_CLEAR_DIRTY |
1007 EXTENT_SET_WRITEBACK |
1008 EXTENT_END_WRITEBACK);
1013 static noinline int cow_file_range(struct inode *inode,
1014 struct page *locked_page,
1015 u64 start, u64 end, int *page_started,
1016 unsigned long *nr_written,
1019 struct btrfs_trans_handle *trans;
1020 struct btrfs_root *root = BTRFS_I(inode)->root;
1023 trans = btrfs_join_transaction(root);
1024 if (IS_ERR(trans)) {
1025 extent_clear_unlock_delalloc(inode,
1026 &BTRFS_I(inode)->io_tree,
1027 start, end, locked_page,
1028 EXTENT_CLEAR_UNLOCK_PAGE |
1029 EXTENT_CLEAR_UNLOCK |
1030 EXTENT_CLEAR_DELALLOC |
1031 EXTENT_CLEAR_DIRTY |
1032 EXTENT_SET_WRITEBACK |
1033 EXTENT_END_WRITEBACK);
1034 return PTR_ERR(trans);
1036 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1038 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1039 page_started, nr_written, unlock);
1041 btrfs_end_transaction(trans, root);
1047 * work queue call back to started compression on a file and pages
1049 static noinline void async_cow_start(struct btrfs_work *work)
1051 struct async_cow *async_cow;
1053 async_cow = container_of(work, struct async_cow, work);
1055 compress_file_range(async_cow->inode, async_cow->locked_page,
1056 async_cow->start, async_cow->end, async_cow,
1058 if (num_added == 0) {
1059 btrfs_add_delayed_iput(async_cow->inode);
1060 async_cow->inode = NULL;
1065 * work queue call back to submit previously compressed pages
1067 static noinline void async_cow_submit(struct btrfs_work *work)
1069 struct async_cow *async_cow;
1070 struct btrfs_root *root;
1071 unsigned long nr_pages;
1073 async_cow = container_of(work, struct async_cow, work);
1075 root = async_cow->root;
1076 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1079 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1081 waitqueue_active(&root->fs_info->async_submit_wait))
1082 wake_up(&root->fs_info->async_submit_wait);
1084 if (async_cow->inode)
1085 submit_compressed_extents(async_cow->inode, async_cow);
1088 static noinline void async_cow_free(struct btrfs_work *work)
1090 struct async_cow *async_cow;
1091 async_cow = container_of(work, struct async_cow, work);
1092 if (async_cow->inode)
1093 btrfs_add_delayed_iput(async_cow->inode);
1097 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1098 u64 start, u64 end, int *page_started,
1099 unsigned long *nr_written)
1101 struct async_cow *async_cow;
1102 struct btrfs_root *root = BTRFS_I(inode)->root;
1103 unsigned long nr_pages;
1105 int limit = 10 * 1024 * 1024;
1107 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1108 1, 0, NULL, GFP_NOFS);
1109 while (start < end) {
1110 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1111 BUG_ON(!async_cow); /* -ENOMEM */
1112 async_cow->inode = igrab(inode);
1113 async_cow->root = root;
1114 async_cow->locked_page = locked_page;
1115 async_cow->start = start;
1117 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1120 cur_end = min(end, start + 512 * 1024 - 1);
1122 async_cow->end = cur_end;
1123 INIT_LIST_HEAD(&async_cow->extents);
1125 async_cow->work.func = async_cow_start;
1126 async_cow->work.ordered_func = async_cow_submit;
1127 async_cow->work.ordered_free = async_cow_free;
1128 async_cow->work.flags = 0;
1130 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1132 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1134 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1137 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1138 wait_event(root->fs_info->async_submit_wait,
1139 (atomic_read(&root->fs_info->async_delalloc_pages) <
1143 while (atomic_read(&root->fs_info->async_submit_draining) &&
1144 atomic_read(&root->fs_info->async_delalloc_pages)) {
1145 wait_event(root->fs_info->async_submit_wait,
1146 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1150 *nr_written += nr_pages;
1151 start = cur_end + 1;
1157 static noinline int csum_exist_in_range(struct btrfs_root *root,
1158 u64 bytenr, u64 num_bytes)
1161 struct btrfs_ordered_sum *sums;
1164 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1165 bytenr + num_bytes - 1, &list, 0);
1166 if (ret == 0 && list_empty(&list))
1169 while (!list_empty(&list)) {
1170 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1171 list_del(&sums->list);
1178 * when nowcow writeback call back. This checks for snapshots or COW copies
1179 * of the extents that exist in the file, and COWs the file as required.
1181 * If no cow copies or snapshots exist, we write directly to the existing
1184 static noinline int run_delalloc_nocow(struct inode *inode,
1185 struct page *locked_page,
1186 u64 start, u64 end, int *page_started, int force,
1187 unsigned long *nr_written)
1189 struct btrfs_root *root = BTRFS_I(inode)->root;
1190 struct btrfs_trans_handle *trans;
1191 struct extent_buffer *leaf;
1192 struct btrfs_path *path;
1193 struct btrfs_file_extent_item *fi;
1194 struct btrfs_key found_key;
1209 u64 ino = btrfs_ino(inode);
1211 path = btrfs_alloc_path();
1213 extent_clear_unlock_delalloc(inode,
1214 &BTRFS_I(inode)->io_tree,
1215 start, end, locked_page,
1216 EXTENT_CLEAR_UNLOCK_PAGE |
1217 EXTENT_CLEAR_UNLOCK |
1218 EXTENT_CLEAR_DELALLOC |
1219 EXTENT_CLEAR_DIRTY |
1220 EXTENT_SET_WRITEBACK |
1221 EXTENT_END_WRITEBACK);
1225 nolock = btrfs_is_free_space_inode(inode);
1228 trans = btrfs_join_transaction_nolock(root);
1230 trans = btrfs_join_transaction(root);
1232 if (IS_ERR(trans)) {
1233 extent_clear_unlock_delalloc(inode,
1234 &BTRFS_I(inode)->io_tree,
1235 start, end, locked_page,
1236 EXTENT_CLEAR_UNLOCK_PAGE |
1237 EXTENT_CLEAR_UNLOCK |
1238 EXTENT_CLEAR_DELALLOC |
1239 EXTENT_CLEAR_DIRTY |
1240 EXTENT_SET_WRITEBACK |
1241 EXTENT_END_WRITEBACK);
1242 btrfs_free_path(path);
1243 return PTR_ERR(trans);
1246 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1248 cow_start = (u64)-1;
1251 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1254 btrfs_abort_transaction(trans, root, ret);
1257 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1258 leaf = path->nodes[0];
1259 btrfs_item_key_to_cpu(leaf, &found_key,
1260 path->slots[0] - 1);
1261 if (found_key.objectid == ino &&
1262 found_key.type == BTRFS_EXTENT_DATA_KEY)
1267 leaf = path->nodes[0];
1268 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1269 ret = btrfs_next_leaf(root, path);
1271 btrfs_abort_transaction(trans, root, ret);
1276 leaf = path->nodes[0];
1282 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1284 if (found_key.objectid > ino ||
1285 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1286 found_key.offset > end)
1289 if (found_key.offset > cur_offset) {
1290 extent_end = found_key.offset;
1295 fi = btrfs_item_ptr(leaf, path->slots[0],
1296 struct btrfs_file_extent_item);
1297 extent_type = btrfs_file_extent_type(leaf, fi);
1299 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1300 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1301 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1302 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1303 extent_offset = btrfs_file_extent_offset(leaf, fi);
1304 extent_end = found_key.offset +
1305 btrfs_file_extent_num_bytes(leaf, fi);
1307 btrfs_file_extent_disk_num_bytes(leaf, fi);
1308 if (extent_end <= start) {
1312 if (disk_bytenr == 0)
1314 if (btrfs_file_extent_compression(leaf, fi) ||
1315 btrfs_file_extent_encryption(leaf, fi) ||
1316 btrfs_file_extent_other_encoding(leaf, fi))
1318 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1320 if (btrfs_extent_readonly(root, disk_bytenr))
1322 if (btrfs_cross_ref_exist(trans, root, ino,
1324 extent_offset, disk_bytenr))
1326 disk_bytenr += extent_offset;
1327 disk_bytenr += cur_offset - found_key.offset;
1328 num_bytes = min(end + 1, extent_end) - cur_offset;
1330 * force cow if csum exists in the range.
1331 * this ensure that csum for a given extent are
1332 * either valid or do not exist.
1334 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1337 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1338 extent_end = found_key.offset +
1339 btrfs_file_extent_inline_len(leaf, fi);
1340 extent_end = ALIGN(extent_end, root->sectorsize);
1345 if (extent_end <= start) {
1350 if (cow_start == (u64)-1)
1351 cow_start = cur_offset;
1352 cur_offset = extent_end;
1353 if (cur_offset > end)
1359 btrfs_release_path(path);
1360 if (cow_start != (u64)-1) {
1361 ret = __cow_file_range(trans, inode, root, locked_page,
1362 cow_start, found_key.offset - 1,
1363 page_started, nr_written, 1);
1365 btrfs_abort_transaction(trans, root, ret);
1368 cow_start = (u64)-1;
1371 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1372 struct extent_map *em;
1373 struct extent_map_tree *em_tree;
1374 em_tree = &BTRFS_I(inode)->extent_tree;
1375 em = alloc_extent_map();
1376 BUG_ON(!em); /* -ENOMEM */
1377 em->start = cur_offset;
1378 em->orig_start = found_key.offset - extent_offset;
1379 em->len = num_bytes;
1380 em->block_len = num_bytes;
1381 em->block_start = disk_bytenr;
1382 em->orig_block_len = disk_num_bytes;
1383 em->ram_bytes = ram_bytes;
1384 em->bdev = root->fs_info->fs_devices->latest_bdev;
1385 em->mod_start = em->start;
1386 em->mod_len = em->len;
1387 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1388 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1389 em->generation = -1;
1391 write_lock(&em_tree->lock);
1392 ret = add_extent_mapping(em_tree, em, 1);
1393 write_unlock(&em_tree->lock);
1394 if (ret != -EEXIST) {
1395 free_extent_map(em);
1398 btrfs_drop_extent_cache(inode, em->start,
1399 em->start + em->len - 1, 0);
1401 type = BTRFS_ORDERED_PREALLOC;
1403 type = BTRFS_ORDERED_NOCOW;
1406 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1407 num_bytes, num_bytes, type);
1408 BUG_ON(ret); /* -ENOMEM */
1410 if (root->root_key.objectid ==
1411 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1412 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1415 btrfs_abort_transaction(trans, root, ret);
1420 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1421 cur_offset, cur_offset + num_bytes - 1,
1422 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1423 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1424 EXTENT_SET_PRIVATE2);
1425 cur_offset = extent_end;
1426 if (cur_offset > end)
1429 btrfs_release_path(path);
1431 if (cur_offset <= end && cow_start == (u64)-1) {
1432 cow_start = cur_offset;
1436 if (cow_start != (u64)-1) {
1437 ret = __cow_file_range(trans, inode, root, locked_page,
1439 page_started, nr_written, 1);
1441 btrfs_abort_transaction(trans, root, ret);
1447 err = btrfs_end_transaction(trans, root);
1451 if (ret && cur_offset < end)
1452 extent_clear_unlock_delalloc(inode,
1453 &BTRFS_I(inode)->io_tree,
1454 cur_offset, end, locked_page,
1455 EXTENT_CLEAR_UNLOCK_PAGE |
1456 EXTENT_CLEAR_UNLOCK |
1457 EXTENT_CLEAR_DELALLOC |
1458 EXTENT_CLEAR_DIRTY |
1459 EXTENT_SET_WRITEBACK |
1460 EXTENT_END_WRITEBACK);
1462 btrfs_free_path(path);
1467 * extent_io.c call back to do delayed allocation processing
1469 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1470 u64 start, u64 end, int *page_started,
1471 unsigned long *nr_written)
1474 struct btrfs_root *root = BTRFS_I(inode)->root;
1476 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1477 ret = run_delalloc_nocow(inode, locked_page, start, end,
1478 page_started, 1, nr_written);
1479 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1480 ret = run_delalloc_nocow(inode, locked_page, start, end,
1481 page_started, 0, nr_written);
1482 } else if (!btrfs_test_opt(root, COMPRESS) &&
1483 !(BTRFS_I(inode)->force_compress) &&
1484 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1485 ret = cow_file_range(inode, locked_page, start, end,
1486 page_started, nr_written, 1);
1488 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1489 &BTRFS_I(inode)->runtime_flags);
1490 ret = cow_file_range_async(inode, locked_page, start, end,
1491 page_started, nr_written);
1496 static void btrfs_split_extent_hook(struct inode *inode,
1497 struct extent_state *orig, u64 split)
1499 /* not delalloc, ignore it */
1500 if (!(orig->state & EXTENT_DELALLOC))
1503 spin_lock(&BTRFS_I(inode)->lock);
1504 BTRFS_I(inode)->outstanding_extents++;
1505 spin_unlock(&BTRFS_I(inode)->lock);
1509 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1510 * extents so we can keep track of new extents that are just merged onto old
1511 * extents, such as when we are doing sequential writes, so we can properly
1512 * account for the metadata space we'll need.
1514 static void btrfs_merge_extent_hook(struct inode *inode,
1515 struct extent_state *new,
1516 struct extent_state *other)
1518 /* not delalloc, ignore it */
1519 if (!(other->state & EXTENT_DELALLOC))
1522 spin_lock(&BTRFS_I(inode)->lock);
1523 BTRFS_I(inode)->outstanding_extents--;
1524 spin_unlock(&BTRFS_I(inode)->lock);
1528 * extent_io.c set_bit_hook, used to track delayed allocation
1529 * bytes in this file, and to maintain the list of inodes that
1530 * have pending delalloc work to be done.
1532 static void btrfs_set_bit_hook(struct inode *inode,
1533 struct extent_state *state, unsigned long *bits)
1537 * set_bit and clear bit hooks normally require _irqsave/restore
1538 * but in this case, we are only testing for the DELALLOC
1539 * bit, which is only set or cleared with irqs on
1541 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1542 struct btrfs_root *root = BTRFS_I(inode)->root;
1543 u64 len = state->end + 1 - state->start;
1544 bool do_list = !btrfs_is_free_space_inode(inode);
1546 if (*bits & EXTENT_FIRST_DELALLOC) {
1547 *bits &= ~EXTENT_FIRST_DELALLOC;
1549 spin_lock(&BTRFS_I(inode)->lock);
1550 BTRFS_I(inode)->outstanding_extents++;
1551 spin_unlock(&BTRFS_I(inode)->lock);
1554 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1555 root->fs_info->delalloc_batch);
1556 spin_lock(&BTRFS_I(inode)->lock);
1557 BTRFS_I(inode)->delalloc_bytes += len;
1558 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1559 &BTRFS_I(inode)->runtime_flags)) {
1560 spin_lock(&root->fs_info->delalloc_lock);
1561 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1562 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1563 &root->fs_info->delalloc_inodes);
1564 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1565 &BTRFS_I(inode)->runtime_flags);
1567 spin_unlock(&root->fs_info->delalloc_lock);
1569 spin_unlock(&BTRFS_I(inode)->lock);
1574 * extent_io.c clear_bit_hook, see set_bit_hook for why
1576 static void btrfs_clear_bit_hook(struct inode *inode,
1577 struct extent_state *state,
1578 unsigned long *bits)
1581 * set_bit and clear bit hooks normally require _irqsave/restore
1582 * but in this case, we are only testing for the DELALLOC
1583 * bit, which is only set or cleared with irqs on
1585 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1586 struct btrfs_root *root = BTRFS_I(inode)->root;
1587 u64 len = state->end + 1 - state->start;
1588 bool do_list = !btrfs_is_free_space_inode(inode);
1590 if (*bits & EXTENT_FIRST_DELALLOC) {
1591 *bits &= ~EXTENT_FIRST_DELALLOC;
1592 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1593 spin_lock(&BTRFS_I(inode)->lock);
1594 BTRFS_I(inode)->outstanding_extents--;
1595 spin_unlock(&BTRFS_I(inode)->lock);
1598 if (*bits & EXTENT_DO_ACCOUNTING)
1599 btrfs_delalloc_release_metadata(inode, len);
1601 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1603 btrfs_free_reserved_data_space(inode, len);
1605 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1606 root->fs_info->delalloc_batch);
1607 spin_lock(&BTRFS_I(inode)->lock);
1608 BTRFS_I(inode)->delalloc_bytes -= len;
1609 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1610 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1611 &BTRFS_I(inode)->runtime_flags)) {
1612 spin_lock(&root->fs_info->delalloc_lock);
1613 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1614 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1615 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1616 &BTRFS_I(inode)->runtime_flags);
1618 spin_unlock(&root->fs_info->delalloc_lock);
1620 spin_unlock(&BTRFS_I(inode)->lock);
1625 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1626 * we don't create bios that span stripes or chunks
1628 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1629 size_t size, struct bio *bio,
1630 unsigned long bio_flags)
1632 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1633 u64 logical = (u64)bio->bi_sector << 9;
1638 if (bio_flags & EXTENT_BIO_COMPRESSED)
1641 length = bio->bi_size;
1642 map_length = length;
1643 ret = btrfs_map_block(root->fs_info, rw, logical,
1644 &map_length, NULL, 0);
1645 /* Will always return 0 with map_multi == NULL */
1647 if (map_length < length + size)
1653 * in order to insert checksums into the metadata in large chunks,
1654 * we wait until bio submission time. All the pages in the bio are
1655 * checksummed and sums are attached onto the ordered extent record.
1657 * At IO completion time the cums attached on the ordered extent record
1658 * are inserted into the btree
1660 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1661 struct bio *bio, int mirror_num,
1662 unsigned long bio_flags,
1665 struct btrfs_root *root = BTRFS_I(inode)->root;
1668 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1669 BUG_ON(ret); /* -ENOMEM */
1674 * in order to insert checksums into the metadata in large chunks,
1675 * we wait until bio submission time. All the pages in the bio are
1676 * checksummed and sums are attached onto the ordered extent record.
1678 * At IO completion time the cums attached on the ordered extent record
1679 * are inserted into the btree
1681 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1682 int mirror_num, unsigned long bio_flags,
1685 struct btrfs_root *root = BTRFS_I(inode)->root;
1688 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1690 bio_endio(bio, ret);
1695 * extent_io.c submission hook. This does the right thing for csum calculation
1696 * on write, or reading the csums from the tree before a read
1698 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1699 int mirror_num, unsigned long bio_flags,
1702 struct btrfs_root *root = BTRFS_I(inode)->root;
1706 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1708 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1710 if (btrfs_is_free_space_inode(inode))
1713 if (!(rw & REQ_WRITE)) {
1714 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1718 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1719 ret = btrfs_submit_compressed_read(inode, bio,
1723 } else if (!skip_sum) {
1724 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1729 } else if (async && !skip_sum) {
1730 /* csum items have already been cloned */
1731 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1733 /* we're doing a write, do the async checksumming */
1734 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1735 inode, rw, bio, mirror_num,
1736 bio_flags, bio_offset,
1737 __btrfs_submit_bio_start,
1738 __btrfs_submit_bio_done);
1740 } else if (!skip_sum) {
1741 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1747 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1751 bio_endio(bio, ret);
1756 * given a list of ordered sums record them in the inode. This happens
1757 * at IO completion time based on sums calculated at bio submission time.
1759 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1760 struct inode *inode, u64 file_offset,
1761 struct list_head *list)
1763 struct btrfs_ordered_sum *sum;
1765 list_for_each_entry(sum, list, list) {
1766 trans->adding_csums = 1;
1767 btrfs_csum_file_blocks(trans,
1768 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1769 trans->adding_csums = 0;
1774 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1775 struct extent_state **cached_state)
1777 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1778 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1779 cached_state, GFP_NOFS);
1782 /* see btrfs_writepage_start_hook for details on why this is required */
1783 struct btrfs_writepage_fixup {
1785 struct btrfs_work work;
1788 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1790 struct btrfs_writepage_fixup *fixup;
1791 struct btrfs_ordered_extent *ordered;
1792 struct extent_state *cached_state = NULL;
1794 struct inode *inode;
1799 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1803 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1804 ClearPageChecked(page);
1808 inode = page->mapping->host;
1809 page_start = page_offset(page);
1810 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1812 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1815 /* already ordered? We're done */
1816 if (PagePrivate2(page))
1819 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1821 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1822 page_end, &cached_state, GFP_NOFS);
1824 btrfs_start_ordered_extent(inode, ordered, 1);
1825 btrfs_put_ordered_extent(ordered);
1829 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1831 mapping_set_error(page->mapping, ret);
1832 end_extent_writepage(page, ret, page_start, page_end);
1833 ClearPageChecked(page);
1837 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1838 ClearPageChecked(page);
1839 set_page_dirty(page);
1841 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1842 &cached_state, GFP_NOFS);
1845 page_cache_release(page);
1850 * There are a few paths in the higher layers of the kernel that directly
1851 * set the page dirty bit without asking the filesystem if it is a
1852 * good idea. This causes problems because we want to make sure COW
1853 * properly happens and the data=ordered rules are followed.
1855 * In our case any range that doesn't have the ORDERED bit set
1856 * hasn't been properly setup for IO. We kick off an async process
1857 * to fix it up. The async helper will wait for ordered extents, set
1858 * the delalloc bit and make it safe to write the page.
1860 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1862 struct inode *inode = page->mapping->host;
1863 struct btrfs_writepage_fixup *fixup;
1864 struct btrfs_root *root = BTRFS_I(inode)->root;
1866 /* this page is properly in the ordered list */
1867 if (TestClearPagePrivate2(page))
1870 if (PageChecked(page))
1873 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1877 SetPageChecked(page);
1878 page_cache_get(page);
1879 fixup->work.func = btrfs_writepage_fixup_worker;
1881 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1885 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1886 struct inode *inode, u64 file_pos,
1887 u64 disk_bytenr, u64 disk_num_bytes,
1888 u64 num_bytes, u64 ram_bytes,
1889 u8 compression, u8 encryption,
1890 u16 other_encoding, int extent_type)
1892 struct btrfs_root *root = BTRFS_I(inode)->root;
1893 struct btrfs_file_extent_item *fi;
1894 struct btrfs_path *path;
1895 struct extent_buffer *leaf;
1896 struct btrfs_key ins;
1899 path = btrfs_alloc_path();
1903 path->leave_spinning = 1;
1906 * we may be replacing one extent in the tree with another.
1907 * The new extent is pinned in the extent map, and we don't want
1908 * to drop it from the cache until it is completely in the btree.
1910 * So, tell btrfs_drop_extents to leave this extent in the cache.
1911 * the caller is expected to unpin it and allow it to be merged
1914 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1915 file_pos + num_bytes, 0);
1919 ins.objectid = btrfs_ino(inode);
1920 ins.offset = file_pos;
1921 ins.type = BTRFS_EXTENT_DATA_KEY;
1922 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1925 leaf = path->nodes[0];
1926 fi = btrfs_item_ptr(leaf, path->slots[0],
1927 struct btrfs_file_extent_item);
1928 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1929 btrfs_set_file_extent_type(leaf, fi, extent_type);
1930 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1931 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1932 btrfs_set_file_extent_offset(leaf, fi, 0);
1933 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1934 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1935 btrfs_set_file_extent_compression(leaf, fi, compression);
1936 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1937 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1939 btrfs_mark_buffer_dirty(leaf);
1940 btrfs_release_path(path);
1942 inode_add_bytes(inode, num_bytes);
1944 ins.objectid = disk_bytenr;
1945 ins.offset = disk_num_bytes;
1946 ins.type = BTRFS_EXTENT_ITEM_KEY;
1947 ret = btrfs_alloc_reserved_file_extent(trans, root,
1948 root->root_key.objectid,
1949 btrfs_ino(inode), file_pos, &ins);
1951 btrfs_free_path(path);
1956 /* snapshot-aware defrag */
1957 struct sa_defrag_extent_backref {
1958 struct rb_node node;
1959 struct old_sa_defrag_extent *old;
1968 struct old_sa_defrag_extent {
1969 struct list_head list;
1970 struct new_sa_defrag_extent *new;
1979 struct new_sa_defrag_extent {
1980 struct rb_root root;
1981 struct list_head head;
1982 struct btrfs_path *path;
1983 struct inode *inode;
1991 static int backref_comp(struct sa_defrag_extent_backref *b1,
1992 struct sa_defrag_extent_backref *b2)
1994 if (b1->root_id < b2->root_id)
1996 else if (b1->root_id > b2->root_id)
1999 if (b1->inum < b2->inum)
2001 else if (b1->inum > b2->inum)
2004 if (b1->file_pos < b2->file_pos)
2006 else if (b1->file_pos > b2->file_pos)
2010 * [------------------------------] ===> (a range of space)
2011 * |<--->| |<---->| =============> (fs/file tree A)
2012 * |<---------------------------->| ===> (fs/file tree B)
2014 * A range of space can refer to two file extents in one tree while
2015 * refer to only one file extent in another tree.
2017 * So we may process a disk offset more than one time(two extents in A)
2018 * and locate at the same extent(one extent in B), then insert two same
2019 * backrefs(both refer to the extent in B).
2024 static void backref_insert(struct rb_root *root,
2025 struct sa_defrag_extent_backref *backref)
2027 struct rb_node **p = &root->rb_node;
2028 struct rb_node *parent = NULL;
2029 struct sa_defrag_extent_backref *entry;
2034 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2036 ret = backref_comp(backref, entry);
2040 p = &(*p)->rb_right;
2043 rb_link_node(&backref->node, parent, p);
2044 rb_insert_color(&backref->node, root);
2048 * Note the backref might has changed, and in this case we just return 0.
2050 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2053 struct btrfs_file_extent_item *extent;
2054 struct btrfs_fs_info *fs_info;
2055 struct old_sa_defrag_extent *old = ctx;
2056 struct new_sa_defrag_extent *new = old->new;
2057 struct btrfs_path *path = new->path;
2058 struct btrfs_key key;
2059 struct btrfs_root *root;
2060 struct sa_defrag_extent_backref *backref;
2061 struct extent_buffer *leaf;
2062 struct inode *inode = new->inode;
2068 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2069 inum == btrfs_ino(inode))
2072 key.objectid = root_id;
2073 key.type = BTRFS_ROOT_ITEM_KEY;
2074 key.offset = (u64)-1;
2076 fs_info = BTRFS_I(inode)->root->fs_info;
2077 root = btrfs_read_fs_root_no_name(fs_info, &key);
2079 if (PTR_ERR(root) == -ENOENT)
2082 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2083 inum, offset, root_id);
2084 return PTR_ERR(root);
2087 key.objectid = inum;
2088 key.type = BTRFS_EXTENT_DATA_KEY;
2089 if (offset > (u64)-1 << 32)
2092 key.offset = offset;
2094 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2103 leaf = path->nodes[0];
2104 slot = path->slots[0];
2106 if (slot >= btrfs_header_nritems(leaf)) {
2107 ret = btrfs_next_leaf(root, path);
2110 } else if (ret > 0) {
2119 btrfs_item_key_to_cpu(leaf, &key, slot);
2121 if (key.objectid > inum)
2124 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2127 extent = btrfs_item_ptr(leaf, slot,
2128 struct btrfs_file_extent_item);
2130 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2133 extent_offset = btrfs_file_extent_offset(leaf, extent);
2134 if (key.offset - extent_offset != offset)
2137 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2138 if (extent_offset >= old->extent_offset + old->offset +
2139 old->len || extent_offset + num_bytes <=
2140 old->extent_offset + old->offset)
2146 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2152 backref->root_id = root_id;
2153 backref->inum = inum;
2154 backref->file_pos = offset + extent_offset;
2155 backref->num_bytes = num_bytes;
2156 backref->extent_offset = extent_offset;
2157 backref->generation = btrfs_file_extent_generation(leaf, extent);
2159 backref_insert(&new->root, backref);
2162 btrfs_release_path(path);
2167 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2168 struct new_sa_defrag_extent *new)
2170 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2171 struct old_sa_defrag_extent *old, *tmp;
2176 list_for_each_entry_safe(old, tmp, &new->head, list) {
2177 ret = iterate_inodes_from_logical(old->bytenr, fs_info,
2178 path, record_one_backref,
2180 BUG_ON(ret < 0 && ret != -ENOENT);
2182 /* no backref to be processed for this extent */
2184 list_del(&old->list);
2189 if (list_empty(&new->head))
2195 static int relink_is_mergable(struct extent_buffer *leaf,
2196 struct btrfs_file_extent_item *fi,
2199 if (btrfs_file_extent_disk_bytenr(leaf, fi) != disk_bytenr)
2202 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2205 if (btrfs_file_extent_compression(leaf, fi) ||
2206 btrfs_file_extent_encryption(leaf, fi) ||
2207 btrfs_file_extent_other_encoding(leaf, fi))
2214 * Note the backref might has changed, and in this case we just return 0.
2216 static noinline int relink_extent_backref(struct btrfs_path *path,
2217 struct sa_defrag_extent_backref *prev,
2218 struct sa_defrag_extent_backref *backref)
2220 struct btrfs_file_extent_item *extent;
2221 struct btrfs_file_extent_item *item;
2222 struct btrfs_ordered_extent *ordered;
2223 struct btrfs_trans_handle *trans;
2224 struct btrfs_fs_info *fs_info;
2225 struct btrfs_root *root;
2226 struct btrfs_key key;
2227 struct extent_buffer *leaf;
2228 struct old_sa_defrag_extent *old = backref->old;
2229 struct new_sa_defrag_extent *new = old->new;
2230 struct inode *src_inode = new->inode;
2231 struct inode *inode;
2232 struct extent_state *cached = NULL;
2241 if (prev && prev->root_id == backref->root_id &&
2242 prev->inum == backref->inum &&
2243 prev->file_pos + prev->num_bytes == backref->file_pos)
2246 /* step 1: get root */
2247 key.objectid = backref->root_id;
2248 key.type = BTRFS_ROOT_ITEM_KEY;
2249 key.offset = (u64)-1;
2251 fs_info = BTRFS_I(src_inode)->root->fs_info;
2252 index = srcu_read_lock(&fs_info->subvol_srcu);
2254 root = btrfs_read_fs_root_no_name(fs_info, &key);
2256 srcu_read_unlock(&fs_info->subvol_srcu, index);
2257 if (PTR_ERR(root) == -ENOENT)
2259 return PTR_ERR(root);
2261 if (btrfs_root_refs(&root->root_item) == 0) {
2262 srcu_read_unlock(&fs_info->subvol_srcu, index);
2263 /* parse ENOENT to 0 */
2267 /* step 2: get inode */
2268 key.objectid = backref->inum;
2269 key.type = BTRFS_INODE_ITEM_KEY;
2272 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2273 if (IS_ERR(inode)) {
2274 srcu_read_unlock(&fs_info->subvol_srcu, index);
2278 srcu_read_unlock(&fs_info->subvol_srcu, index);
2280 /* step 3: relink backref */
2281 lock_start = backref->file_pos;
2282 lock_end = backref->file_pos + backref->num_bytes - 1;
2283 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2286 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2288 btrfs_put_ordered_extent(ordered);
2292 trans = btrfs_join_transaction(root);
2293 if (IS_ERR(trans)) {
2294 ret = PTR_ERR(trans);
2298 key.objectid = backref->inum;
2299 key.type = BTRFS_EXTENT_DATA_KEY;
2300 key.offset = backref->file_pos;
2302 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2305 } else if (ret > 0) {
2310 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2311 struct btrfs_file_extent_item);
2313 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2314 backref->generation)
2317 btrfs_release_path(path);
2319 start = backref->file_pos;
2320 if (backref->extent_offset < old->extent_offset + old->offset)
2321 start += old->extent_offset + old->offset -
2322 backref->extent_offset;
2324 len = min(backref->extent_offset + backref->num_bytes,
2325 old->extent_offset + old->offset + old->len);
2326 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2328 ret = btrfs_drop_extents(trans, root, inode, start,
2333 key.objectid = btrfs_ino(inode);
2334 key.type = BTRFS_EXTENT_DATA_KEY;
2337 path->leave_spinning = 1;
2339 struct btrfs_file_extent_item *fi;
2341 struct btrfs_key found_key;
2343 ret = btrfs_search_slot(trans, root, &key, path, 1, 1);
2348 leaf = path->nodes[0];
2349 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2351 fi = btrfs_item_ptr(leaf, path->slots[0],
2352 struct btrfs_file_extent_item);
2353 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2355 if (relink_is_mergable(leaf, fi, new->bytenr) &&
2356 extent_len + found_key.offset == start) {
2357 btrfs_set_file_extent_num_bytes(leaf, fi,
2359 btrfs_mark_buffer_dirty(leaf);
2360 inode_add_bytes(inode, len);
2366 btrfs_release_path(path);
2371 ret = btrfs_insert_empty_item(trans, root, path, &key,
2374 btrfs_abort_transaction(trans, root, ret);
2378 leaf = path->nodes[0];
2379 item = btrfs_item_ptr(leaf, path->slots[0],
2380 struct btrfs_file_extent_item);
2381 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2382 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2383 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2384 btrfs_set_file_extent_num_bytes(leaf, item, len);
2385 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2386 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2387 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2388 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2389 btrfs_set_file_extent_encryption(leaf, item, 0);
2390 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2392 btrfs_mark_buffer_dirty(leaf);
2393 inode_add_bytes(inode, len);
2394 btrfs_release_path(path);
2396 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2398 backref->root_id, backref->inum,
2399 new->file_pos, 0); /* start - extent_offset */
2401 btrfs_abort_transaction(trans, root, ret);
2407 btrfs_release_path(path);
2408 path->leave_spinning = 0;
2409 btrfs_end_transaction(trans, root);
2411 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2417 static void relink_file_extents(struct new_sa_defrag_extent *new)
2419 struct btrfs_path *path;
2420 struct old_sa_defrag_extent *old, *tmp;
2421 struct sa_defrag_extent_backref *backref;
2422 struct sa_defrag_extent_backref *prev = NULL;
2423 struct inode *inode;
2424 struct btrfs_root *root;
2425 struct rb_node *node;
2429 root = BTRFS_I(inode)->root;
2431 path = btrfs_alloc_path();
2435 if (!record_extent_backrefs(path, new)) {
2436 btrfs_free_path(path);
2439 btrfs_release_path(path);
2442 node = rb_first(&new->root);
2445 rb_erase(node, &new->root);
2447 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2449 ret = relink_extent_backref(path, prev, backref);
2462 btrfs_free_path(path);
2464 list_for_each_entry_safe(old, tmp, &new->head, list) {
2465 list_del(&old->list);
2469 atomic_dec(&root->fs_info->defrag_running);
2470 wake_up(&root->fs_info->transaction_wait);
2475 static struct new_sa_defrag_extent *
2476 record_old_file_extents(struct inode *inode,
2477 struct btrfs_ordered_extent *ordered)
2479 struct btrfs_root *root = BTRFS_I(inode)->root;
2480 struct btrfs_path *path;
2481 struct btrfs_key key;
2482 struct old_sa_defrag_extent *old, *tmp;
2483 struct new_sa_defrag_extent *new;
2486 new = kmalloc(sizeof(*new), GFP_NOFS);
2491 new->file_pos = ordered->file_offset;
2492 new->len = ordered->len;
2493 new->bytenr = ordered->start;
2494 new->disk_len = ordered->disk_len;
2495 new->compress_type = ordered->compress_type;
2496 new->root = RB_ROOT;
2497 INIT_LIST_HEAD(&new->head);
2499 path = btrfs_alloc_path();
2503 key.objectid = btrfs_ino(inode);
2504 key.type = BTRFS_EXTENT_DATA_KEY;
2505 key.offset = new->file_pos;
2507 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2510 if (ret > 0 && path->slots[0] > 0)
2513 /* find out all the old extents for the file range */
2515 struct btrfs_file_extent_item *extent;
2516 struct extent_buffer *l;
2525 slot = path->slots[0];
2527 if (slot >= btrfs_header_nritems(l)) {
2528 ret = btrfs_next_leaf(root, path);
2536 btrfs_item_key_to_cpu(l, &key, slot);
2538 if (key.objectid != btrfs_ino(inode))
2540 if (key.type != BTRFS_EXTENT_DATA_KEY)
2542 if (key.offset >= new->file_pos + new->len)
2545 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2547 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2548 if (key.offset + num_bytes < new->file_pos)
2551 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2555 extent_offset = btrfs_file_extent_offset(l, extent);
2557 old = kmalloc(sizeof(*old), GFP_NOFS);
2561 offset = max(new->file_pos, key.offset);
2562 end = min(new->file_pos + new->len, key.offset + num_bytes);
2564 old->bytenr = disk_bytenr;
2565 old->extent_offset = extent_offset;
2566 old->offset = offset - key.offset;
2567 old->len = end - offset;
2570 list_add_tail(&old->list, &new->head);
2576 btrfs_free_path(path);
2577 atomic_inc(&root->fs_info->defrag_running);
2582 list_for_each_entry_safe(old, tmp, &new->head, list) {
2583 list_del(&old->list);
2587 btrfs_free_path(path);
2594 * helper function for btrfs_finish_ordered_io, this
2595 * just reads in some of the csum leaves to prime them into ram
2596 * before we start the transaction. It limits the amount of btree
2597 * reads required while inside the transaction.
2599 /* as ordered data IO finishes, this gets called so we can finish
2600 * an ordered extent if the range of bytes in the file it covers are
2603 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2605 struct inode *inode = ordered_extent->inode;
2606 struct btrfs_root *root = BTRFS_I(inode)->root;
2607 struct btrfs_trans_handle *trans = NULL;
2608 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2609 struct extent_state *cached_state = NULL;
2610 struct new_sa_defrag_extent *new = NULL;
2611 int compress_type = 0;
2615 nolock = btrfs_is_free_space_inode(inode);
2617 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2622 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2623 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2624 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2626 trans = btrfs_join_transaction_nolock(root);
2628 trans = btrfs_join_transaction(root);
2629 if (IS_ERR(trans)) {
2630 ret = PTR_ERR(trans);
2634 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2635 ret = btrfs_update_inode_fallback(trans, root, inode);
2636 if (ret) /* -ENOMEM or corruption */
2637 btrfs_abort_transaction(trans, root, ret);
2641 lock_extent_bits(io_tree, ordered_extent->file_offset,
2642 ordered_extent->file_offset + ordered_extent->len - 1,
2645 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2646 ordered_extent->file_offset + ordered_extent->len - 1,
2647 EXTENT_DEFRAG, 1, cached_state);
2649 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2650 if (last_snapshot >= BTRFS_I(inode)->generation)
2651 /* the inode is shared */
2652 new = record_old_file_extents(inode, ordered_extent);
2654 clear_extent_bit(io_tree, ordered_extent->file_offset,
2655 ordered_extent->file_offset + ordered_extent->len - 1,
2656 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2660 trans = btrfs_join_transaction_nolock(root);
2662 trans = btrfs_join_transaction(root);
2663 if (IS_ERR(trans)) {
2664 ret = PTR_ERR(trans);
2668 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2670 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2671 compress_type = ordered_extent->compress_type;
2672 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2673 BUG_ON(compress_type);
2674 ret = btrfs_mark_extent_written(trans, inode,
2675 ordered_extent->file_offset,
2676 ordered_extent->file_offset +
2677 ordered_extent->len);
2679 BUG_ON(root == root->fs_info->tree_root);
2680 ret = insert_reserved_file_extent(trans, inode,
2681 ordered_extent->file_offset,
2682 ordered_extent->start,
2683 ordered_extent->disk_len,
2684 ordered_extent->len,
2685 ordered_extent->len,
2686 compress_type, 0, 0,
2687 BTRFS_FILE_EXTENT_REG);
2689 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2690 ordered_extent->file_offset, ordered_extent->len,
2693 btrfs_abort_transaction(trans, root, ret);
2697 add_pending_csums(trans, inode, ordered_extent->file_offset,
2698 &ordered_extent->list);
2700 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2701 ret = btrfs_update_inode_fallback(trans, root, inode);
2702 if (ret) { /* -ENOMEM or corruption */
2703 btrfs_abort_transaction(trans, root, ret);
2708 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2709 ordered_extent->file_offset +
2710 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2712 if (root != root->fs_info->tree_root)
2713 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2715 btrfs_end_transaction(trans, root);
2718 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2719 ordered_extent->file_offset +
2720 ordered_extent->len - 1, NULL, GFP_NOFS);
2723 * If the ordered extent had an IOERR or something else went
2724 * wrong we need to return the space for this ordered extent
2725 * back to the allocator.
2727 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2728 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
2729 btrfs_free_reserved_extent(root, ordered_extent->start,
2730 ordered_extent->disk_len);
2735 * This needs to be done to make sure anybody waiting knows we are done
2736 * updating everything for this ordered extent.
2738 btrfs_remove_ordered_extent(inode, ordered_extent);
2740 /* for snapshot-aware defrag */
2742 relink_file_extents(new);
2745 btrfs_put_ordered_extent(ordered_extent);
2746 /* once for the tree */
2747 btrfs_put_ordered_extent(ordered_extent);
2752 static void finish_ordered_fn(struct btrfs_work *work)
2754 struct btrfs_ordered_extent *ordered_extent;
2755 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2756 btrfs_finish_ordered_io(ordered_extent);
2759 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2760 struct extent_state *state, int uptodate)
2762 struct inode *inode = page->mapping->host;
2763 struct btrfs_root *root = BTRFS_I(inode)->root;
2764 struct btrfs_ordered_extent *ordered_extent = NULL;
2765 struct btrfs_workers *workers;
2767 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2769 ClearPagePrivate2(page);
2770 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2771 end - start + 1, uptodate))
2774 ordered_extent->work.func = finish_ordered_fn;
2775 ordered_extent->work.flags = 0;
2777 if (btrfs_is_free_space_inode(inode))
2778 workers = &root->fs_info->endio_freespace_worker;
2780 workers = &root->fs_info->endio_write_workers;
2781 btrfs_queue_worker(workers, &ordered_extent->work);
2787 * when reads are done, we need to check csums to verify the data is correct
2788 * if there's a match, we allow the bio to finish. If not, the code in
2789 * extent_io.c will try to find good copies for us.
2791 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2792 struct extent_state *state, int mirror)
2794 size_t offset = start - page_offset(page);
2795 struct inode *inode = page->mapping->host;
2796 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2798 u64 private = ~(u32)0;
2800 struct btrfs_root *root = BTRFS_I(inode)->root;
2802 static DEFINE_RATELIMIT_STATE(_rs, DEFAULT_RATELIMIT_INTERVAL,
2803 DEFAULT_RATELIMIT_BURST);
2805 if (PageChecked(page)) {
2806 ClearPageChecked(page);
2810 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2813 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2814 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2815 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2820 if (state && state->start == start) {
2821 private = state->private;
2824 ret = get_state_private(io_tree, start, &private);
2826 kaddr = kmap_atomic(page);
2830 csum = btrfs_csum_data(kaddr + offset, csum, end - start + 1);
2831 btrfs_csum_final(csum, (char *)&csum);
2832 if (csum != private)
2835 kunmap_atomic(kaddr);
2840 if (__ratelimit(&_rs))
2841 btrfs_info(root->fs_info, "csum failed ino %llu off %llu csum %u private %llu",
2842 (unsigned long long)btrfs_ino(page->mapping->host),
2843 (unsigned long long)start, csum,
2844 (unsigned long long)private);
2845 memset(kaddr + offset, 1, end - start + 1);
2846 flush_dcache_page(page);
2847 kunmap_atomic(kaddr);
2853 struct delayed_iput {
2854 struct list_head list;
2855 struct inode *inode;
2858 /* JDM: If this is fs-wide, why can't we add a pointer to
2859 * btrfs_inode instead and avoid the allocation? */
2860 void btrfs_add_delayed_iput(struct inode *inode)
2862 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2863 struct delayed_iput *delayed;
2865 if (atomic_add_unless(&inode->i_count, -1, 1))
2868 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2869 delayed->inode = inode;
2871 spin_lock(&fs_info->delayed_iput_lock);
2872 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2873 spin_unlock(&fs_info->delayed_iput_lock);
2876 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2879 struct btrfs_fs_info *fs_info = root->fs_info;
2880 struct delayed_iput *delayed;
2883 spin_lock(&fs_info->delayed_iput_lock);
2884 empty = list_empty(&fs_info->delayed_iputs);
2885 spin_unlock(&fs_info->delayed_iput_lock);
2889 spin_lock(&fs_info->delayed_iput_lock);
2890 list_splice_init(&fs_info->delayed_iputs, &list);
2891 spin_unlock(&fs_info->delayed_iput_lock);
2893 while (!list_empty(&list)) {
2894 delayed = list_entry(list.next, struct delayed_iput, list);
2895 list_del(&delayed->list);
2896 iput(delayed->inode);
2902 * This is called in transaction commit time. If there are no orphan
2903 * files in the subvolume, it removes orphan item and frees block_rsv
2906 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2907 struct btrfs_root *root)
2909 struct btrfs_block_rsv *block_rsv;
2912 if (atomic_read(&root->orphan_inodes) ||
2913 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2916 spin_lock(&root->orphan_lock);
2917 if (atomic_read(&root->orphan_inodes)) {
2918 spin_unlock(&root->orphan_lock);
2922 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2923 spin_unlock(&root->orphan_lock);
2927 block_rsv = root->orphan_block_rsv;
2928 root->orphan_block_rsv = NULL;
2929 spin_unlock(&root->orphan_lock);
2931 if (root->orphan_item_inserted &&
2932 btrfs_root_refs(&root->root_item) > 0) {
2933 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2934 root->root_key.objectid);
2936 root->orphan_item_inserted = 0;
2940 WARN_ON(block_rsv->size > 0);
2941 btrfs_free_block_rsv(root, block_rsv);
2946 * This creates an orphan entry for the given inode in case something goes
2947 * wrong in the middle of an unlink/truncate.
2949 * NOTE: caller of this function should reserve 5 units of metadata for
2952 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2954 struct btrfs_root *root = BTRFS_I(inode)->root;
2955 struct btrfs_block_rsv *block_rsv = NULL;
2960 if (!root->orphan_block_rsv) {
2961 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2966 spin_lock(&root->orphan_lock);
2967 if (!root->orphan_block_rsv) {
2968 root->orphan_block_rsv = block_rsv;
2969 } else if (block_rsv) {
2970 btrfs_free_block_rsv(root, block_rsv);
2974 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2975 &BTRFS_I(inode)->runtime_flags)) {
2978 * For proper ENOSPC handling, we should do orphan
2979 * cleanup when mounting. But this introduces backward
2980 * compatibility issue.
2982 if (!xchg(&root->orphan_item_inserted, 1))
2988 atomic_inc(&root->orphan_inodes);
2991 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2992 &BTRFS_I(inode)->runtime_flags))
2994 spin_unlock(&root->orphan_lock);
2996 /* grab metadata reservation from transaction handle */
2998 ret = btrfs_orphan_reserve_metadata(trans, inode);
2999 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3002 /* insert an orphan item to track this unlinked/truncated file */
3004 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3005 if (ret && ret != -EEXIST) {
3006 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3007 &BTRFS_I(inode)->runtime_flags);
3008 btrfs_abort_transaction(trans, root, ret);
3014 /* insert an orphan item to track subvolume contains orphan files */
3016 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3017 root->root_key.objectid);
3018 if (ret && ret != -EEXIST) {
3019 btrfs_abort_transaction(trans, root, ret);
3027 * We have done the truncate/delete so we can go ahead and remove the orphan
3028 * item for this particular inode.
3030 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3031 struct inode *inode)
3033 struct btrfs_root *root = BTRFS_I(inode)->root;
3034 int delete_item = 0;
3035 int release_rsv = 0;
3038 spin_lock(&root->orphan_lock);
3039 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3040 &BTRFS_I(inode)->runtime_flags))
3043 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3044 &BTRFS_I(inode)->runtime_flags))
3046 spin_unlock(&root->orphan_lock);
3048 if (trans && delete_item) {
3049 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
3050 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3054 btrfs_orphan_release_metadata(inode);
3055 atomic_dec(&root->orphan_inodes);
3062 * this cleans up any orphans that may be left on the list from the last use
3065 int btrfs_orphan_cleanup(struct btrfs_root *root)
3067 struct btrfs_path *path;
3068 struct extent_buffer *leaf;
3069 struct btrfs_key key, found_key;
3070 struct btrfs_trans_handle *trans;
3071 struct inode *inode;
3072 u64 last_objectid = 0;
3073 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3075 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3078 path = btrfs_alloc_path();
3085 key.objectid = BTRFS_ORPHAN_OBJECTID;
3086 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
3087 key.offset = (u64)-1;
3090 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3095 * if ret == 0 means we found what we were searching for, which
3096 * is weird, but possible, so only screw with path if we didn't
3097 * find the key and see if we have stuff that matches
3101 if (path->slots[0] == 0)
3106 /* pull out the item */
3107 leaf = path->nodes[0];
3108 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3110 /* make sure the item matches what we want */
3111 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3113 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
3116 /* release the path since we're done with it */
3117 btrfs_release_path(path);
3120 * this is where we are basically btrfs_lookup, without the
3121 * crossing root thing. we store the inode number in the
3122 * offset of the orphan item.
3125 if (found_key.offset == last_objectid) {
3126 btrfs_err(root->fs_info,
3127 "Error removing orphan entry, stopping orphan cleanup");
3132 last_objectid = found_key.offset;
3134 found_key.objectid = found_key.offset;
3135 found_key.type = BTRFS_INODE_ITEM_KEY;
3136 found_key.offset = 0;
3137 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3138 ret = PTR_RET(inode);
3139 if (ret && ret != -ESTALE)
3142 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3143 struct btrfs_root *dead_root;
3144 struct btrfs_fs_info *fs_info = root->fs_info;
3145 int is_dead_root = 0;
3148 * this is an orphan in the tree root. Currently these
3149 * could come from 2 sources:
3150 * a) a snapshot deletion in progress
3151 * b) a free space cache inode
3152 * We need to distinguish those two, as the snapshot
3153 * orphan must not get deleted.
3154 * find_dead_roots already ran before us, so if this
3155 * is a snapshot deletion, we should find the root
3156 * in the dead_roots list
3158 spin_lock(&fs_info->trans_lock);
3159 list_for_each_entry(dead_root, &fs_info->dead_roots,
3161 if (dead_root->root_key.objectid ==
3162 found_key.objectid) {
3167 spin_unlock(&fs_info->trans_lock);
3169 /* prevent this orphan from being found again */
3170 key.offset = found_key.objectid - 1;
3175 * Inode is already gone but the orphan item is still there,
3176 * kill the orphan item.
3178 if (ret == -ESTALE) {
3179 trans = btrfs_start_transaction(root, 1);
3180 if (IS_ERR(trans)) {
3181 ret = PTR_ERR(trans);
3184 btrfs_debug(root->fs_info, "auto deleting %Lu",
3185 found_key.objectid);
3186 ret = btrfs_del_orphan_item(trans, root,
3187 found_key.objectid);
3188 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
3189 btrfs_end_transaction(trans, root);
3194 * add this inode to the orphan list so btrfs_orphan_del does
3195 * the proper thing when we hit it
3197 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3198 &BTRFS_I(inode)->runtime_flags);
3199 atomic_inc(&root->orphan_inodes);
3201 /* if we have links, this was a truncate, lets do that */
3202 if (inode->i_nlink) {
3203 if (!S_ISREG(inode->i_mode)) {
3210 /* 1 for the orphan item deletion. */
3211 trans = btrfs_start_transaction(root, 1);
3212 if (IS_ERR(trans)) {
3213 ret = PTR_ERR(trans);
3216 ret = btrfs_orphan_add(trans, inode);
3217 btrfs_end_transaction(trans, root);
3221 ret = btrfs_truncate(inode);
3223 btrfs_orphan_del(NULL, inode);
3228 /* this will do delete_inode and everything for us */
3233 /* release the path since we're done with it */
3234 btrfs_release_path(path);
3236 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3238 if (root->orphan_block_rsv)
3239 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3242 if (root->orphan_block_rsv || root->orphan_item_inserted) {
3243 trans = btrfs_join_transaction(root);
3245 btrfs_end_transaction(trans, root);
3249 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3251 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3255 btrfs_crit(root->fs_info,
3256 "could not do orphan cleanup %d", ret);
3257 btrfs_free_path(path);
3262 * very simple check to peek ahead in the leaf looking for xattrs. If we
3263 * don't find any xattrs, we know there can't be any acls.
3265 * slot is the slot the inode is in, objectid is the objectid of the inode
3267 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3268 int slot, u64 objectid)
3270 u32 nritems = btrfs_header_nritems(leaf);
3271 struct btrfs_key found_key;
3275 while (slot < nritems) {
3276 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3278 /* we found a different objectid, there must not be acls */
3279 if (found_key.objectid != objectid)
3282 /* we found an xattr, assume we've got an acl */
3283 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
3287 * we found a key greater than an xattr key, there can't
3288 * be any acls later on
3290 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3297 * it goes inode, inode backrefs, xattrs, extents,
3298 * so if there are a ton of hard links to an inode there can
3299 * be a lot of backrefs. Don't waste time searching too hard,
3300 * this is just an optimization
3305 /* we hit the end of the leaf before we found an xattr or
3306 * something larger than an xattr. We have to assume the inode
3313 * read an inode from the btree into the in-memory inode
3315 static void btrfs_read_locked_inode(struct inode *inode)
3317 struct btrfs_path *path;
3318 struct extent_buffer *leaf;
3319 struct btrfs_inode_item *inode_item;
3320 struct btrfs_timespec *tspec;
3321 struct btrfs_root *root = BTRFS_I(inode)->root;
3322 struct btrfs_key location;
3326 bool filled = false;
3328 ret = btrfs_fill_inode(inode, &rdev);
3332 path = btrfs_alloc_path();
3336 path->leave_spinning = 1;
3337 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3339 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3343 leaf = path->nodes[0];
3348 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3349 struct btrfs_inode_item);
3350 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3351 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3352 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3353 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3354 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3356 tspec = btrfs_inode_atime(inode_item);
3357 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3358 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3360 tspec = btrfs_inode_mtime(inode_item);
3361 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3362 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3364 tspec = btrfs_inode_ctime(inode_item);
3365 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
3366 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
3368 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3369 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3370 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3373 * If we were modified in the current generation and evicted from memory
3374 * and then re-read we need to do a full sync since we don't have any
3375 * idea about which extents were modified before we were evicted from
3378 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3379 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3380 &BTRFS_I(inode)->runtime_flags);
3382 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3383 inode->i_generation = BTRFS_I(inode)->generation;
3385 rdev = btrfs_inode_rdev(leaf, inode_item);
3387 BTRFS_I(inode)->index_cnt = (u64)-1;
3388 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3391 * try to precache a NULL acl entry for files that don't have
3392 * any xattrs or acls
3394 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3397 cache_no_acl(inode);
3399 btrfs_free_path(path);
3401 switch (inode->i_mode & S_IFMT) {
3403 inode->i_mapping->a_ops = &btrfs_aops;
3404 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3405 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3406 inode->i_fop = &btrfs_file_operations;
3407 inode->i_op = &btrfs_file_inode_operations;
3410 inode->i_fop = &btrfs_dir_file_operations;
3411 if (root == root->fs_info->tree_root)
3412 inode->i_op = &btrfs_dir_ro_inode_operations;
3414 inode->i_op = &btrfs_dir_inode_operations;
3417 inode->i_op = &btrfs_symlink_inode_operations;
3418 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3419 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
3422 inode->i_op = &btrfs_special_inode_operations;
3423 init_special_inode(inode, inode->i_mode, rdev);
3427 btrfs_update_iflags(inode);
3431 btrfs_free_path(path);
3432 make_bad_inode(inode);
3436 * given a leaf and an inode, copy the inode fields into the leaf
3438 static void fill_inode_item(struct btrfs_trans_handle *trans,
3439 struct extent_buffer *leaf,
3440 struct btrfs_inode_item *item,
3441 struct inode *inode)
3443 struct btrfs_map_token token;
3445 btrfs_init_map_token(&token);
3447 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3448 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3449 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3451 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3452 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3454 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
3455 inode->i_atime.tv_sec, &token);
3456 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
3457 inode->i_atime.tv_nsec, &token);
3459 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
3460 inode->i_mtime.tv_sec, &token);
3461 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
3462 inode->i_mtime.tv_nsec, &token);
3464 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
3465 inode->i_ctime.tv_sec, &token);
3466 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
3467 inode->i_ctime.tv_nsec, &token);
3469 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3471 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3473 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3474 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3475 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3476 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3477 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3481 * copy everything in the in-memory inode into the btree.
3483 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3484 struct btrfs_root *root, struct inode *inode)
3486 struct btrfs_inode_item *inode_item;
3487 struct btrfs_path *path;
3488 struct extent_buffer *leaf;
3491 path = btrfs_alloc_path();
3495 path->leave_spinning = 1;
3496 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3504 btrfs_unlock_up_safe(path, 1);
3505 leaf = path->nodes[0];
3506 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3507 struct btrfs_inode_item);
3509 fill_inode_item(trans, leaf, inode_item, inode);
3510 btrfs_mark_buffer_dirty(leaf);
3511 btrfs_set_inode_last_trans(trans, inode);
3514 btrfs_free_path(path);
3519 * copy everything in the in-memory inode into the btree.
3521 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3522 struct btrfs_root *root, struct inode *inode)
3527 * If the inode is a free space inode, we can deadlock during commit
3528 * if we put it into the delayed code.
3530 * The data relocation inode should also be directly updated
3533 if (!btrfs_is_free_space_inode(inode)
3534 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
3535 btrfs_update_root_times(trans, root);
3537 ret = btrfs_delayed_update_inode(trans, root, inode);
3539 btrfs_set_inode_last_trans(trans, inode);
3543 return btrfs_update_inode_item(trans, root, inode);
3546 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3547 struct btrfs_root *root,
3548 struct inode *inode)
3552 ret = btrfs_update_inode(trans, root, inode);
3554 return btrfs_update_inode_item(trans, root, inode);
3559 * unlink helper that gets used here in inode.c and in the tree logging
3560 * recovery code. It remove a link in a directory with a given name, and
3561 * also drops the back refs in the inode to the directory
3563 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3564 struct btrfs_root *root,
3565 struct inode *dir, struct inode *inode,
3566 const char *name, int name_len)
3568 struct btrfs_path *path;
3570 struct extent_buffer *leaf;
3571 struct btrfs_dir_item *di;
3572 struct btrfs_key key;
3574 u64 ino = btrfs_ino(inode);
3575 u64 dir_ino = btrfs_ino(dir);
3577 path = btrfs_alloc_path();
3583 path->leave_spinning = 1;
3584 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3585 name, name_len, -1);
3594 leaf = path->nodes[0];
3595 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3596 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3599 btrfs_release_path(path);
3601 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3604 btrfs_info(root->fs_info,
3605 "failed to delete reference to %.*s, inode %llu parent %llu",
3607 (unsigned long long)ino, (unsigned long long)dir_ino);
3608 btrfs_abort_transaction(trans, root, ret);
3612 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3614 btrfs_abort_transaction(trans, root, ret);
3618 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
3620 if (ret != 0 && ret != -ENOENT) {
3621 btrfs_abort_transaction(trans, root, ret);
3625 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
3630 btrfs_abort_transaction(trans, root, ret);
3632 btrfs_free_path(path);
3636 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3637 inode_inc_iversion(inode);
3638 inode_inc_iversion(dir);
3639 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3640 ret = btrfs_update_inode(trans, root, dir);
3645 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3646 struct btrfs_root *root,
3647 struct inode *dir, struct inode *inode,
3648 const char *name, int name_len)
3651 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3653 btrfs_drop_nlink(inode);
3654 ret = btrfs_update_inode(trans, root, inode);
3660 /* helper to check if there is any shared block in the path */
3661 static int check_path_shared(struct btrfs_root *root,
3662 struct btrfs_path *path)
3664 struct extent_buffer *eb;
3668 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
3671 if (!path->nodes[level])
3673 eb = path->nodes[level];
3674 if (!btrfs_block_can_be_shared(root, eb))
3676 ret = btrfs_lookup_extent_info(NULL, root, eb->start, level, 1,
3685 * helper to start transaction for unlink and rmdir.
3687 * unlink and rmdir are special in btrfs, they do not always free space.
3688 * so in enospc case, we should make sure they will free space before
3689 * allowing them to use the global metadata reservation.
3691 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
3692 struct dentry *dentry)
3694 struct btrfs_trans_handle *trans;
3695 struct btrfs_root *root = BTRFS_I(dir)->root;
3696 struct btrfs_path *path;
3697 struct btrfs_dir_item *di;
3698 struct inode *inode = dentry->d_inode;
3703 u64 ino = btrfs_ino(inode);
3704 u64 dir_ino = btrfs_ino(dir);
3707 * 1 for the possible orphan item
3708 * 1 for the dir item
3709 * 1 for the dir index
3710 * 1 for the inode ref
3713 trans = btrfs_start_transaction(root, 5);
3714 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3717 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
3718 return ERR_PTR(-ENOSPC);
3720 /* check if there is someone else holds reference */
3721 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
3722 return ERR_PTR(-ENOSPC);
3724 if (atomic_read(&inode->i_count) > 2)
3725 return ERR_PTR(-ENOSPC);
3727 if (xchg(&root->fs_info->enospc_unlink, 1))
3728 return ERR_PTR(-ENOSPC);
3730 path = btrfs_alloc_path();
3732 root->fs_info->enospc_unlink = 0;
3733 return ERR_PTR(-ENOMEM);
3736 /* 1 for the orphan item */
3737 trans = btrfs_start_transaction(root, 1);
3738 if (IS_ERR(trans)) {
3739 btrfs_free_path(path);
3740 root->fs_info->enospc_unlink = 0;
3744 path->skip_locking = 1;
3745 path->search_commit_root = 1;
3747 ret = btrfs_lookup_inode(trans, root, path,
3748 &BTRFS_I(dir)->location, 0);
3754 if (check_path_shared(root, path))
3759 btrfs_release_path(path);
3761 ret = btrfs_lookup_inode(trans, root, path,
3762 &BTRFS_I(inode)->location, 0);
3768 if (check_path_shared(root, path))
3773 btrfs_release_path(path);
3775 if (ret == 0 && S_ISREG(inode->i_mode)) {
3776 ret = btrfs_lookup_file_extent(trans, root, path,
3782 BUG_ON(ret == 0); /* Corruption */
3783 if (check_path_shared(root, path))
3785 btrfs_release_path(path);
3793 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3794 dentry->d_name.name, dentry->d_name.len, 0);
3800 if (check_path_shared(root, path))
3806 btrfs_release_path(path);
3808 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3809 dentry->d_name.len, ino, dir_ino, 0,
3816 if (check_path_shared(root, path))
3819 btrfs_release_path(path);
3822 * This is a commit root search, if we can lookup inode item and other
3823 * relative items in the commit root, it means the transaction of
3824 * dir/file creation has been committed, and the dir index item that we
3825 * delay to insert has also been inserted into the commit root. So
3826 * we needn't worry about the delayed insertion of the dir index item
3829 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3830 dentry->d_name.name, dentry->d_name.len, 0);
3835 BUG_ON(ret == -ENOENT);
3836 if (check_path_shared(root, path))
3841 btrfs_free_path(path);
3842 /* Migrate the orphan reservation over */
3844 err = btrfs_block_rsv_migrate(trans->block_rsv,
3845 &root->fs_info->global_block_rsv,
3846 trans->bytes_reserved);
3849 btrfs_end_transaction(trans, root);
3850 root->fs_info->enospc_unlink = 0;
3851 return ERR_PTR(err);
3854 trans->block_rsv = &root->fs_info->global_block_rsv;
3858 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3859 struct btrfs_root *root)
3861 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3862 btrfs_block_rsv_release(root, trans->block_rsv,
3863 trans->bytes_reserved);
3864 trans->block_rsv = &root->fs_info->trans_block_rsv;
3865 BUG_ON(!root->fs_info->enospc_unlink);
3866 root->fs_info->enospc_unlink = 0;
3868 btrfs_end_transaction(trans, root);
3871 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3873 struct btrfs_root *root = BTRFS_I(dir)->root;
3874 struct btrfs_trans_handle *trans;
3875 struct inode *inode = dentry->d_inode;
3878 trans = __unlink_start_trans(dir, dentry);
3880 return PTR_ERR(trans);
3882 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3884 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3885 dentry->d_name.name, dentry->d_name.len);
3889 if (inode->i_nlink == 0) {
3890 ret = btrfs_orphan_add(trans, inode);
3896 __unlink_end_trans(trans, root);
3897 btrfs_btree_balance_dirty(root);
3901 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3902 struct btrfs_root *root,
3903 struct inode *dir, u64 objectid,
3904 const char *name, int name_len)
3906 struct btrfs_path *path;
3907 struct extent_buffer *leaf;
3908 struct btrfs_dir_item *di;
3909 struct btrfs_key key;
3912 u64 dir_ino = btrfs_ino(dir);
3914 path = btrfs_alloc_path();
3918 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3919 name, name_len, -1);
3920 if (IS_ERR_OR_NULL(di)) {
3928 leaf = path->nodes[0];
3929 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3930 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3931 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3933 btrfs_abort_transaction(trans, root, ret);
3936 btrfs_release_path(path);
3938 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3939 objectid, root->root_key.objectid,
3940 dir_ino, &index, name, name_len);
3942 if (ret != -ENOENT) {
3943 btrfs_abort_transaction(trans, root, ret);
3946 di = btrfs_search_dir_index_item(root, path, dir_ino,
3948 if (IS_ERR_OR_NULL(di)) {
3953 btrfs_abort_transaction(trans, root, ret);
3957 leaf = path->nodes[0];
3958 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3959 btrfs_release_path(path);
3962 btrfs_release_path(path);
3964 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3966 btrfs_abort_transaction(trans, root, ret);
3970 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3971 inode_inc_iversion(dir);
3972 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3973 ret = btrfs_update_inode_fallback(trans, root, dir);
3975 btrfs_abort_transaction(trans, root, ret);
3977 btrfs_free_path(path);
3981 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3983 struct inode *inode = dentry->d_inode;
3985 struct btrfs_root *root = BTRFS_I(dir)->root;
3986 struct btrfs_trans_handle *trans;
3988 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3990 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3993 trans = __unlink_start_trans(dir, dentry);
3995 return PTR_ERR(trans);
3997 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3998 err = btrfs_unlink_subvol(trans, root, dir,
3999 BTRFS_I(inode)->location.objectid,
4000 dentry->d_name.name,
4001 dentry->d_name.len);
4005 err = btrfs_orphan_add(trans, inode);
4009 /* now the directory is empty */
4010 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
4011 dentry->d_name.name, dentry->d_name.len);
4013 btrfs_i_size_write(inode, 0);
4015 __unlink_end_trans(trans, root);
4016 btrfs_btree_balance_dirty(root);
4022 * this can truncate away extent items, csum items and directory items.
4023 * It starts at a high offset and removes keys until it can't find
4024 * any higher than new_size
4026 * csum items that cross the new i_size are truncated to the new size
4029 * min_type is the minimum key type to truncate down to. If set to 0, this
4030 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4032 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4033 struct btrfs_root *root,
4034 struct inode *inode,
4035 u64 new_size, u32 min_type)
4037 struct btrfs_path *path;
4038 struct extent_buffer *leaf;
4039 struct btrfs_file_extent_item *fi;
4040 struct btrfs_key key;
4041 struct btrfs_key found_key;
4042 u64 extent_start = 0;
4043 u64 extent_num_bytes = 0;
4044 u64 extent_offset = 0;
4046 u32 found_type = (u8)-1;
4049 int pending_del_nr = 0;
4050 int pending_del_slot = 0;
4051 int extent_type = -1;
4054 u64 ino = btrfs_ino(inode);
4056 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4058 path = btrfs_alloc_path();
4064 * We want to drop from the next block forward in case this new size is
4065 * not block aligned since we will be keeping the last block of the
4066 * extent just the way it is.
4068 if (root->ref_cows || root == root->fs_info->tree_root)
4069 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4070 root->sectorsize), (u64)-1, 0);
4073 * This function is also used to drop the items in the log tree before
4074 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4075 * it is used to drop the loged items. So we shouldn't kill the delayed
4078 if (min_type == 0 && root == BTRFS_I(inode)->root)
4079 btrfs_kill_delayed_inode_items(inode);
4082 key.offset = (u64)-1;
4086 path->leave_spinning = 1;
4087 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4094 /* there are no items in the tree for us to truncate, we're
4097 if (path->slots[0] == 0)
4104 leaf = path->nodes[0];
4105 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4106 found_type = btrfs_key_type(&found_key);
4108 if (found_key.objectid != ino)
4111 if (found_type < min_type)
4114 item_end = found_key.offset;
4115 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4116 fi = btrfs_item_ptr(leaf, path->slots[0],
4117 struct btrfs_file_extent_item);
4118 extent_type = btrfs_file_extent_type(leaf, fi);
4119 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4121 btrfs_file_extent_num_bytes(leaf, fi);
4122 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4123 item_end += btrfs_file_extent_inline_len(leaf,
4128 if (found_type > min_type) {
4131 if (item_end < new_size)
4133 if (found_key.offset >= new_size)
4139 /* FIXME, shrink the extent if the ref count is only 1 */
4140 if (found_type != BTRFS_EXTENT_DATA_KEY)
4143 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4145 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4147 u64 orig_num_bytes =
4148 btrfs_file_extent_num_bytes(leaf, fi);
4149 extent_num_bytes = ALIGN(new_size -
4152 btrfs_set_file_extent_num_bytes(leaf, fi,
4154 num_dec = (orig_num_bytes -
4156 if (root->ref_cows && extent_start != 0)
4157 inode_sub_bytes(inode, num_dec);
4158 btrfs_mark_buffer_dirty(leaf);
4161 btrfs_file_extent_disk_num_bytes(leaf,
4163 extent_offset = found_key.offset -
4164 btrfs_file_extent_offset(leaf, fi);
4166 /* FIXME blocksize != 4096 */
4167 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4168 if (extent_start != 0) {
4171 inode_sub_bytes(inode, num_dec);
4174 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4176 * we can't truncate inline items that have had
4180 btrfs_file_extent_compression(leaf, fi) == 0 &&
4181 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4182 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4183 u32 size = new_size - found_key.offset;
4185 if (root->ref_cows) {
4186 inode_sub_bytes(inode, item_end + 1 -
4190 btrfs_file_extent_calc_inline_size(size);
4191 btrfs_truncate_item(root, path, size, 1);
4192 } else if (root->ref_cows) {
4193 inode_sub_bytes(inode, item_end + 1 -
4199 if (!pending_del_nr) {
4200 /* no pending yet, add ourselves */
4201 pending_del_slot = path->slots[0];
4203 } else if (pending_del_nr &&
4204 path->slots[0] + 1 == pending_del_slot) {
4205 /* hop on the pending chunk */
4207 pending_del_slot = path->slots[0];
4214 if (found_extent && (root->ref_cows ||
4215 root == root->fs_info->tree_root)) {
4216 btrfs_set_path_blocking(path);
4217 ret = btrfs_free_extent(trans, root, extent_start,
4218 extent_num_bytes, 0,
4219 btrfs_header_owner(leaf),
4220 ino, extent_offset, 0);
4224 if (found_type == BTRFS_INODE_ITEM_KEY)
4227 if (path->slots[0] == 0 ||
4228 path->slots[0] != pending_del_slot) {
4229 if (pending_del_nr) {
4230 ret = btrfs_del_items(trans, root, path,
4234 btrfs_abort_transaction(trans,
4240 btrfs_release_path(path);
4247 if (pending_del_nr) {
4248 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4251 btrfs_abort_transaction(trans, root, ret);
4254 btrfs_free_path(path);
4259 * btrfs_truncate_page - read, zero a chunk and write a page
4260 * @inode - inode that we're zeroing
4261 * @from - the offset to start zeroing
4262 * @len - the length to zero, 0 to zero the entire range respective to the
4264 * @front - zero up to the offset instead of from the offset on
4266 * This will find the page for the "from" offset and cow the page and zero the
4267 * part we want to zero. This is used with truncate and hole punching.
4269 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4272 struct address_space *mapping = inode->i_mapping;
4273 struct btrfs_root *root = BTRFS_I(inode)->root;
4274 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4275 struct btrfs_ordered_extent *ordered;
4276 struct extent_state *cached_state = NULL;
4278 u32 blocksize = root->sectorsize;
4279 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4280 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4282 gfp_t mask = btrfs_alloc_write_mask(mapping);
4287 if ((offset & (blocksize - 1)) == 0 &&
4288 (!len || ((len & (blocksize - 1)) == 0)))
4290 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
4295 page = find_or_create_page(mapping, index, mask);
4297 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4302 page_start = page_offset(page);
4303 page_end = page_start + PAGE_CACHE_SIZE - 1;
4305 if (!PageUptodate(page)) {
4306 ret = btrfs_readpage(NULL, page);
4308 if (page->mapping != mapping) {
4310 page_cache_release(page);
4313 if (!PageUptodate(page)) {
4318 wait_on_page_writeback(page);
4320 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4321 set_page_extent_mapped(page);
4323 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4325 unlock_extent_cached(io_tree, page_start, page_end,
4326 &cached_state, GFP_NOFS);
4328 page_cache_release(page);
4329 btrfs_start_ordered_extent(inode, ordered, 1);
4330 btrfs_put_ordered_extent(ordered);
4334 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4335 EXTENT_DIRTY | EXTENT_DELALLOC |
4336 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4337 0, 0, &cached_state, GFP_NOFS);
4339 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4342 unlock_extent_cached(io_tree, page_start, page_end,
4343 &cached_state, GFP_NOFS);
4347 if (offset != PAGE_CACHE_SIZE) {
4349 len = PAGE_CACHE_SIZE - offset;
4352 memset(kaddr, 0, offset);
4354 memset(kaddr + offset, 0, len);
4355 flush_dcache_page(page);
4358 ClearPageChecked(page);
4359 set_page_dirty(page);
4360 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4365 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
4367 page_cache_release(page);
4373 * This function puts in dummy file extents for the area we're creating a hole
4374 * for. So if we are truncating this file to a larger size we need to insert
4375 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4376 * the range between oldsize and size
4378 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4380 struct btrfs_trans_handle *trans;
4381 struct btrfs_root *root = BTRFS_I(inode)->root;
4382 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4383 struct extent_map *em = NULL;
4384 struct extent_state *cached_state = NULL;
4385 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4386 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4387 u64 block_end = ALIGN(size, root->sectorsize);
4393 if (size <= hole_start)
4397 struct btrfs_ordered_extent *ordered;
4398 btrfs_wait_ordered_range(inode, hole_start,
4399 block_end - hole_start);
4400 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4402 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
4405 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4406 &cached_state, GFP_NOFS);
4407 btrfs_put_ordered_extent(ordered);
4410 cur_offset = hole_start;
4412 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4413 block_end - cur_offset, 0);
4419 last_byte = min(extent_map_end(em), block_end);
4420 last_byte = ALIGN(last_byte , root->sectorsize);
4421 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4422 struct extent_map *hole_em;
4423 hole_size = last_byte - cur_offset;
4425 trans = btrfs_start_transaction(root, 3);
4426 if (IS_ERR(trans)) {
4427 err = PTR_ERR(trans);
4431 err = btrfs_drop_extents(trans, root, inode,
4433 cur_offset + hole_size, 1);
4435 btrfs_abort_transaction(trans, root, err);
4436 btrfs_end_transaction(trans, root);
4440 err = btrfs_insert_file_extent(trans, root,
4441 btrfs_ino(inode), cur_offset, 0,
4442 0, hole_size, 0, hole_size,
4445 btrfs_abort_transaction(trans, root, err);
4446 btrfs_end_transaction(trans, root);
4450 btrfs_drop_extent_cache(inode, cur_offset,
4451 cur_offset + hole_size - 1, 0);
4452 hole_em = alloc_extent_map();
4454 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4455 &BTRFS_I(inode)->runtime_flags);
4458 hole_em->start = cur_offset;
4459 hole_em->len = hole_size;
4460 hole_em->orig_start = cur_offset;
4462 hole_em->block_start = EXTENT_MAP_HOLE;
4463 hole_em->block_len = 0;
4464 hole_em->orig_block_len = 0;
4465 hole_em->ram_bytes = hole_size;
4466 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4467 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4468 hole_em->generation = trans->transid;
4471 write_lock(&em_tree->lock);
4472 err = add_extent_mapping(em_tree, hole_em, 1);
4473 write_unlock(&em_tree->lock);
4476 btrfs_drop_extent_cache(inode, cur_offset,
4480 free_extent_map(hole_em);
4482 btrfs_update_inode(trans, root, inode);
4483 btrfs_end_transaction(trans, root);
4485 free_extent_map(em);
4487 cur_offset = last_byte;
4488 if (cur_offset >= block_end)
4492 free_extent_map(em);
4493 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4498 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4500 struct btrfs_root *root = BTRFS_I(inode)->root;
4501 struct btrfs_trans_handle *trans;
4502 loff_t oldsize = i_size_read(inode);
4503 loff_t newsize = attr->ia_size;
4504 int mask = attr->ia_valid;
4507 if (newsize == oldsize)
4511 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4512 * special case where we need to update the times despite not having
4513 * these flags set. For all other operations the VFS set these flags
4514 * explicitly if it wants a timestamp update.
4516 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
4517 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
4519 if (newsize > oldsize) {
4520 truncate_pagecache(inode, oldsize, newsize);
4521 ret = btrfs_cont_expand(inode, oldsize, newsize);
4525 trans = btrfs_start_transaction(root, 1);
4527 return PTR_ERR(trans);
4529 i_size_write(inode, newsize);
4530 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4531 ret = btrfs_update_inode(trans, root, inode);
4532 btrfs_end_transaction(trans, root);
4536 * We're truncating a file that used to have good data down to
4537 * zero. Make sure it gets into the ordered flush list so that
4538 * any new writes get down to disk quickly.
4541 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4542 &BTRFS_I(inode)->runtime_flags);
4545 * 1 for the orphan item we're going to add
4546 * 1 for the orphan item deletion.
4548 trans = btrfs_start_transaction(root, 2);
4550 return PTR_ERR(trans);
4553 * We need to do this in case we fail at _any_ point during the
4554 * actual truncate. Once we do the truncate_setsize we could
4555 * invalidate pages which forces any outstanding ordered io to
4556 * be instantly completed which will give us extents that need
4557 * to be truncated. If we fail to get an orphan inode down we
4558 * could have left over extents that were never meant to live,
4559 * so we need to garuntee from this point on that everything
4560 * will be consistent.
4562 ret = btrfs_orphan_add(trans, inode);
4563 btrfs_end_transaction(trans, root);
4567 /* we don't support swapfiles, so vmtruncate shouldn't fail */
4568 truncate_setsize(inode, newsize);
4570 /* Disable nonlocked read DIO to avoid the end less truncate */
4571 btrfs_inode_block_unlocked_dio(inode);
4572 inode_dio_wait(inode);
4573 btrfs_inode_resume_unlocked_dio(inode);
4575 ret = btrfs_truncate(inode);
4576 if (ret && inode->i_nlink)
4577 btrfs_orphan_del(NULL, inode);
4583 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4585 struct inode *inode = dentry->d_inode;
4586 struct btrfs_root *root = BTRFS_I(inode)->root;
4589 if (btrfs_root_readonly(root))
4592 err = inode_change_ok(inode, attr);
4596 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4597 err = btrfs_setsize(inode, attr);
4602 if (attr->ia_valid) {
4603 setattr_copy(inode, attr);
4604 inode_inc_iversion(inode);
4605 err = btrfs_dirty_inode(inode);
4607 if (!err && attr->ia_valid & ATTR_MODE)
4608 err = btrfs_acl_chmod(inode);
4614 void btrfs_evict_inode(struct inode *inode)
4616 struct btrfs_trans_handle *trans;
4617 struct btrfs_root *root = BTRFS_I(inode)->root;
4618 struct btrfs_block_rsv *rsv, *global_rsv;
4619 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
4622 trace_btrfs_inode_evict(inode);
4624 truncate_inode_pages(&inode->i_data, 0);
4625 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
4626 btrfs_is_free_space_inode(inode)))
4629 if (is_bad_inode(inode)) {
4630 btrfs_orphan_del(NULL, inode);
4633 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
4634 btrfs_wait_ordered_range(inode, 0, (u64)-1);
4636 if (root->fs_info->log_root_recovering) {
4637 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
4638 &BTRFS_I(inode)->runtime_flags));
4642 if (inode->i_nlink > 0) {
4643 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
4647 ret = btrfs_commit_inode_delayed_inode(inode);
4649 btrfs_orphan_del(NULL, inode);
4653 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
4655 btrfs_orphan_del(NULL, inode);
4658 rsv->size = min_size;
4660 global_rsv = &root->fs_info->global_block_rsv;
4662 btrfs_i_size_write(inode, 0);
4665 * This is a bit simpler than btrfs_truncate since we've already
4666 * reserved our space for our orphan item in the unlink, so we just
4667 * need to reserve some slack space in case we add bytes and update
4668 * inode item when doing the truncate.
4671 ret = btrfs_block_rsv_refill(root, rsv, min_size,
4672 BTRFS_RESERVE_FLUSH_LIMIT);
4675 * Try and steal from the global reserve since we will
4676 * likely not use this space anyway, we want to try as
4677 * hard as possible to get this to work.
4680 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
4683 btrfs_warn(root->fs_info,
4684 "Could not get space for a delete, will truncate on mount %d",
4686 btrfs_orphan_del(NULL, inode);
4687 btrfs_free_block_rsv(root, rsv);
4691 trans = btrfs_join_transaction(root);
4692 if (IS_ERR(trans)) {
4693 btrfs_orphan_del(NULL, inode);
4694 btrfs_free_block_rsv(root, rsv);
4698 trans->block_rsv = rsv;
4700 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4704 trans->block_rsv = &root->fs_info->trans_block_rsv;
4705 btrfs_end_transaction(trans, root);
4707 btrfs_btree_balance_dirty(root);
4710 btrfs_free_block_rsv(root, rsv);
4713 trans->block_rsv = root->orphan_block_rsv;
4714 ret = btrfs_orphan_del(trans, inode);
4718 trans->block_rsv = &root->fs_info->trans_block_rsv;
4719 if (!(root == root->fs_info->tree_root ||
4720 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4721 btrfs_return_ino(root, btrfs_ino(inode));
4723 btrfs_end_transaction(trans, root);
4724 btrfs_btree_balance_dirty(root);
4731 * this returns the key found in the dir entry in the location pointer.
4732 * If no dir entries were found, location->objectid is 0.
4734 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4735 struct btrfs_key *location)
4737 const char *name = dentry->d_name.name;
4738 int namelen = dentry->d_name.len;
4739 struct btrfs_dir_item *di;
4740 struct btrfs_path *path;
4741 struct btrfs_root *root = BTRFS_I(dir)->root;
4744 path = btrfs_alloc_path();
4748 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4753 if (IS_ERR_OR_NULL(di))
4756 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4758 btrfs_free_path(path);
4761 location->objectid = 0;
4766 * when we hit a tree root in a directory, the btrfs part of the inode
4767 * needs to be changed to reflect the root directory of the tree root. This
4768 * is kind of like crossing a mount point.
4770 static int fixup_tree_root_location(struct btrfs_root *root,
4772 struct dentry *dentry,
4773 struct btrfs_key *location,
4774 struct btrfs_root **sub_root)
4776 struct btrfs_path *path;
4777 struct btrfs_root *new_root;
4778 struct btrfs_root_ref *ref;
4779 struct extent_buffer *leaf;
4783 path = btrfs_alloc_path();
4790 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4791 BTRFS_I(dir)->root->root_key.objectid,
4792 location->objectid);
4799 leaf = path->nodes[0];
4800 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4801 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4802 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4805 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4806 (unsigned long)(ref + 1),
4807 dentry->d_name.len);
4811 btrfs_release_path(path);
4813 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4814 if (IS_ERR(new_root)) {
4815 err = PTR_ERR(new_root);
4819 if (btrfs_root_refs(&new_root->root_item) == 0) {
4824 *sub_root = new_root;
4825 location->objectid = btrfs_root_dirid(&new_root->root_item);
4826 location->type = BTRFS_INODE_ITEM_KEY;
4827 location->offset = 0;
4830 btrfs_free_path(path);
4834 static void inode_tree_add(struct inode *inode)
4836 struct btrfs_root *root = BTRFS_I(inode)->root;
4837 struct btrfs_inode *entry;
4839 struct rb_node *parent;
4840 u64 ino = btrfs_ino(inode);
4842 p = &root->inode_tree.rb_node;
4845 if (inode_unhashed(inode))
4848 spin_lock(&root->inode_lock);
4851 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4853 if (ino < btrfs_ino(&entry->vfs_inode))
4854 p = &parent->rb_left;
4855 else if (ino > btrfs_ino(&entry->vfs_inode))
4856 p = &parent->rb_right;
4858 WARN_ON(!(entry->vfs_inode.i_state &
4859 (I_WILL_FREE | I_FREEING)));
4860 rb_erase(parent, &root->inode_tree);
4861 RB_CLEAR_NODE(parent);
4862 spin_unlock(&root->inode_lock);
4866 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4867 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4868 spin_unlock(&root->inode_lock);
4871 static void inode_tree_del(struct inode *inode)
4873 struct btrfs_root *root = BTRFS_I(inode)->root;
4876 spin_lock(&root->inode_lock);
4877 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4878 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4879 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4880 empty = RB_EMPTY_ROOT(&root->inode_tree);
4882 spin_unlock(&root->inode_lock);
4885 * Free space cache has inodes in the tree root, but the tree root has a
4886 * root_refs of 0, so this could end up dropping the tree root as a
4887 * snapshot, so we need the extra !root->fs_info->tree_root check to
4888 * make sure we don't drop it.
4890 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4891 root != root->fs_info->tree_root) {
4892 synchronize_srcu(&root->fs_info->subvol_srcu);
4893 spin_lock(&root->inode_lock);
4894 empty = RB_EMPTY_ROOT(&root->inode_tree);
4895 spin_unlock(&root->inode_lock);
4897 btrfs_add_dead_root(root);
4901 void btrfs_invalidate_inodes(struct btrfs_root *root)
4903 struct rb_node *node;
4904 struct rb_node *prev;
4905 struct btrfs_inode *entry;
4906 struct inode *inode;
4909 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4911 spin_lock(&root->inode_lock);
4913 node = root->inode_tree.rb_node;
4917 entry = rb_entry(node, struct btrfs_inode, rb_node);
4919 if (objectid < btrfs_ino(&entry->vfs_inode))
4920 node = node->rb_left;
4921 else if (objectid > btrfs_ino(&entry->vfs_inode))
4922 node = node->rb_right;
4928 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4929 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4933 prev = rb_next(prev);
4937 entry = rb_entry(node, struct btrfs_inode, rb_node);
4938 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4939 inode = igrab(&entry->vfs_inode);
4941 spin_unlock(&root->inode_lock);
4942 if (atomic_read(&inode->i_count) > 1)
4943 d_prune_aliases(inode);
4945 * btrfs_drop_inode will have it removed from
4946 * the inode cache when its usage count
4951 spin_lock(&root->inode_lock);
4955 if (cond_resched_lock(&root->inode_lock))
4958 node = rb_next(node);
4960 spin_unlock(&root->inode_lock);
4963 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4965 struct btrfs_iget_args *args = p;
4966 inode->i_ino = args->ino;
4967 BTRFS_I(inode)->root = args->root;
4971 static int btrfs_find_actor(struct inode *inode, void *opaque)
4973 struct btrfs_iget_args *args = opaque;
4974 return args->ino == btrfs_ino(inode) &&
4975 args->root == BTRFS_I(inode)->root;
4978 static struct inode *btrfs_iget_locked(struct super_block *s,
4980 struct btrfs_root *root)
4982 struct inode *inode;
4983 struct btrfs_iget_args args;
4984 args.ino = objectid;
4987 inode = iget5_locked(s, objectid, btrfs_find_actor,
4988 btrfs_init_locked_inode,
4993 /* Get an inode object given its location and corresponding root.
4994 * Returns in *is_new if the inode was read from disk
4996 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4997 struct btrfs_root *root, int *new)
4999 struct inode *inode;
5001 inode = btrfs_iget_locked(s, location->objectid, root);
5003 return ERR_PTR(-ENOMEM);
5005 if (inode->i_state & I_NEW) {
5006 BTRFS_I(inode)->root = root;
5007 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
5008 btrfs_read_locked_inode(inode);
5009 if (!is_bad_inode(inode)) {
5010 inode_tree_add(inode);
5011 unlock_new_inode(inode);
5015 unlock_new_inode(inode);
5017 inode = ERR_PTR(-ESTALE);
5024 static struct inode *new_simple_dir(struct super_block *s,
5025 struct btrfs_key *key,
5026 struct btrfs_root *root)
5028 struct inode *inode = new_inode(s);
5031 return ERR_PTR(-ENOMEM);
5033 BTRFS_I(inode)->root = root;
5034 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5035 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5037 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5038 inode->i_op = &btrfs_dir_ro_inode_operations;
5039 inode->i_fop = &simple_dir_operations;
5040 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5041 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5046 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5048 struct inode *inode;
5049 struct btrfs_root *root = BTRFS_I(dir)->root;
5050 struct btrfs_root *sub_root = root;
5051 struct btrfs_key location;
5055 if (dentry->d_name.len > BTRFS_NAME_LEN)
5056 return ERR_PTR(-ENAMETOOLONG);
5058 ret = btrfs_inode_by_name(dir, dentry, &location);
5060 return ERR_PTR(ret);
5062 if (location.objectid == 0)
5065 if (location.type == BTRFS_INODE_ITEM_KEY) {
5066 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5070 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5072 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5073 ret = fixup_tree_root_location(root, dir, dentry,
5074 &location, &sub_root);
5077 inode = ERR_PTR(ret);
5079 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5081 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5083 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5085 if (!IS_ERR(inode) && root != sub_root) {
5086 down_read(&root->fs_info->cleanup_work_sem);
5087 if (!(inode->i_sb->s_flags & MS_RDONLY))
5088 ret = btrfs_orphan_cleanup(sub_root);
5089 up_read(&root->fs_info->cleanup_work_sem);
5091 inode = ERR_PTR(ret);
5097 static int btrfs_dentry_delete(const struct dentry *dentry)
5099 struct btrfs_root *root;
5100 struct inode *inode = dentry->d_inode;
5102 if (!inode && !IS_ROOT(dentry))
5103 inode = dentry->d_parent->d_inode;
5106 root = BTRFS_I(inode)->root;
5107 if (btrfs_root_refs(&root->root_item) == 0)
5110 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5116 static void btrfs_dentry_release(struct dentry *dentry)
5118 if (dentry->d_fsdata)
5119 kfree(dentry->d_fsdata);
5122 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5127 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
5131 unsigned char btrfs_filetype_table[] = {
5132 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5135 static int btrfs_real_readdir(struct file *filp, void *dirent,
5138 struct inode *inode = file_inode(filp);
5139 struct btrfs_root *root = BTRFS_I(inode)->root;
5140 struct btrfs_item *item;
5141 struct btrfs_dir_item *di;
5142 struct btrfs_key key;
5143 struct btrfs_key found_key;
5144 struct btrfs_path *path;
5145 struct list_head ins_list;
5146 struct list_head del_list;
5148 struct extent_buffer *leaf;
5150 unsigned char d_type;
5155 int key_type = BTRFS_DIR_INDEX_KEY;
5159 int is_curr = 0; /* filp->f_pos points to the current index? */
5161 /* FIXME, use a real flag for deciding about the key type */
5162 if (root->fs_info->tree_root == root)
5163 key_type = BTRFS_DIR_ITEM_KEY;
5165 /* special case for "." */
5166 if (filp->f_pos == 0) {
5167 over = filldir(dirent, ".", 1,
5168 filp->f_pos, btrfs_ino(inode), DT_DIR);
5173 /* special case for .., just use the back ref */
5174 if (filp->f_pos == 1) {
5175 u64 pino = parent_ino(filp->f_path.dentry);
5176 over = filldir(dirent, "..", 2,
5177 filp->f_pos, pino, DT_DIR);
5182 path = btrfs_alloc_path();
5188 if (key_type == BTRFS_DIR_INDEX_KEY) {
5189 INIT_LIST_HEAD(&ins_list);
5190 INIT_LIST_HEAD(&del_list);
5191 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5194 btrfs_set_key_type(&key, key_type);
5195 key.offset = filp->f_pos;
5196 key.objectid = btrfs_ino(inode);
5198 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5203 leaf = path->nodes[0];
5204 slot = path->slots[0];
5205 if (slot >= btrfs_header_nritems(leaf)) {
5206 ret = btrfs_next_leaf(root, path);
5214 item = btrfs_item_nr(leaf, slot);
5215 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5217 if (found_key.objectid != key.objectid)
5219 if (btrfs_key_type(&found_key) != key_type)
5221 if (found_key.offset < filp->f_pos)
5223 if (key_type == BTRFS_DIR_INDEX_KEY &&
5224 btrfs_should_delete_dir_index(&del_list,
5228 filp->f_pos = found_key.offset;
5231 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5233 di_total = btrfs_item_size(leaf, item);
5235 while (di_cur < di_total) {
5236 struct btrfs_key location;
5238 if (verify_dir_item(root, leaf, di))
5241 name_len = btrfs_dir_name_len(leaf, di);
5242 if (name_len <= sizeof(tmp_name)) {
5243 name_ptr = tmp_name;
5245 name_ptr = kmalloc(name_len, GFP_NOFS);
5251 read_extent_buffer(leaf, name_ptr,
5252 (unsigned long)(di + 1), name_len);
5254 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5255 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5258 /* is this a reference to our own snapshot? If so
5261 * In contrast to old kernels, we insert the snapshot's
5262 * dir item and dir index after it has been created, so
5263 * we won't find a reference to our own snapshot. We
5264 * still keep the following code for backward
5267 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5268 location.objectid == root->root_key.objectid) {
5272 over = filldir(dirent, name_ptr, name_len,
5273 found_key.offset, location.objectid,
5277 if (name_ptr != tmp_name)
5282 di_len = btrfs_dir_name_len(leaf, di) +
5283 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5285 di = (struct btrfs_dir_item *)((char *)di + di_len);
5291 if (key_type == BTRFS_DIR_INDEX_KEY) {
5294 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
5300 /* Reached end of directory/root. Bump pos past the last item. */
5301 if (key_type == BTRFS_DIR_INDEX_KEY)
5303 * 32-bit glibc will use getdents64, but then strtol -
5304 * so the last number we can serve is this.
5306 filp->f_pos = 0x7fffffff;
5312 if (key_type == BTRFS_DIR_INDEX_KEY)
5313 btrfs_put_delayed_items(&ins_list, &del_list);
5314 btrfs_free_path(path);
5318 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5320 struct btrfs_root *root = BTRFS_I(inode)->root;
5321 struct btrfs_trans_handle *trans;
5323 bool nolock = false;
5325 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5328 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5331 if (wbc->sync_mode == WB_SYNC_ALL) {
5333 trans = btrfs_join_transaction_nolock(root);
5335 trans = btrfs_join_transaction(root);
5337 return PTR_ERR(trans);
5338 ret = btrfs_commit_transaction(trans, root);
5344 * This is somewhat expensive, updating the tree every time the
5345 * inode changes. But, it is most likely to find the inode in cache.
5346 * FIXME, needs more benchmarking...there are no reasons other than performance
5347 * to keep or drop this code.
5349 static int btrfs_dirty_inode(struct inode *inode)
5351 struct btrfs_root *root = BTRFS_I(inode)->root;
5352 struct btrfs_trans_handle *trans;
5355 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5358 trans = btrfs_join_transaction(root);
5360 return PTR_ERR(trans);
5362 ret = btrfs_update_inode(trans, root, inode);
5363 if (ret && ret == -ENOSPC) {
5364 /* whoops, lets try again with the full transaction */
5365 btrfs_end_transaction(trans, root);
5366 trans = btrfs_start_transaction(root, 1);
5368 return PTR_ERR(trans);
5370 ret = btrfs_update_inode(trans, root, inode);
5372 btrfs_end_transaction(trans, root);
5373 if (BTRFS_I(inode)->delayed_node)
5374 btrfs_balance_delayed_items(root);
5380 * This is a copy of file_update_time. We need this so we can return error on
5381 * ENOSPC for updating the inode in the case of file write and mmap writes.
5383 static int btrfs_update_time(struct inode *inode, struct timespec *now,
5386 struct btrfs_root *root = BTRFS_I(inode)->root;
5388 if (btrfs_root_readonly(root))
5391 if (flags & S_VERSION)
5392 inode_inc_iversion(inode);
5393 if (flags & S_CTIME)
5394 inode->i_ctime = *now;
5395 if (flags & S_MTIME)
5396 inode->i_mtime = *now;
5397 if (flags & S_ATIME)
5398 inode->i_atime = *now;
5399 return btrfs_dirty_inode(inode);
5403 * find the highest existing sequence number in a directory
5404 * and then set the in-memory index_cnt variable to reflect
5405 * free sequence numbers
5407 static int btrfs_set_inode_index_count(struct inode *inode)
5409 struct btrfs_root *root = BTRFS_I(inode)->root;
5410 struct btrfs_key key, found_key;
5411 struct btrfs_path *path;
5412 struct extent_buffer *leaf;
5415 key.objectid = btrfs_ino(inode);
5416 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
5417 key.offset = (u64)-1;
5419 path = btrfs_alloc_path();
5423 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5426 /* FIXME: we should be able to handle this */
5432 * MAGIC NUMBER EXPLANATION:
5433 * since we search a directory based on f_pos we have to start at 2
5434 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5435 * else has to start at 2
5437 if (path->slots[0] == 0) {
5438 BTRFS_I(inode)->index_cnt = 2;
5444 leaf = path->nodes[0];
5445 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5447 if (found_key.objectid != btrfs_ino(inode) ||
5448 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
5449 BTRFS_I(inode)->index_cnt = 2;
5453 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
5455 btrfs_free_path(path);
5460 * helper to find a free sequence number in a given directory. This current
5461 * code is very simple, later versions will do smarter things in the btree
5463 int btrfs_set_inode_index(struct inode *dir, u64 *index)
5467 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
5468 ret = btrfs_inode_delayed_dir_index_count(dir);
5470 ret = btrfs_set_inode_index_count(dir);
5476 *index = BTRFS_I(dir)->index_cnt;
5477 BTRFS_I(dir)->index_cnt++;
5482 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5483 struct btrfs_root *root,
5485 const char *name, int name_len,
5486 u64 ref_objectid, u64 objectid,
5487 umode_t mode, u64 *index)
5489 struct inode *inode;
5490 struct btrfs_inode_item *inode_item;
5491 struct btrfs_key *location;
5492 struct btrfs_path *path;
5493 struct btrfs_inode_ref *ref;
5494 struct btrfs_key key[2];
5500 path = btrfs_alloc_path();
5502 return ERR_PTR(-ENOMEM);
5504 inode = new_inode(root->fs_info->sb);
5506 btrfs_free_path(path);
5507 return ERR_PTR(-ENOMEM);
5511 * we have to initialize this early, so we can reclaim the inode
5512 * number if we fail afterwards in this function.
5514 inode->i_ino = objectid;
5517 trace_btrfs_inode_request(dir);
5519 ret = btrfs_set_inode_index(dir, index);
5521 btrfs_free_path(path);
5523 return ERR_PTR(ret);
5527 * index_cnt is ignored for everything but a dir,
5528 * btrfs_get_inode_index_count has an explanation for the magic
5531 BTRFS_I(inode)->index_cnt = 2;
5532 BTRFS_I(inode)->root = root;
5533 BTRFS_I(inode)->generation = trans->transid;
5534 inode->i_generation = BTRFS_I(inode)->generation;
5537 * We could have gotten an inode number from somebody who was fsynced
5538 * and then removed in this same transaction, so let's just set full
5539 * sync since it will be a full sync anyway and this will blow away the
5540 * old info in the log.
5542 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5549 key[0].objectid = objectid;
5550 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
5554 * Start new inodes with an inode_ref. This is slightly more
5555 * efficient for small numbers of hard links since they will
5556 * be packed into one item. Extended refs will kick in if we
5557 * add more hard links than can fit in the ref item.
5559 key[1].objectid = objectid;
5560 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
5561 key[1].offset = ref_objectid;
5563 sizes[0] = sizeof(struct btrfs_inode_item);
5564 sizes[1] = name_len + sizeof(*ref);
5566 path->leave_spinning = 1;
5567 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
5571 inode_init_owner(inode, dir, mode);
5572 inode_set_bytes(inode, 0);
5573 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
5574 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5575 struct btrfs_inode_item);
5576 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
5577 sizeof(*inode_item));
5578 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5580 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5581 struct btrfs_inode_ref);
5582 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5583 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5584 ptr = (unsigned long)(ref + 1);
5585 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5587 btrfs_mark_buffer_dirty(path->nodes[0]);
5588 btrfs_free_path(path);
5590 location = &BTRFS_I(inode)->location;
5591 location->objectid = objectid;
5592 location->offset = 0;
5593 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
5595 btrfs_inherit_iflags(inode, dir);
5597 if (S_ISREG(mode)) {
5598 if (btrfs_test_opt(root, NODATASUM))
5599 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5600 if (btrfs_test_opt(root, NODATACOW))
5601 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5602 BTRFS_INODE_NODATASUM;
5605 insert_inode_hash(inode);
5606 inode_tree_add(inode);
5608 trace_btrfs_inode_new(inode);
5609 btrfs_set_inode_last_trans(trans, inode);
5611 btrfs_update_root_times(trans, root);
5616 BTRFS_I(dir)->index_cnt--;
5617 btrfs_free_path(path);
5619 return ERR_PTR(ret);
5622 static inline u8 btrfs_inode_type(struct inode *inode)
5624 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
5628 * utility function to add 'inode' into 'parent_inode' with
5629 * a give name and a given sequence number.
5630 * if 'add_backref' is true, also insert a backref from the
5631 * inode to the parent directory.
5633 int btrfs_add_link(struct btrfs_trans_handle *trans,
5634 struct inode *parent_inode, struct inode *inode,
5635 const char *name, int name_len, int add_backref, u64 index)
5638 struct btrfs_key key;
5639 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
5640 u64 ino = btrfs_ino(inode);
5641 u64 parent_ino = btrfs_ino(parent_inode);
5643 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5644 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
5647 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
5651 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5652 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
5653 key.objectid, root->root_key.objectid,
5654 parent_ino, index, name, name_len);
5655 } else if (add_backref) {
5656 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5660 /* Nothing to clean up yet */
5664 ret = btrfs_insert_dir_item(trans, root, name, name_len,
5666 btrfs_inode_type(inode), index);
5667 if (ret == -EEXIST || ret == -EOVERFLOW)
5670 btrfs_abort_transaction(trans, root, ret);
5674 btrfs_i_size_write(parent_inode, parent_inode->i_size +
5676 inode_inc_iversion(parent_inode);
5677 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
5678 ret = btrfs_update_inode(trans, root, parent_inode);
5680 btrfs_abort_transaction(trans, root, ret);
5684 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5687 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
5688 key.objectid, root->root_key.objectid,
5689 parent_ino, &local_index, name, name_len);
5691 } else if (add_backref) {
5695 err = btrfs_del_inode_ref(trans, root, name, name_len,
5696 ino, parent_ino, &local_index);
5701 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5702 struct inode *dir, struct dentry *dentry,
5703 struct inode *inode, int backref, u64 index)
5705 int err = btrfs_add_link(trans, dir, inode,
5706 dentry->d_name.name, dentry->d_name.len,
5713 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5714 umode_t mode, dev_t rdev)
5716 struct btrfs_trans_handle *trans;
5717 struct btrfs_root *root = BTRFS_I(dir)->root;
5718 struct inode *inode = NULL;
5724 if (!new_valid_dev(rdev))
5728 * 2 for inode item and ref
5730 * 1 for xattr if selinux is on
5732 trans = btrfs_start_transaction(root, 5);
5734 return PTR_ERR(trans);
5736 err = btrfs_find_free_ino(root, &objectid);
5740 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5741 dentry->d_name.len, btrfs_ino(dir), objectid,
5743 if (IS_ERR(inode)) {
5744 err = PTR_ERR(inode);
5748 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5755 * If the active LSM wants to access the inode during
5756 * d_instantiate it needs these. Smack checks to see
5757 * if the filesystem supports xattrs by looking at the
5761 inode->i_op = &btrfs_special_inode_operations;
5762 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5766 init_special_inode(inode, inode->i_mode, rdev);
5767 btrfs_update_inode(trans, root, inode);
5768 d_instantiate(dentry, inode);
5771 btrfs_end_transaction(trans, root);
5772 btrfs_btree_balance_dirty(root);
5774 inode_dec_link_count(inode);
5780 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5781 umode_t mode, bool excl)
5783 struct btrfs_trans_handle *trans;
5784 struct btrfs_root *root = BTRFS_I(dir)->root;
5785 struct inode *inode = NULL;
5786 int drop_inode_on_err = 0;
5792 * 2 for inode item and ref
5794 * 1 for xattr if selinux is on
5796 trans = btrfs_start_transaction(root, 5);
5798 return PTR_ERR(trans);
5800 err = btrfs_find_free_ino(root, &objectid);
5804 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5805 dentry->d_name.len, btrfs_ino(dir), objectid,
5807 if (IS_ERR(inode)) {
5808 err = PTR_ERR(inode);
5811 drop_inode_on_err = 1;
5813 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5817 err = btrfs_update_inode(trans, root, inode);
5822 * If the active LSM wants to access the inode during
5823 * d_instantiate it needs these. Smack checks to see
5824 * if the filesystem supports xattrs by looking at the
5827 inode->i_fop = &btrfs_file_operations;
5828 inode->i_op = &btrfs_file_inode_operations;
5830 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5834 inode->i_mapping->a_ops = &btrfs_aops;
5835 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5836 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5837 d_instantiate(dentry, inode);
5840 btrfs_end_transaction(trans, root);
5841 if (err && drop_inode_on_err) {
5842 inode_dec_link_count(inode);
5845 btrfs_btree_balance_dirty(root);
5849 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5850 struct dentry *dentry)
5852 struct btrfs_trans_handle *trans;
5853 struct btrfs_root *root = BTRFS_I(dir)->root;
5854 struct inode *inode = old_dentry->d_inode;
5859 /* do not allow sys_link's with other subvols of the same device */
5860 if (root->objectid != BTRFS_I(inode)->root->objectid)
5863 if (inode->i_nlink >= BTRFS_LINK_MAX)
5866 err = btrfs_set_inode_index(dir, &index);
5871 * 2 items for inode and inode ref
5872 * 2 items for dir items
5873 * 1 item for parent inode
5875 trans = btrfs_start_transaction(root, 5);
5876 if (IS_ERR(trans)) {
5877 err = PTR_ERR(trans);
5881 btrfs_inc_nlink(inode);
5882 inode_inc_iversion(inode);
5883 inode->i_ctime = CURRENT_TIME;
5885 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5887 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5892 struct dentry *parent = dentry->d_parent;
5893 err = btrfs_update_inode(trans, root, inode);
5896 d_instantiate(dentry, inode);
5897 btrfs_log_new_name(trans, inode, NULL, parent);
5900 btrfs_end_transaction(trans, root);
5903 inode_dec_link_count(inode);
5906 btrfs_btree_balance_dirty(root);
5910 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5912 struct inode *inode = NULL;
5913 struct btrfs_trans_handle *trans;
5914 struct btrfs_root *root = BTRFS_I(dir)->root;
5916 int drop_on_err = 0;
5921 * 2 items for inode and ref
5922 * 2 items for dir items
5923 * 1 for xattr if selinux is on
5925 trans = btrfs_start_transaction(root, 5);
5927 return PTR_ERR(trans);
5929 err = btrfs_find_free_ino(root, &objectid);
5933 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5934 dentry->d_name.len, btrfs_ino(dir), objectid,
5935 S_IFDIR | mode, &index);
5936 if (IS_ERR(inode)) {
5937 err = PTR_ERR(inode);
5943 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5947 inode->i_op = &btrfs_dir_inode_operations;
5948 inode->i_fop = &btrfs_dir_file_operations;
5950 btrfs_i_size_write(inode, 0);
5951 err = btrfs_update_inode(trans, root, inode);
5955 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5956 dentry->d_name.len, 0, index);
5960 d_instantiate(dentry, inode);
5964 btrfs_end_transaction(trans, root);
5967 btrfs_btree_balance_dirty(root);
5971 /* helper for btfs_get_extent. Given an existing extent in the tree,
5972 * and an extent that you want to insert, deal with overlap and insert
5973 * the new extent into the tree.
5975 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5976 struct extent_map *existing,
5977 struct extent_map *em,
5978 u64 map_start, u64 map_len)
5982 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5983 start_diff = map_start - em->start;
5984 em->start = map_start;
5986 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5987 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5988 em->block_start += start_diff;
5989 em->block_len -= start_diff;
5991 return add_extent_mapping(em_tree, em, 0);
5994 static noinline int uncompress_inline(struct btrfs_path *path,
5995 struct inode *inode, struct page *page,
5996 size_t pg_offset, u64 extent_offset,
5997 struct btrfs_file_extent_item *item)
6000 struct extent_buffer *leaf = path->nodes[0];
6003 unsigned long inline_size;
6007 WARN_ON(pg_offset != 0);
6008 compress_type = btrfs_file_extent_compression(leaf, item);
6009 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6010 inline_size = btrfs_file_extent_inline_item_len(leaf,
6011 btrfs_item_nr(leaf, path->slots[0]));
6012 tmp = kmalloc(inline_size, GFP_NOFS);
6015 ptr = btrfs_file_extent_inline_start(item);
6017 read_extent_buffer(leaf, tmp, ptr, inline_size);
6019 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6020 ret = btrfs_decompress(compress_type, tmp, page,
6021 extent_offset, inline_size, max_size);
6023 char *kaddr = kmap_atomic(page);
6024 unsigned long copy_size = min_t(u64,
6025 PAGE_CACHE_SIZE - pg_offset,
6026 max_size - extent_offset);
6027 memset(kaddr + pg_offset, 0, copy_size);
6028 kunmap_atomic(kaddr);
6035 * a bit scary, this does extent mapping from logical file offset to the disk.
6036 * the ugly parts come from merging extents from the disk with the in-ram
6037 * representation. This gets more complex because of the data=ordered code,
6038 * where the in-ram extents might be locked pending data=ordered completion.
6040 * This also copies inline extents directly into the page.
6043 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6044 size_t pg_offset, u64 start, u64 len,
6050 u64 extent_start = 0;
6052 u64 objectid = btrfs_ino(inode);
6054 struct btrfs_path *path = NULL;
6055 struct btrfs_root *root = BTRFS_I(inode)->root;
6056 struct btrfs_file_extent_item *item;
6057 struct extent_buffer *leaf;
6058 struct btrfs_key found_key;
6059 struct extent_map *em = NULL;
6060 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6061 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6062 struct btrfs_trans_handle *trans = NULL;
6066 read_lock(&em_tree->lock);
6067 em = lookup_extent_mapping(em_tree, start, len);
6069 em->bdev = root->fs_info->fs_devices->latest_bdev;
6070 read_unlock(&em_tree->lock);
6073 if (em->start > start || em->start + em->len <= start)
6074 free_extent_map(em);
6075 else if (em->block_start == EXTENT_MAP_INLINE && page)
6076 free_extent_map(em);
6080 em = alloc_extent_map();
6085 em->bdev = root->fs_info->fs_devices->latest_bdev;
6086 em->start = EXTENT_MAP_HOLE;
6087 em->orig_start = EXTENT_MAP_HOLE;
6089 em->block_len = (u64)-1;
6092 path = btrfs_alloc_path();
6098 * Chances are we'll be called again, so go ahead and do
6104 ret = btrfs_lookup_file_extent(trans, root, path,
6105 objectid, start, trans != NULL);
6112 if (path->slots[0] == 0)
6117 leaf = path->nodes[0];
6118 item = btrfs_item_ptr(leaf, path->slots[0],
6119 struct btrfs_file_extent_item);
6120 /* are we inside the extent that was found? */
6121 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6122 found_type = btrfs_key_type(&found_key);
6123 if (found_key.objectid != objectid ||
6124 found_type != BTRFS_EXTENT_DATA_KEY) {
6128 found_type = btrfs_file_extent_type(leaf, item);
6129 extent_start = found_key.offset;
6130 compress_type = btrfs_file_extent_compression(leaf, item);
6131 if (found_type == BTRFS_FILE_EXTENT_REG ||
6132 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6133 extent_end = extent_start +
6134 btrfs_file_extent_num_bytes(leaf, item);
6135 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6137 size = btrfs_file_extent_inline_len(leaf, item);
6138 extent_end = ALIGN(extent_start + size, root->sectorsize);
6141 if (start >= extent_end) {
6143 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6144 ret = btrfs_next_leaf(root, path);
6151 leaf = path->nodes[0];
6153 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6154 if (found_key.objectid != objectid ||
6155 found_key.type != BTRFS_EXTENT_DATA_KEY)
6157 if (start + len <= found_key.offset)
6160 em->orig_start = start;
6161 em->len = found_key.offset - start;
6165 em->ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
6166 if (found_type == BTRFS_FILE_EXTENT_REG ||
6167 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6168 em->start = extent_start;
6169 em->len = extent_end - extent_start;
6170 em->orig_start = extent_start -
6171 btrfs_file_extent_offset(leaf, item);
6172 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
6174 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
6176 em->block_start = EXTENT_MAP_HOLE;
6179 if (compress_type != BTRFS_COMPRESS_NONE) {
6180 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6181 em->compress_type = compress_type;
6182 em->block_start = bytenr;
6183 em->block_len = em->orig_block_len;
6185 bytenr += btrfs_file_extent_offset(leaf, item);
6186 em->block_start = bytenr;
6187 em->block_len = em->len;
6188 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
6189 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6192 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6196 size_t extent_offset;
6199 em->block_start = EXTENT_MAP_INLINE;
6200 if (!page || create) {
6201 em->start = extent_start;
6202 em->len = extent_end - extent_start;
6206 size = btrfs_file_extent_inline_len(leaf, item);
6207 extent_offset = page_offset(page) + pg_offset - extent_start;
6208 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6209 size - extent_offset);
6210 em->start = extent_start + extent_offset;
6211 em->len = ALIGN(copy_size, root->sectorsize);
6212 em->orig_block_len = em->len;
6213 em->orig_start = em->start;
6214 if (compress_type) {
6215 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
6216 em->compress_type = compress_type;
6218 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6219 if (create == 0 && !PageUptodate(page)) {
6220 if (btrfs_file_extent_compression(leaf, item) !=
6221 BTRFS_COMPRESS_NONE) {
6222 ret = uncompress_inline(path, inode, page,
6224 extent_offset, item);
6225 BUG_ON(ret); /* -ENOMEM */
6228 read_extent_buffer(leaf, map + pg_offset, ptr,
6230 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6231 memset(map + pg_offset + copy_size, 0,
6232 PAGE_CACHE_SIZE - pg_offset -
6237 flush_dcache_page(page);
6238 } else if (create && PageUptodate(page)) {
6242 free_extent_map(em);
6245 btrfs_release_path(path);
6246 trans = btrfs_join_transaction(root);
6249 return ERR_CAST(trans);
6253 write_extent_buffer(leaf, map + pg_offset, ptr,
6256 btrfs_mark_buffer_dirty(leaf);
6258 set_extent_uptodate(io_tree, em->start,
6259 extent_map_end(em) - 1, NULL, GFP_NOFS);
6262 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
6266 em->orig_start = start;
6269 em->block_start = EXTENT_MAP_HOLE;
6270 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
6272 btrfs_release_path(path);
6273 if (em->start > start || extent_map_end(em) <= start) {
6274 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
6275 (unsigned long long)em->start,
6276 (unsigned long long)em->len,
6277 (unsigned long long)start,
6278 (unsigned long long)len);
6284 write_lock(&em_tree->lock);
6285 ret = add_extent_mapping(em_tree, em, 0);
6286 /* it is possible that someone inserted the extent into the tree
6287 * while we had the lock dropped. It is also possible that
6288 * an overlapping map exists in the tree
6290 if (ret == -EEXIST) {
6291 struct extent_map *existing;
6295 existing = lookup_extent_mapping(em_tree, start, len);
6296 if (existing && (existing->start > start ||
6297 existing->start + existing->len <= start)) {
6298 free_extent_map(existing);
6302 existing = lookup_extent_mapping(em_tree, em->start,
6305 err = merge_extent_mapping(em_tree, existing,
6308 free_extent_map(existing);
6310 free_extent_map(em);
6315 free_extent_map(em);
6319 free_extent_map(em);
6324 write_unlock(&em_tree->lock);
6328 trace_btrfs_get_extent(root, em);
6331 btrfs_free_path(path);
6333 ret = btrfs_end_transaction(trans, root);
6338 free_extent_map(em);
6339 return ERR_PTR(err);
6341 BUG_ON(!em); /* Error is always set */
6345 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
6346 size_t pg_offset, u64 start, u64 len,
6349 struct extent_map *em;
6350 struct extent_map *hole_em = NULL;
6351 u64 range_start = start;
6357 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
6364 * - a pre-alloc extent,
6365 * there might actually be delalloc bytes behind it.
6367 if (em->block_start != EXTENT_MAP_HOLE &&
6368 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6374 /* check to see if we've wrapped (len == -1 or similar) */
6383 /* ok, we didn't find anything, lets look for delalloc */
6384 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
6385 end, len, EXTENT_DELALLOC, 1);
6386 found_end = range_start + found;
6387 if (found_end < range_start)
6388 found_end = (u64)-1;
6391 * we didn't find anything useful, return
6392 * the original results from get_extent()
6394 if (range_start > end || found_end <= start) {
6400 /* adjust the range_start to make sure it doesn't
6401 * go backwards from the start they passed in
6403 range_start = max(start,range_start);
6404 found = found_end - range_start;
6407 u64 hole_start = start;
6410 em = alloc_extent_map();
6416 * when btrfs_get_extent can't find anything it
6417 * returns one huge hole
6419 * make sure what it found really fits our range, and
6420 * adjust to make sure it is based on the start from
6424 u64 calc_end = extent_map_end(hole_em);
6426 if (calc_end <= start || (hole_em->start > end)) {
6427 free_extent_map(hole_em);
6430 hole_start = max(hole_em->start, start);
6431 hole_len = calc_end - hole_start;
6435 if (hole_em && range_start > hole_start) {
6436 /* our hole starts before our delalloc, so we
6437 * have to return just the parts of the hole
6438 * that go until the delalloc starts
6440 em->len = min(hole_len,
6441 range_start - hole_start);
6442 em->start = hole_start;
6443 em->orig_start = hole_start;
6445 * don't adjust block start at all,
6446 * it is fixed at EXTENT_MAP_HOLE
6448 em->block_start = hole_em->block_start;
6449 em->block_len = hole_len;
6450 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6451 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6453 em->start = range_start;
6455 em->orig_start = range_start;
6456 em->block_start = EXTENT_MAP_DELALLOC;
6457 em->block_len = found;
6459 } else if (hole_em) {
6464 free_extent_map(hole_em);
6466 free_extent_map(em);
6467 return ERR_PTR(err);
6472 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6475 struct btrfs_root *root = BTRFS_I(inode)->root;
6476 struct btrfs_trans_handle *trans;
6477 struct extent_map *em;
6478 struct btrfs_key ins;
6482 trans = btrfs_join_transaction(root);
6484 return ERR_CAST(trans);
6486 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
6488 alloc_hint = get_extent_allocation_hint(inode, start, len);
6489 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
6490 alloc_hint, &ins, 1);
6496 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
6497 ins.offset, ins.offset, ins.offset, 0);
6501 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
6502 ins.offset, ins.offset, 0);
6504 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
6508 btrfs_end_transaction(trans, root);
6513 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6514 * block must be cow'd
6516 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
6517 struct inode *inode, u64 offset, u64 *len,
6518 u64 *orig_start, u64 *orig_block_len,
6521 struct btrfs_path *path;
6523 struct extent_buffer *leaf;
6524 struct btrfs_root *root = BTRFS_I(inode)->root;
6525 struct btrfs_file_extent_item *fi;
6526 struct btrfs_key key;
6534 path = btrfs_alloc_path();
6538 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
6543 slot = path->slots[0];
6546 /* can't find the item, must cow */
6553 leaf = path->nodes[0];
6554 btrfs_item_key_to_cpu(leaf, &key, slot);
6555 if (key.objectid != btrfs_ino(inode) ||
6556 key.type != BTRFS_EXTENT_DATA_KEY) {
6557 /* not our file or wrong item type, must cow */
6561 if (key.offset > offset) {
6562 /* Wrong offset, must cow */
6566 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6567 found_type = btrfs_file_extent_type(leaf, fi);
6568 if (found_type != BTRFS_FILE_EXTENT_REG &&
6569 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6570 /* not a regular extent, must cow */
6573 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6574 backref_offset = btrfs_file_extent_offset(leaf, fi);
6576 *orig_start = key.offset - backref_offset;
6577 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6578 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6580 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6581 if (extent_end < offset + *len) {
6582 /* extent doesn't include our full range, must cow */
6586 if (btrfs_extent_readonly(root, disk_bytenr))
6590 * look for other files referencing this extent, if we
6591 * find any we must cow
6593 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
6594 key.offset - backref_offset, disk_bytenr))
6598 * adjust disk_bytenr and num_bytes to cover just the bytes
6599 * in this extent we are about to write. If there
6600 * are any csums in that range we have to cow in order
6601 * to keep the csums correct
6603 disk_bytenr += backref_offset;
6604 disk_bytenr += offset - key.offset;
6605 num_bytes = min(offset + *len, extent_end) - offset;
6606 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
6609 * all of the above have passed, it is safe to overwrite this extent
6615 btrfs_free_path(path);
6619 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6620 struct extent_state **cached_state, int writing)
6622 struct btrfs_ordered_extent *ordered;
6626 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6629 * We're concerned with the entire range that we're going to be
6630 * doing DIO to, so we need to make sure theres no ordered
6631 * extents in this range.
6633 ordered = btrfs_lookup_ordered_range(inode, lockstart,
6634 lockend - lockstart + 1);
6637 * We need to make sure there are no buffered pages in this
6638 * range either, we could have raced between the invalidate in
6639 * generic_file_direct_write and locking the extent. The
6640 * invalidate needs to happen so that reads after a write do not
6643 if (!ordered && (!writing ||
6644 !test_range_bit(&BTRFS_I(inode)->io_tree,
6645 lockstart, lockend, EXTENT_UPTODATE, 0,
6649 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6650 cached_state, GFP_NOFS);
6653 btrfs_start_ordered_extent(inode, ordered, 1);
6654 btrfs_put_ordered_extent(ordered);
6656 /* Screw you mmap */
6657 ret = filemap_write_and_wait_range(inode->i_mapping,
6664 * If we found a page that couldn't be invalidated just
6665 * fall back to buffered.
6667 ret = invalidate_inode_pages2_range(inode->i_mapping,
6668 lockstart >> PAGE_CACHE_SHIFT,
6669 lockend >> PAGE_CACHE_SHIFT);
6680 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
6681 u64 len, u64 orig_start,
6682 u64 block_start, u64 block_len,
6683 u64 orig_block_len, u64 ram_bytes,
6686 struct extent_map_tree *em_tree;
6687 struct extent_map *em;
6688 struct btrfs_root *root = BTRFS_I(inode)->root;
6691 em_tree = &BTRFS_I(inode)->extent_tree;
6692 em = alloc_extent_map();
6694 return ERR_PTR(-ENOMEM);
6697 em->orig_start = orig_start;
6698 em->mod_start = start;
6701 em->block_len = block_len;
6702 em->block_start = block_start;
6703 em->bdev = root->fs_info->fs_devices->latest_bdev;
6704 em->orig_block_len = orig_block_len;
6705 em->ram_bytes = ram_bytes;
6706 em->generation = -1;
6707 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6708 if (type == BTRFS_ORDERED_PREALLOC)
6709 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6712 btrfs_drop_extent_cache(inode, em->start,
6713 em->start + em->len - 1, 0);
6714 write_lock(&em_tree->lock);
6715 ret = add_extent_mapping(em_tree, em, 1);
6716 write_unlock(&em_tree->lock);
6717 } while (ret == -EEXIST);
6720 free_extent_map(em);
6721 return ERR_PTR(ret);
6728 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6729 struct buffer_head *bh_result, int create)
6731 struct extent_map *em;
6732 struct btrfs_root *root = BTRFS_I(inode)->root;
6733 struct extent_state *cached_state = NULL;
6734 u64 start = iblock << inode->i_blkbits;
6735 u64 lockstart, lockend;
6736 u64 len = bh_result->b_size;
6737 struct btrfs_trans_handle *trans;
6738 int unlock_bits = EXTENT_LOCKED;
6742 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6744 len = min_t(u64, len, root->sectorsize);
6747 lockend = start + len - 1;
6750 * If this errors out it's because we couldn't invalidate pagecache for
6751 * this range and we need to fallback to buffered.
6753 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6756 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6763 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6764 * io. INLINE is special, and we could probably kludge it in here, but
6765 * it's still buffered so for safety lets just fall back to the generic
6768 * For COMPRESSED we _have_ to read the entire extent in so we can
6769 * decompress it, so there will be buffering required no matter what we
6770 * do, so go ahead and fallback to buffered.
6772 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6773 * to buffered IO. Don't blame me, this is the price we pay for using
6776 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6777 em->block_start == EXTENT_MAP_INLINE) {
6778 free_extent_map(em);
6783 /* Just a good old fashioned hole, return */
6784 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6785 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6786 free_extent_map(em);
6791 * We don't allocate a new extent in the following cases
6793 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6795 * 2) The extent is marked as PREALLOC. We're good to go here and can
6796 * just use the extent.
6800 len = min(len, em->len - (start - em->start));
6801 lockstart = start + len;
6805 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6806 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6807 em->block_start != EXTENT_MAP_HOLE)) {
6810 u64 block_start, orig_start, orig_block_len, ram_bytes;
6812 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6813 type = BTRFS_ORDERED_PREALLOC;
6815 type = BTRFS_ORDERED_NOCOW;
6816 len = min(len, em->len - (start - em->start));
6817 block_start = em->block_start + (start - em->start);
6820 * we're not going to log anything, but we do need
6821 * to make sure the current transaction stays open
6822 * while we look for nocow cross refs
6824 trans = btrfs_join_transaction(root);
6828 if (can_nocow_odirect(trans, inode, start, &len, &orig_start,
6829 &orig_block_len, &ram_bytes) == 1) {
6830 if (type == BTRFS_ORDERED_PREALLOC) {
6831 free_extent_map(em);
6832 em = create_pinned_em(inode, start, len,
6838 btrfs_end_transaction(trans, root);
6843 ret = btrfs_add_ordered_extent_dio(inode, start,
6844 block_start, len, len, type);
6845 btrfs_end_transaction(trans, root);
6847 free_extent_map(em);
6852 btrfs_end_transaction(trans, root);
6856 * this will cow the extent, reset the len in case we changed
6859 len = bh_result->b_size;
6860 free_extent_map(em);
6861 em = btrfs_new_extent_direct(inode, start, len);
6866 len = min(len, em->len - (start - em->start));
6868 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6870 bh_result->b_size = len;
6871 bh_result->b_bdev = em->bdev;
6872 set_buffer_mapped(bh_result);
6874 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6875 set_buffer_new(bh_result);
6878 * Need to update the i_size under the extent lock so buffered
6879 * readers will get the updated i_size when we unlock.
6881 if (start + len > i_size_read(inode))
6882 i_size_write(inode, start + len);
6884 spin_lock(&BTRFS_I(inode)->lock);
6885 BTRFS_I(inode)->outstanding_extents++;
6886 spin_unlock(&BTRFS_I(inode)->lock);
6888 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6889 lockstart + len - 1, EXTENT_DELALLOC, NULL,
6890 &cached_state, GFP_NOFS);
6895 * In the case of write we need to clear and unlock the entire range,
6896 * in the case of read we need to unlock only the end area that we
6897 * aren't using if there is any left over space.
6899 if (lockstart < lockend) {
6900 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6901 lockend, unlock_bits, 1, 0,
6902 &cached_state, GFP_NOFS);
6904 free_extent_state(cached_state);
6907 free_extent_map(em);
6912 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6913 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6917 struct btrfs_dio_private {
6918 struct inode *inode;
6924 /* number of bios pending for this dio */
6925 atomic_t pending_bios;
6930 /* orig_bio is our btrfs_io_bio */
6931 struct bio *orig_bio;
6933 /* dio_bio came from fs/direct-io.c */
6934 struct bio *dio_bio;
6937 static void btrfs_endio_direct_read(struct bio *bio, int err)
6939 struct btrfs_dio_private *dip = bio->bi_private;
6940 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6941 struct bio_vec *bvec = bio->bi_io_vec;
6942 struct inode *inode = dip->inode;
6943 struct btrfs_root *root = BTRFS_I(inode)->root;
6944 struct bio *dio_bio;
6947 start = dip->logical_offset;
6949 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6950 struct page *page = bvec->bv_page;
6953 u64 private = ~(u32)0;
6954 unsigned long flags;
6956 if (get_state_private(&BTRFS_I(inode)->io_tree,
6959 local_irq_save(flags);
6960 kaddr = kmap_atomic(page);
6961 csum = btrfs_csum_data(kaddr + bvec->bv_offset,
6962 csum, bvec->bv_len);
6963 btrfs_csum_final(csum, (char *)&csum);
6964 kunmap_atomic(kaddr);
6965 local_irq_restore(flags);
6967 flush_dcache_page(bvec->bv_page);
6968 if (csum != private) {
6970 btrfs_err(root->fs_info, "csum failed ino %llu off %llu csum %u private %u",
6971 (unsigned long long)btrfs_ino(inode),
6972 (unsigned long long)start,
6973 csum, (unsigned)private);
6978 start += bvec->bv_len;
6980 } while (bvec <= bvec_end);
6982 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6983 dip->logical_offset + dip->bytes - 1);
6984 dio_bio = dip->dio_bio;
6988 /* If we had a csum failure make sure to clear the uptodate flag */
6990 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
6991 dio_end_io(dio_bio, err);
6995 static void btrfs_endio_direct_write(struct bio *bio, int err)
6997 struct btrfs_dio_private *dip = bio->bi_private;
6998 struct inode *inode = dip->inode;
6999 struct btrfs_root *root = BTRFS_I(inode)->root;
7000 struct btrfs_ordered_extent *ordered = NULL;
7001 u64 ordered_offset = dip->logical_offset;
7002 u64 ordered_bytes = dip->bytes;
7003 struct bio *dio_bio;
7009 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
7011 ordered_bytes, !err);
7015 ordered->work.func = finish_ordered_fn;
7016 ordered->work.flags = 0;
7017 btrfs_queue_worker(&root->fs_info->endio_write_workers,
7021 * our bio might span multiple ordered extents. If we haven't
7022 * completed the accounting for the whole dio, go back and try again
7024 if (ordered_offset < dip->logical_offset + dip->bytes) {
7025 ordered_bytes = dip->logical_offset + dip->bytes -
7031 dio_bio = dip->dio_bio;
7035 /* If we had an error make sure to clear the uptodate flag */
7037 clear_bit(BIO_UPTODATE, &dio_bio->bi_flags);
7038 dio_end_io(dio_bio, err);
7042 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
7043 struct bio *bio, int mirror_num,
7044 unsigned long bio_flags, u64 offset)
7047 struct btrfs_root *root = BTRFS_I(inode)->root;
7048 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
7049 BUG_ON(ret); /* -ENOMEM */
7053 static void btrfs_end_dio_bio(struct bio *bio, int err)
7055 struct btrfs_dio_private *dip = bio->bi_private;
7058 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
7059 "sector %#Lx len %u err no %d\n",
7060 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
7061 (unsigned long long)bio->bi_sector, bio->bi_size, err);
7065 * before atomic variable goto zero, we must make sure
7066 * dip->errors is perceived to be set.
7068 smp_mb__before_atomic_dec();
7071 /* if there are more bios still pending for this dio, just exit */
7072 if (!atomic_dec_and_test(&dip->pending_bios))
7076 bio_io_error(dip->orig_bio);
7078 set_bit(BIO_UPTODATE, &dip->dio_bio->bi_flags);
7079 bio_endio(dip->orig_bio, 0);
7085 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
7086 u64 first_sector, gfp_t gfp_flags)
7088 int nr_vecs = bio_get_nr_vecs(bdev);
7089 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
7092 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
7093 int rw, u64 file_offset, int skip_sum,
7096 int write = rw & REQ_WRITE;
7097 struct btrfs_root *root = BTRFS_I(inode)->root;
7101 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7106 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
7114 if (write && async_submit) {
7115 ret = btrfs_wq_submit_bio(root->fs_info,
7116 inode, rw, bio, 0, 0,
7118 __btrfs_submit_bio_start_direct_io,
7119 __btrfs_submit_bio_done);
7123 * If we aren't doing async submit, calculate the csum of the
7126 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
7129 } else if (!skip_sum) {
7130 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
7136 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
7142 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
7145 struct inode *inode = dip->inode;
7146 struct btrfs_root *root = BTRFS_I(inode)->root;
7148 struct bio *orig_bio = dip->orig_bio;
7149 struct bio_vec *bvec = orig_bio->bi_io_vec;
7150 u64 start_sector = orig_bio->bi_sector;
7151 u64 file_offset = dip->logical_offset;
7156 int async_submit = 0;
7158 map_length = orig_bio->bi_size;
7159 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
7160 &map_length, NULL, 0);
7165 if (map_length >= orig_bio->bi_size) {
7170 /* async crcs make it difficult to collect full stripe writes. */
7171 if (btrfs_get_alloc_profile(root, 1) &
7172 (BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6))
7177 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
7180 bio->bi_private = dip;
7181 bio->bi_end_io = btrfs_end_dio_bio;
7182 atomic_inc(&dip->pending_bios);
7184 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
7185 if (unlikely(map_length < submit_len + bvec->bv_len ||
7186 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
7187 bvec->bv_offset) < bvec->bv_len)) {
7189 * inc the count before we submit the bio so
7190 * we know the end IO handler won't happen before
7191 * we inc the count. Otherwise, the dip might get freed
7192 * before we're done setting it up
7194 atomic_inc(&dip->pending_bios);
7195 ret = __btrfs_submit_dio_bio(bio, inode, rw,
7196 file_offset, skip_sum,
7200 atomic_dec(&dip->pending_bios);
7204 start_sector += submit_len >> 9;
7205 file_offset += submit_len;
7210 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
7211 start_sector, GFP_NOFS);
7214 bio->bi_private = dip;
7215 bio->bi_end_io = btrfs_end_dio_bio;
7217 map_length = orig_bio->bi_size;
7218 ret = btrfs_map_block(root->fs_info, rw,
7220 &map_length, NULL, 0);
7226 submit_len += bvec->bv_len;
7233 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
7242 * before atomic variable goto zero, we must
7243 * make sure dip->errors is perceived to be set.
7245 smp_mb__before_atomic_dec();
7246 if (atomic_dec_and_test(&dip->pending_bios))
7247 bio_io_error(dip->orig_bio);
7249 /* bio_end_io() will handle error, so we needn't return it */
7253 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
7254 struct inode *inode, loff_t file_offset)
7256 struct btrfs_root *root = BTRFS_I(inode)->root;
7257 struct btrfs_dio_private *dip;
7258 struct bio_vec *bvec = dio_bio->bi_io_vec;
7261 int write = rw & REQ_WRITE;
7264 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7266 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
7273 dip = kmalloc(sizeof(*dip), GFP_NOFS);
7279 dip->private = dio_bio->bi_private;
7280 io_bio->bi_private = dio_bio->bi_private;
7282 dip->logical_offset = file_offset;
7286 dip->bytes += bvec->bv_len;
7288 } while (bvec <= (dio_bio->bi_io_vec + dio_bio->bi_vcnt - 1));
7290 dip->disk_bytenr = (u64)dio_bio->bi_sector << 9;
7291 io_bio->bi_private = dip;
7293 dip->orig_bio = io_bio;
7294 dip->dio_bio = dio_bio;
7295 atomic_set(&dip->pending_bios, 0);
7298 io_bio->bi_end_io = btrfs_endio_direct_write;
7300 io_bio->bi_end_io = btrfs_endio_direct_read;
7302 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
7311 * If this is a write, we need to clean up the reserved space and kill
7312 * the ordered extent.
7315 struct btrfs_ordered_extent *ordered;
7316 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
7317 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
7318 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
7319 btrfs_free_reserved_extent(root, ordered->start,
7321 btrfs_put_ordered_extent(ordered);
7322 btrfs_put_ordered_extent(ordered);
7324 bio_endio(dio_bio, ret);
7327 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
7328 const struct iovec *iov, loff_t offset,
7329 unsigned long nr_segs)
7335 unsigned blocksize_mask = root->sectorsize - 1;
7336 ssize_t retval = -EINVAL;
7337 loff_t end = offset;
7339 if (offset & blocksize_mask)
7342 /* Check the memory alignment. Blocks cannot straddle pages */
7343 for (seg = 0; seg < nr_segs; seg++) {
7344 addr = (unsigned long)iov[seg].iov_base;
7345 size = iov[seg].iov_len;
7347 if ((addr & blocksize_mask) || (size & blocksize_mask))
7350 /* If this is a write we don't need to check anymore */
7355 * Check to make sure we don't have duplicate iov_base's in this
7356 * iovec, if so return EINVAL, otherwise we'll get csum errors
7357 * when reading back.
7359 for (i = seg + 1; i < nr_segs; i++) {
7360 if (iov[seg].iov_base == iov[i].iov_base)
7369 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
7370 const struct iovec *iov, loff_t offset,
7371 unsigned long nr_segs)
7373 struct file *file = iocb->ki_filp;
7374 struct inode *inode = file->f_mapping->host;
7378 bool relock = false;
7381 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
7385 atomic_inc(&inode->i_dio_count);
7386 smp_mb__after_atomic_inc();
7389 count = iov_length(iov, nr_segs);
7391 * If the write DIO is beyond the EOF, we need update
7392 * the isize, but it is protected by i_mutex. So we can
7393 * not unlock the i_mutex at this case.
7395 if (offset + count <= inode->i_size) {
7396 mutex_unlock(&inode->i_mutex);
7399 ret = btrfs_delalloc_reserve_space(inode, count);
7402 } else if (unlikely(test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
7403 &BTRFS_I(inode)->runtime_flags))) {
7404 inode_dio_done(inode);
7405 flags = DIO_LOCKING | DIO_SKIP_HOLES;
7409 ret = __blockdev_direct_IO(rw, iocb, inode,
7410 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
7411 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
7412 btrfs_submit_direct, flags);
7414 if (ret < 0 && ret != -EIOCBQUEUED)
7415 btrfs_delalloc_release_space(inode, count);
7416 else if (ret >= 0 && (size_t)ret < count)
7417 btrfs_delalloc_release_space(inode,
7418 count - (size_t)ret);
7420 btrfs_delalloc_release_metadata(inode, 0);
7424 inode_dio_done(inode);
7426 mutex_lock(&inode->i_mutex);
7431 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
7433 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
7434 __u64 start, __u64 len)
7438 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
7442 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
7445 int btrfs_readpage(struct file *file, struct page *page)
7447 struct extent_io_tree *tree;
7448 tree = &BTRFS_I(page->mapping->host)->io_tree;
7449 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
7452 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
7454 struct extent_io_tree *tree;
7457 if (current->flags & PF_MEMALLOC) {
7458 redirty_page_for_writepage(wbc, page);
7462 tree = &BTRFS_I(page->mapping->host)->io_tree;
7463 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
7466 static int btrfs_writepages(struct address_space *mapping,
7467 struct writeback_control *wbc)
7469 struct extent_io_tree *tree;
7471 tree = &BTRFS_I(mapping->host)->io_tree;
7472 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
7476 btrfs_readpages(struct file *file, struct address_space *mapping,
7477 struct list_head *pages, unsigned nr_pages)
7479 struct extent_io_tree *tree;
7480 tree = &BTRFS_I(mapping->host)->io_tree;
7481 return extent_readpages(tree, mapping, pages, nr_pages,
7484 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7486 struct extent_io_tree *tree;
7487 struct extent_map_tree *map;
7490 tree = &BTRFS_I(page->mapping->host)->io_tree;
7491 map = &BTRFS_I(page->mapping->host)->extent_tree;
7492 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
7494 ClearPagePrivate(page);
7495 set_page_private(page, 0);
7496 page_cache_release(page);
7501 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
7503 if (PageWriteback(page) || PageDirty(page))
7505 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
7508 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
7510 struct inode *inode = page->mapping->host;
7511 struct extent_io_tree *tree;
7512 struct btrfs_ordered_extent *ordered;
7513 struct extent_state *cached_state = NULL;
7514 u64 page_start = page_offset(page);
7515 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
7518 * we have the page locked, so new writeback can't start,
7519 * and the dirty bit won't be cleared while we are here.
7521 * Wait for IO on this page so that we can safely clear
7522 * the PagePrivate2 bit and do ordered accounting
7524 wait_on_page_writeback(page);
7526 tree = &BTRFS_I(inode)->io_tree;
7528 btrfs_releasepage(page, GFP_NOFS);
7531 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7532 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
7535 * IO on this page will never be started, so we need
7536 * to account for any ordered extents now
7538 clear_extent_bit(tree, page_start, page_end,
7539 EXTENT_DIRTY | EXTENT_DELALLOC |
7540 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7541 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
7543 * whoever cleared the private bit is responsible
7544 * for the finish_ordered_io
7546 if (TestClearPagePrivate2(page) &&
7547 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
7548 PAGE_CACHE_SIZE, 1)) {
7549 btrfs_finish_ordered_io(ordered);
7551 btrfs_put_ordered_extent(ordered);
7552 cached_state = NULL;
7553 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
7555 clear_extent_bit(tree, page_start, page_end,
7556 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
7557 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
7558 &cached_state, GFP_NOFS);
7559 __btrfs_releasepage(page, GFP_NOFS);
7561 ClearPageChecked(page);
7562 if (PagePrivate(page)) {
7563 ClearPagePrivate(page);
7564 set_page_private(page, 0);
7565 page_cache_release(page);
7570 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
7571 * called from a page fault handler when a page is first dirtied. Hence we must
7572 * be careful to check for EOF conditions here. We set the page up correctly
7573 * for a written page which means we get ENOSPC checking when writing into
7574 * holes and correct delalloc and unwritten extent mapping on filesystems that
7575 * support these features.
7577 * We are not allowed to take the i_mutex here so we have to play games to
7578 * protect against truncate races as the page could now be beyond EOF. Because
7579 * vmtruncate() writes the inode size before removing pages, once we have the
7580 * page lock we can determine safely if the page is beyond EOF. If it is not
7581 * beyond EOF, then the page is guaranteed safe against truncation until we
7584 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
7586 struct page *page = vmf->page;
7587 struct inode *inode = file_inode(vma->vm_file);
7588 struct btrfs_root *root = BTRFS_I(inode)->root;
7589 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7590 struct btrfs_ordered_extent *ordered;
7591 struct extent_state *cached_state = NULL;
7593 unsigned long zero_start;
7600 sb_start_pagefault(inode->i_sb);
7601 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
7603 ret = file_update_time(vma->vm_file);
7609 else /* -ENOSPC, -EIO, etc */
7610 ret = VM_FAULT_SIGBUS;
7616 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
7619 size = i_size_read(inode);
7620 page_start = page_offset(page);
7621 page_end = page_start + PAGE_CACHE_SIZE - 1;
7623 if ((page->mapping != inode->i_mapping) ||
7624 (page_start >= size)) {
7625 /* page got truncated out from underneath us */
7628 wait_on_page_writeback(page);
7630 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
7631 set_page_extent_mapped(page);
7634 * we can't set the delalloc bits if there are pending ordered
7635 * extents. Drop our locks and wait for them to finish
7637 ordered = btrfs_lookup_ordered_extent(inode, page_start);
7639 unlock_extent_cached(io_tree, page_start, page_end,
7640 &cached_state, GFP_NOFS);
7642 btrfs_start_ordered_extent(inode, ordered, 1);
7643 btrfs_put_ordered_extent(ordered);
7648 * XXX - page_mkwrite gets called every time the page is dirtied, even
7649 * if it was already dirty, so for space accounting reasons we need to
7650 * clear any delalloc bits for the range we are fixing to save. There
7651 * is probably a better way to do this, but for now keep consistent with
7652 * prepare_pages in the normal write path.
7654 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
7655 EXTENT_DIRTY | EXTENT_DELALLOC |
7656 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
7657 0, 0, &cached_state, GFP_NOFS);
7659 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
7662 unlock_extent_cached(io_tree, page_start, page_end,
7663 &cached_state, GFP_NOFS);
7664 ret = VM_FAULT_SIGBUS;
7669 /* page is wholly or partially inside EOF */
7670 if (page_start + PAGE_CACHE_SIZE > size)
7671 zero_start = size & ~PAGE_CACHE_MASK;
7673 zero_start = PAGE_CACHE_SIZE;
7675 if (zero_start != PAGE_CACHE_SIZE) {
7677 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
7678 flush_dcache_page(page);
7681 ClearPageChecked(page);
7682 set_page_dirty(page);
7683 SetPageUptodate(page);
7685 BTRFS_I(inode)->last_trans = root->fs_info->generation;
7686 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
7687 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
7689 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
7693 sb_end_pagefault(inode->i_sb);
7694 return VM_FAULT_LOCKED;
7698 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
7700 sb_end_pagefault(inode->i_sb);
7704 static int btrfs_truncate(struct inode *inode)
7706 struct btrfs_root *root = BTRFS_I(inode)->root;
7707 struct btrfs_block_rsv *rsv;
7710 struct btrfs_trans_handle *trans;
7711 u64 mask = root->sectorsize - 1;
7712 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
7714 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
7718 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
7719 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
7722 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
7723 * 3 things going on here
7725 * 1) We need to reserve space for our orphan item and the space to
7726 * delete our orphan item. Lord knows we don't want to have a dangling
7727 * orphan item because we didn't reserve space to remove it.
7729 * 2) We need to reserve space to update our inode.
7731 * 3) We need to have something to cache all the space that is going to
7732 * be free'd up by the truncate operation, but also have some slack
7733 * space reserved in case it uses space during the truncate (thank you
7734 * very much snapshotting).
7736 * And we need these to all be seperate. The fact is we can use alot of
7737 * space doing the truncate, and we have no earthly idea how much space
7738 * we will use, so we need the truncate reservation to be seperate so it
7739 * doesn't end up using space reserved for updating the inode or
7740 * removing the orphan item. We also need to be able to stop the
7741 * transaction and start a new one, which means we need to be able to
7742 * update the inode several times, and we have no idea of knowing how
7743 * many times that will be, so we can't just reserve 1 item for the
7744 * entirety of the opration, so that has to be done seperately as well.
7745 * Then there is the orphan item, which does indeed need to be held on
7746 * to for the whole operation, and we need nobody to touch this reserved
7747 * space except the orphan code.
7749 * So that leaves us with
7751 * 1) root->orphan_block_rsv - for the orphan deletion.
7752 * 2) rsv - for the truncate reservation, which we will steal from the
7753 * transaction reservation.
7754 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7755 * updating the inode.
7757 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7760 rsv->size = min_size;
7764 * 1 for the truncate slack space
7765 * 1 for updating the inode.
7767 trans = btrfs_start_transaction(root, 2);
7768 if (IS_ERR(trans)) {
7769 err = PTR_ERR(trans);
7773 /* Migrate the slack space for the truncate to our reserve */
7774 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7779 * setattr is responsible for setting the ordered_data_close flag,
7780 * but that is only tested during the last file release. That
7781 * could happen well after the next commit, leaving a great big
7782 * window where new writes may get lost if someone chooses to write
7783 * to this file after truncating to zero
7785 * The inode doesn't have any dirty data here, and so if we commit
7786 * this is a noop. If someone immediately starts writing to the inode
7787 * it is very likely we'll catch some of their writes in this
7788 * transaction, and the commit will find this file on the ordered
7789 * data list with good things to send down.
7791 * This is a best effort solution, there is still a window where
7792 * using truncate to replace the contents of the file will
7793 * end up with a zero length file after a crash.
7795 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7796 &BTRFS_I(inode)->runtime_flags))
7797 btrfs_add_ordered_operation(trans, root, inode);
7800 * So if we truncate and then write and fsync we normally would just
7801 * write the extents that changed, which is a problem if we need to
7802 * first truncate that entire inode. So set this flag so we write out
7803 * all of the extents in the inode to the sync log so we're completely
7806 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7807 trans->block_rsv = rsv;
7810 ret = btrfs_truncate_inode_items(trans, root, inode,
7812 BTRFS_EXTENT_DATA_KEY);
7813 if (ret != -ENOSPC) {
7818 trans->block_rsv = &root->fs_info->trans_block_rsv;
7819 ret = btrfs_update_inode(trans, root, inode);
7825 btrfs_end_transaction(trans, root);
7826 btrfs_btree_balance_dirty(root);
7828 trans = btrfs_start_transaction(root, 2);
7829 if (IS_ERR(trans)) {
7830 ret = err = PTR_ERR(trans);
7835 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7837 BUG_ON(ret); /* shouldn't happen */
7838 trans->block_rsv = rsv;
7841 if (ret == 0 && inode->i_nlink > 0) {
7842 trans->block_rsv = root->orphan_block_rsv;
7843 ret = btrfs_orphan_del(trans, inode);
7849 trans->block_rsv = &root->fs_info->trans_block_rsv;
7850 ret = btrfs_update_inode(trans, root, inode);
7854 ret = btrfs_end_transaction(trans, root);
7855 btrfs_btree_balance_dirty(root);
7859 btrfs_free_block_rsv(root, rsv);
7868 * create a new subvolume directory/inode (helper for the ioctl).
7870 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7871 struct btrfs_root *new_root, u64 new_dirid)
7873 struct inode *inode;
7877 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7878 new_dirid, new_dirid,
7879 S_IFDIR | (~current_umask() & S_IRWXUGO),
7882 return PTR_ERR(inode);
7883 inode->i_op = &btrfs_dir_inode_operations;
7884 inode->i_fop = &btrfs_dir_file_operations;
7886 set_nlink(inode, 1);
7887 btrfs_i_size_write(inode, 0);
7889 err = btrfs_update_inode(trans, new_root, inode);
7895 struct inode *btrfs_alloc_inode(struct super_block *sb)
7897 struct btrfs_inode *ei;
7898 struct inode *inode;
7900 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7907 ei->last_sub_trans = 0;
7908 ei->logged_trans = 0;
7909 ei->delalloc_bytes = 0;
7910 ei->disk_i_size = 0;
7913 ei->index_cnt = (u64)-1;
7914 ei->last_unlink_trans = 0;
7915 ei->last_log_commit = 0;
7917 spin_lock_init(&ei->lock);
7918 ei->outstanding_extents = 0;
7919 ei->reserved_extents = 0;
7921 ei->runtime_flags = 0;
7922 ei->force_compress = BTRFS_COMPRESS_NONE;
7924 ei->delayed_node = NULL;
7926 inode = &ei->vfs_inode;
7927 extent_map_tree_init(&ei->extent_tree);
7928 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7929 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7930 ei->io_tree.track_uptodate = 1;
7931 ei->io_failure_tree.track_uptodate = 1;
7932 atomic_set(&ei->sync_writers, 0);
7933 mutex_init(&ei->log_mutex);
7934 mutex_init(&ei->delalloc_mutex);
7935 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7936 INIT_LIST_HEAD(&ei->delalloc_inodes);
7937 INIT_LIST_HEAD(&ei->ordered_operations);
7938 RB_CLEAR_NODE(&ei->rb_node);
7943 static void btrfs_i_callback(struct rcu_head *head)
7945 struct inode *inode = container_of(head, struct inode, i_rcu);
7946 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7949 void btrfs_destroy_inode(struct inode *inode)
7951 struct btrfs_ordered_extent *ordered;
7952 struct btrfs_root *root = BTRFS_I(inode)->root;
7954 WARN_ON(!hlist_empty(&inode->i_dentry));
7955 WARN_ON(inode->i_data.nrpages);
7956 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7957 WARN_ON(BTRFS_I(inode)->reserved_extents);
7958 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7959 WARN_ON(BTRFS_I(inode)->csum_bytes);
7962 * This can happen where we create an inode, but somebody else also
7963 * created the same inode and we need to destroy the one we already
7970 * Make sure we're properly removed from the ordered operation
7974 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7975 spin_lock(&root->fs_info->ordered_extent_lock);
7976 list_del_init(&BTRFS_I(inode)->ordered_operations);
7977 spin_unlock(&root->fs_info->ordered_extent_lock);
7980 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7981 &BTRFS_I(inode)->runtime_flags)) {
7982 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
7983 (unsigned long long)btrfs_ino(inode));
7984 atomic_dec(&root->orphan_inodes);
7988 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7992 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
7993 (unsigned long long)ordered->file_offset,
7994 (unsigned long long)ordered->len);
7995 btrfs_remove_ordered_extent(inode, ordered);
7996 btrfs_put_ordered_extent(ordered);
7997 btrfs_put_ordered_extent(ordered);
8000 inode_tree_del(inode);
8001 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
8003 btrfs_remove_delayed_node(inode);
8004 call_rcu(&inode->i_rcu, btrfs_i_callback);
8007 int btrfs_drop_inode(struct inode *inode)
8009 struct btrfs_root *root = BTRFS_I(inode)->root;
8011 /* the snap/subvol tree is on deleting */
8012 if (btrfs_root_refs(&root->root_item) == 0 &&
8013 root != root->fs_info->tree_root)
8016 return generic_drop_inode(inode);
8019 static void init_once(void *foo)
8021 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8023 inode_init_once(&ei->vfs_inode);
8026 void btrfs_destroy_cachep(void)
8029 * Make sure all delayed rcu free inodes are flushed before we
8033 if (btrfs_inode_cachep)
8034 kmem_cache_destroy(btrfs_inode_cachep);
8035 if (btrfs_trans_handle_cachep)
8036 kmem_cache_destroy(btrfs_trans_handle_cachep);
8037 if (btrfs_transaction_cachep)
8038 kmem_cache_destroy(btrfs_transaction_cachep);
8039 if (btrfs_path_cachep)
8040 kmem_cache_destroy(btrfs_path_cachep);
8041 if (btrfs_free_space_cachep)
8042 kmem_cache_destroy(btrfs_free_space_cachep);
8043 if (btrfs_delalloc_work_cachep)
8044 kmem_cache_destroy(btrfs_delalloc_work_cachep);
8047 int btrfs_init_cachep(void)
8049 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8050 sizeof(struct btrfs_inode), 0,
8051 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
8052 if (!btrfs_inode_cachep)
8055 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8056 sizeof(struct btrfs_trans_handle), 0,
8057 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8058 if (!btrfs_trans_handle_cachep)
8061 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
8062 sizeof(struct btrfs_transaction), 0,
8063 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8064 if (!btrfs_transaction_cachep)
8067 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8068 sizeof(struct btrfs_path), 0,
8069 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8070 if (!btrfs_path_cachep)
8073 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8074 sizeof(struct btrfs_free_space), 0,
8075 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
8076 if (!btrfs_free_space_cachep)
8079 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
8080 sizeof(struct btrfs_delalloc_work), 0,
8081 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
8083 if (!btrfs_delalloc_work_cachep)
8088 btrfs_destroy_cachep();
8092 static int btrfs_getattr(struct vfsmount *mnt,
8093 struct dentry *dentry, struct kstat *stat)
8096 struct inode *inode = dentry->d_inode;
8097 u32 blocksize = inode->i_sb->s_blocksize;
8099 generic_fillattr(inode, stat);
8100 stat->dev = BTRFS_I(inode)->root->anon_dev;
8101 stat->blksize = PAGE_CACHE_SIZE;
8103 spin_lock(&BTRFS_I(inode)->lock);
8104 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
8105 spin_unlock(&BTRFS_I(inode)->lock);
8106 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8107 ALIGN(delalloc_bytes, blocksize)) >> 9;
8111 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
8112 struct inode *new_dir, struct dentry *new_dentry)
8114 struct btrfs_trans_handle *trans;
8115 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8116 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8117 struct inode *new_inode = new_dentry->d_inode;
8118 struct inode *old_inode = old_dentry->d_inode;
8119 struct timespec ctime = CURRENT_TIME;
8123 u64 old_ino = btrfs_ino(old_inode);
8125 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8128 /* we only allow rename subvolume link between subvolumes */
8129 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8132 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8133 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
8136 if (S_ISDIR(old_inode->i_mode) && new_inode &&
8137 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8141 /* check for collisions, even if the name isn't there */
8142 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
8143 new_dentry->d_name.name,
8144 new_dentry->d_name.len);
8147 if (ret == -EEXIST) {
8149 * eexist without a new_inode */
8155 /* maybe -EOVERFLOW */
8162 * we're using rename to replace one file with another.
8163 * and the replacement file is large. Start IO on it now so
8164 * we don't add too much work to the end of the transaction
8166 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
8167 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
8168 filemap_flush(old_inode->i_mapping);
8170 /* close the racy window with snapshot create/destroy ioctl */
8171 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8172 down_read(&root->fs_info->subvol_sem);
8174 * We want to reserve the absolute worst case amount of items. So if
8175 * both inodes are subvols and we need to unlink them then that would
8176 * require 4 item modifications, but if they are both normal inodes it
8177 * would require 5 item modifications, so we'll assume their normal
8178 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
8179 * should cover the worst case number of items we'll modify.
8181 trans = btrfs_start_transaction(root, 11);
8182 if (IS_ERR(trans)) {
8183 ret = PTR_ERR(trans);
8188 btrfs_record_root_in_trans(trans, dest);
8190 ret = btrfs_set_inode_index(new_dir, &index);
8194 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8195 /* force full log commit if subvolume involved. */
8196 root->fs_info->last_trans_log_full_commit = trans->transid;
8198 ret = btrfs_insert_inode_ref(trans, dest,
8199 new_dentry->d_name.name,
8200 new_dentry->d_name.len,
8202 btrfs_ino(new_dir), index);
8206 * this is an ugly little race, but the rename is required
8207 * to make sure that if we crash, the inode is either at the
8208 * old name or the new one. pinning the log transaction lets
8209 * us make sure we don't allow a log commit to come in after
8210 * we unlink the name but before we add the new name back in.
8212 btrfs_pin_log_trans(root);
8215 * make sure the inode gets flushed if it is replacing
8218 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
8219 btrfs_add_ordered_operation(trans, root, old_inode);
8221 inode_inc_iversion(old_dir);
8222 inode_inc_iversion(new_dir);
8223 inode_inc_iversion(old_inode);
8224 old_dir->i_ctime = old_dir->i_mtime = ctime;
8225 new_dir->i_ctime = new_dir->i_mtime = ctime;
8226 old_inode->i_ctime = ctime;
8228 if (old_dentry->d_parent != new_dentry->d_parent)
8229 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
8231 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8232 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
8233 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
8234 old_dentry->d_name.name,
8235 old_dentry->d_name.len);
8237 ret = __btrfs_unlink_inode(trans, root, old_dir,
8238 old_dentry->d_inode,
8239 old_dentry->d_name.name,
8240 old_dentry->d_name.len);
8242 ret = btrfs_update_inode(trans, root, old_inode);
8245 btrfs_abort_transaction(trans, root, ret);
8250 inode_inc_iversion(new_inode);
8251 new_inode->i_ctime = CURRENT_TIME;
8252 if (unlikely(btrfs_ino(new_inode) ==
8253 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8254 root_objectid = BTRFS_I(new_inode)->location.objectid;
8255 ret = btrfs_unlink_subvol(trans, dest, new_dir,
8257 new_dentry->d_name.name,
8258 new_dentry->d_name.len);
8259 BUG_ON(new_inode->i_nlink == 0);
8261 ret = btrfs_unlink_inode(trans, dest, new_dir,
8262 new_dentry->d_inode,
8263 new_dentry->d_name.name,
8264 new_dentry->d_name.len);
8266 if (!ret && new_inode->i_nlink == 0) {
8267 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
8271 btrfs_abort_transaction(trans, root, ret);
8276 ret = btrfs_add_link(trans, new_dir, old_inode,
8277 new_dentry->d_name.name,
8278 new_dentry->d_name.len, 0, index);
8280 btrfs_abort_transaction(trans, root, ret);
8284 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8285 struct dentry *parent = new_dentry->d_parent;
8286 btrfs_log_new_name(trans, old_inode, old_dir, parent);
8287 btrfs_end_log_trans(root);
8290 btrfs_end_transaction(trans, root);
8292 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8293 up_read(&root->fs_info->subvol_sem);
8298 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8300 struct btrfs_delalloc_work *delalloc_work;
8302 delalloc_work = container_of(work, struct btrfs_delalloc_work,
8304 if (delalloc_work->wait)
8305 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
8307 filemap_flush(delalloc_work->inode->i_mapping);
8309 if (delalloc_work->delay_iput)
8310 btrfs_add_delayed_iput(delalloc_work->inode);
8312 iput(delalloc_work->inode);
8313 complete(&delalloc_work->completion);
8316 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
8317 int wait, int delay_iput)
8319 struct btrfs_delalloc_work *work;
8321 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
8325 init_completion(&work->completion);
8326 INIT_LIST_HEAD(&work->list);
8327 work->inode = inode;
8329 work->delay_iput = delay_iput;
8330 work->work.func = btrfs_run_delalloc_work;
8335 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
8337 wait_for_completion(&work->completion);
8338 kmem_cache_free(btrfs_delalloc_work_cachep, work);
8342 * some fairly slow code that needs optimization. This walks the list
8343 * of all the inodes with pending delalloc and forces them to disk.
8345 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
8347 struct btrfs_inode *binode;
8348 struct inode *inode;
8349 struct btrfs_delalloc_work *work, *next;
8350 struct list_head works;
8351 struct list_head splice;
8354 if (root->fs_info->sb->s_flags & MS_RDONLY)
8357 INIT_LIST_HEAD(&works);
8358 INIT_LIST_HEAD(&splice);
8360 spin_lock(&root->fs_info->delalloc_lock);
8361 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
8362 while (!list_empty(&splice)) {
8363 binode = list_entry(splice.next, struct btrfs_inode,
8366 list_del_init(&binode->delalloc_inodes);
8368 inode = igrab(&binode->vfs_inode);
8370 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
8371 &binode->runtime_flags);
8375 list_add_tail(&binode->delalloc_inodes,
8376 &root->fs_info->delalloc_inodes);
8377 spin_unlock(&root->fs_info->delalloc_lock);
8379 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
8380 if (unlikely(!work)) {
8384 list_add_tail(&work->list, &works);
8385 btrfs_queue_worker(&root->fs_info->flush_workers,
8389 spin_lock(&root->fs_info->delalloc_lock);
8391 spin_unlock(&root->fs_info->delalloc_lock);
8393 list_for_each_entry_safe(work, next, &works, list) {
8394 list_del_init(&work->list);
8395 btrfs_wait_and_free_delalloc_work(work);
8398 /* the filemap_flush will queue IO into the worker threads, but
8399 * we have to make sure the IO is actually started and that
8400 * ordered extents get created before we return
8402 atomic_inc(&root->fs_info->async_submit_draining);
8403 while (atomic_read(&root->fs_info->nr_async_submits) ||
8404 atomic_read(&root->fs_info->async_delalloc_pages)) {
8405 wait_event(root->fs_info->async_submit_wait,
8406 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
8407 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
8409 atomic_dec(&root->fs_info->async_submit_draining);
8412 list_for_each_entry_safe(work, next, &works, list) {
8413 list_del_init(&work->list);
8414 btrfs_wait_and_free_delalloc_work(work);
8417 if (!list_empty_careful(&splice)) {
8418 spin_lock(&root->fs_info->delalloc_lock);
8419 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
8420 spin_unlock(&root->fs_info->delalloc_lock);
8425 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
8426 const char *symname)
8428 struct btrfs_trans_handle *trans;
8429 struct btrfs_root *root = BTRFS_I(dir)->root;
8430 struct btrfs_path *path;
8431 struct btrfs_key key;
8432 struct inode *inode = NULL;
8440 struct btrfs_file_extent_item *ei;
8441 struct extent_buffer *leaf;
8443 name_len = strlen(symname) + 1;
8444 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
8445 return -ENAMETOOLONG;
8448 * 2 items for inode item and ref
8449 * 2 items for dir items
8450 * 1 item for xattr if selinux is on
8452 trans = btrfs_start_transaction(root, 5);
8454 return PTR_ERR(trans);
8456 err = btrfs_find_free_ino(root, &objectid);
8460 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
8461 dentry->d_name.len, btrfs_ino(dir), objectid,
8462 S_IFLNK|S_IRWXUGO, &index);
8463 if (IS_ERR(inode)) {
8464 err = PTR_ERR(inode);
8468 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
8475 * If the active LSM wants to access the inode during
8476 * d_instantiate it needs these. Smack checks to see
8477 * if the filesystem supports xattrs by looking at the
8480 inode->i_fop = &btrfs_file_operations;
8481 inode->i_op = &btrfs_file_inode_operations;
8483 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
8487 inode->i_mapping->a_ops = &btrfs_aops;
8488 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8489 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
8494 path = btrfs_alloc_path();
8500 key.objectid = btrfs_ino(inode);
8502 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
8503 datasize = btrfs_file_extent_calc_inline_size(name_len);
8504 err = btrfs_insert_empty_item(trans, root, path, &key,
8508 btrfs_free_path(path);
8511 leaf = path->nodes[0];
8512 ei = btrfs_item_ptr(leaf, path->slots[0],
8513 struct btrfs_file_extent_item);
8514 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8515 btrfs_set_file_extent_type(leaf, ei,
8516 BTRFS_FILE_EXTENT_INLINE);
8517 btrfs_set_file_extent_encryption(leaf, ei, 0);
8518 btrfs_set_file_extent_compression(leaf, ei, 0);
8519 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8520 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8522 ptr = btrfs_file_extent_inline_start(ei);
8523 write_extent_buffer(leaf, symname, ptr, name_len);
8524 btrfs_mark_buffer_dirty(leaf);
8525 btrfs_free_path(path);
8527 inode->i_op = &btrfs_symlink_inode_operations;
8528 inode->i_mapping->a_ops = &btrfs_symlink_aops;
8529 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
8530 inode_set_bytes(inode, name_len);
8531 btrfs_i_size_write(inode, name_len - 1);
8532 err = btrfs_update_inode(trans, root, inode);
8538 d_instantiate(dentry, inode);
8539 btrfs_end_transaction(trans, root);
8541 inode_dec_link_count(inode);
8544 btrfs_btree_balance_dirty(root);
8548 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
8549 u64 start, u64 num_bytes, u64 min_size,
8550 loff_t actual_len, u64 *alloc_hint,
8551 struct btrfs_trans_handle *trans)
8553 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
8554 struct extent_map *em;
8555 struct btrfs_root *root = BTRFS_I(inode)->root;
8556 struct btrfs_key ins;
8557 u64 cur_offset = start;
8561 bool own_trans = true;
8565 while (num_bytes > 0) {
8567 trans = btrfs_start_transaction(root, 3);
8568 if (IS_ERR(trans)) {
8569 ret = PTR_ERR(trans);
8574 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
8575 cur_bytes = max(cur_bytes, min_size);
8576 ret = btrfs_reserve_extent(trans, root, cur_bytes,
8577 min_size, 0, *alloc_hint, &ins, 1);
8580 btrfs_end_transaction(trans, root);
8584 ret = insert_reserved_file_extent(trans, inode,
8585 cur_offset, ins.objectid,
8586 ins.offset, ins.offset,
8587 ins.offset, 0, 0, 0,
8588 BTRFS_FILE_EXTENT_PREALLOC);
8590 btrfs_abort_transaction(trans, root, ret);
8592 btrfs_end_transaction(trans, root);
8595 btrfs_drop_extent_cache(inode, cur_offset,
8596 cur_offset + ins.offset -1, 0);
8598 em = alloc_extent_map();
8600 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
8601 &BTRFS_I(inode)->runtime_flags);
8605 em->start = cur_offset;
8606 em->orig_start = cur_offset;
8607 em->len = ins.offset;
8608 em->block_start = ins.objectid;
8609 em->block_len = ins.offset;
8610 em->orig_block_len = ins.offset;
8611 em->ram_bytes = ins.offset;
8612 em->bdev = root->fs_info->fs_devices->latest_bdev;
8613 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
8614 em->generation = trans->transid;
8617 write_lock(&em_tree->lock);
8618 ret = add_extent_mapping(em_tree, em, 1);
8619 write_unlock(&em_tree->lock);
8622 btrfs_drop_extent_cache(inode, cur_offset,
8623 cur_offset + ins.offset - 1,
8626 free_extent_map(em);
8628 num_bytes -= ins.offset;
8629 cur_offset += ins.offset;
8630 *alloc_hint = ins.objectid + ins.offset;
8632 inode_inc_iversion(inode);
8633 inode->i_ctime = CURRENT_TIME;
8634 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
8635 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
8636 (actual_len > inode->i_size) &&
8637 (cur_offset > inode->i_size)) {
8638 if (cur_offset > actual_len)
8639 i_size = actual_len;
8641 i_size = cur_offset;
8642 i_size_write(inode, i_size);
8643 btrfs_ordered_update_i_size(inode, i_size, NULL);
8646 ret = btrfs_update_inode(trans, root, inode);
8649 btrfs_abort_transaction(trans, root, ret);
8651 btrfs_end_transaction(trans, root);
8656 btrfs_end_transaction(trans, root);
8661 int btrfs_prealloc_file_range(struct inode *inode, int mode,
8662 u64 start, u64 num_bytes, u64 min_size,
8663 loff_t actual_len, u64 *alloc_hint)
8665 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8666 min_size, actual_len, alloc_hint,
8670 int btrfs_prealloc_file_range_trans(struct inode *inode,
8671 struct btrfs_trans_handle *trans, int mode,
8672 u64 start, u64 num_bytes, u64 min_size,
8673 loff_t actual_len, u64 *alloc_hint)
8675 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
8676 min_size, actual_len, alloc_hint, trans);
8679 static int btrfs_set_page_dirty(struct page *page)
8681 return __set_page_dirty_nobuffers(page);
8684 static int btrfs_permission(struct inode *inode, int mask)
8686 struct btrfs_root *root = BTRFS_I(inode)->root;
8687 umode_t mode = inode->i_mode;
8689 if (mask & MAY_WRITE &&
8690 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
8691 if (btrfs_root_readonly(root))
8693 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
8696 return generic_permission(inode, mask);
8699 static const struct inode_operations btrfs_dir_inode_operations = {
8700 .getattr = btrfs_getattr,
8701 .lookup = btrfs_lookup,
8702 .create = btrfs_create,
8703 .unlink = btrfs_unlink,
8705 .mkdir = btrfs_mkdir,
8706 .rmdir = btrfs_rmdir,
8707 .rename = btrfs_rename,
8708 .symlink = btrfs_symlink,
8709 .setattr = btrfs_setattr,
8710 .mknod = btrfs_mknod,
8711 .setxattr = btrfs_setxattr,
8712 .getxattr = btrfs_getxattr,
8713 .listxattr = btrfs_listxattr,
8714 .removexattr = btrfs_removexattr,
8715 .permission = btrfs_permission,
8716 .get_acl = btrfs_get_acl,
8718 static const struct inode_operations btrfs_dir_ro_inode_operations = {
8719 .lookup = btrfs_lookup,
8720 .permission = btrfs_permission,
8721 .get_acl = btrfs_get_acl,
8724 static const struct file_operations btrfs_dir_file_operations = {
8725 .llseek = generic_file_llseek,
8726 .read = generic_read_dir,
8727 .readdir = btrfs_real_readdir,
8728 .unlocked_ioctl = btrfs_ioctl,
8729 #ifdef CONFIG_COMPAT
8730 .compat_ioctl = btrfs_ioctl,
8732 .release = btrfs_release_file,
8733 .fsync = btrfs_sync_file,
8736 static struct extent_io_ops btrfs_extent_io_ops = {
8737 .fill_delalloc = run_delalloc_range,
8738 .submit_bio_hook = btrfs_submit_bio_hook,
8739 .merge_bio_hook = btrfs_merge_bio_hook,
8740 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8741 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8742 .writepage_start_hook = btrfs_writepage_start_hook,
8743 .set_bit_hook = btrfs_set_bit_hook,
8744 .clear_bit_hook = btrfs_clear_bit_hook,
8745 .merge_extent_hook = btrfs_merge_extent_hook,
8746 .split_extent_hook = btrfs_split_extent_hook,
8750 * btrfs doesn't support the bmap operation because swapfiles
8751 * use bmap to make a mapping of extents in the file. They assume
8752 * these extents won't change over the life of the file and they
8753 * use the bmap result to do IO directly to the drive.
8755 * the btrfs bmap call would return logical addresses that aren't
8756 * suitable for IO and they also will change frequently as COW
8757 * operations happen. So, swapfile + btrfs == corruption.
8759 * For now we're avoiding this by dropping bmap.
8761 static const struct address_space_operations btrfs_aops = {
8762 .readpage = btrfs_readpage,
8763 .writepage = btrfs_writepage,
8764 .writepages = btrfs_writepages,
8765 .readpages = btrfs_readpages,
8766 .direct_IO = btrfs_direct_IO,
8767 .invalidatepage = btrfs_invalidatepage,
8768 .releasepage = btrfs_releasepage,
8769 .set_page_dirty = btrfs_set_page_dirty,
8770 .error_remove_page = generic_error_remove_page,
8773 static const struct address_space_operations btrfs_symlink_aops = {
8774 .readpage = btrfs_readpage,
8775 .writepage = btrfs_writepage,
8776 .invalidatepage = btrfs_invalidatepage,
8777 .releasepage = btrfs_releasepage,
8780 static const struct inode_operations btrfs_file_inode_operations = {
8781 .getattr = btrfs_getattr,
8782 .setattr = btrfs_setattr,
8783 .setxattr = btrfs_setxattr,
8784 .getxattr = btrfs_getxattr,
8785 .listxattr = btrfs_listxattr,
8786 .removexattr = btrfs_removexattr,
8787 .permission = btrfs_permission,
8788 .fiemap = btrfs_fiemap,
8789 .get_acl = btrfs_get_acl,
8790 .update_time = btrfs_update_time,
8792 static const struct inode_operations btrfs_special_inode_operations = {
8793 .getattr = btrfs_getattr,
8794 .setattr = btrfs_setattr,
8795 .permission = btrfs_permission,
8796 .setxattr = btrfs_setxattr,
8797 .getxattr = btrfs_getxattr,
8798 .listxattr = btrfs_listxattr,
8799 .removexattr = btrfs_removexattr,
8800 .get_acl = btrfs_get_acl,
8801 .update_time = btrfs_update_time,
8803 static const struct inode_operations btrfs_symlink_inode_operations = {
8804 .readlink = generic_readlink,
8805 .follow_link = page_follow_link_light,
8806 .put_link = page_put_link,
8807 .getattr = btrfs_getattr,
8808 .setattr = btrfs_setattr,
8809 .permission = btrfs_permission,
8810 .setxattr = btrfs_setxattr,
8811 .getxattr = btrfs_getxattr,
8812 .listxattr = btrfs_listxattr,
8813 .removexattr = btrfs_removexattr,
8814 .get_acl = btrfs_get_acl,
8815 .update_time = btrfs_update_time,
8818 const struct dentry_operations btrfs_dentry_operations = {
8819 .d_delete = btrfs_dentry_delete,
8820 .d_release = btrfs_dentry_release,