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 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 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;
557 WARN_ON(end < start);
558 if (end == (u64)-1) {
566 split = alloc_extent_map();
568 split2 = alloc_extent_map();
569 if (!split || !split2)
572 write_lock(&em_tree->lock);
573 em = lookup_extent_mapping(em_tree, start, len);
575 write_unlock(&em_tree->lock);
579 gen = em->generation;
580 if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
581 if (testend && em->start + em->len >= start + len) {
583 write_unlock(&em_tree->lock);
586 start = em->start + em->len;
588 len = start + len - (em->start + em->len);
590 write_unlock(&em_tree->lock);
593 compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
594 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
595 clear_bit(EXTENT_FLAG_LOGGING, &flags);
596 remove_extent_mapping(em_tree, em);
600 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
602 split->start = em->start;
603 split->len = start - em->start;
604 split->orig_start = em->orig_start;
605 split->block_start = em->block_start;
608 split->block_len = em->block_len;
610 split->block_len = split->len;
611 split->orig_block_len = max(split->block_len,
613 split->generation = gen;
614 split->bdev = em->bdev;
615 split->flags = flags;
616 split->compress_type = em->compress_type;
617 ret = add_extent_mapping(em_tree, split);
618 BUG_ON(ret); /* Logic error */
619 list_move(&split->list, &em_tree->modified_extents);
620 free_extent_map(split);
624 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
625 testend && em->start + em->len > start + len) {
626 u64 diff = start + len - em->start;
628 split->start = start + len;
629 split->len = em->start + em->len - (start + len);
630 split->bdev = em->bdev;
631 split->flags = flags;
632 split->compress_type = em->compress_type;
633 split->generation = gen;
634 split->orig_block_len = max(em->block_len,
638 split->block_len = em->block_len;
639 split->block_start = em->block_start;
640 split->orig_start = em->orig_start;
642 split->block_len = split->len;
643 split->block_start = em->block_start + diff;
644 split->orig_start = em->orig_start;
647 ret = add_extent_mapping(em_tree, split);
648 BUG_ON(ret); /* Logic error */
649 list_move(&split->list, &em_tree->modified_extents);
650 free_extent_map(split);
654 write_unlock(&em_tree->lock);
658 /* once for the tree*/
662 free_extent_map(split);
664 free_extent_map(split2);
668 * this is very complex, but the basic idea is to drop all extents
669 * in the range start - end. hint_block is filled in with a block number
670 * that would be a good hint to the block allocator for this file.
672 * If an extent intersects the range but is not entirely inside the range
673 * it is either truncated or split. Anything entirely inside the range
674 * is deleted from the tree.
676 int __btrfs_drop_extents(struct btrfs_trans_handle *trans,
677 struct btrfs_root *root, struct inode *inode,
678 struct btrfs_path *path, u64 start, u64 end,
679 u64 *drop_end, int drop_cache)
681 struct extent_buffer *leaf;
682 struct btrfs_file_extent_item *fi;
683 struct btrfs_key key;
684 struct btrfs_key new_key;
685 u64 ino = btrfs_ino(inode);
686 u64 search_start = start;
689 u64 extent_offset = 0;
696 int modify_tree = -1;
697 int update_refs = (root->ref_cows || root == root->fs_info->tree_root);
701 btrfs_drop_extent_cache(inode, start, end - 1, 0);
703 if (start >= BTRFS_I(inode)->disk_i_size)
708 ret = btrfs_lookup_file_extent(trans, root, path, ino,
709 search_start, modify_tree);
712 if (ret > 0 && path->slots[0] > 0 && search_start == start) {
713 leaf = path->nodes[0];
714 btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
715 if (key.objectid == ino &&
716 key.type == BTRFS_EXTENT_DATA_KEY)
721 leaf = path->nodes[0];
722 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
724 ret = btrfs_next_leaf(root, path);
731 leaf = path->nodes[0];
735 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
736 if (key.objectid > ino ||
737 key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= end)
740 fi = btrfs_item_ptr(leaf, path->slots[0],
741 struct btrfs_file_extent_item);
742 extent_type = btrfs_file_extent_type(leaf, fi);
744 if (extent_type == BTRFS_FILE_EXTENT_REG ||
745 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
746 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
747 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
748 extent_offset = btrfs_file_extent_offset(leaf, fi);
749 extent_end = key.offset +
750 btrfs_file_extent_num_bytes(leaf, fi);
751 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
752 extent_end = key.offset +
753 btrfs_file_extent_inline_len(leaf, fi);
756 extent_end = search_start;
759 if (extent_end <= search_start) {
765 search_start = max(key.offset, start);
766 if (recow || !modify_tree) {
768 btrfs_release_path(path);
773 * | - range to drop - |
774 * | -------- extent -------- |
776 if (start > key.offset && end < extent_end) {
778 BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
780 memcpy(&new_key, &key, sizeof(new_key));
781 new_key.offset = start;
782 ret = btrfs_duplicate_item(trans, root, path,
784 if (ret == -EAGAIN) {
785 btrfs_release_path(path);
791 leaf = path->nodes[0];
792 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
793 struct btrfs_file_extent_item);
794 btrfs_set_file_extent_num_bytes(leaf, fi,
797 fi = btrfs_item_ptr(leaf, path->slots[0],
798 struct btrfs_file_extent_item);
800 extent_offset += start - key.offset;
801 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
802 btrfs_set_file_extent_num_bytes(leaf, fi,
804 btrfs_mark_buffer_dirty(leaf);
806 if (update_refs && disk_bytenr > 0) {
807 ret = btrfs_inc_extent_ref(trans, root,
808 disk_bytenr, num_bytes, 0,
809 root->root_key.objectid,
811 start - extent_offset, 0);
812 BUG_ON(ret); /* -ENOMEM */
817 * | ---- range to drop ----- |
818 * | -------- extent -------- |
820 if (start <= key.offset && end < extent_end) {
821 BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
823 memcpy(&new_key, &key, sizeof(new_key));
824 new_key.offset = end;
825 btrfs_set_item_key_safe(trans, root, path, &new_key);
827 extent_offset += end - key.offset;
828 btrfs_set_file_extent_offset(leaf, fi, extent_offset);
829 btrfs_set_file_extent_num_bytes(leaf, fi,
831 btrfs_mark_buffer_dirty(leaf);
832 if (update_refs && disk_bytenr > 0)
833 inode_sub_bytes(inode, end - key.offset);
837 search_start = extent_end;
839 * | ---- range to drop ----- |
840 * | -------- extent -------- |
842 if (start > key.offset && end >= extent_end) {
844 BUG_ON(extent_type == BTRFS_FILE_EXTENT_INLINE);
846 btrfs_set_file_extent_num_bytes(leaf, fi,
848 btrfs_mark_buffer_dirty(leaf);
849 if (update_refs && disk_bytenr > 0)
850 inode_sub_bytes(inode, extent_end - start);
851 if (end == extent_end)
859 * | ---- range to drop ----- |
860 * | ------ extent ------ |
862 if (start <= key.offset && end >= extent_end) {
864 del_slot = path->slots[0];
867 BUG_ON(del_slot + del_nr != path->slots[0]);
872 extent_type == BTRFS_FILE_EXTENT_INLINE) {
873 inode_sub_bytes(inode,
874 extent_end - key.offset);
875 extent_end = ALIGN(extent_end,
877 } else if (update_refs && disk_bytenr > 0) {
878 ret = btrfs_free_extent(trans, root,
879 disk_bytenr, num_bytes, 0,
880 root->root_key.objectid,
881 key.objectid, key.offset -
883 BUG_ON(ret); /* -ENOMEM */
884 inode_sub_bytes(inode,
885 extent_end - key.offset);
888 if (end == extent_end)
891 if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
896 ret = btrfs_del_items(trans, root, path, del_slot,
899 btrfs_abort_transaction(trans, root, ret);
906 btrfs_release_path(path);
913 if (!ret && del_nr > 0) {
914 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
916 btrfs_abort_transaction(trans, root, ret);
920 *drop_end = found ? min(end, extent_end) : end;
921 btrfs_release_path(path);
925 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
926 struct btrfs_root *root, struct inode *inode, u64 start,
927 u64 end, int drop_cache)
929 struct btrfs_path *path;
932 path = btrfs_alloc_path();
935 ret = __btrfs_drop_extents(trans, root, inode, path, start, end, NULL,
937 btrfs_free_path(path);
941 static int extent_mergeable(struct extent_buffer *leaf, int slot,
942 u64 objectid, u64 bytenr, u64 orig_offset,
943 u64 *start, u64 *end)
945 struct btrfs_file_extent_item *fi;
946 struct btrfs_key key;
949 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
952 btrfs_item_key_to_cpu(leaf, &key, slot);
953 if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
956 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
957 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
958 btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
959 btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
960 btrfs_file_extent_compression(leaf, fi) ||
961 btrfs_file_extent_encryption(leaf, fi) ||
962 btrfs_file_extent_other_encoding(leaf, fi))
965 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
966 if ((*start && *start != key.offset) || (*end && *end != extent_end))
975 * Mark extent in the range start - end as written.
977 * This changes extent type from 'pre-allocated' to 'regular'. If only
978 * part of extent is marked as written, the extent will be split into
981 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
982 struct inode *inode, u64 start, u64 end)
984 struct btrfs_root *root = BTRFS_I(inode)->root;
985 struct extent_buffer *leaf;
986 struct btrfs_path *path;
987 struct btrfs_file_extent_item *fi;
988 struct btrfs_key key;
989 struct btrfs_key new_key;
1001 u64 ino = btrfs_ino(inode);
1003 path = btrfs_alloc_path();
1010 key.type = BTRFS_EXTENT_DATA_KEY;
1013 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1016 if (ret > 0 && path->slots[0] > 0)
1019 leaf = path->nodes[0];
1020 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1021 BUG_ON(key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY);
1022 fi = btrfs_item_ptr(leaf, path->slots[0],
1023 struct btrfs_file_extent_item);
1024 BUG_ON(btrfs_file_extent_type(leaf, fi) !=
1025 BTRFS_FILE_EXTENT_PREALLOC);
1026 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1027 BUG_ON(key.offset > start || extent_end < end);
1029 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1030 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1031 orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
1032 memcpy(&new_key, &key, sizeof(new_key));
1034 if (start == key.offset && end < extent_end) {
1037 if (extent_mergeable(leaf, path->slots[0] - 1,
1038 ino, bytenr, orig_offset,
1039 &other_start, &other_end)) {
1040 new_key.offset = end;
1041 btrfs_set_item_key_safe(trans, root, path, &new_key);
1042 fi = btrfs_item_ptr(leaf, path->slots[0],
1043 struct btrfs_file_extent_item);
1044 btrfs_set_file_extent_generation(leaf, fi,
1046 btrfs_set_file_extent_num_bytes(leaf, fi,
1048 btrfs_set_file_extent_offset(leaf, fi,
1050 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1051 struct btrfs_file_extent_item);
1052 btrfs_set_file_extent_generation(leaf, fi,
1054 btrfs_set_file_extent_num_bytes(leaf, fi,
1056 btrfs_mark_buffer_dirty(leaf);
1061 if (start > key.offset && end == extent_end) {
1064 if (extent_mergeable(leaf, path->slots[0] + 1,
1065 ino, bytenr, orig_offset,
1066 &other_start, &other_end)) {
1067 fi = btrfs_item_ptr(leaf, path->slots[0],
1068 struct btrfs_file_extent_item);
1069 btrfs_set_file_extent_num_bytes(leaf, fi,
1070 start - key.offset);
1071 btrfs_set_file_extent_generation(leaf, fi,
1074 new_key.offset = start;
1075 btrfs_set_item_key_safe(trans, root, path, &new_key);
1077 fi = btrfs_item_ptr(leaf, path->slots[0],
1078 struct btrfs_file_extent_item);
1079 btrfs_set_file_extent_generation(leaf, fi,
1081 btrfs_set_file_extent_num_bytes(leaf, fi,
1083 btrfs_set_file_extent_offset(leaf, fi,
1084 start - orig_offset);
1085 btrfs_mark_buffer_dirty(leaf);
1090 while (start > key.offset || end < extent_end) {
1091 if (key.offset == start)
1094 new_key.offset = split;
1095 ret = btrfs_duplicate_item(trans, root, path, &new_key);
1096 if (ret == -EAGAIN) {
1097 btrfs_release_path(path);
1101 btrfs_abort_transaction(trans, root, ret);
1105 leaf = path->nodes[0];
1106 fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1107 struct btrfs_file_extent_item);
1108 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1109 btrfs_set_file_extent_num_bytes(leaf, fi,
1110 split - key.offset);
1112 fi = btrfs_item_ptr(leaf, path->slots[0],
1113 struct btrfs_file_extent_item);
1115 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1116 btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1117 btrfs_set_file_extent_num_bytes(leaf, fi,
1118 extent_end - split);
1119 btrfs_mark_buffer_dirty(leaf);
1121 ret = btrfs_inc_extent_ref(trans, root, bytenr, num_bytes, 0,
1122 root->root_key.objectid,
1123 ino, orig_offset, 0);
1124 BUG_ON(ret); /* -ENOMEM */
1126 if (split == start) {
1129 BUG_ON(start != key.offset);
1138 if (extent_mergeable(leaf, path->slots[0] + 1,
1139 ino, bytenr, orig_offset,
1140 &other_start, &other_end)) {
1142 btrfs_release_path(path);
1145 extent_end = other_end;
1146 del_slot = path->slots[0] + 1;
1148 ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
1149 0, root->root_key.objectid,
1150 ino, orig_offset, 0);
1151 BUG_ON(ret); /* -ENOMEM */
1155 if (extent_mergeable(leaf, path->slots[0] - 1,
1156 ino, bytenr, orig_offset,
1157 &other_start, &other_end)) {
1159 btrfs_release_path(path);
1162 key.offset = other_start;
1163 del_slot = path->slots[0];
1165 ret = btrfs_free_extent(trans, root, bytenr, num_bytes,
1166 0, root->root_key.objectid,
1167 ino, orig_offset, 0);
1168 BUG_ON(ret); /* -ENOMEM */
1171 fi = btrfs_item_ptr(leaf, path->slots[0],
1172 struct btrfs_file_extent_item);
1173 btrfs_set_file_extent_type(leaf, fi,
1174 BTRFS_FILE_EXTENT_REG);
1175 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1176 btrfs_mark_buffer_dirty(leaf);
1178 fi = btrfs_item_ptr(leaf, del_slot - 1,
1179 struct btrfs_file_extent_item);
1180 btrfs_set_file_extent_type(leaf, fi,
1181 BTRFS_FILE_EXTENT_REG);
1182 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1183 btrfs_set_file_extent_num_bytes(leaf, fi,
1184 extent_end - key.offset);
1185 btrfs_mark_buffer_dirty(leaf);
1187 ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1189 btrfs_abort_transaction(trans, root, ret);
1194 btrfs_free_path(path);
1199 * on error we return an unlocked page and the error value
1200 * on success we return a locked page and 0
1202 static int prepare_uptodate_page(struct page *page, u64 pos,
1203 bool force_uptodate)
1207 if (((pos & (PAGE_CACHE_SIZE - 1)) || force_uptodate) &&
1208 !PageUptodate(page)) {
1209 ret = btrfs_readpage(NULL, page);
1213 if (!PageUptodate(page)) {
1222 * this gets pages into the page cache and locks them down, it also properly
1223 * waits for data=ordered extents to finish before allowing the pages to be
1226 static noinline int prepare_pages(struct btrfs_root *root, struct file *file,
1227 struct page **pages, size_t num_pages,
1228 loff_t pos, unsigned long first_index,
1229 size_t write_bytes, bool force_uptodate)
1231 struct extent_state *cached_state = NULL;
1233 unsigned long index = pos >> PAGE_CACHE_SHIFT;
1234 struct inode *inode = file_inode(file);
1235 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1241 start_pos = pos & ~((u64)root->sectorsize - 1);
1242 last_pos = ((u64)index + num_pages) << PAGE_CACHE_SHIFT;
1245 for (i = 0; i < num_pages; i++) {
1246 pages[i] = find_or_create_page(inode->i_mapping, index + i,
1247 mask | __GFP_WRITE);
1255 err = prepare_uptodate_page(pages[i], pos,
1257 if (i == num_pages - 1)
1258 err = prepare_uptodate_page(pages[i],
1259 pos + write_bytes, false);
1261 page_cache_release(pages[i]);
1265 wait_on_page_writeback(pages[i]);
1268 if (start_pos < inode->i_size) {
1269 struct btrfs_ordered_extent *ordered;
1270 lock_extent_bits(&BTRFS_I(inode)->io_tree,
1271 start_pos, last_pos - 1, 0, &cached_state);
1272 ordered = btrfs_lookup_first_ordered_extent(inode,
1275 ordered->file_offset + ordered->len > start_pos &&
1276 ordered->file_offset < last_pos) {
1277 btrfs_put_ordered_extent(ordered);
1278 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1279 start_pos, last_pos - 1,
1280 &cached_state, GFP_NOFS);
1281 for (i = 0; i < num_pages; i++) {
1282 unlock_page(pages[i]);
1283 page_cache_release(pages[i]);
1285 btrfs_wait_ordered_range(inode, start_pos,
1286 last_pos - start_pos);
1290 btrfs_put_ordered_extent(ordered);
1292 clear_extent_bit(&BTRFS_I(inode)->io_tree, start_pos,
1293 last_pos - 1, EXTENT_DIRTY | EXTENT_DELALLOC |
1294 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
1295 0, 0, &cached_state, GFP_NOFS);
1296 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1297 start_pos, last_pos - 1, &cached_state,
1300 for (i = 0; i < num_pages; i++) {
1301 if (clear_page_dirty_for_io(pages[i]))
1302 account_page_redirty(pages[i]);
1303 set_page_extent_mapped(pages[i]);
1304 WARN_ON(!PageLocked(pages[i]));
1308 while (faili >= 0) {
1309 unlock_page(pages[faili]);
1310 page_cache_release(pages[faili]);
1317 static noinline ssize_t __btrfs_buffered_write(struct file *file,
1321 struct inode *inode = file_inode(file);
1322 struct btrfs_root *root = BTRFS_I(inode)->root;
1323 struct page **pages = NULL;
1324 unsigned long first_index;
1325 size_t num_written = 0;
1328 bool force_page_uptodate = false;
1330 nrptrs = min((iov_iter_count(i) + PAGE_CACHE_SIZE - 1) /
1331 PAGE_CACHE_SIZE, PAGE_CACHE_SIZE /
1332 (sizeof(struct page *)));
1333 nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1334 nrptrs = max(nrptrs, 8);
1335 pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
1339 first_index = pos >> PAGE_CACHE_SHIFT;
1341 while (iov_iter_count(i) > 0) {
1342 size_t offset = pos & (PAGE_CACHE_SIZE - 1);
1343 size_t write_bytes = min(iov_iter_count(i),
1344 nrptrs * (size_t)PAGE_CACHE_SIZE -
1346 size_t num_pages = (write_bytes + offset +
1347 PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
1351 WARN_ON(num_pages > nrptrs);
1354 * Fault pages before locking them in prepare_pages
1355 * to avoid recursive lock
1357 if (unlikely(iov_iter_fault_in_readable(i, write_bytes))) {
1362 ret = btrfs_delalloc_reserve_space(inode,
1363 num_pages << PAGE_CACHE_SHIFT);
1368 * This is going to setup the pages array with the number of
1369 * pages we want, so we don't really need to worry about the
1370 * contents of pages from loop to loop
1372 ret = prepare_pages(root, file, pages, num_pages,
1373 pos, first_index, write_bytes,
1374 force_page_uptodate);
1376 btrfs_delalloc_release_space(inode,
1377 num_pages << PAGE_CACHE_SHIFT);
1381 copied = btrfs_copy_from_user(pos, num_pages,
1382 write_bytes, pages, i);
1385 * if we have trouble faulting in the pages, fall
1386 * back to one page at a time
1388 if (copied < write_bytes)
1392 force_page_uptodate = true;
1395 force_page_uptodate = false;
1396 dirty_pages = (copied + offset +
1397 PAGE_CACHE_SIZE - 1) >>
1402 * If we had a short copy we need to release the excess delaloc
1403 * bytes we reserved. We need to increment outstanding_extents
1404 * because btrfs_delalloc_release_space will decrement it, but
1405 * we still have an outstanding extent for the chunk we actually
1408 if (num_pages > dirty_pages) {
1410 spin_lock(&BTRFS_I(inode)->lock);
1411 BTRFS_I(inode)->outstanding_extents++;
1412 spin_unlock(&BTRFS_I(inode)->lock);
1414 btrfs_delalloc_release_space(inode,
1415 (num_pages - dirty_pages) <<
1420 ret = btrfs_dirty_pages(root, inode, pages,
1421 dirty_pages, pos, copied,
1424 btrfs_delalloc_release_space(inode,
1425 dirty_pages << PAGE_CACHE_SHIFT);
1426 btrfs_drop_pages(pages, num_pages);
1431 btrfs_drop_pages(pages, num_pages);
1435 balance_dirty_pages_ratelimited(inode->i_mapping);
1436 if (dirty_pages < (root->leafsize >> PAGE_CACHE_SHIFT) + 1)
1437 btrfs_btree_balance_dirty(root);
1440 num_written += copied;
1445 return num_written ? num_written : ret;
1448 static ssize_t __btrfs_direct_write(struct kiocb *iocb,
1449 const struct iovec *iov,
1450 unsigned long nr_segs, loff_t pos,
1451 loff_t *ppos, size_t count, size_t ocount)
1453 struct file *file = iocb->ki_filp;
1456 ssize_t written_buffered;
1460 written = generic_file_direct_write(iocb, iov, &nr_segs, pos, ppos,
1463 if (written < 0 || written == count)
1468 iov_iter_init(&i, iov, nr_segs, count, written);
1469 written_buffered = __btrfs_buffered_write(file, &i, pos);
1470 if (written_buffered < 0) {
1471 err = written_buffered;
1474 endbyte = pos + written_buffered - 1;
1475 err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
1478 written += written_buffered;
1479 *ppos = pos + written_buffered;
1480 invalidate_mapping_pages(file->f_mapping, pos >> PAGE_CACHE_SHIFT,
1481 endbyte >> PAGE_CACHE_SHIFT);
1483 return written ? written : err;
1486 static void update_time_for_write(struct inode *inode)
1488 struct timespec now;
1490 if (IS_NOCMTIME(inode))
1493 now = current_fs_time(inode->i_sb);
1494 if (!timespec_equal(&inode->i_mtime, &now))
1495 inode->i_mtime = now;
1497 if (!timespec_equal(&inode->i_ctime, &now))
1498 inode->i_ctime = now;
1500 if (IS_I_VERSION(inode))
1501 inode_inc_iversion(inode);
1504 static ssize_t btrfs_file_aio_write(struct kiocb *iocb,
1505 const struct iovec *iov,
1506 unsigned long nr_segs, loff_t pos)
1508 struct file *file = iocb->ki_filp;
1509 struct inode *inode = file_inode(file);
1510 struct btrfs_root *root = BTRFS_I(inode)->root;
1511 loff_t *ppos = &iocb->ki_pos;
1513 ssize_t num_written = 0;
1515 size_t count, ocount;
1516 bool sync = (file->f_flags & O_DSYNC) || IS_SYNC(file->f_mapping->host);
1518 mutex_lock(&inode->i_mutex);
1520 err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
1522 mutex_unlock(&inode->i_mutex);
1527 current->backing_dev_info = inode->i_mapping->backing_dev_info;
1528 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
1530 mutex_unlock(&inode->i_mutex);
1535 mutex_unlock(&inode->i_mutex);
1539 err = file_remove_suid(file);
1541 mutex_unlock(&inode->i_mutex);
1546 * If BTRFS flips readonly due to some impossible error
1547 * (fs_info->fs_state now has BTRFS_SUPER_FLAG_ERROR),
1548 * although we have opened a file as writable, we have
1549 * to stop this write operation to ensure FS consistency.
1551 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state)) {
1552 mutex_unlock(&inode->i_mutex);
1558 * We reserve space for updating the inode when we reserve space for the
1559 * extent we are going to write, so we will enospc out there. We don't
1560 * need to start yet another transaction to update the inode as we will
1561 * update the inode when we finish writing whatever data we write.
1563 update_time_for_write(inode);
1565 start_pos = round_down(pos, root->sectorsize);
1566 if (start_pos > i_size_read(inode)) {
1567 err = btrfs_cont_expand(inode, i_size_read(inode), start_pos);
1569 mutex_unlock(&inode->i_mutex);
1575 atomic_inc(&BTRFS_I(inode)->sync_writers);
1577 if (unlikely(file->f_flags & O_DIRECT)) {
1578 num_written = __btrfs_direct_write(iocb, iov, nr_segs,
1579 pos, ppos, count, ocount);
1583 iov_iter_init(&i, iov, nr_segs, count, num_written);
1585 num_written = __btrfs_buffered_write(file, &i, pos);
1586 if (num_written > 0)
1587 *ppos = pos + num_written;
1590 mutex_unlock(&inode->i_mutex);
1593 * we want to make sure fsync finds this change
1594 * but we haven't joined a transaction running right now.
1596 * Later on, someone is sure to update the inode and get the
1597 * real transid recorded.
1599 * We set last_trans now to the fs_info generation + 1,
1600 * this will either be one more than the running transaction
1601 * or the generation used for the next transaction if there isn't
1602 * one running right now.
1604 * We also have to set last_sub_trans to the current log transid,
1605 * otherwise subsequent syncs to a file that's been synced in this
1606 * transaction will appear to have already occured.
1608 BTRFS_I(inode)->last_trans = root->fs_info->generation + 1;
1609 BTRFS_I(inode)->last_sub_trans = root->log_transid;
1610 if (num_written > 0 || num_written == -EIOCBQUEUED) {
1611 err = generic_write_sync(file, pos, num_written);
1612 if (err < 0 && num_written > 0)
1617 atomic_dec(&BTRFS_I(inode)->sync_writers);
1619 current->backing_dev_info = NULL;
1620 return num_written ? num_written : err;
1623 int btrfs_release_file(struct inode *inode, struct file *filp)
1626 * ordered_data_close is set by settattr when we are about to truncate
1627 * a file from a non-zero size to a zero size. This tries to
1628 * flush down new bytes that may have been written if the
1629 * application were using truncate to replace a file in place.
1631 if (test_and_clear_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
1632 &BTRFS_I(inode)->runtime_flags)) {
1633 struct btrfs_trans_handle *trans;
1634 struct btrfs_root *root = BTRFS_I(inode)->root;
1637 * We need to block on a committing transaction to keep us from
1638 * throwing a ordered operation on to the list and causing
1639 * something like sync to deadlock trying to flush out this
1642 trans = btrfs_start_transaction(root, 0);
1644 return PTR_ERR(trans);
1645 btrfs_add_ordered_operation(trans, BTRFS_I(inode)->root, inode);
1646 btrfs_end_transaction(trans, root);
1647 if (inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT)
1648 filemap_flush(inode->i_mapping);
1650 if (filp->private_data)
1651 btrfs_ioctl_trans_end(filp);
1656 * fsync call for both files and directories. This logs the inode into
1657 * the tree log instead of forcing full commits whenever possible.
1659 * It needs to call filemap_fdatawait so that all ordered extent updates are
1660 * in the metadata btree are up to date for copying to the log.
1662 * It drops the inode mutex before doing the tree log commit. This is an
1663 * important optimization for directories because holding the mutex prevents
1664 * new operations on the dir while we write to disk.
1666 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
1668 struct dentry *dentry = file->f_path.dentry;
1669 struct inode *inode = dentry->d_inode;
1670 struct btrfs_root *root = BTRFS_I(inode)->root;
1672 struct btrfs_trans_handle *trans;
1675 trace_btrfs_sync_file(file, datasync);
1678 * We write the dirty pages in the range and wait until they complete
1679 * out of the ->i_mutex. If so, we can flush the dirty pages by
1680 * multi-task, and make the performance up. See
1681 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
1683 atomic_inc(&BTRFS_I(inode)->sync_writers);
1684 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
1685 if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1686 &BTRFS_I(inode)->runtime_flags))
1687 ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
1688 atomic_dec(&BTRFS_I(inode)->sync_writers);
1692 mutex_lock(&inode->i_mutex);
1695 * We flush the dirty pages again to avoid some dirty pages in the
1698 atomic_inc(&root->log_batch);
1699 full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1700 &BTRFS_I(inode)->runtime_flags);
1702 btrfs_wait_ordered_range(inode, start, end - start + 1);
1703 atomic_inc(&root->log_batch);
1706 * check the transaction that last modified this inode
1707 * and see if its already been committed
1709 if (!BTRFS_I(inode)->last_trans) {
1710 mutex_unlock(&inode->i_mutex);
1715 * if the last transaction that changed this file was before
1716 * the current transaction, we can bail out now without any
1720 if (btrfs_inode_in_log(inode, root->fs_info->generation) ||
1721 BTRFS_I(inode)->last_trans <=
1722 root->fs_info->last_trans_committed) {
1723 BTRFS_I(inode)->last_trans = 0;
1726 * We'v had everything committed since the last time we were
1727 * modified so clear this flag in case it was set for whatever
1728 * reason, it's no longer relevant.
1730 clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1731 &BTRFS_I(inode)->runtime_flags);
1732 mutex_unlock(&inode->i_mutex);
1737 * ok we haven't committed the transaction yet, lets do a commit
1739 if (file->private_data)
1740 btrfs_ioctl_trans_end(file);
1742 trans = btrfs_start_transaction(root, 0);
1743 if (IS_ERR(trans)) {
1744 ret = PTR_ERR(trans);
1745 mutex_unlock(&inode->i_mutex);
1749 ret = btrfs_log_dentry_safe(trans, root, dentry);
1751 mutex_unlock(&inode->i_mutex);
1755 /* we've logged all the items and now have a consistent
1756 * version of the file in the log. It is possible that
1757 * someone will come in and modify the file, but that's
1758 * fine because the log is consistent on disk, and we
1759 * have references to all of the file's extents
1761 * It is possible that someone will come in and log the
1762 * file again, but that will end up using the synchronization
1763 * inside btrfs_sync_log to keep things safe.
1765 mutex_unlock(&inode->i_mutex);
1767 if (ret != BTRFS_NO_LOG_SYNC) {
1770 * If we didn't already wait for ordered extents we need
1774 btrfs_wait_ordered_range(inode, start,
1776 ret = btrfs_commit_transaction(trans, root);
1778 ret = btrfs_sync_log(trans, root);
1780 ret = btrfs_end_transaction(trans, root);
1783 btrfs_wait_ordered_range(inode, start,
1786 ret = btrfs_commit_transaction(trans, root);
1790 ret = btrfs_end_transaction(trans, root);
1793 return ret > 0 ? -EIO : ret;
1796 static const struct vm_operations_struct btrfs_file_vm_ops = {
1797 .fault = filemap_fault,
1798 .page_mkwrite = btrfs_page_mkwrite,
1799 .remap_pages = generic_file_remap_pages,
1802 static int btrfs_file_mmap(struct file *filp, struct vm_area_struct *vma)
1804 struct address_space *mapping = filp->f_mapping;
1806 if (!mapping->a_ops->readpage)
1809 file_accessed(filp);
1810 vma->vm_ops = &btrfs_file_vm_ops;
1815 static int hole_mergeable(struct inode *inode, struct extent_buffer *leaf,
1816 int slot, u64 start, u64 end)
1818 struct btrfs_file_extent_item *fi;
1819 struct btrfs_key key;
1821 if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1824 btrfs_item_key_to_cpu(leaf, &key, slot);
1825 if (key.objectid != btrfs_ino(inode) ||
1826 key.type != BTRFS_EXTENT_DATA_KEY)
1829 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1831 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
1834 if (btrfs_file_extent_disk_bytenr(leaf, fi))
1837 if (key.offset == end)
1839 if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
1844 static int fill_holes(struct btrfs_trans_handle *trans, struct inode *inode,
1845 struct btrfs_path *path, u64 offset, u64 end)
1847 struct btrfs_root *root = BTRFS_I(inode)->root;
1848 struct extent_buffer *leaf;
1849 struct btrfs_file_extent_item *fi;
1850 struct extent_map *hole_em;
1851 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
1852 struct btrfs_key key;
1855 key.objectid = btrfs_ino(inode);
1856 key.type = BTRFS_EXTENT_DATA_KEY;
1857 key.offset = offset;
1860 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1865 leaf = path->nodes[0];
1866 if (hole_mergeable(inode, leaf, path->slots[0]-1, offset, end)) {
1870 fi = btrfs_item_ptr(leaf, path->slots[0],
1871 struct btrfs_file_extent_item);
1872 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
1874 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1875 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
1876 btrfs_set_file_extent_offset(leaf, fi, 0);
1877 btrfs_mark_buffer_dirty(leaf);
1881 if (hole_mergeable(inode, leaf, path->slots[0]+1, offset, end)) {
1885 key.offset = offset;
1886 btrfs_set_item_key_safe(trans, root, path, &key);
1887 fi = btrfs_item_ptr(leaf, path->slots[0],
1888 struct btrfs_file_extent_item);
1889 num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
1891 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
1892 btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
1893 btrfs_set_file_extent_offset(leaf, fi, 0);
1894 btrfs_mark_buffer_dirty(leaf);
1897 btrfs_release_path(path);
1899 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
1900 0, 0, end - offset, 0, end - offset,
1906 btrfs_release_path(path);
1908 hole_em = alloc_extent_map();
1910 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
1911 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1912 &BTRFS_I(inode)->runtime_flags);
1914 hole_em->start = offset;
1915 hole_em->len = end - offset;
1916 hole_em->orig_start = offset;
1918 hole_em->block_start = EXTENT_MAP_HOLE;
1919 hole_em->block_len = 0;
1920 hole_em->orig_block_len = 0;
1921 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
1922 hole_em->compress_type = BTRFS_COMPRESS_NONE;
1923 hole_em->generation = trans->transid;
1926 btrfs_drop_extent_cache(inode, offset, end - 1, 0);
1927 write_lock(&em_tree->lock);
1928 ret = add_extent_mapping(em_tree, hole_em);
1930 list_move(&hole_em->list,
1931 &em_tree->modified_extents);
1932 write_unlock(&em_tree->lock);
1933 } while (ret == -EEXIST);
1934 free_extent_map(hole_em);
1936 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
1937 &BTRFS_I(inode)->runtime_flags);
1943 static int btrfs_punch_hole(struct inode *inode, loff_t offset, loff_t len)
1945 struct btrfs_root *root = BTRFS_I(inode)->root;
1946 struct extent_state *cached_state = NULL;
1947 struct btrfs_path *path;
1948 struct btrfs_block_rsv *rsv;
1949 struct btrfs_trans_handle *trans;
1950 u64 lockstart = round_up(offset, BTRFS_I(inode)->root->sectorsize);
1951 u64 lockend = round_down(offset + len,
1952 BTRFS_I(inode)->root->sectorsize) - 1;
1953 u64 cur_offset = lockstart;
1954 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
1958 bool same_page = ((offset >> PAGE_CACHE_SHIFT) ==
1959 ((offset + len - 1) >> PAGE_CACHE_SHIFT));
1961 btrfs_wait_ordered_range(inode, offset, len);
1963 mutex_lock(&inode->i_mutex);
1965 * We needn't truncate any page which is beyond the end of the file
1966 * because we are sure there is no data there.
1969 * Only do this if we are in the same page and we aren't doing the
1972 if (same_page && len < PAGE_CACHE_SIZE) {
1973 if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE))
1974 ret = btrfs_truncate_page(inode, offset, len, 0);
1975 mutex_unlock(&inode->i_mutex);
1979 /* zero back part of the first page */
1980 if (offset < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
1981 ret = btrfs_truncate_page(inode, offset, 0, 0);
1983 mutex_unlock(&inode->i_mutex);
1988 /* zero the front end of the last page */
1989 if (offset + len < round_up(inode->i_size, PAGE_CACHE_SIZE)) {
1990 ret = btrfs_truncate_page(inode, offset + len, 0, 1);
1992 mutex_unlock(&inode->i_mutex);
1997 if (lockend < lockstart) {
1998 mutex_unlock(&inode->i_mutex);
2003 struct btrfs_ordered_extent *ordered;
2005 truncate_pagecache_range(inode, lockstart, lockend);
2007 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2009 ordered = btrfs_lookup_first_ordered_extent(inode, lockend);
2012 * We need to make sure we have no ordered extents in this range
2013 * and nobody raced in and read a page in this range, if we did
2014 * we need to try again.
2017 (ordered->file_offset + ordered->len < lockstart ||
2018 ordered->file_offset > lockend)) &&
2019 !test_range_bit(&BTRFS_I(inode)->io_tree, lockstart,
2020 lockend, EXTENT_UPTODATE, 0,
2023 btrfs_put_ordered_extent(ordered);
2027 btrfs_put_ordered_extent(ordered);
2028 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2029 lockend, &cached_state, GFP_NOFS);
2030 btrfs_wait_ordered_range(inode, lockstart,
2031 lockend - lockstart + 1);
2034 path = btrfs_alloc_path();
2040 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
2045 rsv->size = btrfs_calc_trunc_metadata_size(root, 1);
2049 * 1 - update the inode
2050 * 1 - removing the extents in the range
2051 * 1 - adding the hole extent
2053 trans = btrfs_start_transaction(root, 3);
2054 if (IS_ERR(trans)) {
2055 err = PTR_ERR(trans);
2059 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
2062 trans->block_rsv = rsv;
2064 while (cur_offset < lockend) {
2065 ret = __btrfs_drop_extents(trans, root, inode, path,
2066 cur_offset, lockend + 1,
2071 trans->block_rsv = &root->fs_info->trans_block_rsv;
2073 ret = fill_holes(trans, inode, path, cur_offset, drop_end);
2079 cur_offset = drop_end;
2081 ret = btrfs_update_inode(trans, root, inode);
2087 btrfs_end_transaction(trans, root);
2088 btrfs_btree_balance_dirty(root);
2090 trans = btrfs_start_transaction(root, 3);
2091 if (IS_ERR(trans)) {
2092 ret = PTR_ERR(trans);
2097 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
2099 BUG_ON(ret); /* shouldn't happen */
2100 trans->block_rsv = rsv;
2108 trans->block_rsv = &root->fs_info->trans_block_rsv;
2109 ret = fill_holes(trans, inode, path, cur_offset, drop_end);
2119 inode_inc_iversion(inode);
2120 inode->i_mtime = inode->i_ctime = CURRENT_TIME;
2122 trans->block_rsv = &root->fs_info->trans_block_rsv;
2123 ret = btrfs_update_inode(trans, root, inode);
2124 btrfs_end_transaction(trans, root);
2125 btrfs_btree_balance_dirty(root);
2127 btrfs_free_path(path);
2128 btrfs_free_block_rsv(root, rsv);
2130 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2131 &cached_state, GFP_NOFS);
2132 mutex_unlock(&inode->i_mutex);
2138 static long btrfs_fallocate(struct file *file, int mode,
2139 loff_t offset, loff_t len)
2141 struct inode *inode = file_inode(file);
2142 struct extent_state *cached_state = NULL;
2143 struct btrfs_root *root = BTRFS_I(inode)->root;
2150 struct extent_map *em;
2151 int blocksize = BTRFS_I(inode)->root->sectorsize;
2154 alloc_start = round_down(offset, blocksize);
2155 alloc_end = round_up(offset + len, blocksize);
2157 /* Make sure we aren't being give some crap mode */
2158 if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2161 if (mode & FALLOC_FL_PUNCH_HOLE)
2162 return btrfs_punch_hole(inode, offset, len);
2165 * Make sure we have enough space before we do the
2168 ret = btrfs_check_data_free_space(inode, alloc_end - alloc_start);
2171 if (root->fs_info->quota_enabled) {
2172 ret = btrfs_qgroup_reserve(root, alloc_end - alloc_start);
2174 goto out_reserve_fail;
2178 * wait for ordered IO before we have any locks. We'll loop again
2179 * below with the locks held.
2181 btrfs_wait_ordered_range(inode, alloc_start, alloc_end - alloc_start);
2183 mutex_lock(&inode->i_mutex);
2184 ret = inode_newsize_ok(inode, alloc_end);
2188 if (alloc_start > inode->i_size) {
2189 ret = btrfs_cont_expand(inode, i_size_read(inode),
2195 locked_end = alloc_end - 1;
2197 struct btrfs_ordered_extent *ordered;
2199 /* the extent lock is ordered inside the running
2202 lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start,
2203 locked_end, 0, &cached_state);
2204 ordered = btrfs_lookup_first_ordered_extent(inode,
2207 ordered->file_offset + ordered->len > alloc_start &&
2208 ordered->file_offset < alloc_end) {
2209 btrfs_put_ordered_extent(ordered);
2210 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
2211 alloc_start, locked_end,
2212 &cached_state, GFP_NOFS);
2214 * we can't wait on the range with the transaction
2215 * running or with the extent lock held
2217 btrfs_wait_ordered_range(inode, alloc_start,
2218 alloc_end - alloc_start);
2221 btrfs_put_ordered_extent(ordered);
2226 cur_offset = alloc_start;
2230 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
2231 alloc_end - cur_offset, 0);
2232 if (IS_ERR_OR_NULL(em)) {
2239 last_byte = min(extent_map_end(em), alloc_end);
2240 actual_end = min_t(u64, extent_map_end(em), offset + len);
2241 last_byte = ALIGN(last_byte, blocksize);
2243 if (em->block_start == EXTENT_MAP_HOLE ||
2244 (cur_offset >= inode->i_size &&
2245 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
2246 ret = btrfs_prealloc_file_range(inode, mode, cur_offset,
2247 last_byte - cur_offset,
2248 1 << inode->i_blkbits,
2253 free_extent_map(em);
2256 } else if (actual_end > inode->i_size &&
2257 !(mode & FALLOC_FL_KEEP_SIZE)) {
2259 * We didn't need to allocate any more space, but we
2260 * still extended the size of the file so we need to
2263 inode->i_ctime = CURRENT_TIME;
2264 i_size_write(inode, actual_end);
2265 btrfs_ordered_update_i_size(inode, actual_end, NULL);
2267 free_extent_map(em);
2269 cur_offset = last_byte;
2270 if (cur_offset >= alloc_end) {
2275 unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
2276 &cached_state, GFP_NOFS);
2278 mutex_unlock(&inode->i_mutex);
2279 if (root->fs_info->quota_enabled)
2280 btrfs_qgroup_free(root, alloc_end - alloc_start);
2282 /* Let go of our reservation. */
2283 btrfs_free_reserved_data_space(inode, alloc_end - alloc_start);
2287 static int find_desired_extent(struct inode *inode, loff_t *offset, int whence)
2289 struct btrfs_root *root = BTRFS_I(inode)->root;
2290 struct extent_map *em;
2291 struct extent_state *cached_state = NULL;
2292 u64 lockstart = *offset;
2293 u64 lockend = i_size_read(inode);
2294 u64 start = *offset;
2295 u64 orig_start = *offset;
2296 u64 len = i_size_read(inode);
2300 lockend = max_t(u64, root->sectorsize, lockend);
2301 if (lockend <= lockstart)
2302 lockend = lockstart + root->sectorsize;
2305 len = lockend - lockstart + 1;
2307 len = max_t(u64, len, root->sectorsize);
2308 if (inode->i_size == 0)
2311 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0,
2315 * Delalloc is such a pain. If we have a hole and we have pending
2316 * delalloc for a portion of the hole we will get back a hole that
2317 * exists for the entire range since it hasn't been actually written
2318 * yet. So to take care of this case we need to look for an extent just
2319 * before the position we want in case there is outstanding delalloc
2322 if (whence == SEEK_HOLE && start != 0) {
2323 if (start <= root->sectorsize)
2324 em = btrfs_get_extent_fiemap(inode, NULL, 0, 0,
2325 root->sectorsize, 0);
2327 em = btrfs_get_extent_fiemap(inode, NULL, 0,
2328 start - root->sectorsize,
2329 root->sectorsize, 0);
2334 last_end = em->start + em->len;
2335 if (em->block_start == EXTENT_MAP_DELALLOC)
2336 last_end = min_t(u64, last_end, inode->i_size);
2337 free_extent_map(em);
2341 em = btrfs_get_extent_fiemap(inode, NULL, 0, start, len, 0);
2347 if (em->block_start == EXTENT_MAP_HOLE) {
2348 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2349 if (last_end <= orig_start) {
2350 free_extent_map(em);
2356 if (whence == SEEK_HOLE) {
2358 free_extent_map(em);
2362 if (whence == SEEK_DATA) {
2363 if (em->block_start == EXTENT_MAP_DELALLOC) {
2364 if (start >= inode->i_size) {
2365 free_extent_map(em);
2371 if (!test_bit(EXTENT_FLAG_PREALLOC,
2374 free_extent_map(em);
2380 start = em->start + em->len;
2381 last_end = em->start + em->len;
2383 if (em->block_start == EXTENT_MAP_DELALLOC)
2384 last_end = min_t(u64, last_end, inode->i_size);
2386 if (test_bit(EXTENT_FLAG_VACANCY, &em->flags)) {
2387 free_extent_map(em);
2391 free_extent_map(em);
2395 *offset = min(*offset, inode->i_size);
2397 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2398 &cached_state, GFP_NOFS);
2402 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
2404 struct inode *inode = file->f_mapping->host;
2407 mutex_lock(&inode->i_mutex);
2411 offset = generic_file_llseek(file, offset, whence);
2415 if (offset >= i_size_read(inode)) {
2416 mutex_unlock(&inode->i_mutex);
2420 ret = find_desired_extent(inode, &offset, whence);
2422 mutex_unlock(&inode->i_mutex);
2427 if (offset < 0 && !(file->f_mode & FMODE_UNSIGNED_OFFSET)) {
2431 if (offset > inode->i_sb->s_maxbytes) {
2436 /* Special lock needed here? */
2437 if (offset != file->f_pos) {
2438 file->f_pos = offset;
2439 file->f_version = 0;
2442 mutex_unlock(&inode->i_mutex);
2446 const struct file_operations btrfs_file_operations = {
2447 .llseek = btrfs_file_llseek,
2448 .read = do_sync_read,
2449 .write = do_sync_write,
2450 .aio_read = generic_file_aio_read,
2451 .splice_read = generic_file_splice_read,
2452 .aio_write = btrfs_file_aio_write,
2453 .mmap = btrfs_file_mmap,
2454 .open = generic_file_open,
2455 .release = btrfs_release_file,
2456 .fsync = btrfs_sync_file,
2457 .fallocate = btrfs_fallocate,
2458 .unlocked_ioctl = btrfs_ioctl,
2459 #ifdef CONFIG_COMPAT
2460 .compat_ioctl = btrfs_ioctl,
2464 void btrfs_auto_defrag_exit(void)
2466 if (btrfs_inode_defrag_cachep)
2467 kmem_cache_destroy(btrfs_inode_defrag_cachep);
2470 int btrfs_auto_defrag_init(void)
2472 btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
2473 sizeof(struct inode_defrag), 0,
2474 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
2476 if (!btrfs_inode_defrag_cachep)