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.
20 #include <linux/pagemap.h>
21 #include <linux/highmem.h>
22 #include <linux/time.h>
23 #include <linux/init.h>
24 #include <linux/string.h>
25 #include <linux/backing-dev.h>
26 #include <linux/mpage.h>
27 #include <linux/aio.h>
28 #include <linux/falloc.h>
29 #include <linux/swap.h>
30 #include <linux/writeback.h>
31 #include <linux/statfs.h>
32 #include <linux/compat.h>
33 #include <linux/slab.h>
34 #include <linux/btrfs.h>
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
45 static struct kmem_cache *btrfs_inode_defrag_cachep;
47 * when auto defrag is enabled we
48 * queue up these defrag structs to remember which
49 * inodes need defragging passes
52 struct rb_node rb_node;
56 * transid where the defrag was added, we search for
57 * extents newer than this
64 /* last offset we were able to defrag */
67 /* if we've wrapped around back to zero once already */
71 static int __compare_inode_defrag(struct inode_defrag *defrag1,
72 struct inode_defrag *defrag2)
74 if (defrag1->root > defrag2->root)
76 else if (defrag1->root < defrag2->root)
78 else if (defrag1->ino > defrag2->ino)
80 else if (defrag1->ino < defrag2->ino)
86 /* pop a record for an inode into the defrag tree. The lock
87 * must be held already
89 * If you're inserting a record for an older transid than an
90 * existing record, the transid already in the tree is lowered
92 * If an existing record is found the defrag item you
95 static int __btrfs_add_inode_defrag(struct inode *inode,
96 struct inode_defrag *defrag)
98 struct btrfs_root *root = BTRFS_I(inode)->root;
99 struct inode_defrag *entry;
101 struct rb_node *parent = NULL;
104 p = &root->fs_info->defrag_inodes.rb_node;
107 entry = rb_entry(parent, struct inode_defrag, rb_node);
109 ret = __compare_inode_defrag(defrag, entry);
111 p = &parent->rb_left;
113 p = &parent->rb_right;
115 /* if we're reinserting an entry for
116 * an old defrag run, make sure to
117 * lower the transid of our existing record
119 if (defrag->transid < entry->transid)
120 entry->transid = defrag->transid;
121 if (defrag->last_offset > entry->last_offset)
122 entry->last_offset = defrag->last_offset;
126 set_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
127 rb_link_node(&defrag->rb_node, parent, p);
128 rb_insert_color(&defrag->rb_node, &root->fs_info->defrag_inodes);
132 static inline int __need_auto_defrag(struct btrfs_root *root)
134 if (!btrfs_test_opt(root, AUTO_DEFRAG))
137 if (btrfs_fs_closing(root->fs_info))
144 * insert a defrag record for this inode if auto defrag is
147 int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
150 struct btrfs_root *root = BTRFS_I(inode)->root;
151 struct inode_defrag *defrag;
155 if (!__need_auto_defrag(root))
158 if (test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags))
162 transid = trans->transid;
164 transid = BTRFS_I(inode)->root->last_trans;
166 defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
170 defrag->ino = btrfs_ino(inode);
171 defrag->transid = transid;
172 defrag->root = root->root_key.objectid;
174 spin_lock(&root->fs_info->defrag_inodes_lock);
175 if (!test_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags)) {
177 * If we set IN_DEFRAG flag and evict the inode from memory,
178 * and then re-read this inode, this new inode doesn't have
179 * IN_DEFRAG flag. At the case, we may find the existed defrag.
181 ret = __btrfs_add_inode_defrag(inode, defrag);
183 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
185 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
187 spin_unlock(&root->fs_info->defrag_inodes_lock);
192 * Requeue the defrag object. If there is a defrag object that points to
193 * the same inode in the tree, we will merge them together (by
194 * __btrfs_add_inode_defrag()) and free the one that we want to requeue.
196 static void btrfs_requeue_inode_defrag(struct inode *inode,
197 struct inode_defrag *defrag)
199 struct btrfs_root *root = BTRFS_I(inode)->root;
202 if (!__need_auto_defrag(root))
206 * Here we don't check the IN_DEFRAG flag, because we need merge
209 spin_lock(&root->fs_info->defrag_inodes_lock);
210 ret = __btrfs_add_inode_defrag(inode, defrag);
211 spin_unlock(&root->fs_info->defrag_inodes_lock);
216 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
220 * pick the defragable inode that we want, if it doesn't exist, we will get
223 static struct inode_defrag *
224 btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
226 struct inode_defrag *entry = NULL;
227 struct inode_defrag tmp;
229 struct rb_node *parent = NULL;
235 spin_lock(&fs_info->defrag_inodes_lock);
236 p = fs_info->defrag_inodes.rb_node;
239 entry = rb_entry(parent, struct inode_defrag, rb_node);
241 ret = __compare_inode_defrag(&tmp, entry);
245 p = parent->rb_right;
250 if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
251 parent = rb_next(parent);
253 entry = rb_entry(parent, struct inode_defrag, rb_node);
259 rb_erase(parent, &fs_info->defrag_inodes);
260 spin_unlock(&fs_info->defrag_inodes_lock);
264 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
266 struct inode_defrag *defrag;
267 struct rb_node *node;
269 spin_lock(&fs_info->defrag_inodes_lock);
270 node = rb_first(&fs_info->defrag_inodes);
272 rb_erase(node, &fs_info->defrag_inodes);
273 defrag = rb_entry(node, struct inode_defrag, rb_node);
274 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
276 if (need_resched()) {
277 spin_unlock(&fs_info->defrag_inodes_lock);
279 spin_lock(&fs_info->defrag_inodes_lock);
282 node = rb_first(&fs_info->defrag_inodes);
284 spin_unlock(&fs_info->defrag_inodes_lock);
287 #define BTRFS_DEFRAG_BATCH 1024
289 static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
290 struct inode_defrag *defrag)
292 struct btrfs_root *inode_root;
294 struct btrfs_key key;
295 struct btrfs_ioctl_defrag_range_args range;
301 key.objectid = defrag->root;
302 btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY);
303 key.offset = (u64)-1;
305 index = srcu_read_lock(&fs_info->subvol_srcu);
307 inode_root = btrfs_read_fs_root_no_name(fs_info, &key);
308 if (IS_ERR(inode_root)) {
309 ret = PTR_ERR(inode_root);
312 if (btrfs_root_refs(&inode_root->root_item) == 0) {
317 key.objectid = defrag->ino;
318 btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY);
320 inode = btrfs_iget(fs_info->sb, &key, inode_root, NULL);
322 ret = PTR_ERR(inode);
325 srcu_read_unlock(&fs_info->subvol_srcu, index);
327 /* do a chunk of defrag */
328 clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
329 memset(&range, 0, sizeof(range));
331 range.start = defrag->last_offset;
333 sb_start_write(fs_info->sb);
334 num_defrag = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
336 sb_end_write(fs_info->sb);
338 * if we filled the whole defrag batch, there
339 * must be more work to do. Queue this defrag
342 if (num_defrag == BTRFS_DEFRAG_BATCH) {
343 defrag->last_offset = range.start;
344 btrfs_requeue_inode_defrag(inode, defrag);
345 } else if (defrag->last_offset && !defrag->cycled) {
347 * we didn't fill our defrag batch, but
348 * we didn't start at zero. Make sure we loop
349 * around to the start of the file.
351 defrag->last_offset = 0;
353 btrfs_requeue_inode_defrag(inode, defrag);
355 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
361 srcu_read_unlock(&fs_info->subvol_srcu, index);
362 kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
367 * run through the list of inodes in the FS that need
370 int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
372 struct inode_defrag *defrag;
374 u64 root_objectid = 0;
376 atomic_inc(&fs_info->defrag_running);
378 /* Pause the auto defragger. */
379 if (test_bit(BTRFS_FS_STATE_REMOUNTING,
383 if (!__need_auto_defrag(fs_info->tree_root))
386 /* find an inode to defrag */
387 defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
390 if (root_objectid || first_ino) {
399 first_ino = defrag->ino + 1;
400 root_objectid = defrag->root;
402 __btrfs_run_defrag_inode(fs_info, defrag);
404 atomic_dec(&fs_info->defrag_running);
407 * during unmount, we use the transaction_wait queue to
408 * wait for the defragger to stop
410 wake_up(&fs_info->transaction_wait);
414 /* simple helper to fault in pages and copy. This should go away
415 * and be replaced with calls into generic code.
417 static noinline int btrfs_copy_from_user(loff_t pos, int num_pages,
419 struct page **prepared_pages,
423 size_t total_copied = 0;
425 int offset = pos & (PAGE_CACHE_SIZE - 1);
427 while (write_bytes > 0) {
428 size_t count = min_t(size_t,
429 PAGE_CACHE_SIZE - offset, write_bytes);
430 struct page *page = prepared_pages[pg];
432 * Copy data from userspace to the current page
434 * Disable pagefault to avoid recursive lock since
435 * the pages are already locked
438 copied = iov_iter_copy_from_user_atomic(page, i, offset, count);
441 /* Flush processor's dcache for this page */
442 flush_dcache_page(page);
445 * if we get a partial write, we can end up with
446 * partially up to date pages. These add
447 * a lot of complexity, so make sure they don't
448 * happen by forcing this copy to be retried.
450 * The rest of the btrfs_file_write code will fall
451 * back to page at a time copies after we return 0.
453 if (!PageUptodate(page) && copied < count)
456 iov_iter_advance(i, copied);
457 write_bytes -= copied;
458 total_copied += copied;
460 /* Return to btrfs_file_aio_write to fault page */
461 if (unlikely(copied == 0))
464 if (unlikely(copied < PAGE_CACHE_SIZE - offset)) {
475 * unlocks pages after btrfs_file_write is done with them
477 static void btrfs_drop_pages(struct page **pages, size_t num_pages)
480 for (i = 0; i < num_pages; i++) {
481 /* page checked is some magic around finding pages that
482 * have been modified without going through btrfs_set_page_dirty
485 ClearPageChecked(pages[i]);
486 unlock_page(pages[i]);
487 mark_page_accessed(pages[i]);
488 page_cache_release(pages[i]);
493 * after copy_from_user, pages need to be dirtied and we need to make
494 * sure holes are created between the current EOF and the start of
495 * any next extents (if required).
497 * this also makes the decision about creating an inline extent vs
498 * doing real data extents, marking pages dirty and delalloc as required.
500 int btrfs_dirty_pages(struct btrfs_root *root, struct inode *inode,
501 struct page **pages, size_t num_pages,
502 loff_t pos, size_t write_bytes,
503 struct extent_state **cached)
509 u64 end_of_last_block;
510 u64 end_pos = pos + write_bytes;
511 loff_t isize = i_size_read(inode);
513 start_pos = pos & ~((u64)root->sectorsize - 1);
514 num_bytes = ALIGN(write_bytes + pos - start_pos, root->sectorsize);
516 end_of_last_block = start_pos + num_bytes - 1;
517 err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
522 for (i = 0; i < num_pages; i++) {
523 struct page *p = pages[i];
530 * we've only changed i_size in ram, and we haven't updated
531 * the disk i_size. There is no need to log the inode
535 i_size_write(inode, end_pos);
540 * this drops all the extents in the cache that intersect the range
541 * [start, end]. Existing extents are split as required.
543 void btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end,
546 struct extent_map *em;
547 struct extent_map *split = NULL;
548 struct extent_map *split2 = NULL;
549 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
550 u64 len = end - start + 1;
558 WARN_ON(end < start);
559 if (end == (u64)-1) {
568 split = alloc_extent_map();
570 split2 = alloc_extent_map();
571 if (!split || !split2)
574 write_lock(&em_tree->lock);
575 em = lookup_extent_mapping(em_tree, start, len);
577 write_unlock(&em_tree->lock);
581 gen = em->generation;
582 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
583 if (testend && em->start + em->len >= start + len) {
585 write_unlock(&em_tree->lock);
588 start = em->start + em->len;
590 len = start + len - (em->start + em->len);
592 write_unlock(&em_tree->lock);
595 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
596 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
597 clear_bit(EXTENT_FLAG_LOGGING, &flags);
598 modified = !list_empty(&em->list);
599 remove_extent_mapping(em_tree, em);
603 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
605 split->start = em->start;
606 split->len = start - em->start;
607 split->orig_start = em->orig_start;
608 split->block_start = em->block_start;
611 split->block_len = em->block_len;
613 split->block_len = split->len;
614 split->ram_bytes = em->ram_bytes;
615 split->orig_block_len = max(split->block_len,
617 split->generation = gen;
618 split->bdev = em->bdev;
619 split->flags = flags;
620 split->compress_type = em->compress_type;
621 ret = add_extent_mapping(em_tree, split, modified);
622 BUG_ON(ret); /* Logic error */
623 free_extent_map(split);
627 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
628 testend && em->start + em->len > start + len) {
629 u64 diff = start + len - em->start;
631 split->start = start + len;
632 split->len = em->start + em->len - (start + len);
633 split->bdev = em->bdev;
634 split->flags = flags;
635 split->compress_type = em->compress_type;
636 split->generation = gen;
637 split->orig_block_len = max(em->block_len,
639 split->ram_bytes = em->ram_bytes;
642 split->block_len = em->block_len;
643 split->block_start = em->block_start;
644 split->orig_start = em->orig_start;
646 split->block_len = split->len;
647 split->block_start = em->block_start + diff;
648 split->orig_start = em->orig_start;
651 ret = add_extent_mapping(em_tree, split, modified);
652 BUG_ON(ret); /* Logic error */
653 free_extent_map(split);
657 write_unlock(&em_tree->lock);
661 /* once for the tree*/
665 free_extent_map(split);
667 free_extent_map(split2);
671 * this is very complex, but the basic idea is to drop all extents
672 * in the range start - end. hint_block is filled in with a block number
673 * that would be a good hint to the block allocator for this file.
675 * If an extent intersects the range but is not entirely inside the range
676 * it is either truncated or split. Anything entirely inside the range
677 * is deleted from the tree.
679 int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
680 struct btrfs_root *root, struct inode *inode,
681 struct btrfs_path *path, u64 start, u64 end,
682 u64 *drop_end, int drop_cache)
684 struct extent_buffer *leaf;
685 struct btrfs_file_extent_item *fi;
686 struct btrfs_key key;
687 struct btrfs_key new_key;
688 u64 ino = btrfs_ino(inode);
689 u64 search_start = start;
692 u64 extent_offset = 0;
699 int modify_tree = -1;
700 int update_refs = (root->ref_cows || root == root->fs_info->tree_root);
704 btrfs_drop_extent_cache(inode, start, end - 1, 0);
706 if (start >= BTRFS_I(inode)->disk_i_size)
711 ret = btrfs_lookup_file_extent(trans, root, path, ino,
712 search_start, modify_tree);
715 if (ret > 0 && path->slots[0] > 0 && search_start == start) {
716 leaf = path->nodes[0];
717 btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
718 if (key.objectid == ino &&
719 key.type == BTRFS_EXTENT_DATA_KEY)
724 leaf = path->nodes[0];
725 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
727 ret = btrfs_next_leaf(root, path);
734 leaf = path->nodes[0];
738 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
739 if (key.objectid > ino ||
740 key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
743 fi = btrfs_item_ptr(leaf, path->slots[0],
744 struct btrfs_file_extent_item);
745 extent_type = btrfs_file_extent_type(leaf, fi);
747 if (extent_type == BTRFS_FILE_EXTENT_REG ||
748 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
749 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
750 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
751 extent_offset = btrfs_file_extent_offset(leaf, fi);
752 extent_end = key.offset +
753 btrfs_file_extent_num_bytes(leaf, fi);
754 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
755 extent_end = key.offset +
756 btrfs_file_extent_inline_len(leaf, fi);
759 extent_end = search_start;
762 if (extent_end <= search_start) {
768 search_start = max(key.offset, start);
769 if (recow || !modify_tree) {
771 btrfs_release_path(path);
776 * | - range to drop - |
777 * | -------- extent -------- |
779 if (start > key.offset && end < extent_end) {
781 BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
783 memcpy(&new_key, &key, sizeof(new_key));
784 new_key.offset = start;
785 ret = btrfs_duplicate_item(trans, root, path,
787 if (ret == -EAGAIN) {
788 btrfs_release_path(path);
794 leaf = path->nodes[0];
795 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
796 struct btrfs_file_extent_item);
797 btrfs_set_file_extent_num_bytes(leaf, fi,
800 fi = btrfs_item_ptr(leaf, path->slots[0],
801 struct btrfs_file_extent_item);
803 extent_offset += start - key.offset;
804 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
805 btrfs_set_file_extent_num_bytes(leaf, fi,
807 btrfs_mark_buffer_dirty(leaf);
809 if (update_refs && disk_bytenr > 0) {
810 ret = btrfs_inc_extent_ref(trans, root,
811 disk_bytenr, num_bytes, 0,
812 root->root_key.objectid,
814 start - extent_offset, 0);
815 BUG_ON(ret); /* -ENOMEM */
820 * | ---- range to drop ----- |
821 * | -------- extent -------- |
823 if (start <= key.offset && end < extent_end) {
824 BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
826 memcpy(&new_key, &key, sizeof(new_key));
827 new_key.offset = end;
828 btrfs_set_item_key_safe(root, path, &new_key);
830 extent_offset += end - key.offset;
831 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
832 btrfs_set_file_extent_num_bytes(leaf, fi,
834 btrfs_mark_buffer_dirty(leaf);
835 if (update_refs && disk_bytenr > 0)
836 inode_sub_bytes(inode, end - key.offset);
840 search_start = extent_end;
842 * | ---- range to drop ----- |
843 * | -------- extent -------- |
845 if (start > key.offset && end >= extent_end) {
847 BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
849 btrfs_set_file_extent_num_bytes(leaf, fi,
851 btrfs_mark_buffer_dirty(leaf);
852 if (update_refs && disk_bytenr > 0)
853 inode_sub_bytes(inode, extent_end - start);
854 if (end == extent_end)
862 * | ---- range to drop ----- |
863 * | ------ extent ------ |
865 if (start <= key.offset && end >= extent_end) {
867 del_slot = path->slots[0];
870 BUG_ON(del_slot + del_nr != path->slots[0]);
875 extent_type == BTRFS_FILE_EXTENT_INLINE) {
876 inode_sub_bytes(inode,
877 extent_end - key.offset);
878 extent_end = ALIGN(extent_end,
880 } else if (update_refs && disk_bytenr > 0) {
881 ret = btrfs_free_extent(trans, root,
882 disk_bytenr, num_bytes, 0,
883 root->root_key.objectid,
884 key.objectid, key.offset -
886 BUG_ON(ret); /* -ENOMEM */
887 inode_sub_bytes(inode,
888 extent_end - key.offset);
891 if (end == extent_end)
894 if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
899 ret = btrfs_del_items(trans, root, path, del_slot,
902 btrfs_abort_transaction(trans, root, ret);
909 btrfs_release_path(path);
916 if (!ret && del_nr > 0) {
917 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
919 btrfs_abort_transaction(trans, root, ret);
923 *drop_end = found ? min(end, extent_end) : end;
924 btrfs_release_path(path);
928 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
929 struct btrfs_root *root, struct inode *inode, u64 start,
930 u64 end, int drop_cache)
932 struct btrfs_path *path;
935 path = btrfs_alloc_path();
938 ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
940 btrfs_free_path(path);
944 static int extent_mergeable(struct extent_buffer *leaf, int slot,
945 u64 objectid, u64 bytenr, u64 orig_offset,
946 u64 *start, u64 *end)
948 struct btrfs_file_extent_item *fi;
949 struct btrfs_key key;
952 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
955 btrfs_item_key_to_cpu(leaf, &key, slot);
956 if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
959 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
960 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
961 btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
962 btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
963 btrfs_file_extent_compression(leaf, fi) ||
964 btrfs_file_extent_encryption(leaf, fi) ||
965 btrfs_file_extent_other_encoding(leaf, fi))
968 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
969 if ((*start && *start != key.offset) || (*end && *end != extent_end))
978 * Mark extent in the range start - end as written.
980 * This changes extent type from 'pre-allocated' to 'regular'. If only
981 * part of extent is marked as written, the extent will be split into
984 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
985 struct inode *inode, u64 start, u64 end)
987 struct btrfs_root *root = BTRFS_I(inode)->root;
988 struct extent_buffer *leaf;
989 struct btrfs_path *path;
990 struct btrfs_file_extent_item *fi;
991 struct btrfs_key key;
992 struct btrfs_key new_key;
1004 u64 ino = btrfs_ino(inode);
1006 path = btrfs_alloc_path();
1013 key.type = BTRFS_EXTENT_DATA_KEY;
1016 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1019 if (ret > 0 && path->slots[0] > 0)
1022 leaf = path->nodes[0];
1023 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1024 BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
1025 fi = btrfs_item_ptr(leaf, path->slots[0],
1026 struct btrfs_file_extent_item);
1027 BUG_ON(btrfs_file_extent_type(leaf, fi) !=
1028 BTRFS_FILE_EXTENT_PREALLOC);
1029 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1030 BUG_ON(key.offset > start || extent_end < end);
1032 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1033 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1034 orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
1035 memcpy(&new_key, &key, sizeof(new_key));
1037 if (start == key.offset && end < extent_end) {
1040 if (extent_mergeable(leaf, path->slots[0] - 1,
1041 ino, bytenr, orig_offset,
1042 &other_start, &other_end)) {
1043 new_key.offset = end;
1044 btrfs_set_item_key_safe(root, path, &new_key);
1045 fi = btrfs_item_ptr(leaf, path->slots[0],
1046 struct btrfs_file_extent_item);
1047 btrfs_set_file_extent_generation(leaf, fi,
1049 btrfs_set_file_extent_num_bytes(leaf, fi,
1051 btrfs_set_file_extent_offset(leaf, fi,
1053 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1054 struct btrfs_file_extent_item);
1055 btrfs_set_file_extent_generation(leaf, fi,
1057 btrfs_set_file_extent_num_bytes(leaf, fi,
1059 btrfs_mark_buffer_dirty(leaf);
1064 if (start > key.offset && end == extent_end) {
1067 if (extent_mergeable(leaf, path->slots[0] + 1,
1068 ino, bytenr, orig_offset,
1069 &other_start, &other_end)) {
1070 fi = btrfs_item_ptr(leaf, path->slots[0],
1071 struct btrfs_file_extent_item);
1072 btrfs_set_file_extent_num_bytes(leaf, fi,
1073 start - key.offset);
1074 btrfs_set_file_extent_generation(leaf, fi,
1077 new_key.offset = start;
1078 btrfs_set_item_key_safe(root, path, &new_key);
1080 fi = btrfs_item_ptr(leaf, path->slots[0],
1081 struct btrfs_file_extent_item);
1082 btrfs_set_file_extent_generation(leaf, fi,
1084 btrfs_set_file_extent_num_bytes(leaf, fi,
1086 btrfs_set_file_extent_offset(leaf, fi,
1087 start - orig_offset);
1088 btrfs_mark_buffer_dirty(leaf);
1093 while (start > key.offset || end < extent_end) {
1094 if (key.offset == start)
1097 new_key.offset = split;
1098 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1099 if (ret == -EAGAIN) {
1100 btrfs_release_path(path);
1104 btrfs_abort_transaction(trans, root, ret);
1108 leaf = path->nodes[0];
1109 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1110 struct btrfs_file_extent_item);
1111 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1112 btrfs_set_file_extent_num_bytes(leaf, fi,
1113 split - key.offset);
1115 fi = btrfs_item_ptr(leaf, path->slots[0],
1116 struct btrfs_file_extent_item);
1118 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1119 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1120 btrfs_set_file_extent_num_bytes(leaf, fi,
1121 extent_end - split);
1122 btrfs_mark_buffer_dirty(leaf);
1124 ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
1125 root->root_key.objectid,
1126 ino, orig_offset, 0);
1127 BUG_ON(ret); /* -ENOMEM */
1129 if (split == start) {
1132 BUG_ON(start != key.offset);
1141 if (extent_mergeable(leaf, path->slots[0] + 1,
1142 ino, bytenr, orig_offset,
1143 &other_start, &other_end)) {
1145 btrfs_release_path(path);
1148 extent_end = other_end;
1149 del_slot = path->slots[0] + 1;
1151 ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
1152 0, root->root_key.objectid,
1153 ino, orig_offset, 0);
1154 BUG_ON(ret); /* -ENOMEM */
1158 if (extent_mergeable(leaf, path->slots[0] - 1,
1159 ino, bytenr, orig_offset,
1160 &other_start, &other_end)) {
1162 btrfs_release_path(path);
1165 key.offset = other_start;
1166 del_slot = path->slots[0];
1168 ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
1169 0, root->root_key.objectid,
1170 ino, orig_offset, 0);
1171 BUG_ON(ret); /* -ENOMEM */
1174 fi = btrfs_item_ptr(leaf, path->slots[0],
1175 struct btrfs_file_extent_item);
1176 btrfs_set_file_extent_type(leaf, fi,
1177 BTRFS_FILE_EXTENT_REG);
1178 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1179 btrfs_mark_buffer_dirty(leaf);
1181 fi = btrfs_item_ptr(leaf, del_slot - 1,
1182 struct btrfs_file_extent_item);
1183 btrfs_set_file_extent_type(leaf, fi,
1184 BTRFS_FILE_EXTENT_REG);
1185 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1186 btrfs_set_file_extent_num_bytes(leaf, fi,
1187 extent_end - key.offset);
1188 btrfs_mark_buffer_dirty(leaf);
1190 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1192 btrfs_abort_transaction(trans, root, ret);
1197 btrfs_free_path(path);
1202 * on error we return an unlocked page and the error value
1203 * on success we return a locked page and 0
1205 static int prepare_uptodate_page(struct page *page, u64 pos,
1206 bool force_uptodate)
1210 if (((pos & (PAGE_CACHE_SIZE - 1)) || force_uptodate) &&
1211 !PageUptodate(page)) {
1212 ret = btrfs_readpage(NULL, page);
1216 if (!PageUptodate(page)) {
1225 * this gets pages into the page cache and locks them down, it also properly
1226 * waits for data=ordered extents to finish before allowing the pages to be
1229 static noinline int prepare_pages(struct btrfs_root *root, struct file *file,
1230 struct page **pages, size_t num_pages,
1231 loff_t pos, unsigned long first_index,
1232 size_t write_bytes, bool force_uptodate)
1234 struct extent_state *cached_state = NULL;
1236 unsigned long index = pos >> PAGE_CACHE_SHIFT;
1237 struct inode *inode = file_inode(file);
1238 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1244 start_pos = pos & ~((u64)root->sectorsize - 1);
1245 last_pos = ((u64)index + num_pages) << PAGE_CACHE_SHIFT;
1248 for (i = 0; i < num_pages; i++) {
1249 pages[i] = find_or_create_page(inode->i_mapping, index + i,
1250 mask | __GFP_WRITE);
1258 err = prepare_uptodate_page(pages[i], pos,
1260 if (i == num_pages - 1)
1261 err = prepare_uptodate_page(pages[i],
1262 pos + write_bytes, false);
1264 page_cache_release(pages[i]);
1268 wait_on_page_writeback(pages[i]);
1271 if (start_pos < inode->i_size) {
1272 struct btrfs_ordered_extent *ordered;
1273 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1274 start_pos, last_pos - 1, 0, &cached_state);
1275 ordered = btrfs_lookup_first_ordered_extent(inode,
1278 ordered->file_offset + ordered->len > start_pos &&
1279 ordered->file_offset < last_pos) {
1280 btrfs_put_ordered_extent(ordered);
1281 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1282 start_pos, last_pos - 1,
1283 &cached_state, GFP_NOFS);
1284 for (i = 0; i < num_pages; i++) {
1285 unlock_page(pages[i]);
1286 page_cache_release(pages[i]);
1288 btrfs_wait_ordered_range(inode, start_pos,
1289 last_pos - start_pos);
1293 btrfs_put_ordered_extent(ordered);
1295 clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
1296 last_pos - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1297 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
1298 0, 0, &cached_state, GFP_NOFS);
1299 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1300 start_pos, last_pos - 1, &cached_state,
1303 for (i = 0; i < num_pages; i++) {
1304 if (clear_page_dirty_for_io(pages[i]))
1305 account_page_redirty(pages[i]);
1306 set_page_extent_mapped(pages[i]);
1307 WARN_ON(!PageLocked(pages[i]));
1311 while (faili >= 0) {
1312 unlock_page(pages[faili]);
1313 page_cache_release(pages[faili]);
1320 static noinline ssize_t __btrfs_buffered_write(struct file *file,
1324 struct inode *inode = file_inode(file);
1325 struct btrfs_root *root = BTRFS_I(inode)->root;
1326 struct page **pages = NULL;
1327 unsigned long first_index;
1328 size_t num_written = 0;
1331 bool force_page_uptodate = false;
1333 nrptrs = min((iov_iter_count(i) + PAGE_CACHE_SIZE - 1) /
1334 PAGE_CACHE_SIZE, PAGE_CACHE_SIZE /
1335 (sizeof(struct page *)));
1336 nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1337 nrptrs = max(nrptrs, 8);
1338 pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
1342 first_index = pos >> PAGE_CACHE_SHIFT;
1344 while (iov_iter_count(i) > 0) {
1345 size_t offset = pos & (PAGE_CACHE_SIZE - 1);
1346 size_t write_bytes = min(iov_iter_count(i),
1347 nrptrs * (size_t)PAGE_CACHE_SIZE -
1349 size_t num_pages = (write_bytes + offset +
1350 PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1354 WARN_ON(num_pages > nrptrs);
1357 * Fault pages before locking them in prepare_pages
1358 * to avoid recursive lock
1360 if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
1365 ret = btrfs_delalloc_reserve_space(inode,
1366 num_pages << PAGE_CACHE_SHIFT);
1371 * This is going to setup the pages array with the number of
1372 * pages we want, so we don't really need to worry about the
1373 * contents of pages from loop to loop
1375 ret = prepare_pages(root, file, pages, num_pages,
1376 pos, first_index, write_bytes,
1377 force_page_uptodate);
1379 btrfs_delalloc_release_space(inode,
1380 num_pages << PAGE_CACHE_SHIFT);
1384 copied = btrfs_copy_from_user(pos, num_pages,
1385 write_bytes, pages, i);
1388 * if we have trouble faulting in the pages, fall
1389 * back to one page at a time
1391 if (copied < write_bytes)
1395 force_page_uptodate = true;
1398 force_page_uptodate = false;
1399 dirty_pages = (copied + offset +
1400 PAGE_CACHE_SIZE - 1) >>
1405 * If we had a short copy we need to release the excess delaloc
1406 * bytes we reserved. We need to increment outstanding_extents
1407 * because btrfs_delalloc_release_space will decrement it, but
1408 * we still have an outstanding extent for the chunk we actually
1411 if (num_pages > dirty_pages) {
1413 spin_lock(&BTRFS_I(inode)->lock);
1414 BTRFS_I(inode)->outstanding_extents++;
1415 spin_unlock(&BTRFS_I(inode)->lock);
1417 btrfs_delalloc_release_space(inode,
1418 (num_pages - dirty_pages) <<
1423 ret = btrfs_dirty_pages(root, inode, pages,
1424 dirty_pages, pos, copied,
1427 btrfs_delalloc_release_space(inode,
1428 dirty_pages << PAGE_CACHE_SHIFT);
1429 btrfs_drop_pages(pages, num_pages);
1434 btrfs_drop_pages(pages, num_pages);
1438 balance_dirty_pages_ratelimited(inode->i_mapping);
1439 if (dirty_pages < (root->leafsize >> PAGE_CACHE_SHIFT) + 1)
1440 btrfs_btree_balance_dirty(root);
1443 num_written += copied;
1448 return num_written ? num_written : ret;
1451 static ssize_t __btrfs_direct_write(struct kiocb *iocb,
1452 const struct iovec *iov,
1453 unsigned long nr_segs, loff_t pos,
1454 loff_t *ppos, size_t count, size_t ocount)
1456 struct file *file = iocb->ki_filp;
1459 ssize_t written_buffered;
1463 written = generic_file_direct_write(iocb, iov, &nr_segs, pos, ppos,
1466 if (written < 0 || written == count)
1471 iov_iter_init(&i, iov, nr_segs, count, written);
1472 written_buffered = __btrfs_buffered_write(file, &i, pos);
1473 if (written_buffered < 0) {
1474 err = written_buffered;
1477 endbyte = pos + written_buffered - 1;
1478 err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
1481 written += written_buffered;
1482 *ppos = pos + written_buffered;
1483 invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
1484 endbyte >> PAGE_CACHE_SHIFT);
1486 return written ? written : err;
1489 static void update_time_for_write(struct inode *inode)
1491 struct timespec now;
1493 if (IS_NOCMTIME(inode))
1496 now = current_fs_time(inode->i_sb);
1497 if (!timespec_equal(&inode->i_mtime, &now))
1498 inode->i_mtime = now;
1500 if (!timespec_equal(&inode->i_ctime, &now))
1501 inode->i_ctime = now;
1503 if (IS_I_VERSION(inode))
1504 inode_inc_iversion(inode);
1507 static ssize_t btrfs_file_aio_write(struct kiocb *iocb,
1508 const struct iovec *iov,
1509 unsigned long nr_segs, loff_t pos)
1511 struct file *file = iocb->ki_filp;
1512 struct inode *inode = file_inode(file);
1513 struct btrfs_root *root = BTRFS_I(inode)->root;
1514 loff_t *ppos = &iocb->ki_pos;
1516 ssize_t num_written = 0;
1518 size_t count, ocount;
1519 bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
1521 mutex_lock(&inode->i_mutex);
1523 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
1525 mutex_unlock(&inode->i_mutex);
1530 current->backing_dev_info = inode->i_mapping->backing_dev_info;
1531 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
1533 mutex_unlock(&inode->i_mutex);
1538 mutex_unlock(&inode->i_mutex);
1542 err = file_remove_suid(file);
1544 mutex_unlock(&inode->i_mutex);
1549 * If BTRFS flips readonly due to some impossible error
1550 * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
1551 * although we have opened a file as writable, we have
1552 * to stop this write operation to ensure FS consistency.
1554 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
1555 mutex_unlock(&inode->i_mutex);
1561 * We reserve space for updating the inode when we reserve space for the
1562 * extent we are going to write, so we will enospc out there. We don't
1563 * need to start yet another transaction to update the inode as we will
1564 * update the inode when we finish writing whatever data we write.
1566 update_time_for_write(inode);
1568 start_pos = round_down(pos, root->sectorsize);
1569 if (start_pos > i_size_read(inode)) {
1570 err = btrfs_cont_expand(inode, i_size_read(inode), start_pos);
1572 mutex_unlock(&inode->i_mutex);
1578 atomic_inc(&BTRFS_I(inode)->sync_writers);
1580 if (unlikely(file->f_flags & O_DIRECT)) {
1581 num_written = __btrfs_direct_write(iocb, iov, nr_segs,
1582 pos, ppos, count, ocount);
1586 iov_iter_init(&i, iov, nr_segs, count, num_written);
1588 num_written = __btrfs_buffered_write(file, &i, pos);
1589 if (num_written > 0)
1590 *ppos = pos + num_written;
1593 mutex_unlock(&inode->i_mutex);
1596 * we want to make sure fsync finds this change
1597 * but we haven't joined a transaction running right now.
1599 * Later on, someone is sure to update the inode and get the
1600 * real transid recorded.
1602 * We set last_trans now to the fs_info generation + 1,
1603 * this will either be one more than the running transaction
1604 * or the generation used for the next transaction if there isn't
1605 * one running right now.
1607 * We also have to set last_sub_trans to the current log transid,
1608 * otherwise subsequent syncs to a file that's been synced in this
1609 * transaction will appear to have already occured.
1611 BTRFS_I(inode)->last_trans = root->fs_info->generation + 1;
1612 BTRFS_I(inode)->last_sub_trans = root->log_transid;
1613 if (num_written > 0 || num_written == -EIOCBQUEUED) {
1614 err = generic_write_sync(file, pos, num_written);
1615 if (err < 0 && num_written > 0)
1620 atomic_dec(&BTRFS_I(inode)->sync_writers);
1622 current->backing_dev_info = NULL;
1623 return num_written ? num_written : err;
1626 int btrfs_release_file(struct inode *inode, struct file *filp)
1629 * ordered_data_close is set by settattr when we are about to truncate
1630 * a file from a non-zero size to a zero size. This tries to
1631 * flush down new bytes that may have been written if the
1632 * application were using truncate to replace a file in place.
1634 if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
1635 &BTRFS_I(inode)->runtime_flags)) {
1636 struct btrfs_trans_handle *trans;
1637 struct btrfs_root *root = BTRFS_I(inode)->root;
1640 * We need to block on a committing transaction to keep us from
1641 * throwing a ordered operation on to the list and causing
1642 * something like sync to deadlock trying to flush out this
1645 trans = btrfs_start_transaction(root, 0);
1647 return PTR_ERR(trans);
1648 btrfs_add_ordered_operation(trans, BTRFS_I(inode)->root, inode);
1649 btrfs_end_transaction(trans, root);
1650 if (inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
1651 filemap_flush(inode->i_mapping);
1653 if (filp->private_data)
1654 btrfs_ioctl_trans_end(filp);
1659 * fsync call for both files and directories. This logs the inode into
1660 * the tree log instead of forcing full commits whenever possible.
1662 * It needs to call filemap_fdatawait so that all ordered extent updates are
1663 * in the metadata btree are up to date for copying to the log.
1665 * It drops the inode mutex before doing the tree log commit. This is an
1666 * important optimization for directories because holding the mutex prevents
1667 * new operations on the dir while we write to disk.
1669 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
1671 struct dentry *dentry = file->f_path.dentry;
1672 struct inode *inode = dentry->d_inode;
1673 struct btrfs_root *root = BTRFS_I(inode)->root;
1675 struct btrfs_trans_handle *trans;
1678 trace_btrfs_sync_file(file, datasync);
1681 * We write the dirty pages in the range and wait until they complete
1682 * out of the ->i_mutex. If so, we can flush the dirty pages by
1683 * multi-task, and make the performance up. See
1684 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
1686 atomic_inc(&BTRFS_I(inode)->sync_writers);
1687 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
1688 if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1689 &BTRFS_I(inode)->runtime_flags))
1690 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
1691 atomic_dec(&BTRFS_I(inode)->sync_writers);
1695 mutex_lock(&inode->i_mutex);
1698 * We flush the dirty pages again to avoid some dirty pages in the
1701 atomic_inc(&root->log_batch);
1702 full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1703 &BTRFS_I(inode)->runtime_flags);
1705 btrfs_wait_ordered_range(inode, start, end - start + 1);
1706 atomic_inc(&root->log_batch);
1709 * check the transaction that last modified this inode
1710 * and see if its already been committed
1712 if (!BTRFS_I(inode)->last_trans) {
1713 mutex_unlock(&inode->i_mutex);
1718 * if the last transaction that changed this file was before
1719 * the current transaction, we can bail out now without any
1723 if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
1724 BTRFS_I(inode)->last_trans <=
1725 root->fs_info->last_trans_committed) {
1726 BTRFS_I(inode)->last_trans = 0;
1729 * We'v had everything committed since the last time we were
1730 * modified so clear this flag in case it was set for whatever
1731 * reason, it's no longer relevant.
1733 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1734 &BTRFS_I(inode)->runtime_flags);
1735 mutex_unlock(&inode->i_mutex);
1740 * ok we haven't committed the transaction yet, lets do a commit
1742 if (file->private_data)
1743 btrfs_ioctl_trans_end(file);
1745 trans = btrfs_start_transaction(root, 0);
1746 if (IS_ERR(trans)) {
1747 ret = PTR_ERR(trans);
1748 mutex_unlock(&inode->i_mutex);
1752 ret = btrfs_log_dentry_safe(trans, root, dentry);
1754 mutex_unlock(&inode->i_mutex);
1758 /* we've logged all the items and now have a consistent
1759 * version of the file in the log. It is possible that
1760 * someone will come in and modify the file, but that's
1761 * fine because the log is consistent on disk, and we
1762 * have references to all of the file's extents
1764 * It is possible that someone will come in and log the
1765 * file again, but that will end up using the synchronization
1766 * inside btrfs_sync_log to keep things safe.
1768 mutex_unlock(&inode->i_mutex);
1770 if (ret != BTRFS_NO_LOG_SYNC) {
1773 * If we didn't already wait for ordered extents we need
1777 btrfs_wait_ordered_range(inode, start,
1779 ret = btrfs_commit_transaction(trans, root);
1781 ret = btrfs_sync_log(trans, root);
1783 ret = btrfs_end_transaction(trans, root);
1786 btrfs_wait_ordered_range(inode, start,
1789 ret = btrfs_commit_transaction(trans, root);
1793 ret = btrfs_end_transaction(trans, root);
1796 return ret > 0 ? -EIO : ret;
1799 static const struct vm_operations_struct btrfs_file_vm_ops = {
1800 .fault = filemap_fault,
1801 .page_mkwrite = btrfs_page_mkwrite,
1802 .remap_pages = generic_file_remap_pages,
1805 static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
1807 struct address_space *mapping = filp->f_mapping;
1809 if (!mapping->a_ops->readpage)
1812 file_accessed(filp);
1813 vma->vm_ops = &btrfs_file_vm_ops;
1818 static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
1819 int slot, u64 start, u64 end)
1821 struct btrfs_file_extent_item *fi;
1822 struct btrfs_key key;
1824 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1827 btrfs_item_key_to_cpu(leaf, &key, slot);
1828 if (key.objectid != btrfs_ino(inode) ||
1829 key.type != BTRFS_EXTENT_DATA_KEY)
1832 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1834 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
1837 if (btrfs_file_extent_disk_bytenr(leaf, fi))
1840 if (key.offset == end)
1842 if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
1847 static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
1848 struct btrfs_path *path, u64 offset, u64 end)
1850 struct btrfs_root *root = BTRFS_I(inode)->root;
1851 struct extent_buffer *leaf;
1852 struct btrfs_file_extent_item *fi;
1853 struct extent_map *hole_em;
1854 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1855 struct btrfs_key key;
1858 key.objectid = btrfs_ino(inode);
1859 key.type = BTRFS_EXTENT_DATA_KEY;
1860 key.offset = offset;
1863 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1868 leaf = path->nodes[0];
1869 if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
1873 fi = btrfs_item_ptr(leaf, path->slots[0],
1874 struct btrfs_file_extent_item);
1875 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
1877 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1878 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
1879 btrfs_set_file_extent_offset(leaf, fi, 0);
1880 btrfs_mark_buffer_dirty(leaf);
1884 if (hole_mergeable(inode, leaf, path->slots[0]+1, offset, end)) {
1888 key.offset = offset;
1889 btrfs_set_item_key_safe(root, path, &key);
1890 fi = btrfs_item_ptr(leaf, path->slots[0],
1891 struct btrfs_file_extent_item);
1892 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
1894 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1895 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
1896 btrfs_set_file_extent_offset(leaf, fi, 0);
1897 btrfs_mark_buffer_dirty(leaf);
1900 btrfs_release_path(path);
1902 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
1903 0, 0, end - offset, 0, end - offset,
1909 btrfs_release_path(path);
1911 hole_em = alloc_extent_map();
1913 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
1914 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1915 &BTRFS_I(inode)->runtime_flags);
1917 hole_em->start = offset;
1918 hole_em->len = end - offset;
1919 hole_em->ram_bytes = hole_em->len;
1920 hole_em->orig_start = offset;
1922 hole_em->block_start = EXTENT_MAP_HOLE;
1923 hole_em->block_len = 0;
1924 hole_em->orig_block_len = 0;
1925 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
1926 hole_em->compress_type = BTRFS_COMPRESS_NONE;
1927 hole_em->generation = trans->transid;
1930 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
1931 write_lock(&em_tree->lock);
1932 ret = add_extent_mapping(em_tree, hole_em, 1);
1933 write_unlock(&em_tree->lock);
1934 } while (ret == -EEXIST);
1935 free_extent_map(hole_em);
1937 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1938 &BTRFS_I(inode)->runtime_flags);
1944 static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
1946 struct btrfs_root *root = BTRFS_I(inode)->root;
1947 struct extent_state *cached_state = NULL;
1948 struct btrfs_path *path;
1949 struct btrfs_block_rsv *rsv;
1950 struct btrfs_trans_handle *trans;
1951 u64 lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
1952 u64 lockend = round_down(offset + len,
1953 BTRFS_I(inode)->root->sectorsize) - 1;
1954 u64 cur_offset = lockstart;
1955 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
1959 bool same_page = ((offset >> PAGE_CACHE_SHIFT) ==
1960 ((offset + len - 1) >> PAGE_CACHE_SHIFT));
1962 btrfs_wait_ordered_range(inode, offset, len);
1964 mutex_lock(&inode->i_mutex);
1966 * We needn't truncate any page which is beyond the end of the file
1967 * because we are sure there is no data there.
1970 * Only do this if we are in the same page and we aren't doing the
1973 if (same_page && len < PAGE_CACHE_SIZE) {
1974 if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE))
1975 ret = btrfs_truncate_page(inode, offset, len, 0);
1976 mutex_unlock(&inode->i_mutex);
1980 /* zero back part of the first page */
1981 if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
1982 ret = btrfs_truncate_page(inode, offset, 0, 0);
1984 mutex_unlock(&inode->i_mutex);
1989 /* zero the front end of the last page */
1990 if (offset + len < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
1991 ret = btrfs_truncate_page(inode, offset + len, 0, 1);
1993 mutex_unlock(&inode->i_mutex);
1998 if (lockend < lockstart) {
1999 mutex_unlock(&inode->i_mutex);
2004 struct btrfs_ordered_extent *ordered;
2006 truncate_pagecache_range(inode, lockstart, lockend);
2008 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2010 ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
2013 * We need to make sure we have no ordered extents in this range
2014 * and nobody raced in and read a page in this range, if we did
2015 * we need to try again.
2018 (ordered->file_offset + ordered->len < lockstart ||
2019 ordered->file_offset > lockend)) &&
2020 !test_range_bit(&BTRFS_I(inode)->io_tree, lockstart,
2021 lockend, EXTENT_UPTODATE, 0,
2024 btrfs_put_ordered_extent(ordered);
2028 btrfs_put_ordered_extent(ordered);
2029 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2030 lockend, &cached_state, GFP_NOFS);
2031 btrfs_wait_ordered_range(inode, lockstart,
2032 lockend - lockstart + 1);
2035 path = btrfs_alloc_path();
2041 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2046 rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
2050 * 1 - update the inode
2051 * 1 - removing the extents in the range
2052 * 1 - adding the hole extent
2054 trans = btrfs_start_transaction(root, 3);
2055 if (IS_ERR(trans)) {
2056 err = PTR_ERR(trans);
2060 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
2063 trans->block_rsv = rsv;
2065 while (cur_offset < lockend) {
2066 ret = __btrfs_drop_extents(trans, root, inode, path,
2067 cur_offset, lockend + 1,
2072 trans->block_rsv = &root->fs_info->trans_block_rsv;
2074 ret = fill_holes(trans, inode, path, cur_offset, drop_end);
2080 cur_offset = drop_end;
2082 ret = btrfs_update_inode(trans, root, inode);
2088 btrfs_end_transaction(trans, root);
2089 btrfs_btree_balance_dirty(root);
2091 trans = btrfs_start_transaction(root, 3);
2092 if (IS_ERR(trans)) {
2093 ret = PTR_ERR(trans);
2098 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
2100 BUG_ON(ret); /* shouldn't happen */
2101 trans->block_rsv = rsv;
2109 trans->block_rsv = &root->fs_info->trans_block_rsv;
2110 ret = fill_holes(trans, inode, path, cur_offset, drop_end);
2120 inode_inc_iversion(inode);
2121 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
2123 trans->block_rsv = &root->fs_info->trans_block_rsv;
2124 ret = btrfs_update_inode(trans, root, inode);
2125 btrfs_end_transaction(trans, root);
2126 btrfs_btree_balance_dirty(root);
2128 btrfs_free_path(path);
2129 btrfs_free_block_rsv(root, rsv);
2131 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2132 &cached_state, GFP_NOFS);
2133 mutex_unlock(&inode->i_mutex);
2139 static long btrfs_fallocate(struct file *file, int mode,
2140 loff_t offset, loff_t len)
2142 struct inode *inode = file_inode(file);
2143 struct extent_state *cached_state = NULL;
2144 struct btrfs_root *root = BTRFS_I(inode)->root;
2151 struct extent_map *em;
2152 int blocksize = BTRFS_I(inode)->root->sectorsize;
2155 alloc_start = round_down(offset, blocksize);
2156 alloc_end = round_up(offset + len, blocksize);
2158 /* Make sure we aren't being give some crap mode */
2159 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2162 if (mode & FALLOC_FL_PUNCH_HOLE)
2163 return btrfs_punch_hole(inode, offset, len);
2166 * Make sure we have enough space before we do the
2169 ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
2172 if (root->fs_info->quota_enabled) {
2173 ret = btrfs_qgroup_reserve(root, alloc_end - alloc_start);
2175 goto out_reserve_fail;
2179 * wait for ordered IO before we have any locks. We'll loop again
2180 * below with the locks held.
2182 btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
2184 mutex_lock(&inode->i_mutex);
2185 ret = inode_newsize_ok(inode, alloc_end);
2189 if (alloc_start > inode->i_size) {
2190 ret = btrfs_cont_expand(inode, i_size_read(inode),
2196 locked_end = alloc_end - 1;
2198 struct btrfs_ordered_extent *ordered;
2200 /* the extent lock is ordered inside the running
2203 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
2204 locked_end, 0, &cached_state);
2205 ordered = btrfs_lookup_first_ordered_extent(inode,
2208 ordered->file_offset + ordered->len > alloc_start &&
2209 ordered->file_offset < alloc_end) {
2210 btrfs_put_ordered_extent(ordered);
2211 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
2212 alloc_start, locked_end,
2213 &cached_state, GFP_NOFS);
2215 * we can't wait on the range with the transaction
2216 * running or with the extent lock held
2218 btrfs_wait_ordered_range(inode, alloc_start,
2219 alloc_end - alloc_start);
2222 btrfs_put_ordered_extent(ordered);
2227 cur_offset = alloc_start;
2231 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
2232 alloc_end - cur_offset, 0);
2233 if (IS_ERR_OR_NULL(em)) {
2240 last_byte = min(extent_map_end(em), alloc_end);
2241 actual_end = min_t(u64, extent_map_end(em), offset + len);
2242 last_byte = ALIGN(last_byte, blocksize);
2244 if (em->block_start == EXTENT_MAP_HOLE ||
2245 (cur_offset >= inode->i_size &&
2246 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
2247 ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
2248 last_byte - cur_offset,
2249 1 << inode->i_blkbits,
2254 free_extent_map(em);
2257 } else if (actual_end > inode->i_size &&
2258 !(mode & FALLOC_FL_KEEP_SIZE)) {
2260 * We didn't need to allocate any more space, but we
2261 * still extended the size of the file so we need to
2264 inode->i_ctime = CURRENT_TIME;
2265 i_size_write(inode, actual_end);
2266 btrfs_ordered_update_i_size(inode, actual_end, NULL);
2268 free_extent_map(em);
2270 cur_offset = last_byte;
2271 if (cur_offset >= alloc_end) {
2276 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
2277 &cached_state, GFP_NOFS);
2279 mutex_unlock(&inode->i_mutex);
2280 if (root->fs_info->quota_enabled)
2281 btrfs_qgroup_free(root, alloc_end - alloc_start);
2283 /* Let go of our reservation. */
2284 btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
2288 static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
2290 struct btrfs_root *root = BTRFS_I(inode)->root;
2291 struct extent_map *em;
2292 struct extent_state *cached_state = NULL;
2293 u64 lockstart = *offset;
2294 u64 lockend = i_size_read(inode);
2295 u64 start = *offset;
2296 u64 orig_start = *offset;
2297 u64 len = i_size_read(inode);
2301 lockend = max_t(u64, root->sectorsize, lockend);
2302 if (lockend <= lockstart)
2303 lockend = lockstart + root->sectorsize;
2306 len = lockend - lockstart + 1;
2308 len = max_t(u64, len, root->sectorsize);
2309 if (inode->i_size == 0)
2312 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
2316 * Delalloc is such a pain. If we have a hole and we have pending
2317 * delalloc for a portion of the hole we will get back a hole that
2318 * exists for the entire range since it hasn't been actually written
2319 * yet. So to take care of this case we need to look for an extent just
2320 * before the position we want in case there is outstanding delalloc
2323 if (whence == SEEK_HOLE && start != 0) {
2324 if (start <= root->sectorsize)
2325 em = btrfs_get_extent_fiemap(inode, NULL, 0, 0,
2326 root->sectorsize, 0);
2328 em = btrfs_get_extent_fiemap(inode, NULL, 0,
2329 start - root->sectorsize,
2330 root->sectorsize, 0);
2335 last_end = em->start + em->len;
2336 if (em->block_start == EXTENT_MAP_DELALLOC)
2337 last_end = min_t(u64, last_end, inode->i_size);
2338 free_extent_map(em);
2342 em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
2348 if (em->block_start == EXTENT_MAP_HOLE) {
2349 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2350 if (last_end <= orig_start) {
2351 free_extent_map(em);
2357 if (whence == SEEK_HOLE) {
2359 free_extent_map(em);
2363 if (whence == SEEK_DATA) {
2364 if (em->block_start == EXTENT_MAP_DELALLOC) {
2365 if (start >= inode->i_size) {
2366 free_extent_map(em);
2372 if (!test_bit(EXTENT_FLAG_PREALLOC,
2375 free_extent_map(em);
2381 start = em->start + em->len;
2382 last_end = em->start + em->len;
2384 if (em->block_start == EXTENT_MAP_DELALLOC)
2385 last_end = min_t(u64, last_end, inode->i_size);
2387 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2388 free_extent_map(em);
2392 free_extent_map(em);
2396 *offset = min(*offset, inode->i_size);
2398 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2399 &cached_state, GFP_NOFS);
2403 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
2405 struct inode *inode = file->f_mapping->host;
2408 mutex_lock(&inode->i_mutex);
2412 offset = generic_file_llseek(file, offset, whence);
2416 if (offset >= i_size_read(inode)) {
2417 mutex_unlock(&inode->i_mutex);
2421 ret = find_desired_extent(inode, &offset, whence);
2423 mutex_unlock(&inode->i_mutex);
2428 if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET)) {
2432 if (offset > inode->i_sb->s_maxbytes) {
2437 /* Special lock needed here? */
2438 if (offset != file->f_pos) {
2439 file->f_pos = offset;
2440 file->f_version = 0;
2443 mutex_unlock(&inode->i_mutex);
2447 const struct file_operations btrfs_file_operations = {
2448 .llseek = btrfs_file_llseek,
2449 .read = do_sync_read,
2450 .write = do_sync_write,
2451 .aio_read = generic_file_aio_read,
2452 .splice_read = generic_file_splice_read,
2453 .aio_write = btrfs_file_aio_write,
2454 .mmap = btrfs_file_mmap,
2455 .open = generic_file_open,
2456 .release = btrfs_release_file,
2457 .fsync = btrfs_sync_file,
2458 .fallocate = btrfs_fallocate,
2459 .unlocked_ioctl = btrfs_ioctl,
2460 #ifdef CONFIG_COMPAT
2461 .compat_ioctl = btrfs_ioctl,
2465 void btrfs_auto_defrag_exit(void)
2467 if (btrfs_inode_defrag_cachep)
2468 kmem_cache_destroy(btrfs_inode_defrag_cachep);
2471 int btrfs_auto_defrag_init(void)
2473 btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
2474 sizeof(struct inode_defrag), 0,
2475 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
2477 if (!btrfs_inode_defrag_cachep)