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 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1518 root->fs_info->delalloc_batch);
1519 spin_lock(&BTRFS_I(inode)->lock);
1520 BTRFS_I(inode)->delalloc_bytes += len;
1521 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1522 &BTRFS_I(inode)->runtime_flags)) {
1523 spin_lock(&root->fs_info->delalloc_lock);
1524 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1525 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1526 &root->fs_info->delalloc_inodes);
1527 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1528 &BTRFS_I(inode)->runtime_flags);
1530 spin_unlock(&root->fs_info->delalloc_lock);
1532 spin_unlock(&BTRFS_I(inode)->lock);
1537 * extent_io.c clear_bit_hook, see set_bit_hook for why
1539 static void btrfs_clear_bit_hook(struct inode *inode,
1540 struct extent_state *state, int *bits)
1543 * set_bit and clear bit hooks normally require _irqsave/restore
1544 * but in this case, we are only testing for the DELALLOC
1545 * bit, which is only set or cleared with irqs on
1547 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1548 struct btrfs_root *root = BTRFS_I(inode)->root;
1549 u64 len = state->end + 1 - state->start;
1550 bool do_list = !btrfs_is_free_space_inode(inode);
1552 if (*bits & EXTENT_FIRST_DELALLOC) {
1553 *bits &= ~EXTENT_FIRST_DELALLOC;
1554 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1555 spin_lock(&BTRFS_I(inode)->lock);
1556 BTRFS_I(inode)->outstanding_extents--;
1557 spin_unlock(&BTRFS_I(inode)->lock);
1560 if (*bits & EXTENT_DO_ACCOUNTING)
1561 btrfs_delalloc_release_metadata(inode, len);
1563 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1565 btrfs_free_reserved_data_space(inode, len);
1567 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1568 root->fs_info->delalloc_batch);
1569 spin_lock(&BTRFS_I(inode)->lock);
1570 BTRFS_I(inode)->delalloc_bytes -= len;
1571 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1572 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1573 &BTRFS_I(inode)->runtime_flags)) {
1574 spin_lock(&root->fs_info->delalloc_lock);
1575 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1576 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1577 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1578 &BTRFS_I(inode)->runtime_flags);
1580 spin_unlock(&root->fs_info->delalloc_lock);
1582 spin_unlock(&BTRFS_I(inode)->lock);
1587 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1588 * we don't create bios that span stripes or chunks
1590 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1591 size_t size, struct bio *bio,
1592 unsigned long bio_flags)
1594 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1595 u64 logical = (u64)bio->bi_sector << 9;
1600 if (bio_flags & EXTENT_BIO_COMPRESSED)
1603 length = bio->bi_size;
1604 map_length = length;
1605 ret = btrfs_map_block(root->fs_info, READ, logical,
1606 &map_length, NULL, 0);
1607 /* Will always return 0 with map_multi == NULL */
1609 if (map_length < length + size)
1615 * in order to insert checksums into the metadata in large chunks,
1616 * we wait until bio submission time. All the pages in the bio are
1617 * checksummed and sums are attached onto the ordered extent record.
1619 * At IO completion time the cums attached on the ordered extent record
1620 * are inserted into the btree
1622 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1623 struct bio *bio, int mirror_num,
1624 unsigned long bio_flags,
1627 struct btrfs_root *root = BTRFS_I(inode)->root;
1630 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1631 BUG_ON(ret); /* -ENOMEM */
1636 * in order to insert checksums into the metadata in large chunks,
1637 * we wait until bio submission time. All the pages in the bio are
1638 * checksummed and sums are attached onto the ordered extent record.
1640 * At IO completion time the cums attached on the ordered extent record
1641 * are inserted into the btree
1643 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1644 int mirror_num, unsigned long bio_flags,
1647 struct btrfs_root *root = BTRFS_I(inode)->root;
1650 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1652 bio_endio(bio, ret);
1657 * extent_io.c submission hook. This does the right thing for csum calculation
1658 * on write, or reading the csums from the tree before a read
1660 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1661 int mirror_num, unsigned long bio_flags,
1664 struct btrfs_root *root = BTRFS_I(inode)->root;
1668 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1670 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1672 if (btrfs_is_free_space_inode(inode))
1675 if (!(rw & REQ_WRITE)) {
1676 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1680 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1681 ret = btrfs_submit_compressed_read(inode, bio,
1685 } else if (!skip_sum) {
1686 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1691 } else if (async && !skip_sum) {
1692 /* csum items have already been cloned */
1693 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1695 /* we're doing a write, do the async checksumming */
1696 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1697 inode, rw, bio, mirror_num,
1698 bio_flags, bio_offset,
1699 __btrfs_submit_bio_start,
1700 __btrfs_submit_bio_done);
1702 } else if (!skip_sum) {
1703 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1709 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1713 bio_endio(bio, ret);
1718 * given a list of ordered sums record them in the inode. This happens
1719 * at IO completion time based on sums calculated at bio submission time.
1721 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1722 struct inode *inode, u64 file_offset,
1723 struct list_head *list)
1725 struct btrfs_ordered_sum *sum;
1727 list_for_each_entry(sum, list, list) {
1728 btrfs_csum_file_blocks(trans,
1729 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1734 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1735 struct extent_state **cached_state)
1737 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1738 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1739 cached_state, GFP_NOFS);
1742 /* see btrfs_writepage_start_hook for details on why this is required */
1743 struct btrfs_writepage_fixup {
1745 struct btrfs_work work;
1748 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1750 struct btrfs_writepage_fixup *fixup;
1751 struct btrfs_ordered_extent *ordered;
1752 struct extent_state *cached_state = NULL;
1754 struct inode *inode;
1759 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1763 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1764 ClearPageChecked(page);
1768 inode = page->mapping->host;
1769 page_start = page_offset(page);
1770 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1772 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1775 /* already ordered? We're done */
1776 if (PagePrivate2(page))
1779 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1781 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1782 page_end, &cached_state, GFP_NOFS);
1784 btrfs_start_ordered_extent(inode, ordered, 1);
1785 btrfs_put_ordered_extent(ordered);
1789 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1791 mapping_set_error(page->mapping, ret);
1792 end_extent_writepage(page, ret, page_start, page_end);
1793 ClearPageChecked(page);
1797 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1798 ClearPageChecked(page);
1799 set_page_dirty(page);
1801 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1802 &cached_state, GFP_NOFS);
1805 page_cache_release(page);
1810 * There are a few paths in the higher layers of the kernel that directly
1811 * set the page dirty bit without asking the filesystem if it is a
1812 * good idea. This causes problems because we want to make sure COW
1813 * properly happens and the data=ordered rules are followed.
1815 * In our case any range that doesn't have the ORDERED bit set
1816 * hasn't been properly setup for IO. We kick off an async process
1817 * to fix it up. The async helper will wait for ordered extents, set
1818 * the delalloc bit and make it safe to write the page.
1820 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1822 struct inode *inode = page->mapping->host;
1823 struct btrfs_writepage_fixup *fixup;
1824 struct btrfs_root *root = BTRFS_I(inode)->root;
1826 /* this page is properly in the ordered list */
1827 if (TestClearPagePrivate2(page))
1830 if (PageChecked(page))
1833 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1837 SetPageChecked(page);
1838 page_cache_get(page);
1839 fixup->work.func = btrfs_writepage_fixup_worker;
1841 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1845 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1846 struct inode *inode, u64 file_pos,
1847 u64 disk_bytenr, u64 disk_num_bytes,
1848 u64 num_bytes, u64 ram_bytes,
1849 u8 compression, u8 encryption,
1850 u16 other_encoding, int extent_type)
1852 struct btrfs_root *root = BTRFS_I(inode)->root;
1853 struct btrfs_file_extent_item *fi;
1854 struct btrfs_path *path;
1855 struct extent_buffer *leaf;
1856 struct btrfs_key ins;
1859 path = btrfs_alloc_path();
1863 path->leave_spinning = 1;
1866 * we may be replacing one extent in the tree with another.
1867 * The new extent is pinned in the extent map, and we don't want
1868 * to drop it from the cache until it is completely in the btree.
1870 * So, tell btrfs_drop_extents to leave this extent in the cache.
1871 * the caller is expected to unpin it and allow it to be merged
1874 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1875 file_pos + num_bytes, 0);
1879 ins.objectid = btrfs_ino(inode);
1880 ins.offset = file_pos;
1881 ins.type = BTRFS_EXTENT_DATA_KEY;
1882 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1885 leaf = path->nodes[0];
1886 fi = btrfs_item_ptr(leaf, path->slots[0],
1887 struct btrfs_file_extent_item);
1888 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1889 btrfs_set_file_extent_type(leaf, fi, extent_type);
1890 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1891 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1892 btrfs_set_file_extent_offset(leaf, fi, 0);
1893 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1894 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1895 btrfs_set_file_extent_compression(leaf, fi, compression);
1896 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1897 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1899 btrfs_mark_buffer_dirty(leaf);
1900 btrfs_release_path(path);
1902 inode_add_bytes(inode, num_bytes);
1904 ins.objectid = disk_bytenr;
1905 ins.offset = disk_num_bytes;
1906 ins.type = BTRFS_EXTENT_ITEM_KEY;
1907 ret = btrfs_alloc_reserved_file_extent(trans, root,
1908 root->root_key.objectid,
1909 btrfs_ino(inode), file_pos, &ins);
1911 btrfs_free_path(path);
1917 * helper function for btrfs_finish_ordered_io, this
1918 * just reads in some of the csum leaves to prime them into ram
1919 * before we start the transaction. It limits the amount of btree
1920 * reads required while inside the transaction.
1922 /* as ordered data IO finishes, this gets called so we can finish
1923 * an ordered extent if the range of bytes in the file it covers are
1926 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1928 struct inode *inode = ordered_extent->inode;
1929 struct btrfs_root *root = BTRFS_I(inode)->root;
1930 struct btrfs_trans_handle *trans = NULL;
1931 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1932 struct extent_state *cached_state = NULL;
1933 int compress_type = 0;
1937 nolock = btrfs_is_free_space_inode(inode);
1939 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1944 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1945 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1946 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1948 trans = btrfs_join_transaction_nolock(root);
1950 trans = btrfs_join_transaction(root);
1951 if (IS_ERR(trans)) {
1952 ret = PTR_ERR(trans);
1956 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1957 ret = btrfs_update_inode_fallback(trans, root, inode);
1958 if (ret) /* -ENOMEM or corruption */
1959 btrfs_abort_transaction(trans, root, ret);
1963 lock_extent_bits(io_tree, ordered_extent->file_offset,
1964 ordered_extent->file_offset + ordered_extent->len - 1,
1968 trans = btrfs_join_transaction_nolock(root);
1970 trans = btrfs_join_transaction(root);
1971 if (IS_ERR(trans)) {
1972 ret = PTR_ERR(trans);
1976 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1978 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1979 compress_type = ordered_extent->compress_type;
1980 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1981 BUG_ON(compress_type);
1982 ret = btrfs_mark_extent_written(trans, inode,
1983 ordered_extent->file_offset,
1984 ordered_extent->file_offset +
1985 ordered_extent->len);
1987 BUG_ON(root == root->fs_info->tree_root);
1988 ret = insert_reserved_file_extent(trans, inode,
1989 ordered_extent->file_offset,
1990 ordered_extent->start,
1991 ordered_extent->disk_len,
1992 ordered_extent->len,
1993 ordered_extent->len,
1994 compress_type, 0, 0,
1995 BTRFS_FILE_EXTENT_REG);
1997 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1998 ordered_extent->file_offset, ordered_extent->len,
2001 btrfs_abort_transaction(trans, root, ret);
2005 add_pending_csums(trans, inode, ordered_extent->file_offset,
2006 &ordered_extent->list);
2008 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2009 ret = btrfs_update_inode_fallback(trans, root, inode);
2010 if (ret) { /* -ENOMEM or corruption */
2011 btrfs_abort_transaction(trans, root, ret);
2016 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2017 ordered_extent->file_offset +
2018 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2020 if (root != root->fs_info->tree_root)
2021 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2023 btrfs_end_transaction(trans, root);
2026 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2027 ordered_extent->file_offset +
2028 ordered_extent->len - 1, NULL, GFP_NOFS);
2031 * This needs to be done to make sure anybody waiting knows we are done
2032 * updating everything for this ordered extent.
2034 btrfs_remove_ordered_extent(inode, ordered_extent);
2037 btrfs_put_ordered_extent(ordered_extent);
2038 /* once for the tree */
2039 btrfs_put_ordered_extent(ordered_extent);
2044 static void finish_ordered_fn(struct btrfs_work *work)
2046 struct btrfs_ordered_extent *ordered_extent;
2047 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2048 btrfs_finish_ordered_io(ordered_extent);
2051 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2052 struct extent_state *state, int uptodate)
2054 struct inode *inode = page->mapping->host;
2055 struct btrfs_root *root = BTRFS_I(inode)->root;
2056 struct btrfs_ordered_extent *ordered_extent = NULL;
2057 struct btrfs_workers *workers;
2059 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2061 ClearPagePrivate2(page);
2062 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2063 end - start + 1, uptodate))
2066 ordered_extent->work.func = finish_ordered_fn;
2067 ordered_extent->work.flags = 0;
2069 if (btrfs_is_free_space_inode(inode))
2070 workers = &root->fs_info->endio_freespace_worker;
2072 workers = &root->fs_info->endio_write_workers;
2073 btrfs_queue_worker(workers, &ordered_extent->work);
2079 * when reads are done, we need to check csums to verify the data is correct
2080 * if there's a match, we allow the bio to finish. If not, the code in
2081 * extent_io.c will try to find good copies for us.
2083 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2084 struct extent_state *state, int mirror)
2086 size_t offset = start - page_offset(page);
2087 struct inode *inode = page->mapping->host;
2088 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2090 u64 private = ~(u32)0;
2092 struct btrfs_root *root = BTRFS_I(inode)->root;
2095 if (PageChecked(page)) {
2096 ClearPageChecked(page);
2100 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2103 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2104 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2105 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2110 if (state && state->start == start) {
2111 private = state->private;
2114 ret = get_state_private(io_tree, start, &private);
2116 kaddr = kmap_atomic(page);
2120 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2121 btrfs_csum_final(csum, (char *)&csum);
2122 if (csum != private)
2125 kunmap_atomic(kaddr);
2130 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2132 (unsigned long long)btrfs_ino(page->mapping->host),
2133 (unsigned long long)start, csum,
2134 (unsigned long long)private);
2135 memset(kaddr + offset, 1, end - start + 1);
2136 flush_dcache_page(page);
2137 kunmap_atomic(kaddr);
2143 struct delayed_iput {
2144 struct list_head list;
2145 struct inode *inode;
2148 /* JDM: If this is fs-wide, why can't we add a pointer to
2149 * btrfs_inode instead and avoid the allocation? */
2150 void btrfs_add_delayed_iput(struct inode *inode)
2152 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2153 struct delayed_iput *delayed;
2155 if (atomic_add_unless(&inode->i_count, -1, 1))
2158 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2159 delayed->inode = inode;
2161 spin_lock(&fs_info->delayed_iput_lock);
2162 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2163 spin_unlock(&fs_info->delayed_iput_lock);
2166 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2169 struct btrfs_fs_info *fs_info = root->fs_info;
2170 struct delayed_iput *delayed;
2173 spin_lock(&fs_info->delayed_iput_lock);
2174 empty = list_empty(&fs_info->delayed_iputs);
2175 spin_unlock(&fs_info->delayed_iput_lock);
2179 spin_lock(&fs_info->delayed_iput_lock);
2180 list_splice_init(&fs_info->delayed_iputs, &list);
2181 spin_unlock(&fs_info->delayed_iput_lock);
2183 while (!list_empty(&list)) {
2184 delayed = list_entry(list.next, struct delayed_iput, list);
2185 list_del(&delayed->list);
2186 iput(delayed->inode);
2191 enum btrfs_orphan_cleanup_state {
2192 ORPHAN_CLEANUP_STARTED = 1,
2193 ORPHAN_CLEANUP_DONE = 2,
2197 * This is called in transaction commit time. If there are no orphan
2198 * files in the subvolume, it removes orphan item and frees block_rsv
2201 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2202 struct btrfs_root *root)
2204 struct btrfs_block_rsv *block_rsv;
2207 if (atomic_read(&root->orphan_inodes) ||
2208 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2211 spin_lock(&root->orphan_lock);
2212 if (atomic_read(&root->orphan_inodes)) {
2213 spin_unlock(&root->orphan_lock);
2217 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2218 spin_unlock(&root->orphan_lock);
2222 block_rsv = root->orphan_block_rsv;
2223 root->orphan_block_rsv = NULL;
2224 spin_unlock(&root->orphan_lock);
2226 if (root->orphan_item_inserted &&
2227 btrfs_root_refs(&root->root_item) > 0) {
2228 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2229 root->root_key.objectid);
2231 root->orphan_item_inserted = 0;
2235 WARN_ON(block_rsv->size > 0);
2236 btrfs_free_block_rsv(root, block_rsv);
2241 * This creates an orphan entry for the given inode in case something goes
2242 * wrong in the middle of an unlink/truncate.
2244 * NOTE: caller of this function should reserve 5 units of metadata for
2247 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2249 struct btrfs_root *root = BTRFS_I(inode)->root;
2250 struct btrfs_block_rsv *block_rsv = NULL;
2255 if (!root->orphan_block_rsv) {
2256 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2261 spin_lock(&root->orphan_lock);
2262 if (!root->orphan_block_rsv) {
2263 root->orphan_block_rsv = block_rsv;
2264 } else if (block_rsv) {
2265 btrfs_free_block_rsv(root, block_rsv);
2269 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2270 &BTRFS_I(inode)->runtime_flags)) {
2273 * For proper ENOSPC handling, we should do orphan
2274 * cleanup when mounting. But this introduces backward
2275 * compatibility issue.
2277 if (!xchg(&root->orphan_item_inserted, 1))
2283 atomic_inc(&root->orphan_inodes);
2286 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2287 &BTRFS_I(inode)->runtime_flags))
2289 spin_unlock(&root->orphan_lock);
2291 /* grab metadata reservation from transaction handle */
2293 ret = btrfs_orphan_reserve_metadata(trans, inode);
2294 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2297 /* insert an orphan item to track this unlinked/truncated file */
2299 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2300 if (ret && ret != -EEXIST) {
2301 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2302 &BTRFS_I(inode)->runtime_flags);
2303 btrfs_abort_transaction(trans, root, ret);
2309 /* insert an orphan item to track subvolume contains orphan files */
2311 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2312 root->root_key.objectid);
2313 if (ret && ret != -EEXIST) {
2314 btrfs_abort_transaction(trans, root, ret);
2322 * We have done the truncate/delete so we can go ahead and remove the orphan
2323 * item for this particular inode.
2325 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2327 struct btrfs_root *root = BTRFS_I(inode)->root;
2328 int delete_item = 0;
2329 int release_rsv = 0;
2332 spin_lock(&root->orphan_lock);
2333 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2334 &BTRFS_I(inode)->runtime_flags))
2337 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2338 &BTRFS_I(inode)->runtime_flags))
2340 spin_unlock(&root->orphan_lock);
2342 if (trans && delete_item) {
2343 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2344 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2348 btrfs_orphan_release_metadata(inode);
2349 atomic_dec(&root->orphan_inodes);
2356 * this cleans up any orphans that may be left on the list from the last use
2359 int btrfs_orphan_cleanup(struct btrfs_root *root)
2361 struct btrfs_path *path;
2362 struct extent_buffer *leaf;
2363 struct btrfs_key key, found_key;
2364 struct btrfs_trans_handle *trans;
2365 struct inode *inode;
2366 u64 last_objectid = 0;
2367 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2369 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2372 path = btrfs_alloc_path();
2379 key.objectid = BTRFS_ORPHAN_OBJECTID;
2380 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2381 key.offset = (u64)-1;
2384 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2389 * if ret == 0 means we found what we were searching for, which
2390 * is weird, but possible, so only screw with path if we didn't
2391 * find the key and see if we have stuff that matches
2395 if (path->slots[0] == 0)
2400 /* pull out the item */
2401 leaf = path->nodes[0];
2402 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2404 /* make sure the item matches what we want */
2405 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2407 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2410 /* release the path since we're done with it */
2411 btrfs_release_path(path);
2414 * this is where we are basically btrfs_lookup, without the
2415 * crossing root thing. we store the inode number in the
2416 * offset of the orphan item.
2419 if (found_key.offset == last_objectid) {
2420 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2421 "stopping orphan cleanup\n");
2426 last_objectid = found_key.offset;
2428 found_key.objectid = found_key.offset;
2429 found_key.type = BTRFS_INODE_ITEM_KEY;
2430 found_key.offset = 0;
2431 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2432 ret = PTR_RET(inode);
2433 if (ret && ret != -ESTALE)
2436 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2437 struct btrfs_root *dead_root;
2438 struct btrfs_fs_info *fs_info = root->fs_info;
2439 int is_dead_root = 0;
2442 * this is an orphan in the tree root. Currently these
2443 * could come from 2 sources:
2444 * a) a snapshot deletion in progress
2445 * b) a free space cache inode
2446 * We need to distinguish those two, as the snapshot
2447 * orphan must not get deleted.
2448 * find_dead_roots already ran before us, so if this
2449 * is a snapshot deletion, we should find the root
2450 * in the dead_roots list
2452 spin_lock(&fs_info->trans_lock);
2453 list_for_each_entry(dead_root, &fs_info->dead_roots,
2455 if (dead_root->root_key.objectid ==
2456 found_key.objectid) {
2461 spin_unlock(&fs_info->trans_lock);
2463 /* prevent this orphan from being found again */
2464 key.offset = found_key.objectid - 1;
2469 * Inode is already gone but the orphan item is still there,
2470 * kill the orphan item.
2472 if (ret == -ESTALE) {
2473 trans = btrfs_start_transaction(root, 1);
2474 if (IS_ERR(trans)) {
2475 ret = PTR_ERR(trans);
2478 printk(KERN_ERR "auto deleting %Lu\n",
2479 found_key.objectid);
2480 ret = btrfs_del_orphan_item(trans, root,
2481 found_key.objectid);
2482 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2483 btrfs_end_transaction(trans, root);
2488 * add this inode to the orphan list so btrfs_orphan_del does
2489 * the proper thing when we hit it
2491 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2492 &BTRFS_I(inode)->runtime_flags);
2494 /* if we have links, this was a truncate, lets do that */
2495 if (inode->i_nlink) {
2496 if (!S_ISREG(inode->i_mode)) {
2503 /* 1 for the orphan item deletion. */
2504 trans = btrfs_start_transaction(root, 1);
2505 if (IS_ERR(trans)) {
2506 ret = PTR_ERR(trans);
2509 ret = btrfs_orphan_add(trans, inode);
2510 btrfs_end_transaction(trans, root);
2514 ret = btrfs_truncate(inode);
2519 /* this will do delete_inode and everything for us */
2524 /* release the path since we're done with it */
2525 btrfs_release_path(path);
2527 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2529 if (root->orphan_block_rsv)
2530 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2533 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2534 trans = btrfs_join_transaction(root);
2536 btrfs_end_transaction(trans, root);
2540 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2542 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2546 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2547 btrfs_free_path(path);
2552 * very simple check to peek ahead in the leaf looking for xattrs. If we
2553 * don't find any xattrs, we know there can't be any acls.
2555 * slot is the slot the inode is in, objectid is the objectid of the inode
2557 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2558 int slot, u64 objectid)
2560 u32 nritems = btrfs_header_nritems(leaf);
2561 struct btrfs_key found_key;
2565 while (slot < nritems) {
2566 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2568 /* we found a different objectid, there must not be acls */
2569 if (found_key.objectid != objectid)
2572 /* we found an xattr, assume we've got an acl */
2573 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2577 * we found a key greater than an xattr key, there can't
2578 * be any acls later on
2580 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2587 * it goes inode, inode backrefs, xattrs, extents,
2588 * so if there are a ton of hard links to an inode there can
2589 * be a lot of backrefs. Don't waste time searching too hard,
2590 * this is just an optimization
2595 /* we hit the end of the leaf before we found an xattr or
2596 * something larger than an xattr. We have to assume the inode
2603 * read an inode from the btree into the in-memory inode
2605 static void btrfs_read_locked_inode(struct inode *inode)
2607 struct btrfs_path *path;
2608 struct extent_buffer *leaf;
2609 struct btrfs_inode_item *inode_item;
2610 struct btrfs_timespec *tspec;
2611 struct btrfs_root *root = BTRFS_I(inode)->root;
2612 struct btrfs_key location;
2616 bool filled = false;
2618 ret = btrfs_fill_inode(inode, &rdev);
2622 path = btrfs_alloc_path();
2626 path->leave_spinning = 1;
2627 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2629 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2633 leaf = path->nodes[0];
2638 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2639 struct btrfs_inode_item);
2640 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2641 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2642 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
2643 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
2644 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2646 tspec = btrfs_inode_atime(inode_item);
2647 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2648 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2650 tspec = btrfs_inode_mtime(inode_item);
2651 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2652 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2654 tspec = btrfs_inode_ctime(inode_item);
2655 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2656 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2658 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2659 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2660 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
2663 * If we were modified in the current generation and evicted from memory
2664 * and then re-read we need to do a full sync since we don't have any
2665 * idea about which extents were modified before we were evicted from
2668 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
2669 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2670 &BTRFS_I(inode)->runtime_flags);
2672 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2673 inode->i_generation = BTRFS_I(inode)->generation;
2675 rdev = btrfs_inode_rdev(leaf, inode_item);
2677 BTRFS_I(inode)->index_cnt = (u64)-1;
2678 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2681 * try to precache a NULL acl entry for files that don't have
2682 * any xattrs or acls
2684 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2687 cache_no_acl(inode);
2689 btrfs_free_path(path);
2691 switch (inode->i_mode & S_IFMT) {
2693 inode->i_mapping->a_ops = &btrfs_aops;
2694 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2695 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2696 inode->i_fop = &btrfs_file_operations;
2697 inode->i_op = &btrfs_file_inode_operations;
2700 inode->i_fop = &btrfs_dir_file_operations;
2701 if (root == root->fs_info->tree_root)
2702 inode->i_op = &btrfs_dir_ro_inode_operations;
2704 inode->i_op = &btrfs_dir_inode_operations;
2707 inode->i_op = &btrfs_symlink_inode_operations;
2708 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2709 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2712 inode->i_op = &btrfs_special_inode_operations;
2713 init_special_inode(inode, inode->i_mode, rdev);
2717 btrfs_update_iflags(inode);
2721 btrfs_free_path(path);
2722 make_bad_inode(inode);
2726 * given a leaf and an inode, copy the inode fields into the leaf
2728 static void fill_inode_item(struct btrfs_trans_handle *trans,
2729 struct extent_buffer *leaf,
2730 struct btrfs_inode_item *item,
2731 struct inode *inode)
2733 struct btrfs_map_token token;
2735 btrfs_init_map_token(&token);
2737 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
2738 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
2739 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
2741 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
2742 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
2744 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
2745 inode->i_atime.tv_sec, &token);
2746 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
2747 inode->i_atime.tv_nsec, &token);
2749 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
2750 inode->i_mtime.tv_sec, &token);
2751 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
2752 inode->i_mtime.tv_nsec, &token);
2754 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
2755 inode->i_ctime.tv_sec, &token);
2756 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
2757 inode->i_ctime.tv_nsec, &token);
2759 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
2761 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
2763 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
2764 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
2765 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
2766 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
2767 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
2771 * copy everything in the in-memory inode into the btree.
2773 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2774 struct btrfs_root *root, struct inode *inode)
2776 struct btrfs_inode_item *inode_item;
2777 struct btrfs_path *path;
2778 struct extent_buffer *leaf;
2781 path = btrfs_alloc_path();
2785 path->leave_spinning = 1;
2786 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2794 btrfs_unlock_up_safe(path, 1);
2795 leaf = path->nodes[0];
2796 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2797 struct btrfs_inode_item);
2799 fill_inode_item(trans, leaf, inode_item, inode);
2800 btrfs_mark_buffer_dirty(leaf);
2801 btrfs_set_inode_last_trans(trans, inode);
2804 btrfs_free_path(path);
2809 * copy everything in the in-memory inode into the btree.
2811 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2812 struct btrfs_root *root, struct inode *inode)
2817 * If the inode is a free space inode, we can deadlock during commit
2818 * if we put it into the delayed code.
2820 * The data relocation inode should also be directly updated
2823 if (!btrfs_is_free_space_inode(inode)
2824 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2825 btrfs_update_root_times(trans, root);
2827 ret = btrfs_delayed_update_inode(trans, root, inode);
2829 btrfs_set_inode_last_trans(trans, inode);
2833 return btrfs_update_inode_item(trans, root, inode);
2836 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2837 struct btrfs_root *root,
2838 struct inode *inode)
2842 ret = btrfs_update_inode(trans, root, inode);
2844 return btrfs_update_inode_item(trans, root, inode);
2849 * unlink helper that gets used here in inode.c and in the tree logging
2850 * recovery code. It remove a link in a directory with a given name, and
2851 * also drops the back refs in the inode to the directory
2853 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2854 struct btrfs_root *root,
2855 struct inode *dir, struct inode *inode,
2856 const char *name, int name_len)
2858 struct btrfs_path *path;
2860 struct extent_buffer *leaf;
2861 struct btrfs_dir_item *di;
2862 struct btrfs_key key;
2864 u64 ino = btrfs_ino(inode);
2865 u64 dir_ino = btrfs_ino(dir);
2867 path = btrfs_alloc_path();
2873 path->leave_spinning = 1;
2874 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2875 name, name_len, -1);
2884 leaf = path->nodes[0];
2885 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2886 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2889 btrfs_release_path(path);
2891 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2894 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2895 "inode %llu parent %llu\n", name_len, name,
2896 (unsigned long long)ino, (unsigned long long)dir_ino);
2897 btrfs_abort_transaction(trans, root, ret);
2901 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2903 btrfs_abort_transaction(trans, root, ret);
2907 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2909 if (ret != 0 && ret != -ENOENT) {
2910 btrfs_abort_transaction(trans, root, ret);
2914 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2919 btrfs_free_path(path);
2923 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2924 inode_inc_iversion(inode);
2925 inode_inc_iversion(dir);
2926 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2927 ret = btrfs_update_inode(trans, root, dir);
2932 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2933 struct btrfs_root *root,
2934 struct inode *dir, struct inode *inode,
2935 const char *name, int name_len)
2938 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2940 btrfs_drop_nlink(inode);
2941 ret = btrfs_update_inode(trans, root, inode);
2947 /* helper to check if there is any shared block in the path */
2948 static int check_path_shared(struct btrfs_root *root,
2949 struct btrfs_path *path)
2951 struct extent_buffer *eb;
2955 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2958 if (!path->nodes[level])
2960 eb = path->nodes[level];
2961 if (!btrfs_block_can_be_shared(root, eb))
2963 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2972 * helper to start transaction for unlink and rmdir.
2974 * unlink and rmdir are special in btrfs, they do not always free space.
2975 * so in enospc case, we should make sure they will free space before
2976 * allowing them to use the global metadata reservation.
2978 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2979 struct dentry *dentry)
2981 struct btrfs_trans_handle *trans;
2982 struct btrfs_root *root = BTRFS_I(dir)->root;
2983 struct btrfs_path *path;
2984 struct btrfs_dir_item *di;
2985 struct inode *inode = dentry->d_inode;
2990 u64 ino = btrfs_ino(inode);
2991 u64 dir_ino = btrfs_ino(dir);
2994 * 1 for the possible orphan item
2995 * 1 for the dir item
2996 * 1 for the dir index
2997 * 1 for the inode ref
2998 * 1 for the inode ref in the tree log
2999 * 2 for the dir entries in the log
3002 trans = btrfs_start_transaction(root, 8);
3003 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
3006 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
3007 return ERR_PTR(-ENOSPC);
3009 /* check if there is someone else holds reference */
3010 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
3011 return ERR_PTR(-ENOSPC);
3013 if (atomic_read(&inode->i_count) > 2)
3014 return ERR_PTR(-ENOSPC);
3016 if (xchg(&root->fs_info->enospc_unlink, 1))
3017 return ERR_PTR(-ENOSPC);
3019 path = btrfs_alloc_path();
3021 root->fs_info->enospc_unlink = 0;
3022 return ERR_PTR(-ENOMEM);
3025 /* 1 for the orphan item */
3026 trans = btrfs_start_transaction(root, 1);
3027 if (IS_ERR(trans)) {
3028 btrfs_free_path(path);
3029 root->fs_info->enospc_unlink = 0;
3033 path->skip_locking = 1;
3034 path->search_commit_root = 1;
3036 ret = btrfs_lookup_inode(trans, root, path,
3037 &BTRFS_I(dir)->location, 0);
3043 if (check_path_shared(root, path))
3048 btrfs_release_path(path);
3050 ret = btrfs_lookup_inode(trans, root, path,
3051 &BTRFS_I(inode)->location, 0);
3057 if (check_path_shared(root, path))
3062 btrfs_release_path(path);
3064 if (ret == 0 && S_ISREG(inode->i_mode)) {
3065 ret = btrfs_lookup_file_extent(trans, root, path,
3071 BUG_ON(ret == 0); /* Corruption */
3072 if (check_path_shared(root, path))
3074 btrfs_release_path(path);
3082 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3083 dentry->d_name.name, dentry->d_name.len, 0);
3089 if (check_path_shared(root, path))
3095 btrfs_release_path(path);
3097 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3098 dentry->d_name.len, ino, dir_ino, 0,
3105 if (check_path_shared(root, path))
3108 btrfs_release_path(path);
3111 * This is a commit root search, if we can lookup inode item and other
3112 * relative items in the commit root, it means the transaction of
3113 * dir/file creation has been committed, and the dir index item that we
3114 * delay to insert has also been inserted into the commit root. So
3115 * we needn't worry about the delayed insertion of the dir index item
3118 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3119 dentry->d_name.name, dentry->d_name.len, 0);
3124 BUG_ON(ret == -ENOENT);
3125 if (check_path_shared(root, path))
3130 btrfs_free_path(path);
3131 /* Migrate the orphan reservation over */
3133 err = btrfs_block_rsv_migrate(trans->block_rsv,
3134 &root->fs_info->global_block_rsv,
3135 trans->bytes_reserved);
3138 btrfs_end_transaction(trans, root);
3139 root->fs_info->enospc_unlink = 0;
3140 return ERR_PTR(err);
3143 trans->block_rsv = &root->fs_info->global_block_rsv;
3147 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3148 struct btrfs_root *root)
3150 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3151 btrfs_block_rsv_release(root, trans->block_rsv,
3152 trans->bytes_reserved);
3153 trans->block_rsv = &root->fs_info->trans_block_rsv;
3154 BUG_ON(!root->fs_info->enospc_unlink);
3155 root->fs_info->enospc_unlink = 0;
3157 btrfs_end_transaction(trans, root);
3160 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3162 struct btrfs_root *root = BTRFS_I(dir)->root;
3163 struct btrfs_trans_handle *trans;
3164 struct inode *inode = dentry->d_inode;
3167 trans = __unlink_start_trans(dir, dentry);
3169 return PTR_ERR(trans);
3171 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3173 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3174 dentry->d_name.name, dentry->d_name.len);
3178 if (inode->i_nlink == 0) {
3179 ret = btrfs_orphan_add(trans, inode);
3185 __unlink_end_trans(trans, root);
3186 btrfs_btree_balance_dirty(root);
3190 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3191 struct btrfs_root *root,
3192 struct inode *dir, u64 objectid,
3193 const char *name, int name_len)
3195 struct btrfs_path *path;
3196 struct extent_buffer *leaf;
3197 struct btrfs_dir_item *di;
3198 struct btrfs_key key;
3201 u64 dir_ino = btrfs_ino(dir);
3203 path = btrfs_alloc_path();
3207 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3208 name, name_len, -1);
3209 if (IS_ERR_OR_NULL(di)) {
3217 leaf = path->nodes[0];
3218 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3219 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3220 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3222 btrfs_abort_transaction(trans, root, ret);
3225 btrfs_release_path(path);
3227 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3228 objectid, root->root_key.objectid,
3229 dir_ino, &index, name, name_len);
3231 if (ret != -ENOENT) {
3232 btrfs_abort_transaction(trans, root, ret);
3235 di = btrfs_search_dir_index_item(root, path, dir_ino,
3237 if (IS_ERR_OR_NULL(di)) {
3242 btrfs_abort_transaction(trans, root, ret);
3246 leaf = path->nodes[0];
3247 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3248 btrfs_release_path(path);
3251 btrfs_release_path(path);
3253 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3255 btrfs_abort_transaction(trans, root, ret);
3259 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3260 inode_inc_iversion(dir);
3261 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3262 ret = btrfs_update_inode_fallback(trans, root, dir);
3264 btrfs_abort_transaction(trans, root, ret);
3266 btrfs_free_path(path);
3270 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3272 struct inode *inode = dentry->d_inode;
3274 struct btrfs_root *root = BTRFS_I(dir)->root;
3275 struct btrfs_trans_handle *trans;
3277 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3279 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3282 trans = __unlink_start_trans(dir, dentry);
3284 return PTR_ERR(trans);
3286 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3287 err = btrfs_unlink_subvol(trans, root, dir,
3288 BTRFS_I(inode)->location.objectid,
3289 dentry->d_name.name,
3290 dentry->d_name.len);
3294 err = btrfs_orphan_add(trans, inode);
3298 /* now the directory is empty */
3299 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3300 dentry->d_name.name, dentry->d_name.len);
3302 btrfs_i_size_write(inode, 0);
3304 __unlink_end_trans(trans, root);
3305 btrfs_btree_balance_dirty(root);
3311 * this can truncate away extent items, csum items and directory items.
3312 * It starts at a high offset and removes keys until it can't find
3313 * any higher than new_size
3315 * csum items that cross the new i_size are truncated to the new size
3318 * min_type is the minimum key type to truncate down to. If set to 0, this
3319 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3321 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3322 struct btrfs_root *root,
3323 struct inode *inode,
3324 u64 new_size, u32 min_type)
3326 struct btrfs_path *path;
3327 struct extent_buffer *leaf;
3328 struct btrfs_file_extent_item *fi;
3329 struct btrfs_key key;
3330 struct btrfs_key found_key;
3331 u64 extent_start = 0;
3332 u64 extent_num_bytes = 0;
3333 u64 extent_offset = 0;
3335 u64 mask = root->sectorsize - 1;
3336 u32 found_type = (u8)-1;
3339 int pending_del_nr = 0;
3340 int pending_del_slot = 0;
3341 int extent_type = -1;
3344 u64 ino = btrfs_ino(inode);
3346 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3348 path = btrfs_alloc_path();
3354 * We want to drop from the next block forward in case this new size is
3355 * not block aligned since we will be keeping the last block of the
3356 * extent just the way it is.
3358 if (root->ref_cows || root == root->fs_info->tree_root)
3359 btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0);
3362 * This function is also used to drop the items in the log tree before
3363 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3364 * it is used to drop the loged items. So we shouldn't kill the delayed
3367 if (min_type == 0 && root == BTRFS_I(inode)->root)
3368 btrfs_kill_delayed_inode_items(inode);
3371 key.offset = (u64)-1;
3375 path->leave_spinning = 1;
3376 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3383 /* there are no items in the tree for us to truncate, we're
3386 if (path->slots[0] == 0)
3393 leaf = path->nodes[0];
3394 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3395 found_type = btrfs_key_type(&found_key);
3397 if (found_key.objectid != ino)
3400 if (found_type < min_type)
3403 item_end = found_key.offset;
3404 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3405 fi = btrfs_item_ptr(leaf, path->slots[0],
3406 struct btrfs_file_extent_item);
3407 extent_type = btrfs_file_extent_type(leaf, fi);
3408 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3410 btrfs_file_extent_num_bytes(leaf, fi);
3411 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3412 item_end += btrfs_file_extent_inline_len(leaf,
3417 if (found_type > min_type) {
3420 if (item_end < new_size)
3422 if (found_key.offset >= new_size)
3428 /* FIXME, shrink the extent if the ref count is only 1 */
3429 if (found_type != BTRFS_EXTENT_DATA_KEY)
3432 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3434 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3436 u64 orig_num_bytes =
3437 btrfs_file_extent_num_bytes(leaf, fi);
3438 extent_num_bytes = new_size -
3439 found_key.offset + root->sectorsize - 1;
3440 extent_num_bytes = extent_num_bytes &
3441 ~((u64)root->sectorsize - 1);
3442 btrfs_set_file_extent_num_bytes(leaf, fi,
3444 num_dec = (orig_num_bytes -
3446 if (root->ref_cows && extent_start != 0)
3447 inode_sub_bytes(inode, num_dec);
3448 btrfs_mark_buffer_dirty(leaf);
3451 btrfs_file_extent_disk_num_bytes(leaf,
3453 extent_offset = found_key.offset -
3454 btrfs_file_extent_offset(leaf, fi);
3456 /* FIXME blocksize != 4096 */
3457 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3458 if (extent_start != 0) {
3461 inode_sub_bytes(inode, num_dec);
3464 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3466 * we can't truncate inline items that have had
3470 btrfs_file_extent_compression(leaf, fi) == 0 &&
3471 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3472 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3473 u32 size = new_size - found_key.offset;
3475 if (root->ref_cows) {
3476 inode_sub_bytes(inode, item_end + 1 -
3480 btrfs_file_extent_calc_inline_size(size);
3481 btrfs_truncate_item(trans, root, path,
3483 } else if (root->ref_cows) {
3484 inode_sub_bytes(inode, item_end + 1 -
3490 if (!pending_del_nr) {
3491 /* no pending yet, add ourselves */
3492 pending_del_slot = path->slots[0];
3494 } else if (pending_del_nr &&
3495 path->slots[0] + 1 == pending_del_slot) {
3496 /* hop on the pending chunk */
3498 pending_del_slot = path->slots[0];
3505 if (found_extent && (root->ref_cows ||
3506 root == root->fs_info->tree_root)) {
3507 btrfs_set_path_blocking(path);
3508 ret = btrfs_free_extent(trans, root, extent_start,
3509 extent_num_bytes, 0,
3510 btrfs_header_owner(leaf),
3511 ino, extent_offset, 0);
3515 if (found_type == BTRFS_INODE_ITEM_KEY)
3518 if (path->slots[0] == 0 ||
3519 path->slots[0] != pending_del_slot) {
3520 if (pending_del_nr) {
3521 ret = btrfs_del_items(trans, root, path,
3525 btrfs_abort_transaction(trans,
3531 btrfs_release_path(path);
3538 if (pending_del_nr) {
3539 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3542 btrfs_abort_transaction(trans, root, ret);
3545 btrfs_free_path(path);
3550 * btrfs_truncate_page - read, zero a chunk and write a page
3551 * @inode - inode that we're zeroing
3552 * @from - the offset to start zeroing
3553 * @len - the length to zero, 0 to zero the entire range respective to the
3555 * @front - zero up to the offset instead of from the offset on
3557 * This will find the page for the "from" offset and cow the page and zero the
3558 * part we want to zero. This is used with truncate and hole punching.
3560 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
3563 struct address_space *mapping = inode->i_mapping;
3564 struct btrfs_root *root = BTRFS_I(inode)->root;
3565 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3566 struct btrfs_ordered_extent *ordered;
3567 struct extent_state *cached_state = NULL;
3569 u32 blocksize = root->sectorsize;
3570 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3571 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3573 gfp_t mask = btrfs_alloc_write_mask(mapping);
3578 if ((offset & (blocksize - 1)) == 0 &&
3579 (!len || ((len & (blocksize - 1)) == 0)))
3581 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3586 page = find_or_create_page(mapping, index, mask);
3588 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3593 page_start = page_offset(page);
3594 page_end = page_start + PAGE_CACHE_SIZE - 1;
3596 if (!PageUptodate(page)) {
3597 ret = btrfs_readpage(NULL, page);
3599 if (page->mapping != mapping) {
3601 page_cache_release(page);
3604 if (!PageUptodate(page)) {
3609 wait_on_page_writeback(page);
3611 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3612 set_page_extent_mapped(page);
3614 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3616 unlock_extent_cached(io_tree, page_start, page_end,
3617 &cached_state, GFP_NOFS);
3619 page_cache_release(page);
3620 btrfs_start_ordered_extent(inode, ordered, 1);
3621 btrfs_put_ordered_extent(ordered);
3625 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3626 EXTENT_DIRTY | EXTENT_DELALLOC |
3627 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
3628 0, 0, &cached_state, GFP_NOFS);
3630 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3633 unlock_extent_cached(io_tree, page_start, page_end,
3634 &cached_state, GFP_NOFS);
3638 if (offset != PAGE_CACHE_SIZE) {
3640 len = PAGE_CACHE_SIZE - offset;
3643 memset(kaddr, 0, offset);
3645 memset(kaddr + offset, 0, len);
3646 flush_dcache_page(page);
3649 ClearPageChecked(page);
3650 set_page_dirty(page);
3651 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3656 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3658 page_cache_release(page);
3664 * This function puts in dummy file extents for the area we're creating a hole
3665 * for. So if we are truncating this file to a larger size we need to insert
3666 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3667 * the range between oldsize and size
3669 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3671 struct btrfs_trans_handle *trans;
3672 struct btrfs_root *root = BTRFS_I(inode)->root;
3673 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3674 struct extent_map *em = NULL;
3675 struct extent_state *cached_state = NULL;
3676 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3677 u64 mask = root->sectorsize - 1;
3678 u64 hole_start = (oldsize + mask) & ~mask;
3679 u64 block_end = (size + mask) & ~mask;
3685 if (size <= hole_start)
3689 struct btrfs_ordered_extent *ordered;
3690 btrfs_wait_ordered_range(inode, hole_start,
3691 block_end - hole_start);
3692 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3694 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3697 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3698 &cached_state, GFP_NOFS);
3699 btrfs_put_ordered_extent(ordered);
3702 cur_offset = hole_start;
3704 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3705 block_end - cur_offset, 0);
3711 last_byte = min(extent_map_end(em), block_end);
3712 last_byte = (last_byte + mask) & ~mask;
3713 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3714 struct extent_map *hole_em;
3715 hole_size = last_byte - cur_offset;
3717 trans = btrfs_start_transaction(root, 3);
3718 if (IS_ERR(trans)) {
3719 err = PTR_ERR(trans);
3723 err = btrfs_drop_extents(trans, root, inode,
3725 cur_offset + hole_size, 1);
3727 btrfs_abort_transaction(trans, root, err);
3728 btrfs_end_transaction(trans, root);
3732 err = btrfs_insert_file_extent(trans, root,
3733 btrfs_ino(inode), cur_offset, 0,
3734 0, hole_size, 0, hole_size,
3737 btrfs_abort_transaction(trans, root, err);
3738 btrfs_end_transaction(trans, root);
3742 btrfs_drop_extent_cache(inode, cur_offset,
3743 cur_offset + hole_size - 1, 0);
3744 hole_em = alloc_extent_map();
3746 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3747 &BTRFS_I(inode)->runtime_flags);
3750 hole_em->start = cur_offset;
3751 hole_em->len = hole_size;
3752 hole_em->orig_start = cur_offset;
3754 hole_em->block_start = EXTENT_MAP_HOLE;
3755 hole_em->block_len = 0;
3756 hole_em->orig_block_len = 0;
3757 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
3758 hole_em->compress_type = BTRFS_COMPRESS_NONE;
3759 hole_em->generation = trans->transid;
3762 write_lock(&em_tree->lock);
3763 err = add_extent_mapping(em_tree, hole_em);
3765 list_move(&hole_em->list,
3766 &em_tree->modified_extents);
3767 write_unlock(&em_tree->lock);
3770 btrfs_drop_extent_cache(inode, cur_offset,
3774 free_extent_map(hole_em);
3776 btrfs_update_inode(trans, root, inode);
3777 btrfs_end_transaction(trans, root);
3779 free_extent_map(em);
3781 cur_offset = last_byte;
3782 if (cur_offset >= block_end)
3786 free_extent_map(em);
3787 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3792 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
3794 struct btrfs_root *root = BTRFS_I(inode)->root;
3795 struct btrfs_trans_handle *trans;
3796 loff_t oldsize = i_size_read(inode);
3797 loff_t newsize = attr->ia_size;
3798 int mask = attr->ia_valid;
3801 if (newsize == oldsize)
3805 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
3806 * special case where we need to update the times despite not having
3807 * these flags set. For all other operations the VFS set these flags
3808 * explicitly if it wants a timestamp update.
3810 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
3811 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
3813 if (newsize > oldsize) {
3814 truncate_pagecache(inode, oldsize, newsize);
3815 ret = btrfs_cont_expand(inode, oldsize, newsize);
3819 trans = btrfs_start_transaction(root, 1);
3821 return PTR_ERR(trans);
3823 i_size_write(inode, newsize);
3824 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3825 ret = btrfs_update_inode(trans, root, inode);
3826 btrfs_end_transaction(trans, root);
3830 * We're truncating a file that used to have good data down to
3831 * zero. Make sure it gets into the ordered flush list so that
3832 * any new writes get down to disk quickly.
3835 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3836 &BTRFS_I(inode)->runtime_flags);
3839 * 1 for the orphan item we're going to add
3840 * 1 for the orphan item deletion.
3842 trans = btrfs_start_transaction(root, 2);
3844 return PTR_ERR(trans);
3847 * We need to do this in case we fail at _any_ point during the
3848 * actual truncate. Once we do the truncate_setsize we could
3849 * invalidate pages which forces any outstanding ordered io to
3850 * be instantly completed which will give us extents that need
3851 * to be truncated. If we fail to get an orphan inode down we
3852 * could have left over extents that were never meant to live,
3853 * so we need to garuntee from this point on that everything
3854 * will be consistent.
3856 ret = btrfs_orphan_add(trans, inode);
3857 btrfs_end_transaction(trans, root);
3861 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3862 truncate_setsize(inode, newsize);
3863 ret = btrfs_truncate(inode);
3864 if (ret && inode->i_nlink)
3865 btrfs_orphan_del(NULL, inode);
3871 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3873 struct inode *inode = dentry->d_inode;
3874 struct btrfs_root *root = BTRFS_I(inode)->root;
3877 if (btrfs_root_readonly(root))
3880 err = inode_change_ok(inode, attr);
3884 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3885 err = btrfs_setsize(inode, attr);
3890 if (attr->ia_valid) {
3891 setattr_copy(inode, attr);
3892 inode_inc_iversion(inode);
3893 err = btrfs_dirty_inode(inode);
3895 if (!err && attr->ia_valid & ATTR_MODE)
3896 err = btrfs_acl_chmod(inode);
3902 void btrfs_evict_inode(struct inode *inode)
3904 struct btrfs_trans_handle *trans;
3905 struct btrfs_root *root = BTRFS_I(inode)->root;
3906 struct btrfs_block_rsv *rsv, *global_rsv;
3907 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3910 trace_btrfs_inode_evict(inode);
3912 truncate_inode_pages(&inode->i_data, 0);
3913 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3914 btrfs_is_free_space_inode(inode)))
3917 if (is_bad_inode(inode)) {
3918 btrfs_orphan_del(NULL, inode);
3921 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3922 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3924 if (root->fs_info->log_root_recovering) {
3925 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3926 &BTRFS_I(inode)->runtime_flags));
3930 if (inode->i_nlink > 0) {
3931 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3935 ret = btrfs_commit_inode_delayed_inode(inode);
3937 btrfs_orphan_del(NULL, inode);
3941 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3943 btrfs_orphan_del(NULL, inode);
3946 rsv->size = min_size;
3948 global_rsv = &root->fs_info->global_block_rsv;
3950 btrfs_i_size_write(inode, 0);
3953 * This is a bit simpler than btrfs_truncate since we've already
3954 * reserved our space for our orphan item in the unlink, so we just
3955 * need to reserve some slack space in case we add bytes and update
3956 * inode item when doing the truncate.
3959 ret = btrfs_block_rsv_refill(root, rsv, min_size,
3960 BTRFS_RESERVE_FLUSH_LIMIT);
3963 * Try and steal from the global reserve since we will
3964 * likely not use this space anyway, we want to try as
3965 * hard as possible to get this to work.
3968 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3971 printk(KERN_WARNING "Could not get space for a "
3972 "delete, will truncate on mount %d\n", ret);
3973 btrfs_orphan_del(NULL, inode);
3974 btrfs_free_block_rsv(root, rsv);
3978 trans = btrfs_join_transaction(root);
3979 if (IS_ERR(trans)) {
3980 btrfs_orphan_del(NULL, inode);
3981 btrfs_free_block_rsv(root, rsv);
3985 trans->block_rsv = rsv;
3987 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3991 trans->block_rsv = &root->fs_info->trans_block_rsv;
3992 btrfs_end_transaction(trans, root);
3994 btrfs_btree_balance_dirty(root);
3997 btrfs_free_block_rsv(root, rsv);
4000 trans->block_rsv = root->orphan_block_rsv;
4001 ret = btrfs_orphan_del(trans, inode);
4005 trans->block_rsv = &root->fs_info->trans_block_rsv;
4006 if (!(root == root->fs_info->tree_root ||
4007 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4008 btrfs_return_ino(root, btrfs_ino(inode));
4010 btrfs_end_transaction(trans, root);
4011 btrfs_btree_balance_dirty(root);
4018 * this returns the key found in the dir entry in the location pointer.
4019 * If no dir entries were found, location->objectid is 0.
4021 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4022 struct btrfs_key *location)
4024 const char *name = dentry->d_name.name;
4025 int namelen = dentry->d_name.len;
4026 struct btrfs_dir_item *di;
4027 struct btrfs_path *path;
4028 struct btrfs_root *root = BTRFS_I(dir)->root;
4031 path = btrfs_alloc_path();
4035 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4040 if (IS_ERR_OR_NULL(di))
4043 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4045 btrfs_free_path(path);
4048 location->objectid = 0;
4053 * when we hit a tree root in a directory, the btrfs part of the inode
4054 * needs to be changed to reflect the root directory of the tree root. This
4055 * is kind of like crossing a mount point.
4057 static int fixup_tree_root_location(struct btrfs_root *root,
4059 struct dentry *dentry,
4060 struct btrfs_key *location,
4061 struct btrfs_root **sub_root)
4063 struct btrfs_path *path;
4064 struct btrfs_root *new_root;
4065 struct btrfs_root_ref *ref;
4066 struct extent_buffer *leaf;
4070 path = btrfs_alloc_path();
4077 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4078 BTRFS_I(dir)->root->root_key.objectid,
4079 location->objectid);
4086 leaf = path->nodes[0];
4087 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4088 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4089 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4092 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4093 (unsigned long)(ref + 1),
4094 dentry->d_name.len);
4098 btrfs_release_path(path);
4100 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4101 if (IS_ERR(new_root)) {
4102 err = PTR_ERR(new_root);
4106 if (btrfs_root_refs(&new_root->root_item) == 0) {
4111 *sub_root = new_root;
4112 location->objectid = btrfs_root_dirid(&new_root->root_item);
4113 location->type = BTRFS_INODE_ITEM_KEY;
4114 location->offset = 0;
4117 btrfs_free_path(path);
4121 static void inode_tree_add(struct inode *inode)
4123 struct btrfs_root *root = BTRFS_I(inode)->root;
4124 struct btrfs_inode *entry;
4126 struct rb_node *parent;
4127 u64 ino = btrfs_ino(inode);
4129 p = &root->inode_tree.rb_node;
4132 if (inode_unhashed(inode))
4135 spin_lock(&root->inode_lock);
4138 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4140 if (ino < btrfs_ino(&entry->vfs_inode))
4141 p = &parent->rb_left;
4142 else if (ino > btrfs_ino(&entry->vfs_inode))
4143 p = &parent->rb_right;
4145 WARN_ON(!(entry->vfs_inode.i_state &
4146 (I_WILL_FREE | I_FREEING)));
4147 rb_erase(parent, &root->inode_tree);
4148 RB_CLEAR_NODE(parent);
4149 spin_unlock(&root->inode_lock);
4153 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4154 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4155 spin_unlock(&root->inode_lock);
4158 static void inode_tree_del(struct inode *inode)
4160 struct btrfs_root *root = BTRFS_I(inode)->root;
4163 spin_lock(&root->inode_lock);
4164 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4165 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4166 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4167 empty = RB_EMPTY_ROOT(&root->inode_tree);
4169 spin_unlock(&root->inode_lock);
4172 * Free space cache has inodes in the tree root, but the tree root has a
4173 * root_refs of 0, so this could end up dropping the tree root as a
4174 * snapshot, so we need the extra !root->fs_info->tree_root check to
4175 * make sure we don't drop it.
4177 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4178 root != root->fs_info->tree_root) {
4179 synchronize_srcu(&root->fs_info->subvol_srcu);
4180 spin_lock(&root->inode_lock);
4181 empty = RB_EMPTY_ROOT(&root->inode_tree);
4182 spin_unlock(&root->inode_lock);
4184 btrfs_add_dead_root(root);
4188 void btrfs_invalidate_inodes(struct btrfs_root *root)
4190 struct rb_node *node;
4191 struct rb_node *prev;
4192 struct btrfs_inode *entry;
4193 struct inode *inode;
4196 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4198 spin_lock(&root->inode_lock);
4200 node = root->inode_tree.rb_node;
4204 entry = rb_entry(node, struct btrfs_inode, rb_node);
4206 if (objectid < btrfs_ino(&entry->vfs_inode))
4207 node = node->rb_left;
4208 else if (objectid > btrfs_ino(&entry->vfs_inode))
4209 node = node->rb_right;
4215 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4216 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4220 prev = rb_next(prev);
4224 entry = rb_entry(node, struct btrfs_inode, rb_node);
4225 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4226 inode = igrab(&entry->vfs_inode);
4228 spin_unlock(&root->inode_lock);
4229 if (atomic_read(&inode->i_count) > 1)
4230 d_prune_aliases(inode);
4232 * btrfs_drop_inode will have it removed from
4233 * the inode cache when its usage count
4238 spin_lock(&root->inode_lock);
4242 if (cond_resched_lock(&root->inode_lock))
4245 node = rb_next(node);
4247 spin_unlock(&root->inode_lock);
4250 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4252 struct btrfs_iget_args *args = p;
4253 inode->i_ino = args->ino;
4254 BTRFS_I(inode)->root = args->root;
4258 static int btrfs_find_actor(struct inode *inode, void *opaque)
4260 struct btrfs_iget_args *args = opaque;
4261 return args->ino == btrfs_ino(inode) &&
4262 args->root == BTRFS_I(inode)->root;
4265 static struct inode *btrfs_iget_locked(struct super_block *s,
4267 struct btrfs_root *root)
4269 struct inode *inode;
4270 struct btrfs_iget_args args;
4271 args.ino = objectid;
4274 inode = iget5_locked(s, objectid, btrfs_find_actor,
4275 btrfs_init_locked_inode,
4280 /* Get an inode object given its location and corresponding root.
4281 * Returns in *is_new if the inode was read from disk
4283 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4284 struct btrfs_root *root, int *new)
4286 struct inode *inode;
4288 inode = btrfs_iget_locked(s, location->objectid, root);
4290 return ERR_PTR(-ENOMEM);
4292 if (inode->i_state & I_NEW) {
4293 BTRFS_I(inode)->root = root;
4294 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4295 btrfs_read_locked_inode(inode);
4296 if (!is_bad_inode(inode)) {
4297 inode_tree_add(inode);
4298 unlock_new_inode(inode);
4302 unlock_new_inode(inode);
4304 inode = ERR_PTR(-ESTALE);
4311 static struct inode *new_simple_dir(struct super_block *s,
4312 struct btrfs_key *key,
4313 struct btrfs_root *root)
4315 struct inode *inode = new_inode(s);
4318 return ERR_PTR(-ENOMEM);
4320 BTRFS_I(inode)->root = root;
4321 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4322 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4324 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4325 inode->i_op = &btrfs_dir_ro_inode_operations;
4326 inode->i_fop = &simple_dir_operations;
4327 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4328 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4333 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4335 struct inode *inode;
4336 struct btrfs_root *root = BTRFS_I(dir)->root;
4337 struct btrfs_root *sub_root = root;
4338 struct btrfs_key location;
4342 if (dentry->d_name.len > BTRFS_NAME_LEN)
4343 return ERR_PTR(-ENAMETOOLONG);
4345 if (unlikely(d_need_lookup(dentry))) {
4346 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
4347 kfree(dentry->d_fsdata);
4348 dentry->d_fsdata = NULL;
4349 /* This thing is hashed, drop it for now */
4352 ret = btrfs_inode_by_name(dir, dentry, &location);
4356 return ERR_PTR(ret);
4358 if (location.objectid == 0)
4361 if (location.type == BTRFS_INODE_ITEM_KEY) {
4362 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4366 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4368 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4369 ret = fixup_tree_root_location(root, dir, dentry,
4370 &location, &sub_root);
4373 inode = ERR_PTR(ret);
4375 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4377 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4379 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4381 if (!IS_ERR(inode) && root != sub_root) {
4382 down_read(&root->fs_info->cleanup_work_sem);
4383 if (!(inode->i_sb->s_flags & MS_RDONLY))
4384 ret = btrfs_orphan_cleanup(sub_root);
4385 up_read(&root->fs_info->cleanup_work_sem);
4387 inode = ERR_PTR(ret);
4393 static int btrfs_dentry_delete(const struct dentry *dentry)
4395 struct btrfs_root *root;
4396 struct inode *inode = dentry->d_inode;
4398 if (!inode && !IS_ROOT(dentry))
4399 inode = dentry->d_parent->d_inode;
4402 root = BTRFS_I(inode)->root;
4403 if (btrfs_root_refs(&root->root_item) == 0)
4406 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4412 static void btrfs_dentry_release(struct dentry *dentry)
4414 if (dentry->d_fsdata)
4415 kfree(dentry->d_fsdata);
4418 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4423 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4424 if (unlikely(d_need_lookup(dentry))) {
4425 spin_lock(&dentry->d_lock);
4426 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4427 spin_unlock(&dentry->d_lock);
4432 unsigned char btrfs_filetype_table[] = {
4433 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4436 static int btrfs_real_readdir(struct file *filp, void *dirent,
4439 struct inode *inode = filp->f_dentry->d_inode;
4440 struct btrfs_root *root = BTRFS_I(inode)->root;
4441 struct btrfs_item *item;
4442 struct btrfs_dir_item *di;
4443 struct btrfs_key key;
4444 struct btrfs_key found_key;
4445 struct btrfs_path *path;
4446 struct list_head ins_list;
4447 struct list_head del_list;
4449 struct extent_buffer *leaf;
4451 unsigned char d_type;
4456 int key_type = BTRFS_DIR_INDEX_KEY;
4460 int is_curr = 0; /* filp->f_pos points to the current index? */
4462 /* FIXME, use a real flag for deciding about the key type */
4463 if (root->fs_info->tree_root == root)
4464 key_type = BTRFS_DIR_ITEM_KEY;
4466 /* special case for "." */
4467 if (filp->f_pos == 0) {
4468 over = filldir(dirent, ".", 1,
4469 filp->f_pos, btrfs_ino(inode), DT_DIR);
4474 /* special case for .., just use the back ref */
4475 if (filp->f_pos == 1) {
4476 u64 pino = parent_ino(filp->f_path.dentry);
4477 over = filldir(dirent, "..", 2,
4478 filp->f_pos, pino, DT_DIR);
4483 path = btrfs_alloc_path();
4489 if (key_type == BTRFS_DIR_INDEX_KEY) {
4490 INIT_LIST_HEAD(&ins_list);
4491 INIT_LIST_HEAD(&del_list);
4492 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4495 btrfs_set_key_type(&key, key_type);
4496 key.offset = filp->f_pos;
4497 key.objectid = btrfs_ino(inode);
4499 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4504 leaf = path->nodes[0];
4505 slot = path->slots[0];
4506 if (slot >= btrfs_header_nritems(leaf)) {
4507 ret = btrfs_next_leaf(root, path);
4515 item = btrfs_item_nr(leaf, slot);
4516 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4518 if (found_key.objectid != key.objectid)
4520 if (btrfs_key_type(&found_key) != key_type)
4522 if (found_key.offset < filp->f_pos)
4524 if (key_type == BTRFS_DIR_INDEX_KEY &&
4525 btrfs_should_delete_dir_index(&del_list,
4529 filp->f_pos = found_key.offset;
4532 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4534 di_total = btrfs_item_size(leaf, item);
4536 while (di_cur < di_total) {
4537 struct btrfs_key location;
4539 if (verify_dir_item(root, leaf, di))
4542 name_len = btrfs_dir_name_len(leaf, di);
4543 if (name_len <= sizeof(tmp_name)) {
4544 name_ptr = tmp_name;
4546 name_ptr = kmalloc(name_len, GFP_NOFS);
4552 read_extent_buffer(leaf, name_ptr,
4553 (unsigned long)(di + 1), name_len);
4555 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4556 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4559 /* is this a reference to our own snapshot? If so
4562 * In contrast to old kernels, we insert the snapshot's
4563 * dir item and dir index after it has been created, so
4564 * we won't find a reference to our own snapshot. We
4565 * still keep the following code for backward
4568 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4569 location.objectid == root->root_key.objectid) {
4573 over = filldir(dirent, name_ptr, name_len,
4574 found_key.offset, location.objectid,
4578 if (name_ptr != tmp_name)
4583 di_len = btrfs_dir_name_len(leaf, di) +
4584 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4586 di = (struct btrfs_dir_item *)((char *)di + di_len);
4592 if (key_type == BTRFS_DIR_INDEX_KEY) {
4595 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4601 /* Reached end of directory/root. Bump pos past the last item. */
4602 if (key_type == BTRFS_DIR_INDEX_KEY)
4604 * 32-bit glibc will use getdents64, but then strtol -
4605 * so the last number we can serve is this.
4607 filp->f_pos = 0x7fffffff;
4613 if (key_type == BTRFS_DIR_INDEX_KEY)
4614 btrfs_put_delayed_items(&ins_list, &del_list);
4615 btrfs_free_path(path);
4619 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4621 struct btrfs_root *root = BTRFS_I(inode)->root;
4622 struct btrfs_trans_handle *trans;
4624 bool nolock = false;
4626 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4629 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
4632 if (wbc->sync_mode == WB_SYNC_ALL) {
4634 trans = btrfs_join_transaction_nolock(root);
4636 trans = btrfs_join_transaction(root);
4638 return PTR_ERR(trans);
4639 ret = btrfs_commit_transaction(trans, root);
4645 * This is somewhat expensive, updating the tree every time the
4646 * inode changes. But, it is most likely to find the inode in cache.
4647 * FIXME, needs more benchmarking...there are no reasons other than performance
4648 * to keep or drop this code.
4650 int btrfs_dirty_inode(struct inode *inode)
4652 struct btrfs_root *root = BTRFS_I(inode)->root;
4653 struct btrfs_trans_handle *trans;
4656 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4659 trans = btrfs_join_transaction(root);
4661 return PTR_ERR(trans);
4663 ret = btrfs_update_inode(trans, root, inode);
4664 if (ret && ret == -ENOSPC) {
4665 /* whoops, lets try again with the full transaction */
4666 btrfs_end_transaction(trans, root);
4667 trans = btrfs_start_transaction(root, 1);
4669 return PTR_ERR(trans);
4671 ret = btrfs_update_inode(trans, root, inode);
4673 btrfs_end_transaction(trans, root);
4674 if (BTRFS_I(inode)->delayed_node)
4675 btrfs_balance_delayed_items(root);
4681 * This is a copy of file_update_time. We need this so we can return error on
4682 * ENOSPC for updating the inode in the case of file write and mmap writes.
4684 static int btrfs_update_time(struct inode *inode, struct timespec *now,
4687 struct btrfs_root *root = BTRFS_I(inode)->root;
4689 if (btrfs_root_readonly(root))
4692 if (flags & S_VERSION)
4693 inode_inc_iversion(inode);
4694 if (flags & S_CTIME)
4695 inode->i_ctime = *now;
4696 if (flags & S_MTIME)
4697 inode->i_mtime = *now;
4698 if (flags & S_ATIME)
4699 inode->i_atime = *now;
4700 return btrfs_dirty_inode(inode);
4704 * find the highest existing sequence number in a directory
4705 * and then set the in-memory index_cnt variable to reflect
4706 * free sequence numbers
4708 static int btrfs_set_inode_index_count(struct inode *inode)
4710 struct btrfs_root *root = BTRFS_I(inode)->root;
4711 struct btrfs_key key, found_key;
4712 struct btrfs_path *path;
4713 struct extent_buffer *leaf;
4716 key.objectid = btrfs_ino(inode);
4717 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4718 key.offset = (u64)-1;
4720 path = btrfs_alloc_path();
4724 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4727 /* FIXME: we should be able to handle this */
4733 * MAGIC NUMBER EXPLANATION:
4734 * since we search a directory based on f_pos we have to start at 2
4735 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4736 * else has to start at 2
4738 if (path->slots[0] == 0) {
4739 BTRFS_I(inode)->index_cnt = 2;
4745 leaf = path->nodes[0];
4746 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4748 if (found_key.objectid != btrfs_ino(inode) ||
4749 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4750 BTRFS_I(inode)->index_cnt = 2;
4754 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4756 btrfs_free_path(path);
4761 * helper to find a free sequence number in a given directory. This current
4762 * code is very simple, later versions will do smarter things in the btree
4764 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4768 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4769 ret = btrfs_inode_delayed_dir_index_count(dir);
4771 ret = btrfs_set_inode_index_count(dir);
4777 *index = BTRFS_I(dir)->index_cnt;
4778 BTRFS_I(dir)->index_cnt++;
4783 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4784 struct btrfs_root *root,
4786 const char *name, int name_len,
4787 u64 ref_objectid, u64 objectid,
4788 umode_t mode, u64 *index)
4790 struct inode *inode;
4791 struct btrfs_inode_item *inode_item;
4792 struct btrfs_key *location;
4793 struct btrfs_path *path;
4794 struct btrfs_inode_ref *ref;
4795 struct btrfs_key key[2];
4801 path = btrfs_alloc_path();
4803 return ERR_PTR(-ENOMEM);
4805 inode = new_inode(root->fs_info->sb);
4807 btrfs_free_path(path);
4808 return ERR_PTR(-ENOMEM);
4812 * we have to initialize this early, so we can reclaim the inode
4813 * number if we fail afterwards in this function.
4815 inode->i_ino = objectid;
4818 trace_btrfs_inode_request(dir);
4820 ret = btrfs_set_inode_index(dir, index);
4822 btrfs_free_path(path);
4824 return ERR_PTR(ret);
4828 * index_cnt is ignored for everything but a dir,
4829 * btrfs_get_inode_index_count has an explanation for the magic
4832 BTRFS_I(inode)->index_cnt = 2;
4833 BTRFS_I(inode)->root = root;
4834 BTRFS_I(inode)->generation = trans->transid;
4835 inode->i_generation = BTRFS_I(inode)->generation;
4838 * We could have gotten an inode number from somebody who was fsynced
4839 * and then removed in this same transaction, so let's just set full
4840 * sync since it will be a full sync anyway and this will blow away the
4841 * old info in the log.
4843 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
4850 key[0].objectid = objectid;
4851 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4855 * Start new inodes with an inode_ref. This is slightly more
4856 * efficient for small numbers of hard links since they will
4857 * be packed into one item. Extended refs will kick in if we
4858 * add more hard links than can fit in the ref item.
4860 key[1].objectid = objectid;
4861 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4862 key[1].offset = ref_objectid;
4864 sizes[0] = sizeof(struct btrfs_inode_item);
4865 sizes[1] = name_len + sizeof(*ref);
4867 path->leave_spinning = 1;
4868 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4872 inode_init_owner(inode, dir, mode);
4873 inode_set_bytes(inode, 0);
4874 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4875 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4876 struct btrfs_inode_item);
4877 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
4878 sizeof(*inode_item));
4879 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4881 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4882 struct btrfs_inode_ref);
4883 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4884 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4885 ptr = (unsigned long)(ref + 1);
4886 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4888 btrfs_mark_buffer_dirty(path->nodes[0]);
4889 btrfs_free_path(path);
4891 location = &BTRFS_I(inode)->location;
4892 location->objectid = objectid;
4893 location->offset = 0;
4894 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4896 btrfs_inherit_iflags(inode, dir);
4898 if (S_ISREG(mode)) {
4899 if (btrfs_test_opt(root, NODATASUM))
4900 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4901 if (btrfs_test_opt(root, NODATACOW))
4902 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4905 insert_inode_hash(inode);
4906 inode_tree_add(inode);
4908 trace_btrfs_inode_new(inode);
4909 btrfs_set_inode_last_trans(trans, inode);
4911 btrfs_update_root_times(trans, root);
4916 BTRFS_I(dir)->index_cnt--;
4917 btrfs_free_path(path);
4919 return ERR_PTR(ret);
4922 static inline u8 btrfs_inode_type(struct inode *inode)
4924 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4928 * utility function to add 'inode' into 'parent_inode' with
4929 * a give name and a given sequence number.
4930 * if 'add_backref' is true, also insert a backref from the
4931 * inode to the parent directory.
4933 int btrfs_add_link(struct btrfs_trans_handle *trans,
4934 struct inode *parent_inode, struct inode *inode,
4935 const char *name, int name_len, int add_backref, u64 index)
4938 struct btrfs_key key;
4939 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4940 u64 ino = btrfs_ino(inode);
4941 u64 parent_ino = btrfs_ino(parent_inode);
4943 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4944 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4947 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4951 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4952 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4953 key.objectid, root->root_key.objectid,
4954 parent_ino, index, name, name_len);
4955 } else if (add_backref) {
4956 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4960 /* Nothing to clean up yet */
4964 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4966 btrfs_inode_type(inode), index);
4967 if (ret == -EEXIST || ret == -EOVERFLOW)
4970 btrfs_abort_transaction(trans, root, ret);
4974 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4976 inode_inc_iversion(parent_inode);
4977 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4978 ret = btrfs_update_inode(trans, root, parent_inode);
4980 btrfs_abort_transaction(trans, root, ret);
4984 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4987 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4988 key.objectid, root->root_key.objectid,
4989 parent_ino, &local_index, name, name_len);
4991 } else if (add_backref) {
4995 err = btrfs_del_inode_ref(trans, root, name, name_len,
4996 ino, parent_ino, &local_index);
5001 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
5002 struct inode *dir, struct dentry *dentry,
5003 struct inode *inode, int backref, u64 index)
5005 int err = btrfs_add_link(trans, dir, inode,
5006 dentry->d_name.name, dentry->d_name.len,
5013 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
5014 umode_t mode, dev_t rdev)
5016 struct btrfs_trans_handle *trans;
5017 struct btrfs_root *root = BTRFS_I(dir)->root;
5018 struct inode *inode = NULL;
5024 if (!new_valid_dev(rdev))
5028 * 2 for inode item and ref
5030 * 1 for xattr if selinux is on
5032 trans = btrfs_start_transaction(root, 5);
5034 return PTR_ERR(trans);
5036 err = btrfs_find_free_ino(root, &objectid);
5040 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5041 dentry->d_name.len, btrfs_ino(dir), objectid,
5043 if (IS_ERR(inode)) {
5044 err = PTR_ERR(inode);
5048 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5055 * If the active LSM wants to access the inode during
5056 * d_instantiate it needs these. Smack checks to see
5057 * if the filesystem supports xattrs by looking at the
5061 inode->i_op = &btrfs_special_inode_operations;
5062 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5066 init_special_inode(inode, inode->i_mode, rdev);
5067 btrfs_update_inode(trans, root, inode);
5068 d_instantiate(dentry, inode);
5071 btrfs_end_transaction(trans, root);
5072 btrfs_btree_balance_dirty(root);
5074 inode_dec_link_count(inode);
5080 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5081 umode_t mode, bool excl)
5083 struct btrfs_trans_handle *trans;
5084 struct btrfs_root *root = BTRFS_I(dir)->root;
5085 struct inode *inode = NULL;
5086 int drop_inode_on_err = 0;
5092 * 2 for inode item and ref
5094 * 1 for xattr if selinux is on
5096 trans = btrfs_start_transaction(root, 5);
5098 return PTR_ERR(trans);
5100 err = btrfs_find_free_ino(root, &objectid);
5104 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5105 dentry->d_name.len, btrfs_ino(dir), objectid,
5107 if (IS_ERR(inode)) {
5108 err = PTR_ERR(inode);
5111 drop_inode_on_err = 1;
5113 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5117 err = btrfs_update_inode(trans, root, inode);
5122 * If the active LSM wants to access the inode during
5123 * d_instantiate it needs these. Smack checks to see
5124 * if the filesystem supports xattrs by looking at the
5127 inode->i_fop = &btrfs_file_operations;
5128 inode->i_op = &btrfs_file_inode_operations;
5130 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5134 inode->i_mapping->a_ops = &btrfs_aops;
5135 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5136 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5137 d_instantiate(dentry, inode);
5140 btrfs_end_transaction(trans, root);
5141 if (err && drop_inode_on_err) {
5142 inode_dec_link_count(inode);
5145 btrfs_btree_balance_dirty(root);
5149 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5150 struct dentry *dentry)
5152 struct btrfs_trans_handle *trans;
5153 struct btrfs_root *root = BTRFS_I(dir)->root;
5154 struct inode *inode = old_dentry->d_inode;
5159 /* do not allow sys_link's with other subvols of the same device */
5160 if (root->objectid != BTRFS_I(inode)->root->objectid)
5163 if (inode->i_nlink >= BTRFS_LINK_MAX)
5166 err = btrfs_set_inode_index(dir, &index);
5171 * 2 items for inode and inode ref
5172 * 2 items for dir items
5173 * 1 item for parent inode
5175 trans = btrfs_start_transaction(root, 5);
5176 if (IS_ERR(trans)) {
5177 err = PTR_ERR(trans);
5181 btrfs_inc_nlink(inode);
5182 inode_inc_iversion(inode);
5183 inode->i_ctime = CURRENT_TIME;
5185 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5187 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5192 struct dentry *parent = dentry->d_parent;
5193 err = btrfs_update_inode(trans, root, inode);
5196 d_instantiate(dentry, inode);
5197 btrfs_log_new_name(trans, inode, NULL, parent);
5200 btrfs_end_transaction(trans, root);
5203 inode_dec_link_count(inode);
5206 btrfs_btree_balance_dirty(root);
5210 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5212 struct inode *inode = NULL;
5213 struct btrfs_trans_handle *trans;
5214 struct btrfs_root *root = BTRFS_I(dir)->root;
5216 int drop_on_err = 0;
5221 * 2 items for inode and ref
5222 * 2 items for dir items
5223 * 1 for xattr if selinux is on
5225 trans = btrfs_start_transaction(root, 5);
5227 return PTR_ERR(trans);
5229 err = btrfs_find_free_ino(root, &objectid);
5233 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5234 dentry->d_name.len, btrfs_ino(dir), objectid,
5235 S_IFDIR | mode, &index);
5236 if (IS_ERR(inode)) {
5237 err = PTR_ERR(inode);
5243 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5247 inode->i_op = &btrfs_dir_inode_operations;
5248 inode->i_fop = &btrfs_dir_file_operations;
5250 btrfs_i_size_write(inode, 0);
5251 err = btrfs_update_inode(trans, root, inode);
5255 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5256 dentry->d_name.len, 0, index);
5260 d_instantiate(dentry, inode);
5264 btrfs_end_transaction(trans, root);
5267 btrfs_btree_balance_dirty(root);
5271 /* helper for btfs_get_extent. Given an existing extent in the tree,
5272 * and an extent that you want to insert, deal with overlap and insert
5273 * the new extent into the tree.
5275 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5276 struct extent_map *existing,
5277 struct extent_map *em,
5278 u64 map_start, u64 map_len)
5282 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5283 start_diff = map_start - em->start;
5284 em->start = map_start;
5286 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5287 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5288 em->block_start += start_diff;
5289 em->block_len -= start_diff;
5291 return add_extent_mapping(em_tree, em);
5294 static noinline int uncompress_inline(struct btrfs_path *path,
5295 struct inode *inode, struct page *page,
5296 size_t pg_offset, u64 extent_offset,
5297 struct btrfs_file_extent_item *item)
5300 struct extent_buffer *leaf = path->nodes[0];
5303 unsigned long inline_size;
5307 WARN_ON(pg_offset != 0);
5308 compress_type = btrfs_file_extent_compression(leaf, item);
5309 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5310 inline_size = btrfs_file_extent_inline_item_len(leaf,
5311 btrfs_item_nr(leaf, path->slots[0]));
5312 tmp = kmalloc(inline_size, GFP_NOFS);
5315 ptr = btrfs_file_extent_inline_start(item);
5317 read_extent_buffer(leaf, tmp, ptr, inline_size);
5319 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5320 ret = btrfs_decompress(compress_type, tmp, page,
5321 extent_offset, inline_size, max_size);
5323 char *kaddr = kmap_atomic(page);
5324 unsigned long copy_size = min_t(u64,
5325 PAGE_CACHE_SIZE - pg_offset,
5326 max_size - extent_offset);
5327 memset(kaddr + pg_offset, 0, copy_size);
5328 kunmap_atomic(kaddr);
5335 * a bit scary, this does extent mapping from logical file offset to the disk.
5336 * the ugly parts come from merging extents from the disk with the in-ram
5337 * representation. This gets more complex because of the data=ordered code,
5338 * where the in-ram extents might be locked pending data=ordered completion.
5340 * This also copies inline extents directly into the page.
5343 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5344 size_t pg_offset, u64 start, u64 len,
5350 u64 extent_start = 0;
5352 u64 objectid = btrfs_ino(inode);
5354 struct btrfs_path *path = NULL;
5355 struct btrfs_root *root = BTRFS_I(inode)->root;
5356 struct btrfs_file_extent_item *item;
5357 struct extent_buffer *leaf;
5358 struct btrfs_key found_key;
5359 struct extent_map *em = NULL;
5360 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5361 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5362 struct btrfs_trans_handle *trans = NULL;
5366 read_lock(&em_tree->lock);
5367 em = lookup_extent_mapping(em_tree, start, len);
5369 em->bdev = root->fs_info->fs_devices->latest_bdev;
5370 read_unlock(&em_tree->lock);
5373 if (em->start > start || em->start + em->len <= start)
5374 free_extent_map(em);
5375 else if (em->block_start == EXTENT_MAP_INLINE && page)
5376 free_extent_map(em);
5380 em = alloc_extent_map();
5385 em->bdev = root->fs_info->fs_devices->latest_bdev;
5386 em->start = EXTENT_MAP_HOLE;
5387 em->orig_start = EXTENT_MAP_HOLE;
5389 em->block_len = (u64)-1;
5392 path = btrfs_alloc_path();
5398 * Chances are we'll be called again, so go ahead and do
5404 ret = btrfs_lookup_file_extent(trans, root, path,
5405 objectid, start, trans != NULL);
5412 if (path->slots[0] == 0)
5417 leaf = path->nodes[0];
5418 item = btrfs_item_ptr(leaf, path->slots[0],
5419 struct btrfs_file_extent_item);
5420 /* are we inside the extent that was found? */
5421 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5422 found_type = btrfs_key_type(&found_key);
5423 if (found_key.objectid != objectid ||
5424 found_type != BTRFS_EXTENT_DATA_KEY) {
5428 found_type = btrfs_file_extent_type(leaf, item);
5429 extent_start = found_key.offset;
5430 compress_type = btrfs_file_extent_compression(leaf, item);
5431 if (found_type == BTRFS_FILE_EXTENT_REG ||
5432 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5433 extent_end = extent_start +
5434 btrfs_file_extent_num_bytes(leaf, item);
5435 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5437 size = btrfs_file_extent_inline_len(leaf, item);
5438 extent_end = (extent_start + size + root->sectorsize - 1) &
5439 ~((u64)root->sectorsize - 1);
5442 if (start >= extent_end) {
5444 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5445 ret = btrfs_next_leaf(root, path);
5452 leaf = path->nodes[0];
5454 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5455 if (found_key.objectid != objectid ||
5456 found_key.type != BTRFS_EXTENT_DATA_KEY)
5458 if (start + len <= found_key.offset)
5461 em->orig_start = start;
5462 em->len = found_key.offset - start;
5466 if (found_type == BTRFS_FILE_EXTENT_REG ||
5467 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5468 em->start = extent_start;
5469 em->len = extent_end - extent_start;
5470 em->orig_start = extent_start -
5471 btrfs_file_extent_offset(leaf, item);
5472 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
5474 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5476 em->block_start = EXTENT_MAP_HOLE;
5479 if (compress_type != BTRFS_COMPRESS_NONE) {
5480 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5481 em->compress_type = compress_type;
5482 em->block_start = bytenr;
5483 em->block_len = em->orig_block_len;
5485 bytenr += btrfs_file_extent_offset(leaf, item);
5486 em->block_start = bytenr;
5487 em->block_len = em->len;
5488 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5489 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5492 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5496 size_t extent_offset;
5499 em->block_start = EXTENT_MAP_INLINE;
5500 if (!page || create) {
5501 em->start = extent_start;
5502 em->len = extent_end - extent_start;
5506 size = btrfs_file_extent_inline_len(leaf, item);
5507 extent_offset = page_offset(page) + pg_offset - extent_start;
5508 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5509 size - extent_offset);
5510 em->start = extent_start + extent_offset;
5511 em->len = (copy_size + root->sectorsize - 1) &
5512 ~((u64)root->sectorsize - 1);
5513 em->orig_block_len = em->len;
5514 em->orig_start = em->start;
5515 if (compress_type) {
5516 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5517 em->compress_type = compress_type;
5519 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5520 if (create == 0 && !PageUptodate(page)) {
5521 if (btrfs_file_extent_compression(leaf, item) !=
5522 BTRFS_COMPRESS_NONE) {
5523 ret = uncompress_inline(path, inode, page,
5525 extent_offset, item);
5526 BUG_ON(ret); /* -ENOMEM */
5529 read_extent_buffer(leaf, map + pg_offset, ptr,
5531 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5532 memset(map + pg_offset + copy_size, 0,
5533 PAGE_CACHE_SIZE - pg_offset -
5538 flush_dcache_page(page);
5539 } else if (create && PageUptodate(page)) {
5543 free_extent_map(em);
5546 btrfs_release_path(path);
5547 trans = btrfs_join_transaction(root);
5550 return ERR_CAST(trans);
5554 write_extent_buffer(leaf, map + pg_offset, ptr,
5557 btrfs_mark_buffer_dirty(leaf);
5559 set_extent_uptodate(io_tree, em->start,
5560 extent_map_end(em) - 1, NULL, GFP_NOFS);
5563 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
5567 em->orig_start = start;
5570 em->block_start = EXTENT_MAP_HOLE;
5571 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5573 btrfs_release_path(path);
5574 if (em->start > start || extent_map_end(em) <= start) {
5575 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5576 "[%llu %llu]\n", (unsigned long long)em->start,
5577 (unsigned long long)em->len,
5578 (unsigned long long)start,
5579 (unsigned long long)len);
5585 write_lock(&em_tree->lock);
5586 ret = add_extent_mapping(em_tree, em);
5587 /* it is possible that someone inserted the extent into the tree
5588 * while we had the lock dropped. It is also possible that
5589 * an overlapping map exists in the tree
5591 if (ret == -EEXIST) {
5592 struct extent_map *existing;
5596 existing = lookup_extent_mapping(em_tree, start, len);
5597 if (existing && (existing->start > start ||
5598 existing->start + existing->len <= start)) {
5599 free_extent_map(existing);
5603 existing = lookup_extent_mapping(em_tree, em->start,
5606 err = merge_extent_mapping(em_tree, existing,
5609 free_extent_map(existing);
5611 free_extent_map(em);
5616 free_extent_map(em);
5620 free_extent_map(em);
5625 write_unlock(&em_tree->lock);
5629 trace_btrfs_get_extent(root, em);
5632 btrfs_free_path(path);
5634 ret = btrfs_end_transaction(trans, root);
5639 free_extent_map(em);
5640 return ERR_PTR(err);
5642 BUG_ON(!em); /* Error is always set */
5646 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5647 size_t pg_offset, u64 start, u64 len,
5650 struct extent_map *em;
5651 struct extent_map *hole_em = NULL;
5652 u64 range_start = start;
5658 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5665 * - a pre-alloc extent,
5666 * there might actually be delalloc bytes behind it.
5668 if (em->block_start != EXTENT_MAP_HOLE &&
5669 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5675 /* check to see if we've wrapped (len == -1 or similar) */
5684 /* ok, we didn't find anything, lets look for delalloc */
5685 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5686 end, len, EXTENT_DELALLOC, 1);
5687 found_end = range_start + found;
5688 if (found_end < range_start)
5689 found_end = (u64)-1;
5692 * we didn't find anything useful, return
5693 * the original results from get_extent()
5695 if (range_start > end || found_end <= start) {
5701 /* adjust the range_start to make sure it doesn't
5702 * go backwards from the start they passed in
5704 range_start = max(start,range_start);
5705 found = found_end - range_start;
5708 u64 hole_start = start;
5711 em = alloc_extent_map();
5717 * when btrfs_get_extent can't find anything it
5718 * returns one huge hole
5720 * make sure what it found really fits our range, and
5721 * adjust to make sure it is based on the start from
5725 u64 calc_end = extent_map_end(hole_em);
5727 if (calc_end <= start || (hole_em->start > end)) {
5728 free_extent_map(hole_em);
5731 hole_start = max(hole_em->start, start);
5732 hole_len = calc_end - hole_start;
5736 if (hole_em && range_start > hole_start) {
5737 /* our hole starts before our delalloc, so we
5738 * have to return just the parts of the hole
5739 * that go until the delalloc starts
5741 em->len = min(hole_len,
5742 range_start - hole_start);
5743 em->start = hole_start;
5744 em->orig_start = hole_start;
5746 * don't adjust block start at all,
5747 * it is fixed at EXTENT_MAP_HOLE
5749 em->block_start = hole_em->block_start;
5750 em->block_len = hole_len;
5751 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
5752 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5754 em->start = range_start;
5756 em->orig_start = range_start;
5757 em->block_start = EXTENT_MAP_DELALLOC;
5758 em->block_len = found;
5760 } else if (hole_em) {
5765 free_extent_map(hole_em);
5767 free_extent_map(em);
5768 return ERR_PTR(err);
5773 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5776 struct btrfs_root *root = BTRFS_I(inode)->root;
5777 struct btrfs_trans_handle *trans;
5778 struct extent_map *em;
5779 struct btrfs_key ins;
5783 trans = btrfs_join_transaction(root);
5785 return ERR_CAST(trans);
5787 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5789 alloc_hint = get_extent_allocation_hint(inode, start, len);
5790 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5791 alloc_hint, &ins, 1);
5797 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
5798 ins.offset, ins.offset, 0);
5802 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5803 ins.offset, ins.offset, 0);
5805 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5809 btrfs_end_transaction(trans, root);
5814 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5815 * block must be cow'd
5817 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5818 struct inode *inode, u64 offset, u64 len)
5820 struct btrfs_path *path;
5822 struct extent_buffer *leaf;
5823 struct btrfs_root *root = BTRFS_I(inode)->root;
5824 struct btrfs_file_extent_item *fi;
5825 struct btrfs_key key;
5833 path = btrfs_alloc_path();
5837 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5842 slot = path->slots[0];
5845 /* can't find the item, must cow */
5852 leaf = path->nodes[0];
5853 btrfs_item_key_to_cpu(leaf, &key, slot);
5854 if (key.objectid != btrfs_ino(inode) ||
5855 key.type != BTRFS_EXTENT_DATA_KEY) {
5856 /* not our file or wrong item type, must cow */
5860 if (key.offset > offset) {
5861 /* Wrong offset, must cow */
5865 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5866 found_type = btrfs_file_extent_type(leaf, fi);
5867 if (found_type != BTRFS_FILE_EXTENT_REG &&
5868 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5869 /* not a regular extent, must cow */
5872 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5873 backref_offset = btrfs_file_extent_offset(leaf, fi);
5875 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5876 if (extent_end < offset + len) {
5877 /* extent doesn't include our full range, must cow */
5881 if (btrfs_extent_readonly(root, disk_bytenr))
5885 * look for other files referencing this extent, if we
5886 * find any we must cow
5888 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5889 key.offset - backref_offset, disk_bytenr))
5893 * adjust disk_bytenr and num_bytes to cover just the bytes
5894 * in this extent we are about to write. If there
5895 * are any csums in that range we have to cow in order
5896 * to keep the csums correct
5898 disk_bytenr += backref_offset;
5899 disk_bytenr += offset - key.offset;
5900 num_bytes = min(offset + len, extent_end) - offset;
5901 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5904 * all of the above have passed, it is safe to overwrite this extent
5909 btrfs_free_path(path);
5913 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
5914 struct extent_state **cached_state, int writing)
5916 struct btrfs_ordered_extent *ordered;
5920 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5923 * We're concerned with the entire range that we're going to be
5924 * doing DIO to, so we need to make sure theres no ordered
5925 * extents in this range.
5927 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5928 lockend - lockstart + 1);
5931 * We need to make sure there are no buffered pages in this
5932 * range either, we could have raced between the invalidate in
5933 * generic_file_direct_write and locking the extent. The
5934 * invalidate needs to happen so that reads after a write do not
5937 if (!ordered && (!writing ||
5938 !test_range_bit(&BTRFS_I(inode)->io_tree,
5939 lockstart, lockend, EXTENT_UPTODATE, 0,
5943 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5944 cached_state, GFP_NOFS);
5947 btrfs_start_ordered_extent(inode, ordered, 1);
5948 btrfs_put_ordered_extent(ordered);
5950 /* Screw you mmap */
5951 ret = filemap_write_and_wait_range(inode->i_mapping,
5958 * If we found a page that couldn't be invalidated just
5959 * fall back to buffered.
5961 ret = invalidate_inode_pages2_range(inode->i_mapping,
5962 lockstart >> PAGE_CACHE_SHIFT,
5963 lockend >> PAGE_CACHE_SHIFT);
5974 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
5975 u64 len, u64 orig_start,
5976 u64 block_start, u64 block_len,
5977 u64 orig_block_len, int type)
5979 struct extent_map_tree *em_tree;
5980 struct extent_map *em;
5981 struct btrfs_root *root = BTRFS_I(inode)->root;
5984 em_tree = &BTRFS_I(inode)->extent_tree;
5985 em = alloc_extent_map();
5987 return ERR_PTR(-ENOMEM);
5990 em->orig_start = orig_start;
5991 em->mod_start = start;
5994 em->block_len = block_len;
5995 em->block_start = block_start;
5996 em->bdev = root->fs_info->fs_devices->latest_bdev;
5997 em->orig_block_len = orig_block_len;
5998 em->generation = -1;
5999 set_bit(EXTENT_FLAG_PINNED, &em->flags);
6000 if (type == BTRFS_ORDERED_PREALLOC)
6001 set_bit(EXTENT_FLAG_FILLING, &em->flags);
6004 btrfs_drop_extent_cache(inode, em->start,
6005 em->start + em->len - 1, 0);
6006 write_lock(&em_tree->lock);
6007 ret = add_extent_mapping(em_tree, em);
6009 list_move(&em->list,
6010 &em_tree->modified_extents);
6011 write_unlock(&em_tree->lock);
6012 } while (ret == -EEXIST);
6015 free_extent_map(em);
6016 return ERR_PTR(ret);
6023 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6024 struct buffer_head *bh_result, int create)
6026 struct extent_map *em;
6027 struct btrfs_root *root = BTRFS_I(inode)->root;
6028 struct extent_state *cached_state = NULL;
6029 u64 start = iblock << inode->i_blkbits;
6030 u64 lockstart, lockend;
6031 u64 len = bh_result->b_size;
6032 struct btrfs_trans_handle *trans;
6033 int unlock_bits = EXTENT_LOCKED;
6037 ret = btrfs_delalloc_reserve_space(inode, len);
6040 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6042 len = min_t(u64, len, root->sectorsize);
6046 lockend = start + len - 1;
6049 * If this errors out it's because we couldn't invalidate pagecache for
6050 * this range and we need to fallback to buffered.
6052 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6056 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6057 lockend, EXTENT_DELALLOC, NULL,
6058 &cached_state, GFP_NOFS);
6063 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6070 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6071 * io. INLINE is special, and we could probably kludge it in here, but
6072 * it's still buffered so for safety lets just fall back to the generic
6075 * For COMPRESSED we _have_ to read the entire extent in so we can
6076 * decompress it, so there will be buffering required no matter what we
6077 * do, so go ahead and fallback to buffered.
6079 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6080 * to buffered IO. Don't blame me, this is the price we pay for using
6083 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6084 em->block_start == EXTENT_MAP_INLINE) {
6085 free_extent_map(em);
6090 /* Just a good old fashioned hole, return */
6091 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6092 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6093 free_extent_map(em);
6099 * We don't allocate a new extent in the following cases
6101 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6103 * 2) The extent is marked as PREALLOC. We're good to go here and can
6104 * just use the extent.
6108 len = min(len, em->len - (start - em->start));
6109 lockstart = start + len;
6113 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6114 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6115 em->block_start != EXTENT_MAP_HOLE)) {
6120 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6121 type = BTRFS_ORDERED_PREALLOC;
6123 type = BTRFS_ORDERED_NOCOW;
6124 len = min(len, em->len - (start - em->start));
6125 block_start = em->block_start + (start - em->start);
6128 * we're not going to log anything, but we do need
6129 * to make sure the current transaction stays open
6130 * while we look for nocow cross refs
6132 trans = btrfs_join_transaction(root);
6136 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6137 u64 orig_start = em->orig_start;
6138 u64 orig_block_len = em->orig_block_len;
6140 if (type == BTRFS_ORDERED_PREALLOC) {
6141 free_extent_map(em);
6142 em = create_pinned_em(inode, start, len,
6145 orig_block_len, type);
6147 btrfs_end_transaction(trans, root);
6152 ret = btrfs_add_ordered_extent_dio(inode, start,
6153 block_start, len, len, type);
6154 btrfs_end_transaction(trans, root);
6156 free_extent_map(em);
6161 btrfs_end_transaction(trans, root);
6165 * this will cow the extent, reset the len in case we changed
6168 len = bh_result->b_size;
6169 free_extent_map(em);
6170 em = btrfs_new_extent_direct(inode, start, len);
6175 len = min(len, em->len - (start - em->start));
6177 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6179 bh_result->b_size = len;
6180 bh_result->b_bdev = em->bdev;
6181 set_buffer_mapped(bh_result);
6183 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6184 set_buffer_new(bh_result);
6187 * Need to update the i_size under the extent lock so buffered
6188 * readers will get the updated i_size when we unlock.
6190 if (start + len > i_size_read(inode))
6191 i_size_write(inode, start + len);
6195 * In the case of write we need to clear and unlock the entire range,
6196 * in the case of read we need to unlock only the end area that we
6197 * aren't using if there is any left over space.
6199 if (lockstart < lockend) {
6200 if (create && len < lockend - lockstart) {
6201 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6202 lockstart + len - 1,
6203 unlock_bits | EXTENT_DEFRAG, 1, 0,
6204 &cached_state, GFP_NOFS);
6206 * Beside unlock, we also need to cleanup reserved space
6207 * for the left range by attaching EXTENT_DO_ACCOUNTING.
6209 clear_extent_bit(&BTRFS_I(inode)->io_tree,
6210 lockstart + len, lockend,
6211 unlock_bits | EXTENT_DO_ACCOUNTING |
6212 EXTENT_DEFRAG, 1, 0, NULL, GFP_NOFS);
6214 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6215 lockend, unlock_bits, 1, 0,
6216 &cached_state, GFP_NOFS);
6219 free_extent_state(cached_state);
6222 free_extent_map(em);
6228 unlock_bits |= EXTENT_DO_ACCOUNTING;
6230 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6231 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6235 struct btrfs_dio_private {
6236 struct inode *inode;
6242 /* number of bios pending for this dio */
6243 atomic_t pending_bios;
6248 struct bio *orig_bio;
6251 static void btrfs_endio_direct_read(struct bio *bio, int err)
6253 struct btrfs_dio_private *dip = bio->bi_private;
6254 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6255 struct bio_vec *bvec = bio->bi_io_vec;
6256 struct inode *inode = dip->inode;
6257 struct btrfs_root *root = BTRFS_I(inode)->root;
6260 start = dip->logical_offset;
6262 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6263 struct page *page = bvec->bv_page;
6266 u64 private = ~(u32)0;
6267 unsigned long flags;
6269 if (get_state_private(&BTRFS_I(inode)->io_tree,
6272 local_irq_save(flags);
6273 kaddr = kmap_atomic(page);
6274 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
6275 csum, bvec->bv_len);
6276 btrfs_csum_final(csum, (char *)&csum);
6277 kunmap_atomic(kaddr);
6278 local_irq_restore(flags);
6280 flush_dcache_page(bvec->bv_page);
6281 if (csum != private) {
6283 printk(KERN_ERR "btrfs csum failed ino %llu off"
6284 " %llu csum %u private %u\n",
6285 (unsigned long long)btrfs_ino(inode),
6286 (unsigned long long)start,
6287 csum, (unsigned)private);
6292 start += bvec->bv_len;
6294 } while (bvec <= bvec_end);
6296 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6297 dip->logical_offset + dip->bytes - 1);
6298 bio->bi_private = dip->private;
6302 /* If we had a csum failure make sure to clear the uptodate flag */
6304 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6305 dio_end_io(bio, err);
6308 static void btrfs_endio_direct_write(struct bio *bio, int err)
6310 struct btrfs_dio_private *dip = bio->bi_private;
6311 struct inode *inode = dip->inode;
6312 struct btrfs_root *root = BTRFS_I(inode)->root;
6313 struct btrfs_ordered_extent *ordered = NULL;
6314 u64 ordered_offset = dip->logical_offset;
6315 u64 ordered_bytes = dip->bytes;
6321 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6323 ordered_bytes, !err);
6327 ordered->work.func = finish_ordered_fn;
6328 ordered->work.flags = 0;
6329 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6333 * our bio might span multiple ordered extents. If we haven't
6334 * completed the accounting for the whole dio, go back and try again
6336 if (ordered_offset < dip->logical_offset + dip->bytes) {
6337 ordered_bytes = dip->logical_offset + dip->bytes -
6343 bio->bi_private = dip->private;
6347 /* If we had an error make sure to clear the uptodate flag */
6349 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6350 dio_end_io(bio, err);
6353 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6354 struct bio *bio, int mirror_num,
6355 unsigned long bio_flags, u64 offset)
6358 struct btrfs_root *root = BTRFS_I(inode)->root;
6359 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6360 BUG_ON(ret); /* -ENOMEM */
6364 static void btrfs_end_dio_bio(struct bio *bio, int err)
6366 struct btrfs_dio_private *dip = bio->bi_private;
6369 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6370 "sector %#Lx len %u err no %d\n",
6371 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6372 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6376 * before atomic variable goto zero, we must make sure
6377 * dip->errors is perceived to be set.
6379 smp_mb__before_atomic_dec();
6382 /* if there are more bios still pending for this dio, just exit */
6383 if (!atomic_dec_and_test(&dip->pending_bios))
6387 bio_io_error(dip->orig_bio);
6389 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
6390 bio_endio(dip->orig_bio, 0);
6396 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6397 u64 first_sector, gfp_t gfp_flags)
6399 int nr_vecs = bio_get_nr_vecs(bdev);
6400 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6403 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6404 int rw, u64 file_offset, int skip_sum,
6407 int write = rw & REQ_WRITE;
6408 struct btrfs_root *root = BTRFS_I(inode)->root;
6412 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6417 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6425 if (write && async_submit) {
6426 ret = btrfs_wq_submit_bio(root->fs_info,
6427 inode, rw, bio, 0, 0,
6429 __btrfs_submit_bio_start_direct_io,
6430 __btrfs_submit_bio_done);
6434 * If we aren't doing async submit, calculate the csum of the
6437 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6440 } else if (!skip_sum) {
6441 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
6447 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6453 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6456 struct inode *inode = dip->inode;
6457 struct btrfs_root *root = BTRFS_I(inode)->root;
6459 struct bio *orig_bio = dip->orig_bio;
6460 struct bio_vec *bvec = orig_bio->bi_io_vec;
6461 u64 start_sector = orig_bio->bi_sector;
6462 u64 file_offset = dip->logical_offset;
6467 int async_submit = 0;
6469 map_length = orig_bio->bi_size;
6470 ret = btrfs_map_block(root->fs_info, READ, start_sector << 9,
6471 &map_length, NULL, 0);
6477 if (map_length >= orig_bio->bi_size) {
6483 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6486 bio->bi_private = dip;
6487 bio->bi_end_io = btrfs_end_dio_bio;
6488 atomic_inc(&dip->pending_bios);
6490 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6491 if (unlikely(map_length < submit_len + bvec->bv_len ||
6492 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6493 bvec->bv_offset) < bvec->bv_len)) {
6495 * inc the count before we submit the bio so
6496 * we know the end IO handler won't happen before
6497 * we inc the count. Otherwise, the dip might get freed
6498 * before we're done setting it up
6500 atomic_inc(&dip->pending_bios);
6501 ret = __btrfs_submit_dio_bio(bio, inode, rw,
6502 file_offset, skip_sum,
6506 atomic_dec(&dip->pending_bios);
6510 start_sector += submit_len >> 9;
6511 file_offset += submit_len;
6516 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6517 start_sector, GFP_NOFS);
6520 bio->bi_private = dip;
6521 bio->bi_end_io = btrfs_end_dio_bio;
6523 map_length = orig_bio->bi_size;
6524 ret = btrfs_map_block(root->fs_info, READ,
6526 &map_length, NULL, 0);
6532 submit_len += bvec->bv_len;
6539 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6548 * before atomic variable goto zero, we must
6549 * make sure dip->errors is perceived to be set.
6551 smp_mb__before_atomic_dec();
6552 if (atomic_dec_and_test(&dip->pending_bios))
6553 bio_io_error(dip->orig_bio);
6555 /* bio_end_io() will handle error, so we needn't return it */
6559 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6562 struct btrfs_root *root = BTRFS_I(inode)->root;
6563 struct btrfs_dio_private *dip;
6564 struct bio_vec *bvec = bio->bi_io_vec;
6566 int write = rw & REQ_WRITE;
6569 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6571 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6577 dip->private = bio->bi_private;
6579 dip->logical_offset = file_offset;
6583 dip->bytes += bvec->bv_len;
6585 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6587 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6588 bio->bi_private = dip;
6590 dip->orig_bio = bio;
6591 atomic_set(&dip->pending_bios, 0);
6594 bio->bi_end_io = btrfs_endio_direct_write;
6596 bio->bi_end_io = btrfs_endio_direct_read;
6598 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6603 * If this is a write, we need to clean up the reserved space and kill
6604 * the ordered extent.
6607 struct btrfs_ordered_extent *ordered;
6608 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6609 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6610 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6611 btrfs_free_reserved_extent(root, ordered->start,
6613 btrfs_put_ordered_extent(ordered);
6614 btrfs_put_ordered_extent(ordered);
6616 bio_endio(bio, ret);
6619 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6620 const struct iovec *iov, loff_t offset,
6621 unsigned long nr_segs)
6627 unsigned blocksize_mask = root->sectorsize - 1;
6628 ssize_t retval = -EINVAL;
6629 loff_t end = offset;
6631 if (offset & blocksize_mask)
6634 /* Check the memory alignment. Blocks cannot straddle pages */
6635 for (seg = 0; seg < nr_segs; seg++) {
6636 addr = (unsigned long)iov[seg].iov_base;
6637 size = iov[seg].iov_len;
6639 if ((addr & blocksize_mask) || (size & blocksize_mask))
6642 /* If this is a write we don't need to check anymore */
6647 * Check to make sure we don't have duplicate iov_base's in this
6648 * iovec, if so return EINVAL, otherwise we'll get csum errors
6649 * when reading back.
6651 for (i = seg + 1; i < nr_segs; i++) {
6652 if (iov[seg].iov_base == iov[i].iov_base)
6661 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6662 const struct iovec *iov, loff_t offset,
6663 unsigned long nr_segs)
6665 struct file *file = iocb->ki_filp;
6666 struct inode *inode = file->f_mapping->host;
6668 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6672 return __blockdev_direct_IO(rw, iocb, inode,
6673 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6674 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6675 btrfs_submit_direct, 0);
6678 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
6680 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6681 __u64 start, __u64 len)
6685 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
6689 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6692 int btrfs_readpage(struct file *file, struct page *page)
6694 struct extent_io_tree *tree;
6695 tree = &BTRFS_I(page->mapping->host)->io_tree;
6696 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6699 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6701 struct extent_io_tree *tree;
6704 if (current->flags & PF_MEMALLOC) {
6705 redirty_page_for_writepage(wbc, page);
6709 tree = &BTRFS_I(page->mapping->host)->io_tree;
6710 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6713 int btrfs_writepages(struct address_space *mapping,
6714 struct writeback_control *wbc)
6716 struct extent_io_tree *tree;
6718 tree = &BTRFS_I(mapping->host)->io_tree;
6719 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6723 btrfs_readpages(struct file *file, struct address_space *mapping,
6724 struct list_head *pages, unsigned nr_pages)
6726 struct extent_io_tree *tree;
6727 tree = &BTRFS_I(mapping->host)->io_tree;
6728 return extent_readpages(tree, mapping, pages, nr_pages,
6731 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6733 struct extent_io_tree *tree;
6734 struct extent_map_tree *map;
6737 tree = &BTRFS_I(page->mapping->host)->io_tree;
6738 map = &BTRFS_I(page->mapping->host)->extent_tree;
6739 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6741 ClearPagePrivate(page);
6742 set_page_private(page, 0);
6743 page_cache_release(page);
6748 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6750 if (PageWriteback(page) || PageDirty(page))
6752 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6755 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6757 struct inode *inode = page->mapping->host;
6758 struct extent_io_tree *tree;
6759 struct btrfs_ordered_extent *ordered;
6760 struct extent_state *cached_state = NULL;
6761 u64 page_start = page_offset(page);
6762 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6765 * we have the page locked, so new writeback can't start,
6766 * and the dirty bit won't be cleared while we are here.
6768 * Wait for IO on this page so that we can safely clear
6769 * the PagePrivate2 bit and do ordered accounting
6771 wait_on_page_writeback(page);
6773 tree = &BTRFS_I(inode)->io_tree;
6775 btrfs_releasepage(page, GFP_NOFS);
6778 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6779 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
6782 * IO on this page will never be started, so we need
6783 * to account for any ordered extents now
6785 clear_extent_bit(tree, page_start, page_end,
6786 EXTENT_DIRTY | EXTENT_DELALLOC |
6787 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
6788 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
6790 * whoever cleared the private bit is responsible
6791 * for the finish_ordered_io
6793 if (TestClearPagePrivate2(page) &&
6794 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
6795 PAGE_CACHE_SIZE, 1)) {
6796 btrfs_finish_ordered_io(ordered);
6798 btrfs_put_ordered_extent(ordered);
6799 cached_state = NULL;
6800 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6802 clear_extent_bit(tree, page_start, page_end,
6803 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6804 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
6805 &cached_state, GFP_NOFS);
6806 __btrfs_releasepage(page, GFP_NOFS);
6808 ClearPageChecked(page);
6809 if (PagePrivate(page)) {
6810 ClearPagePrivate(page);
6811 set_page_private(page, 0);
6812 page_cache_release(page);
6817 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6818 * called from a page fault handler when a page is first dirtied. Hence we must
6819 * be careful to check for EOF conditions here. We set the page up correctly
6820 * for a written page which means we get ENOSPC checking when writing into
6821 * holes and correct delalloc and unwritten extent mapping on filesystems that
6822 * support these features.
6824 * We are not allowed to take the i_mutex here so we have to play games to
6825 * protect against truncate races as the page could now be beyond EOF. Because
6826 * vmtruncate() writes the inode size before removing pages, once we have the
6827 * page lock we can determine safely if the page is beyond EOF. If it is not
6828 * beyond EOF, then the page is guaranteed safe against truncation until we
6831 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6833 struct page *page = vmf->page;
6834 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6835 struct btrfs_root *root = BTRFS_I(inode)->root;
6836 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6837 struct btrfs_ordered_extent *ordered;
6838 struct extent_state *cached_state = NULL;
6840 unsigned long zero_start;
6847 sb_start_pagefault(inode->i_sb);
6848 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6850 ret = file_update_time(vma->vm_file);
6856 else /* -ENOSPC, -EIO, etc */
6857 ret = VM_FAULT_SIGBUS;
6863 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6866 size = i_size_read(inode);
6867 page_start = page_offset(page);
6868 page_end = page_start + PAGE_CACHE_SIZE - 1;
6870 if ((page->mapping != inode->i_mapping) ||
6871 (page_start >= size)) {
6872 /* page got truncated out from underneath us */
6875 wait_on_page_writeback(page);
6877 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
6878 set_page_extent_mapped(page);
6881 * we can't set the delalloc bits if there are pending ordered
6882 * extents. Drop our locks and wait for them to finish
6884 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6886 unlock_extent_cached(io_tree, page_start, page_end,
6887 &cached_state, GFP_NOFS);
6889 btrfs_start_ordered_extent(inode, ordered, 1);
6890 btrfs_put_ordered_extent(ordered);
6895 * XXX - page_mkwrite gets called every time the page is dirtied, even
6896 * if it was already dirty, so for space accounting reasons we need to
6897 * clear any delalloc bits for the range we are fixing to save. There
6898 * is probably a better way to do this, but for now keep consistent with
6899 * prepare_pages in the normal write path.
6901 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6902 EXTENT_DIRTY | EXTENT_DELALLOC |
6903 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
6904 0, 0, &cached_state, GFP_NOFS);
6906 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6909 unlock_extent_cached(io_tree, page_start, page_end,
6910 &cached_state, GFP_NOFS);
6911 ret = VM_FAULT_SIGBUS;
6916 /* page is wholly or partially inside EOF */
6917 if (page_start + PAGE_CACHE_SIZE > size)
6918 zero_start = size & ~PAGE_CACHE_MASK;
6920 zero_start = PAGE_CACHE_SIZE;
6922 if (zero_start != PAGE_CACHE_SIZE) {
6924 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6925 flush_dcache_page(page);
6928 ClearPageChecked(page);
6929 set_page_dirty(page);
6930 SetPageUptodate(page);
6932 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6933 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6934 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
6936 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6940 sb_end_pagefault(inode->i_sb);
6941 return VM_FAULT_LOCKED;
6945 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6947 sb_end_pagefault(inode->i_sb);
6951 static int btrfs_truncate(struct inode *inode)
6953 struct btrfs_root *root = BTRFS_I(inode)->root;
6954 struct btrfs_block_rsv *rsv;
6957 struct btrfs_trans_handle *trans;
6958 u64 mask = root->sectorsize - 1;
6959 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6961 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
6965 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6966 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6969 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6970 * 3 things going on here
6972 * 1) We need to reserve space for our orphan item and the space to
6973 * delete our orphan item. Lord knows we don't want to have a dangling
6974 * orphan item because we didn't reserve space to remove it.
6976 * 2) We need to reserve space to update our inode.
6978 * 3) We need to have something to cache all the space that is going to
6979 * be free'd up by the truncate operation, but also have some slack
6980 * space reserved in case it uses space during the truncate (thank you
6981 * very much snapshotting).
6983 * And we need these to all be seperate. The fact is we can use alot of
6984 * space doing the truncate, and we have no earthly idea how much space
6985 * we will use, so we need the truncate reservation to be seperate so it
6986 * doesn't end up using space reserved for updating the inode or
6987 * removing the orphan item. We also need to be able to stop the
6988 * transaction and start a new one, which means we need to be able to
6989 * update the inode several times, and we have no idea of knowing how
6990 * many times that will be, so we can't just reserve 1 item for the
6991 * entirety of the opration, so that has to be done seperately as well.
6992 * Then there is the orphan item, which does indeed need to be held on
6993 * to for the whole operation, and we need nobody to touch this reserved
6994 * space except the orphan code.
6996 * So that leaves us with
6998 * 1) root->orphan_block_rsv - for the orphan deletion.
6999 * 2) rsv - for the truncate reservation, which we will steal from the
7000 * transaction reservation.
7001 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
7002 * updating the inode.
7004 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
7007 rsv->size = min_size;
7011 * 1 for the truncate slack space
7012 * 1 for updating the inode.
7014 trans = btrfs_start_transaction(root, 2);
7015 if (IS_ERR(trans)) {
7016 err = PTR_ERR(trans);
7020 /* Migrate the slack space for the truncate to our reserve */
7021 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7026 * setattr is responsible for setting the ordered_data_close flag,
7027 * but that is only tested during the last file release. That
7028 * could happen well after the next commit, leaving a great big
7029 * window where new writes may get lost if someone chooses to write
7030 * to this file after truncating to zero
7032 * The inode doesn't have any dirty data here, and so if we commit
7033 * this is a noop. If someone immediately starts writing to the inode
7034 * it is very likely we'll catch some of their writes in this
7035 * transaction, and the commit will find this file on the ordered
7036 * data list with good things to send down.
7038 * This is a best effort solution, there is still a window where
7039 * using truncate to replace the contents of the file will
7040 * end up with a zero length file after a crash.
7042 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7043 &BTRFS_I(inode)->runtime_flags))
7044 btrfs_add_ordered_operation(trans, root, inode);
7047 * So if we truncate and then write and fsync we normally would just
7048 * write the extents that changed, which is a problem if we need to
7049 * first truncate that entire inode. So set this flag so we write out
7050 * all of the extents in the inode to the sync log so we're completely
7053 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7054 trans->block_rsv = rsv;
7057 ret = btrfs_truncate_inode_items(trans, root, inode,
7059 BTRFS_EXTENT_DATA_KEY);
7060 if (ret != -ENOSPC) {
7065 trans->block_rsv = &root->fs_info->trans_block_rsv;
7066 ret = btrfs_update_inode(trans, root, inode);
7072 btrfs_end_transaction(trans, root);
7073 btrfs_btree_balance_dirty(root);
7075 trans = btrfs_start_transaction(root, 2);
7076 if (IS_ERR(trans)) {
7077 ret = err = PTR_ERR(trans);
7082 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7084 BUG_ON(ret); /* shouldn't happen */
7085 trans->block_rsv = rsv;
7088 if (ret == 0 && inode->i_nlink > 0) {
7089 trans->block_rsv = root->orphan_block_rsv;
7090 ret = btrfs_orphan_del(trans, inode);
7096 trans->block_rsv = &root->fs_info->trans_block_rsv;
7097 ret = btrfs_update_inode(trans, root, inode);
7101 ret = btrfs_end_transaction(trans, root);
7102 btrfs_btree_balance_dirty(root);
7106 btrfs_free_block_rsv(root, rsv);
7115 * create a new subvolume directory/inode (helper for the ioctl).
7117 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7118 struct btrfs_root *new_root, u64 new_dirid)
7120 struct inode *inode;
7124 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7125 new_dirid, new_dirid,
7126 S_IFDIR | (~current_umask() & S_IRWXUGO),
7129 return PTR_ERR(inode);
7130 inode->i_op = &btrfs_dir_inode_operations;
7131 inode->i_fop = &btrfs_dir_file_operations;
7133 set_nlink(inode, 1);
7134 btrfs_i_size_write(inode, 0);
7136 err = btrfs_update_inode(trans, new_root, inode);
7142 struct inode *btrfs_alloc_inode(struct super_block *sb)
7144 struct btrfs_inode *ei;
7145 struct inode *inode;
7147 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7154 ei->last_sub_trans = 0;
7155 ei->logged_trans = 0;
7156 ei->delalloc_bytes = 0;
7157 ei->disk_i_size = 0;
7160 ei->index_cnt = (u64)-1;
7161 ei->last_unlink_trans = 0;
7162 ei->last_log_commit = 0;
7164 spin_lock_init(&ei->lock);
7165 ei->outstanding_extents = 0;
7166 ei->reserved_extents = 0;
7168 ei->runtime_flags = 0;
7169 ei->force_compress = BTRFS_COMPRESS_NONE;
7171 ei->delayed_node = NULL;
7173 inode = &ei->vfs_inode;
7174 extent_map_tree_init(&ei->extent_tree);
7175 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7176 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7177 ei->io_tree.track_uptodate = 1;
7178 ei->io_failure_tree.track_uptodate = 1;
7179 atomic_set(&ei->sync_writers, 0);
7180 mutex_init(&ei->log_mutex);
7181 mutex_init(&ei->delalloc_mutex);
7182 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7183 INIT_LIST_HEAD(&ei->delalloc_inodes);
7184 INIT_LIST_HEAD(&ei->ordered_operations);
7185 RB_CLEAR_NODE(&ei->rb_node);
7190 static void btrfs_i_callback(struct rcu_head *head)
7192 struct inode *inode = container_of(head, struct inode, i_rcu);
7193 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7196 void btrfs_destroy_inode(struct inode *inode)
7198 struct btrfs_ordered_extent *ordered;
7199 struct btrfs_root *root = BTRFS_I(inode)->root;
7201 WARN_ON(!hlist_empty(&inode->i_dentry));
7202 WARN_ON(inode->i_data.nrpages);
7203 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7204 WARN_ON(BTRFS_I(inode)->reserved_extents);
7205 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7206 WARN_ON(BTRFS_I(inode)->csum_bytes);
7209 * This can happen where we create an inode, but somebody else also
7210 * created the same inode and we need to destroy the one we already
7217 * Make sure we're properly removed from the ordered operation
7221 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7222 spin_lock(&root->fs_info->ordered_extent_lock);
7223 list_del_init(&BTRFS_I(inode)->ordered_operations);
7224 spin_unlock(&root->fs_info->ordered_extent_lock);
7227 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7228 &BTRFS_I(inode)->runtime_flags)) {
7229 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
7230 (unsigned long long)btrfs_ino(inode));
7231 atomic_dec(&root->orphan_inodes);
7235 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7239 printk(KERN_ERR "btrfs found ordered "
7240 "extent %llu %llu on inode cleanup\n",
7241 (unsigned long long)ordered->file_offset,
7242 (unsigned long long)ordered->len);
7243 btrfs_remove_ordered_extent(inode, ordered);
7244 btrfs_put_ordered_extent(ordered);
7245 btrfs_put_ordered_extent(ordered);
7248 inode_tree_del(inode);
7249 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7251 btrfs_remove_delayed_node(inode);
7252 call_rcu(&inode->i_rcu, btrfs_i_callback);
7255 int btrfs_drop_inode(struct inode *inode)
7257 struct btrfs_root *root = BTRFS_I(inode)->root;
7259 if (btrfs_root_refs(&root->root_item) == 0 &&
7260 !btrfs_is_free_space_inode(inode))
7263 return generic_drop_inode(inode);
7266 static void init_once(void *foo)
7268 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7270 inode_init_once(&ei->vfs_inode);
7273 void btrfs_destroy_cachep(void)
7276 * Make sure all delayed rcu free inodes are flushed before we
7280 if (btrfs_inode_cachep)
7281 kmem_cache_destroy(btrfs_inode_cachep);
7282 if (btrfs_trans_handle_cachep)
7283 kmem_cache_destroy(btrfs_trans_handle_cachep);
7284 if (btrfs_transaction_cachep)
7285 kmem_cache_destroy(btrfs_transaction_cachep);
7286 if (btrfs_path_cachep)
7287 kmem_cache_destroy(btrfs_path_cachep);
7288 if (btrfs_free_space_cachep)
7289 kmem_cache_destroy(btrfs_free_space_cachep);
7290 if (btrfs_delalloc_work_cachep)
7291 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7294 int btrfs_init_cachep(void)
7296 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7297 sizeof(struct btrfs_inode), 0,
7298 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7299 if (!btrfs_inode_cachep)
7302 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7303 sizeof(struct btrfs_trans_handle), 0,
7304 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7305 if (!btrfs_trans_handle_cachep)
7308 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7309 sizeof(struct btrfs_transaction), 0,
7310 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7311 if (!btrfs_transaction_cachep)
7314 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7315 sizeof(struct btrfs_path), 0,
7316 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7317 if (!btrfs_path_cachep)
7320 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7321 sizeof(struct btrfs_free_space), 0,
7322 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7323 if (!btrfs_free_space_cachep)
7326 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7327 sizeof(struct btrfs_delalloc_work), 0,
7328 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7330 if (!btrfs_delalloc_work_cachep)
7335 btrfs_destroy_cachep();
7339 static int btrfs_getattr(struct vfsmount *mnt,
7340 struct dentry *dentry, struct kstat *stat)
7343 struct inode *inode = dentry->d_inode;
7344 u32 blocksize = inode->i_sb->s_blocksize;
7346 generic_fillattr(inode, stat);
7347 stat->dev = BTRFS_I(inode)->root->anon_dev;
7348 stat->blksize = PAGE_CACHE_SIZE;
7350 spin_lock(&BTRFS_I(inode)->lock);
7351 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
7352 spin_unlock(&BTRFS_I(inode)->lock);
7353 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7354 ALIGN(delalloc_bytes, blocksize)) >> 9;
7359 * If a file is moved, it will inherit the cow and compression flags of the new
7362 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7364 struct btrfs_inode *b_dir = BTRFS_I(dir);
7365 struct btrfs_inode *b_inode = BTRFS_I(inode);
7367 if (b_dir->flags & BTRFS_INODE_NODATACOW)
7368 b_inode->flags |= BTRFS_INODE_NODATACOW;
7370 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7372 if (b_dir->flags & BTRFS_INODE_COMPRESS) {
7373 b_inode->flags |= BTRFS_INODE_COMPRESS;
7374 b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
7376 b_inode->flags &= ~(BTRFS_INODE_COMPRESS |
7377 BTRFS_INODE_NOCOMPRESS);
7381 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7382 struct inode *new_dir, struct dentry *new_dentry)
7384 struct btrfs_trans_handle *trans;
7385 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7386 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7387 struct inode *new_inode = new_dentry->d_inode;
7388 struct inode *old_inode = old_dentry->d_inode;
7389 struct timespec ctime = CURRENT_TIME;
7393 u64 old_ino = btrfs_ino(old_inode);
7395 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7398 /* we only allow rename subvolume link between subvolumes */
7399 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7402 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7403 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7406 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7407 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7411 /* check for collisions, even if the name isn't there */
7412 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
7413 new_dentry->d_name.name,
7414 new_dentry->d_name.len);
7417 if (ret == -EEXIST) {
7419 * eexist without a new_inode */
7425 /* maybe -EOVERFLOW */
7432 * we're using rename to replace one file with another.
7433 * and the replacement file is large. Start IO on it now so
7434 * we don't add too much work to the end of the transaction
7436 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7437 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7438 filemap_flush(old_inode->i_mapping);
7440 /* close the racy window with snapshot create/destroy ioctl */
7441 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7442 down_read(&root->fs_info->subvol_sem);
7444 * We want to reserve the absolute worst case amount of items. So if
7445 * both inodes are subvols and we need to unlink them then that would
7446 * require 4 item modifications, but if they are both normal inodes it
7447 * would require 5 item modifications, so we'll assume their normal
7448 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7449 * should cover the worst case number of items we'll modify.
7451 trans = btrfs_start_transaction(root, 20);
7452 if (IS_ERR(trans)) {
7453 ret = PTR_ERR(trans);
7458 btrfs_record_root_in_trans(trans, dest);
7460 ret = btrfs_set_inode_index(new_dir, &index);
7464 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7465 /* force full log commit if subvolume involved. */
7466 root->fs_info->last_trans_log_full_commit = trans->transid;
7468 ret = btrfs_insert_inode_ref(trans, dest,
7469 new_dentry->d_name.name,
7470 new_dentry->d_name.len,
7472 btrfs_ino(new_dir), index);
7476 * this is an ugly little race, but the rename is required
7477 * to make sure that if we crash, the inode is either at the
7478 * old name or the new one. pinning the log transaction lets
7479 * us make sure we don't allow a log commit to come in after
7480 * we unlink the name but before we add the new name back in.
7482 btrfs_pin_log_trans(root);
7485 * make sure the inode gets flushed if it is replacing
7488 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7489 btrfs_add_ordered_operation(trans, root, old_inode);
7491 inode_inc_iversion(old_dir);
7492 inode_inc_iversion(new_dir);
7493 inode_inc_iversion(old_inode);
7494 old_dir->i_ctime = old_dir->i_mtime = ctime;
7495 new_dir->i_ctime = new_dir->i_mtime = ctime;
7496 old_inode->i_ctime = ctime;
7498 if (old_dentry->d_parent != new_dentry->d_parent)
7499 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7501 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7502 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7503 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7504 old_dentry->d_name.name,
7505 old_dentry->d_name.len);
7507 ret = __btrfs_unlink_inode(trans, root, old_dir,
7508 old_dentry->d_inode,
7509 old_dentry->d_name.name,
7510 old_dentry->d_name.len);
7512 ret = btrfs_update_inode(trans, root, old_inode);
7515 btrfs_abort_transaction(trans, root, ret);
7520 inode_inc_iversion(new_inode);
7521 new_inode->i_ctime = CURRENT_TIME;
7522 if (unlikely(btrfs_ino(new_inode) ==
7523 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7524 root_objectid = BTRFS_I(new_inode)->location.objectid;
7525 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7527 new_dentry->d_name.name,
7528 new_dentry->d_name.len);
7529 BUG_ON(new_inode->i_nlink == 0);
7531 ret = btrfs_unlink_inode(trans, dest, new_dir,
7532 new_dentry->d_inode,
7533 new_dentry->d_name.name,
7534 new_dentry->d_name.len);
7536 if (!ret && new_inode->i_nlink == 0) {
7537 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7541 btrfs_abort_transaction(trans, root, ret);
7546 fixup_inode_flags(new_dir, old_inode);
7548 ret = btrfs_add_link(trans, new_dir, old_inode,
7549 new_dentry->d_name.name,
7550 new_dentry->d_name.len, 0, index);
7552 btrfs_abort_transaction(trans, root, ret);
7556 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7557 struct dentry *parent = new_dentry->d_parent;
7558 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7559 btrfs_end_log_trans(root);
7562 btrfs_end_transaction(trans, root);
7564 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7565 up_read(&root->fs_info->subvol_sem);
7570 static void btrfs_run_delalloc_work(struct btrfs_work *work)
7572 struct btrfs_delalloc_work *delalloc_work;
7574 delalloc_work = container_of(work, struct btrfs_delalloc_work,
7576 if (delalloc_work->wait)
7577 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
7579 filemap_flush(delalloc_work->inode->i_mapping);
7581 if (delalloc_work->delay_iput)
7582 btrfs_add_delayed_iput(delalloc_work->inode);
7584 iput(delalloc_work->inode);
7585 complete(&delalloc_work->completion);
7588 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
7589 int wait, int delay_iput)
7591 struct btrfs_delalloc_work *work;
7593 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
7597 init_completion(&work->completion);
7598 INIT_LIST_HEAD(&work->list);
7599 work->inode = inode;
7601 work->delay_iput = delay_iput;
7602 work->work.func = btrfs_run_delalloc_work;
7607 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
7609 wait_for_completion(&work->completion);
7610 kmem_cache_free(btrfs_delalloc_work_cachep, work);
7614 * some fairly slow code that needs optimization. This walks the list
7615 * of all the inodes with pending delalloc and forces them to disk.
7617 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7619 struct btrfs_inode *binode;
7620 struct inode *inode;
7621 struct btrfs_delalloc_work *work, *next;
7622 struct list_head works;
7623 struct list_head splice;
7626 if (root->fs_info->sb->s_flags & MS_RDONLY)
7629 INIT_LIST_HEAD(&works);
7630 INIT_LIST_HEAD(&splice);
7632 spin_lock(&root->fs_info->delalloc_lock);
7633 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
7634 while (!list_empty(&splice)) {
7635 binode = list_entry(splice.next, struct btrfs_inode,
7638 list_del_init(&binode->delalloc_inodes);
7640 inode = igrab(&binode->vfs_inode);
7642 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
7643 &binode->runtime_flags);
7647 list_add_tail(&binode->delalloc_inodes,
7648 &root->fs_info->delalloc_inodes);
7649 spin_unlock(&root->fs_info->delalloc_lock);
7651 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
7652 if (unlikely(!work)) {
7656 list_add_tail(&work->list, &works);
7657 btrfs_queue_worker(&root->fs_info->flush_workers,
7661 spin_lock(&root->fs_info->delalloc_lock);
7663 spin_unlock(&root->fs_info->delalloc_lock);
7665 list_for_each_entry_safe(work, next, &works, list) {
7666 list_del_init(&work->list);
7667 btrfs_wait_and_free_delalloc_work(work);
7670 /* the filemap_flush will queue IO into the worker threads, but
7671 * we have to make sure the IO is actually started and that
7672 * ordered extents get created before we return
7674 atomic_inc(&root->fs_info->async_submit_draining);
7675 while (atomic_read(&root->fs_info->nr_async_submits) ||
7676 atomic_read(&root->fs_info->async_delalloc_pages)) {
7677 wait_event(root->fs_info->async_submit_wait,
7678 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7679 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7681 atomic_dec(&root->fs_info->async_submit_draining);
7684 list_for_each_entry_safe(work, next, &works, list) {
7685 list_del_init(&work->list);
7686 btrfs_wait_and_free_delalloc_work(work);
7689 if (!list_empty_careful(&splice)) {
7690 spin_lock(&root->fs_info->delalloc_lock);
7691 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
7692 spin_unlock(&root->fs_info->delalloc_lock);
7697 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7698 const char *symname)
7700 struct btrfs_trans_handle *trans;
7701 struct btrfs_root *root = BTRFS_I(dir)->root;
7702 struct btrfs_path *path;
7703 struct btrfs_key key;
7704 struct inode *inode = NULL;
7712 struct btrfs_file_extent_item *ei;
7713 struct extent_buffer *leaf;
7715 name_len = strlen(symname) + 1;
7716 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7717 return -ENAMETOOLONG;
7720 * 2 items for inode item and ref
7721 * 2 items for dir items
7722 * 1 item for xattr if selinux is on
7724 trans = btrfs_start_transaction(root, 5);
7726 return PTR_ERR(trans);
7728 err = btrfs_find_free_ino(root, &objectid);
7732 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7733 dentry->d_name.len, btrfs_ino(dir), objectid,
7734 S_IFLNK|S_IRWXUGO, &index);
7735 if (IS_ERR(inode)) {
7736 err = PTR_ERR(inode);
7740 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7747 * If the active LSM wants to access the inode during
7748 * d_instantiate it needs these. Smack checks to see
7749 * if the filesystem supports xattrs by looking at the
7752 inode->i_fop = &btrfs_file_operations;
7753 inode->i_op = &btrfs_file_inode_operations;
7755 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7759 inode->i_mapping->a_ops = &btrfs_aops;
7760 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7761 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7766 path = btrfs_alloc_path();
7772 key.objectid = btrfs_ino(inode);
7774 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7775 datasize = btrfs_file_extent_calc_inline_size(name_len);
7776 err = btrfs_insert_empty_item(trans, root, path, &key,
7780 btrfs_free_path(path);
7783 leaf = path->nodes[0];
7784 ei = btrfs_item_ptr(leaf, path->slots[0],
7785 struct btrfs_file_extent_item);
7786 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7787 btrfs_set_file_extent_type(leaf, ei,
7788 BTRFS_FILE_EXTENT_INLINE);
7789 btrfs_set_file_extent_encryption(leaf, ei, 0);
7790 btrfs_set_file_extent_compression(leaf, ei, 0);
7791 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7792 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7794 ptr = btrfs_file_extent_inline_start(ei);
7795 write_extent_buffer(leaf, symname, ptr, name_len);
7796 btrfs_mark_buffer_dirty(leaf);
7797 btrfs_free_path(path);
7799 inode->i_op = &btrfs_symlink_inode_operations;
7800 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7801 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7802 inode_set_bytes(inode, name_len);
7803 btrfs_i_size_write(inode, name_len - 1);
7804 err = btrfs_update_inode(trans, root, inode);
7810 d_instantiate(dentry, inode);
7811 btrfs_end_transaction(trans, root);
7813 inode_dec_link_count(inode);
7816 btrfs_btree_balance_dirty(root);
7820 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7821 u64 start, u64 num_bytes, u64 min_size,
7822 loff_t actual_len, u64 *alloc_hint,
7823 struct btrfs_trans_handle *trans)
7825 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7826 struct extent_map *em;
7827 struct btrfs_root *root = BTRFS_I(inode)->root;
7828 struct btrfs_key ins;
7829 u64 cur_offset = start;
7832 bool own_trans = true;
7836 while (num_bytes > 0) {
7838 trans = btrfs_start_transaction(root, 3);
7839 if (IS_ERR(trans)) {
7840 ret = PTR_ERR(trans);
7845 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7846 0, *alloc_hint, &ins, 1);
7849 btrfs_end_transaction(trans, root);
7853 ret = insert_reserved_file_extent(trans, inode,
7854 cur_offset, ins.objectid,
7855 ins.offset, ins.offset,
7856 ins.offset, 0, 0, 0,
7857 BTRFS_FILE_EXTENT_PREALLOC);
7859 btrfs_abort_transaction(trans, root, ret);
7861 btrfs_end_transaction(trans, root);
7864 btrfs_drop_extent_cache(inode, cur_offset,
7865 cur_offset + ins.offset -1, 0);
7867 em = alloc_extent_map();
7869 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7870 &BTRFS_I(inode)->runtime_flags);
7874 em->start = cur_offset;
7875 em->orig_start = cur_offset;
7876 em->len = ins.offset;
7877 em->block_start = ins.objectid;
7878 em->block_len = ins.offset;
7879 em->orig_block_len = ins.offset;
7880 em->bdev = root->fs_info->fs_devices->latest_bdev;
7881 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7882 em->generation = trans->transid;
7885 write_lock(&em_tree->lock);
7886 ret = add_extent_mapping(em_tree, em);
7888 list_move(&em->list,
7889 &em_tree->modified_extents);
7890 write_unlock(&em_tree->lock);
7893 btrfs_drop_extent_cache(inode, cur_offset,
7894 cur_offset + ins.offset - 1,
7897 free_extent_map(em);
7899 num_bytes -= ins.offset;
7900 cur_offset += ins.offset;
7901 *alloc_hint = ins.objectid + ins.offset;
7903 inode_inc_iversion(inode);
7904 inode->i_ctime = CURRENT_TIME;
7905 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7906 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7907 (actual_len > inode->i_size) &&
7908 (cur_offset > inode->i_size)) {
7909 if (cur_offset > actual_len)
7910 i_size = actual_len;
7912 i_size = cur_offset;
7913 i_size_write(inode, i_size);
7914 btrfs_ordered_update_i_size(inode, i_size, NULL);
7917 ret = btrfs_update_inode(trans, root, inode);
7920 btrfs_abort_transaction(trans, root, ret);
7922 btrfs_end_transaction(trans, root);
7927 btrfs_end_transaction(trans, root);
7932 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7933 u64 start, u64 num_bytes, u64 min_size,
7934 loff_t actual_len, u64 *alloc_hint)
7936 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7937 min_size, actual_len, alloc_hint,
7941 int btrfs_prealloc_file_range_trans(struct inode *inode,
7942 struct btrfs_trans_handle *trans, int mode,
7943 u64 start, u64 num_bytes, u64 min_size,
7944 loff_t actual_len, u64 *alloc_hint)
7946 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7947 min_size, actual_len, alloc_hint, trans);
7950 static int btrfs_set_page_dirty(struct page *page)
7952 return __set_page_dirty_nobuffers(page);
7955 static int btrfs_permission(struct inode *inode, int mask)
7957 struct btrfs_root *root = BTRFS_I(inode)->root;
7958 umode_t mode = inode->i_mode;
7960 if (mask & MAY_WRITE &&
7961 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7962 if (btrfs_root_readonly(root))
7964 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7967 return generic_permission(inode, mask);
7970 static const struct inode_operations btrfs_dir_inode_operations = {
7971 .getattr = btrfs_getattr,
7972 .lookup = btrfs_lookup,
7973 .create = btrfs_create,
7974 .unlink = btrfs_unlink,
7976 .mkdir = btrfs_mkdir,
7977 .rmdir = btrfs_rmdir,
7978 .rename = btrfs_rename,
7979 .symlink = btrfs_symlink,
7980 .setattr = btrfs_setattr,
7981 .mknod = btrfs_mknod,
7982 .setxattr = btrfs_setxattr,
7983 .getxattr = btrfs_getxattr,
7984 .listxattr = btrfs_listxattr,
7985 .removexattr = btrfs_removexattr,
7986 .permission = btrfs_permission,
7987 .get_acl = btrfs_get_acl,
7989 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7990 .lookup = btrfs_lookup,
7991 .permission = btrfs_permission,
7992 .get_acl = btrfs_get_acl,
7995 static const struct file_operations btrfs_dir_file_operations = {
7996 .llseek = generic_file_llseek,
7997 .read = generic_read_dir,
7998 .readdir = btrfs_real_readdir,
7999 .unlocked_ioctl = btrfs_ioctl,
8000 #ifdef CONFIG_COMPAT
8001 .compat_ioctl = btrfs_ioctl,
8003 .release = btrfs_release_file,
8004 .fsync = btrfs_sync_file,
8007 static struct extent_io_ops btrfs_extent_io_ops = {
8008 .fill_delalloc = run_delalloc_range,
8009 .submit_bio_hook = btrfs_submit_bio_hook,
8010 .merge_bio_hook = btrfs_merge_bio_hook,
8011 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
8012 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
8013 .writepage_start_hook = btrfs_writepage_start_hook,
8014 .set_bit_hook = btrfs_set_bit_hook,
8015 .clear_bit_hook = btrfs_clear_bit_hook,
8016 .merge_extent_hook = btrfs_merge_extent_hook,
8017 .split_extent_hook = btrfs_split_extent_hook,
8021 * btrfs doesn't support the bmap operation because swapfiles
8022 * use bmap to make a mapping of extents in the file. They assume
8023 * these extents won't change over the life of the file and they
8024 * use the bmap result to do IO directly to the drive.
8026 * the btrfs bmap call would return logical addresses that aren't
8027 * suitable for IO and they also will change frequently as COW
8028 * operations happen. So, swapfile + btrfs == corruption.
8030 * For now we're avoiding this by dropping bmap.
8032 static const struct address_space_operations btrfs_aops = {
8033 .readpage = btrfs_readpage,
8034 .writepage = btrfs_writepage,
8035 .writepages = btrfs_writepages,
8036 .readpages = btrfs_readpages,
8037 .direct_IO = btrfs_direct_IO,
8038 .invalidatepage = btrfs_invalidatepage,
8039 .releasepage = btrfs_releasepage,
8040 .set_page_dirty = btrfs_set_page_dirty,
8041 .error_remove_page = generic_error_remove_page,
8044 static const struct address_space_operations btrfs_symlink_aops = {
8045 .readpage = btrfs_readpage,
8046 .writepage = btrfs_writepage,
8047 .invalidatepage = btrfs_invalidatepage,
8048 .releasepage = btrfs_releasepage,
8051 static const struct inode_operations btrfs_file_inode_operations = {
8052 .getattr = btrfs_getattr,
8053 .setattr = btrfs_setattr,
8054 .setxattr = btrfs_setxattr,
8055 .getxattr = btrfs_getxattr,
8056 .listxattr = btrfs_listxattr,
8057 .removexattr = btrfs_removexattr,
8058 .permission = btrfs_permission,
8059 .fiemap = btrfs_fiemap,
8060 .get_acl = btrfs_get_acl,
8061 .update_time = btrfs_update_time,
8063 static const struct inode_operations btrfs_special_inode_operations = {
8064 .getattr = btrfs_getattr,
8065 .setattr = btrfs_setattr,
8066 .permission = btrfs_permission,
8067 .setxattr = btrfs_setxattr,
8068 .getxattr = btrfs_getxattr,
8069 .listxattr = btrfs_listxattr,
8070 .removexattr = btrfs_removexattr,
8071 .get_acl = btrfs_get_acl,
8072 .update_time = btrfs_update_time,
8074 static const struct inode_operations btrfs_symlink_inode_operations = {
8075 .readlink = generic_readlink,
8076 .follow_link = page_follow_link_light,
8077 .put_link = page_put_link,
8078 .getattr = btrfs_getattr,
8079 .setattr = btrfs_setattr,
8080 .permission = btrfs_permission,
8081 .setxattr = btrfs_setxattr,
8082 .getxattr = btrfs_getxattr,
8083 .listxattr = btrfs_listxattr,
8084 .removexattr = btrfs_removexattr,
8085 .get_acl = btrfs_get_acl,
8086 .update_time = btrfs_update_time,
8089 const struct dentry_operations btrfs_dentry_operations = {
8090 .d_delete = btrfs_dentry_delete,
8091 .d_release = btrfs_dentry_release,