Linux 5.6.13
[linux/fpc-iii.git] / fs / btrfs / inode.c
blobd267eb5caa7b694a55e733ecd070af5a749a6cc8
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (C) 2007 Oracle. All rights reserved.
4 */
6 #include <linux/kernel.h>
7 #include <linux/bio.h>
8 #include <linux/buffer_head.h>
9 #include <linux/file.h>
10 #include <linux/fs.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>
33 #include "misc.h"
34 #include "ctree.h"
35 #include "disk-io.h"
36 #include "transaction.h"
37 #include "btrfs_inode.h"
38 #include "print-tree.h"
39 #include "ordered-data.h"
40 #include "xattr.h"
41 #include "tree-log.h"
42 #include "volumes.h"
43 #include "compression.h"
44 #include "locking.h"
45 #include "free-space-cache.h"
46 #include "inode-map.h"
47 #include "props.h"
48 #include "qgroup.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 {
58 u64 reserve;
59 u64 unsubmitted_oe_range_start;
60 u64 unsubmitted_oe_range_end;
61 int overwrite;
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_special_inode_operations;
67 static const struct inode_operations btrfs_file_inode_operations;
68 static const struct address_space_operations btrfs_aops;
69 static const struct file_operations btrfs_dir_file_operations;
70 static const struct extent_io_ops btrfs_extent_io_ops;
72 static struct kmem_cache *btrfs_inode_cachep;
73 struct kmem_cache *btrfs_trans_handle_cachep;
74 struct kmem_cache *btrfs_path_cachep;
75 struct kmem_cache *btrfs_free_space_cachep;
76 struct kmem_cache *btrfs_free_space_bitmap_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,
89 int type);
91 static void __endio_write_update_ordered(struct inode *inode,
92 const u64 offset, const u64 bytes,
93 const bool uptodate);
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;
114 struct page *page;
116 while (index <= end_index) {
117 page = find_get_page(inode->i_mapping, index);
118 index++;
119 if (!page)
120 continue;
121 ClearPagePrivate2(page);
122 put_page(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)) {
131 offset += PAGE_SIZE;
132 bytes -= PAGE_SIZE;
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;
145 #endif
147 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
148 struct inode *inode, struct inode *dir,
149 const struct qstr *qstr)
151 int err;
153 err = btrfs_init_acl(trans, inode, dir);
154 if (!err)
155 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
156 return err;
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,
168 int compress_type,
169 struct page **compressed_pages)
171 struct extent_buffer *leaf;
172 struct page *page = NULL;
173 char *kaddr;
174 unsigned long ptr;
175 struct btrfs_file_extent_item *ei;
176 int ret;
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;
190 size_t datasize;
192 key.objectid = btrfs_ino(BTRFS_I(inode));
193 key.offset = start;
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,
199 datasize);
200 if (ret)
201 goto fail;
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) {
214 struct page *cpage;
215 int i = 0;
216 while (compressed_size > 0) {
217 cpage = compressed_pages[i];
218 cur_size = min_t(unsigned long, compressed_size,
219 PAGE_SIZE);
221 kaddr = kmap_atomic(cpage);
222 write_extent_buffer(leaf, kaddr, ptr, cur_size);
223 kunmap_atomic(kaddr);
225 i++;
226 ptr += cur_size;
227 compressed_size -= cur_size;
229 btrfs_set_file_extent_compression(leaf, ei,
230 compress_type);
231 } else {
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);
239 put_page(page);
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);
256 fail:
257 return ret;
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,
268 int compress_type,
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;
279 int ret;
280 struct btrfs_path *path;
281 int extent_inserted = 0;
282 u32 extent_item_size;
284 if (compressed_size)
285 data_len = compressed_size;
287 if (start > 0 ||
288 actual_end > fs_info->sectorsize ||
289 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
290 (!compressed_size &&
291 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
292 end + 1 < isize ||
293 data_len > fs_info->max_inline) {
294 return 1;
297 path = btrfs_alloc_path();
298 if (!path)
299 return -ENOMEM;
301 trans = btrfs_join_transaction(root);
302 if (IS_ERR(trans)) {
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(
310 compressed_size);
311 else
312 extent_item_size = btrfs_file_extent_calc_inline_size(
313 inline_len);
315 ret = __btrfs_drop_extents(trans, root, inode, path,
316 start, aligned_end, NULL,
317 1, 1, extent_item_size, &extent_inserted);
318 if (ret) {
319 btrfs_abort_transaction(trans, ret);
320 goto out;
323 if (isize > actual_end)
324 inline_len = min_t(u64, isize, actual_end);
325 ret = insert_inline_extent(trans, path, extent_inserted,
326 root, inode, start,
327 inline_len, compressed_size,
328 compress_type, compressed_pages);
329 if (ret && ret != -ENOSPC) {
330 btrfs_abort_transaction(trans, ret);
331 goto out;
332 } else if (ret == -ENOSPC) {
333 ret = 1;
334 goto out;
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);
339 out:
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);
349 return ret;
352 struct async_extent {
353 u64 start;
354 u64 ram_size;
355 u64 compressed_size;
356 struct page **pages;
357 unsigned long nr_pages;
358 int compress_type;
359 struct list_head list;
362 struct async_chunk {
363 struct inode *inode;
364 struct page *locked_page;
365 u64 start;
366 u64 end;
367 unsigned int write_flags;
368 struct list_head extents;
369 struct cgroup_subsys_state *blkcg_css;
370 struct btrfs_work work;
371 atomic_t *pending;
374 struct async_cow {
375 /* Number of chunks in flight; must be first in the structure */
376 atomic_t num_chunks;
377 struct async_chunk chunks[];
380 static noinline int add_async_extent(struct async_chunk *cow,
381 u64 start, u64 ram_size,
382 u64 compressed_size,
383 struct page **pages,
384 unsigned long nr_pages,
385 int compress_type)
387 struct async_extent *async_extent;
389 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
390 BUG_ON(!async_extent); /* -ENOMEM */
391 async_extent->start = start;
392 async_extent->ram_size = ram_size;
393 async_extent->compressed_size = compressed_size;
394 async_extent->pages = pages;
395 async_extent->nr_pages = nr_pages;
396 async_extent->compress_type = compress_type;
397 list_add_tail(&async_extent->list, &cow->extents);
398 return 0;
402 * Check if the inode has flags compatible with compression
404 static inline bool inode_can_compress(struct inode *inode)
406 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW ||
407 BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
408 return false;
409 return true;
413 * Check if the inode needs to be submitted to compression, based on mount
414 * options, defragmentation, properties or heuristics.
416 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
418 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
420 if (!inode_can_compress(inode)) {
421 WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
422 KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
423 btrfs_ino(BTRFS_I(inode)));
424 return 0;
426 /* force compress */
427 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
428 return 1;
429 /* defrag ioctl */
430 if (BTRFS_I(inode)->defrag_compress)
431 return 1;
432 /* bad compression ratios */
433 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
434 return 0;
435 if (btrfs_test_opt(fs_info, COMPRESS) ||
436 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
437 BTRFS_I(inode)->prop_compress)
438 return btrfs_compress_heuristic(inode, start, end);
439 return 0;
442 static inline void inode_should_defrag(struct btrfs_inode *inode,
443 u64 start, u64 end, u64 num_bytes, u64 small_write)
445 /* If this is a small write inside eof, kick off a defrag */
446 if (num_bytes < small_write &&
447 (start > 0 || end + 1 < inode->disk_i_size))
448 btrfs_add_inode_defrag(NULL, inode);
452 * we create compressed extents in two phases. The first
453 * phase compresses a range of pages that have already been
454 * locked (both pages and state bits are locked).
456 * This is done inside an ordered work queue, and the compression
457 * is spread across many cpus. The actual IO submission is step
458 * two, and the ordered work queue takes care of making sure that
459 * happens in the same order things were put onto the queue by
460 * writepages and friends.
462 * If this code finds it can't get good compression, it puts an
463 * entry onto the work queue to write the uncompressed bytes. This
464 * makes sure that both compressed inodes and uncompressed inodes
465 * are written in the same order that the flusher thread sent them
466 * down.
468 static noinline int compress_file_range(struct async_chunk *async_chunk)
470 struct inode *inode = async_chunk->inode;
471 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
472 u64 blocksize = fs_info->sectorsize;
473 u64 start = async_chunk->start;
474 u64 end = async_chunk->end;
475 u64 actual_end;
476 u64 i_size;
477 int ret = 0;
478 struct page **pages = NULL;
479 unsigned long nr_pages;
480 unsigned long total_compressed = 0;
481 unsigned long total_in = 0;
482 int i;
483 int will_compress;
484 int compress_type = fs_info->compress_type;
485 int compressed_extents = 0;
486 int redirty = 0;
488 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
489 SZ_16K);
492 * We need to save i_size before now because it could change in between
493 * us evaluating the size and assigning it. This is because we lock and
494 * unlock the page in truncate and fallocate, and then modify the i_size
495 * later on.
497 * The barriers are to emulate READ_ONCE, remove that once i_size_read
498 * does that for us.
500 barrier();
501 i_size = i_size_read(inode);
502 barrier();
503 actual_end = min_t(u64, i_size, end + 1);
504 again:
505 will_compress = 0;
506 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
507 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
508 nr_pages = min_t(unsigned long, nr_pages,
509 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
512 * we don't want to send crud past the end of i_size through
513 * compression, that's just a waste of CPU time. So, if the
514 * end of the file is before the start of our current
515 * requested range of bytes, we bail out to the uncompressed
516 * cleanup code that can deal with all of this.
518 * It isn't really the fastest way to fix things, but this is a
519 * very uncommon corner.
521 if (actual_end <= start)
522 goto cleanup_and_bail_uncompressed;
524 total_compressed = actual_end - start;
527 * skip compression for a small file range(<=blocksize) that
528 * isn't an inline extent, since it doesn't save disk space at all.
530 if (total_compressed <= blocksize &&
531 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
532 goto cleanup_and_bail_uncompressed;
534 total_compressed = min_t(unsigned long, total_compressed,
535 BTRFS_MAX_UNCOMPRESSED);
536 total_in = 0;
537 ret = 0;
540 * we do compression for mount -o compress and when the
541 * inode has not been flagged as nocompress. This flag can
542 * change at any time if we discover bad compression ratios.
544 if (inode_need_compress(inode, start, end)) {
545 WARN_ON(pages);
546 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
547 if (!pages) {
548 /* just bail out to the uncompressed code */
549 nr_pages = 0;
550 goto cont;
553 if (BTRFS_I(inode)->defrag_compress)
554 compress_type = BTRFS_I(inode)->defrag_compress;
555 else if (BTRFS_I(inode)->prop_compress)
556 compress_type = BTRFS_I(inode)->prop_compress;
559 * we need to call clear_page_dirty_for_io on each
560 * page in the range. Otherwise applications with the file
561 * mmap'd can wander in and change the page contents while
562 * we are compressing them.
564 * If the compression fails for any reason, we set the pages
565 * dirty again later on.
567 * Note that the remaining part is redirtied, the start pointer
568 * has moved, the end is the original one.
570 if (!redirty) {
571 extent_range_clear_dirty_for_io(inode, start, end);
572 redirty = 1;
575 /* Compression level is applied here and only here */
576 ret = btrfs_compress_pages(
577 compress_type | (fs_info->compress_level << 4),
578 inode->i_mapping, start,
579 pages,
580 &nr_pages,
581 &total_in,
582 &total_compressed);
584 if (!ret) {
585 unsigned long offset = offset_in_page(total_compressed);
586 struct page *page = pages[nr_pages - 1];
587 char *kaddr;
589 /* zero the tail end of the last page, we might be
590 * sending it down to disk
592 if (offset) {
593 kaddr = kmap_atomic(page);
594 memset(kaddr + offset, 0,
595 PAGE_SIZE - offset);
596 kunmap_atomic(kaddr);
598 will_compress = 1;
601 cont:
602 if (start == 0) {
603 /* lets try to make an inline extent */
604 if (ret || total_in < actual_end) {
605 /* we didn't compress the entire range, try
606 * to make an uncompressed inline extent.
608 ret = cow_file_range_inline(inode, start, end, 0,
609 BTRFS_COMPRESS_NONE, NULL);
610 } else {
611 /* try making a compressed inline extent */
612 ret = cow_file_range_inline(inode, start, end,
613 total_compressed,
614 compress_type, pages);
616 if (ret <= 0) {
617 unsigned long clear_flags = EXTENT_DELALLOC |
618 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
619 EXTENT_DO_ACCOUNTING;
620 unsigned long page_error_op;
622 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
625 * inline extent creation worked or returned error,
626 * we don't need to create any more async work items.
627 * Unlock and free up our temp pages.
629 * We use DO_ACCOUNTING here because we need the
630 * delalloc_release_metadata to be done _after_ we drop
631 * our outstanding extent for clearing delalloc for this
632 * range.
634 extent_clear_unlock_delalloc(inode, start, end, NULL,
635 clear_flags,
636 PAGE_UNLOCK |
637 PAGE_CLEAR_DIRTY |
638 PAGE_SET_WRITEBACK |
639 page_error_op |
640 PAGE_END_WRITEBACK);
642 for (i = 0; i < nr_pages; i++) {
643 WARN_ON(pages[i]->mapping);
644 put_page(pages[i]);
646 kfree(pages);
648 return 0;
652 if (will_compress) {
654 * we aren't doing an inline extent round the compressed size
655 * up to a block size boundary so the allocator does sane
656 * things
658 total_compressed = ALIGN(total_compressed, blocksize);
661 * one last check to make sure the compression is really a
662 * win, compare the page count read with the blocks on disk,
663 * compression must free at least one sector size
665 total_in = ALIGN(total_in, PAGE_SIZE);
666 if (total_compressed + blocksize <= total_in) {
667 compressed_extents++;
670 * The async work queues will take care of doing actual
671 * allocation on disk for these compressed pages, and
672 * will submit them to the elevator.
674 add_async_extent(async_chunk, start, total_in,
675 total_compressed, pages, nr_pages,
676 compress_type);
678 if (start + total_in < end) {
679 start += total_in;
680 pages = NULL;
681 cond_resched();
682 goto again;
684 return compressed_extents;
687 if (pages) {
689 * the compression code ran but failed to make things smaller,
690 * free any pages it allocated and our page pointer array
692 for (i = 0; i < nr_pages; i++) {
693 WARN_ON(pages[i]->mapping);
694 put_page(pages[i]);
696 kfree(pages);
697 pages = NULL;
698 total_compressed = 0;
699 nr_pages = 0;
701 /* flag the file so we don't compress in the future */
702 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
703 !(BTRFS_I(inode)->prop_compress)) {
704 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
707 cleanup_and_bail_uncompressed:
709 * No compression, but we still need to write the pages in the file
710 * we've been given so far. redirty the locked page if it corresponds
711 * to our extent and set things up for the async work queue to run
712 * cow_file_range to do the normal delalloc dance.
714 if (async_chunk->locked_page &&
715 (page_offset(async_chunk->locked_page) >= start &&
716 page_offset(async_chunk->locked_page)) <= end) {
717 __set_page_dirty_nobuffers(async_chunk->locked_page);
718 /* unlocked later on in the async handlers */
721 if (redirty)
722 extent_range_redirty_for_io(inode, start, end);
723 add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
724 BTRFS_COMPRESS_NONE);
725 compressed_extents++;
727 return compressed_extents;
730 static void free_async_extent_pages(struct async_extent *async_extent)
732 int i;
734 if (!async_extent->pages)
735 return;
737 for (i = 0; i < async_extent->nr_pages; i++) {
738 WARN_ON(async_extent->pages[i]->mapping);
739 put_page(async_extent->pages[i]);
741 kfree(async_extent->pages);
742 async_extent->nr_pages = 0;
743 async_extent->pages = NULL;
747 * phase two of compressed writeback. This is the ordered portion
748 * of the code, which only gets called in the order the work was
749 * queued. We walk all the async extents created by compress_file_range
750 * and send them down to the disk.
752 static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
754 struct inode *inode = async_chunk->inode;
755 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
756 struct async_extent *async_extent;
757 u64 alloc_hint = 0;
758 struct btrfs_key ins;
759 struct extent_map *em;
760 struct btrfs_root *root = BTRFS_I(inode)->root;
761 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
762 int ret = 0;
764 again:
765 while (!list_empty(&async_chunk->extents)) {
766 async_extent = list_entry(async_chunk->extents.next,
767 struct async_extent, list);
768 list_del(&async_extent->list);
770 retry:
771 lock_extent(io_tree, async_extent->start,
772 async_extent->start + async_extent->ram_size - 1);
773 /* did the compression code fall back to uncompressed IO? */
774 if (!async_extent->pages) {
775 int page_started = 0;
776 unsigned long nr_written = 0;
778 /* allocate blocks */
779 ret = cow_file_range(inode, async_chunk->locked_page,
780 async_extent->start,
781 async_extent->start +
782 async_extent->ram_size - 1,
783 &page_started, &nr_written, 0);
785 /* JDM XXX */
788 * if page_started, cow_file_range inserted an
789 * inline extent and took care of all the unlocking
790 * and IO for us. Otherwise, we need to submit
791 * all those pages down to the drive.
793 if (!page_started && !ret)
794 extent_write_locked_range(inode,
795 async_extent->start,
796 async_extent->start +
797 async_extent->ram_size - 1,
798 WB_SYNC_ALL);
799 else if (ret && async_chunk->locked_page)
800 unlock_page(async_chunk->locked_page);
801 kfree(async_extent);
802 cond_resched();
803 continue;
806 ret = btrfs_reserve_extent(root, async_extent->ram_size,
807 async_extent->compressed_size,
808 async_extent->compressed_size,
809 0, alloc_hint, &ins, 1, 1);
810 if (ret) {
811 free_async_extent_pages(async_extent);
813 if (ret == -ENOSPC) {
814 unlock_extent(io_tree, async_extent->start,
815 async_extent->start +
816 async_extent->ram_size - 1);
819 * we need to redirty the pages if we decide to
820 * fallback to uncompressed IO, otherwise we
821 * will not submit these pages down to lower
822 * layers.
824 extent_range_redirty_for_io(inode,
825 async_extent->start,
826 async_extent->start +
827 async_extent->ram_size - 1);
829 goto retry;
831 goto out_free;
834 * here we're doing allocation and writeback of the
835 * compressed pages
837 em = create_io_em(inode, async_extent->start,
838 async_extent->ram_size, /* len */
839 async_extent->start, /* orig_start */
840 ins.objectid, /* block_start */
841 ins.offset, /* block_len */
842 ins.offset, /* orig_block_len */
843 async_extent->ram_size, /* ram_bytes */
844 async_extent->compress_type,
845 BTRFS_ORDERED_COMPRESSED);
846 if (IS_ERR(em))
847 /* ret value is not necessary due to void function */
848 goto out_free_reserve;
849 free_extent_map(em);
851 ret = btrfs_add_ordered_extent_compress(inode,
852 async_extent->start,
853 ins.objectid,
854 async_extent->ram_size,
855 ins.offset,
856 BTRFS_ORDERED_COMPRESSED,
857 async_extent->compress_type);
858 if (ret) {
859 btrfs_drop_extent_cache(BTRFS_I(inode),
860 async_extent->start,
861 async_extent->start +
862 async_extent->ram_size - 1, 0);
863 goto out_free_reserve;
865 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
868 * clear dirty, set writeback and unlock the pages.
870 extent_clear_unlock_delalloc(inode, async_extent->start,
871 async_extent->start +
872 async_extent->ram_size - 1,
873 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
874 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
875 PAGE_SET_WRITEBACK);
876 if (btrfs_submit_compressed_write(inode,
877 async_extent->start,
878 async_extent->ram_size,
879 ins.objectid,
880 ins.offset, async_extent->pages,
881 async_extent->nr_pages,
882 async_chunk->write_flags,
883 async_chunk->blkcg_css)) {
884 struct page *p = async_extent->pages[0];
885 const u64 start = async_extent->start;
886 const u64 end = start + async_extent->ram_size - 1;
888 p->mapping = inode->i_mapping;
889 btrfs_writepage_endio_finish_ordered(p, start, end, 0);
891 p->mapping = NULL;
892 extent_clear_unlock_delalloc(inode, start, end,
893 NULL, 0,
894 PAGE_END_WRITEBACK |
895 PAGE_SET_ERROR);
896 free_async_extent_pages(async_extent);
898 alloc_hint = ins.objectid + ins.offset;
899 kfree(async_extent);
900 cond_resched();
902 return;
903 out_free_reserve:
904 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
905 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
906 out_free:
907 extent_clear_unlock_delalloc(inode, async_extent->start,
908 async_extent->start +
909 async_extent->ram_size - 1,
910 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
911 EXTENT_DELALLOC_NEW |
912 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
913 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
914 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
915 PAGE_SET_ERROR);
916 free_async_extent_pages(async_extent);
917 kfree(async_extent);
918 goto again;
921 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
922 u64 num_bytes)
924 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
925 struct extent_map *em;
926 u64 alloc_hint = 0;
928 read_lock(&em_tree->lock);
929 em = search_extent_mapping(em_tree, start, num_bytes);
930 if (em) {
932 * if block start isn't an actual block number then find the
933 * first block in this inode and use that as a hint. If that
934 * block is also bogus then just don't worry about it.
936 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
937 free_extent_map(em);
938 em = search_extent_mapping(em_tree, 0, 0);
939 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
940 alloc_hint = em->block_start;
941 if (em)
942 free_extent_map(em);
943 } else {
944 alloc_hint = em->block_start;
945 free_extent_map(em);
948 read_unlock(&em_tree->lock);
950 return alloc_hint;
954 * when extent_io.c finds a delayed allocation range in the file,
955 * the call backs end up in this code. The basic idea is to
956 * allocate extents on disk for the range, and create ordered data structs
957 * in ram to track those extents.
959 * locked_page is the page that writepage had locked already. We use
960 * it to make sure we don't do extra locks or unlocks.
962 * *page_started is set to one if we unlock locked_page and do everything
963 * required to start IO on it. It may be clean and already done with
964 * IO when we return.
966 static noinline int cow_file_range(struct inode *inode,
967 struct page *locked_page,
968 u64 start, u64 end, int *page_started,
969 unsigned long *nr_written, int unlock)
971 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
972 struct btrfs_root *root = BTRFS_I(inode)->root;
973 u64 alloc_hint = 0;
974 u64 num_bytes;
975 unsigned long ram_size;
976 u64 cur_alloc_size = 0;
977 u64 blocksize = fs_info->sectorsize;
978 struct btrfs_key ins;
979 struct extent_map *em;
980 unsigned clear_bits;
981 unsigned long page_ops;
982 bool extent_reserved = false;
983 int ret = 0;
985 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
986 WARN_ON_ONCE(1);
987 ret = -EINVAL;
988 goto out_unlock;
991 num_bytes = ALIGN(end - start + 1, blocksize);
992 num_bytes = max(blocksize, num_bytes);
993 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
995 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
997 if (start == 0) {
998 /* lets try to make an inline extent */
999 ret = cow_file_range_inline(inode, start, end, 0,
1000 BTRFS_COMPRESS_NONE, NULL);
1001 if (ret == 0) {
1003 * We use DO_ACCOUNTING here because we need the
1004 * delalloc_release_metadata to be run _after_ we drop
1005 * our outstanding extent for clearing delalloc for this
1006 * range.
1008 extent_clear_unlock_delalloc(inode, start, end, NULL,
1009 EXTENT_LOCKED | EXTENT_DELALLOC |
1010 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1011 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1012 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1013 PAGE_END_WRITEBACK);
1014 *nr_written = *nr_written +
1015 (end - start + PAGE_SIZE) / PAGE_SIZE;
1016 *page_started = 1;
1017 goto out;
1018 } else if (ret < 0) {
1019 goto out_unlock;
1023 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
1024 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1025 start + num_bytes - 1, 0);
1027 while (num_bytes > 0) {
1028 cur_alloc_size = num_bytes;
1029 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1030 fs_info->sectorsize, 0, alloc_hint,
1031 &ins, 1, 1);
1032 if (ret < 0)
1033 goto out_unlock;
1034 cur_alloc_size = ins.offset;
1035 extent_reserved = true;
1037 ram_size = ins.offset;
1038 em = create_io_em(inode, start, ins.offset, /* len */
1039 start, /* orig_start */
1040 ins.objectid, /* block_start */
1041 ins.offset, /* block_len */
1042 ins.offset, /* orig_block_len */
1043 ram_size, /* ram_bytes */
1044 BTRFS_COMPRESS_NONE, /* compress_type */
1045 BTRFS_ORDERED_REGULAR /* type */);
1046 if (IS_ERR(em)) {
1047 ret = PTR_ERR(em);
1048 goto out_reserve;
1050 free_extent_map(em);
1052 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1053 ram_size, cur_alloc_size, 0);
1054 if (ret)
1055 goto out_drop_extent_cache;
1057 if (root->root_key.objectid ==
1058 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1059 ret = btrfs_reloc_clone_csums(inode, start,
1060 cur_alloc_size);
1062 * Only drop cache here, and process as normal.
1064 * We must not allow extent_clear_unlock_delalloc()
1065 * at out_unlock label to free meta of this ordered
1066 * extent, as its meta should be freed by
1067 * btrfs_finish_ordered_io().
1069 * So we must continue until @start is increased to
1070 * skip current ordered extent.
1072 if (ret)
1073 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1074 start + ram_size - 1, 0);
1077 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1079 /* we're not doing compressed IO, don't unlock the first
1080 * page (which the caller expects to stay locked), don't
1081 * clear any dirty bits and don't set any writeback bits
1083 * Do set the Private2 bit so we know this page was properly
1084 * setup for writepage
1086 page_ops = unlock ? PAGE_UNLOCK : 0;
1087 page_ops |= PAGE_SET_PRIVATE2;
1089 extent_clear_unlock_delalloc(inode, start,
1090 start + ram_size - 1,
1091 locked_page,
1092 EXTENT_LOCKED | EXTENT_DELALLOC,
1093 page_ops);
1094 if (num_bytes < cur_alloc_size)
1095 num_bytes = 0;
1096 else
1097 num_bytes -= cur_alloc_size;
1098 alloc_hint = ins.objectid + ins.offset;
1099 start += cur_alloc_size;
1100 extent_reserved = false;
1103 * btrfs_reloc_clone_csums() error, since start is increased
1104 * extent_clear_unlock_delalloc() at out_unlock label won't
1105 * free metadata of current ordered extent, we're OK to exit.
1107 if (ret)
1108 goto out_unlock;
1110 out:
1111 return ret;
1113 out_drop_extent_cache:
1114 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1115 out_reserve:
1116 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1117 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1118 out_unlock:
1119 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1120 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1121 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1122 PAGE_END_WRITEBACK;
1124 * If we reserved an extent for our delalloc range (or a subrange) and
1125 * failed to create the respective ordered extent, then it means that
1126 * when we reserved the extent we decremented the extent's size from
1127 * the data space_info's bytes_may_use counter and incremented the
1128 * space_info's bytes_reserved counter by the same amount. We must make
1129 * sure extent_clear_unlock_delalloc() does not try to decrement again
1130 * the data space_info's bytes_may_use counter, therefore we do not pass
1131 * it the flag EXTENT_CLEAR_DATA_RESV.
1133 if (extent_reserved) {
1134 extent_clear_unlock_delalloc(inode, start,
1135 start + cur_alloc_size,
1136 locked_page,
1137 clear_bits,
1138 page_ops);
1139 start += cur_alloc_size;
1140 if (start >= end)
1141 goto out;
1143 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1144 clear_bits | EXTENT_CLEAR_DATA_RESV,
1145 page_ops);
1146 goto out;
1150 * work queue call back to started compression on a file and pages
1152 static noinline void async_cow_start(struct btrfs_work *work)
1154 struct async_chunk *async_chunk;
1155 int compressed_extents;
1157 async_chunk = container_of(work, struct async_chunk, work);
1159 compressed_extents = compress_file_range(async_chunk);
1160 if (compressed_extents == 0) {
1161 btrfs_add_delayed_iput(async_chunk->inode);
1162 async_chunk->inode = NULL;
1167 * work queue call back to submit previously compressed pages
1169 static noinline void async_cow_submit(struct btrfs_work *work)
1171 struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1172 work);
1173 struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1174 unsigned long nr_pages;
1176 nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1177 PAGE_SHIFT;
1179 /* atomic_sub_return implies a barrier */
1180 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1181 5 * SZ_1M)
1182 cond_wake_up_nomb(&fs_info->async_submit_wait);
1185 * ->inode could be NULL if async_chunk_start has failed to compress,
1186 * in which case we don't have anything to submit, yet we need to
1187 * always adjust ->async_delalloc_pages as its paired with the init
1188 * happening in cow_file_range_async
1190 if (async_chunk->inode)
1191 submit_compressed_extents(async_chunk);
1194 static noinline void async_cow_free(struct btrfs_work *work)
1196 struct async_chunk *async_chunk;
1198 async_chunk = container_of(work, struct async_chunk, work);
1199 if (async_chunk->inode)
1200 btrfs_add_delayed_iput(async_chunk->inode);
1201 if (async_chunk->blkcg_css)
1202 css_put(async_chunk->blkcg_css);
1204 * Since the pointer to 'pending' is at the beginning of the array of
1205 * async_chunk's, freeing it ensures the whole array has been freed.
1207 if (atomic_dec_and_test(async_chunk->pending))
1208 kvfree(async_chunk->pending);
1211 static int cow_file_range_async(struct inode *inode,
1212 struct writeback_control *wbc,
1213 struct page *locked_page,
1214 u64 start, u64 end, int *page_started,
1215 unsigned long *nr_written)
1217 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1218 struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1219 struct async_cow *ctx;
1220 struct async_chunk *async_chunk;
1221 unsigned long nr_pages;
1222 u64 cur_end;
1223 u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
1224 int i;
1225 bool should_compress;
1226 unsigned nofs_flag;
1227 const unsigned int write_flags = wbc_to_write_flags(wbc);
1229 unlock_extent(&BTRFS_I(inode)->io_tree, start, end);
1231 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1232 !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
1233 num_chunks = 1;
1234 should_compress = false;
1235 } else {
1236 should_compress = true;
1239 nofs_flag = memalloc_nofs_save();
1240 ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
1241 memalloc_nofs_restore(nofs_flag);
1243 if (!ctx) {
1244 unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
1245 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
1246 EXTENT_DO_ACCOUNTING;
1247 unsigned long page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1248 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
1249 PAGE_SET_ERROR;
1251 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1252 clear_bits, page_ops);
1253 return -ENOMEM;
1256 async_chunk = ctx->chunks;
1257 atomic_set(&ctx->num_chunks, num_chunks);
1259 for (i = 0; i < num_chunks; i++) {
1260 if (should_compress)
1261 cur_end = min(end, start + SZ_512K - 1);
1262 else
1263 cur_end = end;
1266 * igrab is called higher up in the call chain, take only the
1267 * lightweight reference for the callback lifetime
1269 ihold(inode);
1270 async_chunk[i].pending = &ctx->num_chunks;
1271 async_chunk[i].inode = inode;
1272 async_chunk[i].start = start;
1273 async_chunk[i].end = cur_end;
1274 async_chunk[i].write_flags = write_flags;
1275 INIT_LIST_HEAD(&async_chunk[i].extents);
1278 * The locked_page comes all the way from writepage and its
1279 * the original page we were actually given. As we spread
1280 * this large delalloc region across multiple async_chunk
1281 * structs, only the first struct needs a pointer to locked_page
1283 * This way we don't need racey decisions about who is supposed
1284 * to unlock it.
1286 if (locked_page) {
1288 * Depending on the compressibility, the pages might or
1289 * might not go through async. We want all of them to
1290 * be accounted against wbc once. Let's do it here
1291 * before the paths diverge. wbc accounting is used
1292 * only for foreign writeback detection and doesn't
1293 * need full accuracy. Just account the whole thing
1294 * against the first page.
1296 wbc_account_cgroup_owner(wbc, locked_page,
1297 cur_end - start);
1298 async_chunk[i].locked_page = locked_page;
1299 locked_page = NULL;
1300 } else {
1301 async_chunk[i].locked_page = NULL;
1304 if (blkcg_css != blkcg_root_css) {
1305 css_get(blkcg_css);
1306 async_chunk[i].blkcg_css = blkcg_css;
1307 } else {
1308 async_chunk[i].blkcg_css = NULL;
1311 btrfs_init_work(&async_chunk[i].work, async_cow_start,
1312 async_cow_submit, async_cow_free);
1314 nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1315 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1317 btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1319 *nr_written += nr_pages;
1320 start = cur_end + 1;
1322 *page_started = 1;
1323 return 0;
1326 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1327 u64 bytenr, u64 num_bytes)
1329 int ret;
1330 struct btrfs_ordered_sum *sums;
1331 LIST_HEAD(list);
1333 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1334 bytenr + num_bytes - 1, &list, 0);
1335 if (ret == 0 && list_empty(&list))
1336 return 0;
1338 while (!list_empty(&list)) {
1339 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1340 list_del(&sums->list);
1341 kfree(sums);
1343 if (ret < 0)
1344 return ret;
1345 return 1;
1349 * when nowcow writeback call back. This checks for snapshots or COW copies
1350 * of the extents that exist in the file, and COWs the file as required.
1352 * If no cow copies or snapshots exist, we write directly to the existing
1353 * blocks on disk
1355 static noinline int run_delalloc_nocow(struct inode *inode,
1356 struct page *locked_page,
1357 const u64 start, const u64 end,
1358 int *page_started, int force,
1359 unsigned long *nr_written)
1361 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1362 struct btrfs_root *root = BTRFS_I(inode)->root;
1363 struct btrfs_path *path;
1364 u64 cow_start = (u64)-1;
1365 u64 cur_offset = start;
1366 int ret;
1367 bool check_prev = true;
1368 const bool freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
1369 u64 ino = btrfs_ino(BTRFS_I(inode));
1370 bool nocow = false;
1371 u64 disk_bytenr = 0;
1373 path = btrfs_alloc_path();
1374 if (!path) {
1375 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1376 EXTENT_LOCKED | EXTENT_DELALLOC |
1377 EXTENT_DO_ACCOUNTING |
1378 EXTENT_DEFRAG, PAGE_UNLOCK |
1379 PAGE_CLEAR_DIRTY |
1380 PAGE_SET_WRITEBACK |
1381 PAGE_END_WRITEBACK);
1382 return -ENOMEM;
1385 while (1) {
1386 struct btrfs_key found_key;
1387 struct btrfs_file_extent_item *fi;
1388 struct extent_buffer *leaf;
1389 u64 extent_end;
1390 u64 extent_offset;
1391 u64 num_bytes = 0;
1392 u64 disk_num_bytes;
1393 u64 ram_bytes;
1394 int extent_type;
1396 nocow = false;
1398 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1399 cur_offset, 0);
1400 if (ret < 0)
1401 goto error;
1404 * If there is no extent for our range when doing the initial
1405 * search, then go back to the previous slot as it will be the
1406 * one containing the search offset
1408 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1409 leaf = path->nodes[0];
1410 btrfs_item_key_to_cpu(leaf, &found_key,
1411 path->slots[0] - 1);
1412 if (found_key.objectid == ino &&
1413 found_key.type == BTRFS_EXTENT_DATA_KEY)
1414 path->slots[0]--;
1416 check_prev = false;
1417 next_slot:
1418 /* Go to next leaf if we have exhausted the current one */
1419 leaf = path->nodes[0];
1420 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1421 ret = btrfs_next_leaf(root, path);
1422 if (ret < 0) {
1423 if (cow_start != (u64)-1)
1424 cur_offset = cow_start;
1425 goto error;
1427 if (ret > 0)
1428 break;
1429 leaf = path->nodes[0];
1432 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1434 /* Didn't find anything for our INO */
1435 if (found_key.objectid > ino)
1436 break;
1438 * Keep searching until we find an EXTENT_ITEM or there are no
1439 * more extents for this inode
1441 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1442 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1443 path->slots[0]++;
1444 goto next_slot;
1447 /* Found key is not EXTENT_DATA_KEY or starts after req range */
1448 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1449 found_key.offset > end)
1450 break;
1453 * If the found extent starts after requested offset, then
1454 * adjust extent_end to be right before this extent begins
1456 if (found_key.offset > cur_offset) {
1457 extent_end = found_key.offset;
1458 extent_type = 0;
1459 goto out_check;
1463 * Found extent which begins before our range and potentially
1464 * intersect it
1466 fi = btrfs_item_ptr(leaf, path->slots[0],
1467 struct btrfs_file_extent_item);
1468 extent_type = btrfs_file_extent_type(leaf, fi);
1470 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1471 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1472 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1473 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1474 extent_offset = btrfs_file_extent_offset(leaf, fi);
1475 extent_end = found_key.offset +
1476 btrfs_file_extent_num_bytes(leaf, fi);
1477 disk_num_bytes =
1478 btrfs_file_extent_disk_num_bytes(leaf, fi);
1480 * If the extent we got ends before our current offset,
1481 * skip to the next extent.
1483 if (extent_end <= cur_offset) {
1484 path->slots[0]++;
1485 goto next_slot;
1487 /* Skip holes */
1488 if (disk_bytenr == 0)
1489 goto out_check;
1490 /* Skip compressed/encrypted/encoded extents */
1491 if (btrfs_file_extent_compression(leaf, fi) ||
1492 btrfs_file_extent_encryption(leaf, fi) ||
1493 btrfs_file_extent_other_encoding(leaf, fi))
1494 goto out_check;
1496 * If extent is created before the last volume's snapshot
1497 * this implies the extent is shared, hence we can't do
1498 * nocow. This is the same check as in
1499 * btrfs_cross_ref_exist but without calling
1500 * btrfs_search_slot.
1502 if (!freespace_inode &&
1503 btrfs_file_extent_generation(leaf, fi) <=
1504 btrfs_root_last_snapshot(&root->root_item))
1505 goto out_check;
1506 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1507 goto out_check;
1508 /* If extent is RO, we must COW it */
1509 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1510 goto out_check;
1511 ret = btrfs_cross_ref_exist(root, ino,
1512 found_key.offset -
1513 extent_offset, disk_bytenr);
1514 if (ret) {
1516 * ret could be -EIO if the above fails to read
1517 * metadata.
1519 if (ret < 0) {
1520 if (cow_start != (u64)-1)
1521 cur_offset = cow_start;
1522 goto error;
1525 WARN_ON_ONCE(freespace_inode);
1526 goto out_check;
1528 disk_bytenr += extent_offset;
1529 disk_bytenr += cur_offset - found_key.offset;
1530 num_bytes = min(end + 1, extent_end) - cur_offset;
1532 * If there are pending snapshots for this root, we
1533 * fall into common COW way
1535 if (!freespace_inode && atomic_read(&root->snapshot_force_cow))
1536 goto out_check;
1538 * force cow if csum exists in the range.
1539 * this ensure that csum for a given extent are
1540 * either valid or do not exist.
1542 ret = csum_exist_in_range(fs_info, disk_bytenr,
1543 num_bytes);
1544 if (ret) {
1546 * ret could be -EIO if the above fails to read
1547 * metadata.
1549 if (ret < 0) {
1550 if (cow_start != (u64)-1)
1551 cur_offset = cow_start;
1552 goto error;
1554 WARN_ON_ONCE(freespace_inode);
1555 goto out_check;
1557 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr))
1558 goto out_check;
1559 nocow = true;
1560 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1561 extent_end = found_key.offset + ram_bytes;
1562 extent_end = ALIGN(extent_end, fs_info->sectorsize);
1563 /* Skip extents outside of our requested range */
1564 if (extent_end <= start) {
1565 path->slots[0]++;
1566 goto next_slot;
1568 } else {
1569 /* If this triggers then we have a memory corruption */
1570 BUG();
1572 out_check:
1574 * If nocow is false then record the beginning of the range
1575 * that needs to be COWed
1577 if (!nocow) {
1578 if (cow_start == (u64)-1)
1579 cow_start = cur_offset;
1580 cur_offset = extent_end;
1581 if (cur_offset > end)
1582 break;
1583 path->slots[0]++;
1584 goto next_slot;
1587 btrfs_release_path(path);
1590 * COW range from cow_start to found_key.offset - 1. As the key
1591 * will contain the beginning of the first extent that can be
1592 * NOCOW, following one which needs to be COW'ed
1594 if (cow_start != (u64)-1) {
1595 ret = cow_file_range(inode, locked_page,
1596 cow_start, found_key.offset - 1,
1597 page_started, nr_written, 1);
1598 if (ret) {
1599 if (nocow)
1600 btrfs_dec_nocow_writers(fs_info,
1601 disk_bytenr);
1602 goto error;
1604 cow_start = (u64)-1;
1607 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1608 u64 orig_start = found_key.offset - extent_offset;
1609 struct extent_map *em;
1611 em = create_io_em(inode, cur_offset, num_bytes,
1612 orig_start,
1613 disk_bytenr, /* block_start */
1614 num_bytes, /* block_len */
1615 disk_num_bytes, /* orig_block_len */
1616 ram_bytes, BTRFS_COMPRESS_NONE,
1617 BTRFS_ORDERED_PREALLOC);
1618 if (IS_ERR(em)) {
1619 if (nocow)
1620 btrfs_dec_nocow_writers(fs_info,
1621 disk_bytenr);
1622 ret = PTR_ERR(em);
1623 goto error;
1625 free_extent_map(em);
1626 ret = btrfs_add_ordered_extent(inode, cur_offset,
1627 disk_bytenr, num_bytes,
1628 num_bytes,
1629 BTRFS_ORDERED_PREALLOC);
1630 if (ret) {
1631 btrfs_drop_extent_cache(BTRFS_I(inode),
1632 cur_offset,
1633 cur_offset + num_bytes - 1,
1635 goto error;
1637 } else {
1638 ret = btrfs_add_ordered_extent(inode, cur_offset,
1639 disk_bytenr, num_bytes,
1640 num_bytes,
1641 BTRFS_ORDERED_NOCOW);
1642 if (ret)
1643 goto error;
1646 if (nocow)
1647 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1648 nocow = false;
1650 if (root->root_key.objectid ==
1651 BTRFS_DATA_RELOC_TREE_OBJECTID)
1653 * Error handled later, as we must prevent
1654 * extent_clear_unlock_delalloc() in error handler
1655 * from freeing metadata of created ordered extent.
1657 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1658 num_bytes);
1660 extent_clear_unlock_delalloc(inode, cur_offset,
1661 cur_offset + num_bytes - 1,
1662 locked_page, EXTENT_LOCKED |
1663 EXTENT_DELALLOC |
1664 EXTENT_CLEAR_DATA_RESV,
1665 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1667 cur_offset = extent_end;
1670 * btrfs_reloc_clone_csums() error, now we're OK to call error
1671 * handler, as metadata for created ordered extent will only
1672 * be freed by btrfs_finish_ordered_io().
1674 if (ret)
1675 goto error;
1676 if (cur_offset > end)
1677 break;
1679 btrfs_release_path(path);
1681 if (cur_offset <= end && cow_start == (u64)-1)
1682 cow_start = cur_offset;
1684 if (cow_start != (u64)-1) {
1685 cur_offset = end;
1686 ret = cow_file_range(inode, locked_page, cow_start, end,
1687 page_started, nr_written, 1);
1688 if (ret)
1689 goto error;
1692 error:
1693 if (nocow)
1694 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1696 if (ret && cur_offset < end)
1697 extent_clear_unlock_delalloc(inode, cur_offset, end,
1698 locked_page, EXTENT_LOCKED |
1699 EXTENT_DELALLOC | EXTENT_DEFRAG |
1700 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1701 PAGE_CLEAR_DIRTY |
1702 PAGE_SET_WRITEBACK |
1703 PAGE_END_WRITEBACK);
1704 btrfs_free_path(path);
1705 return ret;
1708 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1711 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1712 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1713 return 0;
1716 * @defrag_bytes is a hint value, no spinlock held here,
1717 * if is not zero, it means the file is defragging.
1718 * Force cow if given extent needs to be defragged.
1720 if (BTRFS_I(inode)->defrag_bytes &&
1721 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1722 EXTENT_DEFRAG, 0, NULL))
1723 return 1;
1725 return 0;
1729 * Function to process delayed allocation (create CoW) for ranges which are
1730 * being touched for the first time.
1732 int btrfs_run_delalloc_range(struct inode *inode, struct page *locked_page,
1733 u64 start, u64 end, int *page_started, unsigned long *nr_written,
1734 struct writeback_control *wbc)
1736 int ret;
1737 int force_cow = need_force_cow(inode, start, end);
1739 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1740 ret = run_delalloc_nocow(inode, locked_page, start, end,
1741 page_started, 1, nr_written);
1742 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1743 ret = run_delalloc_nocow(inode, locked_page, start, end,
1744 page_started, 0, nr_written);
1745 } else if (!inode_can_compress(inode) ||
1746 !inode_need_compress(inode, start, end)) {
1747 ret = cow_file_range(inode, locked_page, start, end,
1748 page_started, nr_written, 1);
1749 } else {
1750 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1751 &BTRFS_I(inode)->runtime_flags);
1752 ret = cow_file_range_async(inode, wbc, locked_page, start, end,
1753 page_started, nr_written);
1755 if (ret)
1756 btrfs_cleanup_ordered_extents(inode, locked_page, start,
1757 end - start + 1);
1758 return ret;
1761 void btrfs_split_delalloc_extent(struct inode *inode,
1762 struct extent_state *orig, u64 split)
1764 u64 size;
1766 /* not delalloc, ignore it */
1767 if (!(orig->state & EXTENT_DELALLOC))
1768 return;
1770 size = orig->end - orig->start + 1;
1771 if (size > BTRFS_MAX_EXTENT_SIZE) {
1772 u32 num_extents;
1773 u64 new_size;
1776 * See the explanation in btrfs_merge_delalloc_extent, the same
1777 * applies here, just in reverse.
1779 new_size = orig->end - split + 1;
1780 num_extents = count_max_extents(new_size);
1781 new_size = split - orig->start;
1782 num_extents += count_max_extents(new_size);
1783 if (count_max_extents(size) >= num_extents)
1784 return;
1787 spin_lock(&BTRFS_I(inode)->lock);
1788 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1789 spin_unlock(&BTRFS_I(inode)->lock);
1793 * Handle merged delayed allocation extents so we can keep track of new extents
1794 * that are just merged onto old extents, such as when we are doing sequential
1795 * writes, so we can properly account for the metadata space we'll need.
1797 void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
1798 struct extent_state *other)
1800 u64 new_size, old_size;
1801 u32 num_extents;
1803 /* not delalloc, ignore it */
1804 if (!(other->state & EXTENT_DELALLOC))
1805 return;
1807 if (new->start > other->start)
1808 new_size = new->end - other->start + 1;
1809 else
1810 new_size = other->end - new->start + 1;
1812 /* we're not bigger than the max, unreserve the space and go */
1813 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1814 spin_lock(&BTRFS_I(inode)->lock);
1815 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1816 spin_unlock(&BTRFS_I(inode)->lock);
1817 return;
1821 * We have to add up either side to figure out how many extents were
1822 * accounted for before we merged into one big extent. If the number of
1823 * extents we accounted for is <= the amount we need for the new range
1824 * then we can return, otherwise drop. Think of it like this
1826 * [ 4k][MAX_SIZE]
1828 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1829 * need 2 outstanding extents, on one side we have 1 and the other side
1830 * we have 1 so they are == and we can return. But in this case
1832 * [MAX_SIZE+4k][MAX_SIZE+4k]
1834 * Each range on their own accounts for 2 extents, but merged together
1835 * they are only 3 extents worth of accounting, so we need to drop in
1836 * this case.
1838 old_size = other->end - other->start + 1;
1839 num_extents = count_max_extents(old_size);
1840 old_size = new->end - new->start + 1;
1841 num_extents += count_max_extents(old_size);
1842 if (count_max_extents(new_size) >= num_extents)
1843 return;
1845 spin_lock(&BTRFS_I(inode)->lock);
1846 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1847 spin_unlock(&BTRFS_I(inode)->lock);
1850 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1851 struct inode *inode)
1853 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1855 spin_lock(&root->delalloc_lock);
1856 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1857 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1858 &root->delalloc_inodes);
1859 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1860 &BTRFS_I(inode)->runtime_flags);
1861 root->nr_delalloc_inodes++;
1862 if (root->nr_delalloc_inodes == 1) {
1863 spin_lock(&fs_info->delalloc_root_lock);
1864 BUG_ON(!list_empty(&root->delalloc_root));
1865 list_add_tail(&root->delalloc_root,
1866 &fs_info->delalloc_roots);
1867 spin_unlock(&fs_info->delalloc_root_lock);
1870 spin_unlock(&root->delalloc_lock);
1874 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1875 struct btrfs_inode *inode)
1877 struct btrfs_fs_info *fs_info = root->fs_info;
1879 if (!list_empty(&inode->delalloc_inodes)) {
1880 list_del_init(&inode->delalloc_inodes);
1881 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1882 &inode->runtime_flags);
1883 root->nr_delalloc_inodes--;
1884 if (!root->nr_delalloc_inodes) {
1885 ASSERT(list_empty(&root->delalloc_inodes));
1886 spin_lock(&fs_info->delalloc_root_lock);
1887 BUG_ON(list_empty(&root->delalloc_root));
1888 list_del_init(&root->delalloc_root);
1889 spin_unlock(&fs_info->delalloc_root_lock);
1894 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1895 struct btrfs_inode *inode)
1897 spin_lock(&root->delalloc_lock);
1898 __btrfs_del_delalloc_inode(root, inode);
1899 spin_unlock(&root->delalloc_lock);
1903 * Properly track delayed allocation bytes in the inode and to maintain the
1904 * list of inodes that have pending delalloc work to be done.
1906 void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
1907 unsigned *bits)
1909 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1911 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1912 WARN_ON(1);
1914 * set_bit and clear bit hooks normally require _irqsave/restore
1915 * but in this case, we are only testing for the DELALLOC
1916 * bit, which is only set or cleared with irqs on
1918 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1919 struct btrfs_root *root = BTRFS_I(inode)->root;
1920 u64 len = state->end + 1 - state->start;
1921 u32 num_extents = count_max_extents(len);
1922 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1924 spin_lock(&BTRFS_I(inode)->lock);
1925 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1926 spin_unlock(&BTRFS_I(inode)->lock);
1928 /* For sanity tests */
1929 if (btrfs_is_testing(fs_info))
1930 return;
1932 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1933 fs_info->delalloc_batch);
1934 spin_lock(&BTRFS_I(inode)->lock);
1935 BTRFS_I(inode)->delalloc_bytes += len;
1936 if (*bits & EXTENT_DEFRAG)
1937 BTRFS_I(inode)->defrag_bytes += len;
1938 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1939 &BTRFS_I(inode)->runtime_flags))
1940 btrfs_add_delalloc_inodes(root, inode);
1941 spin_unlock(&BTRFS_I(inode)->lock);
1944 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1945 (*bits & EXTENT_DELALLOC_NEW)) {
1946 spin_lock(&BTRFS_I(inode)->lock);
1947 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1948 state->start;
1949 spin_unlock(&BTRFS_I(inode)->lock);
1954 * Once a range is no longer delalloc this function ensures that proper
1955 * accounting happens.
1957 void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
1958 struct extent_state *state, unsigned *bits)
1960 struct btrfs_inode *inode = BTRFS_I(vfs_inode);
1961 struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
1962 u64 len = state->end + 1 - state->start;
1963 u32 num_extents = count_max_extents(len);
1965 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1966 spin_lock(&inode->lock);
1967 inode->defrag_bytes -= len;
1968 spin_unlock(&inode->lock);
1972 * set_bit and clear bit hooks normally require _irqsave/restore
1973 * but in this case, we are only testing for the DELALLOC
1974 * bit, which is only set or cleared with irqs on
1976 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1977 struct btrfs_root *root = inode->root;
1978 bool do_list = !btrfs_is_free_space_inode(inode);
1980 spin_lock(&inode->lock);
1981 btrfs_mod_outstanding_extents(inode, -num_extents);
1982 spin_unlock(&inode->lock);
1985 * We don't reserve metadata space for space cache inodes so we
1986 * don't need to call delalloc_release_metadata if there is an
1987 * error.
1989 if (*bits & EXTENT_CLEAR_META_RESV &&
1990 root != fs_info->tree_root)
1991 btrfs_delalloc_release_metadata(inode, len, false);
1993 /* For sanity tests. */
1994 if (btrfs_is_testing(fs_info))
1995 return;
1997 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1998 do_list && !(state->state & EXTENT_NORESERVE) &&
1999 (*bits & EXTENT_CLEAR_DATA_RESV))
2000 btrfs_free_reserved_data_space_noquota(
2001 &inode->vfs_inode,
2002 state->start, len);
2004 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2005 fs_info->delalloc_batch);
2006 spin_lock(&inode->lock);
2007 inode->delalloc_bytes -= len;
2008 if (do_list && inode->delalloc_bytes == 0 &&
2009 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
2010 &inode->runtime_flags))
2011 btrfs_del_delalloc_inode(root, inode);
2012 spin_unlock(&inode->lock);
2015 if ((state->state & EXTENT_DELALLOC_NEW) &&
2016 (*bits & EXTENT_DELALLOC_NEW)) {
2017 spin_lock(&inode->lock);
2018 ASSERT(inode->new_delalloc_bytes >= len);
2019 inode->new_delalloc_bytes -= len;
2020 spin_unlock(&inode->lock);
2025 * btrfs_bio_fits_in_stripe - Checks whether the size of the given bio will fit
2026 * in a chunk's stripe. This function ensures that bios do not span a
2027 * stripe/chunk
2029 * @page - The page we are about to add to the bio
2030 * @size - size we want to add to the bio
2031 * @bio - bio we want to ensure is smaller than a stripe
2032 * @bio_flags - flags of the bio
2034 * return 1 if page cannot be added to the bio
2035 * return 0 if page can be added to the bio
2036 * return error otherwise
2038 int btrfs_bio_fits_in_stripe(struct page *page, size_t size, struct bio *bio,
2039 unsigned long bio_flags)
2041 struct inode *inode = page->mapping->host;
2042 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2043 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
2044 u64 length = 0;
2045 u64 map_length;
2046 int ret;
2047 struct btrfs_io_geometry geom;
2049 if (bio_flags & EXTENT_BIO_COMPRESSED)
2050 return 0;
2052 length = bio->bi_iter.bi_size;
2053 map_length = length;
2054 ret = btrfs_get_io_geometry(fs_info, btrfs_op(bio), logical, map_length,
2055 &geom);
2056 if (ret < 0)
2057 return ret;
2059 if (geom.len < length + size)
2060 return 1;
2061 return 0;
2065 * in order to insert checksums into the metadata in large chunks,
2066 * we wait until bio submission time. All the pages in the bio are
2067 * checksummed and sums are attached onto the ordered extent record.
2069 * At IO completion time the cums attached on the ordered extent record
2070 * are inserted into the btree
2072 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
2073 u64 bio_offset)
2075 struct inode *inode = private_data;
2076 blk_status_t ret = 0;
2078 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2079 BUG_ON(ret); /* -ENOMEM */
2080 return 0;
2084 * extent_io.c submission hook. This does the right thing for csum calculation
2085 * on write, or reading the csums from the tree before a read.
2087 * Rules about async/sync submit,
2088 * a) read: sync submit
2090 * b) write without checksum: sync submit
2092 * c) write with checksum:
2093 * c-1) if bio is issued by fsync: sync submit
2094 * (sync_writers != 0)
2096 * c-2) if root is reloc root: sync submit
2097 * (only in case of buffered IO)
2099 * c-3) otherwise: async submit
2101 static blk_status_t btrfs_submit_bio_hook(struct inode *inode, struct bio *bio,
2102 int mirror_num,
2103 unsigned long bio_flags)
2106 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2107 struct btrfs_root *root = BTRFS_I(inode)->root;
2108 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2109 blk_status_t ret = 0;
2110 int skip_sum;
2111 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2113 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2115 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2116 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2118 if (bio_op(bio) != REQ_OP_WRITE) {
2119 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2120 if (ret)
2121 goto out;
2123 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2124 ret = btrfs_submit_compressed_read(inode, bio,
2125 mirror_num,
2126 bio_flags);
2127 goto out;
2128 } else if (!skip_sum) {
2129 ret = btrfs_lookup_bio_sums(inode, bio, (u64)-1, NULL);
2130 if (ret)
2131 goto out;
2133 goto mapit;
2134 } else if (async && !skip_sum) {
2135 /* csum items have already been cloned */
2136 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2137 goto mapit;
2138 /* we're doing a write, do the async checksumming */
2139 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2140 0, inode, btrfs_submit_bio_start);
2141 goto out;
2142 } else if (!skip_sum) {
2143 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2144 if (ret)
2145 goto out;
2148 mapit:
2149 ret = btrfs_map_bio(fs_info, bio, mirror_num);
2151 out:
2152 if (ret) {
2153 bio->bi_status = ret;
2154 bio_endio(bio);
2156 return ret;
2160 * given a list of ordered sums record them in the inode. This happens
2161 * at IO completion time based on sums calculated at bio submission time.
2163 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2164 struct inode *inode, struct list_head *list)
2166 struct btrfs_ordered_sum *sum;
2167 int ret;
2169 list_for_each_entry(sum, list, list) {
2170 trans->adding_csums = true;
2171 ret = btrfs_csum_file_blocks(trans,
2172 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2173 trans->adding_csums = false;
2174 if (ret)
2175 return ret;
2177 return 0;
2180 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2181 unsigned int extra_bits,
2182 struct extent_state **cached_state)
2184 WARN_ON(PAGE_ALIGNED(end));
2185 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2186 extra_bits, cached_state);
2189 /* see btrfs_writepage_start_hook for details on why this is required */
2190 struct btrfs_writepage_fixup {
2191 struct page *page;
2192 struct inode *inode;
2193 struct btrfs_work work;
2196 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2198 struct btrfs_writepage_fixup *fixup;
2199 struct btrfs_ordered_extent *ordered;
2200 struct extent_state *cached_state = NULL;
2201 struct extent_changeset *data_reserved = NULL;
2202 struct page *page;
2203 struct inode *inode;
2204 u64 page_start;
2205 u64 page_end;
2206 int ret = 0;
2207 bool free_delalloc_space = true;
2209 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2210 page = fixup->page;
2211 inode = fixup->inode;
2212 page_start = page_offset(page);
2213 page_end = page_offset(page) + PAGE_SIZE - 1;
2216 * This is similar to page_mkwrite, we need to reserve the space before
2217 * we take the page lock.
2219 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2220 PAGE_SIZE);
2221 again:
2222 lock_page(page);
2225 * Before we queued this fixup, we took a reference on the page.
2226 * page->mapping may go NULL, but it shouldn't be moved to a different
2227 * address space.
2229 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2231 * Unfortunately this is a little tricky, either
2233 * 1) We got here and our page had already been dealt with and
2234 * we reserved our space, thus ret == 0, so we need to just
2235 * drop our space reservation and bail. This can happen the
2236 * first time we come into the fixup worker, or could happen
2237 * while waiting for the ordered extent.
2238 * 2) Our page was already dealt with, but we happened to get an
2239 * ENOSPC above from the btrfs_delalloc_reserve_space. In
2240 * this case we obviously don't have anything to release, but
2241 * because the page was already dealt with we don't want to
2242 * mark the page with an error, so make sure we're resetting
2243 * ret to 0. This is why we have this check _before_ the ret
2244 * check, because we do not want to have a surprise ENOSPC
2245 * when the page was already properly dealt with.
2247 if (!ret) {
2248 btrfs_delalloc_release_extents(BTRFS_I(inode),
2249 PAGE_SIZE);
2250 btrfs_delalloc_release_space(inode, data_reserved,
2251 page_start, PAGE_SIZE,
2252 true);
2254 ret = 0;
2255 goto out_page;
2259 * We can't mess with the page state unless it is locked, so now that
2260 * it is locked bail if we failed to make our space reservation.
2262 if (ret)
2263 goto out_page;
2265 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2266 &cached_state);
2268 /* already ordered? We're done */
2269 if (PagePrivate2(page))
2270 goto out_reserved;
2272 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2273 PAGE_SIZE);
2274 if (ordered) {
2275 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2276 page_end, &cached_state);
2277 unlock_page(page);
2278 btrfs_start_ordered_extent(inode, ordered, 1);
2279 btrfs_put_ordered_extent(ordered);
2280 goto again;
2283 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2284 &cached_state);
2285 if (ret)
2286 goto out_reserved;
2289 * Everything went as planned, we're now the owner of a dirty page with
2290 * delayed allocation bits set and space reserved for our COW
2291 * destination.
2293 * The page was dirty when we started, nothing should have cleaned it.
2295 BUG_ON(!PageDirty(page));
2296 free_delalloc_space = false;
2297 out_reserved:
2298 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
2299 if (free_delalloc_space)
2300 btrfs_delalloc_release_space(inode, data_reserved, page_start,
2301 PAGE_SIZE, true);
2302 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2303 &cached_state);
2304 out_page:
2305 if (ret) {
2307 * We hit ENOSPC or other errors. Update the mapping and page
2308 * to reflect the errors and clean the page.
2310 mapping_set_error(page->mapping, ret);
2311 end_extent_writepage(page, ret, page_start, page_end);
2312 clear_page_dirty_for_io(page);
2313 SetPageError(page);
2315 ClearPageChecked(page);
2316 unlock_page(page);
2317 put_page(page);
2318 kfree(fixup);
2319 extent_changeset_free(data_reserved);
2321 * As a precaution, do a delayed iput in case it would be the last iput
2322 * that could need flushing space. Recursing back to fixup worker would
2323 * deadlock.
2325 btrfs_add_delayed_iput(inode);
2329 * There are a few paths in the higher layers of the kernel that directly
2330 * set the page dirty bit without asking the filesystem if it is a
2331 * good idea. This causes problems because we want to make sure COW
2332 * properly happens and the data=ordered rules are followed.
2334 * In our case any range that doesn't have the ORDERED bit set
2335 * hasn't been properly setup for IO. We kick off an async process
2336 * to fix it up. The async helper will wait for ordered extents, set
2337 * the delalloc bit and make it safe to write the page.
2339 int btrfs_writepage_cow_fixup(struct page *page, u64 start, u64 end)
2341 struct inode *inode = page->mapping->host;
2342 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2343 struct btrfs_writepage_fixup *fixup;
2345 /* this page is properly in the ordered list */
2346 if (TestClearPagePrivate2(page))
2347 return 0;
2350 * PageChecked is set below when we create a fixup worker for this page,
2351 * don't try to create another one if we're already PageChecked()
2353 * The extent_io writepage code will redirty the page if we send back
2354 * EAGAIN.
2356 if (PageChecked(page))
2357 return -EAGAIN;
2359 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2360 if (!fixup)
2361 return -EAGAIN;
2364 * We are already holding a reference to this inode from
2365 * write_cache_pages. We need to hold it because the space reservation
2366 * takes place outside of the page lock, and we can't trust
2367 * page->mapping outside of the page lock.
2369 ihold(inode);
2370 SetPageChecked(page);
2371 get_page(page);
2372 btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
2373 fixup->page = page;
2374 fixup->inode = inode;
2375 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2377 return -EAGAIN;
2380 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2381 struct inode *inode, u64 file_pos,
2382 u64 disk_bytenr, u64 disk_num_bytes,
2383 u64 num_bytes, u64 ram_bytes,
2384 u8 compression, u8 encryption,
2385 u16 other_encoding, int extent_type)
2387 struct btrfs_root *root = BTRFS_I(inode)->root;
2388 struct btrfs_file_extent_item *fi;
2389 struct btrfs_path *path;
2390 struct extent_buffer *leaf;
2391 struct btrfs_key ins;
2392 u64 qg_released;
2393 int extent_inserted = 0;
2394 int ret;
2396 path = btrfs_alloc_path();
2397 if (!path)
2398 return -ENOMEM;
2401 * we may be replacing one extent in the tree with another.
2402 * The new extent is pinned in the extent map, and we don't want
2403 * to drop it from the cache until it is completely in the btree.
2405 * So, tell btrfs_drop_extents to leave this extent in the cache.
2406 * the caller is expected to unpin it and allow it to be merged
2407 * with the others.
2409 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2410 file_pos + num_bytes, NULL, 0,
2411 1, sizeof(*fi), &extent_inserted);
2412 if (ret)
2413 goto out;
2415 if (!extent_inserted) {
2416 ins.objectid = btrfs_ino(BTRFS_I(inode));
2417 ins.offset = file_pos;
2418 ins.type = BTRFS_EXTENT_DATA_KEY;
2420 path->leave_spinning = 1;
2421 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2422 sizeof(*fi));
2423 if (ret)
2424 goto out;
2426 leaf = path->nodes[0];
2427 fi = btrfs_item_ptr(leaf, path->slots[0],
2428 struct btrfs_file_extent_item);
2429 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2430 btrfs_set_file_extent_type(leaf, fi, extent_type);
2431 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2432 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2433 btrfs_set_file_extent_offset(leaf, fi, 0);
2434 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2435 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2436 btrfs_set_file_extent_compression(leaf, fi, compression);
2437 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2438 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2440 btrfs_mark_buffer_dirty(leaf);
2441 btrfs_release_path(path);
2443 inode_add_bytes(inode, num_bytes);
2445 ins.objectid = disk_bytenr;
2446 ins.offset = disk_num_bytes;
2447 ins.type = BTRFS_EXTENT_ITEM_KEY;
2450 * Release the reserved range from inode dirty range map, as it is
2451 * already moved into delayed_ref_head
2453 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2454 if (ret < 0)
2455 goto out;
2456 qg_released = ret;
2457 ret = btrfs_alloc_reserved_file_extent(trans, root,
2458 btrfs_ino(BTRFS_I(inode)),
2459 file_pos, qg_released, &ins);
2460 out:
2461 btrfs_free_path(path);
2463 return ret;
2466 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2467 u64 start, u64 len)
2469 struct btrfs_block_group *cache;
2471 cache = btrfs_lookup_block_group(fs_info, start);
2472 ASSERT(cache);
2474 spin_lock(&cache->lock);
2475 cache->delalloc_bytes -= len;
2476 spin_unlock(&cache->lock);
2478 btrfs_put_block_group(cache);
2481 /* as ordered data IO finishes, this gets called so we can finish
2482 * an ordered extent if the range of bytes in the file it covers are
2483 * fully written.
2485 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2487 struct inode *inode = ordered_extent->inode;
2488 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2489 struct btrfs_root *root = BTRFS_I(inode)->root;
2490 struct btrfs_trans_handle *trans = NULL;
2491 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2492 struct extent_state *cached_state = NULL;
2493 u64 start, end;
2494 int compress_type = 0;
2495 int ret = 0;
2496 u64 logical_len = ordered_extent->num_bytes;
2497 bool freespace_inode;
2498 bool truncated = false;
2499 bool range_locked = false;
2500 bool clear_new_delalloc_bytes = false;
2501 bool clear_reserved_extent = true;
2502 unsigned int clear_bits;
2504 start = ordered_extent->file_offset;
2505 end = start + ordered_extent->num_bytes - 1;
2507 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2508 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2509 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2510 clear_new_delalloc_bytes = true;
2512 freespace_inode = btrfs_is_free_space_inode(BTRFS_I(inode));
2514 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2515 ret = -EIO;
2516 goto out;
2519 btrfs_free_io_failure_record(BTRFS_I(inode), start, end);
2521 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2522 truncated = true;
2523 logical_len = ordered_extent->truncated_len;
2524 /* Truncated the entire extent, don't bother adding */
2525 if (!logical_len)
2526 goto out;
2529 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2530 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2533 * For mwrite(mmap + memset to write) case, we still reserve
2534 * space for NOCOW range.
2535 * As NOCOW won't cause a new delayed ref, just free the space
2537 btrfs_qgroup_free_data(inode, NULL, start,
2538 ordered_extent->num_bytes);
2539 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2540 if (freespace_inode)
2541 trans = btrfs_join_transaction_spacecache(root);
2542 else
2543 trans = btrfs_join_transaction(root);
2544 if (IS_ERR(trans)) {
2545 ret = PTR_ERR(trans);
2546 trans = NULL;
2547 goto out;
2549 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2550 ret = btrfs_update_inode_fallback(trans, root, inode);
2551 if (ret) /* -ENOMEM or corruption */
2552 btrfs_abort_transaction(trans, ret);
2553 goto out;
2556 range_locked = true;
2557 lock_extent_bits(io_tree, start, end, &cached_state);
2559 if (freespace_inode)
2560 trans = btrfs_join_transaction_spacecache(root);
2561 else
2562 trans = btrfs_join_transaction(root);
2563 if (IS_ERR(trans)) {
2564 ret = PTR_ERR(trans);
2565 trans = NULL;
2566 goto out;
2569 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
2571 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2572 compress_type = ordered_extent->compress_type;
2573 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2574 BUG_ON(compress_type);
2575 btrfs_qgroup_free_data(inode, NULL, start,
2576 ordered_extent->num_bytes);
2577 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
2578 ordered_extent->file_offset,
2579 ordered_extent->file_offset +
2580 logical_len);
2581 } else {
2582 BUG_ON(root == fs_info->tree_root);
2583 ret = insert_reserved_file_extent(trans, inode, start,
2584 ordered_extent->disk_bytenr,
2585 ordered_extent->disk_num_bytes,
2586 logical_len, logical_len,
2587 compress_type, 0, 0,
2588 BTRFS_FILE_EXTENT_REG);
2589 if (!ret) {
2590 clear_reserved_extent = false;
2591 btrfs_release_delalloc_bytes(fs_info,
2592 ordered_extent->disk_bytenr,
2593 ordered_extent->disk_num_bytes);
2596 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2597 ordered_extent->file_offset,
2598 ordered_extent->num_bytes, trans->transid);
2599 if (ret < 0) {
2600 btrfs_abort_transaction(trans, ret);
2601 goto out;
2604 ret = add_pending_csums(trans, inode, &ordered_extent->list);
2605 if (ret) {
2606 btrfs_abort_transaction(trans, ret);
2607 goto out;
2610 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2611 ret = btrfs_update_inode_fallback(trans, root, inode);
2612 if (ret) { /* -ENOMEM or corruption */
2613 btrfs_abort_transaction(trans, ret);
2614 goto out;
2616 ret = 0;
2617 out:
2618 clear_bits = EXTENT_DEFRAG;
2619 if (range_locked)
2620 clear_bits |= EXTENT_LOCKED;
2621 if (clear_new_delalloc_bytes)
2622 clear_bits |= EXTENT_DELALLOC_NEW;
2623 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, clear_bits,
2624 (clear_bits & EXTENT_LOCKED) ? 1 : 0, 0,
2625 &cached_state);
2627 if (trans)
2628 btrfs_end_transaction(trans);
2630 if (ret || truncated) {
2631 u64 unwritten_start = start;
2633 if (truncated)
2634 unwritten_start += logical_len;
2635 clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
2637 /* Drop the cache for the part of the extent we didn't write. */
2638 btrfs_drop_extent_cache(BTRFS_I(inode), unwritten_start, end, 0);
2641 * If the ordered extent had an IOERR or something else went
2642 * wrong we need to return the space for this ordered extent
2643 * back to the allocator. We only free the extent in the
2644 * truncated case if we didn't write out the extent at all.
2646 * If we made it past insert_reserved_file_extent before we
2647 * errored out then we don't need to do this as the accounting
2648 * has already been done.
2650 if ((ret || !logical_len) &&
2651 clear_reserved_extent &&
2652 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2653 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2655 * Discard the range before returning it back to the
2656 * free space pool
2658 if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
2659 btrfs_discard_extent(fs_info,
2660 ordered_extent->disk_bytenr,
2661 ordered_extent->disk_num_bytes,
2662 NULL);
2663 btrfs_free_reserved_extent(fs_info,
2664 ordered_extent->disk_bytenr,
2665 ordered_extent->disk_num_bytes, 1);
2670 * This needs to be done to make sure anybody waiting knows we are done
2671 * updating everything for this ordered extent.
2673 btrfs_remove_ordered_extent(inode, ordered_extent);
2675 /* once for us */
2676 btrfs_put_ordered_extent(ordered_extent);
2677 /* once for the tree */
2678 btrfs_put_ordered_extent(ordered_extent);
2680 return ret;
2683 static void finish_ordered_fn(struct btrfs_work *work)
2685 struct btrfs_ordered_extent *ordered_extent;
2686 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
2687 btrfs_finish_ordered_io(ordered_extent);
2690 void btrfs_writepage_endio_finish_ordered(struct page *page, u64 start,
2691 u64 end, int uptodate)
2693 struct inode *inode = page->mapping->host;
2694 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2695 struct btrfs_ordered_extent *ordered_extent = NULL;
2696 struct btrfs_workqueue *wq;
2698 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
2700 ClearPagePrivate2(page);
2701 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
2702 end - start + 1, uptodate))
2703 return;
2705 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2706 wq = fs_info->endio_freespace_worker;
2707 else
2708 wq = fs_info->endio_write_workers;
2710 btrfs_init_work(&ordered_extent->work, finish_ordered_fn, NULL, NULL);
2711 btrfs_queue_work(wq, &ordered_extent->work);
2714 static int __readpage_endio_check(struct inode *inode,
2715 struct btrfs_io_bio *io_bio,
2716 int icsum, struct page *page,
2717 int pgoff, u64 start, size_t len)
2719 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2720 SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
2721 char *kaddr;
2722 u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
2723 u8 *csum_expected;
2724 u8 csum[BTRFS_CSUM_SIZE];
2726 csum_expected = ((u8 *)io_bio->csum) + icsum * csum_size;
2728 kaddr = kmap_atomic(page);
2729 shash->tfm = fs_info->csum_shash;
2731 crypto_shash_init(shash);
2732 crypto_shash_update(shash, kaddr + pgoff, len);
2733 crypto_shash_final(shash, csum);
2735 if (memcmp(csum, csum_expected, csum_size))
2736 goto zeroit;
2738 kunmap_atomic(kaddr);
2739 return 0;
2740 zeroit:
2741 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
2742 io_bio->mirror_num);
2743 memset(kaddr + pgoff, 1, len);
2744 flush_dcache_page(page);
2745 kunmap_atomic(kaddr);
2746 return -EIO;
2750 * when reads are done, we need to check csums to verify the data is correct
2751 * if there's a match, we allow the bio to finish. If not, the code in
2752 * extent_io.c will try to find good copies for us.
2754 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
2755 u64 phy_offset, struct page *page,
2756 u64 start, u64 end, int mirror)
2758 size_t offset = start - page_offset(page);
2759 struct inode *inode = page->mapping->host;
2760 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2761 struct btrfs_root *root = BTRFS_I(inode)->root;
2763 if (PageChecked(page)) {
2764 ClearPageChecked(page);
2765 return 0;
2768 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
2769 return 0;
2771 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
2772 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
2773 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
2774 return 0;
2777 phy_offset >>= inode->i_sb->s_blocksize_bits;
2778 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
2779 start, (size_t)(end - start + 1));
2783 * btrfs_add_delayed_iput - perform a delayed iput on @inode
2785 * @inode: The inode we want to perform iput on
2787 * This function uses the generic vfs_inode::i_count to track whether we should
2788 * just decrement it (in case it's > 1) or if this is the last iput then link
2789 * the inode to the delayed iput machinery. Delayed iputs are processed at
2790 * transaction commit time/superblock commit/cleaner kthread.
2792 void btrfs_add_delayed_iput(struct inode *inode)
2794 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2795 struct btrfs_inode *binode = BTRFS_I(inode);
2797 if (atomic_add_unless(&inode->i_count, -1, 1))
2798 return;
2800 atomic_inc(&fs_info->nr_delayed_iputs);
2801 spin_lock(&fs_info->delayed_iput_lock);
2802 ASSERT(list_empty(&binode->delayed_iput));
2803 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
2804 spin_unlock(&fs_info->delayed_iput_lock);
2805 if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
2806 wake_up_process(fs_info->cleaner_kthread);
2809 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
2810 struct btrfs_inode *inode)
2812 list_del_init(&inode->delayed_iput);
2813 spin_unlock(&fs_info->delayed_iput_lock);
2814 iput(&inode->vfs_inode);
2815 if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
2816 wake_up(&fs_info->delayed_iputs_wait);
2817 spin_lock(&fs_info->delayed_iput_lock);
2820 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
2821 struct btrfs_inode *inode)
2823 if (!list_empty(&inode->delayed_iput)) {
2824 spin_lock(&fs_info->delayed_iput_lock);
2825 if (!list_empty(&inode->delayed_iput))
2826 run_delayed_iput_locked(fs_info, inode);
2827 spin_unlock(&fs_info->delayed_iput_lock);
2831 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
2834 spin_lock(&fs_info->delayed_iput_lock);
2835 while (!list_empty(&fs_info->delayed_iputs)) {
2836 struct btrfs_inode *inode;
2838 inode = list_first_entry(&fs_info->delayed_iputs,
2839 struct btrfs_inode, delayed_iput);
2840 run_delayed_iput_locked(fs_info, inode);
2842 spin_unlock(&fs_info->delayed_iput_lock);
2846 * btrfs_wait_on_delayed_iputs - wait on the delayed iputs to be done running
2847 * @fs_info - the fs_info for this fs
2848 * @return - EINTR if we were killed, 0 if nothing's pending
2850 * This will wait on any delayed iputs that are currently running with KILLABLE
2851 * set. Once they are all done running we will return, unless we are killed in
2852 * which case we return EINTR. This helps in user operations like fallocate etc
2853 * that might get blocked on the iputs.
2855 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
2857 int ret = wait_event_killable(fs_info->delayed_iputs_wait,
2858 atomic_read(&fs_info->nr_delayed_iputs) == 0);
2859 if (ret)
2860 return -EINTR;
2861 return 0;
2865 * This creates an orphan entry for the given inode in case something goes wrong
2866 * in the middle of an unlink.
2868 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
2869 struct btrfs_inode *inode)
2871 int ret;
2873 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
2874 if (ret && ret != -EEXIST) {
2875 btrfs_abort_transaction(trans, ret);
2876 return ret;
2879 return 0;
2883 * We have done the delete so we can go ahead and remove the orphan item for
2884 * this particular inode.
2886 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
2887 struct btrfs_inode *inode)
2889 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
2893 * this cleans up any orphans that may be left on the list from the last use
2894 * of this root.
2896 int btrfs_orphan_cleanup(struct btrfs_root *root)
2898 struct btrfs_fs_info *fs_info = root->fs_info;
2899 struct btrfs_path *path;
2900 struct extent_buffer *leaf;
2901 struct btrfs_key key, found_key;
2902 struct btrfs_trans_handle *trans;
2903 struct inode *inode;
2904 u64 last_objectid = 0;
2905 int ret = 0, nr_unlink = 0;
2907 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
2908 return 0;
2910 path = btrfs_alloc_path();
2911 if (!path) {
2912 ret = -ENOMEM;
2913 goto out;
2915 path->reada = READA_BACK;
2917 key.objectid = BTRFS_ORPHAN_OBJECTID;
2918 key.type = BTRFS_ORPHAN_ITEM_KEY;
2919 key.offset = (u64)-1;
2921 while (1) {
2922 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2923 if (ret < 0)
2924 goto out;
2927 * if ret == 0 means we found what we were searching for, which
2928 * is weird, but possible, so only screw with path if we didn't
2929 * find the key and see if we have stuff that matches
2931 if (ret > 0) {
2932 ret = 0;
2933 if (path->slots[0] == 0)
2934 break;
2935 path->slots[0]--;
2938 /* pull out the item */
2939 leaf = path->nodes[0];
2940 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2942 /* make sure the item matches what we want */
2943 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
2944 break;
2945 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
2946 break;
2948 /* release the path since we're done with it */
2949 btrfs_release_path(path);
2952 * this is where we are basically btrfs_lookup, without the
2953 * crossing root thing. we store the inode number in the
2954 * offset of the orphan item.
2957 if (found_key.offset == last_objectid) {
2958 btrfs_err(fs_info,
2959 "Error removing orphan entry, stopping orphan cleanup");
2960 ret = -EINVAL;
2961 goto out;
2964 last_objectid = found_key.offset;
2966 found_key.objectid = found_key.offset;
2967 found_key.type = BTRFS_INODE_ITEM_KEY;
2968 found_key.offset = 0;
2969 inode = btrfs_iget(fs_info->sb, &found_key, root);
2970 ret = PTR_ERR_OR_ZERO(inode);
2971 if (ret && ret != -ENOENT)
2972 goto out;
2974 if (ret == -ENOENT && root == fs_info->tree_root) {
2975 struct btrfs_root *dead_root;
2976 struct btrfs_fs_info *fs_info = root->fs_info;
2977 int is_dead_root = 0;
2980 * this is an orphan in the tree root. Currently these
2981 * could come from 2 sources:
2982 * a) a snapshot deletion in progress
2983 * b) a free space cache inode
2984 * We need to distinguish those two, as the snapshot
2985 * orphan must not get deleted.
2986 * find_dead_roots already ran before us, so if this
2987 * is a snapshot deletion, we should find the root
2988 * in the dead_roots list
2990 spin_lock(&fs_info->trans_lock);
2991 list_for_each_entry(dead_root, &fs_info->dead_roots,
2992 root_list) {
2993 if (dead_root->root_key.objectid ==
2994 found_key.objectid) {
2995 is_dead_root = 1;
2996 break;
2999 spin_unlock(&fs_info->trans_lock);
3000 if (is_dead_root) {
3001 /* prevent this orphan from being found again */
3002 key.offset = found_key.objectid - 1;
3003 continue;
3009 * If we have an inode with links, there are a couple of
3010 * possibilities. Old kernels (before v3.12) used to create an
3011 * orphan item for truncate indicating that there were possibly
3012 * extent items past i_size that needed to be deleted. In v3.12,
3013 * truncate was changed to update i_size in sync with the extent
3014 * items, but the (useless) orphan item was still created. Since
3015 * v4.18, we don't create the orphan item for truncate at all.
3017 * So, this item could mean that we need to do a truncate, but
3018 * only if this filesystem was last used on a pre-v3.12 kernel
3019 * and was not cleanly unmounted. The odds of that are quite
3020 * slim, and it's a pain to do the truncate now, so just delete
3021 * the orphan item.
3023 * It's also possible that this orphan item was supposed to be
3024 * deleted but wasn't. The inode number may have been reused,
3025 * but either way, we can delete the orphan item.
3027 if (ret == -ENOENT || inode->i_nlink) {
3028 if (!ret)
3029 iput(inode);
3030 trans = btrfs_start_transaction(root, 1);
3031 if (IS_ERR(trans)) {
3032 ret = PTR_ERR(trans);
3033 goto out;
3035 btrfs_debug(fs_info, "auto deleting %Lu",
3036 found_key.objectid);
3037 ret = btrfs_del_orphan_item(trans, root,
3038 found_key.objectid);
3039 btrfs_end_transaction(trans);
3040 if (ret)
3041 goto out;
3042 continue;
3045 nr_unlink++;
3047 /* this will do delete_inode and everything for us */
3048 iput(inode);
3050 /* release the path since we're done with it */
3051 btrfs_release_path(path);
3053 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3055 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3056 trans = btrfs_join_transaction(root);
3057 if (!IS_ERR(trans))
3058 btrfs_end_transaction(trans);
3061 if (nr_unlink)
3062 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3064 out:
3065 if (ret)
3066 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3067 btrfs_free_path(path);
3068 return ret;
3072 * very simple check to peek ahead in the leaf looking for xattrs. If we
3073 * don't find any xattrs, we know there can't be any acls.
3075 * slot is the slot the inode is in, objectid is the objectid of the inode
3077 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3078 int slot, u64 objectid,
3079 int *first_xattr_slot)
3081 u32 nritems = btrfs_header_nritems(leaf);
3082 struct btrfs_key found_key;
3083 static u64 xattr_access = 0;
3084 static u64 xattr_default = 0;
3085 int scanned = 0;
3087 if (!xattr_access) {
3088 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3089 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3090 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3091 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3094 slot++;
3095 *first_xattr_slot = -1;
3096 while (slot < nritems) {
3097 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3099 /* we found a different objectid, there must not be acls */
3100 if (found_key.objectid != objectid)
3101 return 0;
3103 /* we found an xattr, assume we've got an acl */
3104 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3105 if (*first_xattr_slot == -1)
3106 *first_xattr_slot = slot;
3107 if (found_key.offset == xattr_access ||
3108 found_key.offset == xattr_default)
3109 return 1;
3113 * we found a key greater than an xattr key, there can't
3114 * be any acls later on
3116 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3117 return 0;
3119 slot++;
3120 scanned++;
3123 * it goes inode, inode backrefs, xattrs, extents,
3124 * so if there are a ton of hard links to an inode there can
3125 * be a lot of backrefs. Don't waste time searching too hard,
3126 * this is just an optimization
3128 if (scanned >= 8)
3129 break;
3131 /* we hit the end of the leaf before we found an xattr or
3132 * something larger than an xattr. We have to assume the inode
3133 * has acls
3135 if (*first_xattr_slot == -1)
3136 *first_xattr_slot = slot;
3137 return 1;
3141 * read an inode from the btree into the in-memory inode
3143 static int btrfs_read_locked_inode(struct inode *inode,
3144 struct btrfs_path *in_path)
3146 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3147 struct btrfs_path *path = in_path;
3148 struct extent_buffer *leaf;
3149 struct btrfs_inode_item *inode_item;
3150 struct btrfs_root *root = BTRFS_I(inode)->root;
3151 struct btrfs_key location;
3152 unsigned long ptr;
3153 int maybe_acls;
3154 u32 rdev;
3155 int ret;
3156 bool filled = false;
3157 int first_xattr_slot;
3159 ret = btrfs_fill_inode(inode, &rdev);
3160 if (!ret)
3161 filled = true;
3163 if (!path) {
3164 path = btrfs_alloc_path();
3165 if (!path)
3166 return -ENOMEM;
3169 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3171 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3172 if (ret) {
3173 if (path != in_path)
3174 btrfs_free_path(path);
3175 return ret;
3178 leaf = path->nodes[0];
3180 if (filled)
3181 goto cache_index;
3183 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3184 struct btrfs_inode_item);
3185 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3186 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3187 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3188 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3189 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3191 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3192 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3194 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3195 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3197 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3198 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3200 BTRFS_I(inode)->i_otime.tv_sec =
3201 btrfs_timespec_sec(leaf, &inode_item->otime);
3202 BTRFS_I(inode)->i_otime.tv_nsec =
3203 btrfs_timespec_nsec(leaf, &inode_item->otime);
3205 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3206 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3207 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3209 inode_set_iversion_queried(inode,
3210 btrfs_inode_sequence(leaf, inode_item));
3211 inode->i_generation = BTRFS_I(inode)->generation;
3212 inode->i_rdev = 0;
3213 rdev = btrfs_inode_rdev(leaf, inode_item);
3215 BTRFS_I(inode)->index_cnt = (u64)-1;
3216 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3218 cache_index:
3220 * If we were modified in the current generation and evicted from memory
3221 * and then re-read we need to do a full sync since we don't have any
3222 * idea about which extents were modified before we were evicted from
3223 * cache.
3225 * This is required for both inode re-read from disk and delayed inode
3226 * in delayed_nodes_tree.
3228 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3229 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3230 &BTRFS_I(inode)->runtime_flags);
3233 * We don't persist the id of the transaction where an unlink operation
3234 * against the inode was last made. So here we assume the inode might
3235 * have been evicted, and therefore the exact value of last_unlink_trans
3236 * lost, and set it to last_trans to avoid metadata inconsistencies
3237 * between the inode and its parent if the inode is fsync'ed and the log
3238 * replayed. For example, in the scenario:
3240 * touch mydir/foo
3241 * ln mydir/foo mydir/bar
3242 * sync
3243 * unlink mydir/bar
3244 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3245 * xfs_io -c fsync mydir/foo
3246 * <power failure>
3247 * mount fs, triggers fsync log replay
3249 * We must make sure that when we fsync our inode foo we also log its
3250 * parent inode, otherwise after log replay the parent still has the
3251 * dentry with the "bar" name but our inode foo has a link count of 1
3252 * and doesn't have an inode ref with the name "bar" anymore.
3254 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3255 * but it guarantees correctness at the expense of occasional full
3256 * transaction commits on fsync if our inode is a directory, or if our
3257 * inode is not a directory, logging its parent unnecessarily.
3259 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3261 path->slots[0]++;
3262 if (inode->i_nlink != 1 ||
3263 path->slots[0] >= btrfs_header_nritems(leaf))
3264 goto cache_acl;
3266 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3267 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3268 goto cache_acl;
3270 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3271 if (location.type == BTRFS_INODE_REF_KEY) {
3272 struct btrfs_inode_ref *ref;
3274 ref = (struct btrfs_inode_ref *)ptr;
3275 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3276 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3277 struct btrfs_inode_extref *extref;
3279 extref = (struct btrfs_inode_extref *)ptr;
3280 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3281 extref);
3283 cache_acl:
3285 * try to precache a NULL acl entry for files that don't have
3286 * any xattrs or acls
3288 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3289 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3290 if (first_xattr_slot != -1) {
3291 path->slots[0] = first_xattr_slot;
3292 ret = btrfs_load_inode_props(inode, path);
3293 if (ret)
3294 btrfs_err(fs_info,
3295 "error loading props for ino %llu (root %llu): %d",
3296 btrfs_ino(BTRFS_I(inode)),
3297 root->root_key.objectid, ret);
3299 if (path != in_path)
3300 btrfs_free_path(path);
3302 if (!maybe_acls)
3303 cache_no_acl(inode);
3305 switch (inode->i_mode & S_IFMT) {
3306 case S_IFREG:
3307 inode->i_mapping->a_ops = &btrfs_aops;
3308 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3309 inode->i_fop = &btrfs_file_operations;
3310 inode->i_op = &btrfs_file_inode_operations;
3311 break;
3312 case S_IFDIR:
3313 inode->i_fop = &btrfs_dir_file_operations;
3314 inode->i_op = &btrfs_dir_inode_operations;
3315 break;
3316 case S_IFLNK:
3317 inode->i_op = &btrfs_symlink_inode_operations;
3318 inode_nohighmem(inode);
3319 inode->i_mapping->a_ops = &btrfs_aops;
3320 break;
3321 default:
3322 inode->i_op = &btrfs_special_inode_operations;
3323 init_special_inode(inode, inode->i_mode, rdev);
3324 break;
3327 btrfs_sync_inode_flags_to_i_flags(inode);
3328 return 0;
3332 * given a leaf and an inode, copy the inode fields into the leaf
3334 static void fill_inode_item(struct btrfs_trans_handle *trans,
3335 struct extent_buffer *leaf,
3336 struct btrfs_inode_item *item,
3337 struct inode *inode)
3339 struct btrfs_map_token token;
3341 btrfs_init_map_token(&token, leaf);
3343 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3344 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3345 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3346 &token);
3347 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3348 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3350 btrfs_set_token_timespec_sec(leaf, &item->atime,
3351 inode->i_atime.tv_sec, &token);
3352 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3353 inode->i_atime.tv_nsec, &token);
3355 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3356 inode->i_mtime.tv_sec, &token);
3357 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3358 inode->i_mtime.tv_nsec, &token);
3360 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3361 inode->i_ctime.tv_sec, &token);
3362 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3363 inode->i_ctime.tv_nsec, &token);
3365 btrfs_set_token_timespec_sec(leaf, &item->otime,
3366 BTRFS_I(inode)->i_otime.tv_sec, &token);
3367 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3368 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3370 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3371 &token);
3372 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3373 &token);
3374 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3375 &token);
3376 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3377 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3378 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3379 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3383 * copy everything in the in-memory inode into the btree.
3385 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3386 struct btrfs_root *root, struct inode *inode)
3388 struct btrfs_inode_item *inode_item;
3389 struct btrfs_path *path;
3390 struct extent_buffer *leaf;
3391 int ret;
3393 path = btrfs_alloc_path();
3394 if (!path)
3395 return -ENOMEM;
3397 path->leave_spinning = 1;
3398 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3400 if (ret) {
3401 if (ret > 0)
3402 ret = -ENOENT;
3403 goto failed;
3406 leaf = path->nodes[0];
3407 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3408 struct btrfs_inode_item);
3410 fill_inode_item(trans, leaf, inode_item, inode);
3411 btrfs_mark_buffer_dirty(leaf);
3412 btrfs_set_inode_last_trans(trans, inode);
3413 ret = 0;
3414 failed:
3415 btrfs_free_path(path);
3416 return ret;
3420 * copy everything in the in-memory inode into the btree.
3422 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3423 struct btrfs_root *root, struct inode *inode)
3425 struct btrfs_fs_info *fs_info = root->fs_info;
3426 int ret;
3429 * If the inode is a free space inode, we can deadlock during commit
3430 * if we put it into the delayed code.
3432 * The data relocation inode should also be directly updated
3433 * without delay
3435 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3436 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3437 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3438 btrfs_update_root_times(trans, root);
3440 ret = btrfs_delayed_update_inode(trans, root, inode);
3441 if (!ret)
3442 btrfs_set_inode_last_trans(trans, inode);
3443 return ret;
3446 return btrfs_update_inode_item(trans, root, inode);
3449 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3450 struct btrfs_root *root,
3451 struct inode *inode)
3453 int ret;
3455 ret = btrfs_update_inode(trans, root, inode);
3456 if (ret == -ENOSPC)
3457 return btrfs_update_inode_item(trans, root, inode);
3458 return ret;
3462 * unlink helper that gets used here in inode.c and in the tree logging
3463 * recovery code. It remove a link in a directory with a given name, and
3464 * also drops the back refs in the inode to the directory
3466 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3467 struct btrfs_root *root,
3468 struct btrfs_inode *dir,
3469 struct btrfs_inode *inode,
3470 const char *name, int name_len)
3472 struct btrfs_fs_info *fs_info = root->fs_info;
3473 struct btrfs_path *path;
3474 int ret = 0;
3475 struct btrfs_dir_item *di;
3476 u64 index;
3477 u64 ino = btrfs_ino(inode);
3478 u64 dir_ino = btrfs_ino(dir);
3480 path = btrfs_alloc_path();
3481 if (!path) {
3482 ret = -ENOMEM;
3483 goto out;
3486 path->leave_spinning = 1;
3487 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3488 name, name_len, -1);
3489 if (IS_ERR_OR_NULL(di)) {
3490 ret = di ? PTR_ERR(di) : -ENOENT;
3491 goto err;
3493 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3494 if (ret)
3495 goto err;
3496 btrfs_release_path(path);
3499 * If we don't have dir index, we have to get it by looking up
3500 * the inode ref, since we get the inode ref, remove it directly,
3501 * it is unnecessary to do delayed deletion.
3503 * But if we have dir index, needn't search inode ref to get it.
3504 * Since the inode ref is close to the inode item, it is better
3505 * that we delay to delete it, and just do this deletion when
3506 * we update the inode item.
3508 if (inode->dir_index) {
3509 ret = btrfs_delayed_delete_inode_ref(inode);
3510 if (!ret) {
3511 index = inode->dir_index;
3512 goto skip_backref;
3516 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3517 dir_ino, &index);
3518 if (ret) {
3519 btrfs_info(fs_info,
3520 "failed to delete reference to %.*s, inode %llu parent %llu",
3521 name_len, name, ino, dir_ino);
3522 btrfs_abort_transaction(trans, ret);
3523 goto err;
3525 skip_backref:
3526 ret = btrfs_delete_delayed_dir_index(trans, dir, index);
3527 if (ret) {
3528 btrfs_abort_transaction(trans, ret);
3529 goto err;
3532 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3533 dir_ino);
3534 if (ret != 0 && ret != -ENOENT) {
3535 btrfs_abort_transaction(trans, ret);
3536 goto err;
3539 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
3540 index);
3541 if (ret == -ENOENT)
3542 ret = 0;
3543 else if (ret)
3544 btrfs_abort_transaction(trans, ret);
3547 * If we have a pending delayed iput we could end up with the final iput
3548 * being run in btrfs-cleaner context. If we have enough of these built
3549 * up we can end up burning a lot of time in btrfs-cleaner without any
3550 * way to throttle the unlinks. Since we're currently holding a ref on
3551 * the inode we can run the delayed iput here without any issues as the
3552 * final iput won't be done until after we drop the ref we're currently
3553 * holding.
3555 btrfs_run_delayed_iput(fs_info, inode);
3556 err:
3557 btrfs_free_path(path);
3558 if (ret)
3559 goto out;
3561 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
3562 inode_inc_iversion(&inode->vfs_inode);
3563 inode_inc_iversion(&dir->vfs_inode);
3564 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
3565 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
3566 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
3567 out:
3568 return ret;
3571 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3572 struct btrfs_root *root,
3573 struct btrfs_inode *dir, struct btrfs_inode *inode,
3574 const char *name, int name_len)
3576 int ret;
3577 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
3578 if (!ret) {
3579 drop_nlink(&inode->vfs_inode);
3580 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
3582 return ret;
3586 * helper to start transaction for unlink and rmdir.
3588 * unlink and rmdir are special in btrfs, they do not always free space, so
3589 * if we cannot make our reservations the normal way try and see if there is
3590 * plenty of slack room in the global reserve to migrate, otherwise we cannot
3591 * allow the unlink to occur.
3593 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
3595 struct btrfs_root *root = BTRFS_I(dir)->root;
3598 * 1 for the possible orphan item
3599 * 1 for the dir item
3600 * 1 for the dir index
3601 * 1 for the inode ref
3602 * 1 for the inode
3604 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
3607 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
3609 struct btrfs_root *root = BTRFS_I(dir)->root;
3610 struct btrfs_trans_handle *trans;
3611 struct inode *inode = d_inode(dentry);
3612 int ret;
3614 trans = __unlink_start_trans(dir);
3615 if (IS_ERR(trans))
3616 return PTR_ERR(trans);
3618 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
3621 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
3622 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
3623 dentry->d_name.len);
3624 if (ret)
3625 goto out;
3627 if (inode->i_nlink == 0) {
3628 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
3629 if (ret)
3630 goto out;
3633 out:
3634 btrfs_end_transaction(trans);
3635 btrfs_btree_balance_dirty(root->fs_info);
3636 return ret;
3639 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
3640 struct inode *dir, struct dentry *dentry)
3642 struct btrfs_root *root = BTRFS_I(dir)->root;
3643 struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
3644 struct btrfs_path *path;
3645 struct extent_buffer *leaf;
3646 struct btrfs_dir_item *di;
3647 struct btrfs_key key;
3648 const char *name = dentry->d_name.name;
3649 int name_len = dentry->d_name.len;
3650 u64 index;
3651 int ret;
3652 u64 objectid;
3653 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
3655 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
3656 objectid = inode->root->root_key.objectid;
3657 } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3658 objectid = inode->location.objectid;
3659 } else {
3660 WARN_ON(1);
3661 return -EINVAL;
3664 path = btrfs_alloc_path();
3665 if (!path)
3666 return -ENOMEM;
3668 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3669 name, name_len, -1);
3670 if (IS_ERR_OR_NULL(di)) {
3671 ret = di ? PTR_ERR(di) : -ENOENT;
3672 goto out;
3675 leaf = path->nodes[0];
3676 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3677 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
3678 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3679 if (ret) {
3680 btrfs_abort_transaction(trans, ret);
3681 goto out;
3683 btrfs_release_path(path);
3686 * This is a placeholder inode for a subvolume we didn't have a
3687 * reference to at the time of the snapshot creation. In the meantime
3688 * we could have renamed the real subvol link into our snapshot, so
3689 * depending on btrfs_del_root_ref to return -ENOENT here is incorret.
3690 * Instead simply lookup the dir_index_item for this entry so we can
3691 * remove it. Otherwise we know we have a ref to the root and we can
3692 * call btrfs_del_root_ref, and it _shouldn't_ fail.
3694 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
3695 di = btrfs_search_dir_index_item(root, path, dir_ino,
3696 name, name_len);
3697 if (IS_ERR_OR_NULL(di)) {
3698 if (!di)
3699 ret = -ENOENT;
3700 else
3701 ret = PTR_ERR(di);
3702 btrfs_abort_transaction(trans, ret);
3703 goto out;
3706 leaf = path->nodes[0];
3707 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3708 index = key.offset;
3709 btrfs_release_path(path);
3710 } else {
3711 ret = btrfs_del_root_ref(trans, objectid,
3712 root->root_key.objectid, dir_ino,
3713 &index, name, name_len);
3714 if (ret) {
3715 btrfs_abort_transaction(trans, ret);
3716 goto out;
3720 ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
3721 if (ret) {
3722 btrfs_abort_transaction(trans, ret);
3723 goto out;
3726 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
3727 inode_inc_iversion(dir);
3728 dir->i_mtime = dir->i_ctime = current_time(dir);
3729 ret = btrfs_update_inode_fallback(trans, root, dir);
3730 if (ret)
3731 btrfs_abort_transaction(trans, ret);
3732 out:
3733 btrfs_free_path(path);
3734 return ret;
3738 * Helper to check if the subvolume references other subvolumes or if it's
3739 * default.
3741 static noinline int may_destroy_subvol(struct btrfs_root *root)
3743 struct btrfs_fs_info *fs_info = root->fs_info;
3744 struct btrfs_path *path;
3745 struct btrfs_dir_item *di;
3746 struct btrfs_key key;
3747 u64 dir_id;
3748 int ret;
3750 path = btrfs_alloc_path();
3751 if (!path)
3752 return -ENOMEM;
3754 /* Make sure this root isn't set as the default subvol */
3755 dir_id = btrfs_super_root_dir(fs_info->super_copy);
3756 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
3757 dir_id, "default", 7, 0);
3758 if (di && !IS_ERR(di)) {
3759 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
3760 if (key.objectid == root->root_key.objectid) {
3761 ret = -EPERM;
3762 btrfs_err(fs_info,
3763 "deleting default subvolume %llu is not allowed",
3764 key.objectid);
3765 goto out;
3767 btrfs_release_path(path);
3770 key.objectid = root->root_key.objectid;
3771 key.type = BTRFS_ROOT_REF_KEY;
3772 key.offset = (u64)-1;
3774 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3775 if (ret < 0)
3776 goto out;
3777 BUG_ON(ret == 0);
3779 ret = 0;
3780 if (path->slots[0] > 0) {
3781 path->slots[0]--;
3782 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
3783 if (key.objectid == root->root_key.objectid &&
3784 key.type == BTRFS_ROOT_REF_KEY)
3785 ret = -ENOTEMPTY;
3787 out:
3788 btrfs_free_path(path);
3789 return ret;
3792 /* Delete all dentries for inodes belonging to the root */
3793 static void btrfs_prune_dentries(struct btrfs_root *root)
3795 struct btrfs_fs_info *fs_info = root->fs_info;
3796 struct rb_node *node;
3797 struct rb_node *prev;
3798 struct btrfs_inode *entry;
3799 struct inode *inode;
3800 u64 objectid = 0;
3802 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
3803 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
3805 spin_lock(&root->inode_lock);
3806 again:
3807 node = root->inode_tree.rb_node;
3808 prev = NULL;
3809 while (node) {
3810 prev = node;
3811 entry = rb_entry(node, struct btrfs_inode, rb_node);
3813 if (objectid < btrfs_ino(entry))
3814 node = node->rb_left;
3815 else if (objectid > btrfs_ino(entry))
3816 node = node->rb_right;
3817 else
3818 break;
3820 if (!node) {
3821 while (prev) {
3822 entry = rb_entry(prev, struct btrfs_inode, rb_node);
3823 if (objectid <= btrfs_ino(entry)) {
3824 node = prev;
3825 break;
3827 prev = rb_next(prev);
3830 while (node) {
3831 entry = rb_entry(node, struct btrfs_inode, rb_node);
3832 objectid = btrfs_ino(entry) + 1;
3833 inode = igrab(&entry->vfs_inode);
3834 if (inode) {
3835 spin_unlock(&root->inode_lock);
3836 if (atomic_read(&inode->i_count) > 1)
3837 d_prune_aliases(inode);
3839 * btrfs_drop_inode will have it removed from the inode
3840 * cache when its usage count hits zero.
3842 iput(inode);
3843 cond_resched();
3844 spin_lock(&root->inode_lock);
3845 goto again;
3848 if (cond_resched_lock(&root->inode_lock))
3849 goto again;
3851 node = rb_next(node);
3853 spin_unlock(&root->inode_lock);
3856 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
3858 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
3859 struct btrfs_root *root = BTRFS_I(dir)->root;
3860 struct inode *inode = d_inode(dentry);
3861 struct btrfs_root *dest = BTRFS_I(inode)->root;
3862 struct btrfs_trans_handle *trans;
3863 struct btrfs_block_rsv block_rsv;
3864 u64 root_flags;
3865 int ret;
3866 int err;
3869 * Don't allow to delete a subvolume with send in progress. This is
3870 * inside the inode lock so the error handling that has to drop the bit
3871 * again is not run concurrently.
3873 spin_lock(&dest->root_item_lock);
3874 if (dest->send_in_progress) {
3875 spin_unlock(&dest->root_item_lock);
3876 btrfs_warn(fs_info,
3877 "attempt to delete subvolume %llu during send",
3878 dest->root_key.objectid);
3879 return -EPERM;
3881 root_flags = btrfs_root_flags(&dest->root_item);
3882 btrfs_set_root_flags(&dest->root_item,
3883 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
3884 spin_unlock(&dest->root_item_lock);
3886 down_write(&fs_info->subvol_sem);
3888 err = may_destroy_subvol(dest);
3889 if (err)
3890 goto out_up_write;
3892 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
3894 * One for dir inode,
3895 * two for dir entries,
3896 * two for root ref/backref.
3898 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
3899 if (err)
3900 goto out_up_write;
3902 trans = btrfs_start_transaction(root, 0);
3903 if (IS_ERR(trans)) {
3904 err = PTR_ERR(trans);
3905 goto out_release;
3907 trans->block_rsv = &block_rsv;
3908 trans->bytes_reserved = block_rsv.size;
3910 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
3912 ret = btrfs_unlink_subvol(trans, dir, dentry);
3913 if (ret) {
3914 err = ret;
3915 btrfs_abort_transaction(trans, ret);
3916 goto out_end_trans;
3919 btrfs_record_root_in_trans(trans, dest);
3921 memset(&dest->root_item.drop_progress, 0,
3922 sizeof(dest->root_item.drop_progress));
3923 dest->root_item.drop_level = 0;
3924 btrfs_set_root_refs(&dest->root_item, 0);
3926 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
3927 ret = btrfs_insert_orphan_item(trans,
3928 fs_info->tree_root,
3929 dest->root_key.objectid);
3930 if (ret) {
3931 btrfs_abort_transaction(trans, ret);
3932 err = ret;
3933 goto out_end_trans;
3937 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
3938 BTRFS_UUID_KEY_SUBVOL,
3939 dest->root_key.objectid);
3940 if (ret && ret != -ENOENT) {
3941 btrfs_abort_transaction(trans, ret);
3942 err = ret;
3943 goto out_end_trans;
3945 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
3946 ret = btrfs_uuid_tree_remove(trans,
3947 dest->root_item.received_uuid,
3948 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
3949 dest->root_key.objectid);
3950 if (ret && ret != -ENOENT) {
3951 btrfs_abort_transaction(trans, ret);
3952 err = ret;
3953 goto out_end_trans;
3957 out_end_trans:
3958 trans->block_rsv = NULL;
3959 trans->bytes_reserved = 0;
3960 ret = btrfs_end_transaction(trans);
3961 if (ret && !err)
3962 err = ret;
3963 inode->i_flags |= S_DEAD;
3964 out_release:
3965 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
3966 out_up_write:
3967 up_write(&fs_info->subvol_sem);
3968 if (err) {
3969 spin_lock(&dest->root_item_lock);
3970 root_flags = btrfs_root_flags(&dest->root_item);
3971 btrfs_set_root_flags(&dest->root_item,
3972 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
3973 spin_unlock(&dest->root_item_lock);
3974 } else {
3975 d_invalidate(dentry);
3976 btrfs_prune_dentries(dest);
3977 ASSERT(dest->send_in_progress == 0);
3979 /* the last ref */
3980 if (dest->ino_cache_inode) {
3981 iput(dest->ino_cache_inode);
3982 dest->ino_cache_inode = NULL;
3986 return err;
3989 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
3991 struct inode *inode = d_inode(dentry);
3992 int err = 0;
3993 struct btrfs_root *root = BTRFS_I(dir)->root;
3994 struct btrfs_trans_handle *trans;
3995 u64 last_unlink_trans;
3997 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
3998 return -ENOTEMPTY;
3999 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4000 return btrfs_delete_subvolume(dir, dentry);
4002 trans = __unlink_start_trans(dir);
4003 if (IS_ERR(trans))
4004 return PTR_ERR(trans);
4006 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4007 err = btrfs_unlink_subvol(trans, dir, dentry);
4008 goto out;
4011 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4012 if (err)
4013 goto out;
4015 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4017 /* now the directory is empty */
4018 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4019 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4020 dentry->d_name.len);
4021 if (!err) {
4022 btrfs_i_size_write(BTRFS_I(inode), 0);
4024 * Propagate the last_unlink_trans value of the deleted dir to
4025 * its parent directory. This is to prevent an unrecoverable
4026 * log tree in the case we do something like this:
4027 * 1) create dir foo
4028 * 2) create snapshot under dir foo
4029 * 3) delete the snapshot
4030 * 4) rmdir foo
4031 * 5) mkdir foo
4032 * 6) fsync foo or some file inside foo
4034 if (last_unlink_trans >= trans->transid)
4035 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4037 out:
4038 btrfs_end_transaction(trans);
4039 btrfs_btree_balance_dirty(root->fs_info);
4041 return err;
4045 * Return this if we need to call truncate_block for the last bit of the
4046 * truncate.
4048 #define NEED_TRUNCATE_BLOCK 1
4051 * this can truncate away extent items, csum items and directory items.
4052 * It starts at a high offset and removes keys until it can't find
4053 * any higher than new_size
4055 * csum items that cross the new i_size are truncated to the new size
4056 * as well.
4058 * min_type is the minimum key type to truncate down to. If set to 0, this
4059 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4061 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4062 struct btrfs_root *root,
4063 struct inode *inode,
4064 u64 new_size, u32 min_type)
4066 struct btrfs_fs_info *fs_info = root->fs_info;
4067 struct btrfs_path *path;
4068 struct extent_buffer *leaf;
4069 struct btrfs_file_extent_item *fi;
4070 struct btrfs_key key;
4071 struct btrfs_key found_key;
4072 u64 extent_start = 0;
4073 u64 extent_num_bytes = 0;
4074 u64 extent_offset = 0;
4075 u64 item_end = 0;
4076 u64 last_size = new_size;
4077 u32 found_type = (u8)-1;
4078 int found_extent;
4079 int del_item;
4080 int pending_del_nr = 0;
4081 int pending_del_slot = 0;
4082 int extent_type = -1;
4083 int ret;
4084 u64 ino = btrfs_ino(BTRFS_I(inode));
4085 u64 bytes_deleted = 0;
4086 bool be_nice = false;
4087 bool should_throttle = false;
4088 const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
4089 struct extent_state *cached_state = NULL;
4091 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4094 * for non-free space inodes and ref cows, we want to back off from
4095 * time to time
4097 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4098 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4099 be_nice = true;
4101 path = btrfs_alloc_path();
4102 if (!path)
4103 return -ENOMEM;
4104 path->reada = READA_BACK;
4106 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4107 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
4108 &cached_state);
4111 * We want to drop from the next block forward in case this new size is
4112 * not block aligned since we will be keeping the last block of the
4113 * extent just the way it is.
4115 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4116 root == fs_info->tree_root)
4117 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4118 fs_info->sectorsize),
4119 (u64)-1, 0);
4122 * This function is also used to drop the items in the log tree before
4123 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4124 * it is used to drop the logged items. So we shouldn't kill the delayed
4125 * items.
4127 if (min_type == 0 && root == BTRFS_I(inode)->root)
4128 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4130 key.objectid = ino;
4131 key.offset = (u64)-1;
4132 key.type = (u8)-1;
4134 search_again:
4136 * with a 16K leaf size and 128MB extents, you can actually queue
4137 * up a huge file in a single leaf. Most of the time that
4138 * bytes_deleted is > 0, it will be huge by the time we get here
4140 if (be_nice && bytes_deleted > SZ_32M &&
4141 btrfs_should_end_transaction(trans)) {
4142 ret = -EAGAIN;
4143 goto out;
4146 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4147 if (ret < 0)
4148 goto out;
4150 if (ret > 0) {
4151 ret = 0;
4152 /* there are no items in the tree for us to truncate, we're
4153 * done
4155 if (path->slots[0] == 0)
4156 goto out;
4157 path->slots[0]--;
4160 while (1) {
4161 fi = NULL;
4162 leaf = path->nodes[0];
4163 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4164 found_type = found_key.type;
4166 if (found_key.objectid != ino)
4167 break;
4169 if (found_type < min_type)
4170 break;
4172 item_end = found_key.offset;
4173 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4174 fi = btrfs_item_ptr(leaf, path->slots[0],
4175 struct btrfs_file_extent_item);
4176 extent_type = btrfs_file_extent_type(leaf, fi);
4177 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4178 item_end +=
4179 btrfs_file_extent_num_bytes(leaf, fi);
4181 trace_btrfs_truncate_show_fi_regular(
4182 BTRFS_I(inode), leaf, fi,
4183 found_key.offset);
4184 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4185 item_end += btrfs_file_extent_ram_bytes(leaf,
4186 fi);
4188 trace_btrfs_truncate_show_fi_inline(
4189 BTRFS_I(inode), leaf, fi, path->slots[0],
4190 found_key.offset);
4192 item_end--;
4194 if (found_type > min_type) {
4195 del_item = 1;
4196 } else {
4197 if (item_end < new_size)
4198 break;
4199 if (found_key.offset >= new_size)
4200 del_item = 1;
4201 else
4202 del_item = 0;
4204 found_extent = 0;
4205 /* FIXME, shrink the extent if the ref count is only 1 */
4206 if (found_type != BTRFS_EXTENT_DATA_KEY)
4207 goto delete;
4209 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4210 u64 num_dec;
4211 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4212 if (!del_item) {
4213 u64 orig_num_bytes =
4214 btrfs_file_extent_num_bytes(leaf, fi);
4215 extent_num_bytes = ALIGN(new_size -
4216 found_key.offset,
4217 fs_info->sectorsize);
4218 btrfs_set_file_extent_num_bytes(leaf, fi,
4219 extent_num_bytes);
4220 num_dec = (orig_num_bytes -
4221 extent_num_bytes);
4222 if (test_bit(BTRFS_ROOT_REF_COWS,
4223 &root->state) &&
4224 extent_start != 0)
4225 inode_sub_bytes(inode, num_dec);
4226 btrfs_mark_buffer_dirty(leaf);
4227 } else {
4228 extent_num_bytes =
4229 btrfs_file_extent_disk_num_bytes(leaf,
4230 fi);
4231 extent_offset = found_key.offset -
4232 btrfs_file_extent_offset(leaf, fi);
4234 /* FIXME blocksize != 4096 */
4235 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4236 if (extent_start != 0) {
4237 found_extent = 1;
4238 if (test_bit(BTRFS_ROOT_REF_COWS,
4239 &root->state))
4240 inode_sub_bytes(inode, num_dec);
4243 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4245 * we can't truncate inline items that have had
4246 * special encodings
4248 if (!del_item &&
4249 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4250 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4251 btrfs_file_extent_compression(leaf, fi) == 0) {
4252 u32 size = (u32)(new_size - found_key.offset);
4254 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4255 size = btrfs_file_extent_calc_inline_size(size);
4256 btrfs_truncate_item(path, size, 1);
4257 } else if (!del_item) {
4259 * We have to bail so the last_size is set to
4260 * just before this extent.
4262 ret = NEED_TRUNCATE_BLOCK;
4263 break;
4266 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4267 inode_sub_bytes(inode, item_end + 1 - new_size);
4269 delete:
4270 if (del_item)
4271 last_size = found_key.offset;
4272 else
4273 last_size = new_size;
4274 if (del_item) {
4275 if (!pending_del_nr) {
4276 /* no pending yet, add ourselves */
4277 pending_del_slot = path->slots[0];
4278 pending_del_nr = 1;
4279 } else if (pending_del_nr &&
4280 path->slots[0] + 1 == pending_del_slot) {
4281 /* hop on the pending chunk */
4282 pending_del_nr++;
4283 pending_del_slot = path->slots[0];
4284 } else {
4285 BUG();
4287 } else {
4288 break;
4290 should_throttle = false;
4292 if (found_extent &&
4293 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4294 root == fs_info->tree_root)) {
4295 struct btrfs_ref ref = { 0 };
4297 bytes_deleted += extent_num_bytes;
4299 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF,
4300 extent_start, extent_num_bytes, 0);
4301 ref.real_root = root->root_key.objectid;
4302 btrfs_init_data_ref(&ref, btrfs_header_owner(leaf),
4303 ino, extent_offset);
4304 ret = btrfs_free_extent(trans, &ref);
4305 if (ret) {
4306 btrfs_abort_transaction(trans, ret);
4307 break;
4309 if (be_nice) {
4310 if (btrfs_should_throttle_delayed_refs(trans))
4311 should_throttle = true;
4315 if (found_type == BTRFS_INODE_ITEM_KEY)
4316 break;
4318 if (path->slots[0] == 0 ||
4319 path->slots[0] != pending_del_slot ||
4320 should_throttle) {
4321 if (pending_del_nr) {
4322 ret = btrfs_del_items(trans, root, path,
4323 pending_del_slot,
4324 pending_del_nr);
4325 if (ret) {
4326 btrfs_abort_transaction(trans, ret);
4327 break;
4329 pending_del_nr = 0;
4331 btrfs_release_path(path);
4334 * We can generate a lot of delayed refs, so we need to
4335 * throttle every once and a while and make sure we're
4336 * adding enough space to keep up with the work we are
4337 * generating. Since we hold a transaction here we
4338 * can't flush, and we don't want to FLUSH_LIMIT because
4339 * we could have generated too many delayed refs to
4340 * actually allocate, so just bail if we're short and
4341 * let the normal reservation dance happen higher up.
4343 if (should_throttle) {
4344 ret = btrfs_delayed_refs_rsv_refill(fs_info,
4345 BTRFS_RESERVE_NO_FLUSH);
4346 if (ret) {
4347 ret = -EAGAIN;
4348 break;
4351 goto search_again;
4352 } else {
4353 path->slots[0]--;
4356 out:
4357 if (ret >= 0 && pending_del_nr) {
4358 int err;
4360 err = btrfs_del_items(trans, root, path, pending_del_slot,
4361 pending_del_nr);
4362 if (err) {
4363 btrfs_abort_transaction(trans, err);
4364 ret = err;
4367 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4368 ASSERT(last_size >= new_size);
4369 if (!ret && last_size > new_size)
4370 last_size = new_size;
4371 btrfs_ordered_update_i_size(inode, last_size, NULL);
4372 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start,
4373 (u64)-1, &cached_state);
4376 btrfs_free_path(path);
4377 return ret;
4381 * btrfs_truncate_block - read, zero a chunk and write a block
4382 * @inode - inode that we're zeroing
4383 * @from - the offset to start zeroing
4384 * @len - the length to zero, 0 to zero the entire range respective to the
4385 * offset
4386 * @front - zero up to the offset instead of from the offset on
4388 * This will find the block for the "from" offset and cow the block and zero the
4389 * part we want to zero. This is used with truncate and hole punching.
4391 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4392 int front)
4394 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4395 struct address_space *mapping = inode->i_mapping;
4396 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4397 struct btrfs_ordered_extent *ordered;
4398 struct extent_state *cached_state = NULL;
4399 struct extent_changeset *data_reserved = NULL;
4400 char *kaddr;
4401 u32 blocksize = fs_info->sectorsize;
4402 pgoff_t index = from >> PAGE_SHIFT;
4403 unsigned offset = from & (blocksize - 1);
4404 struct page *page;
4405 gfp_t mask = btrfs_alloc_write_mask(mapping);
4406 int ret = 0;
4407 u64 block_start;
4408 u64 block_end;
4410 if (IS_ALIGNED(offset, blocksize) &&
4411 (!len || IS_ALIGNED(len, blocksize)))
4412 goto out;
4414 block_start = round_down(from, blocksize);
4415 block_end = block_start + blocksize - 1;
4417 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4418 block_start, blocksize);
4419 if (ret)
4420 goto out;
4422 again:
4423 page = find_or_create_page(mapping, index, mask);
4424 if (!page) {
4425 btrfs_delalloc_release_space(inode, data_reserved,
4426 block_start, blocksize, true);
4427 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4428 ret = -ENOMEM;
4429 goto out;
4432 if (!PageUptodate(page)) {
4433 ret = btrfs_readpage(NULL, page);
4434 lock_page(page);
4435 if (page->mapping != mapping) {
4436 unlock_page(page);
4437 put_page(page);
4438 goto again;
4440 if (!PageUptodate(page)) {
4441 ret = -EIO;
4442 goto out_unlock;
4445 wait_on_page_writeback(page);
4447 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4448 set_page_extent_mapped(page);
4450 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4451 if (ordered) {
4452 unlock_extent_cached(io_tree, block_start, block_end,
4453 &cached_state);
4454 unlock_page(page);
4455 put_page(page);
4456 btrfs_start_ordered_extent(inode, ordered, 1);
4457 btrfs_put_ordered_extent(ordered);
4458 goto again;
4461 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4462 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4463 0, 0, &cached_state);
4465 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4466 &cached_state);
4467 if (ret) {
4468 unlock_extent_cached(io_tree, block_start, block_end,
4469 &cached_state);
4470 goto out_unlock;
4473 if (offset != blocksize) {
4474 if (!len)
4475 len = blocksize - offset;
4476 kaddr = kmap(page);
4477 if (front)
4478 memset(kaddr + (block_start - page_offset(page)),
4479 0, offset);
4480 else
4481 memset(kaddr + (block_start - page_offset(page)) + offset,
4482 0, len);
4483 flush_dcache_page(page);
4484 kunmap(page);
4486 ClearPageChecked(page);
4487 set_page_dirty(page);
4488 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4490 out_unlock:
4491 if (ret)
4492 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4493 blocksize, true);
4494 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize);
4495 unlock_page(page);
4496 put_page(page);
4497 out:
4498 extent_changeset_free(data_reserved);
4499 return ret;
4502 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4503 u64 offset, u64 len)
4505 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4506 struct btrfs_trans_handle *trans;
4507 int ret;
4510 * Still need to make sure the inode looks like it's been updated so
4511 * that any holes get logged if we fsync.
4513 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4514 BTRFS_I(inode)->last_trans = fs_info->generation;
4515 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4516 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4517 return 0;
4521 * 1 - for the one we're dropping
4522 * 1 - for the one we're adding
4523 * 1 - for updating the inode.
4525 trans = btrfs_start_transaction(root, 3);
4526 if (IS_ERR(trans))
4527 return PTR_ERR(trans);
4529 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4530 if (ret) {
4531 btrfs_abort_transaction(trans, ret);
4532 btrfs_end_transaction(trans);
4533 return ret;
4536 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
4537 offset, 0, 0, len, 0, len, 0, 0, 0);
4538 if (ret)
4539 btrfs_abort_transaction(trans, ret);
4540 else
4541 btrfs_update_inode(trans, root, inode);
4542 btrfs_end_transaction(trans);
4543 return ret;
4547 * This function puts in dummy file extents for the area we're creating a hole
4548 * for. So if we are truncating this file to a larger size we need to insert
4549 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4550 * the range between oldsize and size
4552 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4554 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4555 struct btrfs_root *root = BTRFS_I(inode)->root;
4556 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4557 struct extent_map *em = NULL;
4558 struct extent_state *cached_state = NULL;
4559 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4560 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
4561 u64 block_end = ALIGN(size, fs_info->sectorsize);
4562 u64 last_byte;
4563 u64 cur_offset;
4564 u64 hole_size;
4565 int err = 0;
4568 * If our size started in the middle of a block we need to zero out the
4569 * rest of the block before we expand the i_size, otherwise we could
4570 * expose stale data.
4572 err = btrfs_truncate_block(inode, oldsize, 0, 0);
4573 if (err)
4574 return err;
4576 if (size <= hole_start)
4577 return 0;
4579 btrfs_lock_and_flush_ordered_range(io_tree, BTRFS_I(inode), hole_start,
4580 block_end - 1, &cached_state);
4581 cur_offset = hole_start;
4582 while (1) {
4583 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
4584 block_end - cur_offset);
4585 if (IS_ERR(em)) {
4586 err = PTR_ERR(em);
4587 em = NULL;
4588 break;
4590 last_byte = min(extent_map_end(em), block_end);
4591 last_byte = ALIGN(last_byte, fs_info->sectorsize);
4592 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4593 struct extent_map *hole_em;
4594 hole_size = last_byte - cur_offset;
4596 err = maybe_insert_hole(root, inode, cur_offset,
4597 hole_size);
4598 if (err)
4599 break;
4600 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
4601 cur_offset + hole_size - 1, 0);
4602 hole_em = alloc_extent_map();
4603 if (!hole_em) {
4604 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4605 &BTRFS_I(inode)->runtime_flags);
4606 goto next;
4608 hole_em->start = cur_offset;
4609 hole_em->len = hole_size;
4610 hole_em->orig_start = cur_offset;
4612 hole_em->block_start = EXTENT_MAP_HOLE;
4613 hole_em->block_len = 0;
4614 hole_em->orig_block_len = 0;
4615 hole_em->ram_bytes = hole_size;
4616 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4617 hole_em->generation = fs_info->generation;
4619 while (1) {
4620 write_lock(&em_tree->lock);
4621 err = add_extent_mapping(em_tree, hole_em, 1);
4622 write_unlock(&em_tree->lock);
4623 if (err != -EEXIST)
4624 break;
4625 btrfs_drop_extent_cache(BTRFS_I(inode),
4626 cur_offset,
4627 cur_offset +
4628 hole_size - 1, 0);
4630 free_extent_map(hole_em);
4632 next:
4633 free_extent_map(em);
4634 em = NULL;
4635 cur_offset = last_byte;
4636 if (cur_offset >= block_end)
4637 break;
4639 free_extent_map(em);
4640 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
4641 return err;
4644 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4646 struct btrfs_root *root = BTRFS_I(inode)->root;
4647 struct btrfs_trans_handle *trans;
4648 loff_t oldsize = i_size_read(inode);
4649 loff_t newsize = attr->ia_size;
4650 int mask = attr->ia_valid;
4651 int ret;
4654 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4655 * special case where we need to update the times despite not having
4656 * these flags set. For all other operations the VFS set these flags
4657 * explicitly if it wants a timestamp update.
4659 if (newsize != oldsize) {
4660 inode_inc_iversion(inode);
4661 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4662 inode->i_ctime = inode->i_mtime =
4663 current_time(inode);
4666 if (newsize > oldsize) {
4668 * Don't do an expanding truncate while snapshotting is ongoing.
4669 * This is to ensure the snapshot captures a fully consistent
4670 * state of this file - if the snapshot captures this expanding
4671 * truncation, it must capture all writes that happened before
4672 * this truncation.
4674 btrfs_wait_for_snapshot_creation(root);
4675 ret = btrfs_cont_expand(inode, oldsize, newsize);
4676 if (ret) {
4677 btrfs_end_write_no_snapshotting(root);
4678 return ret;
4681 trans = btrfs_start_transaction(root, 1);
4682 if (IS_ERR(trans)) {
4683 btrfs_end_write_no_snapshotting(root);
4684 return PTR_ERR(trans);
4687 i_size_write(inode, newsize);
4688 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4689 pagecache_isize_extended(inode, oldsize, newsize);
4690 ret = btrfs_update_inode(trans, root, inode);
4691 btrfs_end_write_no_snapshotting(root);
4692 btrfs_end_transaction(trans);
4693 } else {
4696 * We're truncating a file that used to have good data down to
4697 * zero. Make sure it gets into the ordered flush list so that
4698 * any new writes get down to disk quickly.
4700 if (newsize == 0)
4701 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
4702 &BTRFS_I(inode)->runtime_flags);
4704 truncate_setsize(inode, newsize);
4706 /* Disable nonlocked read DIO to avoid the endless truncate */
4707 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
4708 inode_dio_wait(inode);
4709 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
4711 ret = btrfs_truncate(inode, newsize == oldsize);
4712 if (ret && inode->i_nlink) {
4713 int err;
4716 * Truncate failed, so fix up the in-memory size. We
4717 * adjusted disk_i_size down as we removed extents, so
4718 * wait for disk_i_size to be stable and then update the
4719 * in-memory size to match.
4721 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
4722 if (err)
4723 return err;
4724 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
4728 return ret;
4731 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
4733 struct inode *inode = d_inode(dentry);
4734 struct btrfs_root *root = BTRFS_I(inode)->root;
4735 int err;
4737 if (btrfs_root_readonly(root))
4738 return -EROFS;
4740 err = setattr_prepare(dentry, attr);
4741 if (err)
4742 return err;
4744 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
4745 err = btrfs_setsize(inode, attr);
4746 if (err)
4747 return err;
4750 if (attr->ia_valid) {
4751 setattr_copy(inode, attr);
4752 inode_inc_iversion(inode);
4753 err = btrfs_dirty_inode(inode);
4755 if (!err && attr->ia_valid & ATTR_MODE)
4756 err = posix_acl_chmod(inode, inode->i_mode);
4759 return err;
4763 * While truncating the inode pages during eviction, we get the VFS calling
4764 * btrfs_invalidatepage() against each page of the inode. This is slow because
4765 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
4766 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
4767 * extent_state structures over and over, wasting lots of time.
4769 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
4770 * those expensive operations on a per page basis and do only the ordered io
4771 * finishing, while we release here the extent_map and extent_state structures,
4772 * without the excessive merging and splitting.
4774 static void evict_inode_truncate_pages(struct inode *inode)
4776 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4777 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
4778 struct rb_node *node;
4780 ASSERT(inode->i_state & I_FREEING);
4781 truncate_inode_pages_final(&inode->i_data);
4783 write_lock(&map_tree->lock);
4784 while (!RB_EMPTY_ROOT(&map_tree->map.rb_root)) {
4785 struct extent_map *em;
4787 node = rb_first_cached(&map_tree->map);
4788 em = rb_entry(node, struct extent_map, rb_node);
4789 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
4790 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
4791 remove_extent_mapping(map_tree, em);
4792 free_extent_map(em);
4793 if (need_resched()) {
4794 write_unlock(&map_tree->lock);
4795 cond_resched();
4796 write_lock(&map_tree->lock);
4799 write_unlock(&map_tree->lock);
4802 * Keep looping until we have no more ranges in the io tree.
4803 * We can have ongoing bios started by readpages (called from readahead)
4804 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
4805 * still in progress (unlocked the pages in the bio but did not yet
4806 * unlocked the ranges in the io tree). Therefore this means some
4807 * ranges can still be locked and eviction started because before
4808 * submitting those bios, which are executed by a separate task (work
4809 * queue kthread), inode references (inode->i_count) were not taken
4810 * (which would be dropped in the end io callback of each bio).
4811 * Therefore here we effectively end up waiting for those bios and
4812 * anyone else holding locked ranges without having bumped the inode's
4813 * reference count - if we don't do it, when they access the inode's
4814 * io_tree to unlock a range it may be too late, leading to an
4815 * use-after-free issue.
4817 spin_lock(&io_tree->lock);
4818 while (!RB_EMPTY_ROOT(&io_tree->state)) {
4819 struct extent_state *state;
4820 struct extent_state *cached_state = NULL;
4821 u64 start;
4822 u64 end;
4823 unsigned state_flags;
4825 node = rb_first(&io_tree->state);
4826 state = rb_entry(node, struct extent_state, rb_node);
4827 start = state->start;
4828 end = state->end;
4829 state_flags = state->state;
4830 spin_unlock(&io_tree->lock);
4832 lock_extent_bits(io_tree, start, end, &cached_state);
4835 * If still has DELALLOC flag, the extent didn't reach disk,
4836 * and its reserved space won't be freed by delayed_ref.
4837 * So we need to free its reserved space here.
4838 * (Refer to comment in btrfs_invalidatepage, case 2)
4840 * Note, end is the bytenr of last byte, so we need + 1 here.
4842 if (state_flags & EXTENT_DELALLOC)
4843 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
4845 clear_extent_bit(io_tree, start, end,
4846 EXTENT_LOCKED | EXTENT_DELALLOC |
4847 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
4848 &cached_state);
4850 cond_resched();
4851 spin_lock(&io_tree->lock);
4853 spin_unlock(&io_tree->lock);
4856 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
4857 struct btrfs_block_rsv *rsv)
4859 struct btrfs_fs_info *fs_info = root->fs_info;
4860 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4861 struct btrfs_trans_handle *trans;
4862 u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
4863 int ret;
4866 * Eviction should be taking place at some place safe because of our
4867 * delayed iputs. However the normal flushing code will run delayed
4868 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
4870 * We reserve the delayed_refs_extra here again because we can't use
4871 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
4872 * above. We reserve our extra bit here because we generate a ton of
4873 * delayed refs activity by truncating.
4875 * If we cannot make our reservation we'll attempt to steal from the
4876 * global reserve, because we really want to be able to free up space.
4878 ret = btrfs_block_rsv_refill(root, rsv, rsv->size + delayed_refs_extra,
4879 BTRFS_RESERVE_FLUSH_EVICT);
4880 if (ret) {
4882 * Try to steal from the global reserve if there is space for
4883 * it.
4885 if (btrfs_check_space_for_delayed_refs(fs_info) ||
4886 btrfs_block_rsv_migrate(global_rsv, rsv, rsv->size, 0)) {
4887 btrfs_warn(fs_info,
4888 "could not allocate space for delete; will truncate on mount");
4889 return ERR_PTR(-ENOSPC);
4891 delayed_refs_extra = 0;
4894 trans = btrfs_join_transaction(root);
4895 if (IS_ERR(trans))
4896 return trans;
4898 if (delayed_refs_extra) {
4899 trans->block_rsv = &fs_info->trans_block_rsv;
4900 trans->bytes_reserved = delayed_refs_extra;
4901 btrfs_block_rsv_migrate(rsv, trans->block_rsv,
4902 delayed_refs_extra, 1);
4904 return trans;
4907 void btrfs_evict_inode(struct inode *inode)
4909 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4910 struct btrfs_trans_handle *trans;
4911 struct btrfs_root *root = BTRFS_I(inode)->root;
4912 struct btrfs_block_rsv *rsv;
4913 int ret;
4915 trace_btrfs_inode_evict(inode);
4917 if (!root) {
4918 clear_inode(inode);
4919 return;
4922 evict_inode_truncate_pages(inode);
4924 if (inode->i_nlink &&
4925 ((btrfs_root_refs(&root->root_item) != 0 &&
4926 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
4927 btrfs_is_free_space_inode(BTRFS_I(inode))))
4928 goto no_delete;
4930 if (is_bad_inode(inode))
4931 goto no_delete;
4933 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
4935 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
4936 goto no_delete;
4938 if (inode->i_nlink > 0) {
4939 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
4940 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
4941 goto no_delete;
4944 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
4945 if (ret)
4946 goto no_delete;
4948 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
4949 if (!rsv)
4950 goto no_delete;
4951 rsv->size = btrfs_calc_metadata_size(fs_info, 1);
4952 rsv->failfast = 1;
4954 btrfs_i_size_write(BTRFS_I(inode), 0);
4956 while (1) {
4957 trans = evict_refill_and_join(root, rsv);
4958 if (IS_ERR(trans))
4959 goto free_rsv;
4961 trans->block_rsv = rsv;
4963 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
4964 trans->block_rsv = &fs_info->trans_block_rsv;
4965 btrfs_end_transaction(trans);
4966 btrfs_btree_balance_dirty(fs_info);
4967 if (ret && ret != -ENOSPC && ret != -EAGAIN)
4968 goto free_rsv;
4969 else if (!ret)
4970 break;
4974 * Errors here aren't a big deal, it just means we leave orphan items in
4975 * the tree. They will be cleaned up on the next mount. If the inode
4976 * number gets reused, cleanup deletes the orphan item without doing
4977 * anything, and unlink reuses the existing orphan item.
4979 * If it turns out that we are dropping too many of these, we might want
4980 * to add a mechanism for retrying these after a commit.
4982 trans = evict_refill_and_join(root, rsv);
4983 if (!IS_ERR(trans)) {
4984 trans->block_rsv = rsv;
4985 btrfs_orphan_del(trans, BTRFS_I(inode));
4986 trans->block_rsv = &fs_info->trans_block_rsv;
4987 btrfs_end_transaction(trans);
4990 if (!(root == fs_info->tree_root ||
4991 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
4992 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
4994 free_rsv:
4995 btrfs_free_block_rsv(fs_info, rsv);
4996 no_delete:
4998 * If we didn't successfully delete, the orphan item will still be in
4999 * the tree and we'll retry on the next mount. Again, we might also want
5000 * to retry these periodically in the future.
5002 btrfs_remove_delayed_node(BTRFS_I(inode));
5003 clear_inode(inode);
5007 * Return the key found in the dir entry in the location pointer, fill @type
5008 * with BTRFS_FT_*, and return 0.
5010 * If no dir entries were found, returns -ENOENT.
5011 * If found a corrupted location in dir entry, returns -EUCLEAN.
5013 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5014 struct btrfs_key *location, u8 *type)
5016 const char *name = dentry->d_name.name;
5017 int namelen = dentry->d_name.len;
5018 struct btrfs_dir_item *di;
5019 struct btrfs_path *path;
5020 struct btrfs_root *root = BTRFS_I(dir)->root;
5021 int ret = 0;
5023 path = btrfs_alloc_path();
5024 if (!path)
5025 return -ENOMEM;
5027 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5028 name, namelen, 0);
5029 if (IS_ERR_OR_NULL(di)) {
5030 ret = di ? PTR_ERR(di) : -ENOENT;
5031 goto out;
5034 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5035 if (location->type != BTRFS_INODE_ITEM_KEY &&
5036 location->type != BTRFS_ROOT_ITEM_KEY) {
5037 ret = -EUCLEAN;
5038 btrfs_warn(root->fs_info,
5039 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5040 __func__, name, btrfs_ino(BTRFS_I(dir)),
5041 location->objectid, location->type, location->offset);
5043 if (!ret)
5044 *type = btrfs_dir_type(path->nodes[0], di);
5045 out:
5046 btrfs_free_path(path);
5047 return ret;
5051 * when we hit a tree root in a directory, the btrfs part of the inode
5052 * needs to be changed to reflect the root directory of the tree root. This
5053 * is kind of like crossing a mount point.
5055 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5056 struct inode *dir,
5057 struct dentry *dentry,
5058 struct btrfs_key *location,
5059 struct btrfs_root **sub_root)
5061 struct btrfs_path *path;
5062 struct btrfs_root *new_root;
5063 struct btrfs_root_ref *ref;
5064 struct extent_buffer *leaf;
5065 struct btrfs_key key;
5066 int ret;
5067 int err = 0;
5069 path = btrfs_alloc_path();
5070 if (!path) {
5071 err = -ENOMEM;
5072 goto out;
5075 err = -ENOENT;
5076 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5077 key.type = BTRFS_ROOT_REF_KEY;
5078 key.offset = location->objectid;
5080 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5081 if (ret) {
5082 if (ret < 0)
5083 err = ret;
5084 goto out;
5087 leaf = path->nodes[0];
5088 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5089 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5090 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5091 goto out;
5093 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5094 (unsigned long)(ref + 1),
5095 dentry->d_name.len);
5096 if (ret)
5097 goto out;
5099 btrfs_release_path(path);
5101 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5102 if (IS_ERR(new_root)) {
5103 err = PTR_ERR(new_root);
5104 goto out;
5107 *sub_root = new_root;
5108 location->objectid = btrfs_root_dirid(&new_root->root_item);
5109 location->type = BTRFS_INODE_ITEM_KEY;
5110 location->offset = 0;
5111 err = 0;
5112 out:
5113 btrfs_free_path(path);
5114 return err;
5117 static void inode_tree_add(struct inode *inode)
5119 struct btrfs_root *root = BTRFS_I(inode)->root;
5120 struct btrfs_inode *entry;
5121 struct rb_node **p;
5122 struct rb_node *parent;
5123 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5124 u64 ino = btrfs_ino(BTRFS_I(inode));
5126 if (inode_unhashed(inode))
5127 return;
5128 parent = NULL;
5129 spin_lock(&root->inode_lock);
5130 p = &root->inode_tree.rb_node;
5131 while (*p) {
5132 parent = *p;
5133 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5135 if (ino < btrfs_ino(entry))
5136 p = &parent->rb_left;
5137 else if (ino > btrfs_ino(entry))
5138 p = &parent->rb_right;
5139 else {
5140 WARN_ON(!(entry->vfs_inode.i_state &
5141 (I_WILL_FREE | I_FREEING)));
5142 rb_replace_node(parent, new, &root->inode_tree);
5143 RB_CLEAR_NODE(parent);
5144 spin_unlock(&root->inode_lock);
5145 return;
5148 rb_link_node(new, parent, p);
5149 rb_insert_color(new, &root->inode_tree);
5150 spin_unlock(&root->inode_lock);
5153 static void inode_tree_del(struct inode *inode)
5155 struct btrfs_root *root = BTRFS_I(inode)->root;
5156 int empty = 0;
5158 spin_lock(&root->inode_lock);
5159 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5160 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5161 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5162 empty = RB_EMPTY_ROOT(&root->inode_tree);
5164 spin_unlock(&root->inode_lock);
5166 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5167 spin_lock(&root->inode_lock);
5168 empty = RB_EMPTY_ROOT(&root->inode_tree);
5169 spin_unlock(&root->inode_lock);
5170 if (empty)
5171 btrfs_add_dead_root(root);
5176 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5178 struct btrfs_iget_args *args = p;
5179 inode->i_ino = args->location->objectid;
5180 memcpy(&BTRFS_I(inode)->location, args->location,
5181 sizeof(*args->location));
5182 BTRFS_I(inode)->root = args->root;
5183 return 0;
5186 static int btrfs_find_actor(struct inode *inode, void *opaque)
5188 struct btrfs_iget_args *args = opaque;
5189 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5190 args->root == BTRFS_I(inode)->root;
5193 static struct inode *btrfs_iget_locked(struct super_block *s,
5194 struct btrfs_key *location,
5195 struct btrfs_root *root)
5197 struct inode *inode;
5198 struct btrfs_iget_args args;
5199 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5201 args.location = location;
5202 args.root = root;
5204 inode = iget5_locked(s, hashval, btrfs_find_actor,
5205 btrfs_init_locked_inode,
5206 (void *)&args);
5207 return inode;
5211 * Get an inode object given its location and corresponding root.
5212 * Path can be preallocated to prevent recursing back to iget through
5213 * allocator. NULL is also valid but may require an additional allocation
5214 * later.
5216 struct inode *btrfs_iget_path(struct super_block *s, struct btrfs_key *location,
5217 struct btrfs_root *root, struct btrfs_path *path)
5219 struct inode *inode;
5221 inode = btrfs_iget_locked(s, location, root);
5222 if (!inode)
5223 return ERR_PTR(-ENOMEM);
5225 if (inode->i_state & I_NEW) {
5226 int ret;
5228 ret = btrfs_read_locked_inode(inode, path);
5229 if (!ret) {
5230 inode_tree_add(inode);
5231 unlock_new_inode(inode);
5232 } else {
5233 iget_failed(inode);
5235 * ret > 0 can come from btrfs_search_slot called by
5236 * btrfs_read_locked_inode, this means the inode item
5237 * was not found.
5239 if (ret > 0)
5240 ret = -ENOENT;
5241 inode = ERR_PTR(ret);
5245 return inode;
5248 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5249 struct btrfs_root *root)
5251 return btrfs_iget_path(s, location, root, NULL);
5254 static struct inode *new_simple_dir(struct super_block *s,
5255 struct btrfs_key *key,
5256 struct btrfs_root *root)
5258 struct inode *inode = new_inode(s);
5260 if (!inode)
5261 return ERR_PTR(-ENOMEM);
5263 BTRFS_I(inode)->root = root;
5264 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5265 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5267 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5269 * We only need lookup, the rest is read-only and there's no inode
5270 * associated with the dentry
5272 inode->i_op = &simple_dir_inode_operations;
5273 inode->i_opflags &= ~IOP_XATTR;
5274 inode->i_fop = &simple_dir_operations;
5275 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5276 inode->i_mtime = current_time(inode);
5277 inode->i_atime = inode->i_mtime;
5278 inode->i_ctime = inode->i_mtime;
5279 BTRFS_I(inode)->i_otime = inode->i_mtime;
5281 return inode;
5284 static inline u8 btrfs_inode_type(struct inode *inode)
5287 * Compile-time asserts that generic FT_* types still match
5288 * BTRFS_FT_* types
5290 BUILD_BUG_ON(BTRFS_FT_UNKNOWN != FT_UNKNOWN);
5291 BUILD_BUG_ON(BTRFS_FT_REG_FILE != FT_REG_FILE);
5292 BUILD_BUG_ON(BTRFS_FT_DIR != FT_DIR);
5293 BUILD_BUG_ON(BTRFS_FT_CHRDEV != FT_CHRDEV);
5294 BUILD_BUG_ON(BTRFS_FT_BLKDEV != FT_BLKDEV);
5295 BUILD_BUG_ON(BTRFS_FT_FIFO != FT_FIFO);
5296 BUILD_BUG_ON(BTRFS_FT_SOCK != FT_SOCK);
5297 BUILD_BUG_ON(BTRFS_FT_SYMLINK != FT_SYMLINK);
5299 return fs_umode_to_ftype(inode->i_mode);
5302 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5304 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5305 struct inode *inode;
5306 struct btrfs_root *root = BTRFS_I(dir)->root;
5307 struct btrfs_root *sub_root = root;
5308 struct btrfs_key location;
5309 u8 di_type = 0;
5310 int index;
5311 int ret = 0;
5313 if (dentry->d_name.len > BTRFS_NAME_LEN)
5314 return ERR_PTR(-ENAMETOOLONG);
5316 ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
5317 if (ret < 0)
5318 return ERR_PTR(ret);
5320 if (location.type == BTRFS_INODE_ITEM_KEY) {
5321 inode = btrfs_iget(dir->i_sb, &location, root);
5322 if (IS_ERR(inode))
5323 return inode;
5325 /* Do extra check against inode mode with di_type */
5326 if (btrfs_inode_type(inode) != di_type) {
5327 btrfs_crit(fs_info,
5328 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5329 inode->i_mode, btrfs_inode_type(inode),
5330 di_type);
5331 iput(inode);
5332 return ERR_PTR(-EUCLEAN);
5334 return inode;
5337 index = srcu_read_lock(&fs_info->subvol_srcu);
5338 ret = fixup_tree_root_location(fs_info, dir, dentry,
5339 &location, &sub_root);
5340 if (ret < 0) {
5341 if (ret != -ENOENT)
5342 inode = ERR_PTR(ret);
5343 else
5344 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5345 } else {
5346 inode = btrfs_iget(dir->i_sb, &location, sub_root);
5348 srcu_read_unlock(&fs_info->subvol_srcu, index);
5350 if (!IS_ERR(inode) && root != sub_root) {
5351 down_read(&fs_info->cleanup_work_sem);
5352 if (!sb_rdonly(inode->i_sb))
5353 ret = btrfs_orphan_cleanup(sub_root);
5354 up_read(&fs_info->cleanup_work_sem);
5355 if (ret) {
5356 iput(inode);
5357 inode = ERR_PTR(ret);
5361 return inode;
5364 static int btrfs_dentry_delete(const struct dentry *dentry)
5366 struct btrfs_root *root;
5367 struct inode *inode = d_inode(dentry);
5369 if (!inode && !IS_ROOT(dentry))
5370 inode = d_inode(dentry->d_parent);
5372 if (inode) {
5373 root = BTRFS_I(inode)->root;
5374 if (btrfs_root_refs(&root->root_item) == 0)
5375 return 1;
5377 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5378 return 1;
5380 return 0;
5383 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5384 unsigned int flags)
5386 struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5388 if (inode == ERR_PTR(-ENOENT))
5389 inode = NULL;
5390 return d_splice_alias(inode, dentry);
5394 * All this infrastructure exists because dir_emit can fault, and we are holding
5395 * the tree lock when doing readdir. For now just allocate a buffer and copy
5396 * our information into that, and then dir_emit from the buffer. This is
5397 * similar to what NFS does, only we don't keep the buffer around in pagecache
5398 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5399 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5400 * tree lock.
5402 static int btrfs_opendir(struct inode *inode, struct file *file)
5404 struct btrfs_file_private *private;
5406 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5407 if (!private)
5408 return -ENOMEM;
5409 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5410 if (!private->filldir_buf) {
5411 kfree(private);
5412 return -ENOMEM;
5414 file->private_data = private;
5415 return 0;
5418 struct dir_entry {
5419 u64 ino;
5420 u64 offset;
5421 unsigned type;
5422 int name_len;
5425 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5427 while (entries--) {
5428 struct dir_entry *entry = addr;
5429 char *name = (char *)(entry + 1);
5431 ctx->pos = get_unaligned(&entry->offset);
5432 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5433 get_unaligned(&entry->ino),
5434 get_unaligned(&entry->type)))
5435 return 1;
5436 addr += sizeof(struct dir_entry) +
5437 get_unaligned(&entry->name_len);
5438 ctx->pos++;
5440 return 0;
5443 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5445 struct inode *inode = file_inode(file);
5446 struct btrfs_root *root = BTRFS_I(inode)->root;
5447 struct btrfs_file_private *private = file->private_data;
5448 struct btrfs_dir_item *di;
5449 struct btrfs_key key;
5450 struct btrfs_key found_key;
5451 struct btrfs_path *path;
5452 void *addr;
5453 struct list_head ins_list;
5454 struct list_head del_list;
5455 int ret;
5456 struct extent_buffer *leaf;
5457 int slot;
5458 char *name_ptr;
5459 int name_len;
5460 int entries = 0;
5461 int total_len = 0;
5462 bool put = false;
5463 struct btrfs_key location;
5465 if (!dir_emit_dots(file, ctx))
5466 return 0;
5468 path = btrfs_alloc_path();
5469 if (!path)
5470 return -ENOMEM;
5472 addr = private->filldir_buf;
5473 path->reada = READA_FORWARD;
5475 INIT_LIST_HEAD(&ins_list);
5476 INIT_LIST_HEAD(&del_list);
5477 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5479 again:
5480 key.type = BTRFS_DIR_INDEX_KEY;
5481 key.offset = ctx->pos;
5482 key.objectid = btrfs_ino(BTRFS_I(inode));
5484 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5485 if (ret < 0)
5486 goto err;
5488 while (1) {
5489 struct dir_entry *entry;
5491 leaf = path->nodes[0];
5492 slot = path->slots[0];
5493 if (slot >= btrfs_header_nritems(leaf)) {
5494 ret = btrfs_next_leaf(root, path);
5495 if (ret < 0)
5496 goto err;
5497 else if (ret > 0)
5498 break;
5499 continue;
5502 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5504 if (found_key.objectid != key.objectid)
5505 break;
5506 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5507 break;
5508 if (found_key.offset < ctx->pos)
5509 goto next;
5510 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5511 goto next;
5512 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5513 name_len = btrfs_dir_name_len(leaf, di);
5514 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5515 PAGE_SIZE) {
5516 btrfs_release_path(path);
5517 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5518 if (ret)
5519 goto nopos;
5520 addr = private->filldir_buf;
5521 entries = 0;
5522 total_len = 0;
5523 goto again;
5526 entry = addr;
5527 put_unaligned(name_len, &entry->name_len);
5528 name_ptr = (char *)(entry + 1);
5529 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5530 name_len);
5531 put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
5532 &entry->type);
5533 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5534 put_unaligned(location.objectid, &entry->ino);
5535 put_unaligned(found_key.offset, &entry->offset);
5536 entries++;
5537 addr += sizeof(struct dir_entry) + name_len;
5538 total_len += sizeof(struct dir_entry) + name_len;
5539 next:
5540 path->slots[0]++;
5542 btrfs_release_path(path);
5544 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5545 if (ret)
5546 goto nopos;
5548 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5549 if (ret)
5550 goto nopos;
5553 * Stop new entries from being returned after we return the last
5554 * entry.
5556 * New directory entries are assigned a strictly increasing
5557 * offset. This means that new entries created during readdir
5558 * are *guaranteed* to be seen in the future by that readdir.
5559 * This has broken buggy programs which operate on names as
5560 * they're returned by readdir. Until we re-use freed offsets
5561 * we have this hack to stop new entries from being returned
5562 * under the assumption that they'll never reach this huge
5563 * offset.
5565 * This is being careful not to overflow 32bit loff_t unless the
5566 * last entry requires it because doing so has broken 32bit apps
5567 * in the past.
5569 if (ctx->pos >= INT_MAX)
5570 ctx->pos = LLONG_MAX;
5571 else
5572 ctx->pos = INT_MAX;
5573 nopos:
5574 ret = 0;
5575 err:
5576 if (put)
5577 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
5578 btrfs_free_path(path);
5579 return ret;
5583 * This is somewhat expensive, updating the tree every time the
5584 * inode changes. But, it is most likely to find the inode in cache.
5585 * FIXME, needs more benchmarking...there are no reasons other than performance
5586 * to keep or drop this code.
5588 static int btrfs_dirty_inode(struct inode *inode)
5590 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5591 struct btrfs_root *root = BTRFS_I(inode)->root;
5592 struct btrfs_trans_handle *trans;
5593 int ret;
5595 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5596 return 0;
5598 trans = btrfs_join_transaction(root);
5599 if (IS_ERR(trans))
5600 return PTR_ERR(trans);
5602 ret = btrfs_update_inode(trans, root, inode);
5603 if (ret && ret == -ENOSPC) {
5604 /* whoops, lets try again with the full transaction */
5605 btrfs_end_transaction(trans);
5606 trans = btrfs_start_transaction(root, 1);
5607 if (IS_ERR(trans))
5608 return PTR_ERR(trans);
5610 ret = btrfs_update_inode(trans, root, inode);
5612 btrfs_end_transaction(trans);
5613 if (BTRFS_I(inode)->delayed_node)
5614 btrfs_balance_delayed_items(fs_info);
5616 return ret;
5620 * This is a copy of file_update_time. We need this so we can return error on
5621 * ENOSPC for updating the inode in the case of file write and mmap writes.
5623 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
5624 int flags)
5626 struct btrfs_root *root = BTRFS_I(inode)->root;
5627 bool dirty = flags & ~S_VERSION;
5629 if (btrfs_root_readonly(root))
5630 return -EROFS;
5632 if (flags & S_VERSION)
5633 dirty |= inode_maybe_inc_iversion(inode, dirty);
5634 if (flags & S_CTIME)
5635 inode->i_ctime = *now;
5636 if (flags & S_MTIME)
5637 inode->i_mtime = *now;
5638 if (flags & S_ATIME)
5639 inode->i_atime = *now;
5640 return dirty ? btrfs_dirty_inode(inode) : 0;
5644 * find the highest existing sequence number in a directory
5645 * and then set the in-memory index_cnt variable to reflect
5646 * free sequence numbers
5648 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5650 struct btrfs_root *root = inode->root;
5651 struct btrfs_key key, found_key;
5652 struct btrfs_path *path;
5653 struct extent_buffer *leaf;
5654 int ret;
5656 key.objectid = btrfs_ino(inode);
5657 key.type = BTRFS_DIR_INDEX_KEY;
5658 key.offset = (u64)-1;
5660 path = btrfs_alloc_path();
5661 if (!path)
5662 return -ENOMEM;
5664 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5665 if (ret < 0)
5666 goto out;
5667 /* FIXME: we should be able to handle this */
5668 if (ret == 0)
5669 goto out;
5670 ret = 0;
5673 * MAGIC NUMBER EXPLANATION:
5674 * since we search a directory based on f_pos we have to start at 2
5675 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
5676 * else has to start at 2
5678 if (path->slots[0] == 0) {
5679 inode->index_cnt = 2;
5680 goto out;
5683 path->slots[0]--;
5685 leaf = path->nodes[0];
5686 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5688 if (found_key.objectid != btrfs_ino(inode) ||
5689 found_key.type != BTRFS_DIR_INDEX_KEY) {
5690 inode->index_cnt = 2;
5691 goto out;
5694 inode->index_cnt = found_key.offset + 1;
5695 out:
5696 btrfs_free_path(path);
5697 return ret;
5701 * helper to find a free sequence number in a given directory. This current
5702 * code is very simple, later versions will do smarter things in the btree
5704 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
5706 int ret = 0;
5708 if (dir->index_cnt == (u64)-1) {
5709 ret = btrfs_inode_delayed_dir_index_count(dir);
5710 if (ret) {
5711 ret = btrfs_set_inode_index_count(dir);
5712 if (ret)
5713 return ret;
5717 *index = dir->index_cnt;
5718 dir->index_cnt++;
5720 return ret;
5723 static int btrfs_insert_inode_locked(struct inode *inode)
5725 struct btrfs_iget_args args;
5726 args.location = &BTRFS_I(inode)->location;
5727 args.root = BTRFS_I(inode)->root;
5729 return insert_inode_locked4(inode,
5730 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
5731 btrfs_find_actor, &args);
5735 * Inherit flags from the parent inode.
5737 * Currently only the compression flags and the cow flags are inherited.
5739 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
5741 unsigned int flags;
5743 if (!dir)
5744 return;
5746 flags = BTRFS_I(dir)->flags;
5748 if (flags & BTRFS_INODE_NOCOMPRESS) {
5749 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
5750 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
5751 } else if (flags & BTRFS_INODE_COMPRESS) {
5752 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
5753 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
5756 if (flags & BTRFS_INODE_NODATACOW) {
5757 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
5758 if (S_ISREG(inode->i_mode))
5759 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5762 btrfs_sync_inode_flags_to_i_flags(inode);
5765 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
5766 struct btrfs_root *root,
5767 struct inode *dir,
5768 const char *name, int name_len,
5769 u64 ref_objectid, u64 objectid,
5770 umode_t mode, u64 *index)
5772 struct btrfs_fs_info *fs_info = root->fs_info;
5773 struct inode *inode;
5774 struct btrfs_inode_item *inode_item;
5775 struct btrfs_key *location;
5776 struct btrfs_path *path;
5777 struct btrfs_inode_ref *ref;
5778 struct btrfs_key key[2];
5779 u32 sizes[2];
5780 int nitems = name ? 2 : 1;
5781 unsigned long ptr;
5782 unsigned int nofs_flag;
5783 int ret;
5785 path = btrfs_alloc_path();
5786 if (!path)
5787 return ERR_PTR(-ENOMEM);
5789 nofs_flag = memalloc_nofs_save();
5790 inode = new_inode(fs_info->sb);
5791 memalloc_nofs_restore(nofs_flag);
5792 if (!inode) {
5793 btrfs_free_path(path);
5794 return ERR_PTR(-ENOMEM);
5798 * O_TMPFILE, set link count to 0, so that after this point,
5799 * we fill in an inode item with the correct link count.
5801 if (!name)
5802 set_nlink(inode, 0);
5805 * we have to initialize this early, so we can reclaim the inode
5806 * number if we fail afterwards in this function.
5808 inode->i_ino = objectid;
5810 if (dir && name) {
5811 trace_btrfs_inode_request(dir);
5813 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
5814 if (ret) {
5815 btrfs_free_path(path);
5816 iput(inode);
5817 return ERR_PTR(ret);
5819 } else if (dir) {
5820 *index = 0;
5823 * index_cnt is ignored for everything but a dir,
5824 * btrfs_set_inode_index_count has an explanation for the magic
5825 * number
5827 BTRFS_I(inode)->index_cnt = 2;
5828 BTRFS_I(inode)->dir_index = *index;
5829 BTRFS_I(inode)->root = root;
5830 BTRFS_I(inode)->generation = trans->transid;
5831 inode->i_generation = BTRFS_I(inode)->generation;
5834 * We could have gotten an inode number from somebody who was fsynced
5835 * and then removed in this same transaction, so let's just set full
5836 * sync since it will be a full sync anyway and this will blow away the
5837 * old info in the log.
5839 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
5841 key[0].objectid = objectid;
5842 key[0].type = BTRFS_INODE_ITEM_KEY;
5843 key[0].offset = 0;
5845 sizes[0] = sizeof(struct btrfs_inode_item);
5847 if (name) {
5849 * Start new inodes with an inode_ref. This is slightly more
5850 * efficient for small numbers of hard links since they will
5851 * be packed into one item. Extended refs will kick in if we
5852 * add more hard links than can fit in the ref item.
5854 key[1].objectid = objectid;
5855 key[1].type = BTRFS_INODE_REF_KEY;
5856 key[1].offset = ref_objectid;
5858 sizes[1] = name_len + sizeof(*ref);
5861 location = &BTRFS_I(inode)->location;
5862 location->objectid = objectid;
5863 location->offset = 0;
5864 location->type = BTRFS_INODE_ITEM_KEY;
5866 ret = btrfs_insert_inode_locked(inode);
5867 if (ret < 0) {
5868 iput(inode);
5869 goto fail;
5872 path->leave_spinning = 1;
5873 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
5874 if (ret != 0)
5875 goto fail_unlock;
5877 inode_init_owner(inode, dir, mode);
5878 inode_set_bytes(inode, 0);
5880 inode->i_mtime = current_time(inode);
5881 inode->i_atime = inode->i_mtime;
5882 inode->i_ctime = inode->i_mtime;
5883 BTRFS_I(inode)->i_otime = inode->i_mtime;
5885 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
5886 struct btrfs_inode_item);
5887 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
5888 sizeof(*inode_item));
5889 fill_inode_item(trans, path->nodes[0], inode_item, inode);
5891 if (name) {
5892 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
5893 struct btrfs_inode_ref);
5894 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
5895 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
5896 ptr = (unsigned long)(ref + 1);
5897 write_extent_buffer(path->nodes[0], name, ptr, name_len);
5900 btrfs_mark_buffer_dirty(path->nodes[0]);
5901 btrfs_free_path(path);
5903 btrfs_inherit_iflags(inode, dir);
5905 if (S_ISREG(mode)) {
5906 if (btrfs_test_opt(fs_info, NODATASUM))
5907 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
5908 if (btrfs_test_opt(fs_info, NODATACOW))
5909 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
5910 BTRFS_INODE_NODATASUM;
5913 inode_tree_add(inode);
5915 trace_btrfs_inode_new(inode);
5916 btrfs_set_inode_last_trans(trans, inode);
5918 btrfs_update_root_times(trans, root);
5920 ret = btrfs_inode_inherit_props(trans, inode, dir);
5921 if (ret)
5922 btrfs_err(fs_info,
5923 "error inheriting props for ino %llu (root %llu): %d",
5924 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
5926 return inode;
5928 fail_unlock:
5929 discard_new_inode(inode);
5930 fail:
5931 if (dir && name)
5932 BTRFS_I(dir)->index_cnt--;
5933 btrfs_free_path(path);
5934 return ERR_PTR(ret);
5938 * utility function to add 'inode' into 'parent_inode' with
5939 * a give name and a given sequence number.
5940 * if 'add_backref' is true, also insert a backref from the
5941 * inode to the parent directory.
5943 int btrfs_add_link(struct btrfs_trans_handle *trans,
5944 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
5945 const char *name, int name_len, int add_backref, u64 index)
5947 int ret = 0;
5948 struct btrfs_key key;
5949 struct btrfs_root *root = parent_inode->root;
5950 u64 ino = btrfs_ino(inode);
5951 u64 parent_ino = btrfs_ino(parent_inode);
5953 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5954 memcpy(&key, &inode->root->root_key, sizeof(key));
5955 } else {
5956 key.objectid = ino;
5957 key.type = BTRFS_INODE_ITEM_KEY;
5958 key.offset = 0;
5961 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
5962 ret = btrfs_add_root_ref(trans, key.objectid,
5963 root->root_key.objectid, parent_ino,
5964 index, name, name_len);
5965 } else if (add_backref) {
5966 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
5967 parent_ino, index);
5970 /* Nothing to clean up yet */
5971 if (ret)
5972 return ret;
5974 ret = btrfs_insert_dir_item(trans, name, name_len, parent_inode, &key,
5975 btrfs_inode_type(&inode->vfs_inode), index);
5976 if (ret == -EEXIST || ret == -EOVERFLOW)
5977 goto fail_dir_item;
5978 else if (ret) {
5979 btrfs_abort_transaction(trans, ret);
5980 return ret;
5983 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
5984 name_len * 2);
5985 inode_inc_iversion(&parent_inode->vfs_inode);
5987 * If we are replaying a log tree, we do not want to update the mtime
5988 * and ctime of the parent directory with the current time, since the
5989 * log replay procedure is responsible for setting them to their correct
5990 * values (the ones it had when the fsync was done).
5992 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
5993 struct timespec64 now = current_time(&parent_inode->vfs_inode);
5995 parent_inode->vfs_inode.i_mtime = now;
5996 parent_inode->vfs_inode.i_ctime = now;
5998 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
5999 if (ret)
6000 btrfs_abort_transaction(trans, ret);
6001 return ret;
6003 fail_dir_item:
6004 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6005 u64 local_index;
6006 int err;
6007 err = btrfs_del_root_ref(trans, key.objectid,
6008 root->root_key.objectid, parent_ino,
6009 &local_index, name, name_len);
6010 if (err)
6011 btrfs_abort_transaction(trans, err);
6012 } else if (add_backref) {
6013 u64 local_index;
6014 int err;
6016 err = btrfs_del_inode_ref(trans, root, name, name_len,
6017 ino, parent_ino, &local_index);
6018 if (err)
6019 btrfs_abort_transaction(trans, err);
6022 /* Return the original error code */
6023 return ret;
6026 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6027 struct btrfs_inode *dir, struct dentry *dentry,
6028 struct btrfs_inode *inode, int backref, u64 index)
6030 int err = btrfs_add_link(trans, dir, inode,
6031 dentry->d_name.name, dentry->d_name.len,
6032 backref, index);
6033 if (err > 0)
6034 err = -EEXIST;
6035 return err;
6038 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6039 umode_t mode, dev_t rdev)
6041 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6042 struct btrfs_trans_handle *trans;
6043 struct btrfs_root *root = BTRFS_I(dir)->root;
6044 struct inode *inode = NULL;
6045 int err;
6046 u64 objectid;
6047 u64 index = 0;
6050 * 2 for inode item and ref
6051 * 2 for dir items
6052 * 1 for xattr if selinux is on
6054 trans = btrfs_start_transaction(root, 5);
6055 if (IS_ERR(trans))
6056 return PTR_ERR(trans);
6058 err = btrfs_find_free_ino(root, &objectid);
6059 if (err)
6060 goto out_unlock;
6062 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6063 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6064 mode, &index);
6065 if (IS_ERR(inode)) {
6066 err = PTR_ERR(inode);
6067 inode = NULL;
6068 goto out_unlock;
6072 * If the active LSM wants to access the inode during
6073 * d_instantiate it needs these. Smack checks to see
6074 * if the filesystem supports xattrs by looking at the
6075 * ops vector.
6077 inode->i_op = &btrfs_special_inode_operations;
6078 init_special_inode(inode, inode->i_mode, rdev);
6080 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6081 if (err)
6082 goto out_unlock;
6084 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6085 0, index);
6086 if (err)
6087 goto out_unlock;
6089 btrfs_update_inode(trans, root, inode);
6090 d_instantiate_new(dentry, inode);
6092 out_unlock:
6093 btrfs_end_transaction(trans);
6094 btrfs_btree_balance_dirty(fs_info);
6095 if (err && inode) {
6096 inode_dec_link_count(inode);
6097 discard_new_inode(inode);
6099 return err;
6102 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6103 umode_t mode, bool excl)
6105 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6106 struct btrfs_trans_handle *trans;
6107 struct btrfs_root *root = BTRFS_I(dir)->root;
6108 struct inode *inode = NULL;
6109 int err;
6110 u64 objectid;
6111 u64 index = 0;
6114 * 2 for inode item and ref
6115 * 2 for dir items
6116 * 1 for xattr if selinux is on
6118 trans = btrfs_start_transaction(root, 5);
6119 if (IS_ERR(trans))
6120 return PTR_ERR(trans);
6122 err = btrfs_find_free_ino(root, &objectid);
6123 if (err)
6124 goto out_unlock;
6126 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6127 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6128 mode, &index);
6129 if (IS_ERR(inode)) {
6130 err = PTR_ERR(inode);
6131 inode = NULL;
6132 goto out_unlock;
6135 * If the active LSM wants to access the inode during
6136 * d_instantiate it needs these. Smack checks to see
6137 * if the filesystem supports xattrs by looking at the
6138 * ops vector.
6140 inode->i_fop = &btrfs_file_operations;
6141 inode->i_op = &btrfs_file_inode_operations;
6142 inode->i_mapping->a_ops = &btrfs_aops;
6144 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6145 if (err)
6146 goto out_unlock;
6148 err = btrfs_update_inode(trans, root, inode);
6149 if (err)
6150 goto out_unlock;
6152 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6153 0, index);
6154 if (err)
6155 goto out_unlock;
6157 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6158 d_instantiate_new(dentry, inode);
6160 out_unlock:
6161 btrfs_end_transaction(trans);
6162 if (err && inode) {
6163 inode_dec_link_count(inode);
6164 discard_new_inode(inode);
6166 btrfs_btree_balance_dirty(fs_info);
6167 return err;
6170 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6171 struct dentry *dentry)
6173 struct btrfs_trans_handle *trans = NULL;
6174 struct btrfs_root *root = BTRFS_I(dir)->root;
6175 struct inode *inode = d_inode(old_dentry);
6176 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6177 u64 index;
6178 int err;
6179 int drop_inode = 0;
6181 /* do not allow sys_link's with other subvols of the same device */
6182 if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
6183 return -EXDEV;
6185 if (inode->i_nlink >= BTRFS_LINK_MAX)
6186 return -EMLINK;
6188 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6189 if (err)
6190 goto fail;
6193 * 2 items for inode and inode ref
6194 * 2 items for dir items
6195 * 1 item for parent inode
6196 * 1 item for orphan item deletion if O_TMPFILE
6198 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6199 if (IS_ERR(trans)) {
6200 err = PTR_ERR(trans);
6201 trans = NULL;
6202 goto fail;
6205 /* There are several dir indexes for this inode, clear the cache. */
6206 BTRFS_I(inode)->dir_index = 0ULL;
6207 inc_nlink(inode);
6208 inode_inc_iversion(inode);
6209 inode->i_ctime = current_time(inode);
6210 ihold(inode);
6211 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6213 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6214 1, index);
6216 if (err) {
6217 drop_inode = 1;
6218 } else {
6219 struct dentry *parent = dentry->d_parent;
6220 int ret;
6222 err = btrfs_update_inode(trans, root, inode);
6223 if (err)
6224 goto fail;
6225 if (inode->i_nlink == 1) {
6227 * If new hard link count is 1, it's a file created
6228 * with open(2) O_TMPFILE flag.
6230 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6231 if (err)
6232 goto fail;
6234 d_instantiate(dentry, inode);
6235 ret = btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent,
6236 true, NULL);
6237 if (ret == BTRFS_NEED_TRANS_COMMIT) {
6238 err = btrfs_commit_transaction(trans);
6239 trans = NULL;
6243 fail:
6244 if (trans)
6245 btrfs_end_transaction(trans);
6246 if (drop_inode) {
6247 inode_dec_link_count(inode);
6248 iput(inode);
6250 btrfs_btree_balance_dirty(fs_info);
6251 return err;
6254 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6256 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6257 struct inode *inode = NULL;
6258 struct btrfs_trans_handle *trans;
6259 struct btrfs_root *root = BTRFS_I(dir)->root;
6260 int err = 0;
6261 u64 objectid = 0;
6262 u64 index = 0;
6265 * 2 items for inode and ref
6266 * 2 items for dir items
6267 * 1 for xattr if selinux is on
6269 trans = btrfs_start_transaction(root, 5);
6270 if (IS_ERR(trans))
6271 return PTR_ERR(trans);
6273 err = btrfs_find_free_ino(root, &objectid);
6274 if (err)
6275 goto out_fail;
6277 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6278 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6279 S_IFDIR | mode, &index);
6280 if (IS_ERR(inode)) {
6281 err = PTR_ERR(inode);
6282 inode = NULL;
6283 goto out_fail;
6286 /* these must be set before we unlock the inode */
6287 inode->i_op = &btrfs_dir_inode_operations;
6288 inode->i_fop = &btrfs_dir_file_operations;
6290 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6291 if (err)
6292 goto out_fail;
6294 btrfs_i_size_write(BTRFS_I(inode), 0);
6295 err = btrfs_update_inode(trans, root, inode);
6296 if (err)
6297 goto out_fail;
6299 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6300 dentry->d_name.name,
6301 dentry->d_name.len, 0, index);
6302 if (err)
6303 goto out_fail;
6305 d_instantiate_new(dentry, inode);
6307 out_fail:
6308 btrfs_end_transaction(trans);
6309 if (err && inode) {
6310 inode_dec_link_count(inode);
6311 discard_new_inode(inode);
6313 btrfs_btree_balance_dirty(fs_info);
6314 return err;
6317 static noinline int uncompress_inline(struct btrfs_path *path,
6318 struct page *page,
6319 size_t pg_offset, u64 extent_offset,
6320 struct btrfs_file_extent_item *item)
6322 int ret;
6323 struct extent_buffer *leaf = path->nodes[0];
6324 char *tmp;
6325 size_t max_size;
6326 unsigned long inline_size;
6327 unsigned long ptr;
6328 int compress_type;
6330 WARN_ON(pg_offset != 0);
6331 compress_type = btrfs_file_extent_compression(leaf, item);
6332 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6333 inline_size = btrfs_file_extent_inline_item_len(leaf,
6334 btrfs_item_nr(path->slots[0]));
6335 tmp = kmalloc(inline_size, GFP_NOFS);
6336 if (!tmp)
6337 return -ENOMEM;
6338 ptr = btrfs_file_extent_inline_start(item);
6340 read_extent_buffer(leaf, tmp, ptr, inline_size);
6342 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6343 ret = btrfs_decompress(compress_type, tmp, page,
6344 extent_offset, inline_size, max_size);
6347 * decompression code contains a memset to fill in any space between the end
6348 * of the uncompressed data and the end of max_size in case the decompressed
6349 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6350 * the end of an inline extent and the beginning of the next block, so we
6351 * cover that region here.
6354 if (max_size + pg_offset < PAGE_SIZE) {
6355 char *map = kmap(page);
6356 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6357 kunmap(page);
6359 kfree(tmp);
6360 return ret;
6364 * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
6365 * @inode: file to search in
6366 * @page: page to read extent data into if the extent is inline
6367 * @pg_offset: offset into @page to copy to
6368 * @start: file offset
6369 * @len: length of range starting at @start
6371 * This returns the first &struct extent_map which overlaps with the given
6372 * range, reading it from the B-tree and caching it if necessary. Note that
6373 * there may be more extents which overlap the given range after the returned
6374 * extent_map.
6376 * If @page is not NULL and the extent is inline, this also reads the extent
6377 * data directly into the page and marks the extent up to date in the io_tree.
6379 * Return: ERR_PTR on error, non-NULL extent_map on success.
6381 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6382 struct page *page, size_t pg_offset,
6383 u64 start, u64 len)
6385 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6386 int ret;
6387 int err = 0;
6388 u64 extent_start = 0;
6389 u64 extent_end = 0;
6390 u64 objectid = btrfs_ino(inode);
6391 int extent_type = -1;
6392 struct btrfs_path *path = NULL;
6393 struct btrfs_root *root = inode->root;
6394 struct btrfs_file_extent_item *item;
6395 struct extent_buffer *leaf;
6396 struct btrfs_key found_key;
6397 struct extent_map *em = NULL;
6398 struct extent_map_tree *em_tree = &inode->extent_tree;
6399 struct extent_io_tree *io_tree = &inode->io_tree;
6401 read_lock(&em_tree->lock);
6402 em = lookup_extent_mapping(em_tree, start, len);
6403 read_unlock(&em_tree->lock);
6405 if (em) {
6406 if (em->start > start || em->start + em->len <= start)
6407 free_extent_map(em);
6408 else if (em->block_start == EXTENT_MAP_INLINE && page)
6409 free_extent_map(em);
6410 else
6411 goto out;
6413 em = alloc_extent_map();
6414 if (!em) {
6415 err = -ENOMEM;
6416 goto out;
6418 em->start = EXTENT_MAP_HOLE;
6419 em->orig_start = EXTENT_MAP_HOLE;
6420 em->len = (u64)-1;
6421 em->block_len = (u64)-1;
6423 path = btrfs_alloc_path();
6424 if (!path) {
6425 err = -ENOMEM;
6426 goto out;
6429 /* Chances are we'll be called again, so go ahead and do readahead */
6430 path->reada = READA_FORWARD;
6433 * Unless we're going to uncompress the inline extent, no sleep would
6434 * happen.
6436 path->leave_spinning = 1;
6438 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6439 if (ret < 0) {
6440 err = ret;
6441 goto out;
6442 } else if (ret > 0) {
6443 if (path->slots[0] == 0)
6444 goto not_found;
6445 path->slots[0]--;
6448 leaf = path->nodes[0];
6449 item = btrfs_item_ptr(leaf, path->slots[0],
6450 struct btrfs_file_extent_item);
6451 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6452 if (found_key.objectid != objectid ||
6453 found_key.type != BTRFS_EXTENT_DATA_KEY) {
6455 * If we backup past the first extent we want to move forward
6456 * and see if there is an extent in front of us, otherwise we'll
6457 * say there is a hole for our whole search range which can
6458 * cause problems.
6460 extent_end = start;
6461 goto next;
6464 extent_type = btrfs_file_extent_type(leaf, item);
6465 extent_start = found_key.offset;
6466 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6467 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6468 /* Only regular file could have regular/prealloc extent */
6469 if (!S_ISREG(inode->vfs_inode.i_mode)) {
6470 ret = -EUCLEAN;
6471 btrfs_crit(fs_info,
6472 "regular/prealloc extent found for non-regular inode %llu",
6473 btrfs_ino(inode));
6474 goto out;
6476 extent_end = extent_start +
6477 btrfs_file_extent_num_bytes(leaf, item);
6479 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6480 extent_start);
6481 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6482 size_t size;
6484 size = btrfs_file_extent_ram_bytes(leaf, item);
6485 extent_end = ALIGN(extent_start + size,
6486 fs_info->sectorsize);
6488 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6489 path->slots[0],
6490 extent_start);
6492 next:
6493 if (start >= extent_end) {
6494 path->slots[0]++;
6495 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6496 ret = btrfs_next_leaf(root, path);
6497 if (ret < 0) {
6498 err = ret;
6499 goto out;
6500 } else if (ret > 0) {
6501 goto not_found;
6503 leaf = path->nodes[0];
6505 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6506 if (found_key.objectid != objectid ||
6507 found_key.type != BTRFS_EXTENT_DATA_KEY)
6508 goto not_found;
6509 if (start + len <= found_key.offset)
6510 goto not_found;
6511 if (start > found_key.offset)
6512 goto next;
6514 /* New extent overlaps with existing one */
6515 em->start = start;
6516 em->orig_start = start;
6517 em->len = found_key.offset - start;
6518 em->block_start = EXTENT_MAP_HOLE;
6519 goto insert;
6522 btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
6524 if (extent_type == BTRFS_FILE_EXTENT_REG ||
6525 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
6526 goto insert;
6527 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
6528 unsigned long ptr;
6529 char *map;
6530 size_t size;
6531 size_t extent_offset;
6532 size_t copy_size;
6534 if (!page)
6535 goto out;
6537 size = btrfs_file_extent_ram_bytes(leaf, item);
6538 extent_offset = page_offset(page) + pg_offset - extent_start;
6539 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6540 size - extent_offset);
6541 em->start = extent_start + extent_offset;
6542 em->len = ALIGN(copy_size, fs_info->sectorsize);
6543 em->orig_block_len = em->len;
6544 em->orig_start = em->start;
6545 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6547 btrfs_set_path_blocking(path);
6548 if (!PageUptodate(page)) {
6549 if (btrfs_file_extent_compression(leaf, item) !=
6550 BTRFS_COMPRESS_NONE) {
6551 ret = uncompress_inline(path, page, pg_offset,
6552 extent_offset, item);
6553 if (ret) {
6554 err = ret;
6555 goto out;
6557 } else {
6558 map = kmap(page);
6559 read_extent_buffer(leaf, map + pg_offset, ptr,
6560 copy_size);
6561 if (pg_offset + copy_size < PAGE_SIZE) {
6562 memset(map + pg_offset + copy_size, 0,
6563 PAGE_SIZE - pg_offset -
6564 copy_size);
6566 kunmap(page);
6568 flush_dcache_page(page);
6570 set_extent_uptodate(io_tree, em->start,
6571 extent_map_end(em) - 1, NULL, GFP_NOFS);
6572 goto insert;
6574 not_found:
6575 em->start = start;
6576 em->orig_start = start;
6577 em->len = len;
6578 em->block_start = EXTENT_MAP_HOLE;
6579 insert:
6580 btrfs_release_path(path);
6581 if (em->start > start || extent_map_end(em) <= start) {
6582 btrfs_err(fs_info,
6583 "bad extent! em: [%llu %llu] passed [%llu %llu]",
6584 em->start, em->len, start, len);
6585 err = -EIO;
6586 goto out;
6589 err = 0;
6590 write_lock(&em_tree->lock);
6591 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
6592 write_unlock(&em_tree->lock);
6593 out:
6594 btrfs_free_path(path);
6596 trace_btrfs_get_extent(root, inode, em);
6598 if (err) {
6599 free_extent_map(em);
6600 return ERR_PTR(err);
6602 BUG_ON(!em); /* Error is always set */
6603 return em;
6606 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
6607 u64 start, u64 len)
6609 struct extent_map *em;
6610 struct extent_map *hole_em = NULL;
6611 u64 delalloc_start = start;
6612 u64 end;
6613 u64 delalloc_len;
6614 u64 delalloc_end;
6615 int err = 0;
6617 em = btrfs_get_extent(inode, NULL, 0, start, len);
6618 if (IS_ERR(em))
6619 return em;
6621 * If our em maps to:
6622 * - a hole or
6623 * - a pre-alloc extent,
6624 * there might actually be delalloc bytes behind it.
6626 if (em->block_start != EXTENT_MAP_HOLE &&
6627 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
6628 return em;
6629 else
6630 hole_em = em;
6632 /* check to see if we've wrapped (len == -1 or similar) */
6633 end = start + len;
6634 if (end < start)
6635 end = (u64)-1;
6636 else
6637 end -= 1;
6639 em = NULL;
6641 /* ok, we didn't find anything, lets look for delalloc */
6642 delalloc_len = count_range_bits(&inode->io_tree, &delalloc_start,
6643 end, len, EXTENT_DELALLOC, 1);
6644 delalloc_end = delalloc_start + delalloc_len;
6645 if (delalloc_end < delalloc_start)
6646 delalloc_end = (u64)-1;
6649 * We didn't find anything useful, return the original results from
6650 * get_extent()
6652 if (delalloc_start > end || delalloc_end <= start) {
6653 em = hole_em;
6654 hole_em = NULL;
6655 goto out;
6659 * Adjust the delalloc_start to make sure it doesn't go backwards from
6660 * the start they passed in
6662 delalloc_start = max(start, delalloc_start);
6663 delalloc_len = delalloc_end - delalloc_start;
6665 if (delalloc_len > 0) {
6666 u64 hole_start;
6667 u64 hole_len;
6668 const u64 hole_end = extent_map_end(hole_em);
6670 em = alloc_extent_map();
6671 if (!em) {
6672 err = -ENOMEM;
6673 goto out;
6676 ASSERT(hole_em);
6678 * When btrfs_get_extent can't find anything it returns one
6679 * huge hole
6681 * Make sure what it found really fits our range, and adjust to
6682 * make sure it is based on the start from the caller
6684 if (hole_end <= start || hole_em->start > end) {
6685 free_extent_map(hole_em);
6686 hole_em = NULL;
6687 } else {
6688 hole_start = max(hole_em->start, start);
6689 hole_len = hole_end - hole_start;
6692 if (hole_em && delalloc_start > hole_start) {
6694 * Our hole starts before our delalloc, so we have to
6695 * return just the parts of the hole that go until the
6696 * delalloc starts
6698 em->len = min(hole_len, delalloc_start - hole_start);
6699 em->start = hole_start;
6700 em->orig_start = hole_start;
6702 * Don't adjust block start at all, it is fixed at
6703 * EXTENT_MAP_HOLE
6705 em->block_start = hole_em->block_start;
6706 em->block_len = hole_len;
6707 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
6708 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
6709 } else {
6711 * Hole is out of passed range or it starts after
6712 * delalloc range
6714 em->start = delalloc_start;
6715 em->len = delalloc_len;
6716 em->orig_start = delalloc_start;
6717 em->block_start = EXTENT_MAP_DELALLOC;
6718 em->block_len = delalloc_len;
6720 } else {
6721 return hole_em;
6723 out:
6725 free_extent_map(hole_em);
6726 if (err) {
6727 free_extent_map(em);
6728 return ERR_PTR(err);
6730 return em;
6733 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
6734 const u64 start,
6735 const u64 len,
6736 const u64 orig_start,
6737 const u64 block_start,
6738 const u64 block_len,
6739 const u64 orig_block_len,
6740 const u64 ram_bytes,
6741 const int type)
6743 struct extent_map *em = NULL;
6744 int ret;
6746 if (type != BTRFS_ORDERED_NOCOW) {
6747 em = create_io_em(inode, start, len, orig_start,
6748 block_start, block_len, orig_block_len,
6749 ram_bytes,
6750 BTRFS_COMPRESS_NONE, /* compress_type */
6751 type);
6752 if (IS_ERR(em))
6753 goto out;
6755 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
6756 len, block_len, type);
6757 if (ret) {
6758 if (em) {
6759 free_extent_map(em);
6760 btrfs_drop_extent_cache(BTRFS_I(inode), start,
6761 start + len - 1, 0);
6763 em = ERR_PTR(ret);
6765 out:
6767 return em;
6770 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
6771 u64 start, u64 len)
6773 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6774 struct btrfs_root *root = BTRFS_I(inode)->root;
6775 struct extent_map *em;
6776 struct btrfs_key ins;
6777 u64 alloc_hint;
6778 int ret;
6780 alloc_hint = get_extent_allocation_hint(inode, start, len);
6781 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
6782 0, alloc_hint, &ins, 1, 1);
6783 if (ret)
6784 return ERR_PTR(ret);
6786 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
6787 ins.objectid, ins.offset, ins.offset,
6788 ins.offset, BTRFS_ORDERED_REGULAR);
6789 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
6790 if (IS_ERR(em))
6791 btrfs_free_reserved_extent(fs_info, ins.objectid,
6792 ins.offset, 1);
6794 return em;
6798 * returns 1 when the nocow is safe, < 1 on error, 0 if the
6799 * block must be cow'd
6801 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
6802 u64 *orig_start, u64 *orig_block_len,
6803 u64 *ram_bytes)
6805 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6806 struct btrfs_path *path;
6807 int ret;
6808 struct extent_buffer *leaf;
6809 struct btrfs_root *root = BTRFS_I(inode)->root;
6810 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6811 struct btrfs_file_extent_item *fi;
6812 struct btrfs_key key;
6813 u64 disk_bytenr;
6814 u64 backref_offset;
6815 u64 extent_end;
6816 u64 num_bytes;
6817 int slot;
6818 int found_type;
6819 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
6821 path = btrfs_alloc_path();
6822 if (!path)
6823 return -ENOMEM;
6825 ret = btrfs_lookup_file_extent(NULL, root, path,
6826 btrfs_ino(BTRFS_I(inode)), offset, 0);
6827 if (ret < 0)
6828 goto out;
6830 slot = path->slots[0];
6831 if (ret == 1) {
6832 if (slot == 0) {
6833 /* can't find the item, must cow */
6834 ret = 0;
6835 goto out;
6837 slot--;
6839 ret = 0;
6840 leaf = path->nodes[0];
6841 btrfs_item_key_to_cpu(leaf, &key, slot);
6842 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
6843 key.type != BTRFS_EXTENT_DATA_KEY) {
6844 /* not our file or wrong item type, must cow */
6845 goto out;
6848 if (key.offset > offset) {
6849 /* Wrong offset, must cow */
6850 goto out;
6853 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
6854 found_type = btrfs_file_extent_type(leaf, fi);
6855 if (found_type != BTRFS_FILE_EXTENT_REG &&
6856 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
6857 /* not a regular extent, must cow */
6858 goto out;
6861 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
6862 goto out;
6864 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
6865 if (extent_end <= offset)
6866 goto out;
6868 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6869 if (disk_bytenr == 0)
6870 goto out;
6872 if (btrfs_file_extent_compression(leaf, fi) ||
6873 btrfs_file_extent_encryption(leaf, fi) ||
6874 btrfs_file_extent_other_encoding(leaf, fi))
6875 goto out;
6878 * Do the same check as in btrfs_cross_ref_exist but without the
6879 * unnecessary search.
6881 if (btrfs_file_extent_generation(leaf, fi) <=
6882 btrfs_root_last_snapshot(&root->root_item))
6883 goto out;
6885 backref_offset = btrfs_file_extent_offset(leaf, fi);
6887 if (orig_start) {
6888 *orig_start = key.offset - backref_offset;
6889 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
6890 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6893 if (btrfs_extent_readonly(fs_info, disk_bytenr))
6894 goto out;
6896 num_bytes = min(offset + *len, extent_end) - offset;
6897 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6898 u64 range_end;
6900 range_end = round_up(offset + num_bytes,
6901 root->fs_info->sectorsize) - 1;
6902 ret = test_range_bit(io_tree, offset, range_end,
6903 EXTENT_DELALLOC, 0, NULL);
6904 if (ret) {
6905 ret = -EAGAIN;
6906 goto out;
6910 btrfs_release_path(path);
6913 * look for other files referencing this extent, if we
6914 * find any we must cow
6917 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
6918 key.offset - backref_offset, disk_bytenr);
6919 if (ret) {
6920 ret = 0;
6921 goto out;
6925 * adjust disk_bytenr and num_bytes to cover just the bytes
6926 * in this extent we are about to write. If there
6927 * are any csums in that range we have to cow in order
6928 * to keep the csums correct
6930 disk_bytenr += backref_offset;
6931 disk_bytenr += offset - key.offset;
6932 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
6933 goto out;
6935 * all of the above have passed, it is safe to overwrite this extent
6936 * without cow
6938 *len = num_bytes;
6939 ret = 1;
6940 out:
6941 btrfs_free_path(path);
6942 return ret;
6945 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
6946 struct extent_state **cached_state, int writing)
6948 struct btrfs_ordered_extent *ordered;
6949 int ret = 0;
6951 while (1) {
6952 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6953 cached_state);
6955 * We're concerned with the entire range that we're going to be
6956 * doing DIO to, so we need to make sure there's no ordered
6957 * extents in this range.
6959 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
6960 lockend - lockstart + 1);
6963 * We need to make sure there are no buffered pages in this
6964 * range either, we could have raced between the invalidate in
6965 * generic_file_direct_write and locking the extent. The
6966 * invalidate needs to happen so that reads after a write do not
6967 * get stale data.
6969 if (!ordered &&
6970 (!writing || !filemap_range_has_page(inode->i_mapping,
6971 lockstart, lockend)))
6972 break;
6974 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
6975 cached_state);
6977 if (ordered) {
6979 * If we are doing a DIO read and the ordered extent we
6980 * found is for a buffered write, we can not wait for it
6981 * to complete and retry, because if we do so we can
6982 * deadlock with concurrent buffered writes on page
6983 * locks. This happens only if our DIO read covers more
6984 * than one extent map, if at this point has already
6985 * created an ordered extent for a previous extent map
6986 * and locked its range in the inode's io tree, and a
6987 * concurrent write against that previous extent map's
6988 * range and this range started (we unlock the ranges
6989 * in the io tree only when the bios complete and
6990 * buffered writes always lock pages before attempting
6991 * to lock range in the io tree).
6993 if (writing ||
6994 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
6995 btrfs_start_ordered_extent(inode, ordered, 1);
6996 else
6997 ret = -ENOTBLK;
6998 btrfs_put_ordered_extent(ordered);
6999 } else {
7001 * We could trigger writeback for this range (and wait
7002 * for it to complete) and then invalidate the pages for
7003 * this range (through invalidate_inode_pages2_range()),
7004 * but that can lead us to a deadlock with a concurrent
7005 * call to readpages() (a buffered read or a defrag call
7006 * triggered a readahead) on a page lock due to an
7007 * ordered dio extent we created before but did not have
7008 * yet a corresponding bio submitted (whence it can not
7009 * complete), which makes readpages() wait for that
7010 * ordered extent to complete while holding a lock on
7011 * that page.
7013 ret = -ENOTBLK;
7016 if (ret)
7017 break;
7019 cond_resched();
7022 return ret;
7025 /* The callers of this must take lock_extent() */
7026 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7027 u64 orig_start, u64 block_start,
7028 u64 block_len, u64 orig_block_len,
7029 u64 ram_bytes, int compress_type,
7030 int type)
7032 struct extent_map_tree *em_tree;
7033 struct extent_map *em;
7034 int ret;
7036 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7037 type == BTRFS_ORDERED_COMPRESSED ||
7038 type == BTRFS_ORDERED_NOCOW ||
7039 type == BTRFS_ORDERED_REGULAR);
7041 em_tree = &BTRFS_I(inode)->extent_tree;
7042 em = alloc_extent_map();
7043 if (!em)
7044 return ERR_PTR(-ENOMEM);
7046 em->start = start;
7047 em->orig_start = orig_start;
7048 em->len = len;
7049 em->block_len = block_len;
7050 em->block_start = block_start;
7051 em->orig_block_len = orig_block_len;
7052 em->ram_bytes = ram_bytes;
7053 em->generation = -1;
7054 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7055 if (type == BTRFS_ORDERED_PREALLOC) {
7056 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7057 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7058 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7059 em->compress_type = compress_type;
7062 do {
7063 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7064 em->start + em->len - 1, 0);
7065 write_lock(&em_tree->lock);
7066 ret = add_extent_mapping(em_tree, em, 1);
7067 write_unlock(&em_tree->lock);
7069 * The caller has taken lock_extent(), who could race with us
7070 * to add em?
7072 } while (ret == -EEXIST);
7074 if (ret) {
7075 free_extent_map(em);
7076 return ERR_PTR(ret);
7079 /* em got 2 refs now, callers needs to do free_extent_map once. */
7080 return em;
7084 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7085 struct buffer_head *bh_result,
7086 struct inode *inode,
7087 u64 start, u64 len)
7089 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7091 if (em->block_start == EXTENT_MAP_HOLE ||
7092 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7093 return -ENOENT;
7095 len = min(len, em->len - (start - em->start));
7097 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7098 inode->i_blkbits;
7099 bh_result->b_size = len;
7100 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7101 set_buffer_mapped(bh_result);
7103 return 0;
7106 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7107 struct buffer_head *bh_result,
7108 struct inode *inode,
7109 struct btrfs_dio_data *dio_data,
7110 u64 start, u64 len)
7112 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7113 struct extent_map *em = *map;
7114 int ret = 0;
7117 * We don't allocate a new extent in the following cases
7119 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7120 * existing extent.
7121 * 2) The extent is marked as PREALLOC. We're good to go here and can
7122 * just use the extent.
7125 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7126 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7127 em->block_start != EXTENT_MAP_HOLE)) {
7128 int type;
7129 u64 block_start, orig_start, orig_block_len, ram_bytes;
7131 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7132 type = BTRFS_ORDERED_PREALLOC;
7133 else
7134 type = BTRFS_ORDERED_NOCOW;
7135 len = min(len, em->len - (start - em->start));
7136 block_start = em->block_start + (start - em->start);
7138 if (can_nocow_extent(inode, start, &len, &orig_start,
7139 &orig_block_len, &ram_bytes) == 1 &&
7140 btrfs_inc_nocow_writers(fs_info, block_start)) {
7141 struct extent_map *em2;
7143 em2 = btrfs_create_dio_extent(inode, start, len,
7144 orig_start, block_start,
7145 len, orig_block_len,
7146 ram_bytes, type);
7147 btrfs_dec_nocow_writers(fs_info, block_start);
7148 if (type == BTRFS_ORDERED_PREALLOC) {
7149 free_extent_map(em);
7150 *map = em = em2;
7153 if (em2 && IS_ERR(em2)) {
7154 ret = PTR_ERR(em2);
7155 goto out;
7158 * For inode marked NODATACOW or extent marked PREALLOC,
7159 * use the existing or preallocated extent, so does not
7160 * need to adjust btrfs_space_info's bytes_may_use.
7162 btrfs_free_reserved_data_space_noquota(inode, start,
7163 len);
7164 goto skip_cow;
7168 /* this will cow the extent */
7169 len = bh_result->b_size;
7170 free_extent_map(em);
7171 *map = em = btrfs_new_extent_direct(inode, start, len);
7172 if (IS_ERR(em)) {
7173 ret = PTR_ERR(em);
7174 goto out;
7177 len = min(len, em->len - (start - em->start));
7179 skip_cow:
7180 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7181 inode->i_blkbits;
7182 bh_result->b_size = len;
7183 bh_result->b_bdev = fs_info->fs_devices->latest_bdev;
7184 set_buffer_mapped(bh_result);
7186 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7187 set_buffer_new(bh_result);
7190 * Need to update the i_size under the extent lock so buffered
7191 * readers will get the updated i_size when we unlock.
7193 if (!dio_data->overwrite && start + len > i_size_read(inode))
7194 i_size_write(inode, start + len);
7196 WARN_ON(dio_data->reserve < len);
7197 dio_data->reserve -= len;
7198 dio_data->unsubmitted_oe_range_end = start + len;
7199 current->journal_info = dio_data;
7200 out:
7201 return ret;
7204 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7205 struct buffer_head *bh_result, int create)
7207 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7208 struct extent_map *em;
7209 struct extent_state *cached_state = NULL;
7210 struct btrfs_dio_data *dio_data = NULL;
7211 u64 start = iblock << inode->i_blkbits;
7212 u64 lockstart, lockend;
7213 u64 len = bh_result->b_size;
7214 int ret = 0;
7216 if (!create)
7217 len = min_t(u64, len, fs_info->sectorsize);
7219 lockstart = start;
7220 lockend = start + len - 1;
7222 if (current->journal_info) {
7224 * Need to pull our outstanding extents and set journal_info to NULL so
7225 * that anything that needs to check if there's a transaction doesn't get
7226 * confused.
7228 dio_data = current->journal_info;
7229 current->journal_info = NULL;
7233 * If this errors out it's because we couldn't invalidate pagecache for
7234 * this range and we need to fallback to buffered.
7236 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7237 create)) {
7238 ret = -ENOTBLK;
7239 goto err;
7242 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
7243 if (IS_ERR(em)) {
7244 ret = PTR_ERR(em);
7245 goto unlock_err;
7249 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7250 * io. INLINE is special, and we could probably kludge it in here, but
7251 * it's still buffered so for safety lets just fall back to the generic
7252 * buffered path.
7254 * For COMPRESSED we _have_ to read the entire extent in so we can
7255 * decompress it, so there will be buffering required no matter what we
7256 * do, so go ahead and fallback to buffered.
7258 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7259 * to buffered IO. Don't blame me, this is the price we pay for using
7260 * the generic code.
7262 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7263 em->block_start == EXTENT_MAP_INLINE) {
7264 free_extent_map(em);
7265 ret = -ENOTBLK;
7266 goto unlock_err;
7269 if (create) {
7270 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7271 dio_data, start, len);
7272 if (ret < 0)
7273 goto unlock_err;
7275 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
7276 lockend, &cached_state);
7277 } else {
7278 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7279 start, len);
7280 /* Can be negative only if we read from a hole */
7281 if (ret < 0) {
7282 ret = 0;
7283 free_extent_map(em);
7284 goto unlock_err;
7287 * We need to unlock only the end area that we aren't using.
7288 * The rest is going to be unlocked by the endio routine.
7290 lockstart = start + bh_result->b_size;
7291 if (lockstart < lockend) {
7292 unlock_extent_cached(&BTRFS_I(inode)->io_tree,
7293 lockstart, lockend, &cached_state);
7294 } else {
7295 free_extent_state(cached_state);
7299 free_extent_map(em);
7301 return 0;
7303 unlock_err:
7304 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7305 &cached_state);
7306 err:
7307 if (dio_data)
7308 current->journal_info = dio_data;
7309 return ret;
7312 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7313 struct bio *bio,
7314 int mirror_num)
7316 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7317 blk_status_t ret;
7319 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7321 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7322 if (ret)
7323 return ret;
7325 ret = btrfs_map_bio(fs_info, bio, mirror_num);
7327 return ret;
7330 static int btrfs_check_dio_repairable(struct inode *inode,
7331 struct bio *failed_bio,
7332 struct io_failure_record *failrec,
7333 int failed_mirror)
7335 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7336 int num_copies;
7338 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7339 if (num_copies == 1) {
7341 * we only have a single copy of the data, so don't bother with
7342 * all the retry and error correction code that follows. no
7343 * matter what the error is, it is very likely to persist.
7345 btrfs_debug(fs_info,
7346 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7347 num_copies, failrec->this_mirror, failed_mirror);
7348 return 0;
7351 failrec->failed_mirror = failed_mirror;
7352 failrec->this_mirror++;
7353 if (failrec->this_mirror == failed_mirror)
7354 failrec->this_mirror++;
7356 if (failrec->this_mirror > num_copies) {
7357 btrfs_debug(fs_info,
7358 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7359 num_copies, failrec->this_mirror, failed_mirror);
7360 return 0;
7363 return 1;
7366 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7367 struct page *page, unsigned int pgoff,
7368 u64 start, u64 end, int failed_mirror,
7369 bio_end_io_t *repair_endio, void *repair_arg)
7371 struct io_failure_record *failrec;
7372 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7373 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7374 struct bio *bio;
7375 int isector;
7376 unsigned int read_mode = 0;
7377 int segs;
7378 int ret;
7379 blk_status_t status;
7380 struct bio_vec bvec;
7382 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7384 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7385 if (ret)
7386 return errno_to_blk_status(ret);
7388 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7389 failed_mirror);
7390 if (!ret) {
7391 free_io_failure(failure_tree, io_tree, failrec);
7392 return BLK_STS_IOERR;
7395 segs = bio_segments(failed_bio);
7396 bio_get_first_bvec(failed_bio, &bvec);
7397 if (segs > 1 ||
7398 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7399 read_mode |= REQ_FAILFAST_DEV;
7401 isector = start - btrfs_io_bio(failed_bio)->logical;
7402 isector >>= inode->i_sb->s_blocksize_bits;
7403 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7404 pgoff, isector, repair_endio, repair_arg);
7405 bio->bi_opf = REQ_OP_READ | read_mode;
7407 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7408 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7409 read_mode, failrec->this_mirror, failrec->in_validation);
7411 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7412 if (status) {
7413 free_io_failure(failure_tree, io_tree, failrec);
7414 bio_put(bio);
7417 return status;
7420 struct btrfs_retry_complete {
7421 struct completion done;
7422 struct inode *inode;
7423 u64 start;
7424 int uptodate;
7427 static void btrfs_retry_endio_nocsum(struct bio *bio)
7429 struct btrfs_retry_complete *done = bio->bi_private;
7430 struct inode *inode = done->inode;
7431 struct bio_vec *bvec;
7432 struct extent_io_tree *io_tree, *failure_tree;
7433 struct bvec_iter_all iter_all;
7435 if (bio->bi_status)
7436 goto end;
7438 ASSERT(bio->bi_vcnt == 1);
7439 io_tree = &BTRFS_I(inode)->io_tree;
7440 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7441 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7443 done->uptodate = 1;
7444 ASSERT(!bio_flagged(bio, BIO_CLONED));
7445 bio_for_each_segment_all(bvec, bio, iter_all)
7446 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7447 io_tree, done->start, bvec->bv_page,
7448 btrfs_ino(BTRFS_I(inode)), 0);
7449 end:
7450 complete(&done->done);
7451 bio_put(bio);
7454 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7455 struct btrfs_io_bio *io_bio)
7457 struct btrfs_fs_info *fs_info;
7458 struct bio_vec bvec;
7459 struct bvec_iter iter;
7460 struct btrfs_retry_complete done;
7461 u64 start;
7462 unsigned int pgoff;
7463 u32 sectorsize;
7464 int nr_sectors;
7465 blk_status_t ret;
7466 blk_status_t err = BLK_STS_OK;
7468 fs_info = BTRFS_I(inode)->root->fs_info;
7469 sectorsize = fs_info->sectorsize;
7471 start = io_bio->logical;
7472 done.inode = inode;
7473 io_bio->bio.bi_iter = io_bio->iter;
7475 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7476 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7477 pgoff = bvec.bv_offset;
7479 next_block_or_try_again:
7480 done.uptodate = 0;
7481 done.start = start;
7482 init_completion(&done.done);
7484 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7485 pgoff, start, start + sectorsize - 1,
7486 io_bio->mirror_num,
7487 btrfs_retry_endio_nocsum, &done);
7488 if (ret) {
7489 err = ret;
7490 goto next;
7493 wait_for_completion_io(&done.done);
7495 if (!done.uptodate) {
7496 /* We might have another mirror, so try again */
7497 goto next_block_or_try_again;
7500 next:
7501 start += sectorsize;
7503 nr_sectors--;
7504 if (nr_sectors) {
7505 pgoff += sectorsize;
7506 ASSERT(pgoff < PAGE_SIZE);
7507 goto next_block_or_try_again;
7511 return err;
7514 static void btrfs_retry_endio(struct bio *bio)
7516 struct btrfs_retry_complete *done = bio->bi_private;
7517 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7518 struct extent_io_tree *io_tree, *failure_tree;
7519 struct inode *inode = done->inode;
7520 struct bio_vec *bvec;
7521 int uptodate;
7522 int ret;
7523 int i = 0;
7524 struct bvec_iter_all iter_all;
7526 if (bio->bi_status)
7527 goto end;
7529 uptodate = 1;
7531 ASSERT(bio->bi_vcnt == 1);
7532 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7534 io_tree = &BTRFS_I(inode)->io_tree;
7535 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7537 ASSERT(!bio_flagged(bio, BIO_CLONED));
7538 bio_for_each_segment_all(bvec, bio, iter_all) {
7539 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7540 bvec->bv_offset, done->start,
7541 bvec->bv_len);
7542 if (!ret)
7543 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7544 failure_tree, io_tree, done->start,
7545 bvec->bv_page,
7546 btrfs_ino(BTRFS_I(inode)),
7547 bvec->bv_offset);
7548 else
7549 uptodate = 0;
7550 i++;
7553 done->uptodate = uptodate;
7554 end:
7555 complete(&done->done);
7556 bio_put(bio);
7559 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7560 struct btrfs_io_bio *io_bio, blk_status_t err)
7562 struct btrfs_fs_info *fs_info;
7563 struct bio_vec bvec;
7564 struct bvec_iter iter;
7565 struct btrfs_retry_complete done;
7566 u64 start;
7567 u64 offset = 0;
7568 u32 sectorsize;
7569 int nr_sectors;
7570 unsigned int pgoff;
7571 int csum_pos;
7572 bool uptodate = (err == 0);
7573 int ret;
7574 blk_status_t status;
7576 fs_info = BTRFS_I(inode)->root->fs_info;
7577 sectorsize = fs_info->sectorsize;
7579 err = BLK_STS_OK;
7580 start = io_bio->logical;
7581 done.inode = inode;
7582 io_bio->bio.bi_iter = io_bio->iter;
7584 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7585 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7587 pgoff = bvec.bv_offset;
7588 next_block:
7589 if (uptodate) {
7590 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
7591 ret = __readpage_endio_check(inode, io_bio, csum_pos,
7592 bvec.bv_page, pgoff, start, sectorsize);
7593 if (likely(!ret))
7594 goto next;
7596 try_again:
7597 done.uptodate = 0;
7598 done.start = start;
7599 init_completion(&done.done);
7601 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7602 pgoff, start, start + sectorsize - 1,
7603 io_bio->mirror_num, btrfs_retry_endio,
7604 &done);
7605 if (status) {
7606 err = status;
7607 goto next;
7610 wait_for_completion_io(&done.done);
7612 if (!done.uptodate) {
7613 /* We might have another mirror, so try again */
7614 goto try_again;
7616 next:
7617 offset += sectorsize;
7618 start += sectorsize;
7620 ASSERT(nr_sectors);
7622 nr_sectors--;
7623 if (nr_sectors) {
7624 pgoff += sectorsize;
7625 ASSERT(pgoff < PAGE_SIZE);
7626 goto next_block;
7630 return err;
7633 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
7634 struct btrfs_io_bio *io_bio, blk_status_t err)
7636 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
7638 if (skip_csum) {
7639 if (unlikely(err))
7640 return __btrfs_correct_data_nocsum(inode, io_bio);
7641 else
7642 return BLK_STS_OK;
7643 } else {
7644 return __btrfs_subio_endio_read(inode, io_bio, err);
7648 static void btrfs_endio_direct_read(struct bio *bio)
7650 struct btrfs_dio_private *dip = bio->bi_private;
7651 struct inode *inode = dip->inode;
7652 struct bio *dio_bio;
7653 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7654 blk_status_t err = bio->bi_status;
7656 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
7657 err = btrfs_subio_endio_read(inode, io_bio, err);
7659 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
7660 dip->logical_offset + dip->bytes - 1);
7661 dio_bio = dip->dio_bio;
7663 kfree(dip);
7665 dio_bio->bi_status = err;
7666 dio_end_io(dio_bio);
7667 btrfs_io_bio_free_csum(io_bio);
7668 bio_put(bio);
7671 static void __endio_write_update_ordered(struct inode *inode,
7672 const u64 offset, const u64 bytes,
7673 const bool uptodate)
7675 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7676 struct btrfs_ordered_extent *ordered = NULL;
7677 struct btrfs_workqueue *wq;
7678 u64 ordered_offset = offset;
7679 u64 ordered_bytes = bytes;
7680 u64 last_offset;
7682 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
7683 wq = fs_info->endio_freespace_worker;
7684 else
7685 wq = fs_info->endio_write_workers;
7687 while (ordered_offset < offset + bytes) {
7688 last_offset = ordered_offset;
7689 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
7690 &ordered_offset,
7691 ordered_bytes,
7692 uptodate)) {
7693 btrfs_init_work(&ordered->work, finish_ordered_fn, NULL,
7694 NULL);
7695 btrfs_queue_work(wq, &ordered->work);
7698 * If btrfs_dec_test_ordered_pending does not find any ordered
7699 * extent in the range, we can exit.
7701 if (ordered_offset == last_offset)
7702 return;
7704 * Our bio might span multiple ordered extents. In this case
7705 * we keep going until we have accounted the whole dio.
7707 if (ordered_offset < offset + bytes) {
7708 ordered_bytes = offset + bytes - ordered_offset;
7709 ordered = NULL;
7714 static void btrfs_endio_direct_write(struct bio *bio)
7716 struct btrfs_dio_private *dip = bio->bi_private;
7717 struct bio *dio_bio = dip->dio_bio;
7719 __endio_write_update_ordered(dip->inode, dip->logical_offset,
7720 dip->bytes, !bio->bi_status);
7722 kfree(dip);
7724 dio_bio->bi_status = bio->bi_status;
7725 dio_end_io(dio_bio);
7726 bio_put(bio);
7729 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
7730 struct bio *bio, u64 offset)
7732 struct inode *inode = private_data;
7733 blk_status_t ret;
7734 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
7735 BUG_ON(ret); /* -ENOMEM */
7736 return 0;
7739 static void btrfs_end_dio_bio(struct bio *bio)
7741 struct btrfs_dio_private *dip = bio->bi_private;
7742 blk_status_t err = bio->bi_status;
7744 if (err)
7745 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
7746 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
7747 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
7748 bio->bi_opf,
7749 (unsigned long long)bio->bi_iter.bi_sector,
7750 bio->bi_iter.bi_size, err);
7752 if (dip->subio_endio)
7753 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
7755 if (err) {
7757 * We want to perceive the errors flag being set before
7758 * decrementing the reference count. We don't need a barrier
7759 * since atomic operations with a return value are fully
7760 * ordered as per atomic_t.txt
7762 dip->errors = 1;
7765 /* if there are more bios still pending for this dio, just exit */
7766 if (!atomic_dec_and_test(&dip->pending_bios))
7767 goto out;
7769 if (dip->errors) {
7770 bio_io_error(dip->orig_bio);
7771 } else {
7772 dip->dio_bio->bi_status = BLK_STS_OK;
7773 bio_endio(dip->orig_bio);
7775 out:
7776 bio_put(bio);
7779 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
7780 struct btrfs_dio_private *dip,
7781 struct bio *bio,
7782 u64 file_offset)
7784 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7785 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
7786 u16 csum_size;
7787 blk_status_t ret;
7790 * We load all the csum data we need when we submit
7791 * the first bio to reduce the csum tree search and
7792 * contention.
7794 if (dip->logical_offset == file_offset) {
7795 ret = btrfs_lookup_bio_sums(inode, dip->orig_bio, file_offset,
7796 NULL);
7797 if (ret)
7798 return ret;
7801 if (bio == dip->orig_bio)
7802 return 0;
7804 file_offset -= dip->logical_offset;
7805 file_offset >>= inode->i_sb->s_blocksize_bits;
7806 csum_size = btrfs_super_csum_size(btrfs_sb(inode->i_sb)->super_copy);
7807 io_bio->csum = orig_io_bio->csum + csum_size * file_offset;
7809 return 0;
7812 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
7813 struct inode *inode, u64 file_offset, int async_submit)
7815 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7816 struct btrfs_dio_private *dip = bio->bi_private;
7817 bool write = bio_op(bio) == REQ_OP_WRITE;
7818 blk_status_t ret;
7820 /* Check btrfs_submit_bio_hook() for rules about async submit. */
7821 if (async_submit)
7822 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
7824 if (!write) {
7825 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
7826 if (ret)
7827 goto err;
7830 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
7831 goto map;
7833 if (write && async_submit) {
7834 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
7835 file_offset, inode,
7836 btrfs_submit_bio_start_direct_io);
7837 goto err;
7838 } else if (write) {
7840 * If we aren't doing async submit, calculate the csum of the
7841 * bio now.
7843 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
7844 if (ret)
7845 goto err;
7846 } else {
7847 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
7848 file_offset);
7849 if (ret)
7850 goto err;
7852 map:
7853 ret = btrfs_map_bio(fs_info, bio, 0);
7854 err:
7855 return ret;
7858 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
7860 struct inode *inode = dip->inode;
7861 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7862 struct bio *bio;
7863 struct bio *orig_bio = dip->orig_bio;
7864 u64 start_sector = orig_bio->bi_iter.bi_sector;
7865 u64 file_offset = dip->logical_offset;
7866 int async_submit = 0;
7867 u64 submit_len;
7868 int clone_offset = 0;
7869 int clone_len;
7870 int ret;
7871 blk_status_t status;
7872 struct btrfs_io_geometry geom;
7874 submit_len = orig_bio->bi_iter.bi_size;
7875 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
7876 start_sector << 9, submit_len, &geom);
7877 if (ret)
7878 return -EIO;
7880 if (geom.len >= submit_len) {
7881 bio = orig_bio;
7882 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
7883 goto submit;
7886 /* async crcs make it difficult to collect full stripe writes. */
7887 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
7888 async_submit = 0;
7889 else
7890 async_submit = 1;
7892 /* bio split */
7893 ASSERT(geom.len <= INT_MAX);
7894 atomic_inc(&dip->pending_bios);
7895 do {
7896 clone_len = min_t(int, submit_len, geom.len);
7899 * This will never fail as it's passing GPF_NOFS and
7900 * the allocation is backed by btrfs_bioset.
7902 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
7903 clone_len);
7904 bio->bi_private = dip;
7905 bio->bi_end_io = btrfs_end_dio_bio;
7906 btrfs_io_bio(bio)->logical = file_offset;
7908 ASSERT(submit_len >= clone_len);
7909 submit_len -= clone_len;
7910 if (submit_len == 0)
7911 break;
7914 * Increase the count before we submit the bio so we know
7915 * the end IO handler won't happen before we increase the
7916 * count. Otherwise, the dip might get freed before we're
7917 * done setting it up.
7919 atomic_inc(&dip->pending_bios);
7921 status = btrfs_submit_dio_bio(bio, inode, file_offset,
7922 async_submit);
7923 if (status) {
7924 bio_put(bio);
7925 atomic_dec(&dip->pending_bios);
7926 goto out_err;
7929 clone_offset += clone_len;
7930 start_sector += clone_len >> 9;
7931 file_offset += clone_len;
7933 ret = btrfs_get_io_geometry(fs_info, btrfs_op(orig_bio),
7934 start_sector << 9, submit_len, &geom);
7935 if (ret)
7936 goto out_err;
7937 } while (submit_len > 0);
7939 submit:
7940 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
7941 if (!status)
7942 return 0;
7944 bio_put(bio);
7945 out_err:
7946 dip->errors = 1;
7948 * Before atomic variable goto zero, we must make sure dip->errors is
7949 * perceived to be set. This ordering is ensured by the fact that an
7950 * atomic operations with a return value are fully ordered as per
7951 * atomic_t.txt
7953 if (atomic_dec_and_test(&dip->pending_bios))
7954 bio_io_error(dip->orig_bio);
7956 /* bio_end_io() will handle error, so we needn't return it */
7957 return 0;
7960 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
7961 loff_t file_offset)
7963 struct btrfs_dio_private *dip = NULL;
7964 struct bio *bio = NULL;
7965 struct btrfs_io_bio *io_bio;
7966 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
7967 int ret = 0;
7969 bio = btrfs_bio_clone(dio_bio);
7971 dip = kzalloc(sizeof(*dip), GFP_NOFS);
7972 if (!dip) {
7973 ret = -ENOMEM;
7974 goto free_ordered;
7977 dip->private = dio_bio->bi_private;
7978 dip->inode = inode;
7979 dip->logical_offset = file_offset;
7980 dip->bytes = dio_bio->bi_iter.bi_size;
7981 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
7982 bio->bi_private = dip;
7983 dip->orig_bio = bio;
7984 dip->dio_bio = dio_bio;
7985 atomic_set(&dip->pending_bios, 0);
7986 io_bio = btrfs_io_bio(bio);
7987 io_bio->logical = file_offset;
7989 if (write) {
7990 bio->bi_end_io = btrfs_endio_direct_write;
7991 } else {
7992 bio->bi_end_io = btrfs_endio_direct_read;
7993 dip->subio_endio = btrfs_subio_endio_read;
7997 * Reset the range for unsubmitted ordered extents (to a 0 length range)
7998 * even if we fail to submit a bio, because in such case we do the
7999 * corresponding error handling below and it must not be done a second
8000 * time by btrfs_direct_IO().
8002 if (write) {
8003 struct btrfs_dio_data *dio_data = current->journal_info;
8005 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8006 dip->bytes;
8007 dio_data->unsubmitted_oe_range_start =
8008 dio_data->unsubmitted_oe_range_end;
8011 ret = btrfs_submit_direct_hook(dip);
8012 if (!ret)
8013 return;
8015 btrfs_io_bio_free_csum(io_bio);
8017 free_ordered:
8019 * If we arrived here it means either we failed to submit the dip
8020 * or we either failed to clone the dio_bio or failed to allocate the
8021 * dip. If we cloned the dio_bio and allocated the dip, we can just
8022 * call bio_endio against our io_bio so that we get proper resource
8023 * cleanup if we fail to submit the dip, otherwise, we must do the
8024 * same as btrfs_endio_direct_[write|read] because we can't call these
8025 * callbacks - they require an allocated dip and a clone of dio_bio.
8027 if (bio && dip) {
8028 bio_io_error(bio);
8030 * The end io callbacks free our dip, do the final put on bio
8031 * and all the cleanup and final put for dio_bio (through
8032 * dio_end_io()).
8034 dip = NULL;
8035 bio = NULL;
8036 } else {
8037 if (write)
8038 __endio_write_update_ordered(inode,
8039 file_offset,
8040 dio_bio->bi_iter.bi_size,
8041 false);
8042 else
8043 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8044 file_offset + dio_bio->bi_iter.bi_size - 1);
8046 dio_bio->bi_status = BLK_STS_IOERR;
8048 * Releases and cleans up our dio_bio, no need to bio_put()
8049 * nor bio_endio()/bio_io_error() against dio_bio.
8051 dio_end_io(dio_bio);
8053 if (bio)
8054 bio_put(bio);
8055 kfree(dip);
8058 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8059 const struct iov_iter *iter, loff_t offset)
8061 int seg;
8062 int i;
8063 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8064 ssize_t retval = -EINVAL;
8066 if (offset & blocksize_mask)
8067 goto out;
8069 if (iov_iter_alignment(iter) & blocksize_mask)
8070 goto out;
8072 /* If this is a write we don't need to check anymore */
8073 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8074 return 0;
8076 * Check to make sure we don't have duplicate iov_base's in this
8077 * iovec, if so return EINVAL, otherwise we'll get csum errors
8078 * when reading back.
8080 for (seg = 0; seg < iter->nr_segs; seg++) {
8081 for (i = seg + 1; i < iter->nr_segs; i++) {
8082 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8083 goto out;
8086 retval = 0;
8087 out:
8088 return retval;
8091 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8093 struct file *file = iocb->ki_filp;
8094 struct inode *inode = file->f_mapping->host;
8095 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8096 struct btrfs_dio_data dio_data = { 0 };
8097 struct extent_changeset *data_reserved = NULL;
8098 loff_t offset = iocb->ki_pos;
8099 size_t count = 0;
8100 int flags = 0;
8101 bool wakeup = true;
8102 bool relock = false;
8103 ssize_t ret;
8105 if (check_direct_IO(fs_info, iter, offset))
8106 return 0;
8108 inode_dio_begin(inode);
8111 * The generic stuff only does filemap_write_and_wait_range, which
8112 * isn't enough if we've written compressed pages to this area, so
8113 * we need to flush the dirty pages again to make absolutely sure
8114 * that any outstanding dirty pages are on disk.
8116 count = iov_iter_count(iter);
8117 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8118 &BTRFS_I(inode)->runtime_flags))
8119 filemap_fdatawrite_range(inode->i_mapping, offset,
8120 offset + count - 1);
8122 if (iov_iter_rw(iter) == WRITE) {
8124 * If the write DIO is beyond the EOF, we need update
8125 * the isize, but it is protected by i_mutex. So we can
8126 * not unlock the i_mutex at this case.
8128 if (offset + count <= inode->i_size) {
8129 dio_data.overwrite = 1;
8130 inode_unlock(inode);
8131 relock = true;
8132 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8133 ret = -EAGAIN;
8134 goto out;
8136 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8137 offset, count);
8138 if (ret)
8139 goto out;
8142 * We need to know how many extents we reserved so that we can
8143 * do the accounting properly if we go over the number we
8144 * originally calculated. Abuse current->journal_info for this.
8146 dio_data.reserve = round_up(count,
8147 fs_info->sectorsize);
8148 dio_data.unsubmitted_oe_range_start = (u64)offset;
8149 dio_data.unsubmitted_oe_range_end = (u64)offset;
8150 current->journal_info = &dio_data;
8151 down_read(&BTRFS_I(inode)->dio_sem);
8152 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8153 &BTRFS_I(inode)->runtime_flags)) {
8154 inode_dio_end(inode);
8155 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8156 wakeup = false;
8159 ret = __blockdev_direct_IO(iocb, inode,
8160 fs_info->fs_devices->latest_bdev,
8161 iter, btrfs_get_blocks_direct, NULL,
8162 btrfs_submit_direct, flags);
8163 if (iov_iter_rw(iter) == WRITE) {
8164 up_read(&BTRFS_I(inode)->dio_sem);
8165 current->journal_info = NULL;
8166 if (ret < 0 && ret != -EIOCBQUEUED) {
8167 if (dio_data.reserve)
8168 btrfs_delalloc_release_space(inode, data_reserved,
8169 offset, dio_data.reserve, true);
8171 * On error we might have left some ordered extents
8172 * without submitting corresponding bios for them, so
8173 * cleanup them up to avoid other tasks getting them
8174 * and waiting for them to complete forever.
8176 if (dio_data.unsubmitted_oe_range_start <
8177 dio_data.unsubmitted_oe_range_end)
8178 __endio_write_update_ordered(inode,
8179 dio_data.unsubmitted_oe_range_start,
8180 dio_data.unsubmitted_oe_range_end -
8181 dio_data.unsubmitted_oe_range_start,
8182 false);
8183 } else if (ret >= 0 && (size_t)ret < count)
8184 btrfs_delalloc_release_space(inode, data_reserved,
8185 offset, count - (size_t)ret, true);
8186 btrfs_delalloc_release_extents(BTRFS_I(inode), count);
8188 out:
8189 if (wakeup)
8190 inode_dio_end(inode);
8191 if (relock)
8192 inode_lock(inode);
8194 extent_changeset_free(data_reserved);
8195 return ret;
8198 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8200 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8201 __u64 start, __u64 len)
8203 int ret;
8205 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8206 if (ret)
8207 return ret;
8209 return extent_fiemap(inode, fieinfo, start, len);
8212 int btrfs_readpage(struct file *file, struct page *page)
8214 struct extent_io_tree *tree;
8215 tree = &BTRFS_I(page->mapping->host)->io_tree;
8216 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8219 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8221 struct inode *inode = page->mapping->host;
8222 int ret;
8224 if (current->flags & PF_MEMALLOC) {
8225 redirty_page_for_writepage(wbc, page);
8226 unlock_page(page);
8227 return 0;
8231 * If we are under memory pressure we will call this directly from the
8232 * VM, we need to make sure we have the inode referenced for the ordered
8233 * extent. If not just return like we didn't do anything.
8235 if (!igrab(inode)) {
8236 redirty_page_for_writepage(wbc, page);
8237 return AOP_WRITEPAGE_ACTIVATE;
8239 ret = extent_write_full_page(page, wbc);
8240 btrfs_add_delayed_iput(inode);
8241 return ret;
8244 static int btrfs_writepages(struct address_space *mapping,
8245 struct writeback_control *wbc)
8247 return extent_writepages(mapping, wbc);
8250 static int
8251 btrfs_readpages(struct file *file, struct address_space *mapping,
8252 struct list_head *pages, unsigned nr_pages)
8254 return extent_readpages(mapping, pages, nr_pages);
8257 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8259 int ret = try_release_extent_mapping(page, gfp_flags);
8260 if (ret == 1) {
8261 ClearPagePrivate(page);
8262 set_page_private(page, 0);
8263 put_page(page);
8265 return ret;
8268 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8270 if (PageWriteback(page) || PageDirty(page))
8271 return 0;
8272 return __btrfs_releasepage(page, gfp_flags);
8275 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8276 unsigned int length)
8278 struct inode *inode = page->mapping->host;
8279 struct extent_io_tree *tree;
8280 struct btrfs_ordered_extent *ordered;
8281 struct extent_state *cached_state = NULL;
8282 u64 page_start = page_offset(page);
8283 u64 page_end = page_start + PAGE_SIZE - 1;
8284 u64 start;
8285 u64 end;
8286 int inode_evicting = inode->i_state & I_FREEING;
8289 * we have the page locked, so new writeback can't start,
8290 * and the dirty bit won't be cleared while we are here.
8292 * Wait for IO on this page so that we can safely clear
8293 * the PagePrivate2 bit and do ordered accounting
8295 wait_on_page_writeback(page);
8297 tree = &BTRFS_I(inode)->io_tree;
8298 if (offset) {
8299 btrfs_releasepage(page, GFP_NOFS);
8300 return;
8303 if (!inode_evicting)
8304 lock_extent_bits(tree, page_start, page_end, &cached_state);
8305 again:
8306 start = page_start;
8307 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8308 page_end - start + 1);
8309 if (ordered) {
8310 end = min(page_end,
8311 ordered->file_offset + ordered->num_bytes - 1);
8313 * IO on this page will never be started, so we need
8314 * to account for any ordered extents now
8316 if (!inode_evicting)
8317 clear_extent_bit(tree, start, end,
8318 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8319 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8320 EXTENT_DEFRAG, 1, 0, &cached_state);
8322 * whoever cleared the private bit is responsible
8323 * for the finish_ordered_io
8325 if (TestClearPagePrivate2(page)) {
8326 struct btrfs_ordered_inode_tree *tree;
8327 u64 new_len;
8329 tree = &BTRFS_I(inode)->ordered_tree;
8331 spin_lock_irq(&tree->lock);
8332 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8333 new_len = start - ordered->file_offset;
8334 if (new_len < ordered->truncated_len)
8335 ordered->truncated_len = new_len;
8336 spin_unlock_irq(&tree->lock);
8338 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8339 start,
8340 end - start + 1, 1))
8341 btrfs_finish_ordered_io(ordered);
8343 btrfs_put_ordered_extent(ordered);
8344 if (!inode_evicting) {
8345 cached_state = NULL;
8346 lock_extent_bits(tree, start, end,
8347 &cached_state);
8350 start = end + 1;
8351 if (start < page_end)
8352 goto again;
8356 * Qgroup reserved space handler
8357 * Page here will be either
8358 * 1) Already written to disk
8359 * In this case, its reserved space is released from data rsv map
8360 * and will be freed by delayed_ref handler finally.
8361 * So even we call qgroup_free_data(), it won't decrease reserved
8362 * space.
8363 * 2) Not written to disk
8364 * This means the reserved space should be freed here. However,
8365 * if a truncate invalidates the page (by clearing PageDirty)
8366 * and the page is accounted for while allocating extent
8367 * in btrfs_check_data_free_space() we let delayed_ref to
8368 * free the entire extent.
8370 if (PageDirty(page))
8371 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8372 if (!inode_evicting) {
8373 clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED |
8374 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8375 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8376 &cached_state);
8378 __btrfs_releasepage(page, GFP_NOFS);
8381 ClearPageChecked(page);
8382 if (PagePrivate(page)) {
8383 ClearPagePrivate(page);
8384 set_page_private(page, 0);
8385 put_page(page);
8390 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8391 * called from a page fault handler when a page is first dirtied. Hence we must
8392 * be careful to check for EOF conditions here. We set the page up correctly
8393 * for a written page which means we get ENOSPC checking when writing into
8394 * holes and correct delalloc and unwritten extent mapping on filesystems that
8395 * support these features.
8397 * We are not allowed to take the i_mutex here so we have to play games to
8398 * protect against truncate races as the page could now be beyond EOF. Because
8399 * truncate_setsize() writes the inode size before removing pages, once we have
8400 * the page lock we can determine safely if the page is beyond EOF. If it is not
8401 * beyond EOF, then the page is guaranteed safe against truncation until we
8402 * unlock the page.
8404 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8406 struct page *page = vmf->page;
8407 struct inode *inode = file_inode(vmf->vma->vm_file);
8408 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8409 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8410 struct btrfs_ordered_extent *ordered;
8411 struct extent_state *cached_state = NULL;
8412 struct extent_changeset *data_reserved = NULL;
8413 char *kaddr;
8414 unsigned long zero_start;
8415 loff_t size;
8416 vm_fault_t ret;
8417 int ret2;
8418 int reserved = 0;
8419 u64 reserved_space;
8420 u64 page_start;
8421 u64 page_end;
8422 u64 end;
8424 reserved_space = PAGE_SIZE;
8426 sb_start_pagefault(inode->i_sb);
8427 page_start = page_offset(page);
8428 page_end = page_start + PAGE_SIZE - 1;
8429 end = page_end;
8432 * Reserving delalloc space after obtaining the page lock can lead to
8433 * deadlock. For example, if a dirty page is locked by this function
8434 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8435 * dirty page write out, then the btrfs_writepage() function could
8436 * end up waiting indefinitely to get a lock on the page currently
8437 * being processed by btrfs_page_mkwrite() function.
8439 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8440 reserved_space);
8441 if (!ret2) {
8442 ret2 = file_update_time(vmf->vma->vm_file);
8443 reserved = 1;
8445 if (ret2) {
8446 ret = vmf_error(ret2);
8447 if (reserved)
8448 goto out;
8449 goto out_noreserve;
8452 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8453 again:
8454 lock_page(page);
8455 size = i_size_read(inode);
8457 if ((page->mapping != inode->i_mapping) ||
8458 (page_start >= size)) {
8459 /* page got truncated out from underneath us */
8460 goto out_unlock;
8462 wait_on_page_writeback(page);
8464 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8465 set_page_extent_mapped(page);
8468 * we can't set the delalloc bits if there are pending ordered
8469 * extents. Drop our locks and wait for them to finish
8471 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8472 PAGE_SIZE);
8473 if (ordered) {
8474 unlock_extent_cached(io_tree, page_start, page_end,
8475 &cached_state);
8476 unlock_page(page);
8477 btrfs_start_ordered_extent(inode, ordered, 1);
8478 btrfs_put_ordered_extent(ordered);
8479 goto again;
8482 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8483 reserved_space = round_up(size - page_start,
8484 fs_info->sectorsize);
8485 if (reserved_space < PAGE_SIZE) {
8486 end = page_start + reserved_space - 1;
8487 btrfs_delalloc_release_space(inode, data_reserved,
8488 page_start, PAGE_SIZE - reserved_space,
8489 true);
8494 * page_mkwrite gets called when the page is firstly dirtied after it's
8495 * faulted in, but write(2) could also dirty a page and set delalloc
8496 * bits, thus in this case for space account reason, we still need to
8497 * clear any delalloc bits within this page range since we have to
8498 * reserve data&meta space before lock_page() (see above comments).
8500 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8501 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8502 EXTENT_DEFRAG, 0, 0, &cached_state);
8504 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8505 &cached_state);
8506 if (ret2) {
8507 unlock_extent_cached(io_tree, page_start, page_end,
8508 &cached_state);
8509 ret = VM_FAULT_SIGBUS;
8510 goto out_unlock;
8513 /* page is wholly or partially inside EOF */
8514 if (page_start + PAGE_SIZE > size)
8515 zero_start = offset_in_page(size);
8516 else
8517 zero_start = PAGE_SIZE;
8519 if (zero_start != PAGE_SIZE) {
8520 kaddr = kmap(page);
8521 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8522 flush_dcache_page(page);
8523 kunmap(page);
8525 ClearPageChecked(page);
8526 set_page_dirty(page);
8527 SetPageUptodate(page);
8529 BTRFS_I(inode)->last_trans = fs_info->generation;
8530 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8531 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8533 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8535 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8536 sb_end_pagefault(inode->i_sb);
8537 extent_changeset_free(data_reserved);
8538 return VM_FAULT_LOCKED;
8540 out_unlock:
8541 unlock_page(page);
8542 out:
8543 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
8544 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8545 reserved_space, (ret != 0));
8546 out_noreserve:
8547 sb_end_pagefault(inode->i_sb);
8548 extent_changeset_free(data_reserved);
8549 return ret;
8552 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
8554 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8555 struct btrfs_root *root = BTRFS_I(inode)->root;
8556 struct btrfs_block_rsv *rsv;
8557 int ret;
8558 struct btrfs_trans_handle *trans;
8559 u64 mask = fs_info->sectorsize - 1;
8560 u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
8562 if (!skip_writeback) {
8563 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8564 (u64)-1);
8565 if (ret)
8566 return ret;
8570 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
8571 * things going on here:
8573 * 1) We need to reserve space to update our inode.
8575 * 2) We need to have something to cache all the space that is going to
8576 * be free'd up by the truncate operation, but also have some slack
8577 * space reserved in case it uses space during the truncate (thank you
8578 * very much snapshotting).
8580 * And we need these to be separate. The fact is we can use a lot of
8581 * space doing the truncate, and we have no earthly idea how much space
8582 * we will use, so we need the truncate reservation to be separate so it
8583 * doesn't end up using space reserved for updating the inode. We also
8584 * need to be able to stop the transaction and start a new one, which
8585 * means we need to be able to update the inode several times, and we
8586 * have no idea of knowing how many times that will be, so we can't just
8587 * reserve 1 item for the entirety of the operation, so that has to be
8588 * done separately as well.
8590 * So that leaves us with
8592 * 1) rsv - for the truncate reservation, which we will steal from the
8593 * transaction reservation.
8594 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
8595 * updating the inode.
8597 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
8598 if (!rsv)
8599 return -ENOMEM;
8600 rsv->size = min_size;
8601 rsv->failfast = 1;
8604 * 1 for the truncate slack space
8605 * 1 for updating the inode.
8607 trans = btrfs_start_transaction(root, 2);
8608 if (IS_ERR(trans)) {
8609 ret = PTR_ERR(trans);
8610 goto out;
8613 /* Migrate the slack space for the truncate to our reserve */
8614 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
8615 min_size, false);
8616 BUG_ON(ret);
8619 * So if we truncate and then write and fsync we normally would just
8620 * write the extents that changed, which is a problem if we need to
8621 * first truncate that entire inode. So set this flag so we write out
8622 * all of the extents in the inode to the sync log so we're completely
8623 * safe.
8625 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
8626 trans->block_rsv = rsv;
8628 while (1) {
8629 ret = btrfs_truncate_inode_items(trans, root, inode,
8630 inode->i_size,
8631 BTRFS_EXTENT_DATA_KEY);
8632 trans->block_rsv = &fs_info->trans_block_rsv;
8633 if (ret != -ENOSPC && ret != -EAGAIN)
8634 break;
8636 ret = btrfs_update_inode(trans, root, inode);
8637 if (ret)
8638 break;
8640 btrfs_end_transaction(trans);
8641 btrfs_btree_balance_dirty(fs_info);
8643 trans = btrfs_start_transaction(root, 2);
8644 if (IS_ERR(trans)) {
8645 ret = PTR_ERR(trans);
8646 trans = NULL;
8647 break;
8650 btrfs_block_rsv_release(fs_info, rsv, -1);
8651 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
8652 rsv, min_size, false);
8653 BUG_ON(ret); /* shouldn't happen */
8654 trans->block_rsv = rsv;
8658 * We can't call btrfs_truncate_block inside a trans handle as we could
8659 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
8660 * we've truncated everything except the last little bit, and can do
8661 * btrfs_truncate_block and then update the disk_i_size.
8663 if (ret == NEED_TRUNCATE_BLOCK) {
8664 btrfs_end_transaction(trans);
8665 btrfs_btree_balance_dirty(fs_info);
8667 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
8668 if (ret)
8669 goto out;
8670 trans = btrfs_start_transaction(root, 1);
8671 if (IS_ERR(trans)) {
8672 ret = PTR_ERR(trans);
8673 goto out;
8675 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
8678 if (trans) {
8679 int ret2;
8681 trans->block_rsv = &fs_info->trans_block_rsv;
8682 ret2 = btrfs_update_inode(trans, root, inode);
8683 if (ret2 && !ret)
8684 ret = ret2;
8686 ret2 = btrfs_end_transaction(trans);
8687 if (ret2 && !ret)
8688 ret = ret2;
8689 btrfs_btree_balance_dirty(fs_info);
8691 out:
8692 btrfs_free_block_rsv(fs_info, rsv);
8694 return ret;
8698 * create a new subvolume directory/inode (helper for the ioctl).
8700 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
8701 struct btrfs_root *new_root,
8702 struct btrfs_root *parent_root,
8703 u64 new_dirid)
8705 struct inode *inode;
8706 int err;
8707 u64 index = 0;
8709 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
8710 new_dirid, new_dirid,
8711 S_IFDIR | (~current_umask() & S_IRWXUGO),
8712 &index);
8713 if (IS_ERR(inode))
8714 return PTR_ERR(inode);
8715 inode->i_op = &btrfs_dir_inode_operations;
8716 inode->i_fop = &btrfs_dir_file_operations;
8718 set_nlink(inode, 1);
8719 btrfs_i_size_write(BTRFS_I(inode), 0);
8720 unlock_new_inode(inode);
8722 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
8723 if (err)
8724 btrfs_err(new_root->fs_info,
8725 "error inheriting subvolume %llu properties: %d",
8726 new_root->root_key.objectid, err);
8728 err = btrfs_update_inode(trans, new_root, inode);
8730 iput(inode);
8731 return err;
8734 struct inode *btrfs_alloc_inode(struct super_block *sb)
8736 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8737 struct btrfs_inode *ei;
8738 struct inode *inode;
8740 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
8741 if (!ei)
8742 return NULL;
8744 ei->root = NULL;
8745 ei->generation = 0;
8746 ei->last_trans = 0;
8747 ei->last_sub_trans = 0;
8748 ei->logged_trans = 0;
8749 ei->delalloc_bytes = 0;
8750 ei->new_delalloc_bytes = 0;
8751 ei->defrag_bytes = 0;
8752 ei->disk_i_size = 0;
8753 ei->flags = 0;
8754 ei->csum_bytes = 0;
8755 ei->index_cnt = (u64)-1;
8756 ei->dir_index = 0;
8757 ei->last_unlink_trans = 0;
8758 ei->last_log_commit = 0;
8760 spin_lock_init(&ei->lock);
8761 ei->outstanding_extents = 0;
8762 if (sb->s_magic != BTRFS_TEST_MAGIC)
8763 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8764 BTRFS_BLOCK_RSV_DELALLOC);
8765 ei->runtime_flags = 0;
8766 ei->prop_compress = BTRFS_COMPRESS_NONE;
8767 ei->defrag_compress = BTRFS_COMPRESS_NONE;
8769 ei->delayed_node = NULL;
8771 ei->i_otime.tv_sec = 0;
8772 ei->i_otime.tv_nsec = 0;
8774 inode = &ei->vfs_inode;
8775 extent_map_tree_init(&ei->extent_tree);
8776 extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
8777 extent_io_tree_init(fs_info, &ei->io_failure_tree,
8778 IO_TREE_INODE_IO_FAILURE, inode);
8779 ei->io_tree.track_uptodate = true;
8780 ei->io_failure_tree.track_uptodate = true;
8781 atomic_set(&ei->sync_writers, 0);
8782 mutex_init(&ei->log_mutex);
8783 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
8784 INIT_LIST_HEAD(&ei->delalloc_inodes);
8785 INIT_LIST_HEAD(&ei->delayed_iput);
8786 RB_CLEAR_NODE(&ei->rb_node);
8787 init_rwsem(&ei->dio_sem);
8789 return inode;
8792 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8793 void btrfs_test_destroy_inode(struct inode *inode)
8795 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8796 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8798 #endif
8800 void btrfs_free_inode(struct inode *inode)
8802 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8805 void btrfs_destroy_inode(struct inode *inode)
8807 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8808 struct btrfs_ordered_extent *ordered;
8809 struct btrfs_root *root = BTRFS_I(inode)->root;
8811 WARN_ON(!hlist_empty(&inode->i_dentry));
8812 WARN_ON(inode->i_data.nrpages);
8813 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
8814 WARN_ON(BTRFS_I(inode)->block_rsv.size);
8815 WARN_ON(BTRFS_I(inode)->outstanding_extents);
8816 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
8817 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
8818 WARN_ON(BTRFS_I(inode)->csum_bytes);
8819 WARN_ON(BTRFS_I(inode)->defrag_bytes);
8822 * This can happen where we create an inode, but somebody else also
8823 * created the same inode and we need to destroy the one we already
8824 * created.
8826 if (!root)
8827 return;
8829 while (1) {
8830 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8831 if (!ordered)
8832 break;
8833 else {
8834 btrfs_err(fs_info,
8835 "found ordered extent %llu %llu on inode cleanup",
8836 ordered->file_offset, ordered->num_bytes);
8837 btrfs_remove_ordered_extent(inode, ordered);
8838 btrfs_put_ordered_extent(ordered);
8839 btrfs_put_ordered_extent(ordered);
8842 btrfs_qgroup_check_reserved_leak(inode);
8843 inode_tree_del(inode);
8844 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
8847 int btrfs_drop_inode(struct inode *inode)
8849 struct btrfs_root *root = BTRFS_I(inode)->root;
8851 if (root == NULL)
8852 return 1;
8854 /* the snap/subvol tree is on deleting */
8855 if (btrfs_root_refs(&root->root_item) == 0)
8856 return 1;
8857 else
8858 return generic_drop_inode(inode);
8861 static void init_once(void *foo)
8863 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
8865 inode_init_once(&ei->vfs_inode);
8868 void __cold btrfs_destroy_cachep(void)
8871 * Make sure all delayed rcu free inodes are flushed before we
8872 * destroy cache.
8874 rcu_barrier();
8875 kmem_cache_destroy(btrfs_inode_cachep);
8876 kmem_cache_destroy(btrfs_trans_handle_cachep);
8877 kmem_cache_destroy(btrfs_path_cachep);
8878 kmem_cache_destroy(btrfs_free_space_cachep);
8879 kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
8882 int __init btrfs_init_cachep(void)
8884 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8885 sizeof(struct btrfs_inode), 0,
8886 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
8887 init_once);
8888 if (!btrfs_inode_cachep)
8889 goto fail;
8891 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
8892 sizeof(struct btrfs_trans_handle), 0,
8893 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
8894 if (!btrfs_trans_handle_cachep)
8895 goto fail;
8897 btrfs_path_cachep = kmem_cache_create("btrfs_path",
8898 sizeof(struct btrfs_path), 0,
8899 SLAB_MEM_SPREAD, NULL);
8900 if (!btrfs_path_cachep)
8901 goto fail;
8903 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
8904 sizeof(struct btrfs_free_space), 0,
8905 SLAB_MEM_SPREAD, NULL);
8906 if (!btrfs_free_space_cachep)
8907 goto fail;
8909 btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
8910 PAGE_SIZE, PAGE_SIZE,
8911 SLAB_RED_ZONE, NULL);
8912 if (!btrfs_free_space_bitmap_cachep)
8913 goto fail;
8915 return 0;
8916 fail:
8917 btrfs_destroy_cachep();
8918 return -ENOMEM;
8921 static int btrfs_getattr(const struct path *path, struct kstat *stat,
8922 u32 request_mask, unsigned int flags)
8924 u64 delalloc_bytes;
8925 struct inode *inode = d_inode(path->dentry);
8926 u32 blocksize = inode->i_sb->s_blocksize;
8927 u32 bi_flags = BTRFS_I(inode)->flags;
8929 stat->result_mask |= STATX_BTIME;
8930 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
8931 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
8932 if (bi_flags & BTRFS_INODE_APPEND)
8933 stat->attributes |= STATX_ATTR_APPEND;
8934 if (bi_flags & BTRFS_INODE_COMPRESS)
8935 stat->attributes |= STATX_ATTR_COMPRESSED;
8936 if (bi_flags & BTRFS_INODE_IMMUTABLE)
8937 stat->attributes |= STATX_ATTR_IMMUTABLE;
8938 if (bi_flags & BTRFS_INODE_NODUMP)
8939 stat->attributes |= STATX_ATTR_NODUMP;
8941 stat->attributes_mask |= (STATX_ATTR_APPEND |
8942 STATX_ATTR_COMPRESSED |
8943 STATX_ATTR_IMMUTABLE |
8944 STATX_ATTR_NODUMP);
8946 generic_fillattr(inode, stat);
8947 stat->dev = BTRFS_I(inode)->root->anon_dev;
8949 spin_lock(&BTRFS_I(inode)->lock);
8950 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8951 spin_unlock(&BTRFS_I(inode)->lock);
8952 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
8953 ALIGN(delalloc_bytes, blocksize)) >> 9;
8954 return 0;
8957 static int btrfs_rename_exchange(struct inode *old_dir,
8958 struct dentry *old_dentry,
8959 struct inode *new_dir,
8960 struct dentry *new_dentry)
8962 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
8963 struct btrfs_trans_handle *trans;
8964 struct btrfs_root *root = BTRFS_I(old_dir)->root;
8965 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8966 struct inode *new_inode = new_dentry->d_inode;
8967 struct inode *old_inode = old_dentry->d_inode;
8968 struct timespec64 ctime = current_time(old_inode);
8969 struct dentry *parent;
8970 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8971 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8972 u64 old_idx = 0;
8973 u64 new_idx = 0;
8974 int ret;
8975 bool root_log_pinned = false;
8976 bool dest_log_pinned = false;
8977 struct btrfs_log_ctx ctx_root;
8978 struct btrfs_log_ctx ctx_dest;
8979 bool sync_log_root = false;
8980 bool sync_log_dest = false;
8981 bool commit_transaction = false;
8983 /* we only allow rename subvolume link between subvolumes */
8984 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8985 return -EXDEV;
8987 btrfs_init_log_ctx(&ctx_root, old_inode);
8988 btrfs_init_log_ctx(&ctx_dest, new_inode);
8990 /* close the race window with snapshot create/destroy ioctl */
8991 if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8992 new_ino == BTRFS_FIRST_FREE_OBJECTID)
8993 down_read(&fs_info->subvol_sem);
8996 * We want to reserve the absolute worst case amount of items. So if
8997 * both inodes are subvols and we need to unlink them then that would
8998 * require 4 item modifications, but if they are both normal inodes it
8999 * would require 5 item modifications, so we'll assume their normal
9000 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9001 * should cover the worst case number of items we'll modify.
9003 trans = btrfs_start_transaction(root, 12);
9004 if (IS_ERR(trans)) {
9005 ret = PTR_ERR(trans);
9006 goto out_notrans;
9009 if (dest != root)
9010 btrfs_record_root_in_trans(trans, dest);
9013 * We need to find a free sequence number both in the source and
9014 * in the destination directory for the exchange.
9016 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9017 if (ret)
9018 goto out_fail;
9019 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9020 if (ret)
9021 goto out_fail;
9023 BTRFS_I(old_inode)->dir_index = 0ULL;
9024 BTRFS_I(new_inode)->dir_index = 0ULL;
9026 /* Reference for the source. */
9027 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9028 /* force full log commit if subvolume involved. */
9029 btrfs_set_log_full_commit(trans);
9030 } else {
9031 btrfs_pin_log_trans(root);
9032 root_log_pinned = true;
9033 ret = btrfs_insert_inode_ref(trans, dest,
9034 new_dentry->d_name.name,
9035 new_dentry->d_name.len,
9036 old_ino,
9037 btrfs_ino(BTRFS_I(new_dir)),
9038 old_idx);
9039 if (ret)
9040 goto out_fail;
9043 /* And now for the dest. */
9044 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9045 /* force full log commit if subvolume involved. */
9046 btrfs_set_log_full_commit(trans);
9047 } else {
9048 btrfs_pin_log_trans(dest);
9049 dest_log_pinned = true;
9050 ret = btrfs_insert_inode_ref(trans, root,
9051 old_dentry->d_name.name,
9052 old_dentry->d_name.len,
9053 new_ino,
9054 btrfs_ino(BTRFS_I(old_dir)),
9055 new_idx);
9056 if (ret)
9057 goto out_fail;
9060 /* Update inode version and ctime/mtime. */
9061 inode_inc_iversion(old_dir);
9062 inode_inc_iversion(new_dir);
9063 inode_inc_iversion(old_inode);
9064 inode_inc_iversion(new_inode);
9065 old_dir->i_ctime = old_dir->i_mtime = ctime;
9066 new_dir->i_ctime = new_dir->i_mtime = ctime;
9067 old_inode->i_ctime = ctime;
9068 new_inode->i_ctime = ctime;
9070 if (old_dentry->d_parent != new_dentry->d_parent) {
9071 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9072 BTRFS_I(old_inode), 1);
9073 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9074 BTRFS_I(new_inode), 1);
9077 /* src is a subvolume */
9078 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9079 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9080 } else { /* src is an inode */
9081 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9082 BTRFS_I(old_dentry->d_inode),
9083 old_dentry->d_name.name,
9084 old_dentry->d_name.len);
9085 if (!ret)
9086 ret = btrfs_update_inode(trans, root, old_inode);
9088 if (ret) {
9089 btrfs_abort_transaction(trans, ret);
9090 goto out_fail;
9093 /* dest is a subvolume */
9094 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9095 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9096 } else { /* dest is an inode */
9097 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9098 BTRFS_I(new_dentry->d_inode),
9099 new_dentry->d_name.name,
9100 new_dentry->d_name.len);
9101 if (!ret)
9102 ret = btrfs_update_inode(trans, dest, new_inode);
9104 if (ret) {
9105 btrfs_abort_transaction(trans, ret);
9106 goto out_fail;
9109 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9110 new_dentry->d_name.name,
9111 new_dentry->d_name.len, 0, old_idx);
9112 if (ret) {
9113 btrfs_abort_transaction(trans, ret);
9114 goto out_fail;
9117 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9118 old_dentry->d_name.name,
9119 old_dentry->d_name.len, 0, new_idx);
9120 if (ret) {
9121 btrfs_abort_transaction(trans, ret);
9122 goto out_fail;
9125 if (old_inode->i_nlink == 1)
9126 BTRFS_I(old_inode)->dir_index = old_idx;
9127 if (new_inode->i_nlink == 1)
9128 BTRFS_I(new_inode)->dir_index = new_idx;
9130 if (root_log_pinned) {
9131 parent = new_dentry->d_parent;
9132 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9133 BTRFS_I(old_dir), parent,
9134 false, &ctx_root);
9135 if (ret == BTRFS_NEED_LOG_SYNC)
9136 sync_log_root = true;
9137 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9138 commit_transaction = true;
9139 ret = 0;
9140 btrfs_end_log_trans(root);
9141 root_log_pinned = false;
9143 if (dest_log_pinned) {
9144 if (!commit_transaction) {
9145 parent = old_dentry->d_parent;
9146 ret = btrfs_log_new_name(trans, BTRFS_I(new_inode),
9147 BTRFS_I(new_dir), parent,
9148 false, &ctx_dest);
9149 if (ret == BTRFS_NEED_LOG_SYNC)
9150 sync_log_dest = true;
9151 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9152 commit_transaction = true;
9153 ret = 0;
9155 btrfs_end_log_trans(dest);
9156 dest_log_pinned = false;
9158 out_fail:
9160 * If we have pinned a log and an error happened, we unpin tasks
9161 * trying to sync the log and force them to fallback to a transaction
9162 * commit if the log currently contains any of the inodes involved in
9163 * this rename operation (to ensure we do not persist a log with an
9164 * inconsistent state for any of these inodes or leading to any
9165 * inconsistencies when replayed). If the transaction was aborted, the
9166 * abortion reason is propagated to userspace when attempting to commit
9167 * the transaction. If the log does not contain any of these inodes, we
9168 * allow the tasks to sync it.
9170 if (ret && (root_log_pinned || dest_log_pinned)) {
9171 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9172 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9173 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9174 (new_inode &&
9175 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9176 btrfs_set_log_full_commit(trans);
9178 if (root_log_pinned) {
9179 btrfs_end_log_trans(root);
9180 root_log_pinned = false;
9182 if (dest_log_pinned) {
9183 btrfs_end_log_trans(dest);
9184 dest_log_pinned = false;
9187 if (!ret && sync_log_root && !commit_transaction) {
9188 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root,
9189 &ctx_root);
9190 if (ret)
9191 commit_transaction = true;
9193 if (!ret && sync_log_dest && !commit_transaction) {
9194 ret = btrfs_sync_log(trans, BTRFS_I(new_inode)->root,
9195 &ctx_dest);
9196 if (ret)
9197 commit_transaction = true;
9199 if (commit_transaction) {
9201 * We may have set commit_transaction when logging the new name
9202 * in the destination root, in which case we left the source
9203 * root context in the list of log contextes. So make sure we
9204 * remove it to avoid invalid memory accesses, since the context
9205 * was allocated in our stack frame.
9207 if (sync_log_root) {
9208 mutex_lock(&root->log_mutex);
9209 list_del_init(&ctx_root.list);
9210 mutex_unlock(&root->log_mutex);
9212 ret = btrfs_commit_transaction(trans);
9213 } else {
9214 int ret2;
9216 ret2 = btrfs_end_transaction(trans);
9217 ret = ret ? ret : ret2;
9219 out_notrans:
9220 if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
9221 old_ino == BTRFS_FIRST_FREE_OBJECTID)
9222 up_read(&fs_info->subvol_sem);
9224 ASSERT(list_empty(&ctx_root.list));
9225 ASSERT(list_empty(&ctx_dest.list));
9227 return ret;
9230 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9231 struct btrfs_root *root,
9232 struct inode *dir,
9233 struct dentry *dentry)
9235 int ret;
9236 struct inode *inode;
9237 u64 objectid;
9238 u64 index;
9240 ret = btrfs_find_free_ino(root, &objectid);
9241 if (ret)
9242 return ret;
9244 inode = btrfs_new_inode(trans, root, dir,
9245 dentry->d_name.name,
9246 dentry->d_name.len,
9247 btrfs_ino(BTRFS_I(dir)),
9248 objectid,
9249 S_IFCHR | WHITEOUT_MODE,
9250 &index);
9252 if (IS_ERR(inode)) {
9253 ret = PTR_ERR(inode);
9254 return ret;
9257 inode->i_op = &btrfs_special_inode_operations;
9258 init_special_inode(inode, inode->i_mode,
9259 WHITEOUT_DEV);
9261 ret = btrfs_init_inode_security(trans, inode, dir,
9262 &dentry->d_name);
9263 if (ret)
9264 goto out;
9266 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9267 BTRFS_I(inode), 0, index);
9268 if (ret)
9269 goto out;
9271 ret = btrfs_update_inode(trans, root, inode);
9272 out:
9273 unlock_new_inode(inode);
9274 if (ret)
9275 inode_dec_link_count(inode);
9276 iput(inode);
9278 return ret;
9281 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9282 struct inode *new_dir, struct dentry *new_dentry,
9283 unsigned int flags)
9285 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9286 struct btrfs_trans_handle *trans;
9287 unsigned int trans_num_items;
9288 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9289 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9290 struct inode *new_inode = d_inode(new_dentry);
9291 struct inode *old_inode = d_inode(old_dentry);
9292 u64 index = 0;
9293 int ret;
9294 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9295 bool log_pinned = false;
9296 struct btrfs_log_ctx ctx;
9297 bool sync_log = false;
9298 bool commit_transaction = false;
9300 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9301 return -EPERM;
9303 /* we only allow rename subvolume link between subvolumes */
9304 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9305 return -EXDEV;
9307 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9308 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9309 return -ENOTEMPTY;
9311 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9312 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9313 return -ENOTEMPTY;
9316 /* check for collisions, even if the name isn't there */
9317 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9318 new_dentry->d_name.name,
9319 new_dentry->d_name.len);
9321 if (ret) {
9322 if (ret == -EEXIST) {
9323 /* we shouldn't get
9324 * eexist without a new_inode */
9325 if (WARN_ON(!new_inode)) {
9326 return ret;
9328 } else {
9329 /* maybe -EOVERFLOW */
9330 return ret;
9333 ret = 0;
9336 * we're using rename to replace one file with another. Start IO on it
9337 * now so we don't add too much work to the end of the transaction
9339 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9340 filemap_flush(old_inode->i_mapping);
9342 /* close the racy window with snapshot create/destroy ioctl */
9343 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9344 down_read(&fs_info->subvol_sem);
9346 * We want to reserve the absolute worst case amount of items. So if
9347 * both inodes are subvols and we need to unlink them then that would
9348 * require 4 item modifications, but if they are both normal inodes it
9349 * would require 5 item modifications, so we'll assume they are normal
9350 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9351 * should cover the worst case number of items we'll modify.
9352 * If our rename has the whiteout flag, we need more 5 units for the
9353 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9354 * when selinux is enabled).
9356 trans_num_items = 11;
9357 if (flags & RENAME_WHITEOUT)
9358 trans_num_items += 5;
9359 trans = btrfs_start_transaction(root, trans_num_items);
9360 if (IS_ERR(trans)) {
9361 ret = PTR_ERR(trans);
9362 goto out_notrans;
9365 if (dest != root)
9366 btrfs_record_root_in_trans(trans, dest);
9368 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9369 if (ret)
9370 goto out_fail;
9372 BTRFS_I(old_inode)->dir_index = 0ULL;
9373 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9374 /* force full log commit if subvolume involved. */
9375 btrfs_set_log_full_commit(trans);
9376 } else {
9377 btrfs_pin_log_trans(root);
9378 log_pinned = true;
9379 ret = btrfs_insert_inode_ref(trans, dest,
9380 new_dentry->d_name.name,
9381 new_dentry->d_name.len,
9382 old_ino,
9383 btrfs_ino(BTRFS_I(new_dir)), index);
9384 if (ret)
9385 goto out_fail;
9388 inode_inc_iversion(old_dir);
9389 inode_inc_iversion(new_dir);
9390 inode_inc_iversion(old_inode);
9391 old_dir->i_ctime = old_dir->i_mtime =
9392 new_dir->i_ctime = new_dir->i_mtime =
9393 old_inode->i_ctime = current_time(old_dir);
9395 if (old_dentry->d_parent != new_dentry->d_parent)
9396 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9397 BTRFS_I(old_inode), 1);
9399 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9400 ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
9401 } else {
9402 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9403 BTRFS_I(d_inode(old_dentry)),
9404 old_dentry->d_name.name,
9405 old_dentry->d_name.len);
9406 if (!ret)
9407 ret = btrfs_update_inode(trans, root, old_inode);
9409 if (ret) {
9410 btrfs_abort_transaction(trans, ret);
9411 goto out_fail;
9414 if (new_inode) {
9415 inode_inc_iversion(new_inode);
9416 new_inode->i_ctime = current_time(new_inode);
9417 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9418 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9419 ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
9420 BUG_ON(new_inode->i_nlink == 0);
9421 } else {
9422 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9423 BTRFS_I(d_inode(new_dentry)),
9424 new_dentry->d_name.name,
9425 new_dentry->d_name.len);
9427 if (!ret && new_inode->i_nlink == 0)
9428 ret = btrfs_orphan_add(trans,
9429 BTRFS_I(d_inode(new_dentry)));
9430 if (ret) {
9431 btrfs_abort_transaction(trans, ret);
9432 goto out_fail;
9436 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9437 new_dentry->d_name.name,
9438 new_dentry->d_name.len, 0, index);
9439 if (ret) {
9440 btrfs_abort_transaction(trans, ret);
9441 goto out_fail;
9444 if (old_inode->i_nlink == 1)
9445 BTRFS_I(old_inode)->dir_index = index;
9447 if (log_pinned) {
9448 struct dentry *parent = new_dentry->d_parent;
9450 btrfs_init_log_ctx(&ctx, old_inode);
9451 ret = btrfs_log_new_name(trans, BTRFS_I(old_inode),
9452 BTRFS_I(old_dir), parent,
9453 false, &ctx);
9454 if (ret == BTRFS_NEED_LOG_SYNC)
9455 sync_log = true;
9456 else if (ret == BTRFS_NEED_TRANS_COMMIT)
9457 commit_transaction = true;
9458 ret = 0;
9459 btrfs_end_log_trans(root);
9460 log_pinned = false;
9463 if (flags & RENAME_WHITEOUT) {
9464 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9465 old_dentry);
9467 if (ret) {
9468 btrfs_abort_transaction(trans, ret);
9469 goto out_fail;
9472 out_fail:
9474 * If we have pinned the log and an error happened, we unpin tasks
9475 * trying to sync the log and force them to fallback to a transaction
9476 * commit if the log currently contains any of the inodes involved in
9477 * this rename operation (to ensure we do not persist a log with an
9478 * inconsistent state for any of these inodes or leading to any
9479 * inconsistencies when replayed). If the transaction was aborted, the
9480 * abortion reason is propagated to userspace when attempting to commit
9481 * the transaction. If the log does not contain any of these inodes, we
9482 * allow the tasks to sync it.
9484 if (ret && log_pinned) {
9485 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9486 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9487 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9488 (new_inode &&
9489 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9490 btrfs_set_log_full_commit(trans);
9492 btrfs_end_log_trans(root);
9493 log_pinned = false;
9495 if (!ret && sync_log) {
9496 ret = btrfs_sync_log(trans, BTRFS_I(old_inode)->root, &ctx);
9497 if (ret)
9498 commit_transaction = true;
9499 } else if (sync_log) {
9500 mutex_lock(&root->log_mutex);
9501 list_del(&ctx.list);
9502 mutex_unlock(&root->log_mutex);
9504 if (commit_transaction) {
9505 ret = btrfs_commit_transaction(trans);
9506 } else {
9507 int ret2;
9509 ret2 = btrfs_end_transaction(trans);
9510 ret = ret ? ret : ret2;
9512 out_notrans:
9513 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9514 up_read(&fs_info->subvol_sem);
9516 return ret;
9519 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9520 struct inode *new_dir, struct dentry *new_dentry,
9521 unsigned int flags)
9523 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9524 return -EINVAL;
9526 if (flags & RENAME_EXCHANGE)
9527 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9528 new_dentry);
9530 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9533 struct btrfs_delalloc_work {
9534 struct inode *inode;
9535 struct completion completion;
9536 struct list_head list;
9537 struct btrfs_work work;
9540 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9542 struct btrfs_delalloc_work *delalloc_work;
9543 struct inode *inode;
9545 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9546 work);
9547 inode = delalloc_work->inode;
9548 filemap_flush(inode->i_mapping);
9549 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9550 &BTRFS_I(inode)->runtime_flags))
9551 filemap_flush(inode->i_mapping);
9553 iput(inode);
9554 complete(&delalloc_work->completion);
9557 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9559 struct btrfs_delalloc_work *work;
9561 work = kmalloc(sizeof(*work), GFP_NOFS);
9562 if (!work)
9563 return NULL;
9565 init_completion(&work->completion);
9566 INIT_LIST_HEAD(&work->list);
9567 work->inode = inode;
9568 btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
9570 return work;
9574 * some fairly slow code that needs optimization. This walks the list
9575 * of all the inodes with pending delalloc and forces them to disk.
9577 static int start_delalloc_inodes(struct btrfs_root *root, int nr, bool snapshot)
9579 struct btrfs_inode *binode;
9580 struct inode *inode;
9581 struct btrfs_delalloc_work *work, *next;
9582 struct list_head works;
9583 struct list_head splice;
9584 int ret = 0;
9586 INIT_LIST_HEAD(&works);
9587 INIT_LIST_HEAD(&splice);
9589 mutex_lock(&root->delalloc_mutex);
9590 spin_lock(&root->delalloc_lock);
9591 list_splice_init(&root->delalloc_inodes, &splice);
9592 while (!list_empty(&splice)) {
9593 binode = list_entry(splice.next, struct btrfs_inode,
9594 delalloc_inodes);
9596 list_move_tail(&binode->delalloc_inodes,
9597 &root->delalloc_inodes);
9598 inode = igrab(&binode->vfs_inode);
9599 if (!inode) {
9600 cond_resched_lock(&root->delalloc_lock);
9601 continue;
9603 spin_unlock(&root->delalloc_lock);
9605 if (snapshot)
9606 set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
9607 &binode->runtime_flags);
9608 work = btrfs_alloc_delalloc_work(inode);
9609 if (!work) {
9610 iput(inode);
9611 ret = -ENOMEM;
9612 goto out;
9614 list_add_tail(&work->list, &works);
9615 btrfs_queue_work(root->fs_info->flush_workers,
9616 &work->work);
9617 ret++;
9618 if (nr != -1 && ret >= nr)
9619 goto out;
9620 cond_resched();
9621 spin_lock(&root->delalloc_lock);
9623 spin_unlock(&root->delalloc_lock);
9625 out:
9626 list_for_each_entry_safe(work, next, &works, list) {
9627 list_del_init(&work->list);
9628 wait_for_completion(&work->completion);
9629 kfree(work);
9632 if (!list_empty(&splice)) {
9633 spin_lock(&root->delalloc_lock);
9634 list_splice_tail(&splice, &root->delalloc_inodes);
9635 spin_unlock(&root->delalloc_lock);
9637 mutex_unlock(&root->delalloc_mutex);
9638 return ret;
9641 int btrfs_start_delalloc_snapshot(struct btrfs_root *root)
9643 struct btrfs_fs_info *fs_info = root->fs_info;
9644 int ret;
9646 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9647 return -EROFS;
9649 ret = start_delalloc_inodes(root, -1, true);
9650 if (ret > 0)
9651 ret = 0;
9652 return ret;
9655 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
9657 struct btrfs_root *root;
9658 struct list_head splice;
9659 int ret;
9661 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9662 return -EROFS;
9664 INIT_LIST_HEAD(&splice);
9666 mutex_lock(&fs_info->delalloc_root_mutex);
9667 spin_lock(&fs_info->delalloc_root_lock);
9668 list_splice_init(&fs_info->delalloc_roots, &splice);
9669 while (!list_empty(&splice) && nr) {
9670 root = list_first_entry(&splice, struct btrfs_root,
9671 delalloc_root);
9672 root = btrfs_grab_fs_root(root);
9673 BUG_ON(!root);
9674 list_move_tail(&root->delalloc_root,
9675 &fs_info->delalloc_roots);
9676 spin_unlock(&fs_info->delalloc_root_lock);
9678 ret = start_delalloc_inodes(root, nr, false);
9679 btrfs_put_fs_root(root);
9680 if (ret < 0)
9681 goto out;
9683 if (nr != -1) {
9684 nr -= ret;
9685 WARN_ON(nr < 0);
9687 spin_lock(&fs_info->delalloc_root_lock);
9689 spin_unlock(&fs_info->delalloc_root_lock);
9691 ret = 0;
9692 out:
9693 if (!list_empty(&splice)) {
9694 spin_lock(&fs_info->delalloc_root_lock);
9695 list_splice_tail(&splice, &fs_info->delalloc_roots);
9696 spin_unlock(&fs_info->delalloc_root_lock);
9698 mutex_unlock(&fs_info->delalloc_root_mutex);
9699 return ret;
9702 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9703 const char *symname)
9705 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
9706 struct btrfs_trans_handle *trans;
9707 struct btrfs_root *root = BTRFS_I(dir)->root;
9708 struct btrfs_path *path;
9709 struct btrfs_key key;
9710 struct inode *inode = NULL;
9711 int err;
9712 u64 objectid;
9713 u64 index = 0;
9714 int name_len;
9715 int datasize;
9716 unsigned long ptr;
9717 struct btrfs_file_extent_item *ei;
9718 struct extent_buffer *leaf;
9720 name_len = strlen(symname);
9721 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
9722 return -ENAMETOOLONG;
9725 * 2 items for inode item and ref
9726 * 2 items for dir items
9727 * 1 item for updating parent inode item
9728 * 1 item for the inline extent item
9729 * 1 item for xattr if selinux is on
9731 trans = btrfs_start_transaction(root, 7);
9732 if (IS_ERR(trans))
9733 return PTR_ERR(trans);
9735 err = btrfs_find_free_ino(root, &objectid);
9736 if (err)
9737 goto out_unlock;
9739 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9740 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
9741 objectid, S_IFLNK|S_IRWXUGO, &index);
9742 if (IS_ERR(inode)) {
9743 err = PTR_ERR(inode);
9744 inode = NULL;
9745 goto out_unlock;
9749 * If the active LSM wants to access the inode during
9750 * d_instantiate it needs these. Smack checks to see
9751 * if the filesystem supports xattrs by looking at the
9752 * ops vector.
9754 inode->i_fop = &btrfs_file_operations;
9755 inode->i_op = &btrfs_file_inode_operations;
9756 inode->i_mapping->a_ops = &btrfs_aops;
9757 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9759 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9760 if (err)
9761 goto out_unlock;
9763 path = btrfs_alloc_path();
9764 if (!path) {
9765 err = -ENOMEM;
9766 goto out_unlock;
9768 key.objectid = btrfs_ino(BTRFS_I(inode));
9769 key.offset = 0;
9770 key.type = BTRFS_EXTENT_DATA_KEY;
9771 datasize = btrfs_file_extent_calc_inline_size(name_len);
9772 err = btrfs_insert_empty_item(trans, root, path, &key,
9773 datasize);
9774 if (err) {
9775 btrfs_free_path(path);
9776 goto out_unlock;
9778 leaf = path->nodes[0];
9779 ei = btrfs_item_ptr(leaf, path->slots[0],
9780 struct btrfs_file_extent_item);
9781 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9782 btrfs_set_file_extent_type(leaf, ei,
9783 BTRFS_FILE_EXTENT_INLINE);
9784 btrfs_set_file_extent_encryption(leaf, ei, 0);
9785 btrfs_set_file_extent_compression(leaf, ei, 0);
9786 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9787 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9789 ptr = btrfs_file_extent_inline_start(ei);
9790 write_extent_buffer(leaf, symname, ptr, name_len);
9791 btrfs_mark_buffer_dirty(leaf);
9792 btrfs_free_path(path);
9794 inode->i_op = &btrfs_symlink_inode_operations;
9795 inode_nohighmem(inode);
9796 inode_set_bytes(inode, name_len);
9797 btrfs_i_size_write(BTRFS_I(inode), name_len);
9798 err = btrfs_update_inode(trans, root, inode);
9800 * Last step, add directory indexes for our symlink inode. This is the
9801 * last step to avoid extra cleanup of these indexes if an error happens
9802 * elsewhere above.
9804 if (!err)
9805 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9806 BTRFS_I(inode), 0, index);
9807 if (err)
9808 goto out_unlock;
9810 d_instantiate_new(dentry, inode);
9812 out_unlock:
9813 btrfs_end_transaction(trans);
9814 if (err && inode) {
9815 inode_dec_link_count(inode);
9816 discard_new_inode(inode);
9818 btrfs_btree_balance_dirty(fs_info);
9819 return err;
9822 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9823 u64 start, u64 num_bytes, u64 min_size,
9824 loff_t actual_len, u64 *alloc_hint,
9825 struct btrfs_trans_handle *trans)
9827 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9828 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9829 struct extent_map *em;
9830 struct btrfs_root *root = BTRFS_I(inode)->root;
9831 struct btrfs_key ins;
9832 u64 cur_offset = start;
9833 u64 clear_offset = start;
9834 u64 i_size;
9835 u64 cur_bytes;
9836 u64 last_alloc = (u64)-1;
9837 int ret = 0;
9838 bool own_trans = true;
9839 u64 end = start + num_bytes - 1;
9841 if (trans)
9842 own_trans = false;
9843 while (num_bytes > 0) {
9844 if (own_trans) {
9845 trans = btrfs_start_transaction(root, 3);
9846 if (IS_ERR(trans)) {
9847 ret = PTR_ERR(trans);
9848 break;
9852 cur_bytes = min_t(u64, num_bytes, SZ_256M);
9853 cur_bytes = max(cur_bytes, min_size);
9855 * If we are severely fragmented we could end up with really
9856 * small allocations, so if the allocator is returning small
9857 * chunks lets make its job easier by only searching for those
9858 * sized chunks.
9860 cur_bytes = min(cur_bytes, last_alloc);
9861 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9862 min_size, 0, *alloc_hint, &ins, 1, 0);
9863 if (ret) {
9864 if (own_trans)
9865 btrfs_end_transaction(trans);
9866 break;
9870 * We've reserved this space, and thus converted it from
9871 * ->bytes_may_use to ->bytes_reserved. Any error that happens
9872 * from here on out we will only need to clear our reservation
9873 * for the remaining unreserved area, so advance our
9874 * clear_offset by our extent size.
9876 clear_offset += ins.offset;
9877 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9879 last_alloc = ins.offset;
9880 ret = insert_reserved_file_extent(trans, inode,
9881 cur_offset, ins.objectid,
9882 ins.offset, ins.offset,
9883 ins.offset, 0, 0, 0,
9884 BTRFS_FILE_EXTENT_PREALLOC);
9885 if (ret) {
9886 btrfs_free_reserved_extent(fs_info, ins.objectid,
9887 ins.offset, 0);
9888 btrfs_abort_transaction(trans, ret);
9889 if (own_trans)
9890 btrfs_end_transaction(trans);
9891 break;
9894 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9895 cur_offset + ins.offset -1, 0);
9897 em = alloc_extent_map();
9898 if (!em) {
9899 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9900 &BTRFS_I(inode)->runtime_flags);
9901 goto next;
9904 em->start = cur_offset;
9905 em->orig_start = cur_offset;
9906 em->len = ins.offset;
9907 em->block_start = ins.objectid;
9908 em->block_len = ins.offset;
9909 em->orig_block_len = ins.offset;
9910 em->ram_bytes = ins.offset;
9911 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9912 em->generation = trans->transid;
9914 while (1) {
9915 write_lock(&em_tree->lock);
9916 ret = add_extent_mapping(em_tree, em, 1);
9917 write_unlock(&em_tree->lock);
9918 if (ret != -EEXIST)
9919 break;
9920 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
9921 cur_offset + ins.offset - 1,
9924 free_extent_map(em);
9925 next:
9926 num_bytes -= ins.offset;
9927 cur_offset += ins.offset;
9928 *alloc_hint = ins.objectid + ins.offset;
9930 inode_inc_iversion(inode);
9931 inode->i_ctime = current_time(inode);
9932 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9933 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9934 (actual_len > inode->i_size) &&
9935 (cur_offset > inode->i_size)) {
9936 if (cur_offset > actual_len)
9937 i_size = actual_len;
9938 else
9939 i_size = cur_offset;
9940 i_size_write(inode, i_size);
9941 btrfs_ordered_update_i_size(inode, i_size, NULL);
9944 ret = btrfs_update_inode(trans, root, inode);
9946 if (ret) {
9947 btrfs_abort_transaction(trans, ret);
9948 if (own_trans)
9949 btrfs_end_transaction(trans);
9950 break;
9953 if (own_trans)
9954 btrfs_end_transaction(trans);
9956 if (clear_offset < end)
9957 btrfs_free_reserved_data_space(inode, NULL, clear_offset,
9958 end - clear_offset + 1);
9959 return ret;
9962 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9963 u64 start, u64 num_bytes, u64 min_size,
9964 loff_t actual_len, u64 *alloc_hint)
9966 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9967 min_size, actual_len, alloc_hint,
9968 NULL);
9971 int btrfs_prealloc_file_range_trans(struct inode *inode,
9972 struct btrfs_trans_handle *trans, int mode,
9973 u64 start, u64 num_bytes, u64 min_size,
9974 loff_t actual_len, u64 *alloc_hint)
9976 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9977 min_size, actual_len, alloc_hint, trans);
9980 static int btrfs_set_page_dirty(struct page *page)
9982 return __set_page_dirty_nobuffers(page);
9985 static int btrfs_permission(struct inode *inode, int mask)
9987 struct btrfs_root *root = BTRFS_I(inode)->root;
9988 umode_t mode = inode->i_mode;
9990 if (mask & MAY_WRITE &&
9991 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9992 if (btrfs_root_readonly(root))
9993 return -EROFS;
9994 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9995 return -EACCES;
9997 return generic_permission(inode, mask);
10000 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10002 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10003 struct btrfs_trans_handle *trans;
10004 struct btrfs_root *root = BTRFS_I(dir)->root;
10005 struct inode *inode = NULL;
10006 u64 objectid;
10007 u64 index;
10008 int ret = 0;
10011 * 5 units required for adding orphan entry
10013 trans = btrfs_start_transaction(root, 5);
10014 if (IS_ERR(trans))
10015 return PTR_ERR(trans);
10017 ret = btrfs_find_free_ino(root, &objectid);
10018 if (ret)
10019 goto out;
10021 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10022 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10023 if (IS_ERR(inode)) {
10024 ret = PTR_ERR(inode);
10025 inode = NULL;
10026 goto out;
10029 inode->i_fop = &btrfs_file_operations;
10030 inode->i_op = &btrfs_file_inode_operations;
10032 inode->i_mapping->a_ops = &btrfs_aops;
10033 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10035 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10036 if (ret)
10037 goto out;
10039 ret = btrfs_update_inode(trans, root, inode);
10040 if (ret)
10041 goto out;
10042 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10043 if (ret)
10044 goto out;
10047 * We set number of links to 0 in btrfs_new_inode(), and here we set
10048 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10049 * through:
10051 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10053 set_nlink(inode, 1);
10054 d_tmpfile(dentry, inode);
10055 unlock_new_inode(inode);
10056 mark_inode_dirty(inode);
10057 out:
10058 btrfs_end_transaction(trans);
10059 if (ret && inode)
10060 discard_new_inode(inode);
10061 btrfs_btree_balance_dirty(fs_info);
10062 return ret;
10065 void btrfs_set_range_writeback(struct extent_io_tree *tree, u64 start, u64 end)
10067 struct inode *inode = tree->private_data;
10068 unsigned long index = start >> PAGE_SHIFT;
10069 unsigned long end_index = end >> PAGE_SHIFT;
10070 struct page *page;
10072 while (index <= end_index) {
10073 page = find_get_page(inode->i_mapping, index);
10074 ASSERT(page); /* Pages should be in the extent_io_tree */
10075 set_page_writeback(page);
10076 put_page(page);
10077 index++;
10081 #ifdef CONFIG_SWAP
10083 * Add an entry indicating a block group or device which is pinned by a
10084 * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10085 * negative errno on failure.
10087 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10088 bool is_block_group)
10090 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10091 struct btrfs_swapfile_pin *sp, *entry;
10092 struct rb_node **p;
10093 struct rb_node *parent = NULL;
10095 sp = kmalloc(sizeof(*sp), GFP_NOFS);
10096 if (!sp)
10097 return -ENOMEM;
10098 sp->ptr = ptr;
10099 sp->inode = inode;
10100 sp->is_block_group = is_block_group;
10102 spin_lock(&fs_info->swapfile_pins_lock);
10103 p = &fs_info->swapfile_pins.rb_node;
10104 while (*p) {
10105 parent = *p;
10106 entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10107 if (sp->ptr < entry->ptr ||
10108 (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10109 p = &(*p)->rb_left;
10110 } else if (sp->ptr > entry->ptr ||
10111 (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10112 p = &(*p)->rb_right;
10113 } else {
10114 spin_unlock(&fs_info->swapfile_pins_lock);
10115 kfree(sp);
10116 return 1;
10119 rb_link_node(&sp->node, parent, p);
10120 rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10121 spin_unlock(&fs_info->swapfile_pins_lock);
10122 return 0;
10125 /* Free all of the entries pinned by this swapfile. */
10126 static void btrfs_free_swapfile_pins(struct inode *inode)
10128 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10129 struct btrfs_swapfile_pin *sp;
10130 struct rb_node *node, *next;
10132 spin_lock(&fs_info->swapfile_pins_lock);
10133 node = rb_first(&fs_info->swapfile_pins);
10134 while (node) {
10135 next = rb_next(node);
10136 sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10137 if (sp->inode == inode) {
10138 rb_erase(&sp->node, &fs_info->swapfile_pins);
10139 if (sp->is_block_group)
10140 btrfs_put_block_group(sp->ptr);
10141 kfree(sp);
10143 node = next;
10145 spin_unlock(&fs_info->swapfile_pins_lock);
10148 struct btrfs_swap_info {
10149 u64 start;
10150 u64 block_start;
10151 u64 block_len;
10152 u64 lowest_ppage;
10153 u64 highest_ppage;
10154 unsigned long nr_pages;
10155 int nr_extents;
10158 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10159 struct btrfs_swap_info *bsi)
10161 unsigned long nr_pages;
10162 u64 first_ppage, first_ppage_reported, next_ppage;
10163 int ret;
10165 first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
10166 next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
10167 PAGE_SIZE) >> PAGE_SHIFT;
10169 if (first_ppage >= next_ppage)
10170 return 0;
10171 nr_pages = next_ppage - first_ppage;
10173 first_ppage_reported = first_ppage;
10174 if (bsi->start == 0)
10175 first_ppage_reported++;
10176 if (bsi->lowest_ppage > first_ppage_reported)
10177 bsi->lowest_ppage = first_ppage_reported;
10178 if (bsi->highest_ppage < (next_ppage - 1))
10179 bsi->highest_ppage = next_ppage - 1;
10181 ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10182 if (ret < 0)
10183 return ret;
10184 bsi->nr_extents += ret;
10185 bsi->nr_pages += nr_pages;
10186 return 0;
10189 static void btrfs_swap_deactivate(struct file *file)
10191 struct inode *inode = file_inode(file);
10193 btrfs_free_swapfile_pins(inode);
10194 atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10197 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10198 sector_t *span)
10200 struct inode *inode = file_inode(file);
10201 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10202 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10203 struct extent_state *cached_state = NULL;
10204 struct extent_map *em = NULL;
10205 struct btrfs_device *device = NULL;
10206 struct btrfs_swap_info bsi = {
10207 .lowest_ppage = (sector_t)-1ULL,
10209 int ret = 0;
10210 u64 isize;
10211 u64 start;
10214 * If the swap file was just created, make sure delalloc is done. If the
10215 * file changes again after this, the user is doing something stupid and
10216 * we don't really care.
10218 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
10219 if (ret)
10220 return ret;
10223 * The inode is locked, so these flags won't change after we check them.
10225 if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10226 btrfs_warn(fs_info, "swapfile must not be compressed");
10227 return -EINVAL;
10229 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10230 btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10231 return -EINVAL;
10233 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10234 btrfs_warn(fs_info, "swapfile must not be checksummed");
10235 return -EINVAL;
10239 * Balance or device remove/replace/resize can move stuff around from
10240 * under us. The EXCL_OP flag makes sure they aren't running/won't run
10241 * concurrently while we are mapping the swap extents, and
10242 * fs_info->swapfile_pins prevents them from running while the swap file
10243 * is active and moving the extents. Note that this also prevents a
10244 * concurrent device add which isn't actually necessary, but it's not
10245 * really worth the trouble to allow it.
10247 if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
10248 btrfs_warn(fs_info,
10249 "cannot activate swapfile while exclusive operation is running");
10250 return -EBUSY;
10253 * Snapshots can create extents which require COW even if NODATACOW is
10254 * set. We use this counter to prevent snapshots. We must increment it
10255 * before walking the extents because we don't want a concurrent
10256 * snapshot to run after we've already checked the extents.
10258 atomic_inc(&BTRFS_I(inode)->root->nr_swapfiles);
10260 isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10262 lock_extent_bits(io_tree, 0, isize - 1, &cached_state);
10263 start = 0;
10264 while (start < isize) {
10265 u64 logical_block_start, physical_block_start;
10266 struct btrfs_block_group *bg;
10267 u64 len = isize - start;
10269 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
10270 if (IS_ERR(em)) {
10271 ret = PTR_ERR(em);
10272 goto out;
10275 if (em->block_start == EXTENT_MAP_HOLE) {
10276 btrfs_warn(fs_info, "swapfile must not have holes");
10277 ret = -EINVAL;
10278 goto out;
10280 if (em->block_start == EXTENT_MAP_INLINE) {
10282 * It's unlikely we'll ever actually find ourselves
10283 * here, as a file small enough to fit inline won't be
10284 * big enough to store more than the swap header, but in
10285 * case something changes in the future, let's catch it
10286 * here rather than later.
10288 btrfs_warn(fs_info, "swapfile must not be inline");
10289 ret = -EINVAL;
10290 goto out;
10292 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
10293 btrfs_warn(fs_info, "swapfile must not be compressed");
10294 ret = -EINVAL;
10295 goto out;
10298 logical_block_start = em->block_start + (start - em->start);
10299 len = min(len, em->len - (start - em->start));
10300 free_extent_map(em);
10301 em = NULL;
10303 ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL);
10304 if (ret < 0) {
10305 goto out;
10306 } else if (ret) {
10307 ret = 0;
10308 } else {
10309 btrfs_warn(fs_info,
10310 "swapfile must not be copy-on-write");
10311 ret = -EINVAL;
10312 goto out;
10315 em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10316 if (IS_ERR(em)) {
10317 ret = PTR_ERR(em);
10318 goto out;
10321 if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10322 btrfs_warn(fs_info,
10323 "swapfile must have single data profile");
10324 ret = -EINVAL;
10325 goto out;
10328 if (device == NULL) {
10329 device = em->map_lookup->stripes[0].dev;
10330 ret = btrfs_add_swapfile_pin(inode, device, false);
10331 if (ret == 1)
10332 ret = 0;
10333 else if (ret)
10334 goto out;
10335 } else if (device != em->map_lookup->stripes[0].dev) {
10336 btrfs_warn(fs_info, "swapfile must be on one device");
10337 ret = -EINVAL;
10338 goto out;
10341 physical_block_start = (em->map_lookup->stripes[0].physical +
10342 (logical_block_start - em->start));
10343 len = min(len, em->len - (logical_block_start - em->start));
10344 free_extent_map(em);
10345 em = NULL;
10347 bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10348 if (!bg) {
10349 btrfs_warn(fs_info,
10350 "could not find block group containing swapfile");
10351 ret = -EINVAL;
10352 goto out;
10355 ret = btrfs_add_swapfile_pin(inode, bg, true);
10356 if (ret) {
10357 btrfs_put_block_group(bg);
10358 if (ret == 1)
10359 ret = 0;
10360 else
10361 goto out;
10364 if (bsi.block_len &&
10365 bsi.block_start + bsi.block_len == physical_block_start) {
10366 bsi.block_len += len;
10367 } else {
10368 if (bsi.block_len) {
10369 ret = btrfs_add_swap_extent(sis, &bsi);
10370 if (ret)
10371 goto out;
10373 bsi.start = start;
10374 bsi.block_start = physical_block_start;
10375 bsi.block_len = len;
10378 start += len;
10381 if (bsi.block_len)
10382 ret = btrfs_add_swap_extent(sis, &bsi);
10384 out:
10385 if (!IS_ERR_OR_NULL(em))
10386 free_extent_map(em);
10388 unlock_extent_cached(io_tree, 0, isize - 1, &cached_state);
10390 if (ret)
10391 btrfs_swap_deactivate(file);
10393 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
10395 if (ret)
10396 return ret;
10398 if (device)
10399 sis->bdev = device->bdev;
10400 *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10401 sis->max = bsi.nr_pages;
10402 sis->pages = bsi.nr_pages - 1;
10403 sis->highest_bit = bsi.nr_pages - 1;
10404 return bsi.nr_extents;
10406 #else
10407 static void btrfs_swap_deactivate(struct file *file)
10411 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10412 sector_t *span)
10414 return -EOPNOTSUPP;
10416 #endif
10418 static const struct inode_operations btrfs_dir_inode_operations = {
10419 .getattr = btrfs_getattr,
10420 .lookup = btrfs_lookup,
10421 .create = btrfs_create,
10422 .unlink = btrfs_unlink,
10423 .link = btrfs_link,
10424 .mkdir = btrfs_mkdir,
10425 .rmdir = btrfs_rmdir,
10426 .rename = btrfs_rename2,
10427 .symlink = btrfs_symlink,
10428 .setattr = btrfs_setattr,
10429 .mknod = btrfs_mknod,
10430 .listxattr = btrfs_listxattr,
10431 .permission = btrfs_permission,
10432 .get_acl = btrfs_get_acl,
10433 .set_acl = btrfs_set_acl,
10434 .update_time = btrfs_update_time,
10435 .tmpfile = btrfs_tmpfile,
10438 static const struct file_operations btrfs_dir_file_operations = {
10439 .llseek = generic_file_llseek,
10440 .read = generic_read_dir,
10441 .iterate_shared = btrfs_real_readdir,
10442 .open = btrfs_opendir,
10443 .unlocked_ioctl = btrfs_ioctl,
10444 #ifdef CONFIG_COMPAT
10445 .compat_ioctl = btrfs_compat_ioctl,
10446 #endif
10447 .release = btrfs_release_file,
10448 .fsync = btrfs_sync_file,
10451 static const struct extent_io_ops btrfs_extent_io_ops = {
10452 /* mandatory callbacks */
10453 .submit_bio_hook = btrfs_submit_bio_hook,
10454 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10458 * btrfs doesn't support the bmap operation because swapfiles
10459 * use bmap to make a mapping of extents in the file. They assume
10460 * these extents won't change over the life of the file and they
10461 * use the bmap result to do IO directly to the drive.
10463 * the btrfs bmap call would return logical addresses that aren't
10464 * suitable for IO and they also will change frequently as COW
10465 * operations happen. So, swapfile + btrfs == corruption.
10467 * For now we're avoiding this by dropping bmap.
10469 static const struct address_space_operations btrfs_aops = {
10470 .readpage = btrfs_readpage,
10471 .writepage = btrfs_writepage,
10472 .writepages = btrfs_writepages,
10473 .readpages = btrfs_readpages,
10474 .direct_IO = btrfs_direct_IO,
10475 .invalidatepage = btrfs_invalidatepage,
10476 .releasepage = btrfs_releasepage,
10477 .set_page_dirty = btrfs_set_page_dirty,
10478 .error_remove_page = generic_error_remove_page,
10479 .swap_activate = btrfs_swap_activate,
10480 .swap_deactivate = btrfs_swap_deactivate,
10483 static const struct inode_operations btrfs_file_inode_operations = {
10484 .getattr = btrfs_getattr,
10485 .setattr = btrfs_setattr,
10486 .listxattr = btrfs_listxattr,
10487 .permission = btrfs_permission,
10488 .fiemap = btrfs_fiemap,
10489 .get_acl = btrfs_get_acl,
10490 .set_acl = btrfs_set_acl,
10491 .update_time = btrfs_update_time,
10493 static const struct inode_operations btrfs_special_inode_operations = {
10494 .getattr = btrfs_getattr,
10495 .setattr = btrfs_setattr,
10496 .permission = btrfs_permission,
10497 .listxattr = btrfs_listxattr,
10498 .get_acl = btrfs_get_acl,
10499 .set_acl = btrfs_set_acl,
10500 .update_time = btrfs_update_time,
10502 static const struct inode_operations btrfs_symlink_inode_operations = {
10503 .get_link = page_get_link,
10504 .getattr = btrfs_getattr,
10505 .setattr = btrfs_setattr,
10506 .permission = btrfs_permission,
10507 .listxattr = btrfs_listxattr,
10508 .update_time = btrfs_update_time,
10511 const struct dentry_operations btrfs_dentry_operations = {
10512 .d_delete = btrfs_dentry_delete,