2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
45 #include "transaction.h"
46 #include "btrfs_inode.h"
48 #include "print-tree.h"
49 #include "ordered-data.h"
53 #include "compression.h"
55 #include "free-space-cache.h"
56 #include "inode-map.h"
58 struct btrfs_iget_args {
60 struct btrfs_root *root;
63 static const struct inode_operations btrfs_dir_inode_operations;
64 static const struct inode_operations btrfs_symlink_inode_operations;
65 static const struct inode_operations btrfs_dir_ro_inode_operations;
66 static const struct inode_operations btrfs_special_inode_operations;
67 static const struct inode_operations btrfs_file_inode_operations;
68 static const struct address_space_operations btrfs_aops;
69 static const struct address_space_operations btrfs_symlink_aops;
70 static const struct file_operations btrfs_dir_file_operations;
71 static struct extent_io_ops btrfs_extent_io_ops;
73 static struct kmem_cache *btrfs_inode_cachep;
74 static struct kmem_cache *btrfs_delalloc_work_cachep;
75 struct kmem_cache *btrfs_trans_handle_cachep;
76 struct kmem_cache *btrfs_transaction_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
81 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
82 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
83 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
84 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
85 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
86 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
87 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
88 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92 static int btrfs_truncate(struct inode *inode);
93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 static noinline int cow_file_range(struct inode *inode,
95 struct page *locked_page,
96 u64 start, u64 end, int *page_started,
97 unsigned long *nr_written, int unlock);
98 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
99 u64 len, u64 orig_start,
100 u64 block_start, u64 block_len,
101 u64 orig_block_len, int type);
103 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
104 struct inode *inode, struct inode *dir,
105 const struct qstr *qstr)
109 err = btrfs_init_acl(trans, inode, dir);
111 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
116 * this does all the hard work for inserting an inline extent into
117 * the btree. The caller should have done a btrfs_drop_extents so that
118 * no overlapping inline items exist in the btree
120 static noinline int insert_inline_extent(struct btrfs_trans_handle *trans,
121 struct btrfs_root *root, struct inode *inode,
122 u64 start, size_t size, size_t compressed_size,
124 struct page **compressed_pages)
126 struct btrfs_key key;
127 struct btrfs_path *path;
128 struct extent_buffer *leaf;
129 struct page *page = NULL;
132 struct btrfs_file_extent_item *ei;
135 size_t cur_size = size;
137 unsigned long offset;
139 if (compressed_size && compressed_pages)
140 cur_size = compressed_size;
142 path = btrfs_alloc_path();
146 path->leave_spinning = 1;
148 key.objectid = btrfs_ino(inode);
150 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
151 datasize = btrfs_file_extent_calc_inline_size(cur_size);
153 inode_add_bytes(inode, size);
154 ret = btrfs_insert_empty_item(trans, root, path, &key,
160 leaf = path->nodes[0];
161 ei = btrfs_item_ptr(leaf, path->slots[0],
162 struct btrfs_file_extent_item);
163 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
164 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
165 btrfs_set_file_extent_encryption(leaf, ei, 0);
166 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
167 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
168 ptr = btrfs_file_extent_inline_start(ei);
170 if (compress_type != BTRFS_COMPRESS_NONE) {
173 while (compressed_size > 0) {
174 cpage = compressed_pages[i];
175 cur_size = min_t(unsigned long, compressed_size,
178 kaddr = kmap_atomic(cpage);
179 write_extent_buffer(leaf, kaddr, ptr, cur_size);
180 kunmap_atomic(kaddr);
184 compressed_size -= cur_size;
186 btrfs_set_file_extent_compression(leaf, ei,
189 page = find_get_page(inode->i_mapping,
190 start >> PAGE_CACHE_SHIFT);
191 btrfs_set_file_extent_compression(leaf, ei, 0);
192 kaddr = kmap_atomic(page);
193 offset = start & (PAGE_CACHE_SIZE - 1);
194 write_extent_buffer(leaf, kaddr + offset, ptr, size);
195 kunmap_atomic(kaddr);
196 page_cache_release(page);
198 btrfs_mark_buffer_dirty(leaf);
199 btrfs_free_path(path);
202 * we're an inline extent, so nobody can
203 * extend the file past i_size without locking
204 * a page we already have locked.
206 * We must do any isize and inode updates
207 * before we unlock the pages. Otherwise we
208 * could end up racing with unlink.
210 BTRFS_I(inode)->disk_i_size = inode->i_size;
211 ret = btrfs_update_inode(trans, root, inode);
215 btrfs_free_path(path);
221 * conditionally insert an inline extent into the file. This
222 * does the checks required to make sure the data is small enough
223 * to fit as an inline extent.
225 static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans,
226 struct btrfs_root *root,
227 struct inode *inode, u64 start, u64 end,
228 size_t compressed_size, int compress_type,
229 struct page **compressed_pages)
231 u64 isize = i_size_read(inode);
232 u64 actual_end = min(end + 1, isize);
233 u64 inline_len = actual_end - start;
234 u64 aligned_end = (end + root->sectorsize - 1) &
235 ~((u64)root->sectorsize - 1);
236 u64 data_len = inline_len;
240 data_len = compressed_size;
243 actual_end >= PAGE_CACHE_SIZE ||
244 data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
246 (actual_end & (root->sectorsize - 1)) == 0) ||
248 data_len > root->fs_info->max_inline) {
252 ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1);
256 if (isize > actual_end)
257 inline_len = min_t(u64, isize, actual_end);
258 ret = insert_inline_extent(trans, root, inode, start,
259 inline_len, compressed_size,
260 compress_type, compressed_pages);
261 if (ret && ret != -ENOSPC) {
262 btrfs_abort_transaction(trans, root, ret);
264 } else if (ret == -ENOSPC) {
268 btrfs_delalloc_release_metadata(inode, end + 1 - start);
269 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
273 struct async_extent {
278 unsigned long nr_pages;
280 struct list_head list;
285 struct btrfs_root *root;
286 struct page *locked_page;
289 struct list_head extents;
290 struct btrfs_work work;
293 static noinline int add_async_extent(struct async_cow *cow,
294 u64 start, u64 ram_size,
297 unsigned long nr_pages,
300 struct async_extent *async_extent;
302 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
303 BUG_ON(!async_extent); /* -ENOMEM */
304 async_extent->start = start;
305 async_extent->ram_size = ram_size;
306 async_extent->compressed_size = compressed_size;
307 async_extent->pages = pages;
308 async_extent->nr_pages = nr_pages;
309 async_extent->compress_type = compress_type;
310 list_add_tail(&async_extent->list, &cow->extents);
315 * we create compressed extents in two phases. The first
316 * phase compresses a range of pages that have already been
317 * locked (both pages and state bits are locked).
319 * This is done inside an ordered work queue, and the compression
320 * is spread across many cpus. The actual IO submission is step
321 * two, and the ordered work queue takes care of making sure that
322 * happens in the same order things were put onto the queue by
323 * writepages and friends.
325 * If this code finds it can't get good compression, it puts an
326 * entry onto the work queue to write the uncompressed bytes. This
327 * makes sure that both compressed inodes and uncompressed inodes
328 * are written in the same order that the flusher thread sent them
331 static noinline int compress_file_range(struct inode *inode,
332 struct page *locked_page,
334 struct async_cow *async_cow,
337 struct btrfs_root *root = BTRFS_I(inode)->root;
338 struct btrfs_trans_handle *trans;
340 u64 blocksize = root->sectorsize;
342 u64 isize = i_size_read(inode);
344 struct page **pages = NULL;
345 unsigned long nr_pages;
346 unsigned long nr_pages_ret = 0;
347 unsigned long total_compressed = 0;
348 unsigned long total_in = 0;
349 unsigned long max_compressed = 128 * 1024;
350 unsigned long max_uncompressed = 128 * 1024;
353 int compress_type = root->fs_info->compress_type;
355 /* if this is a small write inside eof, kick off a defrag */
356 if ((end - start + 1) < 16 * 1024 &&
357 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
358 btrfs_add_inode_defrag(NULL, inode);
360 actual_end = min_t(u64, isize, end + 1);
363 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
364 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
367 * we don't want to send crud past the end of i_size through
368 * compression, that's just a waste of CPU time. So, if the
369 * end of the file is before the start of our current
370 * requested range of bytes, we bail out to the uncompressed
371 * cleanup code that can deal with all of this.
373 * It isn't really the fastest way to fix things, but this is a
374 * very uncommon corner.
376 if (actual_end <= start)
377 goto cleanup_and_bail_uncompressed;
379 total_compressed = actual_end - start;
381 /* we want to make sure that amount of ram required to uncompress
382 * an extent is reasonable, so we limit the total size in ram
383 * of a compressed extent to 128k. This is a crucial number
384 * because it also controls how easily we can spread reads across
385 * cpus for decompression.
387 * We also want to make sure the amount of IO required to do
388 * a random read is reasonably small, so we limit the size of
389 * a compressed extent to 128k.
391 total_compressed = min(total_compressed, max_uncompressed);
392 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
393 num_bytes = max(blocksize, num_bytes);
398 * we do compression for mount -o compress and when the
399 * inode has not been flagged as nocompress. This flag can
400 * change at any time if we discover bad compression ratios.
402 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) &&
403 (btrfs_test_opt(root, COMPRESS) ||
404 (BTRFS_I(inode)->force_compress) ||
405 (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) {
407 pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS);
409 /* just bail out to the uncompressed code */
413 if (BTRFS_I(inode)->force_compress)
414 compress_type = BTRFS_I(inode)->force_compress;
416 ret = btrfs_compress_pages(compress_type,
417 inode->i_mapping, start,
418 total_compressed, pages,
419 nr_pages, &nr_pages_ret,
425 unsigned long offset = total_compressed &
426 (PAGE_CACHE_SIZE - 1);
427 struct page *page = pages[nr_pages_ret - 1];
430 /* zero the tail end of the last page, we might be
431 * sending it down to disk
434 kaddr = kmap_atomic(page);
435 memset(kaddr + offset, 0,
436 PAGE_CACHE_SIZE - offset);
437 kunmap_atomic(kaddr);
444 trans = btrfs_join_transaction(root);
446 ret = PTR_ERR(trans);
448 goto cleanup_and_out;
450 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
452 /* lets try to make an inline extent */
453 if (ret || total_in < (actual_end - start)) {
454 /* we didn't compress the entire range, try
455 * to make an uncompressed inline extent.
457 ret = cow_file_range_inline(trans, root, inode,
458 start, end, 0, 0, NULL);
460 /* try making a compressed inline extent */
461 ret = cow_file_range_inline(trans, root, inode,
464 compress_type, pages);
468 * inline extent creation worked or returned error,
469 * we don't need to create any more async work items.
470 * Unlock and free up our temp pages.
472 extent_clear_unlock_delalloc(inode,
473 &BTRFS_I(inode)->io_tree,
475 EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY |
476 EXTENT_CLEAR_DELALLOC |
477 EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK);
479 btrfs_end_transaction(trans, root);
482 btrfs_end_transaction(trans, root);
487 * we aren't doing an inline extent round the compressed size
488 * up to a block size boundary so the allocator does sane
491 total_compressed = (total_compressed + blocksize - 1) &
495 * one last check to make sure the compression is really a
496 * win, compare the page count read with the blocks on disk
498 total_in = (total_in + PAGE_CACHE_SIZE - 1) &
499 ~(PAGE_CACHE_SIZE - 1);
500 if (total_compressed >= total_in) {
503 num_bytes = total_in;
506 if (!will_compress && pages) {
508 * the compression code ran but failed to make things smaller,
509 * free any pages it allocated and our page pointer array
511 for (i = 0; i < nr_pages_ret; i++) {
512 WARN_ON(pages[i]->mapping);
513 page_cache_release(pages[i]);
517 total_compressed = 0;
520 /* flag the file so we don't compress in the future */
521 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
522 !(BTRFS_I(inode)->force_compress)) {
523 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
529 /* the async work queues will take care of doing actual
530 * allocation on disk for these compressed pages,
531 * and will submit them to the elevator.
533 add_async_extent(async_cow, start, num_bytes,
534 total_compressed, pages, nr_pages_ret,
537 if (start + num_bytes < end) {
544 cleanup_and_bail_uncompressed:
546 * No compression, but we still need to write the pages in
547 * the file we've been given so far. redirty the locked
548 * page if it corresponds to our extent and set things up
549 * for the async work queue to run cow_file_range to do
550 * the normal delalloc dance
552 if (page_offset(locked_page) >= start &&
553 page_offset(locked_page) <= end) {
554 __set_page_dirty_nobuffers(locked_page);
555 /* unlocked later on in the async handlers */
557 add_async_extent(async_cow, start, end - start + 1,
558 0, NULL, 0, BTRFS_COMPRESS_NONE);
566 for (i = 0; i < nr_pages_ret; i++) {
567 WARN_ON(pages[i]->mapping);
568 page_cache_release(pages[i]);
575 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
577 EXTENT_CLEAR_UNLOCK_PAGE |
579 EXTENT_CLEAR_DELALLOC |
580 EXTENT_SET_WRITEBACK |
581 EXTENT_END_WRITEBACK);
582 if (!trans || IS_ERR(trans))
583 btrfs_error(root->fs_info, ret, "Failed to join transaction");
585 btrfs_abort_transaction(trans, root, ret);
590 * phase two of compressed writeback. This is the ordered portion
591 * of the code, which only gets called in the order the work was
592 * queued. We walk all the async extents created by compress_file_range
593 * and send them down to the disk.
595 static noinline int submit_compressed_extents(struct inode *inode,
596 struct async_cow *async_cow)
598 struct async_extent *async_extent;
600 struct btrfs_trans_handle *trans;
601 struct btrfs_key ins;
602 struct extent_map *em;
603 struct btrfs_root *root = BTRFS_I(inode)->root;
604 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
605 struct extent_io_tree *io_tree;
608 if (list_empty(&async_cow->extents))
612 while (!list_empty(&async_cow->extents)) {
613 async_extent = list_entry(async_cow->extents.next,
614 struct async_extent, list);
615 list_del(&async_extent->list);
617 io_tree = &BTRFS_I(inode)->io_tree;
620 /* did the compression code fall back to uncompressed IO? */
621 if (!async_extent->pages) {
622 int page_started = 0;
623 unsigned long nr_written = 0;
625 lock_extent(io_tree, async_extent->start,
626 async_extent->start +
627 async_extent->ram_size - 1);
629 /* allocate blocks */
630 ret = cow_file_range(inode, async_cow->locked_page,
632 async_extent->start +
633 async_extent->ram_size - 1,
634 &page_started, &nr_written, 0);
639 * if page_started, cow_file_range inserted an
640 * inline extent and took care of all the unlocking
641 * and IO for us. Otherwise, we need to submit
642 * all those pages down to the drive.
644 if (!page_started && !ret)
645 extent_write_locked_range(io_tree,
646 inode, async_extent->start,
647 async_extent->start +
648 async_extent->ram_size - 1,
656 lock_extent(io_tree, async_extent->start,
657 async_extent->start + async_extent->ram_size - 1);
659 trans = btrfs_join_transaction(root);
661 ret = PTR_ERR(trans);
663 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
664 ret = btrfs_reserve_extent(trans, root,
665 async_extent->compressed_size,
666 async_extent->compressed_size,
667 0, alloc_hint, &ins, 1);
668 if (ret && ret != -ENOSPC)
669 btrfs_abort_transaction(trans, root, ret);
670 btrfs_end_transaction(trans, root);
675 for (i = 0; i < async_extent->nr_pages; i++) {
676 WARN_ON(async_extent->pages[i]->mapping);
677 page_cache_release(async_extent->pages[i]);
679 kfree(async_extent->pages);
680 async_extent->nr_pages = 0;
681 async_extent->pages = NULL;
682 unlock_extent(io_tree, async_extent->start,
683 async_extent->start +
684 async_extent->ram_size - 1);
687 goto out_free; /* JDM: Requeue? */
691 * here we're doing allocation and writeback of the
694 btrfs_drop_extent_cache(inode, async_extent->start,
695 async_extent->start +
696 async_extent->ram_size - 1, 0);
698 em = alloc_extent_map();
699 BUG_ON(!em); /* -ENOMEM */
700 em->start = async_extent->start;
701 em->len = async_extent->ram_size;
702 em->orig_start = em->start;
703 em->mod_start = em->start;
704 em->mod_len = em->len;
706 em->block_start = ins.objectid;
707 em->block_len = ins.offset;
708 em->orig_block_len = ins.offset;
709 em->bdev = root->fs_info->fs_devices->latest_bdev;
710 em->compress_type = async_extent->compress_type;
711 set_bit(EXTENT_FLAG_PINNED, &em->flags);
712 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
716 write_lock(&em_tree->lock);
717 ret = add_extent_mapping(em_tree, em);
720 &em_tree->modified_extents);
721 write_unlock(&em_tree->lock);
722 if (ret != -EEXIST) {
726 btrfs_drop_extent_cache(inode, async_extent->start,
727 async_extent->start +
728 async_extent->ram_size - 1, 0);
731 ret = btrfs_add_ordered_extent_compress(inode,
734 async_extent->ram_size,
736 BTRFS_ORDERED_COMPRESSED,
737 async_extent->compress_type);
738 BUG_ON(ret); /* -ENOMEM */
741 * clear dirty, set writeback and unlock the pages.
743 extent_clear_unlock_delalloc(inode,
744 &BTRFS_I(inode)->io_tree,
746 async_extent->start +
747 async_extent->ram_size - 1,
748 NULL, EXTENT_CLEAR_UNLOCK_PAGE |
749 EXTENT_CLEAR_UNLOCK |
750 EXTENT_CLEAR_DELALLOC |
751 EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK);
753 ret = btrfs_submit_compressed_write(inode,
755 async_extent->ram_size,
757 ins.offset, async_extent->pages,
758 async_extent->nr_pages);
760 BUG_ON(ret); /* -ENOMEM */
761 alloc_hint = ins.objectid + ins.offset;
773 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
776 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
777 struct extent_map *em;
780 read_lock(&em_tree->lock);
781 em = search_extent_mapping(em_tree, start, num_bytes);
784 * if block start isn't an actual block number then find the
785 * first block in this inode and use that as a hint. If that
786 * block is also bogus then just don't worry about it.
788 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
790 em = search_extent_mapping(em_tree, 0, 0);
791 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
792 alloc_hint = em->block_start;
796 alloc_hint = em->block_start;
800 read_unlock(&em_tree->lock);
806 * when extent_io.c finds a delayed allocation range in the file,
807 * the call backs end up in this code. The basic idea is to
808 * allocate extents on disk for the range, and create ordered data structs
809 * in ram to track those extents.
811 * locked_page is the page that writepage had locked already. We use
812 * it to make sure we don't do extra locks or unlocks.
814 * *page_started is set to one if we unlock locked_page and do everything
815 * required to start IO on it. It may be clean and already done with
818 static noinline int __cow_file_range(struct btrfs_trans_handle *trans,
820 struct btrfs_root *root,
821 struct page *locked_page,
822 u64 start, u64 end, int *page_started,
823 unsigned long *nr_written,
828 unsigned long ram_size;
831 u64 blocksize = root->sectorsize;
832 struct btrfs_key ins;
833 struct extent_map *em;
834 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
837 BUG_ON(btrfs_is_free_space_inode(inode));
839 num_bytes = (end - start + blocksize) & ~(blocksize - 1);
840 num_bytes = max(blocksize, num_bytes);
841 disk_num_bytes = num_bytes;
843 /* if this is a small write inside eof, kick off defrag */
844 if (num_bytes < 64 * 1024 &&
845 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
846 btrfs_add_inode_defrag(trans, inode);
849 /* lets try to make an inline extent */
850 ret = cow_file_range_inline(trans, root, inode,
851 start, end, 0, 0, NULL);
853 extent_clear_unlock_delalloc(inode,
854 &BTRFS_I(inode)->io_tree,
856 EXTENT_CLEAR_UNLOCK_PAGE |
857 EXTENT_CLEAR_UNLOCK |
858 EXTENT_CLEAR_DELALLOC |
860 EXTENT_SET_WRITEBACK |
861 EXTENT_END_WRITEBACK);
863 *nr_written = *nr_written +
864 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
867 } else if (ret < 0) {
868 btrfs_abort_transaction(trans, root, ret);
873 BUG_ON(disk_num_bytes >
874 btrfs_super_total_bytes(root->fs_info->super_copy));
876 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
877 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
879 while (disk_num_bytes > 0) {
882 cur_alloc_size = disk_num_bytes;
883 ret = btrfs_reserve_extent(trans, root, cur_alloc_size,
884 root->sectorsize, 0, alloc_hint,
887 btrfs_abort_transaction(trans, root, ret);
891 em = alloc_extent_map();
892 BUG_ON(!em); /* -ENOMEM */
894 em->orig_start = em->start;
895 ram_size = ins.offset;
896 em->len = ins.offset;
897 em->mod_start = em->start;
898 em->mod_len = em->len;
900 em->block_start = ins.objectid;
901 em->block_len = ins.offset;
902 em->orig_block_len = ins.offset;
903 em->bdev = root->fs_info->fs_devices->latest_bdev;
904 set_bit(EXTENT_FLAG_PINNED, &em->flags);
908 write_lock(&em_tree->lock);
909 ret = add_extent_mapping(em_tree, em);
912 &em_tree->modified_extents);
913 write_unlock(&em_tree->lock);
914 if (ret != -EEXIST) {
918 btrfs_drop_extent_cache(inode, start,
919 start + ram_size - 1, 0);
922 cur_alloc_size = ins.offset;
923 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
924 ram_size, cur_alloc_size, 0);
925 BUG_ON(ret); /* -ENOMEM */
927 if (root->root_key.objectid ==
928 BTRFS_DATA_RELOC_TREE_OBJECTID) {
929 ret = btrfs_reloc_clone_csums(inode, start,
932 btrfs_abort_transaction(trans, root, ret);
937 if (disk_num_bytes < cur_alloc_size)
940 /* we're not doing compressed IO, don't unlock the first
941 * page (which the caller expects to stay locked), don't
942 * clear any dirty bits and don't set any writeback bits
944 * Do set the Private2 bit so we know this page was properly
945 * setup for writepage
947 op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0;
948 op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
951 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
952 start, start + ram_size - 1,
954 disk_num_bytes -= cur_alloc_size;
955 num_bytes -= cur_alloc_size;
956 alloc_hint = ins.objectid + ins.offset;
957 start += cur_alloc_size;
963 extent_clear_unlock_delalloc(inode,
964 &BTRFS_I(inode)->io_tree,
965 start, end, locked_page,
966 EXTENT_CLEAR_UNLOCK_PAGE |
967 EXTENT_CLEAR_UNLOCK |
968 EXTENT_CLEAR_DELALLOC |
970 EXTENT_SET_WRITEBACK |
971 EXTENT_END_WRITEBACK);
976 static noinline int cow_file_range(struct inode *inode,
977 struct page *locked_page,
978 u64 start, u64 end, int *page_started,
979 unsigned long *nr_written,
982 struct btrfs_trans_handle *trans;
983 struct btrfs_root *root = BTRFS_I(inode)->root;
986 trans = btrfs_join_transaction(root);
988 extent_clear_unlock_delalloc(inode,
989 &BTRFS_I(inode)->io_tree,
990 start, end, locked_page,
991 EXTENT_CLEAR_UNLOCK_PAGE |
992 EXTENT_CLEAR_UNLOCK |
993 EXTENT_CLEAR_DELALLOC |
995 EXTENT_SET_WRITEBACK |
996 EXTENT_END_WRITEBACK);
997 return PTR_ERR(trans);
999 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1001 ret = __cow_file_range(trans, inode, root, locked_page, start, end,
1002 page_started, nr_written, unlock);
1004 btrfs_end_transaction(trans, root);
1010 * work queue call back to started compression on a file and pages
1012 static noinline void async_cow_start(struct btrfs_work *work)
1014 struct async_cow *async_cow;
1016 async_cow = container_of(work, struct async_cow, work);
1018 compress_file_range(async_cow->inode, async_cow->locked_page,
1019 async_cow->start, async_cow->end, async_cow,
1021 if (num_added == 0) {
1022 btrfs_add_delayed_iput(async_cow->inode);
1023 async_cow->inode = NULL;
1028 * work queue call back to submit previously compressed pages
1030 static noinline void async_cow_submit(struct btrfs_work *work)
1032 struct async_cow *async_cow;
1033 struct btrfs_root *root;
1034 unsigned long nr_pages;
1036 async_cow = container_of(work, struct async_cow, work);
1038 root = async_cow->root;
1039 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1042 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1044 waitqueue_active(&root->fs_info->async_submit_wait))
1045 wake_up(&root->fs_info->async_submit_wait);
1047 if (async_cow->inode)
1048 submit_compressed_extents(async_cow->inode, async_cow);
1051 static noinline void async_cow_free(struct btrfs_work *work)
1053 struct async_cow *async_cow;
1054 async_cow = container_of(work, struct async_cow, work);
1055 if (async_cow->inode)
1056 btrfs_add_delayed_iput(async_cow->inode);
1060 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1061 u64 start, u64 end, int *page_started,
1062 unsigned long *nr_written)
1064 struct async_cow *async_cow;
1065 struct btrfs_root *root = BTRFS_I(inode)->root;
1066 unsigned long nr_pages;
1068 int limit = 10 * 1024 * 1024;
1070 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1071 1, 0, NULL, GFP_NOFS);
1072 while (start < end) {
1073 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1074 BUG_ON(!async_cow); /* -ENOMEM */
1075 async_cow->inode = igrab(inode);
1076 async_cow->root = root;
1077 async_cow->locked_page = locked_page;
1078 async_cow->start = start;
1080 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
1083 cur_end = min(end, start + 512 * 1024 - 1);
1085 async_cow->end = cur_end;
1086 INIT_LIST_HEAD(&async_cow->extents);
1088 async_cow->work.func = async_cow_start;
1089 async_cow->work.ordered_func = async_cow_submit;
1090 async_cow->work.ordered_free = async_cow_free;
1091 async_cow->work.flags = 0;
1093 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1095 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1097 btrfs_queue_worker(&root->fs_info->delalloc_workers,
1100 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1101 wait_event(root->fs_info->async_submit_wait,
1102 (atomic_read(&root->fs_info->async_delalloc_pages) <
1106 while (atomic_read(&root->fs_info->async_submit_draining) &&
1107 atomic_read(&root->fs_info->async_delalloc_pages)) {
1108 wait_event(root->fs_info->async_submit_wait,
1109 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1113 *nr_written += nr_pages;
1114 start = cur_end + 1;
1120 static noinline int csum_exist_in_range(struct btrfs_root *root,
1121 u64 bytenr, u64 num_bytes)
1124 struct btrfs_ordered_sum *sums;
1127 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1128 bytenr + num_bytes - 1, &list, 0);
1129 if (ret == 0 && list_empty(&list))
1132 while (!list_empty(&list)) {
1133 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1134 list_del(&sums->list);
1141 * when nowcow writeback call back. This checks for snapshots or COW copies
1142 * of the extents that exist in the file, and COWs the file as required.
1144 * If no cow copies or snapshots exist, we write directly to the existing
1147 static noinline int run_delalloc_nocow(struct inode *inode,
1148 struct page *locked_page,
1149 u64 start, u64 end, int *page_started, int force,
1150 unsigned long *nr_written)
1152 struct btrfs_root *root = BTRFS_I(inode)->root;
1153 struct btrfs_trans_handle *trans;
1154 struct extent_buffer *leaf;
1155 struct btrfs_path *path;
1156 struct btrfs_file_extent_item *fi;
1157 struct btrfs_key found_key;
1171 u64 ino = btrfs_ino(inode);
1173 path = btrfs_alloc_path();
1175 extent_clear_unlock_delalloc(inode,
1176 &BTRFS_I(inode)->io_tree,
1177 start, end, locked_page,
1178 EXTENT_CLEAR_UNLOCK_PAGE |
1179 EXTENT_CLEAR_UNLOCK |
1180 EXTENT_CLEAR_DELALLOC |
1181 EXTENT_CLEAR_DIRTY |
1182 EXTENT_SET_WRITEBACK |
1183 EXTENT_END_WRITEBACK);
1187 nolock = btrfs_is_free_space_inode(inode);
1190 trans = btrfs_join_transaction_nolock(root);
1192 trans = btrfs_join_transaction(root);
1194 if (IS_ERR(trans)) {
1195 extent_clear_unlock_delalloc(inode,
1196 &BTRFS_I(inode)->io_tree,
1197 start, end, locked_page,
1198 EXTENT_CLEAR_UNLOCK_PAGE |
1199 EXTENT_CLEAR_UNLOCK |
1200 EXTENT_CLEAR_DELALLOC |
1201 EXTENT_CLEAR_DIRTY |
1202 EXTENT_SET_WRITEBACK |
1203 EXTENT_END_WRITEBACK);
1204 btrfs_free_path(path);
1205 return PTR_ERR(trans);
1208 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1210 cow_start = (u64)-1;
1213 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1216 btrfs_abort_transaction(trans, root, ret);
1219 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1220 leaf = path->nodes[0];
1221 btrfs_item_key_to_cpu(leaf, &found_key,
1222 path->slots[0] - 1);
1223 if (found_key.objectid == ino &&
1224 found_key.type == BTRFS_EXTENT_DATA_KEY)
1229 leaf = path->nodes[0];
1230 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1231 ret = btrfs_next_leaf(root, path);
1233 btrfs_abort_transaction(trans, root, ret);
1238 leaf = path->nodes[0];
1244 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1246 if (found_key.objectid > ino ||
1247 found_key.type > BTRFS_EXTENT_DATA_KEY ||
1248 found_key.offset > end)
1251 if (found_key.offset > cur_offset) {
1252 extent_end = found_key.offset;
1257 fi = btrfs_item_ptr(leaf, path->slots[0],
1258 struct btrfs_file_extent_item);
1259 extent_type = btrfs_file_extent_type(leaf, fi);
1261 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1262 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1263 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1264 extent_offset = btrfs_file_extent_offset(leaf, fi);
1265 extent_end = found_key.offset +
1266 btrfs_file_extent_num_bytes(leaf, fi);
1268 btrfs_file_extent_disk_num_bytes(leaf, fi);
1269 if (extent_end <= start) {
1273 if (disk_bytenr == 0)
1275 if (btrfs_file_extent_compression(leaf, fi) ||
1276 btrfs_file_extent_encryption(leaf, fi) ||
1277 btrfs_file_extent_other_encoding(leaf, fi))
1279 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1281 if (btrfs_extent_readonly(root, disk_bytenr))
1283 if (btrfs_cross_ref_exist(trans, root, ino,
1285 extent_offset, disk_bytenr))
1287 disk_bytenr += extent_offset;
1288 disk_bytenr += cur_offset - found_key.offset;
1289 num_bytes = min(end + 1, extent_end) - cur_offset;
1291 * force cow if csum exists in the range.
1292 * this ensure that csum for a given extent are
1293 * either valid or do not exist.
1295 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
1298 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1299 extent_end = found_key.offset +
1300 btrfs_file_extent_inline_len(leaf, fi);
1301 extent_end = ALIGN(extent_end, root->sectorsize);
1306 if (extent_end <= start) {
1311 if (cow_start == (u64)-1)
1312 cow_start = cur_offset;
1313 cur_offset = extent_end;
1314 if (cur_offset > end)
1320 btrfs_release_path(path);
1321 if (cow_start != (u64)-1) {
1322 ret = __cow_file_range(trans, inode, root, locked_page,
1323 cow_start, found_key.offset - 1,
1324 page_started, nr_written, 1);
1326 btrfs_abort_transaction(trans, root, ret);
1329 cow_start = (u64)-1;
1332 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1333 struct extent_map *em;
1334 struct extent_map_tree *em_tree;
1335 em_tree = &BTRFS_I(inode)->extent_tree;
1336 em = alloc_extent_map();
1337 BUG_ON(!em); /* -ENOMEM */
1338 em->start = cur_offset;
1339 em->orig_start = found_key.offset - extent_offset;
1340 em->len = num_bytes;
1341 em->block_len = num_bytes;
1342 em->block_start = disk_bytenr;
1343 em->orig_block_len = disk_num_bytes;
1344 em->bdev = root->fs_info->fs_devices->latest_bdev;
1345 em->mod_start = em->start;
1346 em->mod_len = em->len;
1347 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1348 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1349 em->generation = -1;
1351 write_lock(&em_tree->lock);
1352 ret = add_extent_mapping(em_tree, em);
1354 list_move(&em->list,
1355 &em_tree->modified_extents);
1356 write_unlock(&em_tree->lock);
1357 if (ret != -EEXIST) {
1358 free_extent_map(em);
1361 btrfs_drop_extent_cache(inode, em->start,
1362 em->start + em->len - 1, 0);
1364 type = BTRFS_ORDERED_PREALLOC;
1366 type = BTRFS_ORDERED_NOCOW;
1369 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1370 num_bytes, num_bytes, type);
1371 BUG_ON(ret); /* -ENOMEM */
1373 if (root->root_key.objectid ==
1374 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1375 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1378 btrfs_abort_transaction(trans, root, ret);
1383 extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree,
1384 cur_offset, cur_offset + num_bytes - 1,
1385 locked_page, EXTENT_CLEAR_UNLOCK_PAGE |
1386 EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC |
1387 EXTENT_SET_PRIVATE2);
1388 cur_offset = extent_end;
1389 if (cur_offset > end)
1392 btrfs_release_path(path);
1394 if (cur_offset <= end && cow_start == (u64)-1) {
1395 cow_start = cur_offset;
1399 if (cow_start != (u64)-1) {
1400 ret = __cow_file_range(trans, inode, root, locked_page,
1402 page_started, nr_written, 1);
1404 btrfs_abort_transaction(trans, root, ret);
1410 err = btrfs_end_transaction(trans, root);
1414 if (ret && cur_offset < end)
1415 extent_clear_unlock_delalloc(inode,
1416 &BTRFS_I(inode)->io_tree,
1417 cur_offset, end, locked_page,
1418 EXTENT_CLEAR_UNLOCK_PAGE |
1419 EXTENT_CLEAR_UNLOCK |
1420 EXTENT_CLEAR_DELALLOC |
1421 EXTENT_CLEAR_DIRTY |
1422 EXTENT_SET_WRITEBACK |
1423 EXTENT_END_WRITEBACK);
1425 btrfs_free_path(path);
1430 * extent_io.c call back to do delayed allocation processing
1432 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1433 u64 start, u64 end, int *page_started,
1434 unsigned long *nr_written)
1437 struct btrfs_root *root = BTRFS_I(inode)->root;
1439 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) {
1440 ret = run_delalloc_nocow(inode, locked_page, start, end,
1441 page_started, 1, nr_written);
1442 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) {
1443 ret = run_delalloc_nocow(inode, locked_page, start, end,
1444 page_started, 0, nr_written);
1445 } else if (!btrfs_test_opt(root, COMPRESS) &&
1446 !(BTRFS_I(inode)->force_compress) &&
1447 !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) {
1448 ret = cow_file_range(inode, locked_page, start, end,
1449 page_started, nr_written, 1);
1451 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1452 &BTRFS_I(inode)->runtime_flags);
1453 ret = cow_file_range_async(inode, locked_page, start, end,
1454 page_started, nr_written);
1459 static void btrfs_split_extent_hook(struct inode *inode,
1460 struct extent_state *orig, u64 split)
1462 /* not delalloc, ignore it */
1463 if (!(orig->state & EXTENT_DELALLOC))
1466 spin_lock(&BTRFS_I(inode)->lock);
1467 BTRFS_I(inode)->outstanding_extents++;
1468 spin_unlock(&BTRFS_I(inode)->lock);
1472 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1473 * extents so we can keep track of new extents that are just merged onto old
1474 * extents, such as when we are doing sequential writes, so we can properly
1475 * account for the metadata space we'll need.
1477 static void btrfs_merge_extent_hook(struct inode *inode,
1478 struct extent_state *new,
1479 struct extent_state *other)
1481 /* not delalloc, ignore it */
1482 if (!(other->state & EXTENT_DELALLOC))
1485 spin_lock(&BTRFS_I(inode)->lock);
1486 BTRFS_I(inode)->outstanding_extents--;
1487 spin_unlock(&BTRFS_I(inode)->lock);
1491 * extent_io.c set_bit_hook, used to track delayed allocation
1492 * bytes in this file, and to maintain the list of inodes that
1493 * have pending delalloc work to be done.
1495 static void btrfs_set_bit_hook(struct inode *inode,
1496 struct extent_state *state, int *bits)
1500 * set_bit and clear bit hooks normally require _irqsave/restore
1501 * but in this case, we are only testing for the DELALLOC
1502 * bit, which is only set or cleared with irqs on
1504 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1505 struct btrfs_root *root = BTRFS_I(inode)->root;
1506 u64 len = state->end + 1 - state->start;
1507 bool do_list = !btrfs_is_free_space_inode(inode);
1509 if (*bits & EXTENT_FIRST_DELALLOC) {
1510 *bits &= ~EXTENT_FIRST_DELALLOC;
1512 spin_lock(&BTRFS_I(inode)->lock);
1513 BTRFS_I(inode)->outstanding_extents++;
1514 spin_unlock(&BTRFS_I(inode)->lock);
1517 spin_lock(&root->fs_info->delalloc_lock);
1518 BTRFS_I(inode)->delalloc_bytes += len;
1519 root->fs_info->delalloc_bytes += len;
1520 if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1521 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1522 &root->fs_info->delalloc_inodes);
1524 spin_unlock(&root->fs_info->delalloc_lock);
1529 * extent_io.c clear_bit_hook, see set_bit_hook for why
1531 static void btrfs_clear_bit_hook(struct inode *inode,
1532 struct extent_state *state, int *bits)
1535 * set_bit and clear bit hooks normally require _irqsave/restore
1536 * but in this case, we are only testing for the DELALLOC
1537 * bit, which is only set or cleared with irqs on
1539 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1540 struct btrfs_root *root = BTRFS_I(inode)->root;
1541 u64 len = state->end + 1 - state->start;
1542 bool do_list = !btrfs_is_free_space_inode(inode);
1544 if (*bits & EXTENT_FIRST_DELALLOC) {
1545 *bits &= ~EXTENT_FIRST_DELALLOC;
1546 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1547 spin_lock(&BTRFS_I(inode)->lock);
1548 BTRFS_I(inode)->outstanding_extents--;
1549 spin_unlock(&BTRFS_I(inode)->lock);
1552 if (*bits & EXTENT_DO_ACCOUNTING)
1553 btrfs_delalloc_release_metadata(inode, len);
1555 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1557 btrfs_free_reserved_data_space(inode, len);
1559 spin_lock(&root->fs_info->delalloc_lock);
1560 root->fs_info->delalloc_bytes -= len;
1561 BTRFS_I(inode)->delalloc_bytes -= len;
1563 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1564 !list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1565 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1567 spin_unlock(&root->fs_info->delalloc_lock);
1572 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1573 * we don't create bios that span stripes or chunks
1575 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1576 size_t size, struct bio *bio,
1577 unsigned long bio_flags)
1579 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1580 u64 logical = (u64)bio->bi_sector << 9;
1585 if (bio_flags & EXTENT_BIO_COMPRESSED)
1588 length = bio->bi_size;
1589 map_length = length;
1590 ret = btrfs_map_block(root->fs_info, READ, logical,
1591 &map_length, NULL, 0);
1592 /* Will always return 0 with map_multi == NULL */
1594 if (map_length < length + size)
1600 * in order to insert checksums into the metadata in large chunks,
1601 * we wait until bio submission time. All the pages in the bio are
1602 * checksummed and sums are attached onto the ordered extent record.
1604 * At IO completion time the cums attached on the ordered extent record
1605 * are inserted into the btree
1607 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1608 struct bio *bio, int mirror_num,
1609 unsigned long bio_flags,
1612 struct btrfs_root *root = BTRFS_I(inode)->root;
1615 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1616 BUG_ON(ret); /* -ENOMEM */
1621 * in order to insert checksums into the metadata in large chunks,
1622 * we wait until bio submission time. All the pages in the bio are
1623 * checksummed and sums are attached onto the ordered extent record.
1625 * At IO completion time the cums attached on the ordered extent record
1626 * are inserted into the btree
1628 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1629 int mirror_num, unsigned long bio_flags,
1632 struct btrfs_root *root = BTRFS_I(inode)->root;
1635 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1637 bio_endio(bio, ret);
1642 * extent_io.c submission hook. This does the right thing for csum calculation
1643 * on write, or reading the csums from the tree before a read
1645 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1646 int mirror_num, unsigned long bio_flags,
1649 struct btrfs_root *root = BTRFS_I(inode)->root;
1653 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1655 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1657 if (btrfs_is_free_space_inode(inode))
1660 if (!(rw & REQ_WRITE)) {
1661 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1665 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1666 ret = btrfs_submit_compressed_read(inode, bio,
1670 } else if (!skip_sum) {
1671 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1676 } else if (async && !skip_sum) {
1677 /* csum items have already been cloned */
1678 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1680 /* we're doing a write, do the async checksumming */
1681 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1682 inode, rw, bio, mirror_num,
1683 bio_flags, bio_offset,
1684 __btrfs_submit_bio_start,
1685 __btrfs_submit_bio_done);
1687 } else if (!skip_sum) {
1688 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1694 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1698 bio_endio(bio, ret);
1703 * given a list of ordered sums record them in the inode. This happens
1704 * at IO completion time based on sums calculated at bio submission time.
1706 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1707 struct inode *inode, u64 file_offset,
1708 struct list_head *list)
1710 struct btrfs_ordered_sum *sum;
1712 list_for_each_entry(sum, list, list) {
1713 btrfs_csum_file_blocks(trans,
1714 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1719 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1720 struct extent_state **cached_state)
1722 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1723 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1724 cached_state, GFP_NOFS);
1727 /* see btrfs_writepage_start_hook for details on why this is required */
1728 struct btrfs_writepage_fixup {
1730 struct btrfs_work work;
1733 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
1735 struct btrfs_writepage_fixup *fixup;
1736 struct btrfs_ordered_extent *ordered;
1737 struct extent_state *cached_state = NULL;
1739 struct inode *inode;
1744 fixup = container_of(work, struct btrfs_writepage_fixup, work);
1748 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
1749 ClearPageChecked(page);
1753 inode = page->mapping->host;
1754 page_start = page_offset(page);
1755 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
1757 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
1760 /* already ordered? We're done */
1761 if (PagePrivate2(page))
1764 ordered = btrfs_lookup_ordered_extent(inode, page_start);
1766 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
1767 page_end, &cached_state, GFP_NOFS);
1769 btrfs_start_ordered_extent(inode, ordered, 1);
1770 btrfs_put_ordered_extent(ordered);
1774 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
1776 mapping_set_error(page->mapping, ret);
1777 end_extent_writepage(page, ret, page_start, page_end);
1778 ClearPageChecked(page);
1782 btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state);
1783 ClearPageChecked(page);
1784 set_page_dirty(page);
1786 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
1787 &cached_state, GFP_NOFS);
1790 page_cache_release(page);
1795 * There are a few paths in the higher layers of the kernel that directly
1796 * set the page dirty bit without asking the filesystem if it is a
1797 * good idea. This causes problems because we want to make sure COW
1798 * properly happens and the data=ordered rules are followed.
1800 * In our case any range that doesn't have the ORDERED bit set
1801 * hasn't been properly setup for IO. We kick off an async process
1802 * to fix it up. The async helper will wait for ordered extents, set
1803 * the delalloc bit and make it safe to write the page.
1805 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
1807 struct inode *inode = page->mapping->host;
1808 struct btrfs_writepage_fixup *fixup;
1809 struct btrfs_root *root = BTRFS_I(inode)->root;
1811 /* this page is properly in the ordered list */
1812 if (TestClearPagePrivate2(page))
1815 if (PageChecked(page))
1818 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
1822 SetPageChecked(page);
1823 page_cache_get(page);
1824 fixup->work.func = btrfs_writepage_fixup_worker;
1826 btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work);
1830 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
1831 struct inode *inode, u64 file_pos,
1832 u64 disk_bytenr, u64 disk_num_bytes,
1833 u64 num_bytes, u64 ram_bytes,
1834 u8 compression, u8 encryption,
1835 u16 other_encoding, int extent_type)
1837 struct btrfs_root *root = BTRFS_I(inode)->root;
1838 struct btrfs_file_extent_item *fi;
1839 struct btrfs_path *path;
1840 struct extent_buffer *leaf;
1841 struct btrfs_key ins;
1844 path = btrfs_alloc_path();
1848 path->leave_spinning = 1;
1851 * we may be replacing one extent in the tree with another.
1852 * The new extent is pinned in the extent map, and we don't want
1853 * to drop it from the cache until it is completely in the btree.
1855 * So, tell btrfs_drop_extents to leave this extent in the cache.
1856 * the caller is expected to unpin it and allow it to be merged
1859 ret = btrfs_drop_extents(trans, root, inode, file_pos,
1860 file_pos + num_bytes, 0);
1864 ins.objectid = btrfs_ino(inode);
1865 ins.offset = file_pos;
1866 ins.type = BTRFS_EXTENT_DATA_KEY;
1867 ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi));
1870 leaf = path->nodes[0];
1871 fi = btrfs_item_ptr(leaf, path->slots[0],
1872 struct btrfs_file_extent_item);
1873 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1874 btrfs_set_file_extent_type(leaf, fi, extent_type);
1875 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
1876 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
1877 btrfs_set_file_extent_offset(leaf, fi, 0);
1878 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1879 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
1880 btrfs_set_file_extent_compression(leaf, fi, compression);
1881 btrfs_set_file_extent_encryption(leaf, fi, encryption);
1882 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
1884 btrfs_mark_buffer_dirty(leaf);
1885 btrfs_release_path(path);
1887 inode_add_bytes(inode, num_bytes);
1889 ins.objectid = disk_bytenr;
1890 ins.offset = disk_num_bytes;
1891 ins.type = BTRFS_EXTENT_ITEM_KEY;
1892 ret = btrfs_alloc_reserved_file_extent(trans, root,
1893 root->root_key.objectid,
1894 btrfs_ino(inode), file_pos, &ins);
1896 btrfs_free_path(path);
1902 * helper function for btrfs_finish_ordered_io, this
1903 * just reads in some of the csum leaves to prime them into ram
1904 * before we start the transaction. It limits the amount of btree
1905 * reads required while inside the transaction.
1907 /* as ordered data IO finishes, this gets called so we can finish
1908 * an ordered extent if the range of bytes in the file it covers are
1911 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
1913 struct inode *inode = ordered_extent->inode;
1914 struct btrfs_root *root = BTRFS_I(inode)->root;
1915 struct btrfs_trans_handle *trans = NULL;
1916 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
1917 struct extent_state *cached_state = NULL;
1918 int compress_type = 0;
1922 nolock = btrfs_is_free_space_inode(inode);
1924 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
1929 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
1930 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
1931 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1933 trans = btrfs_join_transaction_nolock(root);
1935 trans = btrfs_join_transaction(root);
1936 if (IS_ERR(trans)) {
1937 ret = PTR_ERR(trans);
1941 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1942 ret = btrfs_update_inode_fallback(trans, root, inode);
1943 if (ret) /* -ENOMEM or corruption */
1944 btrfs_abort_transaction(trans, root, ret);
1948 lock_extent_bits(io_tree, ordered_extent->file_offset,
1949 ordered_extent->file_offset + ordered_extent->len - 1,
1953 trans = btrfs_join_transaction_nolock(root);
1955 trans = btrfs_join_transaction(root);
1956 if (IS_ERR(trans)) {
1957 ret = PTR_ERR(trans);
1961 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1963 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
1964 compress_type = ordered_extent->compress_type;
1965 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
1966 BUG_ON(compress_type);
1967 ret = btrfs_mark_extent_written(trans, inode,
1968 ordered_extent->file_offset,
1969 ordered_extent->file_offset +
1970 ordered_extent->len);
1972 BUG_ON(root == root->fs_info->tree_root);
1973 ret = insert_reserved_file_extent(trans, inode,
1974 ordered_extent->file_offset,
1975 ordered_extent->start,
1976 ordered_extent->disk_len,
1977 ordered_extent->len,
1978 ordered_extent->len,
1979 compress_type, 0, 0,
1980 BTRFS_FILE_EXTENT_REG);
1982 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
1983 ordered_extent->file_offset, ordered_extent->len,
1986 btrfs_abort_transaction(trans, root, ret);
1990 add_pending_csums(trans, inode, ordered_extent->file_offset,
1991 &ordered_extent->list);
1993 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
1994 ret = btrfs_update_inode_fallback(trans, root, inode);
1995 if (ret) { /* -ENOMEM or corruption */
1996 btrfs_abort_transaction(trans, root, ret);
2001 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2002 ordered_extent->file_offset +
2003 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2005 if (root != root->fs_info->tree_root)
2006 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2008 btrfs_end_transaction(trans, root);
2011 clear_extent_uptodate(io_tree, ordered_extent->file_offset,
2012 ordered_extent->file_offset +
2013 ordered_extent->len - 1, NULL, GFP_NOFS);
2016 * This needs to be done to make sure anybody waiting knows we are done
2017 * updating everything for this ordered extent.
2019 btrfs_remove_ordered_extent(inode, ordered_extent);
2022 btrfs_put_ordered_extent(ordered_extent);
2023 /* once for the tree */
2024 btrfs_put_ordered_extent(ordered_extent);
2029 static void finish_ordered_fn(struct btrfs_work *work)
2031 struct btrfs_ordered_extent *ordered_extent;
2032 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2033 btrfs_finish_ordered_io(ordered_extent);
2036 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
2037 struct extent_state *state, int uptodate)
2039 struct inode *inode = page->mapping->host;
2040 struct btrfs_root *root = BTRFS_I(inode)->root;
2041 struct btrfs_ordered_extent *ordered_extent = NULL;
2042 struct btrfs_workers *workers;
2044 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2046 ClearPagePrivate2(page);
2047 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2048 end - start + 1, uptodate))
2051 ordered_extent->work.func = finish_ordered_fn;
2052 ordered_extent->work.flags = 0;
2054 if (btrfs_is_free_space_inode(inode))
2055 workers = &root->fs_info->endio_freespace_worker;
2057 workers = &root->fs_info->endio_write_workers;
2058 btrfs_queue_worker(workers, &ordered_extent->work);
2064 * when reads are done, we need to check csums to verify the data is correct
2065 * if there's a match, we allow the bio to finish. If not, the code in
2066 * extent_io.c will try to find good copies for us.
2068 static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end,
2069 struct extent_state *state, int mirror)
2071 size_t offset = start - page_offset(page);
2072 struct inode *inode = page->mapping->host;
2073 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2075 u64 private = ~(u32)0;
2077 struct btrfs_root *root = BTRFS_I(inode)->root;
2080 if (PageChecked(page)) {
2081 ClearPageChecked(page);
2085 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2088 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2089 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2090 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
2095 if (state && state->start == start) {
2096 private = state->private;
2099 ret = get_state_private(io_tree, start, &private);
2101 kaddr = kmap_atomic(page);
2105 csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1);
2106 btrfs_csum_final(csum, (char *)&csum);
2107 if (csum != private)
2110 kunmap_atomic(kaddr);
2115 printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u "
2117 (unsigned long long)btrfs_ino(page->mapping->host),
2118 (unsigned long long)start, csum,
2119 (unsigned long long)private);
2120 memset(kaddr + offset, 1, end - start + 1);
2121 flush_dcache_page(page);
2122 kunmap_atomic(kaddr);
2128 struct delayed_iput {
2129 struct list_head list;
2130 struct inode *inode;
2133 /* JDM: If this is fs-wide, why can't we add a pointer to
2134 * btrfs_inode instead and avoid the allocation? */
2135 void btrfs_add_delayed_iput(struct inode *inode)
2137 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
2138 struct delayed_iput *delayed;
2140 if (atomic_add_unless(&inode->i_count, -1, 1))
2143 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
2144 delayed->inode = inode;
2146 spin_lock(&fs_info->delayed_iput_lock);
2147 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
2148 spin_unlock(&fs_info->delayed_iput_lock);
2151 void btrfs_run_delayed_iputs(struct btrfs_root *root)
2154 struct btrfs_fs_info *fs_info = root->fs_info;
2155 struct delayed_iput *delayed;
2158 spin_lock(&fs_info->delayed_iput_lock);
2159 empty = list_empty(&fs_info->delayed_iputs);
2160 spin_unlock(&fs_info->delayed_iput_lock);
2164 spin_lock(&fs_info->delayed_iput_lock);
2165 list_splice_init(&fs_info->delayed_iputs, &list);
2166 spin_unlock(&fs_info->delayed_iput_lock);
2168 while (!list_empty(&list)) {
2169 delayed = list_entry(list.next, struct delayed_iput, list);
2170 list_del(&delayed->list);
2171 iput(delayed->inode);
2176 enum btrfs_orphan_cleanup_state {
2177 ORPHAN_CLEANUP_STARTED = 1,
2178 ORPHAN_CLEANUP_DONE = 2,
2182 * This is called in transaction commit time. If there are no orphan
2183 * files in the subvolume, it removes orphan item and frees block_rsv
2186 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
2187 struct btrfs_root *root)
2189 struct btrfs_block_rsv *block_rsv;
2192 if (atomic_read(&root->orphan_inodes) ||
2193 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
2196 spin_lock(&root->orphan_lock);
2197 if (atomic_read(&root->orphan_inodes)) {
2198 spin_unlock(&root->orphan_lock);
2202 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
2203 spin_unlock(&root->orphan_lock);
2207 block_rsv = root->orphan_block_rsv;
2208 root->orphan_block_rsv = NULL;
2209 spin_unlock(&root->orphan_lock);
2211 if (root->orphan_item_inserted &&
2212 btrfs_root_refs(&root->root_item) > 0) {
2213 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
2214 root->root_key.objectid);
2216 root->orphan_item_inserted = 0;
2220 WARN_ON(block_rsv->size > 0);
2221 btrfs_free_block_rsv(root, block_rsv);
2226 * This creates an orphan entry for the given inode in case something goes
2227 * wrong in the middle of an unlink/truncate.
2229 * NOTE: caller of this function should reserve 5 units of metadata for
2232 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
2234 struct btrfs_root *root = BTRFS_I(inode)->root;
2235 struct btrfs_block_rsv *block_rsv = NULL;
2240 if (!root->orphan_block_rsv) {
2241 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2246 spin_lock(&root->orphan_lock);
2247 if (!root->orphan_block_rsv) {
2248 root->orphan_block_rsv = block_rsv;
2249 } else if (block_rsv) {
2250 btrfs_free_block_rsv(root, block_rsv);
2254 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2255 &BTRFS_I(inode)->runtime_flags)) {
2258 * For proper ENOSPC handling, we should do orphan
2259 * cleanup when mounting. But this introduces backward
2260 * compatibility issue.
2262 if (!xchg(&root->orphan_item_inserted, 1))
2268 atomic_inc(&root->orphan_inodes);
2271 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2272 &BTRFS_I(inode)->runtime_flags))
2274 spin_unlock(&root->orphan_lock);
2276 /* grab metadata reservation from transaction handle */
2278 ret = btrfs_orphan_reserve_metadata(trans, inode);
2279 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
2282 /* insert an orphan item to track this unlinked/truncated file */
2284 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
2285 if (ret && ret != -EEXIST) {
2286 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2287 &BTRFS_I(inode)->runtime_flags);
2288 btrfs_abort_transaction(trans, root, ret);
2294 /* insert an orphan item to track subvolume contains orphan files */
2296 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
2297 root->root_key.objectid);
2298 if (ret && ret != -EEXIST) {
2299 btrfs_abort_transaction(trans, root, ret);
2307 * We have done the truncate/delete so we can go ahead and remove the orphan
2308 * item for this particular inode.
2310 int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode)
2312 struct btrfs_root *root = BTRFS_I(inode)->root;
2313 int delete_item = 0;
2314 int release_rsv = 0;
2317 spin_lock(&root->orphan_lock);
2318 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2319 &BTRFS_I(inode)->runtime_flags))
2322 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
2323 &BTRFS_I(inode)->runtime_flags))
2325 spin_unlock(&root->orphan_lock);
2327 if (trans && delete_item) {
2328 ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode));
2329 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2333 btrfs_orphan_release_metadata(inode);
2334 atomic_dec(&root->orphan_inodes);
2341 * this cleans up any orphans that may be left on the list from the last use
2344 int btrfs_orphan_cleanup(struct btrfs_root *root)
2346 struct btrfs_path *path;
2347 struct extent_buffer *leaf;
2348 struct btrfs_key key, found_key;
2349 struct btrfs_trans_handle *trans;
2350 struct inode *inode;
2351 u64 last_objectid = 0;
2352 int ret = 0, nr_unlink = 0, nr_truncate = 0;
2354 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2357 path = btrfs_alloc_path();
2364 key.objectid = BTRFS_ORPHAN_OBJECTID;
2365 btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY);
2366 key.offset = (u64)-1;
2369 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2374 * if ret == 0 means we found what we were searching for, which
2375 * is weird, but possible, so only screw with path if we didn't
2376 * find the key and see if we have stuff that matches
2380 if (path->slots[0] == 0)
2385 /* pull out the item */
2386 leaf = path->nodes[0];
2387 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2389 /* make sure the item matches what we want */
2390 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2392 if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY)
2395 /* release the path since we're done with it */
2396 btrfs_release_path(path);
2399 * this is where we are basically btrfs_lookup, without the
2400 * crossing root thing. we store the inode number in the
2401 * offset of the orphan item.
2404 if (found_key.offset == last_objectid) {
2405 printk(KERN_ERR "btrfs: Error removing orphan entry, "
2406 "stopping orphan cleanup\n");
2411 last_objectid = found_key.offset;
2413 found_key.objectid = found_key.offset;
2414 found_key.type = BTRFS_INODE_ITEM_KEY;
2415 found_key.offset = 0;
2416 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
2417 ret = PTR_RET(inode);
2418 if (ret && ret != -ESTALE)
2421 if (ret == -ESTALE && root == root->fs_info->tree_root) {
2422 struct btrfs_root *dead_root;
2423 struct btrfs_fs_info *fs_info = root->fs_info;
2424 int is_dead_root = 0;
2427 * this is an orphan in the tree root. Currently these
2428 * could come from 2 sources:
2429 * a) a snapshot deletion in progress
2430 * b) a free space cache inode
2431 * We need to distinguish those two, as the snapshot
2432 * orphan must not get deleted.
2433 * find_dead_roots already ran before us, so if this
2434 * is a snapshot deletion, we should find the root
2435 * in the dead_roots list
2437 spin_lock(&fs_info->trans_lock);
2438 list_for_each_entry(dead_root, &fs_info->dead_roots,
2440 if (dead_root->root_key.objectid ==
2441 found_key.objectid) {
2446 spin_unlock(&fs_info->trans_lock);
2448 /* prevent this orphan from being found again */
2449 key.offset = found_key.objectid - 1;
2454 * Inode is already gone but the orphan item is still there,
2455 * kill the orphan item.
2457 if (ret == -ESTALE) {
2458 trans = btrfs_start_transaction(root, 1);
2459 if (IS_ERR(trans)) {
2460 ret = PTR_ERR(trans);
2463 printk(KERN_ERR "auto deleting %Lu\n",
2464 found_key.objectid);
2465 ret = btrfs_del_orphan_item(trans, root,
2466 found_key.objectid);
2467 BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */
2468 btrfs_end_transaction(trans, root);
2473 * add this inode to the orphan list so btrfs_orphan_del does
2474 * the proper thing when we hit it
2476 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
2477 &BTRFS_I(inode)->runtime_flags);
2479 /* if we have links, this was a truncate, lets do that */
2480 if (inode->i_nlink) {
2481 if (!S_ISREG(inode->i_mode)) {
2488 /* 1 for the orphan item deletion. */
2489 trans = btrfs_start_transaction(root, 1);
2490 if (IS_ERR(trans)) {
2491 ret = PTR_ERR(trans);
2494 ret = btrfs_orphan_add(trans, inode);
2495 btrfs_end_transaction(trans, root);
2499 ret = btrfs_truncate(inode);
2504 /* this will do delete_inode and everything for us */
2509 /* release the path since we're done with it */
2510 btrfs_release_path(path);
2512 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
2514 if (root->orphan_block_rsv)
2515 btrfs_block_rsv_release(root, root->orphan_block_rsv,
2518 if (root->orphan_block_rsv || root->orphan_item_inserted) {
2519 trans = btrfs_join_transaction(root);
2521 btrfs_end_transaction(trans, root);
2525 printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink);
2527 printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate);
2531 printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret);
2532 btrfs_free_path(path);
2537 * very simple check to peek ahead in the leaf looking for xattrs. If we
2538 * don't find any xattrs, we know there can't be any acls.
2540 * slot is the slot the inode is in, objectid is the objectid of the inode
2542 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
2543 int slot, u64 objectid)
2545 u32 nritems = btrfs_header_nritems(leaf);
2546 struct btrfs_key found_key;
2550 while (slot < nritems) {
2551 btrfs_item_key_to_cpu(leaf, &found_key, slot);
2553 /* we found a different objectid, there must not be acls */
2554 if (found_key.objectid != objectid)
2557 /* we found an xattr, assume we've got an acl */
2558 if (found_key.type == BTRFS_XATTR_ITEM_KEY)
2562 * we found a key greater than an xattr key, there can't
2563 * be any acls later on
2565 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
2572 * it goes inode, inode backrefs, xattrs, extents,
2573 * so if there are a ton of hard links to an inode there can
2574 * be a lot of backrefs. Don't waste time searching too hard,
2575 * this is just an optimization
2580 /* we hit the end of the leaf before we found an xattr or
2581 * something larger than an xattr. We have to assume the inode
2588 * read an inode from the btree into the in-memory inode
2590 static void btrfs_read_locked_inode(struct inode *inode)
2592 struct btrfs_path *path;
2593 struct extent_buffer *leaf;
2594 struct btrfs_inode_item *inode_item;
2595 struct btrfs_timespec *tspec;
2596 struct btrfs_root *root = BTRFS_I(inode)->root;
2597 struct btrfs_key location;
2601 bool filled = false;
2603 ret = btrfs_fill_inode(inode, &rdev);
2607 path = btrfs_alloc_path();
2611 path->leave_spinning = 1;
2612 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
2614 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
2618 leaf = path->nodes[0];
2623 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2624 struct btrfs_inode_item);
2625 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
2626 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
2627 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
2628 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
2629 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
2631 tspec = btrfs_inode_atime(inode_item);
2632 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2633 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2635 tspec = btrfs_inode_mtime(inode_item);
2636 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2637 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2639 tspec = btrfs_inode_ctime(inode_item);
2640 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec);
2641 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec);
2643 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
2644 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
2645 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
2648 * If we were modified in the current generation and evicted from memory
2649 * and then re-read we need to do a full sync since we don't have any
2650 * idea about which extents were modified before we were evicted from
2653 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
2654 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2655 &BTRFS_I(inode)->runtime_flags);
2657 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
2658 inode->i_generation = BTRFS_I(inode)->generation;
2660 rdev = btrfs_inode_rdev(leaf, inode_item);
2662 BTRFS_I(inode)->index_cnt = (u64)-1;
2663 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
2666 * try to precache a NULL acl entry for files that don't have
2667 * any xattrs or acls
2669 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
2672 cache_no_acl(inode);
2674 btrfs_free_path(path);
2676 switch (inode->i_mode & S_IFMT) {
2678 inode->i_mapping->a_ops = &btrfs_aops;
2679 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2680 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
2681 inode->i_fop = &btrfs_file_operations;
2682 inode->i_op = &btrfs_file_inode_operations;
2685 inode->i_fop = &btrfs_dir_file_operations;
2686 if (root == root->fs_info->tree_root)
2687 inode->i_op = &btrfs_dir_ro_inode_operations;
2689 inode->i_op = &btrfs_dir_inode_operations;
2692 inode->i_op = &btrfs_symlink_inode_operations;
2693 inode->i_mapping->a_ops = &btrfs_symlink_aops;
2694 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
2697 inode->i_op = &btrfs_special_inode_operations;
2698 init_special_inode(inode, inode->i_mode, rdev);
2702 btrfs_update_iflags(inode);
2706 btrfs_free_path(path);
2707 make_bad_inode(inode);
2711 * given a leaf and an inode, copy the inode fields into the leaf
2713 static void fill_inode_item(struct btrfs_trans_handle *trans,
2714 struct extent_buffer *leaf,
2715 struct btrfs_inode_item *item,
2716 struct inode *inode)
2718 struct btrfs_map_token token;
2720 btrfs_init_map_token(&token);
2722 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
2723 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
2724 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
2726 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
2727 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
2729 btrfs_set_token_timespec_sec(leaf, btrfs_inode_atime(item),
2730 inode->i_atime.tv_sec, &token);
2731 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_atime(item),
2732 inode->i_atime.tv_nsec, &token);
2734 btrfs_set_token_timespec_sec(leaf, btrfs_inode_mtime(item),
2735 inode->i_mtime.tv_sec, &token);
2736 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_mtime(item),
2737 inode->i_mtime.tv_nsec, &token);
2739 btrfs_set_token_timespec_sec(leaf, btrfs_inode_ctime(item),
2740 inode->i_ctime.tv_sec, &token);
2741 btrfs_set_token_timespec_nsec(leaf, btrfs_inode_ctime(item),
2742 inode->i_ctime.tv_nsec, &token);
2744 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
2746 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
2748 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
2749 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
2750 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
2751 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
2752 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
2756 * copy everything in the in-memory inode into the btree.
2758 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
2759 struct btrfs_root *root, struct inode *inode)
2761 struct btrfs_inode_item *inode_item;
2762 struct btrfs_path *path;
2763 struct extent_buffer *leaf;
2766 path = btrfs_alloc_path();
2770 path->leave_spinning = 1;
2771 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
2779 btrfs_unlock_up_safe(path, 1);
2780 leaf = path->nodes[0];
2781 inode_item = btrfs_item_ptr(leaf, path->slots[0],
2782 struct btrfs_inode_item);
2784 fill_inode_item(trans, leaf, inode_item, inode);
2785 btrfs_mark_buffer_dirty(leaf);
2786 btrfs_set_inode_last_trans(trans, inode);
2789 btrfs_free_path(path);
2794 * copy everything in the in-memory inode into the btree.
2796 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
2797 struct btrfs_root *root, struct inode *inode)
2802 * If the inode is a free space inode, we can deadlock during commit
2803 * if we put it into the delayed code.
2805 * The data relocation inode should also be directly updated
2808 if (!btrfs_is_free_space_inode(inode)
2809 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
2810 btrfs_update_root_times(trans, root);
2812 ret = btrfs_delayed_update_inode(trans, root, inode);
2814 btrfs_set_inode_last_trans(trans, inode);
2818 return btrfs_update_inode_item(trans, root, inode);
2821 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
2822 struct btrfs_root *root,
2823 struct inode *inode)
2827 ret = btrfs_update_inode(trans, root, inode);
2829 return btrfs_update_inode_item(trans, root, inode);
2834 * unlink helper that gets used here in inode.c and in the tree logging
2835 * recovery code. It remove a link in a directory with a given name, and
2836 * also drops the back refs in the inode to the directory
2838 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2839 struct btrfs_root *root,
2840 struct inode *dir, struct inode *inode,
2841 const char *name, int name_len)
2843 struct btrfs_path *path;
2845 struct extent_buffer *leaf;
2846 struct btrfs_dir_item *di;
2847 struct btrfs_key key;
2849 u64 ino = btrfs_ino(inode);
2850 u64 dir_ino = btrfs_ino(dir);
2852 path = btrfs_alloc_path();
2858 path->leave_spinning = 1;
2859 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
2860 name, name_len, -1);
2869 leaf = path->nodes[0];
2870 btrfs_dir_item_key_to_cpu(leaf, di, &key);
2871 ret = btrfs_delete_one_dir_name(trans, root, path, di);
2874 btrfs_release_path(path);
2876 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
2879 printk(KERN_INFO "btrfs failed to delete reference to %.*s, "
2880 "inode %llu parent %llu\n", name_len, name,
2881 (unsigned long long)ino, (unsigned long long)dir_ino);
2882 btrfs_abort_transaction(trans, root, ret);
2886 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
2888 btrfs_abort_transaction(trans, root, ret);
2892 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
2894 if (ret != 0 && ret != -ENOENT) {
2895 btrfs_abort_transaction(trans, root, ret);
2899 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
2904 btrfs_free_path(path);
2908 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
2909 inode_inc_iversion(inode);
2910 inode_inc_iversion(dir);
2911 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
2912 ret = btrfs_update_inode(trans, root, dir);
2917 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
2918 struct btrfs_root *root,
2919 struct inode *dir, struct inode *inode,
2920 const char *name, int name_len)
2923 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
2925 btrfs_drop_nlink(inode);
2926 ret = btrfs_update_inode(trans, root, inode);
2932 /* helper to check if there is any shared block in the path */
2933 static int check_path_shared(struct btrfs_root *root,
2934 struct btrfs_path *path)
2936 struct extent_buffer *eb;
2940 for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
2943 if (!path->nodes[level])
2945 eb = path->nodes[level];
2946 if (!btrfs_block_can_be_shared(root, eb))
2948 ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len,
2957 * helper to start transaction for unlink and rmdir.
2959 * unlink and rmdir are special in btrfs, they do not always free space.
2960 * so in enospc case, we should make sure they will free space before
2961 * allowing them to use the global metadata reservation.
2963 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir,
2964 struct dentry *dentry)
2966 struct btrfs_trans_handle *trans;
2967 struct btrfs_root *root = BTRFS_I(dir)->root;
2968 struct btrfs_path *path;
2969 struct btrfs_dir_item *di;
2970 struct inode *inode = dentry->d_inode;
2975 u64 ino = btrfs_ino(inode);
2976 u64 dir_ino = btrfs_ino(dir);
2979 * 1 for the possible orphan item
2980 * 1 for the dir item
2981 * 1 for the dir index
2982 * 1 for the inode ref
2983 * 1 for the inode ref in the tree log
2984 * 2 for the dir entries in the log
2987 trans = btrfs_start_transaction(root, 8);
2988 if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC)
2991 if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
2992 return ERR_PTR(-ENOSPC);
2994 /* check if there is someone else holds reference */
2995 if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1)
2996 return ERR_PTR(-ENOSPC);
2998 if (atomic_read(&inode->i_count) > 2)
2999 return ERR_PTR(-ENOSPC);
3001 if (xchg(&root->fs_info->enospc_unlink, 1))
3002 return ERR_PTR(-ENOSPC);
3004 path = btrfs_alloc_path();
3006 root->fs_info->enospc_unlink = 0;
3007 return ERR_PTR(-ENOMEM);
3010 /* 1 for the orphan item */
3011 trans = btrfs_start_transaction(root, 1);
3012 if (IS_ERR(trans)) {
3013 btrfs_free_path(path);
3014 root->fs_info->enospc_unlink = 0;
3018 path->skip_locking = 1;
3019 path->search_commit_root = 1;
3021 ret = btrfs_lookup_inode(trans, root, path,
3022 &BTRFS_I(dir)->location, 0);
3028 if (check_path_shared(root, path))
3033 btrfs_release_path(path);
3035 ret = btrfs_lookup_inode(trans, root, path,
3036 &BTRFS_I(inode)->location, 0);
3042 if (check_path_shared(root, path))
3047 btrfs_release_path(path);
3049 if (ret == 0 && S_ISREG(inode->i_mode)) {
3050 ret = btrfs_lookup_file_extent(trans, root, path,
3056 BUG_ON(ret == 0); /* Corruption */
3057 if (check_path_shared(root, path))
3059 btrfs_release_path(path);
3067 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3068 dentry->d_name.name, dentry->d_name.len, 0);
3074 if (check_path_shared(root, path))
3080 btrfs_release_path(path);
3082 ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name,
3083 dentry->d_name.len, ino, dir_ino, 0,
3090 if (check_path_shared(root, path))
3093 btrfs_release_path(path);
3096 * This is a commit root search, if we can lookup inode item and other
3097 * relative items in the commit root, it means the transaction of
3098 * dir/file creation has been committed, and the dir index item that we
3099 * delay to insert has also been inserted into the commit root. So
3100 * we needn't worry about the delayed insertion of the dir index item
3103 di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index,
3104 dentry->d_name.name, dentry->d_name.len, 0);
3109 BUG_ON(ret == -ENOENT);
3110 if (check_path_shared(root, path))
3115 btrfs_free_path(path);
3116 /* Migrate the orphan reservation over */
3118 err = btrfs_block_rsv_migrate(trans->block_rsv,
3119 &root->fs_info->global_block_rsv,
3120 trans->bytes_reserved);
3123 btrfs_end_transaction(trans, root);
3124 root->fs_info->enospc_unlink = 0;
3125 return ERR_PTR(err);
3128 trans->block_rsv = &root->fs_info->global_block_rsv;
3132 static void __unlink_end_trans(struct btrfs_trans_handle *trans,
3133 struct btrfs_root *root)
3135 if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) {
3136 btrfs_block_rsv_release(root, trans->block_rsv,
3137 trans->bytes_reserved);
3138 trans->block_rsv = &root->fs_info->trans_block_rsv;
3139 BUG_ON(!root->fs_info->enospc_unlink);
3140 root->fs_info->enospc_unlink = 0;
3142 btrfs_end_transaction(trans, root);
3145 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3147 struct btrfs_root *root = BTRFS_I(dir)->root;
3148 struct btrfs_trans_handle *trans;
3149 struct inode *inode = dentry->d_inode;
3152 trans = __unlink_start_trans(dir, dentry);
3154 return PTR_ERR(trans);
3156 btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0);
3158 ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3159 dentry->d_name.name, dentry->d_name.len);
3163 if (inode->i_nlink == 0) {
3164 ret = btrfs_orphan_add(trans, inode);
3170 __unlink_end_trans(trans, root);
3171 btrfs_btree_balance_dirty(root);
3175 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3176 struct btrfs_root *root,
3177 struct inode *dir, u64 objectid,
3178 const char *name, int name_len)
3180 struct btrfs_path *path;
3181 struct extent_buffer *leaf;
3182 struct btrfs_dir_item *di;
3183 struct btrfs_key key;
3186 u64 dir_ino = btrfs_ino(dir);
3188 path = btrfs_alloc_path();
3192 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3193 name, name_len, -1);
3194 if (IS_ERR_OR_NULL(di)) {
3202 leaf = path->nodes[0];
3203 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3204 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3205 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3207 btrfs_abort_transaction(trans, root, ret);
3210 btrfs_release_path(path);
3212 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
3213 objectid, root->root_key.objectid,
3214 dir_ino, &index, name, name_len);
3216 if (ret != -ENOENT) {
3217 btrfs_abort_transaction(trans, root, ret);
3220 di = btrfs_search_dir_index_item(root, path, dir_ino,
3222 if (IS_ERR_OR_NULL(di)) {
3227 btrfs_abort_transaction(trans, root, ret);
3231 leaf = path->nodes[0];
3232 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3233 btrfs_release_path(path);
3236 btrfs_release_path(path);
3238 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
3240 btrfs_abort_transaction(trans, root, ret);
3244 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
3245 inode_inc_iversion(dir);
3246 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
3247 ret = btrfs_update_inode_fallback(trans, root, dir);
3249 btrfs_abort_transaction(trans, root, ret);
3251 btrfs_free_path(path);
3255 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3257 struct inode *inode = dentry->d_inode;
3259 struct btrfs_root *root = BTRFS_I(dir)->root;
3260 struct btrfs_trans_handle *trans;
3262 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3264 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
3267 trans = __unlink_start_trans(dir, dentry);
3269 return PTR_ERR(trans);
3271 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
3272 err = btrfs_unlink_subvol(trans, root, dir,
3273 BTRFS_I(inode)->location.objectid,
3274 dentry->d_name.name,
3275 dentry->d_name.len);
3279 err = btrfs_orphan_add(trans, inode);
3283 /* now the directory is empty */
3284 err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode,
3285 dentry->d_name.name, dentry->d_name.len);
3287 btrfs_i_size_write(inode, 0);
3289 __unlink_end_trans(trans, root);
3290 btrfs_btree_balance_dirty(root);
3296 * this can truncate away extent items, csum items and directory items.
3297 * It starts at a high offset and removes keys until it can't find
3298 * any higher than new_size
3300 * csum items that cross the new i_size are truncated to the new size
3303 * min_type is the minimum key type to truncate down to. If set to 0, this
3304 * will kill all the items on this inode, including the INODE_ITEM_KEY.
3306 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
3307 struct btrfs_root *root,
3308 struct inode *inode,
3309 u64 new_size, u32 min_type)
3311 struct btrfs_path *path;
3312 struct extent_buffer *leaf;
3313 struct btrfs_file_extent_item *fi;
3314 struct btrfs_key key;
3315 struct btrfs_key found_key;
3316 u64 extent_start = 0;
3317 u64 extent_num_bytes = 0;
3318 u64 extent_offset = 0;
3320 u64 mask = root->sectorsize - 1;
3321 u32 found_type = (u8)-1;
3324 int pending_del_nr = 0;
3325 int pending_del_slot = 0;
3326 int extent_type = -1;
3329 u64 ino = btrfs_ino(inode);
3331 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
3333 path = btrfs_alloc_path();
3339 * We want to drop from the next block forward in case this new size is
3340 * not block aligned since we will be keeping the last block of the
3341 * extent just the way it is.
3343 if (root->ref_cows || root == root->fs_info->tree_root)
3344 btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0);
3347 * This function is also used to drop the items in the log tree before
3348 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
3349 * it is used to drop the loged items. So we shouldn't kill the delayed
3352 if (min_type == 0 && root == BTRFS_I(inode)->root)
3353 btrfs_kill_delayed_inode_items(inode);
3356 key.offset = (u64)-1;
3360 path->leave_spinning = 1;
3361 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3368 /* there are no items in the tree for us to truncate, we're
3371 if (path->slots[0] == 0)
3378 leaf = path->nodes[0];
3379 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3380 found_type = btrfs_key_type(&found_key);
3382 if (found_key.objectid != ino)
3385 if (found_type < min_type)
3388 item_end = found_key.offset;
3389 if (found_type == BTRFS_EXTENT_DATA_KEY) {
3390 fi = btrfs_item_ptr(leaf, path->slots[0],
3391 struct btrfs_file_extent_item);
3392 extent_type = btrfs_file_extent_type(leaf, fi);
3393 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3395 btrfs_file_extent_num_bytes(leaf, fi);
3396 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3397 item_end += btrfs_file_extent_inline_len(leaf,
3402 if (found_type > min_type) {
3405 if (item_end < new_size)
3407 if (found_key.offset >= new_size)
3413 /* FIXME, shrink the extent if the ref count is only 1 */
3414 if (found_type != BTRFS_EXTENT_DATA_KEY)
3417 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
3419 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
3421 u64 orig_num_bytes =
3422 btrfs_file_extent_num_bytes(leaf, fi);
3423 extent_num_bytes = new_size -
3424 found_key.offset + root->sectorsize - 1;
3425 extent_num_bytes = extent_num_bytes &
3426 ~((u64)root->sectorsize - 1);
3427 btrfs_set_file_extent_num_bytes(leaf, fi,
3429 num_dec = (orig_num_bytes -
3431 if (root->ref_cows && extent_start != 0)
3432 inode_sub_bytes(inode, num_dec);
3433 btrfs_mark_buffer_dirty(leaf);
3436 btrfs_file_extent_disk_num_bytes(leaf,
3438 extent_offset = found_key.offset -
3439 btrfs_file_extent_offset(leaf, fi);
3441 /* FIXME blocksize != 4096 */
3442 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
3443 if (extent_start != 0) {
3446 inode_sub_bytes(inode, num_dec);
3449 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
3451 * we can't truncate inline items that have had
3455 btrfs_file_extent_compression(leaf, fi) == 0 &&
3456 btrfs_file_extent_encryption(leaf, fi) == 0 &&
3457 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
3458 u32 size = new_size - found_key.offset;
3460 if (root->ref_cows) {
3461 inode_sub_bytes(inode, item_end + 1 -
3465 btrfs_file_extent_calc_inline_size(size);
3466 btrfs_truncate_item(trans, root, path,
3468 } else if (root->ref_cows) {
3469 inode_sub_bytes(inode, item_end + 1 -
3475 if (!pending_del_nr) {
3476 /* no pending yet, add ourselves */
3477 pending_del_slot = path->slots[0];
3479 } else if (pending_del_nr &&
3480 path->slots[0] + 1 == pending_del_slot) {
3481 /* hop on the pending chunk */
3483 pending_del_slot = path->slots[0];
3490 if (found_extent && (root->ref_cows ||
3491 root == root->fs_info->tree_root)) {
3492 btrfs_set_path_blocking(path);
3493 ret = btrfs_free_extent(trans, root, extent_start,
3494 extent_num_bytes, 0,
3495 btrfs_header_owner(leaf),
3496 ino, extent_offset, 0);
3500 if (found_type == BTRFS_INODE_ITEM_KEY)
3503 if (path->slots[0] == 0 ||
3504 path->slots[0] != pending_del_slot) {
3505 if (pending_del_nr) {
3506 ret = btrfs_del_items(trans, root, path,
3510 btrfs_abort_transaction(trans,
3516 btrfs_release_path(path);
3523 if (pending_del_nr) {
3524 ret = btrfs_del_items(trans, root, path, pending_del_slot,
3527 btrfs_abort_transaction(trans, root, ret);
3530 btrfs_free_path(path);
3535 * btrfs_truncate_page - read, zero a chunk and write a page
3536 * @inode - inode that we're zeroing
3537 * @from - the offset to start zeroing
3538 * @len - the length to zero, 0 to zero the entire range respective to the
3540 * @front - zero up to the offset instead of from the offset on
3542 * This will find the page for the "from" offset and cow the page and zero the
3543 * part we want to zero. This is used with truncate and hole punching.
3545 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
3548 struct address_space *mapping = inode->i_mapping;
3549 struct btrfs_root *root = BTRFS_I(inode)->root;
3550 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3551 struct btrfs_ordered_extent *ordered;
3552 struct extent_state *cached_state = NULL;
3554 u32 blocksize = root->sectorsize;
3555 pgoff_t index = from >> PAGE_CACHE_SHIFT;
3556 unsigned offset = from & (PAGE_CACHE_SIZE-1);
3558 gfp_t mask = btrfs_alloc_write_mask(mapping);
3563 if ((offset & (blocksize - 1)) == 0 &&
3564 (!len || ((len & (blocksize - 1)) == 0)))
3566 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
3571 page = find_or_create_page(mapping, index, mask);
3573 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3578 page_start = page_offset(page);
3579 page_end = page_start + PAGE_CACHE_SIZE - 1;
3581 if (!PageUptodate(page)) {
3582 ret = btrfs_readpage(NULL, page);
3584 if (page->mapping != mapping) {
3586 page_cache_release(page);
3589 if (!PageUptodate(page)) {
3594 wait_on_page_writeback(page);
3596 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
3597 set_page_extent_mapped(page);
3599 ordered = btrfs_lookup_ordered_extent(inode, page_start);
3601 unlock_extent_cached(io_tree, page_start, page_end,
3602 &cached_state, GFP_NOFS);
3604 page_cache_release(page);
3605 btrfs_start_ordered_extent(inode, ordered, 1);
3606 btrfs_put_ordered_extent(ordered);
3610 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
3611 EXTENT_DIRTY | EXTENT_DELALLOC |
3612 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
3613 0, 0, &cached_state, GFP_NOFS);
3615 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
3618 unlock_extent_cached(io_tree, page_start, page_end,
3619 &cached_state, GFP_NOFS);
3623 if (offset != PAGE_CACHE_SIZE) {
3625 len = PAGE_CACHE_SIZE - offset;
3628 memset(kaddr, 0, offset);
3630 memset(kaddr + offset, 0, len);
3631 flush_dcache_page(page);
3634 ClearPageChecked(page);
3635 set_page_dirty(page);
3636 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
3641 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
3643 page_cache_release(page);
3649 * This function puts in dummy file extents for the area we're creating a hole
3650 * for. So if we are truncating this file to a larger size we need to insert
3651 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
3652 * the range between oldsize and size
3654 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
3656 struct btrfs_trans_handle *trans;
3657 struct btrfs_root *root = BTRFS_I(inode)->root;
3658 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3659 struct extent_map *em = NULL;
3660 struct extent_state *cached_state = NULL;
3661 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
3662 u64 mask = root->sectorsize - 1;
3663 u64 hole_start = (oldsize + mask) & ~mask;
3664 u64 block_end = (size + mask) & ~mask;
3670 if (size <= hole_start)
3674 struct btrfs_ordered_extent *ordered;
3675 btrfs_wait_ordered_range(inode, hole_start,
3676 block_end - hole_start);
3677 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
3679 ordered = btrfs_lookup_ordered_extent(inode, hole_start);
3682 unlock_extent_cached(io_tree, hole_start, block_end - 1,
3683 &cached_state, GFP_NOFS);
3684 btrfs_put_ordered_extent(ordered);
3687 cur_offset = hole_start;
3689 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
3690 block_end - cur_offset, 0);
3696 last_byte = min(extent_map_end(em), block_end);
3697 last_byte = (last_byte + mask) & ~mask;
3698 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3699 struct extent_map *hole_em;
3700 hole_size = last_byte - cur_offset;
3702 trans = btrfs_start_transaction(root, 3);
3703 if (IS_ERR(trans)) {
3704 err = PTR_ERR(trans);
3708 err = btrfs_drop_extents(trans, root, inode,
3710 cur_offset + hole_size, 1);
3712 btrfs_abort_transaction(trans, root, err);
3713 btrfs_end_transaction(trans, root);
3717 err = btrfs_insert_file_extent(trans, root,
3718 btrfs_ino(inode), cur_offset, 0,
3719 0, hole_size, 0, hole_size,
3722 btrfs_abort_transaction(trans, root, err);
3723 btrfs_end_transaction(trans, root);
3727 btrfs_drop_extent_cache(inode, cur_offset,
3728 cur_offset + hole_size - 1, 0);
3729 hole_em = alloc_extent_map();
3731 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3732 &BTRFS_I(inode)->runtime_flags);
3735 hole_em->start = cur_offset;
3736 hole_em->len = hole_size;
3737 hole_em->orig_start = cur_offset;
3739 hole_em->block_start = EXTENT_MAP_HOLE;
3740 hole_em->block_len = 0;
3741 hole_em->orig_block_len = 0;
3742 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
3743 hole_em->compress_type = BTRFS_COMPRESS_NONE;
3744 hole_em->generation = trans->transid;
3747 write_lock(&em_tree->lock);
3748 err = add_extent_mapping(em_tree, hole_em);
3750 list_move(&hole_em->list,
3751 &em_tree->modified_extents);
3752 write_unlock(&em_tree->lock);
3755 btrfs_drop_extent_cache(inode, cur_offset,
3759 free_extent_map(hole_em);
3761 btrfs_update_inode(trans, root, inode);
3762 btrfs_end_transaction(trans, root);
3764 free_extent_map(em);
3766 cur_offset = last_byte;
3767 if (cur_offset >= block_end)
3771 free_extent_map(em);
3772 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
3777 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
3779 struct btrfs_root *root = BTRFS_I(inode)->root;
3780 struct btrfs_trans_handle *trans;
3781 loff_t oldsize = i_size_read(inode);
3782 loff_t newsize = attr->ia_size;
3783 int mask = attr->ia_valid;
3786 if (newsize == oldsize)
3790 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
3791 * special case where we need to update the times despite not having
3792 * these flags set. For all other operations the VFS set these flags
3793 * explicitly if it wants a timestamp update.
3795 if (newsize != oldsize && (!(mask & (ATTR_CTIME | ATTR_MTIME))))
3796 inode->i_ctime = inode->i_mtime = current_fs_time(inode->i_sb);
3798 if (newsize > oldsize) {
3799 truncate_pagecache(inode, oldsize, newsize);
3800 ret = btrfs_cont_expand(inode, oldsize, newsize);
3804 trans = btrfs_start_transaction(root, 1);
3806 return PTR_ERR(trans);
3808 i_size_write(inode, newsize);
3809 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
3810 ret = btrfs_update_inode(trans, root, inode);
3811 btrfs_end_transaction(trans, root);
3815 * We're truncating a file that used to have good data down to
3816 * zero. Make sure it gets into the ordered flush list so that
3817 * any new writes get down to disk quickly.
3820 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
3821 &BTRFS_I(inode)->runtime_flags);
3824 * 1 for the orphan item we're going to add
3825 * 1 for the orphan item deletion.
3827 trans = btrfs_start_transaction(root, 2);
3829 return PTR_ERR(trans);
3832 * We need to do this in case we fail at _any_ point during the
3833 * actual truncate. Once we do the truncate_setsize we could
3834 * invalidate pages which forces any outstanding ordered io to
3835 * be instantly completed which will give us extents that need
3836 * to be truncated. If we fail to get an orphan inode down we
3837 * could have left over extents that were never meant to live,
3838 * so we need to garuntee from this point on that everything
3839 * will be consistent.
3841 ret = btrfs_orphan_add(trans, inode);
3842 btrfs_end_transaction(trans, root);
3846 /* we don't support swapfiles, so vmtruncate shouldn't fail */
3847 truncate_setsize(inode, newsize);
3848 ret = btrfs_truncate(inode);
3849 if (ret && inode->i_nlink)
3850 btrfs_orphan_del(NULL, inode);
3856 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
3858 struct inode *inode = dentry->d_inode;
3859 struct btrfs_root *root = BTRFS_I(inode)->root;
3862 if (btrfs_root_readonly(root))
3865 err = inode_change_ok(inode, attr);
3869 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
3870 err = btrfs_setsize(inode, attr);
3875 if (attr->ia_valid) {
3876 setattr_copy(inode, attr);
3877 inode_inc_iversion(inode);
3878 err = btrfs_dirty_inode(inode);
3880 if (!err && attr->ia_valid & ATTR_MODE)
3881 err = btrfs_acl_chmod(inode);
3887 void btrfs_evict_inode(struct inode *inode)
3889 struct btrfs_trans_handle *trans;
3890 struct btrfs_root *root = BTRFS_I(inode)->root;
3891 struct btrfs_block_rsv *rsv, *global_rsv;
3892 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
3895 trace_btrfs_inode_evict(inode);
3897 truncate_inode_pages(&inode->i_data, 0);
3898 if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 ||
3899 btrfs_is_free_space_inode(inode)))
3902 if (is_bad_inode(inode)) {
3903 btrfs_orphan_del(NULL, inode);
3906 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
3907 btrfs_wait_ordered_range(inode, 0, (u64)-1);
3909 if (root->fs_info->log_root_recovering) {
3910 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3911 &BTRFS_I(inode)->runtime_flags));
3915 if (inode->i_nlink > 0) {
3916 BUG_ON(btrfs_root_refs(&root->root_item) != 0);
3920 ret = btrfs_commit_inode_delayed_inode(inode);
3922 btrfs_orphan_del(NULL, inode);
3926 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3928 btrfs_orphan_del(NULL, inode);
3931 rsv->size = min_size;
3933 global_rsv = &root->fs_info->global_block_rsv;
3935 btrfs_i_size_write(inode, 0);
3938 * This is a bit simpler than btrfs_truncate since we've already
3939 * reserved our space for our orphan item in the unlink, so we just
3940 * need to reserve some slack space in case we add bytes and update
3941 * inode item when doing the truncate.
3944 ret = btrfs_block_rsv_refill(root, rsv, min_size,
3945 BTRFS_RESERVE_FLUSH_LIMIT);
3948 * Try and steal from the global reserve since we will
3949 * likely not use this space anyway, we want to try as
3950 * hard as possible to get this to work.
3953 ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size);
3956 printk(KERN_WARNING "Could not get space for a "
3957 "delete, will truncate on mount %d\n", ret);
3958 btrfs_orphan_del(NULL, inode);
3959 btrfs_free_block_rsv(root, rsv);
3963 trans = btrfs_join_transaction(root);
3964 if (IS_ERR(trans)) {
3965 btrfs_orphan_del(NULL, inode);
3966 btrfs_free_block_rsv(root, rsv);
3970 trans->block_rsv = rsv;
3972 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
3976 trans->block_rsv = &root->fs_info->trans_block_rsv;
3977 btrfs_end_transaction(trans, root);
3979 btrfs_btree_balance_dirty(root);
3982 btrfs_free_block_rsv(root, rsv);
3985 trans->block_rsv = root->orphan_block_rsv;
3986 ret = btrfs_orphan_del(trans, inode);
3990 trans->block_rsv = &root->fs_info->trans_block_rsv;
3991 if (!(root == root->fs_info->tree_root ||
3992 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
3993 btrfs_return_ino(root, btrfs_ino(inode));
3995 btrfs_end_transaction(trans, root);
3996 btrfs_btree_balance_dirty(root);
4003 * this returns the key found in the dir entry in the location pointer.
4004 * If no dir entries were found, location->objectid is 0.
4006 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
4007 struct btrfs_key *location)
4009 const char *name = dentry->d_name.name;
4010 int namelen = dentry->d_name.len;
4011 struct btrfs_dir_item *di;
4012 struct btrfs_path *path;
4013 struct btrfs_root *root = BTRFS_I(dir)->root;
4016 path = btrfs_alloc_path();
4020 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
4025 if (IS_ERR_OR_NULL(di))
4028 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
4030 btrfs_free_path(path);
4033 location->objectid = 0;
4038 * when we hit a tree root in a directory, the btrfs part of the inode
4039 * needs to be changed to reflect the root directory of the tree root. This
4040 * is kind of like crossing a mount point.
4042 static int fixup_tree_root_location(struct btrfs_root *root,
4044 struct dentry *dentry,
4045 struct btrfs_key *location,
4046 struct btrfs_root **sub_root)
4048 struct btrfs_path *path;
4049 struct btrfs_root *new_root;
4050 struct btrfs_root_ref *ref;
4051 struct extent_buffer *leaf;
4055 path = btrfs_alloc_path();
4062 ret = btrfs_find_root_ref(root->fs_info->tree_root, path,
4063 BTRFS_I(dir)->root->root_key.objectid,
4064 location->objectid);
4071 leaf = path->nodes[0];
4072 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
4073 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
4074 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
4077 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
4078 (unsigned long)(ref + 1),
4079 dentry->d_name.len);
4083 btrfs_release_path(path);
4085 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
4086 if (IS_ERR(new_root)) {
4087 err = PTR_ERR(new_root);
4091 if (btrfs_root_refs(&new_root->root_item) == 0) {
4096 *sub_root = new_root;
4097 location->objectid = btrfs_root_dirid(&new_root->root_item);
4098 location->type = BTRFS_INODE_ITEM_KEY;
4099 location->offset = 0;
4102 btrfs_free_path(path);
4106 static void inode_tree_add(struct inode *inode)
4108 struct btrfs_root *root = BTRFS_I(inode)->root;
4109 struct btrfs_inode *entry;
4111 struct rb_node *parent;
4112 u64 ino = btrfs_ino(inode);
4114 p = &root->inode_tree.rb_node;
4117 if (inode_unhashed(inode))
4120 spin_lock(&root->inode_lock);
4123 entry = rb_entry(parent, struct btrfs_inode, rb_node);
4125 if (ino < btrfs_ino(&entry->vfs_inode))
4126 p = &parent->rb_left;
4127 else if (ino > btrfs_ino(&entry->vfs_inode))
4128 p = &parent->rb_right;
4130 WARN_ON(!(entry->vfs_inode.i_state &
4131 (I_WILL_FREE | I_FREEING)));
4132 rb_erase(parent, &root->inode_tree);
4133 RB_CLEAR_NODE(parent);
4134 spin_unlock(&root->inode_lock);
4138 rb_link_node(&BTRFS_I(inode)->rb_node, parent, p);
4139 rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4140 spin_unlock(&root->inode_lock);
4143 static void inode_tree_del(struct inode *inode)
4145 struct btrfs_root *root = BTRFS_I(inode)->root;
4148 spin_lock(&root->inode_lock);
4149 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
4150 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
4151 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
4152 empty = RB_EMPTY_ROOT(&root->inode_tree);
4154 spin_unlock(&root->inode_lock);
4157 * Free space cache has inodes in the tree root, but the tree root has a
4158 * root_refs of 0, so this could end up dropping the tree root as a
4159 * snapshot, so we need the extra !root->fs_info->tree_root check to
4160 * make sure we don't drop it.
4162 if (empty && btrfs_root_refs(&root->root_item) == 0 &&
4163 root != root->fs_info->tree_root) {
4164 synchronize_srcu(&root->fs_info->subvol_srcu);
4165 spin_lock(&root->inode_lock);
4166 empty = RB_EMPTY_ROOT(&root->inode_tree);
4167 spin_unlock(&root->inode_lock);
4169 btrfs_add_dead_root(root);
4173 void btrfs_invalidate_inodes(struct btrfs_root *root)
4175 struct rb_node *node;
4176 struct rb_node *prev;
4177 struct btrfs_inode *entry;
4178 struct inode *inode;
4181 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4183 spin_lock(&root->inode_lock);
4185 node = root->inode_tree.rb_node;
4189 entry = rb_entry(node, struct btrfs_inode, rb_node);
4191 if (objectid < btrfs_ino(&entry->vfs_inode))
4192 node = node->rb_left;
4193 else if (objectid > btrfs_ino(&entry->vfs_inode))
4194 node = node->rb_right;
4200 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4201 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
4205 prev = rb_next(prev);
4209 entry = rb_entry(node, struct btrfs_inode, rb_node);
4210 objectid = btrfs_ino(&entry->vfs_inode) + 1;
4211 inode = igrab(&entry->vfs_inode);
4213 spin_unlock(&root->inode_lock);
4214 if (atomic_read(&inode->i_count) > 1)
4215 d_prune_aliases(inode);
4217 * btrfs_drop_inode will have it removed from
4218 * the inode cache when its usage count
4223 spin_lock(&root->inode_lock);
4227 if (cond_resched_lock(&root->inode_lock))
4230 node = rb_next(node);
4232 spin_unlock(&root->inode_lock);
4235 static int btrfs_init_locked_inode(struct inode *inode, void *p)
4237 struct btrfs_iget_args *args = p;
4238 inode->i_ino = args->ino;
4239 BTRFS_I(inode)->root = args->root;
4243 static int btrfs_find_actor(struct inode *inode, void *opaque)
4245 struct btrfs_iget_args *args = opaque;
4246 return args->ino == btrfs_ino(inode) &&
4247 args->root == BTRFS_I(inode)->root;
4250 static struct inode *btrfs_iget_locked(struct super_block *s,
4252 struct btrfs_root *root)
4254 struct inode *inode;
4255 struct btrfs_iget_args args;
4256 args.ino = objectid;
4259 inode = iget5_locked(s, objectid, btrfs_find_actor,
4260 btrfs_init_locked_inode,
4265 /* Get an inode object given its location and corresponding root.
4266 * Returns in *is_new if the inode was read from disk
4268 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
4269 struct btrfs_root *root, int *new)
4271 struct inode *inode;
4273 inode = btrfs_iget_locked(s, location->objectid, root);
4275 return ERR_PTR(-ENOMEM);
4277 if (inode->i_state & I_NEW) {
4278 BTRFS_I(inode)->root = root;
4279 memcpy(&BTRFS_I(inode)->location, location, sizeof(*location));
4280 btrfs_read_locked_inode(inode);
4281 if (!is_bad_inode(inode)) {
4282 inode_tree_add(inode);
4283 unlock_new_inode(inode);
4287 unlock_new_inode(inode);
4289 inode = ERR_PTR(-ESTALE);
4296 static struct inode *new_simple_dir(struct super_block *s,
4297 struct btrfs_key *key,
4298 struct btrfs_root *root)
4300 struct inode *inode = new_inode(s);
4303 return ERR_PTR(-ENOMEM);
4305 BTRFS_I(inode)->root = root;
4306 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
4307 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
4309 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
4310 inode->i_op = &btrfs_dir_ro_inode_operations;
4311 inode->i_fop = &simple_dir_operations;
4312 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
4313 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4318 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
4320 struct inode *inode;
4321 struct btrfs_root *root = BTRFS_I(dir)->root;
4322 struct btrfs_root *sub_root = root;
4323 struct btrfs_key location;
4327 if (dentry->d_name.len > BTRFS_NAME_LEN)
4328 return ERR_PTR(-ENAMETOOLONG);
4330 if (unlikely(d_need_lookup(dentry))) {
4331 memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key));
4332 kfree(dentry->d_fsdata);
4333 dentry->d_fsdata = NULL;
4334 /* This thing is hashed, drop it for now */
4337 ret = btrfs_inode_by_name(dir, dentry, &location);
4341 return ERR_PTR(ret);
4343 if (location.objectid == 0)
4346 if (location.type == BTRFS_INODE_ITEM_KEY) {
4347 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
4351 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
4353 index = srcu_read_lock(&root->fs_info->subvol_srcu);
4354 ret = fixup_tree_root_location(root, dir, dentry,
4355 &location, &sub_root);
4358 inode = ERR_PTR(ret);
4360 inode = new_simple_dir(dir->i_sb, &location, sub_root);
4362 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
4364 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
4366 if (!IS_ERR(inode) && root != sub_root) {
4367 down_read(&root->fs_info->cleanup_work_sem);
4368 if (!(inode->i_sb->s_flags & MS_RDONLY))
4369 ret = btrfs_orphan_cleanup(sub_root);
4370 up_read(&root->fs_info->cleanup_work_sem);
4372 inode = ERR_PTR(ret);
4378 static int btrfs_dentry_delete(const struct dentry *dentry)
4380 struct btrfs_root *root;
4381 struct inode *inode = dentry->d_inode;
4383 if (!inode && !IS_ROOT(dentry))
4384 inode = dentry->d_parent->d_inode;
4387 root = BTRFS_I(inode)->root;
4388 if (btrfs_root_refs(&root->root_item) == 0)
4391 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
4397 static void btrfs_dentry_release(struct dentry *dentry)
4399 if (dentry->d_fsdata)
4400 kfree(dentry->d_fsdata);
4403 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
4408 ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry);
4409 if (unlikely(d_need_lookup(dentry))) {
4410 spin_lock(&dentry->d_lock);
4411 dentry->d_flags &= ~DCACHE_NEED_LOOKUP;
4412 spin_unlock(&dentry->d_lock);
4417 unsigned char btrfs_filetype_table[] = {
4418 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
4421 static int btrfs_real_readdir(struct file *filp, void *dirent,
4424 struct inode *inode = filp->f_dentry->d_inode;
4425 struct btrfs_root *root = BTRFS_I(inode)->root;
4426 struct btrfs_item *item;
4427 struct btrfs_dir_item *di;
4428 struct btrfs_key key;
4429 struct btrfs_key found_key;
4430 struct btrfs_path *path;
4431 struct list_head ins_list;
4432 struct list_head del_list;
4434 struct extent_buffer *leaf;
4436 unsigned char d_type;
4441 int key_type = BTRFS_DIR_INDEX_KEY;
4445 int is_curr = 0; /* filp->f_pos points to the current index? */
4447 /* FIXME, use a real flag for deciding about the key type */
4448 if (root->fs_info->tree_root == root)
4449 key_type = BTRFS_DIR_ITEM_KEY;
4451 /* special case for "." */
4452 if (filp->f_pos == 0) {
4453 over = filldir(dirent, ".", 1,
4454 filp->f_pos, btrfs_ino(inode), DT_DIR);
4459 /* special case for .., just use the back ref */
4460 if (filp->f_pos == 1) {
4461 u64 pino = parent_ino(filp->f_path.dentry);
4462 over = filldir(dirent, "..", 2,
4463 filp->f_pos, pino, DT_DIR);
4468 path = btrfs_alloc_path();
4474 if (key_type == BTRFS_DIR_INDEX_KEY) {
4475 INIT_LIST_HEAD(&ins_list);
4476 INIT_LIST_HEAD(&del_list);
4477 btrfs_get_delayed_items(inode, &ins_list, &del_list);
4480 btrfs_set_key_type(&key, key_type);
4481 key.offset = filp->f_pos;
4482 key.objectid = btrfs_ino(inode);
4484 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4489 leaf = path->nodes[0];
4490 slot = path->slots[0];
4491 if (slot >= btrfs_header_nritems(leaf)) {
4492 ret = btrfs_next_leaf(root, path);
4500 item = btrfs_item_nr(leaf, slot);
4501 btrfs_item_key_to_cpu(leaf, &found_key, slot);
4503 if (found_key.objectid != key.objectid)
4505 if (btrfs_key_type(&found_key) != key_type)
4507 if (found_key.offset < filp->f_pos)
4509 if (key_type == BTRFS_DIR_INDEX_KEY &&
4510 btrfs_should_delete_dir_index(&del_list,
4514 filp->f_pos = found_key.offset;
4517 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
4519 di_total = btrfs_item_size(leaf, item);
4521 while (di_cur < di_total) {
4522 struct btrfs_key location;
4524 if (verify_dir_item(root, leaf, di))
4527 name_len = btrfs_dir_name_len(leaf, di);
4528 if (name_len <= sizeof(tmp_name)) {
4529 name_ptr = tmp_name;
4531 name_ptr = kmalloc(name_len, GFP_NOFS);
4537 read_extent_buffer(leaf, name_ptr,
4538 (unsigned long)(di + 1), name_len);
4540 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
4541 btrfs_dir_item_key_to_cpu(leaf, di, &location);
4544 /* is this a reference to our own snapshot? If so
4547 * In contrast to old kernels, we insert the snapshot's
4548 * dir item and dir index after it has been created, so
4549 * we won't find a reference to our own snapshot. We
4550 * still keep the following code for backward
4553 if (location.type == BTRFS_ROOT_ITEM_KEY &&
4554 location.objectid == root->root_key.objectid) {
4558 over = filldir(dirent, name_ptr, name_len,
4559 found_key.offset, location.objectid,
4563 if (name_ptr != tmp_name)
4568 di_len = btrfs_dir_name_len(leaf, di) +
4569 btrfs_dir_data_len(leaf, di) + sizeof(*di);
4571 di = (struct btrfs_dir_item *)((char *)di + di_len);
4577 if (key_type == BTRFS_DIR_INDEX_KEY) {
4580 ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir,
4586 /* Reached end of directory/root. Bump pos past the last item. */
4587 if (key_type == BTRFS_DIR_INDEX_KEY)
4589 * 32-bit glibc will use getdents64, but then strtol -
4590 * so the last number we can serve is this.
4592 filp->f_pos = 0x7fffffff;
4598 if (key_type == BTRFS_DIR_INDEX_KEY)
4599 btrfs_put_delayed_items(&ins_list, &del_list);
4600 btrfs_free_path(path);
4604 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
4606 struct btrfs_root *root = BTRFS_I(inode)->root;
4607 struct btrfs_trans_handle *trans;
4609 bool nolock = false;
4611 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4614 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
4617 if (wbc->sync_mode == WB_SYNC_ALL) {
4619 trans = btrfs_join_transaction_nolock(root);
4621 trans = btrfs_join_transaction(root);
4623 return PTR_ERR(trans);
4624 ret = btrfs_commit_transaction(trans, root);
4630 * This is somewhat expensive, updating the tree every time the
4631 * inode changes. But, it is most likely to find the inode in cache.
4632 * FIXME, needs more benchmarking...there are no reasons other than performance
4633 * to keep or drop this code.
4635 int btrfs_dirty_inode(struct inode *inode)
4637 struct btrfs_root *root = BTRFS_I(inode)->root;
4638 struct btrfs_trans_handle *trans;
4641 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
4644 trans = btrfs_join_transaction(root);
4646 return PTR_ERR(trans);
4648 ret = btrfs_update_inode(trans, root, inode);
4649 if (ret && ret == -ENOSPC) {
4650 /* whoops, lets try again with the full transaction */
4651 btrfs_end_transaction(trans, root);
4652 trans = btrfs_start_transaction(root, 1);
4654 return PTR_ERR(trans);
4656 ret = btrfs_update_inode(trans, root, inode);
4658 btrfs_end_transaction(trans, root);
4659 if (BTRFS_I(inode)->delayed_node)
4660 btrfs_balance_delayed_items(root);
4666 * This is a copy of file_update_time. We need this so we can return error on
4667 * ENOSPC for updating the inode in the case of file write and mmap writes.
4669 static int btrfs_update_time(struct inode *inode, struct timespec *now,
4672 struct btrfs_root *root = BTRFS_I(inode)->root;
4674 if (btrfs_root_readonly(root))
4677 if (flags & S_VERSION)
4678 inode_inc_iversion(inode);
4679 if (flags & S_CTIME)
4680 inode->i_ctime = *now;
4681 if (flags & S_MTIME)
4682 inode->i_mtime = *now;
4683 if (flags & S_ATIME)
4684 inode->i_atime = *now;
4685 return btrfs_dirty_inode(inode);
4689 * find the highest existing sequence number in a directory
4690 * and then set the in-memory index_cnt variable to reflect
4691 * free sequence numbers
4693 static int btrfs_set_inode_index_count(struct inode *inode)
4695 struct btrfs_root *root = BTRFS_I(inode)->root;
4696 struct btrfs_key key, found_key;
4697 struct btrfs_path *path;
4698 struct extent_buffer *leaf;
4701 key.objectid = btrfs_ino(inode);
4702 btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY);
4703 key.offset = (u64)-1;
4705 path = btrfs_alloc_path();
4709 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4712 /* FIXME: we should be able to handle this */
4718 * MAGIC NUMBER EXPLANATION:
4719 * since we search a directory based on f_pos we have to start at 2
4720 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
4721 * else has to start at 2
4723 if (path->slots[0] == 0) {
4724 BTRFS_I(inode)->index_cnt = 2;
4730 leaf = path->nodes[0];
4731 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4733 if (found_key.objectid != btrfs_ino(inode) ||
4734 btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) {
4735 BTRFS_I(inode)->index_cnt = 2;
4739 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
4741 btrfs_free_path(path);
4746 * helper to find a free sequence number in a given directory. This current
4747 * code is very simple, later versions will do smarter things in the btree
4749 int btrfs_set_inode_index(struct inode *dir, u64 *index)
4753 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
4754 ret = btrfs_inode_delayed_dir_index_count(dir);
4756 ret = btrfs_set_inode_index_count(dir);
4762 *index = BTRFS_I(dir)->index_cnt;
4763 BTRFS_I(dir)->index_cnt++;
4768 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
4769 struct btrfs_root *root,
4771 const char *name, int name_len,
4772 u64 ref_objectid, u64 objectid,
4773 umode_t mode, u64 *index)
4775 struct inode *inode;
4776 struct btrfs_inode_item *inode_item;
4777 struct btrfs_key *location;
4778 struct btrfs_path *path;
4779 struct btrfs_inode_ref *ref;
4780 struct btrfs_key key[2];
4786 path = btrfs_alloc_path();
4788 return ERR_PTR(-ENOMEM);
4790 inode = new_inode(root->fs_info->sb);
4792 btrfs_free_path(path);
4793 return ERR_PTR(-ENOMEM);
4797 * we have to initialize this early, so we can reclaim the inode
4798 * number if we fail afterwards in this function.
4800 inode->i_ino = objectid;
4803 trace_btrfs_inode_request(dir);
4805 ret = btrfs_set_inode_index(dir, index);
4807 btrfs_free_path(path);
4809 return ERR_PTR(ret);
4813 * index_cnt is ignored for everything but a dir,
4814 * btrfs_get_inode_index_count has an explanation for the magic
4817 BTRFS_I(inode)->index_cnt = 2;
4818 BTRFS_I(inode)->root = root;
4819 BTRFS_I(inode)->generation = trans->transid;
4820 inode->i_generation = BTRFS_I(inode)->generation;
4823 * We could have gotten an inode number from somebody who was fsynced
4824 * and then removed in this same transaction, so let's just set full
4825 * sync since it will be a full sync anyway and this will blow away the
4826 * old info in the log.
4828 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
4835 key[0].objectid = objectid;
4836 btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY);
4840 * Start new inodes with an inode_ref. This is slightly more
4841 * efficient for small numbers of hard links since they will
4842 * be packed into one item. Extended refs will kick in if we
4843 * add more hard links than can fit in the ref item.
4845 key[1].objectid = objectid;
4846 btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY);
4847 key[1].offset = ref_objectid;
4849 sizes[0] = sizeof(struct btrfs_inode_item);
4850 sizes[1] = name_len + sizeof(*ref);
4852 path->leave_spinning = 1;
4853 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2);
4857 inode_init_owner(inode, dir, mode);
4858 inode_set_bytes(inode, 0);
4859 inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME;
4860 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
4861 struct btrfs_inode_item);
4862 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
4863 sizeof(*inode_item));
4864 fill_inode_item(trans, path->nodes[0], inode_item, inode);
4866 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
4867 struct btrfs_inode_ref);
4868 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
4869 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
4870 ptr = (unsigned long)(ref + 1);
4871 write_extent_buffer(path->nodes[0], name, ptr, name_len);
4873 btrfs_mark_buffer_dirty(path->nodes[0]);
4874 btrfs_free_path(path);
4876 location = &BTRFS_I(inode)->location;
4877 location->objectid = objectid;
4878 location->offset = 0;
4879 btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY);
4881 btrfs_inherit_iflags(inode, dir);
4883 if (S_ISREG(mode)) {
4884 if (btrfs_test_opt(root, NODATASUM))
4885 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
4886 if (btrfs_test_opt(root, NODATACOW))
4887 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
4890 insert_inode_hash(inode);
4891 inode_tree_add(inode);
4893 trace_btrfs_inode_new(inode);
4894 btrfs_set_inode_last_trans(trans, inode);
4896 btrfs_update_root_times(trans, root);
4901 BTRFS_I(dir)->index_cnt--;
4902 btrfs_free_path(path);
4904 return ERR_PTR(ret);
4907 static inline u8 btrfs_inode_type(struct inode *inode)
4909 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
4913 * utility function to add 'inode' into 'parent_inode' with
4914 * a give name and a given sequence number.
4915 * if 'add_backref' is true, also insert a backref from the
4916 * inode to the parent directory.
4918 int btrfs_add_link(struct btrfs_trans_handle *trans,
4919 struct inode *parent_inode, struct inode *inode,
4920 const char *name, int name_len, int add_backref, u64 index)
4923 struct btrfs_key key;
4924 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
4925 u64 ino = btrfs_ino(inode);
4926 u64 parent_ino = btrfs_ino(parent_inode);
4928 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4929 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
4932 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
4936 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4937 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
4938 key.objectid, root->root_key.objectid,
4939 parent_ino, index, name, name_len);
4940 } else if (add_backref) {
4941 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
4945 /* Nothing to clean up yet */
4949 ret = btrfs_insert_dir_item(trans, root, name, name_len,
4951 btrfs_inode_type(inode), index);
4952 if (ret == -EEXIST || ret == -EOVERFLOW)
4955 btrfs_abort_transaction(trans, root, ret);
4959 btrfs_i_size_write(parent_inode, parent_inode->i_size +
4961 inode_inc_iversion(parent_inode);
4962 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
4963 ret = btrfs_update_inode(trans, root, parent_inode);
4965 btrfs_abort_transaction(trans, root, ret);
4969 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
4972 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4973 key.objectid, root->root_key.objectid,
4974 parent_ino, &local_index, name, name_len);
4976 } else if (add_backref) {
4980 err = btrfs_del_inode_ref(trans, root, name, name_len,
4981 ino, parent_ino, &local_index);
4986 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
4987 struct inode *dir, struct dentry *dentry,
4988 struct inode *inode, int backref, u64 index)
4990 int err = btrfs_add_link(trans, dir, inode,
4991 dentry->d_name.name, dentry->d_name.len,
4998 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
4999 umode_t mode, dev_t rdev)
5001 struct btrfs_trans_handle *trans;
5002 struct btrfs_root *root = BTRFS_I(dir)->root;
5003 struct inode *inode = NULL;
5009 if (!new_valid_dev(rdev))
5013 * 2 for inode item and ref
5015 * 1 for xattr if selinux is on
5017 trans = btrfs_start_transaction(root, 5);
5019 return PTR_ERR(trans);
5021 err = btrfs_find_free_ino(root, &objectid);
5025 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5026 dentry->d_name.len, btrfs_ino(dir), objectid,
5028 if (IS_ERR(inode)) {
5029 err = PTR_ERR(inode);
5033 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5040 * If the active LSM wants to access the inode during
5041 * d_instantiate it needs these. Smack checks to see
5042 * if the filesystem supports xattrs by looking at the
5046 inode->i_op = &btrfs_special_inode_operations;
5047 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5051 init_special_inode(inode, inode->i_mode, rdev);
5052 btrfs_update_inode(trans, root, inode);
5053 d_instantiate(dentry, inode);
5056 btrfs_end_transaction(trans, root);
5057 btrfs_btree_balance_dirty(root);
5059 inode_dec_link_count(inode);
5065 static int btrfs_create(struct inode *dir, struct dentry *dentry,
5066 umode_t mode, bool excl)
5068 struct btrfs_trans_handle *trans;
5069 struct btrfs_root *root = BTRFS_I(dir)->root;
5070 struct inode *inode = NULL;
5071 int drop_inode_on_err = 0;
5077 * 2 for inode item and ref
5079 * 1 for xattr if selinux is on
5081 trans = btrfs_start_transaction(root, 5);
5083 return PTR_ERR(trans);
5085 err = btrfs_find_free_ino(root, &objectid);
5089 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5090 dentry->d_name.len, btrfs_ino(dir), objectid,
5092 if (IS_ERR(inode)) {
5093 err = PTR_ERR(inode);
5096 drop_inode_on_err = 1;
5098 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5102 err = btrfs_update_inode(trans, root, inode);
5107 * If the active LSM wants to access the inode during
5108 * d_instantiate it needs these. Smack checks to see
5109 * if the filesystem supports xattrs by looking at the
5112 inode->i_fop = &btrfs_file_operations;
5113 inode->i_op = &btrfs_file_inode_operations;
5115 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
5119 inode->i_mapping->a_ops = &btrfs_aops;
5120 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
5121 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
5122 d_instantiate(dentry, inode);
5125 btrfs_end_transaction(trans, root);
5126 if (err && drop_inode_on_err) {
5127 inode_dec_link_count(inode);
5130 btrfs_btree_balance_dirty(root);
5134 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
5135 struct dentry *dentry)
5137 struct btrfs_trans_handle *trans;
5138 struct btrfs_root *root = BTRFS_I(dir)->root;
5139 struct inode *inode = old_dentry->d_inode;
5144 /* do not allow sys_link's with other subvols of the same device */
5145 if (root->objectid != BTRFS_I(inode)->root->objectid)
5148 if (inode->i_nlink >= BTRFS_LINK_MAX)
5151 err = btrfs_set_inode_index(dir, &index);
5156 * 2 items for inode and inode ref
5157 * 2 items for dir items
5158 * 1 item for parent inode
5160 trans = btrfs_start_transaction(root, 5);
5161 if (IS_ERR(trans)) {
5162 err = PTR_ERR(trans);
5166 btrfs_inc_nlink(inode);
5167 inode_inc_iversion(inode);
5168 inode->i_ctime = CURRENT_TIME;
5170 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
5172 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
5177 struct dentry *parent = dentry->d_parent;
5178 err = btrfs_update_inode(trans, root, inode);
5181 d_instantiate(dentry, inode);
5182 btrfs_log_new_name(trans, inode, NULL, parent);
5185 btrfs_end_transaction(trans, root);
5188 inode_dec_link_count(inode);
5191 btrfs_btree_balance_dirty(root);
5195 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
5197 struct inode *inode = NULL;
5198 struct btrfs_trans_handle *trans;
5199 struct btrfs_root *root = BTRFS_I(dir)->root;
5201 int drop_on_err = 0;
5206 * 2 items for inode and ref
5207 * 2 items for dir items
5208 * 1 for xattr if selinux is on
5210 trans = btrfs_start_transaction(root, 5);
5212 return PTR_ERR(trans);
5214 err = btrfs_find_free_ino(root, &objectid);
5218 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
5219 dentry->d_name.len, btrfs_ino(dir), objectid,
5220 S_IFDIR | mode, &index);
5221 if (IS_ERR(inode)) {
5222 err = PTR_ERR(inode);
5228 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
5232 inode->i_op = &btrfs_dir_inode_operations;
5233 inode->i_fop = &btrfs_dir_file_operations;
5235 btrfs_i_size_write(inode, 0);
5236 err = btrfs_update_inode(trans, root, inode);
5240 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
5241 dentry->d_name.len, 0, index);
5245 d_instantiate(dentry, inode);
5249 btrfs_end_transaction(trans, root);
5252 btrfs_btree_balance_dirty(root);
5256 /* helper for btfs_get_extent. Given an existing extent in the tree,
5257 * and an extent that you want to insert, deal with overlap and insert
5258 * the new extent into the tree.
5260 static int merge_extent_mapping(struct extent_map_tree *em_tree,
5261 struct extent_map *existing,
5262 struct extent_map *em,
5263 u64 map_start, u64 map_len)
5267 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
5268 start_diff = map_start - em->start;
5269 em->start = map_start;
5271 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
5272 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
5273 em->block_start += start_diff;
5274 em->block_len -= start_diff;
5276 return add_extent_mapping(em_tree, em);
5279 static noinline int uncompress_inline(struct btrfs_path *path,
5280 struct inode *inode, struct page *page,
5281 size_t pg_offset, u64 extent_offset,
5282 struct btrfs_file_extent_item *item)
5285 struct extent_buffer *leaf = path->nodes[0];
5288 unsigned long inline_size;
5292 WARN_ON(pg_offset != 0);
5293 compress_type = btrfs_file_extent_compression(leaf, item);
5294 max_size = btrfs_file_extent_ram_bytes(leaf, item);
5295 inline_size = btrfs_file_extent_inline_item_len(leaf,
5296 btrfs_item_nr(leaf, path->slots[0]));
5297 tmp = kmalloc(inline_size, GFP_NOFS);
5300 ptr = btrfs_file_extent_inline_start(item);
5302 read_extent_buffer(leaf, tmp, ptr, inline_size);
5304 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
5305 ret = btrfs_decompress(compress_type, tmp, page,
5306 extent_offset, inline_size, max_size);
5308 char *kaddr = kmap_atomic(page);
5309 unsigned long copy_size = min_t(u64,
5310 PAGE_CACHE_SIZE - pg_offset,
5311 max_size - extent_offset);
5312 memset(kaddr + pg_offset, 0, copy_size);
5313 kunmap_atomic(kaddr);
5320 * a bit scary, this does extent mapping from logical file offset to the disk.
5321 * the ugly parts come from merging extents from the disk with the in-ram
5322 * representation. This gets more complex because of the data=ordered code,
5323 * where the in-ram extents might be locked pending data=ordered completion.
5325 * This also copies inline extents directly into the page.
5328 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
5329 size_t pg_offset, u64 start, u64 len,
5335 u64 extent_start = 0;
5337 u64 objectid = btrfs_ino(inode);
5339 struct btrfs_path *path = NULL;
5340 struct btrfs_root *root = BTRFS_I(inode)->root;
5341 struct btrfs_file_extent_item *item;
5342 struct extent_buffer *leaf;
5343 struct btrfs_key found_key;
5344 struct extent_map *em = NULL;
5345 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5346 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5347 struct btrfs_trans_handle *trans = NULL;
5351 read_lock(&em_tree->lock);
5352 em = lookup_extent_mapping(em_tree, start, len);
5354 em->bdev = root->fs_info->fs_devices->latest_bdev;
5355 read_unlock(&em_tree->lock);
5358 if (em->start > start || em->start + em->len <= start)
5359 free_extent_map(em);
5360 else if (em->block_start == EXTENT_MAP_INLINE && page)
5361 free_extent_map(em);
5365 em = alloc_extent_map();
5370 em->bdev = root->fs_info->fs_devices->latest_bdev;
5371 em->start = EXTENT_MAP_HOLE;
5372 em->orig_start = EXTENT_MAP_HOLE;
5374 em->block_len = (u64)-1;
5377 path = btrfs_alloc_path();
5383 * Chances are we'll be called again, so go ahead and do
5389 ret = btrfs_lookup_file_extent(trans, root, path,
5390 objectid, start, trans != NULL);
5397 if (path->slots[0] == 0)
5402 leaf = path->nodes[0];
5403 item = btrfs_item_ptr(leaf, path->slots[0],
5404 struct btrfs_file_extent_item);
5405 /* are we inside the extent that was found? */
5406 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5407 found_type = btrfs_key_type(&found_key);
5408 if (found_key.objectid != objectid ||
5409 found_type != BTRFS_EXTENT_DATA_KEY) {
5413 found_type = btrfs_file_extent_type(leaf, item);
5414 extent_start = found_key.offset;
5415 compress_type = btrfs_file_extent_compression(leaf, item);
5416 if (found_type == BTRFS_FILE_EXTENT_REG ||
5417 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5418 extent_end = extent_start +
5419 btrfs_file_extent_num_bytes(leaf, item);
5420 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5422 size = btrfs_file_extent_inline_len(leaf, item);
5423 extent_end = (extent_start + size + root->sectorsize - 1) &
5424 ~((u64)root->sectorsize - 1);
5427 if (start >= extent_end) {
5429 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
5430 ret = btrfs_next_leaf(root, path);
5437 leaf = path->nodes[0];
5439 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5440 if (found_key.objectid != objectid ||
5441 found_key.type != BTRFS_EXTENT_DATA_KEY)
5443 if (start + len <= found_key.offset)
5446 em->orig_start = start;
5447 em->len = found_key.offset - start;
5451 if (found_type == BTRFS_FILE_EXTENT_REG ||
5452 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
5453 em->start = extent_start;
5454 em->len = extent_end - extent_start;
5455 em->orig_start = extent_start -
5456 btrfs_file_extent_offset(leaf, item);
5457 em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf,
5459 bytenr = btrfs_file_extent_disk_bytenr(leaf, item);
5461 em->block_start = EXTENT_MAP_HOLE;
5464 if (compress_type != BTRFS_COMPRESS_NONE) {
5465 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5466 em->compress_type = compress_type;
5467 em->block_start = bytenr;
5468 em->block_len = em->orig_block_len;
5470 bytenr += btrfs_file_extent_offset(leaf, item);
5471 em->block_start = bytenr;
5472 em->block_len = em->len;
5473 if (found_type == BTRFS_FILE_EXTENT_PREALLOC)
5474 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5477 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
5481 size_t extent_offset;
5484 em->block_start = EXTENT_MAP_INLINE;
5485 if (!page || create) {
5486 em->start = extent_start;
5487 em->len = extent_end - extent_start;
5491 size = btrfs_file_extent_inline_len(leaf, item);
5492 extent_offset = page_offset(page) + pg_offset - extent_start;
5493 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
5494 size - extent_offset);
5495 em->start = extent_start + extent_offset;
5496 em->len = (copy_size + root->sectorsize - 1) &
5497 ~((u64)root->sectorsize - 1);
5498 em->orig_block_len = em->len;
5499 em->orig_start = em->start;
5500 if (compress_type) {
5501 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
5502 em->compress_type = compress_type;
5504 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
5505 if (create == 0 && !PageUptodate(page)) {
5506 if (btrfs_file_extent_compression(leaf, item) !=
5507 BTRFS_COMPRESS_NONE) {
5508 ret = uncompress_inline(path, inode, page,
5510 extent_offset, item);
5511 BUG_ON(ret); /* -ENOMEM */
5514 read_extent_buffer(leaf, map + pg_offset, ptr,
5516 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
5517 memset(map + pg_offset + copy_size, 0,
5518 PAGE_CACHE_SIZE - pg_offset -
5523 flush_dcache_page(page);
5524 } else if (create && PageUptodate(page)) {
5528 free_extent_map(em);
5531 btrfs_release_path(path);
5532 trans = btrfs_join_transaction(root);
5535 return ERR_CAST(trans);
5539 write_extent_buffer(leaf, map + pg_offset, ptr,
5542 btrfs_mark_buffer_dirty(leaf);
5544 set_extent_uptodate(io_tree, em->start,
5545 extent_map_end(em) - 1, NULL, GFP_NOFS);
5548 WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type);
5552 em->orig_start = start;
5555 em->block_start = EXTENT_MAP_HOLE;
5556 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
5558 btrfs_release_path(path);
5559 if (em->start > start || extent_map_end(em) <= start) {
5560 printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed "
5561 "[%llu %llu]\n", (unsigned long long)em->start,
5562 (unsigned long long)em->len,
5563 (unsigned long long)start,
5564 (unsigned long long)len);
5570 write_lock(&em_tree->lock);
5571 ret = add_extent_mapping(em_tree, em);
5572 /* it is possible that someone inserted the extent into the tree
5573 * while we had the lock dropped. It is also possible that
5574 * an overlapping map exists in the tree
5576 if (ret == -EEXIST) {
5577 struct extent_map *existing;
5581 existing = lookup_extent_mapping(em_tree, start, len);
5582 if (existing && (existing->start > start ||
5583 existing->start + existing->len <= start)) {
5584 free_extent_map(existing);
5588 existing = lookup_extent_mapping(em_tree, em->start,
5591 err = merge_extent_mapping(em_tree, existing,
5594 free_extent_map(existing);
5596 free_extent_map(em);
5601 free_extent_map(em);
5605 free_extent_map(em);
5610 write_unlock(&em_tree->lock);
5614 trace_btrfs_get_extent(root, em);
5617 btrfs_free_path(path);
5619 ret = btrfs_end_transaction(trans, root);
5624 free_extent_map(em);
5625 return ERR_PTR(err);
5627 BUG_ON(!em); /* Error is always set */
5631 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
5632 size_t pg_offset, u64 start, u64 len,
5635 struct extent_map *em;
5636 struct extent_map *hole_em = NULL;
5637 u64 range_start = start;
5643 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
5650 * - a pre-alloc extent,
5651 * there might actually be delalloc bytes behind it.
5653 if (em->block_start != EXTENT_MAP_HOLE &&
5654 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
5660 /* check to see if we've wrapped (len == -1 or similar) */
5669 /* ok, we didn't find anything, lets look for delalloc */
5670 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
5671 end, len, EXTENT_DELALLOC, 1);
5672 found_end = range_start + found;
5673 if (found_end < range_start)
5674 found_end = (u64)-1;
5677 * we didn't find anything useful, return
5678 * the original results from get_extent()
5680 if (range_start > end || found_end <= start) {
5686 /* adjust the range_start to make sure it doesn't
5687 * go backwards from the start they passed in
5689 range_start = max(start,range_start);
5690 found = found_end - range_start;
5693 u64 hole_start = start;
5696 em = alloc_extent_map();
5702 * when btrfs_get_extent can't find anything it
5703 * returns one huge hole
5705 * make sure what it found really fits our range, and
5706 * adjust to make sure it is based on the start from
5710 u64 calc_end = extent_map_end(hole_em);
5712 if (calc_end <= start || (hole_em->start > end)) {
5713 free_extent_map(hole_em);
5716 hole_start = max(hole_em->start, start);
5717 hole_len = calc_end - hole_start;
5721 if (hole_em && range_start > hole_start) {
5722 /* our hole starts before our delalloc, so we
5723 * have to return just the parts of the hole
5724 * that go until the delalloc starts
5726 em->len = min(hole_len,
5727 range_start - hole_start);
5728 em->start = hole_start;
5729 em->orig_start = hole_start;
5731 * don't adjust block start at all,
5732 * it is fixed at EXTENT_MAP_HOLE
5734 em->block_start = hole_em->block_start;
5735 em->block_len = hole_len;
5736 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
5737 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
5739 em->start = range_start;
5741 em->orig_start = range_start;
5742 em->block_start = EXTENT_MAP_DELALLOC;
5743 em->block_len = found;
5745 } else if (hole_em) {
5750 free_extent_map(hole_em);
5752 free_extent_map(em);
5753 return ERR_PTR(err);
5758 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
5761 struct btrfs_root *root = BTRFS_I(inode)->root;
5762 struct btrfs_trans_handle *trans;
5763 struct extent_map *em;
5764 struct btrfs_key ins;
5768 trans = btrfs_join_transaction(root);
5770 return ERR_CAST(trans);
5772 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
5774 alloc_hint = get_extent_allocation_hint(inode, start, len);
5775 ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0,
5776 alloc_hint, &ins, 1);
5782 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
5783 ins.offset, ins.offset, 0);
5787 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
5788 ins.offset, ins.offset, 0);
5790 btrfs_free_reserved_extent(root, ins.objectid, ins.offset);
5794 btrfs_end_transaction(trans, root);
5799 * returns 1 when the nocow is safe, < 1 on error, 0 if the
5800 * block must be cow'd
5802 static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans,
5803 struct inode *inode, u64 offset, u64 len)
5805 struct btrfs_path *path;
5807 struct extent_buffer *leaf;
5808 struct btrfs_root *root = BTRFS_I(inode)->root;
5809 struct btrfs_file_extent_item *fi;
5810 struct btrfs_key key;
5818 path = btrfs_alloc_path();
5822 ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode),
5827 slot = path->slots[0];
5830 /* can't find the item, must cow */
5837 leaf = path->nodes[0];
5838 btrfs_item_key_to_cpu(leaf, &key, slot);
5839 if (key.objectid != btrfs_ino(inode) ||
5840 key.type != BTRFS_EXTENT_DATA_KEY) {
5841 /* not our file or wrong item type, must cow */
5845 if (key.offset > offset) {
5846 /* Wrong offset, must cow */
5850 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
5851 found_type = btrfs_file_extent_type(leaf, fi);
5852 if (found_type != BTRFS_FILE_EXTENT_REG &&
5853 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
5854 /* not a regular extent, must cow */
5857 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
5858 backref_offset = btrfs_file_extent_offset(leaf, fi);
5860 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
5861 if (extent_end < offset + len) {
5862 /* extent doesn't include our full range, must cow */
5866 if (btrfs_extent_readonly(root, disk_bytenr))
5870 * look for other files referencing this extent, if we
5871 * find any we must cow
5873 if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
5874 key.offset - backref_offset, disk_bytenr))
5878 * adjust disk_bytenr and num_bytes to cover just the bytes
5879 * in this extent we are about to write. If there
5880 * are any csums in that range we have to cow in order
5881 * to keep the csums correct
5883 disk_bytenr += backref_offset;
5884 disk_bytenr += offset - key.offset;
5885 num_bytes = min(offset + len, extent_end) - offset;
5886 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
5889 * all of the above have passed, it is safe to overwrite this extent
5894 btrfs_free_path(path);
5898 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
5899 struct extent_state **cached_state, int writing)
5901 struct btrfs_ordered_extent *ordered;
5905 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5908 * We're concerned with the entire range that we're going to be
5909 * doing DIO to, so we need to make sure theres no ordered
5910 * extents in this range.
5912 ordered = btrfs_lookup_ordered_range(inode, lockstart,
5913 lockend - lockstart + 1);
5916 * We need to make sure there are no buffered pages in this
5917 * range either, we could have raced between the invalidate in
5918 * generic_file_direct_write and locking the extent. The
5919 * invalidate needs to happen so that reads after a write do not
5922 if (!ordered && (!writing ||
5923 !test_range_bit(&BTRFS_I(inode)->io_tree,
5924 lockstart, lockend, EXTENT_UPTODATE, 0,
5928 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
5929 cached_state, GFP_NOFS);
5932 btrfs_start_ordered_extent(inode, ordered, 1);
5933 btrfs_put_ordered_extent(ordered);
5935 /* Screw you mmap */
5936 ret = filemap_write_and_wait_range(inode->i_mapping,
5943 * If we found a page that couldn't be invalidated just
5944 * fall back to buffered.
5946 ret = invalidate_inode_pages2_range(inode->i_mapping,
5947 lockstart >> PAGE_CACHE_SHIFT,
5948 lockend >> PAGE_CACHE_SHIFT);
5959 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
5960 u64 len, u64 orig_start,
5961 u64 block_start, u64 block_len,
5962 u64 orig_block_len, int type)
5964 struct extent_map_tree *em_tree;
5965 struct extent_map *em;
5966 struct btrfs_root *root = BTRFS_I(inode)->root;
5969 em_tree = &BTRFS_I(inode)->extent_tree;
5970 em = alloc_extent_map();
5972 return ERR_PTR(-ENOMEM);
5975 em->orig_start = orig_start;
5976 em->mod_start = start;
5979 em->block_len = block_len;
5980 em->block_start = block_start;
5981 em->bdev = root->fs_info->fs_devices->latest_bdev;
5982 em->orig_block_len = orig_block_len;
5983 em->generation = -1;
5984 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5985 if (type == BTRFS_ORDERED_PREALLOC)
5986 set_bit(EXTENT_FLAG_FILLING, &em->flags);
5989 btrfs_drop_extent_cache(inode, em->start,
5990 em->start + em->len - 1, 0);
5991 write_lock(&em_tree->lock);
5992 ret = add_extent_mapping(em_tree, em);
5994 list_move(&em->list,
5995 &em_tree->modified_extents);
5996 write_unlock(&em_tree->lock);
5997 } while (ret == -EEXIST);
6000 free_extent_map(em);
6001 return ERR_PTR(ret);
6008 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
6009 struct buffer_head *bh_result, int create)
6011 struct extent_map *em;
6012 struct btrfs_root *root = BTRFS_I(inode)->root;
6013 struct extent_state *cached_state = NULL;
6014 u64 start = iblock << inode->i_blkbits;
6015 u64 lockstart, lockend;
6016 u64 len = bh_result->b_size;
6017 struct btrfs_trans_handle *trans;
6018 int unlock_bits = EXTENT_LOCKED;
6022 ret = btrfs_delalloc_reserve_space(inode, len);
6025 unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY;
6027 len = min_t(u64, len, root->sectorsize);
6031 lockend = start + len - 1;
6034 * If this errors out it's because we couldn't invalidate pagecache for
6035 * this range and we need to fallback to buffered.
6037 if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create))
6041 ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6042 lockend, EXTENT_DELALLOC, NULL,
6043 &cached_state, GFP_NOFS);
6048 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
6055 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
6056 * io. INLINE is special, and we could probably kludge it in here, but
6057 * it's still buffered so for safety lets just fall back to the generic
6060 * For COMPRESSED we _have_ to read the entire extent in so we can
6061 * decompress it, so there will be buffering required no matter what we
6062 * do, so go ahead and fallback to buffered.
6064 * We return -ENOTBLK because thats what makes DIO go ahead and go back
6065 * to buffered IO. Don't blame me, this is the price we pay for using
6068 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
6069 em->block_start == EXTENT_MAP_INLINE) {
6070 free_extent_map(em);
6075 /* Just a good old fashioned hole, return */
6076 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
6077 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
6078 free_extent_map(em);
6084 * We don't allocate a new extent in the following cases
6086 * 1) The inode is marked as NODATACOW. In this case we'll just use the
6088 * 2) The extent is marked as PREALLOC. We're good to go here and can
6089 * just use the extent.
6093 len = min(len, em->len - (start - em->start));
6094 lockstart = start + len;
6098 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
6099 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
6100 em->block_start != EXTENT_MAP_HOLE)) {
6105 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6106 type = BTRFS_ORDERED_PREALLOC;
6108 type = BTRFS_ORDERED_NOCOW;
6109 len = min(len, em->len - (start - em->start));
6110 block_start = em->block_start + (start - em->start);
6113 * we're not going to log anything, but we do need
6114 * to make sure the current transaction stays open
6115 * while we look for nocow cross refs
6117 trans = btrfs_join_transaction(root);
6121 if (can_nocow_odirect(trans, inode, start, len) == 1) {
6122 u64 orig_start = em->orig_start;
6123 u64 orig_block_len = em->orig_block_len;
6125 if (type == BTRFS_ORDERED_PREALLOC) {
6126 free_extent_map(em);
6127 em = create_pinned_em(inode, start, len,
6130 orig_block_len, type);
6132 btrfs_end_transaction(trans, root);
6137 ret = btrfs_add_ordered_extent_dio(inode, start,
6138 block_start, len, len, type);
6139 btrfs_end_transaction(trans, root);
6141 free_extent_map(em);
6146 btrfs_end_transaction(trans, root);
6150 * this will cow the extent, reset the len in case we changed
6153 len = bh_result->b_size;
6154 free_extent_map(em);
6155 em = btrfs_new_extent_direct(inode, start, len);
6160 len = min(len, em->len - (start - em->start));
6162 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
6164 bh_result->b_size = len;
6165 bh_result->b_bdev = em->bdev;
6166 set_buffer_mapped(bh_result);
6168 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6169 set_buffer_new(bh_result);
6172 * Need to update the i_size under the extent lock so buffered
6173 * readers will get the updated i_size when we unlock.
6175 if (start + len > i_size_read(inode))
6176 i_size_write(inode, start + len);
6180 * In the case of write we need to clear and unlock the entire range,
6181 * in the case of read we need to unlock only the end area that we
6182 * aren't using if there is any left over space.
6184 if (lockstart < lockend) {
6185 if (create && len < lockend - lockstart) {
6186 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6187 lockstart + len - 1,
6188 unlock_bits | EXTENT_DEFRAG, 1, 0,
6189 &cached_state, GFP_NOFS);
6191 * Beside unlock, we also need to cleanup reserved space
6192 * for the left range by attaching EXTENT_DO_ACCOUNTING.
6194 clear_extent_bit(&BTRFS_I(inode)->io_tree,
6195 lockstart + len, lockend,
6196 unlock_bits | EXTENT_DO_ACCOUNTING |
6197 EXTENT_DEFRAG, 1, 0, NULL, GFP_NOFS);
6199 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
6200 lockend, unlock_bits, 1, 0,
6201 &cached_state, GFP_NOFS);
6204 free_extent_state(cached_state);
6207 free_extent_map(em);
6213 unlock_bits |= EXTENT_DO_ACCOUNTING;
6215 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6216 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
6220 struct btrfs_dio_private {
6221 struct inode *inode;
6227 /* number of bios pending for this dio */
6228 atomic_t pending_bios;
6233 struct bio *orig_bio;
6236 static void btrfs_endio_direct_read(struct bio *bio, int err)
6238 struct btrfs_dio_private *dip = bio->bi_private;
6239 struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1;
6240 struct bio_vec *bvec = bio->bi_io_vec;
6241 struct inode *inode = dip->inode;
6242 struct btrfs_root *root = BTRFS_I(inode)->root;
6245 start = dip->logical_offset;
6247 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
6248 struct page *page = bvec->bv_page;
6251 u64 private = ~(u32)0;
6252 unsigned long flags;
6254 if (get_state_private(&BTRFS_I(inode)->io_tree,
6257 local_irq_save(flags);
6258 kaddr = kmap_atomic(page);
6259 csum = btrfs_csum_data(root, kaddr + bvec->bv_offset,
6260 csum, bvec->bv_len);
6261 btrfs_csum_final(csum, (char *)&csum);
6262 kunmap_atomic(kaddr);
6263 local_irq_restore(flags);
6265 flush_dcache_page(bvec->bv_page);
6266 if (csum != private) {
6268 printk(KERN_ERR "btrfs csum failed ino %llu off"
6269 " %llu csum %u private %u\n",
6270 (unsigned long long)btrfs_ino(inode),
6271 (unsigned long long)start,
6272 csum, (unsigned)private);
6277 start += bvec->bv_len;
6279 } while (bvec <= bvec_end);
6281 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
6282 dip->logical_offset + dip->bytes - 1);
6283 bio->bi_private = dip->private;
6287 /* If we had a csum failure make sure to clear the uptodate flag */
6289 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6290 dio_end_io(bio, err);
6293 static void btrfs_endio_direct_write(struct bio *bio, int err)
6295 struct btrfs_dio_private *dip = bio->bi_private;
6296 struct inode *inode = dip->inode;
6297 struct btrfs_root *root = BTRFS_I(inode)->root;
6298 struct btrfs_ordered_extent *ordered = NULL;
6299 u64 ordered_offset = dip->logical_offset;
6300 u64 ordered_bytes = dip->bytes;
6306 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
6308 ordered_bytes, !err);
6312 ordered->work.func = finish_ordered_fn;
6313 ordered->work.flags = 0;
6314 btrfs_queue_worker(&root->fs_info->endio_write_workers,
6318 * our bio might span multiple ordered extents. If we haven't
6319 * completed the accounting for the whole dio, go back and try again
6321 if (ordered_offset < dip->logical_offset + dip->bytes) {
6322 ordered_bytes = dip->logical_offset + dip->bytes -
6328 bio->bi_private = dip->private;
6332 /* If we had an error make sure to clear the uptodate flag */
6334 clear_bit(BIO_UPTODATE, &bio->bi_flags);
6335 dio_end_io(bio, err);
6338 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
6339 struct bio *bio, int mirror_num,
6340 unsigned long bio_flags, u64 offset)
6343 struct btrfs_root *root = BTRFS_I(inode)->root;
6344 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
6345 BUG_ON(ret); /* -ENOMEM */
6349 static void btrfs_end_dio_bio(struct bio *bio, int err)
6351 struct btrfs_dio_private *dip = bio->bi_private;
6354 printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu "
6355 "sector %#Lx len %u err no %d\n",
6356 (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw,
6357 (unsigned long long)bio->bi_sector, bio->bi_size, err);
6361 * before atomic variable goto zero, we must make sure
6362 * dip->errors is perceived to be set.
6364 smp_mb__before_atomic_dec();
6367 /* if there are more bios still pending for this dio, just exit */
6368 if (!atomic_dec_and_test(&dip->pending_bios))
6372 bio_io_error(dip->orig_bio);
6374 set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags);
6375 bio_endio(dip->orig_bio, 0);
6381 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
6382 u64 first_sector, gfp_t gfp_flags)
6384 int nr_vecs = bio_get_nr_vecs(bdev);
6385 return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags);
6388 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
6389 int rw, u64 file_offset, int skip_sum,
6392 int write = rw & REQ_WRITE;
6393 struct btrfs_root *root = BTRFS_I(inode)->root;
6397 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
6402 ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0);
6410 if (write && async_submit) {
6411 ret = btrfs_wq_submit_bio(root->fs_info,
6412 inode, rw, bio, 0, 0,
6414 __btrfs_submit_bio_start_direct_io,
6415 __btrfs_submit_bio_done);
6419 * If we aren't doing async submit, calculate the csum of the
6422 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
6425 } else if (!skip_sum) {
6426 ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset);
6432 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
6438 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
6441 struct inode *inode = dip->inode;
6442 struct btrfs_root *root = BTRFS_I(inode)->root;
6444 struct bio *orig_bio = dip->orig_bio;
6445 struct bio_vec *bvec = orig_bio->bi_io_vec;
6446 u64 start_sector = orig_bio->bi_sector;
6447 u64 file_offset = dip->logical_offset;
6452 int async_submit = 0;
6454 map_length = orig_bio->bi_size;
6455 ret = btrfs_map_block(root->fs_info, READ, start_sector << 9,
6456 &map_length, NULL, 0);
6462 if (map_length >= orig_bio->bi_size) {
6468 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
6471 bio->bi_private = dip;
6472 bio->bi_end_io = btrfs_end_dio_bio;
6473 atomic_inc(&dip->pending_bios);
6475 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
6476 if (unlikely(map_length < submit_len + bvec->bv_len ||
6477 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
6478 bvec->bv_offset) < bvec->bv_len)) {
6480 * inc the count before we submit the bio so
6481 * we know the end IO handler won't happen before
6482 * we inc the count. Otherwise, the dip might get freed
6483 * before we're done setting it up
6485 atomic_inc(&dip->pending_bios);
6486 ret = __btrfs_submit_dio_bio(bio, inode, rw,
6487 file_offset, skip_sum,
6491 atomic_dec(&dip->pending_bios);
6495 start_sector += submit_len >> 9;
6496 file_offset += submit_len;
6501 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
6502 start_sector, GFP_NOFS);
6505 bio->bi_private = dip;
6506 bio->bi_end_io = btrfs_end_dio_bio;
6508 map_length = orig_bio->bi_size;
6509 ret = btrfs_map_block(root->fs_info, READ,
6511 &map_length, NULL, 0);
6517 submit_len += bvec->bv_len;
6524 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
6533 * before atomic variable goto zero, we must
6534 * make sure dip->errors is perceived to be set.
6536 smp_mb__before_atomic_dec();
6537 if (atomic_dec_and_test(&dip->pending_bios))
6538 bio_io_error(dip->orig_bio);
6540 /* bio_end_io() will handle error, so we needn't return it */
6544 static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode,
6547 struct btrfs_root *root = BTRFS_I(inode)->root;
6548 struct btrfs_dio_private *dip;
6549 struct bio_vec *bvec = bio->bi_io_vec;
6551 int write = rw & REQ_WRITE;
6554 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
6556 dip = kmalloc(sizeof(*dip), GFP_NOFS);
6562 dip->private = bio->bi_private;
6564 dip->logical_offset = file_offset;
6568 dip->bytes += bvec->bv_len;
6570 } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1));
6572 dip->disk_bytenr = (u64)bio->bi_sector << 9;
6573 bio->bi_private = dip;
6575 dip->orig_bio = bio;
6576 atomic_set(&dip->pending_bios, 0);
6579 bio->bi_end_io = btrfs_endio_direct_write;
6581 bio->bi_end_io = btrfs_endio_direct_read;
6583 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
6588 * If this is a write, we need to clean up the reserved space and kill
6589 * the ordered extent.
6592 struct btrfs_ordered_extent *ordered;
6593 ordered = btrfs_lookup_ordered_extent(inode, file_offset);
6594 if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) &&
6595 !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags))
6596 btrfs_free_reserved_extent(root, ordered->start,
6598 btrfs_put_ordered_extent(ordered);
6599 btrfs_put_ordered_extent(ordered);
6601 bio_endio(bio, ret);
6604 static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb,
6605 const struct iovec *iov, loff_t offset,
6606 unsigned long nr_segs)
6612 unsigned blocksize_mask = root->sectorsize - 1;
6613 ssize_t retval = -EINVAL;
6614 loff_t end = offset;
6616 if (offset & blocksize_mask)
6619 /* Check the memory alignment. Blocks cannot straddle pages */
6620 for (seg = 0; seg < nr_segs; seg++) {
6621 addr = (unsigned long)iov[seg].iov_base;
6622 size = iov[seg].iov_len;
6624 if ((addr & blocksize_mask) || (size & blocksize_mask))
6627 /* If this is a write we don't need to check anymore */
6632 * Check to make sure we don't have duplicate iov_base's in this
6633 * iovec, if so return EINVAL, otherwise we'll get csum errors
6634 * when reading back.
6636 for (i = seg + 1; i < nr_segs; i++) {
6637 if (iov[seg].iov_base == iov[i].iov_base)
6646 static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb,
6647 const struct iovec *iov, loff_t offset,
6648 unsigned long nr_segs)
6650 struct file *file = iocb->ki_filp;
6651 struct inode *inode = file->f_mapping->host;
6653 if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov,
6657 return __blockdev_direct_IO(rw, iocb, inode,
6658 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
6659 iov, offset, nr_segs, btrfs_get_blocks_direct, NULL,
6660 btrfs_submit_direct, 0);
6663 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
6665 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
6666 __u64 start, __u64 len)
6670 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
6674 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
6677 int btrfs_readpage(struct file *file, struct page *page)
6679 struct extent_io_tree *tree;
6680 tree = &BTRFS_I(page->mapping->host)->io_tree;
6681 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
6684 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
6686 struct extent_io_tree *tree;
6689 if (current->flags & PF_MEMALLOC) {
6690 redirty_page_for_writepage(wbc, page);
6694 tree = &BTRFS_I(page->mapping->host)->io_tree;
6695 return extent_write_full_page(tree, page, btrfs_get_extent, wbc);
6698 int btrfs_writepages(struct address_space *mapping,
6699 struct writeback_control *wbc)
6701 struct extent_io_tree *tree;
6703 tree = &BTRFS_I(mapping->host)->io_tree;
6704 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
6708 btrfs_readpages(struct file *file, struct address_space *mapping,
6709 struct list_head *pages, unsigned nr_pages)
6711 struct extent_io_tree *tree;
6712 tree = &BTRFS_I(mapping->host)->io_tree;
6713 return extent_readpages(tree, mapping, pages, nr_pages,
6716 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6718 struct extent_io_tree *tree;
6719 struct extent_map_tree *map;
6722 tree = &BTRFS_I(page->mapping->host)->io_tree;
6723 map = &BTRFS_I(page->mapping->host)->extent_tree;
6724 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
6726 ClearPagePrivate(page);
6727 set_page_private(page, 0);
6728 page_cache_release(page);
6733 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
6735 if (PageWriteback(page) || PageDirty(page))
6737 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
6740 static void btrfs_invalidatepage(struct page *page, unsigned long offset)
6742 struct inode *inode = page->mapping->host;
6743 struct extent_io_tree *tree;
6744 struct btrfs_ordered_extent *ordered;
6745 struct extent_state *cached_state = NULL;
6746 u64 page_start = page_offset(page);
6747 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
6750 * we have the page locked, so new writeback can't start,
6751 * and the dirty bit won't be cleared while we are here.
6753 * Wait for IO on this page so that we can safely clear
6754 * the PagePrivate2 bit and do ordered accounting
6756 wait_on_page_writeback(page);
6758 tree = &BTRFS_I(inode)->io_tree;
6760 btrfs_releasepage(page, GFP_NOFS);
6763 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6764 ordered = btrfs_lookup_ordered_extent(inode, page_offset(page));
6767 * IO on this page will never be started, so we need
6768 * to account for any ordered extents now
6770 clear_extent_bit(tree, page_start, page_end,
6771 EXTENT_DIRTY | EXTENT_DELALLOC |
6772 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
6773 EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS);
6775 * whoever cleared the private bit is responsible
6776 * for the finish_ordered_io
6778 if (TestClearPagePrivate2(page) &&
6779 btrfs_dec_test_ordered_pending(inode, &ordered, page_start,
6780 PAGE_CACHE_SIZE, 1)) {
6781 btrfs_finish_ordered_io(ordered);
6783 btrfs_put_ordered_extent(ordered);
6784 cached_state = NULL;
6785 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
6787 clear_extent_bit(tree, page_start, page_end,
6788 EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC |
6789 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
6790 &cached_state, GFP_NOFS);
6791 __btrfs_releasepage(page, GFP_NOFS);
6793 ClearPageChecked(page);
6794 if (PagePrivate(page)) {
6795 ClearPagePrivate(page);
6796 set_page_private(page, 0);
6797 page_cache_release(page);
6802 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
6803 * called from a page fault handler when a page is first dirtied. Hence we must
6804 * be careful to check for EOF conditions here. We set the page up correctly
6805 * for a written page which means we get ENOSPC checking when writing into
6806 * holes and correct delalloc and unwritten extent mapping on filesystems that
6807 * support these features.
6809 * We are not allowed to take the i_mutex here so we have to play games to
6810 * protect against truncate races as the page could now be beyond EOF. Because
6811 * vmtruncate() writes the inode size before removing pages, once we have the
6812 * page lock we can determine safely if the page is beyond EOF. If it is not
6813 * beyond EOF, then the page is guaranteed safe against truncation until we
6816 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
6818 struct page *page = vmf->page;
6819 struct inode *inode = fdentry(vma->vm_file)->d_inode;
6820 struct btrfs_root *root = BTRFS_I(inode)->root;
6821 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6822 struct btrfs_ordered_extent *ordered;
6823 struct extent_state *cached_state = NULL;
6825 unsigned long zero_start;
6832 sb_start_pagefault(inode->i_sb);
6833 ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE);
6835 ret = file_update_time(vma->vm_file);
6841 else /* -ENOSPC, -EIO, etc */
6842 ret = VM_FAULT_SIGBUS;
6848 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
6851 size = i_size_read(inode);
6852 page_start = page_offset(page);
6853 page_end = page_start + PAGE_CACHE_SIZE - 1;
6855 if ((page->mapping != inode->i_mapping) ||
6856 (page_start >= size)) {
6857 /* page got truncated out from underneath us */
6860 wait_on_page_writeback(page);
6862 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
6863 set_page_extent_mapped(page);
6866 * we can't set the delalloc bits if there are pending ordered
6867 * extents. Drop our locks and wait for them to finish
6869 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6871 unlock_extent_cached(io_tree, page_start, page_end,
6872 &cached_state, GFP_NOFS);
6874 btrfs_start_ordered_extent(inode, ordered, 1);
6875 btrfs_put_ordered_extent(ordered);
6880 * XXX - page_mkwrite gets called every time the page is dirtied, even
6881 * if it was already dirty, so for space accounting reasons we need to
6882 * clear any delalloc bits for the range we are fixing to save. There
6883 * is probably a better way to do this, but for now keep consistent with
6884 * prepare_pages in the normal write path.
6886 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
6887 EXTENT_DIRTY | EXTENT_DELALLOC |
6888 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
6889 0, 0, &cached_state, GFP_NOFS);
6891 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
6894 unlock_extent_cached(io_tree, page_start, page_end,
6895 &cached_state, GFP_NOFS);
6896 ret = VM_FAULT_SIGBUS;
6901 /* page is wholly or partially inside EOF */
6902 if (page_start + PAGE_CACHE_SIZE > size)
6903 zero_start = size & ~PAGE_CACHE_MASK;
6905 zero_start = PAGE_CACHE_SIZE;
6907 if (zero_start != PAGE_CACHE_SIZE) {
6909 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
6910 flush_dcache_page(page);
6913 ClearPageChecked(page);
6914 set_page_dirty(page);
6915 SetPageUptodate(page);
6917 BTRFS_I(inode)->last_trans = root->fs_info->generation;
6918 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
6919 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
6921 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
6925 sb_end_pagefault(inode->i_sb);
6926 return VM_FAULT_LOCKED;
6930 btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE);
6932 sb_end_pagefault(inode->i_sb);
6936 static int btrfs_truncate(struct inode *inode)
6938 struct btrfs_root *root = BTRFS_I(inode)->root;
6939 struct btrfs_block_rsv *rsv;
6942 struct btrfs_trans_handle *trans;
6943 u64 mask = root->sectorsize - 1;
6944 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
6946 ret = btrfs_truncate_page(inode, inode->i_size, 0, 0);
6950 btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1);
6951 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
6954 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
6955 * 3 things going on here
6957 * 1) We need to reserve space for our orphan item and the space to
6958 * delete our orphan item. Lord knows we don't want to have a dangling
6959 * orphan item because we didn't reserve space to remove it.
6961 * 2) We need to reserve space to update our inode.
6963 * 3) We need to have something to cache all the space that is going to
6964 * be free'd up by the truncate operation, but also have some slack
6965 * space reserved in case it uses space during the truncate (thank you
6966 * very much snapshotting).
6968 * And we need these to all be seperate. The fact is we can use alot of
6969 * space doing the truncate, and we have no earthly idea how much space
6970 * we will use, so we need the truncate reservation to be seperate so it
6971 * doesn't end up using space reserved for updating the inode or
6972 * removing the orphan item. We also need to be able to stop the
6973 * transaction and start a new one, which means we need to be able to
6974 * update the inode several times, and we have no idea of knowing how
6975 * many times that will be, so we can't just reserve 1 item for the
6976 * entirety of the opration, so that has to be done seperately as well.
6977 * Then there is the orphan item, which does indeed need to be held on
6978 * to for the whole operation, and we need nobody to touch this reserved
6979 * space except the orphan code.
6981 * So that leaves us with
6983 * 1) root->orphan_block_rsv - for the orphan deletion.
6984 * 2) rsv - for the truncate reservation, which we will steal from the
6985 * transaction reservation.
6986 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
6987 * updating the inode.
6989 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
6992 rsv->size = min_size;
6996 * 1 for the truncate slack space
6997 * 1 for updating the inode.
6999 trans = btrfs_start_transaction(root, 2);
7000 if (IS_ERR(trans)) {
7001 err = PTR_ERR(trans);
7005 /* Migrate the slack space for the truncate to our reserve */
7006 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
7011 * setattr is responsible for setting the ordered_data_close flag,
7012 * but that is only tested during the last file release. That
7013 * could happen well after the next commit, leaving a great big
7014 * window where new writes may get lost if someone chooses to write
7015 * to this file after truncating to zero
7017 * The inode doesn't have any dirty data here, and so if we commit
7018 * this is a noop. If someone immediately starts writing to the inode
7019 * it is very likely we'll catch some of their writes in this
7020 * transaction, and the commit will find this file on the ordered
7021 * data list with good things to send down.
7023 * This is a best effort solution, there is still a window where
7024 * using truncate to replace the contents of the file will
7025 * end up with a zero length file after a crash.
7027 if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
7028 &BTRFS_I(inode)->runtime_flags))
7029 btrfs_add_ordered_operation(trans, root, inode);
7032 * So if we truncate and then write and fsync we normally would just
7033 * write the extents that changed, which is a problem if we need to
7034 * first truncate that entire inode. So set this flag so we write out
7035 * all of the extents in the inode to the sync log so we're completely
7038 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
7039 trans->block_rsv = rsv;
7042 ret = btrfs_truncate_inode_items(trans, root, inode,
7044 BTRFS_EXTENT_DATA_KEY);
7045 if (ret != -ENOSPC) {
7050 trans->block_rsv = &root->fs_info->trans_block_rsv;
7051 ret = btrfs_update_inode(trans, root, inode);
7057 btrfs_end_transaction(trans, root);
7058 btrfs_btree_balance_dirty(root);
7060 trans = btrfs_start_transaction(root, 2);
7061 if (IS_ERR(trans)) {
7062 ret = err = PTR_ERR(trans);
7067 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
7069 BUG_ON(ret); /* shouldn't happen */
7070 trans->block_rsv = rsv;
7073 if (ret == 0 && inode->i_nlink > 0) {
7074 trans->block_rsv = root->orphan_block_rsv;
7075 ret = btrfs_orphan_del(trans, inode);
7081 trans->block_rsv = &root->fs_info->trans_block_rsv;
7082 ret = btrfs_update_inode(trans, root, inode);
7086 ret = btrfs_end_transaction(trans, root);
7087 btrfs_btree_balance_dirty(root);
7091 btrfs_free_block_rsv(root, rsv);
7100 * create a new subvolume directory/inode (helper for the ioctl).
7102 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
7103 struct btrfs_root *new_root, u64 new_dirid)
7105 struct inode *inode;
7109 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
7110 new_dirid, new_dirid,
7111 S_IFDIR | (~current_umask() & S_IRWXUGO),
7114 return PTR_ERR(inode);
7115 inode->i_op = &btrfs_dir_inode_operations;
7116 inode->i_fop = &btrfs_dir_file_operations;
7118 set_nlink(inode, 1);
7119 btrfs_i_size_write(inode, 0);
7121 err = btrfs_update_inode(trans, new_root, inode);
7127 struct inode *btrfs_alloc_inode(struct super_block *sb)
7129 struct btrfs_inode *ei;
7130 struct inode *inode;
7132 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
7139 ei->last_sub_trans = 0;
7140 ei->logged_trans = 0;
7141 ei->delalloc_bytes = 0;
7142 ei->disk_i_size = 0;
7145 ei->index_cnt = (u64)-1;
7146 ei->last_unlink_trans = 0;
7147 ei->last_log_commit = 0;
7149 spin_lock_init(&ei->lock);
7150 ei->outstanding_extents = 0;
7151 ei->reserved_extents = 0;
7153 ei->runtime_flags = 0;
7154 ei->force_compress = BTRFS_COMPRESS_NONE;
7156 ei->delayed_node = NULL;
7158 inode = &ei->vfs_inode;
7159 extent_map_tree_init(&ei->extent_tree);
7160 extent_io_tree_init(&ei->io_tree, &inode->i_data);
7161 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
7162 ei->io_tree.track_uptodate = 1;
7163 ei->io_failure_tree.track_uptodate = 1;
7164 atomic_set(&ei->sync_writers, 0);
7165 mutex_init(&ei->log_mutex);
7166 mutex_init(&ei->delalloc_mutex);
7167 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
7168 INIT_LIST_HEAD(&ei->delalloc_inodes);
7169 INIT_LIST_HEAD(&ei->ordered_operations);
7170 RB_CLEAR_NODE(&ei->rb_node);
7175 static void btrfs_i_callback(struct rcu_head *head)
7177 struct inode *inode = container_of(head, struct inode, i_rcu);
7178 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7181 void btrfs_destroy_inode(struct inode *inode)
7183 struct btrfs_ordered_extent *ordered;
7184 struct btrfs_root *root = BTRFS_I(inode)->root;
7186 WARN_ON(!hlist_empty(&inode->i_dentry));
7187 WARN_ON(inode->i_data.nrpages);
7188 WARN_ON(BTRFS_I(inode)->outstanding_extents);
7189 WARN_ON(BTRFS_I(inode)->reserved_extents);
7190 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
7191 WARN_ON(BTRFS_I(inode)->csum_bytes);
7194 * This can happen where we create an inode, but somebody else also
7195 * created the same inode and we need to destroy the one we already
7202 * Make sure we're properly removed from the ordered operation
7206 if (!list_empty(&BTRFS_I(inode)->ordered_operations)) {
7207 spin_lock(&root->fs_info->ordered_extent_lock);
7208 list_del_init(&BTRFS_I(inode)->ordered_operations);
7209 spin_unlock(&root->fs_info->ordered_extent_lock);
7212 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
7213 &BTRFS_I(inode)->runtime_flags)) {
7214 printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n",
7215 (unsigned long long)btrfs_ino(inode));
7216 atomic_dec(&root->orphan_inodes);
7220 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7224 printk(KERN_ERR "btrfs found ordered "
7225 "extent %llu %llu on inode cleanup\n",
7226 (unsigned long long)ordered->file_offset,
7227 (unsigned long long)ordered->len);
7228 btrfs_remove_ordered_extent(inode, ordered);
7229 btrfs_put_ordered_extent(ordered);
7230 btrfs_put_ordered_extent(ordered);
7233 inode_tree_del(inode);
7234 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
7236 btrfs_remove_delayed_node(inode);
7237 call_rcu(&inode->i_rcu, btrfs_i_callback);
7240 int btrfs_drop_inode(struct inode *inode)
7242 struct btrfs_root *root = BTRFS_I(inode)->root;
7244 if (btrfs_root_refs(&root->root_item) == 0 &&
7245 !btrfs_is_free_space_inode(inode))
7248 return generic_drop_inode(inode);
7251 static void init_once(void *foo)
7253 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
7255 inode_init_once(&ei->vfs_inode);
7258 void btrfs_destroy_cachep(void)
7261 * Make sure all delayed rcu free inodes are flushed before we
7265 if (btrfs_inode_cachep)
7266 kmem_cache_destroy(btrfs_inode_cachep);
7267 if (btrfs_trans_handle_cachep)
7268 kmem_cache_destroy(btrfs_trans_handle_cachep);
7269 if (btrfs_transaction_cachep)
7270 kmem_cache_destroy(btrfs_transaction_cachep);
7271 if (btrfs_path_cachep)
7272 kmem_cache_destroy(btrfs_path_cachep);
7273 if (btrfs_free_space_cachep)
7274 kmem_cache_destroy(btrfs_free_space_cachep);
7275 if (btrfs_delalloc_work_cachep)
7276 kmem_cache_destroy(btrfs_delalloc_work_cachep);
7279 int btrfs_init_cachep(void)
7281 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
7282 sizeof(struct btrfs_inode), 0,
7283 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
7284 if (!btrfs_inode_cachep)
7287 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
7288 sizeof(struct btrfs_trans_handle), 0,
7289 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7290 if (!btrfs_trans_handle_cachep)
7293 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
7294 sizeof(struct btrfs_transaction), 0,
7295 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7296 if (!btrfs_transaction_cachep)
7299 btrfs_path_cachep = kmem_cache_create("btrfs_path",
7300 sizeof(struct btrfs_path), 0,
7301 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7302 if (!btrfs_path_cachep)
7305 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
7306 sizeof(struct btrfs_free_space), 0,
7307 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
7308 if (!btrfs_free_space_cachep)
7311 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
7312 sizeof(struct btrfs_delalloc_work), 0,
7313 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
7315 if (!btrfs_delalloc_work_cachep)
7320 btrfs_destroy_cachep();
7324 static int btrfs_getattr(struct vfsmount *mnt,
7325 struct dentry *dentry, struct kstat *stat)
7327 struct inode *inode = dentry->d_inode;
7328 u32 blocksize = inode->i_sb->s_blocksize;
7330 generic_fillattr(inode, stat);
7331 stat->dev = BTRFS_I(inode)->root->anon_dev;
7332 stat->blksize = PAGE_CACHE_SIZE;
7333 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
7334 ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9;
7339 * If a file is moved, it will inherit the cow and compression flags of the new
7342 static void fixup_inode_flags(struct inode *dir, struct inode *inode)
7344 struct btrfs_inode *b_dir = BTRFS_I(dir);
7345 struct btrfs_inode *b_inode = BTRFS_I(inode);
7347 if (b_dir->flags & BTRFS_INODE_NODATACOW)
7348 b_inode->flags |= BTRFS_INODE_NODATACOW;
7350 b_inode->flags &= ~BTRFS_INODE_NODATACOW;
7352 if (b_dir->flags & BTRFS_INODE_COMPRESS) {
7353 b_inode->flags |= BTRFS_INODE_COMPRESS;
7354 b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
7356 b_inode->flags &= ~(BTRFS_INODE_COMPRESS |
7357 BTRFS_INODE_NOCOMPRESS);
7361 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
7362 struct inode *new_dir, struct dentry *new_dentry)
7364 struct btrfs_trans_handle *trans;
7365 struct btrfs_root *root = BTRFS_I(old_dir)->root;
7366 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
7367 struct inode *new_inode = new_dentry->d_inode;
7368 struct inode *old_inode = old_dentry->d_inode;
7369 struct timespec ctime = CURRENT_TIME;
7373 u64 old_ino = btrfs_ino(old_inode);
7375 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
7378 /* we only allow rename subvolume link between subvolumes */
7379 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
7382 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
7383 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
7386 if (S_ISDIR(old_inode->i_mode) && new_inode &&
7387 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
7391 /* check for collisions, even if the name isn't there */
7392 ret = btrfs_check_dir_item_collision(root, new_dir->i_ino,
7393 new_dentry->d_name.name,
7394 new_dentry->d_name.len);
7397 if (ret == -EEXIST) {
7399 * eexist without a new_inode */
7405 /* maybe -EOVERFLOW */
7412 * we're using rename to replace one file with another.
7413 * and the replacement file is large. Start IO on it now so
7414 * we don't add too much work to the end of the transaction
7416 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size &&
7417 old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
7418 filemap_flush(old_inode->i_mapping);
7420 /* close the racy window with snapshot create/destroy ioctl */
7421 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7422 down_read(&root->fs_info->subvol_sem);
7424 * We want to reserve the absolute worst case amount of items. So if
7425 * both inodes are subvols and we need to unlink them then that would
7426 * require 4 item modifications, but if they are both normal inodes it
7427 * would require 5 item modifications, so we'll assume their normal
7428 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
7429 * should cover the worst case number of items we'll modify.
7431 trans = btrfs_start_transaction(root, 20);
7432 if (IS_ERR(trans)) {
7433 ret = PTR_ERR(trans);
7438 btrfs_record_root_in_trans(trans, dest);
7440 ret = btrfs_set_inode_index(new_dir, &index);
7444 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7445 /* force full log commit if subvolume involved. */
7446 root->fs_info->last_trans_log_full_commit = trans->transid;
7448 ret = btrfs_insert_inode_ref(trans, dest,
7449 new_dentry->d_name.name,
7450 new_dentry->d_name.len,
7452 btrfs_ino(new_dir), index);
7456 * this is an ugly little race, but the rename is required
7457 * to make sure that if we crash, the inode is either at the
7458 * old name or the new one. pinning the log transaction lets
7459 * us make sure we don't allow a log commit to come in after
7460 * we unlink the name but before we add the new name back in.
7462 btrfs_pin_log_trans(root);
7465 * make sure the inode gets flushed if it is replacing
7468 if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode))
7469 btrfs_add_ordered_operation(trans, root, old_inode);
7471 inode_inc_iversion(old_dir);
7472 inode_inc_iversion(new_dir);
7473 inode_inc_iversion(old_inode);
7474 old_dir->i_ctime = old_dir->i_mtime = ctime;
7475 new_dir->i_ctime = new_dir->i_mtime = ctime;
7476 old_inode->i_ctime = ctime;
7478 if (old_dentry->d_parent != new_dentry->d_parent)
7479 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
7481 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
7482 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
7483 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
7484 old_dentry->d_name.name,
7485 old_dentry->d_name.len);
7487 ret = __btrfs_unlink_inode(trans, root, old_dir,
7488 old_dentry->d_inode,
7489 old_dentry->d_name.name,
7490 old_dentry->d_name.len);
7492 ret = btrfs_update_inode(trans, root, old_inode);
7495 btrfs_abort_transaction(trans, root, ret);
7500 inode_inc_iversion(new_inode);
7501 new_inode->i_ctime = CURRENT_TIME;
7502 if (unlikely(btrfs_ino(new_inode) ==
7503 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
7504 root_objectid = BTRFS_I(new_inode)->location.objectid;
7505 ret = btrfs_unlink_subvol(trans, dest, new_dir,
7507 new_dentry->d_name.name,
7508 new_dentry->d_name.len);
7509 BUG_ON(new_inode->i_nlink == 0);
7511 ret = btrfs_unlink_inode(trans, dest, new_dir,
7512 new_dentry->d_inode,
7513 new_dentry->d_name.name,
7514 new_dentry->d_name.len);
7516 if (!ret && new_inode->i_nlink == 0) {
7517 ret = btrfs_orphan_add(trans, new_dentry->d_inode);
7521 btrfs_abort_transaction(trans, root, ret);
7526 fixup_inode_flags(new_dir, old_inode);
7528 ret = btrfs_add_link(trans, new_dir, old_inode,
7529 new_dentry->d_name.name,
7530 new_dentry->d_name.len, 0, index);
7532 btrfs_abort_transaction(trans, root, ret);
7536 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
7537 struct dentry *parent = new_dentry->d_parent;
7538 btrfs_log_new_name(trans, old_inode, old_dir, parent);
7539 btrfs_end_log_trans(root);
7542 btrfs_end_transaction(trans, root);
7544 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
7545 up_read(&root->fs_info->subvol_sem);
7550 static void btrfs_run_delalloc_work(struct btrfs_work *work)
7552 struct btrfs_delalloc_work *delalloc_work;
7554 delalloc_work = container_of(work, struct btrfs_delalloc_work,
7556 if (delalloc_work->wait)
7557 btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1);
7559 filemap_flush(delalloc_work->inode->i_mapping);
7561 if (delalloc_work->delay_iput)
7562 btrfs_add_delayed_iput(delalloc_work->inode);
7564 iput(delalloc_work->inode);
7565 complete(&delalloc_work->completion);
7568 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
7569 int wait, int delay_iput)
7571 struct btrfs_delalloc_work *work;
7573 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
7577 init_completion(&work->completion);
7578 INIT_LIST_HEAD(&work->list);
7579 work->inode = inode;
7581 work->delay_iput = delay_iput;
7582 work->work.func = btrfs_run_delalloc_work;
7587 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
7589 wait_for_completion(&work->completion);
7590 kmem_cache_free(btrfs_delalloc_work_cachep, work);
7594 * some fairly slow code that needs optimization. This walks the list
7595 * of all the inodes with pending delalloc and forces them to disk.
7597 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
7599 struct btrfs_inode *binode;
7600 struct inode *inode;
7601 struct btrfs_delalloc_work *work, *next;
7602 struct list_head works;
7603 struct list_head splice;
7606 if (root->fs_info->sb->s_flags & MS_RDONLY)
7609 INIT_LIST_HEAD(&works);
7610 INIT_LIST_HEAD(&splice);
7612 spin_lock(&root->fs_info->delalloc_lock);
7613 list_splice_init(&root->fs_info->delalloc_inodes, &splice);
7614 while (!list_empty(&splice)) {
7615 binode = list_entry(splice.next, struct btrfs_inode,
7618 list_del_init(&binode->delalloc_inodes);
7620 inode = igrab(&binode->vfs_inode);
7624 list_add_tail(&binode->delalloc_inodes,
7625 &root->fs_info->delalloc_inodes);
7626 spin_unlock(&root->fs_info->delalloc_lock);
7628 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
7629 if (unlikely(!work)) {
7633 list_add_tail(&work->list, &works);
7634 btrfs_queue_worker(&root->fs_info->flush_workers,
7638 spin_lock(&root->fs_info->delalloc_lock);
7640 spin_unlock(&root->fs_info->delalloc_lock);
7642 list_for_each_entry_safe(work, next, &works, list) {
7643 list_del_init(&work->list);
7644 btrfs_wait_and_free_delalloc_work(work);
7647 /* the filemap_flush will queue IO into the worker threads, but
7648 * we have to make sure the IO is actually started and that
7649 * ordered extents get created before we return
7651 atomic_inc(&root->fs_info->async_submit_draining);
7652 while (atomic_read(&root->fs_info->nr_async_submits) ||
7653 atomic_read(&root->fs_info->async_delalloc_pages)) {
7654 wait_event(root->fs_info->async_submit_wait,
7655 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
7656 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
7658 atomic_dec(&root->fs_info->async_submit_draining);
7661 list_for_each_entry_safe(work, next, &works, list) {
7662 list_del_init(&work->list);
7663 btrfs_wait_and_free_delalloc_work(work);
7666 if (!list_empty_careful(&splice)) {
7667 spin_lock(&root->fs_info->delalloc_lock);
7668 list_splice_tail(&splice, &root->fs_info->delalloc_inodes);
7669 spin_unlock(&root->fs_info->delalloc_lock);
7674 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
7675 const char *symname)
7677 struct btrfs_trans_handle *trans;
7678 struct btrfs_root *root = BTRFS_I(dir)->root;
7679 struct btrfs_path *path;
7680 struct btrfs_key key;
7681 struct inode *inode = NULL;
7689 struct btrfs_file_extent_item *ei;
7690 struct extent_buffer *leaf;
7692 name_len = strlen(symname) + 1;
7693 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
7694 return -ENAMETOOLONG;
7697 * 2 items for inode item and ref
7698 * 2 items for dir items
7699 * 1 item for xattr if selinux is on
7701 trans = btrfs_start_transaction(root, 5);
7703 return PTR_ERR(trans);
7705 err = btrfs_find_free_ino(root, &objectid);
7709 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
7710 dentry->d_name.len, btrfs_ino(dir), objectid,
7711 S_IFLNK|S_IRWXUGO, &index);
7712 if (IS_ERR(inode)) {
7713 err = PTR_ERR(inode);
7717 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
7724 * If the active LSM wants to access the inode during
7725 * d_instantiate it needs these. Smack checks to see
7726 * if the filesystem supports xattrs by looking at the
7729 inode->i_fop = &btrfs_file_operations;
7730 inode->i_op = &btrfs_file_inode_operations;
7732 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
7736 inode->i_mapping->a_ops = &btrfs_aops;
7737 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7738 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
7743 path = btrfs_alloc_path();
7749 key.objectid = btrfs_ino(inode);
7751 btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
7752 datasize = btrfs_file_extent_calc_inline_size(name_len);
7753 err = btrfs_insert_empty_item(trans, root, path, &key,
7757 btrfs_free_path(path);
7760 leaf = path->nodes[0];
7761 ei = btrfs_item_ptr(leaf, path->slots[0],
7762 struct btrfs_file_extent_item);
7763 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
7764 btrfs_set_file_extent_type(leaf, ei,
7765 BTRFS_FILE_EXTENT_INLINE);
7766 btrfs_set_file_extent_encryption(leaf, ei, 0);
7767 btrfs_set_file_extent_compression(leaf, ei, 0);
7768 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
7769 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
7771 ptr = btrfs_file_extent_inline_start(ei);
7772 write_extent_buffer(leaf, symname, ptr, name_len);
7773 btrfs_mark_buffer_dirty(leaf);
7774 btrfs_free_path(path);
7776 inode->i_op = &btrfs_symlink_inode_operations;
7777 inode->i_mapping->a_ops = &btrfs_symlink_aops;
7778 inode->i_mapping->backing_dev_info = &root->fs_info->bdi;
7779 inode_set_bytes(inode, name_len);
7780 btrfs_i_size_write(inode, name_len - 1);
7781 err = btrfs_update_inode(trans, root, inode);
7787 d_instantiate(dentry, inode);
7788 btrfs_end_transaction(trans, root);
7790 inode_dec_link_count(inode);
7793 btrfs_btree_balance_dirty(root);
7797 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
7798 u64 start, u64 num_bytes, u64 min_size,
7799 loff_t actual_len, u64 *alloc_hint,
7800 struct btrfs_trans_handle *trans)
7802 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
7803 struct extent_map *em;
7804 struct btrfs_root *root = BTRFS_I(inode)->root;
7805 struct btrfs_key ins;
7806 u64 cur_offset = start;
7809 bool own_trans = true;
7813 while (num_bytes > 0) {
7815 trans = btrfs_start_transaction(root, 3);
7816 if (IS_ERR(trans)) {
7817 ret = PTR_ERR(trans);
7822 ret = btrfs_reserve_extent(trans, root, num_bytes, min_size,
7823 0, *alloc_hint, &ins, 1);
7826 btrfs_end_transaction(trans, root);
7830 ret = insert_reserved_file_extent(trans, inode,
7831 cur_offset, ins.objectid,
7832 ins.offset, ins.offset,
7833 ins.offset, 0, 0, 0,
7834 BTRFS_FILE_EXTENT_PREALLOC);
7836 btrfs_abort_transaction(trans, root, ret);
7838 btrfs_end_transaction(trans, root);
7841 btrfs_drop_extent_cache(inode, cur_offset,
7842 cur_offset + ins.offset -1, 0);
7844 em = alloc_extent_map();
7846 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
7847 &BTRFS_I(inode)->runtime_flags);
7851 em->start = cur_offset;
7852 em->orig_start = cur_offset;
7853 em->len = ins.offset;
7854 em->block_start = ins.objectid;
7855 em->block_len = ins.offset;
7856 em->orig_block_len = ins.offset;
7857 em->bdev = root->fs_info->fs_devices->latest_bdev;
7858 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7859 em->generation = trans->transid;
7862 write_lock(&em_tree->lock);
7863 ret = add_extent_mapping(em_tree, em);
7865 list_move(&em->list,
7866 &em_tree->modified_extents);
7867 write_unlock(&em_tree->lock);
7870 btrfs_drop_extent_cache(inode, cur_offset,
7871 cur_offset + ins.offset - 1,
7874 free_extent_map(em);
7876 num_bytes -= ins.offset;
7877 cur_offset += ins.offset;
7878 *alloc_hint = ins.objectid + ins.offset;
7880 inode_inc_iversion(inode);
7881 inode->i_ctime = CURRENT_TIME;
7882 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
7883 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
7884 (actual_len > inode->i_size) &&
7885 (cur_offset > inode->i_size)) {
7886 if (cur_offset > actual_len)
7887 i_size = actual_len;
7889 i_size = cur_offset;
7890 i_size_write(inode, i_size);
7891 btrfs_ordered_update_i_size(inode, i_size, NULL);
7894 ret = btrfs_update_inode(trans, root, inode);
7897 btrfs_abort_transaction(trans, root, ret);
7899 btrfs_end_transaction(trans, root);
7904 btrfs_end_transaction(trans, root);
7909 int btrfs_prealloc_file_range(struct inode *inode, int mode,
7910 u64 start, u64 num_bytes, u64 min_size,
7911 loff_t actual_len, u64 *alloc_hint)
7913 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7914 min_size, actual_len, alloc_hint,
7918 int btrfs_prealloc_file_range_trans(struct inode *inode,
7919 struct btrfs_trans_handle *trans, int mode,
7920 u64 start, u64 num_bytes, u64 min_size,
7921 loff_t actual_len, u64 *alloc_hint)
7923 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
7924 min_size, actual_len, alloc_hint, trans);
7927 static int btrfs_set_page_dirty(struct page *page)
7929 return __set_page_dirty_nobuffers(page);
7932 static int btrfs_permission(struct inode *inode, int mask)
7934 struct btrfs_root *root = BTRFS_I(inode)->root;
7935 umode_t mode = inode->i_mode;
7937 if (mask & MAY_WRITE &&
7938 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
7939 if (btrfs_root_readonly(root))
7941 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
7944 return generic_permission(inode, mask);
7947 static const struct inode_operations btrfs_dir_inode_operations = {
7948 .getattr = btrfs_getattr,
7949 .lookup = btrfs_lookup,
7950 .create = btrfs_create,
7951 .unlink = btrfs_unlink,
7953 .mkdir = btrfs_mkdir,
7954 .rmdir = btrfs_rmdir,
7955 .rename = btrfs_rename,
7956 .symlink = btrfs_symlink,
7957 .setattr = btrfs_setattr,
7958 .mknod = btrfs_mknod,
7959 .setxattr = btrfs_setxattr,
7960 .getxattr = btrfs_getxattr,
7961 .listxattr = btrfs_listxattr,
7962 .removexattr = btrfs_removexattr,
7963 .permission = btrfs_permission,
7964 .get_acl = btrfs_get_acl,
7966 static const struct inode_operations btrfs_dir_ro_inode_operations = {
7967 .lookup = btrfs_lookup,
7968 .permission = btrfs_permission,
7969 .get_acl = btrfs_get_acl,
7972 static const struct file_operations btrfs_dir_file_operations = {
7973 .llseek = generic_file_llseek,
7974 .read = generic_read_dir,
7975 .readdir = btrfs_real_readdir,
7976 .unlocked_ioctl = btrfs_ioctl,
7977 #ifdef CONFIG_COMPAT
7978 .compat_ioctl = btrfs_ioctl,
7980 .release = btrfs_release_file,
7981 .fsync = btrfs_sync_file,
7984 static struct extent_io_ops btrfs_extent_io_ops = {
7985 .fill_delalloc = run_delalloc_range,
7986 .submit_bio_hook = btrfs_submit_bio_hook,
7987 .merge_bio_hook = btrfs_merge_bio_hook,
7988 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
7989 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
7990 .writepage_start_hook = btrfs_writepage_start_hook,
7991 .set_bit_hook = btrfs_set_bit_hook,
7992 .clear_bit_hook = btrfs_clear_bit_hook,
7993 .merge_extent_hook = btrfs_merge_extent_hook,
7994 .split_extent_hook = btrfs_split_extent_hook,
7998 * btrfs doesn't support the bmap operation because swapfiles
7999 * use bmap to make a mapping of extents in the file. They assume
8000 * these extents won't change over the life of the file and they
8001 * use the bmap result to do IO directly to the drive.
8003 * the btrfs bmap call would return logical addresses that aren't
8004 * suitable for IO and they also will change frequently as COW
8005 * operations happen. So, swapfile + btrfs == corruption.
8007 * For now we're avoiding this by dropping bmap.
8009 static const struct address_space_operations btrfs_aops = {
8010 .readpage = btrfs_readpage,
8011 .writepage = btrfs_writepage,
8012 .writepages = btrfs_writepages,
8013 .readpages = btrfs_readpages,
8014 .direct_IO = btrfs_direct_IO,
8015 .invalidatepage = btrfs_invalidatepage,
8016 .releasepage = btrfs_releasepage,
8017 .set_page_dirty = btrfs_set_page_dirty,
8018 .error_remove_page = generic_error_remove_page,
8021 static const struct address_space_operations btrfs_symlink_aops = {
8022 .readpage = btrfs_readpage,
8023 .writepage = btrfs_writepage,
8024 .invalidatepage = btrfs_invalidatepage,
8025 .releasepage = btrfs_releasepage,
8028 static const struct inode_operations btrfs_file_inode_operations = {
8029 .getattr = btrfs_getattr,
8030 .setattr = btrfs_setattr,
8031 .setxattr = btrfs_setxattr,
8032 .getxattr = btrfs_getxattr,
8033 .listxattr = btrfs_listxattr,
8034 .removexattr = btrfs_removexattr,
8035 .permission = btrfs_permission,
8036 .fiemap = btrfs_fiemap,
8037 .get_acl = btrfs_get_acl,
8038 .update_time = btrfs_update_time,
8040 static const struct inode_operations btrfs_special_inode_operations = {
8041 .getattr = btrfs_getattr,
8042 .setattr = btrfs_setattr,
8043 .permission = btrfs_permission,
8044 .setxattr = btrfs_setxattr,
8045 .getxattr = btrfs_getxattr,
8046 .listxattr = btrfs_listxattr,
8047 .removexattr = btrfs_removexattr,
8048 .get_acl = btrfs_get_acl,
8049 .update_time = btrfs_update_time,
8051 static const struct inode_operations btrfs_symlink_inode_operations = {
8052 .readlink = generic_readlink,
8053 .follow_link = page_follow_link_light,
8054 .put_link = page_put_link,
8055 .getattr = btrfs_getattr,
8056 .setattr = btrfs_setattr,
8057 .permission = btrfs_permission,
8058 .setxattr = btrfs_setxattr,
8059 .getxattr = btrfs_getxattr,
8060 .listxattr = btrfs_listxattr,
8061 .removexattr = btrfs_removexattr,
8062 .get_acl = btrfs_get_acl,
8063 .update_time = btrfs_update_time,
8066 const struct dentry_operations btrfs_dentry_operations = {
8067 .d_delete = btrfs_dentry_delete,
8068 .d_release = btrfs_dentry_release,