1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (C) 2007 Oracle. All rights reserved.
6 #include <linux/kernel.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <linux/time.h>
14 #include <linux/init.h>
15 #include <linux/string.h>
16 #include <linux/backing-dev.h>
17 #include <linux/writeback.h>
18 #include <linux/compat.h>
19 #include <linux/xattr.h>
20 #include <linux/posix_acl.h>
21 #include <linux/falloc.h>
22 #include <linux/slab.h>
23 #include <linux/ratelimit.h>
24 #include <linux/btrfs.h>
25 #include <linux/blkdev.h>
26 #include <linux/posix_acl_xattr.h>
27 #include <linux/uio.h>
28 #include <linux/magic.h>
29 #include <linux/iversion.h>
30 #include <linux/swap.h>
31 #include <linux/sched/mm.h>
32 #include <asm/unaligned.h>
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "print-tree.h"
38 #include "ordered-data.h"
42 #include "compression.h"
44 #include "free-space-cache.h"
45 #include "inode-map.h"
49 #include "delalloc-space.h"
50 #include "block-group.h"
52 struct btrfs_iget_args
{
53 struct btrfs_key
*location
;
54 struct btrfs_root
*root
;
57 struct btrfs_dio_data
{
59 u64 unsubmitted_oe_range_start
;
60 u64 unsubmitted_oe_range_end
;
64 static const struct inode_operations btrfs_dir_inode_operations
;
65 static const struct inode_operations btrfs_symlink_inode_operations
;
66 static const struct inode_operations btrfs_dir_ro_inode_operations
;
67 static const struct inode_operations btrfs_special_inode_operations
;
68 static const struct inode_operations btrfs_file_inode_operations
;
69 static const struct address_space_operations btrfs_aops
;
70 static const struct file_operations btrfs_dir_file_operations
;
71 static const struct extent_io_ops btrfs_extent_io_ops
;
73 static struct kmem_cache
*btrfs_inode_cachep
;
74 struct kmem_cache
*btrfs_trans_handle_cachep
;
75 struct kmem_cache
*btrfs_path_cachep
;
76 struct kmem_cache
*btrfs_free_space_cachep
;
78 static int btrfs_setsize(struct inode
*inode
, struct iattr
*attr
);
79 static int btrfs_truncate(struct inode
*inode
, bool skip_writeback
);
80 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent
*ordered_extent
);
81 static noinline
int cow_file_range(struct inode
*inode
,
82 struct page
*locked_page
,
83 u64 start
, u64 end
, int *page_started
,
84 unsigned long *nr_written
, int unlock
);
85 static struct extent_map
*create_io_em(struct inode
*inode
, u64 start
, u64 len
,
86 u64 orig_start
, u64 block_start
,
87 u64 block_len
, u64 orig_block_len
,
88 u64 ram_bytes
, int compress_type
,
91 static void __endio_write_update_ordered(struct inode
*inode
,
92 const u64 offset
, const u64 bytes
,
96 * Cleanup all submitted ordered extents in specified range to handle errors
97 * from the btrfs_run_delalloc_range() callback.
99 * NOTE: caller must ensure that when an error happens, it can not call
100 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
101 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
102 * to be released, which we want to happen only when finishing the ordered
103 * extent (btrfs_finish_ordered_io()).
105 static inline void btrfs_cleanup_ordered_extents(struct inode
*inode
,
106 struct page
*locked_page
,
107 u64 offset
, u64 bytes
)
109 unsigned long index
= offset
>> PAGE_SHIFT
;
110 unsigned long end_index
= (offset
+ bytes
- 1) >> PAGE_SHIFT
;
111 u64 page_start
= page_offset(locked_page
);
112 u64 page_end
= page_start
+ PAGE_SIZE
- 1;
116 while (index
<= end_index
) {
117 page
= find_get_page(inode
->i_mapping
, index
);
121 ClearPagePrivate2(page
);
126 * In case this page belongs to the delalloc range being instantiated
127 * then skip it, since the first page of a range is going to be
128 * properly cleaned up by the caller of run_delalloc_range
130 if (page_start
>= offset
&& page_end
<= (offset
+ bytes
- 1)) {
135 return __endio_write_update_ordered(inode
, offset
, bytes
, false);
138 static int btrfs_dirty_inode(struct inode
*inode
);
140 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
141 void btrfs_test_inode_set_ops(struct inode
*inode
)
143 BTRFS_I(inode
)->io_tree
.ops
= &btrfs_extent_io_ops
;
147 static int btrfs_init_inode_security(struct btrfs_trans_handle
*trans
,
148 struct inode
*inode
, struct inode
*dir
,
149 const struct qstr
*qstr
)
153 err
= btrfs_init_acl(trans
, inode
, dir
);
155 err
= btrfs_xattr_security_init(trans
, inode
, dir
, qstr
);
160 * this does all the hard work for inserting an inline extent into
161 * the btree. The caller should have done a btrfs_drop_extents so that
162 * no overlapping inline items exist in the btree
164 static int insert_inline_extent(struct btrfs_trans_handle
*trans
,
165 struct btrfs_path
*path
, int extent_inserted
,
166 struct btrfs_root
*root
, struct inode
*inode
,
167 u64 start
, size_t size
, size_t compressed_size
,
169 struct page
**compressed_pages
)
171 struct extent_buffer
*leaf
;
172 struct page
*page
= NULL
;
175 struct btrfs_file_extent_item
*ei
;
177 size_t cur_size
= size
;
178 unsigned long offset
;
180 ASSERT((compressed_size
> 0 && compressed_pages
) ||
181 (compressed_size
== 0 && !compressed_pages
));
183 if (compressed_size
&& compressed_pages
)
184 cur_size
= compressed_size
;
186 inode_add_bytes(inode
, size
);
188 if (!extent_inserted
) {
189 struct btrfs_key key
;
192 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
194 key
.type
= BTRFS_EXTENT_DATA_KEY
;
196 datasize
= btrfs_file_extent_calc_inline_size(cur_size
);
197 path
->leave_spinning
= 1;
198 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
203 leaf
= path
->nodes
[0];
204 ei
= btrfs_item_ptr(leaf
, path
->slots
[0],
205 struct btrfs_file_extent_item
);
206 btrfs_set_file_extent_generation(leaf
, ei
, trans
->transid
);
207 btrfs_set_file_extent_type(leaf
, ei
, BTRFS_FILE_EXTENT_INLINE
);
208 btrfs_set_file_extent_encryption(leaf
, ei
, 0);
209 btrfs_set_file_extent_other_encoding(leaf
, ei
, 0);
210 btrfs_set_file_extent_ram_bytes(leaf
, ei
, size
);
211 ptr
= btrfs_file_extent_inline_start(ei
);
213 if (compress_type
!= BTRFS_COMPRESS_NONE
) {
216 while (compressed_size
> 0) {
217 cpage
= compressed_pages
[i
];
218 cur_size
= min_t(unsigned long, compressed_size
,
221 kaddr
= kmap_atomic(cpage
);
222 write_extent_buffer(leaf
, kaddr
, ptr
, cur_size
);
223 kunmap_atomic(kaddr
);
227 compressed_size
-= cur_size
;
229 btrfs_set_file_extent_compression(leaf
, ei
,
232 page
= find_get_page(inode
->i_mapping
,
233 start
>> PAGE_SHIFT
);
234 btrfs_set_file_extent_compression(leaf
, ei
, 0);
235 kaddr
= kmap_atomic(page
);
236 offset
= offset_in_page(start
);
237 write_extent_buffer(leaf
, kaddr
+ offset
, ptr
, size
);
238 kunmap_atomic(kaddr
);
241 btrfs_mark_buffer_dirty(leaf
);
242 btrfs_release_path(path
);
245 * we're an inline extent, so nobody can
246 * extend the file past i_size without locking
247 * a page we already have locked.
249 * We must do any isize and inode updates
250 * before we unlock the pages. Otherwise we
251 * could end up racing with unlink.
253 BTRFS_I(inode
)->disk_i_size
= inode
->i_size
;
254 ret
= btrfs_update_inode(trans
, root
, inode
);
262 * conditionally insert an inline extent into the file. This
263 * does the checks required to make sure the data is small enough
264 * to fit as an inline extent.
266 static noinline
int cow_file_range_inline(struct inode
*inode
, u64 start
,
267 u64 end
, size_t compressed_size
,
269 struct page
**compressed_pages
)
271 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
272 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
273 struct btrfs_trans_handle
*trans
;
274 u64 isize
= i_size_read(inode
);
275 u64 actual_end
= min(end
+ 1, isize
);
276 u64 inline_len
= actual_end
- start
;
277 u64 aligned_end
= ALIGN(end
, fs_info
->sectorsize
);
278 u64 data_len
= inline_len
;
280 struct btrfs_path
*path
;
281 int extent_inserted
= 0;
282 u32 extent_item_size
;
285 data_len
= compressed_size
;
288 actual_end
> fs_info
->sectorsize
||
289 data_len
> BTRFS_MAX_INLINE_DATA_SIZE(fs_info
) ||
291 (actual_end
& (fs_info
->sectorsize
- 1)) == 0) ||
293 data_len
> fs_info
->max_inline
) {
297 path
= btrfs_alloc_path();
301 trans
= btrfs_join_transaction(root
);
303 btrfs_free_path(path
);
304 return PTR_ERR(trans
);
306 trans
->block_rsv
= &BTRFS_I(inode
)->block_rsv
;
308 if (compressed_size
&& compressed_pages
)
309 extent_item_size
= btrfs_file_extent_calc_inline_size(
312 extent_item_size
= btrfs_file_extent_calc_inline_size(
315 ret
= __btrfs_drop_extents(trans
, root
, inode
, path
,
316 start
, aligned_end
, NULL
,
317 1, 1, extent_item_size
, &extent_inserted
);
319 btrfs_abort_transaction(trans
, ret
);
323 if (isize
> actual_end
)
324 inline_len
= min_t(u64
, isize
, actual_end
);
325 ret
= insert_inline_extent(trans
, path
, extent_inserted
,
327 inline_len
, compressed_size
,
328 compress_type
, compressed_pages
);
329 if (ret
&& ret
!= -ENOSPC
) {
330 btrfs_abort_transaction(trans
, ret
);
332 } else if (ret
== -ENOSPC
) {
337 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
, &BTRFS_I(inode
)->runtime_flags
);
338 btrfs_drop_extent_cache(BTRFS_I(inode
), start
, aligned_end
- 1, 0);
341 * Don't forget to free the reserved space, as for inlined extent
342 * it won't count as data extent, free them directly here.
343 * And at reserve time, it's always aligned to page size, so
344 * just free one page here.
346 btrfs_qgroup_free_data(inode
, NULL
, 0, PAGE_SIZE
);
347 btrfs_free_path(path
);
348 btrfs_end_transaction(trans
);
352 struct async_extent
{
357 unsigned long nr_pages
;
359 struct list_head list
;
364 struct page
*locked_page
;
367 unsigned int write_flags
;
368 struct list_head extents
;
369 struct btrfs_work work
;
374 /* Number of chunks in flight; must be first in the structure */
376 struct async_chunk chunks
[];
379 static noinline
int add_async_extent(struct async_chunk
*cow
,
380 u64 start
, u64 ram_size
,
383 unsigned long nr_pages
,
386 struct async_extent
*async_extent
;
388 async_extent
= kmalloc(sizeof(*async_extent
), GFP_NOFS
);
389 BUG_ON(!async_extent
); /* -ENOMEM */
390 async_extent
->start
= start
;
391 async_extent
->ram_size
= ram_size
;
392 async_extent
->compressed_size
= compressed_size
;
393 async_extent
->pages
= pages
;
394 async_extent
->nr_pages
= nr_pages
;
395 async_extent
->compress_type
= compress_type
;
396 list_add_tail(&async_extent
->list
, &cow
->extents
);
401 * Check if the inode has flags compatible with compression
403 static inline bool inode_can_compress(struct inode
*inode
)
405 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
||
406 BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
)
412 * Check if the inode needs to be submitted to compression, based on mount
413 * options, defragmentation, properties or heuristics.
415 static inline int inode_need_compress(struct inode
*inode
, u64 start
, u64 end
)
417 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
419 if (!inode_can_compress(inode
)) {
420 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG
),
421 KERN_ERR
"BTRFS: unexpected compression for ino %llu\n",
422 btrfs_ino(BTRFS_I(inode
)));
426 if (btrfs_test_opt(fs_info
, FORCE_COMPRESS
))
429 if (BTRFS_I(inode
)->defrag_compress
)
431 /* bad compression ratios */
432 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_NOCOMPRESS
)
434 if (btrfs_test_opt(fs_info
, COMPRESS
) ||
435 BTRFS_I(inode
)->flags
& BTRFS_INODE_COMPRESS
||
436 BTRFS_I(inode
)->prop_compress
)
437 return btrfs_compress_heuristic(inode
, start
, end
);
441 static inline void inode_should_defrag(struct btrfs_inode
*inode
,
442 u64 start
, u64 end
, u64 num_bytes
, u64 small_write
)
444 /* If this is a small write inside eof, kick off a defrag */
445 if (num_bytes
< small_write
&&
446 (start
> 0 || end
+ 1 < inode
->disk_i_size
))
447 btrfs_add_inode_defrag(NULL
, inode
);
451 * we create compressed extents in two phases. The first
452 * phase compresses a range of pages that have already been
453 * locked (both pages and state bits are locked).
455 * This is done inside an ordered work queue, and the compression
456 * is spread across many cpus. The actual IO submission is step
457 * two, and the ordered work queue takes care of making sure that
458 * happens in the same order things were put onto the queue by
459 * writepages and friends.
461 * If this code finds it can't get good compression, it puts an
462 * entry onto the work queue to write the uncompressed bytes. This
463 * makes sure that both compressed inodes and uncompressed inodes
464 * are written in the same order that the flusher thread sent them
467 static noinline
int compress_file_range(struct async_chunk
*async_chunk
)
469 struct inode
*inode
= async_chunk
->inode
;
470 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
471 u64 blocksize
= fs_info
->sectorsize
;
472 u64 start
= async_chunk
->start
;
473 u64 end
= async_chunk
->end
;
476 struct page
**pages
= NULL
;
477 unsigned long nr_pages
;
478 unsigned long total_compressed
= 0;
479 unsigned long total_in
= 0;
482 int compress_type
= fs_info
->compress_type
;
483 int compressed_extents
= 0;
486 inode_should_defrag(BTRFS_I(inode
), start
, end
, end
- start
+ 1,
489 actual_end
= min_t(u64
, i_size_read(inode
), end
+ 1);
492 nr_pages
= (end
>> PAGE_SHIFT
) - (start
>> PAGE_SHIFT
) + 1;
493 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED
% PAGE_SIZE
) != 0);
494 nr_pages
= min_t(unsigned long, nr_pages
,
495 BTRFS_MAX_COMPRESSED
/ PAGE_SIZE
);
498 * we don't want to send crud past the end of i_size through
499 * compression, that's just a waste of CPU time. So, if the
500 * end of the file is before the start of our current
501 * requested range of bytes, we bail out to the uncompressed
502 * cleanup code that can deal with all of this.
504 * It isn't really the fastest way to fix things, but this is a
505 * very uncommon corner.
507 if (actual_end
<= start
)
508 goto cleanup_and_bail_uncompressed
;
510 total_compressed
= actual_end
- start
;
513 * skip compression for a small file range(<=blocksize) that
514 * isn't an inline extent, since it doesn't save disk space at all.
516 if (total_compressed
<= blocksize
&&
517 (start
> 0 || end
+ 1 < BTRFS_I(inode
)->disk_i_size
))
518 goto cleanup_and_bail_uncompressed
;
520 total_compressed
= min_t(unsigned long, total_compressed
,
521 BTRFS_MAX_UNCOMPRESSED
);
526 * we do compression for mount -o compress and when the
527 * inode has not been flagged as nocompress. This flag can
528 * change at any time if we discover bad compression ratios.
530 if (inode_need_compress(inode
, start
, end
)) {
532 pages
= kcalloc(nr_pages
, sizeof(struct page
*), GFP_NOFS
);
534 /* just bail out to the uncompressed code */
539 if (BTRFS_I(inode
)->defrag_compress
)
540 compress_type
= BTRFS_I(inode
)->defrag_compress
;
541 else if (BTRFS_I(inode
)->prop_compress
)
542 compress_type
= BTRFS_I(inode
)->prop_compress
;
545 * we need to call clear_page_dirty_for_io on each
546 * page in the range. Otherwise applications with the file
547 * mmap'd can wander in and change the page contents while
548 * we are compressing them.
550 * If the compression fails for any reason, we set the pages
551 * dirty again later on.
553 * Note that the remaining part is redirtied, the start pointer
554 * has moved, the end is the original one.
557 extent_range_clear_dirty_for_io(inode
, start
, end
);
561 /* Compression level is applied here and only here */
562 ret
= btrfs_compress_pages(
563 compress_type
| (fs_info
->compress_level
<< 4),
564 inode
->i_mapping
, start
,
571 unsigned long offset
= offset_in_page(total_compressed
);
572 struct page
*page
= pages
[nr_pages
- 1];
575 /* zero the tail end of the last page, we might be
576 * sending it down to disk
579 kaddr
= kmap_atomic(page
);
580 memset(kaddr
+ offset
, 0,
582 kunmap_atomic(kaddr
);
589 /* lets try to make an inline extent */
590 if (ret
|| total_in
< actual_end
) {
591 /* we didn't compress the entire range, try
592 * to make an uncompressed inline extent.
594 ret
= cow_file_range_inline(inode
, start
, end
, 0,
595 BTRFS_COMPRESS_NONE
, NULL
);
597 /* try making a compressed inline extent */
598 ret
= cow_file_range_inline(inode
, start
, end
,
600 compress_type
, pages
);
603 unsigned long clear_flags
= EXTENT_DELALLOC
|
604 EXTENT_DELALLOC_NEW
| EXTENT_DEFRAG
|
605 EXTENT_DO_ACCOUNTING
;
606 unsigned long page_error_op
;
608 page_error_op
= ret
< 0 ? PAGE_SET_ERROR
: 0;
611 * inline extent creation worked or returned error,
612 * we don't need to create any more async work items.
613 * Unlock and free up our temp pages.
615 * We use DO_ACCOUNTING here because we need the
616 * delalloc_release_metadata to be done _after_ we drop
617 * our outstanding extent for clearing delalloc for this
620 extent_clear_unlock_delalloc(inode
, start
, end
, NULL
,
628 for (i
= 0; i
< nr_pages
; i
++) {
629 WARN_ON(pages
[i
]->mapping
);
640 * we aren't doing an inline extent round the compressed size
641 * up to a block size boundary so the allocator does sane
644 total_compressed
= ALIGN(total_compressed
, blocksize
);
647 * one last check to make sure the compression is really a
648 * win, compare the page count read with the blocks on disk,
649 * compression must free at least one sector size
651 total_in
= ALIGN(total_in
, PAGE_SIZE
);
652 if (total_compressed
+ blocksize
<= total_in
) {
653 compressed_extents
++;
656 * The async work queues will take care of doing actual
657 * allocation on disk for these compressed pages, and
658 * will submit them to the elevator.
660 add_async_extent(async_chunk
, start
, total_in
,
661 total_compressed
, pages
, nr_pages
,
664 if (start
+ total_in
< end
) {
670 return compressed_extents
;
675 * the compression code ran but failed to make things smaller,
676 * free any pages it allocated and our page pointer array
678 for (i
= 0; i
< nr_pages
; i
++) {
679 WARN_ON(pages
[i
]->mapping
);
684 total_compressed
= 0;
687 /* flag the file so we don't compress in the future */
688 if (!btrfs_test_opt(fs_info
, FORCE_COMPRESS
) &&
689 !(BTRFS_I(inode
)->prop_compress
)) {
690 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NOCOMPRESS
;
693 cleanup_and_bail_uncompressed
:
695 * No compression, but we still need to write the pages in the file
696 * we've been given so far. redirty the locked page if it corresponds
697 * to our extent and set things up for the async work queue to run
698 * cow_file_range to do the normal delalloc dance.
700 if (page_offset(async_chunk
->locked_page
) >= start
&&
701 page_offset(async_chunk
->locked_page
) <= end
)
702 __set_page_dirty_nobuffers(async_chunk
->locked_page
);
703 /* unlocked later on in the async handlers */
706 extent_range_redirty_for_io(inode
, start
, end
);
707 add_async_extent(async_chunk
, start
, end
- start
+ 1, 0, NULL
, 0,
708 BTRFS_COMPRESS_NONE
);
709 compressed_extents
++;
711 return compressed_extents
;
714 static void free_async_extent_pages(struct async_extent
*async_extent
)
718 if (!async_extent
->pages
)
721 for (i
= 0; i
< async_extent
->nr_pages
; i
++) {
722 WARN_ON(async_extent
->pages
[i
]->mapping
);
723 put_page(async_extent
->pages
[i
]);
725 kfree(async_extent
->pages
);
726 async_extent
->nr_pages
= 0;
727 async_extent
->pages
= NULL
;
731 * phase two of compressed writeback. This is the ordered portion
732 * of the code, which only gets called in the order the work was
733 * queued. We walk all the async extents created by compress_file_range
734 * and send them down to the disk.
736 static noinline
void submit_compressed_extents(struct async_chunk
*async_chunk
)
738 struct inode
*inode
= async_chunk
->inode
;
739 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
740 struct async_extent
*async_extent
;
742 struct btrfs_key ins
;
743 struct extent_map
*em
;
744 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
745 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
749 while (!list_empty(&async_chunk
->extents
)) {
750 async_extent
= list_entry(async_chunk
->extents
.next
,
751 struct async_extent
, list
);
752 list_del(&async_extent
->list
);
755 lock_extent(io_tree
, async_extent
->start
,
756 async_extent
->start
+ async_extent
->ram_size
- 1);
757 /* did the compression code fall back to uncompressed IO? */
758 if (!async_extent
->pages
) {
759 int page_started
= 0;
760 unsigned long nr_written
= 0;
762 /* allocate blocks */
763 ret
= cow_file_range(inode
, async_chunk
->locked_page
,
765 async_extent
->start
+
766 async_extent
->ram_size
- 1,
767 &page_started
, &nr_written
, 0);
772 * if page_started, cow_file_range inserted an
773 * inline extent and took care of all the unlocking
774 * and IO for us. Otherwise, we need to submit
775 * all those pages down to the drive.
777 if (!page_started
&& !ret
)
778 extent_write_locked_range(inode
,
780 async_extent
->start
+
781 async_extent
->ram_size
- 1,
784 unlock_page(async_chunk
->locked_page
);
790 ret
= btrfs_reserve_extent(root
, async_extent
->ram_size
,
791 async_extent
->compressed_size
,
792 async_extent
->compressed_size
,
793 0, alloc_hint
, &ins
, 1, 1);
795 free_async_extent_pages(async_extent
);
797 if (ret
== -ENOSPC
) {
798 unlock_extent(io_tree
, async_extent
->start
,
799 async_extent
->start
+
800 async_extent
->ram_size
- 1);
803 * we need to redirty the pages if we decide to
804 * fallback to uncompressed IO, otherwise we
805 * will not submit these pages down to lower
808 extent_range_redirty_for_io(inode
,
810 async_extent
->start
+
811 async_extent
->ram_size
- 1);
818 * here we're doing allocation and writeback of the
821 em
= create_io_em(inode
, async_extent
->start
,
822 async_extent
->ram_size
, /* len */
823 async_extent
->start
, /* orig_start */
824 ins
.objectid
, /* block_start */
825 ins
.offset
, /* block_len */
826 ins
.offset
, /* orig_block_len */
827 async_extent
->ram_size
, /* ram_bytes */
828 async_extent
->compress_type
,
829 BTRFS_ORDERED_COMPRESSED
);
831 /* ret value is not necessary due to void function */
832 goto out_free_reserve
;
835 ret
= btrfs_add_ordered_extent_compress(inode
,
838 async_extent
->ram_size
,
840 BTRFS_ORDERED_COMPRESSED
,
841 async_extent
->compress_type
);
843 btrfs_drop_extent_cache(BTRFS_I(inode
),
845 async_extent
->start
+
846 async_extent
->ram_size
- 1, 0);
847 goto out_free_reserve
;
849 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
852 * clear dirty, set writeback and unlock the pages.
854 extent_clear_unlock_delalloc(inode
, async_extent
->start
,
855 async_extent
->start
+
856 async_extent
->ram_size
- 1,
857 NULL
, EXTENT_LOCKED
| EXTENT_DELALLOC
,
858 PAGE_UNLOCK
| PAGE_CLEAR_DIRTY
|
860 if (btrfs_submit_compressed_write(inode
,
862 async_extent
->ram_size
,
864 ins
.offset
, async_extent
->pages
,
865 async_extent
->nr_pages
,
866 async_chunk
->write_flags
)) {
867 struct page
*p
= async_extent
->pages
[0];
868 const u64 start
= async_extent
->start
;
869 const u64 end
= start
+ async_extent
->ram_size
- 1;
871 p
->mapping
= inode
->i_mapping
;
872 btrfs_writepage_endio_finish_ordered(p
, start
, end
, 0);
875 extent_clear_unlock_delalloc(inode
, start
, end
,
879 free_async_extent_pages(async_extent
);
881 alloc_hint
= ins
.objectid
+ ins
.offset
;
887 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
888 btrfs_free_reserved_extent(fs_info
, ins
.objectid
, ins
.offset
, 1);
890 extent_clear_unlock_delalloc(inode
, async_extent
->start
,
891 async_extent
->start
+
892 async_extent
->ram_size
- 1,
893 NULL
, EXTENT_LOCKED
| EXTENT_DELALLOC
|
894 EXTENT_DELALLOC_NEW
|
895 EXTENT_DEFRAG
| EXTENT_DO_ACCOUNTING
,
896 PAGE_UNLOCK
| PAGE_CLEAR_DIRTY
|
897 PAGE_SET_WRITEBACK
| PAGE_END_WRITEBACK
|
899 free_async_extent_pages(async_extent
);
904 static u64
get_extent_allocation_hint(struct inode
*inode
, u64 start
,
907 struct extent_map_tree
*em_tree
= &BTRFS_I(inode
)->extent_tree
;
908 struct extent_map
*em
;
911 read_lock(&em_tree
->lock
);
912 em
= search_extent_mapping(em_tree
, start
, num_bytes
);
915 * if block start isn't an actual block number then find the
916 * first block in this inode and use that as a hint. If that
917 * block is also bogus then just don't worry about it.
919 if (em
->block_start
>= EXTENT_MAP_LAST_BYTE
) {
921 em
= search_extent_mapping(em_tree
, 0, 0);
922 if (em
&& em
->block_start
< EXTENT_MAP_LAST_BYTE
)
923 alloc_hint
= em
->block_start
;
927 alloc_hint
= em
->block_start
;
931 read_unlock(&em_tree
->lock
);
937 * when extent_io.c finds a delayed allocation range in the file,
938 * the call backs end up in this code. The basic idea is to
939 * allocate extents on disk for the range, and create ordered data structs
940 * in ram to track those extents.
942 * locked_page is the page that writepage had locked already. We use
943 * it to make sure we don't do extra locks or unlocks.
945 * *page_started is set to one if we unlock locked_page and do everything
946 * required to start IO on it. It may be clean and already done with
949 static noinline
int cow_file_range(struct inode
*inode
,
950 struct page
*locked_page
,
951 u64 start
, u64 end
, int *page_started
,
952 unsigned long *nr_written
, int unlock
)
954 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
955 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
958 unsigned long ram_size
;
959 u64 cur_alloc_size
= 0;
960 u64 blocksize
= fs_info
->sectorsize
;
961 struct btrfs_key ins
;
962 struct extent_map
*em
;
964 unsigned long page_ops
;
965 bool extent_reserved
= false;
968 if (btrfs_is_free_space_inode(BTRFS_I(inode
))) {
974 num_bytes
= ALIGN(end
- start
+ 1, blocksize
);
975 num_bytes
= max(blocksize
, num_bytes
);
976 ASSERT(num_bytes
<= btrfs_super_total_bytes(fs_info
->super_copy
));
978 inode_should_defrag(BTRFS_I(inode
), start
, end
, num_bytes
, SZ_64K
);
981 /* lets try to make an inline extent */
982 ret
= cow_file_range_inline(inode
, start
, end
, 0,
983 BTRFS_COMPRESS_NONE
, NULL
);
986 * We use DO_ACCOUNTING here because we need the
987 * delalloc_release_metadata to be run _after_ we drop
988 * our outstanding extent for clearing delalloc for this
991 extent_clear_unlock_delalloc(inode
, start
, end
, NULL
,
992 EXTENT_LOCKED
| EXTENT_DELALLOC
|
993 EXTENT_DELALLOC_NEW
| EXTENT_DEFRAG
|
994 EXTENT_DO_ACCOUNTING
, PAGE_UNLOCK
|
995 PAGE_CLEAR_DIRTY
| PAGE_SET_WRITEBACK
|
997 *nr_written
= *nr_written
+
998 (end
- start
+ PAGE_SIZE
) / PAGE_SIZE
;
1001 } else if (ret
< 0) {
1006 alloc_hint
= get_extent_allocation_hint(inode
, start
, num_bytes
);
1007 btrfs_drop_extent_cache(BTRFS_I(inode
), start
,
1008 start
+ num_bytes
- 1, 0);
1010 while (num_bytes
> 0) {
1011 cur_alloc_size
= num_bytes
;
1012 ret
= btrfs_reserve_extent(root
, cur_alloc_size
, cur_alloc_size
,
1013 fs_info
->sectorsize
, 0, alloc_hint
,
1017 cur_alloc_size
= ins
.offset
;
1018 extent_reserved
= true;
1020 ram_size
= ins
.offset
;
1021 em
= create_io_em(inode
, start
, ins
.offset
, /* len */
1022 start
, /* orig_start */
1023 ins
.objectid
, /* block_start */
1024 ins
.offset
, /* block_len */
1025 ins
.offset
, /* orig_block_len */
1026 ram_size
, /* ram_bytes */
1027 BTRFS_COMPRESS_NONE
, /* compress_type */
1028 BTRFS_ORDERED_REGULAR
/* type */);
1033 free_extent_map(em
);
1035 ret
= btrfs_add_ordered_extent(inode
, start
, ins
.objectid
,
1036 ram_size
, cur_alloc_size
, 0);
1038 goto out_drop_extent_cache
;
1040 if (root
->root_key
.objectid
==
1041 BTRFS_DATA_RELOC_TREE_OBJECTID
) {
1042 ret
= btrfs_reloc_clone_csums(inode
, start
,
1045 * Only drop cache here, and process as normal.
1047 * We must not allow extent_clear_unlock_delalloc()
1048 * at out_unlock label to free meta of this ordered
1049 * extent, as its meta should be freed by
1050 * btrfs_finish_ordered_io().
1052 * So we must continue until @start is increased to
1053 * skip current ordered extent.
1056 btrfs_drop_extent_cache(BTRFS_I(inode
), start
,
1057 start
+ ram_size
- 1, 0);
1060 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
1062 /* we're not doing compressed IO, don't unlock the first
1063 * page (which the caller expects to stay locked), don't
1064 * clear any dirty bits and don't set any writeback bits
1066 * Do set the Private2 bit so we know this page was properly
1067 * setup for writepage
1069 page_ops
= unlock
? PAGE_UNLOCK
: 0;
1070 page_ops
|= PAGE_SET_PRIVATE2
;
1072 extent_clear_unlock_delalloc(inode
, start
,
1073 start
+ ram_size
- 1,
1075 EXTENT_LOCKED
| EXTENT_DELALLOC
,
1077 if (num_bytes
< cur_alloc_size
)
1080 num_bytes
-= cur_alloc_size
;
1081 alloc_hint
= ins
.objectid
+ ins
.offset
;
1082 start
+= cur_alloc_size
;
1083 extent_reserved
= false;
1086 * btrfs_reloc_clone_csums() error, since start is increased
1087 * extent_clear_unlock_delalloc() at out_unlock label won't
1088 * free metadata of current ordered extent, we're OK to exit.
1096 out_drop_extent_cache
:
1097 btrfs_drop_extent_cache(BTRFS_I(inode
), start
, start
+ ram_size
- 1, 0);
1099 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
1100 btrfs_free_reserved_extent(fs_info
, ins
.objectid
, ins
.offset
, 1);
1102 clear_bits
= EXTENT_LOCKED
| EXTENT_DELALLOC
| EXTENT_DELALLOC_NEW
|
1103 EXTENT_DEFRAG
| EXTENT_CLEAR_META_RESV
;
1104 page_ops
= PAGE_UNLOCK
| PAGE_CLEAR_DIRTY
| PAGE_SET_WRITEBACK
|
1107 * If we reserved an extent for our delalloc range (or a subrange) and
1108 * failed to create the respective ordered extent, then it means that
1109 * when we reserved the extent we decremented the extent's size from
1110 * the data space_info's bytes_may_use counter and incremented the
1111 * space_info's bytes_reserved counter by the same amount. We must make
1112 * sure extent_clear_unlock_delalloc() does not try to decrement again
1113 * the data space_info's bytes_may_use counter, therefore we do not pass
1114 * it the flag EXTENT_CLEAR_DATA_RESV.
1116 if (extent_reserved
) {
1117 extent_clear_unlock_delalloc(inode
, start
,
1118 start
+ cur_alloc_size
,
1122 start
+= cur_alloc_size
;
1126 extent_clear_unlock_delalloc(inode
, start
, end
, locked_page
,
1127 clear_bits
| EXTENT_CLEAR_DATA_RESV
,
1133 * work queue call back to started compression on a file and pages
1135 static noinline
void async_cow_start(struct btrfs_work
*work
)
1137 struct async_chunk
*async_chunk
;
1138 int compressed_extents
;
1140 async_chunk
= container_of(work
, struct async_chunk
, work
);
1142 compressed_extents
= compress_file_range(async_chunk
);
1143 if (compressed_extents
== 0) {
1144 btrfs_add_delayed_iput(async_chunk
->inode
);
1145 async_chunk
->inode
= NULL
;
1150 * work queue call back to submit previously compressed pages
1152 static noinline
void async_cow_submit(struct btrfs_work
*work
)
1154 struct async_chunk
*async_chunk
= container_of(work
, struct async_chunk
,
1156 struct btrfs_fs_info
*fs_info
= btrfs_work_owner(work
);
1157 unsigned long nr_pages
;
1159 nr_pages
= (async_chunk
->end
- async_chunk
->start
+ PAGE_SIZE
) >>
1162 /* atomic_sub_return implies a barrier */
1163 if (atomic_sub_return(nr_pages
, &fs_info
->async_delalloc_pages
) <
1165 cond_wake_up_nomb(&fs_info
->async_submit_wait
);
1168 * ->inode could be NULL if async_chunk_start has failed to compress,
1169 * in which case we don't have anything to submit, yet we need to
1170 * always adjust ->async_delalloc_pages as its paired with the init
1171 * happening in cow_file_range_async
1173 if (async_chunk
->inode
)
1174 submit_compressed_extents(async_chunk
);
1177 static noinline
void async_cow_free(struct btrfs_work
*work
)
1179 struct async_chunk
*async_chunk
;
1181 async_chunk
= container_of(work
, struct async_chunk
, work
);
1182 if (async_chunk
->inode
)
1183 btrfs_add_delayed_iput(async_chunk
->inode
);
1185 * Since the pointer to 'pending' is at the beginning of the array of
1186 * async_chunk's, freeing it ensures the whole array has been freed.
1188 if (atomic_dec_and_test(async_chunk
->pending
))
1189 kvfree(async_chunk
->pending
);
1192 static int cow_file_range_async(struct inode
*inode
, struct page
*locked_page
,
1193 u64 start
, u64 end
, int *page_started
,
1194 unsigned long *nr_written
,
1195 unsigned int write_flags
)
1197 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1198 struct async_cow
*ctx
;
1199 struct async_chunk
*async_chunk
;
1200 unsigned long nr_pages
;
1202 u64 num_chunks
= DIV_ROUND_UP(end
- start
, SZ_512K
);
1204 bool should_compress
;
1207 unlock_extent(&BTRFS_I(inode
)->io_tree
, start
, end
);
1209 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_NOCOMPRESS
&&
1210 !btrfs_test_opt(fs_info
, FORCE_COMPRESS
)) {
1212 should_compress
= false;
1214 should_compress
= true;
1217 nofs_flag
= memalloc_nofs_save();
1218 ctx
= kvmalloc(struct_size(ctx
, chunks
, num_chunks
), GFP_KERNEL
);
1219 memalloc_nofs_restore(nofs_flag
);
1222 unsigned clear_bits
= EXTENT_LOCKED
| EXTENT_DELALLOC
|
1223 EXTENT_DELALLOC_NEW
| EXTENT_DEFRAG
|
1224 EXTENT_DO_ACCOUNTING
;
1225 unsigned long page_ops
= PAGE_UNLOCK
| PAGE_CLEAR_DIRTY
|
1226 PAGE_SET_WRITEBACK
| PAGE_END_WRITEBACK
|
1229 extent_clear_unlock_delalloc(inode
, start
, end
, locked_page
,
1230 clear_bits
, page_ops
);
1234 async_chunk
= ctx
->chunks
;
1235 atomic_set(&ctx
->num_chunks
, num_chunks
);
1237 for (i
= 0; i
< num_chunks
; i
++) {
1238 if (should_compress
)
1239 cur_end
= min(end
, start
+ SZ_512K
- 1);
1244 * igrab is called higher up in the call chain, take only the
1245 * lightweight reference for the callback lifetime
1248 async_chunk
[i
].pending
= &ctx
->num_chunks
;
1249 async_chunk
[i
].inode
= inode
;
1250 async_chunk
[i
].start
= start
;
1251 async_chunk
[i
].end
= cur_end
;
1252 async_chunk
[i
].locked_page
= locked_page
;
1253 async_chunk
[i
].write_flags
= write_flags
;
1254 INIT_LIST_HEAD(&async_chunk
[i
].extents
);
1256 btrfs_init_work(&async_chunk
[i
].work
,
1257 btrfs_delalloc_helper
,
1258 async_cow_start
, async_cow_submit
,
1261 nr_pages
= DIV_ROUND_UP(cur_end
- start
, PAGE_SIZE
);
1262 atomic_add(nr_pages
, &fs_info
->async_delalloc_pages
);
1264 btrfs_queue_work(fs_info
->delalloc_workers
, &async_chunk
[i
].work
);
1266 *nr_written
+= nr_pages
;
1267 start
= cur_end
+ 1;
1273 static noinline
int csum_exist_in_range(struct btrfs_fs_info
*fs_info
,
1274 u64 bytenr
, u64 num_bytes
)
1277 struct btrfs_ordered_sum
*sums
;
1280 ret
= btrfs_lookup_csums_range(fs_info
->csum_root
, bytenr
,
1281 bytenr
+ num_bytes
- 1, &list
, 0);
1282 if (ret
== 0 && list_empty(&list
))
1285 while (!list_empty(&list
)) {
1286 sums
= list_entry(list
.next
, struct btrfs_ordered_sum
, list
);
1287 list_del(&sums
->list
);
1296 * when nowcow writeback call back. This checks for snapshots or COW copies
1297 * of the extents that exist in the file, and COWs the file as required.
1299 * If no cow copies or snapshots exist, we write directly to the existing
1302 static noinline
int run_delalloc_nocow(struct inode
*inode
,
1303 struct page
*locked_page
,
1304 const u64 start
, const u64 end
,
1305 int *page_started
, int force
,
1306 unsigned long *nr_written
)
1308 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1309 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
1310 struct btrfs_path
*path
;
1311 u64 cow_start
= (u64
)-1;
1312 u64 cur_offset
= start
;
1314 bool check_prev
= true;
1315 const bool freespace_inode
= btrfs_is_free_space_inode(BTRFS_I(inode
));
1316 u64 ino
= btrfs_ino(BTRFS_I(inode
));
1318 path
= btrfs_alloc_path();
1320 extent_clear_unlock_delalloc(inode
, start
, end
, locked_page
,
1321 EXTENT_LOCKED
| EXTENT_DELALLOC
|
1322 EXTENT_DO_ACCOUNTING
|
1323 EXTENT_DEFRAG
, PAGE_UNLOCK
|
1325 PAGE_SET_WRITEBACK
|
1326 PAGE_END_WRITEBACK
);
1331 struct btrfs_key found_key
;
1332 struct btrfs_file_extent_item
*fi
;
1333 struct extent_buffer
*leaf
;
1336 u64 disk_bytenr
= 0;
1344 ret
= btrfs_lookup_file_extent(NULL
, root
, path
, ino
,
1348 if (ret
> 0 && path
->slots
[0] > 0 && check_prev
) {
1349 leaf
= path
->nodes
[0];
1350 btrfs_item_key_to_cpu(leaf
, &found_key
,
1351 path
->slots
[0] - 1);
1352 if (found_key
.objectid
== ino
&&
1353 found_key
.type
== BTRFS_EXTENT_DATA_KEY
)
1358 leaf
= path
->nodes
[0];
1359 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
1360 ret
= btrfs_next_leaf(root
, path
);
1362 if (cow_start
!= (u64
)-1)
1363 cur_offset
= cow_start
;
1368 leaf
= path
->nodes
[0];
1371 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
1373 if (found_key
.objectid
> ino
)
1375 if (WARN_ON_ONCE(found_key
.objectid
< ino
) ||
1376 found_key
.type
< BTRFS_EXTENT_DATA_KEY
) {
1380 if (found_key
.type
> BTRFS_EXTENT_DATA_KEY
||
1381 found_key
.offset
> end
)
1384 if (found_key
.offset
> cur_offset
) {
1385 extent_end
= found_key
.offset
;
1390 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
1391 struct btrfs_file_extent_item
);
1392 extent_type
= btrfs_file_extent_type(leaf
, fi
);
1394 ram_bytes
= btrfs_file_extent_ram_bytes(leaf
, fi
);
1395 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
1396 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
1397 disk_bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
1398 extent_offset
= btrfs_file_extent_offset(leaf
, fi
);
1399 extent_end
= found_key
.offset
+
1400 btrfs_file_extent_num_bytes(leaf
, fi
);
1402 btrfs_file_extent_disk_num_bytes(leaf
, fi
);
1403 if (extent_end
<= start
) {
1407 if (disk_bytenr
== 0)
1409 if (btrfs_file_extent_compression(leaf
, fi
) ||
1410 btrfs_file_extent_encryption(leaf
, fi
) ||
1411 btrfs_file_extent_other_encoding(leaf
, fi
))
1414 * Do the same check as in btrfs_cross_ref_exist but
1415 * without the unnecessary search.
1417 if (!freespace_inode
&&
1418 btrfs_file_extent_generation(leaf
, fi
) <=
1419 btrfs_root_last_snapshot(&root
->root_item
))
1421 if (extent_type
== BTRFS_FILE_EXTENT_REG
&& !force
)
1423 if (btrfs_extent_readonly(fs_info
, disk_bytenr
))
1425 ret
= btrfs_cross_ref_exist(root
, ino
,
1427 extent_offset
, disk_bytenr
);
1430 * ret could be -EIO if the above fails to read
1434 if (cow_start
!= (u64
)-1)
1435 cur_offset
= cow_start
;
1439 WARN_ON_ONCE(freespace_inode
);
1442 disk_bytenr
+= extent_offset
;
1443 disk_bytenr
+= cur_offset
- found_key
.offset
;
1444 num_bytes
= min(end
+ 1, extent_end
) - cur_offset
;
1446 * if there are pending snapshots for this root,
1447 * we fall into common COW way.
1449 if (!freespace_inode
&& atomic_read(&root
->snapshot_force_cow
))
1452 * force cow if csum exists in the range.
1453 * this ensure that csum for a given extent are
1454 * either valid or do not exist.
1456 ret
= csum_exist_in_range(fs_info
, disk_bytenr
,
1460 * ret could be -EIO if the above fails to read
1464 if (cow_start
!= (u64
)-1)
1465 cur_offset
= cow_start
;
1468 WARN_ON_ONCE(freespace_inode
);
1471 if (!btrfs_inc_nocow_writers(fs_info
, disk_bytenr
))
1474 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
1475 extent_end
= found_key
.offset
+
1476 btrfs_file_extent_ram_bytes(leaf
, fi
);
1477 extent_end
= ALIGN(extent_end
,
1478 fs_info
->sectorsize
);
1483 if (extent_end
<= start
) {
1486 btrfs_dec_nocow_writers(fs_info
, disk_bytenr
);
1490 if (cow_start
== (u64
)-1)
1491 cow_start
= cur_offset
;
1492 cur_offset
= extent_end
;
1493 if (cur_offset
> end
)
1499 btrfs_release_path(path
);
1500 if (cow_start
!= (u64
)-1) {
1501 ret
= cow_file_range(inode
, locked_page
,
1502 cow_start
, found_key
.offset
- 1,
1503 page_started
, nr_written
, 1);
1506 btrfs_dec_nocow_writers(fs_info
,
1510 cow_start
= (u64
)-1;
1513 if (extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
1514 u64 orig_start
= found_key
.offset
- extent_offset
;
1515 struct extent_map
*em
;
1517 em
= create_io_em(inode
, cur_offset
, num_bytes
,
1519 disk_bytenr
, /* block_start */
1520 num_bytes
, /* block_len */
1521 disk_num_bytes
, /* orig_block_len */
1522 ram_bytes
, BTRFS_COMPRESS_NONE
,
1523 BTRFS_ORDERED_PREALLOC
);
1526 btrfs_dec_nocow_writers(fs_info
,
1531 free_extent_map(em
);
1534 if (extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
1535 type
= BTRFS_ORDERED_PREALLOC
;
1537 type
= BTRFS_ORDERED_NOCOW
;
1540 ret
= btrfs_add_ordered_extent(inode
, cur_offset
, disk_bytenr
,
1541 num_bytes
, num_bytes
,type
);
1543 btrfs_dec_nocow_writers(fs_info
, disk_bytenr
);
1544 BUG_ON(ret
); /* -ENOMEM */
1546 if (root
->root_key
.objectid
==
1547 BTRFS_DATA_RELOC_TREE_OBJECTID
)
1549 * Error handled later, as we must prevent
1550 * extent_clear_unlock_delalloc() in error handler
1551 * from freeing metadata of created ordered extent.
1553 ret
= btrfs_reloc_clone_csums(inode
, cur_offset
,
1556 extent_clear_unlock_delalloc(inode
, cur_offset
,
1557 cur_offset
+ num_bytes
- 1,
1558 locked_page
, EXTENT_LOCKED
|
1560 EXTENT_CLEAR_DATA_RESV
,
1561 PAGE_UNLOCK
| PAGE_SET_PRIVATE2
);
1563 cur_offset
= extent_end
;
1566 * btrfs_reloc_clone_csums() error, now we're OK to call error
1567 * handler, as metadata for created ordered extent will only
1568 * be freed by btrfs_finish_ordered_io().
1572 if (cur_offset
> end
)
1575 btrfs_release_path(path
);
1577 if (cur_offset
<= end
&& cow_start
== (u64
)-1)
1578 cow_start
= cur_offset
;
1580 if (cow_start
!= (u64
)-1) {
1582 ret
= cow_file_range(inode
, locked_page
, cow_start
, end
,
1583 page_started
, nr_written
, 1);
1589 if (ret
&& cur_offset
< end
)
1590 extent_clear_unlock_delalloc(inode
, cur_offset
, end
,
1591 locked_page
, EXTENT_LOCKED
|
1592 EXTENT_DELALLOC
| EXTENT_DEFRAG
|
1593 EXTENT_DO_ACCOUNTING
, PAGE_UNLOCK
|
1595 PAGE_SET_WRITEBACK
|
1596 PAGE_END_WRITEBACK
);
1597 btrfs_free_path(path
);
1601 static inline int need_force_cow(struct inode
*inode
, u64 start
, u64 end
)
1604 if (!(BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
) &&
1605 !(BTRFS_I(inode
)->flags
& BTRFS_INODE_PREALLOC
))
1609 * @defrag_bytes is a hint value, no spinlock held here,
1610 * if is not zero, it means the file is defragging.
1611 * Force cow if given extent needs to be defragged.
1613 if (BTRFS_I(inode
)->defrag_bytes
&&
1614 test_range_bit(&BTRFS_I(inode
)->io_tree
, start
, end
,
1615 EXTENT_DEFRAG
, 0, NULL
))
1622 * Function to process delayed allocation (create CoW) for ranges which are
1623 * being touched for the first time.
1625 int btrfs_run_delalloc_range(struct inode
*inode
, struct page
*locked_page
,
1626 u64 start
, u64 end
, int *page_started
, unsigned long *nr_written
,
1627 struct writeback_control
*wbc
)
1630 int force_cow
= need_force_cow(inode
, start
, end
);
1631 unsigned int write_flags
= wbc_to_write_flags(wbc
);
1633 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
&& !force_cow
) {
1634 ret
= run_delalloc_nocow(inode
, locked_page
, start
, end
,
1635 page_started
, 1, nr_written
);
1636 } else if (BTRFS_I(inode
)->flags
& BTRFS_INODE_PREALLOC
&& !force_cow
) {
1637 ret
= run_delalloc_nocow(inode
, locked_page
, start
, end
,
1638 page_started
, 0, nr_written
);
1639 } else if (!inode_can_compress(inode
) ||
1640 !inode_need_compress(inode
, start
, end
)) {
1641 ret
= cow_file_range(inode
, locked_page
, start
, end
,
1642 page_started
, nr_written
, 1);
1644 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
1645 &BTRFS_I(inode
)->runtime_flags
);
1646 ret
= cow_file_range_async(inode
, locked_page
, start
, end
,
1647 page_started
, nr_written
,
1651 btrfs_cleanup_ordered_extents(inode
, locked_page
, start
,
1656 void btrfs_split_delalloc_extent(struct inode
*inode
,
1657 struct extent_state
*orig
, u64 split
)
1661 /* not delalloc, ignore it */
1662 if (!(orig
->state
& EXTENT_DELALLOC
))
1665 size
= orig
->end
- orig
->start
+ 1;
1666 if (size
> BTRFS_MAX_EXTENT_SIZE
) {
1671 * See the explanation in btrfs_merge_delalloc_extent, the same
1672 * applies here, just in reverse.
1674 new_size
= orig
->end
- split
+ 1;
1675 num_extents
= count_max_extents(new_size
);
1676 new_size
= split
- orig
->start
;
1677 num_extents
+= count_max_extents(new_size
);
1678 if (count_max_extents(size
) >= num_extents
)
1682 spin_lock(&BTRFS_I(inode
)->lock
);
1683 btrfs_mod_outstanding_extents(BTRFS_I(inode
), 1);
1684 spin_unlock(&BTRFS_I(inode
)->lock
);
1688 * Handle merged delayed allocation extents so we can keep track of new extents
1689 * that are just merged onto old extents, such as when we are doing sequential
1690 * writes, so we can properly account for the metadata space we'll need.
1692 void btrfs_merge_delalloc_extent(struct inode
*inode
, struct extent_state
*new,
1693 struct extent_state
*other
)
1695 u64 new_size
, old_size
;
1698 /* not delalloc, ignore it */
1699 if (!(other
->state
& EXTENT_DELALLOC
))
1702 if (new->start
> other
->start
)
1703 new_size
= new->end
- other
->start
+ 1;
1705 new_size
= other
->end
- new->start
+ 1;
1707 /* we're not bigger than the max, unreserve the space and go */
1708 if (new_size
<= BTRFS_MAX_EXTENT_SIZE
) {
1709 spin_lock(&BTRFS_I(inode
)->lock
);
1710 btrfs_mod_outstanding_extents(BTRFS_I(inode
), -1);
1711 spin_unlock(&BTRFS_I(inode
)->lock
);
1716 * We have to add up either side to figure out how many extents were
1717 * accounted for before we merged into one big extent. If the number of
1718 * extents we accounted for is <= the amount we need for the new range
1719 * then we can return, otherwise drop. Think of it like this
1723 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1724 * need 2 outstanding extents, on one side we have 1 and the other side
1725 * we have 1 so they are == and we can return. But in this case
1727 * [MAX_SIZE+4k][MAX_SIZE+4k]
1729 * Each range on their own accounts for 2 extents, but merged together
1730 * they are only 3 extents worth of accounting, so we need to drop in
1733 old_size
= other
->end
- other
->start
+ 1;
1734 num_extents
= count_max_extents(old_size
);
1735 old_size
= new->end
- new->start
+ 1;
1736 num_extents
+= count_max_extents(old_size
);
1737 if (count_max_extents(new_size
) >= num_extents
)
1740 spin_lock(&BTRFS_I(inode
)->lock
);
1741 btrfs_mod_outstanding_extents(BTRFS_I(inode
), -1);
1742 spin_unlock(&BTRFS_I(inode
)->lock
);
1745 static void btrfs_add_delalloc_inodes(struct btrfs_root
*root
,
1746 struct inode
*inode
)
1748 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1750 spin_lock(&root
->delalloc_lock
);
1751 if (list_empty(&BTRFS_I(inode
)->delalloc_inodes
)) {
1752 list_add_tail(&BTRFS_I(inode
)->delalloc_inodes
,
1753 &root
->delalloc_inodes
);
1754 set_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
1755 &BTRFS_I(inode
)->runtime_flags
);
1756 root
->nr_delalloc_inodes
++;
1757 if (root
->nr_delalloc_inodes
== 1) {
1758 spin_lock(&fs_info
->delalloc_root_lock
);
1759 BUG_ON(!list_empty(&root
->delalloc_root
));
1760 list_add_tail(&root
->delalloc_root
,
1761 &fs_info
->delalloc_roots
);
1762 spin_unlock(&fs_info
->delalloc_root_lock
);
1765 spin_unlock(&root
->delalloc_lock
);
1769 void __btrfs_del_delalloc_inode(struct btrfs_root
*root
,
1770 struct btrfs_inode
*inode
)
1772 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
1774 if (!list_empty(&inode
->delalloc_inodes
)) {
1775 list_del_init(&inode
->delalloc_inodes
);
1776 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
1777 &inode
->runtime_flags
);
1778 root
->nr_delalloc_inodes
--;
1779 if (!root
->nr_delalloc_inodes
) {
1780 ASSERT(list_empty(&root
->delalloc_inodes
));
1781 spin_lock(&fs_info
->delalloc_root_lock
);
1782 BUG_ON(list_empty(&root
->delalloc_root
));
1783 list_del_init(&root
->delalloc_root
);
1784 spin_unlock(&fs_info
->delalloc_root_lock
);
1789 static void btrfs_del_delalloc_inode(struct btrfs_root
*root
,
1790 struct btrfs_inode
*inode
)
1792 spin_lock(&root
->delalloc_lock
);
1793 __btrfs_del_delalloc_inode(root
, inode
);
1794 spin_unlock(&root
->delalloc_lock
);
1798 * Properly track delayed allocation bytes in the inode and to maintain the
1799 * list of inodes that have pending delalloc work to be done.
1801 void btrfs_set_delalloc_extent(struct inode
*inode
, struct extent_state
*state
,
1804 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1806 if ((*bits
& EXTENT_DEFRAG
) && !(*bits
& EXTENT_DELALLOC
))
1809 * set_bit and clear bit hooks normally require _irqsave/restore
1810 * but in this case, we are only testing for the DELALLOC
1811 * bit, which is only set or cleared with irqs on
1813 if (!(state
->state
& EXTENT_DELALLOC
) && (*bits
& EXTENT_DELALLOC
)) {
1814 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
1815 u64 len
= state
->end
+ 1 - state
->start
;
1816 u32 num_extents
= count_max_extents(len
);
1817 bool do_list
= !btrfs_is_free_space_inode(BTRFS_I(inode
));
1819 spin_lock(&BTRFS_I(inode
)->lock
);
1820 btrfs_mod_outstanding_extents(BTRFS_I(inode
), num_extents
);
1821 spin_unlock(&BTRFS_I(inode
)->lock
);
1823 /* For sanity tests */
1824 if (btrfs_is_testing(fs_info
))
1827 percpu_counter_add_batch(&fs_info
->delalloc_bytes
, len
,
1828 fs_info
->delalloc_batch
);
1829 spin_lock(&BTRFS_I(inode
)->lock
);
1830 BTRFS_I(inode
)->delalloc_bytes
+= len
;
1831 if (*bits
& EXTENT_DEFRAG
)
1832 BTRFS_I(inode
)->defrag_bytes
+= len
;
1833 if (do_list
&& !test_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
1834 &BTRFS_I(inode
)->runtime_flags
))
1835 btrfs_add_delalloc_inodes(root
, inode
);
1836 spin_unlock(&BTRFS_I(inode
)->lock
);
1839 if (!(state
->state
& EXTENT_DELALLOC_NEW
) &&
1840 (*bits
& EXTENT_DELALLOC_NEW
)) {
1841 spin_lock(&BTRFS_I(inode
)->lock
);
1842 BTRFS_I(inode
)->new_delalloc_bytes
+= state
->end
+ 1 -
1844 spin_unlock(&BTRFS_I(inode
)->lock
);
1849 * Once a range is no longer delalloc this function ensures that proper
1850 * accounting happens.
1852 void btrfs_clear_delalloc_extent(struct inode
*vfs_inode
,
1853 struct extent_state
*state
, unsigned *bits
)
1855 struct btrfs_inode
*inode
= BTRFS_I(vfs_inode
);
1856 struct btrfs_fs_info
*fs_info
= btrfs_sb(vfs_inode
->i_sb
);
1857 u64 len
= state
->end
+ 1 - state
->start
;
1858 u32 num_extents
= count_max_extents(len
);
1860 if ((state
->state
& EXTENT_DEFRAG
) && (*bits
& EXTENT_DEFRAG
)) {
1861 spin_lock(&inode
->lock
);
1862 inode
->defrag_bytes
-= len
;
1863 spin_unlock(&inode
->lock
);
1867 * set_bit and clear bit hooks normally require _irqsave/restore
1868 * but in this case, we are only testing for the DELALLOC
1869 * bit, which is only set or cleared with irqs on
1871 if ((state
->state
& EXTENT_DELALLOC
) && (*bits
& EXTENT_DELALLOC
)) {
1872 struct btrfs_root
*root
= inode
->root
;
1873 bool do_list
= !btrfs_is_free_space_inode(inode
);
1875 spin_lock(&inode
->lock
);
1876 btrfs_mod_outstanding_extents(inode
, -num_extents
);
1877 spin_unlock(&inode
->lock
);
1880 * We don't reserve metadata space for space cache inodes so we
1881 * don't need to call delalloc_release_metadata if there is an
1884 if (*bits
& EXTENT_CLEAR_META_RESV
&&
1885 root
!= fs_info
->tree_root
)
1886 btrfs_delalloc_release_metadata(inode
, len
, false);
1888 /* For sanity tests. */
1889 if (btrfs_is_testing(fs_info
))
1892 if (root
->root_key
.objectid
!= BTRFS_DATA_RELOC_TREE_OBJECTID
&&
1893 do_list
&& !(state
->state
& EXTENT_NORESERVE
) &&
1894 (*bits
& EXTENT_CLEAR_DATA_RESV
))
1895 btrfs_free_reserved_data_space_noquota(
1899 percpu_counter_add_batch(&fs_info
->delalloc_bytes
, -len
,
1900 fs_info
->delalloc_batch
);
1901 spin_lock(&inode
->lock
);
1902 inode
->delalloc_bytes
-= len
;
1903 if (do_list
&& inode
->delalloc_bytes
== 0 &&
1904 test_bit(BTRFS_INODE_IN_DELALLOC_LIST
,
1905 &inode
->runtime_flags
))
1906 btrfs_del_delalloc_inode(root
, inode
);
1907 spin_unlock(&inode
->lock
);
1910 if ((state
->state
& EXTENT_DELALLOC_NEW
) &&
1911 (*bits
& EXTENT_DELALLOC_NEW
)) {
1912 spin_lock(&inode
->lock
);
1913 ASSERT(inode
->new_delalloc_bytes
>= len
);
1914 inode
->new_delalloc_bytes
-= len
;
1915 spin_unlock(&inode
->lock
);
1920 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
1921 * in a chunk's stripe. This function ensures that bios do not span a
1924 * @page - The page we are about to add to the bio
1925 * @size - size we want to add to the bio
1926 * @bio - bio we want to ensure is smaller than a stripe
1927 * @bio_flags - flags of the bio
1929 * return 1 if page cannot be added to the bio
1930 * return 0 if page can be added to the bio
1931 * return error otherwise
1933 int btrfs_bio_fits_in_stripe(struct page
*page
, size_t size
, struct bio
*bio
,
1934 unsigned long bio_flags
)
1936 struct inode
*inode
= page
->mapping
->host
;
1937 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
1938 u64 logical
= (u64
)bio
->bi_iter
.bi_sector
<< 9;
1942 struct btrfs_io_geometry geom
;
1944 if (bio_flags
& EXTENT_BIO_COMPRESSED
)
1947 length
= bio
->bi_iter
.bi_size
;
1948 map_length
= length
;
1949 ret
= btrfs_get_io_geometry(fs_info
, btrfs_op(bio
), logical
, map_length
,
1954 if (geom
.len
< length
+ size
)
1960 * in order to insert checksums into the metadata in large chunks,
1961 * we wait until bio submission time. All the pages in the bio are
1962 * checksummed and sums are attached onto the ordered extent record.
1964 * At IO completion time the cums attached on the ordered extent record
1965 * are inserted into the btree
1967 static blk_status_t
btrfs_submit_bio_start(void *private_data
, struct bio
*bio
,
1970 struct inode
*inode
= private_data
;
1971 blk_status_t ret
= 0;
1973 ret
= btrfs_csum_one_bio(inode
, bio
, 0, 0);
1974 BUG_ON(ret
); /* -ENOMEM */
1979 * extent_io.c submission hook. This does the right thing for csum calculation
1980 * on write, or reading the csums from the tree before a read.
1982 * Rules about async/sync submit,
1983 * a) read: sync submit
1985 * b) write without checksum: sync submit
1987 * c) write with checksum:
1988 * c-1) if bio is issued by fsync: sync submit
1989 * (sync_writers != 0)
1991 * c-2) if root is reloc root: sync submit
1992 * (only in case of buffered IO)
1994 * c-3) otherwise: async submit
1996 static blk_status_t
btrfs_submit_bio_hook(struct inode
*inode
, struct bio
*bio
,
1998 unsigned long bio_flags
)
2001 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2002 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2003 enum btrfs_wq_endio_type metadata
= BTRFS_WQ_ENDIO_DATA
;
2004 blk_status_t ret
= 0;
2006 int async
= !atomic_read(&BTRFS_I(inode
)->sync_writers
);
2008 skip_sum
= BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
;
2010 if (btrfs_is_free_space_inode(BTRFS_I(inode
)))
2011 metadata
= BTRFS_WQ_ENDIO_FREE_SPACE
;
2013 if (bio_op(bio
) != REQ_OP_WRITE
) {
2014 ret
= btrfs_bio_wq_end_io(fs_info
, bio
, metadata
);
2018 if (bio_flags
& EXTENT_BIO_COMPRESSED
) {
2019 ret
= btrfs_submit_compressed_read(inode
, bio
,
2023 } else if (!skip_sum
) {
2024 ret
= btrfs_lookup_bio_sums(inode
, bio
, NULL
);
2029 } else if (async
&& !skip_sum
) {
2030 /* csum items have already been cloned */
2031 if (root
->root_key
.objectid
== BTRFS_DATA_RELOC_TREE_OBJECTID
)
2033 /* we're doing a write, do the async checksumming */
2034 ret
= btrfs_wq_submit_bio(fs_info
, bio
, mirror_num
, bio_flags
,
2035 0, inode
, btrfs_submit_bio_start
);
2037 } else if (!skip_sum
) {
2038 ret
= btrfs_csum_one_bio(inode
, bio
, 0, 0);
2044 ret
= btrfs_map_bio(fs_info
, bio
, mirror_num
, 0);
2048 bio
->bi_status
= ret
;
2055 * given a list of ordered sums record them in the inode. This happens
2056 * at IO completion time based on sums calculated at bio submission time.
2058 static noinline
int add_pending_csums(struct btrfs_trans_handle
*trans
,
2059 struct inode
*inode
, struct list_head
*list
)
2061 struct btrfs_ordered_sum
*sum
;
2064 list_for_each_entry(sum
, list
, list
) {
2065 trans
->adding_csums
= true;
2066 ret
= btrfs_csum_file_blocks(trans
,
2067 BTRFS_I(inode
)->root
->fs_info
->csum_root
, sum
);
2068 trans
->adding_csums
= false;
2075 int btrfs_set_extent_delalloc(struct inode
*inode
, u64 start
, u64 end
,
2076 unsigned int extra_bits
,
2077 struct extent_state
**cached_state
)
2079 WARN_ON(PAGE_ALIGNED(end
));
2080 return set_extent_delalloc(&BTRFS_I(inode
)->io_tree
, start
, end
,
2081 extra_bits
, cached_state
);
2084 /* see btrfs_writepage_start_hook for details on why this is required */
2085 struct btrfs_writepage_fixup
{
2087 struct btrfs_work work
;
2090 static void btrfs_writepage_fixup_worker(struct btrfs_work
*work
)
2092 struct btrfs_writepage_fixup
*fixup
;
2093 struct btrfs_ordered_extent
*ordered
;
2094 struct extent_state
*cached_state
= NULL
;
2095 struct extent_changeset
*data_reserved
= NULL
;
2097 struct inode
*inode
;
2102 fixup
= container_of(work
, struct btrfs_writepage_fixup
, work
);
2106 if (!page
->mapping
|| !PageDirty(page
) || !PageChecked(page
)) {
2107 ClearPageChecked(page
);
2111 inode
= page
->mapping
->host
;
2112 page_start
= page_offset(page
);
2113 page_end
= page_offset(page
) + PAGE_SIZE
- 1;
2115 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, page_start
, page_end
,
2118 /* already ordered? We're done */
2119 if (PagePrivate2(page
))
2122 ordered
= btrfs_lookup_ordered_range(BTRFS_I(inode
), page_start
,
2125 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, page_start
,
2126 page_end
, &cached_state
);
2128 btrfs_start_ordered_extent(inode
, ordered
, 1);
2129 btrfs_put_ordered_extent(ordered
);
2133 ret
= btrfs_delalloc_reserve_space(inode
, &data_reserved
, page_start
,
2136 mapping_set_error(page
->mapping
, ret
);
2137 end_extent_writepage(page
, ret
, page_start
, page_end
);
2138 ClearPageChecked(page
);
2142 ret
= btrfs_set_extent_delalloc(inode
, page_start
, page_end
, 0,
2145 mapping_set_error(page
->mapping
, ret
);
2146 end_extent_writepage(page
, ret
, page_start
, page_end
);
2147 ClearPageChecked(page
);
2151 ClearPageChecked(page
);
2152 set_page_dirty(page
);
2153 btrfs_delalloc_release_extents(BTRFS_I(inode
), PAGE_SIZE
, false);
2155 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, page_start
, page_end
,
2161 extent_changeset_free(data_reserved
);
2165 * There are a few paths in the higher layers of the kernel that directly
2166 * set the page dirty bit without asking the filesystem if it is a
2167 * good idea. This causes problems because we want to make sure COW
2168 * properly happens and the data=ordered rules are followed.
2170 * In our case any range that doesn't have the ORDERED bit set
2171 * hasn't been properly setup for IO. We kick off an async process
2172 * to fix it up. The async helper will wait for ordered extents, set
2173 * the delalloc bit and make it safe to write the page.
2175 int btrfs_writepage_cow_fixup(struct page
*page
, u64 start
, u64 end
)
2177 struct inode
*inode
= page
->mapping
->host
;
2178 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2179 struct btrfs_writepage_fixup
*fixup
;
2181 /* this page is properly in the ordered list */
2182 if (TestClearPagePrivate2(page
))
2185 if (PageChecked(page
))
2188 fixup
= kzalloc(sizeof(*fixup
), GFP_NOFS
);
2192 SetPageChecked(page
);
2194 btrfs_init_work(&fixup
->work
, btrfs_fixup_helper
,
2195 btrfs_writepage_fixup_worker
, NULL
, NULL
);
2197 btrfs_queue_work(fs_info
->fixup_workers
, &fixup
->work
);
2201 static int insert_reserved_file_extent(struct btrfs_trans_handle
*trans
,
2202 struct inode
*inode
, u64 file_pos
,
2203 u64 disk_bytenr
, u64 disk_num_bytes
,
2204 u64 num_bytes
, u64 ram_bytes
,
2205 u8 compression
, u8 encryption
,
2206 u16 other_encoding
, int extent_type
)
2208 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2209 struct btrfs_file_extent_item
*fi
;
2210 struct btrfs_path
*path
;
2211 struct extent_buffer
*leaf
;
2212 struct btrfs_key ins
;
2214 int extent_inserted
= 0;
2217 path
= btrfs_alloc_path();
2222 * we may be replacing one extent in the tree with another.
2223 * The new extent is pinned in the extent map, and we don't want
2224 * to drop it from the cache until it is completely in the btree.
2226 * So, tell btrfs_drop_extents to leave this extent in the cache.
2227 * the caller is expected to unpin it and allow it to be merged
2230 ret
= __btrfs_drop_extents(trans
, root
, inode
, path
, file_pos
,
2231 file_pos
+ num_bytes
, NULL
, 0,
2232 1, sizeof(*fi
), &extent_inserted
);
2236 if (!extent_inserted
) {
2237 ins
.objectid
= btrfs_ino(BTRFS_I(inode
));
2238 ins
.offset
= file_pos
;
2239 ins
.type
= BTRFS_EXTENT_DATA_KEY
;
2241 path
->leave_spinning
= 1;
2242 ret
= btrfs_insert_empty_item(trans
, root
, path
, &ins
,
2247 leaf
= path
->nodes
[0];
2248 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2249 struct btrfs_file_extent_item
);
2250 btrfs_set_file_extent_generation(leaf
, fi
, trans
->transid
);
2251 btrfs_set_file_extent_type(leaf
, fi
, extent_type
);
2252 btrfs_set_file_extent_disk_bytenr(leaf
, fi
, disk_bytenr
);
2253 btrfs_set_file_extent_disk_num_bytes(leaf
, fi
, disk_num_bytes
);
2254 btrfs_set_file_extent_offset(leaf
, fi
, 0);
2255 btrfs_set_file_extent_num_bytes(leaf
, fi
, num_bytes
);
2256 btrfs_set_file_extent_ram_bytes(leaf
, fi
, ram_bytes
);
2257 btrfs_set_file_extent_compression(leaf
, fi
, compression
);
2258 btrfs_set_file_extent_encryption(leaf
, fi
, encryption
);
2259 btrfs_set_file_extent_other_encoding(leaf
, fi
, other_encoding
);
2261 btrfs_mark_buffer_dirty(leaf
);
2262 btrfs_release_path(path
);
2264 inode_add_bytes(inode
, num_bytes
);
2266 ins
.objectid
= disk_bytenr
;
2267 ins
.offset
= disk_num_bytes
;
2268 ins
.type
= BTRFS_EXTENT_ITEM_KEY
;
2271 * Release the reserved range from inode dirty range map, as it is
2272 * already moved into delayed_ref_head
2274 ret
= btrfs_qgroup_release_data(inode
, file_pos
, ram_bytes
);
2278 ret
= btrfs_alloc_reserved_file_extent(trans
, root
,
2279 btrfs_ino(BTRFS_I(inode
)),
2280 file_pos
, qg_released
, &ins
);
2282 btrfs_free_path(path
);
2287 /* snapshot-aware defrag */
2288 struct sa_defrag_extent_backref
{
2289 struct rb_node node
;
2290 struct old_sa_defrag_extent
*old
;
2299 struct old_sa_defrag_extent
{
2300 struct list_head list
;
2301 struct new_sa_defrag_extent
*new;
2310 struct new_sa_defrag_extent
{
2311 struct rb_root root
;
2312 struct list_head head
;
2313 struct btrfs_path
*path
;
2314 struct inode
*inode
;
2322 static int backref_comp(struct sa_defrag_extent_backref
*b1
,
2323 struct sa_defrag_extent_backref
*b2
)
2325 if (b1
->root_id
< b2
->root_id
)
2327 else if (b1
->root_id
> b2
->root_id
)
2330 if (b1
->inum
< b2
->inum
)
2332 else if (b1
->inum
> b2
->inum
)
2335 if (b1
->file_pos
< b2
->file_pos
)
2337 else if (b1
->file_pos
> b2
->file_pos
)
2341 * [------------------------------] ===> (a range of space)
2342 * |<--->| |<---->| =============> (fs/file tree A)
2343 * |<---------------------------->| ===> (fs/file tree B)
2345 * A range of space can refer to two file extents in one tree while
2346 * refer to only one file extent in another tree.
2348 * So we may process a disk offset more than one time(two extents in A)
2349 * and locate at the same extent(one extent in B), then insert two same
2350 * backrefs(both refer to the extent in B).
2355 static void backref_insert(struct rb_root
*root
,
2356 struct sa_defrag_extent_backref
*backref
)
2358 struct rb_node
**p
= &root
->rb_node
;
2359 struct rb_node
*parent
= NULL
;
2360 struct sa_defrag_extent_backref
*entry
;
2365 entry
= rb_entry(parent
, struct sa_defrag_extent_backref
, node
);
2367 ret
= backref_comp(backref
, entry
);
2371 p
= &(*p
)->rb_right
;
2374 rb_link_node(&backref
->node
, parent
, p
);
2375 rb_insert_color(&backref
->node
, root
);
2379 * Note the backref might has changed, and in this case we just return 0.
2381 static noinline
int record_one_backref(u64 inum
, u64 offset
, u64 root_id
,
2384 struct btrfs_file_extent_item
*extent
;
2385 struct old_sa_defrag_extent
*old
= ctx
;
2386 struct new_sa_defrag_extent
*new = old
->new;
2387 struct btrfs_path
*path
= new->path
;
2388 struct btrfs_key key
;
2389 struct btrfs_root
*root
;
2390 struct sa_defrag_extent_backref
*backref
;
2391 struct extent_buffer
*leaf
;
2392 struct inode
*inode
= new->inode
;
2393 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2399 if (BTRFS_I(inode
)->root
->root_key
.objectid
== root_id
&&
2400 inum
== btrfs_ino(BTRFS_I(inode
)))
2403 key
.objectid
= root_id
;
2404 key
.type
= BTRFS_ROOT_ITEM_KEY
;
2405 key
.offset
= (u64
)-1;
2407 root
= btrfs_read_fs_root_no_name(fs_info
, &key
);
2409 if (PTR_ERR(root
) == -ENOENT
)
2412 btrfs_debug(fs_info
, "inum=%llu, offset=%llu, root_id=%llu",
2413 inum
, offset
, root_id
);
2414 return PTR_ERR(root
);
2417 key
.objectid
= inum
;
2418 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2419 if (offset
> (u64
)-1 << 32)
2422 key
.offset
= offset
;
2424 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
2425 if (WARN_ON(ret
< 0))
2432 leaf
= path
->nodes
[0];
2433 slot
= path
->slots
[0];
2435 if (slot
>= btrfs_header_nritems(leaf
)) {
2436 ret
= btrfs_next_leaf(root
, path
);
2439 } else if (ret
> 0) {
2448 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
2450 if (key
.objectid
> inum
)
2453 if (key
.objectid
< inum
|| key
.type
!= BTRFS_EXTENT_DATA_KEY
)
2456 extent
= btrfs_item_ptr(leaf
, slot
,
2457 struct btrfs_file_extent_item
);
2459 if (btrfs_file_extent_disk_bytenr(leaf
, extent
) != old
->bytenr
)
2463 * 'offset' refers to the exact key.offset,
2464 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2465 * (key.offset - extent_offset).
2467 if (key
.offset
!= offset
)
2470 extent_offset
= btrfs_file_extent_offset(leaf
, extent
);
2471 num_bytes
= btrfs_file_extent_num_bytes(leaf
, extent
);
2473 if (extent_offset
>= old
->extent_offset
+ old
->offset
+
2474 old
->len
|| extent_offset
+ num_bytes
<=
2475 old
->extent_offset
+ old
->offset
)
2480 backref
= kmalloc(sizeof(*backref
), GFP_NOFS
);
2486 backref
->root_id
= root_id
;
2487 backref
->inum
= inum
;
2488 backref
->file_pos
= offset
;
2489 backref
->num_bytes
= num_bytes
;
2490 backref
->extent_offset
= extent_offset
;
2491 backref
->generation
= btrfs_file_extent_generation(leaf
, extent
);
2493 backref_insert(&new->root
, backref
);
2496 btrfs_release_path(path
);
2501 static noinline
bool record_extent_backrefs(struct btrfs_path
*path
,
2502 struct new_sa_defrag_extent
*new)
2504 struct btrfs_fs_info
*fs_info
= btrfs_sb(new->inode
->i_sb
);
2505 struct old_sa_defrag_extent
*old
, *tmp
;
2510 list_for_each_entry_safe(old
, tmp
, &new->head
, list
) {
2511 ret
= iterate_inodes_from_logical(old
->bytenr
+
2512 old
->extent_offset
, fs_info
,
2513 path
, record_one_backref
,
2515 if (ret
< 0 && ret
!= -ENOENT
)
2518 /* no backref to be processed for this extent */
2520 list_del(&old
->list
);
2525 if (list_empty(&new->head
))
2531 static int relink_is_mergable(struct extent_buffer
*leaf
,
2532 struct btrfs_file_extent_item
*fi
,
2533 struct new_sa_defrag_extent
*new)
2535 if (btrfs_file_extent_disk_bytenr(leaf
, fi
) != new->bytenr
)
2538 if (btrfs_file_extent_type(leaf
, fi
) != BTRFS_FILE_EXTENT_REG
)
2541 if (btrfs_file_extent_compression(leaf
, fi
) != new->compress_type
)
2544 if (btrfs_file_extent_encryption(leaf
, fi
) ||
2545 btrfs_file_extent_other_encoding(leaf
, fi
))
2552 * Note the backref might has changed, and in this case we just return 0.
2554 static noinline
int relink_extent_backref(struct btrfs_path
*path
,
2555 struct sa_defrag_extent_backref
*prev
,
2556 struct sa_defrag_extent_backref
*backref
)
2558 struct btrfs_file_extent_item
*extent
;
2559 struct btrfs_file_extent_item
*item
;
2560 struct btrfs_ordered_extent
*ordered
;
2561 struct btrfs_trans_handle
*trans
;
2562 struct btrfs_ref ref
= { 0 };
2563 struct btrfs_root
*root
;
2564 struct btrfs_key key
;
2565 struct extent_buffer
*leaf
;
2566 struct old_sa_defrag_extent
*old
= backref
->old
;
2567 struct new_sa_defrag_extent
*new = old
->new;
2568 struct btrfs_fs_info
*fs_info
= btrfs_sb(new->inode
->i_sb
);
2569 struct inode
*inode
;
2570 struct extent_state
*cached
= NULL
;
2579 if (prev
&& prev
->root_id
== backref
->root_id
&&
2580 prev
->inum
== backref
->inum
&&
2581 prev
->file_pos
+ prev
->num_bytes
== backref
->file_pos
)
2584 /* step 1: get root */
2585 key
.objectid
= backref
->root_id
;
2586 key
.type
= BTRFS_ROOT_ITEM_KEY
;
2587 key
.offset
= (u64
)-1;
2589 index
= srcu_read_lock(&fs_info
->subvol_srcu
);
2591 root
= btrfs_read_fs_root_no_name(fs_info
, &key
);
2593 srcu_read_unlock(&fs_info
->subvol_srcu
, index
);
2594 if (PTR_ERR(root
) == -ENOENT
)
2596 return PTR_ERR(root
);
2599 if (btrfs_root_readonly(root
)) {
2600 srcu_read_unlock(&fs_info
->subvol_srcu
, index
);
2604 /* step 2: get inode */
2605 key
.objectid
= backref
->inum
;
2606 key
.type
= BTRFS_INODE_ITEM_KEY
;
2609 inode
= btrfs_iget(fs_info
->sb
, &key
, root
, NULL
);
2610 if (IS_ERR(inode
)) {
2611 srcu_read_unlock(&fs_info
->subvol_srcu
, index
);
2615 srcu_read_unlock(&fs_info
->subvol_srcu
, index
);
2617 /* step 3: relink backref */
2618 lock_start
= backref
->file_pos
;
2619 lock_end
= backref
->file_pos
+ backref
->num_bytes
- 1;
2620 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, lock_start
, lock_end
,
2623 ordered
= btrfs_lookup_first_ordered_extent(inode
, lock_end
);
2625 btrfs_put_ordered_extent(ordered
);
2629 trans
= btrfs_join_transaction(root
);
2630 if (IS_ERR(trans
)) {
2631 ret
= PTR_ERR(trans
);
2635 key
.objectid
= backref
->inum
;
2636 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2637 key
.offset
= backref
->file_pos
;
2639 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
2642 } else if (ret
> 0) {
2647 extent
= btrfs_item_ptr(path
->nodes
[0], path
->slots
[0],
2648 struct btrfs_file_extent_item
);
2650 if (btrfs_file_extent_generation(path
->nodes
[0], extent
) !=
2651 backref
->generation
)
2654 btrfs_release_path(path
);
2656 start
= backref
->file_pos
;
2657 if (backref
->extent_offset
< old
->extent_offset
+ old
->offset
)
2658 start
+= old
->extent_offset
+ old
->offset
-
2659 backref
->extent_offset
;
2661 len
= min(backref
->extent_offset
+ backref
->num_bytes
,
2662 old
->extent_offset
+ old
->offset
+ old
->len
);
2663 len
-= max(backref
->extent_offset
, old
->extent_offset
+ old
->offset
);
2665 ret
= btrfs_drop_extents(trans
, root
, inode
, start
,
2670 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
2671 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2674 path
->leave_spinning
= 1;
2676 struct btrfs_file_extent_item
*fi
;
2678 struct btrfs_key found_key
;
2680 ret
= btrfs_search_slot(trans
, root
, &key
, path
, 0, 1);
2685 leaf
= path
->nodes
[0];
2686 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
2688 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
2689 struct btrfs_file_extent_item
);
2690 extent_len
= btrfs_file_extent_num_bytes(leaf
, fi
);
2692 if (extent_len
+ found_key
.offset
== start
&&
2693 relink_is_mergable(leaf
, fi
, new)) {
2694 btrfs_set_file_extent_num_bytes(leaf
, fi
,
2696 btrfs_mark_buffer_dirty(leaf
);
2697 inode_add_bytes(inode
, len
);
2703 btrfs_release_path(path
);
2708 ret
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
2711 btrfs_abort_transaction(trans
, ret
);
2715 leaf
= path
->nodes
[0];
2716 item
= btrfs_item_ptr(leaf
, path
->slots
[0],
2717 struct btrfs_file_extent_item
);
2718 btrfs_set_file_extent_disk_bytenr(leaf
, item
, new->bytenr
);
2719 btrfs_set_file_extent_disk_num_bytes(leaf
, item
, new->disk_len
);
2720 btrfs_set_file_extent_offset(leaf
, item
, start
- new->file_pos
);
2721 btrfs_set_file_extent_num_bytes(leaf
, item
, len
);
2722 btrfs_set_file_extent_ram_bytes(leaf
, item
, new->len
);
2723 btrfs_set_file_extent_generation(leaf
, item
, trans
->transid
);
2724 btrfs_set_file_extent_type(leaf
, item
, BTRFS_FILE_EXTENT_REG
);
2725 btrfs_set_file_extent_compression(leaf
, item
, new->compress_type
);
2726 btrfs_set_file_extent_encryption(leaf
, item
, 0);
2727 btrfs_set_file_extent_other_encoding(leaf
, item
, 0);
2729 btrfs_mark_buffer_dirty(leaf
);
2730 inode_add_bytes(inode
, len
);
2731 btrfs_release_path(path
);
2733 btrfs_init_generic_ref(&ref
, BTRFS_ADD_DELAYED_REF
, new->bytenr
,
2735 btrfs_init_data_ref(&ref
, backref
->root_id
, backref
->inum
,
2736 new->file_pos
); /* start - extent_offset */
2737 ret
= btrfs_inc_extent_ref(trans
, &ref
);
2739 btrfs_abort_transaction(trans
, ret
);
2745 btrfs_release_path(path
);
2746 path
->leave_spinning
= 0;
2747 btrfs_end_transaction(trans
);
2749 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lock_start
, lock_end
,
2755 static void free_sa_defrag_extent(struct new_sa_defrag_extent
*new)
2757 struct old_sa_defrag_extent
*old
, *tmp
;
2762 list_for_each_entry_safe(old
, tmp
, &new->head
, list
) {
2768 static void relink_file_extents(struct new_sa_defrag_extent
*new)
2770 struct btrfs_fs_info
*fs_info
= btrfs_sb(new->inode
->i_sb
);
2771 struct btrfs_path
*path
;
2772 struct sa_defrag_extent_backref
*backref
;
2773 struct sa_defrag_extent_backref
*prev
= NULL
;
2774 struct rb_node
*node
;
2777 path
= btrfs_alloc_path();
2781 if (!record_extent_backrefs(path
, new)) {
2782 btrfs_free_path(path
);
2785 btrfs_release_path(path
);
2788 node
= rb_first(&new->root
);
2791 rb_erase(node
, &new->root
);
2793 backref
= rb_entry(node
, struct sa_defrag_extent_backref
, node
);
2795 ret
= relink_extent_backref(path
, prev
, backref
);
2808 btrfs_free_path(path
);
2810 free_sa_defrag_extent(new);
2812 atomic_dec(&fs_info
->defrag_running
);
2813 wake_up(&fs_info
->transaction_wait
);
2816 static struct new_sa_defrag_extent
*
2817 record_old_file_extents(struct inode
*inode
,
2818 struct btrfs_ordered_extent
*ordered
)
2820 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2821 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2822 struct btrfs_path
*path
;
2823 struct btrfs_key key
;
2824 struct old_sa_defrag_extent
*old
;
2825 struct new_sa_defrag_extent
*new;
2828 new = kmalloc(sizeof(*new), GFP_NOFS
);
2833 new->file_pos
= ordered
->file_offset
;
2834 new->len
= ordered
->len
;
2835 new->bytenr
= ordered
->start
;
2836 new->disk_len
= ordered
->disk_len
;
2837 new->compress_type
= ordered
->compress_type
;
2838 new->root
= RB_ROOT
;
2839 INIT_LIST_HEAD(&new->head
);
2841 path
= btrfs_alloc_path();
2845 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
2846 key
.type
= BTRFS_EXTENT_DATA_KEY
;
2847 key
.offset
= new->file_pos
;
2849 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
2852 if (ret
> 0 && path
->slots
[0] > 0)
2855 /* find out all the old extents for the file range */
2857 struct btrfs_file_extent_item
*extent
;
2858 struct extent_buffer
*l
;
2867 slot
= path
->slots
[0];
2869 if (slot
>= btrfs_header_nritems(l
)) {
2870 ret
= btrfs_next_leaf(root
, path
);
2878 btrfs_item_key_to_cpu(l
, &key
, slot
);
2880 if (key
.objectid
!= btrfs_ino(BTRFS_I(inode
)))
2882 if (key
.type
!= BTRFS_EXTENT_DATA_KEY
)
2884 if (key
.offset
>= new->file_pos
+ new->len
)
2887 extent
= btrfs_item_ptr(l
, slot
, struct btrfs_file_extent_item
);
2889 num_bytes
= btrfs_file_extent_num_bytes(l
, extent
);
2890 if (key
.offset
+ num_bytes
< new->file_pos
)
2893 disk_bytenr
= btrfs_file_extent_disk_bytenr(l
, extent
);
2897 extent_offset
= btrfs_file_extent_offset(l
, extent
);
2899 old
= kmalloc(sizeof(*old
), GFP_NOFS
);
2903 offset
= max(new->file_pos
, key
.offset
);
2904 end
= min(new->file_pos
+ new->len
, key
.offset
+ num_bytes
);
2906 old
->bytenr
= disk_bytenr
;
2907 old
->extent_offset
= extent_offset
;
2908 old
->offset
= offset
- key
.offset
;
2909 old
->len
= end
- offset
;
2912 list_add_tail(&old
->list
, &new->head
);
2918 btrfs_free_path(path
);
2919 atomic_inc(&fs_info
->defrag_running
);
2924 btrfs_free_path(path
);
2926 free_sa_defrag_extent(new);
2930 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info
*fs_info
,
2933 struct btrfs_block_group_cache
*cache
;
2935 cache
= btrfs_lookup_block_group(fs_info
, start
);
2938 spin_lock(&cache
->lock
);
2939 cache
->delalloc_bytes
-= len
;
2940 spin_unlock(&cache
->lock
);
2942 btrfs_put_block_group(cache
);
2945 /* as ordered data IO finishes, this gets called so we can finish
2946 * an ordered extent if the range of bytes in the file it covers are
2949 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent
*ordered_extent
)
2951 struct inode
*inode
= ordered_extent
->inode
;
2952 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
2953 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
2954 struct btrfs_trans_handle
*trans
= NULL
;
2955 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
2956 struct extent_state
*cached_state
= NULL
;
2957 struct new_sa_defrag_extent
*new = NULL
;
2958 int compress_type
= 0;
2960 u64 logical_len
= ordered_extent
->len
;
2962 bool truncated
= false;
2963 bool range_locked
= false;
2964 bool clear_new_delalloc_bytes
= false;
2965 bool clear_reserved_extent
= true;
2967 if (!test_bit(BTRFS_ORDERED_NOCOW
, &ordered_extent
->flags
) &&
2968 !test_bit(BTRFS_ORDERED_PREALLOC
, &ordered_extent
->flags
) &&
2969 !test_bit(BTRFS_ORDERED_DIRECT
, &ordered_extent
->flags
))
2970 clear_new_delalloc_bytes
= true;
2972 nolock
= btrfs_is_free_space_inode(BTRFS_I(inode
));
2974 if (test_bit(BTRFS_ORDERED_IOERR
, &ordered_extent
->flags
)) {
2979 btrfs_free_io_failure_record(BTRFS_I(inode
),
2980 ordered_extent
->file_offset
,
2981 ordered_extent
->file_offset
+
2982 ordered_extent
->len
- 1);
2984 if (test_bit(BTRFS_ORDERED_TRUNCATED
, &ordered_extent
->flags
)) {
2986 logical_len
= ordered_extent
->truncated_len
;
2987 /* Truncated the entire extent, don't bother adding */
2992 if (test_bit(BTRFS_ORDERED_NOCOW
, &ordered_extent
->flags
)) {
2993 BUG_ON(!list_empty(&ordered_extent
->list
)); /* Logic error */
2996 * For mwrite(mmap + memset to write) case, we still reserve
2997 * space for NOCOW range.
2998 * As NOCOW won't cause a new delayed ref, just free the space
3000 btrfs_qgroup_free_data(inode
, NULL
, ordered_extent
->file_offset
,
3001 ordered_extent
->len
);
3002 btrfs_ordered_update_i_size(inode
, 0, ordered_extent
);
3004 trans
= btrfs_join_transaction_nolock(root
);
3006 trans
= btrfs_join_transaction(root
);
3007 if (IS_ERR(trans
)) {
3008 ret
= PTR_ERR(trans
);
3012 trans
->block_rsv
= &BTRFS_I(inode
)->block_rsv
;
3013 ret
= btrfs_update_inode_fallback(trans
, root
, inode
);
3014 if (ret
) /* -ENOMEM or corruption */
3015 btrfs_abort_transaction(trans
, ret
);
3019 range_locked
= true;
3020 lock_extent_bits(io_tree
, ordered_extent
->file_offset
,
3021 ordered_extent
->file_offset
+ ordered_extent
->len
- 1,
3024 ret
= test_range_bit(io_tree
, ordered_extent
->file_offset
,
3025 ordered_extent
->file_offset
+ ordered_extent
->len
- 1,
3026 EXTENT_DEFRAG
, 0, cached_state
);
3028 u64 last_snapshot
= btrfs_root_last_snapshot(&root
->root_item
);
3029 if (0 && last_snapshot
>= BTRFS_I(inode
)->generation
)
3030 /* the inode is shared */
3031 new = record_old_file_extents(inode
, ordered_extent
);
3033 clear_extent_bit(io_tree
, ordered_extent
->file_offset
,
3034 ordered_extent
->file_offset
+ ordered_extent
->len
- 1,
3035 EXTENT_DEFRAG
, 0, 0, &cached_state
);
3039 trans
= btrfs_join_transaction_nolock(root
);
3041 trans
= btrfs_join_transaction(root
);
3042 if (IS_ERR(trans
)) {
3043 ret
= PTR_ERR(trans
);
3048 trans
->block_rsv
= &BTRFS_I(inode
)->block_rsv
;
3050 if (test_bit(BTRFS_ORDERED_COMPRESSED
, &ordered_extent
->flags
))
3051 compress_type
= ordered_extent
->compress_type
;
3052 if (test_bit(BTRFS_ORDERED_PREALLOC
, &ordered_extent
->flags
)) {
3053 BUG_ON(compress_type
);
3054 btrfs_qgroup_free_data(inode
, NULL
, ordered_extent
->file_offset
,
3055 ordered_extent
->len
);
3056 ret
= btrfs_mark_extent_written(trans
, BTRFS_I(inode
),
3057 ordered_extent
->file_offset
,
3058 ordered_extent
->file_offset
+
3061 BUG_ON(root
== fs_info
->tree_root
);
3062 ret
= insert_reserved_file_extent(trans
, inode
,
3063 ordered_extent
->file_offset
,
3064 ordered_extent
->start
,
3065 ordered_extent
->disk_len
,
3066 logical_len
, logical_len
,
3067 compress_type
, 0, 0,
3068 BTRFS_FILE_EXTENT_REG
);
3070 clear_reserved_extent
= false;
3071 btrfs_release_delalloc_bytes(fs_info
,
3072 ordered_extent
->start
,
3073 ordered_extent
->disk_len
);
3076 unpin_extent_cache(&BTRFS_I(inode
)->extent_tree
,
3077 ordered_extent
->file_offset
, ordered_extent
->len
,
3080 btrfs_abort_transaction(trans
, ret
);
3084 ret
= add_pending_csums(trans
, inode
, &ordered_extent
->list
);
3086 btrfs_abort_transaction(trans
, ret
);
3090 btrfs_ordered_update_i_size(inode
, 0, ordered_extent
);
3091 ret
= btrfs_update_inode_fallback(trans
, root
, inode
);
3092 if (ret
) { /* -ENOMEM or corruption */
3093 btrfs_abort_transaction(trans
, ret
);
3098 if (range_locked
|| clear_new_delalloc_bytes
) {
3099 unsigned int clear_bits
= 0;
3102 clear_bits
|= EXTENT_LOCKED
;
3103 if (clear_new_delalloc_bytes
)
3104 clear_bits
|= EXTENT_DELALLOC_NEW
;
3105 clear_extent_bit(&BTRFS_I(inode
)->io_tree
,
3106 ordered_extent
->file_offset
,
3107 ordered_extent
->file_offset
+
3108 ordered_extent
->len
- 1,
3110 (clear_bits
& EXTENT_LOCKED
) ? 1 : 0,
3115 btrfs_end_transaction(trans
);
3117 if (ret
|| truncated
) {
3121 start
= ordered_extent
->file_offset
+ logical_len
;
3123 start
= ordered_extent
->file_offset
;
3124 end
= ordered_extent
->file_offset
+ ordered_extent
->len
- 1;
3125 clear_extent_uptodate(io_tree
, start
, end
, NULL
);
3127 /* Drop the cache for the part of the extent we didn't write. */
3128 btrfs_drop_extent_cache(BTRFS_I(inode
), start
, end
, 0);
3131 * If the ordered extent had an IOERR or something else went
3132 * wrong we need to return the space for this ordered extent
3133 * back to the allocator. We only free the extent in the
3134 * truncated case if we didn't write out the extent at all.
3136 * If we made it past insert_reserved_file_extent before we
3137 * errored out then we don't need to do this as the accounting
3138 * has already been done.
3140 if ((ret
|| !logical_len
) &&
3141 clear_reserved_extent
&&
3142 !test_bit(BTRFS_ORDERED_NOCOW
, &ordered_extent
->flags
) &&
3143 !test_bit(BTRFS_ORDERED_PREALLOC
, &ordered_extent
->flags
))
3144 btrfs_free_reserved_extent(fs_info
,
3145 ordered_extent
->start
,
3146 ordered_extent
->disk_len
, 1);
3151 * This needs to be done to make sure anybody waiting knows we are done
3152 * updating everything for this ordered extent.
3154 btrfs_remove_ordered_extent(inode
, ordered_extent
);
3156 /* for snapshot-aware defrag */
3159 free_sa_defrag_extent(new);
3160 atomic_dec(&fs_info
->defrag_running
);
3162 relink_file_extents(new);
3167 btrfs_put_ordered_extent(ordered_extent
);
3168 /* once for the tree */
3169 btrfs_put_ordered_extent(ordered_extent
);
3174 static void finish_ordered_fn(struct btrfs_work
*work
)
3176 struct btrfs_ordered_extent
*ordered_extent
;
3177 ordered_extent
= container_of(work
, struct btrfs_ordered_extent
, work
);
3178 btrfs_finish_ordered_io(ordered_extent
);
3181 void btrfs_writepage_endio_finish_ordered(struct page
*page
, u64 start
,
3182 u64 end
, int uptodate
)
3184 struct inode
*inode
= page
->mapping
->host
;
3185 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3186 struct btrfs_ordered_extent
*ordered_extent
= NULL
;
3187 struct btrfs_workqueue
*wq
;
3188 btrfs_work_func_t func
;
3190 trace_btrfs_writepage_end_io_hook(page
, start
, end
, uptodate
);
3192 ClearPagePrivate2(page
);
3193 if (!btrfs_dec_test_ordered_pending(inode
, &ordered_extent
, start
,
3194 end
- start
+ 1, uptodate
))
3197 if (btrfs_is_free_space_inode(BTRFS_I(inode
))) {
3198 wq
= fs_info
->endio_freespace_worker
;
3199 func
= btrfs_freespace_write_helper
;
3201 wq
= fs_info
->endio_write_workers
;
3202 func
= btrfs_endio_write_helper
;
3205 btrfs_init_work(&ordered_extent
->work
, func
, finish_ordered_fn
, NULL
,
3207 btrfs_queue_work(wq
, &ordered_extent
->work
);
3210 static int __readpage_endio_check(struct inode
*inode
,
3211 struct btrfs_io_bio
*io_bio
,
3212 int icsum
, struct page
*page
,
3213 int pgoff
, u64 start
, size_t len
)
3215 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3216 SHASH_DESC_ON_STACK(shash
, fs_info
->csum_shash
);
3218 u16 csum_size
= btrfs_super_csum_size(fs_info
->super_copy
);
3220 u8 csum
[BTRFS_CSUM_SIZE
];
3222 csum_expected
= ((u8
*)io_bio
->csum
) + icsum
* csum_size
;
3224 kaddr
= kmap_atomic(page
);
3225 shash
->tfm
= fs_info
->csum_shash
;
3227 crypto_shash_init(shash
);
3228 crypto_shash_update(shash
, kaddr
+ pgoff
, len
);
3229 crypto_shash_final(shash
, csum
);
3231 if (memcmp(csum
, csum_expected
, csum_size
))
3234 kunmap_atomic(kaddr
);
3237 btrfs_print_data_csum_error(BTRFS_I(inode
), start
, csum
, csum_expected
,
3238 io_bio
->mirror_num
);
3239 memset(kaddr
+ pgoff
, 1, len
);
3240 flush_dcache_page(page
);
3241 kunmap_atomic(kaddr
);
3246 * when reads are done, we need to check csums to verify the data is correct
3247 * if there's a match, we allow the bio to finish. If not, the code in
3248 * extent_io.c will try to find good copies for us.
3250 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio
*io_bio
,
3251 u64 phy_offset
, struct page
*page
,
3252 u64 start
, u64 end
, int mirror
)
3254 size_t offset
= start
- page_offset(page
);
3255 struct inode
*inode
= page
->mapping
->host
;
3256 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
3257 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
3259 if (PageChecked(page
)) {
3260 ClearPageChecked(page
);
3264 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
)
3267 if (root
->root_key
.objectid
== BTRFS_DATA_RELOC_TREE_OBJECTID
&&
3268 test_range_bit(io_tree
, start
, end
, EXTENT_NODATASUM
, 1, NULL
)) {
3269 clear_extent_bits(io_tree
, start
, end
, EXTENT_NODATASUM
);
3273 phy_offset
>>= inode
->i_sb
->s_blocksize_bits
;
3274 return __readpage_endio_check(inode
, io_bio
, phy_offset
, page
, offset
,
3275 start
, (size_t)(end
- start
+ 1));
3279 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3281 * @inode: The inode we want to perform iput on
3283 * This function uses the generic vfs_inode::i_count to track whether we should
3284 * just decrement it (in case it's > 1) or if this is the last iput then link
3285 * the inode to the delayed iput machinery. Delayed iputs are processed at
3286 * transaction commit time/superblock commit/cleaner kthread.
3288 void btrfs_add_delayed_iput(struct inode
*inode
)
3290 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3291 struct btrfs_inode
*binode
= BTRFS_I(inode
);
3293 if (atomic_add_unless(&inode
->i_count
, -1, 1))
3296 atomic_inc(&fs_info
->nr_delayed_iputs
);
3297 spin_lock(&fs_info
->delayed_iput_lock
);
3298 ASSERT(list_empty(&binode
->delayed_iput
));
3299 list_add_tail(&binode
->delayed_iput
, &fs_info
->delayed_iputs
);
3300 spin_unlock(&fs_info
->delayed_iput_lock
);
3301 if (!test_bit(BTRFS_FS_CLEANER_RUNNING
, &fs_info
->flags
))
3302 wake_up_process(fs_info
->cleaner_kthread
);
3305 static void run_delayed_iput_locked(struct btrfs_fs_info
*fs_info
,
3306 struct btrfs_inode
*inode
)
3308 list_del_init(&inode
->delayed_iput
);
3309 spin_unlock(&fs_info
->delayed_iput_lock
);
3310 iput(&inode
->vfs_inode
);
3311 if (atomic_dec_and_test(&fs_info
->nr_delayed_iputs
))
3312 wake_up(&fs_info
->delayed_iputs_wait
);
3313 spin_lock(&fs_info
->delayed_iput_lock
);
3316 static void btrfs_run_delayed_iput(struct btrfs_fs_info
*fs_info
,
3317 struct btrfs_inode
*inode
)
3319 if (!list_empty(&inode
->delayed_iput
)) {
3320 spin_lock(&fs_info
->delayed_iput_lock
);
3321 if (!list_empty(&inode
->delayed_iput
))
3322 run_delayed_iput_locked(fs_info
, inode
);
3323 spin_unlock(&fs_info
->delayed_iput_lock
);
3327 void btrfs_run_delayed_iputs(struct btrfs_fs_info
*fs_info
)
3330 spin_lock(&fs_info
->delayed_iput_lock
);
3331 while (!list_empty(&fs_info
->delayed_iputs
)) {
3332 struct btrfs_inode
*inode
;
3334 inode
= list_first_entry(&fs_info
->delayed_iputs
,
3335 struct btrfs_inode
, delayed_iput
);
3336 run_delayed_iput_locked(fs_info
, inode
);
3338 spin_unlock(&fs_info
->delayed_iput_lock
);
3342 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
3343 * @fs_info - the fs_info for this fs
3344 * @return - EINTR if we were killed, 0 if nothing's pending
3346 * This will wait on any delayed iputs that are currently running with KILLABLE
3347 * set. Once they are all done running we will return, unless we are killed in
3348 * which case we return EINTR. This helps in user operations like fallocate etc
3349 * that might get blocked on the iputs.
3351 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info
*fs_info
)
3353 int ret
= wait_event_killable(fs_info
->delayed_iputs_wait
,
3354 atomic_read(&fs_info
->nr_delayed_iputs
) == 0);
3361 * This creates an orphan entry for the given inode in case something goes wrong
3362 * in the middle of an unlink.
3364 int btrfs_orphan_add(struct btrfs_trans_handle
*trans
,
3365 struct btrfs_inode
*inode
)
3369 ret
= btrfs_insert_orphan_item(trans
, inode
->root
, btrfs_ino(inode
));
3370 if (ret
&& ret
!= -EEXIST
) {
3371 btrfs_abort_transaction(trans
, ret
);
3379 * We have done the delete so we can go ahead and remove the orphan item for
3380 * this particular inode.
3382 static int btrfs_orphan_del(struct btrfs_trans_handle
*trans
,
3383 struct btrfs_inode
*inode
)
3385 return btrfs_del_orphan_item(trans
, inode
->root
, btrfs_ino(inode
));
3389 * this cleans up any orphans that may be left on the list from the last use
3392 int btrfs_orphan_cleanup(struct btrfs_root
*root
)
3394 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
3395 struct btrfs_path
*path
;
3396 struct extent_buffer
*leaf
;
3397 struct btrfs_key key
, found_key
;
3398 struct btrfs_trans_handle
*trans
;
3399 struct inode
*inode
;
3400 u64 last_objectid
= 0;
3401 int ret
= 0, nr_unlink
= 0;
3403 if (cmpxchg(&root
->orphan_cleanup_state
, 0, ORPHAN_CLEANUP_STARTED
))
3406 path
= btrfs_alloc_path();
3411 path
->reada
= READA_BACK
;
3413 key
.objectid
= BTRFS_ORPHAN_OBJECTID
;
3414 key
.type
= BTRFS_ORPHAN_ITEM_KEY
;
3415 key
.offset
= (u64
)-1;
3418 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
3423 * if ret == 0 means we found what we were searching for, which
3424 * is weird, but possible, so only screw with path if we didn't
3425 * find the key and see if we have stuff that matches
3429 if (path
->slots
[0] == 0)
3434 /* pull out the item */
3435 leaf
= path
->nodes
[0];
3436 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
3438 /* make sure the item matches what we want */
3439 if (found_key
.objectid
!= BTRFS_ORPHAN_OBJECTID
)
3441 if (found_key
.type
!= BTRFS_ORPHAN_ITEM_KEY
)
3444 /* release the path since we're done with it */
3445 btrfs_release_path(path
);
3448 * this is where we are basically btrfs_lookup, without the
3449 * crossing root thing. we store the inode number in the
3450 * offset of the orphan item.
3453 if (found_key
.offset
== last_objectid
) {
3455 "Error removing orphan entry, stopping orphan cleanup");
3460 last_objectid
= found_key
.offset
;
3462 found_key
.objectid
= found_key
.offset
;
3463 found_key
.type
= BTRFS_INODE_ITEM_KEY
;
3464 found_key
.offset
= 0;
3465 inode
= btrfs_iget(fs_info
->sb
, &found_key
, root
, NULL
);
3466 ret
= PTR_ERR_OR_ZERO(inode
);
3467 if (ret
&& ret
!= -ENOENT
)
3470 if (ret
== -ENOENT
&& root
== fs_info
->tree_root
) {
3471 struct btrfs_root
*dead_root
;
3472 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
3473 int is_dead_root
= 0;
3476 * this is an orphan in the tree root. Currently these
3477 * could come from 2 sources:
3478 * a) a snapshot deletion in progress
3479 * b) a free space cache inode
3480 * We need to distinguish those two, as the snapshot
3481 * orphan must not get deleted.
3482 * find_dead_roots already ran before us, so if this
3483 * is a snapshot deletion, we should find the root
3484 * in the dead_roots list
3486 spin_lock(&fs_info
->trans_lock
);
3487 list_for_each_entry(dead_root
, &fs_info
->dead_roots
,
3489 if (dead_root
->root_key
.objectid
==
3490 found_key
.objectid
) {
3495 spin_unlock(&fs_info
->trans_lock
);
3497 /* prevent this orphan from being found again */
3498 key
.offset
= found_key
.objectid
- 1;
3505 * If we have an inode with links, there are a couple of
3506 * possibilities. Old kernels (before v3.12) used to create an
3507 * orphan item for truncate indicating that there were possibly
3508 * extent items past i_size that needed to be deleted. In v3.12,
3509 * truncate was changed to update i_size in sync with the extent
3510 * items, but the (useless) orphan item was still created. Since
3511 * v4.18, we don't create the orphan item for truncate at all.
3513 * So, this item could mean that we need to do a truncate, but
3514 * only if this filesystem was last used on a pre-v3.12 kernel
3515 * and was not cleanly unmounted. The odds of that are quite
3516 * slim, and it's a pain to do the truncate now, so just delete
3519 * It's also possible that this orphan item was supposed to be
3520 * deleted but wasn't. The inode number may have been reused,
3521 * but either way, we can delete the orphan item.
3523 if (ret
== -ENOENT
|| inode
->i_nlink
) {
3526 trans
= btrfs_start_transaction(root
, 1);
3527 if (IS_ERR(trans
)) {
3528 ret
= PTR_ERR(trans
);
3531 btrfs_debug(fs_info
, "auto deleting %Lu",
3532 found_key
.objectid
);
3533 ret
= btrfs_del_orphan_item(trans
, root
,
3534 found_key
.objectid
);
3535 btrfs_end_transaction(trans
);
3543 /* this will do delete_inode and everything for us */
3546 /* release the path since we're done with it */
3547 btrfs_release_path(path
);
3549 root
->orphan_cleanup_state
= ORPHAN_CLEANUP_DONE
;
3551 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED
, &root
->state
)) {
3552 trans
= btrfs_join_transaction(root
);
3554 btrfs_end_transaction(trans
);
3558 btrfs_debug(fs_info
, "unlinked %d orphans", nr_unlink
);
3562 btrfs_err(fs_info
, "could not do orphan cleanup %d", ret
);
3563 btrfs_free_path(path
);
3568 * very simple check to peek ahead in the leaf looking for xattrs. If we
3569 * don't find any xattrs, we know there can't be any acls.
3571 * slot is the slot the inode is in, objectid is the objectid of the inode
3573 static noinline
int acls_after_inode_item(struct extent_buffer
*leaf
,
3574 int slot
, u64 objectid
,
3575 int *first_xattr_slot
)
3577 u32 nritems
= btrfs_header_nritems(leaf
);
3578 struct btrfs_key found_key
;
3579 static u64 xattr_access
= 0;
3580 static u64 xattr_default
= 0;
3583 if (!xattr_access
) {
3584 xattr_access
= btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS
,
3585 strlen(XATTR_NAME_POSIX_ACL_ACCESS
));
3586 xattr_default
= btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT
,
3587 strlen(XATTR_NAME_POSIX_ACL_DEFAULT
));
3591 *first_xattr_slot
= -1;
3592 while (slot
< nritems
) {
3593 btrfs_item_key_to_cpu(leaf
, &found_key
, slot
);
3595 /* we found a different objectid, there must not be acls */
3596 if (found_key
.objectid
!= objectid
)
3599 /* we found an xattr, assume we've got an acl */
3600 if (found_key
.type
== BTRFS_XATTR_ITEM_KEY
) {
3601 if (*first_xattr_slot
== -1)
3602 *first_xattr_slot
= slot
;
3603 if (found_key
.offset
== xattr_access
||
3604 found_key
.offset
== xattr_default
)
3609 * we found a key greater than an xattr key, there can't
3610 * be any acls later on
3612 if (found_key
.type
> BTRFS_XATTR_ITEM_KEY
)
3619 * it goes inode, inode backrefs, xattrs, extents,
3620 * so if there are a ton of hard links to an inode there can
3621 * be a lot of backrefs. Don't waste time searching too hard,
3622 * this is just an optimization
3627 /* we hit the end of the leaf before we found an xattr or
3628 * something larger than an xattr. We have to assume the inode
3631 if (*first_xattr_slot
== -1)
3632 *first_xattr_slot
= slot
;
3637 * read an inode from the btree into the in-memory inode
3639 static int btrfs_read_locked_inode(struct inode
*inode
,
3640 struct btrfs_path
*in_path
)
3642 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
3643 struct btrfs_path
*path
= in_path
;
3644 struct extent_buffer
*leaf
;
3645 struct btrfs_inode_item
*inode_item
;
3646 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
3647 struct btrfs_key location
;
3652 bool filled
= false;
3653 int first_xattr_slot
;
3655 ret
= btrfs_fill_inode(inode
, &rdev
);
3660 path
= btrfs_alloc_path();
3665 memcpy(&location
, &BTRFS_I(inode
)->location
, sizeof(location
));
3667 ret
= btrfs_lookup_inode(NULL
, root
, path
, &location
, 0);
3669 if (path
!= in_path
)
3670 btrfs_free_path(path
);
3674 leaf
= path
->nodes
[0];
3679 inode_item
= btrfs_item_ptr(leaf
, path
->slots
[0],
3680 struct btrfs_inode_item
);
3681 inode
->i_mode
= btrfs_inode_mode(leaf
, inode_item
);
3682 set_nlink(inode
, btrfs_inode_nlink(leaf
, inode_item
));
3683 i_uid_write(inode
, btrfs_inode_uid(leaf
, inode_item
));
3684 i_gid_write(inode
, btrfs_inode_gid(leaf
, inode_item
));
3685 btrfs_i_size_write(BTRFS_I(inode
), btrfs_inode_size(leaf
, inode_item
));
3687 inode
->i_atime
.tv_sec
= btrfs_timespec_sec(leaf
, &inode_item
->atime
);
3688 inode
->i_atime
.tv_nsec
= btrfs_timespec_nsec(leaf
, &inode_item
->atime
);
3690 inode
->i_mtime
.tv_sec
= btrfs_timespec_sec(leaf
, &inode_item
->mtime
);
3691 inode
->i_mtime
.tv_nsec
= btrfs_timespec_nsec(leaf
, &inode_item
->mtime
);
3693 inode
->i_ctime
.tv_sec
= btrfs_timespec_sec(leaf
, &inode_item
->ctime
);
3694 inode
->i_ctime
.tv_nsec
= btrfs_timespec_nsec(leaf
, &inode_item
->ctime
);
3696 BTRFS_I(inode
)->i_otime
.tv_sec
=
3697 btrfs_timespec_sec(leaf
, &inode_item
->otime
);
3698 BTRFS_I(inode
)->i_otime
.tv_nsec
=
3699 btrfs_timespec_nsec(leaf
, &inode_item
->otime
);
3701 inode_set_bytes(inode
, btrfs_inode_nbytes(leaf
, inode_item
));
3702 BTRFS_I(inode
)->generation
= btrfs_inode_generation(leaf
, inode_item
);
3703 BTRFS_I(inode
)->last_trans
= btrfs_inode_transid(leaf
, inode_item
);
3705 inode_set_iversion_queried(inode
,
3706 btrfs_inode_sequence(leaf
, inode_item
));
3707 inode
->i_generation
= BTRFS_I(inode
)->generation
;
3709 rdev
= btrfs_inode_rdev(leaf
, inode_item
);
3711 BTRFS_I(inode
)->index_cnt
= (u64
)-1;
3712 BTRFS_I(inode
)->flags
= btrfs_inode_flags(leaf
, inode_item
);
3716 * If we were modified in the current generation and evicted from memory
3717 * and then re-read we need to do a full sync since we don't have any
3718 * idea about which extents were modified before we were evicted from
3721 * This is required for both inode re-read from disk and delayed inode
3722 * in delayed_nodes_tree.
3724 if (BTRFS_I(inode
)->last_trans
== fs_info
->generation
)
3725 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
3726 &BTRFS_I(inode
)->runtime_flags
);
3729 * We don't persist the id of the transaction where an unlink operation
3730 * against the inode was last made. So here we assume the inode might
3731 * have been evicted, and therefore the exact value of last_unlink_trans
3732 * lost, and set it to last_trans to avoid metadata inconsistencies
3733 * between the inode and its parent if the inode is fsync'ed and the log
3734 * replayed. For example, in the scenario:
3737 * ln mydir/foo mydir/bar
3740 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3741 * xfs_io -c fsync mydir/foo
3743 * mount fs, triggers fsync log replay
3745 * We must make sure that when we fsync our inode foo we also log its
3746 * parent inode, otherwise after log replay the parent still has the
3747 * dentry with the "bar" name but our inode foo has a link count of 1
3748 * and doesn't have an inode ref with the name "bar" anymore.
3750 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3751 * but it guarantees correctness at the expense of occasional full
3752 * transaction commits on fsync if our inode is a directory, or if our
3753 * inode is not a directory, logging its parent unnecessarily.
3755 BTRFS_I(inode
)->last_unlink_trans
= BTRFS_I(inode
)->last_trans
;
3758 if (inode
->i_nlink
!= 1 ||
3759 path
->slots
[0] >= btrfs_header_nritems(leaf
))
3762 btrfs_item_key_to_cpu(leaf
, &location
, path
->slots
[0]);
3763 if (location
.objectid
!= btrfs_ino(BTRFS_I(inode
)))
3766 ptr
= btrfs_item_ptr_offset(leaf
, path
->slots
[0]);
3767 if (location
.type
== BTRFS_INODE_REF_KEY
) {
3768 struct btrfs_inode_ref
*ref
;
3770 ref
= (struct btrfs_inode_ref
*)ptr
;
3771 BTRFS_I(inode
)->dir_index
= btrfs_inode_ref_index(leaf
, ref
);
3772 } else if (location
.type
== BTRFS_INODE_EXTREF_KEY
) {
3773 struct btrfs_inode_extref
*extref
;
3775 extref
= (struct btrfs_inode_extref
*)ptr
;
3776 BTRFS_I(inode
)->dir_index
= btrfs_inode_extref_index(leaf
,
3781 * try to precache a NULL acl entry for files that don't have
3782 * any xattrs or acls
3784 maybe_acls
= acls_after_inode_item(leaf
, path
->slots
[0],
3785 btrfs_ino(BTRFS_I(inode
)), &first_xattr_slot
);
3786 if (first_xattr_slot
!= -1) {
3787 path
->slots
[0] = first_xattr_slot
;
3788 ret
= btrfs_load_inode_props(inode
, path
);
3791 "error loading props for ino %llu (root %llu): %d",
3792 btrfs_ino(BTRFS_I(inode
)),
3793 root
->root_key
.objectid
, ret
);
3795 if (path
!= in_path
)
3796 btrfs_free_path(path
);
3799 cache_no_acl(inode
);
3801 switch (inode
->i_mode
& S_IFMT
) {
3803 inode
->i_mapping
->a_ops
= &btrfs_aops
;
3804 BTRFS_I(inode
)->io_tree
.ops
= &btrfs_extent_io_ops
;
3805 inode
->i_fop
= &btrfs_file_operations
;
3806 inode
->i_op
= &btrfs_file_inode_operations
;
3809 inode
->i_fop
= &btrfs_dir_file_operations
;
3810 inode
->i_op
= &btrfs_dir_inode_operations
;
3813 inode
->i_op
= &btrfs_symlink_inode_operations
;
3814 inode_nohighmem(inode
);
3815 inode
->i_mapping
->a_ops
= &btrfs_aops
;
3818 inode
->i_op
= &btrfs_special_inode_operations
;
3819 init_special_inode(inode
, inode
->i_mode
, rdev
);
3823 btrfs_sync_inode_flags_to_i_flags(inode
);
3828 * given a leaf and an inode, copy the inode fields into the leaf
3830 static void fill_inode_item(struct btrfs_trans_handle
*trans
,
3831 struct extent_buffer
*leaf
,
3832 struct btrfs_inode_item
*item
,
3833 struct inode
*inode
)
3835 struct btrfs_map_token token
;
3837 btrfs_init_map_token(&token
);
3839 btrfs_set_token_inode_uid(leaf
, item
, i_uid_read(inode
), &token
);
3840 btrfs_set_token_inode_gid(leaf
, item
, i_gid_read(inode
), &token
);
3841 btrfs_set_token_inode_size(leaf
, item
, BTRFS_I(inode
)->disk_i_size
,
3843 btrfs_set_token_inode_mode(leaf
, item
, inode
->i_mode
, &token
);
3844 btrfs_set_token_inode_nlink(leaf
, item
, inode
->i_nlink
, &token
);
3846 btrfs_set_token_timespec_sec(leaf
, &item
->atime
,
3847 inode
->i_atime
.tv_sec
, &token
);
3848 btrfs_set_token_timespec_nsec(leaf
, &item
->atime
,
3849 inode
->i_atime
.tv_nsec
, &token
);
3851 btrfs_set_token_timespec_sec(leaf
, &item
->mtime
,
3852 inode
->i_mtime
.tv_sec
, &token
);
3853 btrfs_set_token_timespec_nsec(leaf
, &item
->mtime
,
3854 inode
->i_mtime
.tv_nsec
, &token
);
3856 btrfs_set_token_timespec_sec(leaf
, &item
->ctime
,
3857 inode
->i_ctime
.tv_sec
, &token
);
3858 btrfs_set_token_timespec_nsec(leaf
, &item
->ctime
,
3859 inode
->i_ctime
.tv_nsec
, &token
);
3861 btrfs_set_token_timespec_sec(leaf
, &item
->otime
,
3862 BTRFS_I(inode
)->i_otime
.tv_sec
, &token
);
3863 btrfs_set_token_timespec_nsec(leaf
, &item
->otime
,
3864 BTRFS_I(inode
)->i_otime
.tv_nsec
, &token
);
3866 btrfs_set_token_inode_nbytes(leaf
, item
, inode_get_bytes(inode
),
3868 btrfs_set_token_inode_generation(leaf
, item
, BTRFS_I(inode
)->generation
,
3870 btrfs_set_token_inode_sequence(leaf
, item
, inode_peek_iversion(inode
),
3872 btrfs_set_token_inode_transid(leaf
, item
, trans
->transid
, &token
);
3873 btrfs_set_token_inode_rdev(leaf
, item
, inode
->i_rdev
, &token
);
3874 btrfs_set_token_inode_flags(leaf
, item
, BTRFS_I(inode
)->flags
, &token
);
3875 btrfs_set_token_inode_block_group(leaf
, item
, 0, &token
);
3879 * copy everything in the in-memory inode into the btree.
3881 static noinline
int btrfs_update_inode_item(struct btrfs_trans_handle
*trans
,
3882 struct btrfs_root
*root
, struct inode
*inode
)
3884 struct btrfs_inode_item
*inode_item
;
3885 struct btrfs_path
*path
;
3886 struct extent_buffer
*leaf
;
3889 path
= btrfs_alloc_path();
3893 path
->leave_spinning
= 1;
3894 ret
= btrfs_lookup_inode(trans
, root
, path
, &BTRFS_I(inode
)->location
,
3902 leaf
= path
->nodes
[0];
3903 inode_item
= btrfs_item_ptr(leaf
, path
->slots
[0],
3904 struct btrfs_inode_item
);
3906 fill_inode_item(trans
, leaf
, inode_item
, inode
);
3907 btrfs_mark_buffer_dirty(leaf
);
3908 btrfs_set_inode_last_trans(trans
, inode
);
3911 btrfs_free_path(path
);
3916 * copy everything in the in-memory inode into the btree.
3918 noinline
int btrfs_update_inode(struct btrfs_trans_handle
*trans
,
3919 struct btrfs_root
*root
, struct inode
*inode
)
3921 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
3925 * If the inode is a free space inode, we can deadlock during commit
3926 * if we put it into the delayed code.
3928 * The data relocation inode should also be directly updated
3931 if (!btrfs_is_free_space_inode(BTRFS_I(inode
))
3932 && root
->root_key
.objectid
!= BTRFS_DATA_RELOC_TREE_OBJECTID
3933 && !test_bit(BTRFS_FS_LOG_RECOVERING
, &fs_info
->flags
)) {
3934 btrfs_update_root_times(trans
, root
);
3936 ret
= btrfs_delayed_update_inode(trans
, root
, inode
);
3938 btrfs_set_inode_last_trans(trans
, inode
);
3942 return btrfs_update_inode_item(trans
, root
, inode
);
3945 noinline
int btrfs_update_inode_fallback(struct btrfs_trans_handle
*trans
,
3946 struct btrfs_root
*root
,
3947 struct inode
*inode
)
3951 ret
= btrfs_update_inode(trans
, root
, inode
);
3953 return btrfs_update_inode_item(trans
, root
, inode
);
3958 * unlink helper that gets used here in inode.c and in the tree logging
3959 * recovery code. It remove a link in a directory with a given name, and
3960 * also drops the back refs in the inode to the directory
3962 static int __btrfs_unlink_inode(struct btrfs_trans_handle
*trans
,
3963 struct btrfs_root
*root
,
3964 struct btrfs_inode
*dir
,
3965 struct btrfs_inode
*inode
,
3966 const char *name
, int name_len
)
3968 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
3969 struct btrfs_path
*path
;
3971 struct btrfs_dir_item
*di
;
3973 u64 ino
= btrfs_ino(inode
);
3974 u64 dir_ino
= btrfs_ino(dir
);
3976 path
= btrfs_alloc_path();
3982 path
->leave_spinning
= 1;
3983 di
= btrfs_lookup_dir_item(trans
, root
, path
, dir_ino
,
3984 name
, name_len
, -1);
3985 if (IS_ERR_OR_NULL(di
)) {
3986 ret
= di
? PTR_ERR(di
) : -ENOENT
;
3989 ret
= btrfs_delete_one_dir_name(trans
, root
, path
, di
);
3992 btrfs_release_path(path
);
3995 * If we don't have dir index, we have to get it by looking up
3996 * the inode ref, since we get the inode ref, remove it directly,
3997 * it is unnecessary to do delayed deletion.
3999 * But if we have dir index, needn't search inode ref to get it.
4000 * Since the inode ref is close to the inode item, it is better
4001 * that we delay to delete it, and just do this deletion when
4002 * we update the inode item.
4004 if (inode
->dir_index
) {
4005 ret
= btrfs_delayed_delete_inode_ref(inode
);
4007 index
= inode
->dir_index
;
4012 ret
= btrfs_del_inode_ref(trans
, root
, name
, name_len
, ino
,
4016 "failed to delete reference to %.*s, inode %llu parent %llu",
4017 name_len
, name
, ino
, dir_ino
);
4018 btrfs_abort_transaction(trans
, ret
);
4022 ret
= btrfs_delete_delayed_dir_index(trans
, dir
, index
);
4024 btrfs_abort_transaction(trans
, ret
);
4028 ret
= btrfs_del_inode_ref_in_log(trans
, root
, name
, name_len
, inode
,
4030 if (ret
!= 0 && ret
!= -ENOENT
) {
4031 btrfs_abort_transaction(trans
, ret
);
4035 ret
= btrfs_del_dir_entries_in_log(trans
, root
, name
, name_len
, dir
,
4040 btrfs_abort_transaction(trans
, ret
);
4043 * If we have a pending delayed iput we could end up with the final iput
4044 * being run in btrfs-cleaner context. If we have enough of these built
4045 * up we can end up burning a lot of time in btrfs-cleaner without any
4046 * way to throttle the unlinks. Since we're currently holding a ref on
4047 * the inode we can run the delayed iput here without any issues as the
4048 * final iput won't be done until after we drop the ref we're currently
4051 btrfs_run_delayed_iput(fs_info
, inode
);
4053 btrfs_free_path(path
);
4057 btrfs_i_size_write(dir
, dir
->vfs_inode
.i_size
- name_len
* 2);
4058 inode_inc_iversion(&inode
->vfs_inode
);
4059 inode_inc_iversion(&dir
->vfs_inode
);
4060 inode
->vfs_inode
.i_ctime
= dir
->vfs_inode
.i_mtime
=
4061 dir
->vfs_inode
.i_ctime
= current_time(&inode
->vfs_inode
);
4062 ret
= btrfs_update_inode(trans
, root
, &dir
->vfs_inode
);
4067 int btrfs_unlink_inode(struct btrfs_trans_handle
*trans
,
4068 struct btrfs_root
*root
,
4069 struct btrfs_inode
*dir
, struct btrfs_inode
*inode
,
4070 const char *name
, int name_len
)
4073 ret
= __btrfs_unlink_inode(trans
, root
, dir
, inode
, name
, name_len
);
4075 drop_nlink(&inode
->vfs_inode
);
4076 ret
= btrfs_update_inode(trans
, root
, &inode
->vfs_inode
);
4082 * helper to start transaction for unlink and rmdir.
4084 * unlink and rmdir are special in btrfs, they do not always free space, so
4085 * if we cannot make our reservations the normal way try and see if there is
4086 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4087 * allow the unlink to occur.
4089 static struct btrfs_trans_handle
*__unlink_start_trans(struct inode
*dir
)
4091 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
4094 * 1 for the possible orphan item
4095 * 1 for the dir item
4096 * 1 for the dir index
4097 * 1 for the inode ref
4100 return btrfs_start_transaction_fallback_global_rsv(root
, 5, 5);
4103 static int btrfs_unlink(struct inode
*dir
, struct dentry
*dentry
)
4105 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
4106 struct btrfs_trans_handle
*trans
;
4107 struct inode
*inode
= d_inode(dentry
);
4110 trans
= __unlink_start_trans(dir
);
4112 return PTR_ERR(trans
);
4114 btrfs_record_unlink_dir(trans
, BTRFS_I(dir
), BTRFS_I(d_inode(dentry
)),
4117 ret
= btrfs_unlink_inode(trans
, root
, BTRFS_I(dir
),
4118 BTRFS_I(d_inode(dentry
)), dentry
->d_name
.name
,
4119 dentry
->d_name
.len
);
4123 if (inode
->i_nlink
== 0) {
4124 ret
= btrfs_orphan_add(trans
, BTRFS_I(inode
));
4130 btrfs_end_transaction(trans
);
4131 btrfs_btree_balance_dirty(root
->fs_info
);
4135 static int btrfs_unlink_subvol(struct btrfs_trans_handle
*trans
,
4136 struct inode
*dir
, u64 objectid
,
4137 const char *name
, int name_len
)
4139 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
4140 struct btrfs_path
*path
;
4141 struct extent_buffer
*leaf
;
4142 struct btrfs_dir_item
*di
;
4143 struct btrfs_key key
;
4146 u64 dir_ino
= btrfs_ino(BTRFS_I(dir
));
4148 path
= btrfs_alloc_path();
4152 di
= btrfs_lookup_dir_item(trans
, root
, path
, dir_ino
,
4153 name
, name_len
, -1);
4154 if (IS_ERR_OR_NULL(di
)) {
4155 ret
= di
? PTR_ERR(di
) : -ENOENT
;
4159 leaf
= path
->nodes
[0];
4160 btrfs_dir_item_key_to_cpu(leaf
, di
, &key
);
4161 WARN_ON(key
.type
!= BTRFS_ROOT_ITEM_KEY
|| key
.objectid
!= objectid
);
4162 ret
= btrfs_delete_one_dir_name(trans
, root
, path
, di
);
4164 btrfs_abort_transaction(trans
, ret
);
4167 btrfs_release_path(path
);
4169 ret
= btrfs_del_root_ref(trans
, objectid
, root
->root_key
.objectid
,
4170 dir_ino
, &index
, name
, name_len
);
4172 if (ret
!= -ENOENT
) {
4173 btrfs_abort_transaction(trans
, ret
);
4176 di
= btrfs_search_dir_index_item(root
, path
, dir_ino
,
4178 if (IS_ERR_OR_NULL(di
)) {
4183 btrfs_abort_transaction(trans
, ret
);
4187 leaf
= path
->nodes
[0];
4188 btrfs_item_key_to_cpu(leaf
, &key
, path
->slots
[0]);
4191 btrfs_release_path(path
);
4193 ret
= btrfs_delete_delayed_dir_index(trans
, BTRFS_I(dir
), index
);
4195 btrfs_abort_transaction(trans
, ret
);
4199 btrfs_i_size_write(BTRFS_I(dir
), dir
->i_size
- name_len
* 2);
4200 inode_inc_iversion(dir
);
4201 dir
->i_mtime
= dir
->i_ctime
= current_time(dir
);
4202 ret
= btrfs_update_inode_fallback(trans
, root
, dir
);
4204 btrfs_abort_transaction(trans
, ret
);
4206 btrfs_free_path(path
);
4211 * Helper to check if the subvolume references other subvolumes or if it's
4214 static noinline
int may_destroy_subvol(struct btrfs_root
*root
)
4216 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4217 struct btrfs_path
*path
;
4218 struct btrfs_dir_item
*di
;
4219 struct btrfs_key key
;
4223 path
= btrfs_alloc_path();
4227 /* Make sure this root isn't set as the default subvol */
4228 dir_id
= btrfs_super_root_dir(fs_info
->super_copy
);
4229 di
= btrfs_lookup_dir_item(NULL
, fs_info
->tree_root
, path
,
4230 dir_id
, "default", 7, 0);
4231 if (di
&& !IS_ERR(di
)) {
4232 btrfs_dir_item_key_to_cpu(path
->nodes
[0], di
, &key
);
4233 if (key
.objectid
== root
->root_key
.objectid
) {
4236 "deleting default subvolume %llu is not allowed",
4240 btrfs_release_path(path
);
4243 key
.objectid
= root
->root_key
.objectid
;
4244 key
.type
= BTRFS_ROOT_REF_KEY
;
4245 key
.offset
= (u64
)-1;
4247 ret
= btrfs_search_slot(NULL
, fs_info
->tree_root
, &key
, path
, 0, 0);
4253 if (path
->slots
[0] > 0) {
4255 btrfs_item_key_to_cpu(path
->nodes
[0], &key
, path
->slots
[0]);
4256 if (key
.objectid
== root
->root_key
.objectid
&&
4257 key
.type
== BTRFS_ROOT_REF_KEY
)
4261 btrfs_free_path(path
);
4265 /* Delete all dentries for inodes belonging to the root */
4266 static void btrfs_prune_dentries(struct btrfs_root
*root
)
4268 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4269 struct rb_node
*node
;
4270 struct rb_node
*prev
;
4271 struct btrfs_inode
*entry
;
4272 struct inode
*inode
;
4275 if (!test_bit(BTRFS_FS_STATE_ERROR
, &fs_info
->fs_state
))
4276 WARN_ON(btrfs_root_refs(&root
->root_item
) != 0);
4278 spin_lock(&root
->inode_lock
);
4280 node
= root
->inode_tree
.rb_node
;
4284 entry
= rb_entry(node
, struct btrfs_inode
, rb_node
);
4286 if (objectid
< btrfs_ino(entry
))
4287 node
= node
->rb_left
;
4288 else if (objectid
> btrfs_ino(entry
))
4289 node
= node
->rb_right
;
4295 entry
= rb_entry(prev
, struct btrfs_inode
, rb_node
);
4296 if (objectid
<= btrfs_ino(entry
)) {
4300 prev
= rb_next(prev
);
4304 entry
= rb_entry(node
, struct btrfs_inode
, rb_node
);
4305 objectid
= btrfs_ino(entry
) + 1;
4306 inode
= igrab(&entry
->vfs_inode
);
4308 spin_unlock(&root
->inode_lock
);
4309 if (atomic_read(&inode
->i_count
) > 1)
4310 d_prune_aliases(inode
);
4312 * btrfs_drop_inode will have it removed from the inode
4313 * cache when its usage count hits zero.
4317 spin_lock(&root
->inode_lock
);
4321 if (cond_resched_lock(&root
->inode_lock
))
4324 node
= rb_next(node
);
4326 spin_unlock(&root
->inode_lock
);
4329 int btrfs_delete_subvolume(struct inode
*dir
, struct dentry
*dentry
)
4331 struct btrfs_fs_info
*fs_info
= btrfs_sb(dentry
->d_sb
);
4332 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
4333 struct inode
*inode
= d_inode(dentry
);
4334 struct btrfs_root
*dest
= BTRFS_I(inode
)->root
;
4335 struct btrfs_trans_handle
*trans
;
4336 struct btrfs_block_rsv block_rsv
;
4342 * Don't allow to delete a subvolume with send in progress. This is
4343 * inside the inode lock so the error handling that has to drop the bit
4344 * again is not run concurrently.
4346 spin_lock(&dest
->root_item_lock
);
4347 if (dest
->send_in_progress
) {
4348 spin_unlock(&dest
->root_item_lock
);
4350 "attempt to delete subvolume %llu during send",
4351 dest
->root_key
.objectid
);
4354 root_flags
= btrfs_root_flags(&dest
->root_item
);
4355 btrfs_set_root_flags(&dest
->root_item
,
4356 root_flags
| BTRFS_ROOT_SUBVOL_DEAD
);
4357 spin_unlock(&dest
->root_item_lock
);
4359 down_write(&fs_info
->subvol_sem
);
4361 err
= may_destroy_subvol(dest
);
4365 btrfs_init_block_rsv(&block_rsv
, BTRFS_BLOCK_RSV_TEMP
);
4367 * One for dir inode,
4368 * two for dir entries,
4369 * two for root ref/backref.
4371 err
= btrfs_subvolume_reserve_metadata(root
, &block_rsv
, 5, true);
4375 trans
= btrfs_start_transaction(root
, 0);
4376 if (IS_ERR(trans
)) {
4377 err
= PTR_ERR(trans
);
4380 trans
->block_rsv
= &block_rsv
;
4381 trans
->bytes_reserved
= block_rsv
.size
;
4383 btrfs_record_snapshot_destroy(trans
, BTRFS_I(dir
));
4385 ret
= btrfs_unlink_subvol(trans
, dir
, dest
->root_key
.objectid
,
4386 dentry
->d_name
.name
, dentry
->d_name
.len
);
4389 btrfs_abort_transaction(trans
, ret
);
4393 btrfs_record_root_in_trans(trans
, dest
);
4395 memset(&dest
->root_item
.drop_progress
, 0,
4396 sizeof(dest
->root_item
.drop_progress
));
4397 dest
->root_item
.drop_level
= 0;
4398 btrfs_set_root_refs(&dest
->root_item
, 0);
4400 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED
, &dest
->state
)) {
4401 ret
= btrfs_insert_orphan_item(trans
,
4403 dest
->root_key
.objectid
);
4405 btrfs_abort_transaction(trans
, ret
);
4411 ret
= btrfs_uuid_tree_remove(trans
, dest
->root_item
.uuid
,
4412 BTRFS_UUID_KEY_SUBVOL
,
4413 dest
->root_key
.objectid
);
4414 if (ret
&& ret
!= -ENOENT
) {
4415 btrfs_abort_transaction(trans
, ret
);
4419 if (!btrfs_is_empty_uuid(dest
->root_item
.received_uuid
)) {
4420 ret
= btrfs_uuid_tree_remove(trans
,
4421 dest
->root_item
.received_uuid
,
4422 BTRFS_UUID_KEY_RECEIVED_SUBVOL
,
4423 dest
->root_key
.objectid
);
4424 if (ret
&& ret
!= -ENOENT
) {
4425 btrfs_abort_transaction(trans
, ret
);
4432 trans
->block_rsv
= NULL
;
4433 trans
->bytes_reserved
= 0;
4434 ret
= btrfs_end_transaction(trans
);
4437 inode
->i_flags
|= S_DEAD
;
4439 btrfs_subvolume_release_metadata(fs_info
, &block_rsv
);
4441 up_write(&fs_info
->subvol_sem
);
4443 spin_lock(&dest
->root_item_lock
);
4444 root_flags
= btrfs_root_flags(&dest
->root_item
);
4445 btrfs_set_root_flags(&dest
->root_item
,
4446 root_flags
& ~BTRFS_ROOT_SUBVOL_DEAD
);
4447 spin_unlock(&dest
->root_item_lock
);
4449 d_invalidate(dentry
);
4450 btrfs_prune_dentries(dest
);
4451 ASSERT(dest
->send_in_progress
== 0);
4454 if (dest
->ino_cache_inode
) {
4455 iput(dest
->ino_cache_inode
);
4456 dest
->ino_cache_inode
= NULL
;
4463 static int btrfs_rmdir(struct inode
*dir
, struct dentry
*dentry
)
4465 struct inode
*inode
= d_inode(dentry
);
4467 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
4468 struct btrfs_trans_handle
*trans
;
4469 u64 last_unlink_trans
;
4471 if (inode
->i_size
> BTRFS_EMPTY_DIR_SIZE
)
4473 if (btrfs_ino(BTRFS_I(inode
)) == BTRFS_FIRST_FREE_OBJECTID
)
4474 return btrfs_delete_subvolume(dir
, dentry
);
4476 trans
= __unlink_start_trans(dir
);
4478 return PTR_ERR(trans
);
4480 if (unlikely(btrfs_ino(BTRFS_I(inode
)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)) {
4481 err
= btrfs_unlink_subvol(trans
, dir
,
4482 BTRFS_I(inode
)->location
.objectid
,
4483 dentry
->d_name
.name
,
4484 dentry
->d_name
.len
);
4488 err
= btrfs_orphan_add(trans
, BTRFS_I(inode
));
4492 last_unlink_trans
= BTRFS_I(inode
)->last_unlink_trans
;
4494 /* now the directory is empty */
4495 err
= btrfs_unlink_inode(trans
, root
, BTRFS_I(dir
),
4496 BTRFS_I(d_inode(dentry
)), dentry
->d_name
.name
,
4497 dentry
->d_name
.len
);
4499 btrfs_i_size_write(BTRFS_I(inode
), 0);
4501 * Propagate the last_unlink_trans value of the deleted dir to
4502 * its parent directory. This is to prevent an unrecoverable
4503 * log tree in the case we do something like this:
4505 * 2) create snapshot under dir foo
4506 * 3) delete the snapshot
4509 * 6) fsync foo or some file inside foo
4511 if (last_unlink_trans
>= trans
->transid
)
4512 BTRFS_I(dir
)->last_unlink_trans
= last_unlink_trans
;
4515 btrfs_end_transaction(trans
);
4516 btrfs_btree_balance_dirty(root
->fs_info
);
4522 * Return this if we need to call truncate_block for the last bit of the
4525 #define NEED_TRUNCATE_BLOCK 1
4528 * this can truncate away extent items, csum items and directory items.
4529 * It starts at a high offset and removes keys until it can't find
4530 * any higher than new_size
4532 * csum items that cross the new i_size are truncated to the new size
4535 * min_type is the minimum key type to truncate down to. If set to 0, this
4536 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4538 int btrfs_truncate_inode_items(struct btrfs_trans_handle
*trans
,
4539 struct btrfs_root
*root
,
4540 struct inode
*inode
,
4541 u64 new_size
, u32 min_type
)
4543 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
4544 struct btrfs_path
*path
;
4545 struct extent_buffer
*leaf
;
4546 struct btrfs_file_extent_item
*fi
;
4547 struct btrfs_key key
;
4548 struct btrfs_key found_key
;
4549 u64 extent_start
= 0;
4550 u64 extent_num_bytes
= 0;
4551 u64 extent_offset
= 0;
4553 u64 last_size
= new_size
;
4554 u32 found_type
= (u8
)-1;
4557 int pending_del_nr
= 0;
4558 int pending_del_slot
= 0;
4559 int extent_type
= -1;
4561 u64 ino
= btrfs_ino(BTRFS_I(inode
));
4562 u64 bytes_deleted
= 0;
4563 bool be_nice
= false;
4564 bool should_throttle
= false;
4566 BUG_ON(new_size
> 0 && min_type
!= BTRFS_EXTENT_DATA_KEY
);
4569 * for non-free space inodes and ref cows, we want to back off from
4572 if (!btrfs_is_free_space_inode(BTRFS_I(inode
)) &&
4573 test_bit(BTRFS_ROOT_REF_COWS
, &root
->state
))
4576 path
= btrfs_alloc_path();
4579 path
->reada
= READA_BACK
;
4582 * We want to drop from the next block forward in case this new size is
4583 * not block aligned since we will be keeping the last block of the
4584 * extent just the way it is.
4586 if (test_bit(BTRFS_ROOT_REF_COWS
, &root
->state
) ||
4587 root
== fs_info
->tree_root
)
4588 btrfs_drop_extent_cache(BTRFS_I(inode
), ALIGN(new_size
,
4589 fs_info
->sectorsize
),
4593 * This function is also used to drop the items in the log tree before
4594 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4595 * it is used to drop the logged items. So we shouldn't kill the delayed
4598 if (min_type
== 0 && root
== BTRFS_I(inode
)->root
)
4599 btrfs_kill_delayed_inode_items(BTRFS_I(inode
));
4602 key
.offset
= (u64
)-1;
4607 * with a 16K leaf size and 128MB extents, you can actually queue
4608 * up a huge file in a single leaf. Most of the time that
4609 * bytes_deleted is > 0, it will be huge by the time we get here
4611 if (be_nice
&& bytes_deleted
> SZ_32M
&&
4612 btrfs_should_end_transaction(trans
)) {
4617 path
->leave_spinning
= 1;
4618 ret
= btrfs_search_slot(trans
, root
, &key
, path
, -1, 1);
4624 /* there are no items in the tree for us to truncate, we're
4627 if (path
->slots
[0] == 0)
4634 leaf
= path
->nodes
[0];
4635 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
4636 found_type
= found_key
.type
;
4638 if (found_key
.objectid
!= ino
)
4641 if (found_type
< min_type
)
4644 item_end
= found_key
.offset
;
4645 if (found_type
== BTRFS_EXTENT_DATA_KEY
) {
4646 fi
= btrfs_item_ptr(leaf
, path
->slots
[0],
4647 struct btrfs_file_extent_item
);
4648 extent_type
= btrfs_file_extent_type(leaf
, fi
);
4649 if (extent_type
!= BTRFS_FILE_EXTENT_INLINE
) {
4651 btrfs_file_extent_num_bytes(leaf
, fi
);
4653 trace_btrfs_truncate_show_fi_regular(
4654 BTRFS_I(inode
), leaf
, fi
,
4656 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
4657 item_end
+= btrfs_file_extent_ram_bytes(leaf
,
4660 trace_btrfs_truncate_show_fi_inline(
4661 BTRFS_I(inode
), leaf
, fi
, path
->slots
[0],
4666 if (found_type
> min_type
) {
4669 if (item_end
< new_size
)
4671 if (found_key
.offset
>= new_size
)
4677 /* FIXME, shrink the extent if the ref count is only 1 */
4678 if (found_type
!= BTRFS_EXTENT_DATA_KEY
)
4681 if (extent_type
!= BTRFS_FILE_EXTENT_INLINE
) {
4683 extent_start
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
4685 u64 orig_num_bytes
=
4686 btrfs_file_extent_num_bytes(leaf
, fi
);
4687 extent_num_bytes
= ALIGN(new_size
-
4689 fs_info
->sectorsize
);
4690 btrfs_set_file_extent_num_bytes(leaf
, fi
,
4692 num_dec
= (orig_num_bytes
-
4694 if (test_bit(BTRFS_ROOT_REF_COWS
,
4697 inode_sub_bytes(inode
, num_dec
);
4698 btrfs_mark_buffer_dirty(leaf
);
4701 btrfs_file_extent_disk_num_bytes(leaf
,
4703 extent_offset
= found_key
.offset
-
4704 btrfs_file_extent_offset(leaf
, fi
);
4706 /* FIXME blocksize != 4096 */
4707 num_dec
= btrfs_file_extent_num_bytes(leaf
, fi
);
4708 if (extent_start
!= 0) {
4710 if (test_bit(BTRFS_ROOT_REF_COWS
,
4712 inode_sub_bytes(inode
, num_dec
);
4715 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
4717 * we can't truncate inline items that have had
4721 btrfs_file_extent_encryption(leaf
, fi
) == 0 &&
4722 btrfs_file_extent_other_encoding(leaf
, fi
) == 0 &&
4723 btrfs_file_extent_compression(leaf
, fi
) == 0) {
4724 u32 size
= (u32
)(new_size
- found_key
.offset
);
4726 btrfs_set_file_extent_ram_bytes(leaf
, fi
, size
);
4727 size
= btrfs_file_extent_calc_inline_size(size
);
4728 btrfs_truncate_item(path
, size
, 1);
4729 } else if (!del_item
) {
4731 * We have to bail so the last_size is set to
4732 * just before this extent.
4734 ret
= NEED_TRUNCATE_BLOCK
;
4738 if (test_bit(BTRFS_ROOT_REF_COWS
, &root
->state
))
4739 inode_sub_bytes(inode
, item_end
+ 1 - new_size
);
4743 last_size
= found_key
.offset
;
4745 last_size
= new_size
;
4747 if (!pending_del_nr
) {
4748 /* no pending yet, add ourselves */
4749 pending_del_slot
= path
->slots
[0];
4751 } else if (pending_del_nr
&&
4752 path
->slots
[0] + 1 == pending_del_slot
) {
4753 /* hop on the pending chunk */
4755 pending_del_slot
= path
->slots
[0];
4762 should_throttle
= false;
4765 (test_bit(BTRFS_ROOT_REF_COWS
, &root
->state
) ||
4766 root
== fs_info
->tree_root
)) {
4767 struct btrfs_ref ref
= { 0 };
4769 btrfs_set_path_blocking(path
);
4770 bytes_deleted
+= extent_num_bytes
;
4772 btrfs_init_generic_ref(&ref
, BTRFS_DROP_DELAYED_REF
,
4773 extent_start
, extent_num_bytes
, 0);
4774 ref
.real_root
= root
->root_key
.objectid
;
4775 btrfs_init_data_ref(&ref
, btrfs_header_owner(leaf
),
4776 ino
, extent_offset
);
4777 ret
= btrfs_free_extent(trans
, &ref
);
4779 btrfs_abort_transaction(trans
, ret
);
4783 if (btrfs_should_throttle_delayed_refs(trans
))
4784 should_throttle
= true;
4788 if (found_type
== BTRFS_INODE_ITEM_KEY
)
4791 if (path
->slots
[0] == 0 ||
4792 path
->slots
[0] != pending_del_slot
||
4794 if (pending_del_nr
) {
4795 ret
= btrfs_del_items(trans
, root
, path
,
4799 btrfs_abort_transaction(trans
, ret
);
4804 btrfs_release_path(path
);
4807 * We can generate a lot of delayed refs, so we need to
4808 * throttle every once and a while and make sure we're
4809 * adding enough space to keep up with the work we are
4810 * generating. Since we hold a transaction here we
4811 * can't flush, and we don't want to FLUSH_LIMIT because
4812 * we could have generated too many delayed refs to
4813 * actually allocate, so just bail if we're short and
4814 * let the normal reservation dance happen higher up.
4816 if (should_throttle
) {
4817 ret
= btrfs_delayed_refs_rsv_refill(fs_info
,
4818 BTRFS_RESERVE_NO_FLUSH
);
4830 if (ret
>= 0 && pending_del_nr
) {
4833 err
= btrfs_del_items(trans
, root
, path
, pending_del_slot
,
4836 btrfs_abort_transaction(trans
, err
);
4840 if (root
->root_key
.objectid
!= BTRFS_TREE_LOG_OBJECTID
) {
4841 ASSERT(last_size
>= new_size
);
4842 if (!ret
&& last_size
> new_size
)
4843 last_size
= new_size
;
4844 btrfs_ordered_update_i_size(inode
, last_size
, NULL
);
4847 btrfs_free_path(path
);
4852 * btrfs_truncate_block - read, zero a chunk and write a block
4853 * @inode - inode that we're zeroing
4854 * @from - the offset to start zeroing
4855 * @len - the length to zero, 0 to zero the entire range respective to the
4857 * @front - zero up to the offset instead of from the offset on
4859 * This will find the block for the "from" offset and cow the block and zero the
4860 * part we want to zero. This is used with truncate and hole punching.
4862 int btrfs_truncate_block(struct inode
*inode
, loff_t from
, loff_t len
,
4865 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
4866 struct address_space
*mapping
= inode
->i_mapping
;
4867 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
4868 struct btrfs_ordered_extent
*ordered
;
4869 struct extent_state
*cached_state
= NULL
;
4870 struct extent_changeset
*data_reserved
= NULL
;
4872 u32 blocksize
= fs_info
->sectorsize
;
4873 pgoff_t index
= from
>> PAGE_SHIFT
;
4874 unsigned offset
= from
& (blocksize
- 1);
4876 gfp_t mask
= btrfs_alloc_write_mask(mapping
);
4881 if (IS_ALIGNED(offset
, blocksize
) &&
4882 (!len
|| IS_ALIGNED(len
, blocksize
)))
4885 block_start
= round_down(from
, blocksize
);
4886 block_end
= block_start
+ blocksize
- 1;
4888 ret
= btrfs_delalloc_reserve_space(inode
, &data_reserved
,
4889 block_start
, blocksize
);
4894 page
= find_or_create_page(mapping
, index
, mask
);
4896 btrfs_delalloc_release_space(inode
, data_reserved
,
4897 block_start
, blocksize
, true);
4898 btrfs_delalloc_release_extents(BTRFS_I(inode
), blocksize
, true);
4903 if (!PageUptodate(page
)) {
4904 ret
= btrfs_readpage(NULL
, page
);
4906 if (page
->mapping
!= mapping
) {
4911 if (!PageUptodate(page
)) {
4916 wait_on_page_writeback(page
);
4918 lock_extent_bits(io_tree
, block_start
, block_end
, &cached_state
);
4919 set_page_extent_mapped(page
);
4921 ordered
= btrfs_lookup_ordered_extent(inode
, block_start
);
4923 unlock_extent_cached(io_tree
, block_start
, block_end
,
4927 btrfs_start_ordered_extent(inode
, ordered
, 1);
4928 btrfs_put_ordered_extent(ordered
);
4932 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, block_start
, block_end
,
4933 EXTENT_DIRTY
| EXTENT_DELALLOC
|
4934 EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
,
4935 0, 0, &cached_state
);
4937 ret
= btrfs_set_extent_delalloc(inode
, block_start
, block_end
, 0,
4940 unlock_extent_cached(io_tree
, block_start
, block_end
,
4945 if (offset
!= blocksize
) {
4947 len
= blocksize
- offset
;
4950 memset(kaddr
+ (block_start
- page_offset(page
)),
4953 memset(kaddr
+ (block_start
- page_offset(page
)) + offset
,
4955 flush_dcache_page(page
);
4958 ClearPageChecked(page
);
4959 set_page_dirty(page
);
4960 unlock_extent_cached(io_tree
, block_start
, block_end
, &cached_state
);
4964 btrfs_delalloc_release_space(inode
, data_reserved
, block_start
,
4966 btrfs_delalloc_release_extents(BTRFS_I(inode
), blocksize
, (ret
!= 0));
4970 extent_changeset_free(data_reserved
);
4974 static int maybe_insert_hole(struct btrfs_root
*root
, struct inode
*inode
,
4975 u64 offset
, u64 len
)
4977 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
4978 struct btrfs_trans_handle
*trans
;
4982 * Still need to make sure the inode looks like it's been updated so
4983 * that any holes get logged if we fsync.
4985 if (btrfs_fs_incompat(fs_info
, NO_HOLES
)) {
4986 BTRFS_I(inode
)->last_trans
= fs_info
->generation
;
4987 BTRFS_I(inode
)->last_sub_trans
= root
->log_transid
;
4988 BTRFS_I(inode
)->last_log_commit
= root
->last_log_commit
;
4993 * 1 - for the one we're dropping
4994 * 1 - for the one we're adding
4995 * 1 - for updating the inode.
4997 trans
= btrfs_start_transaction(root
, 3);
4999 return PTR_ERR(trans
);
5001 ret
= btrfs_drop_extents(trans
, root
, inode
, offset
, offset
+ len
, 1);
5003 btrfs_abort_transaction(trans
, ret
);
5004 btrfs_end_transaction(trans
);
5008 ret
= btrfs_insert_file_extent(trans
, root
, btrfs_ino(BTRFS_I(inode
)),
5009 offset
, 0, 0, len
, 0, len
, 0, 0, 0);
5011 btrfs_abort_transaction(trans
, ret
);
5013 btrfs_update_inode(trans
, root
, inode
);
5014 btrfs_end_transaction(trans
);
5019 * This function puts in dummy file extents for the area we're creating a hole
5020 * for. So if we are truncating this file to a larger size we need to insert
5021 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5022 * the range between oldsize and size
5024 int btrfs_cont_expand(struct inode
*inode
, loff_t oldsize
, loff_t size
)
5026 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
5027 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5028 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
5029 struct extent_map
*em
= NULL
;
5030 struct extent_state
*cached_state
= NULL
;
5031 struct extent_map_tree
*em_tree
= &BTRFS_I(inode
)->extent_tree
;
5032 u64 hole_start
= ALIGN(oldsize
, fs_info
->sectorsize
);
5033 u64 block_end
= ALIGN(size
, fs_info
->sectorsize
);
5040 * If our size started in the middle of a block we need to zero out the
5041 * rest of the block before we expand the i_size, otherwise we could
5042 * expose stale data.
5044 err
= btrfs_truncate_block(inode
, oldsize
, 0, 0);
5048 if (size
<= hole_start
)
5051 btrfs_lock_and_flush_ordered_range(io_tree
, BTRFS_I(inode
), hole_start
,
5052 block_end
- 1, &cached_state
);
5053 cur_offset
= hole_start
;
5055 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, cur_offset
,
5056 block_end
- cur_offset
, 0);
5062 last_byte
= min(extent_map_end(em
), block_end
);
5063 last_byte
= ALIGN(last_byte
, fs_info
->sectorsize
);
5064 if (!test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
)) {
5065 struct extent_map
*hole_em
;
5066 hole_size
= last_byte
- cur_offset
;
5068 err
= maybe_insert_hole(root
, inode
, cur_offset
,
5072 btrfs_drop_extent_cache(BTRFS_I(inode
), cur_offset
,
5073 cur_offset
+ hole_size
- 1, 0);
5074 hole_em
= alloc_extent_map();
5076 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
5077 &BTRFS_I(inode
)->runtime_flags
);
5080 hole_em
->start
= cur_offset
;
5081 hole_em
->len
= hole_size
;
5082 hole_em
->orig_start
= cur_offset
;
5084 hole_em
->block_start
= EXTENT_MAP_HOLE
;
5085 hole_em
->block_len
= 0;
5086 hole_em
->orig_block_len
= 0;
5087 hole_em
->ram_bytes
= hole_size
;
5088 hole_em
->bdev
= fs_info
->fs_devices
->latest_bdev
;
5089 hole_em
->compress_type
= BTRFS_COMPRESS_NONE
;
5090 hole_em
->generation
= fs_info
->generation
;
5093 write_lock(&em_tree
->lock
);
5094 err
= add_extent_mapping(em_tree
, hole_em
, 1);
5095 write_unlock(&em_tree
->lock
);
5098 btrfs_drop_extent_cache(BTRFS_I(inode
),
5103 free_extent_map(hole_em
);
5106 free_extent_map(em
);
5108 cur_offset
= last_byte
;
5109 if (cur_offset
>= block_end
)
5112 free_extent_map(em
);
5113 unlock_extent_cached(io_tree
, hole_start
, block_end
- 1, &cached_state
);
5117 static int btrfs_setsize(struct inode
*inode
, struct iattr
*attr
)
5119 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5120 struct btrfs_trans_handle
*trans
;
5121 loff_t oldsize
= i_size_read(inode
);
5122 loff_t newsize
= attr
->ia_size
;
5123 int mask
= attr
->ia_valid
;
5127 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5128 * special case where we need to update the times despite not having
5129 * these flags set. For all other operations the VFS set these flags
5130 * explicitly if it wants a timestamp update.
5132 if (newsize
!= oldsize
) {
5133 inode_inc_iversion(inode
);
5134 if (!(mask
& (ATTR_CTIME
| ATTR_MTIME
)))
5135 inode
->i_ctime
= inode
->i_mtime
=
5136 current_time(inode
);
5139 if (newsize
> oldsize
) {
5141 * Don't do an expanding truncate while snapshotting is ongoing.
5142 * This is to ensure the snapshot captures a fully consistent
5143 * state of this file - if the snapshot captures this expanding
5144 * truncation, it must capture all writes that happened before
5147 btrfs_wait_for_snapshot_creation(root
);
5148 ret
= btrfs_cont_expand(inode
, oldsize
, newsize
);
5150 btrfs_end_write_no_snapshotting(root
);
5154 trans
= btrfs_start_transaction(root
, 1);
5155 if (IS_ERR(trans
)) {
5156 btrfs_end_write_no_snapshotting(root
);
5157 return PTR_ERR(trans
);
5160 i_size_write(inode
, newsize
);
5161 btrfs_ordered_update_i_size(inode
, i_size_read(inode
), NULL
);
5162 pagecache_isize_extended(inode
, oldsize
, newsize
);
5163 ret
= btrfs_update_inode(trans
, root
, inode
);
5164 btrfs_end_write_no_snapshotting(root
);
5165 btrfs_end_transaction(trans
);
5169 * We're truncating a file that used to have good data down to
5170 * zero. Make sure it gets into the ordered flush list so that
5171 * any new writes get down to disk quickly.
5174 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE
,
5175 &BTRFS_I(inode
)->runtime_flags
);
5177 truncate_setsize(inode
, newsize
);
5179 /* Disable nonlocked read DIO to avoid the endless truncate */
5180 btrfs_inode_block_unlocked_dio(BTRFS_I(inode
));
5181 inode_dio_wait(inode
);
5182 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode
));
5184 ret
= btrfs_truncate(inode
, newsize
== oldsize
);
5185 if (ret
&& inode
->i_nlink
) {
5189 * Truncate failed, so fix up the in-memory size. We
5190 * adjusted disk_i_size down as we removed extents, so
5191 * wait for disk_i_size to be stable and then update the
5192 * in-memory size to match.
5194 err
= btrfs_wait_ordered_range(inode
, 0, (u64
)-1);
5197 i_size_write(inode
, BTRFS_I(inode
)->disk_i_size
);
5204 static int btrfs_setattr(struct dentry
*dentry
, struct iattr
*attr
)
5206 struct inode
*inode
= d_inode(dentry
);
5207 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5210 if (btrfs_root_readonly(root
))
5213 err
= setattr_prepare(dentry
, attr
);
5217 if (S_ISREG(inode
->i_mode
) && (attr
->ia_valid
& ATTR_SIZE
)) {
5218 err
= btrfs_setsize(inode
, attr
);
5223 if (attr
->ia_valid
) {
5224 setattr_copy(inode
, attr
);
5225 inode_inc_iversion(inode
);
5226 err
= btrfs_dirty_inode(inode
);
5228 if (!err
&& attr
->ia_valid
& ATTR_MODE
)
5229 err
= posix_acl_chmod(inode
, inode
->i_mode
);
5236 * While truncating the inode pages during eviction, we get the VFS calling
5237 * btrfs_invalidatepage() against each page of the inode. This is slow because
5238 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5239 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5240 * extent_state structures over and over, wasting lots of time.
5242 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5243 * those expensive operations on a per page basis and do only the ordered io
5244 * finishing, while we release here the extent_map and extent_state structures,
5245 * without the excessive merging and splitting.
5247 static void evict_inode_truncate_pages(struct inode
*inode
)
5249 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
5250 struct extent_map_tree
*map_tree
= &BTRFS_I(inode
)->extent_tree
;
5251 struct rb_node
*node
;
5253 ASSERT(inode
->i_state
& I_FREEING
);
5254 truncate_inode_pages_final(&inode
->i_data
);
5256 write_lock(&map_tree
->lock
);
5257 while (!RB_EMPTY_ROOT(&map_tree
->map
.rb_root
)) {
5258 struct extent_map
*em
;
5260 node
= rb_first_cached(&map_tree
->map
);
5261 em
= rb_entry(node
, struct extent_map
, rb_node
);
5262 clear_bit(EXTENT_FLAG_PINNED
, &em
->flags
);
5263 clear_bit(EXTENT_FLAG_LOGGING
, &em
->flags
);
5264 remove_extent_mapping(map_tree
, em
);
5265 free_extent_map(em
);
5266 if (need_resched()) {
5267 write_unlock(&map_tree
->lock
);
5269 write_lock(&map_tree
->lock
);
5272 write_unlock(&map_tree
->lock
);
5275 * Keep looping until we have no more ranges in the io tree.
5276 * We can have ongoing bios started by readpages (called from readahead)
5277 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5278 * still in progress (unlocked the pages in the bio but did not yet
5279 * unlocked the ranges in the io tree). Therefore this means some
5280 * ranges can still be locked and eviction started because before
5281 * submitting those bios, which are executed by a separate task (work
5282 * queue kthread), inode references (inode->i_count) were not taken
5283 * (which would be dropped in the end io callback of each bio).
5284 * Therefore here we effectively end up waiting for those bios and
5285 * anyone else holding locked ranges without having bumped the inode's
5286 * reference count - if we don't do it, when they access the inode's
5287 * io_tree to unlock a range it may be too late, leading to an
5288 * use-after-free issue.
5290 spin_lock(&io_tree
->lock
);
5291 while (!RB_EMPTY_ROOT(&io_tree
->state
)) {
5292 struct extent_state
*state
;
5293 struct extent_state
*cached_state
= NULL
;
5296 unsigned state_flags
;
5298 node
= rb_first(&io_tree
->state
);
5299 state
= rb_entry(node
, struct extent_state
, rb_node
);
5300 start
= state
->start
;
5302 state_flags
= state
->state
;
5303 spin_unlock(&io_tree
->lock
);
5305 lock_extent_bits(io_tree
, start
, end
, &cached_state
);
5308 * If still has DELALLOC flag, the extent didn't reach disk,
5309 * and its reserved space won't be freed by delayed_ref.
5310 * So we need to free its reserved space here.
5311 * (Refer to comment in btrfs_invalidatepage, case 2)
5313 * Note, end is the bytenr of last byte, so we need + 1 here.
5315 if (state_flags
& EXTENT_DELALLOC
)
5316 btrfs_qgroup_free_data(inode
, NULL
, start
, end
- start
+ 1);
5318 clear_extent_bit(io_tree
, start
, end
,
5319 EXTENT_LOCKED
| EXTENT_DIRTY
|
5320 EXTENT_DELALLOC
| EXTENT_DO_ACCOUNTING
|
5321 EXTENT_DEFRAG
, 1, 1, &cached_state
);
5324 spin_lock(&io_tree
->lock
);
5326 spin_unlock(&io_tree
->lock
);
5329 static struct btrfs_trans_handle
*evict_refill_and_join(struct btrfs_root
*root
,
5330 struct btrfs_block_rsv
*rsv
)
5332 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
5333 struct btrfs_block_rsv
*global_rsv
= &fs_info
->global_block_rsv
;
5334 struct btrfs_trans_handle
*trans
;
5335 u64 delayed_refs_extra
= btrfs_calc_insert_metadata_size(fs_info
, 1);
5339 * Eviction should be taking place at some place safe because of our
5340 * delayed iputs. However the normal flushing code will run delayed
5341 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5343 * We reserve the delayed_refs_extra here again because we can't use
5344 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5345 * above. We reserve our extra bit here because we generate a ton of
5346 * delayed refs activity by truncating.
5348 * If we cannot make our reservation we'll attempt to steal from the
5349 * global reserve, because we really want to be able to free up space.
5351 ret
= btrfs_block_rsv_refill(root
, rsv
, rsv
->size
+ delayed_refs_extra
,
5352 BTRFS_RESERVE_FLUSH_EVICT
);
5355 * Try to steal from the global reserve if there is space for
5358 if (btrfs_check_space_for_delayed_refs(fs_info
) ||
5359 btrfs_block_rsv_migrate(global_rsv
, rsv
, rsv
->size
, 0)) {
5361 "could not allocate space for delete; will truncate on mount");
5362 return ERR_PTR(-ENOSPC
);
5364 delayed_refs_extra
= 0;
5367 trans
= btrfs_join_transaction(root
);
5371 if (delayed_refs_extra
) {
5372 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
5373 trans
->bytes_reserved
= delayed_refs_extra
;
5374 btrfs_block_rsv_migrate(rsv
, trans
->block_rsv
,
5375 delayed_refs_extra
, 1);
5380 void btrfs_evict_inode(struct inode
*inode
)
5382 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
5383 struct btrfs_trans_handle
*trans
;
5384 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5385 struct btrfs_block_rsv
*rsv
;
5388 trace_btrfs_inode_evict(inode
);
5395 evict_inode_truncate_pages(inode
);
5397 if (inode
->i_nlink
&&
5398 ((btrfs_root_refs(&root
->root_item
) != 0 &&
5399 root
->root_key
.objectid
!= BTRFS_ROOT_TREE_OBJECTID
) ||
5400 btrfs_is_free_space_inode(BTRFS_I(inode
))))
5403 if (is_bad_inode(inode
))
5406 btrfs_free_io_failure_record(BTRFS_I(inode
), 0, (u64
)-1);
5408 if (test_bit(BTRFS_FS_LOG_RECOVERING
, &fs_info
->flags
))
5411 if (inode
->i_nlink
> 0) {
5412 BUG_ON(btrfs_root_refs(&root
->root_item
) != 0 &&
5413 root
->root_key
.objectid
!= BTRFS_ROOT_TREE_OBJECTID
);
5417 ret
= btrfs_commit_inode_delayed_inode(BTRFS_I(inode
));
5421 rsv
= btrfs_alloc_block_rsv(fs_info
, BTRFS_BLOCK_RSV_TEMP
);
5424 rsv
->size
= btrfs_calc_metadata_size(fs_info
, 1);
5427 btrfs_i_size_write(BTRFS_I(inode
), 0);
5430 trans
= evict_refill_and_join(root
, rsv
);
5434 trans
->block_rsv
= rsv
;
5436 ret
= btrfs_truncate_inode_items(trans
, root
, inode
, 0, 0);
5437 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
5438 btrfs_end_transaction(trans
);
5439 btrfs_btree_balance_dirty(fs_info
);
5440 if (ret
&& ret
!= -ENOSPC
&& ret
!= -EAGAIN
)
5447 * Errors here aren't a big deal, it just means we leave orphan items in
5448 * the tree. They will be cleaned up on the next mount. If the inode
5449 * number gets reused, cleanup deletes the orphan item without doing
5450 * anything, and unlink reuses the existing orphan item.
5452 * If it turns out that we are dropping too many of these, we might want
5453 * to add a mechanism for retrying these after a commit.
5455 trans
= evict_refill_and_join(root
, rsv
);
5456 if (!IS_ERR(trans
)) {
5457 trans
->block_rsv
= rsv
;
5458 btrfs_orphan_del(trans
, BTRFS_I(inode
));
5459 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
5460 btrfs_end_transaction(trans
);
5463 if (!(root
== fs_info
->tree_root
||
5464 root
->root_key
.objectid
== BTRFS_TREE_RELOC_OBJECTID
))
5465 btrfs_return_ino(root
, btrfs_ino(BTRFS_I(inode
)));
5468 btrfs_free_block_rsv(fs_info
, rsv
);
5471 * If we didn't successfully delete, the orphan item will still be in
5472 * the tree and we'll retry on the next mount. Again, we might also want
5473 * to retry these periodically in the future.
5475 btrfs_remove_delayed_node(BTRFS_I(inode
));
5480 * Return the key found in the dir entry in the location pointer, fill @type
5481 * with BTRFS_FT_*, and return 0.
5483 * If no dir entries were found, returns -ENOENT.
5484 * If found a corrupted location in dir entry, returns -EUCLEAN.
5486 static int btrfs_inode_by_name(struct inode
*dir
, struct dentry
*dentry
,
5487 struct btrfs_key
*location
, u8
*type
)
5489 const char *name
= dentry
->d_name
.name
;
5490 int namelen
= dentry
->d_name
.len
;
5491 struct btrfs_dir_item
*di
;
5492 struct btrfs_path
*path
;
5493 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
5496 path
= btrfs_alloc_path();
5500 di
= btrfs_lookup_dir_item(NULL
, root
, path
, btrfs_ino(BTRFS_I(dir
)),
5502 if (IS_ERR_OR_NULL(di
)) {
5503 ret
= di
? PTR_ERR(di
) : -ENOENT
;
5507 btrfs_dir_item_key_to_cpu(path
->nodes
[0], di
, location
);
5508 if (location
->type
!= BTRFS_INODE_ITEM_KEY
&&
5509 location
->type
!= BTRFS_ROOT_ITEM_KEY
) {
5511 btrfs_warn(root
->fs_info
,
5512 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5513 __func__
, name
, btrfs_ino(BTRFS_I(dir
)),
5514 location
->objectid
, location
->type
, location
->offset
);
5517 *type
= btrfs_dir_type(path
->nodes
[0], di
);
5519 btrfs_free_path(path
);
5524 * when we hit a tree root in a directory, the btrfs part of the inode
5525 * needs to be changed to reflect the root directory of the tree root. This
5526 * is kind of like crossing a mount point.
5528 static int fixup_tree_root_location(struct btrfs_fs_info
*fs_info
,
5530 struct dentry
*dentry
,
5531 struct btrfs_key
*location
,
5532 struct btrfs_root
**sub_root
)
5534 struct btrfs_path
*path
;
5535 struct btrfs_root
*new_root
;
5536 struct btrfs_root_ref
*ref
;
5537 struct extent_buffer
*leaf
;
5538 struct btrfs_key key
;
5542 path
= btrfs_alloc_path();
5549 key
.objectid
= BTRFS_I(dir
)->root
->root_key
.objectid
;
5550 key
.type
= BTRFS_ROOT_REF_KEY
;
5551 key
.offset
= location
->objectid
;
5553 ret
= btrfs_search_slot(NULL
, fs_info
->tree_root
, &key
, path
, 0, 0);
5560 leaf
= path
->nodes
[0];
5561 ref
= btrfs_item_ptr(leaf
, path
->slots
[0], struct btrfs_root_ref
);
5562 if (btrfs_root_ref_dirid(leaf
, ref
) != btrfs_ino(BTRFS_I(dir
)) ||
5563 btrfs_root_ref_name_len(leaf
, ref
) != dentry
->d_name
.len
)
5566 ret
= memcmp_extent_buffer(leaf
, dentry
->d_name
.name
,
5567 (unsigned long)(ref
+ 1),
5568 dentry
->d_name
.len
);
5572 btrfs_release_path(path
);
5574 new_root
= btrfs_read_fs_root_no_name(fs_info
, location
);
5575 if (IS_ERR(new_root
)) {
5576 err
= PTR_ERR(new_root
);
5580 *sub_root
= new_root
;
5581 location
->objectid
= btrfs_root_dirid(&new_root
->root_item
);
5582 location
->type
= BTRFS_INODE_ITEM_KEY
;
5583 location
->offset
= 0;
5586 btrfs_free_path(path
);
5590 static void inode_tree_add(struct inode
*inode
)
5592 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5593 struct btrfs_inode
*entry
;
5595 struct rb_node
*parent
;
5596 struct rb_node
*new = &BTRFS_I(inode
)->rb_node
;
5597 u64 ino
= btrfs_ino(BTRFS_I(inode
));
5599 if (inode_unhashed(inode
))
5602 spin_lock(&root
->inode_lock
);
5603 p
= &root
->inode_tree
.rb_node
;
5606 entry
= rb_entry(parent
, struct btrfs_inode
, rb_node
);
5608 if (ino
< btrfs_ino(entry
))
5609 p
= &parent
->rb_left
;
5610 else if (ino
> btrfs_ino(entry
))
5611 p
= &parent
->rb_right
;
5613 WARN_ON(!(entry
->vfs_inode
.i_state
&
5614 (I_WILL_FREE
| I_FREEING
)));
5615 rb_replace_node(parent
, new, &root
->inode_tree
);
5616 RB_CLEAR_NODE(parent
);
5617 spin_unlock(&root
->inode_lock
);
5621 rb_link_node(new, parent
, p
);
5622 rb_insert_color(new, &root
->inode_tree
);
5623 spin_unlock(&root
->inode_lock
);
5626 static void inode_tree_del(struct inode
*inode
)
5628 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
5629 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5632 spin_lock(&root
->inode_lock
);
5633 if (!RB_EMPTY_NODE(&BTRFS_I(inode
)->rb_node
)) {
5634 rb_erase(&BTRFS_I(inode
)->rb_node
, &root
->inode_tree
);
5635 RB_CLEAR_NODE(&BTRFS_I(inode
)->rb_node
);
5636 empty
= RB_EMPTY_ROOT(&root
->inode_tree
);
5638 spin_unlock(&root
->inode_lock
);
5640 if (empty
&& btrfs_root_refs(&root
->root_item
) == 0) {
5641 synchronize_srcu(&fs_info
->subvol_srcu
);
5642 spin_lock(&root
->inode_lock
);
5643 empty
= RB_EMPTY_ROOT(&root
->inode_tree
);
5644 spin_unlock(&root
->inode_lock
);
5646 btrfs_add_dead_root(root
);
5651 static int btrfs_init_locked_inode(struct inode
*inode
, void *p
)
5653 struct btrfs_iget_args
*args
= p
;
5654 inode
->i_ino
= args
->location
->objectid
;
5655 memcpy(&BTRFS_I(inode
)->location
, args
->location
,
5656 sizeof(*args
->location
));
5657 BTRFS_I(inode
)->root
= args
->root
;
5661 static int btrfs_find_actor(struct inode
*inode
, void *opaque
)
5663 struct btrfs_iget_args
*args
= opaque
;
5664 return args
->location
->objectid
== BTRFS_I(inode
)->location
.objectid
&&
5665 args
->root
== BTRFS_I(inode
)->root
;
5668 static struct inode
*btrfs_iget_locked(struct super_block
*s
,
5669 struct btrfs_key
*location
,
5670 struct btrfs_root
*root
)
5672 struct inode
*inode
;
5673 struct btrfs_iget_args args
;
5674 unsigned long hashval
= btrfs_inode_hash(location
->objectid
, root
);
5676 args
.location
= location
;
5679 inode
= iget5_locked(s
, hashval
, btrfs_find_actor
,
5680 btrfs_init_locked_inode
,
5685 /* Get an inode object given its location and corresponding root.
5686 * Returns in *is_new if the inode was read from disk
5688 struct inode
*btrfs_iget_path(struct super_block
*s
, struct btrfs_key
*location
,
5689 struct btrfs_root
*root
, int *new,
5690 struct btrfs_path
*path
)
5692 struct inode
*inode
;
5694 inode
= btrfs_iget_locked(s
, location
, root
);
5696 return ERR_PTR(-ENOMEM
);
5698 if (inode
->i_state
& I_NEW
) {
5701 ret
= btrfs_read_locked_inode(inode
, path
);
5703 inode_tree_add(inode
);
5704 unlock_new_inode(inode
);
5710 * ret > 0 can come from btrfs_search_slot called by
5711 * btrfs_read_locked_inode, this means the inode item
5716 inode
= ERR_PTR(ret
);
5723 struct inode
*btrfs_iget(struct super_block
*s
, struct btrfs_key
*location
,
5724 struct btrfs_root
*root
, int *new)
5726 return btrfs_iget_path(s
, location
, root
, new, NULL
);
5729 static struct inode
*new_simple_dir(struct super_block
*s
,
5730 struct btrfs_key
*key
,
5731 struct btrfs_root
*root
)
5733 struct inode
*inode
= new_inode(s
);
5736 return ERR_PTR(-ENOMEM
);
5738 BTRFS_I(inode
)->root
= root
;
5739 memcpy(&BTRFS_I(inode
)->location
, key
, sizeof(*key
));
5740 set_bit(BTRFS_INODE_DUMMY
, &BTRFS_I(inode
)->runtime_flags
);
5742 inode
->i_ino
= BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
;
5743 inode
->i_op
= &btrfs_dir_ro_inode_operations
;
5744 inode
->i_opflags
&= ~IOP_XATTR
;
5745 inode
->i_fop
= &simple_dir_operations
;
5746 inode
->i_mode
= S_IFDIR
| S_IRUGO
| S_IWUSR
| S_IXUGO
;
5747 inode
->i_mtime
= current_time(inode
);
5748 inode
->i_atime
= inode
->i_mtime
;
5749 inode
->i_ctime
= inode
->i_mtime
;
5750 BTRFS_I(inode
)->i_otime
= inode
->i_mtime
;
5755 static inline u8
btrfs_inode_type(struct inode
*inode
)
5758 * Compile-time asserts that generic FT_* types still match
5761 BUILD_BUG_ON(BTRFS_FT_UNKNOWN
!= FT_UNKNOWN
);
5762 BUILD_BUG_ON(BTRFS_FT_REG_FILE
!= FT_REG_FILE
);
5763 BUILD_BUG_ON(BTRFS_FT_DIR
!= FT_DIR
);
5764 BUILD_BUG_ON(BTRFS_FT_CHRDEV
!= FT_CHRDEV
);
5765 BUILD_BUG_ON(BTRFS_FT_BLKDEV
!= FT_BLKDEV
);
5766 BUILD_BUG_ON(BTRFS_FT_FIFO
!= FT_FIFO
);
5767 BUILD_BUG_ON(BTRFS_FT_SOCK
!= FT_SOCK
);
5768 BUILD_BUG_ON(BTRFS_FT_SYMLINK
!= FT_SYMLINK
);
5770 return fs_umode_to_ftype(inode
->i_mode
);
5773 struct inode
*btrfs_lookup_dentry(struct inode
*dir
, struct dentry
*dentry
)
5775 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
5776 struct inode
*inode
;
5777 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
5778 struct btrfs_root
*sub_root
= root
;
5779 struct btrfs_key location
;
5784 if (dentry
->d_name
.len
> BTRFS_NAME_LEN
)
5785 return ERR_PTR(-ENAMETOOLONG
);
5787 ret
= btrfs_inode_by_name(dir
, dentry
, &location
, &di_type
);
5789 return ERR_PTR(ret
);
5791 if (location
.type
== BTRFS_INODE_ITEM_KEY
) {
5792 inode
= btrfs_iget(dir
->i_sb
, &location
, root
, NULL
);
5796 /* Do extra check against inode mode with di_type */
5797 if (btrfs_inode_type(inode
) != di_type
) {
5799 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5800 inode
->i_mode
, btrfs_inode_type(inode
),
5803 return ERR_PTR(-EUCLEAN
);
5808 index
= srcu_read_lock(&fs_info
->subvol_srcu
);
5809 ret
= fixup_tree_root_location(fs_info
, dir
, dentry
,
5810 &location
, &sub_root
);
5813 inode
= ERR_PTR(ret
);
5815 inode
= new_simple_dir(dir
->i_sb
, &location
, sub_root
);
5817 inode
= btrfs_iget(dir
->i_sb
, &location
, sub_root
, NULL
);
5819 srcu_read_unlock(&fs_info
->subvol_srcu
, index
);
5821 if (!IS_ERR(inode
) && root
!= sub_root
) {
5822 down_read(&fs_info
->cleanup_work_sem
);
5823 if (!sb_rdonly(inode
->i_sb
))
5824 ret
= btrfs_orphan_cleanup(sub_root
);
5825 up_read(&fs_info
->cleanup_work_sem
);
5828 inode
= ERR_PTR(ret
);
5835 static int btrfs_dentry_delete(const struct dentry
*dentry
)
5837 struct btrfs_root
*root
;
5838 struct inode
*inode
= d_inode(dentry
);
5840 if (!inode
&& !IS_ROOT(dentry
))
5841 inode
= d_inode(dentry
->d_parent
);
5844 root
= BTRFS_I(inode
)->root
;
5845 if (btrfs_root_refs(&root
->root_item
) == 0)
5848 if (btrfs_ino(BTRFS_I(inode
)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)
5854 static struct dentry
*btrfs_lookup(struct inode
*dir
, struct dentry
*dentry
,
5857 struct inode
*inode
= btrfs_lookup_dentry(dir
, dentry
);
5859 if (inode
== ERR_PTR(-ENOENT
))
5861 return d_splice_alias(inode
, dentry
);
5865 * All this infrastructure exists because dir_emit can fault, and we are holding
5866 * the tree lock when doing readdir. For now just allocate a buffer and copy
5867 * our information into that, and then dir_emit from the buffer. This is
5868 * similar to what NFS does, only we don't keep the buffer around in pagecache
5869 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5870 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5873 static int btrfs_opendir(struct inode
*inode
, struct file
*file
)
5875 struct btrfs_file_private
*private;
5877 private = kzalloc(sizeof(struct btrfs_file_private
), GFP_KERNEL
);
5880 private->filldir_buf
= kzalloc(PAGE_SIZE
, GFP_KERNEL
);
5881 if (!private->filldir_buf
) {
5885 file
->private_data
= private;
5896 static int btrfs_filldir(void *addr
, int entries
, struct dir_context
*ctx
)
5899 struct dir_entry
*entry
= addr
;
5900 char *name
= (char *)(entry
+ 1);
5902 ctx
->pos
= get_unaligned(&entry
->offset
);
5903 if (!dir_emit(ctx
, name
, get_unaligned(&entry
->name_len
),
5904 get_unaligned(&entry
->ino
),
5905 get_unaligned(&entry
->type
)))
5907 addr
+= sizeof(struct dir_entry
) +
5908 get_unaligned(&entry
->name_len
);
5914 static int btrfs_real_readdir(struct file
*file
, struct dir_context
*ctx
)
5916 struct inode
*inode
= file_inode(file
);
5917 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
5918 struct btrfs_file_private
*private = file
->private_data
;
5919 struct btrfs_dir_item
*di
;
5920 struct btrfs_key key
;
5921 struct btrfs_key found_key
;
5922 struct btrfs_path
*path
;
5924 struct list_head ins_list
;
5925 struct list_head del_list
;
5927 struct extent_buffer
*leaf
;
5934 struct btrfs_key location
;
5936 if (!dir_emit_dots(file
, ctx
))
5939 path
= btrfs_alloc_path();
5943 addr
= private->filldir_buf
;
5944 path
->reada
= READA_FORWARD
;
5946 INIT_LIST_HEAD(&ins_list
);
5947 INIT_LIST_HEAD(&del_list
);
5948 put
= btrfs_readdir_get_delayed_items(inode
, &ins_list
, &del_list
);
5951 key
.type
= BTRFS_DIR_INDEX_KEY
;
5952 key
.offset
= ctx
->pos
;
5953 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
5955 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
5960 struct dir_entry
*entry
;
5962 leaf
= path
->nodes
[0];
5963 slot
= path
->slots
[0];
5964 if (slot
>= btrfs_header_nritems(leaf
)) {
5965 ret
= btrfs_next_leaf(root
, path
);
5973 btrfs_item_key_to_cpu(leaf
, &found_key
, slot
);
5975 if (found_key
.objectid
!= key
.objectid
)
5977 if (found_key
.type
!= BTRFS_DIR_INDEX_KEY
)
5979 if (found_key
.offset
< ctx
->pos
)
5981 if (btrfs_should_delete_dir_index(&del_list
, found_key
.offset
))
5983 di
= btrfs_item_ptr(leaf
, slot
, struct btrfs_dir_item
);
5984 name_len
= btrfs_dir_name_len(leaf
, di
);
5985 if ((total_len
+ sizeof(struct dir_entry
) + name_len
) >=
5987 btrfs_release_path(path
);
5988 ret
= btrfs_filldir(private->filldir_buf
, entries
, ctx
);
5991 addr
= private->filldir_buf
;
5998 put_unaligned(name_len
, &entry
->name_len
);
5999 name_ptr
= (char *)(entry
+ 1);
6000 read_extent_buffer(leaf
, name_ptr
, (unsigned long)(di
+ 1),
6002 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf
, di
)),
6004 btrfs_dir_item_key_to_cpu(leaf
, di
, &location
);
6005 put_unaligned(location
.objectid
, &entry
->ino
);
6006 put_unaligned(found_key
.offset
, &entry
->offset
);
6008 addr
+= sizeof(struct dir_entry
) + name_len
;
6009 total_len
+= sizeof(struct dir_entry
) + name_len
;
6013 btrfs_release_path(path
);
6015 ret
= btrfs_filldir(private->filldir_buf
, entries
, ctx
);
6019 ret
= btrfs_readdir_delayed_dir_index(ctx
, &ins_list
);
6024 * Stop new entries from being returned after we return the last
6027 * New directory entries are assigned a strictly increasing
6028 * offset. This means that new entries created during readdir
6029 * are *guaranteed* to be seen in the future by that readdir.
6030 * This has broken buggy programs which operate on names as
6031 * they're returned by readdir. Until we re-use freed offsets
6032 * we have this hack to stop new entries from being returned
6033 * under the assumption that they'll never reach this huge
6036 * This is being careful not to overflow 32bit loff_t unless the
6037 * last entry requires it because doing so has broken 32bit apps
6040 if (ctx
->pos
>= INT_MAX
)
6041 ctx
->pos
= LLONG_MAX
;
6048 btrfs_readdir_put_delayed_items(inode
, &ins_list
, &del_list
);
6049 btrfs_free_path(path
);
6054 * This is somewhat expensive, updating the tree every time the
6055 * inode changes. But, it is most likely to find the inode in cache.
6056 * FIXME, needs more benchmarking...there are no reasons other than performance
6057 * to keep or drop this code.
6059 static int btrfs_dirty_inode(struct inode
*inode
)
6061 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
6062 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
6063 struct btrfs_trans_handle
*trans
;
6066 if (test_bit(BTRFS_INODE_DUMMY
, &BTRFS_I(inode
)->runtime_flags
))
6069 trans
= btrfs_join_transaction(root
);
6071 return PTR_ERR(trans
);
6073 ret
= btrfs_update_inode(trans
, root
, inode
);
6074 if (ret
&& ret
== -ENOSPC
) {
6075 /* whoops, lets try again with the full transaction */
6076 btrfs_end_transaction(trans
);
6077 trans
= btrfs_start_transaction(root
, 1);
6079 return PTR_ERR(trans
);
6081 ret
= btrfs_update_inode(trans
, root
, inode
);
6083 btrfs_end_transaction(trans
);
6084 if (BTRFS_I(inode
)->delayed_node
)
6085 btrfs_balance_delayed_items(fs_info
);
6091 * This is a copy of file_update_time. We need this so we can return error on
6092 * ENOSPC for updating the inode in the case of file write and mmap writes.
6094 static int btrfs_update_time(struct inode
*inode
, struct timespec64
*now
,
6097 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
6098 bool dirty
= flags
& ~S_VERSION
;
6100 if (btrfs_root_readonly(root
))
6103 if (flags
& S_VERSION
)
6104 dirty
|= inode_maybe_inc_iversion(inode
, dirty
);
6105 if (flags
& S_CTIME
)
6106 inode
->i_ctime
= *now
;
6107 if (flags
& S_MTIME
)
6108 inode
->i_mtime
= *now
;
6109 if (flags
& S_ATIME
)
6110 inode
->i_atime
= *now
;
6111 return dirty
? btrfs_dirty_inode(inode
) : 0;
6115 * find the highest existing sequence number in a directory
6116 * and then set the in-memory index_cnt variable to reflect
6117 * free sequence numbers
6119 static int btrfs_set_inode_index_count(struct btrfs_inode
*inode
)
6121 struct btrfs_root
*root
= inode
->root
;
6122 struct btrfs_key key
, found_key
;
6123 struct btrfs_path
*path
;
6124 struct extent_buffer
*leaf
;
6127 key
.objectid
= btrfs_ino(inode
);
6128 key
.type
= BTRFS_DIR_INDEX_KEY
;
6129 key
.offset
= (u64
)-1;
6131 path
= btrfs_alloc_path();
6135 ret
= btrfs_search_slot(NULL
, root
, &key
, path
, 0, 0);
6138 /* FIXME: we should be able to handle this */
6144 * MAGIC NUMBER EXPLANATION:
6145 * since we search a directory based on f_pos we have to start at 2
6146 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6147 * else has to start at 2
6149 if (path
->slots
[0] == 0) {
6150 inode
->index_cnt
= 2;
6156 leaf
= path
->nodes
[0];
6157 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
6159 if (found_key
.objectid
!= btrfs_ino(inode
) ||
6160 found_key
.type
!= BTRFS_DIR_INDEX_KEY
) {
6161 inode
->index_cnt
= 2;
6165 inode
->index_cnt
= found_key
.offset
+ 1;
6167 btrfs_free_path(path
);
6172 * helper to find a free sequence number in a given directory. This current
6173 * code is very simple, later versions will do smarter things in the btree
6175 int btrfs_set_inode_index(struct btrfs_inode
*dir
, u64
*index
)
6179 if (dir
->index_cnt
== (u64
)-1) {
6180 ret
= btrfs_inode_delayed_dir_index_count(dir
);
6182 ret
= btrfs_set_inode_index_count(dir
);
6188 *index
= dir
->index_cnt
;
6194 static int btrfs_insert_inode_locked(struct inode
*inode
)
6196 struct btrfs_iget_args args
;
6197 args
.location
= &BTRFS_I(inode
)->location
;
6198 args
.root
= BTRFS_I(inode
)->root
;
6200 return insert_inode_locked4(inode
,
6201 btrfs_inode_hash(inode
->i_ino
, BTRFS_I(inode
)->root
),
6202 btrfs_find_actor
, &args
);
6206 * Inherit flags from the parent inode.
6208 * Currently only the compression flags and the cow flags are inherited.
6210 static void btrfs_inherit_iflags(struct inode
*inode
, struct inode
*dir
)
6217 flags
= BTRFS_I(dir
)->flags
;
6219 if (flags
& BTRFS_INODE_NOCOMPRESS
) {
6220 BTRFS_I(inode
)->flags
&= ~BTRFS_INODE_COMPRESS
;
6221 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NOCOMPRESS
;
6222 } else if (flags
& BTRFS_INODE_COMPRESS
) {
6223 BTRFS_I(inode
)->flags
&= ~BTRFS_INODE_NOCOMPRESS
;
6224 BTRFS_I(inode
)->flags
|= BTRFS_INODE_COMPRESS
;
6227 if (flags
& BTRFS_INODE_NODATACOW
) {
6228 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NODATACOW
;
6229 if (S_ISREG(inode
->i_mode
))
6230 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NODATASUM
;
6233 btrfs_sync_inode_flags_to_i_flags(inode
);
6236 static struct inode
*btrfs_new_inode(struct btrfs_trans_handle
*trans
,
6237 struct btrfs_root
*root
,
6239 const char *name
, int name_len
,
6240 u64 ref_objectid
, u64 objectid
,
6241 umode_t mode
, u64
*index
)
6243 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
6244 struct inode
*inode
;
6245 struct btrfs_inode_item
*inode_item
;
6246 struct btrfs_key
*location
;
6247 struct btrfs_path
*path
;
6248 struct btrfs_inode_ref
*ref
;
6249 struct btrfs_key key
[2];
6251 int nitems
= name
? 2 : 1;
6255 path
= btrfs_alloc_path();
6257 return ERR_PTR(-ENOMEM
);
6259 inode
= new_inode(fs_info
->sb
);
6261 btrfs_free_path(path
);
6262 return ERR_PTR(-ENOMEM
);
6266 * O_TMPFILE, set link count to 0, so that after this point,
6267 * we fill in an inode item with the correct link count.
6270 set_nlink(inode
, 0);
6273 * we have to initialize this early, so we can reclaim the inode
6274 * number if we fail afterwards in this function.
6276 inode
->i_ino
= objectid
;
6279 trace_btrfs_inode_request(dir
);
6281 ret
= btrfs_set_inode_index(BTRFS_I(dir
), index
);
6283 btrfs_free_path(path
);
6285 return ERR_PTR(ret
);
6291 * index_cnt is ignored for everything but a dir,
6292 * btrfs_set_inode_index_count has an explanation for the magic
6295 BTRFS_I(inode
)->index_cnt
= 2;
6296 BTRFS_I(inode
)->dir_index
= *index
;
6297 BTRFS_I(inode
)->root
= root
;
6298 BTRFS_I(inode
)->generation
= trans
->transid
;
6299 inode
->i_generation
= BTRFS_I(inode
)->generation
;
6302 * We could have gotten an inode number from somebody who was fsynced
6303 * and then removed in this same transaction, so let's just set full
6304 * sync since it will be a full sync anyway and this will blow away the
6305 * old info in the log.
6307 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
, &BTRFS_I(inode
)->runtime_flags
);
6309 key
[0].objectid
= objectid
;
6310 key
[0].type
= BTRFS_INODE_ITEM_KEY
;
6313 sizes
[0] = sizeof(struct btrfs_inode_item
);
6317 * Start new inodes with an inode_ref. This is slightly more
6318 * efficient for small numbers of hard links since they will
6319 * be packed into one item. Extended refs will kick in if we
6320 * add more hard links than can fit in the ref item.
6322 key
[1].objectid
= objectid
;
6323 key
[1].type
= BTRFS_INODE_REF_KEY
;
6324 key
[1].offset
= ref_objectid
;
6326 sizes
[1] = name_len
+ sizeof(*ref
);
6329 location
= &BTRFS_I(inode
)->location
;
6330 location
->objectid
= objectid
;
6331 location
->offset
= 0;
6332 location
->type
= BTRFS_INODE_ITEM_KEY
;
6334 ret
= btrfs_insert_inode_locked(inode
);
6340 path
->leave_spinning
= 1;
6341 ret
= btrfs_insert_empty_items(trans
, root
, path
, key
, sizes
, nitems
);
6345 inode_init_owner(inode
, dir
, mode
);
6346 inode_set_bytes(inode
, 0);
6348 inode
->i_mtime
= current_time(inode
);
6349 inode
->i_atime
= inode
->i_mtime
;
6350 inode
->i_ctime
= inode
->i_mtime
;
6351 BTRFS_I(inode
)->i_otime
= inode
->i_mtime
;
6353 inode_item
= btrfs_item_ptr(path
->nodes
[0], path
->slots
[0],
6354 struct btrfs_inode_item
);
6355 memzero_extent_buffer(path
->nodes
[0], (unsigned long)inode_item
,
6356 sizeof(*inode_item
));
6357 fill_inode_item(trans
, path
->nodes
[0], inode_item
, inode
);
6360 ref
= btrfs_item_ptr(path
->nodes
[0], path
->slots
[0] + 1,
6361 struct btrfs_inode_ref
);
6362 btrfs_set_inode_ref_name_len(path
->nodes
[0], ref
, name_len
);
6363 btrfs_set_inode_ref_index(path
->nodes
[0], ref
, *index
);
6364 ptr
= (unsigned long)(ref
+ 1);
6365 write_extent_buffer(path
->nodes
[0], name
, ptr
, name_len
);
6368 btrfs_mark_buffer_dirty(path
->nodes
[0]);
6369 btrfs_free_path(path
);
6371 btrfs_inherit_iflags(inode
, dir
);
6373 if (S_ISREG(mode
)) {
6374 if (btrfs_test_opt(fs_info
, NODATASUM
))
6375 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NODATASUM
;
6376 if (btrfs_test_opt(fs_info
, NODATACOW
))
6377 BTRFS_I(inode
)->flags
|= BTRFS_INODE_NODATACOW
|
6378 BTRFS_INODE_NODATASUM
;
6381 inode_tree_add(inode
);
6383 trace_btrfs_inode_new(inode
);
6384 btrfs_set_inode_last_trans(trans
, inode
);
6386 btrfs_update_root_times(trans
, root
);
6388 ret
= btrfs_inode_inherit_props(trans
, inode
, dir
);
6391 "error inheriting props for ino %llu (root %llu): %d",
6392 btrfs_ino(BTRFS_I(inode
)), root
->root_key
.objectid
, ret
);
6397 discard_new_inode(inode
);
6400 BTRFS_I(dir
)->index_cnt
--;
6401 btrfs_free_path(path
);
6402 return ERR_PTR(ret
);
6406 * utility function to add 'inode' into 'parent_inode' with
6407 * a give name and a given sequence number.
6408 * if 'add_backref' is true, also insert a backref from the
6409 * inode to the parent directory.
6411 int btrfs_add_link(struct btrfs_trans_handle
*trans
,
6412 struct btrfs_inode
*parent_inode
, struct btrfs_inode
*inode
,
6413 const char *name
, int name_len
, int add_backref
, u64 index
)
6416 struct btrfs_key key
;
6417 struct btrfs_root
*root
= parent_inode
->root
;
6418 u64 ino
= btrfs_ino(inode
);
6419 u64 parent_ino
= btrfs_ino(parent_inode
);
6421 if (unlikely(ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
6422 memcpy(&key
, &inode
->root
->root_key
, sizeof(key
));
6425 key
.type
= BTRFS_INODE_ITEM_KEY
;
6429 if (unlikely(ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
6430 ret
= btrfs_add_root_ref(trans
, key
.objectid
,
6431 root
->root_key
.objectid
, parent_ino
,
6432 index
, name
, name_len
);
6433 } else if (add_backref
) {
6434 ret
= btrfs_insert_inode_ref(trans
, root
, name
, name_len
, ino
,
6438 /* Nothing to clean up yet */
6442 ret
= btrfs_insert_dir_item(trans
, name
, name_len
, parent_inode
, &key
,
6443 btrfs_inode_type(&inode
->vfs_inode
), index
);
6444 if (ret
== -EEXIST
|| ret
== -EOVERFLOW
)
6447 btrfs_abort_transaction(trans
, ret
);
6451 btrfs_i_size_write(parent_inode
, parent_inode
->vfs_inode
.i_size
+
6453 inode_inc_iversion(&parent_inode
->vfs_inode
);
6455 * If we are replaying a log tree, we do not want to update the mtime
6456 * and ctime of the parent directory with the current time, since the
6457 * log replay procedure is responsible for setting them to their correct
6458 * values (the ones it had when the fsync was done).
6460 if (!test_bit(BTRFS_FS_LOG_RECOVERING
, &root
->fs_info
->flags
)) {
6461 struct timespec64 now
= current_time(&parent_inode
->vfs_inode
);
6463 parent_inode
->vfs_inode
.i_mtime
= now
;
6464 parent_inode
->vfs_inode
.i_ctime
= now
;
6466 ret
= btrfs_update_inode(trans
, root
, &parent_inode
->vfs_inode
);
6468 btrfs_abort_transaction(trans
, ret
);
6472 if (unlikely(ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
6475 err
= btrfs_del_root_ref(trans
, key
.objectid
,
6476 root
->root_key
.objectid
, parent_ino
,
6477 &local_index
, name
, name_len
);
6479 btrfs_abort_transaction(trans
, err
);
6480 } else if (add_backref
) {
6484 err
= btrfs_del_inode_ref(trans
, root
, name
, name_len
,
6485 ino
, parent_ino
, &local_index
);
6487 btrfs_abort_transaction(trans
, err
);
6490 /* Return the original error code */
6494 static int btrfs_add_nondir(struct btrfs_trans_handle
*trans
,
6495 struct btrfs_inode
*dir
, struct dentry
*dentry
,
6496 struct btrfs_inode
*inode
, int backref
, u64 index
)
6498 int err
= btrfs_add_link(trans
, dir
, inode
,
6499 dentry
->d_name
.name
, dentry
->d_name
.len
,
6506 static int btrfs_mknod(struct inode
*dir
, struct dentry
*dentry
,
6507 umode_t mode
, dev_t rdev
)
6509 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
6510 struct btrfs_trans_handle
*trans
;
6511 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
6512 struct inode
*inode
= NULL
;
6518 * 2 for inode item and ref
6520 * 1 for xattr if selinux is on
6522 trans
= btrfs_start_transaction(root
, 5);
6524 return PTR_ERR(trans
);
6526 err
= btrfs_find_free_ino(root
, &objectid
);
6530 inode
= btrfs_new_inode(trans
, root
, dir
, dentry
->d_name
.name
,
6531 dentry
->d_name
.len
, btrfs_ino(BTRFS_I(dir
)), objectid
,
6533 if (IS_ERR(inode
)) {
6534 err
= PTR_ERR(inode
);
6540 * If the active LSM wants to access the inode during
6541 * d_instantiate it needs these. Smack checks to see
6542 * if the filesystem supports xattrs by looking at the
6545 inode
->i_op
= &btrfs_special_inode_operations
;
6546 init_special_inode(inode
, inode
->i_mode
, rdev
);
6548 err
= btrfs_init_inode_security(trans
, inode
, dir
, &dentry
->d_name
);
6552 err
= btrfs_add_nondir(trans
, BTRFS_I(dir
), dentry
, BTRFS_I(inode
),
6557 btrfs_update_inode(trans
, root
, inode
);
6558 d_instantiate_new(dentry
, inode
);
6561 btrfs_end_transaction(trans
);
6562 btrfs_btree_balance_dirty(fs_info
);
6564 inode_dec_link_count(inode
);
6565 discard_new_inode(inode
);
6570 static int btrfs_create(struct inode
*dir
, struct dentry
*dentry
,
6571 umode_t mode
, bool excl
)
6573 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
6574 struct btrfs_trans_handle
*trans
;
6575 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
6576 struct inode
*inode
= NULL
;
6582 * 2 for inode item and ref
6584 * 1 for xattr if selinux is on
6586 trans
= btrfs_start_transaction(root
, 5);
6588 return PTR_ERR(trans
);
6590 err
= btrfs_find_free_ino(root
, &objectid
);
6594 inode
= btrfs_new_inode(trans
, root
, dir
, dentry
->d_name
.name
,
6595 dentry
->d_name
.len
, btrfs_ino(BTRFS_I(dir
)), objectid
,
6597 if (IS_ERR(inode
)) {
6598 err
= PTR_ERR(inode
);
6603 * If the active LSM wants to access the inode during
6604 * d_instantiate it needs these. Smack checks to see
6605 * if the filesystem supports xattrs by looking at the
6608 inode
->i_fop
= &btrfs_file_operations
;
6609 inode
->i_op
= &btrfs_file_inode_operations
;
6610 inode
->i_mapping
->a_ops
= &btrfs_aops
;
6612 err
= btrfs_init_inode_security(trans
, inode
, dir
, &dentry
->d_name
);
6616 err
= btrfs_update_inode(trans
, root
, inode
);
6620 err
= btrfs_add_nondir(trans
, BTRFS_I(dir
), dentry
, BTRFS_I(inode
),
6625 BTRFS_I(inode
)->io_tree
.ops
= &btrfs_extent_io_ops
;
6626 d_instantiate_new(dentry
, inode
);
6629 btrfs_end_transaction(trans
);
6631 inode_dec_link_count(inode
);
6632 discard_new_inode(inode
);
6634 btrfs_btree_balance_dirty(fs_info
);
6638 static int btrfs_link(struct dentry
*old_dentry
, struct inode
*dir
,
6639 struct dentry
*dentry
)
6641 struct btrfs_trans_handle
*trans
= NULL
;
6642 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
6643 struct inode
*inode
= d_inode(old_dentry
);
6644 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
6649 /* do not allow sys_link's with other subvols of the same device */
6650 if (root
->root_key
.objectid
!= BTRFS_I(inode
)->root
->root_key
.objectid
)
6653 if (inode
->i_nlink
>= BTRFS_LINK_MAX
)
6656 err
= btrfs_set_inode_index(BTRFS_I(dir
), &index
);
6661 * 2 items for inode and inode ref
6662 * 2 items for dir items
6663 * 1 item for parent inode
6664 * 1 item for orphan item deletion if O_TMPFILE
6666 trans
= btrfs_start_transaction(root
, inode
->i_nlink
? 5 : 6);
6667 if (IS_ERR(trans
)) {
6668 err
= PTR_ERR(trans
);
6673 /* There are several dir indexes for this inode, clear the cache. */
6674 BTRFS_I(inode
)->dir_index
= 0ULL;
6676 inode_inc_iversion(inode
);
6677 inode
->i_ctime
= current_time(inode
);
6679 set_bit(BTRFS_INODE_COPY_EVERYTHING
, &BTRFS_I(inode
)->runtime_flags
);
6681 err
= btrfs_add_nondir(trans
, BTRFS_I(dir
), dentry
, BTRFS_I(inode
),
6687 struct dentry
*parent
= dentry
->d_parent
;
6690 err
= btrfs_update_inode(trans
, root
, inode
);
6693 if (inode
->i_nlink
== 1) {
6695 * If new hard link count is 1, it's a file created
6696 * with open(2) O_TMPFILE flag.
6698 err
= btrfs_orphan_del(trans
, BTRFS_I(inode
));
6702 d_instantiate(dentry
, inode
);
6703 ret
= btrfs_log_new_name(trans
, BTRFS_I(inode
), NULL
, parent
,
6705 if (ret
== BTRFS_NEED_TRANS_COMMIT
) {
6706 err
= btrfs_commit_transaction(trans
);
6713 btrfs_end_transaction(trans
);
6715 inode_dec_link_count(inode
);
6718 btrfs_btree_balance_dirty(fs_info
);
6722 static int btrfs_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
6724 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
6725 struct inode
*inode
= NULL
;
6726 struct btrfs_trans_handle
*trans
;
6727 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
6733 * 2 items for inode and ref
6734 * 2 items for dir items
6735 * 1 for xattr if selinux is on
6737 trans
= btrfs_start_transaction(root
, 5);
6739 return PTR_ERR(trans
);
6741 err
= btrfs_find_free_ino(root
, &objectid
);
6745 inode
= btrfs_new_inode(trans
, root
, dir
, dentry
->d_name
.name
,
6746 dentry
->d_name
.len
, btrfs_ino(BTRFS_I(dir
)), objectid
,
6747 S_IFDIR
| mode
, &index
);
6748 if (IS_ERR(inode
)) {
6749 err
= PTR_ERR(inode
);
6754 /* these must be set before we unlock the inode */
6755 inode
->i_op
= &btrfs_dir_inode_operations
;
6756 inode
->i_fop
= &btrfs_dir_file_operations
;
6758 err
= btrfs_init_inode_security(trans
, inode
, dir
, &dentry
->d_name
);
6762 btrfs_i_size_write(BTRFS_I(inode
), 0);
6763 err
= btrfs_update_inode(trans
, root
, inode
);
6767 err
= btrfs_add_link(trans
, BTRFS_I(dir
), BTRFS_I(inode
),
6768 dentry
->d_name
.name
,
6769 dentry
->d_name
.len
, 0, index
);
6773 d_instantiate_new(dentry
, inode
);
6776 btrfs_end_transaction(trans
);
6778 inode_dec_link_count(inode
);
6779 discard_new_inode(inode
);
6781 btrfs_btree_balance_dirty(fs_info
);
6785 static noinline
int uncompress_inline(struct btrfs_path
*path
,
6787 size_t pg_offset
, u64 extent_offset
,
6788 struct btrfs_file_extent_item
*item
)
6791 struct extent_buffer
*leaf
= path
->nodes
[0];
6794 unsigned long inline_size
;
6798 WARN_ON(pg_offset
!= 0);
6799 compress_type
= btrfs_file_extent_compression(leaf
, item
);
6800 max_size
= btrfs_file_extent_ram_bytes(leaf
, item
);
6801 inline_size
= btrfs_file_extent_inline_item_len(leaf
,
6802 btrfs_item_nr(path
->slots
[0]));
6803 tmp
= kmalloc(inline_size
, GFP_NOFS
);
6806 ptr
= btrfs_file_extent_inline_start(item
);
6808 read_extent_buffer(leaf
, tmp
, ptr
, inline_size
);
6810 max_size
= min_t(unsigned long, PAGE_SIZE
, max_size
);
6811 ret
= btrfs_decompress(compress_type
, tmp
, page
,
6812 extent_offset
, inline_size
, max_size
);
6815 * decompression code contains a memset to fill in any space between the end
6816 * of the uncompressed data and the end of max_size in case the decompressed
6817 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6818 * the end of an inline extent and the beginning of the next block, so we
6819 * cover that region here.
6822 if (max_size
+ pg_offset
< PAGE_SIZE
) {
6823 char *map
= kmap(page
);
6824 memset(map
+ pg_offset
+ max_size
, 0, PAGE_SIZE
- max_size
- pg_offset
);
6832 * a bit scary, this does extent mapping from logical file offset to the disk.
6833 * the ugly parts come from merging extents from the disk with the in-ram
6834 * representation. This gets more complex because of the data=ordered code,
6835 * where the in-ram extents might be locked pending data=ordered completion.
6837 * This also copies inline extents directly into the page.
6839 struct extent_map
*btrfs_get_extent(struct btrfs_inode
*inode
,
6841 size_t pg_offset
, u64 start
, u64 len
,
6844 struct btrfs_fs_info
*fs_info
= inode
->root
->fs_info
;
6847 u64 extent_start
= 0;
6849 u64 objectid
= btrfs_ino(inode
);
6850 int extent_type
= -1;
6851 struct btrfs_path
*path
= NULL
;
6852 struct btrfs_root
*root
= inode
->root
;
6853 struct btrfs_file_extent_item
*item
;
6854 struct extent_buffer
*leaf
;
6855 struct btrfs_key found_key
;
6856 struct extent_map
*em
= NULL
;
6857 struct extent_map_tree
*em_tree
= &inode
->extent_tree
;
6858 struct extent_io_tree
*io_tree
= &inode
->io_tree
;
6859 const bool new_inline
= !page
|| create
;
6861 read_lock(&em_tree
->lock
);
6862 em
= lookup_extent_mapping(em_tree
, start
, len
);
6864 em
->bdev
= fs_info
->fs_devices
->latest_bdev
;
6865 read_unlock(&em_tree
->lock
);
6868 if (em
->start
> start
|| em
->start
+ em
->len
<= start
)
6869 free_extent_map(em
);
6870 else if (em
->block_start
== EXTENT_MAP_INLINE
&& page
)
6871 free_extent_map(em
);
6875 em
= alloc_extent_map();
6880 em
->bdev
= fs_info
->fs_devices
->latest_bdev
;
6881 em
->start
= EXTENT_MAP_HOLE
;
6882 em
->orig_start
= EXTENT_MAP_HOLE
;
6884 em
->block_len
= (u64
)-1;
6886 path
= btrfs_alloc_path();
6892 /* Chances are we'll be called again, so go ahead and do readahead */
6893 path
->reada
= READA_FORWARD
;
6896 * Unless we're going to uncompress the inline extent, no sleep would
6899 path
->leave_spinning
= 1;
6901 ret
= btrfs_lookup_file_extent(NULL
, root
, path
, objectid
, start
, 0);
6905 } else if (ret
> 0) {
6906 if (path
->slots
[0] == 0)
6911 leaf
= path
->nodes
[0];
6912 item
= btrfs_item_ptr(leaf
, path
->slots
[0],
6913 struct btrfs_file_extent_item
);
6914 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
6915 if (found_key
.objectid
!= objectid
||
6916 found_key
.type
!= BTRFS_EXTENT_DATA_KEY
) {
6918 * If we backup past the first extent we want to move forward
6919 * and see if there is an extent in front of us, otherwise we'll
6920 * say there is a hole for our whole search range which can
6927 extent_type
= btrfs_file_extent_type(leaf
, item
);
6928 extent_start
= found_key
.offset
;
6929 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
6930 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
6931 /* Only regular file could have regular/prealloc extent */
6932 if (!S_ISREG(inode
->vfs_inode
.i_mode
)) {
6935 "regular/prealloc extent found for non-regular inode %llu",
6939 extent_end
= extent_start
+
6940 btrfs_file_extent_num_bytes(leaf
, item
);
6942 trace_btrfs_get_extent_show_fi_regular(inode
, leaf
, item
,
6944 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
6947 size
= btrfs_file_extent_ram_bytes(leaf
, item
);
6948 extent_end
= ALIGN(extent_start
+ size
,
6949 fs_info
->sectorsize
);
6951 trace_btrfs_get_extent_show_fi_inline(inode
, leaf
, item
,
6956 if (start
>= extent_end
) {
6958 if (path
->slots
[0] >= btrfs_header_nritems(leaf
)) {
6959 ret
= btrfs_next_leaf(root
, path
);
6963 } else if (ret
> 0) {
6966 leaf
= path
->nodes
[0];
6968 btrfs_item_key_to_cpu(leaf
, &found_key
, path
->slots
[0]);
6969 if (found_key
.objectid
!= objectid
||
6970 found_key
.type
!= BTRFS_EXTENT_DATA_KEY
)
6972 if (start
+ len
<= found_key
.offset
)
6974 if (start
> found_key
.offset
)
6977 /* New extent overlaps with existing one */
6979 em
->orig_start
= start
;
6980 em
->len
= found_key
.offset
- start
;
6981 em
->block_start
= EXTENT_MAP_HOLE
;
6985 btrfs_extent_item_to_extent_map(inode
, path
, item
,
6988 if (extent_type
== BTRFS_FILE_EXTENT_REG
||
6989 extent_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
6991 } else if (extent_type
== BTRFS_FILE_EXTENT_INLINE
) {
6995 size_t extent_offset
;
7001 size
= btrfs_file_extent_ram_bytes(leaf
, item
);
7002 extent_offset
= page_offset(page
) + pg_offset
- extent_start
;
7003 copy_size
= min_t(u64
, PAGE_SIZE
- pg_offset
,
7004 size
- extent_offset
);
7005 em
->start
= extent_start
+ extent_offset
;
7006 em
->len
= ALIGN(copy_size
, fs_info
->sectorsize
);
7007 em
->orig_block_len
= em
->len
;
7008 em
->orig_start
= em
->start
;
7009 ptr
= btrfs_file_extent_inline_start(item
) + extent_offset
;
7011 btrfs_set_path_blocking(path
);
7012 if (!PageUptodate(page
)) {
7013 if (btrfs_file_extent_compression(leaf
, item
) !=
7014 BTRFS_COMPRESS_NONE
) {
7015 ret
= uncompress_inline(path
, page
, pg_offset
,
7016 extent_offset
, item
);
7023 read_extent_buffer(leaf
, map
+ pg_offset
, ptr
,
7025 if (pg_offset
+ copy_size
< PAGE_SIZE
) {
7026 memset(map
+ pg_offset
+ copy_size
, 0,
7027 PAGE_SIZE
- pg_offset
-
7032 flush_dcache_page(page
);
7034 set_extent_uptodate(io_tree
, em
->start
,
7035 extent_map_end(em
) - 1, NULL
, GFP_NOFS
);
7040 em
->orig_start
= start
;
7042 em
->block_start
= EXTENT_MAP_HOLE
;
7044 btrfs_release_path(path
);
7045 if (em
->start
> start
|| extent_map_end(em
) <= start
) {
7047 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7048 em
->start
, em
->len
, start
, len
);
7054 write_lock(&em_tree
->lock
);
7055 err
= btrfs_add_extent_mapping(fs_info
, em_tree
, &em
, start
, len
);
7056 write_unlock(&em_tree
->lock
);
7058 btrfs_free_path(path
);
7060 trace_btrfs_get_extent(root
, inode
, em
);
7063 free_extent_map(em
);
7064 return ERR_PTR(err
);
7066 BUG_ON(!em
); /* Error is always set */
7070 struct extent_map
*btrfs_get_extent_fiemap(struct btrfs_inode
*inode
,
7073 struct extent_map
*em
;
7074 struct extent_map
*hole_em
= NULL
;
7075 u64 delalloc_start
= start
;
7081 em
= btrfs_get_extent(inode
, NULL
, 0, start
, len
, 0);
7085 * If our em maps to:
7087 * - a pre-alloc extent,
7088 * there might actually be delalloc bytes behind it.
7090 if (em
->block_start
!= EXTENT_MAP_HOLE
&&
7091 !test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
7096 /* check to see if we've wrapped (len == -1 or similar) */
7105 /* ok, we didn't find anything, lets look for delalloc */
7106 delalloc_len
= count_range_bits(&inode
->io_tree
, &delalloc_start
,
7107 end
, len
, EXTENT_DELALLOC
, 1);
7108 delalloc_end
= delalloc_start
+ delalloc_len
;
7109 if (delalloc_end
< delalloc_start
)
7110 delalloc_end
= (u64
)-1;
7113 * We didn't find anything useful, return the original results from
7116 if (delalloc_start
> end
|| delalloc_end
<= start
) {
7123 * Adjust the delalloc_start to make sure it doesn't go backwards from
7124 * the start they passed in
7126 delalloc_start
= max(start
, delalloc_start
);
7127 delalloc_len
= delalloc_end
- delalloc_start
;
7129 if (delalloc_len
> 0) {
7132 const u64 hole_end
= extent_map_end(hole_em
);
7134 em
= alloc_extent_map();
7143 * When btrfs_get_extent can't find anything it returns one
7146 * Make sure what it found really fits our range, and adjust to
7147 * make sure it is based on the start from the caller
7149 if (hole_end
<= start
|| hole_em
->start
> end
) {
7150 free_extent_map(hole_em
);
7153 hole_start
= max(hole_em
->start
, start
);
7154 hole_len
= hole_end
- hole_start
;
7157 if (hole_em
&& delalloc_start
> hole_start
) {
7159 * Our hole starts before our delalloc, so we have to
7160 * return just the parts of the hole that go until the
7163 em
->len
= min(hole_len
, delalloc_start
- hole_start
);
7164 em
->start
= hole_start
;
7165 em
->orig_start
= hole_start
;
7167 * Don't adjust block start at all, it is fixed at
7170 em
->block_start
= hole_em
->block_start
;
7171 em
->block_len
= hole_len
;
7172 if (test_bit(EXTENT_FLAG_PREALLOC
, &hole_em
->flags
))
7173 set_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
);
7176 * Hole is out of passed range or it starts after
7179 em
->start
= delalloc_start
;
7180 em
->len
= delalloc_len
;
7181 em
->orig_start
= delalloc_start
;
7182 em
->block_start
= EXTENT_MAP_DELALLOC
;
7183 em
->block_len
= delalloc_len
;
7190 free_extent_map(hole_em
);
7192 free_extent_map(em
);
7193 return ERR_PTR(err
);
7198 static struct extent_map
*btrfs_create_dio_extent(struct inode
*inode
,
7201 const u64 orig_start
,
7202 const u64 block_start
,
7203 const u64 block_len
,
7204 const u64 orig_block_len
,
7205 const u64 ram_bytes
,
7208 struct extent_map
*em
= NULL
;
7211 if (type
!= BTRFS_ORDERED_NOCOW
) {
7212 em
= create_io_em(inode
, start
, len
, orig_start
,
7213 block_start
, block_len
, orig_block_len
,
7215 BTRFS_COMPRESS_NONE
, /* compress_type */
7220 ret
= btrfs_add_ordered_extent_dio(inode
, start
, block_start
,
7221 len
, block_len
, type
);
7224 free_extent_map(em
);
7225 btrfs_drop_extent_cache(BTRFS_I(inode
), start
,
7226 start
+ len
- 1, 0);
7235 static struct extent_map
*btrfs_new_extent_direct(struct inode
*inode
,
7238 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7239 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
7240 struct extent_map
*em
;
7241 struct btrfs_key ins
;
7245 alloc_hint
= get_extent_allocation_hint(inode
, start
, len
);
7246 ret
= btrfs_reserve_extent(root
, len
, len
, fs_info
->sectorsize
,
7247 0, alloc_hint
, &ins
, 1, 1);
7249 return ERR_PTR(ret
);
7251 em
= btrfs_create_dio_extent(inode
, start
, ins
.offset
, start
,
7252 ins
.objectid
, ins
.offset
, ins
.offset
,
7253 ins
.offset
, BTRFS_ORDERED_REGULAR
);
7254 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
7256 btrfs_free_reserved_extent(fs_info
, ins
.objectid
,
7263 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7264 * block must be cow'd
7266 noinline
int can_nocow_extent(struct inode
*inode
, u64 offset
, u64
*len
,
7267 u64
*orig_start
, u64
*orig_block_len
,
7270 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7271 struct btrfs_path
*path
;
7273 struct extent_buffer
*leaf
;
7274 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
7275 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
7276 struct btrfs_file_extent_item
*fi
;
7277 struct btrfs_key key
;
7284 bool nocow
= (BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
);
7286 path
= btrfs_alloc_path();
7290 ret
= btrfs_lookup_file_extent(NULL
, root
, path
,
7291 btrfs_ino(BTRFS_I(inode
)), offset
, 0);
7295 slot
= path
->slots
[0];
7298 /* can't find the item, must cow */
7305 leaf
= path
->nodes
[0];
7306 btrfs_item_key_to_cpu(leaf
, &key
, slot
);
7307 if (key
.objectid
!= btrfs_ino(BTRFS_I(inode
)) ||
7308 key
.type
!= BTRFS_EXTENT_DATA_KEY
) {
7309 /* not our file or wrong item type, must cow */
7313 if (key
.offset
> offset
) {
7314 /* Wrong offset, must cow */
7318 fi
= btrfs_item_ptr(leaf
, slot
, struct btrfs_file_extent_item
);
7319 found_type
= btrfs_file_extent_type(leaf
, fi
);
7320 if (found_type
!= BTRFS_FILE_EXTENT_REG
&&
7321 found_type
!= BTRFS_FILE_EXTENT_PREALLOC
) {
7322 /* not a regular extent, must cow */
7326 if (!nocow
&& found_type
== BTRFS_FILE_EXTENT_REG
)
7329 extent_end
= key
.offset
+ btrfs_file_extent_num_bytes(leaf
, fi
);
7330 if (extent_end
<= offset
)
7333 disk_bytenr
= btrfs_file_extent_disk_bytenr(leaf
, fi
);
7334 if (disk_bytenr
== 0)
7337 if (btrfs_file_extent_compression(leaf
, fi
) ||
7338 btrfs_file_extent_encryption(leaf
, fi
) ||
7339 btrfs_file_extent_other_encoding(leaf
, fi
))
7343 * Do the same check as in btrfs_cross_ref_exist but without the
7344 * unnecessary search.
7346 if (btrfs_file_extent_generation(leaf
, fi
) <=
7347 btrfs_root_last_snapshot(&root
->root_item
))
7350 backref_offset
= btrfs_file_extent_offset(leaf
, fi
);
7353 *orig_start
= key
.offset
- backref_offset
;
7354 *orig_block_len
= btrfs_file_extent_disk_num_bytes(leaf
, fi
);
7355 *ram_bytes
= btrfs_file_extent_ram_bytes(leaf
, fi
);
7358 if (btrfs_extent_readonly(fs_info
, disk_bytenr
))
7361 num_bytes
= min(offset
+ *len
, extent_end
) - offset
;
7362 if (!nocow
&& found_type
== BTRFS_FILE_EXTENT_PREALLOC
) {
7365 range_end
= round_up(offset
+ num_bytes
,
7366 root
->fs_info
->sectorsize
) - 1;
7367 ret
= test_range_bit(io_tree
, offset
, range_end
,
7368 EXTENT_DELALLOC
, 0, NULL
);
7375 btrfs_release_path(path
);
7378 * look for other files referencing this extent, if we
7379 * find any we must cow
7382 ret
= btrfs_cross_ref_exist(root
, btrfs_ino(BTRFS_I(inode
)),
7383 key
.offset
- backref_offset
, disk_bytenr
);
7390 * adjust disk_bytenr and num_bytes to cover just the bytes
7391 * in this extent we are about to write. If there
7392 * are any csums in that range we have to cow in order
7393 * to keep the csums correct
7395 disk_bytenr
+= backref_offset
;
7396 disk_bytenr
+= offset
- key
.offset
;
7397 if (csum_exist_in_range(fs_info
, disk_bytenr
, num_bytes
))
7400 * all of the above have passed, it is safe to overwrite this extent
7406 btrfs_free_path(path
);
7410 static int lock_extent_direct(struct inode
*inode
, u64 lockstart
, u64 lockend
,
7411 struct extent_state
**cached_state
, int writing
)
7413 struct btrfs_ordered_extent
*ordered
;
7417 lock_extent_bits(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
7420 * We're concerned with the entire range that we're going to be
7421 * doing DIO to, so we need to make sure there's no ordered
7422 * extents in this range.
7424 ordered
= btrfs_lookup_ordered_range(BTRFS_I(inode
), lockstart
,
7425 lockend
- lockstart
+ 1);
7428 * We need to make sure there are no buffered pages in this
7429 * range either, we could have raced between the invalidate in
7430 * generic_file_direct_write and locking the extent. The
7431 * invalidate needs to happen so that reads after a write do not
7435 (!writing
|| !filemap_range_has_page(inode
->i_mapping
,
7436 lockstart
, lockend
)))
7439 unlock_extent_cached(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
7444 * If we are doing a DIO read and the ordered extent we
7445 * found is for a buffered write, we can not wait for it
7446 * to complete and retry, because if we do so we can
7447 * deadlock with concurrent buffered writes on page
7448 * locks. This happens only if our DIO read covers more
7449 * than one extent map, if at this point has already
7450 * created an ordered extent for a previous extent map
7451 * and locked its range in the inode's io tree, and a
7452 * concurrent write against that previous extent map's
7453 * range and this range started (we unlock the ranges
7454 * in the io tree only when the bios complete and
7455 * buffered writes always lock pages before attempting
7456 * to lock range in the io tree).
7459 test_bit(BTRFS_ORDERED_DIRECT
, &ordered
->flags
))
7460 btrfs_start_ordered_extent(inode
, ordered
, 1);
7463 btrfs_put_ordered_extent(ordered
);
7466 * We could trigger writeback for this range (and wait
7467 * for it to complete) and then invalidate the pages for
7468 * this range (through invalidate_inode_pages2_range()),
7469 * but that can lead us to a deadlock with a concurrent
7470 * call to readpages() (a buffered read or a defrag call
7471 * triggered a readahead) on a page lock due to an
7472 * ordered dio extent we created before but did not have
7473 * yet a corresponding bio submitted (whence it can not
7474 * complete), which makes readpages() wait for that
7475 * ordered extent to complete while holding a lock on
7490 /* The callers of this must take lock_extent() */
7491 static struct extent_map
*create_io_em(struct inode
*inode
, u64 start
, u64 len
,
7492 u64 orig_start
, u64 block_start
,
7493 u64 block_len
, u64 orig_block_len
,
7494 u64 ram_bytes
, int compress_type
,
7497 struct extent_map_tree
*em_tree
;
7498 struct extent_map
*em
;
7499 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
7502 ASSERT(type
== BTRFS_ORDERED_PREALLOC
||
7503 type
== BTRFS_ORDERED_COMPRESSED
||
7504 type
== BTRFS_ORDERED_NOCOW
||
7505 type
== BTRFS_ORDERED_REGULAR
);
7507 em_tree
= &BTRFS_I(inode
)->extent_tree
;
7508 em
= alloc_extent_map();
7510 return ERR_PTR(-ENOMEM
);
7513 em
->orig_start
= orig_start
;
7515 em
->block_len
= block_len
;
7516 em
->block_start
= block_start
;
7517 em
->bdev
= root
->fs_info
->fs_devices
->latest_bdev
;
7518 em
->orig_block_len
= orig_block_len
;
7519 em
->ram_bytes
= ram_bytes
;
7520 em
->generation
= -1;
7521 set_bit(EXTENT_FLAG_PINNED
, &em
->flags
);
7522 if (type
== BTRFS_ORDERED_PREALLOC
) {
7523 set_bit(EXTENT_FLAG_FILLING
, &em
->flags
);
7524 } else if (type
== BTRFS_ORDERED_COMPRESSED
) {
7525 set_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
);
7526 em
->compress_type
= compress_type
;
7530 btrfs_drop_extent_cache(BTRFS_I(inode
), em
->start
,
7531 em
->start
+ em
->len
- 1, 0);
7532 write_lock(&em_tree
->lock
);
7533 ret
= add_extent_mapping(em_tree
, em
, 1);
7534 write_unlock(&em_tree
->lock
);
7536 * The caller has taken lock_extent(), who could race with us
7539 } while (ret
== -EEXIST
);
7542 free_extent_map(em
);
7543 return ERR_PTR(ret
);
7546 /* em got 2 refs now, callers needs to do free_extent_map once. */
7551 static int btrfs_get_blocks_direct_read(struct extent_map
*em
,
7552 struct buffer_head
*bh_result
,
7553 struct inode
*inode
,
7556 if (em
->block_start
== EXTENT_MAP_HOLE
||
7557 test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
7560 len
= min(len
, em
->len
- (start
- em
->start
));
7562 bh_result
->b_blocknr
= (em
->block_start
+ (start
- em
->start
)) >>
7564 bh_result
->b_size
= len
;
7565 bh_result
->b_bdev
= em
->bdev
;
7566 set_buffer_mapped(bh_result
);
7571 static int btrfs_get_blocks_direct_write(struct extent_map
**map
,
7572 struct buffer_head
*bh_result
,
7573 struct inode
*inode
,
7574 struct btrfs_dio_data
*dio_data
,
7577 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7578 struct extent_map
*em
= *map
;
7582 * We don't allocate a new extent in the following cases
7584 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7586 * 2) The extent is marked as PREALLOC. We're good to go here and can
7587 * just use the extent.
7590 if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
) ||
7591 ((BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
) &&
7592 em
->block_start
!= EXTENT_MAP_HOLE
)) {
7594 u64 block_start
, orig_start
, orig_block_len
, ram_bytes
;
7596 if (test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
7597 type
= BTRFS_ORDERED_PREALLOC
;
7599 type
= BTRFS_ORDERED_NOCOW
;
7600 len
= min(len
, em
->len
- (start
- em
->start
));
7601 block_start
= em
->block_start
+ (start
- em
->start
);
7603 if (can_nocow_extent(inode
, start
, &len
, &orig_start
,
7604 &orig_block_len
, &ram_bytes
) == 1 &&
7605 btrfs_inc_nocow_writers(fs_info
, block_start
)) {
7606 struct extent_map
*em2
;
7608 em2
= btrfs_create_dio_extent(inode
, start
, len
,
7609 orig_start
, block_start
,
7610 len
, orig_block_len
,
7612 btrfs_dec_nocow_writers(fs_info
, block_start
);
7613 if (type
== BTRFS_ORDERED_PREALLOC
) {
7614 free_extent_map(em
);
7618 if (em2
&& IS_ERR(em2
)) {
7623 * For inode marked NODATACOW or extent marked PREALLOC,
7624 * use the existing or preallocated extent, so does not
7625 * need to adjust btrfs_space_info's bytes_may_use.
7627 btrfs_free_reserved_data_space_noquota(inode
, start
,
7633 /* this will cow the extent */
7634 len
= bh_result
->b_size
;
7635 free_extent_map(em
);
7636 *map
= em
= btrfs_new_extent_direct(inode
, start
, len
);
7642 len
= min(len
, em
->len
- (start
- em
->start
));
7645 bh_result
->b_blocknr
= (em
->block_start
+ (start
- em
->start
)) >>
7647 bh_result
->b_size
= len
;
7648 bh_result
->b_bdev
= em
->bdev
;
7649 set_buffer_mapped(bh_result
);
7651 if (!test_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
))
7652 set_buffer_new(bh_result
);
7655 * Need to update the i_size under the extent lock so buffered
7656 * readers will get the updated i_size when we unlock.
7658 if (!dio_data
->overwrite
&& start
+ len
> i_size_read(inode
))
7659 i_size_write(inode
, start
+ len
);
7661 WARN_ON(dio_data
->reserve
< len
);
7662 dio_data
->reserve
-= len
;
7663 dio_data
->unsubmitted_oe_range_end
= start
+ len
;
7664 current
->journal_info
= dio_data
;
7669 static int btrfs_get_blocks_direct(struct inode
*inode
, sector_t iblock
,
7670 struct buffer_head
*bh_result
, int create
)
7672 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7673 struct extent_map
*em
;
7674 struct extent_state
*cached_state
= NULL
;
7675 struct btrfs_dio_data
*dio_data
= NULL
;
7676 u64 start
= iblock
<< inode
->i_blkbits
;
7677 u64 lockstart
, lockend
;
7678 u64 len
= bh_result
->b_size
;
7679 int unlock_bits
= EXTENT_LOCKED
;
7683 unlock_bits
|= EXTENT_DIRTY
;
7685 len
= min_t(u64
, len
, fs_info
->sectorsize
);
7688 lockend
= start
+ len
- 1;
7690 if (current
->journal_info
) {
7692 * Need to pull our outstanding extents and set journal_info to NULL so
7693 * that anything that needs to check if there's a transaction doesn't get
7696 dio_data
= current
->journal_info
;
7697 current
->journal_info
= NULL
;
7701 * If this errors out it's because we couldn't invalidate pagecache for
7702 * this range and we need to fallback to buffered.
7704 if (lock_extent_direct(inode
, lockstart
, lockend
, &cached_state
,
7710 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, start
, len
, 0);
7717 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7718 * io. INLINE is special, and we could probably kludge it in here, but
7719 * it's still buffered so for safety lets just fall back to the generic
7722 * For COMPRESSED we _have_ to read the entire extent in so we can
7723 * decompress it, so there will be buffering required no matter what we
7724 * do, so go ahead and fallback to buffered.
7726 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7727 * to buffered IO. Don't blame me, this is the price we pay for using
7730 if (test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
) ||
7731 em
->block_start
== EXTENT_MAP_INLINE
) {
7732 free_extent_map(em
);
7738 ret
= btrfs_get_blocks_direct_write(&em
, bh_result
, inode
,
7739 dio_data
, start
, len
);
7743 /* clear and unlock the entire range */
7744 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
7745 unlock_bits
, 1, 0, &cached_state
);
7747 ret
= btrfs_get_blocks_direct_read(em
, bh_result
, inode
,
7749 /* Can be negative only if we read from a hole */
7752 free_extent_map(em
);
7756 * We need to unlock only the end area that we aren't using.
7757 * The rest is going to be unlocked by the endio routine.
7759 lockstart
= start
+ bh_result
->b_size
;
7760 if (lockstart
< lockend
) {
7761 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, lockstart
,
7762 lockend
, unlock_bits
, 1, 0,
7765 free_extent_state(cached_state
);
7769 free_extent_map(em
);
7774 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, lockstart
, lockend
,
7775 unlock_bits
, 1, 0, &cached_state
);
7778 current
->journal_info
= dio_data
;
7782 static inline blk_status_t
submit_dio_repair_bio(struct inode
*inode
,
7786 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7789 BUG_ON(bio_op(bio
) == REQ_OP_WRITE
);
7791 ret
= btrfs_bio_wq_end_io(fs_info
, bio
, BTRFS_WQ_ENDIO_DIO_REPAIR
);
7795 ret
= btrfs_map_bio(fs_info
, bio
, mirror_num
, 0);
7800 static int btrfs_check_dio_repairable(struct inode
*inode
,
7801 struct bio
*failed_bio
,
7802 struct io_failure_record
*failrec
,
7805 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
7808 num_copies
= btrfs_num_copies(fs_info
, failrec
->logical
, failrec
->len
);
7809 if (num_copies
== 1) {
7811 * we only have a single copy of the data, so don't bother with
7812 * all the retry and error correction code that follows. no
7813 * matter what the error is, it is very likely to persist.
7815 btrfs_debug(fs_info
,
7816 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7817 num_copies
, failrec
->this_mirror
, failed_mirror
);
7821 failrec
->failed_mirror
= failed_mirror
;
7822 failrec
->this_mirror
++;
7823 if (failrec
->this_mirror
== failed_mirror
)
7824 failrec
->this_mirror
++;
7826 if (failrec
->this_mirror
> num_copies
) {
7827 btrfs_debug(fs_info
,
7828 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7829 num_copies
, failrec
->this_mirror
, failed_mirror
);
7836 static blk_status_t
dio_read_error(struct inode
*inode
, struct bio
*failed_bio
,
7837 struct page
*page
, unsigned int pgoff
,
7838 u64 start
, u64 end
, int failed_mirror
,
7839 bio_end_io_t
*repair_endio
, void *repair_arg
)
7841 struct io_failure_record
*failrec
;
7842 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
7843 struct extent_io_tree
*failure_tree
= &BTRFS_I(inode
)->io_failure_tree
;
7846 unsigned int read_mode
= 0;
7849 blk_status_t status
;
7850 struct bio_vec bvec
;
7852 BUG_ON(bio_op(failed_bio
) == REQ_OP_WRITE
);
7854 ret
= btrfs_get_io_failure_record(inode
, start
, end
, &failrec
);
7856 return errno_to_blk_status(ret
);
7858 ret
= btrfs_check_dio_repairable(inode
, failed_bio
, failrec
,
7861 free_io_failure(failure_tree
, io_tree
, failrec
);
7862 return BLK_STS_IOERR
;
7865 segs
= bio_segments(failed_bio
);
7866 bio_get_first_bvec(failed_bio
, &bvec
);
7868 (bvec
.bv_len
> btrfs_inode_sectorsize(inode
)))
7869 read_mode
|= REQ_FAILFAST_DEV
;
7871 isector
= start
- btrfs_io_bio(failed_bio
)->logical
;
7872 isector
>>= inode
->i_sb
->s_blocksize_bits
;
7873 bio
= btrfs_create_repair_bio(inode
, failed_bio
, failrec
, page
,
7874 pgoff
, isector
, repair_endio
, repair_arg
);
7875 bio
->bi_opf
= REQ_OP_READ
| read_mode
;
7877 btrfs_debug(BTRFS_I(inode
)->root
->fs_info
,
7878 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7879 read_mode
, failrec
->this_mirror
, failrec
->in_validation
);
7881 status
= submit_dio_repair_bio(inode
, bio
, failrec
->this_mirror
);
7883 free_io_failure(failure_tree
, io_tree
, failrec
);
7890 struct btrfs_retry_complete
{
7891 struct completion done
;
7892 struct inode
*inode
;
7897 static void btrfs_retry_endio_nocsum(struct bio
*bio
)
7899 struct btrfs_retry_complete
*done
= bio
->bi_private
;
7900 struct inode
*inode
= done
->inode
;
7901 struct bio_vec
*bvec
;
7902 struct extent_io_tree
*io_tree
, *failure_tree
;
7903 struct bvec_iter_all iter_all
;
7908 ASSERT(bio
->bi_vcnt
== 1);
7909 io_tree
= &BTRFS_I(inode
)->io_tree
;
7910 failure_tree
= &BTRFS_I(inode
)->io_failure_tree
;
7911 ASSERT(bio_first_bvec_all(bio
)->bv_len
== btrfs_inode_sectorsize(inode
));
7914 ASSERT(!bio_flagged(bio
, BIO_CLONED
));
7915 bio_for_each_segment_all(bvec
, bio
, iter_all
)
7916 clean_io_failure(BTRFS_I(inode
)->root
->fs_info
, failure_tree
,
7917 io_tree
, done
->start
, bvec
->bv_page
,
7918 btrfs_ino(BTRFS_I(inode
)), 0);
7920 complete(&done
->done
);
7924 static blk_status_t
__btrfs_correct_data_nocsum(struct inode
*inode
,
7925 struct btrfs_io_bio
*io_bio
)
7927 struct btrfs_fs_info
*fs_info
;
7928 struct bio_vec bvec
;
7929 struct bvec_iter iter
;
7930 struct btrfs_retry_complete done
;
7936 blk_status_t err
= BLK_STS_OK
;
7938 fs_info
= BTRFS_I(inode
)->root
->fs_info
;
7939 sectorsize
= fs_info
->sectorsize
;
7941 start
= io_bio
->logical
;
7943 io_bio
->bio
.bi_iter
= io_bio
->iter
;
7945 bio_for_each_segment(bvec
, &io_bio
->bio
, iter
) {
7946 nr_sectors
= BTRFS_BYTES_TO_BLKS(fs_info
, bvec
.bv_len
);
7947 pgoff
= bvec
.bv_offset
;
7949 next_block_or_try_again
:
7952 init_completion(&done
.done
);
7954 ret
= dio_read_error(inode
, &io_bio
->bio
, bvec
.bv_page
,
7955 pgoff
, start
, start
+ sectorsize
- 1,
7957 btrfs_retry_endio_nocsum
, &done
);
7963 wait_for_completion_io(&done
.done
);
7965 if (!done
.uptodate
) {
7966 /* We might have another mirror, so try again */
7967 goto next_block_or_try_again
;
7971 start
+= sectorsize
;
7975 pgoff
+= sectorsize
;
7976 ASSERT(pgoff
< PAGE_SIZE
);
7977 goto next_block_or_try_again
;
7984 static void btrfs_retry_endio(struct bio
*bio
)
7986 struct btrfs_retry_complete
*done
= bio
->bi_private
;
7987 struct btrfs_io_bio
*io_bio
= btrfs_io_bio(bio
);
7988 struct extent_io_tree
*io_tree
, *failure_tree
;
7989 struct inode
*inode
= done
->inode
;
7990 struct bio_vec
*bvec
;
7994 struct bvec_iter_all iter_all
;
8001 ASSERT(bio
->bi_vcnt
== 1);
8002 ASSERT(bio_first_bvec_all(bio
)->bv_len
== btrfs_inode_sectorsize(done
->inode
));
8004 io_tree
= &BTRFS_I(inode
)->io_tree
;
8005 failure_tree
= &BTRFS_I(inode
)->io_failure_tree
;
8007 ASSERT(!bio_flagged(bio
, BIO_CLONED
));
8008 bio_for_each_segment_all(bvec
, bio
, iter_all
) {
8009 ret
= __readpage_endio_check(inode
, io_bio
, i
, bvec
->bv_page
,
8010 bvec
->bv_offset
, done
->start
,
8013 clean_io_failure(BTRFS_I(inode
)->root
->fs_info
,
8014 failure_tree
, io_tree
, done
->start
,
8016 btrfs_ino(BTRFS_I(inode
)),
8023 done
->uptodate
= uptodate
;
8025 complete(&done
->done
);
8029 static blk_status_t
__btrfs_subio_endio_read(struct inode
*inode
,
8030 struct btrfs_io_bio
*io_bio
, blk_status_t err
)
8032 struct btrfs_fs_info
*fs_info
;
8033 struct bio_vec bvec
;
8034 struct bvec_iter iter
;
8035 struct btrfs_retry_complete done
;
8042 bool uptodate
= (err
== 0);
8044 blk_status_t status
;
8046 fs_info
= BTRFS_I(inode
)->root
->fs_info
;
8047 sectorsize
= fs_info
->sectorsize
;
8050 start
= io_bio
->logical
;
8052 io_bio
->bio
.bi_iter
= io_bio
->iter
;
8054 bio_for_each_segment(bvec
, &io_bio
->bio
, iter
) {
8055 nr_sectors
= BTRFS_BYTES_TO_BLKS(fs_info
, bvec
.bv_len
);
8057 pgoff
= bvec
.bv_offset
;
8060 csum_pos
= BTRFS_BYTES_TO_BLKS(fs_info
, offset
);
8061 ret
= __readpage_endio_check(inode
, io_bio
, csum_pos
,
8062 bvec
.bv_page
, pgoff
, start
, sectorsize
);
8069 init_completion(&done
.done
);
8071 status
= dio_read_error(inode
, &io_bio
->bio
, bvec
.bv_page
,
8072 pgoff
, start
, start
+ sectorsize
- 1,
8073 io_bio
->mirror_num
, btrfs_retry_endio
,
8080 wait_for_completion_io(&done
.done
);
8082 if (!done
.uptodate
) {
8083 /* We might have another mirror, so try again */
8087 offset
+= sectorsize
;
8088 start
+= sectorsize
;
8094 pgoff
+= sectorsize
;
8095 ASSERT(pgoff
< PAGE_SIZE
);
8103 static blk_status_t
btrfs_subio_endio_read(struct inode
*inode
,
8104 struct btrfs_io_bio
*io_bio
, blk_status_t err
)
8106 bool skip_csum
= BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
;
8110 return __btrfs_correct_data_nocsum(inode
, io_bio
);
8114 return __btrfs_subio_endio_read(inode
, io_bio
, err
);
8118 static void btrfs_endio_direct_read(struct bio
*bio
)
8120 struct btrfs_dio_private
*dip
= bio
->bi_private
;
8121 struct inode
*inode
= dip
->inode
;
8122 struct bio
*dio_bio
;
8123 struct btrfs_io_bio
*io_bio
= btrfs_io_bio(bio
);
8124 blk_status_t err
= bio
->bi_status
;
8126 if (dip
->flags
& BTRFS_DIO_ORIG_BIO_SUBMITTED
)
8127 err
= btrfs_subio_endio_read(inode
, io_bio
, err
);
8129 unlock_extent(&BTRFS_I(inode
)->io_tree
, dip
->logical_offset
,
8130 dip
->logical_offset
+ dip
->bytes
- 1);
8131 dio_bio
= dip
->dio_bio
;
8135 dio_bio
->bi_status
= err
;
8136 dio_end_io(dio_bio
);
8137 btrfs_io_bio_free_csum(io_bio
);
8141 static void __endio_write_update_ordered(struct inode
*inode
,
8142 const u64 offset
, const u64 bytes
,
8143 const bool uptodate
)
8145 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
8146 struct btrfs_ordered_extent
*ordered
= NULL
;
8147 struct btrfs_workqueue
*wq
;
8148 btrfs_work_func_t func
;
8149 u64 ordered_offset
= offset
;
8150 u64 ordered_bytes
= bytes
;
8153 if (btrfs_is_free_space_inode(BTRFS_I(inode
))) {
8154 wq
= fs_info
->endio_freespace_worker
;
8155 func
= btrfs_freespace_write_helper
;
8157 wq
= fs_info
->endio_write_workers
;
8158 func
= btrfs_endio_write_helper
;
8161 while (ordered_offset
< offset
+ bytes
) {
8162 last_offset
= ordered_offset
;
8163 if (btrfs_dec_test_first_ordered_pending(inode
, &ordered
,
8167 btrfs_init_work(&ordered
->work
, func
,
8170 btrfs_queue_work(wq
, &ordered
->work
);
8173 * If btrfs_dec_test_ordered_pending does not find any ordered
8174 * extent in the range, we can exit.
8176 if (ordered_offset
== last_offset
)
8179 * Our bio might span multiple ordered extents. In this case
8180 * we keep going until we have accounted the whole dio.
8182 if (ordered_offset
< offset
+ bytes
) {
8183 ordered_bytes
= offset
+ bytes
- ordered_offset
;
8189 static void btrfs_endio_direct_write(struct bio
*bio
)
8191 struct btrfs_dio_private
*dip
= bio
->bi_private
;
8192 struct bio
*dio_bio
= dip
->dio_bio
;
8194 __endio_write_update_ordered(dip
->inode
, dip
->logical_offset
,
8195 dip
->bytes
, !bio
->bi_status
);
8199 dio_bio
->bi_status
= bio
->bi_status
;
8200 dio_end_io(dio_bio
);
8204 static blk_status_t
btrfs_submit_bio_start_direct_io(void *private_data
,
8205 struct bio
*bio
, u64 offset
)
8207 struct inode
*inode
= private_data
;
8209 ret
= btrfs_csum_one_bio(inode
, bio
, offset
, 1);
8210 BUG_ON(ret
); /* -ENOMEM */
8214 static void btrfs_end_dio_bio(struct bio
*bio
)
8216 struct btrfs_dio_private
*dip
= bio
->bi_private
;
8217 blk_status_t err
= bio
->bi_status
;
8220 btrfs_warn(BTRFS_I(dip
->inode
)->root
->fs_info
,
8221 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8222 btrfs_ino(BTRFS_I(dip
->inode
)), bio_op(bio
),
8224 (unsigned long long)bio
->bi_iter
.bi_sector
,
8225 bio
->bi_iter
.bi_size
, err
);
8227 if (dip
->subio_endio
)
8228 err
= dip
->subio_endio(dip
->inode
, btrfs_io_bio(bio
), err
);
8232 * We want to perceive the errors flag being set before
8233 * decrementing the reference count. We don't need a barrier
8234 * since atomic operations with a return value are fully
8235 * ordered as per atomic_t.txt
8240 /* if there are more bios still pending for this dio, just exit */
8241 if (!atomic_dec_and_test(&dip
->pending_bios
))
8245 bio_io_error(dip
->orig_bio
);
8247 dip
->dio_bio
->bi_status
= BLK_STS_OK
;
8248 bio_endio(dip
->orig_bio
);
8254 static inline blk_status_t
btrfs_lookup_and_bind_dio_csum(struct inode
*inode
,
8255 struct btrfs_dio_private
*dip
,
8259 struct btrfs_io_bio
*io_bio
= btrfs_io_bio(bio
);
8260 struct btrfs_io_bio
*orig_io_bio
= btrfs_io_bio(dip
->orig_bio
);
8264 * We load all the csum data we need when we submit
8265 * the first bio to reduce the csum tree search and
8268 if (dip
->logical_offset
== file_offset
) {
8269 ret
= btrfs_lookup_bio_sums_dio(inode
, dip
->orig_bio
,
8275 if (bio
== dip
->orig_bio
)
8278 file_offset
-= dip
->logical_offset
;
8279 file_offset
>>= inode
->i_sb
->s_blocksize_bits
;
8280 io_bio
->csum
= (u8
*)(((u32
*)orig_io_bio
->csum
) + file_offset
);
8285 static inline blk_status_t
btrfs_submit_dio_bio(struct bio
*bio
,
8286 struct inode
*inode
, u64 file_offset
, int async_submit
)
8288 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
8289 struct btrfs_dio_private
*dip
= bio
->bi_private
;
8290 bool write
= bio_op(bio
) == REQ_OP_WRITE
;
8293 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8295 async_submit
= !atomic_read(&BTRFS_I(inode
)->sync_writers
);
8298 ret
= btrfs_bio_wq_end_io(fs_info
, bio
, BTRFS_WQ_ENDIO_DATA
);
8303 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
)
8306 if (write
&& async_submit
) {
8307 ret
= btrfs_wq_submit_bio(fs_info
, bio
, 0, 0,
8309 btrfs_submit_bio_start_direct_io
);
8313 * If we aren't doing async submit, calculate the csum of the
8316 ret
= btrfs_csum_one_bio(inode
, bio
, file_offset
, 1);
8320 ret
= btrfs_lookup_and_bind_dio_csum(inode
, dip
, bio
,
8326 ret
= btrfs_map_bio(fs_info
, bio
, 0, 0);
8331 static int btrfs_submit_direct_hook(struct btrfs_dio_private
*dip
)
8333 struct inode
*inode
= dip
->inode
;
8334 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
8336 struct bio
*orig_bio
= dip
->orig_bio
;
8337 u64 start_sector
= orig_bio
->bi_iter
.bi_sector
;
8338 u64 file_offset
= dip
->logical_offset
;
8339 int async_submit
= 0;
8341 int clone_offset
= 0;
8344 blk_status_t status
;
8345 struct btrfs_io_geometry geom
;
8347 submit_len
= orig_bio
->bi_iter
.bi_size
;
8348 ret
= btrfs_get_io_geometry(fs_info
, btrfs_op(orig_bio
),
8349 start_sector
<< 9, submit_len
, &geom
);
8353 if (geom
.len
>= submit_len
) {
8355 dip
->flags
|= BTRFS_DIO_ORIG_BIO_SUBMITTED
;
8359 /* async crcs make it difficult to collect full stripe writes. */
8360 if (btrfs_data_alloc_profile(fs_info
) & BTRFS_BLOCK_GROUP_RAID56_MASK
)
8366 ASSERT(geom
.len
<= INT_MAX
);
8367 atomic_inc(&dip
->pending_bios
);
8369 clone_len
= min_t(int, submit_len
, geom
.len
);
8372 * This will never fail as it's passing GPF_NOFS and
8373 * the allocation is backed by btrfs_bioset.
8375 bio
= btrfs_bio_clone_partial(orig_bio
, clone_offset
,
8377 bio
->bi_private
= dip
;
8378 bio
->bi_end_io
= btrfs_end_dio_bio
;
8379 btrfs_io_bio(bio
)->logical
= file_offset
;
8381 ASSERT(submit_len
>= clone_len
);
8382 submit_len
-= clone_len
;
8383 if (submit_len
== 0)
8387 * Increase the count before we submit the bio so we know
8388 * the end IO handler won't happen before we increase the
8389 * count. Otherwise, the dip might get freed before we're
8390 * done setting it up.
8392 atomic_inc(&dip
->pending_bios
);
8394 status
= btrfs_submit_dio_bio(bio
, inode
, file_offset
,
8398 atomic_dec(&dip
->pending_bios
);
8402 clone_offset
+= clone_len
;
8403 start_sector
+= clone_len
>> 9;
8404 file_offset
+= clone_len
;
8406 ret
= btrfs_get_io_geometry(fs_info
, btrfs_op(orig_bio
),
8407 start_sector
<< 9, submit_len
, &geom
);
8410 } while (submit_len
> 0);
8413 status
= btrfs_submit_dio_bio(bio
, inode
, file_offset
, async_submit
);
8421 * Before atomic variable goto zero, we must make sure dip->errors is
8422 * perceived to be set. This ordering is ensured by the fact that an
8423 * atomic operations with a return value are fully ordered as per
8426 if (atomic_dec_and_test(&dip
->pending_bios
))
8427 bio_io_error(dip
->orig_bio
);
8429 /* bio_end_io() will handle error, so we needn't return it */
8433 static void btrfs_submit_direct(struct bio
*dio_bio
, struct inode
*inode
,
8436 struct btrfs_dio_private
*dip
= NULL
;
8437 struct bio
*bio
= NULL
;
8438 struct btrfs_io_bio
*io_bio
;
8439 bool write
= (bio_op(dio_bio
) == REQ_OP_WRITE
);
8442 bio
= btrfs_bio_clone(dio_bio
);
8444 dip
= kzalloc(sizeof(*dip
), GFP_NOFS
);
8450 dip
->private = dio_bio
->bi_private
;
8452 dip
->logical_offset
= file_offset
;
8453 dip
->bytes
= dio_bio
->bi_iter
.bi_size
;
8454 dip
->disk_bytenr
= (u64
)dio_bio
->bi_iter
.bi_sector
<< 9;
8455 bio
->bi_private
= dip
;
8456 dip
->orig_bio
= bio
;
8457 dip
->dio_bio
= dio_bio
;
8458 atomic_set(&dip
->pending_bios
, 0);
8459 io_bio
= btrfs_io_bio(bio
);
8460 io_bio
->logical
= file_offset
;
8463 bio
->bi_end_io
= btrfs_endio_direct_write
;
8465 bio
->bi_end_io
= btrfs_endio_direct_read
;
8466 dip
->subio_endio
= btrfs_subio_endio_read
;
8470 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8471 * even if we fail to submit a bio, because in such case we do the
8472 * corresponding error handling below and it must not be done a second
8473 * time by btrfs_direct_IO().
8476 struct btrfs_dio_data
*dio_data
= current
->journal_info
;
8478 dio_data
->unsubmitted_oe_range_end
= dip
->logical_offset
+
8480 dio_data
->unsubmitted_oe_range_start
=
8481 dio_data
->unsubmitted_oe_range_end
;
8484 ret
= btrfs_submit_direct_hook(dip
);
8488 btrfs_io_bio_free_csum(io_bio
);
8492 * If we arrived here it means either we failed to submit the dip
8493 * or we either failed to clone the dio_bio or failed to allocate the
8494 * dip. If we cloned the dio_bio and allocated the dip, we can just
8495 * call bio_endio against our io_bio so that we get proper resource
8496 * cleanup if we fail to submit the dip, otherwise, we must do the
8497 * same as btrfs_endio_direct_[write|read] because we can't call these
8498 * callbacks - they require an allocated dip and a clone of dio_bio.
8503 * The end io callbacks free our dip, do the final put on bio
8504 * and all the cleanup and final put for dio_bio (through
8511 __endio_write_update_ordered(inode
,
8513 dio_bio
->bi_iter
.bi_size
,
8516 unlock_extent(&BTRFS_I(inode
)->io_tree
, file_offset
,
8517 file_offset
+ dio_bio
->bi_iter
.bi_size
- 1);
8519 dio_bio
->bi_status
= BLK_STS_IOERR
;
8521 * Releases and cleans up our dio_bio, no need to bio_put()
8522 * nor bio_endio()/bio_io_error() against dio_bio.
8524 dio_end_io(dio_bio
);
8531 static ssize_t
check_direct_IO(struct btrfs_fs_info
*fs_info
,
8532 const struct iov_iter
*iter
, loff_t offset
)
8536 unsigned int blocksize_mask
= fs_info
->sectorsize
- 1;
8537 ssize_t retval
= -EINVAL
;
8539 if (offset
& blocksize_mask
)
8542 if (iov_iter_alignment(iter
) & blocksize_mask
)
8545 /* If this is a write we don't need to check anymore */
8546 if (iov_iter_rw(iter
) != READ
|| !iter_is_iovec(iter
))
8549 * Check to make sure we don't have duplicate iov_base's in this
8550 * iovec, if so return EINVAL, otherwise we'll get csum errors
8551 * when reading back.
8553 for (seg
= 0; seg
< iter
->nr_segs
; seg
++) {
8554 for (i
= seg
+ 1; i
< iter
->nr_segs
; i
++) {
8555 if (iter
->iov
[seg
].iov_base
== iter
->iov
[i
].iov_base
)
8564 static ssize_t
btrfs_direct_IO(struct kiocb
*iocb
, struct iov_iter
*iter
)
8566 struct file
*file
= iocb
->ki_filp
;
8567 struct inode
*inode
= file
->f_mapping
->host
;
8568 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
8569 struct btrfs_dio_data dio_data
= { 0 };
8570 struct extent_changeset
*data_reserved
= NULL
;
8571 loff_t offset
= iocb
->ki_pos
;
8575 bool relock
= false;
8578 if (check_direct_IO(fs_info
, iter
, offset
))
8581 inode_dio_begin(inode
);
8584 * The generic stuff only does filemap_write_and_wait_range, which
8585 * isn't enough if we've written compressed pages to this area, so
8586 * we need to flush the dirty pages again to make absolutely sure
8587 * that any outstanding dirty pages are on disk.
8589 count
= iov_iter_count(iter
);
8590 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
8591 &BTRFS_I(inode
)->runtime_flags
))
8592 filemap_fdatawrite_range(inode
->i_mapping
, offset
,
8593 offset
+ count
- 1);
8595 if (iov_iter_rw(iter
) == WRITE
) {
8597 * If the write DIO is beyond the EOF, we need update
8598 * the isize, but it is protected by i_mutex. So we can
8599 * not unlock the i_mutex at this case.
8601 if (offset
+ count
<= inode
->i_size
) {
8602 dio_data
.overwrite
= 1;
8603 inode_unlock(inode
);
8605 } else if (iocb
->ki_flags
& IOCB_NOWAIT
) {
8609 ret
= btrfs_delalloc_reserve_space(inode
, &data_reserved
,
8615 * We need to know how many extents we reserved so that we can
8616 * do the accounting properly if we go over the number we
8617 * originally calculated. Abuse current->journal_info for this.
8619 dio_data
.reserve
= round_up(count
,
8620 fs_info
->sectorsize
);
8621 dio_data
.unsubmitted_oe_range_start
= (u64
)offset
;
8622 dio_data
.unsubmitted_oe_range_end
= (u64
)offset
;
8623 current
->journal_info
= &dio_data
;
8624 down_read(&BTRFS_I(inode
)->dio_sem
);
8625 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK
,
8626 &BTRFS_I(inode
)->runtime_flags
)) {
8627 inode_dio_end(inode
);
8628 flags
= DIO_LOCKING
| DIO_SKIP_HOLES
;
8632 ret
= __blockdev_direct_IO(iocb
, inode
,
8633 fs_info
->fs_devices
->latest_bdev
,
8634 iter
, btrfs_get_blocks_direct
, NULL
,
8635 btrfs_submit_direct
, flags
);
8636 if (iov_iter_rw(iter
) == WRITE
) {
8637 up_read(&BTRFS_I(inode
)->dio_sem
);
8638 current
->journal_info
= NULL
;
8639 if (ret
< 0 && ret
!= -EIOCBQUEUED
) {
8640 if (dio_data
.reserve
)
8641 btrfs_delalloc_release_space(inode
, data_reserved
,
8642 offset
, dio_data
.reserve
, true);
8644 * On error we might have left some ordered extents
8645 * without submitting corresponding bios for them, so
8646 * cleanup them up to avoid other tasks getting them
8647 * and waiting for them to complete forever.
8649 if (dio_data
.unsubmitted_oe_range_start
<
8650 dio_data
.unsubmitted_oe_range_end
)
8651 __endio_write_update_ordered(inode
,
8652 dio_data
.unsubmitted_oe_range_start
,
8653 dio_data
.unsubmitted_oe_range_end
-
8654 dio_data
.unsubmitted_oe_range_start
,
8656 } else if (ret
>= 0 && (size_t)ret
< count
)
8657 btrfs_delalloc_release_space(inode
, data_reserved
,
8658 offset
, count
- (size_t)ret
, true);
8659 btrfs_delalloc_release_extents(BTRFS_I(inode
), count
, false);
8663 inode_dio_end(inode
);
8667 extent_changeset_free(data_reserved
);
8671 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8673 static int btrfs_fiemap(struct inode
*inode
, struct fiemap_extent_info
*fieinfo
,
8674 __u64 start
, __u64 len
)
8678 ret
= fiemap_check_flags(fieinfo
, BTRFS_FIEMAP_FLAGS
);
8682 return extent_fiemap(inode
, fieinfo
, start
, len
);
8685 int btrfs_readpage(struct file
*file
, struct page
*page
)
8687 struct extent_io_tree
*tree
;
8688 tree
= &BTRFS_I(page
->mapping
->host
)->io_tree
;
8689 return extent_read_full_page(tree
, page
, btrfs_get_extent
, 0);
8692 static int btrfs_writepage(struct page
*page
, struct writeback_control
*wbc
)
8694 struct inode
*inode
= page
->mapping
->host
;
8697 if (current
->flags
& PF_MEMALLOC
) {
8698 redirty_page_for_writepage(wbc
, page
);
8704 * If we are under memory pressure we will call this directly from the
8705 * VM, we need to make sure we have the inode referenced for the ordered
8706 * extent. If not just return like we didn't do anything.
8708 if (!igrab(inode
)) {
8709 redirty_page_for_writepage(wbc
, page
);
8710 return AOP_WRITEPAGE_ACTIVATE
;
8712 ret
= extent_write_full_page(page
, wbc
);
8713 btrfs_add_delayed_iput(inode
);
8717 static int btrfs_writepages(struct address_space
*mapping
,
8718 struct writeback_control
*wbc
)
8720 return extent_writepages(mapping
, wbc
);
8724 btrfs_readpages(struct file
*file
, struct address_space
*mapping
,
8725 struct list_head
*pages
, unsigned nr_pages
)
8727 return extent_readpages(mapping
, pages
, nr_pages
);
8730 static int __btrfs_releasepage(struct page
*page
, gfp_t gfp_flags
)
8732 int ret
= try_release_extent_mapping(page
, gfp_flags
);
8734 ClearPagePrivate(page
);
8735 set_page_private(page
, 0);
8741 static int btrfs_releasepage(struct page
*page
, gfp_t gfp_flags
)
8743 if (PageWriteback(page
) || PageDirty(page
))
8745 return __btrfs_releasepage(page
, gfp_flags
);
8748 static void btrfs_invalidatepage(struct page
*page
, unsigned int offset
,
8749 unsigned int length
)
8751 struct inode
*inode
= page
->mapping
->host
;
8752 struct extent_io_tree
*tree
;
8753 struct btrfs_ordered_extent
*ordered
;
8754 struct extent_state
*cached_state
= NULL
;
8755 u64 page_start
= page_offset(page
);
8756 u64 page_end
= page_start
+ PAGE_SIZE
- 1;
8759 int inode_evicting
= inode
->i_state
& I_FREEING
;
8762 * we have the page locked, so new writeback can't start,
8763 * and the dirty bit won't be cleared while we are here.
8765 * Wait for IO on this page so that we can safely clear
8766 * the PagePrivate2 bit and do ordered accounting
8768 wait_on_page_writeback(page
);
8770 tree
= &BTRFS_I(inode
)->io_tree
;
8772 btrfs_releasepage(page
, GFP_NOFS
);
8776 if (!inode_evicting
)
8777 lock_extent_bits(tree
, page_start
, page_end
, &cached_state
);
8780 ordered
= btrfs_lookup_ordered_range(BTRFS_I(inode
), start
,
8781 page_end
- start
+ 1);
8783 end
= min(page_end
, ordered
->file_offset
+ ordered
->len
- 1);
8785 * IO on this page will never be started, so we need
8786 * to account for any ordered extents now
8788 if (!inode_evicting
)
8789 clear_extent_bit(tree
, start
, end
,
8790 EXTENT_DIRTY
| EXTENT_DELALLOC
|
8791 EXTENT_DELALLOC_NEW
|
8792 EXTENT_LOCKED
| EXTENT_DO_ACCOUNTING
|
8793 EXTENT_DEFRAG
, 1, 0, &cached_state
);
8795 * whoever cleared the private bit is responsible
8796 * for the finish_ordered_io
8798 if (TestClearPagePrivate2(page
)) {
8799 struct btrfs_ordered_inode_tree
*tree
;
8802 tree
= &BTRFS_I(inode
)->ordered_tree
;
8804 spin_lock_irq(&tree
->lock
);
8805 set_bit(BTRFS_ORDERED_TRUNCATED
, &ordered
->flags
);
8806 new_len
= start
- ordered
->file_offset
;
8807 if (new_len
< ordered
->truncated_len
)
8808 ordered
->truncated_len
= new_len
;
8809 spin_unlock_irq(&tree
->lock
);
8811 if (btrfs_dec_test_ordered_pending(inode
, &ordered
,
8813 end
- start
+ 1, 1))
8814 btrfs_finish_ordered_io(ordered
);
8816 btrfs_put_ordered_extent(ordered
);
8817 if (!inode_evicting
) {
8818 cached_state
= NULL
;
8819 lock_extent_bits(tree
, start
, end
,
8824 if (start
< page_end
)
8829 * Qgroup reserved space handler
8830 * Page here will be either
8831 * 1) Already written to disk
8832 * In this case, its reserved space is released from data rsv map
8833 * and will be freed by delayed_ref handler finally.
8834 * So even we call qgroup_free_data(), it won't decrease reserved
8836 * 2) Not written to disk
8837 * This means the reserved space should be freed here. However,
8838 * if a truncate invalidates the page (by clearing PageDirty)
8839 * and the page is accounted for while allocating extent
8840 * in btrfs_check_data_free_space() we let delayed_ref to
8841 * free the entire extent.
8843 if (PageDirty(page
))
8844 btrfs_qgroup_free_data(inode
, NULL
, page_start
, PAGE_SIZE
);
8845 if (!inode_evicting
) {
8846 clear_extent_bit(tree
, page_start
, page_end
,
8847 EXTENT_LOCKED
| EXTENT_DIRTY
|
8848 EXTENT_DELALLOC
| EXTENT_DELALLOC_NEW
|
8849 EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
, 1, 1,
8852 __btrfs_releasepage(page
, GFP_NOFS
);
8855 ClearPageChecked(page
);
8856 if (PagePrivate(page
)) {
8857 ClearPagePrivate(page
);
8858 set_page_private(page
, 0);
8864 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8865 * called from a page fault handler when a page is first dirtied. Hence we must
8866 * be careful to check for EOF conditions here. We set the page up correctly
8867 * for a written page which means we get ENOSPC checking when writing into
8868 * holes and correct delalloc and unwritten extent mapping on filesystems that
8869 * support these features.
8871 * We are not allowed to take the i_mutex here so we have to play games to
8872 * protect against truncate races as the page could now be beyond EOF. Because
8873 * truncate_setsize() writes the inode size before removing pages, once we have
8874 * the page lock we can determine safely if the page is beyond EOF. If it is not
8875 * beyond EOF, then the page is guaranteed safe against truncation until we
8878 vm_fault_t
btrfs_page_mkwrite(struct vm_fault
*vmf
)
8880 struct page
*page
= vmf
->page
;
8881 struct inode
*inode
= file_inode(vmf
->vma
->vm_file
);
8882 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
8883 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
8884 struct btrfs_ordered_extent
*ordered
;
8885 struct extent_state
*cached_state
= NULL
;
8886 struct extent_changeset
*data_reserved
= NULL
;
8888 unsigned long zero_start
;
8898 reserved_space
= PAGE_SIZE
;
8900 sb_start_pagefault(inode
->i_sb
);
8901 page_start
= page_offset(page
);
8902 page_end
= page_start
+ PAGE_SIZE
- 1;
8906 * Reserving delalloc space after obtaining the page lock can lead to
8907 * deadlock. For example, if a dirty page is locked by this function
8908 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8909 * dirty page write out, then the btrfs_writepage() function could
8910 * end up waiting indefinitely to get a lock on the page currently
8911 * being processed by btrfs_page_mkwrite() function.
8913 ret2
= btrfs_delalloc_reserve_space(inode
, &data_reserved
, page_start
,
8916 ret2
= file_update_time(vmf
->vma
->vm_file
);
8920 ret
= vmf_error(ret2
);
8926 ret
= VM_FAULT_NOPAGE
; /* make the VM retry the fault */
8929 size
= i_size_read(inode
);
8931 if ((page
->mapping
!= inode
->i_mapping
) ||
8932 (page_start
>= size
)) {
8933 /* page got truncated out from underneath us */
8936 wait_on_page_writeback(page
);
8938 lock_extent_bits(io_tree
, page_start
, page_end
, &cached_state
);
8939 set_page_extent_mapped(page
);
8942 * we can't set the delalloc bits if there are pending ordered
8943 * extents. Drop our locks and wait for them to finish
8945 ordered
= btrfs_lookup_ordered_range(BTRFS_I(inode
), page_start
,
8948 unlock_extent_cached(io_tree
, page_start
, page_end
,
8951 btrfs_start_ordered_extent(inode
, ordered
, 1);
8952 btrfs_put_ordered_extent(ordered
);
8956 if (page
->index
== ((size
- 1) >> PAGE_SHIFT
)) {
8957 reserved_space
= round_up(size
- page_start
,
8958 fs_info
->sectorsize
);
8959 if (reserved_space
< PAGE_SIZE
) {
8960 end
= page_start
+ reserved_space
- 1;
8961 btrfs_delalloc_release_space(inode
, data_reserved
,
8962 page_start
, PAGE_SIZE
- reserved_space
,
8968 * page_mkwrite gets called when the page is firstly dirtied after it's
8969 * faulted in, but write(2) could also dirty a page and set delalloc
8970 * bits, thus in this case for space account reason, we still need to
8971 * clear any delalloc bits within this page range since we have to
8972 * reserve data&meta space before lock_page() (see above comments).
8974 clear_extent_bit(&BTRFS_I(inode
)->io_tree
, page_start
, end
,
8975 EXTENT_DIRTY
| EXTENT_DELALLOC
|
8976 EXTENT_DO_ACCOUNTING
| EXTENT_DEFRAG
,
8977 0, 0, &cached_state
);
8979 ret2
= btrfs_set_extent_delalloc(inode
, page_start
, end
, 0,
8982 unlock_extent_cached(io_tree
, page_start
, page_end
,
8984 ret
= VM_FAULT_SIGBUS
;
8989 /* page is wholly or partially inside EOF */
8990 if (page_start
+ PAGE_SIZE
> size
)
8991 zero_start
= offset_in_page(size
);
8993 zero_start
= PAGE_SIZE
;
8995 if (zero_start
!= PAGE_SIZE
) {
8997 memset(kaddr
+ zero_start
, 0, PAGE_SIZE
- zero_start
);
8998 flush_dcache_page(page
);
9001 ClearPageChecked(page
);
9002 set_page_dirty(page
);
9003 SetPageUptodate(page
);
9005 BTRFS_I(inode
)->last_trans
= fs_info
->generation
;
9006 BTRFS_I(inode
)->last_sub_trans
= BTRFS_I(inode
)->root
->log_transid
;
9007 BTRFS_I(inode
)->last_log_commit
= BTRFS_I(inode
)->root
->last_log_commit
;
9009 unlock_extent_cached(io_tree
, page_start
, page_end
, &cached_state
);
9012 btrfs_delalloc_release_extents(BTRFS_I(inode
), PAGE_SIZE
, true);
9013 sb_end_pagefault(inode
->i_sb
);
9014 extent_changeset_free(data_reserved
);
9015 return VM_FAULT_LOCKED
;
9021 btrfs_delalloc_release_extents(BTRFS_I(inode
), PAGE_SIZE
, (ret
!= 0));
9022 btrfs_delalloc_release_space(inode
, data_reserved
, page_start
,
9023 reserved_space
, (ret
!= 0));
9025 sb_end_pagefault(inode
->i_sb
);
9026 extent_changeset_free(data_reserved
);
9030 static int btrfs_truncate(struct inode
*inode
, bool skip_writeback
)
9032 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
9033 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
9034 struct btrfs_block_rsv
*rsv
;
9036 struct btrfs_trans_handle
*trans
;
9037 u64 mask
= fs_info
->sectorsize
- 1;
9038 u64 min_size
= btrfs_calc_metadata_size(fs_info
, 1);
9040 if (!skip_writeback
) {
9041 ret
= btrfs_wait_ordered_range(inode
, inode
->i_size
& (~mask
),
9048 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9049 * things going on here:
9051 * 1) We need to reserve space to update our inode.
9053 * 2) We need to have something to cache all the space that is going to
9054 * be free'd up by the truncate operation, but also have some slack
9055 * space reserved in case it uses space during the truncate (thank you
9056 * very much snapshotting).
9058 * And we need these to be separate. The fact is we can use a lot of
9059 * space doing the truncate, and we have no earthly idea how much space
9060 * we will use, so we need the truncate reservation to be separate so it
9061 * doesn't end up using space reserved for updating the inode. We also
9062 * need to be able to stop the transaction and start a new one, which
9063 * means we need to be able to update the inode several times, and we
9064 * have no idea of knowing how many times that will be, so we can't just
9065 * reserve 1 item for the entirety of the operation, so that has to be
9066 * done separately as well.
9068 * So that leaves us with
9070 * 1) rsv - for the truncate reservation, which we will steal from the
9071 * transaction reservation.
9072 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9073 * updating the inode.
9075 rsv
= btrfs_alloc_block_rsv(fs_info
, BTRFS_BLOCK_RSV_TEMP
);
9078 rsv
->size
= min_size
;
9082 * 1 for the truncate slack space
9083 * 1 for updating the inode.
9085 trans
= btrfs_start_transaction(root
, 2);
9086 if (IS_ERR(trans
)) {
9087 ret
= PTR_ERR(trans
);
9091 /* Migrate the slack space for the truncate to our reserve */
9092 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
, rsv
,
9097 * So if we truncate and then write and fsync we normally would just
9098 * write the extents that changed, which is a problem if we need to
9099 * first truncate that entire inode. So set this flag so we write out
9100 * all of the extents in the inode to the sync log so we're completely
9103 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
, &BTRFS_I(inode
)->runtime_flags
);
9104 trans
->block_rsv
= rsv
;
9107 ret
= btrfs_truncate_inode_items(trans
, root
, inode
,
9109 BTRFS_EXTENT_DATA_KEY
);
9110 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
9111 if (ret
!= -ENOSPC
&& ret
!= -EAGAIN
)
9114 ret
= btrfs_update_inode(trans
, root
, inode
);
9118 btrfs_end_transaction(trans
);
9119 btrfs_btree_balance_dirty(fs_info
);
9121 trans
= btrfs_start_transaction(root
, 2);
9122 if (IS_ERR(trans
)) {
9123 ret
= PTR_ERR(trans
);
9128 btrfs_block_rsv_release(fs_info
, rsv
, -1);
9129 ret
= btrfs_block_rsv_migrate(&fs_info
->trans_block_rsv
,
9130 rsv
, min_size
, false);
9131 BUG_ON(ret
); /* shouldn't happen */
9132 trans
->block_rsv
= rsv
;
9136 * We can't call btrfs_truncate_block inside a trans handle as we could
9137 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9138 * we've truncated everything except the last little bit, and can do
9139 * btrfs_truncate_block and then update the disk_i_size.
9141 if (ret
== NEED_TRUNCATE_BLOCK
) {
9142 btrfs_end_transaction(trans
);
9143 btrfs_btree_balance_dirty(fs_info
);
9145 ret
= btrfs_truncate_block(inode
, inode
->i_size
, 0, 0);
9148 trans
= btrfs_start_transaction(root
, 1);
9149 if (IS_ERR(trans
)) {
9150 ret
= PTR_ERR(trans
);
9153 btrfs_ordered_update_i_size(inode
, inode
->i_size
, NULL
);
9159 trans
->block_rsv
= &fs_info
->trans_block_rsv
;
9160 ret2
= btrfs_update_inode(trans
, root
, inode
);
9164 ret2
= btrfs_end_transaction(trans
);
9167 btrfs_btree_balance_dirty(fs_info
);
9170 btrfs_free_block_rsv(fs_info
, rsv
);
9176 * create a new subvolume directory/inode (helper for the ioctl).
9178 int btrfs_create_subvol_root(struct btrfs_trans_handle
*trans
,
9179 struct btrfs_root
*new_root
,
9180 struct btrfs_root
*parent_root
,
9183 struct inode
*inode
;
9187 inode
= btrfs_new_inode(trans
, new_root
, NULL
, "..", 2,
9188 new_dirid
, new_dirid
,
9189 S_IFDIR
| (~current_umask() & S_IRWXUGO
),
9192 return PTR_ERR(inode
);
9193 inode
->i_op
= &btrfs_dir_inode_operations
;
9194 inode
->i_fop
= &btrfs_dir_file_operations
;
9196 set_nlink(inode
, 1);
9197 btrfs_i_size_write(BTRFS_I(inode
), 0);
9198 unlock_new_inode(inode
);
9200 err
= btrfs_subvol_inherit_props(trans
, new_root
, parent_root
);
9202 btrfs_err(new_root
->fs_info
,
9203 "error inheriting subvolume %llu properties: %d",
9204 new_root
->root_key
.objectid
, err
);
9206 err
= btrfs_update_inode(trans
, new_root
, inode
);
9212 struct inode
*btrfs_alloc_inode(struct super_block
*sb
)
9214 struct btrfs_fs_info
*fs_info
= btrfs_sb(sb
);
9215 struct btrfs_inode
*ei
;
9216 struct inode
*inode
;
9218 ei
= kmem_cache_alloc(btrfs_inode_cachep
, GFP_KERNEL
);
9225 ei
->last_sub_trans
= 0;
9226 ei
->logged_trans
= 0;
9227 ei
->delalloc_bytes
= 0;
9228 ei
->new_delalloc_bytes
= 0;
9229 ei
->defrag_bytes
= 0;
9230 ei
->disk_i_size
= 0;
9233 ei
->index_cnt
= (u64
)-1;
9235 ei
->last_unlink_trans
= 0;
9236 ei
->last_log_commit
= 0;
9238 spin_lock_init(&ei
->lock
);
9239 ei
->outstanding_extents
= 0;
9240 if (sb
->s_magic
!= BTRFS_TEST_MAGIC
)
9241 btrfs_init_metadata_block_rsv(fs_info
, &ei
->block_rsv
,
9242 BTRFS_BLOCK_RSV_DELALLOC
);
9243 ei
->runtime_flags
= 0;
9244 ei
->prop_compress
= BTRFS_COMPRESS_NONE
;
9245 ei
->defrag_compress
= BTRFS_COMPRESS_NONE
;
9247 ei
->delayed_node
= NULL
;
9249 ei
->i_otime
.tv_sec
= 0;
9250 ei
->i_otime
.tv_nsec
= 0;
9252 inode
= &ei
->vfs_inode
;
9253 extent_map_tree_init(&ei
->extent_tree
);
9254 extent_io_tree_init(fs_info
, &ei
->io_tree
, IO_TREE_INODE_IO
, inode
);
9255 extent_io_tree_init(fs_info
, &ei
->io_failure_tree
,
9256 IO_TREE_INODE_IO_FAILURE
, inode
);
9257 ei
->io_tree
.track_uptodate
= true;
9258 ei
->io_failure_tree
.track_uptodate
= true;
9259 atomic_set(&ei
->sync_writers
, 0);
9260 mutex_init(&ei
->log_mutex
);
9261 mutex_init(&ei
->delalloc_mutex
);
9262 btrfs_ordered_inode_tree_init(&ei
->ordered_tree
);
9263 INIT_LIST_HEAD(&ei
->delalloc_inodes
);
9264 INIT_LIST_HEAD(&ei
->delayed_iput
);
9265 RB_CLEAR_NODE(&ei
->rb_node
);
9266 init_rwsem(&ei
->dio_sem
);
9271 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9272 void btrfs_test_destroy_inode(struct inode
*inode
)
9274 btrfs_drop_extent_cache(BTRFS_I(inode
), 0, (u64
)-1, 0);
9275 kmem_cache_free(btrfs_inode_cachep
, BTRFS_I(inode
));
9279 void btrfs_free_inode(struct inode
*inode
)
9281 kmem_cache_free(btrfs_inode_cachep
, BTRFS_I(inode
));
9284 void btrfs_destroy_inode(struct inode
*inode
)
9286 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
9287 struct btrfs_ordered_extent
*ordered
;
9288 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
9290 WARN_ON(!hlist_empty(&inode
->i_dentry
));
9291 WARN_ON(inode
->i_data
.nrpages
);
9292 WARN_ON(BTRFS_I(inode
)->block_rsv
.reserved
);
9293 WARN_ON(BTRFS_I(inode
)->block_rsv
.size
);
9294 WARN_ON(BTRFS_I(inode
)->outstanding_extents
);
9295 WARN_ON(BTRFS_I(inode
)->delalloc_bytes
);
9296 WARN_ON(BTRFS_I(inode
)->new_delalloc_bytes
);
9297 WARN_ON(BTRFS_I(inode
)->csum_bytes
);
9298 WARN_ON(BTRFS_I(inode
)->defrag_bytes
);
9301 * This can happen where we create an inode, but somebody else also
9302 * created the same inode and we need to destroy the one we already
9309 ordered
= btrfs_lookup_first_ordered_extent(inode
, (u64
)-1);
9314 "found ordered extent %llu %llu on inode cleanup",
9315 ordered
->file_offset
, ordered
->len
);
9316 btrfs_remove_ordered_extent(inode
, ordered
);
9317 btrfs_put_ordered_extent(ordered
);
9318 btrfs_put_ordered_extent(ordered
);
9321 btrfs_qgroup_check_reserved_leak(inode
);
9322 inode_tree_del(inode
);
9323 btrfs_drop_extent_cache(BTRFS_I(inode
), 0, (u64
)-1, 0);
9326 int btrfs_drop_inode(struct inode
*inode
)
9328 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
9333 /* the snap/subvol tree is on deleting */
9334 if (btrfs_root_refs(&root
->root_item
) == 0)
9337 return generic_drop_inode(inode
);
9340 static void init_once(void *foo
)
9342 struct btrfs_inode
*ei
= (struct btrfs_inode
*) foo
;
9344 inode_init_once(&ei
->vfs_inode
);
9347 void __cold
btrfs_destroy_cachep(void)
9350 * Make sure all delayed rcu free inodes are flushed before we
9354 kmem_cache_destroy(btrfs_inode_cachep
);
9355 kmem_cache_destroy(btrfs_trans_handle_cachep
);
9356 kmem_cache_destroy(btrfs_path_cachep
);
9357 kmem_cache_destroy(btrfs_free_space_cachep
);
9360 int __init
btrfs_init_cachep(void)
9362 btrfs_inode_cachep
= kmem_cache_create("btrfs_inode",
9363 sizeof(struct btrfs_inode
), 0,
9364 SLAB_RECLAIM_ACCOUNT
| SLAB_MEM_SPREAD
| SLAB_ACCOUNT
,
9366 if (!btrfs_inode_cachep
)
9369 btrfs_trans_handle_cachep
= kmem_cache_create("btrfs_trans_handle",
9370 sizeof(struct btrfs_trans_handle
), 0,
9371 SLAB_TEMPORARY
| SLAB_MEM_SPREAD
, NULL
);
9372 if (!btrfs_trans_handle_cachep
)
9375 btrfs_path_cachep
= kmem_cache_create("btrfs_path",
9376 sizeof(struct btrfs_path
), 0,
9377 SLAB_MEM_SPREAD
, NULL
);
9378 if (!btrfs_path_cachep
)
9381 btrfs_free_space_cachep
= kmem_cache_create("btrfs_free_space",
9382 sizeof(struct btrfs_free_space
), 0,
9383 SLAB_MEM_SPREAD
, NULL
);
9384 if (!btrfs_free_space_cachep
)
9389 btrfs_destroy_cachep();
9393 static int btrfs_getattr(const struct path
*path
, struct kstat
*stat
,
9394 u32 request_mask
, unsigned int flags
)
9397 struct inode
*inode
= d_inode(path
->dentry
);
9398 u32 blocksize
= inode
->i_sb
->s_blocksize
;
9399 u32 bi_flags
= BTRFS_I(inode
)->flags
;
9401 stat
->result_mask
|= STATX_BTIME
;
9402 stat
->btime
.tv_sec
= BTRFS_I(inode
)->i_otime
.tv_sec
;
9403 stat
->btime
.tv_nsec
= BTRFS_I(inode
)->i_otime
.tv_nsec
;
9404 if (bi_flags
& BTRFS_INODE_APPEND
)
9405 stat
->attributes
|= STATX_ATTR_APPEND
;
9406 if (bi_flags
& BTRFS_INODE_COMPRESS
)
9407 stat
->attributes
|= STATX_ATTR_COMPRESSED
;
9408 if (bi_flags
& BTRFS_INODE_IMMUTABLE
)
9409 stat
->attributes
|= STATX_ATTR_IMMUTABLE
;
9410 if (bi_flags
& BTRFS_INODE_NODUMP
)
9411 stat
->attributes
|= STATX_ATTR_NODUMP
;
9413 stat
->attributes_mask
|= (STATX_ATTR_APPEND
|
9414 STATX_ATTR_COMPRESSED
|
9415 STATX_ATTR_IMMUTABLE
|
9418 generic_fillattr(inode
, stat
);
9419 stat
->dev
= BTRFS_I(inode
)->root
->anon_dev
;
9421 spin_lock(&BTRFS_I(inode
)->lock
);
9422 delalloc_bytes
= BTRFS_I(inode
)->new_delalloc_bytes
;
9423 spin_unlock(&BTRFS_I(inode
)->lock
);
9424 stat
->blocks
= (ALIGN(inode_get_bytes(inode
), blocksize
) +
9425 ALIGN(delalloc_bytes
, blocksize
)) >> 9;
9429 static int btrfs_rename_exchange(struct inode
*old_dir
,
9430 struct dentry
*old_dentry
,
9431 struct inode
*new_dir
,
9432 struct dentry
*new_dentry
)
9434 struct btrfs_fs_info
*fs_info
= btrfs_sb(old_dir
->i_sb
);
9435 struct btrfs_trans_handle
*trans
;
9436 struct btrfs_root
*root
= BTRFS_I(old_dir
)->root
;
9437 struct btrfs_root
*dest
= BTRFS_I(new_dir
)->root
;
9438 struct inode
*new_inode
= new_dentry
->d_inode
;
9439 struct inode
*old_inode
= old_dentry
->d_inode
;
9440 struct timespec64 ctime
= current_time(old_inode
);
9441 struct dentry
*parent
;
9442 u64 old_ino
= btrfs_ino(BTRFS_I(old_inode
));
9443 u64 new_ino
= btrfs_ino(BTRFS_I(new_inode
));
9448 bool root_log_pinned
= false;
9449 bool dest_log_pinned
= false;
9450 struct btrfs_log_ctx ctx_root
;
9451 struct btrfs_log_ctx ctx_dest
;
9452 bool sync_log_root
= false;
9453 bool sync_log_dest
= false;
9454 bool commit_transaction
= false;
9456 /* we only allow rename subvolume link between subvolumes */
9457 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
&& root
!= dest
)
9460 btrfs_init_log_ctx(&ctx_root
, old_inode
);
9461 btrfs_init_log_ctx(&ctx_dest
, new_inode
);
9463 /* close the race window with snapshot create/destroy ioctl */
9464 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9465 down_read(&fs_info
->subvol_sem
);
9466 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9467 down_read(&fs_info
->subvol_sem
);
9470 * We want to reserve the absolute worst case amount of items. So if
9471 * both inodes are subvols and we need to unlink them then that would
9472 * require 4 item modifications, but if they are both normal inodes it
9473 * would require 5 item modifications, so we'll assume their normal
9474 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9475 * should cover the worst case number of items we'll modify.
9477 trans
= btrfs_start_transaction(root
, 12);
9478 if (IS_ERR(trans
)) {
9479 ret
= PTR_ERR(trans
);
9484 * We need to find a free sequence number both in the source and
9485 * in the destination directory for the exchange.
9487 ret
= btrfs_set_inode_index(BTRFS_I(new_dir
), &old_idx
);
9490 ret
= btrfs_set_inode_index(BTRFS_I(old_dir
), &new_idx
);
9494 BTRFS_I(old_inode
)->dir_index
= 0ULL;
9495 BTRFS_I(new_inode
)->dir_index
= 0ULL;
9497 /* Reference for the source. */
9498 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
9499 /* force full log commit if subvolume involved. */
9500 btrfs_set_log_full_commit(trans
);
9502 btrfs_pin_log_trans(root
);
9503 root_log_pinned
= true;
9504 ret
= btrfs_insert_inode_ref(trans
, dest
,
9505 new_dentry
->d_name
.name
,
9506 new_dentry
->d_name
.len
,
9508 btrfs_ino(BTRFS_I(new_dir
)),
9514 /* And now for the dest. */
9515 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
9516 /* force full log commit if subvolume involved. */
9517 btrfs_set_log_full_commit(trans
);
9519 btrfs_pin_log_trans(dest
);
9520 dest_log_pinned
= true;
9521 ret
= btrfs_insert_inode_ref(trans
, root
,
9522 old_dentry
->d_name
.name
,
9523 old_dentry
->d_name
.len
,
9525 btrfs_ino(BTRFS_I(old_dir
)),
9531 /* Update inode version and ctime/mtime. */
9532 inode_inc_iversion(old_dir
);
9533 inode_inc_iversion(new_dir
);
9534 inode_inc_iversion(old_inode
);
9535 inode_inc_iversion(new_inode
);
9536 old_dir
->i_ctime
= old_dir
->i_mtime
= ctime
;
9537 new_dir
->i_ctime
= new_dir
->i_mtime
= ctime
;
9538 old_inode
->i_ctime
= ctime
;
9539 new_inode
->i_ctime
= ctime
;
9541 if (old_dentry
->d_parent
!= new_dentry
->d_parent
) {
9542 btrfs_record_unlink_dir(trans
, BTRFS_I(old_dir
),
9543 BTRFS_I(old_inode
), 1);
9544 btrfs_record_unlink_dir(trans
, BTRFS_I(new_dir
),
9545 BTRFS_I(new_inode
), 1);
9548 /* src is a subvolume */
9549 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
9550 root_objectid
= BTRFS_I(old_inode
)->root
->root_key
.objectid
;
9551 ret
= btrfs_unlink_subvol(trans
, old_dir
, root_objectid
,
9552 old_dentry
->d_name
.name
,
9553 old_dentry
->d_name
.len
);
9554 } else { /* src is an inode */
9555 ret
= __btrfs_unlink_inode(trans
, root
, BTRFS_I(old_dir
),
9556 BTRFS_I(old_dentry
->d_inode
),
9557 old_dentry
->d_name
.name
,
9558 old_dentry
->d_name
.len
);
9560 ret
= btrfs_update_inode(trans
, root
, old_inode
);
9563 btrfs_abort_transaction(trans
, ret
);
9567 /* dest is a subvolume */
9568 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
) {
9569 root_objectid
= BTRFS_I(new_inode
)->root
->root_key
.objectid
;
9570 ret
= btrfs_unlink_subvol(trans
, new_dir
, root_objectid
,
9571 new_dentry
->d_name
.name
,
9572 new_dentry
->d_name
.len
);
9573 } else { /* dest is an inode */
9574 ret
= __btrfs_unlink_inode(trans
, dest
, BTRFS_I(new_dir
),
9575 BTRFS_I(new_dentry
->d_inode
),
9576 new_dentry
->d_name
.name
,
9577 new_dentry
->d_name
.len
);
9579 ret
= btrfs_update_inode(trans
, dest
, new_inode
);
9582 btrfs_abort_transaction(trans
, ret
);
9586 ret
= btrfs_add_link(trans
, BTRFS_I(new_dir
), BTRFS_I(old_inode
),
9587 new_dentry
->d_name
.name
,
9588 new_dentry
->d_name
.len
, 0, old_idx
);
9590 btrfs_abort_transaction(trans
, ret
);
9594 ret
= btrfs_add_link(trans
, BTRFS_I(old_dir
), BTRFS_I(new_inode
),
9595 old_dentry
->d_name
.name
,
9596 old_dentry
->d_name
.len
, 0, new_idx
);
9598 btrfs_abort_transaction(trans
, ret
);
9602 if (old_inode
->i_nlink
== 1)
9603 BTRFS_I(old_inode
)->dir_index
= old_idx
;
9604 if (new_inode
->i_nlink
== 1)
9605 BTRFS_I(new_inode
)->dir_index
= new_idx
;
9607 if (root_log_pinned
) {
9608 parent
= new_dentry
->d_parent
;
9609 ret
= btrfs_log_new_name(trans
, BTRFS_I(old_inode
),
9610 BTRFS_I(old_dir
), parent
,
9612 if (ret
== BTRFS_NEED_LOG_SYNC
)
9613 sync_log_root
= true;
9614 else if (ret
== BTRFS_NEED_TRANS_COMMIT
)
9615 commit_transaction
= true;
9617 btrfs_end_log_trans(root
);
9618 root_log_pinned
= false;
9620 if (dest_log_pinned
) {
9621 if (!commit_transaction
) {
9622 parent
= old_dentry
->d_parent
;
9623 ret
= btrfs_log_new_name(trans
, BTRFS_I(new_inode
),
9624 BTRFS_I(new_dir
), parent
,
9626 if (ret
== BTRFS_NEED_LOG_SYNC
)
9627 sync_log_dest
= true;
9628 else if (ret
== BTRFS_NEED_TRANS_COMMIT
)
9629 commit_transaction
= true;
9632 btrfs_end_log_trans(dest
);
9633 dest_log_pinned
= false;
9637 * If we have pinned a log and an error happened, we unpin tasks
9638 * trying to sync the log and force them to fallback to a transaction
9639 * commit if the log currently contains any of the inodes involved in
9640 * this rename operation (to ensure we do not persist a log with an
9641 * inconsistent state for any of these inodes or leading to any
9642 * inconsistencies when replayed). If the transaction was aborted, the
9643 * abortion reason is propagated to userspace when attempting to commit
9644 * the transaction. If the log does not contain any of these inodes, we
9645 * allow the tasks to sync it.
9647 if (ret
&& (root_log_pinned
|| dest_log_pinned
)) {
9648 if (btrfs_inode_in_log(BTRFS_I(old_dir
), fs_info
->generation
) ||
9649 btrfs_inode_in_log(BTRFS_I(new_dir
), fs_info
->generation
) ||
9650 btrfs_inode_in_log(BTRFS_I(old_inode
), fs_info
->generation
) ||
9652 btrfs_inode_in_log(BTRFS_I(new_inode
), fs_info
->generation
)))
9653 btrfs_set_log_full_commit(trans
);
9655 if (root_log_pinned
) {
9656 btrfs_end_log_trans(root
);
9657 root_log_pinned
= false;
9659 if (dest_log_pinned
) {
9660 btrfs_end_log_trans(dest
);
9661 dest_log_pinned
= false;
9664 if (!ret
&& sync_log_root
&& !commit_transaction
) {
9665 ret
= btrfs_sync_log(trans
, BTRFS_I(old_inode
)->root
,
9668 commit_transaction
= true;
9670 if (!ret
&& sync_log_dest
&& !commit_transaction
) {
9671 ret
= btrfs_sync_log(trans
, BTRFS_I(new_inode
)->root
,
9674 commit_transaction
= true;
9676 if (commit_transaction
) {
9677 ret
= btrfs_commit_transaction(trans
);
9681 ret2
= btrfs_end_transaction(trans
);
9682 ret
= ret
? ret
: ret2
;
9685 if (new_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9686 up_read(&fs_info
->subvol_sem
);
9687 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9688 up_read(&fs_info
->subvol_sem
);
9693 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle
*trans
,
9694 struct btrfs_root
*root
,
9696 struct dentry
*dentry
)
9699 struct inode
*inode
;
9703 ret
= btrfs_find_free_ino(root
, &objectid
);
9707 inode
= btrfs_new_inode(trans
, root
, dir
,
9708 dentry
->d_name
.name
,
9710 btrfs_ino(BTRFS_I(dir
)),
9712 S_IFCHR
| WHITEOUT_MODE
,
9715 if (IS_ERR(inode
)) {
9716 ret
= PTR_ERR(inode
);
9720 inode
->i_op
= &btrfs_special_inode_operations
;
9721 init_special_inode(inode
, inode
->i_mode
,
9724 ret
= btrfs_init_inode_security(trans
, inode
, dir
,
9729 ret
= btrfs_add_nondir(trans
, BTRFS_I(dir
), dentry
,
9730 BTRFS_I(inode
), 0, index
);
9734 ret
= btrfs_update_inode(trans
, root
, inode
);
9736 unlock_new_inode(inode
);
9738 inode_dec_link_count(inode
);
9744 static int btrfs_rename(struct inode
*old_dir
, struct dentry
*old_dentry
,
9745 struct inode
*new_dir
, struct dentry
*new_dentry
,
9748 struct btrfs_fs_info
*fs_info
= btrfs_sb(old_dir
->i_sb
);
9749 struct btrfs_trans_handle
*trans
;
9750 unsigned int trans_num_items
;
9751 struct btrfs_root
*root
= BTRFS_I(old_dir
)->root
;
9752 struct btrfs_root
*dest
= BTRFS_I(new_dir
)->root
;
9753 struct inode
*new_inode
= d_inode(new_dentry
);
9754 struct inode
*old_inode
= d_inode(old_dentry
);
9758 u64 old_ino
= btrfs_ino(BTRFS_I(old_inode
));
9759 bool log_pinned
= false;
9760 struct btrfs_log_ctx ctx
;
9761 bool sync_log
= false;
9762 bool commit_transaction
= false;
9764 if (btrfs_ino(BTRFS_I(new_dir
)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)
9767 /* we only allow rename subvolume link between subvolumes */
9768 if (old_ino
!= BTRFS_FIRST_FREE_OBJECTID
&& root
!= dest
)
9771 if (old_ino
== BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
||
9772 (new_inode
&& btrfs_ino(BTRFS_I(new_inode
)) == BTRFS_FIRST_FREE_OBJECTID
))
9775 if (S_ISDIR(old_inode
->i_mode
) && new_inode
&&
9776 new_inode
->i_size
> BTRFS_EMPTY_DIR_SIZE
)
9780 /* check for collisions, even if the name isn't there */
9781 ret
= btrfs_check_dir_item_collision(dest
, new_dir
->i_ino
,
9782 new_dentry
->d_name
.name
,
9783 new_dentry
->d_name
.len
);
9786 if (ret
== -EEXIST
) {
9788 * eexist without a new_inode */
9789 if (WARN_ON(!new_inode
)) {
9793 /* maybe -EOVERFLOW */
9800 * we're using rename to replace one file with another. Start IO on it
9801 * now so we don't add too much work to the end of the transaction
9803 if (new_inode
&& S_ISREG(old_inode
->i_mode
) && new_inode
->i_size
)
9804 filemap_flush(old_inode
->i_mapping
);
9806 /* close the racy window with snapshot create/destroy ioctl */
9807 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9808 down_read(&fs_info
->subvol_sem
);
9810 * We want to reserve the absolute worst case amount of items. So if
9811 * both inodes are subvols and we need to unlink them then that would
9812 * require 4 item modifications, but if they are both normal inodes it
9813 * would require 5 item modifications, so we'll assume they are normal
9814 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9815 * should cover the worst case number of items we'll modify.
9816 * If our rename has the whiteout flag, we need more 5 units for the
9817 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9818 * when selinux is enabled).
9820 trans_num_items
= 11;
9821 if (flags
& RENAME_WHITEOUT
)
9822 trans_num_items
+= 5;
9823 trans
= btrfs_start_transaction(root
, trans_num_items
);
9824 if (IS_ERR(trans
)) {
9825 ret
= PTR_ERR(trans
);
9830 btrfs_record_root_in_trans(trans
, dest
);
9832 ret
= btrfs_set_inode_index(BTRFS_I(new_dir
), &index
);
9836 BTRFS_I(old_inode
)->dir_index
= 0ULL;
9837 if (unlikely(old_ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
9838 /* force full log commit if subvolume involved. */
9839 btrfs_set_log_full_commit(trans
);
9841 btrfs_pin_log_trans(root
);
9843 ret
= btrfs_insert_inode_ref(trans
, dest
,
9844 new_dentry
->d_name
.name
,
9845 new_dentry
->d_name
.len
,
9847 btrfs_ino(BTRFS_I(new_dir
)), index
);
9852 inode_inc_iversion(old_dir
);
9853 inode_inc_iversion(new_dir
);
9854 inode_inc_iversion(old_inode
);
9855 old_dir
->i_ctime
= old_dir
->i_mtime
=
9856 new_dir
->i_ctime
= new_dir
->i_mtime
=
9857 old_inode
->i_ctime
= current_time(old_dir
);
9859 if (old_dentry
->d_parent
!= new_dentry
->d_parent
)
9860 btrfs_record_unlink_dir(trans
, BTRFS_I(old_dir
),
9861 BTRFS_I(old_inode
), 1);
9863 if (unlikely(old_ino
== BTRFS_FIRST_FREE_OBJECTID
)) {
9864 root_objectid
= BTRFS_I(old_inode
)->root
->root_key
.objectid
;
9865 ret
= btrfs_unlink_subvol(trans
, old_dir
, root_objectid
,
9866 old_dentry
->d_name
.name
,
9867 old_dentry
->d_name
.len
);
9869 ret
= __btrfs_unlink_inode(trans
, root
, BTRFS_I(old_dir
),
9870 BTRFS_I(d_inode(old_dentry
)),
9871 old_dentry
->d_name
.name
,
9872 old_dentry
->d_name
.len
);
9874 ret
= btrfs_update_inode(trans
, root
, old_inode
);
9877 btrfs_abort_transaction(trans
, ret
);
9882 inode_inc_iversion(new_inode
);
9883 new_inode
->i_ctime
= current_time(new_inode
);
9884 if (unlikely(btrfs_ino(BTRFS_I(new_inode
)) ==
9885 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID
)) {
9886 root_objectid
= BTRFS_I(new_inode
)->location
.objectid
;
9887 ret
= btrfs_unlink_subvol(trans
, new_dir
, root_objectid
,
9888 new_dentry
->d_name
.name
,
9889 new_dentry
->d_name
.len
);
9890 BUG_ON(new_inode
->i_nlink
== 0);
9892 ret
= btrfs_unlink_inode(trans
, dest
, BTRFS_I(new_dir
),
9893 BTRFS_I(d_inode(new_dentry
)),
9894 new_dentry
->d_name
.name
,
9895 new_dentry
->d_name
.len
);
9897 if (!ret
&& new_inode
->i_nlink
== 0)
9898 ret
= btrfs_orphan_add(trans
,
9899 BTRFS_I(d_inode(new_dentry
)));
9901 btrfs_abort_transaction(trans
, ret
);
9906 ret
= btrfs_add_link(trans
, BTRFS_I(new_dir
), BTRFS_I(old_inode
),
9907 new_dentry
->d_name
.name
,
9908 new_dentry
->d_name
.len
, 0, index
);
9910 btrfs_abort_transaction(trans
, ret
);
9914 if (old_inode
->i_nlink
== 1)
9915 BTRFS_I(old_inode
)->dir_index
= index
;
9918 struct dentry
*parent
= new_dentry
->d_parent
;
9920 btrfs_init_log_ctx(&ctx
, old_inode
);
9921 ret
= btrfs_log_new_name(trans
, BTRFS_I(old_inode
),
9922 BTRFS_I(old_dir
), parent
,
9924 if (ret
== BTRFS_NEED_LOG_SYNC
)
9926 else if (ret
== BTRFS_NEED_TRANS_COMMIT
)
9927 commit_transaction
= true;
9929 btrfs_end_log_trans(root
);
9933 if (flags
& RENAME_WHITEOUT
) {
9934 ret
= btrfs_whiteout_for_rename(trans
, root
, old_dir
,
9938 btrfs_abort_transaction(trans
, ret
);
9944 * If we have pinned the log and an error happened, we unpin tasks
9945 * trying to sync the log and force them to fallback to a transaction
9946 * commit if the log currently contains any of the inodes involved in
9947 * this rename operation (to ensure we do not persist a log with an
9948 * inconsistent state for any of these inodes or leading to any
9949 * inconsistencies when replayed). If the transaction was aborted, the
9950 * abortion reason is propagated to userspace when attempting to commit
9951 * the transaction. If the log does not contain any of these inodes, we
9952 * allow the tasks to sync it.
9954 if (ret
&& log_pinned
) {
9955 if (btrfs_inode_in_log(BTRFS_I(old_dir
), fs_info
->generation
) ||
9956 btrfs_inode_in_log(BTRFS_I(new_dir
), fs_info
->generation
) ||
9957 btrfs_inode_in_log(BTRFS_I(old_inode
), fs_info
->generation
) ||
9959 btrfs_inode_in_log(BTRFS_I(new_inode
), fs_info
->generation
)))
9960 btrfs_set_log_full_commit(trans
);
9962 btrfs_end_log_trans(root
);
9965 if (!ret
&& sync_log
) {
9966 ret
= btrfs_sync_log(trans
, BTRFS_I(old_inode
)->root
, &ctx
);
9968 commit_transaction
= true;
9970 if (commit_transaction
) {
9971 ret
= btrfs_commit_transaction(trans
);
9975 ret2
= btrfs_end_transaction(trans
);
9976 ret
= ret
? ret
: ret2
;
9979 if (old_ino
== BTRFS_FIRST_FREE_OBJECTID
)
9980 up_read(&fs_info
->subvol_sem
);
9985 static int btrfs_rename2(struct inode
*old_dir
, struct dentry
*old_dentry
,
9986 struct inode
*new_dir
, struct dentry
*new_dentry
,
9989 if (flags
& ~(RENAME_NOREPLACE
| RENAME_EXCHANGE
| RENAME_WHITEOUT
))
9992 if (flags
& RENAME_EXCHANGE
)
9993 return btrfs_rename_exchange(old_dir
, old_dentry
, new_dir
,
9996 return btrfs_rename(old_dir
, old_dentry
, new_dir
, new_dentry
, flags
);
9999 struct btrfs_delalloc_work
{
10000 struct inode
*inode
;
10001 struct completion completion
;
10002 struct list_head list
;
10003 struct btrfs_work work
;
10006 static void btrfs_run_delalloc_work(struct btrfs_work
*work
)
10008 struct btrfs_delalloc_work
*delalloc_work
;
10009 struct inode
*inode
;
10011 delalloc_work
= container_of(work
, struct btrfs_delalloc_work
,
10013 inode
= delalloc_work
->inode
;
10014 filemap_flush(inode
->i_mapping
);
10015 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT
,
10016 &BTRFS_I(inode
)->runtime_flags
))
10017 filemap_flush(inode
->i_mapping
);
10020 complete(&delalloc_work
->completion
);
10023 static struct btrfs_delalloc_work
*btrfs_alloc_delalloc_work(struct inode
*inode
)
10025 struct btrfs_delalloc_work
*work
;
10027 work
= kmalloc(sizeof(*work
), GFP_NOFS
);
10031 init_completion(&work
->completion
);
10032 INIT_LIST_HEAD(&work
->list
);
10033 work
->inode
= inode
;
10034 btrfs_init_work(&work
->work
, btrfs_flush_delalloc_helper
,
10035 btrfs_run_delalloc_work
, NULL
, NULL
);
10041 * some fairly slow code that needs optimization. This walks the list
10042 * of all the inodes with pending delalloc and forces them to disk.
10044 static int start_delalloc_inodes(struct btrfs_root
*root
, int nr
, bool snapshot
)
10046 struct btrfs_inode
*binode
;
10047 struct inode
*inode
;
10048 struct btrfs_delalloc_work
*work
, *next
;
10049 struct list_head works
;
10050 struct list_head splice
;
10053 INIT_LIST_HEAD(&works
);
10054 INIT_LIST_HEAD(&splice
);
10056 mutex_lock(&root
->delalloc_mutex
);
10057 spin_lock(&root
->delalloc_lock
);
10058 list_splice_init(&root
->delalloc_inodes
, &splice
);
10059 while (!list_empty(&splice
)) {
10060 binode
= list_entry(splice
.next
, struct btrfs_inode
,
10063 list_move_tail(&binode
->delalloc_inodes
,
10064 &root
->delalloc_inodes
);
10065 inode
= igrab(&binode
->vfs_inode
);
10067 cond_resched_lock(&root
->delalloc_lock
);
10070 spin_unlock(&root
->delalloc_lock
);
10073 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH
,
10074 &binode
->runtime_flags
);
10075 work
= btrfs_alloc_delalloc_work(inode
);
10081 list_add_tail(&work
->list
, &works
);
10082 btrfs_queue_work(root
->fs_info
->flush_workers
,
10085 if (nr
!= -1 && ret
>= nr
)
10088 spin_lock(&root
->delalloc_lock
);
10090 spin_unlock(&root
->delalloc_lock
);
10093 list_for_each_entry_safe(work
, next
, &works
, list
) {
10094 list_del_init(&work
->list
);
10095 wait_for_completion(&work
->completion
);
10099 if (!list_empty(&splice
)) {
10100 spin_lock(&root
->delalloc_lock
);
10101 list_splice_tail(&splice
, &root
->delalloc_inodes
);
10102 spin_unlock(&root
->delalloc_lock
);
10104 mutex_unlock(&root
->delalloc_mutex
);
10108 int btrfs_start_delalloc_snapshot(struct btrfs_root
*root
)
10110 struct btrfs_fs_info
*fs_info
= root
->fs_info
;
10113 if (test_bit(BTRFS_FS_STATE_ERROR
, &fs_info
->fs_state
))
10116 ret
= start_delalloc_inodes(root
, -1, true);
10122 int btrfs_start_delalloc_roots(struct btrfs_fs_info
*fs_info
, int nr
)
10124 struct btrfs_root
*root
;
10125 struct list_head splice
;
10128 if (test_bit(BTRFS_FS_STATE_ERROR
, &fs_info
->fs_state
))
10131 INIT_LIST_HEAD(&splice
);
10133 mutex_lock(&fs_info
->delalloc_root_mutex
);
10134 spin_lock(&fs_info
->delalloc_root_lock
);
10135 list_splice_init(&fs_info
->delalloc_roots
, &splice
);
10136 while (!list_empty(&splice
) && nr
) {
10137 root
= list_first_entry(&splice
, struct btrfs_root
,
10139 root
= btrfs_grab_fs_root(root
);
10141 list_move_tail(&root
->delalloc_root
,
10142 &fs_info
->delalloc_roots
);
10143 spin_unlock(&fs_info
->delalloc_root_lock
);
10145 ret
= start_delalloc_inodes(root
, nr
, false);
10146 btrfs_put_fs_root(root
);
10154 spin_lock(&fs_info
->delalloc_root_lock
);
10156 spin_unlock(&fs_info
->delalloc_root_lock
);
10160 if (!list_empty(&splice
)) {
10161 spin_lock(&fs_info
->delalloc_root_lock
);
10162 list_splice_tail(&splice
, &fs_info
->delalloc_roots
);
10163 spin_unlock(&fs_info
->delalloc_root_lock
);
10165 mutex_unlock(&fs_info
->delalloc_root_mutex
);
10169 static int btrfs_symlink(struct inode
*dir
, struct dentry
*dentry
,
10170 const char *symname
)
10172 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
10173 struct btrfs_trans_handle
*trans
;
10174 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
10175 struct btrfs_path
*path
;
10176 struct btrfs_key key
;
10177 struct inode
*inode
= NULL
;
10184 struct btrfs_file_extent_item
*ei
;
10185 struct extent_buffer
*leaf
;
10187 name_len
= strlen(symname
);
10188 if (name_len
> BTRFS_MAX_INLINE_DATA_SIZE(fs_info
))
10189 return -ENAMETOOLONG
;
10192 * 2 items for inode item and ref
10193 * 2 items for dir items
10194 * 1 item for updating parent inode item
10195 * 1 item for the inline extent item
10196 * 1 item for xattr if selinux is on
10198 trans
= btrfs_start_transaction(root
, 7);
10200 return PTR_ERR(trans
);
10202 err
= btrfs_find_free_ino(root
, &objectid
);
10206 inode
= btrfs_new_inode(trans
, root
, dir
, dentry
->d_name
.name
,
10207 dentry
->d_name
.len
, btrfs_ino(BTRFS_I(dir
)),
10208 objectid
, S_IFLNK
|S_IRWXUGO
, &index
);
10209 if (IS_ERR(inode
)) {
10210 err
= PTR_ERR(inode
);
10216 * If the active LSM wants to access the inode during
10217 * d_instantiate it needs these. Smack checks to see
10218 * if the filesystem supports xattrs by looking at the
10221 inode
->i_fop
= &btrfs_file_operations
;
10222 inode
->i_op
= &btrfs_file_inode_operations
;
10223 inode
->i_mapping
->a_ops
= &btrfs_aops
;
10224 BTRFS_I(inode
)->io_tree
.ops
= &btrfs_extent_io_ops
;
10226 err
= btrfs_init_inode_security(trans
, inode
, dir
, &dentry
->d_name
);
10230 path
= btrfs_alloc_path();
10235 key
.objectid
= btrfs_ino(BTRFS_I(inode
));
10237 key
.type
= BTRFS_EXTENT_DATA_KEY
;
10238 datasize
= btrfs_file_extent_calc_inline_size(name_len
);
10239 err
= btrfs_insert_empty_item(trans
, root
, path
, &key
,
10242 btrfs_free_path(path
);
10245 leaf
= path
->nodes
[0];
10246 ei
= btrfs_item_ptr(leaf
, path
->slots
[0],
10247 struct btrfs_file_extent_item
);
10248 btrfs_set_file_extent_generation(leaf
, ei
, trans
->transid
);
10249 btrfs_set_file_extent_type(leaf
, ei
,
10250 BTRFS_FILE_EXTENT_INLINE
);
10251 btrfs_set_file_extent_encryption(leaf
, ei
, 0);
10252 btrfs_set_file_extent_compression(leaf
, ei
, 0);
10253 btrfs_set_file_extent_other_encoding(leaf
, ei
, 0);
10254 btrfs_set_file_extent_ram_bytes(leaf
, ei
, name_len
);
10256 ptr
= btrfs_file_extent_inline_start(ei
);
10257 write_extent_buffer(leaf
, symname
, ptr
, name_len
);
10258 btrfs_mark_buffer_dirty(leaf
);
10259 btrfs_free_path(path
);
10261 inode
->i_op
= &btrfs_symlink_inode_operations
;
10262 inode_nohighmem(inode
);
10263 inode_set_bytes(inode
, name_len
);
10264 btrfs_i_size_write(BTRFS_I(inode
), name_len
);
10265 err
= btrfs_update_inode(trans
, root
, inode
);
10267 * Last step, add directory indexes for our symlink inode. This is the
10268 * last step to avoid extra cleanup of these indexes if an error happens
10272 err
= btrfs_add_nondir(trans
, BTRFS_I(dir
), dentry
,
10273 BTRFS_I(inode
), 0, index
);
10277 d_instantiate_new(dentry
, inode
);
10280 btrfs_end_transaction(trans
);
10281 if (err
&& inode
) {
10282 inode_dec_link_count(inode
);
10283 discard_new_inode(inode
);
10285 btrfs_btree_balance_dirty(fs_info
);
10289 static int __btrfs_prealloc_file_range(struct inode
*inode
, int mode
,
10290 u64 start
, u64 num_bytes
, u64 min_size
,
10291 loff_t actual_len
, u64
*alloc_hint
,
10292 struct btrfs_trans_handle
*trans
)
10294 struct btrfs_fs_info
*fs_info
= btrfs_sb(inode
->i_sb
);
10295 struct extent_map_tree
*em_tree
= &BTRFS_I(inode
)->extent_tree
;
10296 struct extent_map
*em
;
10297 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
10298 struct btrfs_key ins
;
10299 u64 cur_offset
= start
;
10302 u64 last_alloc
= (u64
)-1;
10304 bool own_trans
= true;
10305 u64 end
= start
+ num_bytes
- 1;
10309 while (num_bytes
> 0) {
10311 trans
= btrfs_start_transaction(root
, 3);
10312 if (IS_ERR(trans
)) {
10313 ret
= PTR_ERR(trans
);
10318 cur_bytes
= min_t(u64
, num_bytes
, SZ_256M
);
10319 cur_bytes
= max(cur_bytes
, min_size
);
10321 * If we are severely fragmented we could end up with really
10322 * small allocations, so if the allocator is returning small
10323 * chunks lets make its job easier by only searching for those
10326 cur_bytes
= min(cur_bytes
, last_alloc
);
10327 ret
= btrfs_reserve_extent(root
, cur_bytes
, cur_bytes
,
10328 min_size
, 0, *alloc_hint
, &ins
, 1, 0);
10331 btrfs_end_transaction(trans
);
10334 btrfs_dec_block_group_reservations(fs_info
, ins
.objectid
);
10336 last_alloc
= ins
.offset
;
10337 ret
= insert_reserved_file_extent(trans
, inode
,
10338 cur_offset
, ins
.objectid
,
10339 ins
.offset
, ins
.offset
,
10340 ins
.offset
, 0, 0, 0,
10341 BTRFS_FILE_EXTENT_PREALLOC
);
10343 btrfs_free_reserved_extent(fs_info
, ins
.objectid
,
10345 btrfs_abort_transaction(trans
, ret
);
10347 btrfs_end_transaction(trans
);
10351 btrfs_drop_extent_cache(BTRFS_I(inode
), cur_offset
,
10352 cur_offset
+ ins
.offset
-1, 0);
10354 em
= alloc_extent_map();
10356 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC
,
10357 &BTRFS_I(inode
)->runtime_flags
);
10361 em
->start
= cur_offset
;
10362 em
->orig_start
= cur_offset
;
10363 em
->len
= ins
.offset
;
10364 em
->block_start
= ins
.objectid
;
10365 em
->block_len
= ins
.offset
;
10366 em
->orig_block_len
= ins
.offset
;
10367 em
->ram_bytes
= ins
.offset
;
10368 em
->bdev
= fs_info
->fs_devices
->latest_bdev
;
10369 set_bit(EXTENT_FLAG_PREALLOC
, &em
->flags
);
10370 em
->generation
= trans
->transid
;
10373 write_lock(&em_tree
->lock
);
10374 ret
= add_extent_mapping(em_tree
, em
, 1);
10375 write_unlock(&em_tree
->lock
);
10376 if (ret
!= -EEXIST
)
10378 btrfs_drop_extent_cache(BTRFS_I(inode
), cur_offset
,
10379 cur_offset
+ ins
.offset
- 1,
10382 free_extent_map(em
);
10384 num_bytes
-= ins
.offset
;
10385 cur_offset
+= ins
.offset
;
10386 *alloc_hint
= ins
.objectid
+ ins
.offset
;
10388 inode_inc_iversion(inode
);
10389 inode
->i_ctime
= current_time(inode
);
10390 BTRFS_I(inode
)->flags
|= BTRFS_INODE_PREALLOC
;
10391 if (!(mode
& FALLOC_FL_KEEP_SIZE
) &&
10392 (actual_len
> inode
->i_size
) &&
10393 (cur_offset
> inode
->i_size
)) {
10394 if (cur_offset
> actual_len
)
10395 i_size
= actual_len
;
10397 i_size
= cur_offset
;
10398 i_size_write(inode
, i_size
);
10399 btrfs_ordered_update_i_size(inode
, i_size
, NULL
);
10402 ret
= btrfs_update_inode(trans
, root
, inode
);
10405 btrfs_abort_transaction(trans
, ret
);
10407 btrfs_end_transaction(trans
);
10412 btrfs_end_transaction(trans
);
10414 if (cur_offset
< end
)
10415 btrfs_free_reserved_data_space(inode
, NULL
, cur_offset
,
10416 end
- cur_offset
+ 1);
10420 int btrfs_prealloc_file_range(struct inode
*inode
, int mode
,
10421 u64 start
, u64 num_bytes
, u64 min_size
,
10422 loff_t actual_len
, u64
*alloc_hint
)
10424 return __btrfs_prealloc_file_range(inode
, mode
, start
, num_bytes
,
10425 min_size
, actual_len
, alloc_hint
,
10429 int btrfs_prealloc_file_range_trans(struct inode
*inode
,
10430 struct btrfs_trans_handle
*trans
, int mode
,
10431 u64 start
, u64 num_bytes
, u64 min_size
,
10432 loff_t actual_len
, u64
*alloc_hint
)
10434 return __btrfs_prealloc_file_range(inode
, mode
, start
, num_bytes
,
10435 min_size
, actual_len
, alloc_hint
, trans
);
10438 static int btrfs_set_page_dirty(struct page
*page
)
10440 return __set_page_dirty_nobuffers(page
);
10443 static int btrfs_permission(struct inode
*inode
, int mask
)
10445 struct btrfs_root
*root
= BTRFS_I(inode
)->root
;
10446 umode_t mode
= inode
->i_mode
;
10448 if (mask
& MAY_WRITE
&&
10449 (S_ISREG(mode
) || S_ISDIR(mode
) || S_ISLNK(mode
))) {
10450 if (btrfs_root_readonly(root
))
10452 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_READONLY
)
10455 return generic_permission(inode
, mask
);
10458 static int btrfs_tmpfile(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
10460 struct btrfs_fs_info
*fs_info
= btrfs_sb(dir
->i_sb
);
10461 struct btrfs_trans_handle
*trans
;
10462 struct btrfs_root
*root
= BTRFS_I(dir
)->root
;
10463 struct inode
*inode
= NULL
;
10469 * 5 units required for adding orphan entry
10471 trans
= btrfs_start_transaction(root
, 5);
10473 return PTR_ERR(trans
);
10475 ret
= btrfs_find_free_ino(root
, &objectid
);
10479 inode
= btrfs_new_inode(trans
, root
, dir
, NULL
, 0,
10480 btrfs_ino(BTRFS_I(dir
)), objectid
, mode
, &index
);
10481 if (IS_ERR(inode
)) {
10482 ret
= PTR_ERR(inode
);
10487 inode
->i_fop
= &btrfs_file_operations
;
10488 inode
->i_op
= &btrfs_file_inode_operations
;
10490 inode
->i_mapping
->a_ops
= &btrfs_aops
;
10491 BTRFS_I(inode
)->io_tree
.ops
= &btrfs_extent_io_ops
;
10493 ret
= btrfs_init_inode_security(trans
, inode
, dir
, NULL
);
10497 ret
= btrfs_update_inode(trans
, root
, inode
);
10500 ret
= btrfs_orphan_add(trans
, BTRFS_I(inode
));
10505 * We set number of links to 0 in btrfs_new_inode(), and here we set
10506 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10509 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10511 set_nlink(inode
, 1);
10512 d_tmpfile(dentry
, inode
);
10513 unlock_new_inode(inode
);
10514 mark_inode_dirty(inode
);
10516 btrfs_end_transaction(trans
);
10518 discard_new_inode(inode
);
10519 btrfs_btree_balance_dirty(fs_info
);
10523 void btrfs_set_range_writeback(struct extent_io_tree
*tree
, u64 start
, u64 end
)
10525 struct inode
*inode
= tree
->private_data
;
10526 unsigned long index
= start
>> PAGE_SHIFT
;
10527 unsigned long end_index
= end
>> PAGE_SHIFT
;
10530 while (index
<= end_index
) {
10531 page
= find_get_page(inode
->i_mapping
, index
);
10532 ASSERT(page
); /* Pages should be in the extent_io_tree */
10533 set_page_writeback(page
);
10541 * Add an entry indicating a block group or device which is pinned by a
10542 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10543 * negative errno on failure.
10545 static int btrfs_add_swapfile_pin(struct inode
*inode
, void *ptr
,
10546 bool is_block_group
)
10548 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
10549 struct btrfs_swapfile_pin
*sp
, *entry
;
10550 struct rb_node
**p
;
10551 struct rb_node
*parent
= NULL
;
10553 sp
= kmalloc(sizeof(*sp
), GFP_NOFS
);
10558 sp
->is_block_group
= is_block_group
;
10560 spin_lock(&fs_info
->swapfile_pins_lock
);
10561 p
= &fs_info
->swapfile_pins
.rb_node
;
10564 entry
= rb_entry(parent
, struct btrfs_swapfile_pin
, node
);
10565 if (sp
->ptr
< entry
->ptr
||
10566 (sp
->ptr
== entry
->ptr
&& sp
->inode
< entry
->inode
)) {
10567 p
= &(*p
)->rb_left
;
10568 } else if (sp
->ptr
> entry
->ptr
||
10569 (sp
->ptr
== entry
->ptr
&& sp
->inode
> entry
->inode
)) {
10570 p
= &(*p
)->rb_right
;
10572 spin_unlock(&fs_info
->swapfile_pins_lock
);
10577 rb_link_node(&sp
->node
, parent
, p
);
10578 rb_insert_color(&sp
->node
, &fs_info
->swapfile_pins
);
10579 spin_unlock(&fs_info
->swapfile_pins_lock
);
10583 /* Free all of the entries pinned by this swapfile. */
10584 static void btrfs_free_swapfile_pins(struct inode
*inode
)
10586 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
10587 struct btrfs_swapfile_pin
*sp
;
10588 struct rb_node
*node
, *next
;
10590 spin_lock(&fs_info
->swapfile_pins_lock
);
10591 node
= rb_first(&fs_info
->swapfile_pins
);
10593 next
= rb_next(node
);
10594 sp
= rb_entry(node
, struct btrfs_swapfile_pin
, node
);
10595 if (sp
->inode
== inode
) {
10596 rb_erase(&sp
->node
, &fs_info
->swapfile_pins
);
10597 if (sp
->is_block_group
)
10598 btrfs_put_block_group(sp
->ptr
);
10603 spin_unlock(&fs_info
->swapfile_pins_lock
);
10606 struct btrfs_swap_info
{
10612 unsigned long nr_pages
;
10616 static int btrfs_add_swap_extent(struct swap_info_struct
*sis
,
10617 struct btrfs_swap_info
*bsi
)
10619 unsigned long nr_pages
;
10620 u64 first_ppage
, first_ppage_reported
, next_ppage
;
10623 first_ppage
= ALIGN(bsi
->block_start
, PAGE_SIZE
) >> PAGE_SHIFT
;
10624 next_ppage
= ALIGN_DOWN(bsi
->block_start
+ bsi
->block_len
,
10625 PAGE_SIZE
) >> PAGE_SHIFT
;
10627 if (first_ppage
>= next_ppage
)
10629 nr_pages
= next_ppage
- first_ppage
;
10631 first_ppage_reported
= first_ppage
;
10632 if (bsi
->start
== 0)
10633 first_ppage_reported
++;
10634 if (bsi
->lowest_ppage
> first_ppage_reported
)
10635 bsi
->lowest_ppage
= first_ppage_reported
;
10636 if (bsi
->highest_ppage
< (next_ppage
- 1))
10637 bsi
->highest_ppage
= next_ppage
- 1;
10639 ret
= add_swap_extent(sis
, bsi
->nr_pages
, nr_pages
, first_ppage
);
10642 bsi
->nr_extents
+= ret
;
10643 bsi
->nr_pages
+= nr_pages
;
10647 static void btrfs_swap_deactivate(struct file
*file
)
10649 struct inode
*inode
= file_inode(file
);
10651 btrfs_free_swapfile_pins(inode
);
10652 atomic_dec(&BTRFS_I(inode
)->root
->nr_swapfiles
);
10655 static int btrfs_swap_activate(struct swap_info_struct
*sis
, struct file
*file
,
10658 struct inode
*inode
= file_inode(file
);
10659 struct btrfs_fs_info
*fs_info
= BTRFS_I(inode
)->root
->fs_info
;
10660 struct extent_io_tree
*io_tree
= &BTRFS_I(inode
)->io_tree
;
10661 struct extent_state
*cached_state
= NULL
;
10662 struct extent_map
*em
= NULL
;
10663 struct btrfs_device
*device
= NULL
;
10664 struct btrfs_swap_info bsi
= {
10665 .lowest_ppage
= (sector_t
)-1ULL,
10672 * If the swap file was just created, make sure delalloc is done. If the
10673 * file changes again after this, the user is doing something stupid and
10674 * we don't really care.
10676 ret
= btrfs_wait_ordered_range(inode
, 0, (u64
)-1);
10681 * The inode is locked, so these flags won't change after we check them.
10683 if (BTRFS_I(inode
)->flags
& BTRFS_INODE_COMPRESS
) {
10684 btrfs_warn(fs_info
, "swapfile must not be compressed");
10687 if (!(BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATACOW
)) {
10688 btrfs_warn(fs_info
, "swapfile must not be copy-on-write");
10691 if (!(BTRFS_I(inode
)->flags
& BTRFS_INODE_NODATASUM
)) {
10692 btrfs_warn(fs_info
, "swapfile must not be checksummed");
10697 * Balance or device remove/replace/resize can move stuff around from
10698 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10699 * concurrently while we are mapping the swap extents, and
10700 * fs_info->swapfile_pins prevents them from running while the swap file
10701 * is active and moving the extents. Note that this also prevents a
10702 * concurrent device add which isn't actually necessary, but it's not
10703 * really worth the trouble to allow it.
10705 if (test_and_set_bit(BTRFS_FS_EXCL_OP
, &fs_info
->flags
)) {
10706 btrfs_warn(fs_info
,
10707 "cannot activate swapfile while exclusive operation is running");
10711 * Snapshots can create extents which require COW even if NODATACOW is
10712 * set. We use this counter to prevent snapshots. We must increment it
10713 * before walking the extents because we don't want a concurrent
10714 * snapshot to run after we've already checked the extents.
10716 atomic_inc(&BTRFS_I(inode
)->root
->nr_swapfiles
);
10718 isize
= ALIGN_DOWN(inode
->i_size
, fs_info
->sectorsize
);
10720 lock_extent_bits(io_tree
, 0, isize
- 1, &cached_state
);
10722 while (start
< isize
) {
10723 u64 logical_block_start
, physical_block_start
;
10724 struct btrfs_block_group_cache
*bg
;
10725 u64 len
= isize
- start
;
10727 em
= btrfs_get_extent(BTRFS_I(inode
), NULL
, 0, start
, len
, 0);
10733 if (em
->block_start
== EXTENT_MAP_HOLE
) {
10734 btrfs_warn(fs_info
, "swapfile must not have holes");
10738 if (em
->block_start
== EXTENT_MAP_INLINE
) {
10740 * It's unlikely we'll ever actually find ourselves
10741 * here, as a file small enough to fit inline won't be
10742 * big enough to store more than the swap header, but in
10743 * case something changes in the future, let's catch it
10744 * here rather than later.
10746 btrfs_warn(fs_info
, "swapfile must not be inline");
10750 if (test_bit(EXTENT_FLAG_COMPRESSED
, &em
->flags
)) {
10751 btrfs_warn(fs_info
, "swapfile must not be compressed");
10756 logical_block_start
= em
->block_start
+ (start
- em
->start
);
10757 len
= min(len
, em
->len
- (start
- em
->start
));
10758 free_extent_map(em
);
10761 ret
= can_nocow_extent(inode
, start
, &len
, NULL
, NULL
, NULL
);
10767 btrfs_warn(fs_info
,
10768 "swapfile must not be copy-on-write");
10773 em
= btrfs_get_chunk_map(fs_info
, logical_block_start
, len
);
10779 if (em
->map_lookup
->type
& BTRFS_BLOCK_GROUP_PROFILE_MASK
) {
10780 btrfs_warn(fs_info
,
10781 "swapfile must have single data profile");
10786 if (device
== NULL
) {
10787 device
= em
->map_lookup
->stripes
[0].dev
;
10788 ret
= btrfs_add_swapfile_pin(inode
, device
, false);
10793 } else if (device
!= em
->map_lookup
->stripes
[0].dev
) {
10794 btrfs_warn(fs_info
, "swapfile must be on one device");
10799 physical_block_start
= (em
->map_lookup
->stripes
[0].physical
+
10800 (logical_block_start
- em
->start
));
10801 len
= min(len
, em
->len
- (logical_block_start
- em
->start
));
10802 free_extent_map(em
);
10805 bg
= btrfs_lookup_block_group(fs_info
, logical_block_start
);
10807 btrfs_warn(fs_info
,
10808 "could not find block group containing swapfile");
10813 ret
= btrfs_add_swapfile_pin(inode
, bg
, true);
10815 btrfs_put_block_group(bg
);
10822 if (bsi
.block_len
&&
10823 bsi
.block_start
+ bsi
.block_len
== physical_block_start
) {
10824 bsi
.block_len
+= len
;
10826 if (bsi
.block_len
) {
10827 ret
= btrfs_add_swap_extent(sis
, &bsi
);
10832 bsi
.block_start
= physical_block_start
;
10833 bsi
.block_len
= len
;
10840 ret
= btrfs_add_swap_extent(sis
, &bsi
);
10843 if (!IS_ERR_OR_NULL(em
))
10844 free_extent_map(em
);
10846 unlock_extent_cached(io_tree
, 0, isize
- 1, &cached_state
);
10849 btrfs_swap_deactivate(file
);
10851 clear_bit(BTRFS_FS_EXCL_OP
, &fs_info
->flags
);
10857 sis
->bdev
= device
->bdev
;
10858 *span
= bsi
.highest_ppage
- bsi
.lowest_ppage
+ 1;
10859 sis
->max
= bsi
.nr_pages
;
10860 sis
->pages
= bsi
.nr_pages
- 1;
10861 sis
->highest_bit
= bsi
.nr_pages
- 1;
10862 return bsi
.nr_extents
;
10865 static void btrfs_swap_deactivate(struct file
*file
)
10869 static int btrfs_swap_activate(struct swap_info_struct
*sis
, struct file
*file
,
10872 return -EOPNOTSUPP
;
10876 static const struct inode_operations btrfs_dir_inode_operations
= {
10877 .getattr
= btrfs_getattr
,
10878 .lookup
= btrfs_lookup
,
10879 .create
= btrfs_create
,
10880 .unlink
= btrfs_unlink
,
10881 .link
= btrfs_link
,
10882 .mkdir
= btrfs_mkdir
,
10883 .rmdir
= btrfs_rmdir
,
10884 .rename
= btrfs_rename2
,
10885 .symlink
= btrfs_symlink
,
10886 .setattr
= btrfs_setattr
,
10887 .mknod
= btrfs_mknod
,
10888 .listxattr
= btrfs_listxattr
,
10889 .permission
= btrfs_permission
,
10890 .get_acl
= btrfs_get_acl
,
10891 .set_acl
= btrfs_set_acl
,
10892 .update_time
= btrfs_update_time
,
10893 .tmpfile
= btrfs_tmpfile
,
10895 static const struct inode_operations btrfs_dir_ro_inode_operations
= {
10896 .lookup
= btrfs_lookup
,
10897 .permission
= btrfs_permission
,
10898 .update_time
= btrfs_update_time
,
10901 static const struct file_operations btrfs_dir_file_operations
= {
10902 .llseek
= generic_file_llseek
,
10903 .read
= generic_read_dir
,
10904 .iterate_shared
= btrfs_real_readdir
,
10905 .open
= btrfs_opendir
,
10906 .unlocked_ioctl
= btrfs_ioctl
,
10907 #ifdef CONFIG_COMPAT
10908 .compat_ioctl
= btrfs_compat_ioctl
,
10910 .release
= btrfs_release_file
,
10911 .fsync
= btrfs_sync_file
,
10914 static const struct extent_io_ops btrfs_extent_io_ops
= {
10915 /* mandatory callbacks */
10916 .submit_bio_hook
= btrfs_submit_bio_hook
,
10917 .readpage_end_io_hook
= btrfs_readpage_end_io_hook
,
10921 * btrfs doesn't support the bmap operation because swapfiles
10922 * use bmap to make a mapping of extents in the file. They assume
10923 * these extents won't change over the life of the file and they
10924 * use the bmap result to do IO directly to the drive.
10926 * the btrfs bmap call would return logical addresses that aren't
10927 * suitable for IO and they also will change frequently as COW
10928 * operations happen. So, swapfile + btrfs == corruption.
10930 * For now we're avoiding this by dropping bmap.
10932 static const struct address_space_operations btrfs_aops
= {
10933 .readpage
= btrfs_readpage
,
10934 .writepage
= btrfs_writepage
,
10935 .writepages
= btrfs_writepages
,
10936 .readpages
= btrfs_readpages
,
10937 .direct_IO
= btrfs_direct_IO
,
10938 .invalidatepage
= btrfs_invalidatepage
,
10939 .releasepage
= btrfs_releasepage
,
10940 .set_page_dirty
= btrfs_set_page_dirty
,
10941 .error_remove_page
= generic_error_remove_page
,
10942 .swap_activate
= btrfs_swap_activate
,
10943 .swap_deactivate
= btrfs_swap_deactivate
,
10946 static const struct inode_operations btrfs_file_inode_operations
= {
10947 .getattr
= btrfs_getattr
,
10948 .setattr
= btrfs_setattr
,
10949 .listxattr
= btrfs_listxattr
,
10950 .permission
= btrfs_permission
,
10951 .fiemap
= btrfs_fiemap
,
10952 .get_acl
= btrfs_get_acl
,
10953 .set_acl
= btrfs_set_acl
,
10954 .update_time
= btrfs_update_time
,
10956 static const struct inode_operations btrfs_special_inode_operations
= {
10957 .getattr
= btrfs_getattr
,
10958 .setattr
= btrfs_setattr
,
10959 .permission
= btrfs_permission
,
10960 .listxattr
= btrfs_listxattr
,
10961 .get_acl
= btrfs_get_acl
,
10962 .set_acl
= btrfs_set_acl
,
10963 .update_time
= btrfs_update_time
,
10965 static const struct inode_operations btrfs_symlink_inode_operations
= {
10966 .get_link
= page_get_link
,
10967 .getattr
= btrfs_getattr
,
10968 .setattr
= btrfs_setattr
,
10969 .permission
= btrfs_permission
,
10970 .listxattr
= btrfs_listxattr
,
10971 .update_time
= btrfs_update_time
,
10974 const struct dentry_operations btrfs_dentry_operations
= {
10975 .d_delete
= btrfs_dentry_delete
,