2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
46 #include "transaction.h"
47 #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 static struct kmem_cache *btrfs_delalloc_work_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_transaction_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
81 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
82 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
83 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
84 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
85 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
86 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
87 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
88 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92 static int btrfs_truncate(struct inode *inode);
93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 static noinline int cow_file_range(struct inode *inode,
95 struct page *locked_page,
96 u64 start, u64 end, int *page_started,
97 unsigned long *nr_written, int unlock);
98 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
99 u64 len, u64 orig_start,
100 u64 block_start, u64 block_len,
101 u64 orig_block_len, int type);
103 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
104 struct inode *inode, struct inode *dir,
105 const struct qstr *qstr)
109 err = btrfs_init_acl(trans, inode, dir);
111 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
116 * this does all the hard work for inserting an inline extent into
117 * the btree. The caller should have done a btrfs_drop_extents so that
118 * no overlapping inline items exist in the btree
120 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
121 struct btrfs_root *root, struct inode *inode,
122 u64 start, size_t size, size_t compressed_size,
124 struct page **compressed_pages)
126 struct btrfs_key key;
127 struct btrfs_path *path;
128 struct extent_buffer *leaf;
129 struct page *page = NULL;
132 struct btrfs_file_extent_item *ei;
135 size_t cur_size = size;
137 unsigned long offset;
139 if (compressed_size && compressed_pages)
140 cur_size = compressed_size;
142 path = btrfs_alloc_path();
146 path->leave_spinning = 1;
148 key.objectid = btrfs_ino(inode);
150 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
151 datasize = btrfs_file_extent_calc_inline_size(cur_size);
153 inode_add_bytes(inode, size);
154 ret = btrfs_insert_empty_item(trans, root, path, &key,
160 leaf = path->nodes[0];
161 ei = btrfs_item_ptr(leaf, path->slots[0],
162 struct btrfs_file_extent_item);
163 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
164 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
165 btrfs_set_file_extent_encryption(leaf, ei, 0);
166 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
167 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
168 ptr = btrfs_file_extent_inline_start(ei);
170 if (compress_type != BTRFS_COMPRESS_NONE) {
173 while (compressed_size > 0) {
174 cpage = compressed_pages[i];
175 cur_size = min_t(unsigned long, compressed_size,
178 kaddr = kmap_atomic(cpage);
179 write_extent_buffer(leaf, kaddr, ptr, cur_size);
180 kunmap_atomic(kaddr);
184 compressed_size -= cur_size;
186 btrfs_set_file_extent_compression(leaf, ei,
189 page = find_get_page(inode->i_mapping,
190 start >> PAGE_CACHE_SHIFT);
191 btrfs_set_file_extent_compression(leaf, ei, 0);
192 kaddr = kmap_atomic(page);
193 offset = start & (PAGE_CACHE_SIZE - 1);
194 write_extent_buffer(leaf, kaddr + offset, ptr, size);
195 kunmap_atomic(kaddr);
196 page_cache_release(page);
198 btrfs_mark_buffer_dirty(leaf);
199 btrfs_free_path(path);
202 * we're an inline extent, so nobody can
203 * extend the file past i_size without locking
204 * a page we already have locked.
206 * We must do any isize and inode updates
207 * before we unlock the pages. Otherwise we
208 * could end up racing with unlink.
210 BTRFS_I(inode)->disk_i_size = inode->i_size;
211 ret = btrfs_update_inode(trans, root, inode);
215 btrfs_free_path(path);
221 * conditionally insert an inline extent into the file. This
222 * does the checks required to make sure the data is small enough
223 * to fit as an inline extent.
225 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
226 struct btrfs_root *root,
227 struct inode *inode, u64 start, u64 end,
228 size_t compressed_size, int compress_type,
229 struct page **compressed_pages)
231 u64 isize = i_size_read(inode);
232 u64 actual_end = min(end + 1, isize);
233 u64 inline_len = actual_end - start;
234 u64 aligned_end = (end + root->sectorsize - 1) &
235 ~((u64)root->sectorsize - 1);
236 u64 data_len = inline_len;
240 data_len = compressed_size;
243 actual_end >= PAGE_CACHE_SIZE ||
244 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
246 (actual_end & (root->sectorsize - 1)) == 0) ||
248 data_len > root->fs_info->max_inline) {
252 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
256 if (isize > actual_end)
257 inline_len = min_t(u64, isize, actual_end);
258 ret = insert_inline_extent(trans, root, inode, start,
259 inline_len, compressed_size,
260 compress_type, compressed_pages);
261 if (ret && ret != -ENOSPC) {
262 btrfs_abort_transaction(trans, root, ret);
264 } else if (ret == -ENOSPC) {
268 btrfs_delalloc_release_metadata(inode, end + 1 - start);
269 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
273 struct async_extent {
278 unsigned long nr_pages;
280 struct list_head list;
285 struct btrfs_root *root;
286 struct page *locked_page;
289 struct list_head extents;
290 struct btrfs_work work;
293 static noinline int add_async_extent(struct async_cow *cow,
294 u64 start, u64 ram_size,
297 unsigned long nr_pages,
300 struct async_extent *async_extent;
302 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
303 BUG_ON(!async_extent); /* -ENOMEM */
304 async_extent->start = start;
305 async_extent->ram_size = ram_size;
306 async_extent->compressed_size = compressed_size;
307 async_extent->pages = pages;
308 async_extent->nr_pages = nr_pages;
309 async_extent->compress_type = compress_type;
310 list_add_tail(&async_extent->list, &cow->extents);
315 * we create compressed extents in two phases. The first
316 * phase compresses a range of pages that have already been
317 * locked (both pages and state bits are locked).
319 * This is done inside an ordered work queue, and the compression
320 * is spread across many cpus. The actual IO submission is step
321 * two, and the ordered work queue takes care of making sure that
322 * happens in the same order things were put onto the queue by
323 * writepages and friends.
325 * If this code finds it can't get good compression, it puts an
326 * entry onto the work queue to write the uncompressed bytes. This
327 * makes sure that both compressed inodes and uncompressed inodes
328 * are written in the same order that the flusher thread sent them
331 static noinline int compress_file_range(struct inode *inode,
332 struct page *locked_page,
334 struct async_cow *async_cow,
337 struct btrfs_root *root = BTRFS_I(inode)->root;
338 struct btrfs_trans_handle *trans;
340 u64 blocksize = root->sectorsize;
342 u64 isize = i_size_read(inode);
344 struct page **pages = NULL;
345 unsigned long nr_pages;
346 unsigned long nr_pages_ret = 0;
347 unsigned long total_compressed = 0;
348 unsigned long total_in = 0;
349 unsigned long max_compressed = 128 * 1024;
350 unsigned long max_uncompressed = 128 * 1024;
353 int compress_type = root->fs_info->compress_type;
355 /* if this is a small write inside eof, kick off a defrag */
356 if ((end - start + 1) < 16 * 1024 &&
357 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
358 btrfs_add_inode_defrag(NULL, inode);
360 actual_end = min_t(u64, isize, end + 1);
363 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
364 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
367 * we don't want to send crud past the end of i_size through
368 * compression, that's just a waste of CPU time. So, if the
369 * end of the file is before the start of our current
370 * requested range of bytes, we bail out to the uncompressed
371 * cleanup code that can deal with all of this.
373 * It isn't really the fastest way to fix things, but this is a
374 * very uncommon corner.
376 if (actual_end <= start)
377 goto cleanup_and_bail_uncompressed;
379 total_compressed = actual_end - start;
381 /* we want to make sure that amount of ram required to uncompress
382 * an extent is reasonable, so we limit the total size in ram
383 * of a compressed extent to 128k. This is a crucial number
384 * because it also controls how easily we can spread reads across
385 * cpus for decompression.
387 * We also want to make sure the amount of IO required to do
388 * a random read is reasonably small, so we limit the size of
389 * a compressed extent to 128k.
391 total_compressed = min(total_compressed, max_uncompressed);
392 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
393 num_bytes = max(blocksize, num_bytes);
398 * we do compression for mount -o compress and when the
399 * inode has not been flagged as nocompress. This flag can
400 * change at any time if we discover bad compression ratios.
402 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
403 (btrfs_test_opt(root, COMPRESS) ||
404 (BTRFS_I(inode)->force_compress) ||
405 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
407 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
409 /* just bail out to the uncompressed code */
413 if (BTRFS_I(inode)->force_compress)
414 compress_type = BTRFS_I(inode)->force_compress;
416 ret = btrfs_compress_pages(compress_type,
417 inode->i_mapping, start,
418 total_compressed, pages,
419 nr_pages, &nr_pages_ret,
425 unsigned long offset = total_compressed &
426 (PAGE_CACHE_SIZE - 1);
427 struct page *page = pages[nr_pages_ret - 1];
430 /* zero the tail end of the last page, we might be
431 * sending it down to disk
434 kaddr = kmap_atomic(page);
435 memset(kaddr + offset, 0,
436 PAGE_CACHE_SIZE - offset);
437 kunmap_atomic(kaddr);
444 trans = btrfs_join_transaction(root);
446 ret = PTR_ERR(trans);
448 goto cleanup_and_out;
450 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
452 /* lets try to make an inline extent */
453 if (ret || total_in < (actual_end - start)) {
454 /* we didn't compress the entire range, try
455 * to make an uncompressed inline extent.
457 ret = cow_file_range_inline(trans, root, inode,
458 start, end, 0, 0, NULL);
460 /* try making a compressed inline extent */
461 ret = cow_file_range_inline(trans, root, inode,
464 compress_type, pages);
468 * inline extent creation worked or returned error,
469 * we don't need to create any more async work items.
470 * Unlock and free up our temp pages.
472 extent_clear_unlock_delalloc(inode,
473 &BTRFS_I(inode)->io_tree,
475 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
476 EXTENT_CLEAR_DELALLOC |
477 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
479 btrfs_end_transaction(trans, root);
482 btrfs_end_transaction(trans, root);
487 * we aren't doing an inline extent round the compressed size
488 * up to a block size boundary so the allocator does sane
491 total_compressed = (total_compressed + blocksize - 1) &
495 * one last check to make sure the compression is really a
496 * win, compare the page count read with the blocks on disk
498 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
499 ~(PAGE_CACHE_SIZE - 1);
500 if (total_compressed >= total_in) {
503 num_bytes = total_in;
506 if (!will_compress && pages) {
508 * the compression code ran but failed to make things smaller,
509 * free any pages it allocated and our page pointer array
511 for (i = 0; i < nr_pages_ret; i++) {
512 WARN_ON(pages[i]->mapping);
513 page_cache_release(pages[i]);
517 total_compressed = 0;
520 /* flag the file so we don't compress in the future */
521 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
522 !(BTRFS_I(inode)->force_compress)) {
523 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
529 /* the async work queues will take care of doing actual
530 * allocation on disk for these compressed pages,
531 * and will submit them to the elevator.
533 add_async_extent(async_cow, start, num_bytes,
534 total_compressed, pages, nr_pages_ret,
537 if (start + num_bytes < end) {
544 cleanup_and_bail_uncompressed:
546 * No compression, but we still need to write the pages in
547 * the file we've been given so far. redirty the locked
548 * page if it corresponds to our extent and set things up
549 * for the async work queue to run cow_file_range to do
550 * the normal delalloc dance
552 if (page_offset(locked_page) >= start &&
553 page_offset(locked_page) <= end) {
554 __set_page_dirty_nobuffers(locked_page);
555 /* unlocked later on in the async handlers */
557 add_async_extent(async_cow, start, end - start + 1,
558 0, NULL, 0, BTRFS_COMPRESS_NONE);
566 for (i = 0; i < nr_pages_ret; i++) {
567 WARN_ON(pages[i]->mapping);
568 page_cache_release(pages[i]);
575 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
577 EXTENT_CLEAR_UNLOCK_PAGE |
579 EXTENT_CLEAR_DELALLOC |
580 EXTENT_SET_WRITEBACK |
581 EXTENT_END_WRITEBACK);
582 if (!trans || IS_ERR(trans))
583 btrfs_error(root->fs_info, ret, "Failed to join transaction");
585 btrfs_abort_transaction(trans, root, ret);
590 * phase two of compressed writeback. This is the ordered portion
591 * of the code, which only gets called in the order the work was
592 * queued. We walk all the async extents created by compress_file_range
593 * and send them down to the disk.
595 static noinline int submit_compressed_extents(struct inode *inode,
596 struct async_cow *async_cow)
598 struct async_extent *async_extent;
600 struct btrfs_trans_handle *trans;
601 struct btrfs_key ins;
602 struct extent_map *em;
603 struct btrfs_root *root = BTRFS_I(inode)->root;
604 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
605 struct extent_io_tree *io_tree;
608 if (list_empty(&async_cow->extents))
612 while (!list_empty(&async_cow->extents)) {
613 async_extent = list_entry(async_cow->extents.next,
614 struct async_extent, list);
615 list_del(&async_extent->list);
617 io_tree = &BTRFS_I(inode)->io_tree;
620 /* did the compression code fall back to uncompressed IO? */
621 if (!async_extent->pages) {
622 int page_started = 0;
623 unsigned long nr_written = 0;
625 lock_extent(io_tree, async_extent->start,
626 async_extent->start +
627 async_extent->ram_size - 1);
629 /* allocate blocks */
630 ret = cow_file_range(inode, async_cow->locked_page,
632 async_extent->start +
633 async_extent->ram_size - 1,
634 &page_started, &nr_written, 0);
639 * if page_started, cow_file_range inserted an
640 * inline extent and took care of all the unlocking
641 * and IO for us. Otherwise, we need to submit
642 * all those pages down to the drive.
644 if (!page_started && !ret)
645 extent_write_locked_range(io_tree,
646 inode, async_extent->start,
647 async_extent->start +
648 async_extent->ram_size - 1,
656 lock_extent(io_tree, async_extent->start,
657 async_extent->start + async_extent->ram_size - 1);
659 trans = btrfs_join_transaction(root);
661 ret = PTR_ERR(trans);
663 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
664 ret = btrfs_reserve_extent(trans, root,
665 async_extent->compressed_size,
666 async_extent->compressed_size,
667 0, alloc_hint, &ins, 1);
668 if (ret && ret != -ENOSPC)
669 btrfs_abort_transaction(trans, root, ret);
670 btrfs_end_transaction(trans, root);
675 for (i = 0; i < async_extent->nr_pages; i++) {
676 WARN_ON(async_extent->pages[i]->mapping);
677 page_cache_release(async_extent->pages[i]);
679 kfree(async_extent->pages);
680 async_extent->nr_pages = 0;
681 async_extent->pages = NULL;
682 unlock_extent(io_tree, async_extent->start,
683 async_extent->start +
684 async_extent->ram_size - 1);
687 goto out_free; /* JDM: Requeue? */
691 * here we're doing allocation and writeback of the
694 btrfs_drop_extent_cache(inode, async_extent->start,
695 async_extent->start +
696 async_extent->ram_size - 1, 0);
698 em = alloc_extent_map();
699 BUG_ON(!em); /* -ENOMEM */
700 em->start = async_extent->start;
701 em->len = async_extent->ram_size;
702 em->orig_start = em->start;
703 em->mod_start = em->start;
704 em->mod_len = em->len;
706 em->block_start = ins.objectid;
707 em->block_len = ins.offset;
708 em->orig_block_len = ins.offset;
709 em->bdev = root->fs_info->fs_devices->latest_bdev;
710 em->compress_type = async_extent->compress_type;
711 set_bit(EXTENT_FLAG_PINNED, &em->flags);
712 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
716 write_lock(&em_tree->lock);
717 ret = add_extent_mapping(em_tree, em);
720 &em_tree->modified_extents);
721 write_unlock(&em_tree->lock);
722 if (ret != -EEXIST) {
726 btrfs_drop_extent_cache(inode, async_extent->start,
727 async_extent->start +
728 async_extent->ram_size - 1, 0);
731 ret = btrfs_add_ordered_extent_compress(inode,
734 async_extent->ram_size,
736 BTRFS_ORDERED_COMPRESSED,
737 async_extent->compress_type);
738 BUG_ON(ret); /* -ENOMEM */
741 * clear dirty, set writeback and unlock the pages.
743 extent_clear_unlock_delalloc(inode,
744 &BTRFS_I(inode)->io_tree,
746 async_extent->start +
747 async_extent->ram_size - 1,
748 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
749 EXTENT_CLEAR_UNLOCK |
750 EXTENT_CLEAR_DELALLOC |
751 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
753 ret = btrfs_submit_compressed_write(inode,
755 async_extent->ram_size,
757 ins.offset, async_extent->pages,
758 async_extent->nr_pages);
760 BUG_ON(ret); /* -ENOMEM */
761 alloc_hint = ins.objectid + ins.offset;
773 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
776 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
777 struct extent_map *em;
780 read_lock(&em_tree->lock);
781 em = search_extent_mapping(em_tree, start, num_bytes);
784 * if block start isn't an actual block number then find the
785 * first block in this inode and use that as a hint. If that
786 * block is also bogus then just don't worry about it.
788 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
790 em = search_extent_mapping(em_tree, 0, 0);
791 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
792 alloc_hint = em->block_start;
796 alloc_hint = em->block_start;
800 read_unlock(&em_tree->lock);
806 * when extent_io.c finds a delayed allocation range in the file,
807 * the call backs end up in this code. The basic idea is to
808 * allocate extents on disk for the range, and create ordered data structs
809 * in ram to track those extents.
811 * locked_page is the page that writepage had locked already. We use
812 * it to make sure we don't do extra locks or unlocks.
814 * *page_started is set to one if we unlock locked_page and do everything
815 * required to start IO on it. It may be clean and already done with
818 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
820 struct btrfs_root *root,
821 struct page *locked_page,
822 u64 start, u64 end, int *page_started,
823 unsigned long *nr_written,
828 unsigned long ram_size;
831 u64 blocksize = root->sectorsize;
832 struct btrfs_key ins;
833 struct extent_map *em;
834 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
837 BUG_ON(btrfs_is_free_space_inode(inode));
839 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
840 num_bytes = max(blocksize, num_bytes);
841 disk_num_bytes = num_bytes;
843 /* if this is a small write inside eof, kick off defrag */
844 if (num_bytes < 64 * 1024 &&
845 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
846 btrfs_add_inode_defrag(trans, inode);
849 /* lets try to make an inline extent */
850 ret = cow_file_range_inline(trans, root, inode,
851 start, end, 0, 0, NULL);
853 extent_clear_unlock_delalloc(inode,
854 &BTRFS_I(inode)->io_tree,
856 EXTENT_CLEAR_UNLOCK_PAGE |
857 EXTENT_CLEAR_UNLOCK |
858 EXTENT_CLEAR_DELALLOC |
860 EXTENT_SET_WRITEBACK |
861 EXTENT_END_WRITEBACK);
863 *nr_written = *nr_written +
864 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
867 } else if (ret < 0) {
868 btrfs_abort_transaction(trans, root, ret);
873 BUG_ON(disk_num_bytes >
874 btrfs_super_total_bytes(root->fs_info->super_copy));
876 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
877 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
879 while (disk_num_bytes > 0) {
882 cur_alloc_size = disk_num_bytes;
883 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
884 root->sectorsize, 0, alloc_hint,
887 btrfs_abort_transaction(trans, root, ret);
891 em = alloc_extent_map();
892 BUG_ON(!em); /* -ENOMEM */
894 em->orig_start = em->start;
895 ram_size = ins.offset;
896 em->len = ins.offset;
897 em->mod_start = em->start;
898 em->mod_len = em->len;
900 em->block_start = ins.objectid;
901 em->block_len = ins.offset;
902 em->orig_block_len = ins.offset;
903 em->bdev = root->fs_info->fs_devices->latest_bdev;
904 set_bit(EXTENT_FLAG_PINNED, &em->flags);
908 write_lock(&em_tree->lock);
909 ret = add_extent_mapping(em_tree, em);
912 &em_tree->modified_extents);
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;
963 extent_clear_unlock_delalloc(inode,
964 &BTRFS_I(inode)->io_tree,
965 start, end, locked_page,
966 EXTENT_CLEAR_UNLOCK_PAGE |
967 EXTENT_CLEAR_UNLOCK |
968 EXTENT_CLEAR_DELALLOC |
970 EXTENT_SET_WRITEBACK |
971 EXTENT_END_WRITEBACK);
976 static noinline int cow_file_range(struct inode *inode,
977 struct page *locked_page,
978 u64 start, u64 end, int *page_started,
979 unsigned long *nr_written,
982 struct btrfs_trans_handle *trans;
983 struct btrfs_root *root = BTRFS_I(inode)->root;
986 trans = btrfs_join_transaction(root);
988 extent_clear_unlock_delalloc(inode,
989 &BTRFS_I(inode)->io_tree,
990 start, end, locked_page,
991 EXTENT_CLEAR_UNLOCK_PAGE |
992 EXTENT_CLEAR_UNLOCK |
993 EXTENT_CLEAR_DELALLOC |
995 EXTENT_SET_WRITEBACK |
996 EXTENT_END_WRITEBACK);
997 return PTR_ERR(trans);
999 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1001 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1002 page_started, nr_written, unlock);
1004 btrfs_end_transaction(trans, root);
1010 * work queue call back to started compression on a file and pages
1012 static noinline void async_cow_start(struct btrfs_work *work)
1014 struct async_cow *async_cow;
1016 async_cow = container_of(work, struct async_cow, work);
1018 compress_file_range(async_cow->inode, async_cow->locked_page,
1019 async_cow->start, async_cow->end, async_cow,
1021 if (num_added == 0) {
1022 btrfs_add_delayed_iput(async_cow->inode);
1023 async_cow->inode = NULL;
1028 * work queue call back to submit previously compressed pages
1030 static noinline void async_cow_submit(struct btrfs_work *work)
1032 struct async_cow *async_cow;
1033 struct btrfs_root *root;
1034 unsigned long nr_pages;
1036 async_cow = container_of(work, struct async_cow, work);
1038 root = async_cow->root;
1039 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1042 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1044 waitqueue_active(&root->fs_info->async_submit_wait))
1045 wake_up(&root->fs_info->async_submit_wait);
1047 if (async_cow->inode)
1048 submit_compressed_extents(async_cow->inode, async_cow);
1051 static noinline void async_cow_free(struct btrfs_work *work)
1053 struct async_cow *async_cow;
1054 async_cow = container_of(work, struct async_cow, work);
1055 if (async_cow->inode)
1056 btrfs_add_delayed_iput(async_cow->inode);
1060 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1061 u64 start, u64 end, int *page_started,
1062 unsigned long *nr_written)
1064 struct async_cow *async_cow;
1065 struct btrfs_root *root = BTRFS_I(inode)->root;
1066 unsigned long nr_pages;
1068 int limit = 10 * 1024 * 1024;
1070 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1071 1, 0, NULL, GFP_NOFS);
1072 while (start < end) {
1073 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1074 BUG_ON(!async_cow); /* -ENOMEM */
1075 async_cow->inode = igrab(inode);
1076 async_cow->root = root;
1077 async_cow->locked_page = locked_page;
1078 async_cow->start = start;
1080 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1083 cur_end = min(end, start + 512 * 1024 - 1);
1085 async_cow->end = cur_end;
1086 INIT_LIST_HEAD(&async_cow->extents);
1088 async_cow->work.func = async_cow_start;
1089 async_cow->work.ordered_func = async_cow_submit;
1090 async_cow->work.ordered_free = async_cow_free;
1091 async_cow->work.flags = 0;
1093 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1095 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1097 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1100 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1101 wait_event(root->fs_info->async_submit_wait,
1102 (atomic_read(&root->fs_info->async_delalloc_pages) <
1106 while (atomic_read(&root->fs_info->async_submit_draining) &&
1107 atomic_read(&root->fs_info->async_delalloc_pages)) {
1108 wait_event(root->fs_info->async_submit_wait,
1109 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1113 *nr_written += nr_pages;
1114 start = cur_end + 1;
1120 static noinline int csum_exist_in_range(struct btrfs_root *root,
1121 u64 bytenr, u64 num_bytes)
1124 struct btrfs_ordered_sum *sums;
1127 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1128 bytenr + num_bytes - 1, &list, 0);
1129 if (ret == 0 && list_empty(&list))
1132 while (!list_empty(&list)) {
1133 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1134 list_del(&sums->list);
1141 * when nowcow writeback call back. This checks for snapshots or COW copies
1142 * of the extents that exist in the file, and COWs the file as required.
1144 * If no cow copies or snapshots exist, we write directly to the existing
1147 static noinline int run_delalloc_nocow(struct inode *inode,
1148 struct page *locked_page,
1149 u64 start, u64 end, int *page_started, int force,
1150 unsigned long *nr_written)
1152 struct btrfs_root *root = BTRFS_I(inode)->root;
1153 struct btrfs_trans_handle *trans;
1154 struct extent_buffer *leaf;
1155 struct btrfs_path *path;
1156 struct btrfs_file_extent_item *fi;
1157 struct btrfs_key found_key;
1171 u64 ino = btrfs_ino(inode);
1173 path = btrfs_alloc_path();
1175 extent_clear_unlock_delalloc(inode,
1176 &BTRFS_I(inode)->io_tree,
1177 start, end, locked_page,
1178 EXTENT_CLEAR_UNLOCK_PAGE |
1179 EXTENT_CLEAR_UNLOCK |
1180 EXTENT_CLEAR_DELALLOC |
1181 EXTENT_CLEAR_DIRTY |
1182 EXTENT_SET_WRITEBACK |
1183 EXTENT_END_WRITEBACK);
1187 nolock = btrfs_is_free_space_inode(inode);
1190 trans = btrfs_join_transaction_nolock(root);
1192 trans = btrfs_join_transaction(root);
1194 if (IS_ERR(trans)) {
1195 extent_clear_unlock_delalloc(inode,
1196 &BTRFS_I(inode)->io_tree,
1197 start, end, locked_page,
1198 EXTENT_CLEAR_UNLOCK_PAGE |
1199 EXTENT_CLEAR_UNLOCK |
1200 EXTENT_CLEAR_DELALLOC |
1201 EXTENT_CLEAR_DIRTY |
1202 EXTENT_SET_WRITEBACK |
1203 EXTENT_END_WRITEBACK);
1204 btrfs_free_path(path);
1205 return PTR_ERR(trans);
1208 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1210 cow_start = (u64)-1;
1213 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1216 btrfs_abort_transaction(trans, root, ret);
1219 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1220 leaf = path->nodes[0];
1221 btrfs_item_key_to_cpu(leaf, &found_key,
1222 path->slots[0] - 1);
1223 if (found_key.objectid == ino &&
1224 found_key.type == BTRFS_EXTENT_DATA_KEY)
1229 leaf = path->nodes[0];
1230 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1231 ret = btrfs_next_leaf(root, path);
1233 btrfs_abort_transaction(trans, root, ret);
1238 leaf = path->nodes[0];
1244 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1246 if (found_key.objectid > ino ||
1247 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1248 found_key.offset > end)
1251 if (found_key.offset > cur_offset) {
1252 extent_end = found_key.offset;
1257 fi = btrfs_item_ptr(leaf, path->slots[0],
1258 struct btrfs_file_extent_item);
1259 extent_type = btrfs_file_extent_type(leaf, fi);
1261 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1262 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1263 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1264 extent_offset = btrfs_file_extent_offset(leaf, fi);
1265 extent_end = found_key.offset +
1266 btrfs_file_extent_num_bytes(leaf, fi);
1268 btrfs_file_extent_disk_num_bytes(leaf, fi);
1269 if (extent_end <= start) {
1273 if (disk_bytenr == 0)
1275 if (btrfs_file_extent_compression(leaf, fi) ||
1276 btrfs_file_extent_encryption(leaf, fi) ||
1277 btrfs_file_extent_other_encoding(leaf, fi))
1279 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1281 if (btrfs_extent_readonly(root, disk_bytenr))
1283 if (btrfs_cross_ref_exist(trans, root, ino,
1285 extent_offset, disk_bytenr))
1287 disk_bytenr += extent_offset;
1288 disk_bytenr += cur_offset - found_key.offset;
1289 num_bytes = min(end + 1, extent_end) - cur_offset;
1291 * force cow if csum exists in the range.
1292 * this ensure that csum for a given extent are
1293 * either valid or do not exist.
1295 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1298 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1299 extent_end = found_key.offset +
1300 btrfs_file_extent_inline_len(leaf, fi);
1301 extent_end = ALIGN(extent_end, root->sectorsize);
1306 if (extent_end <= start) {
1311 if (cow_start == (u64)-1)
1312 cow_start = cur_offset;
1313 cur_offset = extent_end;
1314 if (cur_offset > end)
1320 btrfs_release_path(path);
1321 if (cow_start != (u64)-1) {
1322 ret = __cow_file_range(trans, inode, root, locked_page,
1323 cow_start, found_key.offset - 1,
1324 page_started, nr_written, 1);
1326 btrfs_abort_transaction(trans, root, ret);
1329 cow_start = (u64)-1;
1332 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1333 struct extent_map *em;
1334 struct extent_map_tree *em_tree;
1335 em_tree = &BTRFS_I(inode)->extent_tree;
1336 em = alloc_extent_map();
1337 BUG_ON(!em); /* -ENOMEM */
1338 em->start = cur_offset;
1339 em->orig_start = found_key.offset - extent_offset;
1340 em->len = num_bytes;
1341 em->block_len = num_bytes;
1342 em->block_start = disk_bytenr;
1343 em->orig_block_len = disk_num_bytes;
1344 em->bdev = root->fs_info->fs_devices->latest_bdev;
1345 em->mod_start = em->start;
1346 em->mod_len = em->len;
1347 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1348 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1349 em->generation = -1;
1351 write_lock(&em_tree->lock);
1352 ret = add_extent_mapping(em_tree, em);
1354 list_move(&em->list,
1355 &em_tree->modified_extents);
1356 write_unlock(&em_tree->lock);
1357 if (ret != -EEXIST) {
1358 free_extent_map(em);
1361 btrfs_drop_extent_cache(inode, em->start,
1362 em->start + em->len - 1, 0);
1364 type = BTRFS_ORDERED_PREALLOC;
1366 type = BTRFS_ORDERED_NOCOW;
1369 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1370 num_bytes, num_bytes, type);
1371 BUG_ON(ret); /* -ENOMEM */
1373 if (root->root_key.objectid ==
1374 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1375 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1378 btrfs_abort_transaction(trans, root, ret);
1383 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1384 cur_offset, cur_offset + num_bytes - 1,
1385 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1386 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1387 EXTENT_SET_PRIVATE2);
1388 cur_offset = extent_end;
1389 if (cur_offset > end)
1392 btrfs_release_path(path);
1394 if (cur_offset <= end && cow_start == (u64)-1) {
1395 cow_start = cur_offset;
1399 if (cow_start != (u64)-1) {
1400 ret = __cow_file_range(trans, inode, root, locked_page,
1402 page_started, nr_written, 1);
1404 btrfs_abort_transaction(trans, root, ret);
1410 err = btrfs_end_transaction(trans, root);
1414 if (ret && cur_offset < end)
1415 extent_clear_unlock_delalloc(inode,
1416 &BTRFS_I(inode)->io_tree,
1417 cur_offset, end, locked_page,
1418 EXTENT_CLEAR_UNLOCK_PAGE |
1419 EXTENT_CLEAR_UNLOCK |
1420 EXTENT_CLEAR_DELALLOC |
1421 EXTENT_CLEAR_DIRTY |
1422 EXTENT_SET_WRITEBACK |
1423 EXTENT_END_WRITEBACK);
1425 btrfs_free_path(path);
1430 * extent_io.c call back to do delayed allocation processing
1432 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1433 u64 start, u64 end, int *page_started,
1434 unsigned long *nr_written)
1437 struct btrfs_root *root = BTRFS_I(inode)->root;
1439 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1440 ret = run_delalloc_nocow(inode, locked_page, start, end,
1441 page_started, 1, nr_written);
1442 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1443 ret = run_delalloc_nocow(inode, locked_page, start, end,
1444 page_started, 0, nr_written);
1445 } else if (!btrfs_test_opt(root, COMPRESS) &&
1446 !(BTRFS_I(inode)->force_compress) &&
1447 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1448 ret = cow_file_range(inode, locked_page, start, end,
1449 page_started, nr_written, 1);
1451 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1452 &BTRFS_I(inode)->runtime_flags);
1453 ret = cow_file_range_async(inode, locked_page, start, end,
1454 page_started, nr_written);
1459 static void btrfs_split_extent_hook(struct inode *inode,
1460 struct extent_state *orig, u64 split)
1462 /* not delalloc, ignore it */
1463 if (!(orig->state & EXTENT_DELALLOC))
1466 spin_lock(&BTRFS_I(inode)->lock);
1467 BTRFS_I(inode)->outstanding_extents++;
1468 spin_unlock(&BTRFS_I(inode)->lock);
1472 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1473 * extents so we can keep track of new extents that are just merged onto old
1474 * extents, such as when we are doing sequential writes, so we can properly
1475 * account for the metadata space we'll need.
1477 static void btrfs_merge_extent_hook(struct inode *inode,
1478 struct extent_state *new,
1479 struct extent_state *other)
1481 /* not delalloc, ignore it */
1482 if (!(other->state & EXTENT_DELALLOC))
1485 spin_lock(&BTRFS_I(inode)->lock);
1486 BTRFS_I(inode)->outstanding_extents--;
1487 spin_unlock(&BTRFS_I(inode)->lock);
1491 * extent_io.c set_bit_hook, used to track delayed allocation
1492 * bytes in this file, and to maintain the list of inodes that
1493 * have pending delalloc work to be done.
1495 static void btrfs_set_bit_hook(struct inode *inode,
1496 struct extent_state *state, int *bits)
1500 * set_bit and clear bit hooks normally require _irqsave/restore
1501 * but in this case, we are only testing for the DELALLOC
1502 * bit, which is only set or cleared with irqs on
1504 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1505 struct btrfs_root *root = BTRFS_I(inode)->root;
1506 u64 len = state->end + 1 - state->start;
1507 bool do_list = !btrfs_is_free_space_inode(inode);
1509 if (*bits & EXTENT_FIRST_DELALLOC) {
1510 *bits &= ~EXTENT_FIRST_DELALLOC;
1512 spin_lock(&BTRFS_I(inode)->lock);
1513 BTRFS_I(inode)->outstanding_extents++;
1514 spin_unlock(&BTRFS_I(inode)->lock);
1517 spin_lock(&root->fs_info->delalloc_lock);
1518 BTRFS_I(inode)->delalloc_bytes += len;
1519 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1520 root->fs_info->delalloc_batch);
1521 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1522 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1523 &root->fs_info->delalloc_inodes);
1525 spin_unlock(&root->fs_info->delalloc_lock);
1530 * extent_io.c clear_bit_hook, see set_bit_hook for why
1532 static void btrfs_clear_bit_hook(struct inode *inode,
1533 struct extent_state *state, int *bits)
1536 * set_bit and clear bit hooks normally require _irqsave/restore
1537 * but in this case, we are only testing for the DELALLOC
1538 * bit, which is only set or cleared with irqs on
1540 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1541 struct btrfs_root *root = BTRFS_I(inode)->root;
1542 u64 len = state->end + 1 - state->start;
1543 bool do_list = !btrfs_is_free_space_inode(inode);
1545 if (*bits & EXTENT_FIRST_DELALLOC) {
1546 *bits &= ~EXTENT_FIRST_DELALLOC;
1547 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1548 spin_lock(&BTRFS_I(inode)->lock);
1549 BTRFS_I(inode)->outstanding_extents--;
1550 spin_unlock(&BTRFS_I(inode)->lock);
1553 if (*bits & EXTENT_DO_ACCOUNTING)
1554 btrfs_delalloc_release_metadata(inode, len);
1556 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1558 btrfs_free_reserved_data_space(inode, len);
1560 spin_lock(&root->fs_info->delalloc_lock);
1561 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1562 root->fs_info->delalloc_batch);
1563 BTRFS_I(inode)->delalloc_bytes -= len;
1565 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1566 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1567 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1569 spin_unlock(&root->fs_info->delalloc_lock);
1574 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1575 * we don't create bios that span stripes or chunks
1577 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1578 size_t size, struct bio *bio,
1579 unsigned long bio_flags)
1581 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1582 u64 logical = (u64)bio->bi_sector << 9;
1587 if (bio_flags & EXTENT_BIO_COMPRESSED)
1590 length = bio->bi_size;
1591 map_length = length;
1592 ret = btrfs_map_block(root->fs_info, READ, logical,
1593 &map_length, NULL, 0);
1594 /* Will always return 0 with map_multi == NULL */
1596 if (map_length < length + size)
1602 * in order to insert checksums into the metadata in large chunks,
1603 * we wait until bio submission time. All the pages in the bio are
1604 * checksummed and sums are attached onto the ordered extent record.
1606 * At IO completion time the cums attached on the ordered extent record
1607 * are inserted into the btree
1609 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1610 struct bio *bio, int mirror_num,
1611 unsigned long bio_flags,
1614 struct btrfs_root *root = BTRFS_I(inode)->root;
1617 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1618 BUG_ON(ret); /* -ENOMEM */
1623 * in order to insert checksums into the metadata in large chunks,
1624 * we wait until bio submission time. All the pages in the bio are
1625 * checksummed and sums are attached onto the ordered extent record.
1627 * At IO completion time the cums attached on the ordered extent record
1628 * are inserted into the btree
1630 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1631 int mirror_num, unsigned long bio_flags,
1634 struct btrfs_root *root = BTRFS_I(inode)->root;
1637 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1639 bio_endio(bio, ret);
1644 * extent_io.c submission hook. This does the right thing for csum calculation
1645 * on write, or reading the csums from the tree before a read
1647 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1648 int mirror_num, unsigned long bio_flags,
1651 struct btrfs_root *root = BTRFS_I(inode)->root;
1655 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1657 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1659 if (btrfs_is_free_space_inode(inode))
1662 if (!(rw & REQ_WRITE)) {
1663 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1667 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1668 ret = btrfs_submit_compressed_read(inode, bio,
1672 } else if (!skip_sum) {
1673 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1678 } else if (async && !skip_sum) {
1679 /* csum items have already been cloned */
1680 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1682 /* we're doing a write, do the async checksumming */
1683 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1684 inode, rw, bio, mirror_num,
1685 bio_flags, bio_offset,
1686 __btrfs_submit_bio_start,
1687 __btrfs_submit_bio_done);
1689 } else if (!skip_sum) {
1690 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1696 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1700 bio_endio(bio, ret);
1705 * given a list of ordered sums record them in the inode. This happens
1706 * at IO completion time based on sums calculated at bio submission time.
1708 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1709 struct inode *inode, u64 file_offset,
1710 struct list_head *list)
1712 struct btrfs_ordered_sum *sum;
1714 list_for_each_entry(sum, list, list) {
1715 btrfs_csum_file_blocks(trans,
1716 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1721 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1722 struct extent_state **cached_state)
1724 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1725 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1726 cached_state, GFP_NOFS);
1729 /* see btrfs_writepage_start_hook for details on why this is required */
1730 struct btrfs_writepage_fixup {
1732 struct btrfs_work work;
1735 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1737 struct btrfs_writepage_fixup *fixup;
1738 struct btrfs_ordered_extent *ordered;
1739 struct extent_state *cached_state = NULL;
1741 struct inode *inode;
1746 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1750 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1751 ClearPageChecked(page);
1755 inode = page->mapping->host;
1756 page_start = page_offset(page);
1757 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1759 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1762 /* already ordered? We're done */
1763 if (PagePrivate2(page))
1766 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1768 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1769 page_end, &cached_state, GFP_NOFS);
1771 btrfs_start_ordered_extent(inode, ordered, 1);
1772 btrfs_put_ordered_extent(ordered);
1776 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1778 mapping_set_error(page->mapping, ret);
1779 end_extent_writepage(page, ret, page_start, page_end);
1780 ClearPageChecked(page);
1784 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1785 ClearPageChecked(page);
1786 set_page_dirty(page);
1788 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1789 &cached_state, GFP_NOFS);
1792 page_cache_release(page);
1797 * There are a few paths in the higher layers of the kernel that directly
1798 * set the page dirty bit without asking the filesystem if it is a
1799 * good idea. This causes problems because we want to make sure COW
1800 * properly happens and the data=ordered rules are followed.
1802 * In our case any range that doesn't have the ORDERED bit set
1803 * hasn't been properly setup for IO. We kick off an async process
1804 * to fix it up. The async helper will wait for ordered extents, set
1805 * the delalloc bit and make it safe to write the page.
1807 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1809 struct inode *inode = page->mapping->host;
1810 struct btrfs_writepage_fixup *fixup;
1811 struct btrfs_root *root = BTRFS_I(inode)->root;
1813 /* this page is properly in the ordered list */
1814 if (TestClearPagePrivate2(page))
1817 if (PageChecked(page))
1820 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1824 SetPageChecked(page);
1825 page_cache_get(page);
1826 fixup->work.func = btrfs_writepage_fixup_worker;
1828 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1832 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1833 struct inode *inode, u64 file_pos,
1834 u64 disk_bytenr, u64 disk_num_bytes,
1835 u64 num_bytes, u64 ram_bytes,
1836 u8 compression, u8 encryption,
1837 u16 other_encoding, int extent_type)
1839 struct btrfs_root *root = BTRFS_I(inode)->root;
1840 struct btrfs_file_extent_item *fi;
1841 struct btrfs_path *path;
1842 struct extent_buffer *leaf;
1843 struct btrfs_key ins;
1846 path = btrfs_alloc_path();
1850 path->leave_spinning = 1;
1853 * we may be replacing one extent in the tree with another.
1854 * The new extent is pinned in the extent map, and we don't want
1855 * to drop it from the cache until it is completely in the btree.
1857 * So, tell btrfs_drop_extents to leave this extent in the cache.
1858 * the caller is expected to unpin it and allow it to be merged
1861 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1862 file_pos + num_bytes, 0);
1866 ins.objectid = btrfs_ino(inode);
1867 ins.offset = file_pos;
1868 ins.type = BTRFS_EXTENT_DATA_KEY;
1869 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1872 leaf = path->nodes[0];
1873 fi = btrfs_item_ptr(leaf, path->slots[0],
1874 struct btrfs_file_extent_item);
1875 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1876 btrfs_set_file_extent_type(leaf, fi, extent_type);
1877 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1878 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1879 btrfs_set_file_extent_offset(leaf, fi, 0);
1880 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1881 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1882 btrfs_set_file_extent_compression(leaf, fi, compression);
1883 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1884 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1886 btrfs_mark_buffer_dirty(leaf);
1887 btrfs_release_path(path);
1889 inode_add_bytes(inode, num_bytes);
1891 ins.objectid = disk_bytenr;
1892 ins.offset = disk_num_bytes;
1893 ins.type = BTRFS_EXTENT_ITEM_KEY;
1894 ret = btrfs_alloc_reserved_file_extent(trans, root,
1895 root->root_key.objectid,
1896 btrfs_ino(inode), file_pos, &ins);
1898 btrfs_free_path(path);
1904 * helper function for btrfs_finish_ordered_io, this
1905 * just reads in some of the csum leaves to prime them into ram
1906 * before we start the transaction. It limits the amount of btree
1907 * reads required while inside the transaction.
1909 /* as ordered data IO finishes, this gets called so we can finish
1910 * an ordered extent if the range of bytes in the file it covers are
1913 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1915 struct inode *inode = ordered_extent->inode;
1916 struct btrfs_root *root = BTRFS_I(inode)->root;
1917 struct btrfs_trans_handle *trans = NULL;
1918 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1919 struct extent_state *cached_state = NULL;
1920 int compress_type = 0;
1924 nolock = btrfs_is_free_space_inode(inode);
1926 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1931 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1932 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1933 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1935 trans = btrfs_join_transaction_nolock(root);
1937 trans = btrfs_join_transaction(root);
1938 if (IS_ERR(trans)) {
1939 ret = PTR_ERR(trans);
1943 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1944 ret = btrfs_update_inode_fallback(trans, root, inode);
1945 if (ret) /* -ENOMEM or corruption */
1946 btrfs_abort_transaction(trans, root, ret);
1950 lock_extent_bits(io_tree, ordered_extent->file_offset,
1951 ordered_extent->file_offset + ordered_extent->len - 1,
1955 trans = btrfs_join_transaction_nolock(root);
1957 trans = btrfs_join_transaction(root);
1958 if (IS_ERR(trans)) {
1959 ret = PTR_ERR(trans);
1963 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1965 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1966 compress_type = ordered_extent->compress_type;
1967 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1968 BUG_ON(compress_type);
1969 ret = btrfs_mark_extent_written(trans, inode,
1970 ordered_extent->file_offset,
1971 ordered_extent->file_offset +
1972 ordered_extent->len);
1974 BUG_ON(root == root->fs_info->tree_root);
1975 ret = insert_reserved_file_extent(trans, inode,
1976 ordered_extent->file_offset,
1977 ordered_extent->start,
1978 ordered_extent->disk_len,
1979 ordered_extent->len,
1980 ordered_extent->len,
1981 compress_type, 0, 0,
1982 BTRFS_FILE_EXTENT_REG);
1984 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1985 ordered_extent->file_offset, ordered_extent->len,
1988 btrfs_abort_transaction(trans, root, ret);
1992 add_pending_csums(trans, inode, ordered_extent->file_offset,
1993 &ordered_extent->list);
1995 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1996 ret = btrfs_update_inode_fallback(trans, root, inode);
1997 if (ret) { /* -ENOMEM or corruption */
1998 btrfs_abort_transaction(trans, root, ret);
2003 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2004 ordered_extent->file_offset +
2005 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2007 if (root != root->fs_info->tree_root)
2008 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2010 btrfs_end_transaction(trans, root);
2013 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2014 ordered_extent->file_offset +
2015 ordered_extent->len - 1, NULL, GFP_NOFS);
2018 * This needs to be done to make sure anybody waiting knows we are done
2019 * updating everything for this ordered extent.
2021 btrfs_remove_ordered_extent(inode, ordered_extent);
2024 btrfs_put_ordered_extent(ordered_extent);
2025 /* once for the tree */
2026 btrfs_put_ordered_extent(ordered_extent);
2031 static void finish_ordered_fn(struct btrfs_work *work)
2033 struct btrfs_ordered_extent *ordered_extent;
2034 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2035 btrfs_finish_ordered_io(ordered_extent);
2038 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2039 struct extent_state *state, int uptodate)
2041 struct inode *inode = page->mapping->host;
2042 struct btrfs_root *root = BTRFS_I(inode)->root;
2043 struct btrfs_ordered_extent *ordered_extent = NULL;
2044 struct btrfs_workers *workers;
2046 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2048 ClearPagePrivate2(page);
2049 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2050 end - start + 1, uptodate))
2053 ordered_extent->work.func = finish_ordered_fn;
2054 ordered_extent->work.flags = 0;
2056 if (btrfs_is_free_space_inode(inode))
2057 workers = &root->fs_info->endio_freespace_worker;
2059 workers = &root->fs_info->endio_write_workers;
2060 btrfs_queue_worker(workers, &ordered_extent->work);
2066 * when reads are done, we need to check csums to verify the data is correct
2067 * if there's a match, we allow the bio to finish. If not, the code in
2068 * extent_io.c will try to find good copies for us.
2070 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2071 struct extent_state *state, int mirror)
2073 size_t offset = start - page_offset(page);
2074 struct inode *inode = page->mapping->host;
2075 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2077 u64 private = ~(u32)0;
2079 struct btrfs_root *root = BTRFS_I(inode)->root;
2082 if (PageChecked(page)) {
2083 ClearPageChecked(page);
2087 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2090 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2091 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2092 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2097 if (state && state->start == start) {
2098 private = state->private;
2101 ret = get_state_private(io_tree, start, &private);
2103 kaddr = kmap_atomic(page);
2107 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2108 btrfs_csum_final(csum, (char *)&csum);
2109 if (csum != private)
2112 kunmap_atomic(kaddr);
2117 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2119 (unsigned long long)btrfs_ino(page->mapping->host),
2120 (unsigned long long)start, csum,
2121 (unsigned long long)private);
2122 memset(kaddr + offset, 1, end - start + 1);
2123 flush_dcache_page(page);
2124 kunmap_atomic(kaddr);
2130 struct delayed_iput {
2131 struct list_head list;
2132 struct inode *inode;
2135 /* JDM: If this is fs-wide, why can't we add a pointer to
2136 * btrfs_inode instead and avoid the allocation? */
2137 void btrfs_add_delayed_iput(struct inode *inode)
2139 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2140 struct delayed_iput *delayed;
2142 if (atomic_add_unless(&inode->i_count, -1, 1))
2145 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2146 delayed->inode = inode;
2148 spin_lock(&fs_info->delayed_iput_lock);
2149 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2150 spin_unlock(&fs_info->delayed_iput_lock);
2153 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2156 struct btrfs_fs_info *fs_info = root->fs_info;
2157 struct delayed_iput *delayed;
2160 spin_lock(&fs_info->delayed_iput_lock);
2161 empty = list_empty(&fs_info->delayed_iputs);
2162 spin_unlock(&fs_info->delayed_iput_lock);
2166 spin_lock(&fs_info->delayed_iput_lock);
2167 list_splice_init(&fs_info->delayed_iputs, &list);
2168 spin_unlock(&fs_info->delayed_iput_lock);
2170 while (!list_empty(&list)) {
2171 delayed = list_entry(list.next, struct delayed_iput, list);
2172 list_del(&delayed->list);
2173 iput(delayed->inode);
2178 enum btrfs_orphan_cleanup_state {
2179 ORPHAN_CLEANUP_STARTED = 1,
2180 ORPHAN_CLEANUP_DONE = 2,
2184 * This is called in transaction commit time. If there are no orphan
2185 * files in the subvolume, it removes orphan item and frees block_rsv
2188 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2189 struct btrfs_root *root)
2191 struct btrfs_block_rsv *block_rsv;
2194 if (atomic_read(&root->orphan_inodes) ||
2195 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2198 spin_lock(&root->orphan_lock);
2199 if (atomic_read(&root->orphan_inodes)) {
2200 spin_unlock(&root->orphan_lock);
2204 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2205 spin_unlock(&root->orphan_lock);
2209 block_rsv = root->orphan_block_rsv;
2210 root->orphan_block_rsv = NULL;
2211 spin_unlock(&root->orphan_lock);
2213 if (root->orphan_item_inserted &&
2214 btrfs_root_refs(&root->root_item) > 0) {
2215 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2216 root->root_key.objectid);
2218 root->orphan_item_inserted = 0;
2222 WARN_ON(block_rsv->size > 0);
2223 btrfs_free_block_rsv(root, block_rsv);
2228 * This creates an orphan entry for the given inode in case something goes
2229 * wrong in the middle of an unlink/truncate.
2231 * NOTE: caller of this function should reserve 5 units of metadata for
2234 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2236 struct btrfs_root *root = BTRFS_I(inode)->root;
2237 struct btrfs_block_rsv *block_rsv = NULL;
2242 if (!root->orphan_block_rsv) {
2243 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2248 spin_lock(&root->orphan_lock);
2249 if (!root->orphan_block_rsv) {
2250 root->orphan_block_rsv = block_rsv;
2251 } else if (block_rsv) {
2252 btrfs_free_block_rsv(root, block_rsv);
2256 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2257 &BTRFS_I(inode)->runtime_flags)) {
2260 * For proper ENOSPC handling, we should do orphan
2261 * cleanup when mounting. But this introduces backward
2262 * compatibility issue.
2264 if (!xchg(&root->orphan_item_inserted, 1))
2270 atomic_inc(&root->orphan_inodes);
2273 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2274 &BTRFS_I(inode)->runtime_flags))
2276 spin_unlock(&root->orphan_lock);
2278 /* grab metadata reservation from transaction handle */
2280 ret = btrfs_orphan_reserve_metadata(trans, inode);
2281 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2284 /* insert an orphan item to track this unlinked/truncated file */
2286 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2287 if (ret && ret != -EEXIST) {
2288 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2289 &BTRFS_I(inode)->runtime_flags);
2290 btrfs_abort_transaction(trans, root, ret);
2296 /* insert an orphan item to track subvolume contains orphan files */
2298 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2299 root->root_key.objectid);
2300 if (ret && ret != -EEXIST) {
2301 btrfs_abort_transaction(trans, root, ret);
2309 * We have done the truncate/delete so we can go ahead and remove the orphan
2310 * item for this particular inode.
2312 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2314 struct btrfs_root *root = BTRFS_I(inode)->root;
2315 int delete_item = 0;
2316 int release_rsv = 0;
2319 spin_lock(&root->orphan_lock);
2320 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2321 &BTRFS_I(inode)->runtime_flags))
2324 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2325 &BTRFS_I(inode)->runtime_flags))
2327 spin_unlock(&root->orphan_lock);
2329 if (trans && delete_item) {
2330 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2331 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2335 btrfs_orphan_release_metadata(inode);
2336 atomic_dec(&root->orphan_inodes);
2343 * this cleans up any orphans that may be left on the list from the last use
2346 int btrfs_orphan_cleanup(struct btrfs_root *root)
2348 struct btrfs_path *path;
2349 struct extent_buffer *leaf;
2350 struct btrfs_key key, found_key;
2351 struct btrfs_trans_handle *trans;
2352 struct inode *inode;
2353 u64 last_objectid = 0;
2354 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2356 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2359 path = btrfs_alloc_path();
2366 key.objectid = BTRFS_ORPHAN_OBJECTID;
2367 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2368 key.offset = (u64)-1;
2371 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2376 * if ret == 0 means we found what we were searching for, which
2377 * is weird, but possible, so only screw with path if we didn't
2378 * find the key and see if we have stuff that matches
2382 if (path->slots[0] == 0)
2387 /* pull out the item */
2388 leaf = path->nodes[0];
2389 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2391 /* make sure the item matches what we want */
2392 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2394 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2397 /* release the path since we're done with it */
2398 btrfs_release_path(path);
2401 * this is where we are basically btrfs_lookup, without the
2402 * crossing root thing. we store the inode number in the
2403 * offset of the orphan item.
2406 if (found_key.offset == last_objectid) {
2407 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2408 "stopping orphan cleanup\n");
2413 last_objectid = found_key.offset;
2415 found_key.objectid = found_key.offset;
2416 found_key.type = BTRFS_INODE_ITEM_KEY;
2417 found_key.offset = 0;
2418 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2419 ret = PTR_RET(inode);
2420 if (ret && ret != -ESTALE)
2423 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2424 struct btrfs_root *dead_root;
2425 struct btrfs_fs_info *fs_info = root->fs_info;
2426 int is_dead_root = 0;
2429 * this is an orphan in the tree root. Currently these
2430 * could come from 2 sources:
2431 * a) a snapshot deletion in progress
2432 * b) a free space cache inode
2433 * We need to distinguish those two, as the snapshot
2434 * orphan must not get deleted.
2435 * find_dead_roots already ran before us, so if this
2436 * is a snapshot deletion, we should find the root
2437 * in the dead_roots list
2439 spin_lock(&fs_info->trans_lock);
2440 list_for_each_entry(dead_root, &fs_info->dead_roots,
2442 if (dead_root->root_key.objectid ==
2443 found_key.objectid) {
2448 spin_unlock(&fs_info->trans_lock);
2450 /* prevent this orphan from being found again */
2451 key.offset = found_key.objectid - 1;
2456 * Inode is already gone but the orphan item is still there,
2457 * kill the orphan item.
2459 if (ret == -ESTALE) {
2460 trans = btrfs_start_transaction(root, 1);
2461 if (IS_ERR(trans)) {
2462 ret = PTR_ERR(trans);
2465 printk(KERN_ERR "auto deleting %Lu\n",
2466 found_key.objectid);
2467 ret = btrfs_del_orphan_item(trans, root,
2468 found_key.objectid);
2469 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2470 btrfs_end_transaction(trans, root);
2475 * add this inode to the orphan list so btrfs_orphan_del does
2476 * the proper thing when we hit it
2478 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2479 &BTRFS_I(inode)->runtime_flags);
2481 /* if we have links, this was a truncate, lets do that */
2482 if (inode->i_nlink) {
2483 if (!S_ISREG(inode->i_mode)) {
2490 /* 1 for the orphan item deletion. */
2491 trans = btrfs_start_transaction(root, 1);
2492 if (IS_ERR(trans)) {
2493 ret = PTR_ERR(trans);
2496 ret = btrfs_orphan_add(trans, inode);
2497 btrfs_end_transaction(trans, root);
2501 ret = btrfs_truncate(inode);
2506 /* this will do delete_inode and everything for us */
2511 /* release the path since we're done with it */
2512 btrfs_release_path(path);
2514 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2516 if (root->orphan_block_rsv)
2517 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2520 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2521 trans = btrfs_join_transaction(root);
2523 btrfs_end_transaction(trans, root);
2527 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2529 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2533 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2534 btrfs_free_path(path);
2539 * very simple check to peek ahead in the leaf looking for xattrs. If we
2540 * don't find any xattrs, we know there can't be any acls.
2542 * slot is the slot the inode is in, objectid is the objectid of the inode
2544 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2545 int slot, u64 objectid)
2547 u32 nritems = btrfs_header_nritems(leaf);
2548 struct btrfs_key found_key;
2552 while (slot < nritems) {
2553 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2555 /* we found a different objectid, there must not be acls */
2556 if (found_key.objectid != objectid)
2559 /* we found an xattr, assume we've got an acl */
2560 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2564 * we found a key greater than an xattr key, there can't
2565 * be any acls later on
2567 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2574 * it goes inode, inode backrefs, xattrs, extents,
2575 * so if there are a ton of hard links to an inode there can
2576 * be a lot of backrefs. Don't waste time searching too hard,
2577 * this is just an optimization
2582 /* we hit the end of the leaf before we found an xattr or
2583 * something larger than an xattr. We have to assume the inode
2590 * read an inode from the btree into the in-memory inode
2592 static void btrfs_read_locked_inode(struct inode *inode)
2594 struct btrfs_path *path;
2595 struct extent_buffer *leaf;
2596 struct btrfs_inode_item *inode_item;
2597 struct btrfs_timespec *tspec;
2598 struct btrfs_root *root = BTRFS_I(inode)->root;
2599 struct btrfs_key location;
2603 bool filled = false;
2605 ret = btrfs_fill_inode(inode, &rdev);
2609 path = btrfs_alloc_path();
2613 path->leave_spinning = 1;
2614 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2616 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2620 leaf = path->nodes[0];
2625 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2626 struct btrfs_inode_item);
2627 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2628 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2629 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
2630 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
2631 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2633 tspec = btrfs_inode_atime(inode_item);
2634 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2635 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2637 tspec = btrfs_inode_mtime(inode_item);
2638 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2639 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2641 tspec = btrfs_inode_ctime(inode_item);
2642 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2643 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2645 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2646 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2647 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
2650 * If we were modified in the current generation and evicted from memory
2651 * and then re-read we need to do a full sync since we don't have any
2652 * idea about which extents were modified before we were evicted from
2655 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
2656 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2657 &BTRFS_I(inode)->runtime_flags);
2659 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2660 inode->i_generation = BTRFS_I(inode)->generation;
2662 rdev = btrfs_inode_rdev(leaf, inode_item);
2664 BTRFS_I(inode)->index_cnt = (u64)-1;
2665 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2668 * try to precache a NULL acl entry for files that don't have
2669 * any xattrs or acls
2671 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2674 cache_no_acl(inode);
2676 btrfs_free_path(path);
2678 switch (inode->i_mode & S_IFMT) {
2680 inode->i_mapping->a_ops = &btrfs_aops;
2681 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2682 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2683 inode->i_fop = &btrfs_file_operations;
2684 inode->i_op = &btrfs_file_inode_operations;
2687 inode->i_fop = &btrfs_dir_file_operations;
2688 if (root == root->fs_info->tree_root)
2689 inode->i_op = &btrfs_dir_ro_inode_operations;
2691 inode->i_op = &btrfs_dir_inode_operations;
2694 inode->i_op = &btrfs_symlink_inode_operations;
2695 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2696 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2699 inode->i_op = &btrfs_special_inode_operations;
2700 init_special_inode(inode, inode->i_mode, rdev);
2704 btrfs_update_iflags(inode);
2708 btrfs_free_path(path);
2709 make_bad_inode(inode);
2713 * given a leaf and an inode, copy the inode fields into the leaf
2715 static void fill_inode_item(struct btrfs_trans_handle *trans,
2716 struct extent_buffer *leaf,
2717 struct btrfs_inode_item *item,
2718 struct inode *inode)
2720 struct btrfs_map_token token;
2722 btrfs_init_map_token(&token);
2724 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
2725 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
2726 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
2728 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
2729 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
2731 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
2732 inode->i_atime.tv_sec, &token);
2733 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
2734 inode->i_atime.tv_nsec, &token);
2736 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
2737 inode->i_mtime.tv_sec, &token);
2738 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
2739 inode->i_mtime.tv_nsec, &token);
2741 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
2742 inode->i_ctime.tv_sec, &token);
2743 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
2744 inode->i_ctime.tv_nsec, &token);
2746 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
2748 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
2750 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
2751 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
2752 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
2753 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
2754 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
2758 * copy everything in the in-memory inode into the btree.
2760 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2761 struct btrfs_root *root, struct inode *inode)
2763 struct btrfs_inode_item *inode_item;
2764 struct btrfs_path *path;
2765 struct extent_buffer *leaf;
2768 path = btrfs_alloc_path();
2772 path->leave_spinning = 1;
2773 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2781 btrfs_unlock_up_safe(path, 1);
2782 leaf = path->nodes[0];
2783 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2784 struct btrfs_inode_item);
2786 fill_inode_item(trans, leaf, inode_item, inode);
2787 btrfs_mark_buffer_dirty(leaf);
2788 btrfs_set_inode_last_trans(trans, inode);
2791 btrfs_free_path(path);
2796 * copy everything in the in-memory inode into the btree.
2798 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2799 struct btrfs_root *root, struct inode *inode)
2804 * If the inode is a free space inode, we can deadlock during commit
2805 * if we put it into the delayed code.
2807 * The data relocation inode should also be directly updated
2810 if (!btrfs_is_free_space_inode(inode)
2811 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2812 btrfs_update_root_times(trans, root);
2814 ret = btrfs_delayed_update_inode(trans, root, inode);
2816 btrfs_set_inode_last_trans(trans, inode);
2820 return btrfs_update_inode_item(trans, root, inode);
2823 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2824 struct btrfs_root *root,
2825 struct inode *inode)
2829 ret = btrfs_update_inode(trans, root, inode);
2831 return btrfs_update_inode_item(trans, root, inode);
2836 * unlink helper that gets used here in inode.c and in the tree logging
2837 * recovery code. It remove a link in a directory with a given name, and
2838 * also drops the back refs in the inode to the directory
2840 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2841 struct btrfs_root *root,
2842 struct inode *dir, struct inode *inode,
2843 const char *name, int name_len)
2845 struct btrfs_path *path;
2847 struct extent_buffer *leaf;
2848 struct btrfs_dir_item *di;
2849 struct btrfs_key key;
2851 u64 ino = btrfs_ino(inode);
2852 u64 dir_ino = btrfs_ino(dir);
2854 path = btrfs_alloc_path();
2860 path->leave_spinning = 1;
2861 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2862 name, name_len, -1);
2871 leaf = path->nodes[0];
2872 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2873 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2876 btrfs_release_path(path);
2878 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2881 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2882 "inode %llu parent %llu\n", name_len, name,
2883 (unsigned long long)ino, (unsigned long long)dir_ino);
2884 btrfs_abort_transaction(trans, root, ret);
2888 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2890 btrfs_abort_transaction(trans, root, ret);
2894 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2896 if (ret != 0 && ret != -ENOENT) {
2897 btrfs_abort_transaction(trans, root, ret);
2901 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2906 btrfs_free_path(path);
2910 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2911 inode_inc_iversion(inode);
2912 inode_inc_iversion(dir);
2913 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2914 ret = btrfs_update_inode(trans, root, dir);
2919 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2920 struct btrfs_root *root,
2921 struct inode *dir, struct inode *inode,
2922 const char *name, int name_len)
2925 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2927 btrfs_drop_nlink(inode);
2928 ret = btrfs_update_inode(trans, root, inode);
2934 /* helper to check if there is any shared block in the path */
2935 static int check_path_shared(struct btrfs_root *root,
2936 struct btrfs_path *path)
2938 struct extent_buffer *eb;
2942 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2945 if (!path->nodes[level])
2947 eb = path->nodes[level];
2948 if (!btrfs_block_can_be_shared(root, eb))
2950 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2959 * helper to start transaction for unlink and rmdir.
2961 * unlink and rmdir are special in btrfs, they do not always free space.
2962 * so in enospc case, we should make sure they will free space before
2963 * allowing them to use the global metadata reservation.
2965 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2966 struct dentry *dentry)
2968 struct btrfs_trans_handle *trans;
2969 struct btrfs_root *root = BTRFS_I(dir)->root;
2970 struct btrfs_path *path;
2971 struct btrfs_dir_item *di;
2972 struct inode *inode = dentry->d_inode;
2977 u64 ino = btrfs_ino(inode);
2978 u64 dir_ino = btrfs_ino(dir);
2981 * 1 for the possible orphan item
2982 * 1 for the dir item
2983 * 1 for the dir index
2984 * 1 for the inode ref
2985 * 1 for the inode ref in the tree log
2986 * 2 for the dir entries in the log
2989 trans = btrfs_start_transaction(root, 8);
2990 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2993 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2994 return ERR_PTR(-ENOSPC);
2996 /* check if there is someone else holds reference */
2997 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2998 return ERR_PTR(-ENOSPC);
3000 if (atomic_read(&inode->i_count) > 2)
3001 return ERR_PTR(-ENOSPC);
3003 if (xchg(&root->fs_info->enospc_unlink, 1))
3004 return ERR_PTR(-ENOSPC);
3006 path = btrfs_alloc_path();
3008 root->fs_info->enospc_unlink = 0;
3009 return ERR_PTR(-ENOMEM);
3012 /* 1 for the orphan item */
3013 trans = btrfs_start_transaction(root, 1);
3014 if (IS_ERR(trans)) {
3015 btrfs_free_path(path);
3016 root->fs_info->enospc_unlink = 0;
3020 path->skip_locking = 1;
3021 path->search_commit_root = 1;
3023 ret = btrfs_lookup_inode(trans, root, path,
3024 &BTRFS_I(dir)->location, 0);
3030 if (check_path_shared(root, path))
3035 btrfs_release_path(path);
3037 ret = btrfs_lookup_inode(trans, root, path,
3038 &BTRFS_I(inode)->location, 0);
3044 if (check_path_shared(root, path))
3049 btrfs_release_path(path);
3051 if (ret == 0 && S_ISREG(inode->i_mode)) {
3052 ret = btrfs_lookup_file_extent(trans, root, path,
3058 BUG_ON(ret == 0); /* Corruption */
3059 if (check_path_shared(root, path))
3061 btrfs_release_path(path);
3069 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3070 dentry->d_name.name, dentry->d_name.len, 0);
3076 if (check_path_shared(root, path))
3082 btrfs_release_path(path);
3084 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3085 dentry->d_name.len, ino, dir_ino, 0,
3092 if (check_path_shared(root, path))
3095 btrfs_release_path(path);
3098 * This is a commit root search, if we can lookup inode item and other
3099 * relative items in the commit root, it means the transaction of
3100 * dir/file creation has been committed, and the dir index item that we
3101 * delay to insert has also been inserted into the commit root. So
3102 * we needn't worry about the delayed insertion of the dir index item
3105 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3106 dentry->d_name.name, dentry->d_name.len, 0);
3111 BUG_ON(ret == -ENOENT);
3112 if (check_path_shared(root, path))
3117 btrfs_free_path(path);
3118 /* Migrate the orphan reservation over */
3120 err = btrfs_block_rsv_migrate(trans->block_rsv,
3121 &root->fs_info->global_block_rsv,
3122 trans->bytes_reserved);
3125 btrfs_end_transaction(trans, root);
3126 root->fs_info->enospc_unlink = 0;
3127 return ERR_PTR(err);
3130 trans->block_rsv = &root->fs_info->global_block_rsv;
3134 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3135 struct btrfs_root *root)
3137 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3138 btrfs_block_rsv_release(root, trans->block_rsv,
3139 trans->bytes_reserved);
3140 trans->block_rsv = &root->fs_info->trans_block_rsv;
3141 BUG_ON(!root->fs_info->enospc_unlink);
3142 root->fs_info->enospc_unlink = 0;
3144 btrfs_end_transaction(trans, root);
3147 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3149 struct btrfs_root *root = BTRFS_I(dir)->root;
3150 struct btrfs_trans_handle *trans;
3151 struct inode *inode = dentry->d_inode;
3154 trans = __unlink_start_trans(dir, dentry);
3156 return PTR_ERR(trans);
3158 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3160 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3161 dentry->d_name.name, dentry->d_name.len);
3165 if (inode->i_nlink == 0) {
3166 ret = btrfs_orphan_add(trans, inode);
3172 __unlink_end_trans(trans, root);
3173 btrfs_btree_balance_dirty(root);
3177 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3178 struct btrfs_root *root,
3179 struct inode *dir, u64 objectid,
3180 const char *name, int name_len)
3182 struct btrfs_path *path;
3183 struct extent_buffer *leaf;
3184 struct btrfs_dir_item *di;
3185 struct btrfs_key key;
3188 u64 dir_ino = btrfs_ino(dir);
3190 path = btrfs_alloc_path();
3194 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3195 name, name_len, -1);
3196 if (IS_ERR_OR_NULL(di)) {
3204 leaf = path->nodes[0];
3205 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3206 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3207 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3209 btrfs_abort_transaction(trans, root, ret);
3212 btrfs_release_path(path);
3214 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3215 objectid, root->root_key.objectid,
3216 dir_ino, &index, name, name_len);
3218 if (ret != -ENOENT) {
3219 btrfs_abort_transaction(trans, root, ret);
3222 di = btrfs_search_dir_index_item(root, path, dir_ino,
3224 if (IS_ERR_OR_NULL(di)) {
3229 btrfs_abort_transaction(trans, root, ret);
3233 leaf = path->nodes[0];
3234 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3235 btrfs_release_path(path);
3238 btrfs_release_path(path);
3240 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3242 btrfs_abort_transaction(trans, root, ret);
3246 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3247 inode_inc_iversion(dir);
3248 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3249 ret = btrfs_update_inode_fallback(trans, root, dir);
3251 btrfs_abort_transaction(trans, root, ret);
3253 btrfs_free_path(path);
3257 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3259 struct inode *inode = dentry->d_inode;
3261 struct btrfs_root *root = BTRFS_I(dir)->root;
3262 struct btrfs_trans_handle *trans;
3264 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3266 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3269 trans = __unlink_start_trans(dir, dentry);
3271 return PTR_ERR(trans);
3273 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3274 err = btrfs_unlink_subvol(trans, root, dir,
3275 BTRFS_I(inode)->location.objectid,
3276 dentry->d_name.name,
3277 dentry->d_name.len);
3281 err = btrfs_orphan_add(trans, inode);
3285 /* now the directory is empty */
3286 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3287 dentry->d_name.name, dentry->d_name.len);
3289 btrfs_i_size_write(inode, 0);
3291 __unlink_end_trans(trans, root);
3292 btrfs_btree_balance_dirty(root);
3298 * this can truncate away extent items, csum items and directory items.
3299 * It starts at a high offset and removes keys until it can't find
3300 * any higher than new_size
3302 * csum items that cross the new i_size are truncated to the new size
3305 * min_type is the minimum key type to truncate down to. If set to 0, this
3306 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3308 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3309 struct btrfs_root *root,
3310 struct inode *inode,
3311 u64 new_size, u32 min_type)
3313 struct btrfs_path *path;
3314 struct extent_buffer *leaf;
3315 struct btrfs_file_extent_item *fi;
3316 struct btrfs_key key;
3317 struct btrfs_key found_key;
3318 u64 extent_start = 0;
3319 u64 extent_num_bytes = 0;
3320 u64 extent_offset = 0;
3322 u64 mask = root->sectorsize - 1;
3323 u32 found_type = (u8)-1;
3326 int pending_del_nr = 0;
3327 int pending_del_slot = 0;
3328 int extent_type = -1;
3331 u64 ino = btrfs_ino(inode);
3333 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3335 path = btrfs_alloc_path();
3341 * We want to drop from the next block forward in case this new size is
3342 * not block aligned since we will be keeping the last block of the
3343 * extent just the way it is.
3345 if (root->ref_cows || root == root->fs_info->tree_root)
3346 btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0);
3349 * This function is also used to drop the items in the log tree before
3350 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3351 * it is used to drop the loged items. So we shouldn't kill the delayed
3354 if (min_type == 0 && root == BTRFS_I(inode)->root)
3355 btrfs_kill_delayed_inode_items(inode);
3358 key.offset = (u64)-1;
3362 path->leave_spinning = 1;
3363 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3370 /* there are no items in the tree for us to truncate, we're
3373 if (path->slots[0] == 0)
3380 leaf = path->nodes[0];
3381 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3382 found_type = btrfs_key_type(&found_key);
3384 if (found_key.objectid != ino)
3387 if (found_type < min_type)
3390 item_end = found_key.offset;
3391 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3392 fi = btrfs_item_ptr(leaf, path->slots[0],
3393 struct btrfs_file_extent_item);
3394 extent_type = btrfs_file_extent_type(leaf, fi);
3395 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3397 btrfs_file_extent_num_bytes(leaf, fi);
3398 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3399 item_end += btrfs_file_extent_inline_len(leaf,
3404 if (found_type > min_type) {
3407 if (item_end < new_size)
3409 if (found_key.offset >= new_size)
3415 /* FIXME, shrink the extent if the ref count is only 1 */
3416 if (found_type != BTRFS_EXTENT_DATA_KEY)
3419 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3421 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3423 u64 orig_num_bytes =
3424 btrfs_file_extent_num_bytes(leaf, fi);
3425 extent_num_bytes = new_size -
3426 found_key.offset + root->sectorsize - 1;
3427 extent_num_bytes = extent_num_bytes &
3428 ~((u64)root->sectorsize - 1);
3429 btrfs_set_file_extent_num_bytes(leaf, fi,
3431 num_dec = (orig_num_bytes -
3433 if (root->ref_cows && extent_start != 0)
3434 inode_sub_bytes(inode, num_dec);
3435 btrfs_mark_buffer_dirty(leaf);
3438 btrfs_file_extent_disk_num_bytes(leaf,
3440 extent_offset = found_key.offset -
3441 btrfs_file_extent_offset(leaf, fi);
3443 /* FIXME blocksize != 4096 */
3444 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3445 if (extent_start != 0) {
3448 inode_sub_bytes(inode, num_dec);
3451 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3453 * we can't truncate inline items that have had
3457 btrfs_file_extent_compression(leaf, fi) == 0 &&
3458 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3459 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3460 u32 size = new_size - found_key.offset;
3462 if (root->ref_cows) {
3463 inode_sub_bytes(inode, item_end + 1 -
3467 btrfs_file_extent_calc_inline_size(size);
3468 btrfs_truncate_item(trans, root, path,
3470 } else if (root->ref_cows) {
3471 inode_sub_bytes(inode, item_end + 1 -
3477 if (!pending_del_nr) {
3478 /* no pending yet, add ourselves */
3479 pending_del_slot = path->slots[0];
3481 } else if (pending_del_nr &&
3482 path->slots[0] + 1 == pending_del_slot) {
3483 /* hop on the pending chunk */
3485 pending_del_slot = path->slots[0];
3492 if (found_extent && (root->ref_cows ||
3493 root == root->fs_info->tree_root)) {
3494 btrfs_set_path_blocking(path);
3495 ret = btrfs_free_extent(trans, root, extent_start,
3496 extent_num_bytes, 0,
3497 btrfs_header_owner(leaf),
3498 ino, extent_offset, 0);
3502 if (found_type == BTRFS_INODE_ITEM_KEY)
3505 if (path->slots[0] == 0 ||
3506 path->slots[0] != pending_del_slot) {
3507 if (pending_del_nr) {
3508 ret = btrfs_del_items(trans, root, path,
3512 btrfs_abort_transaction(trans,
3518 btrfs_release_path(path);
3525 if (pending_del_nr) {
3526 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3529 btrfs_abort_transaction(trans, root, ret);
3532 btrfs_free_path(path);
3537 * btrfs_truncate_page - read, zero a chunk and write a page
3538 * @inode - inode that we're zeroing
3539 * @from - the offset to start zeroing
3540 * @len - the length to zero, 0 to zero the entire range respective to the
3542 * @front - zero up to the offset instead of from the offset on
3544 * This will find the page for the "from" offset and cow the page and zero the
3545 * part we want to zero. This is used with truncate and hole punching.
3547 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
3550 struct address_space *mapping = inode->i_mapping;
3551 struct btrfs_root *root = BTRFS_I(inode)->root;
3552 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3553 struct btrfs_ordered_extent *ordered;
3554 struct extent_state *cached_state = NULL;
3556 u32 blocksize = root->sectorsize;
3557 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3558 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3560 gfp_t mask = btrfs_alloc_write_mask(mapping);
3565 if ((offset & (blocksize - 1)) == 0 &&
3566 (!len || ((len & (blocksize - 1)) == 0)))
3568 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3573 page = find_or_create_page(mapping, index, mask);
3575 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3580 page_start = page_offset(page);
3581 page_end = page_start + PAGE_CACHE_SIZE - 1;
3583 if (!PageUptodate(page)) {
3584 ret = btrfs_readpage(NULL, page);
3586 if (page->mapping != mapping) {
3588 page_cache_release(page);
3591 if (!PageUptodate(page)) {
3596 wait_on_page_writeback(page);
3598 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3599 set_page_extent_mapped(page);
3601 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3603 unlock_extent_cached(io_tree, page_start, page_end,
3604 &cached_state, GFP_NOFS);
3606 page_cache_release(page);
3607 btrfs_start_ordered_extent(inode, ordered, 1);
3608 btrfs_put_ordered_extent(ordered);
3612 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3613 EXTENT_DIRTY | EXTENT_DELALLOC |
3614 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
3615 0, 0, &cached_state, GFP_NOFS);
3617 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3620 unlock_extent_cached(io_tree, page_start, page_end,
3621 &cached_state, GFP_NOFS);
3625 if (offset != PAGE_CACHE_SIZE) {
3627 len = PAGE_CACHE_SIZE - offset;
3630 memset(kaddr, 0, offset);
3632 memset(kaddr + offset, 0, len);
3633 flush_dcache_page(page);
3636 ClearPageChecked(page);
3637 set_page_dirty(page);
3638 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3643 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3645 page_cache_release(page);
3651 * This function puts in dummy file extents for the area we're creating a hole
3652 * for. So if we are truncating this file to a larger size we need to insert
3653 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3654 * the range between oldsize and size
3656 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3658 struct btrfs_trans_handle *trans;
3659 struct btrfs_root *root = BTRFS_I(inode)->root;
3660 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3661 struct extent_map *em = NULL;
3662 struct extent_state *cached_state = NULL;
3663 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3664 u64 mask = root->sectorsize - 1;
3665 u64 hole_start = (oldsize + mask) & ~mask;
3666 u64 block_end = (size + mask) & ~mask;
3672 if (size <= hole_start)
3676 struct btrfs_ordered_extent *ordered;
3677 btrfs_wait_ordered_range(inode, hole_start,
3678 block_end - hole_start);
3679 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3681 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3684 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3685 &cached_state, GFP_NOFS);
3686 btrfs_put_ordered_extent(ordered);
3689 cur_offset = hole_start;
3691 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3692 block_end - cur_offset, 0);
3698 last_byte = min(extent_map_end(em), block_end);
3699 last_byte = (last_byte + mask) & ~mask;
3700 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3701 struct extent_map *hole_em;
3702 hole_size = last_byte - cur_offset;
3704 trans = btrfs_start_transaction(root, 3);
3705 if (IS_ERR(trans)) {
3706 err = PTR_ERR(trans);
3710 err = btrfs_drop_extents(trans, root, inode,
3712 cur_offset + hole_size, 1);
3714 btrfs_abort_transaction(trans, root, err);
3715 btrfs_end_transaction(trans, root);
3719 err = btrfs_insert_file_extent(trans, root,
3720 btrfs_ino(inode), cur_offset, 0,
3721 0, hole_size, 0, hole_size,
3724 btrfs_abort_transaction(trans, root, err);
3725 btrfs_end_transaction(trans, root);
3729 btrfs_drop_extent_cache(inode, cur_offset,
3730 cur_offset + hole_size - 1, 0);
3731 hole_em = alloc_extent_map();
3733 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3734 &BTRFS_I(inode)->runtime_flags);
3737 hole_em->start = cur_offset;
3738 hole_em->len = hole_size;
3739 hole_em->orig_start = cur_offset;
3741 hole_em->block_start = EXTENT_MAP_HOLE;
3742 hole_em->block_len = 0;
3743 hole_em->orig_block_len = 0;
3744 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
3745 hole_em->compress_type = BTRFS_COMPRESS_NONE;
3746 hole_em->generation = trans->transid;
3749 write_lock(&em_tree->lock);
3750 err = add_extent_mapping(em_tree, hole_em);
3752 list_move(&hole_em->list,
3753 &em_tree->modified_extents);
3754 write_unlock(&em_tree->lock);
3757 btrfs_drop_extent_cache(inode, cur_offset,
3761 free_extent_map(hole_em);
3763 btrfs_update_inode(trans, root, inode);
3764 btrfs_end_transaction(trans, root);
3766 free_extent_map(em);
3768 cur_offset = last_byte;
3769 if (cur_offset >= block_end)
3773 free_extent_map(em);
3774 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3779 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
3781 struct btrfs_root *root = BTRFS_I(inode)->root;
3782 struct btrfs_trans_handle *trans;
3783 loff_t oldsize = i_size_read(inode);
3784 loff_t newsize = attr->ia_size;
3785 int mask = attr->ia_valid;
3788 if (newsize == oldsize)
3792 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
3793 * special case where we need to update the times despite not having
3794 * these flags set. For all other operations the VFS set these flags
3795 * explicitly if it wants a timestamp update.
3797 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
3798 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
3800 if (newsize > oldsize) {
3801 truncate_pagecache(inode, oldsize, newsize);
3802 ret = btrfs_cont_expand(inode, oldsize, newsize);
3806 trans = btrfs_start_transaction(root, 1);
3808 return PTR_ERR(trans);
3810 i_size_write(inode, newsize);
3811 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3812 ret = btrfs_update_inode(trans, root, inode);
3813 btrfs_end_transaction(trans, root);
3817 * We're truncating a file that used to have good data down to
3818 * zero. Make sure it gets into the ordered flush list so that
3819 * any new writes get down to disk quickly.
3822 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3823 &BTRFS_I(inode)->runtime_flags);
3826 * 1 for the orphan item we're going to add
3827 * 1 for the orphan item deletion.
3829 trans = btrfs_start_transaction(root, 2);
3831 return PTR_ERR(trans);
3834 * We need to do this in case we fail at _any_ point during the
3835 * actual truncate. Once we do the truncate_setsize we could
3836 * invalidate pages which forces any outstanding ordered io to
3837 * be instantly completed which will give us extents that need
3838 * to be truncated. If we fail to get an orphan inode down we
3839 * could have left over extents that were never meant to live,
3840 * so we need to garuntee from this point on that everything
3841 * will be consistent.
3843 ret = btrfs_orphan_add(trans, inode);
3844 btrfs_end_transaction(trans, root);
3848 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3849 truncate_setsize(inode, newsize);
3850 ret = btrfs_truncate(inode);
3851 if (ret && inode->i_nlink)
3852 btrfs_orphan_del(NULL, inode);
3858 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3860 struct inode *inode = dentry->d_inode;
3861 struct btrfs_root *root = BTRFS_I(inode)->root;
3864 if (btrfs_root_readonly(root))
3867 err = inode_change_ok(inode, attr);
3871 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3872 err = btrfs_setsize(inode, attr);
3877 if (attr->ia_valid) {
3878 setattr_copy(inode, attr);
3879 inode_inc_iversion(inode);
3880 err = btrfs_dirty_inode(inode);
3882 if (!err && attr->ia_valid & ATTR_MODE)
3883 err = btrfs_acl_chmod(inode);
3889 void btrfs_evict_inode(struct inode *inode)
3891 struct btrfs_trans_handle *trans;
3892 struct btrfs_root *root = BTRFS_I(inode)->root;
3893 struct btrfs_block_rsv *rsv, *global_rsv;
3894 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3897 trace_btrfs_inode_evict(inode);
3899 truncate_inode_pages(&inode->i_data, 0);
3900 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3901 btrfs_is_free_space_inode(inode)))
3904 if (is_bad_inode(inode)) {
3905 btrfs_orphan_del(NULL, inode);
3908 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3909 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3911 if (root->fs_info->log_root_recovering) {
3912 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3913 &BTRFS_I(inode)->runtime_flags));
3917 if (inode->i_nlink > 0) {
3918 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3922 ret = btrfs_commit_inode_delayed_inode(inode);
3924 btrfs_orphan_del(NULL, inode);
3928 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3930 btrfs_orphan_del(NULL, inode);
3933 rsv->size = min_size;
3935 global_rsv = &root->fs_info->global_block_rsv;
3937 btrfs_i_size_write(inode, 0);
3940 * This is a bit simpler than btrfs_truncate since we've already
3941 * reserved our space for our orphan item in the unlink, so we just
3942 * need to reserve some slack space in case we add bytes and update
3943 * inode item when doing the truncate.
3946 ret = btrfs_block_rsv_refill(root, rsv, min_size,
3947 BTRFS_RESERVE_FLUSH_LIMIT);
3950 * Try and steal from the global reserve since we will
3951 * likely not use this space anyway, we want to try as
3952 * hard as possible to get this to work.
3955 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3958 printk(KERN_WARNING "Could not get space for a "
3959 "delete, will truncate on mount %d\n", ret);
3960 btrfs_orphan_del(NULL, inode);
3961 btrfs_free_block_rsv(root, rsv);
3965 trans = btrfs_join_transaction(root);
3966 if (IS_ERR(trans)) {
3967 btrfs_orphan_del(NULL, inode);
3968 btrfs_free_block_rsv(root, rsv);
3972 trans->block_rsv = rsv;
3974 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3978 trans->block_rsv = &root->fs_info->trans_block_rsv;
3979 btrfs_end_transaction(trans, root);
3981 btrfs_btree_balance_dirty(root);
3984 btrfs_free_block_rsv(root, rsv);
3987 trans->block_rsv = root->orphan_block_rsv;
3988 ret = btrfs_orphan_del(trans, inode);
3992 trans->block_rsv = &root->fs_info->trans_block_rsv;
3993 if (!(root == root->fs_info->tree_root ||
3994 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3995 btrfs_return_ino(root, btrfs_ino(inode));
3997 btrfs_end_transaction(trans, root);
3998 btrfs_btree_balance_dirty(root);
4005 * this returns the key found in the dir entry in the location pointer.
4006 * If no dir entries were found, location->objectid is 0.
4008 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4009 struct btrfs_key *location)
4011 const char *name = dentry->d_name.name;
4012 int namelen = dentry->d_name.len;
4013 struct btrfs_dir_item *di;
4014 struct btrfs_path *path;
4015 struct btrfs_root *root = BTRFS_I(dir)->root;
4018 path = btrfs_alloc_path();
4022 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4027 if (IS_ERR_OR_NULL(di))
4030 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4032 btrfs_free_path(path);
4035 location->objectid = 0;
4040 * when we hit a tree root in a directory, the btrfs part of the inode
4041 * needs to be changed to reflect the root directory of the tree root. This
4042 * is kind of like crossing a mount point.
4044 static int fixup_tree_root_location(struct btrfs_root *root,
4046 struct dentry *dentry,
4047 struct btrfs_key *location,
4048 struct btrfs_root **sub_root)
4050 struct btrfs_path *path;
4051 struct btrfs_root *new_root;
4052 struct btrfs_root_ref *ref;
4053 struct extent_buffer *leaf;
4057 path = btrfs_alloc_path();
4064 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4065 BTRFS_I(dir)->root->root_key.objectid,
4066 location->objectid);
4073 leaf = path->nodes[0];
4074 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4075 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4076 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4079 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4080 (unsigned long)(ref + 1),
4081 dentry->d_name.len);
4085 btrfs_release_path(path);
4087 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4088 if (IS_ERR(new_root)) {
4089 err = PTR_ERR(new_root);
4093 if (btrfs_root_refs(&new_root->root_item) == 0) {
4098 *sub_root = new_root;
4099 location->objectid = btrfs_root_dirid(&new_root->root_item);
4100 location->type = BTRFS_INODE_ITEM_KEY;
4101 location->offset = 0;
4104 btrfs_free_path(path);
4108 static void inode_tree_add(struct inode *inode)
4110 struct btrfs_root *root = BTRFS_I(inode)->root;
4111 struct btrfs_inode *entry;
4113 struct rb_node *parent;
4114 u64 ino = btrfs_ino(inode);
4116 p = &root->inode_tree.rb_node;
4119 if (inode_unhashed(inode))
4122 spin_lock(&root->inode_lock);
4125 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4127 if (ino < btrfs_ino(&entry->vfs_inode))
4128 p = &parent->rb_left;
4129 else if (ino > btrfs_ino(&entry->vfs_inode))
4130 p = &parent->rb_right;
4132 WARN_ON(!(entry->vfs_inode.i_state &
4133 (I_WILL_FREE | I_FREEING)));
4134 rb_erase(parent, &root->inode_tree);
4135 RB_CLEAR_NODE(parent);
4136 spin_unlock(&root->inode_lock);
4140 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4141 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4142 spin_unlock(&root->inode_lock);
4145 static void inode_tree_del(struct inode *inode)
4147 struct btrfs_root *root = BTRFS_I(inode)->root;
4150 spin_lock(&root->inode_lock);
4151 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4152 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4153 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4154 empty = RB_EMPTY_ROOT(&root->inode_tree);
4156 spin_unlock(&root->inode_lock);
4159 * Free space cache has inodes in the tree root, but the tree root has a
4160 * root_refs of 0, so this could end up dropping the tree root as a
4161 * snapshot, so we need the extra !root->fs_info->tree_root check to
4162 * make sure we don't drop it.
4164 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4165 root != root->fs_info->tree_root) {
4166 synchronize_srcu(&root->fs_info->subvol_srcu);
4167 spin_lock(&root->inode_lock);
4168 empty = RB_EMPTY_ROOT(&root->inode_tree);
4169 spin_unlock(&root->inode_lock);
4171 btrfs_add_dead_root(root);
4175 void btrfs_invalidate_inodes(struct btrfs_root *root)
4177 struct rb_node *node;
4178 struct rb_node *prev;
4179 struct btrfs_inode *entry;
4180 struct inode *inode;
4183 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4185 spin_lock(&root->inode_lock);
4187 node = root->inode_tree.rb_node;
4191 entry = rb_entry(node, struct btrfs_inode, rb_node);
4193 if (objectid < btrfs_ino(&entry->vfs_inode))
4194 node = node->rb_left;
4195 else if (objectid > btrfs_ino(&entry->vfs_inode))
4196 node = node->rb_right;
4202 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4203 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4207 prev = rb_next(prev);
4211 entry = rb_entry(node, struct btrfs_inode, rb_node);
4212 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4213 inode = igrab(&entry->vfs_inode);
4215 spin_unlock(&root->inode_lock);
4216 if (atomic_read(&inode->i_count) > 1)
4217 d_prune_aliases(inode);
4219 * btrfs_drop_inode will have it removed from
4220 * the inode cache when its usage count
4225 spin_lock(&root->inode_lock);
4229 if (cond_resched_lock(&root->inode_lock))
4232 node = rb_next(node);
4234 spin_unlock(&root->inode_lock);
4237 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4239 struct btrfs_iget_args *args = p;
4240 inode->i_ino = args->ino;
4241 BTRFS_I(inode)->root = args->root;
4245 static int btrfs_find_actor(struct inode *inode, void *opaque)
4247 struct btrfs_iget_args *args = opaque;
4248 return args->ino == btrfs_ino(inode) &&
4249 args->root == BTRFS_I(inode)->root;
4252 static struct inode *btrfs_iget_locked(struct super_block *s,
4254 struct btrfs_root *root)
4256 struct inode *inode;
4257 struct btrfs_iget_args args;
4258 args.ino = objectid;
4261 inode = iget5_locked(s, objectid, btrfs_find_actor,
4262 btrfs_init_locked_inode,
4267 /* Get an inode object given its location and corresponding root.
4268 * Returns in *is_new if the inode was read from disk
4270 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4271 struct btrfs_root *root, int *new)
4273 struct inode *inode;
4275 inode = btrfs_iget_locked(s, location->objectid, root);
4277 return ERR_PTR(-ENOMEM);
4279 if (inode->i_state & I_NEW) {
4280 BTRFS_I(inode)->root = root;
4281 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4282 btrfs_read_locked_inode(inode);
4283 if (!is_bad_inode(inode)) {
4284 inode_tree_add(inode);
4285 unlock_new_inode(inode);
4289 unlock_new_inode(inode);
4291 inode = ERR_PTR(-ESTALE);
4298 static struct inode *new_simple_dir(struct super_block *s,
4299 struct btrfs_key *key,
4300 struct btrfs_root *root)
4302 struct inode *inode = new_inode(s);
4305 return ERR_PTR(-ENOMEM);
4307 BTRFS_I(inode)->root = root;
4308 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4309 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4311 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4312 inode->i_op = &btrfs_dir_ro_inode_operations;
4313 inode->i_fop = &simple_dir_operations;
4314 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4315 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4320 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4322 struct inode *inode;
4323 struct btrfs_root *root = BTRFS_I(dir)->root;
4324 struct btrfs_root *sub_root = root;
4325 struct btrfs_key location;
4329 if (dentry->d_name.len > BTRFS_NAME_LEN)
4330 return ERR_PTR(-ENAMETOOLONG);
4332 if (unlikely(d_need_lookup(dentry))) {
4333 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
4334 kfree(dentry->d_fsdata);
4335 dentry->d_fsdata = NULL;
4336 /* This thing is hashed, drop it for now */
4339 ret = btrfs_inode_by_name(dir, dentry, &location);
4343 return ERR_PTR(ret);
4345 if (location.objectid == 0)
4348 if (location.type == BTRFS_INODE_ITEM_KEY) {
4349 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4353 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4355 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4356 ret = fixup_tree_root_location(root, dir, dentry,
4357 &location, &sub_root);
4360 inode = ERR_PTR(ret);
4362 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4364 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4366 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4368 if (!IS_ERR(inode) && root != sub_root) {
4369 down_read(&root->fs_info->cleanup_work_sem);
4370 if (!(inode->i_sb->s_flags & MS_RDONLY))
4371 ret = btrfs_orphan_cleanup(sub_root);
4372 up_read(&root->fs_info->cleanup_work_sem);
4374 inode = ERR_PTR(ret);
4380 static int btrfs_dentry_delete(const struct dentry *dentry)
4382 struct btrfs_root *root;
4383 struct inode *inode = dentry->d_inode;
4385 if (!inode && !IS_ROOT(dentry))
4386 inode = dentry->d_parent->d_inode;
4389 root = BTRFS_I(inode)->root;
4390 if (btrfs_root_refs(&root->root_item) == 0)
4393 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4399 static void btrfs_dentry_release(struct dentry *dentry)
4401 if (dentry->d_fsdata)
4402 kfree(dentry->d_fsdata);
4405 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4410 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4411 if (unlikely(d_need_lookup(dentry))) {
4412 spin_lock(&dentry->d_lock);
4413 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4414 spin_unlock(&dentry->d_lock);
4419 unsigned char btrfs_filetype_table[] = {
4420 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4423 static int btrfs_real_readdir(struct file *filp, void *dirent,
4426 struct inode *inode = filp->f_dentry->d_inode;
4427 struct btrfs_root *root = BTRFS_I(inode)->root;
4428 struct btrfs_item *item;
4429 struct btrfs_dir_item *di;
4430 struct btrfs_key key;
4431 struct btrfs_key found_key;
4432 struct btrfs_path *path;
4433 struct list_head ins_list;
4434 struct list_head del_list;
4436 struct extent_buffer *leaf;
4438 unsigned char d_type;
4443 int key_type = BTRFS_DIR_INDEX_KEY;
4447 int is_curr = 0; /* filp->f_pos points to the current index? */
4449 /* FIXME, use a real flag for deciding about the key type */
4450 if (root->fs_info->tree_root == root)
4451 key_type = BTRFS_DIR_ITEM_KEY;
4453 /* special case for "." */
4454 if (filp->f_pos == 0) {
4455 over = filldir(dirent, ".", 1,
4456 filp->f_pos, btrfs_ino(inode), DT_DIR);
4461 /* special case for .., just use the back ref */
4462 if (filp->f_pos == 1) {
4463 u64 pino = parent_ino(filp->f_path.dentry);
4464 over = filldir(dirent, "..", 2,
4465 filp->f_pos, pino, DT_DIR);
4470 path = btrfs_alloc_path();
4476 if (key_type == BTRFS_DIR_INDEX_KEY) {
4477 INIT_LIST_HEAD(&ins_list);
4478 INIT_LIST_HEAD(&del_list);
4479 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4482 btrfs_set_key_type(&key, key_type);
4483 key.offset = filp->f_pos;
4484 key.objectid = btrfs_ino(inode);
4486 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4491 leaf = path->nodes[0];
4492 slot = path->slots[0];
4493 if (slot >= btrfs_header_nritems(leaf)) {
4494 ret = btrfs_next_leaf(root, path);
4502 item = btrfs_item_nr(leaf, slot);
4503 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4505 if (found_key.objectid != key.objectid)
4507 if (btrfs_key_type(&found_key) != key_type)
4509 if (found_key.offset < filp->f_pos)
4511 if (key_type == BTRFS_DIR_INDEX_KEY &&
4512 btrfs_should_delete_dir_index(&del_list,
4516 filp->f_pos = found_key.offset;
4519 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4521 di_total = btrfs_item_size(leaf, item);
4523 while (di_cur < di_total) {
4524 struct btrfs_key location;
4526 if (verify_dir_item(root, leaf, di))
4529 name_len = btrfs_dir_name_len(leaf, di);
4530 if (name_len <= sizeof(tmp_name)) {
4531 name_ptr = tmp_name;
4533 name_ptr = kmalloc(name_len, GFP_NOFS);
4539 read_extent_buffer(leaf, name_ptr,
4540 (unsigned long)(di + 1), name_len);
4542 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4543 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4546 /* is this a reference to our own snapshot? If so
4549 * In contrast to old kernels, we insert the snapshot's
4550 * dir item and dir index after it has been created, so
4551 * we won't find a reference to our own snapshot. We
4552 * still keep the following code for backward
4555 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4556 location.objectid == root->root_key.objectid) {
4560 over = filldir(dirent, name_ptr, name_len,
4561 found_key.offset, location.objectid,
4565 if (name_ptr != tmp_name)
4570 di_len = btrfs_dir_name_len(leaf, di) +
4571 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4573 di = (struct btrfs_dir_item *)((char *)di + di_len);
4579 if (key_type == BTRFS_DIR_INDEX_KEY) {
4582 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4588 /* Reached end of directory/root. Bump pos past the last item. */
4589 if (key_type == BTRFS_DIR_INDEX_KEY)
4591 * 32-bit glibc will use getdents64, but then strtol -
4592 * so the last number we can serve is this.
4594 filp->f_pos = 0x7fffffff;
4600 if (key_type == BTRFS_DIR_INDEX_KEY)
4601 btrfs_put_delayed_items(&ins_list, &del_list);
4602 btrfs_free_path(path);
4606 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4608 struct btrfs_root *root = BTRFS_I(inode)->root;
4609 struct btrfs_trans_handle *trans;
4611 bool nolock = false;
4613 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4616 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
4619 if (wbc->sync_mode == WB_SYNC_ALL) {
4621 trans = btrfs_join_transaction_nolock(root);
4623 trans = btrfs_join_transaction(root);
4625 return PTR_ERR(trans);
4626 ret = btrfs_commit_transaction(trans, root);
4632 * This is somewhat expensive, updating the tree every time the
4633 * inode changes. But, it is most likely to find the inode in cache.
4634 * FIXME, needs more benchmarking...there are no reasons other than performance
4635 * to keep or drop this code.
4637 int btrfs_dirty_inode(struct inode *inode)
4639 struct btrfs_root *root = BTRFS_I(inode)->root;
4640 struct btrfs_trans_handle *trans;
4643 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4646 trans = btrfs_join_transaction(root);
4648 return PTR_ERR(trans);
4650 ret = btrfs_update_inode(trans, root, inode);
4651 if (ret && ret == -ENOSPC) {
4652 /* whoops, lets try again with the full transaction */
4653 btrfs_end_transaction(trans, root);
4654 trans = btrfs_start_transaction(root, 1);
4656 return PTR_ERR(trans);
4658 ret = btrfs_update_inode(trans, root, inode);
4660 btrfs_end_transaction(trans, root);
4661 if (BTRFS_I(inode)->delayed_node)
4662 btrfs_balance_delayed_items(root);
4668 * This is a copy of file_update_time. We need this so we can return error on
4669 * ENOSPC for updating the inode in the case of file write and mmap writes.
4671 static int btrfs_update_time(struct inode *inode, struct timespec *now,
4674 struct btrfs_root *root = BTRFS_I(inode)->root;
4676 if (btrfs_root_readonly(root))
4679 if (flags & S_VERSION)
4680 inode_inc_iversion(inode);
4681 if (flags & S_CTIME)
4682 inode->i_ctime = *now;
4683 if (flags & S_MTIME)
4684 inode->i_mtime = *now;
4685 if (flags & S_ATIME)
4686 inode->i_atime = *now;
4687 return btrfs_dirty_inode(inode);
4691 * find the highest existing sequence number in a directory
4692 * and then set the in-memory index_cnt variable to reflect
4693 * free sequence numbers
4695 static int btrfs_set_inode_index_count(struct inode *inode)
4697 struct btrfs_root *root = BTRFS_I(inode)->root;
4698 struct btrfs_key key, found_key;
4699 struct btrfs_path *path;
4700 struct extent_buffer *leaf;
4703 key.objectid = btrfs_ino(inode);
4704 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4705 key.offset = (u64)-1;
4707 path = btrfs_alloc_path();
4711 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4714 /* FIXME: we should be able to handle this */
4720 * MAGIC NUMBER EXPLANATION:
4721 * since we search a directory based on f_pos we have to start at 2
4722 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4723 * else has to start at 2
4725 if (path->slots[0] == 0) {
4726 BTRFS_I(inode)->index_cnt = 2;
4732 leaf = path->nodes[0];
4733 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4735 if (found_key.objectid != btrfs_ino(inode) ||
4736 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4737 BTRFS_I(inode)->index_cnt = 2;
4741 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4743 btrfs_free_path(path);
4748 * helper to find a free sequence number in a given directory. This current
4749 * code is very simple, later versions will do smarter things in the btree
4751 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4755 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4756 ret = btrfs_inode_delayed_dir_index_count(dir);
4758 ret = btrfs_set_inode_index_count(dir);
4764 *index = BTRFS_I(dir)->index_cnt;
4765 BTRFS_I(dir)->index_cnt++;
4770 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4771 struct btrfs_root *root,
4773 const char *name, int name_len,
4774 u64 ref_objectid, u64 objectid,
4775 umode_t mode, u64 *index)
4777 struct inode *inode;
4778 struct btrfs_inode_item *inode_item;
4779 struct btrfs_key *location;
4780 struct btrfs_path *path;
4781 struct btrfs_inode_ref *ref;
4782 struct btrfs_key key[2];
4788 path = btrfs_alloc_path();
4790 return ERR_PTR(-ENOMEM);
4792 inode = new_inode(root->fs_info->sb);
4794 btrfs_free_path(path);
4795 return ERR_PTR(-ENOMEM);
4799 * we have to initialize this early, so we can reclaim the inode
4800 * number if we fail afterwards in this function.
4802 inode->i_ino = objectid;
4805 trace_btrfs_inode_request(dir);
4807 ret = btrfs_set_inode_index(dir, index);
4809 btrfs_free_path(path);
4811 return ERR_PTR(ret);
4815 * index_cnt is ignored for everything but a dir,
4816 * btrfs_get_inode_index_count has an explanation for the magic
4819 BTRFS_I(inode)->index_cnt = 2;
4820 BTRFS_I(inode)->root = root;
4821 BTRFS_I(inode)->generation = trans->transid;
4822 inode->i_generation = BTRFS_I(inode)->generation;
4825 * We could have gotten an inode number from somebody who was fsynced
4826 * and then removed in this same transaction, so let's just set full
4827 * sync since it will be a full sync anyway and this will blow away the
4828 * old info in the log.
4830 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
4837 key[0].objectid = objectid;
4838 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4842 * Start new inodes with an inode_ref. This is slightly more
4843 * efficient for small numbers of hard links since they will
4844 * be packed into one item. Extended refs will kick in if we
4845 * add more hard links than can fit in the ref item.
4847 key[1].objectid = objectid;
4848 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4849 key[1].offset = ref_objectid;
4851 sizes[0] = sizeof(struct btrfs_inode_item);
4852 sizes[1] = name_len + sizeof(*ref);
4854 path->leave_spinning = 1;
4855 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4859 inode_init_owner(inode, dir, mode);
4860 inode_set_bytes(inode, 0);
4861 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4862 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4863 struct btrfs_inode_item);
4864 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
4865 sizeof(*inode_item));
4866 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4868 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4869 struct btrfs_inode_ref);
4870 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4871 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4872 ptr = (unsigned long)(ref + 1);
4873 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4875 btrfs_mark_buffer_dirty(path->nodes[0]);
4876 btrfs_free_path(path);
4878 location = &BTRFS_I(inode)->location;
4879 location->objectid = objectid;
4880 location->offset = 0;
4881 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4883 btrfs_inherit_iflags(inode, dir);
4885 if (S_ISREG(mode)) {
4886 if (btrfs_test_opt(root, NODATASUM))
4887 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4888 if (btrfs_test_opt(root, NODATACOW))
4889 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4892 insert_inode_hash(inode);
4893 inode_tree_add(inode);
4895 trace_btrfs_inode_new(inode);
4896 btrfs_set_inode_last_trans(trans, inode);
4898 btrfs_update_root_times(trans, root);
4903 BTRFS_I(dir)->index_cnt--;
4904 btrfs_free_path(path);
4906 return ERR_PTR(ret);
4909 static inline u8 btrfs_inode_type(struct inode *inode)
4911 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4915 * utility function to add 'inode' into 'parent_inode' with
4916 * a give name and a given sequence number.
4917 * if 'add_backref' is true, also insert a backref from the
4918 * inode to the parent directory.
4920 int btrfs_add_link(struct btrfs_trans_handle *trans,
4921 struct inode *parent_inode, struct inode *inode,
4922 const char *name, int name_len, int add_backref, u64 index)
4925 struct btrfs_key key;
4926 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4927 u64 ino = btrfs_ino(inode);
4928 u64 parent_ino = btrfs_ino(parent_inode);
4930 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4931 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4934 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4938 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4939 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4940 key.objectid, root->root_key.objectid,
4941 parent_ino, index, name, name_len);
4942 } else if (add_backref) {
4943 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4947 /* Nothing to clean up yet */
4951 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4953 btrfs_inode_type(inode), index);
4954 if (ret == -EEXIST || ret == -EOVERFLOW)
4957 btrfs_abort_transaction(trans, root, ret);
4961 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4963 inode_inc_iversion(parent_inode);
4964 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4965 ret = btrfs_update_inode(trans, root, parent_inode);
4967 btrfs_abort_transaction(trans, root, ret);
4971 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4974 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4975 key.objectid, root->root_key.objectid,
4976 parent_ino, &local_index, name, name_len);
4978 } else if (add_backref) {
4982 err = btrfs_del_inode_ref(trans, root, name, name_len,
4983 ino, parent_ino, &local_index);
4988 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4989 struct inode *dir, struct dentry *dentry,
4990 struct inode *inode, int backref, u64 index)
4992 int err = btrfs_add_link(trans, dir, inode,
4993 dentry->d_name.name, dentry->d_name.len,
5000 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5001 umode_t mode, dev_t rdev)
5003 struct btrfs_trans_handle *trans;
5004 struct btrfs_root *root = BTRFS_I(dir)->root;
5005 struct inode *inode = NULL;
5011 if (!new_valid_dev(rdev))
5015 * 2 for inode item and ref
5017 * 1 for xattr if selinux is on
5019 trans = btrfs_start_transaction(root, 5);
5021 return PTR_ERR(trans);
5023 err = btrfs_find_free_ino(root, &objectid);
5027 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5028 dentry->d_name.len, btrfs_ino(dir), objectid,
5030 if (IS_ERR(inode)) {
5031 err = PTR_ERR(inode);
5035 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5042 * If the active LSM wants to access the inode during
5043 * d_instantiate it needs these. Smack checks to see
5044 * if the filesystem supports xattrs by looking at the
5048 inode->i_op = &btrfs_special_inode_operations;
5049 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5053 init_special_inode(inode, inode->i_mode, rdev);
5054 btrfs_update_inode(trans, root, inode);
5055 d_instantiate(dentry, inode);
5058 btrfs_end_transaction(trans, root);
5059 btrfs_btree_balance_dirty(root);
5061 inode_dec_link_count(inode);
5067 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5068 umode_t mode, bool excl)
5070 struct btrfs_trans_handle *trans;
5071 struct btrfs_root *root = BTRFS_I(dir)->root;
5072 struct inode *inode = NULL;
5073 int drop_inode_on_err = 0;
5079 * 2 for inode item and ref
5081 * 1 for xattr if selinux is on
5083 trans = btrfs_start_transaction(root, 5);
5085 return PTR_ERR(trans);
5087 err = btrfs_find_free_ino(root, &objectid);
5091 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5092 dentry->d_name.len, btrfs_ino(dir), objectid,
5094 if (IS_ERR(inode)) {
5095 err = PTR_ERR(inode);
5098 drop_inode_on_err = 1;
5100 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5104 err = btrfs_update_inode(trans, root, inode);
5109 * If the active LSM wants to access the inode during
5110 * d_instantiate it needs these. Smack checks to see
5111 * if the filesystem supports xattrs by looking at the
5114 inode->i_fop = &btrfs_file_operations;
5115 inode->i_op = &btrfs_file_inode_operations;
5117 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5121 inode->i_mapping->a_ops = &btrfs_aops;
5122 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5123 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5124 d_instantiate(dentry, inode);
5127 btrfs_end_transaction(trans, root);
5128 if (err && drop_inode_on_err) {
5129 inode_dec_link_count(inode);
5132 btrfs_btree_balance_dirty(root);
5136 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5137 struct dentry *dentry)
5139 struct btrfs_trans_handle *trans;
5140 struct btrfs_root *root = BTRFS_I(dir)->root;
5141 struct inode *inode = old_dentry->d_inode;
5146 /* do not allow sys_link's with other subvols of the same device */
5147 if (root->objectid != BTRFS_I(inode)->root->objectid)
5150 if (inode->i_nlink >= BTRFS_LINK_MAX)
5153 err = btrfs_set_inode_index(dir, &index);
5158 * 2 items for inode and inode ref
5159 * 2 items for dir items
5160 * 1 item for parent inode
5162 trans = btrfs_start_transaction(root, 5);
5163 if (IS_ERR(trans)) {
5164 err = PTR_ERR(trans);
5168 btrfs_inc_nlink(inode);
5169 inode_inc_iversion(inode);
5170 inode->i_ctime = CURRENT_TIME;
5172 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5174 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5179 struct dentry *parent = dentry->d_parent;
5180 err = btrfs_update_inode(trans, root, inode);
5183 d_instantiate(dentry, inode);
5184 btrfs_log_new_name(trans, inode, NULL, parent);
5187 btrfs_end_transaction(trans, root);
5190 inode_dec_link_count(inode);
5193 btrfs_btree_balance_dirty(root);
5197 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5199 struct inode *inode = NULL;
5200 struct btrfs_trans_handle *trans;
5201 struct btrfs_root *root = BTRFS_I(dir)->root;
5203 int drop_on_err = 0;
5208 * 2 items for inode and ref
5209 * 2 items for dir items
5210 * 1 for xattr if selinux is on
5212 trans = btrfs_start_transaction(root, 5);
5214 return PTR_ERR(trans);
5216 err = btrfs_find_free_ino(root, &objectid);
5220 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5221 dentry->d_name.len, btrfs_ino(dir), objectid,
5222 S_IFDIR | mode, &index);
5223 if (IS_ERR(inode)) {
5224 err = PTR_ERR(inode);
5230 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5234 inode->i_op = &btrfs_dir_inode_operations;
5235 inode->i_fop = &btrfs_dir_file_operations;
5237 btrfs_i_size_write(inode, 0);
5238 err = btrfs_update_inode(trans, root, inode);
5242 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5243 dentry->d_name.len, 0, index);
5247 d_instantiate(dentry, inode);
5251 btrfs_end_transaction(trans, root);
5254 btrfs_btree_balance_dirty(root);
5258 /* helper for btfs_get_extent. Given an existing extent in the tree,
5259 * and an extent that you want to insert, deal with overlap and insert
5260 * the new extent into the tree.
5262 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5263 struct extent_map *existing,
5264 struct extent_map *em,
5265 u64 map_start, u64 map_len)
5269 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5270 start_diff = map_start - em->start;
5271 em->start = map_start;
5273 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5274 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5275 em->block_start += start_diff;
5276 em->block_len -= start_diff;
5278 return add_extent_mapping(em_tree, em);
5281 static noinline int uncompress_inline(struct btrfs_path *path,
5282 struct inode *inode, struct page *page,
5283 size_t pg_offset, u64 extent_offset,
5284 struct btrfs_file_extent_item *item)
5287 struct extent_buffer *leaf = path->nodes[0];
5290 unsigned long inline_size;
5294 WARN_ON(pg_offset != 0);
5295 compress_type = btrfs_file_extent_compression(leaf, item);
5296 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5297 inline_size = btrfs_file_extent_inline_item_len(leaf,
5298 btrfs_item_nr(leaf, path->slots[0]));
5299 tmp = kmalloc(inline_size, GFP_NOFS);
5302 ptr = btrfs_file_extent_inline_start(item);
5304 read_extent_buffer(leaf, tmp, ptr, inline_size);
5306 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5307 ret = btrfs_decompress(compress_type, tmp, page,
5308 extent_offset, inline_size, max_size);
5310 char *kaddr = kmap_atomic(page);
5311 unsigned long copy_size = min_t(u64,
5312 PAGE_CACHE_SIZE - pg_offset,
5313 max_size - extent_offset);
5314 memset(kaddr + pg_offset, 0, copy_size);
5315 kunmap_atomic(kaddr);
5322 * a bit scary, this does extent mapping from logical file offset to the disk.
5323 * the ugly parts come from merging extents from the disk with the in-ram
5324 * representation. This gets more complex because of the data=ordered code,
5325 * where the in-ram extents might be locked pending data=ordered completion.
5327 * This also copies inline extents directly into the page.
5330 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5331 size_t pg_offset, u64 start, u64 len,
5337 u64 extent_start = 0;
5339 u64 objectid = btrfs_ino(inode);
5341 struct btrfs_path *path = NULL;
5342 struct btrfs_root *root = BTRFS_I(inode)->root;
5343 struct btrfs_file_extent_item *item;
5344 struct extent_buffer *leaf;
5345 struct btrfs_key found_key;
5346 struct extent_map *em = NULL;
5347 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5348 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5349 struct btrfs_trans_handle *trans = NULL;
5353 read_lock(&em_tree->lock);
5354 em = lookup_extent_mapping(em_tree, start, len);
5356 em->bdev = root->fs_info->fs_devices->latest_bdev;
5357 read_unlock(&em_tree->lock);
5360 if (em->start > start || em->start + em->len <= start)
5361 free_extent_map(em);
5362 else if (em->block_start == EXTENT_MAP_INLINE && page)
5363 free_extent_map(em);
5367 em = alloc_extent_map();
5372 em->bdev = root->fs_info->fs_devices->latest_bdev;
5373 em->start = EXTENT_MAP_HOLE;
5374 em->orig_start = EXTENT_MAP_HOLE;
5376 em->block_len = (u64)-1;
5379 path = btrfs_alloc_path();
5385 * Chances are we'll be called again, so go ahead and do
5391 ret = btrfs_lookup_file_extent(trans, root, path,
5392 objectid, start, trans != NULL);
5399 if (path->slots[0] == 0)
5404 leaf = path->nodes[0];
5405 item = btrfs_item_ptr(leaf, path->slots[0],
5406 struct btrfs_file_extent_item);
5407 /* are we inside the extent that was found? */
5408 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5409 found_type = btrfs_key_type(&found_key);
5410 if (found_key.objectid != objectid ||
5411 found_type != BTRFS_EXTENT_DATA_KEY) {
5415 found_type = btrfs_file_extent_type(leaf, item);
5416 extent_start = found_key.offset;
5417 compress_type = btrfs_file_extent_compression(leaf, item);
5418 if (found_type == BTRFS_FILE_EXTENT_REG ||
5419 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5420 extent_end = extent_start +
5421 btrfs_file_extent_num_bytes(leaf, item);
5422 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5424 size = btrfs_file_extent_inline_len(leaf, item);
5425 extent_end = (extent_start + size + root->sectorsize - 1) &
5426 ~((u64)root->sectorsize - 1);
5429 if (start >= extent_end) {
5431 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5432 ret = btrfs_next_leaf(root, path);
5439 leaf = path->nodes[0];
5441 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5442 if (found_key.objectid != objectid ||
5443 found_key.type != BTRFS_EXTENT_DATA_KEY)
5445 if (start + len <= found_key.offset)
5448 em->orig_start = start;
5449 em->len = found_key.offset - start;
5453 if (found_type == BTRFS_FILE_EXTENT_REG ||
5454 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5455 em->start = extent_start;
5456 em->len = extent_end - extent_start;
5457 em->orig_start = extent_start -
5458 btrfs_file_extent_offset(leaf, item);
5459 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
5461 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5463 em->block_start = EXTENT_MAP_HOLE;
5466 if (compress_type != BTRFS_COMPRESS_NONE) {
5467 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5468 em->compress_type = compress_type;
5469 em->block_start = bytenr;
5470 em->block_len = em->orig_block_len;
5472 bytenr += btrfs_file_extent_offset(leaf, item);
5473 em->block_start = bytenr;
5474 em->block_len = em->len;
5475 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5476 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5479 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5483 size_t extent_offset;
5486 em->block_start = EXTENT_MAP_INLINE;
5487 if (!page || create) {
5488 em->start = extent_start;
5489 em->len = extent_end - extent_start;
5493 size = btrfs_file_extent_inline_len(leaf, item);
5494 extent_offset = page_offset(page) + pg_offset - extent_start;
5495 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5496 size - extent_offset);
5497 em->start = extent_start + extent_offset;
5498 em->len = (copy_size + root->sectorsize - 1) &
5499 ~((u64)root->sectorsize - 1);
5500 em->orig_block_len = em->len;
5501 em->orig_start = em->start;
5502 if (compress_type) {
5503 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5504 em->compress_type = compress_type;
5506 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5507 if (create == 0 && !PageUptodate(page)) {
5508 if (btrfs_file_extent_compression(leaf, item) !=
5509 BTRFS_COMPRESS_NONE) {
5510 ret = uncompress_inline(path, inode, page,
5512 extent_offset, item);
5513 BUG_ON(ret); /* -ENOMEM */
5516 read_extent_buffer(leaf, map + pg_offset, ptr,
5518 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5519 memset(map + pg_offset + copy_size, 0,
5520 PAGE_CACHE_SIZE - pg_offset -
5525 flush_dcache_page(page);
5526 } else if (create && PageUptodate(page)) {
5530 free_extent_map(em);
5533 btrfs_release_path(path);
5534 trans = btrfs_join_transaction(root);
5537 return ERR_CAST(trans);
5541 write_extent_buffer(leaf, map + pg_offset, ptr,
5544 btrfs_mark_buffer_dirty(leaf);
5546 set_extent_uptodate(io_tree, em->start,
5547 extent_map_end(em) - 1, NULL, GFP_NOFS);
5550 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
5554 em->orig_start = start;
5557 em->block_start = EXTENT_MAP_HOLE;
5558 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5560 btrfs_release_path(path);
5561 if (em->start > start || extent_map_end(em) <= start) {
5562 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5563 "[%llu %llu]\n", (unsigned long long)em->start,
5564 (unsigned long long)em->len,
5565 (unsigned long long)start,
5566 (unsigned long long)len);
5572 write_lock(&em_tree->lock);
5573 ret = add_extent_mapping(em_tree, em);
5574 /* it is possible that someone inserted the extent into the tree
5575 * while we had the lock dropped. It is also possible that
5576 * an overlapping map exists in the tree
5578 if (ret == -EEXIST) {
5579 struct extent_map *existing;
5583 existing = lookup_extent_mapping(em_tree, start, len);
5584 if (existing && (existing->start > start ||
5585 existing->start + existing->len <= start)) {
5586 free_extent_map(existing);
5590 existing = lookup_extent_mapping(em_tree, em->start,
5593 err = merge_extent_mapping(em_tree, existing,
5596 free_extent_map(existing);
5598 free_extent_map(em);
5603 free_extent_map(em);
5607 free_extent_map(em);
5612 write_unlock(&em_tree->lock);
5616 trace_btrfs_get_extent(root, em);
5619 btrfs_free_path(path);
5621 ret = btrfs_end_transaction(trans, root);
5626 free_extent_map(em);
5627 return ERR_PTR(err);
5629 BUG_ON(!em); /* Error is always set */
5633 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5634 size_t pg_offset, u64 start, u64 len,
5637 struct extent_map *em;
5638 struct extent_map *hole_em = NULL;
5639 u64 range_start = start;
5645 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5652 * - a pre-alloc extent,
5653 * there might actually be delalloc bytes behind it.
5655 if (em->block_start != EXTENT_MAP_HOLE &&
5656 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5662 /* check to see if we've wrapped (len == -1 or similar) */
5671 /* ok, we didn't find anything, lets look for delalloc */
5672 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5673 end, len, EXTENT_DELALLOC, 1);
5674 found_end = range_start + found;
5675 if (found_end < range_start)
5676 found_end = (u64)-1;
5679 * we didn't find anything useful, return
5680 * the original results from get_extent()
5682 if (range_start > end || found_end <= start) {
5688 /* adjust the range_start to make sure it doesn't
5689 * go backwards from the start they passed in
5691 range_start = max(start,range_start);
5692 found = found_end - range_start;
5695 u64 hole_start = start;
5698 em = alloc_extent_map();
5704 * when btrfs_get_extent can't find anything it
5705 * returns one huge hole
5707 * make sure what it found really fits our range, and
5708 * adjust to make sure it is based on the start from
5712 u64 calc_end = extent_map_end(hole_em);
5714 if (calc_end <= start || (hole_em->start > end)) {
5715 free_extent_map(hole_em);
5718 hole_start = max(hole_em->start, start);
5719 hole_len = calc_end - hole_start;
5723 if (hole_em && range_start > hole_start) {
5724 /* our hole starts before our delalloc, so we
5725 * have to return just the parts of the hole
5726 * that go until the delalloc starts
5728 em->len = min(hole_len,
5729 range_start - hole_start);
5730 em->start = hole_start;
5731 em->orig_start = hole_start;
5733 * don't adjust block start at all,
5734 * it is fixed at EXTENT_MAP_HOLE
5736 em->block_start = hole_em->block_start;
5737 em->block_len = hole_len;
5738 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
5739 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5741 em->start = range_start;
5743 em->orig_start = range_start;
5744 em->block_start = EXTENT_MAP_DELALLOC;
5745 em->block_len = found;
5747 } else if (hole_em) {
5752 free_extent_map(hole_em);
5754 free_extent_map(em);
5755 return ERR_PTR(err);
5760 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5763 struct btrfs_root *root = BTRFS_I(inode)->root;
5764 struct btrfs_trans_handle *trans;
5765 struct extent_map *em;
5766 struct btrfs_key ins;
5770 trans = btrfs_join_transaction(root);
5772 return ERR_CAST(trans);
5774 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5776 alloc_hint = get_extent_allocation_hint(inode, start, len);
5777 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5778 alloc_hint, &ins, 1);
5784 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
5785 ins.offset, ins.offset, 0);
5789 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5790 ins.offset, ins.offset, 0);
5792 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5796 btrfs_end_transaction(trans, root);
5801 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5802 * block must be cow'd
5804 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5805 struct inode *inode, u64 offset, u64 len)
5807 struct btrfs_path *path;
5809 struct extent_buffer *leaf;
5810 struct btrfs_root *root = BTRFS_I(inode)->root;
5811 struct btrfs_file_extent_item *fi;
5812 struct btrfs_key key;
5820 path = btrfs_alloc_path();
5824 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5829 slot = path->slots[0];
5832 /* can't find the item, must cow */
5839 leaf = path->nodes[0];
5840 btrfs_item_key_to_cpu(leaf, &key, slot);
5841 if (key.objectid != btrfs_ino(inode) ||
5842 key.type != BTRFS_EXTENT_DATA_KEY) {
5843 /* not our file or wrong item type, must cow */
5847 if (key.offset > offset) {
5848 /* Wrong offset, must cow */
5852 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5853 found_type = btrfs_file_extent_type(leaf, fi);
5854 if (found_type != BTRFS_FILE_EXTENT_REG &&
5855 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5856 /* not a regular extent, must cow */
5859 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5860 backref_offset = btrfs_file_extent_offset(leaf, fi);
5862 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5863 if (extent_end < offset + len) {
5864 /* extent doesn't include our full range, must cow */
5868 if (btrfs_extent_readonly(root, disk_bytenr))
5872 * look for other files referencing this extent, if we
5873 * find any we must cow
5875 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5876 key.offset - backref_offset, disk_bytenr))
5880 * adjust disk_bytenr and num_bytes to cover just the bytes
5881 * in this extent we are about to write. If there
5882 * are any csums in that range we have to cow in order
5883 * to keep the csums correct
5885 disk_bytenr += backref_offset;
5886 disk_bytenr += offset - key.offset;
5887 num_bytes = min(offset + len, extent_end) - offset;
5888 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5891 * all of the above have passed, it is safe to overwrite this extent
5896 btrfs_free_path(path);
5900 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
5901 struct extent_state **cached_state, int writing)
5903 struct btrfs_ordered_extent *ordered;
5907 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5910 * We're concerned with the entire range that we're going to be
5911 * doing DIO to, so we need to make sure theres no ordered
5912 * extents in this range.
5914 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5915 lockend - lockstart + 1);
5918 * We need to make sure there are no buffered pages in this
5919 * range either, we could have raced between the invalidate in
5920 * generic_file_direct_write and locking the extent. The
5921 * invalidate needs to happen so that reads after a write do not
5924 if (!ordered && (!writing ||
5925 !test_range_bit(&BTRFS_I(inode)->io_tree,
5926 lockstart, lockend, EXTENT_UPTODATE, 0,
5930 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5931 cached_state, GFP_NOFS);
5934 btrfs_start_ordered_extent(inode, ordered, 1);
5935 btrfs_put_ordered_extent(ordered);
5937 /* Screw you mmap */
5938 ret = filemap_write_and_wait_range(inode->i_mapping,
5945 * If we found a page that couldn't be invalidated just
5946 * fall back to buffered.
5948 ret = invalidate_inode_pages2_range(inode->i_mapping,
5949 lockstart >> PAGE_CACHE_SHIFT,
5950 lockend >> PAGE_CACHE_SHIFT);
5961 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
5962 u64 len, u64 orig_start,
5963 u64 block_start, u64 block_len,
5964 u64 orig_block_len, int type)
5966 struct extent_map_tree *em_tree;
5967 struct extent_map *em;
5968 struct btrfs_root *root = BTRFS_I(inode)->root;
5971 em_tree = &BTRFS_I(inode)->extent_tree;
5972 em = alloc_extent_map();
5974 return ERR_PTR(-ENOMEM);
5977 em->orig_start = orig_start;
5978 em->mod_start = start;
5981 em->block_len = block_len;
5982 em->block_start = block_start;
5983 em->bdev = root->fs_info->fs_devices->latest_bdev;
5984 em->orig_block_len = orig_block_len;
5985 em->generation = -1;
5986 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5987 if (type == BTRFS_ORDERED_PREALLOC)
5988 set_bit(EXTENT_FLAG_FILLING, &em->flags);
5991 btrfs_drop_extent_cache(inode, em->start,
5992 em->start + em->len - 1, 0);
5993 write_lock(&em_tree->lock);
5994 ret = add_extent_mapping(em_tree, em);
5996 list_move(&em->list,
5997 &em_tree->modified_extents);
5998 write_unlock(&em_tree->lock);
5999 } while (ret == -EEXIST);
6002 free_extent_map(em);
6003 return ERR_PTR(ret);
6010 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6011 struct buffer_head *bh_result, int create)
6013 struct extent_map *em;
6014 struct btrfs_root *root = BTRFS_I(inode)->root;
6015 struct extent_state *cached_state = NULL;
6016 u64 start = iblock << inode->i_blkbits;
6017 u64 lockstart, lockend;
6018 u64 len = bh_result->b_size;
6019 struct btrfs_trans_handle *trans;
6020 int unlock_bits = EXTENT_LOCKED;
6024 ret = btrfs_delalloc_reserve_space(inode, len);
6027 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6029 len = min_t(u64, len, root->sectorsize);
6033 lockend = start + len - 1;
6036 * If this errors out it's because we couldn't invalidate pagecache for
6037 * this range and we need to fallback to buffered.
6039 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6043 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6044 lockend, EXTENT_DELALLOC, NULL,
6045 &cached_state, GFP_NOFS);
6050 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6057 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6058 * io. INLINE is special, and we could probably kludge it in here, but
6059 * it's still buffered so for safety lets just fall back to the generic
6062 * For COMPRESSED we _have_ to read the entire extent in so we can
6063 * decompress it, so there will be buffering required no matter what we
6064 * do, so go ahead and fallback to buffered.
6066 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6067 * to buffered IO. Don't blame me, this is the price we pay for using
6070 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6071 em->block_start == EXTENT_MAP_INLINE) {
6072 free_extent_map(em);
6077 /* Just a good old fashioned hole, return */
6078 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6079 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6080 free_extent_map(em);
6086 * We don't allocate a new extent in the following cases
6088 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6090 * 2) The extent is marked as PREALLOC. We're good to go here and can
6091 * just use the extent.
6095 len = min(len, em->len - (start - em->start));
6096 lockstart = start + len;
6100 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6101 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6102 em->block_start != EXTENT_MAP_HOLE)) {
6107 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6108 type = BTRFS_ORDERED_PREALLOC;
6110 type = BTRFS_ORDERED_NOCOW;
6111 len = min(len, em->len - (start - em->start));
6112 block_start = em->block_start + (start - em->start);
6115 * we're not going to log anything, but we do need
6116 * to make sure the current transaction stays open
6117 * while we look for nocow cross refs
6119 trans = btrfs_join_transaction(root);
6123 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6124 u64 orig_start = em->orig_start;
6125 u64 orig_block_len = em->orig_block_len;
6127 if (type == BTRFS_ORDERED_PREALLOC) {
6128 free_extent_map(em);
6129 em = create_pinned_em(inode, start, len,
6132 orig_block_len, type);
6134 btrfs_end_transaction(trans, root);
6139 ret = btrfs_add_ordered_extent_dio(inode, start,
6140 block_start, len, len, type);
6141 btrfs_end_transaction(trans, root);
6143 free_extent_map(em);
6148 btrfs_end_transaction(trans, root);
6152 * this will cow the extent, reset the len in case we changed
6155 len = bh_result->b_size;
6156 free_extent_map(em);
6157 em = btrfs_new_extent_direct(inode, start, len);
6162 len = min(len, em->len - (start - em->start));
6164 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6166 bh_result->b_size = len;
6167 bh_result->b_bdev = em->bdev;
6168 set_buffer_mapped(bh_result);
6170 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6171 set_buffer_new(bh_result);
6174 * Need to update the i_size under the extent lock so buffered
6175 * readers will get the updated i_size when we unlock.
6177 if (start + len > i_size_read(inode))
6178 i_size_write(inode, start + len);
6182 * In the case of write we need to clear and unlock the entire range,
6183 * in the case of read we need to unlock only the end area that we
6184 * aren't using if there is any left over space.
6186 if (lockstart < lockend) {
6187 if (create && len < lockend - lockstart) {
6188 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6189 lockstart + len - 1,
6190 unlock_bits | EXTENT_DEFRAG, 1, 0,
6191 &cached_state, GFP_NOFS);
6193 * Beside unlock, we also need to cleanup reserved space
6194 * for the left range by attaching EXTENT_DO_ACCOUNTING.
6196 clear_extent_bit(&BTRFS_I(inode)->io_tree,
6197 lockstart + len, lockend,
6198 unlock_bits | EXTENT_DO_ACCOUNTING |
6199 EXTENT_DEFRAG, 1, 0, NULL, GFP_NOFS);
6201 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6202 lockend, unlock_bits, 1, 0,
6203 &cached_state, GFP_NOFS);
6206 free_extent_state(cached_state);
6209 free_extent_map(em);
6215 unlock_bits |= EXTENT_DO_ACCOUNTING;
6217 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6218 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6222 struct btrfs_dio_private {
6223 struct inode *inode;
6229 /* number of bios pending for this dio */
6230 atomic_t pending_bios;
6235 struct bio *orig_bio;
6238 static void btrfs_endio_direct_read(struct bio *bio, int err)
6240 struct btrfs_dio_private *dip = bio->bi_private;
6241 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6242 struct bio_vec *bvec = bio->bi_io_vec;
6243 struct inode *inode = dip->inode;
6244 struct btrfs_root *root = BTRFS_I(inode)->root;
6247 start = dip->logical_offset;
6249 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6250 struct page *page = bvec->bv_page;
6253 u64 private = ~(u32)0;
6254 unsigned long flags;
6256 if (get_state_private(&BTRFS_I(inode)->io_tree,
6259 local_irq_save(flags);
6260 kaddr = kmap_atomic(page);
6261 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
6262 csum, bvec->bv_len);
6263 btrfs_csum_final(csum, (char *)&csum);
6264 kunmap_atomic(kaddr);
6265 local_irq_restore(flags);
6267 flush_dcache_page(bvec->bv_page);
6268 if (csum != private) {
6270 printk(KERN_ERR "btrfs csum failed ino %llu off"
6271 " %llu csum %u private %u\n",
6272 (unsigned long long)btrfs_ino(inode),
6273 (unsigned long long)start,
6274 csum, (unsigned)private);
6279 start += bvec->bv_len;
6281 } while (bvec <= bvec_end);
6283 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6284 dip->logical_offset + dip->bytes - 1);
6285 bio->bi_private = dip->private;
6289 /* If we had a csum failure make sure to clear the uptodate flag */
6291 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6292 dio_end_io(bio, err);
6295 static void btrfs_endio_direct_write(struct bio *bio, int err)
6297 struct btrfs_dio_private *dip = bio->bi_private;
6298 struct inode *inode = dip->inode;
6299 struct btrfs_root *root = BTRFS_I(inode)->root;
6300 struct btrfs_ordered_extent *ordered = NULL;
6301 u64 ordered_offset = dip->logical_offset;
6302 u64 ordered_bytes = dip->bytes;
6308 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6310 ordered_bytes, !err);
6314 ordered->work.func = finish_ordered_fn;
6315 ordered->work.flags = 0;
6316 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6320 * our bio might span multiple ordered extents. If we haven't
6321 * completed the accounting for the whole dio, go back and try again
6323 if (ordered_offset < dip->logical_offset + dip->bytes) {
6324 ordered_bytes = dip->logical_offset + dip->bytes -
6330 bio->bi_private = dip->private;
6334 /* If we had an error make sure to clear the uptodate flag */
6336 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6337 dio_end_io(bio, err);
6340 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6341 struct bio *bio, int mirror_num,
6342 unsigned long bio_flags, u64 offset)
6345 struct btrfs_root *root = BTRFS_I(inode)->root;
6346 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6347 BUG_ON(ret); /* -ENOMEM */
6351 static void btrfs_end_dio_bio(struct bio *bio, int err)
6353 struct btrfs_dio_private *dip = bio->bi_private;
6356 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6357 "sector %#Lx len %u err no %d\n",
6358 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6359 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6363 * before atomic variable goto zero, we must make sure
6364 * dip->errors is perceived to be set.
6366 smp_mb__before_atomic_dec();
6369 /* if there are more bios still pending for this dio, just exit */
6370 if (!atomic_dec_and_test(&dip->pending_bios))
6374 bio_io_error(dip->orig_bio);
6376 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
6377 bio_endio(dip->orig_bio, 0);
6383 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6384 u64 first_sector, gfp_t gfp_flags)
6386 int nr_vecs = bio_get_nr_vecs(bdev);
6387 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6390 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6391 int rw, u64 file_offset, int skip_sum,
6394 int write = rw & REQ_WRITE;
6395 struct btrfs_root *root = BTRFS_I(inode)->root;
6399 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6404 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6412 if (write && async_submit) {
6413 ret = btrfs_wq_submit_bio(root->fs_info,
6414 inode, rw, bio, 0, 0,
6416 __btrfs_submit_bio_start_direct_io,
6417 __btrfs_submit_bio_done);
6421 * If we aren't doing async submit, calculate the csum of the
6424 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6427 } else if (!skip_sum) {
6428 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
6434 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6440 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6443 struct inode *inode = dip->inode;
6444 struct btrfs_root *root = BTRFS_I(inode)->root;
6446 struct bio *orig_bio = dip->orig_bio;
6447 struct bio_vec *bvec = orig_bio->bi_io_vec;
6448 u64 start_sector = orig_bio->bi_sector;
6449 u64 file_offset = dip->logical_offset;
6454 int async_submit = 0;
6456 map_length = orig_bio->bi_size;
6457 ret = btrfs_map_block(root->fs_info, READ, start_sector << 9,
6458 &map_length, NULL, 0);
6464 if (map_length >= orig_bio->bi_size) {
6470 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6473 bio->bi_private = dip;
6474 bio->bi_end_io = btrfs_end_dio_bio;
6475 atomic_inc(&dip->pending_bios);
6477 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6478 if (unlikely(map_length < submit_len + bvec->bv_len ||
6479 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6480 bvec->bv_offset) < bvec->bv_len)) {
6482 * inc the count before we submit the bio so
6483 * we know the end IO handler won't happen before
6484 * we inc the count. Otherwise, the dip might get freed
6485 * before we're done setting it up
6487 atomic_inc(&dip->pending_bios);
6488 ret = __btrfs_submit_dio_bio(bio, inode, rw,
6489 file_offset, skip_sum,
6493 atomic_dec(&dip->pending_bios);
6497 start_sector += submit_len >> 9;
6498 file_offset += submit_len;
6503 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6504 start_sector, GFP_NOFS);
6507 bio->bi_private = dip;
6508 bio->bi_end_io = btrfs_end_dio_bio;
6510 map_length = orig_bio->bi_size;
6511 ret = btrfs_map_block(root->fs_info, READ,
6513 &map_length, NULL, 0);
6519 submit_len += bvec->bv_len;
6526 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6535 * before atomic variable goto zero, we must
6536 * make sure dip->errors is perceived to be set.
6538 smp_mb__before_atomic_dec();
6539 if (atomic_dec_and_test(&dip->pending_bios))
6540 bio_io_error(dip->orig_bio);
6542 /* bio_end_io() will handle error, so we needn't return it */
6546 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6549 struct btrfs_root *root = BTRFS_I(inode)->root;
6550 struct btrfs_dio_private *dip;
6551 struct bio_vec *bvec = bio->bi_io_vec;
6553 int write = rw & REQ_WRITE;
6556 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6558 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6564 dip->private = bio->bi_private;
6566 dip->logical_offset = file_offset;
6570 dip->bytes += bvec->bv_len;
6572 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6574 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6575 bio->bi_private = dip;
6577 dip->orig_bio = bio;
6578 atomic_set(&dip->pending_bios, 0);
6581 bio->bi_end_io = btrfs_endio_direct_write;
6583 bio->bi_end_io = btrfs_endio_direct_read;
6585 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6590 * If this is a write, we need to clean up the reserved space and kill
6591 * the ordered extent.
6594 struct btrfs_ordered_extent *ordered;
6595 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6596 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6597 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6598 btrfs_free_reserved_extent(root, ordered->start,
6600 btrfs_put_ordered_extent(ordered);
6601 btrfs_put_ordered_extent(ordered);
6603 bio_endio(bio, ret);
6606 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6607 const struct iovec *iov, loff_t offset,
6608 unsigned long nr_segs)
6614 unsigned blocksize_mask = root->sectorsize - 1;
6615 ssize_t retval = -EINVAL;
6616 loff_t end = offset;
6618 if (offset & blocksize_mask)
6621 /* Check the memory alignment. Blocks cannot straddle pages */
6622 for (seg = 0; seg < nr_segs; seg++) {
6623 addr = (unsigned long)iov[seg].iov_base;
6624 size = iov[seg].iov_len;
6626 if ((addr & blocksize_mask) || (size & blocksize_mask))
6629 /* If this is a write we don't need to check anymore */
6634 * Check to make sure we don't have duplicate iov_base's in this
6635 * iovec, if so return EINVAL, otherwise we'll get csum errors
6636 * when reading back.
6638 for (i = seg + 1; i < nr_segs; i++) {
6639 if (iov[seg].iov_base == iov[i].iov_base)
6648 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6649 const struct iovec *iov, loff_t offset,
6650 unsigned long nr_segs)
6652 struct file *file = iocb->ki_filp;
6653 struct inode *inode = file->f_mapping->host;
6655 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6659 return __blockdev_direct_IO(rw, iocb, inode,
6660 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6661 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6662 btrfs_submit_direct, 0);
6665 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
6667 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6668 __u64 start, __u64 len)
6672 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
6676 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6679 int btrfs_readpage(struct file *file, struct page *page)
6681 struct extent_io_tree *tree;
6682 tree = &BTRFS_I(page->mapping->host)->io_tree;
6683 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6686 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6688 struct extent_io_tree *tree;
6691 if (current->flags & PF_MEMALLOC) {
6692 redirty_page_for_writepage(wbc, page);
6696 tree = &BTRFS_I(page->mapping->host)->io_tree;
6697 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6700 int btrfs_writepages(struct address_space *mapping,
6701 struct writeback_control *wbc)
6703 struct extent_io_tree *tree;
6705 tree = &BTRFS_I(mapping->host)->io_tree;
6706 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6710 btrfs_readpages(struct file *file, struct address_space *mapping,
6711 struct list_head *pages, unsigned nr_pages)
6713 struct extent_io_tree *tree;
6714 tree = &BTRFS_I(mapping->host)->io_tree;
6715 return extent_readpages(tree, mapping, pages, nr_pages,
6718 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6720 struct extent_io_tree *tree;
6721 struct extent_map_tree *map;
6724 tree = &BTRFS_I(page->mapping->host)->io_tree;
6725 map = &BTRFS_I(page->mapping->host)->extent_tree;
6726 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6728 ClearPagePrivate(page);
6729 set_page_private(page, 0);
6730 page_cache_release(page);
6735 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6737 if (PageWriteback(page) || PageDirty(page))
6739 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6742 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6744 struct inode *inode = page->mapping->host;
6745 struct extent_io_tree *tree;
6746 struct btrfs_ordered_extent *ordered;
6747 struct extent_state *cached_state = NULL;
6748 u64 page_start = page_offset(page);
6749 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6752 * we have the page locked, so new writeback can't start,
6753 * and the dirty bit won't be cleared while we are here.
6755 * Wait for IO on this page so that we can safely clear
6756 * the PagePrivate2 bit and do ordered accounting
6758 wait_on_page_writeback(page);
6760 tree = &BTRFS_I(inode)->io_tree;
6762 btrfs_releasepage(page, GFP_NOFS);
6765 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6766 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
6769 * IO on this page will never be started, so we need
6770 * to account for any ordered extents now
6772 clear_extent_bit(tree, page_start, page_end,
6773 EXTENT_DIRTY | EXTENT_DELALLOC |
6774 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
6775 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
6777 * whoever cleared the private bit is responsible
6778 * for the finish_ordered_io
6780 if (TestClearPagePrivate2(page) &&
6781 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
6782 PAGE_CACHE_SIZE, 1)) {
6783 btrfs_finish_ordered_io(ordered);
6785 btrfs_put_ordered_extent(ordered);
6786 cached_state = NULL;
6787 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6789 clear_extent_bit(tree, page_start, page_end,
6790 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6791 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
6792 &cached_state, GFP_NOFS);
6793 __btrfs_releasepage(page, GFP_NOFS);
6795 ClearPageChecked(page);
6796 if (PagePrivate(page)) {
6797 ClearPagePrivate(page);
6798 set_page_private(page, 0);
6799 page_cache_release(page);
6804 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6805 * called from a page fault handler when a page is first dirtied. Hence we must
6806 * be careful to check for EOF conditions here. We set the page up correctly
6807 * for a written page which means we get ENOSPC checking when writing into
6808 * holes and correct delalloc and unwritten extent mapping on filesystems that
6809 * support these features.
6811 * We are not allowed to take the i_mutex here so we have to play games to
6812 * protect against truncate races as the page could now be beyond EOF. Because
6813 * vmtruncate() writes the inode size before removing pages, once we have the
6814 * page lock we can determine safely if the page is beyond EOF. If it is not
6815 * beyond EOF, then the page is guaranteed safe against truncation until we
6818 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6820 struct page *page = vmf->page;
6821 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6822 struct btrfs_root *root = BTRFS_I(inode)->root;
6823 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6824 struct btrfs_ordered_extent *ordered;
6825 struct extent_state *cached_state = NULL;
6827 unsigned long zero_start;
6834 sb_start_pagefault(inode->i_sb);
6835 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6837 ret = file_update_time(vma->vm_file);
6843 else /* -ENOSPC, -EIO, etc */
6844 ret = VM_FAULT_SIGBUS;
6850 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6853 size = i_size_read(inode);
6854 page_start = page_offset(page);
6855 page_end = page_start + PAGE_CACHE_SIZE - 1;
6857 if ((page->mapping != inode->i_mapping) ||
6858 (page_start >= size)) {
6859 /* page got truncated out from underneath us */
6862 wait_on_page_writeback(page);
6864 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
6865 set_page_extent_mapped(page);
6868 * we can't set the delalloc bits if there are pending ordered
6869 * extents. Drop our locks and wait for them to finish
6871 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6873 unlock_extent_cached(io_tree, page_start, page_end,
6874 &cached_state, GFP_NOFS);
6876 btrfs_start_ordered_extent(inode, ordered, 1);
6877 btrfs_put_ordered_extent(ordered);
6882 * XXX - page_mkwrite gets called every time the page is dirtied, even
6883 * if it was already dirty, so for space accounting reasons we need to
6884 * clear any delalloc bits for the range we are fixing to save. There
6885 * is probably a better way to do this, but for now keep consistent with
6886 * prepare_pages in the normal write path.
6888 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6889 EXTENT_DIRTY | EXTENT_DELALLOC |
6890 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
6891 0, 0, &cached_state, GFP_NOFS);
6893 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6896 unlock_extent_cached(io_tree, page_start, page_end,
6897 &cached_state, GFP_NOFS);
6898 ret = VM_FAULT_SIGBUS;
6903 /* page is wholly or partially inside EOF */
6904 if (page_start + PAGE_CACHE_SIZE > size)
6905 zero_start = size & ~PAGE_CACHE_MASK;
6907 zero_start = PAGE_CACHE_SIZE;
6909 if (zero_start != PAGE_CACHE_SIZE) {
6911 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6912 flush_dcache_page(page);
6915 ClearPageChecked(page);
6916 set_page_dirty(page);
6917 SetPageUptodate(page);
6919 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6920 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6921 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
6923 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6927 sb_end_pagefault(inode->i_sb);
6928 return VM_FAULT_LOCKED;
6932 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6934 sb_end_pagefault(inode->i_sb);
6938 static int btrfs_truncate(struct inode *inode)
6940 struct btrfs_root *root = BTRFS_I(inode)->root;
6941 struct btrfs_block_rsv *rsv;
6944 struct btrfs_trans_handle *trans;
6945 u64 mask = root->sectorsize - 1;
6946 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6948 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
6952 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6953 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6956 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6957 * 3 things going on here
6959 * 1) We need to reserve space for our orphan item and the space to
6960 * delete our orphan item. Lord knows we don't want to have a dangling
6961 * orphan item because we didn't reserve space to remove it.
6963 * 2) We need to reserve space to update our inode.
6965 * 3) We need to have something to cache all the space that is going to
6966 * be free'd up by the truncate operation, but also have some slack
6967 * space reserved in case it uses space during the truncate (thank you
6968 * very much snapshotting).
6970 * And we need these to all be seperate. The fact is we can use alot of
6971 * space doing the truncate, and we have no earthly idea how much space
6972 * we will use, so we need the truncate reservation to be seperate so it
6973 * doesn't end up using space reserved for updating the inode or
6974 * removing the orphan item. We also need to be able to stop the
6975 * transaction and start a new one, which means we need to be able to
6976 * update the inode several times, and we have no idea of knowing how
6977 * many times that will be, so we can't just reserve 1 item for the
6978 * entirety of the opration, so that has to be done seperately as well.
6979 * Then there is the orphan item, which does indeed need to be held on
6980 * to for the whole operation, and we need nobody to touch this reserved
6981 * space except the orphan code.
6983 * So that leaves us with
6985 * 1) root->orphan_block_rsv - for the orphan deletion.
6986 * 2) rsv - for the truncate reservation, which we will steal from the
6987 * transaction reservation.
6988 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6989 * updating the inode.
6991 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
6994 rsv->size = min_size;
6998 * 1 for the truncate slack space
6999 * 1 for updating the inode.
7001 trans = btrfs_start_transaction(root, 2);
7002 if (IS_ERR(trans)) {
7003 err = PTR_ERR(trans);
7007 /* Migrate the slack space for the truncate to our reserve */
7008 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7013 * setattr is responsible for setting the ordered_data_close flag,
7014 * but that is only tested during the last file release. That
7015 * could happen well after the next commit, leaving a great big
7016 * window where new writes may get lost if someone chooses to write
7017 * to this file after truncating to zero
7019 * The inode doesn't have any dirty data here, and so if we commit
7020 * this is a noop. If someone immediately starts writing to the inode
7021 * it is very likely we'll catch some of their writes in this
7022 * transaction, and the commit will find this file on the ordered
7023 * data list with good things to send down.
7025 * This is a best effort solution, there is still a window where
7026 * using truncate to replace the contents of the file will
7027 * end up with a zero length file after a crash.
7029 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7030 &BTRFS_I(inode)->runtime_flags))
7031 btrfs_add_ordered_operation(trans, root, inode);
7034 * So if we truncate and then write and fsync we normally would just
7035 * write the extents that changed, which is a problem if we need to
7036 * first truncate that entire inode. So set this flag so we write out
7037 * all of the extents in the inode to the sync log so we're completely
7040 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7041 trans->block_rsv = rsv;
7044 ret = btrfs_truncate_inode_items(trans, root, inode,
7046 BTRFS_EXTENT_DATA_KEY);
7047 if (ret != -ENOSPC) {
7052 trans->block_rsv = &root->fs_info->trans_block_rsv;
7053 ret = btrfs_update_inode(trans, root, inode);
7059 btrfs_end_transaction(trans, root);
7060 btrfs_btree_balance_dirty(root);
7062 trans = btrfs_start_transaction(root, 2);
7063 if (IS_ERR(trans)) {
7064 ret = err = PTR_ERR(trans);
7069 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7071 BUG_ON(ret); /* shouldn't happen */
7072 trans->block_rsv = rsv;
7075 if (ret == 0 && inode->i_nlink > 0) {
7076 trans->block_rsv = root->orphan_block_rsv;
7077 ret = btrfs_orphan_del(trans, inode);
7083 trans->block_rsv = &root->fs_info->trans_block_rsv;
7084 ret = btrfs_update_inode(trans, root, inode);
7088 ret = btrfs_end_transaction(trans, root);
7089 btrfs_btree_balance_dirty(root);
7093 btrfs_free_block_rsv(root, rsv);
7102 * create a new subvolume directory/inode (helper for the ioctl).
7104 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7105 struct btrfs_root *new_root, u64 new_dirid)
7107 struct inode *inode;
7111 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7112 new_dirid, new_dirid,
7113 S_IFDIR | (~current_umask() & S_IRWXUGO),
7116 return PTR_ERR(inode);
7117 inode->i_op = &btrfs_dir_inode_operations;
7118 inode->i_fop = &btrfs_dir_file_operations;
7120 set_nlink(inode, 1);
7121 btrfs_i_size_write(inode, 0);
7123 err = btrfs_update_inode(trans, new_root, inode);
7129 struct inode *btrfs_alloc_inode(struct super_block *sb)
7131 struct btrfs_inode *ei;
7132 struct inode *inode;
7134 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7141 ei->last_sub_trans = 0;
7142 ei->logged_trans = 0;
7143 ei->delalloc_bytes = 0;
7144 ei->disk_i_size = 0;
7147 ei->index_cnt = (u64)-1;
7148 ei->last_unlink_trans = 0;
7149 ei->last_log_commit = 0;
7151 spin_lock_init(&ei->lock);
7152 ei->outstanding_extents = 0;
7153 ei->reserved_extents = 0;
7155 ei->runtime_flags = 0;
7156 ei->force_compress = BTRFS_COMPRESS_NONE;
7158 ei->delayed_node = NULL;
7160 inode = &ei->vfs_inode;
7161 extent_map_tree_init(&ei->extent_tree);
7162 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7163 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7164 ei->io_tree.track_uptodate = 1;
7165 ei->io_failure_tree.track_uptodate = 1;
7166 atomic_set(&ei->sync_writers, 0);
7167 mutex_init(&ei->log_mutex);
7168 mutex_init(&ei->delalloc_mutex);
7169 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7170 INIT_LIST_HEAD(&ei->delalloc_inodes);
7171 INIT_LIST_HEAD(&ei->ordered_operations);
7172 RB_CLEAR_NODE(&ei->rb_node);
7177 static void btrfs_i_callback(struct rcu_head *head)
7179 struct inode *inode = container_of(head, struct inode, i_rcu);
7180 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7183 void btrfs_destroy_inode(struct inode *inode)
7185 struct btrfs_ordered_extent *ordered;
7186 struct btrfs_root *root = BTRFS_I(inode)->root;
7188 WARN_ON(!hlist_empty(&inode->i_dentry));
7189 WARN_ON(inode->i_data.nrpages);
7190 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7191 WARN_ON(BTRFS_I(inode)->reserved_extents);
7192 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7193 WARN_ON(BTRFS_I(inode)->csum_bytes);
7196 * This can happen where we create an inode, but somebody else also
7197 * created the same inode and we need to destroy the one we already
7204 * Make sure we're properly removed from the ordered operation
7208 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7209 spin_lock(&root->fs_info->ordered_extent_lock);
7210 list_del_init(&BTRFS_I(inode)->ordered_operations);
7211 spin_unlock(&root->fs_info->ordered_extent_lock);
7214 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7215 &BTRFS_I(inode)->runtime_flags)) {
7216 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
7217 (unsigned long long)btrfs_ino(inode));
7218 atomic_dec(&root->orphan_inodes);
7222 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7226 printk(KERN_ERR "btrfs found ordered "
7227 "extent %llu %llu on inode cleanup\n",
7228 (unsigned long long)ordered->file_offset,
7229 (unsigned long long)ordered->len);
7230 btrfs_remove_ordered_extent(inode, ordered);
7231 btrfs_put_ordered_extent(ordered);
7232 btrfs_put_ordered_extent(ordered);
7235 inode_tree_del(inode);
7236 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7238 btrfs_remove_delayed_node(inode);
7239 call_rcu(&inode->i_rcu, btrfs_i_callback);
7242 int btrfs_drop_inode(struct inode *inode)
7244 struct btrfs_root *root = BTRFS_I(inode)->root;
7246 if (btrfs_root_refs(&root->root_item) == 0 &&
7247 !btrfs_is_free_space_inode(inode))
7250 return generic_drop_inode(inode);
7253 static void init_once(void *foo)
7255 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7257 inode_init_once(&ei->vfs_inode);
7260 void btrfs_destroy_cachep(void)
7263 * Make sure all delayed rcu free inodes are flushed before we
7267 if (btrfs_inode_cachep)
7268 kmem_cache_destroy(btrfs_inode_cachep);
7269 if (btrfs_trans_handle_cachep)
7270 kmem_cache_destroy(btrfs_trans_handle_cachep);
7271 if (btrfs_transaction_cachep)
7272 kmem_cache_destroy(btrfs_transaction_cachep);
7273 if (btrfs_path_cachep)
7274 kmem_cache_destroy(btrfs_path_cachep);
7275 if (btrfs_free_space_cachep)
7276 kmem_cache_destroy(btrfs_free_space_cachep);
7277 if (btrfs_delalloc_work_cachep)
7278 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7281 int btrfs_init_cachep(void)
7283 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7284 sizeof(struct btrfs_inode), 0,
7285 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7286 if (!btrfs_inode_cachep)
7289 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7290 sizeof(struct btrfs_trans_handle), 0,
7291 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7292 if (!btrfs_trans_handle_cachep)
7295 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7296 sizeof(struct btrfs_transaction), 0,
7297 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7298 if (!btrfs_transaction_cachep)
7301 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7302 sizeof(struct btrfs_path), 0,
7303 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7304 if (!btrfs_path_cachep)
7307 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7308 sizeof(struct btrfs_free_space), 0,
7309 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7310 if (!btrfs_free_space_cachep)
7313 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7314 sizeof(struct btrfs_delalloc_work), 0,
7315 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7317 if (!btrfs_delalloc_work_cachep)
7322 btrfs_destroy_cachep();
7326 static int btrfs_getattr(struct vfsmount *mnt,
7327 struct dentry *dentry, struct kstat *stat)
7329 struct inode *inode = dentry->d_inode;
7330 u32 blocksize = inode->i_sb->s_blocksize;
7332 generic_fillattr(inode, stat);
7333 stat->dev = BTRFS_I(inode)->root->anon_dev;
7334 stat->blksize = PAGE_CACHE_SIZE;
7335 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7336 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
7341 * If a file is moved, it will inherit the cow and compression flags of the new
7344 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7346 struct btrfs_inode *b_dir = BTRFS_I(dir);
7347 struct btrfs_inode *b_inode = BTRFS_I(inode);
7349 if (b_dir->flags & BTRFS_INODE_NODATACOW)
7350 b_inode->flags |= BTRFS_INODE_NODATACOW;
7352 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7354 if (b_dir->flags & BTRFS_INODE_COMPRESS) {
7355 b_inode->flags |= BTRFS_INODE_COMPRESS;
7356 b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
7358 b_inode->flags &= ~(BTRFS_INODE_COMPRESS |
7359 BTRFS_INODE_NOCOMPRESS);
7363 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7364 struct inode *new_dir, struct dentry *new_dentry)
7366 struct btrfs_trans_handle *trans;
7367 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7368 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7369 struct inode *new_inode = new_dentry->d_inode;
7370 struct inode *old_inode = old_dentry->d_inode;
7371 struct timespec ctime = CURRENT_TIME;
7375 u64 old_ino = btrfs_ino(old_inode);
7377 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7380 /* we only allow rename subvolume link between subvolumes */
7381 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7384 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7385 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7388 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7389 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7393 /* check for collisions, even if the name isn't there */
7394 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
7395 new_dentry->d_name.name,
7396 new_dentry->d_name.len);
7399 if (ret == -EEXIST) {
7401 * eexist without a new_inode */
7407 /* maybe -EOVERFLOW */
7414 * we're using rename to replace one file with another.
7415 * and the replacement file is large. Start IO on it now so
7416 * we don't add too much work to the end of the transaction
7418 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7419 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7420 filemap_flush(old_inode->i_mapping);
7422 /* close the racy window with snapshot create/destroy ioctl */
7423 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7424 down_read(&root->fs_info->subvol_sem);
7426 * We want to reserve the absolute worst case amount of items. So if
7427 * both inodes are subvols and we need to unlink them then that would
7428 * require 4 item modifications, but if they are both normal inodes it
7429 * would require 5 item modifications, so we'll assume their normal
7430 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7431 * should cover the worst case number of items we'll modify.
7433 trans = btrfs_start_transaction(root, 20);
7434 if (IS_ERR(trans)) {
7435 ret = PTR_ERR(trans);
7440 btrfs_record_root_in_trans(trans, dest);
7442 ret = btrfs_set_inode_index(new_dir, &index);
7446 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7447 /* force full log commit if subvolume involved. */
7448 root->fs_info->last_trans_log_full_commit = trans->transid;
7450 ret = btrfs_insert_inode_ref(trans, dest,
7451 new_dentry->d_name.name,
7452 new_dentry->d_name.len,
7454 btrfs_ino(new_dir), index);
7458 * this is an ugly little race, but the rename is required
7459 * to make sure that if we crash, the inode is either at the
7460 * old name or the new one. pinning the log transaction lets
7461 * us make sure we don't allow a log commit to come in after
7462 * we unlink the name but before we add the new name back in.
7464 btrfs_pin_log_trans(root);
7467 * make sure the inode gets flushed if it is replacing
7470 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7471 btrfs_add_ordered_operation(trans, root, old_inode);
7473 inode_inc_iversion(old_dir);
7474 inode_inc_iversion(new_dir);
7475 inode_inc_iversion(old_inode);
7476 old_dir->i_ctime = old_dir->i_mtime = ctime;
7477 new_dir->i_ctime = new_dir->i_mtime = ctime;
7478 old_inode->i_ctime = ctime;
7480 if (old_dentry->d_parent != new_dentry->d_parent)
7481 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7483 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7484 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7485 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7486 old_dentry->d_name.name,
7487 old_dentry->d_name.len);
7489 ret = __btrfs_unlink_inode(trans, root, old_dir,
7490 old_dentry->d_inode,
7491 old_dentry->d_name.name,
7492 old_dentry->d_name.len);
7494 ret = btrfs_update_inode(trans, root, old_inode);
7497 btrfs_abort_transaction(trans, root, ret);
7502 inode_inc_iversion(new_inode);
7503 new_inode->i_ctime = CURRENT_TIME;
7504 if (unlikely(btrfs_ino(new_inode) ==
7505 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7506 root_objectid = BTRFS_I(new_inode)->location.objectid;
7507 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7509 new_dentry->d_name.name,
7510 new_dentry->d_name.len);
7511 BUG_ON(new_inode->i_nlink == 0);
7513 ret = btrfs_unlink_inode(trans, dest, new_dir,
7514 new_dentry->d_inode,
7515 new_dentry->d_name.name,
7516 new_dentry->d_name.len);
7518 if (!ret && new_inode->i_nlink == 0) {
7519 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7523 btrfs_abort_transaction(trans, root, ret);
7528 fixup_inode_flags(new_dir, old_inode);
7530 ret = btrfs_add_link(trans, new_dir, old_inode,
7531 new_dentry->d_name.name,
7532 new_dentry->d_name.len, 0, index);
7534 btrfs_abort_transaction(trans, root, ret);
7538 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7539 struct dentry *parent = new_dentry->d_parent;
7540 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7541 btrfs_end_log_trans(root);
7544 btrfs_end_transaction(trans, root);
7546 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7547 up_read(&root->fs_info->subvol_sem);
7552 static void btrfs_run_delalloc_work(struct btrfs_work *work)
7554 struct btrfs_delalloc_work *delalloc_work;
7556 delalloc_work = container_of(work, struct btrfs_delalloc_work,
7558 if (delalloc_work->wait)
7559 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
7561 filemap_flush(delalloc_work->inode->i_mapping);
7563 if (delalloc_work->delay_iput)
7564 btrfs_add_delayed_iput(delalloc_work->inode);
7566 iput(delalloc_work->inode);
7567 complete(&delalloc_work->completion);
7570 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
7571 int wait, int delay_iput)
7573 struct btrfs_delalloc_work *work;
7575 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
7579 init_completion(&work->completion);
7580 INIT_LIST_HEAD(&work->list);
7581 work->inode = inode;
7583 work->delay_iput = delay_iput;
7584 work->work.func = btrfs_run_delalloc_work;
7589 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
7591 wait_for_completion(&work->completion);
7592 kmem_cache_free(btrfs_delalloc_work_cachep, work);
7596 * some fairly slow code that needs optimization. This walks the list
7597 * of all the inodes with pending delalloc and forces them to disk.
7599 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7601 struct btrfs_inode *binode;
7602 struct inode *inode;
7603 struct btrfs_delalloc_work *work, *next;
7604 struct list_head works;
7605 struct list_head splice;
7608 if (root->fs_info->sb->s_flags & MS_RDONLY)
7611 INIT_LIST_HEAD(&works);
7612 INIT_LIST_HEAD(&splice);
7614 spin_lock(&root->fs_info->delalloc_lock);
7615 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
7616 while (!list_empty(&splice)) {
7617 binode = list_entry(splice.next, struct btrfs_inode,
7620 list_del_init(&binode->delalloc_inodes);
7622 inode = igrab(&binode->vfs_inode);
7626 list_add_tail(&binode->delalloc_inodes,
7627 &root->fs_info->delalloc_inodes);
7628 spin_unlock(&root->fs_info->delalloc_lock);
7630 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
7631 if (unlikely(!work)) {
7635 list_add_tail(&work->list, &works);
7636 btrfs_queue_worker(&root->fs_info->flush_workers,
7640 spin_lock(&root->fs_info->delalloc_lock);
7642 spin_unlock(&root->fs_info->delalloc_lock);
7644 list_for_each_entry_safe(work, next, &works, list) {
7645 list_del_init(&work->list);
7646 btrfs_wait_and_free_delalloc_work(work);
7649 /* the filemap_flush will queue IO into the worker threads, but
7650 * we have to make sure the IO is actually started and that
7651 * ordered extents get created before we return
7653 atomic_inc(&root->fs_info->async_submit_draining);
7654 while (atomic_read(&root->fs_info->nr_async_submits) ||
7655 atomic_read(&root->fs_info->async_delalloc_pages)) {
7656 wait_event(root->fs_info->async_submit_wait,
7657 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7658 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7660 atomic_dec(&root->fs_info->async_submit_draining);
7663 list_for_each_entry_safe(work, next, &works, list) {
7664 list_del_init(&work->list);
7665 btrfs_wait_and_free_delalloc_work(work);
7668 if (!list_empty_careful(&splice)) {
7669 spin_lock(&root->fs_info->delalloc_lock);
7670 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
7671 spin_unlock(&root->fs_info->delalloc_lock);
7676 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7677 const char *symname)
7679 struct btrfs_trans_handle *trans;
7680 struct btrfs_root *root = BTRFS_I(dir)->root;
7681 struct btrfs_path *path;
7682 struct btrfs_key key;
7683 struct inode *inode = NULL;
7691 struct btrfs_file_extent_item *ei;
7692 struct extent_buffer *leaf;
7694 name_len = strlen(symname) + 1;
7695 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7696 return -ENAMETOOLONG;
7699 * 2 items for inode item and ref
7700 * 2 items for dir items
7701 * 1 item for xattr if selinux is on
7703 trans = btrfs_start_transaction(root, 5);
7705 return PTR_ERR(trans);
7707 err = btrfs_find_free_ino(root, &objectid);
7711 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7712 dentry->d_name.len, btrfs_ino(dir), objectid,
7713 S_IFLNK|S_IRWXUGO, &index);
7714 if (IS_ERR(inode)) {
7715 err = PTR_ERR(inode);
7719 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7726 * If the active LSM wants to access the inode during
7727 * d_instantiate it needs these. Smack checks to see
7728 * if the filesystem supports xattrs by looking at the
7731 inode->i_fop = &btrfs_file_operations;
7732 inode->i_op = &btrfs_file_inode_operations;
7734 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7738 inode->i_mapping->a_ops = &btrfs_aops;
7739 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7740 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7745 path = btrfs_alloc_path();
7751 key.objectid = btrfs_ino(inode);
7753 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7754 datasize = btrfs_file_extent_calc_inline_size(name_len);
7755 err = btrfs_insert_empty_item(trans, root, path, &key,
7759 btrfs_free_path(path);
7762 leaf = path->nodes[0];
7763 ei = btrfs_item_ptr(leaf, path->slots[0],
7764 struct btrfs_file_extent_item);
7765 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7766 btrfs_set_file_extent_type(leaf, ei,
7767 BTRFS_FILE_EXTENT_INLINE);
7768 btrfs_set_file_extent_encryption(leaf, ei, 0);
7769 btrfs_set_file_extent_compression(leaf, ei, 0);
7770 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7771 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7773 ptr = btrfs_file_extent_inline_start(ei);
7774 write_extent_buffer(leaf, symname, ptr, name_len);
7775 btrfs_mark_buffer_dirty(leaf);
7776 btrfs_free_path(path);
7778 inode->i_op = &btrfs_symlink_inode_operations;
7779 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7780 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7781 inode_set_bytes(inode, name_len);
7782 btrfs_i_size_write(inode, name_len - 1);
7783 err = btrfs_update_inode(trans, root, inode);
7789 d_instantiate(dentry, inode);
7790 btrfs_end_transaction(trans, root);
7792 inode_dec_link_count(inode);
7795 btrfs_btree_balance_dirty(root);
7799 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7800 u64 start, u64 num_bytes, u64 min_size,
7801 loff_t actual_len, u64 *alloc_hint,
7802 struct btrfs_trans_handle *trans)
7804 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7805 struct extent_map *em;
7806 struct btrfs_root *root = BTRFS_I(inode)->root;
7807 struct btrfs_key ins;
7808 u64 cur_offset = start;
7811 bool own_trans = true;
7815 while (num_bytes > 0) {
7817 trans = btrfs_start_transaction(root, 3);
7818 if (IS_ERR(trans)) {
7819 ret = PTR_ERR(trans);
7824 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7825 0, *alloc_hint, &ins, 1);
7828 btrfs_end_transaction(trans, root);
7832 ret = insert_reserved_file_extent(trans, inode,
7833 cur_offset, ins.objectid,
7834 ins.offset, ins.offset,
7835 ins.offset, 0, 0, 0,
7836 BTRFS_FILE_EXTENT_PREALLOC);
7838 btrfs_abort_transaction(trans, root, ret);
7840 btrfs_end_transaction(trans, root);
7843 btrfs_drop_extent_cache(inode, cur_offset,
7844 cur_offset + ins.offset -1, 0);
7846 em = alloc_extent_map();
7848 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7849 &BTRFS_I(inode)->runtime_flags);
7853 em->start = cur_offset;
7854 em->orig_start = cur_offset;
7855 em->len = ins.offset;
7856 em->block_start = ins.objectid;
7857 em->block_len = ins.offset;
7858 em->orig_block_len = ins.offset;
7859 em->bdev = root->fs_info->fs_devices->latest_bdev;
7860 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7861 em->generation = trans->transid;
7864 write_lock(&em_tree->lock);
7865 ret = add_extent_mapping(em_tree, em);
7867 list_move(&em->list,
7868 &em_tree->modified_extents);
7869 write_unlock(&em_tree->lock);
7872 btrfs_drop_extent_cache(inode, cur_offset,
7873 cur_offset + ins.offset - 1,
7876 free_extent_map(em);
7878 num_bytes -= ins.offset;
7879 cur_offset += ins.offset;
7880 *alloc_hint = ins.objectid + ins.offset;
7882 inode_inc_iversion(inode);
7883 inode->i_ctime = CURRENT_TIME;
7884 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7885 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7886 (actual_len > inode->i_size) &&
7887 (cur_offset > inode->i_size)) {
7888 if (cur_offset > actual_len)
7889 i_size = actual_len;
7891 i_size = cur_offset;
7892 i_size_write(inode, i_size);
7893 btrfs_ordered_update_i_size(inode, i_size, NULL);
7896 ret = btrfs_update_inode(trans, root, inode);
7899 btrfs_abort_transaction(trans, root, ret);
7901 btrfs_end_transaction(trans, root);
7906 btrfs_end_transaction(trans, root);
7911 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7912 u64 start, u64 num_bytes, u64 min_size,
7913 loff_t actual_len, u64 *alloc_hint)
7915 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7916 min_size, actual_len, alloc_hint,
7920 int btrfs_prealloc_file_range_trans(struct inode *inode,
7921 struct btrfs_trans_handle *trans, int mode,
7922 u64 start, u64 num_bytes, u64 min_size,
7923 loff_t actual_len, u64 *alloc_hint)
7925 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7926 min_size, actual_len, alloc_hint, trans);
7929 static int btrfs_set_page_dirty(struct page *page)
7931 return __set_page_dirty_nobuffers(page);
7934 static int btrfs_permission(struct inode *inode, int mask)
7936 struct btrfs_root *root = BTRFS_I(inode)->root;
7937 umode_t mode = inode->i_mode;
7939 if (mask & MAY_WRITE &&
7940 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7941 if (btrfs_root_readonly(root))
7943 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7946 return generic_permission(inode, mask);
7949 static const struct inode_operations btrfs_dir_inode_operations = {
7950 .getattr = btrfs_getattr,
7951 .lookup = btrfs_lookup,
7952 .create = btrfs_create,
7953 .unlink = btrfs_unlink,
7955 .mkdir = btrfs_mkdir,
7956 .rmdir = btrfs_rmdir,
7957 .rename = btrfs_rename,
7958 .symlink = btrfs_symlink,
7959 .setattr = btrfs_setattr,
7960 .mknod = btrfs_mknod,
7961 .setxattr = btrfs_setxattr,
7962 .getxattr = btrfs_getxattr,
7963 .listxattr = btrfs_listxattr,
7964 .removexattr = btrfs_removexattr,
7965 .permission = btrfs_permission,
7966 .get_acl = btrfs_get_acl,
7968 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7969 .lookup = btrfs_lookup,
7970 .permission = btrfs_permission,
7971 .get_acl = btrfs_get_acl,
7974 static const struct file_operations btrfs_dir_file_operations = {
7975 .llseek = generic_file_llseek,
7976 .read = generic_read_dir,
7977 .readdir = btrfs_real_readdir,
7978 .unlocked_ioctl = btrfs_ioctl,
7979 #ifdef CONFIG_COMPAT
7980 .compat_ioctl = btrfs_ioctl,
7982 .release = btrfs_release_file,
7983 .fsync = btrfs_sync_file,
7986 static struct extent_io_ops btrfs_extent_io_ops = {
7987 .fill_delalloc = run_delalloc_range,
7988 .submit_bio_hook = btrfs_submit_bio_hook,
7989 .merge_bio_hook = btrfs_merge_bio_hook,
7990 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7991 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7992 .writepage_start_hook = btrfs_writepage_start_hook,
7993 .set_bit_hook = btrfs_set_bit_hook,
7994 .clear_bit_hook = btrfs_clear_bit_hook,
7995 .merge_extent_hook = btrfs_merge_extent_hook,
7996 .split_extent_hook = btrfs_split_extent_hook,
8000 * btrfs doesn't support the bmap operation because swapfiles
8001 * use bmap to make a mapping of extents in the file. They assume
8002 * these extents won't change over the life of the file and they
8003 * use the bmap result to do IO directly to the drive.
8005 * the btrfs bmap call would return logical addresses that aren't
8006 * suitable for IO and they also will change frequently as COW
8007 * operations happen. So, swapfile + btrfs == corruption.
8009 * For now we're avoiding this by dropping bmap.
8011 static const struct address_space_operations btrfs_aops = {
8012 .readpage = btrfs_readpage,
8013 .writepage = btrfs_writepage,
8014 .writepages = btrfs_writepages,
8015 .readpages = btrfs_readpages,
8016 .direct_IO = btrfs_direct_IO,
8017 .invalidatepage = btrfs_invalidatepage,
8018 .releasepage = btrfs_releasepage,
8019 .set_page_dirty = btrfs_set_page_dirty,
8020 .error_remove_page = generic_error_remove_page,
8023 static const struct address_space_operations btrfs_symlink_aops = {
8024 .readpage = btrfs_readpage,
8025 .writepage = btrfs_writepage,
8026 .invalidatepage = btrfs_invalidatepage,
8027 .releasepage = btrfs_releasepage,
8030 static const struct inode_operations btrfs_file_inode_operations = {
8031 .getattr = btrfs_getattr,
8032 .setattr = btrfs_setattr,
8033 .setxattr = btrfs_setxattr,
8034 .getxattr = btrfs_getxattr,
8035 .listxattr = btrfs_listxattr,
8036 .removexattr = btrfs_removexattr,
8037 .permission = btrfs_permission,
8038 .fiemap = btrfs_fiemap,
8039 .get_acl = btrfs_get_acl,
8040 .update_time = btrfs_update_time,
8042 static const struct inode_operations btrfs_special_inode_operations = {
8043 .getattr = btrfs_getattr,
8044 .setattr = btrfs_setattr,
8045 .permission = btrfs_permission,
8046 .setxattr = btrfs_setxattr,
8047 .getxattr = btrfs_getxattr,
8048 .listxattr = btrfs_listxattr,
8049 .removexattr = btrfs_removexattr,
8050 .get_acl = btrfs_get_acl,
8051 .update_time = btrfs_update_time,
8053 static const struct inode_operations btrfs_symlink_inode_operations = {
8054 .readlink = generic_readlink,
8055 .follow_link = page_follow_link_light,
8056 .put_link = page_put_link,
8057 .getattr = btrfs_getattr,
8058 .setattr = btrfs_setattr,
8059 .permission = btrfs_permission,
8060 .setxattr = btrfs_setxattr,
8061 .getxattr = btrfs_getxattr,
8062 .listxattr = btrfs_listxattr,
8063 .removexattr = btrfs_removexattr,
8064 .get_acl = btrfs_get_acl,
8065 .update_time = btrfs_update_time,
8068 const struct dentry_operations btrfs_dentry_operations = {
8069 .d_delete = btrfs_dentry_delete,
8070 .d_release = btrfs_dentry_release,