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>
45 #include "transaction.h"
46 #include "btrfs_inode.h"
48 #include "print-tree.h"
49 #include "ordered-data.h"
53 #include "compression.h"
55 #include "free-space-cache.h"
56 #include "inode-map.h"
58 struct btrfs_iget_args {
60 struct btrfs_root *root;
63 static const struct inode_operations btrfs_dir_inode_operations;
64 static const struct inode_operations btrfs_symlink_inode_operations;
65 static const struct inode_operations btrfs_dir_ro_inode_operations;
66 static const struct inode_operations btrfs_special_inode_operations;
67 static const struct inode_operations btrfs_file_inode_operations;
68 static const struct address_space_operations btrfs_aops;
69 static const struct address_space_operations btrfs_symlink_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static struct extent_io_ops btrfs_extent_io_ops;
73 static struct kmem_cache *btrfs_inode_cachep;
74 struct kmem_cache *btrfs_trans_handle_cachep;
75 struct kmem_cache *btrfs_transaction_cachep;
76 struct kmem_cache *btrfs_path_cachep;
77 struct kmem_cache *btrfs_free_space_cachep;
80 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
81 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
82 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
83 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
84 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
85 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
86 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
87 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
90 static int btrfs_setsize(struct inode *inode, loff_t newsize);
91 static int btrfs_truncate(struct inode *inode);
92 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
93 static noinline int cow_file_range(struct inode *inode,
94 struct page *locked_page,
95 u64 start, u64 end, int *page_started,
96 unsigned long *nr_written, int unlock);
97 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
98 struct btrfs_root *root, struct inode *inode);
100 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
101 struct inode *inode, struct inode *dir,
102 const struct qstr *qstr)
106 err = btrfs_init_acl(trans, inode, dir);
108 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
113 * this does all the hard work for inserting an inline extent into
114 * the btree. The caller should have done a btrfs_drop_extents so that
115 * no overlapping inline items exist in the btree
117 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
118 struct btrfs_root *root, struct inode *inode,
119 u64 start, size_t size, size_t compressed_size,
121 struct page **compressed_pages)
123 struct btrfs_key key;
124 struct btrfs_path *path;
125 struct extent_buffer *leaf;
126 struct page *page = NULL;
129 struct btrfs_file_extent_item *ei;
132 size_t cur_size = size;
134 unsigned long offset;
136 if (compressed_size && compressed_pages)
137 cur_size = compressed_size;
139 path = btrfs_alloc_path();
143 path->leave_spinning = 1;
145 key.objectid = btrfs_ino(inode);
147 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
148 datasize = btrfs_file_extent_calc_inline_size(cur_size);
150 inode_add_bytes(inode, size);
151 ret = btrfs_insert_empty_item(trans, root, path, &key,
157 leaf = path->nodes[0];
158 ei = btrfs_item_ptr(leaf, path->slots[0],
159 struct btrfs_file_extent_item);
160 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
161 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
162 btrfs_set_file_extent_encryption(leaf, ei, 0);
163 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
164 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
165 ptr = btrfs_file_extent_inline_start(ei);
167 if (compress_type != BTRFS_COMPRESS_NONE) {
170 while (compressed_size > 0) {
171 cpage = compressed_pages[i];
172 cur_size = min_t(unsigned long, compressed_size,
175 kaddr = kmap_atomic(cpage);
176 write_extent_buffer(leaf, kaddr, ptr, cur_size);
177 kunmap_atomic(kaddr);
181 compressed_size -= cur_size;
183 btrfs_set_file_extent_compression(leaf, ei,
186 page = find_get_page(inode->i_mapping,
187 start >> PAGE_CACHE_SHIFT);
188 btrfs_set_file_extent_compression(leaf, ei, 0);
189 kaddr = kmap_atomic(page);
190 offset = start & (PAGE_CACHE_SIZE - 1);
191 write_extent_buffer(leaf, kaddr + offset, ptr, size);
192 kunmap_atomic(kaddr);
193 page_cache_release(page);
195 btrfs_mark_buffer_dirty(leaf);
196 btrfs_free_path(path);
199 * we're an inline extent, so nobody can
200 * extend the file past i_size without locking
201 * a page we already have locked.
203 * We must do any isize and inode updates
204 * before we unlock the pages. Otherwise we
205 * could end up racing with unlink.
207 BTRFS_I(inode)->disk_i_size = inode->i_size;
208 ret = btrfs_update_inode(trans, root, inode);
212 btrfs_free_path(path);
218 * conditionally insert an inline extent into the file. This
219 * does the checks required to make sure the data is small enough
220 * to fit as an inline extent.
222 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
223 struct btrfs_root *root,
224 struct inode *inode, u64 start, u64 end,
225 size_t compressed_size, int compress_type,
226 struct page **compressed_pages)
228 u64 isize = i_size_read(inode);
229 u64 actual_end = min(end + 1, isize);
230 u64 inline_len = actual_end - start;
231 u64 aligned_end = (end + root->sectorsize - 1) &
232 ~((u64)root->sectorsize - 1);
234 u64 data_len = inline_len;
238 data_len = compressed_size;
241 actual_end >= PAGE_CACHE_SIZE ||
242 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
244 (actual_end & (root->sectorsize - 1)) == 0) ||
246 data_len > root->fs_info->max_inline) {
250 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end,
255 if (isize > actual_end)
256 inline_len = min_t(u64, isize, actual_end);
257 ret = insert_inline_extent(trans, root, inode, start,
258 inline_len, compressed_size,
259 compress_type, compressed_pages);
260 if (ret && ret != -ENOSPC) {
261 btrfs_abort_transaction(trans, root, ret);
263 } else if (ret == -ENOSPC) {
267 btrfs_delalloc_release_metadata(inode, end + 1 - start);
268 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
272 struct async_extent {
277 unsigned long nr_pages;
279 struct list_head list;
284 struct btrfs_root *root;
285 struct page *locked_page;
288 struct list_head extents;
289 struct btrfs_work work;
292 static noinline int add_async_extent(struct async_cow *cow,
293 u64 start, u64 ram_size,
296 unsigned long nr_pages,
299 struct async_extent *async_extent;
301 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
302 BUG_ON(!async_extent); /* -ENOMEM */
303 async_extent->start = start;
304 async_extent->ram_size = ram_size;
305 async_extent->compressed_size = compressed_size;
306 async_extent->pages = pages;
307 async_extent->nr_pages = nr_pages;
308 async_extent->compress_type = compress_type;
309 list_add_tail(&async_extent->list, &cow->extents);
314 * we create compressed extents in two phases. The first
315 * phase compresses a range of pages that have already been
316 * locked (both pages and state bits are locked).
318 * This is done inside an ordered work queue, and the compression
319 * is spread across many cpus. The actual IO submission is step
320 * two, and the ordered work queue takes care of making sure that
321 * happens in the same order things were put onto the queue by
322 * writepages and friends.
324 * If this code finds it can't get good compression, it puts an
325 * entry onto the work queue to write the uncompressed bytes. This
326 * makes sure that both compressed inodes and uncompressed inodes
327 * are written in the same order that the flusher thread sent them
330 static noinline int compress_file_range(struct inode *inode,
331 struct page *locked_page,
333 struct async_cow *async_cow,
336 struct btrfs_root *root = BTRFS_I(inode)->root;
337 struct btrfs_trans_handle *trans;
339 u64 blocksize = root->sectorsize;
341 u64 isize = i_size_read(inode);
343 struct page **pages = NULL;
344 unsigned long nr_pages;
345 unsigned long nr_pages_ret = 0;
346 unsigned long total_compressed = 0;
347 unsigned long total_in = 0;
348 unsigned long max_compressed = 128 * 1024;
349 unsigned long max_uncompressed = 128 * 1024;
352 int compress_type = root->fs_info->compress_type;
354 /* if this is a small write inside eof, kick off a defrag */
355 if ((end - start + 1) < 16 * 1024 &&
356 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
357 btrfs_add_inode_defrag(NULL, inode);
359 actual_end = min_t(u64, isize, end + 1);
362 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
363 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
366 * we don't want to send crud past the end of i_size through
367 * compression, that's just a waste of CPU time. So, if the
368 * end of the file is before the start of our current
369 * requested range of bytes, we bail out to the uncompressed
370 * cleanup code that can deal with all of this.
372 * It isn't really the fastest way to fix things, but this is a
373 * very uncommon corner.
375 if (actual_end <= start)
376 goto cleanup_and_bail_uncompressed;
378 total_compressed = actual_end - start;
380 /* we want to make sure that amount of ram required to uncompress
381 * an extent is reasonable, so we limit the total size in ram
382 * of a compressed extent to 128k. This is a crucial number
383 * because it also controls how easily we can spread reads across
384 * cpus for decompression.
386 * We also want to make sure the amount of IO required to do
387 * a random read is reasonably small, so we limit the size of
388 * a compressed extent to 128k.
390 total_compressed = min(total_compressed, max_uncompressed);
391 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
392 num_bytes = max(blocksize, num_bytes);
397 * we do compression for mount -o compress and when the
398 * inode has not been flagged as nocompress. This flag can
399 * change at any time if we discover bad compression ratios.
401 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
402 (btrfs_test_opt(root, COMPRESS) ||
403 (BTRFS_I(inode)->force_compress) ||
404 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
406 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
408 /* just bail out to the uncompressed code */
412 if (BTRFS_I(inode)->force_compress)
413 compress_type = BTRFS_I(inode)->force_compress;
415 ret = btrfs_compress_pages(compress_type,
416 inode->i_mapping, start,
417 total_compressed, pages,
418 nr_pages, &nr_pages_ret,
424 unsigned long offset = total_compressed &
425 (PAGE_CACHE_SIZE - 1);
426 struct page *page = pages[nr_pages_ret - 1];
429 /* zero the tail end of the last page, we might be
430 * sending it down to disk
433 kaddr = kmap_atomic(page);
434 memset(kaddr + offset, 0,
435 PAGE_CACHE_SIZE - offset);
436 kunmap_atomic(kaddr);
443 trans = btrfs_join_transaction(root);
445 ret = PTR_ERR(trans);
447 goto cleanup_and_out;
449 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
451 /* lets try to make an inline extent */
452 if (ret || total_in < (actual_end - start)) {
453 /* we didn't compress the entire range, try
454 * to make an uncompressed inline extent.
456 ret = cow_file_range_inline(trans, root, inode,
457 start, end, 0, 0, NULL);
459 /* try making a compressed inline extent */
460 ret = cow_file_range_inline(trans, root, inode,
463 compress_type, pages);
467 * inline extent creation worked or returned error,
468 * we don't need to create any more async work items.
469 * Unlock and free up our temp pages.
471 extent_clear_unlock_delalloc(inode,
472 &BTRFS_I(inode)->io_tree,
474 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
475 EXTENT_CLEAR_DELALLOC |
476 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
478 btrfs_end_transaction(trans, root);
481 btrfs_end_transaction(trans, root);
486 * we aren't doing an inline extent round the compressed size
487 * up to a block size boundary so the allocator does sane
490 total_compressed = (total_compressed + blocksize - 1) &
494 * one last check to make sure the compression is really a
495 * win, compare the page count read with the blocks on disk
497 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
498 ~(PAGE_CACHE_SIZE - 1);
499 if (total_compressed >= total_in) {
502 num_bytes = total_in;
505 if (!will_compress && pages) {
507 * the compression code ran but failed to make things smaller,
508 * free any pages it allocated and our page pointer array
510 for (i = 0; i < nr_pages_ret; i++) {
511 WARN_ON(pages[i]->mapping);
512 page_cache_release(pages[i]);
516 total_compressed = 0;
519 /* flag the file so we don't compress in the future */
520 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
521 !(BTRFS_I(inode)->force_compress)) {
522 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
528 /* the async work queues will take care of doing actual
529 * allocation on disk for these compressed pages,
530 * and will submit them to the elevator.
532 add_async_extent(async_cow, start, num_bytes,
533 total_compressed, pages, nr_pages_ret,
536 if (start + num_bytes < end) {
543 cleanup_and_bail_uncompressed:
545 * No compression, but we still need to write the pages in
546 * the file we've been given so far. redirty the locked
547 * page if it corresponds to our extent and set things up
548 * for the async work queue to run cow_file_range to do
549 * the normal delalloc dance
551 if (page_offset(locked_page) >= start &&
552 page_offset(locked_page) <= end) {
553 __set_page_dirty_nobuffers(locked_page);
554 /* unlocked later on in the async handlers */
556 add_async_extent(async_cow, start, end - start + 1,
557 0, NULL, 0, BTRFS_COMPRESS_NONE);
565 for (i = 0; i < nr_pages_ret; i++) {
566 WARN_ON(pages[i]->mapping);
567 page_cache_release(pages[i]);
574 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
576 EXTENT_CLEAR_UNLOCK_PAGE |
578 EXTENT_CLEAR_DELALLOC |
579 EXTENT_SET_WRITEBACK |
580 EXTENT_END_WRITEBACK);
581 if (!trans || IS_ERR(trans))
582 btrfs_error(root->fs_info, ret, "Failed to join transaction");
584 btrfs_abort_transaction(trans, root, ret);
589 * phase two of compressed writeback. This is the ordered portion
590 * of the code, which only gets called in the order the work was
591 * queued. We walk all the async extents created by compress_file_range
592 * and send them down to the disk.
594 static noinline int submit_compressed_extents(struct inode *inode,
595 struct async_cow *async_cow)
597 struct async_extent *async_extent;
599 struct btrfs_trans_handle *trans;
600 struct btrfs_key ins;
601 struct extent_map *em;
602 struct btrfs_root *root = BTRFS_I(inode)->root;
603 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
604 struct extent_io_tree *io_tree;
607 if (list_empty(&async_cow->extents))
611 while (!list_empty(&async_cow->extents)) {
612 async_extent = list_entry(async_cow->extents.next,
613 struct async_extent, list);
614 list_del(&async_extent->list);
616 io_tree = &BTRFS_I(inode)->io_tree;
619 /* did the compression code fall back to uncompressed IO? */
620 if (!async_extent->pages) {
621 int page_started = 0;
622 unsigned long nr_written = 0;
624 lock_extent(io_tree, async_extent->start,
625 async_extent->start +
626 async_extent->ram_size - 1);
628 /* allocate blocks */
629 ret = cow_file_range(inode, async_cow->locked_page,
631 async_extent->start +
632 async_extent->ram_size - 1,
633 &page_started, &nr_written, 0);
638 * if page_started, cow_file_range inserted an
639 * inline extent and took care of all the unlocking
640 * and IO for us. Otherwise, we need to submit
641 * all those pages down to the drive.
643 if (!page_started && !ret)
644 extent_write_locked_range(io_tree,
645 inode, async_extent->start,
646 async_extent->start +
647 async_extent->ram_size - 1,
655 lock_extent(io_tree, async_extent->start,
656 async_extent->start + async_extent->ram_size - 1);
658 trans = btrfs_join_transaction(root);
660 ret = PTR_ERR(trans);
662 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
663 ret = btrfs_reserve_extent(trans, root,
664 async_extent->compressed_size,
665 async_extent->compressed_size,
666 0, alloc_hint, &ins, 1);
668 btrfs_abort_transaction(trans, root, ret);
669 btrfs_end_transaction(trans, root);
674 for (i = 0; i < async_extent->nr_pages; i++) {
675 WARN_ON(async_extent->pages[i]->mapping);
676 page_cache_release(async_extent->pages[i]);
678 kfree(async_extent->pages);
679 async_extent->nr_pages = 0;
680 async_extent->pages = NULL;
681 unlock_extent(io_tree, async_extent->start,
682 async_extent->start +
683 async_extent->ram_size - 1);
686 goto out_free; /* JDM: Requeue? */
690 * here we're doing allocation and writeback of the
693 btrfs_drop_extent_cache(inode, async_extent->start,
694 async_extent->start +
695 async_extent->ram_size - 1, 0);
697 em = alloc_extent_map();
698 BUG_ON(!em); /* -ENOMEM */
699 em->start = async_extent->start;
700 em->len = async_extent->ram_size;
701 em->orig_start = em->start;
703 em->block_start = ins.objectid;
704 em->block_len = ins.offset;
705 em->bdev = root->fs_info->fs_devices->latest_bdev;
706 em->compress_type = async_extent->compress_type;
707 set_bit(EXTENT_FLAG_PINNED, &em->flags);
708 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
711 write_lock(&em_tree->lock);
712 ret = add_extent_mapping(em_tree, em);
713 write_unlock(&em_tree->lock);
714 if (ret != -EEXIST) {
718 btrfs_drop_extent_cache(inode, async_extent->start,
719 async_extent->start +
720 async_extent->ram_size - 1, 0);
723 ret = btrfs_add_ordered_extent_compress(inode,
726 async_extent->ram_size,
728 BTRFS_ORDERED_COMPRESSED,
729 async_extent->compress_type);
730 BUG_ON(ret); /* -ENOMEM */
733 * clear dirty, set writeback and unlock the pages.
735 extent_clear_unlock_delalloc(inode,
736 &BTRFS_I(inode)->io_tree,
738 async_extent->start +
739 async_extent->ram_size - 1,
740 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
741 EXTENT_CLEAR_UNLOCK |
742 EXTENT_CLEAR_DELALLOC |
743 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
745 ret = btrfs_submit_compressed_write(inode,
747 async_extent->ram_size,
749 ins.offset, async_extent->pages,
750 async_extent->nr_pages);
752 BUG_ON(ret); /* -ENOMEM */
753 alloc_hint = ins.objectid + ins.offset;
765 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
768 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
769 struct extent_map *em;
772 read_lock(&em_tree->lock);
773 em = search_extent_mapping(em_tree, start, num_bytes);
776 * if block start isn't an actual block number then find the
777 * first block in this inode and use that as a hint. If that
778 * block is also bogus then just don't worry about it.
780 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
782 em = search_extent_mapping(em_tree, 0, 0);
783 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
784 alloc_hint = em->block_start;
788 alloc_hint = em->block_start;
792 read_unlock(&em_tree->lock);
798 * when extent_io.c finds a delayed allocation range in the file,
799 * the call backs end up in this code. The basic idea is to
800 * allocate extents on disk for the range, and create ordered data structs
801 * in ram to track those extents.
803 * locked_page is the page that writepage had locked already. We use
804 * it to make sure we don't do extra locks or unlocks.
806 * *page_started is set to one if we unlock locked_page and do everything
807 * required to start IO on it. It may be clean and already done with
810 static noinline int cow_file_range(struct inode *inode,
811 struct page *locked_page,
812 u64 start, u64 end, int *page_started,
813 unsigned long *nr_written,
816 struct btrfs_root *root = BTRFS_I(inode)->root;
817 struct btrfs_trans_handle *trans;
820 unsigned long ram_size;
823 u64 blocksize = root->sectorsize;
824 struct btrfs_key ins;
825 struct extent_map *em;
826 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
829 BUG_ON(btrfs_is_free_space_inode(inode));
830 trans = btrfs_join_transaction(root);
832 extent_clear_unlock_delalloc(inode,
833 &BTRFS_I(inode)->io_tree,
834 start, end, locked_page,
835 EXTENT_CLEAR_UNLOCK_PAGE |
836 EXTENT_CLEAR_UNLOCK |
837 EXTENT_CLEAR_DELALLOC |
839 EXTENT_SET_WRITEBACK |
840 EXTENT_END_WRITEBACK);
841 return PTR_ERR(trans);
843 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
845 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
846 num_bytes = max(blocksize, num_bytes);
847 disk_num_bytes = num_bytes;
850 /* if this is a small write inside eof, kick off defrag */
851 if (num_bytes < 64 * 1024 &&
852 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
853 btrfs_add_inode_defrag(trans, inode);
856 /* lets try to make an inline extent */
857 ret = cow_file_range_inline(trans, root, inode,
858 start, end, 0, 0, NULL);
860 extent_clear_unlock_delalloc(inode,
861 &BTRFS_I(inode)->io_tree,
863 EXTENT_CLEAR_UNLOCK_PAGE |
864 EXTENT_CLEAR_UNLOCK |
865 EXTENT_CLEAR_DELALLOC |
867 EXTENT_SET_WRITEBACK |
868 EXTENT_END_WRITEBACK);
870 *nr_written = *nr_written +
871 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
874 } else if (ret < 0) {
875 btrfs_abort_transaction(trans, root, ret);
880 BUG_ON(disk_num_bytes >
881 btrfs_super_total_bytes(root->fs_info->super_copy));
883 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
884 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
886 while (disk_num_bytes > 0) {
889 cur_alloc_size = disk_num_bytes;
890 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
891 root->sectorsize, 0, alloc_hint,
894 btrfs_abort_transaction(trans, root, ret);
898 em = alloc_extent_map();
899 BUG_ON(!em); /* -ENOMEM */
901 em->orig_start = em->start;
902 ram_size = ins.offset;
903 em->len = ins.offset;
905 em->block_start = ins.objectid;
906 em->block_len = ins.offset;
907 em->bdev = root->fs_info->fs_devices->latest_bdev;
908 set_bit(EXTENT_FLAG_PINNED, &em->flags);
911 write_lock(&em_tree->lock);
912 ret = add_extent_mapping(em_tree, em);
913 write_unlock(&em_tree->lock);
914 if (ret != -EEXIST) {
918 btrfs_drop_extent_cache(inode, start,
919 start + ram_size - 1, 0);
922 cur_alloc_size = ins.offset;
923 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
924 ram_size, cur_alloc_size, 0);
925 BUG_ON(ret); /* -ENOMEM */
927 if (root->root_key.objectid ==
928 BTRFS_DATA_RELOC_TREE_OBJECTID) {
929 ret = btrfs_reloc_clone_csums(inode, start,
932 btrfs_abort_transaction(trans, root, ret);
937 if (disk_num_bytes < cur_alloc_size)
940 /* we're not doing compressed IO, don't unlock the first
941 * page (which the caller expects to stay locked), don't
942 * clear any dirty bits and don't set any writeback bits
944 * Do set the Private2 bit so we know this page was properly
945 * setup for writepage
947 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
948 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
951 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
952 start, start + ram_size - 1,
954 disk_num_bytes -= cur_alloc_size;
955 num_bytes -= cur_alloc_size;
956 alloc_hint = ins.objectid + ins.offset;
957 start += cur_alloc_size;
961 btrfs_end_transaction(trans, root);
965 extent_clear_unlock_delalloc(inode,
966 &BTRFS_I(inode)->io_tree,
967 start, end, locked_page,
968 EXTENT_CLEAR_UNLOCK_PAGE |
969 EXTENT_CLEAR_UNLOCK |
970 EXTENT_CLEAR_DELALLOC |
972 EXTENT_SET_WRITEBACK |
973 EXTENT_END_WRITEBACK);
979 * work queue call back to started compression on a file and pages
981 static noinline void async_cow_start(struct btrfs_work *work)
983 struct async_cow *async_cow;
985 async_cow = container_of(work, struct async_cow, work);
987 compress_file_range(async_cow->inode, async_cow->locked_page,
988 async_cow->start, async_cow->end, async_cow,
990 if (num_added == 0) {
991 btrfs_add_delayed_iput(async_cow->inode);
992 async_cow->inode = NULL;
997 * work queue call back to submit previously compressed pages
999 static noinline void async_cow_submit(struct btrfs_work *work)
1001 struct async_cow *async_cow;
1002 struct btrfs_root *root;
1003 unsigned long nr_pages;
1005 async_cow = container_of(work, struct async_cow, work);
1007 root = async_cow->root;
1008 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1011 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1013 waitqueue_active(&root->fs_info->async_submit_wait))
1014 wake_up(&root->fs_info->async_submit_wait);
1016 if (async_cow->inode)
1017 submit_compressed_extents(async_cow->inode, async_cow);
1020 static noinline void async_cow_free(struct btrfs_work *work)
1022 struct async_cow *async_cow;
1023 async_cow = container_of(work, struct async_cow, work);
1024 if (async_cow->inode)
1025 btrfs_add_delayed_iput(async_cow->inode);
1029 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1030 u64 start, u64 end, int *page_started,
1031 unsigned long *nr_written)
1033 struct async_cow *async_cow;
1034 struct btrfs_root *root = BTRFS_I(inode)->root;
1035 unsigned long nr_pages;
1037 int limit = 10 * 1024 * 1024;
1039 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1040 1, 0, NULL, GFP_NOFS);
1041 while (start < end) {
1042 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1043 BUG_ON(!async_cow); /* -ENOMEM */
1044 async_cow->inode = igrab(inode);
1045 async_cow->root = root;
1046 async_cow->locked_page = locked_page;
1047 async_cow->start = start;
1049 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1052 cur_end = min(end, start + 512 * 1024 - 1);
1054 async_cow->end = cur_end;
1055 INIT_LIST_HEAD(&async_cow->extents);
1057 async_cow->work.func = async_cow_start;
1058 async_cow->work.ordered_func = async_cow_submit;
1059 async_cow->work.ordered_free = async_cow_free;
1060 async_cow->work.flags = 0;
1062 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1064 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1066 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1069 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1070 wait_event(root->fs_info->async_submit_wait,
1071 (atomic_read(&root->fs_info->async_delalloc_pages) <
1075 while (atomic_read(&root->fs_info->async_submit_draining) &&
1076 atomic_read(&root->fs_info->async_delalloc_pages)) {
1077 wait_event(root->fs_info->async_submit_wait,
1078 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1082 *nr_written += nr_pages;
1083 start = cur_end + 1;
1089 static noinline int csum_exist_in_range(struct btrfs_root *root,
1090 u64 bytenr, u64 num_bytes)
1093 struct btrfs_ordered_sum *sums;
1096 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1097 bytenr + num_bytes - 1, &list, 0);
1098 if (ret == 0 && list_empty(&list))
1101 while (!list_empty(&list)) {
1102 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1103 list_del(&sums->list);
1110 * when nowcow writeback call back. This checks for snapshots or COW copies
1111 * of the extents that exist in the file, and COWs the file as required.
1113 * If no cow copies or snapshots exist, we write directly to the existing
1116 static noinline int run_delalloc_nocow(struct inode *inode,
1117 struct page *locked_page,
1118 u64 start, u64 end, int *page_started, int force,
1119 unsigned long *nr_written)
1121 struct btrfs_root *root = BTRFS_I(inode)->root;
1122 struct btrfs_trans_handle *trans;
1123 struct extent_buffer *leaf;
1124 struct btrfs_path *path;
1125 struct btrfs_file_extent_item *fi;
1126 struct btrfs_key found_key;
1139 u64 ino = btrfs_ino(inode);
1141 path = btrfs_alloc_path();
1143 extent_clear_unlock_delalloc(inode,
1144 &BTRFS_I(inode)->io_tree,
1145 start, end, locked_page,
1146 EXTENT_CLEAR_UNLOCK_PAGE |
1147 EXTENT_CLEAR_UNLOCK |
1148 EXTENT_CLEAR_DELALLOC |
1149 EXTENT_CLEAR_DIRTY |
1150 EXTENT_SET_WRITEBACK |
1151 EXTENT_END_WRITEBACK);
1155 nolock = btrfs_is_free_space_inode(inode);
1158 trans = btrfs_join_transaction_nolock(root);
1160 trans = btrfs_join_transaction(root);
1162 if (IS_ERR(trans)) {
1163 extent_clear_unlock_delalloc(inode,
1164 &BTRFS_I(inode)->io_tree,
1165 start, end, locked_page,
1166 EXTENT_CLEAR_UNLOCK_PAGE |
1167 EXTENT_CLEAR_UNLOCK |
1168 EXTENT_CLEAR_DELALLOC |
1169 EXTENT_CLEAR_DIRTY |
1170 EXTENT_SET_WRITEBACK |
1171 EXTENT_END_WRITEBACK);
1172 btrfs_free_path(path);
1173 return PTR_ERR(trans);
1176 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1178 cow_start = (u64)-1;
1181 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1184 btrfs_abort_transaction(trans, root, ret);
1187 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1188 leaf = path->nodes[0];
1189 btrfs_item_key_to_cpu(leaf, &found_key,
1190 path->slots[0] - 1);
1191 if (found_key.objectid == ino &&
1192 found_key.type == BTRFS_EXTENT_DATA_KEY)
1197 leaf = path->nodes[0];
1198 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1199 ret = btrfs_next_leaf(root, path);
1201 btrfs_abort_transaction(trans, root, ret);
1206 leaf = path->nodes[0];
1212 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1214 if (found_key.objectid > ino ||
1215 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1216 found_key.offset > end)
1219 if (found_key.offset > cur_offset) {
1220 extent_end = found_key.offset;
1225 fi = btrfs_item_ptr(leaf, path->slots[0],
1226 struct btrfs_file_extent_item);
1227 extent_type = btrfs_file_extent_type(leaf, fi);
1229 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1230 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1231 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1232 extent_offset = btrfs_file_extent_offset(leaf, fi);
1233 extent_end = found_key.offset +
1234 btrfs_file_extent_num_bytes(leaf, fi);
1235 if (extent_end <= start) {
1239 if (disk_bytenr == 0)
1241 if (btrfs_file_extent_compression(leaf, fi) ||
1242 btrfs_file_extent_encryption(leaf, fi) ||
1243 btrfs_file_extent_other_encoding(leaf, fi))
1245 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1247 if (btrfs_extent_readonly(root, disk_bytenr))
1249 if (btrfs_cross_ref_exist(trans, root, ino,
1251 extent_offset, disk_bytenr))
1253 disk_bytenr += extent_offset;
1254 disk_bytenr += cur_offset - found_key.offset;
1255 num_bytes = min(end + 1, extent_end) - cur_offset;
1257 * force cow if csum exists in the range.
1258 * this ensure that csum for a given extent are
1259 * either valid or do not exist.
1261 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1264 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1265 extent_end = found_key.offset +
1266 btrfs_file_extent_inline_len(leaf, fi);
1267 extent_end = ALIGN(extent_end, root->sectorsize);
1272 if (extent_end <= start) {
1277 if (cow_start == (u64)-1)
1278 cow_start = cur_offset;
1279 cur_offset = extent_end;
1280 if (cur_offset > end)
1286 btrfs_release_path(path);
1287 if (cow_start != (u64)-1) {
1288 ret = cow_file_range(inode, locked_page, cow_start,
1289 found_key.offset - 1, page_started,
1292 btrfs_abort_transaction(trans, root, ret);
1295 cow_start = (u64)-1;
1298 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1299 struct extent_map *em;
1300 struct extent_map_tree *em_tree;
1301 em_tree = &BTRFS_I(inode)->extent_tree;
1302 em = alloc_extent_map();
1303 BUG_ON(!em); /* -ENOMEM */
1304 em->start = cur_offset;
1305 em->orig_start = em->start;
1306 em->len = num_bytes;
1307 em->block_len = num_bytes;
1308 em->block_start = disk_bytenr;
1309 em->bdev = root->fs_info->fs_devices->latest_bdev;
1310 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1312 write_lock(&em_tree->lock);
1313 ret = add_extent_mapping(em_tree, em);
1314 write_unlock(&em_tree->lock);
1315 if (ret != -EEXIST) {
1316 free_extent_map(em);
1319 btrfs_drop_extent_cache(inode, em->start,
1320 em->start + em->len - 1, 0);
1322 type = BTRFS_ORDERED_PREALLOC;
1324 type = BTRFS_ORDERED_NOCOW;
1327 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1328 num_bytes, num_bytes, type);
1329 BUG_ON(ret); /* -ENOMEM */
1331 if (root->root_key.objectid ==
1332 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1333 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1336 btrfs_abort_transaction(trans, root, ret);
1341 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1342 cur_offset, cur_offset + num_bytes - 1,
1343 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1344 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1345 EXTENT_SET_PRIVATE2);
1346 cur_offset = extent_end;
1347 if (cur_offset > end)
1350 btrfs_release_path(path);
1352 if (cur_offset <= end && cow_start == (u64)-1) {
1353 cow_start = cur_offset;
1357 if (cow_start != (u64)-1) {
1358 ret = cow_file_range(inode, locked_page, cow_start, end,
1359 page_started, nr_written, 1);
1361 btrfs_abort_transaction(trans, root, ret);
1368 err = btrfs_end_transaction_nolock(trans, root);
1370 err = btrfs_end_transaction(trans, root);
1375 if (ret && cur_offset < end)
1376 extent_clear_unlock_delalloc(inode,
1377 &BTRFS_I(inode)->io_tree,
1378 cur_offset, end, locked_page,
1379 EXTENT_CLEAR_UNLOCK_PAGE |
1380 EXTENT_CLEAR_UNLOCK |
1381 EXTENT_CLEAR_DELALLOC |
1382 EXTENT_CLEAR_DIRTY |
1383 EXTENT_SET_WRITEBACK |
1384 EXTENT_END_WRITEBACK);
1386 btrfs_free_path(path);
1391 * extent_io.c call back to do delayed allocation processing
1393 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1394 u64 start, u64 end, int *page_started,
1395 unsigned long *nr_written)
1398 struct btrfs_root *root = BTRFS_I(inode)->root;
1400 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1401 ret = run_delalloc_nocow(inode, locked_page, start, end,
1402 page_started, 1, nr_written);
1403 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1404 ret = run_delalloc_nocow(inode, locked_page, start, end,
1405 page_started, 0, nr_written);
1406 } else if (!btrfs_test_opt(root, COMPRESS) &&
1407 !(BTRFS_I(inode)->force_compress) &&
1408 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1409 ret = cow_file_range(inode, locked_page, start, end,
1410 page_started, nr_written, 1);
1412 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1413 &BTRFS_I(inode)->runtime_flags);
1414 ret = cow_file_range_async(inode, locked_page, start, end,
1415 page_started, nr_written);
1420 static void btrfs_split_extent_hook(struct inode *inode,
1421 struct extent_state *orig, u64 split)
1423 /* not delalloc, ignore it */
1424 if (!(orig->state & EXTENT_DELALLOC))
1427 spin_lock(&BTRFS_I(inode)->lock);
1428 BTRFS_I(inode)->outstanding_extents++;
1429 spin_unlock(&BTRFS_I(inode)->lock);
1433 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1434 * extents so we can keep track of new extents that are just merged onto old
1435 * extents, such as when we are doing sequential writes, so we can properly
1436 * account for the metadata space we'll need.
1438 static void btrfs_merge_extent_hook(struct inode *inode,
1439 struct extent_state *new,
1440 struct extent_state *other)
1442 /* not delalloc, ignore it */
1443 if (!(other->state & EXTENT_DELALLOC))
1446 spin_lock(&BTRFS_I(inode)->lock);
1447 BTRFS_I(inode)->outstanding_extents--;
1448 spin_unlock(&BTRFS_I(inode)->lock);
1452 * extent_io.c set_bit_hook, used to track delayed allocation
1453 * bytes in this file, and to maintain the list of inodes that
1454 * have pending delalloc work to be done.
1456 static void btrfs_set_bit_hook(struct inode *inode,
1457 struct extent_state *state, int *bits)
1461 * set_bit and clear bit hooks normally require _irqsave/restore
1462 * but in this case, we are only testing for the DELALLOC
1463 * bit, which is only set or cleared with irqs on
1465 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1466 struct btrfs_root *root = BTRFS_I(inode)->root;
1467 u64 len = state->end + 1 - state->start;
1468 bool do_list = !btrfs_is_free_space_inode(inode);
1470 if (*bits & EXTENT_FIRST_DELALLOC) {
1471 *bits &= ~EXTENT_FIRST_DELALLOC;
1473 spin_lock(&BTRFS_I(inode)->lock);
1474 BTRFS_I(inode)->outstanding_extents++;
1475 spin_unlock(&BTRFS_I(inode)->lock);
1478 spin_lock(&root->fs_info->delalloc_lock);
1479 BTRFS_I(inode)->delalloc_bytes += len;
1480 root->fs_info->delalloc_bytes += len;
1481 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1482 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1483 &root->fs_info->delalloc_inodes);
1485 spin_unlock(&root->fs_info->delalloc_lock);
1490 * extent_io.c clear_bit_hook, see set_bit_hook for why
1492 static void btrfs_clear_bit_hook(struct inode *inode,
1493 struct extent_state *state, int *bits)
1496 * set_bit and clear bit hooks normally require _irqsave/restore
1497 * but in this case, we are only testing for the DELALLOC
1498 * bit, which is only set or cleared with irqs on
1500 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1501 struct btrfs_root *root = BTRFS_I(inode)->root;
1502 u64 len = state->end + 1 - state->start;
1503 bool do_list = !btrfs_is_free_space_inode(inode);
1505 if (*bits & EXTENT_FIRST_DELALLOC) {
1506 *bits &= ~EXTENT_FIRST_DELALLOC;
1507 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1508 spin_lock(&BTRFS_I(inode)->lock);
1509 BTRFS_I(inode)->outstanding_extents--;
1510 spin_unlock(&BTRFS_I(inode)->lock);
1513 if (*bits & EXTENT_DO_ACCOUNTING)
1514 btrfs_delalloc_release_metadata(inode, len);
1516 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1518 btrfs_free_reserved_data_space(inode, len);
1520 spin_lock(&root->fs_info->delalloc_lock);
1521 root->fs_info->delalloc_bytes -= len;
1522 BTRFS_I(inode)->delalloc_bytes -= len;
1524 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1525 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1526 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1528 spin_unlock(&root->fs_info->delalloc_lock);
1533 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1534 * we don't create bios that span stripes or chunks
1536 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1537 size_t size, struct bio *bio,
1538 unsigned long bio_flags)
1540 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1541 struct btrfs_mapping_tree *map_tree;
1542 u64 logical = (u64)bio->bi_sector << 9;
1547 if (bio_flags & EXTENT_BIO_COMPRESSED)
1550 length = bio->bi_size;
1551 map_tree = &root->fs_info->mapping_tree;
1552 map_length = length;
1553 ret = btrfs_map_block(map_tree, READ, logical,
1554 &map_length, NULL, 0);
1555 /* Will always return 0 or 1 with map_multi == NULL */
1557 if (map_length < length + size)
1563 * in order to insert checksums into the metadata in large chunks,
1564 * we wait until bio submission time. All the pages in the bio are
1565 * checksummed and sums are attached onto the ordered extent record.
1567 * At IO completion time the cums attached on the ordered extent record
1568 * are inserted into the btree
1570 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1571 struct bio *bio, int mirror_num,
1572 unsigned long bio_flags,
1575 struct btrfs_root *root = BTRFS_I(inode)->root;
1578 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1579 BUG_ON(ret); /* -ENOMEM */
1584 * in order to insert checksums into the metadata in large chunks,
1585 * we wait until bio submission time. All the pages in the bio are
1586 * checksummed and sums are attached onto the ordered extent record.
1588 * At IO completion time the cums attached on the ordered extent record
1589 * are inserted into the btree
1591 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1592 int mirror_num, unsigned long bio_flags,
1595 struct btrfs_root *root = BTRFS_I(inode)->root;
1596 return btrfs_map_bio(root, rw, bio, mirror_num, 1);
1600 * extent_io.c submission hook. This does the right thing for csum calculation
1601 * on write, or reading the csums from the tree before a read
1603 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1604 int mirror_num, unsigned long bio_flags,
1607 struct btrfs_root *root = BTRFS_I(inode)->root;
1612 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1614 if (btrfs_is_free_space_inode(inode))
1617 if (!(rw & REQ_WRITE)) {
1618 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1622 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1623 return btrfs_submit_compressed_read(inode, bio,
1624 mirror_num, bio_flags);
1625 } else if (!skip_sum) {
1626 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1631 } else if (!skip_sum) {
1632 /* csum items have already been cloned */
1633 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1635 /* we're doing a write, do the async checksumming */
1636 return btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1637 inode, rw, bio, mirror_num,
1638 bio_flags, bio_offset,
1639 __btrfs_submit_bio_start,
1640 __btrfs_submit_bio_done);
1644 return btrfs_map_bio(root, rw, bio, mirror_num, 0);
1648 * given a list of ordered sums record them in the inode. This happens
1649 * at IO completion time based on sums calculated at bio submission time.
1651 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1652 struct inode *inode, u64 file_offset,
1653 struct list_head *list)
1655 struct btrfs_ordered_sum *sum;
1657 list_for_each_entry(sum, list, list) {
1658 btrfs_csum_file_blocks(trans,
1659 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1664 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1665 struct extent_state **cached_state)
1667 if ((end & (PAGE_CACHE_SIZE - 1)) == 0)
1669 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1670 cached_state, GFP_NOFS);
1673 /* see btrfs_writepage_start_hook for details on why this is required */
1674 struct btrfs_writepage_fixup {
1676 struct btrfs_work work;
1679 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1681 struct btrfs_writepage_fixup *fixup;
1682 struct btrfs_ordered_extent *ordered;
1683 struct extent_state *cached_state = NULL;
1685 struct inode *inode;
1690 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1694 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1695 ClearPageChecked(page);
1699 inode = page->mapping->host;
1700 page_start = page_offset(page);
1701 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1703 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1706 /* already ordered? We're done */
1707 if (PagePrivate2(page))
1710 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1712 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1713 page_end, &cached_state, GFP_NOFS);
1715 btrfs_start_ordered_extent(inode, ordered, 1);
1716 btrfs_put_ordered_extent(ordered);
1720 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1722 mapping_set_error(page->mapping, ret);
1723 end_extent_writepage(page, ret, page_start, page_end);
1724 ClearPageChecked(page);
1728 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1729 ClearPageChecked(page);
1730 set_page_dirty(page);
1732 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1733 &cached_state, GFP_NOFS);
1736 page_cache_release(page);
1741 * There are a few paths in the higher layers of the kernel that directly
1742 * set the page dirty bit without asking the filesystem if it is a
1743 * good idea. This causes problems because we want to make sure COW
1744 * properly happens and the data=ordered rules are followed.
1746 * In our case any range that doesn't have the ORDERED bit set
1747 * hasn't been properly setup for IO. We kick off an async process
1748 * to fix it up. The async helper will wait for ordered extents, set
1749 * the delalloc bit and make it safe to write the page.
1751 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1753 struct inode *inode = page->mapping->host;
1754 struct btrfs_writepage_fixup *fixup;
1755 struct btrfs_root *root = BTRFS_I(inode)->root;
1757 /* this page is properly in the ordered list */
1758 if (TestClearPagePrivate2(page))
1761 if (PageChecked(page))
1764 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1768 SetPageChecked(page);
1769 page_cache_get(page);
1770 fixup->work.func = btrfs_writepage_fixup_worker;
1772 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1776 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1777 struct inode *inode, u64 file_pos,
1778 u64 disk_bytenr, u64 disk_num_bytes,
1779 u64 num_bytes, u64 ram_bytes,
1780 u8 compression, u8 encryption,
1781 u16 other_encoding, int extent_type)
1783 struct btrfs_root *root = BTRFS_I(inode)->root;
1784 struct btrfs_file_extent_item *fi;
1785 struct btrfs_path *path;
1786 struct extent_buffer *leaf;
1787 struct btrfs_key ins;
1791 path = btrfs_alloc_path();
1795 path->leave_spinning = 1;
1798 * we may be replacing one extent in the tree with another.
1799 * The new extent is pinned in the extent map, and we don't want
1800 * to drop it from the cache until it is completely in the btree.
1802 * So, tell btrfs_drop_extents to leave this extent in the cache.
1803 * the caller is expected to unpin it and allow it to be merged
1806 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1807 file_pos + num_bytes,
1812 ins.objectid = btrfs_ino(inode);
1813 ins.offset = file_pos;
1814 ins.type = BTRFS_EXTENT_DATA_KEY;
1815 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1818 leaf = path->nodes[0];
1819 fi = btrfs_item_ptr(leaf, path->slots[0],
1820 struct btrfs_file_extent_item);
1821 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1822 btrfs_set_file_extent_type(leaf, fi, extent_type);
1823 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1824 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1825 btrfs_set_file_extent_offset(leaf, fi, 0);
1826 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1827 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1828 btrfs_set_file_extent_compression(leaf, fi, compression);
1829 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1830 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1832 btrfs_unlock_up_safe(path, 1);
1833 btrfs_set_lock_blocking(leaf);
1835 btrfs_mark_buffer_dirty(leaf);
1837 inode_add_bytes(inode, num_bytes);
1839 ins.objectid = disk_bytenr;
1840 ins.offset = disk_num_bytes;
1841 ins.type = BTRFS_EXTENT_ITEM_KEY;
1842 ret = btrfs_alloc_reserved_file_extent(trans, root,
1843 root->root_key.objectid,
1844 btrfs_ino(inode), file_pos, &ins);
1846 btrfs_free_path(path);
1852 * helper function for btrfs_finish_ordered_io, this
1853 * just reads in some of the csum leaves to prime them into ram
1854 * before we start the transaction. It limits the amount of btree
1855 * reads required while inside the transaction.
1857 /* as ordered data IO finishes, this gets called so we can finish
1858 * an ordered extent if the range of bytes in the file it covers are
1861 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1863 struct inode *inode = ordered_extent->inode;
1864 struct btrfs_root *root = BTRFS_I(inode)->root;
1865 struct btrfs_trans_handle *trans = NULL;
1866 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1867 struct extent_state *cached_state = NULL;
1868 int compress_type = 0;
1872 nolock = btrfs_is_free_space_inode(inode);
1874 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1879 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1880 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1881 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1884 trans = btrfs_join_transaction_nolock(root);
1886 trans = btrfs_join_transaction(root);
1887 if (IS_ERR(trans)) {
1888 ret = PTR_ERR(trans);
1892 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1893 ret = btrfs_update_inode_fallback(trans, root, inode);
1894 if (ret) /* -ENOMEM or corruption */
1895 btrfs_abort_transaction(trans, root, ret);
1900 lock_extent_bits(io_tree, ordered_extent->file_offset,
1901 ordered_extent->file_offset + ordered_extent->len - 1,
1905 trans = btrfs_join_transaction_nolock(root);
1907 trans = btrfs_join_transaction(root);
1908 if (IS_ERR(trans)) {
1909 ret = PTR_ERR(trans);
1913 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1915 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1916 compress_type = ordered_extent->compress_type;
1917 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1918 BUG_ON(compress_type);
1919 ret = btrfs_mark_extent_written(trans, inode,
1920 ordered_extent->file_offset,
1921 ordered_extent->file_offset +
1922 ordered_extent->len);
1924 BUG_ON(root == root->fs_info->tree_root);
1925 ret = insert_reserved_file_extent(trans, inode,
1926 ordered_extent->file_offset,
1927 ordered_extent->start,
1928 ordered_extent->disk_len,
1929 ordered_extent->len,
1930 ordered_extent->len,
1931 compress_type, 0, 0,
1932 BTRFS_FILE_EXTENT_REG);
1934 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1935 ordered_extent->file_offset, ordered_extent->len,
1938 btrfs_abort_transaction(trans, root, ret);
1942 add_pending_csums(trans, inode, ordered_extent->file_offset,
1943 &ordered_extent->list);
1945 ret = btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1946 if (!ret || !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1947 ret = btrfs_update_inode_fallback(trans, root, inode);
1948 if (ret) { /* -ENOMEM or corruption */
1949 btrfs_abort_transaction(trans, root, ret);
1953 btrfs_set_inode_last_trans(trans, inode);
1957 unlock_extent_cached(io_tree, ordered_extent->file_offset,
1958 ordered_extent->file_offset +
1959 ordered_extent->len - 1, &cached_state, GFP_NOFS);
1961 if (root != root->fs_info->tree_root)
1962 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
1965 btrfs_end_transaction_nolock(trans, root);
1967 btrfs_end_transaction(trans, root);
1971 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
1972 ordered_extent->file_offset +
1973 ordered_extent->len - 1, NULL, GFP_NOFS);
1976 * This needs to be dont to make sure anybody waiting knows we are done
1977 * upating everything for this ordered extent.
1979 btrfs_remove_ordered_extent(inode, ordered_extent);
1982 btrfs_put_ordered_extent(ordered_extent);
1983 /* once for the tree */
1984 btrfs_put_ordered_extent(ordered_extent);
1989 static void finish_ordered_fn(struct btrfs_work *work)
1991 struct btrfs_ordered_extent *ordered_extent;
1992 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
1993 btrfs_finish_ordered_io(ordered_extent);
1996 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
1997 struct extent_state *state, int uptodate)
1999 struct inode *inode = page->mapping->host;
2000 struct btrfs_root *root = BTRFS_I(inode)->root;
2001 struct btrfs_ordered_extent *ordered_extent = NULL;
2002 struct btrfs_workers *workers;
2004 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2006 ClearPagePrivate2(page);
2007 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2008 end - start + 1, uptodate))
2011 ordered_extent->work.func = finish_ordered_fn;
2012 ordered_extent->work.flags = 0;
2014 if (btrfs_is_free_space_inode(inode))
2015 workers = &root->fs_info->endio_freespace_worker;
2017 workers = &root->fs_info->endio_write_workers;
2018 btrfs_queue_worker(workers, &ordered_extent->work);
2024 * when reads are done, we need to check csums to verify the data is correct
2025 * if there's a match, we allow the bio to finish. If not, the code in
2026 * extent_io.c will try to find good copies for us.
2028 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2029 struct extent_state *state, int mirror)
2031 size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT);
2032 struct inode *inode = page->mapping->host;
2033 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2035 u64 private = ~(u32)0;
2037 struct btrfs_root *root = BTRFS_I(inode)->root;
2040 if (PageChecked(page)) {
2041 ClearPageChecked(page);
2045 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2048 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2049 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2050 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2055 if (state && state->start == start) {
2056 private = state->private;
2059 ret = get_state_private(io_tree, start, &private);
2061 kaddr = kmap_atomic(page);
2065 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2066 btrfs_csum_final(csum, (char *)&csum);
2067 if (csum != private)
2070 kunmap_atomic(kaddr);
2075 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2077 (unsigned long long)btrfs_ino(page->mapping->host),
2078 (unsigned long long)start, csum,
2079 (unsigned long long)private);
2080 memset(kaddr + offset, 1, end - start + 1);
2081 flush_dcache_page(page);
2082 kunmap_atomic(kaddr);
2088 struct delayed_iput {
2089 struct list_head list;
2090 struct inode *inode;
2093 /* JDM: If this is fs-wide, why can't we add a pointer to
2094 * btrfs_inode instead and avoid the allocation? */
2095 void btrfs_add_delayed_iput(struct inode *inode)
2097 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2098 struct delayed_iput *delayed;
2100 if (atomic_add_unless(&inode->i_count, -1, 1))
2103 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2104 delayed->inode = inode;
2106 spin_lock(&fs_info->delayed_iput_lock);
2107 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2108 spin_unlock(&fs_info->delayed_iput_lock);
2111 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2114 struct btrfs_fs_info *fs_info = root->fs_info;
2115 struct delayed_iput *delayed;
2118 spin_lock(&fs_info->delayed_iput_lock);
2119 empty = list_empty(&fs_info->delayed_iputs);
2120 spin_unlock(&fs_info->delayed_iput_lock);
2124 down_read(&root->fs_info->cleanup_work_sem);
2125 spin_lock(&fs_info->delayed_iput_lock);
2126 list_splice_init(&fs_info->delayed_iputs, &list);
2127 spin_unlock(&fs_info->delayed_iput_lock);
2129 while (!list_empty(&list)) {
2130 delayed = list_entry(list.next, struct delayed_iput, list);
2131 list_del(&delayed->list);
2132 iput(delayed->inode);
2135 up_read(&root->fs_info->cleanup_work_sem);
2138 enum btrfs_orphan_cleanup_state {
2139 ORPHAN_CLEANUP_STARTED = 1,
2140 ORPHAN_CLEANUP_DONE = 2,
2144 * This is called in transaction commit time. If there are no orphan
2145 * files in the subvolume, it removes orphan item and frees block_rsv
2148 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2149 struct btrfs_root *root)
2151 struct btrfs_block_rsv *block_rsv;
2154 if (atomic_read(&root->orphan_inodes) ||
2155 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2158 spin_lock(&root->orphan_lock);
2159 if (atomic_read(&root->orphan_inodes)) {
2160 spin_unlock(&root->orphan_lock);
2164 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2165 spin_unlock(&root->orphan_lock);
2169 block_rsv = root->orphan_block_rsv;
2170 root->orphan_block_rsv = NULL;
2171 spin_unlock(&root->orphan_lock);
2173 if (root->orphan_item_inserted &&
2174 btrfs_root_refs(&root->root_item) > 0) {
2175 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2176 root->root_key.objectid);
2178 root->orphan_item_inserted = 0;
2182 WARN_ON(block_rsv->size > 0);
2183 btrfs_free_block_rsv(root, block_rsv);
2188 * This creates an orphan entry for the given inode in case something goes
2189 * wrong in the middle of an unlink/truncate.
2191 * NOTE: caller of this function should reserve 5 units of metadata for
2194 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2196 struct btrfs_root *root = BTRFS_I(inode)->root;
2197 struct btrfs_block_rsv *block_rsv = NULL;
2202 if (!root->orphan_block_rsv) {
2203 block_rsv = btrfs_alloc_block_rsv(root);
2208 spin_lock(&root->orphan_lock);
2209 if (!root->orphan_block_rsv) {
2210 root->orphan_block_rsv = block_rsv;
2211 } else if (block_rsv) {
2212 btrfs_free_block_rsv(root, block_rsv);
2216 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2217 &BTRFS_I(inode)->runtime_flags)) {
2220 * For proper ENOSPC handling, we should do orphan
2221 * cleanup when mounting. But this introduces backward
2222 * compatibility issue.
2224 if (!xchg(&root->orphan_item_inserted, 1))
2230 atomic_dec(&root->orphan_inodes);
2233 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2234 &BTRFS_I(inode)->runtime_flags))
2236 spin_unlock(&root->orphan_lock);
2238 /* grab metadata reservation from transaction handle */
2240 ret = btrfs_orphan_reserve_metadata(trans, inode);
2241 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2244 /* insert an orphan item to track this unlinked/truncated file */
2246 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2247 if (ret && ret != -EEXIST) {
2248 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2249 &BTRFS_I(inode)->runtime_flags);
2250 btrfs_abort_transaction(trans, root, ret);
2256 /* insert an orphan item to track subvolume contains orphan files */
2258 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2259 root->root_key.objectid);
2260 if (ret && ret != -EEXIST) {
2261 btrfs_abort_transaction(trans, root, ret);
2269 * We have done the truncate/delete so we can go ahead and remove the orphan
2270 * item for this particular inode.
2272 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2274 struct btrfs_root *root = BTRFS_I(inode)->root;
2275 int delete_item = 0;
2276 int release_rsv = 0;
2279 spin_lock(&root->orphan_lock);
2280 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2281 &BTRFS_I(inode)->runtime_flags))
2284 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2285 &BTRFS_I(inode)->runtime_flags))
2287 spin_unlock(&root->orphan_lock);
2289 if (trans && delete_item) {
2290 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2291 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2295 btrfs_orphan_release_metadata(inode);
2296 atomic_dec(&root->orphan_inodes);
2303 * this cleans up any orphans that may be left on the list from the last use
2306 int btrfs_orphan_cleanup(struct btrfs_root *root)
2308 struct btrfs_path *path;
2309 struct extent_buffer *leaf;
2310 struct btrfs_key key, found_key;
2311 struct btrfs_trans_handle *trans;
2312 struct inode *inode;
2313 u64 last_objectid = 0;
2314 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2316 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2319 path = btrfs_alloc_path();
2326 key.objectid = BTRFS_ORPHAN_OBJECTID;
2327 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2328 key.offset = (u64)-1;
2331 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2336 * if ret == 0 means we found what we were searching for, which
2337 * is weird, but possible, so only screw with path if we didn't
2338 * find the key and see if we have stuff that matches
2342 if (path->slots[0] == 0)
2347 /* pull out the item */
2348 leaf = path->nodes[0];
2349 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2351 /* make sure the item matches what we want */
2352 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2354 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2357 /* release the path since we're done with it */
2358 btrfs_release_path(path);
2361 * this is where we are basically btrfs_lookup, without the
2362 * crossing root thing. we store the inode number in the
2363 * offset of the orphan item.
2366 if (found_key.offset == last_objectid) {
2367 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2368 "stopping orphan cleanup\n");
2373 last_objectid = found_key.offset;
2375 found_key.objectid = found_key.offset;
2376 found_key.type = BTRFS_INODE_ITEM_KEY;
2377 found_key.offset = 0;
2378 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2379 ret = PTR_RET(inode);
2380 if (ret && ret != -ESTALE)
2383 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2384 struct btrfs_root *dead_root;
2385 struct btrfs_fs_info *fs_info = root->fs_info;
2386 int is_dead_root = 0;
2389 * this is an orphan in the tree root. Currently these
2390 * could come from 2 sources:
2391 * a) a snapshot deletion in progress
2392 * b) a free space cache inode
2393 * We need to distinguish those two, as the snapshot
2394 * orphan must not get deleted.
2395 * find_dead_roots already ran before us, so if this
2396 * is a snapshot deletion, we should find the root
2397 * in the dead_roots list
2399 spin_lock(&fs_info->trans_lock);
2400 list_for_each_entry(dead_root, &fs_info->dead_roots,
2402 if (dead_root->root_key.objectid ==
2403 found_key.objectid) {
2408 spin_unlock(&fs_info->trans_lock);
2410 /* prevent this orphan from being found again */
2411 key.offset = found_key.objectid - 1;
2416 * Inode is already gone but the orphan item is still there,
2417 * kill the orphan item.
2419 if (ret == -ESTALE) {
2420 trans = btrfs_start_transaction(root, 1);
2421 if (IS_ERR(trans)) {
2422 ret = PTR_ERR(trans);
2425 printk(KERN_ERR "auto deleting %Lu\n",
2426 found_key.objectid);
2427 ret = btrfs_del_orphan_item(trans, root,
2428 found_key.objectid);
2429 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2430 btrfs_end_transaction(trans, root);
2435 * add this inode to the orphan list so btrfs_orphan_del does
2436 * the proper thing when we hit it
2438 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2439 &BTRFS_I(inode)->runtime_flags);
2441 /* if we have links, this was a truncate, lets do that */
2442 if (inode->i_nlink) {
2443 if (!S_ISREG(inode->i_mode)) {
2449 ret = btrfs_truncate(inode);
2454 /* this will do delete_inode and everything for us */
2459 /* release the path since we're done with it */
2460 btrfs_release_path(path);
2462 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2464 if (root->orphan_block_rsv)
2465 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2468 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2469 trans = btrfs_join_transaction(root);
2471 btrfs_end_transaction(trans, root);
2475 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2477 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2481 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2482 btrfs_free_path(path);
2487 * very simple check to peek ahead in the leaf looking for xattrs. If we
2488 * don't find any xattrs, we know there can't be any acls.
2490 * slot is the slot the inode is in, objectid is the objectid of the inode
2492 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2493 int slot, u64 objectid)
2495 u32 nritems = btrfs_header_nritems(leaf);
2496 struct btrfs_key found_key;
2500 while (slot < nritems) {
2501 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2503 /* we found a different objectid, there must not be acls */
2504 if (found_key.objectid != objectid)
2507 /* we found an xattr, assume we've got an acl */
2508 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2512 * we found a key greater than an xattr key, there can't
2513 * be any acls later on
2515 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2522 * it goes inode, inode backrefs, xattrs, extents,
2523 * so if there are a ton of hard links to an inode there can
2524 * be a lot of backrefs. Don't waste time searching too hard,
2525 * this is just an optimization
2530 /* we hit the end of the leaf before we found an xattr or
2531 * something larger than an xattr. We have to assume the inode
2538 * read an inode from the btree into the in-memory inode
2540 static void btrfs_read_locked_inode(struct inode *inode)
2542 struct btrfs_path *path;
2543 struct extent_buffer *leaf;
2544 struct btrfs_inode_item *inode_item;
2545 struct btrfs_timespec *tspec;
2546 struct btrfs_root *root = BTRFS_I(inode)->root;
2547 struct btrfs_key location;
2551 bool filled = false;
2553 ret = btrfs_fill_inode(inode, &rdev);
2557 path = btrfs_alloc_path();
2561 path->leave_spinning = 1;
2562 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2564 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2568 leaf = path->nodes[0];
2573 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2574 struct btrfs_inode_item);
2575 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2576 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2577 inode->i_uid = btrfs_inode_uid(leaf, inode_item);
2578 inode->i_gid = btrfs_inode_gid(leaf, inode_item);
2579 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2581 tspec = btrfs_inode_atime(inode_item);
2582 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2583 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2585 tspec = btrfs_inode_mtime(inode_item);
2586 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2587 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2589 tspec = btrfs_inode_ctime(inode_item);
2590 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2591 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2593 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2594 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2595 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
2598 * If we were modified in the current generation and evicted from memory
2599 * and then re-read we need to do a full sync since we don't have any
2600 * idea about which extents were modified before we were evicted from
2603 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
2604 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2605 &BTRFS_I(inode)->runtime_flags);
2607 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2608 inode->i_generation = BTRFS_I(inode)->generation;
2610 rdev = btrfs_inode_rdev(leaf, inode_item);
2612 BTRFS_I(inode)->index_cnt = (u64)-1;
2613 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2616 * try to precache a NULL acl entry for files that don't have
2617 * any xattrs or acls
2619 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2622 cache_no_acl(inode);
2624 btrfs_free_path(path);
2626 switch (inode->i_mode & S_IFMT) {
2628 inode->i_mapping->a_ops = &btrfs_aops;
2629 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2630 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2631 inode->i_fop = &btrfs_file_operations;
2632 inode->i_op = &btrfs_file_inode_operations;
2635 inode->i_fop = &btrfs_dir_file_operations;
2636 if (root == root->fs_info->tree_root)
2637 inode->i_op = &btrfs_dir_ro_inode_operations;
2639 inode->i_op = &btrfs_dir_inode_operations;
2642 inode->i_op = &btrfs_symlink_inode_operations;
2643 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2644 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2647 inode->i_op = &btrfs_special_inode_operations;
2648 init_special_inode(inode, inode->i_mode, rdev);
2652 btrfs_update_iflags(inode);
2656 btrfs_free_path(path);
2657 make_bad_inode(inode);
2661 * given a leaf and an inode, copy the inode fields into the leaf
2663 static void fill_inode_item(struct btrfs_trans_handle *trans,
2664 struct extent_buffer *leaf,
2665 struct btrfs_inode_item *item,
2666 struct inode *inode)
2668 btrfs_set_inode_uid(leaf, item, inode->i_uid);
2669 btrfs_set_inode_gid(leaf, item, inode->i_gid);
2670 btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
2671 btrfs_set_inode_mode(leaf, item, inode->i_mode);
2672 btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
2674 btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item),
2675 inode->i_atime.tv_sec);
2676 btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item),
2677 inode->i_atime.tv_nsec);
2679 btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item),
2680 inode->i_mtime.tv_sec);
2681 btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item),
2682 inode->i_mtime.tv_nsec);
2684 btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item),
2685 inode->i_ctime.tv_sec);
2686 btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item),
2687 inode->i_ctime.tv_nsec);
2689 btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
2690 btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
2691 btrfs_set_inode_sequence(leaf, item, inode->i_version);
2692 btrfs_set_inode_transid(leaf, item, trans->transid);
2693 btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
2694 btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags);
2695 btrfs_set_inode_block_group(leaf, item, 0);
2699 * copy everything in the in-memory inode into the btree.
2701 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2702 struct btrfs_root *root, struct inode *inode)
2704 struct btrfs_inode_item *inode_item;
2705 struct btrfs_path *path;
2706 struct extent_buffer *leaf;
2709 path = btrfs_alloc_path();
2713 path->leave_spinning = 1;
2714 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2722 btrfs_unlock_up_safe(path, 1);
2723 leaf = path->nodes[0];
2724 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2725 struct btrfs_inode_item);
2727 fill_inode_item(trans, leaf, inode_item, inode);
2728 btrfs_mark_buffer_dirty(leaf);
2729 btrfs_set_inode_last_trans(trans, inode);
2732 btrfs_free_path(path);
2737 * copy everything in the in-memory inode into the btree.
2739 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2740 struct btrfs_root *root, struct inode *inode)
2745 * If the inode is a free space inode, we can deadlock during commit
2746 * if we put it into the delayed code.
2748 * The data relocation inode should also be directly updated
2751 if (!btrfs_is_free_space_inode(inode)
2752 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2753 btrfs_update_root_times(trans, root);
2755 ret = btrfs_delayed_update_inode(trans, root, inode);
2757 btrfs_set_inode_last_trans(trans, inode);
2761 return btrfs_update_inode_item(trans, root, inode);
2764 static noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2765 struct btrfs_root *root, struct inode *inode)
2769 ret = btrfs_update_inode(trans, root, inode);
2771 return btrfs_update_inode_item(trans, root, inode);
2776 * unlink helper that gets used here in inode.c and in the tree logging
2777 * recovery code. It remove a link in a directory with a given name, and
2778 * also drops the back refs in the inode to the directory
2780 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2781 struct btrfs_root *root,
2782 struct inode *dir, struct inode *inode,
2783 const char *name, int name_len)
2785 struct btrfs_path *path;
2787 struct extent_buffer *leaf;
2788 struct btrfs_dir_item *di;
2789 struct btrfs_key key;
2791 u64 ino = btrfs_ino(inode);
2792 u64 dir_ino = btrfs_ino(dir);
2794 path = btrfs_alloc_path();
2800 path->leave_spinning = 1;
2801 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2802 name, name_len, -1);
2811 leaf = path->nodes[0];
2812 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2813 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2816 btrfs_release_path(path);
2818 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2821 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2822 "inode %llu parent %llu\n", name_len, name,
2823 (unsigned long long)ino, (unsigned long long)dir_ino);
2824 btrfs_abort_transaction(trans, root, ret);
2828 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2830 btrfs_abort_transaction(trans, root, ret);
2834 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2836 if (ret != 0 && ret != -ENOENT) {
2837 btrfs_abort_transaction(trans, root, ret);
2841 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2846 btrfs_free_path(path);
2850 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2851 inode_inc_iversion(inode);
2852 inode_inc_iversion(dir);
2853 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2854 ret = btrfs_update_inode(trans, root, dir);
2859 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2860 struct btrfs_root *root,
2861 struct inode *dir, struct inode *inode,
2862 const char *name, int name_len)
2865 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2867 btrfs_drop_nlink(inode);
2868 ret = btrfs_update_inode(trans, root, inode);
2874 /* helper to check if there is any shared block in the path */
2875 static int check_path_shared(struct btrfs_root *root,
2876 struct btrfs_path *path)
2878 struct extent_buffer *eb;
2882 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2885 if (!path->nodes[level])
2887 eb = path->nodes[level];
2888 if (!btrfs_block_can_be_shared(root, eb))
2890 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2899 * helper to start transaction for unlink and rmdir.
2901 * unlink and rmdir are special in btrfs, they do not always free space.
2902 * so in enospc case, we should make sure they will free space before
2903 * allowing them to use the global metadata reservation.
2905 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2906 struct dentry *dentry)
2908 struct btrfs_trans_handle *trans;
2909 struct btrfs_root *root = BTRFS_I(dir)->root;
2910 struct btrfs_path *path;
2911 struct btrfs_inode_ref *ref;
2912 struct btrfs_dir_item *di;
2913 struct inode *inode = dentry->d_inode;
2918 u64 ino = btrfs_ino(inode);
2919 u64 dir_ino = btrfs_ino(dir);
2922 * 1 for the possible orphan item
2923 * 1 for the dir item
2924 * 1 for the dir index
2925 * 1 for the inode ref
2926 * 1 for the inode ref in the tree log
2927 * 2 for the dir entries in the log
2930 trans = btrfs_start_transaction(root, 8);
2931 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2934 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2935 return ERR_PTR(-ENOSPC);
2937 /* check if there is someone else holds reference */
2938 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2939 return ERR_PTR(-ENOSPC);
2941 if (atomic_read(&inode->i_count) > 2)
2942 return ERR_PTR(-ENOSPC);
2944 if (xchg(&root->fs_info->enospc_unlink, 1))
2945 return ERR_PTR(-ENOSPC);
2947 path = btrfs_alloc_path();
2949 root->fs_info->enospc_unlink = 0;
2950 return ERR_PTR(-ENOMEM);
2953 /* 1 for the orphan item */
2954 trans = btrfs_start_transaction(root, 1);
2955 if (IS_ERR(trans)) {
2956 btrfs_free_path(path);
2957 root->fs_info->enospc_unlink = 0;
2961 path->skip_locking = 1;
2962 path->search_commit_root = 1;
2964 ret = btrfs_lookup_inode(trans, root, path,
2965 &BTRFS_I(dir)->location, 0);
2971 if (check_path_shared(root, path))
2976 btrfs_release_path(path);
2978 ret = btrfs_lookup_inode(trans, root, path,
2979 &BTRFS_I(inode)->location, 0);
2985 if (check_path_shared(root, path))
2990 btrfs_release_path(path);
2992 if (ret == 0 && S_ISREG(inode->i_mode)) {
2993 ret = btrfs_lookup_file_extent(trans, root, path,
2999 BUG_ON(ret == 0); /* Corruption */
3000 if (check_path_shared(root, path))
3002 btrfs_release_path(path);
3010 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3011 dentry->d_name.name, dentry->d_name.len, 0);
3017 if (check_path_shared(root, path))
3023 btrfs_release_path(path);
3025 ref = btrfs_lookup_inode_ref(trans, root, path,
3026 dentry->d_name.name, dentry->d_name.len,
3032 BUG_ON(!ref); /* Logic error */
3033 if (check_path_shared(root, path))
3035 index = btrfs_inode_ref_index(path->nodes[0], ref);
3036 btrfs_release_path(path);
3039 * This is a commit root search, if we can lookup inode item and other
3040 * relative items in the commit root, it means the transaction of
3041 * dir/file creation has been committed, and the dir index item that we
3042 * delay to insert has also been inserted into the commit root. So
3043 * we needn't worry about the delayed insertion of the dir index item
3046 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3047 dentry->d_name.name, dentry->d_name.len, 0);
3052 BUG_ON(ret == -ENOENT);
3053 if (check_path_shared(root, path))
3058 btrfs_free_path(path);
3059 /* Migrate the orphan reservation over */
3061 err = btrfs_block_rsv_migrate(trans->block_rsv,
3062 &root->fs_info->global_block_rsv,
3063 trans->bytes_reserved);
3066 btrfs_end_transaction(trans, root);
3067 root->fs_info->enospc_unlink = 0;
3068 return ERR_PTR(err);
3071 trans->block_rsv = &root->fs_info->global_block_rsv;
3075 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3076 struct btrfs_root *root)
3078 if (trans->block_rsv == &root->fs_info->global_block_rsv) {
3079 btrfs_block_rsv_release(root, trans->block_rsv,
3080 trans->bytes_reserved);
3081 trans->block_rsv = &root->fs_info->trans_block_rsv;
3082 BUG_ON(!root->fs_info->enospc_unlink);
3083 root->fs_info->enospc_unlink = 0;
3085 btrfs_end_transaction(trans, root);
3088 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3090 struct btrfs_root *root = BTRFS_I(dir)->root;
3091 struct btrfs_trans_handle *trans;
3092 struct inode *inode = dentry->d_inode;
3094 unsigned long nr = 0;
3096 trans = __unlink_start_trans(dir, dentry);
3098 return PTR_ERR(trans);
3100 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3102 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3103 dentry->d_name.name, dentry->d_name.len);
3107 if (inode->i_nlink == 0) {
3108 ret = btrfs_orphan_add(trans, inode);
3114 nr = trans->blocks_used;
3115 __unlink_end_trans(trans, root);
3116 btrfs_btree_balance_dirty(root, nr);
3120 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3121 struct btrfs_root *root,
3122 struct inode *dir, u64 objectid,
3123 const char *name, int name_len)
3125 struct btrfs_path *path;
3126 struct extent_buffer *leaf;
3127 struct btrfs_dir_item *di;
3128 struct btrfs_key key;
3131 u64 dir_ino = btrfs_ino(dir);
3133 path = btrfs_alloc_path();
3137 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3138 name, name_len, -1);
3139 if (IS_ERR_OR_NULL(di)) {
3147 leaf = path->nodes[0];
3148 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3149 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3150 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3152 btrfs_abort_transaction(trans, root, ret);
3155 btrfs_release_path(path);
3157 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3158 objectid, root->root_key.objectid,
3159 dir_ino, &index, name, name_len);
3161 if (ret != -ENOENT) {
3162 btrfs_abort_transaction(trans, root, ret);
3165 di = btrfs_search_dir_index_item(root, path, dir_ino,
3167 if (IS_ERR_OR_NULL(di)) {
3172 btrfs_abort_transaction(trans, root, ret);
3176 leaf = path->nodes[0];
3177 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3178 btrfs_release_path(path);
3181 btrfs_release_path(path);
3183 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3185 btrfs_abort_transaction(trans, root, ret);
3189 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3190 inode_inc_iversion(dir);
3191 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3192 ret = btrfs_update_inode_fallback(trans, root, dir);
3194 btrfs_abort_transaction(trans, root, ret);
3196 btrfs_free_path(path);
3200 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3202 struct inode *inode = dentry->d_inode;
3204 struct btrfs_root *root = BTRFS_I(dir)->root;
3205 struct btrfs_trans_handle *trans;
3206 unsigned long nr = 0;
3208 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE ||
3209 btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3212 trans = __unlink_start_trans(dir, dentry);
3214 return PTR_ERR(trans);
3216 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3217 err = btrfs_unlink_subvol(trans, root, dir,
3218 BTRFS_I(inode)->location.objectid,
3219 dentry->d_name.name,
3220 dentry->d_name.len);
3224 err = btrfs_orphan_add(trans, inode);
3228 /* now the directory is empty */
3229 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3230 dentry->d_name.name, dentry->d_name.len);
3232 btrfs_i_size_write(inode, 0);
3234 nr = trans->blocks_used;
3235 __unlink_end_trans(trans, root);
3236 btrfs_btree_balance_dirty(root, nr);
3242 * this can truncate away extent items, csum items and directory items.
3243 * It starts at a high offset and removes keys until it can't find
3244 * any higher than new_size
3246 * csum items that cross the new i_size are truncated to the new size
3249 * min_type is the minimum key type to truncate down to. If set to 0, this
3250 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3252 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3253 struct btrfs_root *root,
3254 struct inode *inode,
3255 u64 new_size, u32 min_type)
3257 struct btrfs_path *path;
3258 struct extent_buffer *leaf;
3259 struct btrfs_file_extent_item *fi;
3260 struct btrfs_key key;
3261 struct btrfs_key found_key;
3262 u64 extent_start = 0;
3263 u64 extent_num_bytes = 0;
3264 u64 extent_offset = 0;
3266 u64 mask = root->sectorsize - 1;
3267 u32 found_type = (u8)-1;
3270 int pending_del_nr = 0;
3271 int pending_del_slot = 0;
3272 int extent_type = -1;
3275 u64 ino = btrfs_ino(inode);
3277 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3279 path = btrfs_alloc_path();
3285 * We want to drop from the next block forward in case this new size is
3286 * not block aligned since we will be keeping the last block of the
3287 * extent just the way it is.
3289 if (root->ref_cows || root == root->fs_info->tree_root)
3290 btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0);
3293 * This function is also used to drop the items in the log tree before
3294 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3295 * it is used to drop the loged items. So we shouldn't kill the delayed
3298 if (min_type == 0 && root == BTRFS_I(inode)->root)
3299 btrfs_kill_delayed_inode_items(inode);
3302 key.offset = (u64)-1;
3306 path->leave_spinning = 1;
3307 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3314 /* there are no items in the tree for us to truncate, we're
3317 if (path->slots[0] == 0)
3324 leaf = path->nodes[0];
3325 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3326 found_type = btrfs_key_type(&found_key);
3328 if (found_key.objectid != ino)
3331 if (found_type < min_type)
3334 item_end = found_key.offset;
3335 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3336 fi = btrfs_item_ptr(leaf, path->slots[0],
3337 struct btrfs_file_extent_item);
3338 extent_type = btrfs_file_extent_type(leaf, fi);
3339 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3341 btrfs_file_extent_num_bytes(leaf, fi);
3342 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3343 item_end += btrfs_file_extent_inline_len(leaf,
3348 if (found_type > min_type) {
3351 if (item_end < new_size)
3353 if (found_key.offset >= new_size)
3359 /* FIXME, shrink the extent if the ref count is only 1 */
3360 if (found_type != BTRFS_EXTENT_DATA_KEY)
3363 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3365 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3367 u64 orig_num_bytes =
3368 btrfs_file_extent_num_bytes(leaf, fi);
3369 extent_num_bytes = new_size -
3370 found_key.offset + root->sectorsize - 1;
3371 extent_num_bytes = extent_num_bytes &
3372 ~((u64)root->sectorsize - 1);
3373 btrfs_set_file_extent_num_bytes(leaf, fi,
3375 num_dec = (orig_num_bytes -
3377 if (root->ref_cows && extent_start != 0)
3378 inode_sub_bytes(inode, num_dec);
3379 btrfs_mark_buffer_dirty(leaf);
3382 btrfs_file_extent_disk_num_bytes(leaf,
3384 extent_offset = found_key.offset -
3385 btrfs_file_extent_offset(leaf, fi);
3387 /* FIXME blocksize != 4096 */
3388 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3389 if (extent_start != 0) {
3392 inode_sub_bytes(inode, num_dec);
3395 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3397 * we can't truncate inline items that have had
3401 btrfs_file_extent_compression(leaf, fi) == 0 &&
3402 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3403 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3404 u32 size = new_size - found_key.offset;
3406 if (root->ref_cows) {
3407 inode_sub_bytes(inode, item_end + 1 -
3411 btrfs_file_extent_calc_inline_size(size);
3412 btrfs_truncate_item(trans, root, path,
3414 } else if (root->ref_cows) {
3415 inode_sub_bytes(inode, item_end + 1 -
3421 if (!pending_del_nr) {
3422 /* no pending yet, add ourselves */
3423 pending_del_slot = path->slots[0];
3425 } else if (pending_del_nr &&
3426 path->slots[0] + 1 == pending_del_slot) {
3427 /* hop on the pending chunk */
3429 pending_del_slot = path->slots[0];
3436 if (found_extent && (root->ref_cows ||
3437 root == root->fs_info->tree_root)) {
3438 btrfs_set_path_blocking(path);
3439 ret = btrfs_free_extent(trans, root, extent_start,
3440 extent_num_bytes, 0,
3441 btrfs_header_owner(leaf),
3442 ino, extent_offset, 0);
3446 if (found_type == BTRFS_INODE_ITEM_KEY)
3449 if (path->slots[0] == 0 ||
3450 path->slots[0] != pending_del_slot) {
3451 if (pending_del_nr) {
3452 ret = btrfs_del_items(trans, root, path,
3456 btrfs_abort_transaction(trans,
3462 btrfs_release_path(path);
3469 if (pending_del_nr) {
3470 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3473 btrfs_abort_transaction(trans, root, ret);
3476 btrfs_free_path(path);
3481 * taken from block_truncate_page, but does cow as it zeros out
3482 * any bytes left in the last page in the file.
3484 static int btrfs_truncate_page(struct address_space *mapping, loff_t from)
3486 struct inode *inode = mapping->host;
3487 struct btrfs_root *root = BTRFS_I(inode)->root;
3488 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3489 struct btrfs_ordered_extent *ordered;
3490 struct extent_state *cached_state = NULL;
3492 u32 blocksize = root->sectorsize;
3493 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3494 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3496 gfp_t mask = btrfs_alloc_write_mask(mapping);
3501 if ((offset & (blocksize - 1)) == 0)
3503 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3509 page = find_or_create_page(mapping, index, mask);
3511 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3515 page_start = page_offset(page);
3516 page_end = page_start + PAGE_CACHE_SIZE - 1;
3518 if (!PageUptodate(page)) {
3519 ret = btrfs_readpage(NULL, page);
3521 if (page->mapping != mapping) {
3523 page_cache_release(page);
3526 if (!PageUptodate(page)) {
3531 wait_on_page_writeback(page);
3533 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3534 set_page_extent_mapped(page);
3536 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3538 unlock_extent_cached(io_tree, page_start, page_end,
3539 &cached_state, GFP_NOFS);
3541 page_cache_release(page);
3542 btrfs_start_ordered_extent(inode, ordered, 1);
3543 btrfs_put_ordered_extent(ordered);
3547 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3548 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
3549 0, 0, &cached_state, GFP_NOFS);
3551 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3554 unlock_extent_cached(io_tree, page_start, page_end,
3555 &cached_state, GFP_NOFS);
3560 if (offset != PAGE_CACHE_SIZE) {
3562 memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset);
3563 flush_dcache_page(page);
3566 ClearPageChecked(page);
3567 set_page_dirty(page);
3568 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3573 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3575 page_cache_release(page);
3581 * This function puts in dummy file extents for the area we're creating a hole
3582 * for. So if we are truncating this file to a larger size we need to insert
3583 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3584 * the range between oldsize and size
3586 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3588 struct btrfs_trans_handle *trans;
3589 struct btrfs_root *root = BTRFS_I(inode)->root;
3590 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3591 struct extent_map *em = NULL;
3592 struct extent_state *cached_state = NULL;
3593 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3594 u64 mask = root->sectorsize - 1;
3595 u64 hole_start = (oldsize + mask) & ~mask;
3596 u64 block_end = (size + mask) & ~mask;
3602 if (size <= hole_start)
3606 struct btrfs_ordered_extent *ordered;
3607 btrfs_wait_ordered_range(inode, hole_start,
3608 block_end - hole_start);
3609 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3611 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3614 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3615 &cached_state, GFP_NOFS);
3616 btrfs_put_ordered_extent(ordered);
3619 cur_offset = hole_start;
3621 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3622 block_end - cur_offset, 0);
3627 last_byte = min(extent_map_end(em), block_end);
3628 last_byte = (last_byte + mask) & ~mask;
3629 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3630 struct extent_map *hole_em;
3632 hole_size = last_byte - cur_offset;
3634 trans = btrfs_start_transaction(root, 3);
3635 if (IS_ERR(trans)) {
3636 err = PTR_ERR(trans);
3640 err = btrfs_drop_extents(trans, root, inode,
3642 cur_offset + hole_size,
3645 btrfs_abort_transaction(trans, root, err);
3646 btrfs_end_transaction(trans, root);
3650 err = btrfs_insert_file_extent(trans, root,
3651 btrfs_ino(inode), cur_offset, 0,
3652 0, hole_size, 0, hole_size,
3655 btrfs_abort_transaction(trans, root, err);
3656 btrfs_end_transaction(trans, root);
3660 btrfs_drop_extent_cache(inode, cur_offset,
3661 cur_offset + hole_size - 1, 0);
3662 hole_em = alloc_extent_map();
3664 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3665 &BTRFS_I(inode)->runtime_flags);
3668 hole_em->start = cur_offset;
3669 hole_em->len = hole_size;
3670 hole_em->orig_start = cur_offset;
3672 hole_em->block_start = EXTENT_MAP_HOLE;
3673 hole_em->block_len = 0;
3674 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
3675 hole_em->compress_type = BTRFS_COMPRESS_NONE;
3676 hole_em->generation = trans->transid;
3679 write_lock(&em_tree->lock);
3680 err = add_extent_mapping(em_tree, hole_em);
3682 list_move(&hole_em->list,
3683 &em_tree->modified_extents);
3684 write_unlock(&em_tree->lock);
3687 btrfs_drop_extent_cache(inode, cur_offset,
3691 free_extent_map(hole_em);
3693 btrfs_update_inode(trans, root, inode);
3694 btrfs_end_transaction(trans, root);
3696 free_extent_map(em);
3698 cur_offset = last_byte;
3699 if (cur_offset >= block_end)
3703 free_extent_map(em);
3704 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3709 static int btrfs_setsize(struct inode *inode, loff_t newsize)
3711 struct btrfs_root *root = BTRFS_I(inode)->root;
3712 struct btrfs_trans_handle *trans;
3713 loff_t oldsize = i_size_read(inode);
3716 if (newsize == oldsize)
3719 if (newsize > oldsize) {
3720 truncate_pagecache(inode, oldsize, newsize);
3721 ret = btrfs_cont_expand(inode, oldsize, newsize);
3725 trans = btrfs_start_transaction(root, 1);
3727 return PTR_ERR(trans);
3729 i_size_write(inode, newsize);
3730 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3731 ret = btrfs_update_inode(trans, root, inode);
3732 btrfs_end_transaction(trans, root);
3736 * We're truncating a file that used to have good data down to
3737 * zero. Make sure it gets into the ordered flush list so that
3738 * any new writes get down to disk quickly.
3741 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3742 &BTRFS_I(inode)->runtime_flags);
3744 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3745 truncate_setsize(inode, newsize);
3746 ret = btrfs_truncate(inode);
3752 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3754 struct inode *inode = dentry->d_inode;
3755 struct btrfs_root *root = BTRFS_I(inode)->root;
3758 if (btrfs_root_readonly(root))
3761 err = inode_change_ok(inode, attr);
3765 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3766 err = btrfs_setsize(inode, attr->ia_size);
3771 if (attr->ia_valid) {
3772 setattr_copy(inode, attr);
3773 inode_inc_iversion(inode);
3774 err = btrfs_dirty_inode(inode);
3776 if (!err && attr->ia_valid & ATTR_MODE)
3777 err = btrfs_acl_chmod(inode);
3783 void btrfs_evict_inode(struct inode *inode)
3785 struct btrfs_trans_handle *trans;
3786 struct btrfs_root *root = BTRFS_I(inode)->root;
3787 struct btrfs_block_rsv *rsv, *global_rsv;
3788 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3792 trace_btrfs_inode_evict(inode);
3794 truncate_inode_pages(&inode->i_data, 0);
3795 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3796 btrfs_is_free_space_inode(inode)))
3799 if (is_bad_inode(inode)) {
3800 btrfs_orphan_del(NULL, inode);
3803 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3804 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3806 if (root->fs_info->log_root_recovering) {
3807 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3808 &BTRFS_I(inode)->runtime_flags));
3812 if (inode->i_nlink > 0) {
3813 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3817 rsv = btrfs_alloc_block_rsv(root);
3819 btrfs_orphan_del(NULL, inode);
3822 rsv->size = min_size;
3824 global_rsv = &root->fs_info->global_block_rsv;
3826 btrfs_i_size_write(inode, 0);
3829 * This is a bit simpler than btrfs_truncate since
3831 * 1) We've already reserved our space for our orphan item in the
3833 * 2) We're going to delete the inode item, so we don't need to update
3836 * So we just need to reserve some slack space in case we add bytes when
3837 * doing the truncate.
3840 ret = btrfs_block_rsv_refill_noflush(root, rsv, min_size);
3843 * Try and steal from the global reserve since we will
3844 * likely not use this space anyway, we want to try as
3845 * hard as possible to get this to work.
3848 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3851 printk(KERN_WARNING "Could not get space for a "
3852 "delete, will truncate on mount %d\n", ret);
3853 btrfs_orphan_del(NULL, inode);
3854 btrfs_free_block_rsv(root, rsv);
3858 trans = btrfs_start_transaction(root, 0);
3859 if (IS_ERR(trans)) {
3860 btrfs_orphan_del(NULL, inode);
3861 btrfs_free_block_rsv(root, rsv);
3865 trans->block_rsv = rsv;
3867 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3871 nr = trans->blocks_used;
3872 btrfs_end_transaction(trans, root);
3874 btrfs_btree_balance_dirty(root, nr);
3877 btrfs_free_block_rsv(root, rsv);
3880 trans->block_rsv = root->orphan_block_rsv;
3881 ret = btrfs_orphan_del(trans, inode);
3885 trans->block_rsv = &root->fs_info->trans_block_rsv;
3886 if (!(root == root->fs_info->tree_root ||
3887 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3888 btrfs_return_ino(root, btrfs_ino(inode));
3890 nr = trans->blocks_used;
3891 btrfs_end_transaction(trans, root);
3892 btrfs_btree_balance_dirty(root, nr);
3899 * this returns the key found in the dir entry in the location pointer.
3900 * If no dir entries were found, location->objectid is 0.
3902 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
3903 struct btrfs_key *location)
3905 const char *name = dentry->d_name.name;
3906 int namelen = dentry->d_name.len;
3907 struct btrfs_dir_item *di;
3908 struct btrfs_path *path;
3909 struct btrfs_root *root = BTRFS_I(dir)->root;
3912 path = btrfs_alloc_path();
3916 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
3921 if (IS_ERR_OR_NULL(di))
3924 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
3926 btrfs_free_path(path);
3929 location->objectid = 0;
3934 * when we hit a tree root in a directory, the btrfs part of the inode
3935 * needs to be changed to reflect the root directory of the tree root. This
3936 * is kind of like crossing a mount point.
3938 static int fixup_tree_root_location(struct btrfs_root *root,
3940 struct dentry *dentry,
3941 struct btrfs_key *location,
3942 struct btrfs_root **sub_root)
3944 struct btrfs_path *path;
3945 struct btrfs_root *new_root;
3946 struct btrfs_root_ref *ref;
3947 struct extent_buffer *leaf;
3951 path = btrfs_alloc_path();
3958 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
3959 BTRFS_I(dir)->root->root_key.objectid,
3960 location->objectid);
3967 leaf = path->nodes[0];
3968 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
3969 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
3970 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
3973 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
3974 (unsigned long)(ref + 1),
3975 dentry->d_name.len);
3979 btrfs_release_path(path);
3981 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
3982 if (IS_ERR(new_root)) {
3983 err = PTR_ERR(new_root);
3987 if (btrfs_root_refs(&new_root->root_item) == 0) {
3992 *sub_root = new_root;
3993 location->objectid = btrfs_root_dirid(&new_root->root_item);
3994 location->type = BTRFS_INODE_ITEM_KEY;
3995 location->offset = 0;
3998 btrfs_free_path(path);
4002 static void inode_tree_add(struct inode *inode)
4004 struct btrfs_root *root = BTRFS_I(inode)->root;
4005 struct btrfs_inode *entry;
4007 struct rb_node *parent;
4008 u64 ino = btrfs_ino(inode);
4010 p = &root->inode_tree.rb_node;
4013 if (inode_unhashed(inode))
4016 spin_lock(&root->inode_lock);
4019 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4021 if (ino < btrfs_ino(&entry->vfs_inode))
4022 p = &parent->rb_left;
4023 else if (ino > btrfs_ino(&entry->vfs_inode))
4024 p = &parent->rb_right;
4026 WARN_ON(!(entry->vfs_inode.i_state &
4027 (I_WILL_FREE | I_FREEING)));
4028 rb_erase(parent, &root->inode_tree);
4029 RB_CLEAR_NODE(parent);
4030 spin_unlock(&root->inode_lock);
4034 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4035 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4036 spin_unlock(&root->inode_lock);
4039 static void inode_tree_del(struct inode *inode)
4041 struct btrfs_root *root = BTRFS_I(inode)->root;
4044 spin_lock(&root->inode_lock);
4045 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4046 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4047 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4048 empty = RB_EMPTY_ROOT(&root->inode_tree);
4050 spin_unlock(&root->inode_lock);
4053 * Free space cache has inodes in the tree root, but the tree root has a
4054 * root_refs of 0, so this could end up dropping the tree root as a
4055 * snapshot, so we need the extra !root->fs_info->tree_root check to
4056 * make sure we don't drop it.
4058 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4059 root != root->fs_info->tree_root) {
4060 synchronize_srcu(&root->fs_info->subvol_srcu);
4061 spin_lock(&root->inode_lock);
4062 empty = RB_EMPTY_ROOT(&root->inode_tree);
4063 spin_unlock(&root->inode_lock);
4065 btrfs_add_dead_root(root);
4069 void btrfs_invalidate_inodes(struct btrfs_root *root)
4071 struct rb_node *node;
4072 struct rb_node *prev;
4073 struct btrfs_inode *entry;
4074 struct inode *inode;
4077 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4079 spin_lock(&root->inode_lock);
4081 node = root->inode_tree.rb_node;
4085 entry = rb_entry(node, struct btrfs_inode, rb_node);
4087 if (objectid < btrfs_ino(&entry->vfs_inode))
4088 node = node->rb_left;
4089 else if (objectid > btrfs_ino(&entry->vfs_inode))
4090 node = node->rb_right;
4096 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4097 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4101 prev = rb_next(prev);
4105 entry = rb_entry(node, struct btrfs_inode, rb_node);
4106 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4107 inode = igrab(&entry->vfs_inode);
4109 spin_unlock(&root->inode_lock);
4110 if (atomic_read(&inode->i_count) > 1)
4111 d_prune_aliases(inode);
4113 * btrfs_drop_inode will have it removed from
4114 * the inode cache when its usage count
4119 spin_lock(&root->inode_lock);
4123 if (cond_resched_lock(&root->inode_lock))
4126 node = rb_next(node);
4128 spin_unlock(&root->inode_lock);
4131 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4133 struct btrfs_iget_args *args = p;
4134 inode->i_ino = args->ino;
4135 BTRFS_I(inode)->root = args->root;
4139 static int btrfs_find_actor(struct inode *inode, void *opaque)
4141 struct btrfs_iget_args *args = opaque;
4142 return args->ino == btrfs_ino(inode) &&
4143 args->root == BTRFS_I(inode)->root;
4146 static struct inode *btrfs_iget_locked(struct super_block *s,
4148 struct btrfs_root *root)
4150 struct inode *inode;
4151 struct btrfs_iget_args args;
4152 args.ino = objectid;
4155 inode = iget5_locked(s, objectid, btrfs_find_actor,
4156 btrfs_init_locked_inode,
4161 /* Get an inode object given its location and corresponding root.
4162 * Returns in *is_new if the inode was read from disk
4164 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4165 struct btrfs_root *root, int *new)
4167 struct inode *inode;
4169 inode = btrfs_iget_locked(s, location->objectid, root);
4171 return ERR_PTR(-ENOMEM);
4173 if (inode->i_state & I_NEW) {
4174 BTRFS_I(inode)->root = root;
4175 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4176 btrfs_read_locked_inode(inode);
4177 if (!is_bad_inode(inode)) {
4178 inode_tree_add(inode);
4179 unlock_new_inode(inode);
4183 unlock_new_inode(inode);
4185 inode = ERR_PTR(-ESTALE);
4192 static struct inode *new_simple_dir(struct super_block *s,
4193 struct btrfs_key *key,
4194 struct btrfs_root *root)
4196 struct inode *inode = new_inode(s);
4199 return ERR_PTR(-ENOMEM);
4201 BTRFS_I(inode)->root = root;
4202 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4203 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4205 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4206 inode->i_op = &btrfs_dir_ro_inode_operations;
4207 inode->i_fop = &simple_dir_operations;
4208 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4209 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4214 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4216 struct inode *inode;
4217 struct btrfs_root *root = BTRFS_I(dir)->root;
4218 struct btrfs_root *sub_root = root;
4219 struct btrfs_key location;
4223 if (dentry->d_name.len > BTRFS_NAME_LEN)
4224 return ERR_PTR(-ENAMETOOLONG);
4226 if (unlikely(d_need_lookup(dentry))) {
4227 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
4228 kfree(dentry->d_fsdata);
4229 dentry->d_fsdata = NULL;
4230 /* This thing is hashed, drop it for now */
4233 ret = btrfs_inode_by_name(dir, dentry, &location);
4237 return ERR_PTR(ret);
4239 if (location.objectid == 0)
4242 if (location.type == BTRFS_INODE_ITEM_KEY) {
4243 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4247 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4249 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4250 ret = fixup_tree_root_location(root, dir, dentry,
4251 &location, &sub_root);
4254 inode = ERR_PTR(ret);
4256 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4258 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4260 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4262 if (!IS_ERR(inode) && root != sub_root) {
4263 down_read(&root->fs_info->cleanup_work_sem);
4264 if (!(inode->i_sb->s_flags & MS_RDONLY))
4265 ret = btrfs_orphan_cleanup(sub_root);
4266 up_read(&root->fs_info->cleanup_work_sem);
4268 inode = ERR_PTR(ret);
4274 static int btrfs_dentry_delete(const struct dentry *dentry)
4276 struct btrfs_root *root;
4277 struct inode *inode = dentry->d_inode;
4279 if (!inode && !IS_ROOT(dentry))
4280 inode = dentry->d_parent->d_inode;
4283 root = BTRFS_I(inode)->root;
4284 if (btrfs_root_refs(&root->root_item) == 0)
4287 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4293 static void btrfs_dentry_release(struct dentry *dentry)
4295 if (dentry->d_fsdata)
4296 kfree(dentry->d_fsdata);
4299 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4304 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4305 if (unlikely(d_need_lookup(dentry))) {
4306 spin_lock(&dentry->d_lock);
4307 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4308 spin_unlock(&dentry->d_lock);
4313 unsigned char btrfs_filetype_table[] = {
4314 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4317 static int btrfs_real_readdir(struct file *filp, void *dirent,
4320 struct inode *inode = filp->f_dentry->d_inode;
4321 struct btrfs_root *root = BTRFS_I(inode)->root;
4322 struct btrfs_item *item;
4323 struct btrfs_dir_item *di;
4324 struct btrfs_key key;
4325 struct btrfs_key found_key;
4326 struct btrfs_path *path;
4327 struct list_head ins_list;
4328 struct list_head del_list;
4330 struct extent_buffer *leaf;
4332 unsigned char d_type;
4337 int key_type = BTRFS_DIR_INDEX_KEY;
4341 int is_curr = 0; /* filp->f_pos points to the current index? */
4343 /* FIXME, use a real flag for deciding about the key type */
4344 if (root->fs_info->tree_root == root)
4345 key_type = BTRFS_DIR_ITEM_KEY;
4347 /* special case for "." */
4348 if (filp->f_pos == 0) {
4349 over = filldir(dirent, ".", 1,
4350 filp->f_pos, btrfs_ino(inode), DT_DIR);
4355 /* special case for .., just use the back ref */
4356 if (filp->f_pos == 1) {
4357 u64 pino = parent_ino(filp->f_path.dentry);
4358 over = filldir(dirent, "..", 2,
4359 filp->f_pos, pino, DT_DIR);
4364 path = btrfs_alloc_path();
4370 if (key_type == BTRFS_DIR_INDEX_KEY) {
4371 INIT_LIST_HEAD(&ins_list);
4372 INIT_LIST_HEAD(&del_list);
4373 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4376 btrfs_set_key_type(&key, key_type);
4377 key.offset = filp->f_pos;
4378 key.objectid = btrfs_ino(inode);
4380 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4385 leaf = path->nodes[0];
4386 slot = path->slots[0];
4387 if (slot >= btrfs_header_nritems(leaf)) {
4388 ret = btrfs_next_leaf(root, path);
4396 item = btrfs_item_nr(leaf, slot);
4397 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4399 if (found_key.objectid != key.objectid)
4401 if (btrfs_key_type(&found_key) != key_type)
4403 if (found_key.offset < filp->f_pos)
4405 if (key_type == BTRFS_DIR_INDEX_KEY &&
4406 btrfs_should_delete_dir_index(&del_list,
4410 filp->f_pos = found_key.offset;
4413 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4415 di_total = btrfs_item_size(leaf, item);
4417 while (di_cur < di_total) {
4418 struct btrfs_key location;
4420 if (verify_dir_item(root, leaf, di))
4423 name_len = btrfs_dir_name_len(leaf, di);
4424 if (name_len <= sizeof(tmp_name)) {
4425 name_ptr = tmp_name;
4427 name_ptr = kmalloc(name_len, GFP_NOFS);
4433 read_extent_buffer(leaf, name_ptr,
4434 (unsigned long)(di + 1), name_len);
4436 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4437 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4440 /* is this a reference to our own snapshot? If so
4443 * In contrast to old kernels, we insert the snapshot's
4444 * dir item and dir index after it has been created, so
4445 * we won't find a reference to our own snapshot. We
4446 * still keep the following code for backward
4449 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4450 location.objectid == root->root_key.objectid) {
4454 over = filldir(dirent, name_ptr, name_len,
4455 found_key.offset, location.objectid,
4459 if (name_ptr != tmp_name)
4464 di_len = btrfs_dir_name_len(leaf, di) +
4465 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4467 di = (struct btrfs_dir_item *)((char *)di + di_len);
4473 if (key_type == BTRFS_DIR_INDEX_KEY) {
4476 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4482 /* Reached end of directory/root. Bump pos past the last item. */
4483 if (key_type == BTRFS_DIR_INDEX_KEY)
4485 * 32-bit glibc will use getdents64, but then strtol -
4486 * so the last number we can serve is this.
4488 filp->f_pos = 0x7fffffff;
4494 if (key_type == BTRFS_DIR_INDEX_KEY)
4495 btrfs_put_delayed_items(&ins_list, &del_list);
4496 btrfs_free_path(path);
4500 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4502 struct btrfs_root *root = BTRFS_I(inode)->root;
4503 struct btrfs_trans_handle *trans;
4505 bool nolock = false;
4507 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4510 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
4513 if (wbc->sync_mode == WB_SYNC_ALL) {
4515 trans = btrfs_join_transaction_nolock(root);
4517 trans = btrfs_join_transaction(root);
4519 return PTR_ERR(trans);
4521 ret = btrfs_end_transaction_nolock(trans, root);
4523 ret = btrfs_commit_transaction(trans, root);
4529 * This is somewhat expensive, updating the tree every time the
4530 * inode changes. But, it is most likely to find the inode in cache.
4531 * FIXME, needs more benchmarking...there are no reasons other than performance
4532 * to keep or drop this code.
4534 int btrfs_dirty_inode(struct inode *inode)
4536 struct btrfs_root *root = BTRFS_I(inode)->root;
4537 struct btrfs_trans_handle *trans;
4540 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4543 trans = btrfs_join_transaction(root);
4545 return PTR_ERR(trans);
4547 ret = btrfs_update_inode(trans, root, inode);
4548 if (ret && ret == -ENOSPC) {
4549 /* whoops, lets try again with the full transaction */
4550 btrfs_end_transaction(trans, root);
4551 trans = btrfs_start_transaction(root, 1);
4553 return PTR_ERR(trans);
4555 ret = btrfs_update_inode(trans, root, inode);
4557 btrfs_end_transaction(trans, root);
4558 if (BTRFS_I(inode)->delayed_node)
4559 btrfs_balance_delayed_items(root);
4565 * This is a copy of file_update_time. We need this so we can return error on
4566 * ENOSPC for updating the inode in the case of file write and mmap writes.
4568 static int btrfs_update_time(struct inode *inode, struct timespec *now,
4571 struct btrfs_root *root = BTRFS_I(inode)->root;
4573 if (btrfs_root_readonly(root))
4576 if (flags & S_VERSION)
4577 inode_inc_iversion(inode);
4578 if (flags & S_CTIME)
4579 inode->i_ctime = *now;
4580 if (flags & S_MTIME)
4581 inode->i_mtime = *now;
4582 if (flags & S_ATIME)
4583 inode->i_atime = *now;
4584 return btrfs_dirty_inode(inode);
4588 * find the highest existing sequence number in a directory
4589 * and then set the in-memory index_cnt variable to reflect
4590 * free sequence numbers
4592 static int btrfs_set_inode_index_count(struct inode *inode)
4594 struct btrfs_root *root = BTRFS_I(inode)->root;
4595 struct btrfs_key key, found_key;
4596 struct btrfs_path *path;
4597 struct extent_buffer *leaf;
4600 key.objectid = btrfs_ino(inode);
4601 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4602 key.offset = (u64)-1;
4604 path = btrfs_alloc_path();
4608 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4611 /* FIXME: we should be able to handle this */
4617 * MAGIC NUMBER EXPLANATION:
4618 * since we search a directory based on f_pos we have to start at 2
4619 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4620 * else has to start at 2
4622 if (path->slots[0] == 0) {
4623 BTRFS_I(inode)->index_cnt = 2;
4629 leaf = path->nodes[0];
4630 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4632 if (found_key.objectid != btrfs_ino(inode) ||
4633 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4634 BTRFS_I(inode)->index_cnt = 2;
4638 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4640 btrfs_free_path(path);
4645 * helper to find a free sequence number in a given directory. This current
4646 * code is very simple, later versions will do smarter things in the btree
4648 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4652 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4653 ret = btrfs_inode_delayed_dir_index_count(dir);
4655 ret = btrfs_set_inode_index_count(dir);
4661 *index = BTRFS_I(dir)->index_cnt;
4662 BTRFS_I(dir)->index_cnt++;
4667 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4668 struct btrfs_root *root,
4670 const char *name, int name_len,
4671 u64 ref_objectid, u64 objectid,
4672 umode_t mode, u64 *index)
4674 struct inode *inode;
4675 struct btrfs_inode_item *inode_item;
4676 struct btrfs_key *location;
4677 struct btrfs_path *path;
4678 struct btrfs_inode_ref *ref;
4679 struct btrfs_key key[2];
4685 path = btrfs_alloc_path();
4687 return ERR_PTR(-ENOMEM);
4689 inode = new_inode(root->fs_info->sb);
4691 btrfs_free_path(path);
4692 return ERR_PTR(-ENOMEM);
4696 * we have to initialize this early, so we can reclaim the inode
4697 * number if we fail afterwards in this function.
4699 inode->i_ino = objectid;
4702 trace_btrfs_inode_request(dir);
4704 ret = btrfs_set_inode_index(dir, index);
4706 btrfs_free_path(path);
4708 return ERR_PTR(ret);
4712 * index_cnt is ignored for everything but a dir,
4713 * btrfs_get_inode_index_count has an explanation for the magic
4716 BTRFS_I(inode)->index_cnt = 2;
4717 BTRFS_I(inode)->root = root;
4718 BTRFS_I(inode)->generation = trans->transid;
4719 inode->i_generation = BTRFS_I(inode)->generation;
4722 * We could have gotten an inode number from somebody who was fsynced
4723 * and then removed in this same transaction, so let's just set full
4724 * sync since it will be a full sync anyway and this will blow away the
4725 * old info in the log.
4727 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
4734 key[0].objectid = objectid;
4735 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4738 key[1].objectid = objectid;
4739 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4740 key[1].offset = ref_objectid;
4742 sizes[0] = sizeof(struct btrfs_inode_item);
4743 sizes[1] = name_len + sizeof(*ref);
4745 path->leave_spinning = 1;
4746 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4750 inode_init_owner(inode, dir, mode);
4751 inode_set_bytes(inode, 0);
4752 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4753 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4754 struct btrfs_inode_item);
4755 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
4756 sizeof(*inode_item));
4757 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4759 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4760 struct btrfs_inode_ref);
4761 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4762 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4763 ptr = (unsigned long)(ref + 1);
4764 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4766 btrfs_mark_buffer_dirty(path->nodes[0]);
4767 btrfs_free_path(path);
4769 location = &BTRFS_I(inode)->location;
4770 location->objectid = objectid;
4771 location->offset = 0;
4772 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4774 btrfs_inherit_iflags(inode, dir);
4776 if (S_ISREG(mode)) {
4777 if (btrfs_test_opt(root, NODATASUM))
4778 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4779 if (btrfs_test_opt(root, NODATACOW) ||
4780 (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW))
4781 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4784 insert_inode_hash(inode);
4785 inode_tree_add(inode);
4787 trace_btrfs_inode_new(inode);
4788 btrfs_set_inode_last_trans(trans, inode);
4790 btrfs_update_root_times(trans, root);
4795 BTRFS_I(dir)->index_cnt--;
4796 btrfs_free_path(path);
4798 return ERR_PTR(ret);
4801 static inline u8 btrfs_inode_type(struct inode *inode)
4803 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4807 * utility function to add 'inode' into 'parent_inode' with
4808 * a give name and a given sequence number.
4809 * if 'add_backref' is true, also insert a backref from the
4810 * inode to the parent directory.
4812 int btrfs_add_link(struct btrfs_trans_handle *trans,
4813 struct inode *parent_inode, struct inode *inode,
4814 const char *name, int name_len, int add_backref, u64 index)
4817 struct btrfs_key key;
4818 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4819 u64 ino = btrfs_ino(inode);
4820 u64 parent_ino = btrfs_ino(parent_inode);
4822 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4823 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4826 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4830 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4831 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4832 key.objectid, root->root_key.objectid,
4833 parent_ino, index, name, name_len);
4834 } else if (add_backref) {
4835 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4839 /* Nothing to clean up yet */
4843 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4845 btrfs_inode_type(inode), index);
4849 btrfs_abort_transaction(trans, root, ret);
4853 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4855 inode_inc_iversion(parent_inode);
4856 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4857 ret = btrfs_update_inode(trans, root, parent_inode);
4859 btrfs_abort_transaction(trans, root, ret);
4863 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4866 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4867 key.objectid, root->root_key.objectid,
4868 parent_ino, &local_index, name, name_len);
4870 } else if (add_backref) {
4874 err = btrfs_del_inode_ref(trans, root, name, name_len,
4875 ino, parent_ino, &local_index);
4880 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4881 struct inode *dir, struct dentry *dentry,
4882 struct inode *inode, int backref, u64 index)
4884 int err = btrfs_add_link(trans, dir, inode,
4885 dentry->d_name.name, dentry->d_name.len,
4892 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4893 umode_t mode, dev_t rdev)
4895 struct btrfs_trans_handle *trans;
4896 struct btrfs_root *root = BTRFS_I(dir)->root;
4897 struct inode *inode = NULL;
4901 unsigned long nr = 0;
4904 if (!new_valid_dev(rdev))
4908 * 2 for inode item and ref
4910 * 1 for xattr if selinux is on
4912 trans = btrfs_start_transaction(root, 5);
4914 return PTR_ERR(trans);
4916 err = btrfs_find_free_ino(root, &objectid);
4920 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4921 dentry->d_name.len, btrfs_ino(dir), objectid,
4923 if (IS_ERR(inode)) {
4924 err = PTR_ERR(inode);
4928 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
4935 * If the active LSM wants to access the inode during
4936 * d_instantiate it needs these. Smack checks to see
4937 * if the filesystem supports xattrs by looking at the
4941 inode->i_op = &btrfs_special_inode_operations;
4942 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
4946 init_special_inode(inode, inode->i_mode, rdev);
4947 btrfs_update_inode(trans, root, inode);
4948 d_instantiate(dentry, inode);
4951 nr = trans->blocks_used;
4952 btrfs_end_transaction(trans, root);
4953 btrfs_btree_balance_dirty(root, nr);
4955 inode_dec_link_count(inode);
4961 static int btrfs_create(struct inode *dir, struct dentry *dentry,
4962 umode_t mode, bool excl)
4964 struct btrfs_trans_handle *trans;
4965 struct btrfs_root *root = BTRFS_I(dir)->root;
4966 struct inode *inode = NULL;
4969 unsigned long nr = 0;
4974 * 2 for inode item and ref
4976 * 1 for xattr if selinux is on
4978 trans = btrfs_start_transaction(root, 5);
4980 return PTR_ERR(trans);
4982 err = btrfs_find_free_ino(root, &objectid);
4986 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
4987 dentry->d_name.len, btrfs_ino(dir), objectid,
4989 if (IS_ERR(inode)) {
4990 err = PTR_ERR(inode);
4994 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5001 * If the active LSM wants to access the inode during
5002 * d_instantiate it needs these. Smack checks to see
5003 * if the filesystem supports xattrs by looking at the
5006 inode->i_fop = &btrfs_file_operations;
5007 inode->i_op = &btrfs_file_inode_operations;
5009 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5013 inode->i_mapping->a_ops = &btrfs_aops;
5014 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5015 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5016 d_instantiate(dentry, inode);
5019 nr = trans->blocks_used;
5020 btrfs_end_transaction(trans, root);
5022 inode_dec_link_count(inode);
5025 btrfs_btree_balance_dirty(root, nr);
5029 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5030 struct dentry *dentry)
5032 struct btrfs_trans_handle *trans;
5033 struct btrfs_root *root = BTRFS_I(dir)->root;
5034 struct inode *inode = old_dentry->d_inode;
5036 unsigned long nr = 0;
5040 /* do not allow sys_link's with other subvols of the same device */
5041 if (root->objectid != BTRFS_I(inode)->root->objectid)
5044 if (inode->i_nlink == ~0U)
5047 err = btrfs_set_inode_index(dir, &index);
5052 * 2 items for inode and inode ref
5053 * 2 items for dir items
5054 * 1 item for parent inode
5056 trans = btrfs_start_transaction(root, 5);
5057 if (IS_ERR(trans)) {
5058 err = PTR_ERR(trans);
5062 btrfs_inc_nlink(inode);
5063 inode_inc_iversion(inode);
5064 inode->i_ctime = CURRENT_TIME;
5067 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5072 struct dentry *parent = dentry->d_parent;
5073 err = btrfs_update_inode(trans, root, inode);
5076 d_instantiate(dentry, inode);
5077 btrfs_log_new_name(trans, inode, NULL, parent);
5080 nr = trans->blocks_used;
5081 btrfs_end_transaction(trans, root);
5084 inode_dec_link_count(inode);
5087 btrfs_btree_balance_dirty(root, nr);
5091 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5093 struct inode *inode = NULL;
5094 struct btrfs_trans_handle *trans;
5095 struct btrfs_root *root = BTRFS_I(dir)->root;
5097 int drop_on_err = 0;
5100 unsigned long nr = 1;
5103 * 2 items for inode and ref
5104 * 2 items for dir items
5105 * 1 for xattr if selinux is on
5107 trans = btrfs_start_transaction(root, 5);
5109 return PTR_ERR(trans);
5111 err = btrfs_find_free_ino(root, &objectid);
5115 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5116 dentry->d_name.len, btrfs_ino(dir), objectid,
5117 S_IFDIR | mode, &index);
5118 if (IS_ERR(inode)) {
5119 err = PTR_ERR(inode);
5125 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5129 inode->i_op = &btrfs_dir_inode_operations;
5130 inode->i_fop = &btrfs_dir_file_operations;
5132 btrfs_i_size_write(inode, 0);
5133 err = btrfs_update_inode(trans, root, inode);
5137 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5138 dentry->d_name.len, 0, index);
5142 d_instantiate(dentry, inode);
5146 nr = trans->blocks_used;
5147 btrfs_end_transaction(trans, root);
5150 btrfs_btree_balance_dirty(root, nr);
5154 /* helper for btfs_get_extent. Given an existing extent in the tree,
5155 * and an extent that you want to insert, deal with overlap and insert
5156 * the new extent into the tree.
5158 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5159 struct extent_map *existing,
5160 struct extent_map *em,
5161 u64 map_start, u64 map_len)
5165 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5166 start_diff = map_start - em->start;
5167 em->start = map_start;
5169 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5170 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5171 em->block_start += start_diff;
5172 em->block_len -= start_diff;
5174 return add_extent_mapping(em_tree, em);
5177 static noinline int uncompress_inline(struct btrfs_path *path,
5178 struct inode *inode, struct page *page,
5179 size_t pg_offset, u64 extent_offset,
5180 struct btrfs_file_extent_item *item)
5183 struct extent_buffer *leaf = path->nodes[0];
5186 unsigned long inline_size;
5190 WARN_ON(pg_offset != 0);
5191 compress_type = btrfs_file_extent_compression(leaf, item);
5192 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5193 inline_size = btrfs_file_extent_inline_item_len(leaf,
5194 btrfs_item_nr(leaf, path->slots[0]));
5195 tmp = kmalloc(inline_size, GFP_NOFS);
5198 ptr = btrfs_file_extent_inline_start(item);
5200 read_extent_buffer(leaf, tmp, ptr, inline_size);
5202 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5203 ret = btrfs_decompress(compress_type, tmp, page,
5204 extent_offset, inline_size, max_size);
5206 char *kaddr = kmap_atomic(page);
5207 unsigned long copy_size = min_t(u64,
5208 PAGE_CACHE_SIZE - pg_offset,
5209 max_size - extent_offset);
5210 memset(kaddr + pg_offset, 0, copy_size);
5211 kunmap_atomic(kaddr);
5218 * a bit scary, this does extent mapping from logical file offset to the disk.
5219 * the ugly parts come from merging extents from the disk with the in-ram
5220 * representation. This gets more complex because of the data=ordered code,
5221 * where the in-ram extents might be locked pending data=ordered completion.
5223 * This also copies inline extents directly into the page.
5226 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5227 size_t pg_offset, u64 start, u64 len,
5233 u64 extent_start = 0;
5235 u64 objectid = btrfs_ino(inode);
5237 struct btrfs_path *path = NULL;
5238 struct btrfs_root *root = BTRFS_I(inode)->root;
5239 struct btrfs_file_extent_item *item;
5240 struct extent_buffer *leaf;
5241 struct btrfs_key found_key;
5242 struct extent_map *em = NULL;
5243 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5244 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5245 struct btrfs_trans_handle *trans = NULL;
5249 read_lock(&em_tree->lock);
5250 em = lookup_extent_mapping(em_tree, start, len);
5252 em->bdev = root->fs_info->fs_devices->latest_bdev;
5253 read_unlock(&em_tree->lock);
5256 if (em->start > start || em->start + em->len <= start)
5257 free_extent_map(em);
5258 else if (em->block_start == EXTENT_MAP_INLINE && page)
5259 free_extent_map(em);
5263 em = alloc_extent_map();
5268 em->bdev = root->fs_info->fs_devices->latest_bdev;
5269 em->start = EXTENT_MAP_HOLE;
5270 em->orig_start = EXTENT_MAP_HOLE;
5272 em->block_len = (u64)-1;
5275 path = btrfs_alloc_path();
5281 * Chances are we'll be called again, so go ahead and do
5287 ret = btrfs_lookup_file_extent(trans, root, path,
5288 objectid, start, trans != NULL);
5295 if (path->slots[0] == 0)
5300 leaf = path->nodes[0];
5301 item = btrfs_item_ptr(leaf, path->slots[0],
5302 struct btrfs_file_extent_item);
5303 /* are we inside the extent that was found? */
5304 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5305 found_type = btrfs_key_type(&found_key);
5306 if (found_key.objectid != objectid ||
5307 found_type != BTRFS_EXTENT_DATA_KEY) {
5311 found_type = btrfs_file_extent_type(leaf, item);
5312 extent_start = found_key.offset;
5313 compress_type = btrfs_file_extent_compression(leaf, item);
5314 if (found_type == BTRFS_FILE_EXTENT_REG ||
5315 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5316 extent_end = extent_start +
5317 btrfs_file_extent_num_bytes(leaf, item);
5318 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5320 size = btrfs_file_extent_inline_len(leaf, item);
5321 extent_end = (extent_start + size + root->sectorsize - 1) &
5322 ~((u64)root->sectorsize - 1);
5325 if (start >= extent_end) {
5327 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5328 ret = btrfs_next_leaf(root, path);
5335 leaf = path->nodes[0];
5337 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5338 if (found_key.objectid != objectid ||
5339 found_key.type != BTRFS_EXTENT_DATA_KEY)
5341 if (start + len <= found_key.offset)
5344 em->len = found_key.offset - start;
5348 if (found_type == BTRFS_FILE_EXTENT_REG ||
5349 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5350 em->start = extent_start;
5351 em->len = extent_end - extent_start;
5352 em->orig_start = extent_start -
5353 btrfs_file_extent_offset(leaf, item);
5354 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5356 em->block_start = EXTENT_MAP_HOLE;
5359 if (compress_type != BTRFS_COMPRESS_NONE) {
5360 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5361 em->compress_type = compress_type;
5362 em->block_start = bytenr;
5363 em->block_len = btrfs_file_extent_disk_num_bytes(leaf,
5366 bytenr += btrfs_file_extent_offset(leaf, item);
5367 em->block_start = bytenr;
5368 em->block_len = em->len;
5369 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5370 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5373 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5377 size_t extent_offset;
5380 em->block_start = EXTENT_MAP_INLINE;
5381 if (!page || create) {
5382 em->start = extent_start;
5383 em->len = extent_end - extent_start;
5387 size = btrfs_file_extent_inline_len(leaf, item);
5388 extent_offset = page_offset(page) + pg_offset - extent_start;
5389 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5390 size - extent_offset);
5391 em->start = extent_start + extent_offset;
5392 em->len = (copy_size + root->sectorsize - 1) &
5393 ~((u64)root->sectorsize - 1);
5394 em->orig_start = EXTENT_MAP_INLINE;
5395 if (compress_type) {
5396 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5397 em->compress_type = compress_type;
5399 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5400 if (create == 0 && !PageUptodate(page)) {
5401 if (btrfs_file_extent_compression(leaf, item) !=
5402 BTRFS_COMPRESS_NONE) {
5403 ret = uncompress_inline(path, inode, page,
5405 extent_offset, item);
5406 BUG_ON(ret); /* -ENOMEM */
5409 read_extent_buffer(leaf, map + pg_offset, ptr,
5411 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5412 memset(map + pg_offset + copy_size, 0,
5413 PAGE_CACHE_SIZE - pg_offset -
5418 flush_dcache_page(page);
5419 } else if (create && PageUptodate(page)) {
5423 free_extent_map(em);
5426 btrfs_release_path(path);
5427 trans = btrfs_join_transaction(root);
5430 return ERR_CAST(trans);
5434 write_extent_buffer(leaf, map + pg_offset, ptr,
5437 btrfs_mark_buffer_dirty(leaf);
5439 set_extent_uptodate(io_tree, em->start,
5440 extent_map_end(em) - 1, NULL, GFP_NOFS);
5443 printk(KERN_ERR "btrfs unknown found_type %d\n", found_type);
5450 em->block_start = EXTENT_MAP_HOLE;
5451 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5453 btrfs_release_path(path);
5454 if (em->start > start || extent_map_end(em) <= start) {
5455 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5456 "[%llu %llu]\n", (unsigned long long)em->start,
5457 (unsigned long long)em->len,
5458 (unsigned long long)start,
5459 (unsigned long long)len);
5465 write_lock(&em_tree->lock);
5466 ret = add_extent_mapping(em_tree, em);
5467 /* it is possible that someone inserted the extent into the tree
5468 * while we had the lock dropped. It is also possible that
5469 * an overlapping map exists in the tree
5471 if (ret == -EEXIST) {
5472 struct extent_map *existing;
5476 existing = lookup_extent_mapping(em_tree, start, len);
5477 if (existing && (existing->start > start ||
5478 existing->start + existing->len <= start)) {
5479 free_extent_map(existing);
5483 existing = lookup_extent_mapping(em_tree, em->start,
5486 err = merge_extent_mapping(em_tree, existing,
5489 free_extent_map(existing);
5491 free_extent_map(em);
5496 free_extent_map(em);
5500 free_extent_map(em);
5505 write_unlock(&em_tree->lock);
5508 trace_btrfs_get_extent(root, em);
5511 btrfs_free_path(path);
5513 ret = btrfs_end_transaction(trans, root);
5518 free_extent_map(em);
5519 return ERR_PTR(err);
5521 BUG_ON(!em); /* Error is always set */
5525 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5526 size_t pg_offset, u64 start, u64 len,
5529 struct extent_map *em;
5530 struct extent_map *hole_em = NULL;
5531 u64 range_start = start;
5537 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5542 * if our em maps to a hole, there might
5543 * actually be delalloc bytes behind it
5545 if (em->block_start != EXTENT_MAP_HOLE)
5551 /* check to see if we've wrapped (len == -1 or similar) */
5560 /* ok, we didn't find anything, lets look for delalloc */
5561 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5562 end, len, EXTENT_DELALLOC, 1);
5563 found_end = range_start + found;
5564 if (found_end < range_start)
5565 found_end = (u64)-1;
5568 * we didn't find anything useful, return
5569 * the original results from get_extent()
5571 if (range_start > end || found_end <= start) {
5577 /* adjust the range_start to make sure it doesn't
5578 * go backwards from the start they passed in
5580 range_start = max(start,range_start);
5581 found = found_end - range_start;
5584 u64 hole_start = start;
5587 em = alloc_extent_map();
5593 * when btrfs_get_extent can't find anything it
5594 * returns one huge hole
5596 * make sure what it found really fits our range, and
5597 * adjust to make sure it is based on the start from
5601 u64 calc_end = extent_map_end(hole_em);
5603 if (calc_end <= start || (hole_em->start > end)) {
5604 free_extent_map(hole_em);
5607 hole_start = max(hole_em->start, start);
5608 hole_len = calc_end - hole_start;
5612 if (hole_em && range_start > hole_start) {
5613 /* our hole starts before our delalloc, so we
5614 * have to return just the parts of the hole
5615 * that go until the delalloc starts
5617 em->len = min(hole_len,
5618 range_start - hole_start);
5619 em->start = hole_start;
5620 em->orig_start = hole_start;
5622 * don't adjust block start at all,
5623 * it is fixed at EXTENT_MAP_HOLE
5625 em->block_start = hole_em->block_start;
5626 em->block_len = hole_len;
5628 em->start = range_start;
5630 em->orig_start = range_start;
5631 em->block_start = EXTENT_MAP_DELALLOC;
5632 em->block_len = found;
5634 } else if (hole_em) {
5639 free_extent_map(hole_em);
5641 free_extent_map(em);
5642 return ERR_PTR(err);
5647 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5648 struct extent_map *em,
5651 struct btrfs_root *root = BTRFS_I(inode)->root;
5652 struct btrfs_trans_handle *trans;
5653 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5654 struct btrfs_key ins;
5657 bool insert = false;
5660 * Ok if the extent map we looked up is a hole and is for the exact
5661 * range we want, there is no reason to allocate a new one, however if
5662 * it is not right then we need to free this one and drop the cache for
5665 if (em->block_start != EXTENT_MAP_HOLE || em->start != start ||
5667 free_extent_map(em);
5670 btrfs_drop_extent_cache(inode, start, start + len - 1, 0);
5673 trans = btrfs_join_transaction(root);
5675 return ERR_CAST(trans);
5677 if (start <= BTRFS_I(inode)->disk_i_size && len < 64 * 1024)
5678 btrfs_add_inode_defrag(trans, inode);
5680 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5682 alloc_hint = get_extent_allocation_hint(inode, start, len);
5683 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5684 alloc_hint, &ins, 1);
5691 em = alloc_extent_map();
5693 em = ERR_PTR(-ENOMEM);
5699 em->orig_start = em->start;
5700 em->len = ins.offset;
5702 em->block_start = ins.objectid;
5703 em->block_len = ins.offset;
5704 em->bdev = root->fs_info->fs_devices->latest_bdev;
5707 * We need to do this because if we're using the original em we searched
5708 * for, we could have EXTENT_FLAG_VACANCY set, and we don't want that.
5711 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5714 write_lock(&em_tree->lock);
5715 ret = add_extent_mapping(em_tree, em);
5716 write_unlock(&em_tree->lock);
5719 btrfs_drop_extent_cache(inode, start, start + em->len - 1, 0);
5722 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5723 ins.offset, ins.offset, 0);
5725 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5729 btrfs_end_transaction(trans, root);
5734 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5735 * block must be cow'd
5737 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5738 struct inode *inode, u64 offset, u64 len)
5740 struct btrfs_path *path;
5742 struct extent_buffer *leaf;
5743 struct btrfs_root *root = BTRFS_I(inode)->root;
5744 struct btrfs_file_extent_item *fi;
5745 struct btrfs_key key;
5753 path = btrfs_alloc_path();
5757 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5762 slot = path->slots[0];
5765 /* can't find the item, must cow */
5772 leaf = path->nodes[0];
5773 btrfs_item_key_to_cpu(leaf, &key, slot);
5774 if (key.objectid != btrfs_ino(inode) ||
5775 key.type != BTRFS_EXTENT_DATA_KEY) {
5776 /* not our file or wrong item type, must cow */
5780 if (key.offset > offset) {
5781 /* Wrong offset, must cow */
5785 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5786 found_type = btrfs_file_extent_type(leaf, fi);
5787 if (found_type != BTRFS_FILE_EXTENT_REG &&
5788 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5789 /* not a regular extent, must cow */
5792 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5793 backref_offset = btrfs_file_extent_offset(leaf, fi);
5795 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5796 if (extent_end < offset + len) {
5797 /* extent doesn't include our full range, must cow */
5801 if (btrfs_extent_readonly(root, disk_bytenr))
5805 * look for other files referencing this extent, if we
5806 * find any we must cow
5808 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5809 key.offset - backref_offset, disk_bytenr))
5813 * adjust disk_bytenr and num_bytes to cover just the bytes
5814 * in this extent we are about to write. If there
5815 * are any csums in that range we have to cow in order
5816 * to keep the csums correct
5818 disk_bytenr += backref_offset;
5819 disk_bytenr += offset - key.offset;
5820 num_bytes = min(offset + len, extent_end) - offset;
5821 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5824 * all of the above have passed, it is safe to overwrite this extent
5829 btrfs_free_path(path);
5833 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
5834 struct extent_state **cached_state, int writing)
5836 struct btrfs_ordered_extent *ordered;
5840 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5843 * We're concerned with the entire range that we're going to be
5844 * doing DIO to, so we need to make sure theres no ordered
5845 * extents in this range.
5847 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5848 lockend - lockstart + 1);
5851 * We need to make sure there are no buffered pages in this
5852 * range either, we could have raced between the invalidate in
5853 * generic_file_direct_write and locking the extent. The
5854 * invalidate needs to happen so that reads after a write do not
5857 if (!ordered && (!writing ||
5858 !test_range_bit(&BTRFS_I(inode)->io_tree,
5859 lockstart, lockend, EXTENT_UPTODATE, 0,
5863 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5864 cached_state, GFP_NOFS);
5867 btrfs_start_ordered_extent(inode, ordered, 1);
5868 btrfs_put_ordered_extent(ordered);
5870 /* Screw you mmap */
5871 ret = filemap_write_and_wait_range(inode->i_mapping,
5878 * If we found a page that couldn't be invalidated just
5879 * fall back to buffered.
5881 ret = invalidate_inode_pages2_range(inode->i_mapping,
5882 lockstart >> PAGE_CACHE_SHIFT,
5883 lockend >> PAGE_CACHE_SHIFT);
5894 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
5895 struct buffer_head *bh_result, int create)
5897 struct extent_map *em;
5898 struct btrfs_root *root = BTRFS_I(inode)->root;
5899 struct extent_state *cached_state = NULL;
5900 u64 start = iblock << inode->i_blkbits;
5901 u64 lockstart, lockend;
5902 u64 len = bh_result->b_size;
5903 struct btrfs_trans_handle *trans;
5904 int unlock_bits = EXTENT_LOCKED;
5908 ret = btrfs_delalloc_reserve_space(inode, len);
5911 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
5913 len = min_t(u64, len, root->sectorsize);
5917 lockend = start + len - 1;
5920 * If this errors out it's because we couldn't invalidate pagecache for
5921 * this range and we need to fallback to buffered.
5923 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
5927 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
5928 lockend, EXTENT_DELALLOC, NULL,
5929 &cached_state, GFP_NOFS);
5934 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
5941 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
5942 * io. INLINE is special, and we could probably kludge it in here, but
5943 * it's still buffered so for safety lets just fall back to the generic
5946 * For COMPRESSED we _have_ to read the entire extent in so we can
5947 * decompress it, so there will be buffering required no matter what we
5948 * do, so go ahead and fallback to buffered.
5950 * We return -ENOTBLK because thats what makes DIO go ahead and go back
5951 * to buffered IO. Don't blame me, this is the price we pay for using
5954 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
5955 em->block_start == EXTENT_MAP_INLINE) {
5956 free_extent_map(em);
5961 /* Just a good old fashioned hole, return */
5962 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
5963 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
5964 free_extent_map(em);
5970 * We don't allocate a new extent in the following cases
5972 * 1) The inode is marked as NODATACOW. In this case we'll just use the
5974 * 2) The extent is marked as PREALLOC. We're good to go here and can
5975 * just use the extent.
5979 len = min(len, em->len - (start - em->start));
5980 lockstart = start + len;
5984 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
5985 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
5986 em->block_start != EXTENT_MAP_HOLE)) {
5991 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5992 type = BTRFS_ORDERED_PREALLOC;
5994 type = BTRFS_ORDERED_NOCOW;
5995 len = min(len, em->len - (start - em->start));
5996 block_start = em->block_start + (start - em->start);
5999 * we're not going to log anything, but we do need
6000 * to make sure the current transaction stays open
6001 * while we look for nocow cross refs
6003 trans = btrfs_join_transaction(root);
6007 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6008 ret = btrfs_add_ordered_extent_dio(inode, start,
6009 block_start, len, len, type);
6010 btrfs_end_transaction(trans, root);
6012 free_extent_map(em);
6017 btrfs_end_transaction(trans, root);
6021 * this will cow the extent, reset the len in case we changed
6024 len = bh_result->b_size;
6025 em = btrfs_new_extent_direct(inode, em, start, len);
6030 len = min(len, em->len - (start - em->start));
6032 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6034 bh_result->b_size = len;
6035 bh_result->b_bdev = em->bdev;
6036 set_buffer_mapped(bh_result);
6038 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6039 set_buffer_new(bh_result);
6042 * Need to update the i_size under the extent lock so buffered
6043 * readers will get the updated i_size when we unlock.
6045 if (start + len > i_size_read(inode))
6046 i_size_write(inode, start + len);
6050 * In the case of write we need to clear and unlock the entire range,
6051 * in the case of read we need to unlock only the end area that we
6052 * aren't using if there is any left over space.
6054 if (lockstart < lockend) {
6055 if (create && len < lockend - lockstart) {
6056 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6057 lockstart + len - 1, unlock_bits, 1, 0,
6058 &cached_state, GFP_NOFS);
6060 * Beside unlock, we also need to cleanup reserved space
6061 * for the left range by attaching EXTENT_DO_ACCOUNTING.
6063 clear_extent_bit(&BTRFS_I(inode)->io_tree,
6064 lockstart + len, lockend,
6065 unlock_bits | EXTENT_DO_ACCOUNTING,
6066 1, 0, NULL, GFP_NOFS);
6068 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6069 lockend, unlock_bits, 1, 0,
6070 &cached_state, GFP_NOFS);
6073 free_extent_state(cached_state);
6076 free_extent_map(em);
6082 unlock_bits |= EXTENT_DO_ACCOUNTING;
6084 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6085 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6089 struct btrfs_dio_private {
6090 struct inode *inode;
6096 /* number of bios pending for this dio */
6097 atomic_t pending_bios;
6102 struct bio *orig_bio;
6105 static void btrfs_endio_direct_read(struct bio *bio, int err)
6107 struct btrfs_dio_private *dip = bio->bi_private;
6108 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6109 struct bio_vec *bvec = bio->bi_io_vec;
6110 struct inode *inode = dip->inode;
6111 struct btrfs_root *root = BTRFS_I(inode)->root;
6114 start = dip->logical_offset;
6116 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6117 struct page *page = bvec->bv_page;
6120 u64 private = ~(u32)0;
6121 unsigned long flags;
6123 if (get_state_private(&BTRFS_I(inode)->io_tree,
6126 local_irq_save(flags);
6127 kaddr = kmap_atomic(page);
6128 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
6129 csum, bvec->bv_len);
6130 btrfs_csum_final(csum, (char *)&csum);
6131 kunmap_atomic(kaddr);
6132 local_irq_restore(flags);
6134 flush_dcache_page(bvec->bv_page);
6135 if (csum != private) {
6137 printk(KERN_ERR "btrfs csum failed ino %llu off"
6138 " %llu csum %u private %u\n",
6139 (unsigned long long)btrfs_ino(inode),
6140 (unsigned long long)start,
6141 csum, (unsigned)private);
6146 start += bvec->bv_len;
6148 } while (bvec <= bvec_end);
6150 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6151 dip->logical_offset + dip->bytes - 1);
6152 bio->bi_private = dip->private;
6156 /* If we had a csum failure make sure to clear the uptodate flag */
6158 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6159 dio_end_io(bio, err);
6162 static void btrfs_endio_direct_write(struct bio *bio, int err)
6164 struct btrfs_dio_private *dip = bio->bi_private;
6165 struct inode *inode = dip->inode;
6166 struct btrfs_root *root = BTRFS_I(inode)->root;
6167 struct btrfs_ordered_extent *ordered = NULL;
6168 u64 ordered_offset = dip->logical_offset;
6169 u64 ordered_bytes = dip->bytes;
6175 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6177 ordered_bytes, !err);
6181 ordered->work.func = finish_ordered_fn;
6182 ordered->work.flags = 0;
6183 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6187 * our bio might span multiple ordered extents. If we haven't
6188 * completed the accounting for the whole dio, go back and try again
6190 if (ordered_offset < dip->logical_offset + dip->bytes) {
6191 ordered_bytes = dip->logical_offset + dip->bytes -
6197 bio->bi_private = dip->private;
6201 /* If we had an error make sure to clear the uptodate flag */
6203 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6204 dio_end_io(bio, err);
6207 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6208 struct bio *bio, int mirror_num,
6209 unsigned long bio_flags, u64 offset)
6212 struct btrfs_root *root = BTRFS_I(inode)->root;
6213 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6214 BUG_ON(ret); /* -ENOMEM */
6218 static void btrfs_end_dio_bio(struct bio *bio, int err)
6220 struct btrfs_dio_private *dip = bio->bi_private;
6223 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6224 "sector %#Lx len %u err no %d\n",
6225 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6226 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6230 * before atomic variable goto zero, we must make sure
6231 * dip->errors is perceived to be set.
6233 smp_mb__before_atomic_dec();
6236 /* if there are more bios still pending for this dio, just exit */
6237 if (!atomic_dec_and_test(&dip->pending_bios))
6241 bio_io_error(dip->orig_bio);
6243 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
6244 bio_endio(dip->orig_bio, 0);
6250 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6251 u64 first_sector, gfp_t gfp_flags)
6253 int nr_vecs = bio_get_nr_vecs(bdev);
6254 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6257 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6258 int rw, u64 file_offset, int skip_sum,
6261 int write = rw & REQ_WRITE;
6262 struct btrfs_root *root = BTRFS_I(inode)->root;
6268 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6276 if (write && async_submit) {
6277 ret = btrfs_wq_submit_bio(root->fs_info,
6278 inode, rw, bio, 0, 0,
6280 __btrfs_submit_bio_start_direct_io,
6281 __btrfs_submit_bio_done);
6285 * If we aren't doing async submit, calculate the csum of the
6288 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6291 } else if (!skip_sum) {
6292 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
6298 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6304 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6307 struct inode *inode = dip->inode;
6308 struct btrfs_root *root = BTRFS_I(inode)->root;
6309 struct btrfs_mapping_tree *map_tree = &root->fs_info->mapping_tree;
6311 struct bio *orig_bio = dip->orig_bio;
6312 struct bio_vec *bvec = orig_bio->bi_io_vec;
6313 u64 start_sector = orig_bio->bi_sector;
6314 u64 file_offset = dip->logical_offset;
6319 int async_submit = 0;
6321 map_length = orig_bio->bi_size;
6322 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6323 &map_length, NULL, 0);
6329 if (map_length >= orig_bio->bi_size) {
6335 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6338 bio->bi_private = dip;
6339 bio->bi_end_io = btrfs_end_dio_bio;
6340 atomic_inc(&dip->pending_bios);
6342 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6343 if (unlikely(map_length < submit_len + bvec->bv_len ||
6344 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6345 bvec->bv_offset) < bvec->bv_len)) {
6347 * inc the count before we submit the bio so
6348 * we know the end IO handler won't happen before
6349 * we inc the count. Otherwise, the dip might get freed
6350 * before we're done setting it up
6352 atomic_inc(&dip->pending_bios);
6353 ret = __btrfs_submit_dio_bio(bio, inode, rw,
6354 file_offset, skip_sum,
6358 atomic_dec(&dip->pending_bios);
6362 start_sector += submit_len >> 9;
6363 file_offset += submit_len;
6368 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6369 start_sector, GFP_NOFS);
6372 bio->bi_private = dip;
6373 bio->bi_end_io = btrfs_end_dio_bio;
6375 map_length = orig_bio->bi_size;
6376 ret = btrfs_map_block(map_tree, READ, start_sector << 9,
6377 &map_length, NULL, 0);
6383 submit_len += bvec->bv_len;
6390 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6399 * before atomic variable goto zero, we must
6400 * make sure dip->errors is perceived to be set.
6402 smp_mb__before_atomic_dec();
6403 if (atomic_dec_and_test(&dip->pending_bios))
6404 bio_io_error(dip->orig_bio);
6406 /* bio_end_io() will handle error, so we needn't return it */
6410 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6413 struct btrfs_root *root = BTRFS_I(inode)->root;
6414 struct btrfs_dio_private *dip;
6415 struct bio_vec *bvec = bio->bi_io_vec;
6417 int write = rw & REQ_WRITE;
6420 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6422 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6428 dip->private = bio->bi_private;
6430 dip->logical_offset = file_offset;
6434 dip->bytes += bvec->bv_len;
6436 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6438 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6439 bio->bi_private = dip;
6441 dip->orig_bio = bio;
6442 atomic_set(&dip->pending_bios, 0);
6445 bio->bi_end_io = btrfs_endio_direct_write;
6447 bio->bi_end_io = btrfs_endio_direct_read;
6449 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6454 * If this is a write, we need to clean up the reserved space and kill
6455 * the ordered extent.
6458 struct btrfs_ordered_extent *ordered;
6459 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6460 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6461 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6462 btrfs_free_reserved_extent(root, ordered->start,
6464 btrfs_put_ordered_extent(ordered);
6465 btrfs_put_ordered_extent(ordered);
6467 bio_endio(bio, ret);
6470 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6471 const struct iovec *iov, loff_t offset,
6472 unsigned long nr_segs)
6478 unsigned blocksize_mask = root->sectorsize - 1;
6479 ssize_t retval = -EINVAL;
6480 loff_t end = offset;
6482 if (offset & blocksize_mask)
6485 /* Check the memory alignment. Blocks cannot straddle pages */
6486 for (seg = 0; seg < nr_segs; seg++) {
6487 addr = (unsigned long)iov[seg].iov_base;
6488 size = iov[seg].iov_len;
6490 if ((addr & blocksize_mask) || (size & blocksize_mask))
6493 /* If this is a write we don't need to check anymore */
6498 * Check to make sure we don't have duplicate iov_base's in this
6499 * iovec, if so return EINVAL, otherwise we'll get csum errors
6500 * when reading back.
6502 for (i = seg + 1; i < nr_segs; i++) {
6503 if (iov[seg].iov_base == iov[i].iov_base)
6512 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6513 const struct iovec *iov, loff_t offset,
6514 unsigned long nr_segs)
6516 struct file *file = iocb->ki_filp;
6517 struct inode *inode = file->f_mapping->host;
6519 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6523 return __blockdev_direct_IO(rw, iocb, inode,
6524 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6525 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6526 btrfs_submit_direct, 0);
6529 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6530 __u64 start, __u64 len)
6532 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6535 int btrfs_readpage(struct file *file, struct page *page)
6537 struct extent_io_tree *tree;
6538 tree = &BTRFS_I(page->mapping->host)->io_tree;
6539 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6542 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6544 struct extent_io_tree *tree;
6547 if (current->flags & PF_MEMALLOC) {
6548 redirty_page_for_writepage(wbc, page);
6552 tree = &BTRFS_I(page->mapping->host)->io_tree;
6553 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6556 int btrfs_writepages(struct address_space *mapping,
6557 struct writeback_control *wbc)
6559 struct extent_io_tree *tree;
6561 tree = &BTRFS_I(mapping->host)->io_tree;
6562 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6566 btrfs_readpages(struct file *file, struct address_space *mapping,
6567 struct list_head *pages, unsigned nr_pages)
6569 struct extent_io_tree *tree;
6570 tree = &BTRFS_I(mapping->host)->io_tree;
6571 return extent_readpages(tree, mapping, pages, nr_pages,
6574 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6576 struct extent_io_tree *tree;
6577 struct extent_map_tree *map;
6580 tree = &BTRFS_I(page->mapping->host)->io_tree;
6581 map = &BTRFS_I(page->mapping->host)->extent_tree;
6582 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6584 ClearPagePrivate(page);
6585 set_page_private(page, 0);
6586 page_cache_release(page);
6591 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6593 if (PageWriteback(page) || PageDirty(page))
6595 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6598 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6600 struct inode *inode = page->mapping->host;
6601 struct extent_io_tree *tree;
6602 struct btrfs_ordered_extent *ordered;
6603 struct extent_state *cached_state = NULL;
6604 u64 page_start = page_offset(page);
6605 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6608 * we have the page locked, so new writeback can't start,
6609 * and the dirty bit won't be cleared while we are here.
6611 * Wait for IO on this page so that we can safely clear
6612 * the PagePrivate2 bit and do ordered accounting
6614 wait_on_page_writeback(page);
6616 tree = &BTRFS_I(inode)->io_tree;
6618 btrfs_releasepage(page, GFP_NOFS);
6621 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6622 ordered = btrfs_lookup_ordered_extent(inode,
6626 * IO on this page will never be started, so we need
6627 * to account for any ordered extents now
6629 clear_extent_bit(tree, page_start, page_end,
6630 EXTENT_DIRTY | EXTENT_DELALLOC |
6631 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING, 1, 0,
6632 &cached_state, GFP_NOFS);
6634 * whoever cleared the private bit is responsible
6635 * for the finish_ordered_io
6637 if (TestClearPagePrivate2(page) &&
6638 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
6639 PAGE_CACHE_SIZE, 1)) {
6640 btrfs_finish_ordered_io(ordered);
6642 btrfs_put_ordered_extent(ordered);
6643 cached_state = NULL;
6644 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6646 clear_extent_bit(tree, page_start, page_end,
6647 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6648 EXTENT_DO_ACCOUNTING, 1, 1, &cached_state, GFP_NOFS);
6649 __btrfs_releasepage(page, GFP_NOFS);
6651 ClearPageChecked(page);
6652 if (PagePrivate(page)) {
6653 ClearPagePrivate(page);
6654 set_page_private(page, 0);
6655 page_cache_release(page);
6660 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6661 * called from a page fault handler when a page is first dirtied. Hence we must
6662 * be careful to check for EOF conditions here. We set the page up correctly
6663 * for a written page which means we get ENOSPC checking when writing into
6664 * holes and correct delalloc and unwritten extent mapping on filesystems that
6665 * support these features.
6667 * We are not allowed to take the i_mutex here so we have to play games to
6668 * protect against truncate races as the page could now be beyond EOF. Because
6669 * vmtruncate() writes the inode size before removing pages, once we have the
6670 * page lock we can determine safely if the page is beyond EOF. If it is not
6671 * beyond EOF, then the page is guaranteed safe against truncation until we
6674 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6676 struct page *page = vmf->page;
6677 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6678 struct btrfs_root *root = BTRFS_I(inode)->root;
6679 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6680 struct btrfs_ordered_extent *ordered;
6681 struct extent_state *cached_state = NULL;
6683 unsigned long zero_start;
6690 sb_start_pagefault(inode->i_sb);
6691 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6693 ret = file_update_time(vma->vm_file);
6699 else /* -ENOSPC, -EIO, etc */
6700 ret = VM_FAULT_SIGBUS;
6706 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6709 size = i_size_read(inode);
6710 page_start = page_offset(page);
6711 page_end = page_start + PAGE_CACHE_SIZE - 1;
6713 if ((page->mapping != inode->i_mapping) ||
6714 (page_start >= size)) {
6715 /* page got truncated out from underneath us */
6718 wait_on_page_writeback(page);
6720 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
6721 set_page_extent_mapped(page);
6724 * we can't set the delalloc bits if there are pending ordered
6725 * extents. Drop our locks and wait for them to finish
6727 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6729 unlock_extent_cached(io_tree, page_start, page_end,
6730 &cached_state, GFP_NOFS);
6732 btrfs_start_ordered_extent(inode, ordered, 1);
6733 btrfs_put_ordered_extent(ordered);
6738 * XXX - page_mkwrite gets called every time the page is dirtied, even
6739 * if it was already dirty, so for space accounting reasons we need to
6740 * clear any delalloc bits for the range we are fixing to save. There
6741 * is probably a better way to do this, but for now keep consistent with
6742 * prepare_pages in the normal write path.
6744 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6745 EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING,
6746 0, 0, &cached_state, GFP_NOFS);
6748 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6751 unlock_extent_cached(io_tree, page_start, page_end,
6752 &cached_state, GFP_NOFS);
6753 ret = VM_FAULT_SIGBUS;
6758 /* page is wholly or partially inside EOF */
6759 if (page_start + PAGE_CACHE_SIZE > size)
6760 zero_start = size & ~PAGE_CACHE_MASK;
6762 zero_start = PAGE_CACHE_SIZE;
6764 if (zero_start != PAGE_CACHE_SIZE) {
6766 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6767 flush_dcache_page(page);
6770 ClearPageChecked(page);
6771 set_page_dirty(page);
6772 SetPageUptodate(page);
6774 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6775 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6777 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6781 sb_end_pagefault(inode->i_sb);
6782 return VM_FAULT_LOCKED;
6786 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6788 sb_end_pagefault(inode->i_sb);
6792 static int btrfs_truncate(struct inode *inode)
6794 struct btrfs_root *root = BTRFS_I(inode)->root;
6795 struct btrfs_block_rsv *rsv;
6798 struct btrfs_trans_handle *trans;
6800 u64 mask = root->sectorsize - 1;
6801 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6803 ret = btrfs_truncate_page(inode->i_mapping, inode->i_size);
6807 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6808 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6811 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6812 * 3 things going on here
6814 * 1) We need to reserve space for our orphan item and the space to
6815 * delete our orphan item. Lord knows we don't want to have a dangling
6816 * orphan item because we didn't reserve space to remove it.
6818 * 2) We need to reserve space to update our inode.
6820 * 3) We need to have something to cache all the space that is going to
6821 * be free'd up by the truncate operation, but also have some slack
6822 * space reserved in case it uses space during the truncate (thank you
6823 * very much snapshotting).
6825 * And we need these to all be seperate. The fact is we can use alot of
6826 * space doing the truncate, and we have no earthly idea how much space
6827 * we will use, so we need the truncate reservation to be seperate so it
6828 * doesn't end up using space reserved for updating the inode or
6829 * removing the orphan item. We also need to be able to stop the
6830 * transaction and start a new one, which means we need to be able to
6831 * update the inode several times, and we have no idea of knowing how
6832 * many times that will be, so we can't just reserve 1 item for the
6833 * entirety of the opration, so that has to be done seperately as well.
6834 * Then there is the orphan item, which does indeed need to be held on
6835 * to for the whole operation, and we need nobody to touch this reserved
6836 * space except the orphan code.
6838 * So that leaves us with
6840 * 1) root->orphan_block_rsv - for the orphan deletion.
6841 * 2) rsv - for the truncate reservation, which we will steal from the
6842 * transaction reservation.
6843 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6844 * updating the inode.
6846 rsv = btrfs_alloc_block_rsv(root);
6849 rsv->size = min_size;
6853 * 1 for the truncate slack space
6854 * 1 for the orphan item we're going to add
6855 * 1 for the orphan item deletion
6856 * 1 for updating the inode.
6858 trans = btrfs_start_transaction(root, 4);
6859 if (IS_ERR(trans)) {
6860 err = PTR_ERR(trans);
6864 /* Migrate the slack space for the truncate to our reserve */
6865 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
6869 ret = btrfs_orphan_add(trans, inode);
6871 btrfs_end_transaction(trans, root);
6876 * setattr is responsible for setting the ordered_data_close flag,
6877 * but that is only tested during the last file release. That
6878 * could happen well after the next commit, leaving a great big
6879 * window where new writes may get lost if someone chooses to write
6880 * to this file after truncating to zero
6882 * The inode doesn't have any dirty data here, and so if we commit
6883 * this is a noop. If someone immediately starts writing to the inode
6884 * it is very likely we'll catch some of their writes in this
6885 * transaction, and the commit will find this file on the ordered
6886 * data list with good things to send down.
6888 * This is a best effort solution, there is still a window where
6889 * using truncate to replace the contents of the file will
6890 * end up with a zero length file after a crash.
6892 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
6893 &BTRFS_I(inode)->runtime_flags))
6894 btrfs_add_ordered_operation(trans, root, inode);
6897 * So if we truncate and then write and fsync we normally would just
6898 * write the extents that changed, which is a problem if we need to
6899 * first truncate that entire inode. So set this flag so we write out
6900 * all of the extents in the inode to the sync log so we're completely
6903 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6904 trans->block_rsv = rsv;
6907 ret = btrfs_truncate_inode_items(trans, root, inode,
6909 BTRFS_EXTENT_DATA_KEY);
6910 if (ret != -ENOSPC) {
6915 trans->block_rsv = &root->fs_info->trans_block_rsv;
6916 ret = btrfs_update_inode(trans, root, inode);
6922 nr = trans->blocks_used;
6923 btrfs_end_transaction(trans, root);
6924 btrfs_btree_balance_dirty(root, nr);
6926 trans = btrfs_start_transaction(root, 2);
6927 if (IS_ERR(trans)) {
6928 ret = err = PTR_ERR(trans);
6933 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
6935 BUG_ON(ret); /* shouldn't happen */
6936 trans->block_rsv = rsv;
6939 if (ret == 0 && inode->i_nlink > 0) {
6940 trans->block_rsv = root->orphan_block_rsv;
6941 ret = btrfs_orphan_del(trans, inode);
6944 } else if (ret && inode->i_nlink > 0) {
6946 * Failed to do the truncate, remove us from the in memory
6949 ret = btrfs_orphan_del(NULL, inode);
6953 trans->block_rsv = &root->fs_info->trans_block_rsv;
6954 ret = btrfs_update_inode(trans, root, inode);
6958 nr = trans->blocks_used;
6959 ret = btrfs_end_transaction(trans, root);
6960 btrfs_btree_balance_dirty(root, nr);
6964 btrfs_free_block_rsv(root, rsv);
6973 * create a new subvolume directory/inode (helper for the ioctl).
6975 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
6976 struct btrfs_root *new_root, u64 new_dirid)
6978 struct inode *inode;
6982 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
6983 new_dirid, new_dirid,
6984 S_IFDIR | (~current_umask() & S_IRWXUGO),
6987 return PTR_ERR(inode);
6988 inode->i_op = &btrfs_dir_inode_operations;
6989 inode->i_fop = &btrfs_dir_file_operations;
6991 set_nlink(inode, 1);
6992 btrfs_i_size_write(inode, 0);
6994 err = btrfs_update_inode(trans, new_root, inode);
7000 struct inode *btrfs_alloc_inode(struct super_block *sb)
7002 struct btrfs_inode *ei;
7003 struct inode *inode;
7005 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7012 ei->last_sub_trans = 0;
7013 ei->logged_trans = 0;
7014 ei->delalloc_bytes = 0;
7015 ei->disk_i_size = 0;
7018 ei->index_cnt = (u64)-1;
7019 ei->last_unlink_trans = 0;
7021 spin_lock_init(&ei->lock);
7022 ei->outstanding_extents = 0;
7023 ei->reserved_extents = 0;
7025 ei->runtime_flags = 0;
7026 ei->force_compress = BTRFS_COMPRESS_NONE;
7028 ei->delayed_node = NULL;
7030 inode = &ei->vfs_inode;
7031 extent_map_tree_init(&ei->extent_tree);
7032 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7033 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7034 ei->io_tree.track_uptodate = 1;
7035 ei->io_failure_tree.track_uptodate = 1;
7036 mutex_init(&ei->log_mutex);
7037 mutex_init(&ei->delalloc_mutex);
7038 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7039 INIT_LIST_HEAD(&ei->delalloc_inodes);
7040 INIT_LIST_HEAD(&ei->ordered_operations);
7041 RB_CLEAR_NODE(&ei->rb_node);
7046 static void btrfs_i_callback(struct rcu_head *head)
7048 struct inode *inode = container_of(head, struct inode, i_rcu);
7049 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7052 void btrfs_destroy_inode(struct inode *inode)
7054 struct btrfs_ordered_extent *ordered;
7055 struct btrfs_root *root = BTRFS_I(inode)->root;
7057 WARN_ON(!hlist_empty(&inode->i_dentry));
7058 WARN_ON(inode->i_data.nrpages);
7059 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7060 WARN_ON(BTRFS_I(inode)->reserved_extents);
7061 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7062 WARN_ON(BTRFS_I(inode)->csum_bytes);
7065 * This can happen where we create an inode, but somebody else also
7066 * created the same inode and we need to destroy the one we already
7073 * Make sure we're properly removed from the ordered operation
7077 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7078 spin_lock(&root->fs_info->ordered_extent_lock);
7079 list_del_init(&BTRFS_I(inode)->ordered_operations);
7080 spin_unlock(&root->fs_info->ordered_extent_lock);
7083 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7084 &BTRFS_I(inode)->runtime_flags)) {
7085 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
7086 (unsigned long long)btrfs_ino(inode));
7087 atomic_dec(&root->orphan_inodes);
7091 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7095 printk(KERN_ERR "btrfs found ordered "
7096 "extent %llu %llu on inode cleanup\n",
7097 (unsigned long long)ordered->file_offset,
7098 (unsigned long long)ordered->len);
7099 btrfs_remove_ordered_extent(inode, ordered);
7100 btrfs_put_ordered_extent(ordered);
7101 btrfs_put_ordered_extent(ordered);
7104 inode_tree_del(inode);
7105 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7107 btrfs_remove_delayed_node(inode);
7108 call_rcu(&inode->i_rcu, btrfs_i_callback);
7111 int btrfs_drop_inode(struct inode *inode)
7113 struct btrfs_root *root = BTRFS_I(inode)->root;
7115 if (btrfs_root_refs(&root->root_item) == 0 &&
7116 !btrfs_is_free_space_inode(inode))
7119 return generic_drop_inode(inode);
7122 static void init_once(void *foo)
7124 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7126 inode_init_once(&ei->vfs_inode);
7129 void btrfs_destroy_cachep(void)
7131 if (btrfs_inode_cachep)
7132 kmem_cache_destroy(btrfs_inode_cachep);
7133 if (btrfs_trans_handle_cachep)
7134 kmem_cache_destroy(btrfs_trans_handle_cachep);
7135 if (btrfs_transaction_cachep)
7136 kmem_cache_destroy(btrfs_transaction_cachep);
7137 if (btrfs_path_cachep)
7138 kmem_cache_destroy(btrfs_path_cachep);
7139 if (btrfs_free_space_cachep)
7140 kmem_cache_destroy(btrfs_free_space_cachep);
7143 int btrfs_init_cachep(void)
7145 btrfs_inode_cachep = kmem_cache_create("btrfs_inode_cache",
7146 sizeof(struct btrfs_inode), 0,
7147 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7148 if (!btrfs_inode_cachep)
7151 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle_cache",
7152 sizeof(struct btrfs_trans_handle), 0,
7153 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7154 if (!btrfs_trans_handle_cachep)
7157 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction_cache",
7158 sizeof(struct btrfs_transaction), 0,
7159 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7160 if (!btrfs_transaction_cachep)
7163 btrfs_path_cachep = kmem_cache_create("btrfs_path_cache",
7164 sizeof(struct btrfs_path), 0,
7165 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7166 if (!btrfs_path_cachep)
7169 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space_cache",
7170 sizeof(struct btrfs_free_space), 0,
7171 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7172 if (!btrfs_free_space_cachep)
7177 btrfs_destroy_cachep();
7181 static int btrfs_getattr(struct vfsmount *mnt,
7182 struct dentry *dentry, struct kstat *stat)
7184 struct inode *inode = dentry->d_inode;
7185 u32 blocksize = inode->i_sb->s_blocksize;
7187 generic_fillattr(inode, stat);
7188 stat->dev = BTRFS_I(inode)->root->anon_dev;
7189 stat->blksize = PAGE_CACHE_SIZE;
7190 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7191 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
7196 * If a file is moved, it will inherit the cow and compression flags of the new
7199 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7201 struct btrfs_inode *b_dir = BTRFS_I(dir);
7202 struct btrfs_inode *b_inode = BTRFS_I(inode);
7204 if (b_dir->flags & BTRFS_INODE_NODATACOW)
7205 b_inode->flags |= BTRFS_INODE_NODATACOW;
7207 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7209 if (b_dir->flags & BTRFS_INODE_COMPRESS) {
7210 b_inode->flags |= BTRFS_INODE_COMPRESS;
7211 b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
7213 b_inode->flags &= ~(BTRFS_INODE_COMPRESS |
7214 BTRFS_INODE_NOCOMPRESS);
7218 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7219 struct inode *new_dir, struct dentry *new_dentry)
7221 struct btrfs_trans_handle *trans;
7222 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7223 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7224 struct inode *new_inode = new_dentry->d_inode;
7225 struct inode *old_inode = old_dentry->d_inode;
7226 struct timespec ctime = CURRENT_TIME;
7230 u64 old_ino = btrfs_ino(old_inode);
7232 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7235 /* we only allow rename subvolume link between subvolumes */
7236 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7239 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7240 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7243 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7244 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7247 * we're using rename to replace one file with another.
7248 * and the replacement file is large. Start IO on it now so
7249 * we don't add too much work to the end of the transaction
7251 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7252 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7253 filemap_flush(old_inode->i_mapping);
7255 /* close the racy window with snapshot create/destroy ioctl */
7256 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7257 down_read(&root->fs_info->subvol_sem);
7259 * We want to reserve the absolute worst case amount of items. So if
7260 * both inodes are subvols and we need to unlink them then that would
7261 * require 4 item modifications, but if they are both normal inodes it
7262 * would require 5 item modifications, so we'll assume their normal
7263 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7264 * should cover the worst case number of items we'll modify.
7266 trans = btrfs_start_transaction(root, 20);
7267 if (IS_ERR(trans)) {
7268 ret = PTR_ERR(trans);
7273 btrfs_record_root_in_trans(trans, dest);
7275 ret = btrfs_set_inode_index(new_dir, &index);
7279 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7280 /* force full log commit if subvolume involved. */
7281 root->fs_info->last_trans_log_full_commit = trans->transid;
7283 ret = btrfs_insert_inode_ref(trans, dest,
7284 new_dentry->d_name.name,
7285 new_dentry->d_name.len,
7287 btrfs_ino(new_dir), index);
7291 * this is an ugly little race, but the rename is required
7292 * to make sure that if we crash, the inode is either at the
7293 * old name or the new one. pinning the log transaction lets
7294 * us make sure we don't allow a log commit to come in after
7295 * we unlink the name but before we add the new name back in.
7297 btrfs_pin_log_trans(root);
7300 * make sure the inode gets flushed if it is replacing
7303 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7304 btrfs_add_ordered_operation(trans, root, old_inode);
7306 inode_inc_iversion(old_dir);
7307 inode_inc_iversion(new_dir);
7308 inode_inc_iversion(old_inode);
7309 old_dir->i_ctime = old_dir->i_mtime = ctime;
7310 new_dir->i_ctime = new_dir->i_mtime = ctime;
7311 old_inode->i_ctime = ctime;
7313 if (old_dentry->d_parent != new_dentry->d_parent)
7314 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7316 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7317 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7318 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7319 old_dentry->d_name.name,
7320 old_dentry->d_name.len);
7322 ret = __btrfs_unlink_inode(trans, root, old_dir,
7323 old_dentry->d_inode,
7324 old_dentry->d_name.name,
7325 old_dentry->d_name.len);
7327 ret = btrfs_update_inode(trans, root, old_inode);
7330 btrfs_abort_transaction(trans, root, ret);
7335 inode_inc_iversion(new_inode);
7336 new_inode->i_ctime = CURRENT_TIME;
7337 if (unlikely(btrfs_ino(new_inode) ==
7338 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7339 root_objectid = BTRFS_I(new_inode)->location.objectid;
7340 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7342 new_dentry->d_name.name,
7343 new_dentry->d_name.len);
7344 BUG_ON(new_inode->i_nlink == 0);
7346 ret = btrfs_unlink_inode(trans, dest, new_dir,
7347 new_dentry->d_inode,
7348 new_dentry->d_name.name,
7349 new_dentry->d_name.len);
7351 if (!ret && new_inode->i_nlink == 0) {
7352 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7356 btrfs_abort_transaction(trans, root, ret);
7361 fixup_inode_flags(new_dir, old_inode);
7363 ret = btrfs_add_link(trans, new_dir, old_inode,
7364 new_dentry->d_name.name,
7365 new_dentry->d_name.len, 0, index);
7367 btrfs_abort_transaction(trans, root, ret);
7371 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7372 struct dentry *parent = new_dentry->d_parent;
7373 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7374 btrfs_end_log_trans(root);
7377 btrfs_end_transaction(trans, root);
7379 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7380 up_read(&root->fs_info->subvol_sem);
7386 * some fairly slow code that needs optimization. This walks the list
7387 * of all the inodes with pending delalloc and forces them to disk.
7389 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7391 struct list_head *head = &root->fs_info->delalloc_inodes;
7392 struct btrfs_inode *binode;
7393 struct inode *inode;
7395 if (root->fs_info->sb->s_flags & MS_RDONLY)
7398 spin_lock(&root->fs_info->delalloc_lock);
7399 while (!list_empty(head)) {
7400 binode = list_entry(head->next, struct btrfs_inode,
7402 inode = igrab(&binode->vfs_inode);
7404 list_del_init(&binode->delalloc_inodes);
7405 spin_unlock(&root->fs_info->delalloc_lock);
7407 filemap_flush(inode->i_mapping);
7409 btrfs_add_delayed_iput(inode);
7414 spin_lock(&root->fs_info->delalloc_lock);
7416 spin_unlock(&root->fs_info->delalloc_lock);
7418 /* the filemap_flush will queue IO into the worker threads, but
7419 * we have to make sure the IO is actually started and that
7420 * ordered extents get created before we return
7422 atomic_inc(&root->fs_info->async_submit_draining);
7423 while (atomic_read(&root->fs_info->nr_async_submits) ||
7424 atomic_read(&root->fs_info->async_delalloc_pages)) {
7425 wait_event(root->fs_info->async_submit_wait,
7426 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7427 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7429 atomic_dec(&root->fs_info->async_submit_draining);
7433 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7434 const char *symname)
7436 struct btrfs_trans_handle *trans;
7437 struct btrfs_root *root = BTRFS_I(dir)->root;
7438 struct btrfs_path *path;
7439 struct btrfs_key key;
7440 struct inode *inode = NULL;
7448 struct btrfs_file_extent_item *ei;
7449 struct extent_buffer *leaf;
7450 unsigned long nr = 0;
7452 name_len = strlen(symname) + 1;
7453 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7454 return -ENAMETOOLONG;
7457 * 2 items for inode item and ref
7458 * 2 items for dir items
7459 * 1 item for xattr if selinux is on
7461 trans = btrfs_start_transaction(root, 5);
7463 return PTR_ERR(trans);
7465 err = btrfs_find_free_ino(root, &objectid);
7469 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7470 dentry->d_name.len, btrfs_ino(dir), objectid,
7471 S_IFLNK|S_IRWXUGO, &index);
7472 if (IS_ERR(inode)) {
7473 err = PTR_ERR(inode);
7477 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7484 * If the active LSM wants to access the inode during
7485 * d_instantiate it needs these. Smack checks to see
7486 * if the filesystem supports xattrs by looking at the
7489 inode->i_fop = &btrfs_file_operations;
7490 inode->i_op = &btrfs_file_inode_operations;
7492 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7496 inode->i_mapping->a_ops = &btrfs_aops;
7497 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7498 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7503 path = btrfs_alloc_path();
7509 key.objectid = btrfs_ino(inode);
7511 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7512 datasize = btrfs_file_extent_calc_inline_size(name_len);
7513 err = btrfs_insert_empty_item(trans, root, path, &key,
7517 btrfs_free_path(path);
7520 leaf = path->nodes[0];
7521 ei = btrfs_item_ptr(leaf, path->slots[0],
7522 struct btrfs_file_extent_item);
7523 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7524 btrfs_set_file_extent_type(leaf, ei,
7525 BTRFS_FILE_EXTENT_INLINE);
7526 btrfs_set_file_extent_encryption(leaf, ei, 0);
7527 btrfs_set_file_extent_compression(leaf, ei, 0);
7528 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7529 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7531 ptr = btrfs_file_extent_inline_start(ei);
7532 write_extent_buffer(leaf, symname, ptr, name_len);
7533 btrfs_mark_buffer_dirty(leaf);
7534 btrfs_free_path(path);
7536 inode->i_op = &btrfs_symlink_inode_operations;
7537 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7538 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7539 inode_set_bytes(inode, name_len);
7540 btrfs_i_size_write(inode, name_len - 1);
7541 err = btrfs_update_inode(trans, root, inode);
7547 d_instantiate(dentry, inode);
7548 nr = trans->blocks_used;
7549 btrfs_end_transaction(trans, root);
7551 inode_dec_link_count(inode);
7554 btrfs_btree_balance_dirty(root, nr);
7558 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7559 u64 start, u64 num_bytes, u64 min_size,
7560 loff_t actual_len, u64 *alloc_hint,
7561 struct btrfs_trans_handle *trans)
7563 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7564 struct extent_map *em;
7565 struct btrfs_root *root = BTRFS_I(inode)->root;
7566 struct btrfs_key ins;
7567 u64 cur_offset = start;
7570 bool own_trans = true;
7574 while (num_bytes > 0) {
7576 trans = btrfs_start_transaction(root, 3);
7577 if (IS_ERR(trans)) {
7578 ret = PTR_ERR(trans);
7583 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7584 0, *alloc_hint, &ins, 1);
7587 btrfs_end_transaction(trans, root);
7591 ret = insert_reserved_file_extent(trans, inode,
7592 cur_offset, ins.objectid,
7593 ins.offset, ins.offset,
7594 ins.offset, 0, 0, 0,
7595 BTRFS_FILE_EXTENT_PREALLOC);
7597 btrfs_abort_transaction(trans, root, ret);
7599 btrfs_end_transaction(trans, root);
7602 btrfs_drop_extent_cache(inode, cur_offset,
7603 cur_offset + ins.offset -1, 0);
7605 em = alloc_extent_map();
7607 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7608 &BTRFS_I(inode)->runtime_flags);
7612 em->start = cur_offset;
7613 em->orig_start = cur_offset;
7614 em->len = ins.offset;
7615 em->block_start = ins.objectid;
7616 em->block_len = ins.offset;
7617 em->bdev = root->fs_info->fs_devices->latest_bdev;
7618 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7619 em->generation = trans->transid;
7622 write_lock(&em_tree->lock);
7623 ret = add_extent_mapping(em_tree, em);
7625 list_move(&em->list,
7626 &em_tree->modified_extents);
7627 write_unlock(&em_tree->lock);
7630 btrfs_drop_extent_cache(inode, cur_offset,
7631 cur_offset + ins.offset - 1,
7634 free_extent_map(em);
7636 num_bytes -= ins.offset;
7637 cur_offset += ins.offset;
7638 *alloc_hint = ins.objectid + ins.offset;
7640 inode_inc_iversion(inode);
7641 inode->i_ctime = CURRENT_TIME;
7642 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7643 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7644 (actual_len > inode->i_size) &&
7645 (cur_offset > inode->i_size)) {
7646 if (cur_offset > actual_len)
7647 i_size = actual_len;
7649 i_size = cur_offset;
7650 i_size_write(inode, i_size);
7651 btrfs_ordered_update_i_size(inode, i_size, NULL);
7654 ret = btrfs_update_inode(trans, root, inode);
7657 btrfs_abort_transaction(trans, root, ret);
7659 btrfs_end_transaction(trans, root);
7664 btrfs_end_transaction(trans, root);
7669 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7670 u64 start, u64 num_bytes, u64 min_size,
7671 loff_t actual_len, u64 *alloc_hint)
7673 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7674 min_size, actual_len, alloc_hint,
7678 int btrfs_prealloc_file_range_trans(struct inode *inode,
7679 struct btrfs_trans_handle *trans, int mode,
7680 u64 start, u64 num_bytes, u64 min_size,
7681 loff_t actual_len, u64 *alloc_hint)
7683 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7684 min_size, actual_len, alloc_hint, trans);
7687 static int btrfs_set_page_dirty(struct page *page)
7689 return __set_page_dirty_nobuffers(page);
7692 static int btrfs_permission(struct inode *inode, int mask)
7694 struct btrfs_root *root = BTRFS_I(inode)->root;
7695 umode_t mode = inode->i_mode;
7697 if (mask & MAY_WRITE &&
7698 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7699 if (btrfs_root_readonly(root))
7701 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7704 return generic_permission(inode, mask);
7707 static const struct inode_operations btrfs_dir_inode_operations = {
7708 .getattr = btrfs_getattr,
7709 .lookup = btrfs_lookup,
7710 .create = btrfs_create,
7711 .unlink = btrfs_unlink,
7713 .mkdir = btrfs_mkdir,
7714 .rmdir = btrfs_rmdir,
7715 .rename = btrfs_rename,
7716 .symlink = btrfs_symlink,
7717 .setattr = btrfs_setattr,
7718 .mknod = btrfs_mknod,
7719 .setxattr = btrfs_setxattr,
7720 .getxattr = btrfs_getxattr,
7721 .listxattr = btrfs_listxattr,
7722 .removexattr = btrfs_removexattr,
7723 .permission = btrfs_permission,
7724 .get_acl = btrfs_get_acl,
7726 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7727 .lookup = btrfs_lookup,
7728 .permission = btrfs_permission,
7729 .get_acl = btrfs_get_acl,
7732 static const struct file_operations btrfs_dir_file_operations = {
7733 .llseek = generic_file_llseek,
7734 .read = generic_read_dir,
7735 .readdir = btrfs_real_readdir,
7736 .unlocked_ioctl = btrfs_ioctl,
7737 #ifdef CONFIG_COMPAT
7738 .compat_ioctl = btrfs_ioctl,
7740 .release = btrfs_release_file,
7741 .fsync = btrfs_sync_file,
7744 static struct extent_io_ops btrfs_extent_io_ops = {
7745 .fill_delalloc = run_delalloc_range,
7746 .submit_bio_hook = btrfs_submit_bio_hook,
7747 .merge_bio_hook = btrfs_merge_bio_hook,
7748 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7749 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7750 .writepage_start_hook = btrfs_writepage_start_hook,
7751 .set_bit_hook = btrfs_set_bit_hook,
7752 .clear_bit_hook = btrfs_clear_bit_hook,
7753 .merge_extent_hook = btrfs_merge_extent_hook,
7754 .split_extent_hook = btrfs_split_extent_hook,
7758 * btrfs doesn't support the bmap operation because swapfiles
7759 * use bmap to make a mapping of extents in the file. They assume
7760 * these extents won't change over the life of the file and they
7761 * use the bmap result to do IO directly to the drive.
7763 * the btrfs bmap call would return logical addresses that aren't
7764 * suitable for IO and they also will change frequently as COW
7765 * operations happen. So, swapfile + btrfs == corruption.
7767 * For now we're avoiding this by dropping bmap.
7769 static const struct address_space_operations btrfs_aops = {
7770 .readpage = btrfs_readpage,
7771 .writepage = btrfs_writepage,
7772 .writepages = btrfs_writepages,
7773 .readpages = btrfs_readpages,
7774 .direct_IO = btrfs_direct_IO,
7775 .invalidatepage = btrfs_invalidatepage,
7776 .releasepage = btrfs_releasepage,
7777 .set_page_dirty = btrfs_set_page_dirty,
7778 .error_remove_page = generic_error_remove_page,
7781 static const struct address_space_operations btrfs_symlink_aops = {
7782 .readpage = btrfs_readpage,
7783 .writepage = btrfs_writepage,
7784 .invalidatepage = btrfs_invalidatepage,
7785 .releasepage = btrfs_releasepage,
7788 static const struct inode_operations btrfs_file_inode_operations = {
7789 .getattr = btrfs_getattr,
7790 .setattr = btrfs_setattr,
7791 .setxattr = btrfs_setxattr,
7792 .getxattr = btrfs_getxattr,
7793 .listxattr = btrfs_listxattr,
7794 .removexattr = btrfs_removexattr,
7795 .permission = btrfs_permission,
7796 .fiemap = btrfs_fiemap,
7797 .get_acl = btrfs_get_acl,
7798 .update_time = btrfs_update_time,
7800 static const struct inode_operations btrfs_special_inode_operations = {
7801 .getattr = btrfs_getattr,
7802 .setattr = btrfs_setattr,
7803 .permission = btrfs_permission,
7804 .setxattr = btrfs_setxattr,
7805 .getxattr = btrfs_getxattr,
7806 .listxattr = btrfs_listxattr,
7807 .removexattr = btrfs_removexattr,
7808 .get_acl = btrfs_get_acl,
7809 .update_time = btrfs_update_time,
7811 static const struct inode_operations btrfs_symlink_inode_operations = {
7812 .readlink = generic_readlink,
7813 .follow_link = page_follow_link_light,
7814 .put_link = page_put_link,
7815 .getattr = btrfs_getattr,
7816 .setattr = btrfs_setattr,
7817 .permission = btrfs_permission,
7818 .setxattr = btrfs_setxattr,
7819 .getxattr = btrfs_getxattr,
7820 .listxattr = btrfs_listxattr,
7821 .removexattr = btrfs_removexattr,
7822 .get_acl = btrfs_get_acl,
7823 .update_time = btrfs_update_time,
7826 const struct dentry_operations btrfs_dentry_operations = {
7827 .d_delete = btrfs_dentry_delete,
7828 .d_release = btrfs_dentry_release,