Linux 4.18.10
[linux/fpc-iii.git] / fs / btrfs / inode.c
blob071d949f69eca427cf447aaff2d0271debbd6d5f
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/mpage.h>
18 #include <linux/swap.h>
19 #include <linux/writeback.h>
20 #include <linux/compat.h>
21 #include <linux/bit_spinlock.h>
22 #include <linux/xattr.h>
23 #include <linux/posix_acl.h>
24 #include <linux/falloc.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/mount.h>
28 #include <linux/btrfs.h>
29 #include <linux/blkdev.h>
30 #include <linux/posix_acl_xattr.h>
31 #include <linux/uio.h>
32 #include <linux/magic.h>
33 #include <linux/iversion.h>
34 #include <asm/unaligned.h>
35 #include "ctree.h"
36 #include "disk-io.h"
37 #include "transaction.h"
38 #include "btrfs_inode.h"
39 #include "print-tree.h"
40 #include "ordered-data.h"
41 #include "xattr.h"
42 #include "tree-log.h"
43 #include "volumes.h"
44 #include "compression.h"
45 #include "locking.h"
46 #include "free-space-cache.h"
47 #include "inode-map.h"
48 #include "backref.h"
49 #include "props.h"
50 #include "qgroup.h"
51 #include "dedupe.h"
53 struct btrfs_iget_args {
54 struct btrfs_key *location;
55 struct btrfs_root *root;
58 struct btrfs_dio_data {
59 u64 reserve;
60 u64 unsubmitted_oe_range_start;
61 u64 unsubmitted_oe_range_end;
62 int overwrite;
65 static const struct inode_operations btrfs_dir_inode_operations;
66 static const struct inode_operations btrfs_symlink_inode_operations;
67 static const struct inode_operations btrfs_dir_ro_inode_operations;
68 static const struct inode_operations btrfs_special_inode_operations;
69 static const struct inode_operations btrfs_file_inode_operations;
70 static const struct address_space_operations btrfs_aops;
71 static const struct address_space_operations btrfs_symlink_aops;
72 static const struct file_operations btrfs_dir_file_operations;
73 static const struct extent_io_ops btrfs_extent_io_ops;
75 static struct kmem_cache *btrfs_inode_cachep;
76 struct kmem_cache *btrfs_trans_handle_cachep;
77 struct kmem_cache *btrfs_path_cachep;
78 struct kmem_cache *btrfs_free_space_cachep;
80 #define S_SHIFT 12
81 static const unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
82 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
83 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
84 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
85 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
86 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
87 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
88 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
91 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
92 static int btrfs_truncate(struct inode *inode, bool skip_writeback);
93 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
94 static noinline int cow_file_range(struct inode *inode,
95 struct page *locked_page,
96 u64 start, u64 end, u64 delalloc_end,
97 int *page_started, unsigned long *nr_written,
98 int unlock, struct btrfs_dedupe_hash *hash);
99 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
100 u64 orig_start, u64 block_start,
101 u64 block_len, u64 orig_block_len,
102 u64 ram_bytes, int compress_type,
103 int type);
105 static void __endio_write_update_ordered(struct inode *inode,
106 const u64 offset, const u64 bytes,
107 const bool uptodate);
110 * Cleanup all submitted ordered extents in specified range to handle errors
111 * from the fill_dellaloc() callback.
113 * NOTE: caller must ensure that when an error happens, it can not call
114 * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
115 * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
116 * to be released, which we want to happen only when finishing the ordered
117 * extent (btrfs_finish_ordered_io()). Also note that the caller of the
118 * fill_delalloc() callback already does proper cleanup for the first page of
119 * the range, that is, it invokes the callback writepage_end_io_hook() for the
120 * range of the first page.
122 static inline void btrfs_cleanup_ordered_extents(struct inode *inode,
123 const u64 offset,
124 const u64 bytes)
126 unsigned long index = offset >> PAGE_SHIFT;
127 unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
128 struct page *page;
130 while (index <= end_index) {
131 page = find_get_page(inode->i_mapping, index);
132 index++;
133 if (!page)
134 continue;
135 ClearPagePrivate2(page);
136 put_page(page);
138 return __endio_write_update_ordered(inode, offset + PAGE_SIZE,
139 bytes - PAGE_SIZE, false);
142 static int btrfs_dirty_inode(struct inode *inode);
144 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
145 void btrfs_test_inode_set_ops(struct inode *inode)
147 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
149 #endif
151 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
152 struct inode *inode, struct inode *dir,
153 const struct qstr *qstr)
155 int err;
157 err = btrfs_init_acl(trans, inode, dir);
158 if (!err)
159 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
160 return err;
164 * this does all the hard work for inserting an inline extent into
165 * the btree. The caller should have done a btrfs_drop_extents so that
166 * no overlapping inline items exist in the btree
168 static int insert_inline_extent(struct btrfs_trans_handle *trans,
169 struct btrfs_path *path, int extent_inserted,
170 struct btrfs_root *root, struct inode *inode,
171 u64 start, size_t size, size_t compressed_size,
172 int compress_type,
173 struct page **compressed_pages)
175 struct extent_buffer *leaf;
176 struct page *page = NULL;
177 char *kaddr;
178 unsigned long ptr;
179 struct btrfs_file_extent_item *ei;
180 int ret;
181 size_t cur_size = size;
182 unsigned long offset;
184 if (compressed_size && compressed_pages)
185 cur_size = compressed_size;
187 inode_add_bytes(inode, size);
189 if (!extent_inserted) {
190 struct btrfs_key key;
191 size_t datasize;
193 key.objectid = btrfs_ino(BTRFS_I(inode));
194 key.offset = start;
195 key.type = BTRFS_EXTENT_DATA_KEY;
197 datasize = btrfs_file_extent_calc_inline_size(cur_size);
198 path->leave_spinning = 1;
199 ret = btrfs_insert_empty_item(trans, root, path, &key,
200 datasize);
201 if (ret)
202 goto fail;
204 leaf = path->nodes[0];
205 ei = btrfs_item_ptr(leaf, path->slots[0],
206 struct btrfs_file_extent_item);
207 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
208 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
209 btrfs_set_file_extent_encryption(leaf, ei, 0);
210 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
211 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
212 ptr = btrfs_file_extent_inline_start(ei);
214 if (compress_type != BTRFS_COMPRESS_NONE) {
215 struct page *cpage;
216 int i = 0;
217 while (compressed_size > 0) {
218 cpage = compressed_pages[i];
219 cur_size = min_t(unsigned long, compressed_size,
220 PAGE_SIZE);
222 kaddr = kmap_atomic(cpage);
223 write_extent_buffer(leaf, kaddr, ptr, cur_size);
224 kunmap_atomic(kaddr);
226 i++;
227 ptr += cur_size;
228 compressed_size -= cur_size;
230 btrfs_set_file_extent_compression(leaf, ei,
231 compress_type);
232 } else {
233 page = find_get_page(inode->i_mapping,
234 start >> PAGE_SHIFT);
235 btrfs_set_file_extent_compression(leaf, ei, 0);
236 kaddr = kmap_atomic(page);
237 offset = start & (PAGE_SIZE - 1);
238 write_extent_buffer(leaf, kaddr + offset, ptr, size);
239 kunmap_atomic(kaddr);
240 put_page(page);
242 btrfs_mark_buffer_dirty(leaf);
243 btrfs_release_path(path);
246 * we're an inline extent, so nobody can
247 * extend the file past i_size without locking
248 * a page we already have locked.
250 * We must do any isize and inode updates
251 * before we unlock the pages. Otherwise we
252 * could end up racing with unlink.
254 BTRFS_I(inode)->disk_i_size = inode->i_size;
255 ret = btrfs_update_inode(trans, root, inode);
257 fail:
258 return ret;
263 * conditionally insert an inline extent into the file. This
264 * does the checks required to make sure the data is small enough
265 * to fit as an inline extent.
267 static noinline int cow_file_range_inline(struct inode *inode, u64 start,
268 u64 end, size_t compressed_size,
269 int compress_type,
270 struct page **compressed_pages)
272 struct btrfs_root *root = BTRFS_I(inode)->root;
273 struct btrfs_fs_info *fs_info = root->fs_info;
274 struct btrfs_trans_handle *trans;
275 u64 isize = i_size_read(inode);
276 u64 actual_end = min(end + 1, isize);
277 u64 inline_len = actual_end - start;
278 u64 aligned_end = ALIGN(end, fs_info->sectorsize);
279 u64 data_len = inline_len;
280 int ret;
281 struct btrfs_path *path;
282 int extent_inserted = 0;
283 u32 extent_item_size;
285 if (compressed_size)
286 data_len = compressed_size;
288 if (start > 0 ||
289 actual_end > fs_info->sectorsize ||
290 data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
291 (!compressed_size &&
292 (actual_end & (fs_info->sectorsize - 1)) == 0) ||
293 end + 1 < isize ||
294 data_len > fs_info->max_inline) {
295 return 1;
298 path = btrfs_alloc_path();
299 if (!path)
300 return -ENOMEM;
302 trans = btrfs_join_transaction(root);
303 if (IS_ERR(trans)) {
304 btrfs_free_path(path);
305 return PTR_ERR(trans);
307 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
309 if (compressed_size && compressed_pages)
310 extent_item_size = btrfs_file_extent_calc_inline_size(
311 compressed_size);
312 else
313 extent_item_size = btrfs_file_extent_calc_inline_size(
314 inline_len);
316 ret = __btrfs_drop_extents(trans, root, inode, path,
317 start, aligned_end, NULL,
318 1, 1, extent_item_size, &extent_inserted);
319 if (ret) {
320 btrfs_abort_transaction(trans, ret);
321 goto out;
324 if (isize > actual_end)
325 inline_len = min_t(u64, isize, actual_end);
326 ret = insert_inline_extent(trans, path, extent_inserted,
327 root, inode, start,
328 inline_len, compressed_size,
329 compress_type, compressed_pages);
330 if (ret && ret != -ENOSPC) {
331 btrfs_abort_transaction(trans, ret);
332 goto out;
333 } else if (ret == -ENOSPC) {
334 ret = 1;
335 goto out;
338 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
339 btrfs_drop_extent_cache(BTRFS_I(inode), start, aligned_end - 1, 0);
340 out:
342 * Don't forget to free the reserved space, as for inlined extent
343 * it won't count as data extent, free them directly here.
344 * And at reserve time, it's always aligned to page size, so
345 * just free one page here.
347 btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
348 btrfs_free_path(path);
349 btrfs_end_transaction(trans);
350 return ret;
353 struct async_extent {
354 u64 start;
355 u64 ram_size;
356 u64 compressed_size;
357 struct page **pages;
358 unsigned long nr_pages;
359 int compress_type;
360 struct list_head list;
363 struct async_cow {
364 struct inode *inode;
365 struct btrfs_root *root;
366 struct page *locked_page;
367 u64 start;
368 u64 end;
369 unsigned int write_flags;
370 struct list_head extents;
371 struct btrfs_work work;
374 static noinline int add_async_extent(struct async_cow *cow,
375 u64 start, u64 ram_size,
376 u64 compressed_size,
377 struct page **pages,
378 unsigned long nr_pages,
379 int compress_type)
381 struct async_extent *async_extent;
383 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
384 BUG_ON(!async_extent); /* -ENOMEM */
385 async_extent->start = start;
386 async_extent->ram_size = ram_size;
387 async_extent->compressed_size = compressed_size;
388 async_extent->pages = pages;
389 async_extent->nr_pages = nr_pages;
390 async_extent->compress_type = compress_type;
391 list_add_tail(&async_extent->list, &cow->extents);
392 return 0;
395 static inline int inode_need_compress(struct inode *inode, u64 start, u64 end)
397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
399 /* force compress */
400 if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
401 return 1;
402 /* defrag ioctl */
403 if (BTRFS_I(inode)->defrag_compress)
404 return 1;
405 /* bad compression ratios */
406 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
407 return 0;
408 if (btrfs_test_opt(fs_info, COMPRESS) ||
409 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
410 BTRFS_I(inode)->prop_compress)
411 return btrfs_compress_heuristic(inode, start, end);
412 return 0;
415 static inline void inode_should_defrag(struct btrfs_inode *inode,
416 u64 start, u64 end, u64 num_bytes, u64 small_write)
418 /* If this is a small write inside eof, kick off a defrag */
419 if (num_bytes < small_write &&
420 (start > 0 || end + 1 < inode->disk_i_size))
421 btrfs_add_inode_defrag(NULL, inode);
425 * we create compressed extents in two phases. The first
426 * phase compresses a range of pages that have already been
427 * locked (both pages and state bits are locked).
429 * This is done inside an ordered work queue, and the compression
430 * is spread across many cpus. The actual IO submission is step
431 * two, and the ordered work queue takes care of making sure that
432 * happens in the same order things were put onto the queue by
433 * writepages and friends.
435 * If this code finds it can't get good compression, it puts an
436 * entry onto the work queue to write the uncompressed bytes. This
437 * makes sure that both compressed inodes and uncompressed inodes
438 * are written in the same order that the flusher thread sent them
439 * down.
441 static noinline void compress_file_range(struct inode *inode,
442 struct page *locked_page,
443 u64 start, u64 end,
444 struct async_cow *async_cow,
445 int *num_added)
447 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
448 u64 blocksize = fs_info->sectorsize;
449 u64 actual_end;
450 u64 isize = i_size_read(inode);
451 int ret = 0;
452 struct page **pages = NULL;
453 unsigned long nr_pages;
454 unsigned long total_compressed = 0;
455 unsigned long total_in = 0;
456 int i;
457 int will_compress;
458 int compress_type = fs_info->compress_type;
459 int redirty = 0;
461 inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
462 SZ_16K);
464 actual_end = min_t(u64, isize, end + 1);
465 again:
466 will_compress = 0;
467 nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
468 BUILD_BUG_ON((BTRFS_MAX_COMPRESSED % PAGE_SIZE) != 0);
469 nr_pages = min_t(unsigned long, nr_pages,
470 BTRFS_MAX_COMPRESSED / PAGE_SIZE);
473 * we don't want to send crud past the end of i_size through
474 * compression, that's just a waste of CPU time. So, if the
475 * end of the file is before the start of our current
476 * requested range of bytes, we bail out to the uncompressed
477 * cleanup code that can deal with all of this.
479 * It isn't really the fastest way to fix things, but this is a
480 * very uncommon corner.
482 if (actual_end <= start)
483 goto cleanup_and_bail_uncompressed;
485 total_compressed = actual_end - start;
488 * skip compression for a small file range(<=blocksize) that
489 * isn't an inline extent, since it doesn't save disk space at all.
491 if (total_compressed <= blocksize &&
492 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
493 goto cleanup_and_bail_uncompressed;
495 total_compressed = min_t(unsigned long, total_compressed,
496 BTRFS_MAX_UNCOMPRESSED);
497 total_in = 0;
498 ret = 0;
501 * we do compression for mount -o compress and when the
502 * inode has not been flagged as nocompress. This flag can
503 * change at any time if we discover bad compression ratios.
505 if (inode_need_compress(inode, start, end)) {
506 WARN_ON(pages);
507 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
508 if (!pages) {
509 /* just bail out to the uncompressed code */
510 goto cont;
513 if (BTRFS_I(inode)->defrag_compress)
514 compress_type = BTRFS_I(inode)->defrag_compress;
515 else if (BTRFS_I(inode)->prop_compress)
516 compress_type = BTRFS_I(inode)->prop_compress;
519 * we need to call clear_page_dirty_for_io on each
520 * page in the range. Otherwise applications with the file
521 * mmap'd can wander in and change the page contents while
522 * we are compressing them.
524 * If the compression fails for any reason, we set the pages
525 * dirty again later on.
527 * Note that the remaining part is redirtied, the start pointer
528 * has moved, the end is the original one.
530 if (!redirty) {
531 extent_range_clear_dirty_for_io(inode, start, end);
532 redirty = 1;
535 /* Compression level is applied here and only here */
536 ret = btrfs_compress_pages(
537 compress_type | (fs_info->compress_level << 4),
538 inode->i_mapping, start,
539 pages,
540 &nr_pages,
541 &total_in,
542 &total_compressed);
544 if (!ret) {
545 unsigned long offset = total_compressed &
546 (PAGE_SIZE - 1);
547 struct page *page = pages[nr_pages - 1];
548 char *kaddr;
550 /* zero the tail end of the last page, we might be
551 * sending it down to disk
553 if (offset) {
554 kaddr = kmap_atomic(page);
555 memset(kaddr + offset, 0,
556 PAGE_SIZE - offset);
557 kunmap_atomic(kaddr);
559 will_compress = 1;
562 cont:
563 if (start == 0) {
564 /* lets try to make an inline extent */
565 if (ret || total_in < actual_end) {
566 /* we didn't compress the entire range, try
567 * to make an uncompressed inline extent.
569 ret = cow_file_range_inline(inode, start, end, 0,
570 BTRFS_COMPRESS_NONE, NULL);
571 } else {
572 /* try making a compressed inline extent */
573 ret = cow_file_range_inline(inode, start, end,
574 total_compressed,
575 compress_type, pages);
577 if (ret <= 0) {
578 unsigned long clear_flags = EXTENT_DELALLOC |
579 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
580 EXTENT_DO_ACCOUNTING;
581 unsigned long page_error_op;
583 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
586 * inline extent creation worked or returned error,
587 * we don't need to create any more async work items.
588 * Unlock and free up our temp pages.
590 * We use DO_ACCOUNTING here because we need the
591 * delalloc_release_metadata to be done _after_ we drop
592 * our outstanding extent for clearing delalloc for this
593 * range.
595 extent_clear_unlock_delalloc(inode, start, end, end,
596 NULL, clear_flags,
597 PAGE_UNLOCK |
598 PAGE_CLEAR_DIRTY |
599 PAGE_SET_WRITEBACK |
600 page_error_op |
601 PAGE_END_WRITEBACK);
602 goto free_pages_out;
606 if (will_compress) {
608 * we aren't doing an inline extent round the compressed size
609 * up to a block size boundary so the allocator does sane
610 * things
612 total_compressed = ALIGN(total_compressed, blocksize);
615 * one last check to make sure the compression is really a
616 * win, compare the page count read with the blocks on disk,
617 * compression must free at least one sector size
619 total_in = ALIGN(total_in, PAGE_SIZE);
620 if (total_compressed + blocksize <= total_in) {
621 *num_added += 1;
624 * The async work queues will take care of doing actual
625 * allocation on disk for these compressed pages, and
626 * will submit them to the elevator.
628 add_async_extent(async_cow, start, total_in,
629 total_compressed, pages, nr_pages,
630 compress_type);
632 if (start + total_in < end) {
633 start += total_in;
634 pages = NULL;
635 cond_resched();
636 goto again;
638 return;
641 if (pages) {
643 * the compression code ran but failed to make things smaller,
644 * free any pages it allocated and our page pointer array
646 for (i = 0; i < nr_pages; i++) {
647 WARN_ON(pages[i]->mapping);
648 put_page(pages[i]);
650 kfree(pages);
651 pages = NULL;
652 total_compressed = 0;
653 nr_pages = 0;
655 /* flag the file so we don't compress in the future */
656 if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
657 !(BTRFS_I(inode)->prop_compress)) {
658 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
661 cleanup_and_bail_uncompressed:
663 * No compression, but we still need to write the pages in the file
664 * we've been given so far. redirty the locked page if it corresponds
665 * to our extent and set things up for the async work queue to run
666 * cow_file_range to do the normal delalloc dance.
668 if (page_offset(locked_page) >= start &&
669 page_offset(locked_page) <= end)
670 __set_page_dirty_nobuffers(locked_page);
671 /* unlocked later on in the async handlers */
673 if (redirty)
674 extent_range_redirty_for_io(inode, start, end);
675 add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0,
676 BTRFS_COMPRESS_NONE);
677 *num_added += 1;
679 return;
681 free_pages_out:
682 for (i = 0; i < nr_pages; i++) {
683 WARN_ON(pages[i]->mapping);
684 put_page(pages[i]);
686 kfree(pages);
689 static void free_async_extent_pages(struct async_extent *async_extent)
691 int i;
693 if (!async_extent->pages)
694 return;
696 for (i = 0; i < async_extent->nr_pages; i++) {
697 WARN_ON(async_extent->pages[i]->mapping);
698 put_page(async_extent->pages[i]);
700 kfree(async_extent->pages);
701 async_extent->nr_pages = 0;
702 async_extent->pages = NULL;
706 * phase two of compressed writeback. This is the ordered portion
707 * of the code, which only gets called in the order the work was
708 * queued. We walk all the async extents created by compress_file_range
709 * and send them down to the disk.
711 static noinline void submit_compressed_extents(struct inode *inode,
712 struct async_cow *async_cow)
714 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
715 struct async_extent *async_extent;
716 u64 alloc_hint = 0;
717 struct btrfs_key ins;
718 struct extent_map *em;
719 struct btrfs_root *root = BTRFS_I(inode)->root;
720 struct extent_io_tree *io_tree;
721 int ret = 0;
723 again:
724 while (!list_empty(&async_cow->extents)) {
725 async_extent = list_entry(async_cow->extents.next,
726 struct async_extent, list);
727 list_del(&async_extent->list);
729 io_tree = &BTRFS_I(inode)->io_tree;
731 retry:
732 /* did the compression code fall back to uncompressed IO? */
733 if (!async_extent->pages) {
734 int page_started = 0;
735 unsigned long nr_written = 0;
737 lock_extent(io_tree, async_extent->start,
738 async_extent->start +
739 async_extent->ram_size - 1);
741 /* allocate blocks */
742 ret = cow_file_range(inode, async_cow->locked_page,
743 async_extent->start,
744 async_extent->start +
745 async_extent->ram_size - 1,
746 async_extent->start +
747 async_extent->ram_size - 1,
748 &page_started, &nr_written, 0,
749 NULL);
751 /* JDM XXX */
754 * if page_started, cow_file_range inserted an
755 * inline extent and took care of all the unlocking
756 * and IO for us. Otherwise, we need to submit
757 * all those pages down to the drive.
759 if (!page_started && !ret)
760 extent_write_locked_range(inode,
761 async_extent->start,
762 async_extent->start +
763 async_extent->ram_size - 1,
764 WB_SYNC_ALL);
765 else if (ret)
766 unlock_page(async_cow->locked_page);
767 kfree(async_extent);
768 cond_resched();
769 continue;
772 lock_extent(io_tree, async_extent->start,
773 async_extent->start + async_extent->ram_size - 1);
775 ret = btrfs_reserve_extent(root, async_extent->ram_size,
776 async_extent->compressed_size,
777 async_extent->compressed_size,
778 0, alloc_hint, &ins, 1, 1);
779 if (ret) {
780 free_async_extent_pages(async_extent);
782 if (ret == -ENOSPC) {
783 unlock_extent(io_tree, async_extent->start,
784 async_extent->start +
785 async_extent->ram_size - 1);
788 * we need to redirty the pages if we decide to
789 * fallback to uncompressed IO, otherwise we
790 * will not submit these pages down to lower
791 * layers.
793 extent_range_redirty_for_io(inode,
794 async_extent->start,
795 async_extent->start +
796 async_extent->ram_size - 1);
798 goto retry;
800 goto out_free;
803 * here we're doing allocation and writeback of the
804 * compressed pages
806 em = create_io_em(inode, async_extent->start,
807 async_extent->ram_size, /* len */
808 async_extent->start, /* orig_start */
809 ins.objectid, /* block_start */
810 ins.offset, /* block_len */
811 ins.offset, /* orig_block_len */
812 async_extent->ram_size, /* ram_bytes */
813 async_extent->compress_type,
814 BTRFS_ORDERED_COMPRESSED);
815 if (IS_ERR(em))
816 /* ret value is not necessary due to void function */
817 goto out_free_reserve;
818 free_extent_map(em);
820 ret = btrfs_add_ordered_extent_compress(inode,
821 async_extent->start,
822 ins.objectid,
823 async_extent->ram_size,
824 ins.offset,
825 BTRFS_ORDERED_COMPRESSED,
826 async_extent->compress_type);
827 if (ret) {
828 btrfs_drop_extent_cache(BTRFS_I(inode),
829 async_extent->start,
830 async_extent->start +
831 async_extent->ram_size - 1, 0);
832 goto out_free_reserve;
834 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
837 * clear dirty, set writeback and unlock the pages.
839 extent_clear_unlock_delalloc(inode, async_extent->start,
840 async_extent->start +
841 async_extent->ram_size - 1,
842 async_extent->start +
843 async_extent->ram_size - 1,
844 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
845 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
846 PAGE_SET_WRITEBACK);
847 if (btrfs_submit_compressed_write(inode,
848 async_extent->start,
849 async_extent->ram_size,
850 ins.objectid,
851 ins.offset, async_extent->pages,
852 async_extent->nr_pages,
853 async_cow->write_flags)) {
854 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
855 struct page *p = async_extent->pages[0];
856 const u64 start = async_extent->start;
857 const u64 end = start + async_extent->ram_size - 1;
859 p->mapping = inode->i_mapping;
860 tree->ops->writepage_end_io_hook(p, start, end,
861 NULL, 0);
862 p->mapping = NULL;
863 extent_clear_unlock_delalloc(inode, start, end, end,
864 NULL, 0,
865 PAGE_END_WRITEBACK |
866 PAGE_SET_ERROR);
867 free_async_extent_pages(async_extent);
869 alloc_hint = ins.objectid + ins.offset;
870 kfree(async_extent);
871 cond_resched();
873 return;
874 out_free_reserve:
875 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
876 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
877 out_free:
878 extent_clear_unlock_delalloc(inode, async_extent->start,
879 async_extent->start +
880 async_extent->ram_size - 1,
881 async_extent->start +
882 async_extent->ram_size - 1,
883 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
884 EXTENT_DELALLOC_NEW |
885 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
886 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
887 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
888 PAGE_SET_ERROR);
889 free_async_extent_pages(async_extent);
890 kfree(async_extent);
891 goto again;
894 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
895 u64 num_bytes)
897 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
898 struct extent_map *em;
899 u64 alloc_hint = 0;
901 read_lock(&em_tree->lock);
902 em = search_extent_mapping(em_tree, start, num_bytes);
903 if (em) {
905 * if block start isn't an actual block number then find the
906 * first block in this inode and use that as a hint. If that
907 * block is also bogus then just don't worry about it.
909 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
910 free_extent_map(em);
911 em = search_extent_mapping(em_tree, 0, 0);
912 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
913 alloc_hint = em->block_start;
914 if (em)
915 free_extent_map(em);
916 } else {
917 alloc_hint = em->block_start;
918 free_extent_map(em);
921 read_unlock(&em_tree->lock);
923 return alloc_hint;
927 * when extent_io.c finds a delayed allocation range in the file,
928 * the call backs end up in this code. The basic idea is to
929 * allocate extents on disk for the range, and create ordered data structs
930 * in ram to track those extents.
932 * locked_page is the page that writepage had locked already. We use
933 * it to make sure we don't do extra locks or unlocks.
935 * *page_started is set to one if we unlock locked_page and do everything
936 * required to start IO on it. It may be clean and already done with
937 * IO when we return.
939 static noinline int cow_file_range(struct inode *inode,
940 struct page *locked_page,
941 u64 start, u64 end, u64 delalloc_end,
942 int *page_started, unsigned long *nr_written,
943 int unlock, struct btrfs_dedupe_hash *hash)
945 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
946 struct btrfs_root *root = BTRFS_I(inode)->root;
947 u64 alloc_hint = 0;
948 u64 num_bytes;
949 unsigned long ram_size;
950 u64 cur_alloc_size = 0;
951 u64 blocksize = fs_info->sectorsize;
952 struct btrfs_key ins;
953 struct extent_map *em;
954 unsigned clear_bits;
955 unsigned long page_ops;
956 bool extent_reserved = false;
957 int ret = 0;
959 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
960 WARN_ON_ONCE(1);
961 ret = -EINVAL;
962 goto out_unlock;
965 num_bytes = ALIGN(end - start + 1, blocksize);
966 num_bytes = max(blocksize, num_bytes);
967 ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
969 inode_should_defrag(BTRFS_I(inode), start, end, num_bytes, SZ_64K);
971 if (start == 0) {
972 /* lets try to make an inline extent */
973 ret = cow_file_range_inline(inode, start, end, 0,
974 BTRFS_COMPRESS_NONE, NULL);
975 if (ret == 0) {
977 * We use DO_ACCOUNTING here because we need the
978 * delalloc_release_metadata to be run _after_ we drop
979 * our outstanding extent for clearing delalloc for this
980 * range.
982 extent_clear_unlock_delalloc(inode, start, end,
983 delalloc_end, NULL,
984 EXTENT_LOCKED | EXTENT_DELALLOC |
985 EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
986 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
987 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
988 PAGE_END_WRITEBACK);
989 *nr_written = *nr_written +
990 (end - start + PAGE_SIZE) / PAGE_SIZE;
991 *page_started = 1;
992 goto out;
993 } else if (ret < 0) {
994 goto out_unlock;
998 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
999 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1000 start + num_bytes - 1, 0);
1002 while (num_bytes > 0) {
1003 cur_alloc_size = num_bytes;
1004 ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
1005 fs_info->sectorsize, 0, alloc_hint,
1006 &ins, 1, 1);
1007 if (ret < 0)
1008 goto out_unlock;
1009 cur_alloc_size = ins.offset;
1010 extent_reserved = true;
1012 ram_size = ins.offset;
1013 em = create_io_em(inode, start, ins.offset, /* len */
1014 start, /* orig_start */
1015 ins.objectid, /* block_start */
1016 ins.offset, /* block_len */
1017 ins.offset, /* orig_block_len */
1018 ram_size, /* ram_bytes */
1019 BTRFS_COMPRESS_NONE, /* compress_type */
1020 BTRFS_ORDERED_REGULAR /* type */);
1021 if (IS_ERR(em)) {
1022 ret = PTR_ERR(em);
1023 goto out_reserve;
1025 free_extent_map(em);
1027 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1028 ram_size, cur_alloc_size, 0);
1029 if (ret)
1030 goto out_drop_extent_cache;
1032 if (root->root_key.objectid ==
1033 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1034 ret = btrfs_reloc_clone_csums(inode, start,
1035 cur_alloc_size);
1037 * Only drop cache here, and process as normal.
1039 * We must not allow extent_clear_unlock_delalloc()
1040 * at out_unlock label to free meta of this ordered
1041 * extent, as its meta should be freed by
1042 * btrfs_finish_ordered_io().
1044 * So we must continue until @start is increased to
1045 * skip current ordered extent.
1047 if (ret)
1048 btrfs_drop_extent_cache(BTRFS_I(inode), start,
1049 start + ram_size - 1, 0);
1052 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1054 /* we're not doing compressed IO, don't unlock the first
1055 * page (which the caller expects to stay locked), don't
1056 * clear any dirty bits and don't set any writeback bits
1058 * Do set the Private2 bit so we know this page was properly
1059 * setup for writepage
1061 page_ops = unlock ? PAGE_UNLOCK : 0;
1062 page_ops |= PAGE_SET_PRIVATE2;
1064 extent_clear_unlock_delalloc(inode, start,
1065 start + ram_size - 1,
1066 delalloc_end, locked_page,
1067 EXTENT_LOCKED | EXTENT_DELALLOC,
1068 page_ops);
1069 if (num_bytes < cur_alloc_size)
1070 num_bytes = 0;
1071 else
1072 num_bytes -= cur_alloc_size;
1073 alloc_hint = ins.objectid + ins.offset;
1074 start += cur_alloc_size;
1075 extent_reserved = false;
1078 * btrfs_reloc_clone_csums() error, since start is increased
1079 * extent_clear_unlock_delalloc() at out_unlock label won't
1080 * free metadata of current ordered extent, we're OK to exit.
1082 if (ret)
1083 goto out_unlock;
1085 out:
1086 return ret;
1088 out_drop_extent_cache:
1089 btrfs_drop_extent_cache(BTRFS_I(inode), start, start + ram_size - 1, 0);
1090 out_reserve:
1091 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1092 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
1093 out_unlock:
1094 clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1095 EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1096 page_ops = PAGE_UNLOCK | PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
1097 PAGE_END_WRITEBACK;
1099 * If we reserved an extent for our delalloc range (or a subrange) and
1100 * failed to create the respective ordered extent, then it means that
1101 * when we reserved the extent we decremented the extent's size from
1102 * the data space_info's bytes_may_use counter and incremented the
1103 * space_info's bytes_reserved counter by the same amount. We must make
1104 * sure extent_clear_unlock_delalloc() does not try to decrement again
1105 * the data space_info's bytes_may_use counter, therefore we do not pass
1106 * it the flag EXTENT_CLEAR_DATA_RESV.
1108 if (extent_reserved) {
1109 extent_clear_unlock_delalloc(inode, start,
1110 start + cur_alloc_size,
1111 start + cur_alloc_size,
1112 locked_page,
1113 clear_bits,
1114 page_ops);
1115 start += cur_alloc_size;
1116 if (start >= end)
1117 goto out;
1119 extent_clear_unlock_delalloc(inode, start, end, delalloc_end,
1120 locked_page,
1121 clear_bits | EXTENT_CLEAR_DATA_RESV,
1122 page_ops);
1123 goto out;
1127 * work queue call back to started compression on a file and pages
1129 static noinline void async_cow_start(struct btrfs_work *work)
1131 struct async_cow *async_cow;
1132 int num_added = 0;
1133 async_cow = container_of(work, struct async_cow, work);
1135 compress_file_range(async_cow->inode, async_cow->locked_page,
1136 async_cow->start, async_cow->end, async_cow,
1137 &num_added);
1138 if (num_added == 0) {
1139 btrfs_add_delayed_iput(async_cow->inode);
1140 async_cow->inode = NULL;
1145 * work queue call back to submit previously compressed pages
1147 static noinline void async_cow_submit(struct btrfs_work *work)
1149 struct btrfs_fs_info *fs_info;
1150 struct async_cow *async_cow;
1151 struct btrfs_root *root;
1152 unsigned long nr_pages;
1154 async_cow = container_of(work, struct async_cow, work);
1156 root = async_cow->root;
1157 fs_info = root->fs_info;
1158 nr_pages = (async_cow->end - async_cow->start + PAGE_SIZE) >>
1159 PAGE_SHIFT;
1161 /* atomic_sub_return implies a barrier */
1162 if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1163 5 * SZ_1M)
1164 cond_wake_up_nomb(&fs_info->async_submit_wait);
1166 if (async_cow->inode)
1167 submit_compressed_extents(async_cow->inode, async_cow);
1170 static noinline void async_cow_free(struct btrfs_work *work)
1172 struct async_cow *async_cow;
1173 async_cow = container_of(work, struct async_cow, work);
1174 if (async_cow->inode)
1175 btrfs_add_delayed_iput(async_cow->inode);
1176 kfree(async_cow);
1179 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1180 u64 start, u64 end, int *page_started,
1181 unsigned long *nr_written,
1182 unsigned int write_flags)
1184 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1185 struct async_cow *async_cow;
1186 struct btrfs_root *root = BTRFS_I(inode)->root;
1187 unsigned long nr_pages;
1188 u64 cur_end;
1190 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1191 1, 0, NULL);
1192 while (start < end) {
1193 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1194 BUG_ON(!async_cow); /* -ENOMEM */
1195 async_cow->inode = igrab(inode);
1196 async_cow->root = root;
1197 async_cow->locked_page = locked_page;
1198 async_cow->start = start;
1199 async_cow->write_flags = write_flags;
1201 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1202 !btrfs_test_opt(fs_info, FORCE_COMPRESS))
1203 cur_end = end;
1204 else
1205 cur_end = min(end, start + SZ_512K - 1);
1207 async_cow->end = cur_end;
1208 INIT_LIST_HEAD(&async_cow->extents);
1210 btrfs_init_work(&async_cow->work,
1211 btrfs_delalloc_helper,
1212 async_cow_start, async_cow_submit,
1213 async_cow_free);
1215 nr_pages = (cur_end - start + PAGE_SIZE) >>
1216 PAGE_SHIFT;
1217 atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1219 btrfs_queue_work(fs_info->delalloc_workers, &async_cow->work);
1221 *nr_written += nr_pages;
1222 start = cur_end + 1;
1224 *page_started = 1;
1225 return 0;
1228 static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
1229 u64 bytenr, u64 num_bytes)
1231 int ret;
1232 struct btrfs_ordered_sum *sums;
1233 LIST_HEAD(list);
1235 ret = btrfs_lookup_csums_range(fs_info->csum_root, bytenr,
1236 bytenr + num_bytes - 1, &list, 0);
1237 if (ret == 0 && list_empty(&list))
1238 return 0;
1240 while (!list_empty(&list)) {
1241 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1242 list_del(&sums->list);
1243 kfree(sums);
1245 if (ret < 0)
1246 return ret;
1247 return 1;
1251 * when nowcow writeback call back. This checks for snapshots or COW copies
1252 * of the extents that exist in the file, and COWs the file as required.
1254 * If no cow copies or snapshots exist, we write directly to the existing
1255 * blocks on disk
1257 static noinline int run_delalloc_nocow(struct inode *inode,
1258 struct page *locked_page,
1259 u64 start, u64 end, int *page_started, int force,
1260 unsigned long *nr_written)
1262 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1263 struct btrfs_root *root = BTRFS_I(inode)->root;
1264 struct extent_buffer *leaf;
1265 struct btrfs_path *path;
1266 struct btrfs_file_extent_item *fi;
1267 struct btrfs_key found_key;
1268 struct extent_map *em;
1269 u64 cow_start;
1270 u64 cur_offset;
1271 u64 extent_end;
1272 u64 extent_offset;
1273 u64 disk_bytenr;
1274 u64 num_bytes;
1275 u64 disk_num_bytes;
1276 u64 ram_bytes;
1277 int extent_type;
1278 int ret, err;
1279 int type;
1280 int nocow;
1281 int check_prev = 1;
1282 bool nolock;
1283 u64 ino = btrfs_ino(BTRFS_I(inode));
1285 path = btrfs_alloc_path();
1286 if (!path) {
1287 extent_clear_unlock_delalloc(inode, start, end, end,
1288 locked_page,
1289 EXTENT_LOCKED | EXTENT_DELALLOC |
1290 EXTENT_DO_ACCOUNTING |
1291 EXTENT_DEFRAG, PAGE_UNLOCK |
1292 PAGE_CLEAR_DIRTY |
1293 PAGE_SET_WRITEBACK |
1294 PAGE_END_WRITEBACK);
1295 return -ENOMEM;
1298 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
1300 cow_start = (u64)-1;
1301 cur_offset = start;
1302 while (1) {
1303 ret = btrfs_lookup_file_extent(NULL, root, path, ino,
1304 cur_offset, 0);
1305 if (ret < 0)
1306 goto error;
1307 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1308 leaf = path->nodes[0];
1309 btrfs_item_key_to_cpu(leaf, &found_key,
1310 path->slots[0] - 1);
1311 if (found_key.objectid == ino &&
1312 found_key.type == BTRFS_EXTENT_DATA_KEY)
1313 path->slots[0]--;
1315 check_prev = 0;
1316 next_slot:
1317 leaf = path->nodes[0];
1318 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1319 ret = btrfs_next_leaf(root, path);
1320 if (ret < 0) {
1321 if (cow_start != (u64)-1)
1322 cur_offset = cow_start;
1323 goto error;
1325 if (ret > 0)
1326 break;
1327 leaf = path->nodes[0];
1330 nocow = 0;
1331 disk_bytenr = 0;
1332 num_bytes = 0;
1333 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1335 if (found_key.objectid > ino)
1336 break;
1337 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1338 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1339 path->slots[0]++;
1340 goto next_slot;
1342 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1343 found_key.offset > end)
1344 break;
1346 if (found_key.offset > cur_offset) {
1347 extent_end = found_key.offset;
1348 extent_type = 0;
1349 goto out_check;
1352 fi = btrfs_item_ptr(leaf, path->slots[0],
1353 struct btrfs_file_extent_item);
1354 extent_type = btrfs_file_extent_type(leaf, fi);
1356 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1357 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1358 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1359 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1360 extent_offset = btrfs_file_extent_offset(leaf, fi);
1361 extent_end = found_key.offset +
1362 btrfs_file_extent_num_bytes(leaf, fi);
1363 disk_num_bytes =
1364 btrfs_file_extent_disk_num_bytes(leaf, fi);
1365 if (extent_end <= start) {
1366 path->slots[0]++;
1367 goto next_slot;
1369 if (disk_bytenr == 0)
1370 goto out_check;
1371 if (btrfs_file_extent_compression(leaf, fi) ||
1372 btrfs_file_extent_encryption(leaf, fi) ||
1373 btrfs_file_extent_other_encoding(leaf, fi))
1374 goto out_check;
1376 * Do the same check as in btrfs_cross_ref_exist but
1377 * without the unnecessary search.
1379 if (btrfs_file_extent_generation(leaf, fi) <=
1380 btrfs_root_last_snapshot(&root->root_item))
1381 goto out_check;
1382 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1383 goto out_check;
1384 if (btrfs_extent_readonly(fs_info, disk_bytenr))
1385 goto out_check;
1386 ret = btrfs_cross_ref_exist(root, ino,
1387 found_key.offset -
1388 extent_offset, disk_bytenr);
1389 if (ret) {
1391 * ret could be -EIO if the above fails to read
1392 * metadata.
1394 if (ret < 0) {
1395 if (cow_start != (u64)-1)
1396 cur_offset = cow_start;
1397 goto error;
1400 WARN_ON_ONCE(nolock);
1401 goto out_check;
1403 disk_bytenr += extent_offset;
1404 disk_bytenr += cur_offset - found_key.offset;
1405 num_bytes = min(end + 1, extent_end) - cur_offset;
1407 * if there are pending snapshots for this root,
1408 * we fall into common COW way.
1410 if (!nolock) {
1411 err = btrfs_start_write_no_snapshotting(root);
1412 if (!err)
1413 goto out_check;
1416 * force cow if csum exists in the range.
1417 * this ensure that csum for a given extent are
1418 * either valid or do not exist.
1420 ret = csum_exist_in_range(fs_info, disk_bytenr,
1421 num_bytes);
1422 if (ret) {
1423 if (!nolock)
1424 btrfs_end_write_no_snapshotting(root);
1427 * ret could be -EIO if the above fails to read
1428 * metadata.
1430 if (ret < 0) {
1431 if (cow_start != (u64)-1)
1432 cur_offset = cow_start;
1433 goto error;
1435 WARN_ON_ONCE(nolock);
1436 goto out_check;
1438 if (!btrfs_inc_nocow_writers(fs_info, disk_bytenr)) {
1439 if (!nolock)
1440 btrfs_end_write_no_snapshotting(root);
1441 goto out_check;
1443 nocow = 1;
1444 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1445 extent_end = found_key.offset +
1446 btrfs_file_extent_inline_len(leaf,
1447 path->slots[0], fi);
1448 extent_end = ALIGN(extent_end,
1449 fs_info->sectorsize);
1450 } else {
1451 BUG_ON(1);
1453 out_check:
1454 if (extent_end <= start) {
1455 path->slots[0]++;
1456 if (!nolock && nocow)
1457 btrfs_end_write_no_snapshotting(root);
1458 if (nocow)
1459 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1460 goto next_slot;
1462 if (!nocow) {
1463 if (cow_start == (u64)-1)
1464 cow_start = cur_offset;
1465 cur_offset = extent_end;
1466 if (cur_offset > end)
1467 break;
1468 path->slots[0]++;
1469 goto next_slot;
1472 btrfs_release_path(path);
1473 if (cow_start != (u64)-1) {
1474 ret = cow_file_range(inode, locked_page,
1475 cow_start, found_key.offset - 1,
1476 end, page_started, nr_written, 1,
1477 NULL);
1478 if (ret) {
1479 if (!nolock && nocow)
1480 btrfs_end_write_no_snapshotting(root);
1481 if (nocow)
1482 btrfs_dec_nocow_writers(fs_info,
1483 disk_bytenr);
1484 goto error;
1486 cow_start = (u64)-1;
1489 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1490 u64 orig_start = found_key.offset - extent_offset;
1492 em = create_io_em(inode, cur_offset, num_bytes,
1493 orig_start,
1494 disk_bytenr, /* block_start */
1495 num_bytes, /* block_len */
1496 disk_num_bytes, /* orig_block_len */
1497 ram_bytes, BTRFS_COMPRESS_NONE,
1498 BTRFS_ORDERED_PREALLOC);
1499 if (IS_ERR(em)) {
1500 if (!nolock && nocow)
1501 btrfs_end_write_no_snapshotting(root);
1502 if (nocow)
1503 btrfs_dec_nocow_writers(fs_info,
1504 disk_bytenr);
1505 ret = PTR_ERR(em);
1506 goto error;
1508 free_extent_map(em);
1511 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1512 type = BTRFS_ORDERED_PREALLOC;
1513 } else {
1514 type = BTRFS_ORDERED_NOCOW;
1517 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1518 num_bytes, num_bytes, type);
1519 if (nocow)
1520 btrfs_dec_nocow_writers(fs_info, disk_bytenr);
1521 BUG_ON(ret); /* -ENOMEM */
1523 if (root->root_key.objectid ==
1524 BTRFS_DATA_RELOC_TREE_OBJECTID)
1526 * Error handled later, as we must prevent
1527 * extent_clear_unlock_delalloc() in error handler
1528 * from freeing metadata of created ordered extent.
1530 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1531 num_bytes);
1533 extent_clear_unlock_delalloc(inode, cur_offset,
1534 cur_offset + num_bytes - 1, end,
1535 locked_page, EXTENT_LOCKED |
1536 EXTENT_DELALLOC |
1537 EXTENT_CLEAR_DATA_RESV,
1538 PAGE_UNLOCK | PAGE_SET_PRIVATE2);
1540 if (!nolock && nocow)
1541 btrfs_end_write_no_snapshotting(root);
1542 cur_offset = extent_end;
1545 * btrfs_reloc_clone_csums() error, now we're OK to call error
1546 * handler, as metadata for created ordered extent will only
1547 * be freed by btrfs_finish_ordered_io().
1549 if (ret)
1550 goto error;
1551 if (cur_offset > end)
1552 break;
1554 btrfs_release_path(path);
1556 if (cur_offset <= end && cow_start == (u64)-1) {
1557 cow_start = cur_offset;
1558 cur_offset = end;
1561 if (cow_start != (u64)-1) {
1562 ret = cow_file_range(inode, locked_page, cow_start, end, end,
1563 page_started, nr_written, 1, NULL);
1564 if (ret)
1565 goto error;
1568 error:
1569 if (ret && cur_offset < end)
1570 extent_clear_unlock_delalloc(inode, cur_offset, end, end,
1571 locked_page, EXTENT_LOCKED |
1572 EXTENT_DELALLOC | EXTENT_DEFRAG |
1573 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1574 PAGE_CLEAR_DIRTY |
1575 PAGE_SET_WRITEBACK |
1576 PAGE_END_WRITEBACK);
1577 btrfs_free_path(path);
1578 return ret;
1581 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1584 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1585 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1586 return 0;
1589 * @defrag_bytes is a hint value, no spinlock held here,
1590 * if is not zero, it means the file is defragging.
1591 * Force cow if given extent needs to be defragged.
1593 if (BTRFS_I(inode)->defrag_bytes &&
1594 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1595 EXTENT_DEFRAG, 0, NULL))
1596 return 1;
1598 return 0;
1602 * extent_io.c call back to do delayed allocation processing
1604 static int run_delalloc_range(void *private_data, struct page *locked_page,
1605 u64 start, u64 end, int *page_started,
1606 unsigned long *nr_written,
1607 struct writeback_control *wbc)
1609 struct inode *inode = private_data;
1610 int ret;
1611 int force_cow = need_force_cow(inode, start, end);
1612 unsigned int write_flags = wbc_to_write_flags(wbc);
1614 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1615 ret = run_delalloc_nocow(inode, locked_page, start, end,
1616 page_started, 1, nr_written);
1617 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1618 ret = run_delalloc_nocow(inode, locked_page, start, end,
1619 page_started, 0, nr_written);
1620 } else if (!inode_need_compress(inode, start, end)) {
1621 ret = cow_file_range(inode, locked_page, start, end, end,
1622 page_started, nr_written, 1, NULL);
1623 } else {
1624 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1625 &BTRFS_I(inode)->runtime_flags);
1626 ret = cow_file_range_async(inode, locked_page, start, end,
1627 page_started, nr_written,
1628 write_flags);
1630 if (ret)
1631 btrfs_cleanup_ordered_extents(inode, start, end - start + 1);
1632 return ret;
1635 static void btrfs_split_extent_hook(void *private_data,
1636 struct extent_state *orig, u64 split)
1638 struct inode *inode = private_data;
1639 u64 size;
1641 /* not delalloc, ignore it */
1642 if (!(orig->state & EXTENT_DELALLOC))
1643 return;
1645 size = orig->end - orig->start + 1;
1646 if (size > BTRFS_MAX_EXTENT_SIZE) {
1647 u32 num_extents;
1648 u64 new_size;
1651 * See the explanation in btrfs_merge_extent_hook, the same
1652 * applies here, just in reverse.
1654 new_size = orig->end - split + 1;
1655 num_extents = count_max_extents(new_size);
1656 new_size = split - orig->start;
1657 num_extents += count_max_extents(new_size);
1658 if (count_max_extents(size) >= num_extents)
1659 return;
1662 spin_lock(&BTRFS_I(inode)->lock);
1663 btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
1664 spin_unlock(&BTRFS_I(inode)->lock);
1668 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1669 * extents so we can keep track of new extents that are just merged onto old
1670 * extents, such as when we are doing sequential writes, so we can properly
1671 * account for the metadata space we'll need.
1673 static void btrfs_merge_extent_hook(void *private_data,
1674 struct extent_state *new,
1675 struct extent_state *other)
1677 struct inode *inode = private_data;
1678 u64 new_size, old_size;
1679 u32 num_extents;
1681 /* not delalloc, ignore it */
1682 if (!(other->state & EXTENT_DELALLOC))
1683 return;
1685 if (new->start > other->start)
1686 new_size = new->end - other->start + 1;
1687 else
1688 new_size = other->end - new->start + 1;
1690 /* we're not bigger than the max, unreserve the space and go */
1691 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1692 spin_lock(&BTRFS_I(inode)->lock);
1693 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1694 spin_unlock(&BTRFS_I(inode)->lock);
1695 return;
1699 * We have to add up either side to figure out how many extents were
1700 * accounted for before we merged into one big extent. If the number of
1701 * extents we accounted for is <= the amount we need for the new range
1702 * then we can return, otherwise drop. Think of it like this
1704 * [ 4k][MAX_SIZE]
1706 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1707 * need 2 outstanding extents, on one side we have 1 and the other side
1708 * we have 1 so they are == and we can return. But in this case
1710 * [MAX_SIZE+4k][MAX_SIZE+4k]
1712 * Each range on their own accounts for 2 extents, but merged together
1713 * they are only 3 extents worth of accounting, so we need to drop in
1714 * this case.
1716 old_size = other->end - other->start + 1;
1717 num_extents = count_max_extents(old_size);
1718 old_size = new->end - new->start + 1;
1719 num_extents += count_max_extents(old_size);
1720 if (count_max_extents(new_size) >= num_extents)
1721 return;
1723 spin_lock(&BTRFS_I(inode)->lock);
1724 btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
1725 spin_unlock(&BTRFS_I(inode)->lock);
1728 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1729 struct inode *inode)
1731 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1733 spin_lock(&root->delalloc_lock);
1734 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1735 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1736 &root->delalloc_inodes);
1737 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1738 &BTRFS_I(inode)->runtime_flags);
1739 root->nr_delalloc_inodes++;
1740 if (root->nr_delalloc_inodes == 1) {
1741 spin_lock(&fs_info->delalloc_root_lock);
1742 BUG_ON(!list_empty(&root->delalloc_root));
1743 list_add_tail(&root->delalloc_root,
1744 &fs_info->delalloc_roots);
1745 spin_unlock(&fs_info->delalloc_root_lock);
1748 spin_unlock(&root->delalloc_lock);
1752 void __btrfs_del_delalloc_inode(struct btrfs_root *root,
1753 struct btrfs_inode *inode)
1755 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1757 if (!list_empty(&inode->delalloc_inodes)) {
1758 list_del_init(&inode->delalloc_inodes);
1759 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1760 &inode->runtime_flags);
1761 root->nr_delalloc_inodes--;
1762 if (!root->nr_delalloc_inodes) {
1763 ASSERT(list_empty(&root->delalloc_inodes));
1764 spin_lock(&fs_info->delalloc_root_lock);
1765 BUG_ON(list_empty(&root->delalloc_root));
1766 list_del_init(&root->delalloc_root);
1767 spin_unlock(&fs_info->delalloc_root_lock);
1772 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1773 struct btrfs_inode *inode)
1775 spin_lock(&root->delalloc_lock);
1776 __btrfs_del_delalloc_inode(root, inode);
1777 spin_unlock(&root->delalloc_lock);
1781 * extent_io.c set_bit_hook, used to track delayed allocation
1782 * bytes in this file, and to maintain the list of inodes that
1783 * have pending delalloc work to be done.
1785 static void btrfs_set_bit_hook(void *private_data,
1786 struct extent_state *state, unsigned *bits)
1788 struct inode *inode = private_data;
1790 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1792 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1793 WARN_ON(1);
1795 * set_bit and clear bit hooks normally require _irqsave/restore
1796 * but in this case, we are only testing for the DELALLOC
1797 * bit, which is only set or cleared with irqs on
1799 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1800 struct btrfs_root *root = BTRFS_I(inode)->root;
1801 u64 len = state->end + 1 - state->start;
1802 u32 num_extents = count_max_extents(len);
1803 bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
1805 spin_lock(&BTRFS_I(inode)->lock);
1806 btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
1807 spin_unlock(&BTRFS_I(inode)->lock);
1809 /* For sanity tests */
1810 if (btrfs_is_testing(fs_info))
1811 return;
1813 percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
1814 fs_info->delalloc_batch);
1815 spin_lock(&BTRFS_I(inode)->lock);
1816 BTRFS_I(inode)->delalloc_bytes += len;
1817 if (*bits & EXTENT_DEFRAG)
1818 BTRFS_I(inode)->defrag_bytes += len;
1819 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1820 &BTRFS_I(inode)->runtime_flags))
1821 btrfs_add_delalloc_inodes(root, inode);
1822 spin_unlock(&BTRFS_I(inode)->lock);
1825 if (!(state->state & EXTENT_DELALLOC_NEW) &&
1826 (*bits & EXTENT_DELALLOC_NEW)) {
1827 spin_lock(&BTRFS_I(inode)->lock);
1828 BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
1829 state->start;
1830 spin_unlock(&BTRFS_I(inode)->lock);
1835 * extent_io.c clear_bit_hook, see set_bit_hook for why
1837 static void btrfs_clear_bit_hook(void *private_data,
1838 struct extent_state *state,
1839 unsigned *bits)
1841 struct btrfs_inode *inode = BTRFS_I((struct inode *)private_data);
1842 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
1843 u64 len = state->end + 1 - state->start;
1844 u32 num_extents = count_max_extents(len);
1846 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG)) {
1847 spin_lock(&inode->lock);
1848 inode->defrag_bytes -= len;
1849 spin_unlock(&inode->lock);
1853 * set_bit and clear bit hooks normally require _irqsave/restore
1854 * but in this case, we are only testing for the DELALLOC
1855 * bit, which is only set or cleared with irqs on
1857 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1858 struct btrfs_root *root = inode->root;
1859 bool do_list = !btrfs_is_free_space_inode(inode);
1861 spin_lock(&inode->lock);
1862 btrfs_mod_outstanding_extents(inode, -num_extents);
1863 spin_unlock(&inode->lock);
1866 * We don't reserve metadata space for space cache inodes so we
1867 * don't need to call dellalloc_release_metadata if there is an
1868 * error.
1870 if (*bits & EXTENT_CLEAR_META_RESV &&
1871 root != fs_info->tree_root)
1872 btrfs_delalloc_release_metadata(inode, len, false);
1874 /* For sanity tests. */
1875 if (btrfs_is_testing(fs_info))
1876 return;
1878 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID &&
1879 do_list && !(state->state & EXTENT_NORESERVE) &&
1880 (*bits & EXTENT_CLEAR_DATA_RESV))
1881 btrfs_free_reserved_data_space_noquota(
1882 &inode->vfs_inode,
1883 state->start, len);
1885 percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
1886 fs_info->delalloc_batch);
1887 spin_lock(&inode->lock);
1888 inode->delalloc_bytes -= len;
1889 if (do_list && inode->delalloc_bytes == 0 &&
1890 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1891 &inode->runtime_flags))
1892 btrfs_del_delalloc_inode(root, inode);
1893 spin_unlock(&inode->lock);
1896 if ((state->state & EXTENT_DELALLOC_NEW) &&
1897 (*bits & EXTENT_DELALLOC_NEW)) {
1898 spin_lock(&inode->lock);
1899 ASSERT(inode->new_delalloc_bytes >= len);
1900 inode->new_delalloc_bytes -= len;
1901 spin_unlock(&inode->lock);
1906 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1907 * we don't create bios that span stripes or chunks
1909 * return 1 if page cannot be merged to bio
1910 * return 0 if page can be merged to bio
1911 * return error otherwise
1913 int btrfs_merge_bio_hook(struct page *page, unsigned long offset,
1914 size_t size, struct bio *bio,
1915 unsigned long bio_flags)
1917 struct inode *inode = page->mapping->host;
1918 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1919 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1920 u64 length = 0;
1921 u64 map_length;
1922 int ret;
1924 if (bio_flags & EXTENT_BIO_COMPRESSED)
1925 return 0;
1927 length = bio->bi_iter.bi_size;
1928 map_length = length;
1929 ret = btrfs_map_block(fs_info, btrfs_op(bio), logical, &map_length,
1930 NULL, 0);
1931 if (ret < 0)
1932 return ret;
1933 if (map_length < length + size)
1934 return 1;
1935 return 0;
1939 * in order to insert checksums into the metadata in large chunks,
1940 * we wait until bio submission time. All the pages in the bio are
1941 * checksummed and sums are attached onto the ordered extent record.
1943 * At IO completion time the cums attached on the ordered extent record
1944 * are inserted into the btree
1946 static blk_status_t btrfs_submit_bio_start(void *private_data, struct bio *bio,
1947 u64 bio_offset)
1949 struct inode *inode = private_data;
1950 blk_status_t ret = 0;
1952 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
1953 BUG_ON(ret); /* -ENOMEM */
1954 return 0;
1958 * in order to insert checksums into the metadata in large chunks,
1959 * we wait until bio submission time. All the pages in the bio are
1960 * checksummed and sums are attached onto the ordered extent record.
1962 * At IO completion time the cums attached on the ordered extent record
1963 * are inserted into the btree
1965 static blk_status_t btrfs_submit_bio_done(void *private_data, struct bio *bio,
1966 int mirror_num)
1968 struct inode *inode = private_data;
1969 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1970 blk_status_t ret;
1972 ret = btrfs_map_bio(fs_info, bio, mirror_num, 1);
1973 if (ret) {
1974 bio->bi_status = ret;
1975 bio_endio(bio);
1977 return ret;
1981 * extent_io.c submission hook. This does the right thing for csum calculation
1982 * on write, or reading the csums from the tree before a read.
1984 * Rules about async/sync submit,
1985 * a) read: sync submit
1987 * b) write without checksum: sync submit
1989 * c) write with checksum:
1990 * c-1) if bio is issued by fsync: sync submit
1991 * (sync_writers != 0)
1993 * c-2) if root is reloc root: sync submit
1994 * (only in case of buffered IO)
1996 * c-3) otherwise: async submit
1998 static blk_status_t btrfs_submit_bio_hook(void *private_data, struct bio *bio,
1999 int mirror_num, unsigned long bio_flags,
2000 u64 bio_offset)
2002 struct inode *inode = private_data;
2003 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2004 struct btrfs_root *root = BTRFS_I(inode)->root;
2005 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
2006 blk_status_t ret = 0;
2007 int skip_sum;
2008 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
2010 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
2012 if (btrfs_is_free_space_inode(BTRFS_I(inode)))
2013 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
2015 if (bio_op(bio) != REQ_OP_WRITE) {
2016 ret = btrfs_bio_wq_end_io(fs_info, bio, metadata);
2017 if (ret)
2018 goto out;
2020 if (bio_flags & EXTENT_BIO_COMPRESSED) {
2021 ret = btrfs_submit_compressed_read(inode, bio,
2022 mirror_num,
2023 bio_flags);
2024 goto out;
2025 } else if (!skip_sum) {
2026 ret = btrfs_lookup_bio_sums(inode, bio, NULL);
2027 if (ret)
2028 goto out;
2030 goto mapit;
2031 } else if (async && !skip_sum) {
2032 /* csum items have already been cloned */
2033 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2034 goto mapit;
2035 /* we're doing a write, do the async checksumming */
2036 ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, bio_flags,
2037 bio_offset, inode,
2038 btrfs_submit_bio_start,
2039 btrfs_submit_bio_done);
2040 goto out;
2041 } else if (!skip_sum) {
2042 ret = btrfs_csum_one_bio(inode, bio, 0, 0);
2043 if (ret)
2044 goto out;
2047 mapit:
2048 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
2050 out:
2051 if (ret) {
2052 bio->bi_status = ret;
2053 bio_endio(bio);
2055 return ret;
2059 * given a list of ordered sums record them in the inode. This happens
2060 * at IO completion time based on sums calculated at bio submission time.
2062 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
2063 struct inode *inode, struct list_head *list)
2065 struct btrfs_ordered_sum *sum;
2066 int ret;
2068 list_for_each_entry(sum, list, list) {
2069 trans->adding_csums = true;
2070 ret = btrfs_csum_file_blocks(trans,
2071 BTRFS_I(inode)->root->fs_info->csum_root, sum);
2072 trans->adding_csums = false;
2073 if (ret)
2074 return ret;
2076 return 0;
2079 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
2080 unsigned int extra_bits,
2081 struct extent_state **cached_state, int dedupe)
2083 WARN_ON((end & (PAGE_SIZE - 1)) == 0);
2084 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
2085 extra_bits, cached_state);
2088 /* see btrfs_writepage_start_hook for details on why this is required */
2089 struct btrfs_writepage_fixup {
2090 struct page *page;
2091 struct btrfs_work work;
2094 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2096 struct btrfs_writepage_fixup *fixup;
2097 struct btrfs_ordered_extent *ordered;
2098 struct extent_state *cached_state = NULL;
2099 struct extent_changeset *data_reserved = NULL;
2100 struct page *page;
2101 struct inode *inode;
2102 u64 page_start;
2103 u64 page_end;
2104 int ret;
2106 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2107 page = fixup->page;
2108 again:
2109 lock_page(page);
2110 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2111 ClearPageChecked(page);
2112 goto out_page;
2115 inode = page->mapping->host;
2116 page_start = page_offset(page);
2117 page_end = page_offset(page) + PAGE_SIZE - 1;
2119 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end,
2120 &cached_state);
2122 /* already ordered? We're done */
2123 if (PagePrivate2(page))
2124 goto out;
2126 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
2127 PAGE_SIZE);
2128 if (ordered) {
2129 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2130 page_end, &cached_state);
2131 unlock_page(page);
2132 btrfs_start_ordered_extent(inode, ordered, 1);
2133 btrfs_put_ordered_extent(ordered);
2134 goto again;
2137 ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2138 PAGE_SIZE);
2139 if (ret) {
2140 mapping_set_error(page->mapping, ret);
2141 end_extent_writepage(page, ret, page_start, page_end);
2142 ClearPageChecked(page);
2143 goto out;
2146 ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
2147 &cached_state, 0);
2148 if (ret) {
2149 mapping_set_error(page->mapping, ret);
2150 end_extent_writepage(page, ret, page_start, page_end);
2151 ClearPageChecked(page);
2152 goto out;
2155 ClearPageChecked(page);
2156 set_page_dirty(page);
2157 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, false);
2158 out:
2159 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2160 &cached_state);
2161 out_page:
2162 unlock_page(page);
2163 put_page(page);
2164 kfree(fixup);
2165 extent_changeset_free(data_reserved);
2169 * There are a few paths in the higher layers of the kernel that directly
2170 * set the page dirty bit without asking the filesystem if it is a
2171 * good idea. This causes problems because we want to make sure COW
2172 * properly happens and the data=ordered rules are followed.
2174 * In our case any range that doesn't have the ORDERED bit set
2175 * hasn't been properly setup for IO. We kick off an async process
2176 * to fix it up. The async helper will wait for ordered extents, set
2177 * the delalloc bit and make it safe to write the page.
2179 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2181 struct inode *inode = page->mapping->host;
2182 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2183 struct btrfs_writepage_fixup *fixup;
2185 /* this page is properly in the ordered list */
2186 if (TestClearPagePrivate2(page))
2187 return 0;
2189 if (PageChecked(page))
2190 return -EAGAIN;
2192 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2193 if (!fixup)
2194 return -EAGAIN;
2196 SetPageChecked(page);
2197 get_page(page);
2198 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2199 btrfs_writepage_fixup_worker, NULL, NULL);
2200 fixup->page = page;
2201 btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
2202 return -EBUSY;
2205 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2206 struct inode *inode, u64 file_pos,
2207 u64 disk_bytenr, u64 disk_num_bytes,
2208 u64 num_bytes, u64 ram_bytes,
2209 u8 compression, u8 encryption,
2210 u16 other_encoding, int extent_type)
2212 struct btrfs_root *root = BTRFS_I(inode)->root;
2213 struct btrfs_file_extent_item *fi;
2214 struct btrfs_path *path;
2215 struct extent_buffer *leaf;
2216 struct btrfs_key ins;
2217 u64 qg_released;
2218 int extent_inserted = 0;
2219 int ret;
2221 path = btrfs_alloc_path();
2222 if (!path)
2223 return -ENOMEM;
2226 * we may be replacing one extent in the tree with another.
2227 * The new extent is pinned in the extent map, and we don't want
2228 * to drop it from the cache until it is completely in the btree.
2230 * So, tell btrfs_drop_extents to leave this extent in the cache.
2231 * the caller is expected to unpin it and allow it to be merged
2232 * with the others.
2234 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2235 file_pos + num_bytes, NULL, 0,
2236 1, sizeof(*fi), &extent_inserted);
2237 if (ret)
2238 goto out;
2240 if (!extent_inserted) {
2241 ins.objectid = btrfs_ino(BTRFS_I(inode));
2242 ins.offset = file_pos;
2243 ins.type = BTRFS_EXTENT_DATA_KEY;
2245 path->leave_spinning = 1;
2246 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2247 sizeof(*fi));
2248 if (ret)
2249 goto out;
2251 leaf = path->nodes[0];
2252 fi = btrfs_item_ptr(leaf, path->slots[0],
2253 struct btrfs_file_extent_item);
2254 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2255 btrfs_set_file_extent_type(leaf, fi, extent_type);
2256 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2257 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2258 btrfs_set_file_extent_offset(leaf, fi, 0);
2259 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2260 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2261 btrfs_set_file_extent_compression(leaf, fi, compression);
2262 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2263 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2265 btrfs_mark_buffer_dirty(leaf);
2266 btrfs_release_path(path);
2268 inode_add_bytes(inode, num_bytes);
2270 ins.objectid = disk_bytenr;
2271 ins.offset = disk_num_bytes;
2272 ins.type = BTRFS_EXTENT_ITEM_KEY;
2275 * Release the reserved range from inode dirty range map, as it is
2276 * already moved into delayed_ref_head
2278 ret = btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2279 if (ret < 0)
2280 goto out;
2281 qg_released = ret;
2282 ret = btrfs_alloc_reserved_file_extent(trans, root,
2283 btrfs_ino(BTRFS_I(inode)),
2284 file_pos, qg_released, &ins);
2285 out:
2286 btrfs_free_path(path);
2288 return ret;
2291 /* snapshot-aware defrag */
2292 struct sa_defrag_extent_backref {
2293 struct rb_node node;
2294 struct old_sa_defrag_extent *old;
2295 u64 root_id;
2296 u64 inum;
2297 u64 file_pos;
2298 u64 extent_offset;
2299 u64 num_bytes;
2300 u64 generation;
2303 struct old_sa_defrag_extent {
2304 struct list_head list;
2305 struct new_sa_defrag_extent *new;
2307 u64 extent_offset;
2308 u64 bytenr;
2309 u64 offset;
2310 u64 len;
2311 int count;
2314 struct new_sa_defrag_extent {
2315 struct rb_root root;
2316 struct list_head head;
2317 struct btrfs_path *path;
2318 struct inode *inode;
2319 u64 file_pos;
2320 u64 len;
2321 u64 bytenr;
2322 u64 disk_len;
2323 u8 compress_type;
2326 static int backref_comp(struct sa_defrag_extent_backref *b1,
2327 struct sa_defrag_extent_backref *b2)
2329 if (b1->root_id < b2->root_id)
2330 return -1;
2331 else if (b1->root_id > b2->root_id)
2332 return 1;
2334 if (b1->inum < b2->inum)
2335 return -1;
2336 else if (b1->inum > b2->inum)
2337 return 1;
2339 if (b1->file_pos < b2->file_pos)
2340 return -1;
2341 else if (b1->file_pos > b2->file_pos)
2342 return 1;
2345 * [------------------------------] ===> (a range of space)
2346 * |<--->| |<---->| =============> (fs/file tree A)
2347 * |<---------------------------->| ===> (fs/file tree B)
2349 * A range of space can refer to two file extents in one tree while
2350 * refer to only one file extent in another tree.
2352 * So we may process a disk offset more than one time(two extents in A)
2353 * and locate at the same extent(one extent in B), then insert two same
2354 * backrefs(both refer to the extent in B).
2356 return 0;
2359 static void backref_insert(struct rb_root *root,
2360 struct sa_defrag_extent_backref *backref)
2362 struct rb_node **p = &root->rb_node;
2363 struct rb_node *parent = NULL;
2364 struct sa_defrag_extent_backref *entry;
2365 int ret;
2367 while (*p) {
2368 parent = *p;
2369 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2371 ret = backref_comp(backref, entry);
2372 if (ret < 0)
2373 p = &(*p)->rb_left;
2374 else
2375 p = &(*p)->rb_right;
2378 rb_link_node(&backref->node, parent, p);
2379 rb_insert_color(&backref->node, root);
2383 * Note the backref might has changed, and in this case we just return 0.
2385 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2386 void *ctx)
2388 struct btrfs_file_extent_item *extent;
2389 struct old_sa_defrag_extent *old = ctx;
2390 struct new_sa_defrag_extent *new = old->new;
2391 struct btrfs_path *path = new->path;
2392 struct btrfs_key key;
2393 struct btrfs_root *root;
2394 struct sa_defrag_extent_backref *backref;
2395 struct extent_buffer *leaf;
2396 struct inode *inode = new->inode;
2397 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2398 int slot;
2399 int ret;
2400 u64 extent_offset;
2401 u64 num_bytes;
2403 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2404 inum == btrfs_ino(BTRFS_I(inode)))
2405 return 0;
2407 key.objectid = root_id;
2408 key.type = BTRFS_ROOT_ITEM_KEY;
2409 key.offset = (u64)-1;
2411 root = btrfs_read_fs_root_no_name(fs_info, &key);
2412 if (IS_ERR(root)) {
2413 if (PTR_ERR(root) == -ENOENT)
2414 return 0;
2415 WARN_ON(1);
2416 btrfs_debug(fs_info, "inum=%llu, offset=%llu, root_id=%llu",
2417 inum, offset, root_id);
2418 return PTR_ERR(root);
2421 key.objectid = inum;
2422 key.type = BTRFS_EXTENT_DATA_KEY;
2423 if (offset > (u64)-1 << 32)
2424 key.offset = 0;
2425 else
2426 key.offset = offset;
2428 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2429 if (WARN_ON(ret < 0))
2430 return ret;
2431 ret = 0;
2433 while (1) {
2434 cond_resched();
2436 leaf = path->nodes[0];
2437 slot = path->slots[0];
2439 if (slot >= btrfs_header_nritems(leaf)) {
2440 ret = btrfs_next_leaf(root, path);
2441 if (ret < 0) {
2442 goto out;
2443 } else if (ret > 0) {
2444 ret = 0;
2445 goto out;
2447 continue;
2450 path->slots[0]++;
2452 btrfs_item_key_to_cpu(leaf, &key, slot);
2454 if (key.objectid > inum)
2455 goto out;
2457 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2458 continue;
2460 extent = btrfs_item_ptr(leaf, slot,
2461 struct btrfs_file_extent_item);
2463 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2464 continue;
2467 * 'offset' refers to the exact key.offset,
2468 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2469 * (key.offset - extent_offset).
2471 if (key.offset != offset)
2472 continue;
2474 extent_offset = btrfs_file_extent_offset(leaf, extent);
2475 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2477 if (extent_offset >= old->extent_offset + old->offset +
2478 old->len || extent_offset + num_bytes <=
2479 old->extent_offset + old->offset)
2480 continue;
2481 break;
2484 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2485 if (!backref) {
2486 ret = -ENOENT;
2487 goto out;
2490 backref->root_id = root_id;
2491 backref->inum = inum;
2492 backref->file_pos = offset;
2493 backref->num_bytes = num_bytes;
2494 backref->extent_offset = extent_offset;
2495 backref->generation = btrfs_file_extent_generation(leaf, extent);
2496 backref->old = old;
2497 backref_insert(&new->root, backref);
2498 old->count++;
2499 out:
2500 btrfs_release_path(path);
2501 WARN_ON(ret);
2502 return ret;
2505 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2506 struct new_sa_defrag_extent *new)
2508 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2509 struct old_sa_defrag_extent *old, *tmp;
2510 int ret;
2512 new->path = path;
2514 list_for_each_entry_safe(old, tmp, &new->head, list) {
2515 ret = iterate_inodes_from_logical(old->bytenr +
2516 old->extent_offset, fs_info,
2517 path, record_one_backref,
2518 old, false);
2519 if (ret < 0 && ret != -ENOENT)
2520 return false;
2522 /* no backref to be processed for this extent */
2523 if (!old->count) {
2524 list_del(&old->list);
2525 kfree(old);
2529 if (list_empty(&new->head))
2530 return false;
2532 return true;
2535 static int relink_is_mergable(struct extent_buffer *leaf,
2536 struct btrfs_file_extent_item *fi,
2537 struct new_sa_defrag_extent *new)
2539 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2540 return 0;
2542 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2543 return 0;
2545 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2546 return 0;
2548 if (btrfs_file_extent_encryption(leaf, fi) ||
2549 btrfs_file_extent_other_encoding(leaf, fi))
2550 return 0;
2552 return 1;
2556 * Note the backref might has changed, and in this case we just return 0.
2558 static noinline int relink_extent_backref(struct btrfs_path *path,
2559 struct sa_defrag_extent_backref *prev,
2560 struct sa_defrag_extent_backref *backref)
2562 struct btrfs_file_extent_item *extent;
2563 struct btrfs_file_extent_item *item;
2564 struct btrfs_ordered_extent *ordered;
2565 struct btrfs_trans_handle *trans;
2566 struct btrfs_root *root;
2567 struct btrfs_key key;
2568 struct extent_buffer *leaf;
2569 struct old_sa_defrag_extent *old = backref->old;
2570 struct new_sa_defrag_extent *new = old->new;
2571 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2572 struct inode *inode;
2573 struct extent_state *cached = NULL;
2574 int ret = 0;
2575 u64 start;
2576 u64 len;
2577 u64 lock_start;
2578 u64 lock_end;
2579 bool merge = false;
2580 int index;
2582 if (prev && prev->root_id == backref->root_id &&
2583 prev->inum == backref->inum &&
2584 prev->file_pos + prev->num_bytes == backref->file_pos)
2585 merge = true;
2587 /* step 1: get root */
2588 key.objectid = backref->root_id;
2589 key.type = BTRFS_ROOT_ITEM_KEY;
2590 key.offset = (u64)-1;
2592 index = srcu_read_lock(&fs_info->subvol_srcu);
2594 root = btrfs_read_fs_root_no_name(fs_info, &key);
2595 if (IS_ERR(root)) {
2596 srcu_read_unlock(&fs_info->subvol_srcu, index);
2597 if (PTR_ERR(root) == -ENOENT)
2598 return 0;
2599 return PTR_ERR(root);
2602 if (btrfs_root_readonly(root)) {
2603 srcu_read_unlock(&fs_info->subvol_srcu, index);
2604 return 0;
2607 /* step 2: get inode */
2608 key.objectid = backref->inum;
2609 key.type = BTRFS_INODE_ITEM_KEY;
2610 key.offset = 0;
2612 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2613 if (IS_ERR(inode)) {
2614 srcu_read_unlock(&fs_info->subvol_srcu, index);
2615 return 0;
2618 srcu_read_unlock(&fs_info->subvol_srcu, index);
2620 /* step 3: relink backref */
2621 lock_start = backref->file_pos;
2622 lock_end = backref->file_pos + backref->num_bytes - 1;
2623 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2624 &cached);
2626 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2627 if (ordered) {
2628 btrfs_put_ordered_extent(ordered);
2629 goto out_unlock;
2632 trans = btrfs_join_transaction(root);
2633 if (IS_ERR(trans)) {
2634 ret = PTR_ERR(trans);
2635 goto out_unlock;
2638 key.objectid = backref->inum;
2639 key.type = BTRFS_EXTENT_DATA_KEY;
2640 key.offset = backref->file_pos;
2642 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2643 if (ret < 0) {
2644 goto out_free_path;
2645 } else if (ret > 0) {
2646 ret = 0;
2647 goto out_free_path;
2650 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2651 struct btrfs_file_extent_item);
2653 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2654 backref->generation)
2655 goto out_free_path;
2657 btrfs_release_path(path);
2659 start = backref->file_pos;
2660 if (backref->extent_offset < old->extent_offset + old->offset)
2661 start += old->extent_offset + old->offset -
2662 backref->extent_offset;
2664 len = min(backref->extent_offset + backref->num_bytes,
2665 old->extent_offset + old->offset + old->len);
2666 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2668 ret = btrfs_drop_extents(trans, root, inode, start,
2669 start + len, 1);
2670 if (ret)
2671 goto out_free_path;
2672 again:
2673 key.objectid = btrfs_ino(BTRFS_I(inode));
2674 key.type = BTRFS_EXTENT_DATA_KEY;
2675 key.offset = start;
2677 path->leave_spinning = 1;
2678 if (merge) {
2679 struct btrfs_file_extent_item *fi;
2680 u64 extent_len;
2681 struct btrfs_key found_key;
2683 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2684 if (ret < 0)
2685 goto out_free_path;
2687 path->slots[0]--;
2688 leaf = path->nodes[0];
2689 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2691 fi = btrfs_item_ptr(leaf, path->slots[0],
2692 struct btrfs_file_extent_item);
2693 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2695 if (extent_len + found_key.offset == start &&
2696 relink_is_mergable(leaf, fi, new)) {
2697 btrfs_set_file_extent_num_bytes(leaf, fi,
2698 extent_len + len);
2699 btrfs_mark_buffer_dirty(leaf);
2700 inode_add_bytes(inode, len);
2702 ret = 1;
2703 goto out_free_path;
2704 } else {
2705 merge = false;
2706 btrfs_release_path(path);
2707 goto again;
2711 ret = btrfs_insert_empty_item(trans, root, path, &key,
2712 sizeof(*extent));
2713 if (ret) {
2714 btrfs_abort_transaction(trans, ret);
2715 goto out_free_path;
2718 leaf = path->nodes[0];
2719 item = btrfs_item_ptr(leaf, path->slots[0],
2720 struct btrfs_file_extent_item);
2721 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2722 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2723 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2724 btrfs_set_file_extent_num_bytes(leaf, item, len);
2725 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2726 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2727 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2728 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2729 btrfs_set_file_extent_encryption(leaf, item, 0);
2730 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2732 btrfs_mark_buffer_dirty(leaf);
2733 inode_add_bytes(inode, len);
2734 btrfs_release_path(path);
2736 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2737 new->disk_len, 0,
2738 backref->root_id, backref->inum,
2739 new->file_pos); /* start - extent_offset */
2740 if (ret) {
2741 btrfs_abort_transaction(trans, ret);
2742 goto out_free_path;
2745 ret = 1;
2746 out_free_path:
2747 btrfs_release_path(path);
2748 path->leave_spinning = 0;
2749 btrfs_end_transaction(trans);
2750 out_unlock:
2751 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2752 &cached);
2753 iput(inode);
2754 return ret;
2757 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2759 struct old_sa_defrag_extent *old, *tmp;
2761 if (!new)
2762 return;
2764 list_for_each_entry_safe(old, tmp, &new->head, list) {
2765 kfree(old);
2767 kfree(new);
2770 static void relink_file_extents(struct new_sa_defrag_extent *new)
2772 struct btrfs_fs_info *fs_info = btrfs_sb(new->inode->i_sb);
2773 struct btrfs_path *path;
2774 struct sa_defrag_extent_backref *backref;
2775 struct sa_defrag_extent_backref *prev = NULL;
2776 struct inode *inode;
2777 struct rb_node *node;
2778 int ret;
2780 inode = new->inode;
2782 path = btrfs_alloc_path();
2783 if (!path)
2784 return;
2786 if (!record_extent_backrefs(path, new)) {
2787 btrfs_free_path(path);
2788 goto out;
2790 btrfs_release_path(path);
2792 while (1) {
2793 node = rb_first(&new->root);
2794 if (!node)
2795 break;
2796 rb_erase(node, &new->root);
2798 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2800 ret = relink_extent_backref(path, prev, backref);
2801 WARN_ON(ret < 0);
2803 kfree(prev);
2805 if (ret == 1)
2806 prev = backref;
2807 else
2808 prev = NULL;
2809 cond_resched();
2811 kfree(prev);
2813 btrfs_free_path(path);
2814 out:
2815 free_sa_defrag_extent(new);
2817 atomic_dec(&fs_info->defrag_running);
2818 wake_up(&fs_info->transaction_wait);
2821 static struct new_sa_defrag_extent *
2822 record_old_file_extents(struct inode *inode,
2823 struct btrfs_ordered_extent *ordered)
2825 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2826 struct btrfs_root *root = BTRFS_I(inode)->root;
2827 struct btrfs_path *path;
2828 struct btrfs_key key;
2829 struct old_sa_defrag_extent *old;
2830 struct new_sa_defrag_extent *new;
2831 int ret;
2833 new = kmalloc(sizeof(*new), GFP_NOFS);
2834 if (!new)
2835 return NULL;
2837 new->inode = inode;
2838 new->file_pos = ordered->file_offset;
2839 new->len = ordered->len;
2840 new->bytenr = ordered->start;
2841 new->disk_len = ordered->disk_len;
2842 new->compress_type = ordered->compress_type;
2843 new->root = RB_ROOT;
2844 INIT_LIST_HEAD(&new->head);
2846 path = btrfs_alloc_path();
2847 if (!path)
2848 goto out_kfree;
2850 key.objectid = btrfs_ino(BTRFS_I(inode));
2851 key.type = BTRFS_EXTENT_DATA_KEY;
2852 key.offset = new->file_pos;
2854 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2855 if (ret < 0)
2856 goto out_free_path;
2857 if (ret > 0 && path->slots[0] > 0)
2858 path->slots[0]--;
2860 /* find out all the old extents for the file range */
2861 while (1) {
2862 struct btrfs_file_extent_item *extent;
2863 struct extent_buffer *l;
2864 int slot;
2865 u64 num_bytes;
2866 u64 offset;
2867 u64 end;
2868 u64 disk_bytenr;
2869 u64 extent_offset;
2871 l = path->nodes[0];
2872 slot = path->slots[0];
2874 if (slot >= btrfs_header_nritems(l)) {
2875 ret = btrfs_next_leaf(root, path);
2876 if (ret < 0)
2877 goto out_free_path;
2878 else if (ret > 0)
2879 break;
2880 continue;
2883 btrfs_item_key_to_cpu(l, &key, slot);
2885 if (key.objectid != btrfs_ino(BTRFS_I(inode)))
2886 break;
2887 if (key.type != BTRFS_EXTENT_DATA_KEY)
2888 break;
2889 if (key.offset >= new->file_pos + new->len)
2890 break;
2892 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2894 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2895 if (key.offset + num_bytes < new->file_pos)
2896 goto next;
2898 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2899 if (!disk_bytenr)
2900 goto next;
2902 extent_offset = btrfs_file_extent_offset(l, extent);
2904 old = kmalloc(sizeof(*old), GFP_NOFS);
2905 if (!old)
2906 goto out_free_path;
2908 offset = max(new->file_pos, key.offset);
2909 end = min(new->file_pos + new->len, key.offset + num_bytes);
2911 old->bytenr = disk_bytenr;
2912 old->extent_offset = extent_offset;
2913 old->offset = offset - key.offset;
2914 old->len = end - offset;
2915 old->new = new;
2916 old->count = 0;
2917 list_add_tail(&old->list, &new->head);
2918 next:
2919 path->slots[0]++;
2920 cond_resched();
2923 btrfs_free_path(path);
2924 atomic_inc(&fs_info->defrag_running);
2926 return new;
2928 out_free_path:
2929 btrfs_free_path(path);
2930 out_kfree:
2931 free_sa_defrag_extent(new);
2932 return NULL;
2935 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2936 u64 start, u64 len)
2938 struct btrfs_block_group_cache *cache;
2940 cache = btrfs_lookup_block_group(fs_info, start);
2941 ASSERT(cache);
2943 spin_lock(&cache->lock);
2944 cache->delalloc_bytes -= len;
2945 spin_unlock(&cache->lock);
2947 btrfs_put_block_group(cache);
2950 /* as ordered data IO finishes, this gets called so we can finish
2951 * an ordered extent if the range of bytes in the file it covers are
2952 * fully written.
2954 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2956 struct inode *inode = ordered_extent->inode;
2957 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2958 struct btrfs_root *root = BTRFS_I(inode)->root;
2959 struct btrfs_trans_handle *trans = NULL;
2960 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2961 struct extent_state *cached_state = NULL;
2962 struct new_sa_defrag_extent *new = NULL;
2963 int compress_type = 0;
2964 int ret = 0;
2965 u64 logical_len = ordered_extent->len;
2966 bool nolock;
2967 bool truncated = false;
2968 bool range_locked = false;
2969 bool clear_new_delalloc_bytes = false;
2971 if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
2972 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
2973 !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags))
2974 clear_new_delalloc_bytes = true;
2976 nolock = btrfs_is_free_space_inode(BTRFS_I(inode));
2978 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2979 ret = -EIO;
2980 goto out;
2983 btrfs_free_io_failure_record(BTRFS_I(inode),
2984 ordered_extent->file_offset,
2985 ordered_extent->file_offset +
2986 ordered_extent->len - 1);
2988 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2989 truncated = true;
2990 logical_len = ordered_extent->truncated_len;
2991 /* Truncated the entire extent, don't bother adding */
2992 if (!logical_len)
2993 goto out;
2996 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2997 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
3000 * For mwrite(mmap + memset to write) case, we still reserve
3001 * space for NOCOW range.
3002 * As NOCOW won't cause a new delayed ref, just free the space
3004 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3005 ordered_extent->len);
3006 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3007 if (nolock)
3008 trans = btrfs_join_transaction_nolock(root);
3009 else
3010 trans = btrfs_join_transaction(root);
3011 if (IS_ERR(trans)) {
3012 ret = PTR_ERR(trans);
3013 trans = NULL;
3014 goto out;
3016 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3017 ret = btrfs_update_inode_fallback(trans, root, inode);
3018 if (ret) /* -ENOMEM or corruption */
3019 btrfs_abort_transaction(trans, ret);
3020 goto out;
3023 range_locked = true;
3024 lock_extent_bits(io_tree, ordered_extent->file_offset,
3025 ordered_extent->file_offset + ordered_extent->len - 1,
3026 &cached_state);
3028 ret = test_range_bit(io_tree, ordered_extent->file_offset,
3029 ordered_extent->file_offset + ordered_extent->len - 1,
3030 EXTENT_DEFRAG, 0, cached_state);
3031 if (ret) {
3032 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
3033 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
3034 /* the inode is shared */
3035 new = record_old_file_extents(inode, ordered_extent);
3037 clear_extent_bit(io_tree, ordered_extent->file_offset,
3038 ordered_extent->file_offset + ordered_extent->len - 1,
3039 EXTENT_DEFRAG, 0, 0, &cached_state);
3042 if (nolock)
3043 trans = btrfs_join_transaction_nolock(root);
3044 else
3045 trans = btrfs_join_transaction(root);
3046 if (IS_ERR(trans)) {
3047 ret = PTR_ERR(trans);
3048 trans = NULL;
3049 goto out;
3052 trans->block_rsv = &BTRFS_I(inode)->block_rsv;
3054 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3055 compress_type = ordered_extent->compress_type;
3056 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3057 BUG_ON(compress_type);
3058 btrfs_qgroup_free_data(inode, NULL, ordered_extent->file_offset,
3059 ordered_extent->len);
3060 ret = btrfs_mark_extent_written(trans, BTRFS_I(inode),
3061 ordered_extent->file_offset,
3062 ordered_extent->file_offset +
3063 logical_len);
3064 } else {
3065 BUG_ON(root == fs_info->tree_root);
3066 ret = insert_reserved_file_extent(trans, inode,
3067 ordered_extent->file_offset,
3068 ordered_extent->start,
3069 ordered_extent->disk_len,
3070 logical_len, logical_len,
3071 compress_type, 0, 0,
3072 BTRFS_FILE_EXTENT_REG);
3073 if (!ret)
3074 btrfs_release_delalloc_bytes(fs_info,
3075 ordered_extent->start,
3076 ordered_extent->disk_len);
3078 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
3079 ordered_extent->file_offset, ordered_extent->len,
3080 trans->transid);
3081 if (ret < 0) {
3082 btrfs_abort_transaction(trans, ret);
3083 goto out;
3086 ret = add_pending_csums(trans, inode, &ordered_extent->list);
3087 if (ret) {
3088 btrfs_abort_transaction(trans, ret);
3089 goto out;
3092 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
3093 ret = btrfs_update_inode_fallback(trans, root, inode);
3094 if (ret) { /* -ENOMEM or corruption */
3095 btrfs_abort_transaction(trans, ret);
3096 goto out;
3098 ret = 0;
3099 out:
3100 if (range_locked || clear_new_delalloc_bytes) {
3101 unsigned int clear_bits = 0;
3103 if (range_locked)
3104 clear_bits |= EXTENT_LOCKED;
3105 if (clear_new_delalloc_bytes)
3106 clear_bits |= EXTENT_DELALLOC_NEW;
3107 clear_extent_bit(&BTRFS_I(inode)->io_tree,
3108 ordered_extent->file_offset,
3109 ordered_extent->file_offset +
3110 ordered_extent->len - 1,
3111 clear_bits,
3112 (clear_bits & EXTENT_LOCKED) ? 1 : 0,
3113 0, &cached_state);
3116 if (trans)
3117 btrfs_end_transaction(trans);
3119 if (ret || truncated) {
3120 u64 start, end;
3122 if (truncated)
3123 start = ordered_extent->file_offset + logical_len;
3124 else
3125 start = ordered_extent->file_offset;
3126 end = ordered_extent->file_offset + ordered_extent->len - 1;
3127 clear_extent_uptodate(io_tree, start, end, NULL);
3129 /* Drop the cache for the part of the extent we didn't write. */
3130 btrfs_drop_extent_cache(BTRFS_I(inode), start, end, 0);
3133 * If the ordered extent had an IOERR or something else went
3134 * wrong we need to return the space for this ordered extent
3135 * back to the allocator. We only free the extent in the
3136 * truncated case if we didn't write out the extent at all.
3138 if ((ret || !logical_len) &&
3139 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3140 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3141 btrfs_free_reserved_extent(fs_info,
3142 ordered_extent->start,
3143 ordered_extent->disk_len, 1);
3148 * This needs to be done to make sure anybody waiting knows we are done
3149 * updating everything for this ordered extent.
3151 btrfs_remove_ordered_extent(inode, ordered_extent);
3153 /* for snapshot-aware defrag */
3154 if (new) {
3155 if (ret) {
3156 free_sa_defrag_extent(new);
3157 atomic_dec(&fs_info->defrag_running);
3158 } else {
3159 relink_file_extents(new);
3163 /* once for us */
3164 btrfs_put_ordered_extent(ordered_extent);
3165 /* once for the tree */
3166 btrfs_put_ordered_extent(ordered_extent);
3168 /* Try to release some metadata so we don't get an OOM but don't wait */
3169 btrfs_btree_balance_dirty_nodelay(fs_info);
3171 return ret;
3174 static void finish_ordered_fn(struct btrfs_work *work)
3176 struct btrfs_ordered_extent *ordered_extent;
3177 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3178 btrfs_finish_ordered_io(ordered_extent);
3181 static void btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3182 struct extent_state *state, int uptodate)
3184 struct inode *inode = page->mapping->host;
3185 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3186 struct btrfs_ordered_extent *ordered_extent = NULL;
3187 struct btrfs_workqueue *wq;
3188 btrfs_work_func_t func;
3190 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3192 ClearPagePrivate2(page);
3193 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3194 end - start + 1, uptodate))
3195 return;
3197 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
3198 wq = fs_info->endio_freespace_worker;
3199 func = btrfs_freespace_write_helper;
3200 } else {
3201 wq = fs_info->endio_write_workers;
3202 func = btrfs_endio_write_helper;
3205 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3206 NULL);
3207 btrfs_queue_work(wq, &ordered_extent->work);
3210 static int __readpage_endio_check(struct inode *inode,
3211 struct btrfs_io_bio *io_bio,
3212 int icsum, struct page *page,
3213 int pgoff, u64 start, size_t len)
3215 char *kaddr;
3216 u32 csum_expected;
3217 u32 csum = ~(u32)0;
3219 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3221 kaddr = kmap_atomic(page);
3222 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3223 btrfs_csum_final(csum, (u8 *)&csum);
3224 if (csum != csum_expected)
3225 goto zeroit;
3227 kunmap_atomic(kaddr);
3228 return 0;
3229 zeroit:
3230 btrfs_print_data_csum_error(BTRFS_I(inode), start, csum, csum_expected,
3231 io_bio->mirror_num);
3232 memset(kaddr + pgoff, 1, len);
3233 flush_dcache_page(page);
3234 kunmap_atomic(kaddr);
3235 return -EIO;
3239 * when reads are done, we need to check csums to verify the data is correct
3240 * if there's a match, we allow the bio to finish. If not, the code in
3241 * extent_io.c will try to find good copies for us.
3243 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3244 u64 phy_offset, struct page *page,
3245 u64 start, u64 end, int mirror)
3247 size_t offset = start - page_offset(page);
3248 struct inode *inode = page->mapping->host;
3249 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3250 struct btrfs_root *root = BTRFS_I(inode)->root;
3252 if (PageChecked(page)) {
3253 ClearPageChecked(page);
3254 return 0;
3257 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3258 return 0;
3260 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3261 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3262 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM);
3263 return 0;
3266 phy_offset >>= inode->i_sb->s_blocksize_bits;
3267 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3268 start, (size_t)(end - start + 1));
3272 * btrfs_add_delayed_iput - perform a delayed iput on @inode
3274 * @inode: The inode we want to perform iput on
3276 * This function uses the generic vfs_inode::i_count to track whether we should
3277 * just decrement it (in case it's > 1) or if this is the last iput then link
3278 * the inode to the delayed iput machinery. Delayed iputs are processed at
3279 * transaction commit time/superblock commit/cleaner kthread.
3281 void btrfs_add_delayed_iput(struct inode *inode)
3283 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3284 struct btrfs_inode *binode = BTRFS_I(inode);
3286 if (atomic_add_unless(&inode->i_count, -1, 1))
3287 return;
3289 spin_lock(&fs_info->delayed_iput_lock);
3290 ASSERT(list_empty(&binode->delayed_iput));
3291 list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
3292 spin_unlock(&fs_info->delayed_iput_lock);
3295 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3298 spin_lock(&fs_info->delayed_iput_lock);
3299 while (!list_empty(&fs_info->delayed_iputs)) {
3300 struct btrfs_inode *inode;
3302 inode = list_first_entry(&fs_info->delayed_iputs,
3303 struct btrfs_inode, delayed_iput);
3304 list_del_init(&inode->delayed_iput);
3305 spin_unlock(&fs_info->delayed_iput_lock);
3306 iput(&inode->vfs_inode);
3307 spin_lock(&fs_info->delayed_iput_lock);
3309 spin_unlock(&fs_info->delayed_iput_lock);
3313 * This creates an orphan entry for the given inode in case something goes wrong
3314 * in the middle of an unlink.
3316 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3317 struct btrfs_inode *inode)
3319 int ret;
3321 ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3322 if (ret && ret != -EEXIST) {
3323 btrfs_abort_transaction(trans, ret);
3324 return ret;
3327 return 0;
3331 * We have done the delete so we can go ahead and remove the orphan item for
3332 * this particular inode.
3334 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3335 struct btrfs_inode *inode)
3337 return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3341 * this cleans up any orphans that may be left on the list from the last use
3342 * of this root.
3344 int btrfs_orphan_cleanup(struct btrfs_root *root)
3346 struct btrfs_fs_info *fs_info = root->fs_info;
3347 struct btrfs_path *path;
3348 struct extent_buffer *leaf;
3349 struct btrfs_key key, found_key;
3350 struct btrfs_trans_handle *trans;
3351 struct inode *inode;
3352 u64 last_objectid = 0;
3353 int ret = 0, nr_unlink = 0;
3355 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3356 return 0;
3358 path = btrfs_alloc_path();
3359 if (!path) {
3360 ret = -ENOMEM;
3361 goto out;
3363 path->reada = READA_BACK;
3365 key.objectid = BTRFS_ORPHAN_OBJECTID;
3366 key.type = BTRFS_ORPHAN_ITEM_KEY;
3367 key.offset = (u64)-1;
3369 while (1) {
3370 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3371 if (ret < 0)
3372 goto out;
3375 * if ret == 0 means we found what we were searching for, which
3376 * is weird, but possible, so only screw with path if we didn't
3377 * find the key and see if we have stuff that matches
3379 if (ret > 0) {
3380 ret = 0;
3381 if (path->slots[0] == 0)
3382 break;
3383 path->slots[0]--;
3386 /* pull out the item */
3387 leaf = path->nodes[0];
3388 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3390 /* make sure the item matches what we want */
3391 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3392 break;
3393 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3394 break;
3396 /* release the path since we're done with it */
3397 btrfs_release_path(path);
3400 * this is where we are basically btrfs_lookup, without the
3401 * crossing root thing. we store the inode number in the
3402 * offset of the orphan item.
3405 if (found_key.offset == last_objectid) {
3406 btrfs_err(fs_info,
3407 "Error removing orphan entry, stopping orphan cleanup");
3408 ret = -EINVAL;
3409 goto out;
3412 last_objectid = found_key.offset;
3414 found_key.objectid = found_key.offset;
3415 found_key.type = BTRFS_INODE_ITEM_KEY;
3416 found_key.offset = 0;
3417 inode = btrfs_iget(fs_info->sb, &found_key, root, NULL);
3418 ret = PTR_ERR_OR_ZERO(inode);
3419 if (ret && ret != -ENOENT)
3420 goto out;
3422 if (ret == -ENOENT && root == fs_info->tree_root) {
3423 struct btrfs_root *dead_root;
3424 struct btrfs_fs_info *fs_info = root->fs_info;
3425 int is_dead_root = 0;
3428 * this is an orphan in the tree root. Currently these
3429 * could come from 2 sources:
3430 * a) a snapshot deletion in progress
3431 * b) a free space cache inode
3432 * We need to distinguish those two, as the snapshot
3433 * orphan must not get deleted.
3434 * find_dead_roots already ran before us, so if this
3435 * is a snapshot deletion, we should find the root
3436 * in the dead_roots list
3438 spin_lock(&fs_info->trans_lock);
3439 list_for_each_entry(dead_root, &fs_info->dead_roots,
3440 root_list) {
3441 if (dead_root->root_key.objectid ==
3442 found_key.objectid) {
3443 is_dead_root = 1;
3444 break;
3447 spin_unlock(&fs_info->trans_lock);
3448 if (is_dead_root) {
3449 /* prevent this orphan from being found again */
3450 key.offset = found_key.objectid - 1;
3451 continue;
3457 * If we have an inode with links, there are a couple of
3458 * possibilities. Old kernels (before v3.12) used to create an
3459 * orphan item for truncate indicating that there were possibly
3460 * extent items past i_size that needed to be deleted. In v3.12,
3461 * truncate was changed to update i_size in sync with the extent
3462 * items, but the (useless) orphan item was still created. Since
3463 * v4.18, we don't create the orphan item for truncate at all.
3465 * So, this item could mean that we need to do a truncate, but
3466 * only if this filesystem was last used on a pre-v3.12 kernel
3467 * and was not cleanly unmounted. The odds of that are quite
3468 * slim, and it's a pain to do the truncate now, so just delete
3469 * the orphan item.
3471 * It's also possible that this orphan item was supposed to be
3472 * deleted but wasn't. The inode number may have been reused,
3473 * but either way, we can delete the orphan item.
3475 if (ret == -ENOENT || inode->i_nlink) {
3476 if (!ret)
3477 iput(inode);
3478 trans = btrfs_start_transaction(root, 1);
3479 if (IS_ERR(trans)) {
3480 ret = PTR_ERR(trans);
3481 goto out;
3483 btrfs_debug(fs_info, "auto deleting %Lu",
3484 found_key.objectid);
3485 ret = btrfs_del_orphan_item(trans, root,
3486 found_key.objectid);
3487 btrfs_end_transaction(trans);
3488 if (ret)
3489 goto out;
3490 continue;
3493 nr_unlink++;
3495 /* this will do delete_inode and everything for us */
3496 iput(inode);
3497 if (ret)
3498 goto out;
3500 /* release the path since we're done with it */
3501 btrfs_release_path(path);
3503 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3505 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3506 trans = btrfs_join_transaction(root);
3507 if (!IS_ERR(trans))
3508 btrfs_end_transaction(trans);
3511 if (nr_unlink)
3512 btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3514 out:
3515 if (ret)
3516 btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3517 btrfs_free_path(path);
3518 return ret;
3522 * very simple check to peek ahead in the leaf looking for xattrs. If we
3523 * don't find any xattrs, we know there can't be any acls.
3525 * slot is the slot the inode is in, objectid is the objectid of the inode
3527 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3528 int slot, u64 objectid,
3529 int *first_xattr_slot)
3531 u32 nritems = btrfs_header_nritems(leaf);
3532 struct btrfs_key found_key;
3533 static u64 xattr_access = 0;
3534 static u64 xattr_default = 0;
3535 int scanned = 0;
3537 if (!xattr_access) {
3538 xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3539 strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3540 xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3541 strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3544 slot++;
3545 *first_xattr_slot = -1;
3546 while (slot < nritems) {
3547 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3549 /* we found a different objectid, there must not be acls */
3550 if (found_key.objectid != objectid)
3551 return 0;
3553 /* we found an xattr, assume we've got an acl */
3554 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3555 if (*first_xattr_slot == -1)
3556 *first_xattr_slot = slot;
3557 if (found_key.offset == xattr_access ||
3558 found_key.offset == xattr_default)
3559 return 1;
3563 * we found a key greater than an xattr key, there can't
3564 * be any acls later on
3566 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3567 return 0;
3569 slot++;
3570 scanned++;
3573 * it goes inode, inode backrefs, xattrs, extents,
3574 * so if there are a ton of hard links to an inode there can
3575 * be a lot of backrefs. Don't waste time searching too hard,
3576 * this is just an optimization
3578 if (scanned >= 8)
3579 break;
3581 /* we hit the end of the leaf before we found an xattr or
3582 * something larger than an xattr. We have to assume the inode
3583 * has acls
3585 if (*first_xattr_slot == -1)
3586 *first_xattr_slot = slot;
3587 return 1;
3591 * read an inode from the btree into the in-memory inode
3593 static int btrfs_read_locked_inode(struct inode *inode)
3595 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
3596 struct btrfs_path *path;
3597 struct extent_buffer *leaf;
3598 struct btrfs_inode_item *inode_item;
3599 struct btrfs_root *root = BTRFS_I(inode)->root;
3600 struct btrfs_key location;
3601 unsigned long ptr;
3602 int maybe_acls;
3603 u32 rdev;
3604 int ret;
3605 bool filled = false;
3606 int first_xattr_slot;
3608 ret = btrfs_fill_inode(inode, &rdev);
3609 if (!ret)
3610 filled = true;
3612 path = btrfs_alloc_path();
3613 if (!path) {
3614 ret = -ENOMEM;
3615 goto make_bad;
3618 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3620 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3621 if (ret) {
3622 if (ret > 0)
3623 ret = -ENOENT;
3624 goto make_bad;
3627 leaf = path->nodes[0];
3629 if (filled)
3630 goto cache_index;
3632 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3633 struct btrfs_inode_item);
3634 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3635 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3636 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3637 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3638 btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
3640 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3641 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3643 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3644 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3646 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3647 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3649 BTRFS_I(inode)->i_otime.tv_sec =
3650 btrfs_timespec_sec(leaf, &inode_item->otime);
3651 BTRFS_I(inode)->i_otime.tv_nsec =
3652 btrfs_timespec_nsec(leaf, &inode_item->otime);
3654 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3655 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3656 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3658 inode_set_iversion_queried(inode,
3659 btrfs_inode_sequence(leaf, inode_item));
3660 inode->i_generation = BTRFS_I(inode)->generation;
3661 inode->i_rdev = 0;
3662 rdev = btrfs_inode_rdev(leaf, inode_item);
3664 BTRFS_I(inode)->index_cnt = (u64)-1;
3665 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3667 cache_index:
3669 * If we were modified in the current generation and evicted from memory
3670 * and then re-read we need to do a full sync since we don't have any
3671 * idea about which extents were modified before we were evicted from
3672 * cache.
3674 * This is required for both inode re-read from disk and delayed inode
3675 * in delayed_nodes_tree.
3677 if (BTRFS_I(inode)->last_trans == fs_info->generation)
3678 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3679 &BTRFS_I(inode)->runtime_flags);
3682 * We don't persist the id of the transaction where an unlink operation
3683 * against the inode was last made. So here we assume the inode might
3684 * have been evicted, and therefore the exact value of last_unlink_trans
3685 * lost, and set it to last_trans to avoid metadata inconsistencies
3686 * between the inode and its parent if the inode is fsync'ed and the log
3687 * replayed. For example, in the scenario:
3689 * touch mydir/foo
3690 * ln mydir/foo mydir/bar
3691 * sync
3692 * unlink mydir/bar
3693 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3694 * xfs_io -c fsync mydir/foo
3695 * <power failure>
3696 * mount fs, triggers fsync log replay
3698 * We must make sure that when we fsync our inode foo we also log its
3699 * parent inode, otherwise after log replay the parent still has the
3700 * dentry with the "bar" name but our inode foo has a link count of 1
3701 * and doesn't have an inode ref with the name "bar" anymore.
3703 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3704 * but it guarantees correctness at the expense of occasional full
3705 * transaction commits on fsync if our inode is a directory, or if our
3706 * inode is not a directory, logging its parent unnecessarily.
3708 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3710 path->slots[0]++;
3711 if (inode->i_nlink != 1 ||
3712 path->slots[0] >= btrfs_header_nritems(leaf))
3713 goto cache_acl;
3715 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3716 if (location.objectid != btrfs_ino(BTRFS_I(inode)))
3717 goto cache_acl;
3719 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3720 if (location.type == BTRFS_INODE_REF_KEY) {
3721 struct btrfs_inode_ref *ref;
3723 ref = (struct btrfs_inode_ref *)ptr;
3724 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3725 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3726 struct btrfs_inode_extref *extref;
3728 extref = (struct btrfs_inode_extref *)ptr;
3729 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3730 extref);
3732 cache_acl:
3734 * try to precache a NULL acl entry for files that don't have
3735 * any xattrs or acls
3737 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3738 btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
3739 if (first_xattr_slot != -1) {
3740 path->slots[0] = first_xattr_slot;
3741 ret = btrfs_load_inode_props(inode, path);
3742 if (ret)
3743 btrfs_err(fs_info,
3744 "error loading props for ino %llu (root %llu): %d",
3745 btrfs_ino(BTRFS_I(inode)),
3746 root->root_key.objectid, ret);
3748 btrfs_free_path(path);
3750 if (!maybe_acls)
3751 cache_no_acl(inode);
3753 switch (inode->i_mode & S_IFMT) {
3754 case S_IFREG:
3755 inode->i_mapping->a_ops = &btrfs_aops;
3756 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3757 inode->i_fop = &btrfs_file_operations;
3758 inode->i_op = &btrfs_file_inode_operations;
3759 break;
3760 case S_IFDIR:
3761 inode->i_fop = &btrfs_dir_file_operations;
3762 inode->i_op = &btrfs_dir_inode_operations;
3763 break;
3764 case S_IFLNK:
3765 inode->i_op = &btrfs_symlink_inode_operations;
3766 inode_nohighmem(inode);
3767 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3768 break;
3769 default:
3770 inode->i_op = &btrfs_special_inode_operations;
3771 init_special_inode(inode, inode->i_mode, rdev);
3772 break;
3775 btrfs_sync_inode_flags_to_i_flags(inode);
3776 return 0;
3778 make_bad:
3779 btrfs_free_path(path);
3780 make_bad_inode(inode);
3781 return ret;
3785 * given a leaf and an inode, copy the inode fields into the leaf
3787 static void fill_inode_item(struct btrfs_trans_handle *trans,
3788 struct extent_buffer *leaf,
3789 struct btrfs_inode_item *item,
3790 struct inode *inode)
3792 struct btrfs_map_token token;
3794 btrfs_init_map_token(&token);
3796 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3797 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3798 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3799 &token);
3800 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3801 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3803 btrfs_set_token_timespec_sec(leaf, &item->atime,
3804 inode->i_atime.tv_sec, &token);
3805 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3806 inode->i_atime.tv_nsec, &token);
3808 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3809 inode->i_mtime.tv_sec, &token);
3810 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3811 inode->i_mtime.tv_nsec, &token);
3813 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3814 inode->i_ctime.tv_sec, &token);
3815 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3816 inode->i_ctime.tv_nsec, &token);
3818 btrfs_set_token_timespec_sec(leaf, &item->otime,
3819 BTRFS_I(inode)->i_otime.tv_sec, &token);
3820 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3821 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3823 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3824 &token);
3825 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3826 &token);
3827 btrfs_set_token_inode_sequence(leaf, item, inode_peek_iversion(inode),
3828 &token);
3829 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3830 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3831 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3832 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3836 * copy everything in the in-memory inode into the btree.
3838 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3839 struct btrfs_root *root, struct inode *inode)
3841 struct btrfs_inode_item *inode_item;
3842 struct btrfs_path *path;
3843 struct extent_buffer *leaf;
3844 int ret;
3846 path = btrfs_alloc_path();
3847 if (!path)
3848 return -ENOMEM;
3850 path->leave_spinning = 1;
3851 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3853 if (ret) {
3854 if (ret > 0)
3855 ret = -ENOENT;
3856 goto failed;
3859 leaf = path->nodes[0];
3860 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3861 struct btrfs_inode_item);
3863 fill_inode_item(trans, leaf, inode_item, inode);
3864 btrfs_mark_buffer_dirty(leaf);
3865 btrfs_set_inode_last_trans(trans, inode);
3866 ret = 0;
3867 failed:
3868 btrfs_free_path(path);
3869 return ret;
3873 * copy everything in the in-memory inode into the btree.
3875 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3876 struct btrfs_root *root, struct inode *inode)
3878 struct btrfs_fs_info *fs_info = root->fs_info;
3879 int ret;
3882 * If the inode is a free space inode, we can deadlock during commit
3883 * if we put it into the delayed code.
3885 * The data relocation inode should also be directly updated
3886 * without delay
3888 if (!btrfs_is_free_space_inode(BTRFS_I(inode))
3889 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3890 && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
3891 btrfs_update_root_times(trans, root);
3893 ret = btrfs_delayed_update_inode(trans, root, inode);
3894 if (!ret)
3895 btrfs_set_inode_last_trans(trans, inode);
3896 return ret;
3899 return btrfs_update_inode_item(trans, root, inode);
3902 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3903 struct btrfs_root *root,
3904 struct inode *inode)
3906 int ret;
3908 ret = btrfs_update_inode(trans, root, inode);
3909 if (ret == -ENOSPC)
3910 return btrfs_update_inode_item(trans, root, inode);
3911 return ret;
3915 * unlink helper that gets used here in inode.c and in the tree logging
3916 * recovery code. It remove a link in a directory with a given name, and
3917 * also drops the back refs in the inode to the directory
3919 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3920 struct btrfs_root *root,
3921 struct btrfs_inode *dir,
3922 struct btrfs_inode *inode,
3923 const char *name, int name_len)
3925 struct btrfs_fs_info *fs_info = root->fs_info;
3926 struct btrfs_path *path;
3927 int ret = 0;
3928 struct extent_buffer *leaf;
3929 struct btrfs_dir_item *di;
3930 struct btrfs_key key;
3931 u64 index;
3932 u64 ino = btrfs_ino(inode);
3933 u64 dir_ino = btrfs_ino(dir);
3935 path = btrfs_alloc_path();
3936 if (!path) {
3937 ret = -ENOMEM;
3938 goto out;
3941 path->leave_spinning = 1;
3942 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3943 name, name_len, -1);
3944 if (IS_ERR(di)) {
3945 ret = PTR_ERR(di);
3946 goto err;
3948 if (!di) {
3949 ret = -ENOENT;
3950 goto err;
3952 leaf = path->nodes[0];
3953 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3954 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3955 if (ret)
3956 goto err;
3957 btrfs_release_path(path);
3960 * If we don't have dir index, we have to get it by looking up
3961 * the inode ref, since we get the inode ref, remove it directly,
3962 * it is unnecessary to do delayed deletion.
3964 * But if we have dir index, needn't search inode ref to get it.
3965 * Since the inode ref is close to the inode item, it is better
3966 * that we delay to delete it, and just do this deletion when
3967 * we update the inode item.
3969 if (inode->dir_index) {
3970 ret = btrfs_delayed_delete_inode_ref(inode);
3971 if (!ret) {
3972 index = inode->dir_index;
3973 goto skip_backref;
3977 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
3978 dir_ino, &index);
3979 if (ret) {
3980 btrfs_info(fs_info,
3981 "failed to delete reference to %.*s, inode %llu parent %llu",
3982 name_len, name, ino, dir_ino);
3983 btrfs_abort_transaction(trans, ret);
3984 goto err;
3986 skip_backref:
3987 ret = btrfs_delete_delayed_dir_index(trans, fs_info, dir, index);
3988 if (ret) {
3989 btrfs_abort_transaction(trans, ret);
3990 goto err;
3993 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode,
3994 dir_ino);
3995 if (ret != 0 && ret != -ENOENT) {
3996 btrfs_abort_transaction(trans, ret);
3997 goto err;
4000 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir,
4001 index);
4002 if (ret == -ENOENT)
4003 ret = 0;
4004 else if (ret)
4005 btrfs_abort_transaction(trans, ret);
4006 err:
4007 btrfs_free_path(path);
4008 if (ret)
4009 goto out;
4011 btrfs_i_size_write(dir, dir->vfs_inode.i_size - name_len * 2);
4012 inode_inc_iversion(&inode->vfs_inode);
4013 inode_inc_iversion(&dir->vfs_inode);
4014 inode->vfs_inode.i_ctime = dir->vfs_inode.i_mtime =
4015 dir->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
4016 ret = btrfs_update_inode(trans, root, &dir->vfs_inode);
4017 out:
4018 return ret;
4021 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4022 struct btrfs_root *root,
4023 struct btrfs_inode *dir, struct btrfs_inode *inode,
4024 const char *name, int name_len)
4026 int ret;
4027 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4028 if (!ret) {
4029 drop_nlink(&inode->vfs_inode);
4030 ret = btrfs_update_inode(trans, root, &inode->vfs_inode);
4032 return ret;
4036 * helper to start transaction for unlink and rmdir.
4038 * unlink and rmdir are special in btrfs, they do not always free space, so
4039 * if we cannot make our reservations the normal way try and see if there is
4040 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4041 * allow the unlink to occur.
4043 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4045 struct btrfs_root *root = BTRFS_I(dir)->root;
4048 * 1 for the possible orphan item
4049 * 1 for the dir item
4050 * 1 for the dir index
4051 * 1 for the inode ref
4052 * 1 for the inode
4054 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4057 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4059 struct btrfs_root *root = BTRFS_I(dir)->root;
4060 struct btrfs_trans_handle *trans;
4061 struct inode *inode = d_inode(dentry);
4062 int ret;
4064 trans = __unlink_start_trans(dir);
4065 if (IS_ERR(trans))
4066 return PTR_ERR(trans);
4068 btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4071 ret = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4072 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4073 dentry->d_name.len);
4074 if (ret)
4075 goto out;
4077 if (inode->i_nlink == 0) {
4078 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4079 if (ret)
4080 goto out;
4083 out:
4084 btrfs_end_transaction(trans);
4085 btrfs_btree_balance_dirty(root->fs_info);
4086 return ret;
4089 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4090 struct btrfs_root *root,
4091 struct inode *dir, u64 objectid,
4092 const char *name, int name_len)
4094 struct btrfs_fs_info *fs_info = root->fs_info;
4095 struct btrfs_path *path;
4096 struct extent_buffer *leaf;
4097 struct btrfs_dir_item *di;
4098 struct btrfs_key key;
4099 u64 index;
4100 int ret;
4101 u64 dir_ino = btrfs_ino(BTRFS_I(dir));
4103 path = btrfs_alloc_path();
4104 if (!path)
4105 return -ENOMEM;
4107 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4108 name, name_len, -1);
4109 if (IS_ERR_OR_NULL(di)) {
4110 if (!di)
4111 ret = -ENOENT;
4112 else
4113 ret = PTR_ERR(di);
4114 goto out;
4117 leaf = path->nodes[0];
4118 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4119 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4120 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4121 if (ret) {
4122 btrfs_abort_transaction(trans, ret);
4123 goto out;
4125 btrfs_release_path(path);
4127 ret = btrfs_del_root_ref(trans, fs_info, objectid,
4128 root->root_key.objectid, dir_ino,
4129 &index, name, name_len);
4130 if (ret < 0) {
4131 if (ret != -ENOENT) {
4132 btrfs_abort_transaction(trans, ret);
4133 goto out;
4135 di = btrfs_search_dir_index_item(root, path, dir_ino,
4136 name, name_len);
4137 if (IS_ERR_OR_NULL(di)) {
4138 if (!di)
4139 ret = -ENOENT;
4140 else
4141 ret = PTR_ERR(di);
4142 btrfs_abort_transaction(trans, ret);
4143 goto out;
4146 leaf = path->nodes[0];
4147 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4148 btrfs_release_path(path);
4149 index = key.offset;
4151 btrfs_release_path(path);
4153 ret = btrfs_delete_delayed_dir_index(trans, fs_info, BTRFS_I(dir), index);
4154 if (ret) {
4155 btrfs_abort_transaction(trans, ret);
4156 goto out;
4159 btrfs_i_size_write(BTRFS_I(dir), dir->i_size - name_len * 2);
4160 inode_inc_iversion(dir);
4161 dir->i_mtime = dir->i_ctime = current_time(dir);
4162 ret = btrfs_update_inode_fallback(trans, root, dir);
4163 if (ret)
4164 btrfs_abort_transaction(trans, ret);
4165 out:
4166 btrfs_free_path(path);
4167 return ret;
4171 * Helper to check if the subvolume references other subvolumes or if it's
4172 * default.
4174 static noinline int may_destroy_subvol(struct btrfs_root *root)
4176 struct btrfs_fs_info *fs_info = root->fs_info;
4177 struct btrfs_path *path;
4178 struct btrfs_dir_item *di;
4179 struct btrfs_key key;
4180 u64 dir_id;
4181 int ret;
4183 path = btrfs_alloc_path();
4184 if (!path)
4185 return -ENOMEM;
4187 /* Make sure this root isn't set as the default subvol */
4188 dir_id = btrfs_super_root_dir(fs_info->super_copy);
4189 di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4190 dir_id, "default", 7, 0);
4191 if (di && !IS_ERR(di)) {
4192 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4193 if (key.objectid == root->root_key.objectid) {
4194 ret = -EPERM;
4195 btrfs_err(fs_info,
4196 "deleting default subvolume %llu is not allowed",
4197 key.objectid);
4198 goto out;
4200 btrfs_release_path(path);
4203 key.objectid = root->root_key.objectid;
4204 key.type = BTRFS_ROOT_REF_KEY;
4205 key.offset = (u64)-1;
4207 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4208 if (ret < 0)
4209 goto out;
4210 BUG_ON(ret == 0);
4212 ret = 0;
4213 if (path->slots[0] > 0) {
4214 path->slots[0]--;
4215 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4216 if (key.objectid == root->root_key.objectid &&
4217 key.type == BTRFS_ROOT_REF_KEY)
4218 ret = -ENOTEMPTY;
4220 out:
4221 btrfs_free_path(path);
4222 return ret;
4225 /* Delete all dentries for inodes belonging to the root */
4226 static void btrfs_prune_dentries(struct btrfs_root *root)
4228 struct btrfs_fs_info *fs_info = root->fs_info;
4229 struct rb_node *node;
4230 struct rb_node *prev;
4231 struct btrfs_inode *entry;
4232 struct inode *inode;
4233 u64 objectid = 0;
4235 if (!test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
4236 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4238 spin_lock(&root->inode_lock);
4239 again:
4240 node = root->inode_tree.rb_node;
4241 prev = NULL;
4242 while (node) {
4243 prev = node;
4244 entry = rb_entry(node, struct btrfs_inode, rb_node);
4246 if (objectid < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4247 node = node->rb_left;
4248 else if (objectid > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
4249 node = node->rb_right;
4250 else
4251 break;
4253 if (!node) {
4254 while (prev) {
4255 entry = rb_entry(prev, struct btrfs_inode, rb_node);
4256 if (objectid <= btrfs_ino(BTRFS_I(&entry->vfs_inode))) {
4257 node = prev;
4258 break;
4260 prev = rb_next(prev);
4263 while (node) {
4264 entry = rb_entry(node, struct btrfs_inode, rb_node);
4265 objectid = btrfs_ino(BTRFS_I(&entry->vfs_inode)) + 1;
4266 inode = igrab(&entry->vfs_inode);
4267 if (inode) {
4268 spin_unlock(&root->inode_lock);
4269 if (atomic_read(&inode->i_count) > 1)
4270 d_prune_aliases(inode);
4272 * btrfs_drop_inode will have it removed from the inode
4273 * cache when its usage count hits zero.
4275 iput(inode);
4276 cond_resched();
4277 spin_lock(&root->inode_lock);
4278 goto again;
4281 if (cond_resched_lock(&root->inode_lock))
4282 goto again;
4284 node = rb_next(node);
4286 spin_unlock(&root->inode_lock);
4289 int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
4291 struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
4292 struct btrfs_root *root = BTRFS_I(dir)->root;
4293 struct inode *inode = d_inode(dentry);
4294 struct btrfs_root *dest = BTRFS_I(inode)->root;
4295 struct btrfs_trans_handle *trans;
4296 struct btrfs_block_rsv block_rsv;
4297 u64 root_flags;
4298 int ret;
4299 int err;
4302 * Don't allow to delete a subvolume with send in progress. This is
4303 * inside the inode lock so the error handling that has to drop the bit
4304 * again is not run concurrently.
4306 spin_lock(&dest->root_item_lock);
4307 root_flags = btrfs_root_flags(&dest->root_item);
4308 if (dest->send_in_progress == 0) {
4309 btrfs_set_root_flags(&dest->root_item,
4310 root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4311 spin_unlock(&dest->root_item_lock);
4312 } else {
4313 spin_unlock(&dest->root_item_lock);
4314 btrfs_warn(fs_info,
4315 "attempt to delete subvolume %llu during send",
4316 dest->root_key.objectid);
4317 return -EPERM;
4320 down_write(&fs_info->subvol_sem);
4322 err = may_destroy_subvol(dest);
4323 if (err)
4324 goto out_up_write;
4326 btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4328 * One for dir inode,
4329 * two for dir entries,
4330 * two for root ref/backref.
4332 err = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4333 if (err)
4334 goto out_up_write;
4336 trans = btrfs_start_transaction(root, 0);
4337 if (IS_ERR(trans)) {
4338 err = PTR_ERR(trans);
4339 goto out_release;
4341 trans->block_rsv = &block_rsv;
4342 trans->bytes_reserved = block_rsv.size;
4344 btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
4346 ret = btrfs_unlink_subvol(trans, root, dir,
4347 dest->root_key.objectid,
4348 dentry->d_name.name,
4349 dentry->d_name.len);
4350 if (ret) {
4351 err = ret;
4352 btrfs_abort_transaction(trans, ret);
4353 goto out_end_trans;
4356 btrfs_record_root_in_trans(trans, dest);
4358 memset(&dest->root_item.drop_progress, 0,
4359 sizeof(dest->root_item.drop_progress));
4360 dest->root_item.drop_level = 0;
4361 btrfs_set_root_refs(&dest->root_item, 0);
4363 if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4364 ret = btrfs_insert_orphan_item(trans,
4365 fs_info->tree_root,
4366 dest->root_key.objectid);
4367 if (ret) {
4368 btrfs_abort_transaction(trans, ret);
4369 err = ret;
4370 goto out_end_trans;
4374 ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4375 BTRFS_UUID_KEY_SUBVOL,
4376 dest->root_key.objectid);
4377 if (ret && ret != -ENOENT) {
4378 btrfs_abort_transaction(trans, ret);
4379 err = ret;
4380 goto out_end_trans;
4382 if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4383 ret = btrfs_uuid_tree_remove(trans,
4384 dest->root_item.received_uuid,
4385 BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4386 dest->root_key.objectid);
4387 if (ret && ret != -ENOENT) {
4388 btrfs_abort_transaction(trans, ret);
4389 err = ret;
4390 goto out_end_trans;
4394 out_end_trans:
4395 trans->block_rsv = NULL;
4396 trans->bytes_reserved = 0;
4397 ret = btrfs_end_transaction(trans);
4398 if (ret && !err)
4399 err = ret;
4400 inode->i_flags |= S_DEAD;
4401 out_release:
4402 btrfs_subvolume_release_metadata(fs_info, &block_rsv);
4403 out_up_write:
4404 up_write(&fs_info->subvol_sem);
4405 if (err) {
4406 spin_lock(&dest->root_item_lock);
4407 root_flags = btrfs_root_flags(&dest->root_item);
4408 btrfs_set_root_flags(&dest->root_item,
4409 root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4410 spin_unlock(&dest->root_item_lock);
4411 } else {
4412 d_invalidate(dentry);
4413 btrfs_prune_dentries(dest);
4414 ASSERT(dest->send_in_progress == 0);
4416 /* the last ref */
4417 if (dest->ino_cache_inode) {
4418 iput(dest->ino_cache_inode);
4419 dest->ino_cache_inode = NULL;
4423 return err;
4426 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4428 struct inode *inode = d_inode(dentry);
4429 int err = 0;
4430 struct btrfs_root *root = BTRFS_I(dir)->root;
4431 struct btrfs_trans_handle *trans;
4432 u64 last_unlink_trans;
4434 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4435 return -ENOTEMPTY;
4436 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID)
4437 return btrfs_delete_subvolume(dir, dentry);
4439 trans = __unlink_start_trans(dir);
4440 if (IS_ERR(trans))
4441 return PTR_ERR(trans);
4443 if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4444 err = btrfs_unlink_subvol(trans, root, dir,
4445 BTRFS_I(inode)->location.objectid,
4446 dentry->d_name.name,
4447 dentry->d_name.len);
4448 goto out;
4451 err = btrfs_orphan_add(trans, BTRFS_I(inode));
4452 if (err)
4453 goto out;
4455 last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
4457 /* now the directory is empty */
4458 err = btrfs_unlink_inode(trans, root, BTRFS_I(dir),
4459 BTRFS_I(d_inode(dentry)), dentry->d_name.name,
4460 dentry->d_name.len);
4461 if (!err) {
4462 btrfs_i_size_write(BTRFS_I(inode), 0);
4464 * Propagate the last_unlink_trans value of the deleted dir to
4465 * its parent directory. This is to prevent an unrecoverable
4466 * log tree in the case we do something like this:
4467 * 1) create dir foo
4468 * 2) create snapshot under dir foo
4469 * 3) delete the snapshot
4470 * 4) rmdir foo
4471 * 5) mkdir foo
4472 * 6) fsync foo or some file inside foo
4474 if (last_unlink_trans >= trans->transid)
4475 BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
4477 out:
4478 btrfs_end_transaction(trans);
4479 btrfs_btree_balance_dirty(root->fs_info);
4481 return err;
4484 static int truncate_space_check(struct btrfs_trans_handle *trans,
4485 struct btrfs_root *root,
4486 u64 bytes_deleted)
4488 struct btrfs_fs_info *fs_info = root->fs_info;
4489 int ret;
4492 * This is only used to apply pressure to the enospc system, we don't
4493 * intend to use this reservation at all.
4495 bytes_deleted = btrfs_csum_bytes_to_leaves(fs_info, bytes_deleted);
4496 bytes_deleted *= fs_info->nodesize;
4497 ret = btrfs_block_rsv_add(root, &fs_info->trans_block_rsv,
4498 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4499 if (!ret) {
4500 trace_btrfs_space_reservation(fs_info, "transaction",
4501 trans->transid,
4502 bytes_deleted, 1);
4503 trans->bytes_reserved += bytes_deleted;
4505 return ret;
4510 * Return this if we need to call truncate_block for the last bit of the
4511 * truncate.
4513 #define NEED_TRUNCATE_BLOCK 1
4516 * this can truncate away extent items, csum items and directory items.
4517 * It starts at a high offset and removes keys until it can't find
4518 * any higher than new_size
4520 * csum items that cross the new i_size are truncated to the new size
4521 * as well.
4523 * min_type is the minimum key type to truncate down to. If set to 0, this
4524 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4526 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4527 struct btrfs_root *root,
4528 struct inode *inode,
4529 u64 new_size, u32 min_type)
4531 struct btrfs_fs_info *fs_info = root->fs_info;
4532 struct btrfs_path *path;
4533 struct extent_buffer *leaf;
4534 struct btrfs_file_extent_item *fi;
4535 struct btrfs_key key;
4536 struct btrfs_key found_key;
4537 u64 extent_start = 0;
4538 u64 extent_num_bytes = 0;
4539 u64 extent_offset = 0;
4540 u64 item_end = 0;
4541 u64 last_size = new_size;
4542 u32 found_type = (u8)-1;
4543 int found_extent;
4544 int del_item;
4545 int pending_del_nr = 0;
4546 int pending_del_slot = 0;
4547 int extent_type = -1;
4548 int ret;
4549 u64 ino = btrfs_ino(BTRFS_I(inode));
4550 u64 bytes_deleted = 0;
4551 bool be_nice = false;
4552 bool should_throttle = false;
4553 bool should_end = false;
4555 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4558 * for non-free space inodes and ref cows, we want to back off from
4559 * time to time
4561 if (!btrfs_is_free_space_inode(BTRFS_I(inode)) &&
4562 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4563 be_nice = true;
4565 path = btrfs_alloc_path();
4566 if (!path)
4567 return -ENOMEM;
4568 path->reada = READA_BACK;
4571 * We want to drop from the next block forward in case this new size is
4572 * not block aligned since we will be keeping the last block of the
4573 * extent just the way it is.
4575 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4576 root == fs_info->tree_root)
4577 btrfs_drop_extent_cache(BTRFS_I(inode), ALIGN(new_size,
4578 fs_info->sectorsize),
4579 (u64)-1, 0);
4582 * This function is also used to drop the items in the log tree before
4583 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4584 * it is used to drop the loged items. So we shouldn't kill the delayed
4585 * items.
4587 if (min_type == 0 && root == BTRFS_I(inode)->root)
4588 btrfs_kill_delayed_inode_items(BTRFS_I(inode));
4590 key.objectid = ino;
4591 key.offset = (u64)-1;
4592 key.type = (u8)-1;
4594 search_again:
4596 * with a 16K leaf size and 128MB extents, you can actually queue
4597 * up a huge file in a single leaf. Most of the time that
4598 * bytes_deleted is > 0, it will be huge by the time we get here
4600 if (be_nice && bytes_deleted > SZ_32M &&
4601 btrfs_should_end_transaction(trans)) {
4602 ret = -EAGAIN;
4603 goto out;
4606 path->leave_spinning = 1;
4607 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4608 if (ret < 0)
4609 goto out;
4611 if (ret > 0) {
4612 ret = 0;
4613 /* there are no items in the tree for us to truncate, we're
4614 * done
4616 if (path->slots[0] == 0)
4617 goto out;
4618 path->slots[0]--;
4621 while (1) {
4622 fi = NULL;
4623 leaf = path->nodes[0];
4624 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4625 found_type = found_key.type;
4627 if (found_key.objectid != ino)
4628 break;
4630 if (found_type < min_type)
4631 break;
4633 item_end = found_key.offset;
4634 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4635 fi = btrfs_item_ptr(leaf, path->slots[0],
4636 struct btrfs_file_extent_item);
4637 extent_type = btrfs_file_extent_type(leaf, fi);
4638 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4639 item_end +=
4640 btrfs_file_extent_num_bytes(leaf, fi);
4642 trace_btrfs_truncate_show_fi_regular(
4643 BTRFS_I(inode), leaf, fi,
4644 found_key.offset);
4645 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4646 item_end += btrfs_file_extent_inline_len(leaf,
4647 path->slots[0], fi);
4649 trace_btrfs_truncate_show_fi_inline(
4650 BTRFS_I(inode), leaf, fi, path->slots[0],
4651 found_key.offset);
4653 item_end--;
4655 if (found_type > min_type) {
4656 del_item = 1;
4657 } else {
4658 if (item_end < new_size)
4659 break;
4660 if (found_key.offset >= new_size)
4661 del_item = 1;
4662 else
4663 del_item = 0;
4665 found_extent = 0;
4666 /* FIXME, shrink the extent if the ref count is only 1 */
4667 if (found_type != BTRFS_EXTENT_DATA_KEY)
4668 goto delete;
4670 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4671 u64 num_dec;
4672 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4673 if (!del_item) {
4674 u64 orig_num_bytes =
4675 btrfs_file_extent_num_bytes(leaf, fi);
4676 extent_num_bytes = ALIGN(new_size -
4677 found_key.offset,
4678 fs_info->sectorsize);
4679 btrfs_set_file_extent_num_bytes(leaf, fi,
4680 extent_num_bytes);
4681 num_dec = (orig_num_bytes -
4682 extent_num_bytes);
4683 if (test_bit(BTRFS_ROOT_REF_COWS,
4684 &root->state) &&
4685 extent_start != 0)
4686 inode_sub_bytes(inode, num_dec);
4687 btrfs_mark_buffer_dirty(leaf);
4688 } else {
4689 extent_num_bytes =
4690 btrfs_file_extent_disk_num_bytes(leaf,
4691 fi);
4692 extent_offset = found_key.offset -
4693 btrfs_file_extent_offset(leaf, fi);
4695 /* FIXME blocksize != 4096 */
4696 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4697 if (extent_start != 0) {
4698 found_extent = 1;
4699 if (test_bit(BTRFS_ROOT_REF_COWS,
4700 &root->state))
4701 inode_sub_bytes(inode, num_dec);
4704 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4706 * we can't truncate inline items that have had
4707 * special encodings
4709 if (!del_item &&
4710 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4711 btrfs_file_extent_other_encoding(leaf, fi) == 0 &&
4712 btrfs_file_extent_compression(leaf, fi) == 0) {
4713 u32 size = (u32)(new_size - found_key.offset);
4715 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4716 size = btrfs_file_extent_calc_inline_size(size);
4717 btrfs_truncate_item(root->fs_info, path, size, 1);
4718 } else if (!del_item) {
4720 * We have to bail so the last_size is set to
4721 * just before this extent.
4723 ret = NEED_TRUNCATE_BLOCK;
4724 break;
4727 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4728 inode_sub_bytes(inode, item_end + 1 - new_size);
4730 delete:
4731 if (del_item)
4732 last_size = found_key.offset;
4733 else
4734 last_size = new_size;
4735 if (del_item) {
4736 if (!pending_del_nr) {
4737 /* no pending yet, add ourselves */
4738 pending_del_slot = path->slots[0];
4739 pending_del_nr = 1;
4740 } else if (pending_del_nr &&
4741 path->slots[0] + 1 == pending_del_slot) {
4742 /* hop on the pending chunk */
4743 pending_del_nr++;
4744 pending_del_slot = path->slots[0];
4745 } else {
4746 BUG();
4748 } else {
4749 break;
4751 should_throttle = false;
4753 if (found_extent &&
4754 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4755 root == fs_info->tree_root)) {
4756 btrfs_set_path_blocking(path);
4757 bytes_deleted += extent_num_bytes;
4758 ret = btrfs_free_extent(trans, root, extent_start,
4759 extent_num_bytes, 0,
4760 btrfs_header_owner(leaf),
4761 ino, extent_offset);
4762 if (ret) {
4763 btrfs_abort_transaction(trans, ret);
4764 break;
4766 if (btrfs_should_throttle_delayed_refs(trans, fs_info))
4767 btrfs_async_run_delayed_refs(fs_info,
4768 trans->delayed_ref_updates * 2,
4769 trans->transid, 0);
4770 if (be_nice) {
4771 if (truncate_space_check(trans, root,
4772 extent_num_bytes)) {
4773 should_end = true;
4775 if (btrfs_should_throttle_delayed_refs(trans,
4776 fs_info))
4777 should_throttle = true;
4781 if (found_type == BTRFS_INODE_ITEM_KEY)
4782 break;
4784 if (path->slots[0] == 0 ||
4785 path->slots[0] != pending_del_slot ||
4786 should_throttle || should_end) {
4787 if (pending_del_nr) {
4788 ret = btrfs_del_items(trans, root, path,
4789 pending_del_slot,
4790 pending_del_nr);
4791 if (ret) {
4792 btrfs_abort_transaction(trans, ret);
4793 break;
4795 pending_del_nr = 0;
4797 btrfs_release_path(path);
4798 if (should_throttle) {
4799 unsigned long updates = trans->delayed_ref_updates;
4800 if (updates) {
4801 trans->delayed_ref_updates = 0;
4802 ret = btrfs_run_delayed_refs(trans,
4803 updates * 2);
4804 if (ret)
4805 break;
4809 * if we failed to refill our space rsv, bail out
4810 * and let the transaction restart
4812 if (should_end) {
4813 ret = -EAGAIN;
4814 break;
4816 goto search_again;
4817 } else {
4818 path->slots[0]--;
4821 out:
4822 if (ret >= 0 && pending_del_nr) {
4823 int err;
4825 err = btrfs_del_items(trans, root, path, pending_del_slot,
4826 pending_del_nr);
4827 if (err) {
4828 btrfs_abort_transaction(trans, err);
4829 ret = err;
4832 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4833 ASSERT(last_size >= new_size);
4834 if (!ret && last_size > new_size)
4835 last_size = new_size;
4836 btrfs_ordered_update_i_size(inode, last_size, NULL);
4839 btrfs_free_path(path);
4841 if (be_nice && bytes_deleted > SZ_32M && (ret >= 0 || ret == -EAGAIN)) {
4842 unsigned long updates = trans->delayed_ref_updates;
4843 int err;
4845 if (updates) {
4846 trans->delayed_ref_updates = 0;
4847 err = btrfs_run_delayed_refs(trans, updates * 2);
4848 if (err)
4849 ret = err;
4852 return ret;
4856 * btrfs_truncate_block - read, zero a chunk and write a block
4857 * @inode - inode that we're zeroing
4858 * @from - the offset to start zeroing
4859 * @len - the length to zero, 0 to zero the entire range respective to the
4860 * offset
4861 * @front - zero up to the offset instead of from the offset on
4863 * This will find the block for the "from" offset and cow the block and zero the
4864 * part we want to zero. This is used with truncate and hole punching.
4866 int btrfs_truncate_block(struct inode *inode, loff_t from, loff_t len,
4867 int front)
4869 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4870 struct address_space *mapping = inode->i_mapping;
4871 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4872 struct btrfs_ordered_extent *ordered;
4873 struct extent_state *cached_state = NULL;
4874 struct extent_changeset *data_reserved = NULL;
4875 char *kaddr;
4876 u32 blocksize = fs_info->sectorsize;
4877 pgoff_t index = from >> PAGE_SHIFT;
4878 unsigned offset = from & (blocksize - 1);
4879 struct page *page;
4880 gfp_t mask = btrfs_alloc_write_mask(mapping);
4881 int ret = 0;
4882 u64 block_start;
4883 u64 block_end;
4885 if (IS_ALIGNED(offset, blocksize) &&
4886 (!len || IS_ALIGNED(len, blocksize)))
4887 goto out;
4889 block_start = round_down(from, blocksize);
4890 block_end = block_start + blocksize - 1;
4892 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
4893 block_start, blocksize);
4894 if (ret)
4895 goto out;
4897 again:
4898 page = find_or_create_page(mapping, index, mask);
4899 if (!page) {
4900 btrfs_delalloc_release_space(inode, data_reserved,
4901 block_start, blocksize, true);
4902 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, true);
4903 ret = -ENOMEM;
4904 goto out;
4907 if (!PageUptodate(page)) {
4908 ret = btrfs_readpage(NULL, page);
4909 lock_page(page);
4910 if (page->mapping != mapping) {
4911 unlock_page(page);
4912 put_page(page);
4913 goto again;
4915 if (!PageUptodate(page)) {
4916 ret = -EIO;
4917 goto out_unlock;
4920 wait_on_page_writeback(page);
4922 lock_extent_bits(io_tree, block_start, block_end, &cached_state);
4923 set_page_extent_mapped(page);
4925 ordered = btrfs_lookup_ordered_extent(inode, block_start);
4926 if (ordered) {
4927 unlock_extent_cached(io_tree, block_start, block_end,
4928 &cached_state);
4929 unlock_page(page);
4930 put_page(page);
4931 btrfs_start_ordered_extent(inode, ordered, 1);
4932 btrfs_put_ordered_extent(ordered);
4933 goto again;
4936 clear_extent_bit(&BTRFS_I(inode)->io_tree, block_start, block_end,
4937 EXTENT_DIRTY | EXTENT_DELALLOC |
4938 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4939 0, 0, &cached_state);
4941 ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
4942 &cached_state, 0);
4943 if (ret) {
4944 unlock_extent_cached(io_tree, block_start, block_end,
4945 &cached_state);
4946 goto out_unlock;
4949 if (offset != blocksize) {
4950 if (!len)
4951 len = blocksize - offset;
4952 kaddr = kmap(page);
4953 if (front)
4954 memset(kaddr + (block_start - page_offset(page)),
4955 0, offset);
4956 else
4957 memset(kaddr + (block_start - page_offset(page)) + offset,
4958 0, len);
4959 flush_dcache_page(page);
4960 kunmap(page);
4962 ClearPageChecked(page);
4963 set_page_dirty(page);
4964 unlock_extent_cached(io_tree, block_start, block_end, &cached_state);
4966 out_unlock:
4967 if (ret)
4968 btrfs_delalloc_release_space(inode, data_reserved, block_start,
4969 blocksize, true);
4970 btrfs_delalloc_release_extents(BTRFS_I(inode), blocksize, (ret != 0));
4971 unlock_page(page);
4972 put_page(page);
4973 out:
4974 extent_changeset_free(data_reserved);
4975 return ret;
4978 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4979 u64 offset, u64 len)
4981 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4982 struct btrfs_trans_handle *trans;
4983 int ret;
4986 * Still need to make sure the inode looks like it's been updated so
4987 * that any holes get logged if we fsync.
4989 if (btrfs_fs_incompat(fs_info, NO_HOLES)) {
4990 BTRFS_I(inode)->last_trans = fs_info->generation;
4991 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4992 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4993 return 0;
4997 * 1 - for the one we're dropping
4998 * 1 - for the one we're adding
4999 * 1 - for updating the inode.
5001 trans = btrfs_start_transaction(root, 3);
5002 if (IS_ERR(trans))
5003 return PTR_ERR(trans);
5005 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
5006 if (ret) {
5007 btrfs_abort_transaction(trans, ret);
5008 btrfs_end_transaction(trans);
5009 return ret;
5012 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(BTRFS_I(inode)),
5013 offset, 0, 0, len, 0, len, 0, 0, 0);
5014 if (ret)
5015 btrfs_abort_transaction(trans, ret);
5016 else
5017 btrfs_update_inode(trans, root, inode);
5018 btrfs_end_transaction(trans);
5019 return ret;
5023 * This function puts in dummy file extents for the area we're creating a hole
5024 * for. So if we are truncating this file to a larger size we need to insert
5025 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5026 * the range between oldsize and size
5028 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
5030 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5031 struct btrfs_root *root = BTRFS_I(inode)->root;
5032 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5033 struct extent_map *em = NULL;
5034 struct extent_state *cached_state = NULL;
5035 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
5036 u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5037 u64 block_end = ALIGN(size, fs_info->sectorsize);
5038 u64 last_byte;
5039 u64 cur_offset;
5040 u64 hole_size;
5041 int err = 0;
5044 * If our size started in the middle of a block we need to zero out the
5045 * rest of the block before we expand the i_size, otherwise we could
5046 * expose stale data.
5048 err = btrfs_truncate_block(inode, oldsize, 0, 0);
5049 if (err)
5050 return err;
5052 if (size <= hole_start)
5053 return 0;
5055 while (1) {
5056 struct btrfs_ordered_extent *ordered;
5058 lock_extent_bits(io_tree, hole_start, block_end - 1,
5059 &cached_state);
5060 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), hole_start,
5061 block_end - hole_start);
5062 if (!ordered)
5063 break;
5064 unlock_extent_cached(io_tree, hole_start, block_end - 1,
5065 &cached_state);
5066 btrfs_start_ordered_extent(inode, ordered, 1);
5067 btrfs_put_ordered_extent(ordered);
5070 cur_offset = hole_start;
5071 while (1) {
5072 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
5073 block_end - cur_offset, 0);
5074 if (IS_ERR(em)) {
5075 err = PTR_ERR(em);
5076 em = NULL;
5077 break;
5079 last_byte = min(extent_map_end(em), block_end);
5080 last_byte = ALIGN(last_byte, fs_info->sectorsize);
5081 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
5082 struct extent_map *hole_em;
5083 hole_size = last_byte - cur_offset;
5085 err = maybe_insert_hole(root, inode, cur_offset,
5086 hole_size);
5087 if (err)
5088 break;
5089 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
5090 cur_offset + hole_size - 1, 0);
5091 hole_em = alloc_extent_map();
5092 if (!hole_em) {
5093 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
5094 &BTRFS_I(inode)->runtime_flags);
5095 goto next;
5097 hole_em->start = cur_offset;
5098 hole_em->len = hole_size;
5099 hole_em->orig_start = cur_offset;
5101 hole_em->block_start = EXTENT_MAP_HOLE;
5102 hole_em->block_len = 0;
5103 hole_em->orig_block_len = 0;
5104 hole_em->ram_bytes = hole_size;
5105 hole_em->bdev = fs_info->fs_devices->latest_bdev;
5106 hole_em->compress_type = BTRFS_COMPRESS_NONE;
5107 hole_em->generation = fs_info->generation;
5109 while (1) {
5110 write_lock(&em_tree->lock);
5111 err = add_extent_mapping(em_tree, hole_em, 1);
5112 write_unlock(&em_tree->lock);
5113 if (err != -EEXIST)
5114 break;
5115 btrfs_drop_extent_cache(BTRFS_I(inode),
5116 cur_offset,
5117 cur_offset +
5118 hole_size - 1, 0);
5120 free_extent_map(hole_em);
5122 next:
5123 free_extent_map(em);
5124 em = NULL;
5125 cur_offset = last_byte;
5126 if (cur_offset >= block_end)
5127 break;
5129 free_extent_map(em);
5130 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state);
5131 return err;
5134 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5136 struct btrfs_root *root = BTRFS_I(inode)->root;
5137 struct btrfs_trans_handle *trans;
5138 loff_t oldsize = i_size_read(inode);
5139 loff_t newsize = attr->ia_size;
5140 int mask = attr->ia_valid;
5141 int ret;
5144 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5145 * special case where we need to update the times despite not having
5146 * these flags set. For all other operations the VFS set these flags
5147 * explicitly if it wants a timestamp update.
5149 if (newsize != oldsize) {
5150 inode_inc_iversion(inode);
5151 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
5152 inode->i_ctime = inode->i_mtime =
5153 current_time(inode);
5156 if (newsize > oldsize) {
5158 * Don't do an expanding truncate while snapshotting is ongoing.
5159 * This is to ensure the snapshot captures a fully consistent
5160 * state of this file - if the snapshot captures this expanding
5161 * truncation, it must capture all writes that happened before
5162 * this truncation.
5164 btrfs_wait_for_snapshot_creation(root);
5165 ret = btrfs_cont_expand(inode, oldsize, newsize);
5166 if (ret) {
5167 btrfs_end_write_no_snapshotting(root);
5168 return ret;
5171 trans = btrfs_start_transaction(root, 1);
5172 if (IS_ERR(trans)) {
5173 btrfs_end_write_no_snapshotting(root);
5174 return PTR_ERR(trans);
5177 i_size_write(inode, newsize);
5178 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
5179 pagecache_isize_extended(inode, oldsize, newsize);
5180 ret = btrfs_update_inode(trans, root, inode);
5181 btrfs_end_write_no_snapshotting(root);
5182 btrfs_end_transaction(trans);
5183 } else {
5186 * We're truncating a file that used to have good data down to
5187 * zero. Make sure it gets into the ordered flush list so that
5188 * any new writes get down to disk quickly.
5190 if (newsize == 0)
5191 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5192 &BTRFS_I(inode)->runtime_flags);
5194 truncate_setsize(inode, newsize);
5196 /* Disable nonlocked read DIO to avoid the end less truncate */
5197 btrfs_inode_block_unlocked_dio(BTRFS_I(inode));
5198 inode_dio_wait(inode);
5199 btrfs_inode_resume_unlocked_dio(BTRFS_I(inode));
5201 ret = btrfs_truncate(inode, newsize == oldsize);
5202 if (ret && inode->i_nlink) {
5203 int err;
5206 * Truncate failed, so fix up the in-memory size. We
5207 * adjusted disk_i_size down as we removed extents, so
5208 * wait for disk_i_size to be stable and then update the
5209 * in-memory size to match.
5211 err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5212 if (err)
5213 return err;
5214 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5218 return ret;
5221 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5223 struct inode *inode = d_inode(dentry);
5224 struct btrfs_root *root = BTRFS_I(inode)->root;
5225 int err;
5227 if (btrfs_root_readonly(root))
5228 return -EROFS;
5230 err = setattr_prepare(dentry, attr);
5231 if (err)
5232 return err;
5234 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5235 err = btrfs_setsize(inode, attr);
5236 if (err)
5237 return err;
5240 if (attr->ia_valid) {
5241 setattr_copy(inode, attr);
5242 inode_inc_iversion(inode);
5243 err = btrfs_dirty_inode(inode);
5245 if (!err && attr->ia_valid & ATTR_MODE)
5246 err = posix_acl_chmod(inode, inode->i_mode);
5249 return err;
5253 * While truncating the inode pages during eviction, we get the VFS calling
5254 * btrfs_invalidatepage() against each page of the inode. This is slow because
5255 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5256 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5257 * extent_state structures over and over, wasting lots of time.
5259 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5260 * those expensive operations on a per page basis and do only the ordered io
5261 * finishing, while we release here the extent_map and extent_state structures,
5262 * without the excessive merging and splitting.
5264 static void evict_inode_truncate_pages(struct inode *inode)
5266 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5267 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5268 struct rb_node *node;
5270 ASSERT(inode->i_state & I_FREEING);
5271 truncate_inode_pages_final(&inode->i_data);
5273 write_lock(&map_tree->lock);
5274 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5275 struct extent_map *em;
5277 node = rb_first(&map_tree->map);
5278 em = rb_entry(node, struct extent_map, rb_node);
5279 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5280 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5281 remove_extent_mapping(map_tree, em);
5282 free_extent_map(em);
5283 if (need_resched()) {
5284 write_unlock(&map_tree->lock);
5285 cond_resched();
5286 write_lock(&map_tree->lock);
5289 write_unlock(&map_tree->lock);
5292 * Keep looping until we have no more ranges in the io tree.
5293 * We can have ongoing bios started by readpages (called from readahead)
5294 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5295 * still in progress (unlocked the pages in the bio but did not yet
5296 * unlocked the ranges in the io tree). Therefore this means some
5297 * ranges can still be locked and eviction started because before
5298 * submitting those bios, which are executed by a separate task (work
5299 * queue kthread), inode references (inode->i_count) were not taken
5300 * (which would be dropped in the end io callback of each bio).
5301 * Therefore here we effectively end up waiting for those bios and
5302 * anyone else holding locked ranges without having bumped the inode's
5303 * reference count - if we don't do it, when they access the inode's
5304 * io_tree to unlock a range it may be too late, leading to an
5305 * use-after-free issue.
5307 spin_lock(&io_tree->lock);
5308 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5309 struct extent_state *state;
5310 struct extent_state *cached_state = NULL;
5311 u64 start;
5312 u64 end;
5314 node = rb_first(&io_tree->state);
5315 state = rb_entry(node, struct extent_state, rb_node);
5316 start = state->start;
5317 end = state->end;
5318 spin_unlock(&io_tree->lock);
5320 lock_extent_bits(io_tree, start, end, &cached_state);
5323 * If still has DELALLOC flag, the extent didn't reach disk,
5324 * and its reserved space won't be freed by delayed_ref.
5325 * So we need to free its reserved space here.
5326 * (Refer to comment in btrfs_invalidatepage, case 2)
5328 * Note, end is the bytenr of last byte, so we need + 1 here.
5330 if (state->state & EXTENT_DELALLOC)
5331 btrfs_qgroup_free_data(inode, NULL, start, end - start + 1);
5333 clear_extent_bit(io_tree, start, end,
5334 EXTENT_LOCKED | EXTENT_DIRTY |
5335 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5336 EXTENT_DEFRAG, 1, 1, &cached_state);
5338 cond_resched();
5339 spin_lock(&io_tree->lock);
5341 spin_unlock(&io_tree->lock);
5344 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5345 struct btrfs_block_rsv *rsv,
5346 u64 min_size)
5348 struct btrfs_fs_info *fs_info = root->fs_info;
5349 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5350 int failures = 0;
5352 for (;;) {
5353 struct btrfs_trans_handle *trans;
5354 int ret;
5356 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5357 BTRFS_RESERVE_FLUSH_LIMIT);
5359 if (ret && ++failures > 2) {
5360 btrfs_warn(fs_info,
5361 "could not allocate space for a delete; will truncate on mount");
5362 return ERR_PTR(-ENOSPC);
5365 trans = btrfs_join_transaction(root);
5366 if (IS_ERR(trans) || !ret)
5367 return trans;
5370 * Try to steal from the global reserve if there is space for
5371 * it.
5373 if (!btrfs_check_space_for_delayed_refs(trans, fs_info) &&
5374 !btrfs_block_rsv_migrate(global_rsv, rsv, min_size, 0))
5375 return trans;
5377 /* If not, commit and try again. */
5378 ret = btrfs_commit_transaction(trans);
5379 if (ret)
5380 return ERR_PTR(ret);
5384 void btrfs_evict_inode(struct inode *inode)
5386 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5387 struct btrfs_trans_handle *trans;
5388 struct btrfs_root *root = BTRFS_I(inode)->root;
5389 struct btrfs_block_rsv *rsv;
5390 u64 min_size;
5391 int ret;
5393 trace_btrfs_inode_evict(inode);
5395 if (!root) {
5396 clear_inode(inode);
5397 return;
5400 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
5402 evict_inode_truncate_pages(inode);
5404 if (inode->i_nlink &&
5405 ((btrfs_root_refs(&root->root_item) != 0 &&
5406 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5407 btrfs_is_free_space_inode(BTRFS_I(inode))))
5408 goto no_delete;
5410 if (is_bad_inode(inode))
5411 goto no_delete;
5412 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5413 if (!special_file(inode->i_mode))
5414 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5416 btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
5418 if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5419 goto no_delete;
5421 if (inode->i_nlink > 0) {
5422 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5423 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5424 goto no_delete;
5427 ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5428 if (ret)
5429 goto no_delete;
5431 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
5432 if (!rsv)
5433 goto no_delete;
5434 rsv->size = min_size;
5435 rsv->failfast = 1;
5437 btrfs_i_size_write(BTRFS_I(inode), 0);
5439 while (1) {
5440 trans = evict_refill_and_join(root, rsv, min_size);
5441 if (IS_ERR(trans))
5442 goto free_rsv;
5444 trans->block_rsv = rsv;
5446 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5447 trans->block_rsv = &fs_info->trans_block_rsv;
5448 btrfs_end_transaction(trans);
5449 btrfs_btree_balance_dirty(fs_info);
5450 if (ret && ret != -ENOSPC && ret != -EAGAIN)
5451 goto free_rsv;
5452 else if (!ret)
5453 break;
5457 * Errors here aren't a big deal, it just means we leave orphan items in
5458 * the tree. They will be cleaned up on the next mount. If the inode
5459 * number gets reused, cleanup deletes the orphan item without doing
5460 * anything, and unlink reuses the existing orphan item.
5462 * If it turns out that we are dropping too many of these, we might want
5463 * to add a mechanism for retrying these after a commit.
5465 trans = evict_refill_and_join(root, rsv, min_size);
5466 if (!IS_ERR(trans)) {
5467 trans->block_rsv = rsv;
5468 btrfs_orphan_del(trans, BTRFS_I(inode));
5469 trans->block_rsv = &fs_info->trans_block_rsv;
5470 btrfs_end_transaction(trans);
5473 if (!(root == fs_info->tree_root ||
5474 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5475 btrfs_return_ino(root, btrfs_ino(BTRFS_I(inode)));
5477 free_rsv:
5478 btrfs_free_block_rsv(fs_info, rsv);
5479 no_delete:
5481 * If we didn't successfully delete, the orphan item will still be in
5482 * the tree and we'll retry on the next mount. Again, we might also want
5483 * to retry these periodically in the future.
5485 btrfs_remove_delayed_node(BTRFS_I(inode));
5486 clear_inode(inode);
5490 * this returns the key found in the dir entry in the location pointer.
5491 * If no dir entries were found, returns -ENOENT.
5492 * If found a corrupted location in dir entry, returns -EUCLEAN.
5494 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5495 struct btrfs_key *location)
5497 const char *name = dentry->d_name.name;
5498 int namelen = dentry->d_name.len;
5499 struct btrfs_dir_item *di;
5500 struct btrfs_path *path;
5501 struct btrfs_root *root = BTRFS_I(dir)->root;
5502 int ret = 0;
5504 path = btrfs_alloc_path();
5505 if (!path)
5506 return -ENOMEM;
5508 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
5509 name, namelen, 0);
5510 if (!di) {
5511 ret = -ENOENT;
5512 goto out;
5514 if (IS_ERR(di)) {
5515 ret = PTR_ERR(di);
5516 goto out;
5519 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5520 if (location->type != BTRFS_INODE_ITEM_KEY &&
5521 location->type != BTRFS_ROOT_ITEM_KEY) {
5522 ret = -EUCLEAN;
5523 btrfs_warn(root->fs_info,
5524 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
5525 __func__, name, btrfs_ino(BTRFS_I(dir)),
5526 location->objectid, location->type, location->offset);
5528 out:
5529 btrfs_free_path(path);
5530 return ret;
5534 * when we hit a tree root in a directory, the btrfs part of the inode
5535 * needs to be changed to reflect the root directory of the tree root. This
5536 * is kind of like crossing a mount point.
5538 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5539 struct inode *dir,
5540 struct dentry *dentry,
5541 struct btrfs_key *location,
5542 struct btrfs_root **sub_root)
5544 struct btrfs_path *path;
5545 struct btrfs_root *new_root;
5546 struct btrfs_root_ref *ref;
5547 struct extent_buffer *leaf;
5548 struct btrfs_key key;
5549 int ret;
5550 int err = 0;
5552 path = btrfs_alloc_path();
5553 if (!path) {
5554 err = -ENOMEM;
5555 goto out;
5558 err = -ENOENT;
5559 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5560 key.type = BTRFS_ROOT_REF_KEY;
5561 key.offset = location->objectid;
5563 ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5564 if (ret) {
5565 if (ret < 0)
5566 err = ret;
5567 goto out;
5570 leaf = path->nodes[0];
5571 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5572 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
5573 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5574 goto out;
5576 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5577 (unsigned long)(ref + 1),
5578 dentry->d_name.len);
5579 if (ret)
5580 goto out;
5582 btrfs_release_path(path);
5584 new_root = btrfs_read_fs_root_no_name(fs_info, location);
5585 if (IS_ERR(new_root)) {
5586 err = PTR_ERR(new_root);
5587 goto out;
5590 *sub_root = new_root;
5591 location->objectid = btrfs_root_dirid(&new_root->root_item);
5592 location->type = BTRFS_INODE_ITEM_KEY;
5593 location->offset = 0;
5594 err = 0;
5595 out:
5596 btrfs_free_path(path);
5597 return err;
5600 static void inode_tree_add(struct inode *inode)
5602 struct btrfs_root *root = BTRFS_I(inode)->root;
5603 struct btrfs_inode *entry;
5604 struct rb_node **p;
5605 struct rb_node *parent;
5606 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5607 u64 ino = btrfs_ino(BTRFS_I(inode));
5609 if (inode_unhashed(inode))
5610 return;
5611 parent = NULL;
5612 spin_lock(&root->inode_lock);
5613 p = &root->inode_tree.rb_node;
5614 while (*p) {
5615 parent = *p;
5616 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5618 if (ino < btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5619 p = &parent->rb_left;
5620 else if (ino > btrfs_ino(BTRFS_I(&entry->vfs_inode)))
5621 p = &parent->rb_right;
5622 else {
5623 WARN_ON(!(entry->vfs_inode.i_state &
5624 (I_WILL_FREE | I_FREEING)));
5625 rb_replace_node(parent, new, &root->inode_tree);
5626 RB_CLEAR_NODE(parent);
5627 spin_unlock(&root->inode_lock);
5628 return;
5631 rb_link_node(new, parent, p);
5632 rb_insert_color(new, &root->inode_tree);
5633 spin_unlock(&root->inode_lock);
5636 static void inode_tree_del(struct inode *inode)
5638 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5639 struct btrfs_root *root = BTRFS_I(inode)->root;
5640 int empty = 0;
5642 spin_lock(&root->inode_lock);
5643 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5644 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5645 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5646 empty = RB_EMPTY_ROOT(&root->inode_tree);
5648 spin_unlock(&root->inode_lock);
5650 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5651 synchronize_srcu(&fs_info->subvol_srcu);
5652 spin_lock(&root->inode_lock);
5653 empty = RB_EMPTY_ROOT(&root->inode_tree);
5654 spin_unlock(&root->inode_lock);
5655 if (empty)
5656 btrfs_add_dead_root(root);
5661 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5663 struct btrfs_iget_args *args = p;
5664 inode->i_ino = args->location->objectid;
5665 memcpy(&BTRFS_I(inode)->location, args->location,
5666 sizeof(*args->location));
5667 BTRFS_I(inode)->root = args->root;
5668 return 0;
5671 static int btrfs_find_actor(struct inode *inode, void *opaque)
5673 struct btrfs_iget_args *args = opaque;
5674 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5675 args->root == BTRFS_I(inode)->root;
5678 static struct inode *btrfs_iget_locked(struct super_block *s,
5679 struct btrfs_key *location,
5680 struct btrfs_root *root)
5682 struct inode *inode;
5683 struct btrfs_iget_args args;
5684 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5686 args.location = location;
5687 args.root = root;
5689 inode = iget5_locked(s, hashval, btrfs_find_actor,
5690 btrfs_init_locked_inode,
5691 (void *)&args);
5692 return inode;
5695 /* Get an inode object given its location and corresponding root.
5696 * Returns in *is_new if the inode was read from disk
5698 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5699 struct btrfs_root *root, int *new)
5701 struct inode *inode;
5703 inode = btrfs_iget_locked(s, location, root);
5704 if (!inode)
5705 return ERR_PTR(-ENOMEM);
5707 if (inode->i_state & I_NEW) {
5708 int ret;
5710 ret = btrfs_read_locked_inode(inode);
5711 if (!is_bad_inode(inode)) {
5712 inode_tree_add(inode);
5713 unlock_new_inode(inode);
5714 if (new)
5715 *new = 1;
5716 } else {
5717 unlock_new_inode(inode);
5718 iput(inode);
5719 ASSERT(ret < 0);
5720 inode = ERR_PTR(ret < 0 ? ret : -ESTALE);
5724 return inode;
5727 static struct inode *new_simple_dir(struct super_block *s,
5728 struct btrfs_key *key,
5729 struct btrfs_root *root)
5731 struct inode *inode = new_inode(s);
5733 if (!inode)
5734 return ERR_PTR(-ENOMEM);
5736 BTRFS_I(inode)->root = root;
5737 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5738 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5740 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5741 inode->i_op = &btrfs_dir_ro_inode_operations;
5742 inode->i_opflags &= ~IOP_XATTR;
5743 inode->i_fop = &simple_dir_operations;
5744 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5745 inode->i_mtime = current_time(inode);
5746 inode->i_atime = inode->i_mtime;
5747 inode->i_ctime = inode->i_mtime;
5748 BTRFS_I(inode)->i_otime = timespec64_to_timespec(inode->i_mtime);
5750 return inode;
5753 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5755 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
5756 struct inode *inode;
5757 struct btrfs_root *root = BTRFS_I(dir)->root;
5758 struct btrfs_root *sub_root = root;
5759 struct btrfs_key location;
5760 int index;
5761 int ret = 0;
5763 if (dentry->d_name.len > BTRFS_NAME_LEN)
5764 return ERR_PTR(-ENAMETOOLONG);
5766 ret = btrfs_inode_by_name(dir, dentry, &location);
5767 if (ret < 0)
5768 return ERR_PTR(ret);
5770 if (location.type == BTRFS_INODE_ITEM_KEY) {
5771 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5772 return inode;
5775 index = srcu_read_lock(&fs_info->subvol_srcu);
5776 ret = fixup_tree_root_location(fs_info, dir, dentry,
5777 &location, &sub_root);
5778 if (ret < 0) {
5779 if (ret != -ENOENT)
5780 inode = ERR_PTR(ret);
5781 else
5782 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5783 } else {
5784 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5786 srcu_read_unlock(&fs_info->subvol_srcu, index);
5788 if (!IS_ERR(inode) && root != sub_root) {
5789 down_read(&fs_info->cleanup_work_sem);
5790 if (!sb_rdonly(inode->i_sb))
5791 ret = btrfs_orphan_cleanup(sub_root);
5792 up_read(&fs_info->cleanup_work_sem);
5793 if (ret) {
5794 iput(inode);
5795 inode = ERR_PTR(ret);
5799 return inode;
5802 static int btrfs_dentry_delete(const struct dentry *dentry)
5804 struct btrfs_root *root;
5805 struct inode *inode = d_inode(dentry);
5807 if (!inode && !IS_ROOT(dentry))
5808 inode = d_inode(dentry->d_parent);
5810 if (inode) {
5811 root = BTRFS_I(inode)->root;
5812 if (btrfs_root_refs(&root->root_item) == 0)
5813 return 1;
5815 if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5816 return 1;
5818 return 0;
5821 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5822 unsigned int flags)
5824 struct inode *inode;
5826 inode = btrfs_lookup_dentry(dir, dentry);
5827 if (IS_ERR(inode)) {
5828 if (PTR_ERR(inode) == -ENOENT)
5829 inode = NULL;
5830 else
5831 return ERR_CAST(inode);
5834 return d_splice_alias(inode, dentry);
5837 unsigned char btrfs_filetype_table[] = {
5838 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5842 * All this infrastructure exists because dir_emit can fault, and we are holding
5843 * the tree lock when doing readdir. For now just allocate a buffer and copy
5844 * our information into that, and then dir_emit from the buffer. This is
5845 * similar to what NFS does, only we don't keep the buffer around in pagecache
5846 * because I'm afraid I'll mess that up. Long term we need to make filldir do
5847 * copy_to_user_inatomic so we don't have to worry about page faulting under the
5848 * tree lock.
5850 static int btrfs_opendir(struct inode *inode, struct file *file)
5852 struct btrfs_file_private *private;
5854 private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
5855 if (!private)
5856 return -ENOMEM;
5857 private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
5858 if (!private->filldir_buf) {
5859 kfree(private);
5860 return -ENOMEM;
5862 file->private_data = private;
5863 return 0;
5866 struct dir_entry {
5867 u64 ino;
5868 u64 offset;
5869 unsigned type;
5870 int name_len;
5873 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
5875 while (entries--) {
5876 struct dir_entry *entry = addr;
5877 char *name = (char *)(entry + 1);
5879 ctx->pos = get_unaligned(&entry->offset);
5880 if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
5881 get_unaligned(&entry->ino),
5882 get_unaligned(&entry->type)))
5883 return 1;
5884 addr += sizeof(struct dir_entry) +
5885 get_unaligned(&entry->name_len);
5886 ctx->pos++;
5888 return 0;
5891 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5893 struct inode *inode = file_inode(file);
5894 struct btrfs_root *root = BTRFS_I(inode)->root;
5895 struct btrfs_file_private *private = file->private_data;
5896 struct btrfs_dir_item *di;
5897 struct btrfs_key key;
5898 struct btrfs_key found_key;
5899 struct btrfs_path *path;
5900 void *addr;
5901 struct list_head ins_list;
5902 struct list_head del_list;
5903 int ret;
5904 struct extent_buffer *leaf;
5905 int slot;
5906 char *name_ptr;
5907 int name_len;
5908 int entries = 0;
5909 int total_len = 0;
5910 bool put = false;
5911 struct btrfs_key location;
5913 if (!dir_emit_dots(file, ctx))
5914 return 0;
5916 path = btrfs_alloc_path();
5917 if (!path)
5918 return -ENOMEM;
5920 addr = private->filldir_buf;
5921 path->reada = READA_FORWARD;
5923 INIT_LIST_HEAD(&ins_list);
5924 INIT_LIST_HEAD(&del_list);
5925 put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
5927 again:
5928 key.type = BTRFS_DIR_INDEX_KEY;
5929 key.offset = ctx->pos;
5930 key.objectid = btrfs_ino(BTRFS_I(inode));
5932 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5933 if (ret < 0)
5934 goto err;
5936 while (1) {
5937 struct dir_entry *entry;
5939 leaf = path->nodes[0];
5940 slot = path->slots[0];
5941 if (slot >= btrfs_header_nritems(leaf)) {
5942 ret = btrfs_next_leaf(root, path);
5943 if (ret < 0)
5944 goto err;
5945 else if (ret > 0)
5946 break;
5947 continue;
5950 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5952 if (found_key.objectid != key.objectid)
5953 break;
5954 if (found_key.type != BTRFS_DIR_INDEX_KEY)
5955 break;
5956 if (found_key.offset < ctx->pos)
5957 goto next;
5958 if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
5959 goto next;
5960 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5961 name_len = btrfs_dir_name_len(leaf, di);
5962 if ((total_len + sizeof(struct dir_entry) + name_len) >=
5963 PAGE_SIZE) {
5964 btrfs_release_path(path);
5965 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5966 if (ret)
5967 goto nopos;
5968 addr = private->filldir_buf;
5969 entries = 0;
5970 total_len = 0;
5971 goto again;
5974 entry = addr;
5975 put_unaligned(name_len, &entry->name_len);
5976 name_ptr = (char *)(entry + 1);
5977 read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
5978 name_len);
5979 put_unaligned(btrfs_filetype_table[btrfs_dir_type(leaf, di)],
5980 &entry->type);
5981 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5982 put_unaligned(location.objectid, &entry->ino);
5983 put_unaligned(found_key.offset, &entry->offset);
5984 entries++;
5985 addr += sizeof(struct dir_entry) + name_len;
5986 total_len += sizeof(struct dir_entry) + name_len;
5987 next:
5988 path->slots[0]++;
5990 btrfs_release_path(path);
5992 ret = btrfs_filldir(private->filldir_buf, entries, ctx);
5993 if (ret)
5994 goto nopos;
5996 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
5997 if (ret)
5998 goto nopos;
6001 * Stop new entries from being returned after we return the last
6002 * entry.
6004 * New directory entries are assigned a strictly increasing
6005 * offset. This means that new entries created during readdir
6006 * are *guaranteed* to be seen in the future by that readdir.
6007 * This has broken buggy programs which operate on names as
6008 * they're returned by readdir. Until we re-use freed offsets
6009 * we have this hack to stop new entries from being returned
6010 * under the assumption that they'll never reach this huge
6011 * offset.
6013 * This is being careful not to overflow 32bit loff_t unless the
6014 * last entry requires it because doing so has broken 32bit apps
6015 * in the past.
6017 if (ctx->pos >= INT_MAX)
6018 ctx->pos = LLONG_MAX;
6019 else
6020 ctx->pos = INT_MAX;
6021 nopos:
6022 ret = 0;
6023 err:
6024 if (put)
6025 btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
6026 btrfs_free_path(path);
6027 return ret;
6031 * This is somewhat expensive, updating the tree every time the
6032 * inode changes. But, it is most likely to find the inode in cache.
6033 * FIXME, needs more benchmarking...there are no reasons other than performance
6034 * to keep or drop this code.
6036 static int btrfs_dirty_inode(struct inode *inode)
6038 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6039 struct btrfs_root *root = BTRFS_I(inode)->root;
6040 struct btrfs_trans_handle *trans;
6041 int ret;
6043 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
6044 return 0;
6046 trans = btrfs_join_transaction(root);
6047 if (IS_ERR(trans))
6048 return PTR_ERR(trans);
6050 ret = btrfs_update_inode(trans, root, inode);
6051 if (ret && ret == -ENOSPC) {
6052 /* whoops, lets try again with the full transaction */
6053 btrfs_end_transaction(trans);
6054 trans = btrfs_start_transaction(root, 1);
6055 if (IS_ERR(trans))
6056 return PTR_ERR(trans);
6058 ret = btrfs_update_inode(trans, root, inode);
6060 btrfs_end_transaction(trans);
6061 if (BTRFS_I(inode)->delayed_node)
6062 btrfs_balance_delayed_items(fs_info);
6064 return ret;
6068 * This is a copy of file_update_time. We need this so we can return error on
6069 * ENOSPC for updating the inode in the case of file write and mmap writes.
6071 static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
6072 int flags)
6074 struct btrfs_root *root = BTRFS_I(inode)->root;
6075 bool dirty = flags & ~S_VERSION;
6077 if (btrfs_root_readonly(root))
6078 return -EROFS;
6080 if (flags & S_VERSION)
6081 dirty |= inode_maybe_inc_iversion(inode, dirty);
6082 if (flags & S_CTIME)
6083 inode->i_ctime = *now;
6084 if (flags & S_MTIME)
6085 inode->i_mtime = *now;
6086 if (flags & S_ATIME)
6087 inode->i_atime = *now;
6088 return dirty ? btrfs_dirty_inode(inode) : 0;
6092 * find the highest existing sequence number in a directory
6093 * and then set the in-memory index_cnt variable to reflect
6094 * free sequence numbers
6096 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6098 struct btrfs_root *root = inode->root;
6099 struct btrfs_key key, found_key;
6100 struct btrfs_path *path;
6101 struct extent_buffer *leaf;
6102 int ret;
6104 key.objectid = btrfs_ino(inode);
6105 key.type = BTRFS_DIR_INDEX_KEY;
6106 key.offset = (u64)-1;
6108 path = btrfs_alloc_path();
6109 if (!path)
6110 return -ENOMEM;
6112 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6113 if (ret < 0)
6114 goto out;
6115 /* FIXME: we should be able to handle this */
6116 if (ret == 0)
6117 goto out;
6118 ret = 0;
6121 * MAGIC NUMBER EXPLANATION:
6122 * since we search a directory based on f_pos we have to start at 2
6123 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6124 * else has to start at 2
6126 if (path->slots[0] == 0) {
6127 inode->index_cnt = 2;
6128 goto out;
6131 path->slots[0]--;
6133 leaf = path->nodes[0];
6134 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6136 if (found_key.objectid != btrfs_ino(inode) ||
6137 found_key.type != BTRFS_DIR_INDEX_KEY) {
6138 inode->index_cnt = 2;
6139 goto out;
6142 inode->index_cnt = found_key.offset + 1;
6143 out:
6144 btrfs_free_path(path);
6145 return ret;
6149 * helper to find a free sequence number in a given directory. This current
6150 * code is very simple, later versions will do smarter things in the btree
6152 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6154 int ret = 0;
6156 if (dir->index_cnt == (u64)-1) {
6157 ret = btrfs_inode_delayed_dir_index_count(dir);
6158 if (ret) {
6159 ret = btrfs_set_inode_index_count(dir);
6160 if (ret)
6161 return ret;
6165 *index = dir->index_cnt;
6166 dir->index_cnt++;
6168 return ret;
6171 static int btrfs_insert_inode_locked(struct inode *inode)
6173 struct btrfs_iget_args args;
6174 args.location = &BTRFS_I(inode)->location;
6175 args.root = BTRFS_I(inode)->root;
6177 return insert_inode_locked4(inode,
6178 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6179 btrfs_find_actor, &args);
6183 * Inherit flags from the parent inode.
6185 * Currently only the compression flags and the cow flags are inherited.
6187 static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
6189 unsigned int flags;
6191 if (!dir)
6192 return;
6194 flags = BTRFS_I(dir)->flags;
6196 if (flags & BTRFS_INODE_NOCOMPRESS) {
6197 BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
6198 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
6199 } else if (flags & BTRFS_INODE_COMPRESS) {
6200 BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
6201 BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
6204 if (flags & BTRFS_INODE_NODATACOW) {
6205 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
6206 if (S_ISREG(inode->i_mode))
6207 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6210 btrfs_sync_inode_flags_to_i_flags(inode);
6213 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6214 struct btrfs_root *root,
6215 struct inode *dir,
6216 const char *name, int name_len,
6217 u64 ref_objectid, u64 objectid,
6218 umode_t mode, u64 *index)
6220 struct btrfs_fs_info *fs_info = root->fs_info;
6221 struct inode *inode;
6222 struct btrfs_inode_item *inode_item;
6223 struct btrfs_key *location;
6224 struct btrfs_path *path;
6225 struct btrfs_inode_ref *ref;
6226 struct btrfs_key key[2];
6227 u32 sizes[2];
6228 int nitems = name ? 2 : 1;
6229 unsigned long ptr;
6230 int ret;
6232 path = btrfs_alloc_path();
6233 if (!path)
6234 return ERR_PTR(-ENOMEM);
6236 inode = new_inode(fs_info->sb);
6237 if (!inode) {
6238 btrfs_free_path(path);
6239 return ERR_PTR(-ENOMEM);
6243 * O_TMPFILE, set link count to 0, so that after this point,
6244 * we fill in an inode item with the correct link count.
6246 if (!name)
6247 set_nlink(inode, 0);
6250 * we have to initialize this early, so we can reclaim the inode
6251 * number if we fail afterwards in this function.
6253 inode->i_ino = objectid;
6255 if (dir && name) {
6256 trace_btrfs_inode_request(dir);
6258 ret = btrfs_set_inode_index(BTRFS_I(dir), index);
6259 if (ret) {
6260 btrfs_free_path(path);
6261 iput(inode);
6262 return ERR_PTR(ret);
6264 } else if (dir) {
6265 *index = 0;
6268 * index_cnt is ignored for everything but a dir,
6269 * btrfs_set_inode_index_count has an explanation for the magic
6270 * number
6272 BTRFS_I(inode)->index_cnt = 2;
6273 BTRFS_I(inode)->dir_index = *index;
6274 BTRFS_I(inode)->root = root;
6275 BTRFS_I(inode)->generation = trans->transid;
6276 inode->i_generation = BTRFS_I(inode)->generation;
6279 * We could have gotten an inode number from somebody who was fsynced
6280 * and then removed in this same transaction, so let's just set full
6281 * sync since it will be a full sync anyway and this will blow away the
6282 * old info in the log.
6284 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6286 key[0].objectid = objectid;
6287 key[0].type = BTRFS_INODE_ITEM_KEY;
6288 key[0].offset = 0;
6290 sizes[0] = sizeof(struct btrfs_inode_item);
6292 if (name) {
6294 * Start new inodes with an inode_ref. This is slightly more
6295 * efficient for small numbers of hard links since they will
6296 * be packed into one item. Extended refs will kick in if we
6297 * add more hard links than can fit in the ref item.
6299 key[1].objectid = objectid;
6300 key[1].type = BTRFS_INODE_REF_KEY;
6301 key[1].offset = ref_objectid;
6303 sizes[1] = name_len + sizeof(*ref);
6306 location = &BTRFS_I(inode)->location;
6307 location->objectid = objectid;
6308 location->offset = 0;
6309 location->type = BTRFS_INODE_ITEM_KEY;
6311 ret = btrfs_insert_inode_locked(inode);
6312 if (ret < 0)
6313 goto fail;
6315 path->leave_spinning = 1;
6316 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6317 if (ret != 0)
6318 goto fail_unlock;
6320 inode_init_owner(inode, dir, mode);
6321 inode_set_bytes(inode, 0);
6323 inode->i_mtime = current_time(inode);
6324 inode->i_atime = inode->i_mtime;
6325 inode->i_ctime = inode->i_mtime;
6326 BTRFS_I(inode)->i_otime = timespec64_to_timespec(inode->i_mtime);
6328 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6329 struct btrfs_inode_item);
6330 memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6331 sizeof(*inode_item));
6332 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6334 if (name) {
6335 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6336 struct btrfs_inode_ref);
6337 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6338 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6339 ptr = (unsigned long)(ref + 1);
6340 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6343 btrfs_mark_buffer_dirty(path->nodes[0]);
6344 btrfs_free_path(path);
6346 btrfs_inherit_iflags(inode, dir);
6348 if (S_ISREG(mode)) {
6349 if (btrfs_test_opt(fs_info, NODATASUM))
6350 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6351 if (btrfs_test_opt(fs_info, NODATACOW))
6352 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6353 BTRFS_INODE_NODATASUM;
6356 inode_tree_add(inode);
6358 trace_btrfs_inode_new(inode);
6359 btrfs_set_inode_last_trans(trans, inode);
6361 btrfs_update_root_times(trans, root);
6363 ret = btrfs_inode_inherit_props(trans, inode, dir);
6364 if (ret)
6365 btrfs_err(fs_info,
6366 "error inheriting props for ino %llu (root %llu): %d",
6367 btrfs_ino(BTRFS_I(inode)), root->root_key.objectid, ret);
6369 return inode;
6371 fail_unlock:
6372 unlock_new_inode(inode);
6373 fail:
6374 if (dir && name)
6375 BTRFS_I(dir)->index_cnt--;
6376 btrfs_free_path(path);
6377 iput(inode);
6378 return ERR_PTR(ret);
6381 static inline u8 btrfs_inode_type(struct inode *inode)
6383 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6387 * utility function to add 'inode' into 'parent_inode' with
6388 * a give name and a given sequence number.
6389 * if 'add_backref' is true, also insert a backref from the
6390 * inode to the parent directory.
6392 int btrfs_add_link(struct btrfs_trans_handle *trans,
6393 struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6394 const char *name, int name_len, int add_backref, u64 index)
6396 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6397 int ret = 0;
6398 struct btrfs_key key;
6399 struct btrfs_root *root = parent_inode->root;
6400 u64 ino = btrfs_ino(inode);
6401 u64 parent_ino = btrfs_ino(parent_inode);
6403 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6404 memcpy(&key, &inode->root->root_key, sizeof(key));
6405 } else {
6406 key.objectid = ino;
6407 key.type = BTRFS_INODE_ITEM_KEY;
6408 key.offset = 0;
6411 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6412 ret = btrfs_add_root_ref(trans, fs_info, key.objectid,
6413 root->root_key.objectid, parent_ino,
6414 index, name, name_len);
6415 } else if (add_backref) {
6416 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6417 parent_ino, index);
6420 /* Nothing to clean up yet */
6421 if (ret)
6422 return ret;
6424 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6425 parent_inode, &key,
6426 btrfs_inode_type(&inode->vfs_inode), index);
6427 if (ret == -EEXIST || ret == -EOVERFLOW)
6428 goto fail_dir_item;
6429 else if (ret) {
6430 btrfs_abort_transaction(trans, ret);
6431 return ret;
6434 btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6435 name_len * 2);
6436 inode_inc_iversion(&parent_inode->vfs_inode);
6437 parent_inode->vfs_inode.i_mtime = parent_inode->vfs_inode.i_ctime =
6438 current_time(&parent_inode->vfs_inode);
6439 ret = btrfs_update_inode(trans, root, &parent_inode->vfs_inode);
6440 if (ret)
6441 btrfs_abort_transaction(trans, ret);
6442 return ret;
6444 fail_dir_item:
6445 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6446 u64 local_index;
6447 int err;
6448 err = btrfs_del_root_ref(trans, fs_info, key.objectid,
6449 root->root_key.objectid, parent_ino,
6450 &local_index, name, name_len);
6452 } else if (add_backref) {
6453 u64 local_index;
6454 int err;
6456 err = btrfs_del_inode_ref(trans, root, name, name_len,
6457 ino, parent_ino, &local_index);
6459 return ret;
6462 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6463 struct btrfs_inode *dir, struct dentry *dentry,
6464 struct btrfs_inode *inode, int backref, u64 index)
6466 int err = btrfs_add_link(trans, dir, inode,
6467 dentry->d_name.name, dentry->d_name.len,
6468 backref, index);
6469 if (err > 0)
6470 err = -EEXIST;
6471 return err;
6474 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6475 umode_t mode, dev_t rdev)
6477 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6478 struct btrfs_trans_handle *trans;
6479 struct btrfs_root *root = BTRFS_I(dir)->root;
6480 struct inode *inode = NULL;
6481 int err;
6482 int drop_inode = 0;
6483 u64 objectid;
6484 u64 index = 0;
6487 * 2 for inode item and ref
6488 * 2 for dir items
6489 * 1 for xattr if selinux is on
6491 trans = btrfs_start_transaction(root, 5);
6492 if (IS_ERR(trans))
6493 return PTR_ERR(trans);
6495 err = btrfs_find_free_ino(root, &objectid);
6496 if (err)
6497 goto out_unlock;
6499 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6500 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6501 mode, &index);
6502 if (IS_ERR(inode)) {
6503 err = PTR_ERR(inode);
6504 goto out_unlock;
6508 * If the active LSM wants to access the inode during
6509 * d_instantiate it needs these. Smack checks to see
6510 * if the filesystem supports xattrs by looking at the
6511 * ops vector.
6513 inode->i_op = &btrfs_special_inode_operations;
6514 init_special_inode(inode, inode->i_mode, rdev);
6516 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6517 if (err)
6518 goto out_unlock_inode;
6520 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6521 0, index);
6522 if (err) {
6523 goto out_unlock_inode;
6524 } else {
6525 btrfs_update_inode(trans, root, inode);
6526 d_instantiate_new(dentry, inode);
6529 out_unlock:
6530 btrfs_end_transaction(trans);
6531 btrfs_btree_balance_dirty(fs_info);
6532 if (drop_inode) {
6533 inode_dec_link_count(inode);
6534 iput(inode);
6536 return err;
6538 out_unlock_inode:
6539 drop_inode = 1;
6540 unlock_new_inode(inode);
6541 goto out_unlock;
6545 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6546 umode_t mode, bool excl)
6548 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6549 struct btrfs_trans_handle *trans;
6550 struct btrfs_root *root = BTRFS_I(dir)->root;
6551 struct inode *inode = NULL;
6552 int drop_inode_on_err = 0;
6553 int err;
6554 u64 objectid;
6555 u64 index = 0;
6558 * 2 for inode item and ref
6559 * 2 for dir items
6560 * 1 for xattr if selinux is on
6562 trans = btrfs_start_transaction(root, 5);
6563 if (IS_ERR(trans))
6564 return PTR_ERR(trans);
6566 err = btrfs_find_free_ino(root, &objectid);
6567 if (err)
6568 goto out_unlock;
6570 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6571 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6572 mode, &index);
6573 if (IS_ERR(inode)) {
6574 err = PTR_ERR(inode);
6575 goto out_unlock;
6577 drop_inode_on_err = 1;
6579 * If the active LSM wants to access the inode during
6580 * d_instantiate it needs these. Smack checks to see
6581 * if the filesystem supports xattrs by looking at the
6582 * ops vector.
6584 inode->i_fop = &btrfs_file_operations;
6585 inode->i_op = &btrfs_file_inode_operations;
6586 inode->i_mapping->a_ops = &btrfs_aops;
6588 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6589 if (err)
6590 goto out_unlock_inode;
6592 err = btrfs_update_inode(trans, root, inode);
6593 if (err)
6594 goto out_unlock_inode;
6596 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6597 0, index);
6598 if (err)
6599 goto out_unlock_inode;
6601 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6602 d_instantiate_new(dentry, inode);
6604 out_unlock:
6605 btrfs_end_transaction(trans);
6606 if (err && drop_inode_on_err) {
6607 inode_dec_link_count(inode);
6608 iput(inode);
6610 btrfs_btree_balance_dirty(fs_info);
6611 return err;
6613 out_unlock_inode:
6614 unlock_new_inode(inode);
6615 goto out_unlock;
6619 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6620 struct dentry *dentry)
6622 struct btrfs_trans_handle *trans = NULL;
6623 struct btrfs_root *root = BTRFS_I(dir)->root;
6624 struct inode *inode = d_inode(old_dentry);
6625 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6626 u64 index;
6627 int err;
6628 int drop_inode = 0;
6630 /* do not allow sys_link's with other subvols of the same device */
6631 if (root->objectid != BTRFS_I(inode)->root->objectid)
6632 return -EXDEV;
6634 if (inode->i_nlink >= BTRFS_LINK_MAX)
6635 return -EMLINK;
6637 err = btrfs_set_inode_index(BTRFS_I(dir), &index);
6638 if (err)
6639 goto fail;
6642 * 2 items for inode and inode ref
6643 * 2 items for dir items
6644 * 1 item for parent inode
6645 * 1 item for orphan item deletion if O_TMPFILE
6647 trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6648 if (IS_ERR(trans)) {
6649 err = PTR_ERR(trans);
6650 trans = NULL;
6651 goto fail;
6654 /* There are several dir indexes for this inode, clear the cache. */
6655 BTRFS_I(inode)->dir_index = 0ULL;
6656 inc_nlink(inode);
6657 inode_inc_iversion(inode);
6658 inode->i_ctime = current_time(inode);
6659 ihold(inode);
6660 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6662 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry, BTRFS_I(inode),
6663 1, index);
6665 if (err) {
6666 drop_inode = 1;
6667 } else {
6668 struct dentry *parent = dentry->d_parent;
6669 err = btrfs_update_inode(trans, root, inode);
6670 if (err)
6671 goto fail;
6672 if (inode->i_nlink == 1) {
6674 * If new hard link count is 1, it's a file created
6675 * with open(2) O_TMPFILE flag.
6677 err = btrfs_orphan_del(trans, BTRFS_I(inode));
6678 if (err)
6679 goto fail;
6681 d_instantiate(dentry, inode);
6682 btrfs_log_new_name(trans, BTRFS_I(inode), NULL, parent);
6685 fail:
6686 if (trans)
6687 btrfs_end_transaction(trans);
6688 if (drop_inode) {
6689 inode_dec_link_count(inode);
6690 iput(inode);
6692 btrfs_btree_balance_dirty(fs_info);
6693 return err;
6696 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6698 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
6699 struct inode *inode = NULL;
6700 struct btrfs_trans_handle *trans;
6701 struct btrfs_root *root = BTRFS_I(dir)->root;
6702 int err = 0;
6703 int drop_on_err = 0;
6704 u64 objectid = 0;
6705 u64 index = 0;
6708 * 2 items for inode and ref
6709 * 2 items for dir items
6710 * 1 for xattr if selinux is on
6712 trans = btrfs_start_transaction(root, 5);
6713 if (IS_ERR(trans))
6714 return PTR_ERR(trans);
6716 err = btrfs_find_free_ino(root, &objectid);
6717 if (err)
6718 goto out_fail;
6720 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6721 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)), objectid,
6722 S_IFDIR | mode, &index);
6723 if (IS_ERR(inode)) {
6724 err = PTR_ERR(inode);
6725 goto out_fail;
6728 drop_on_err = 1;
6729 /* these must be set before we unlock the inode */
6730 inode->i_op = &btrfs_dir_inode_operations;
6731 inode->i_fop = &btrfs_dir_file_operations;
6733 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6734 if (err)
6735 goto out_fail_inode;
6737 btrfs_i_size_write(BTRFS_I(inode), 0);
6738 err = btrfs_update_inode(trans, root, inode);
6739 if (err)
6740 goto out_fail_inode;
6742 err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6743 dentry->d_name.name,
6744 dentry->d_name.len, 0, index);
6745 if (err)
6746 goto out_fail_inode;
6748 d_instantiate_new(dentry, inode);
6749 drop_on_err = 0;
6751 out_fail:
6752 btrfs_end_transaction(trans);
6753 if (drop_on_err) {
6754 inode_dec_link_count(inode);
6755 iput(inode);
6757 btrfs_btree_balance_dirty(fs_info);
6758 return err;
6760 out_fail_inode:
6761 unlock_new_inode(inode);
6762 goto out_fail;
6765 static noinline int uncompress_inline(struct btrfs_path *path,
6766 struct page *page,
6767 size_t pg_offset, u64 extent_offset,
6768 struct btrfs_file_extent_item *item)
6770 int ret;
6771 struct extent_buffer *leaf = path->nodes[0];
6772 char *tmp;
6773 size_t max_size;
6774 unsigned long inline_size;
6775 unsigned long ptr;
6776 int compress_type;
6778 WARN_ON(pg_offset != 0);
6779 compress_type = btrfs_file_extent_compression(leaf, item);
6780 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6781 inline_size = btrfs_file_extent_inline_item_len(leaf,
6782 btrfs_item_nr(path->slots[0]));
6783 tmp = kmalloc(inline_size, GFP_NOFS);
6784 if (!tmp)
6785 return -ENOMEM;
6786 ptr = btrfs_file_extent_inline_start(item);
6788 read_extent_buffer(leaf, tmp, ptr, inline_size);
6790 max_size = min_t(unsigned long, PAGE_SIZE, max_size);
6791 ret = btrfs_decompress(compress_type, tmp, page,
6792 extent_offset, inline_size, max_size);
6795 * decompression code contains a memset to fill in any space between the end
6796 * of the uncompressed data and the end of max_size in case the decompressed
6797 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6798 * the end of an inline extent and the beginning of the next block, so we
6799 * cover that region here.
6802 if (max_size + pg_offset < PAGE_SIZE) {
6803 char *map = kmap(page);
6804 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6805 kunmap(page);
6807 kfree(tmp);
6808 return ret;
6812 * a bit scary, this does extent mapping from logical file offset to the disk.
6813 * the ugly parts come from merging extents from the disk with the in-ram
6814 * representation. This gets more complex because of the data=ordered code,
6815 * where the in-ram extents might be locked pending data=ordered completion.
6817 * This also copies inline extents directly into the page.
6819 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
6820 struct page *page,
6821 size_t pg_offset, u64 start, u64 len,
6822 int create)
6824 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
6825 int ret;
6826 int err = 0;
6827 u64 extent_start = 0;
6828 u64 extent_end = 0;
6829 u64 objectid = btrfs_ino(inode);
6830 u32 found_type;
6831 struct btrfs_path *path = NULL;
6832 struct btrfs_root *root = inode->root;
6833 struct btrfs_file_extent_item *item;
6834 struct extent_buffer *leaf;
6835 struct btrfs_key found_key;
6836 struct extent_map *em = NULL;
6837 struct extent_map_tree *em_tree = &inode->extent_tree;
6838 struct extent_io_tree *io_tree = &inode->io_tree;
6839 const bool new_inline = !page || create;
6841 read_lock(&em_tree->lock);
6842 em = lookup_extent_mapping(em_tree, start, len);
6843 if (em)
6844 em->bdev = fs_info->fs_devices->latest_bdev;
6845 read_unlock(&em_tree->lock);
6847 if (em) {
6848 if (em->start > start || em->start + em->len <= start)
6849 free_extent_map(em);
6850 else if (em->block_start == EXTENT_MAP_INLINE && page)
6851 free_extent_map(em);
6852 else
6853 goto out;
6855 em = alloc_extent_map();
6856 if (!em) {
6857 err = -ENOMEM;
6858 goto out;
6860 em->bdev = fs_info->fs_devices->latest_bdev;
6861 em->start = EXTENT_MAP_HOLE;
6862 em->orig_start = EXTENT_MAP_HOLE;
6863 em->len = (u64)-1;
6864 em->block_len = (u64)-1;
6866 if (!path) {
6867 path = btrfs_alloc_path();
6868 if (!path) {
6869 err = -ENOMEM;
6870 goto out;
6873 * Chances are we'll be called again, so go ahead and do
6874 * readahead
6876 path->reada = READA_FORWARD;
6879 ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
6880 if (ret < 0) {
6881 err = ret;
6882 goto out;
6885 if (ret != 0) {
6886 if (path->slots[0] == 0)
6887 goto not_found;
6888 path->slots[0]--;
6891 leaf = path->nodes[0];
6892 item = btrfs_item_ptr(leaf, path->slots[0],
6893 struct btrfs_file_extent_item);
6894 /* are we inside the extent that was found? */
6895 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6896 found_type = found_key.type;
6897 if (found_key.objectid != objectid ||
6898 found_type != BTRFS_EXTENT_DATA_KEY) {
6900 * If we backup past the first extent we want to move forward
6901 * and see if there is an extent in front of us, otherwise we'll
6902 * say there is a hole for our whole search range which can
6903 * cause problems.
6905 extent_end = start;
6906 goto next;
6909 found_type = btrfs_file_extent_type(leaf, item);
6910 extent_start = found_key.offset;
6911 if (found_type == BTRFS_FILE_EXTENT_REG ||
6912 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6913 extent_end = extent_start +
6914 btrfs_file_extent_num_bytes(leaf, item);
6916 trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
6917 extent_start);
6918 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6919 size_t size;
6920 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6921 extent_end = ALIGN(extent_start + size,
6922 fs_info->sectorsize);
6924 trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
6925 path->slots[0],
6926 extent_start);
6928 next:
6929 if (start >= extent_end) {
6930 path->slots[0]++;
6931 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6932 ret = btrfs_next_leaf(root, path);
6933 if (ret < 0) {
6934 err = ret;
6935 goto out;
6937 if (ret > 0)
6938 goto not_found;
6939 leaf = path->nodes[0];
6941 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6942 if (found_key.objectid != objectid ||
6943 found_key.type != BTRFS_EXTENT_DATA_KEY)
6944 goto not_found;
6945 if (start + len <= found_key.offset)
6946 goto not_found;
6947 if (start > found_key.offset)
6948 goto next;
6949 em->start = start;
6950 em->orig_start = start;
6951 em->len = found_key.offset - start;
6952 goto not_found_em;
6955 btrfs_extent_item_to_extent_map(inode, path, item,
6956 new_inline, em);
6958 if (found_type == BTRFS_FILE_EXTENT_REG ||
6959 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6960 goto insert;
6961 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6962 unsigned long ptr;
6963 char *map;
6964 size_t size;
6965 size_t extent_offset;
6966 size_t copy_size;
6968 if (new_inline)
6969 goto out;
6971 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6972 extent_offset = page_offset(page) + pg_offset - extent_start;
6973 copy_size = min_t(u64, PAGE_SIZE - pg_offset,
6974 size - extent_offset);
6975 em->start = extent_start + extent_offset;
6976 em->len = ALIGN(copy_size, fs_info->sectorsize);
6977 em->orig_block_len = em->len;
6978 em->orig_start = em->start;
6979 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6980 if (!PageUptodate(page)) {
6981 if (btrfs_file_extent_compression(leaf, item) !=
6982 BTRFS_COMPRESS_NONE) {
6983 ret = uncompress_inline(path, page, pg_offset,
6984 extent_offset, item);
6985 if (ret) {
6986 err = ret;
6987 goto out;
6989 } else {
6990 map = kmap(page);
6991 read_extent_buffer(leaf, map + pg_offset, ptr,
6992 copy_size);
6993 if (pg_offset + copy_size < PAGE_SIZE) {
6994 memset(map + pg_offset + copy_size, 0,
6995 PAGE_SIZE - pg_offset -
6996 copy_size);
6998 kunmap(page);
7000 flush_dcache_page(page);
7002 set_extent_uptodate(io_tree, em->start,
7003 extent_map_end(em) - 1, NULL, GFP_NOFS);
7004 goto insert;
7006 not_found:
7007 em->start = start;
7008 em->orig_start = start;
7009 em->len = len;
7010 not_found_em:
7011 em->block_start = EXTENT_MAP_HOLE;
7012 insert:
7013 btrfs_release_path(path);
7014 if (em->start > start || extent_map_end(em) <= start) {
7015 btrfs_err(fs_info,
7016 "bad extent! em: [%llu %llu] passed [%llu %llu]",
7017 em->start, em->len, start, len);
7018 err = -EIO;
7019 goto out;
7022 err = 0;
7023 write_lock(&em_tree->lock);
7024 err = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
7025 write_unlock(&em_tree->lock);
7026 out:
7028 trace_btrfs_get_extent(root, inode, em);
7030 btrfs_free_path(path);
7031 if (err) {
7032 free_extent_map(em);
7033 return ERR_PTR(err);
7035 BUG_ON(!em); /* Error is always set */
7036 return em;
7039 struct extent_map *btrfs_get_extent_fiemap(struct btrfs_inode *inode,
7040 struct page *page,
7041 size_t pg_offset, u64 start, u64 len,
7042 int create)
7044 struct extent_map *em;
7045 struct extent_map *hole_em = NULL;
7046 u64 range_start = start;
7047 u64 end;
7048 u64 found;
7049 u64 found_end;
7050 int err = 0;
7052 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7053 if (IS_ERR(em))
7054 return em;
7056 * If our em maps to:
7057 * - a hole or
7058 * - a pre-alloc extent,
7059 * there might actually be delalloc bytes behind it.
7061 if (em->block_start != EXTENT_MAP_HOLE &&
7062 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7063 return em;
7064 else
7065 hole_em = em;
7067 /* check to see if we've wrapped (len == -1 or similar) */
7068 end = start + len;
7069 if (end < start)
7070 end = (u64)-1;
7071 else
7072 end -= 1;
7074 em = NULL;
7076 /* ok, we didn't find anything, lets look for delalloc */
7077 found = count_range_bits(&inode->io_tree, &range_start,
7078 end, len, EXTENT_DELALLOC, 1);
7079 found_end = range_start + found;
7080 if (found_end < range_start)
7081 found_end = (u64)-1;
7084 * we didn't find anything useful, return
7085 * the original results from get_extent()
7087 if (range_start > end || found_end <= start) {
7088 em = hole_em;
7089 hole_em = NULL;
7090 goto out;
7093 /* adjust the range_start to make sure it doesn't
7094 * go backwards from the start they passed in
7096 range_start = max(start, range_start);
7097 found = found_end - range_start;
7099 if (found > 0) {
7100 u64 hole_start = start;
7101 u64 hole_len = len;
7103 em = alloc_extent_map();
7104 if (!em) {
7105 err = -ENOMEM;
7106 goto out;
7109 * when btrfs_get_extent can't find anything it
7110 * returns one huge hole
7112 * make sure what it found really fits our range, and
7113 * adjust to make sure it is based on the start from
7114 * the caller
7116 if (hole_em) {
7117 u64 calc_end = extent_map_end(hole_em);
7119 if (calc_end <= start || (hole_em->start > end)) {
7120 free_extent_map(hole_em);
7121 hole_em = NULL;
7122 } else {
7123 hole_start = max(hole_em->start, start);
7124 hole_len = calc_end - hole_start;
7127 em->bdev = NULL;
7128 if (hole_em && range_start > hole_start) {
7129 /* our hole starts before our delalloc, so we
7130 * have to return just the parts of the hole
7131 * that go until the delalloc starts
7133 em->len = min(hole_len,
7134 range_start - hole_start);
7135 em->start = hole_start;
7136 em->orig_start = hole_start;
7138 * don't adjust block start at all,
7139 * it is fixed at EXTENT_MAP_HOLE
7141 em->block_start = hole_em->block_start;
7142 em->block_len = hole_len;
7143 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7144 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7145 } else {
7146 em->start = range_start;
7147 em->len = found;
7148 em->orig_start = range_start;
7149 em->block_start = EXTENT_MAP_DELALLOC;
7150 em->block_len = found;
7152 } else {
7153 return hole_em;
7155 out:
7157 free_extent_map(hole_em);
7158 if (err) {
7159 free_extent_map(em);
7160 return ERR_PTR(err);
7162 return em;
7165 static struct extent_map *btrfs_create_dio_extent(struct inode *inode,
7166 const u64 start,
7167 const u64 len,
7168 const u64 orig_start,
7169 const u64 block_start,
7170 const u64 block_len,
7171 const u64 orig_block_len,
7172 const u64 ram_bytes,
7173 const int type)
7175 struct extent_map *em = NULL;
7176 int ret;
7178 if (type != BTRFS_ORDERED_NOCOW) {
7179 em = create_io_em(inode, start, len, orig_start,
7180 block_start, block_len, orig_block_len,
7181 ram_bytes,
7182 BTRFS_COMPRESS_NONE, /* compress_type */
7183 type);
7184 if (IS_ERR(em))
7185 goto out;
7187 ret = btrfs_add_ordered_extent_dio(inode, start, block_start,
7188 len, block_len, type);
7189 if (ret) {
7190 if (em) {
7191 free_extent_map(em);
7192 btrfs_drop_extent_cache(BTRFS_I(inode), start,
7193 start + len - 1, 0);
7195 em = ERR_PTR(ret);
7197 out:
7199 return em;
7202 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7203 u64 start, u64 len)
7205 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7206 struct btrfs_root *root = BTRFS_I(inode)->root;
7207 struct extent_map *em;
7208 struct btrfs_key ins;
7209 u64 alloc_hint;
7210 int ret;
7212 alloc_hint = get_extent_allocation_hint(inode, start, len);
7213 ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
7214 0, alloc_hint, &ins, 1, 1);
7215 if (ret)
7216 return ERR_PTR(ret);
7218 em = btrfs_create_dio_extent(inode, start, ins.offset, start,
7219 ins.objectid, ins.offset, ins.offset,
7220 ins.offset, BTRFS_ORDERED_REGULAR);
7221 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
7222 if (IS_ERR(em))
7223 btrfs_free_reserved_extent(fs_info, ins.objectid,
7224 ins.offset, 1);
7226 return em;
7230 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7231 * block must be cow'd
7233 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7234 u64 *orig_start, u64 *orig_block_len,
7235 u64 *ram_bytes)
7237 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7238 struct btrfs_path *path;
7239 int ret;
7240 struct extent_buffer *leaf;
7241 struct btrfs_root *root = BTRFS_I(inode)->root;
7242 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7243 struct btrfs_file_extent_item *fi;
7244 struct btrfs_key key;
7245 u64 disk_bytenr;
7246 u64 backref_offset;
7247 u64 extent_end;
7248 u64 num_bytes;
7249 int slot;
7250 int found_type;
7251 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7253 path = btrfs_alloc_path();
7254 if (!path)
7255 return -ENOMEM;
7257 ret = btrfs_lookup_file_extent(NULL, root, path,
7258 btrfs_ino(BTRFS_I(inode)), offset, 0);
7259 if (ret < 0)
7260 goto out;
7262 slot = path->slots[0];
7263 if (ret == 1) {
7264 if (slot == 0) {
7265 /* can't find the item, must cow */
7266 ret = 0;
7267 goto out;
7269 slot--;
7271 ret = 0;
7272 leaf = path->nodes[0];
7273 btrfs_item_key_to_cpu(leaf, &key, slot);
7274 if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
7275 key.type != BTRFS_EXTENT_DATA_KEY) {
7276 /* not our file or wrong item type, must cow */
7277 goto out;
7280 if (key.offset > offset) {
7281 /* Wrong offset, must cow */
7282 goto out;
7285 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7286 found_type = btrfs_file_extent_type(leaf, fi);
7287 if (found_type != BTRFS_FILE_EXTENT_REG &&
7288 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7289 /* not a regular extent, must cow */
7290 goto out;
7293 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7294 goto out;
7296 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7297 if (extent_end <= offset)
7298 goto out;
7300 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7301 if (disk_bytenr == 0)
7302 goto out;
7304 if (btrfs_file_extent_compression(leaf, fi) ||
7305 btrfs_file_extent_encryption(leaf, fi) ||
7306 btrfs_file_extent_other_encoding(leaf, fi))
7307 goto out;
7310 * Do the same check as in btrfs_cross_ref_exist but without the
7311 * unnecessary search.
7313 if (btrfs_file_extent_generation(leaf, fi) <=
7314 btrfs_root_last_snapshot(&root->root_item))
7315 goto out;
7317 backref_offset = btrfs_file_extent_offset(leaf, fi);
7319 if (orig_start) {
7320 *orig_start = key.offset - backref_offset;
7321 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7322 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7325 if (btrfs_extent_readonly(fs_info, disk_bytenr))
7326 goto out;
7328 num_bytes = min(offset + *len, extent_end) - offset;
7329 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7330 u64 range_end;
7332 range_end = round_up(offset + num_bytes,
7333 root->fs_info->sectorsize) - 1;
7334 ret = test_range_bit(io_tree, offset, range_end,
7335 EXTENT_DELALLOC, 0, NULL);
7336 if (ret) {
7337 ret = -EAGAIN;
7338 goto out;
7342 btrfs_release_path(path);
7345 * look for other files referencing this extent, if we
7346 * find any we must cow
7349 ret = btrfs_cross_ref_exist(root, btrfs_ino(BTRFS_I(inode)),
7350 key.offset - backref_offset, disk_bytenr);
7351 if (ret) {
7352 ret = 0;
7353 goto out;
7357 * adjust disk_bytenr and num_bytes to cover just the bytes
7358 * in this extent we are about to write. If there
7359 * are any csums in that range we have to cow in order
7360 * to keep the csums correct
7362 disk_bytenr += backref_offset;
7363 disk_bytenr += offset - key.offset;
7364 if (csum_exist_in_range(fs_info, disk_bytenr, num_bytes))
7365 goto out;
7367 * all of the above have passed, it is safe to overwrite this extent
7368 * without cow
7370 *len = num_bytes;
7371 ret = 1;
7372 out:
7373 btrfs_free_path(path);
7374 return ret;
7377 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7378 struct extent_state **cached_state, int writing)
7380 struct btrfs_ordered_extent *ordered;
7381 int ret = 0;
7383 while (1) {
7384 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7385 cached_state);
7387 * We're concerned with the entire range that we're going to be
7388 * doing DIO to, so we need to make sure there's no ordered
7389 * extents in this range.
7391 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
7392 lockend - lockstart + 1);
7395 * We need to make sure there are no buffered pages in this
7396 * range either, we could have raced between the invalidate in
7397 * generic_file_direct_write and locking the extent. The
7398 * invalidate needs to happen so that reads after a write do not
7399 * get stale data.
7401 if (!ordered &&
7402 (!writing || !filemap_range_has_page(inode->i_mapping,
7403 lockstart, lockend)))
7404 break;
7406 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7407 cached_state);
7409 if (ordered) {
7411 * If we are doing a DIO read and the ordered extent we
7412 * found is for a buffered write, we can not wait for it
7413 * to complete and retry, because if we do so we can
7414 * deadlock with concurrent buffered writes on page
7415 * locks. This happens only if our DIO read covers more
7416 * than one extent map, if at this point has already
7417 * created an ordered extent for a previous extent map
7418 * and locked its range in the inode's io tree, and a
7419 * concurrent write against that previous extent map's
7420 * range and this range started (we unlock the ranges
7421 * in the io tree only when the bios complete and
7422 * buffered writes always lock pages before attempting
7423 * to lock range in the io tree).
7425 if (writing ||
7426 test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
7427 btrfs_start_ordered_extent(inode, ordered, 1);
7428 else
7429 ret = -ENOTBLK;
7430 btrfs_put_ordered_extent(ordered);
7431 } else {
7433 * We could trigger writeback for this range (and wait
7434 * for it to complete) and then invalidate the pages for
7435 * this range (through invalidate_inode_pages2_range()),
7436 * but that can lead us to a deadlock with a concurrent
7437 * call to readpages() (a buffered read or a defrag call
7438 * triggered a readahead) on a page lock due to an
7439 * ordered dio extent we created before but did not have
7440 * yet a corresponding bio submitted (whence it can not
7441 * complete), which makes readpages() wait for that
7442 * ordered extent to complete while holding a lock on
7443 * that page.
7445 ret = -ENOTBLK;
7448 if (ret)
7449 break;
7451 cond_resched();
7454 return ret;
7457 /* The callers of this must take lock_extent() */
7458 static struct extent_map *create_io_em(struct inode *inode, u64 start, u64 len,
7459 u64 orig_start, u64 block_start,
7460 u64 block_len, u64 orig_block_len,
7461 u64 ram_bytes, int compress_type,
7462 int type)
7464 struct extent_map_tree *em_tree;
7465 struct extent_map *em;
7466 struct btrfs_root *root = BTRFS_I(inode)->root;
7467 int ret;
7469 ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7470 type == BTRFS_ORDERED_COMPRESSED ||
7471 type == BTRFS_ORDERED_NOCOW ||
7472 type == BTRFS_ORDERED_REGULAR);
7474 em_tree = &BTRFS_I(inode)->extent_tree;
7475 em = alloc_extent_map();
7476 if (!em)
7477 return ERR_PTR(-ENOMEM);
7479 em->start = start;
7480 em->orig_start = orig_start;
7481 em->len = len;
7482 em->block_len = block_len;
7483 em->block_start = block_start;
7484 em->bdev = root->fs_info->fs_devices->latest_bdev;
7485 em->orig_block_len = orig_block_len;
7486 em->ram_bytes = ram_bytes;
7487 em->generation = -1;
7488 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7489 if (type == BTRFS_ORDERED_PREALLOC) {
7490 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7491 } else if (type == BTRFS_ORDERED_COMPRESSED) {
7492 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
7493 em->compress_type = compress_type;
7496 do {
7497 btrfs_drop_extent_cache(BTRFS_I(inode), em->start,
7498 em->start + em->len - 1, 0);
7499 write_lock(&em_tree->lock);
7500 ret = add_extent_mapping(em_tree, em, 1);
7501 write_unlock(&em_tree->lock);
7503 * The caller has taken lock_extent(), who could race with us
7504 * to add em?
7506 } while (ret == -EEXIST);
7508 if (ret) {
7509 free_extent_map(em);
7510 return ERR_PTR(ret);
7513 /* em got 2 refs now, callers needs to do free_extent_map once. */
7514 return em;
7518 static int btrfs_get_blocks_direct_read(struct extent_map *em,
7519 struct buffer_head *bh_result,
7520 struct inode *inode,
7521 u64 start, u64 len)
7523 if (em->block_start == EXTENT_MAP_HOLE ||
7524 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7525 return -ENOENT;
7527 len = min(len, em->len - (start - em->start));
7529 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7530 inode->i_blkbits;
7531 bh_result->b_size = len;
7532 bh_result->b_bdev = em->bdev;
7533 set_buffer_mapped(bh_result);
7535 return 0;
7538 static int btrfs_get_blocks_direct_write(struct extent_map **map,
7539 struct buffer_head *bh_result,
7540 struct inode *inode,
7541 struct btrfs_dio_data *dio_data,
7542 u64 start, u64 len)
7544 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7545 struct extent_map *em = *map;
7546 int ret = 0;
7549 * We don't allocate a new extent in the following cases
7551 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7552 * existing extent.
7553 * 2) The extent is marked as PREALLOC. We're good to go here and can
7554 * just use the extent.
7557 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7558 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7559 em->block_start != EXTENT_MAP_HOLE)) {
7560 int type;
7561 u64 block_start, orig_start, orig_block_len, ram_bytes;
7563 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7564 type = BTRFS_ORDERED_PREALLOC;
7565 else
7566 type = BTRFS_ORDERED_NOCOW;
7567 len = min(len, em->len - (start - em->start));
7568 block_start = em->block_start + (start - em->start);
7570 if (can_nocow_extent(inode, start, &len, &orig_start,
7571 &orig_block_len, &ram_bytes) == 1 &&
7572 btrfs_inc_nocow_writers(fs_info, block_start)) {
7573 struct extent_map *em2;
7575 em2 = btrfs_create_dio_extent(inode, start, len,
7576 orig_start, block_start,
7577 len, orig_block_len,
7578 ram_bytes, type);
7579 btrfs_dec_nocow_writers(fs_info, block_start);
7580 if (type == BTRFS_ORDERED_PREALLOC) {
7581 free_extent_map(em);
7582 *map = em = em2;
7585 if (em2 && IS_ERR(em2)) {
7586 ret = PTR_ERR(em2);
7587 goto out;
7590 * For inode marked NODATACOW or extent marked PREALLOC,
7591 * use the existing or preallocated extent, so does not
7592 * need to adjust btrfs_space_info's bytes_may_use.
7594 btrfs_free_reserved_data_space_noquota(inode, start,
7595 len);
7596 goto skip_cow;
7600 /* this will cow the extent */
7601 len = bh_result->b_size;
7602 free_extent_map(em);
7603 *map = em = btrfs_new_extent_direct(inode, start, len);
7604 if (IS_ERR(em)) {
7605 ret = PTR_ERR(em);
7606 goto out;
7609 len = min(len, em->len - (start - em->start));
7611 skip_cow:
7612 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7613 inode->i_blkbits;
7614 bh_result->b_size = len;
7615 bh_result->b_bdev = em->bdev;
7616 set_buffer_mapped(bh_result);
7618 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7619 set_buffer_new(bh_result);
7622 * Need to update the i_size under the extent lock so buffered
7623 * readers will get the updated i_size when we unlock.
7625 if (!dio_data->overwrite && start + len > i_size_read(inode))
7626 i_size_write(inode, start + len);
7628 WARN_ON(dio_data->reserve < len);
7629 dio_data->reserve -= len;
7630 dio_data->unsubmitted_oe_range_end = start + len;
7631 current->journal_info = dio_data;
7632 out:
7633 return ret;
7636 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7637 struct buffer_head *bh_result, int create)
7639 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7640 struct extent_map *em;
7641 struct extent_state *cached_state = NULL;
7642 struct btrfs_dio_data *dio_data = NULL;
7643 u64 start = iblock << inode->i_blkbits;
7644 u64 lockstart, lockend;
7645 u64 len = bh_result->b_size;
7646 int unlock_bits = EXTENT_LOCKED;
7647 int ret = 0;
7649 if (create)
7650 unlock_bits |= EXTENT_DIRTY;
7651 else
7652 len = min_t(u64, len, fs_info->sectorsize);
7654 lockstart = start;
7655 lockend = start + len - 1;
7657 if (current->journal_info) {
7659 * Need to pull our outstanding extents and set journal_info to NULL so
7660 * that anything that needs to check if there's a transaction doesn't get
7661 * confused.
7663 dio_data = current->journal_info;
7664 current->journal_info = NULL;
7668 * If this errors out it's because we couldn't invalidate pagecache for
7669 * this range and we need to fallback to buffered.
7671 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7672 create)) {
7673 ret = -ENOTBLK;
7674 goto err;
7677 em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len, 0);
7678 if (IS_ERR(em)) {
7679 ret = PTR_ERR(em);
7680 goto unlock_err;
7684 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7685 * io. INLINE is special, and we could probably kludge it in here, but
7686 * it's still buffered so for safety lets just fall back to the generic
7687 * buffered path.
7689 * For COMPRESSED we _have_ to read the entire extent in so we can
7690 * decompress it, so there will be buffering required no matter what we
7691 * do, so go ahead and fallback to buffered.
7693 * We return -ENOTBLK because that's what makes DIO go ahead and go back
7694 * to buffered IO. Don't blame me, this is the price we pay for using
7695 * the generic code.
7697 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7698 em->block_start == EXTENT_MAP_INLINE) {
7699 free_extent_map(em);
7700 ret = -ENOTBLK;
7701 goto unlock_err;
7704 if (create) {
7705 ret = btrfs_get_blocks_direct_write(&em, bh_result, inode,
7706 dio_data, start, len);
7707 if (ret < 0)
7708 goto unlock_err;
7710 /* clear and unlock the entire range */
7711 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7712 unlock_bits, 1, 0, &cached_state);
7713 } else {
7714 ret = btrfs_get_blocks_direct_read(em, bh_result, inode,
7715 start, len);
7716 /* Can be negative only if we read from a hole */
7717 if (ret < 0) {
7718 ret = 0;
7719 free_extent_map(em);
7720 goto unlock_err;
7723 * We need to unlock only the end area that we aren't using.
7724 * The rest is going to be unlocked by the endio routine.
7726 lockstart = start + bh_result->b_size;
7727 if (lockstart < lockend) {
7728 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7729 lockend, unlock_bits, 1, 0,
7730 &cached_state);
7731 } else {
7732 free_extent_state(cached_state);
7736 free_extent_map(em);
7738 return 0;
7740 unlock_err:
7741 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7742 unlock_bits, 1, 0, &cached_state);
7743 err:
7744 if (dio_data)
7745 current->journal_info = dio_data;
7746 return ret;
7749 static inline blk_status_t submit_dio_repair_bio(struct inode *inode,
7750 struct bio *bio,
7751 int mirror_num)
7753 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7754 blk_status_t ret;
7756 BUG_ON(bio_op(bio) == REQ_OP_WRITE);
7758 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DIO_REPAIR);
7759 if (ret)
7760 return ret;
7762 ret = btrfs_map_bio(fs_info, bio, mirror_num, 0);
7764 return ret;
7767 static int btrfs_check_dio_repairable(struct inode *inode,
7768 struct bio *failed_bio,
7769 struct io_failure_record *failrec,
7770 int failed_mirror)
7772 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
7773 int num_copies;
7775 num_copies = btrfs_num_copies(fs_info, failrec->logical, failrec->len);
7776 if (num_copies == 1) {
7778 * we only have a single copy of the data, so don't bother with
7779 * all the retry and error correction code that follows. no
7780 * matter what the error is, it is very likely to persist.
7782 btrfs_debug(fs_info,
7783 "Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d",
7784 num_copies, failrec->this_mirror, failed_mirror);
7785 return 0;
7788 failrec->failed_mirror = failed_mirror;
7789 failrec->this_mirror++;
7790 if (failrec->this_mirror == failed_mirror)
7791 failrec->this_mirror++;
7793 if (failrec->this_mirror > num_copies) {
7794 btrfs_debug(fs_info,
7795 "Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d",
7796 num_copies, failrec->this_mirror, failed_mirror);
7797 return 0;
7800 return 1;
7803 static blk_status_t dio_read_error(struct inode *inode, struct bio *failed_bio,
7804 struct page *page, unsigned int pgoff,
7805 u64 start, u64 end, int failed_mirror,
7806 bio_end_io_t *repair_endio, void *repair_arg)
7808 struct io_failure_record *failrec;
7809 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7810 struct extent_io_tree *failure_tree = &BTRFS_I(inode)->io_failure_tree;
7811 struct bio *bio;
7812 int isector;
7813 unsigned int read_mode = 0;
7814 int segs;
7815 int ret;
7816 blk_status_t status;
7817 struct bio_vec bvec;
7819 BUG_ON(bio_op(failed_bio) == REQ_OP_WRITE);
7821 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7822 if (ret)
7823 return errno_to_blk_status(ret);
7825 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7826 failed_mirror);
7827 if (!ret) {
7828 free_io_failure(failure_tree, io_tree, failrec);
7829 return BLK_STS_IOERR;
7832 segs = bio_segments(failed_bio);
7833 bio_get_first_bvec(failed_bio, &bvec);
7834 if (segs > 1 ||
7835 (bvec.bv_len > btrfs_inode_sectorsize(inode)))
7836 read_mode |= REQ_FAILFAST_DEV;
7838 isector = start - btrfs_io_bio(failed_bio)->logical;
7839 isector >>= inode->i_sb->s_blocksize_bits;
7840 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7841 pgoff, isector, repair_endio, repair_arg);
7842 bio_set_op_attrs(bio, REQ_OP_READ, read_mode);
7844 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7845 "repair DIO read error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d",
7846 read_mode, failrec->this_mirror, failrec->in_validation);
7848 status = submit_dio_repair_bio(inode, bio, failrec->this_mirror);
7849 if (status) {
7850 free_io_failure(failure_tree, io_tree, failrec);
7851 bio_put(bio);
7854 return status;
7857 struct btrfs_retry_complete {
7858 struct completion done;
7859 struct inode *inode;
7860 u64 start;
7861 int uptodate;
7864 static void btrfs_retry_endio_nocsum(struct bio *bio)
7866 struct btrfs_retry_complete *done = bio->bi_private;
7867 struct inode *inode = done->inode;
7868 struct bio_vec *bvec;
7869 struct extent_io_tree *io_tree, *failure_tree;
7870 int i;
7872 if (bio->bi_status)
7873 goto end;
7875 ASSERT(bio->bi_vcnt == 1);
7876 io_tree = &BTRFS_I(inode)->io_tree;
7877 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7878 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(inode));
7880 done->uptodate = 1;
7881 ASSERT(!bio_flagged(bio, BIO_CLONED));
7882 bio_for_each_segment_all(bvec, bio, i)
7883 clean_io_failure(BTRFS_I(inode)->root->fs_info, failure_tree,
7884 io_tree, done->start, bvec->bv_page,
7885 btrfs_ino(BTRFS_I(inode)), 0);
7886 end:
7887 complete(&done->done);
7888 bio_put(bio);
7891 static blk_status_t __btrfs_correct_data_nocsum(struct inode *inode,
7892 struct btrfs_io_bio *io_bio)
7894 struct btrfs_fs_info *fs_info;
7895 struct bio_vec bvec;
7896 struct bvec_iter iter;
7897 struct btrfs_retry_complete done;
7898 u64 start;
7899 unsigned int pgoff;
7900 u32 sectorsize;
7901 int nr_sectors;
7902 blk_status_t ret;
7903 blk_status_t err = BLK_STS_OK;
7905 fs_info = BTRFS_I(inode)->root->fs_info;
7906 sectorsize = fs_info->sectorsize;
7908 start = io_bio->logical;
7909 done.inode = inode;
7910 io_bio->bio.bi_iter = io_bio->iter;
7912 bio_for_each_segment(bvec, &io_bio->bio, iter) {
7913 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
7914 pgoff = bvec.bv_offset;
7916 next_block_or_try_again:
7917 done.uptodate = 0;
7918 done.start = start;
7919 init_completion(&done.done);
7921 ret = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
7922 pgoff, start, start + sectorsize - 1,
7923 io_bio->mirror_num,
7924 btrfs_retry_endio_nocsum, &done);
7925 if (ret) {
7926 err = ret;
7927 goto next;
7930 wait_for_completion_io(&done.done);
7932 if (!done.uptodate) {
7933 /* We might have another mirror, so try again */
7934 goto next_block_or_try_again;
7937 next:
7938 start += sectorsize;
7940 nr_sectors--;
7941 if (nr_sectors) {
7942 pgoff += sectorsize;
7943 ASSERT(pgoff < PAGE_SIZE);
7944 goto next_block_or_try_again;
7948 return err;
7951 static void btrfs_retry_endio(struct bio *bio)
7953 struct btrfs_retry_complete *done = bio->bi_private;
7954 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7955 struct extent_io_tree *io_tree, *failure_tree;
7956 struct inode *inode = done->inode;
7957 struct bio_vec *bvec;
7958 int uptodate;
7959 int ret;
7960 int i;
7962 if (bio->bi_status)
7963 goto end;
7965 uptodate = 1;
7967 ASSERT(bio->bi_vcnt == 1);
7968 ASSERT(bio_first_bvec_all(bio)->bv_len == btrfs_inode_sectorsize(done->inode));
7970 io_tree = &BTRFS_I(inode)->io_tree;
7971 failure_tree = &BTRFS_I(inode)->io_failure_tree;
7973 ASSERT(!bio_flagged(bio, BIO_CLONED));
7974 bio_for_each_segment_all(bvec, bio, i) {
7975 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7976 bvec->bv_offset, done->start,
7977 bvec->bv_len);
7978 if (!ret)
7979 clean_io_failure(BTRFS_I(inode)->root->fs_info,
7980 failure_tree, io_tree, done->start,
7981 bvec->bv_page,
7982 btrfs_ino(BTRFS_I(inode)),
7983 bvec->bv_offset);
7984 else
7985 uptodate = 0;
7988 done->uptodate = uptodate;
7989 end:
7990 complete(&done->done);
7991 bio_put(bio);
7994 static blk_status_t __btrfs_subio_endio_read(struct inode *inode,
7995 struct btrfs_io_bio *io_bio, blk_status_t err)
7997 struct btrfs_fs_info *fs_info;
7998 struct bio_vec bvec;
7999 struct bvec_iter iter;
8000 struct btrfs_retry_complete done;
8001 u64 start;
8002 u64 offset = 0;
8003 u32 sectorsize;
8004 int nr_sectors;
8005 unsigned int pgoff;
8006 int csum_pos;
8007 bool uptodate = (err == 0);
8008 int ret;
8009 blk_status_t status;
8011 fs_info = BTRFS_I(inode)->root->fs_info;
8012 sectorsize = fs_info->sectorsize;
8014 err = BLK_STS_OK;
8015 start = io_bio->logical;
8016 done.inode = inode;
8017 io_bio->bio.bi_iter = io_bio->iter;
8019 bio_for_each_segment(bvec, &io_bio->bio, iter) {
8020 nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec.bv_len);
8022 pgoff = bvec.bv_offset;
8023 next_block:
8024 if (uptodate) {
8025 csum_pos = BTRFS_BYTES_TO_BLKS(fs_info, offset);
8026 ret = __readpage_endio_check(inode, io_bio, csum_pos,
8027 bvec.bv_page, pgoff, start, sectorsize);
8028 if (likely(!ret))
8029 goto next;
8031 try_again:
8032 done.uptodate = 0;
8033 done.start = start;
8034 init_completion(&done.done);
8036 status = dio_read_error(inode, &io_bio->bio, bvec.bv_page,
8037 pgoff, start, start + sectorsize - 1,
8038 io_bio->mirror_num, btrfs_retry_endio,
8039 &done);
8040 if (status) {
8041 err = status;
8042 goto next;
8045 wait_for_completion_io(&done.done);
8047 if (!done.uptodate) {
8048 /* We might have another mirror, so try again */
8049 goto try_again;
8051 next:
8052 offset += sectorsize;
8053 start += sectorsize;
8055 ASSERT(nr_sectors);
8057 nr_sectors--;
8058 if (nr_sectors) {
8059 pgoff += sectorsize;
8060 ASSERT(pgoff < PAGE_SIZE);
8061 goto next_block;
8065 return err;
8068 static blk_status_t btrfs_subio_endio_read(struct inode *inode,
8069 struct btrfs_io_bio *io_bio, blk_status_t err)
8071 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8073 if (skip_csum) {
8074 if (unlikely(err))
8075 return __btrfs_correct_data_nocsum(inode, io_bio);
8076 else
8077 return BLK_STS_OK;
8078 } else {
8079 return __btrfs_subio_endio_read(inode, io_bio, err);
8083 static void btrfs_endio_direct_read(struct bio *bio)
8085 struct btrfs_dio_private *dip = bio->bi_private;
8086 struct inode *inode = dip->inode;
8087 struct bio *dio_bio;
8088 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8089 blk_status_t err = bio->bi_status;
8091 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8092 err = btrfs_subio_endio_read(inode, io_bio, err);
8094 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8095 dip->logical_offset + dip->bytes - 1);
8096 dio_bio = dip->dio_bio;
8098 kfree(dip);
8100 dio_bio->bi_status = err;
8101 dio_end_io(dio_bio);
8103 if (io_bio->end_io)
8104 io_bio->end_io(io_bio, blk_status_to_errno(err));
8105 bio_put(bio);
8108 static void __endio_write_update_ordered(struct inode *inode,
8109 const u64 offset, const u64 bytes,
8110 const bool uptodate)
8112 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8113 struct btrfs_ordered_extent *ordered = NULL;
8114 struct btrfs_workqueue *wq;
8115 btrfs_work_func_t func;
8116 u64 ordered_offset = offset;
8117 u64 ordered_bytes = bytes;
8118 u64 last_offset;
8120 if (btrfs_is_free_space_inode(BTRFS_I(inode))) {
8121 wq = fs_info->endio_freespace_worker;
8122 func = btrfs_freespace_write_helper;
8123 } else {
8124 wq = fs_info->endio_write_workers;
8125 func = btrfs_endio_write_helper;
8128 while (ordered_offset < offset + bytes) {
8129 last_offset = ordered_offset;
8130 if (btrfs_dec_test_first_ordered_pending(inode, &ordered,
8131 &ordered_offset,
8132 ordered_bytes,
8133 uptodate)) {
8134 btrfs_init_work(&ordered->work, func,
8135 finish_ordered_fn,
8136 NULL, NULL);
8137 btrfs_queue_work(wq, &ordered->work);
8140 * If btrfs_dec_test_ordered_pending does not find any ordered
8141 * extent in the range, we can exit.
8143 if (ordered_offset == last_offset)
8144 return;
8146 * Our bio might span multiple ordered extents. In this case
8147 * we keep goin until we have accounted the whole dio.
8149 if (ordered_offset < offset + bytes) {
8150 ordered_bytes = offset + bytes - ordered_offset;
8151 ordered = NULL;
8156 static void btrfs_endio_direct_write(struct bio *bio)
8158 struct btrfs_dio_private *dip = bio->bi_private;
8159 struct bio *dio_bio = dip->dio_bio;
8161 __endio_write_update_ordered(dip->inode, dip->logical_offset,
8162 dip->bytes, !bio->bi_status);
8164 kfree(dip);
8166 dio_bio->bi_status = bio->bi_status;
8167 dio_end_io(dio_bio);
8168 bio_put(bio);
8171 static blk_status_t btrfs_submit_bio_start_direct_io(void *private_data,
8172 struct bio *bio, u64 offset)
8174 struct inode *inode = private_data;
8175 blk_status_t ret;
8176 ret = btrfs_csum_one_bio(inode, bio, offset, 1);
8177 BUG_ON(ret); /* -ENOMEM */
8178 return 0;
8181 static void btrfs_end_dio_bio(struct bio *bio)
8183 struct btrfs_dio_private *dip = bio->bi_private;
8184 blk_status_t err = bio->bi_status;
8186 if (err)
8187 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8188 "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
8189 btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
8190 bio->bi_opf,
8191 (unsigned long long)bio->bi_iter.bi_sector,
8192 bio->bi_iter.bi_size, err);
8194 if (dip->subio_endio)
8195 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8197 if (err) {
8199 * We want to perceive the errors flag being set before
8200 * decrementing the reference count. We don't need a barrier
8201 * since atomic operations with a return value are fully
8202 * ordered as per atomic_t.txt
8204 dip->errors = 1;
8207 /* if there are more bios still pending for this dio, just exit */
8208 if (!atomic_dec_and_test(&dip->pending_bios))
8209 goto out;
8211 if (dip->errors) {
8212 bio_io_error(dip->orig_bio);
8213 } else {
8214 dip->dio_bio->bi_status = BLK_STS_OK;
8215 bio_endio(dip->orig_bio);
8217 out:
8218 bio_put(bio);
8221 static inline blk_status_t btrfs_lookup_and_bind_dio_csum(struct inode *inode,
8222 struct btrfs_dio_private *dip,
8223 struct bio *bio,
8224 u64 file_offset)
8226 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8227 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8228 blk_status_t ret;
8231 * We load all the csum data we need when we submit
8232 * the first bio to reduce the csum tree search and
8233 * contention.
8235 if (dip->logical_offset == file_offset) {
8236 ret = btrfs_lookup_bio_sums_dio(inode, dip->orig_bio,
8237 file_offset);
8238 if (ret)
8239 return ret;
8242 if (bio == dip->orig_bio)
8243 return 0;
8245 file_offset -= dip->logical_offset;
8246 file_offset >>= inode->i_sb->s_blocksize_bits;
8247 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8249 return 0;
8252 static inline blk_status_t btrfs_submit_dio_bio(struct bio *bio,
8253 struct inode *inode, u64 file_offset, int async_submit)
8255 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8256 struct btrfs_dio_private *dip = bio->bi_private;
8257 bool write = bio_op(bio) == REQ_OP_WRITE;
8258 blk_status_t ret;
8260 /* Check btrfs_submit_bio_hook() for rules about async submit. */
8261 if (async_submit)
8262 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8264 if (!write) {
8265 ret = btrfs_bio_wq_end_io(fs_info, bio, BTRFS_WQ_ENDIO_DATA);
8266 if (ret)
8267 goto err;
8270 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
8271 goto map;
8273 if (write && async_submit) {
8274 ret = btrfs_wq_submit_bio(fs_info, bio, 0, 0,
8275 file_offset, inode,
8276 btrfs_submit_bio_start_direct_io,
8277 btrfs_submit_bio_done);
8278 goto err;
8279 } else if (write) {
8281 * If we aren't doing async submit, calculate the csum of the
8282 * bio now.
8284 ret = btrfs_csum_one_bio(inode, bio, file_offset, 1);
8285 if (ret)
8286 goto err;
8287 } else {
8288 ret = btrfs_lookup_and_bind_dio_csum(inode, dip, bio,
8289 file_offset);
8290 if (ret)
8291 goto err;
8293 map:
8294 ret = btrfs_map_bio(fs_info, bio, 0, 0);
8295 err:
8296 return ret;
8299 static int btrfs_submit_direct_hook(struct btrfs_dio_private *dip)
8301 struct inode *inode = dip->inode;
8302 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8303 struct bio *bio;
8304 struct bio *orig_bio = dip->orig_bio;
8305 u64 start_sector = orig_bio->bi_iter.bi_sector;
8306 u64 file_offset = dip->logical_offset;
8307 u64 map_length;
8308 int async_submit = 0;
8309 u64 submit_len;
8310 int clone_offset = 0;
8311 int clone_len;
8312 int ret;
8313 blk_status_t status;
8315 map_length = orig_bio->bi_iter.bi_size;
8316 submit_len = map_length;
8317 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio), start_sector << 9,
8318 &map_length, NULL, 0);
8319 if (ret)
8320 return -EIO;
8322 if (map_length >= submit_len) {
8323 bio = orig_bio;
8324 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8325 goto submit;
8328 /* async crcs make it difficult to collect full stripe writes. */
8329 if (btrfs_data_alloc_profile(fs_info) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8330 async_submit = 0;
8331 else
8332 async_submit = 1;
8334 /* bio split */
8335 ASSERT(map_length <= INT_MAX);
8336 atomic_inc(&dip->pending_bios);
8337 do {
8338 clone_len = min_t(int, submit_len, map_length);
8341 * This will never fail as it's passing GPF_NOFS and
8342 * the allocation is backed by btrfs_bioset.
8344 bio = btrfs_bio_clone_partial(orig_bio, clone_offset,
8345 clone_len);
8346 bio->bi_private = dip;
8347 bio->bi_end_io = btrfs_end_dio_bio;
8348 btrfs_io_bio(bio)->logical = file_offset;
8350 ASSERT(submit_len >= clone_len);
8351 submit_len -= clone_len;
8352 if (submit_len == 0)
8353 break;
8356 * Increase the count before we submit the bio so we know
8357 * the end IO handler won't happen before we increase the
8358 * count. Otherwise, the dip might get freed before we're
8359 * done setting it up.
8361 atomic_inc(&dip->pending_bios);
8363 status = btrfs_submit_dio_bio(bio, inode, file_offset,
8364 async_submit);
8365 if (status) {
8366 bio_put(bio);
8367 atomic_dec(&dip->pending_bios);
8368 goto out_err;
8371 clone_offset += clone_len;
8372 start_sector += clone_len >> 9;
8373 file_offset += clone_len;
8375 map_length = submit_len;
8376 ret = btrfs_map_block(fs_info, btrfs_op(orig_bio),
8377 start_sector << 9, &map_length, NULL, 0);
8378 if (ret)
8379 goto out_err;
8380 } while (submit_len > 0);
8382 submit:
8383 status = btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
8384 if (!status)
8385 return 0;
8387 bio_put(bio);
8388 out_err:
8389 dip->errors = 1;
8391 * Before atomic variable goto zero, we must make sure dip->errors is
8392 * perceived to be set. This ordering is ensured by the fact that an
8393 * atomic operations with a return value are fully ordered as per
8394 * atomic_t.txt
8396 if (atomic_dec_and_test(&dip->pending_bios))
8397 bio_io_error(dip->orig_bio);
8399 /* bio_end_io() will handle error, so we needn't return it */
8400 return 0;
8403 static void btrfs_submit_direct(struct bio *dio_bio, struct inode *inode,
8404 loff_t file_offset)
8406 struct btrfs_dio_private *dip = NULL;
8407 struct bio *bio = NULL;
8408 struct btrfs_io_bio *io_bio;
8409 bool write = (bio_op(dio_bio) == REQ_OP_WRITE);
8410 int ret = 0;
8412 bio = btrfs_bio_clone(dio_bio);
8414 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8415 if (!dip) {
8416 ret = -ENOMEM;
8417 goto free_ordered;
8420 dip->private = dio_bio->bi_private;
8421 dip->inode = inode;
8422 dip->logical_offset = file_offset;
8423 dip->bytes = dio_bio->bi_iter.bi_size;
8424 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8425 bio->bi_private = dip;
8426 dip->orig_bio = bio;
8427 dip->dio_bio = dio_bio;
8428 atomic_set(&dip->pending_bios, 0);
8429 io_bio = btrfs_io_bio(bio);
8430 io_bio->logical = file_offset;
8432 if (write) {
8433 bio->bi_end_io = btrfs_endio_direct_write;
8434 } else {
8435 bio->bi_end_io = btrfs_endio_direct_read;
8436 dip->subio_endio = btrfs_subio_endio_read;
8440 * Reset the range for unsubmitted ordered extents (to a 0 length range)
8441 * even if we fail to submit a bio, because in such case we do the
8442 * corresponding error handling below and it must not be done a second
8443 * time by btrfs_direct_IO().
8445 if (write) {
8446 struct btrfs_dio_data *dio_data = current->journal_info;
8448 dio_data->unsubmitted_oe_range_end = dip->logical_offset +
8449 dip->bytes;
8450 dio_data->unsubmitted_oe_range_start =
8451 dio_data->unsubmitted_oe_range_end;
8454 ret = btrfs_submit_direct_hook(dip);
8455 if (!ret)
8456 return;
8458 if (io_bio->end_io)
8459 io_bio->end_io(io_bio, ret);
8461 free_ordered:
8463 * If we arrived here it means either we failed to submit the dip
8464 * or we either failed to clone the dio_bio or failed to allocate the
8465 * dip. If we cloned the dio_bio and allocated the dip, we can just
8466 * call bio_endio against our io_bio so that we get proper resource
8467 * cleanup if we fail to submit the dip, otherwise, we must do the
8468 * same as btrfs_endio_direct_[write|read] because we can't call these
8469 * callbacks - they require an allocated dip and a clone of dio_bio.
8471 if (bio && dip) {
8472 bio_io_error(bio);
8474 * The end io callbacks free our dip, do the final put on bio
8475 * and all the cleanup and final put for dio_bio (through
8476 * dio_end_io()).
8478 dip = NULL;
8479 bio = NULL;
8480 } else {
8481 if (write)
8482 __endio_write_update_ordered(inode,
8483 file_offset,
8484 dio_bio->bi_iter.bi_size,
8485 false);
8486 else
8487 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8488 file_offset + dio_bio->bi_iter.bi_size - 1);
8490 dio_bio->bi_status = BLK_STS_IOERR;
8492 * Releases and cleans up our dio_bio, no need to bio_put()
8493 * nor bio_endio()/bio_io_error() against dio_bio.
8495 dio_end_io(dio_bio);
8497 if (bio)
8498 bio_put(bio);
8499 kfree(dip);
8502 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
8503 const struct iov_iter *iter, loff_t offset)
8505 int seg;
8506 int i;
8507 unsigned int blocksize_mask = fs_info->sectorsize - 1;
8508 ssize_t retval = -EINVAL;
8510 if (offset & blocksize_mask)
8511 goto out;
8513 if (iov_iter_alignment(iter) & blocksize_mask)
8514 goto out;
8516 /* If this is a write we don't need to check anymore */
8517 if (iov_iter_rw(iter) != READ || !iter_is_iovec(iter))
8518 return 0;
8520 * Check to make sure we don't have duplicate iov_base's in this
8521 * iovec, if so return EINVAL, otherwise we'll get csum errors
8522 * when reading back.
8524 for (seg = 0; seg < iter->nr_segs; seg++) {
8525 for (i = seg + 1; i < iter->nr_segs; i++) {
8526 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8527 goto out;
8530 retval = 0;
8531 out:
8532 return retval;
8535 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
8537 struct file *file = iocb->ki_filp;
8538 struct inode *inode = file->f_mapping->host;
8539 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8540 struct btrfs_dio_data dio_data = { 0 };
8541 struct extent_changeset *data_reserved = NULL;
8542 loff_t offset = iocb->ki_pos;
8543 size_t count = 0;
8544 int flags = 0;
8545 bool wakeup = true;
8546 bool relock = false;
8547 ssize_t ret;
8549 if (check_direct_IO(fs_info, iter, offset))
8550 return 0;
8552 inode_dio_begin(inode);
8555 * The generic stuff only does filemap_write_and_wait_range, which
8556 * isn't enough if we've written compressed pages to this area, so
8557 * we need to flush the dirty pages again to make absolutely sure
8558 * that any outstanding dirty pages are on disk.
8560 count = iov_iter_count(iter);
8561 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8562 &BTRFS_I(inode)->runtime_flags))
8563 filemap_fdatawrite_range(inode->i_mapping, offset,
8564 offset + count - 1);
8566 if (iov_iter_rw(iter) == WRITE) {
8568 * If the write DIO is beyond the EOF, we need update
8569 * the isize, but it is protected by i_mutex. So we can
8570 * not unlock the i_mutex at this case.
8572 if (offset + count <= inode->i_size) {
8573 dio_data.overwrite = 1;
8574 inode_unlock(inode);
8575 relock = true;
8576 } else if (iocb->ki_flags & IOCB_NOWAIT) {
8577 ret = -EAGAIN;
8578 goto out;
8580 ret = btrfs_delalloc_reserve_space(inode, &data_reserved,
8581 offset, count);
8582 if (ret)
8583 goto out;
8586 * We need to know how many extents we reserved so that we can
8587 * do the accounting properly if we go over the number we
8588 * originally calculated. Abuse current->journal_info for this.
8590 dio_data.reserve = round_up(count,
8591 fs_info->sectorsize);
8592 dio_data.unsubmitted_oe_range_start = (u64)offset;
8593 dio_data.unsubmitted_oe_range_end = (u64)offset;
8594 current->journal_info = &dio_data;
8595 down_read(&BTRFS_I(inode)->dio_sem);
8596 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8597 &BTRFS_I(inode)->runtime_flags)) {
8598 inode_dio_end(inode);
8599 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8600 wakeup = false;
8603 ret = __blockdev_direct_IO(iocb, inode,
8604 fs_info->fs_devices->latest_bdev,
8605 iter, btrfs_get_blocks_direct, NULL,
8606 btrfs_submit_direct, flags);
8607 if (iov_iter_rw(iter) == WRITE) {
8608 up_read(&BTRFS_I(inode)->dio_sem);
8609 current->journal_info = NULL;
8610 if (ret < 0 && ret != -EIOCBQUEUED) {
8611 if (dio_data.reserve)
8612 btrfs_delalloc_release_space(inode, data_reserved,
8613 offset, dio_data.reserve, true);
8615 * On error we might have left some ordered extents
8616 * without submitting corresponding bios for them, so
8617 * cleanup them up to avoid other tasks getting them
8618 * and waiting for them to complete forever.
8620 if (dio_data.unsubmitted_oe_range_start <
8621 dio_data.unsubmitted_oe_range_end)
8622 __endio_write_update_ordered(inode,
8623 dio_data.unsubmitted_oe_range_start,
8624 dio_data.unsubmitted_oe_range_end -
8625 dio_data.unsubmitted_oe_range_start,
8626 false);
8627 } else if (ret >= 0 && (size_t)ret < count)
8628 btrfs_delalloc_release_space(inode, data_reserved,
8629 offset, count - (size_t)ret, true);
8630 btrfs_delalloc_release_extents(BTRFS_I(inode), count, false);
8632 out:
8633 if (wakeup)
8634 inode_dio_end(inode);
8635 if (relock)
8636 inode_lock(inode);
8638 extent_changeset_free(data_reserved);
8639 return ret;
8642 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8644 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8645 __u64 start, __u64 len)
8647 int ret;
8649 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8650 if (ret)
8651 return ret;
8653 return extent_fiemap(inode, fieinfo, start, len);
8656 int btrfs_readpage(struct file *file, struct page *page)
8658 struct extent_io_tree *tree;
8659 tree = &BTRFS_I(page->mapping->host)->io_tree;
8660 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8663 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8665 struct inode *inode = page->mapping->host;
8666 int ret;
8668 if (current->flags & PF_MEMALLOC) {
8669 redirty_page_for_writepage(wbc, page);
8670 unlock_page(page);
8671 return 0;
8675 * If we are under memory pressure we will call this directly from the
8676 * VM, we need to make sure we have the inode referenced for the ordered
8677 * extent. If not just return like we didn't do anything.
8679 if (!igrab(inode)) {
8680 redirty_page_for_writepage(wbc, page);
8681 return AOP_WRITEPAGE_ACTIVATE;
8683 ret = extent_write_full_page(page, wbc);
8684 btrfs_add_delayed_iput(inode);
8685 return ret;
8688 static int btrfs_writepages(struct address_space *mapping,
8689 struct writeback_control *wbc)
8691 return extent_writepages(mapping, wbc);
8694 static int
8695 btrfs_readpages(struct file *file, struct address_space *mapping,
8696 struct list_head *pages, unsigned nr_pages)
8698 return extent_readpages(mapping, pages, nr_pages);
8701 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8703 int ret = try_release_extent_mapping(page, gfp_flags);
8704 if (ret == 1) {
8705 ClearPagePrivate(page);
8706 set_page_private(page, 0);
8707 put_page(page);
8709 return ret;
8712 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8714 if (PageWriteback(page) || PageDirty(page))
8715 return 0;
8716 return __btrfs_releasepage(page, gfp_flags);
8719 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8720 unsigned int length)
8722 struct inode *inode = page->mapping->host;
8723 struct extent_io_tree *tree;
8724 struct btrfs_ordered_extent *ordered;
8725 struct extent_state *cached_state = NULL;
8726 u64 page_start = page_offset(page);
8727 u64 page_end = page_start + PAGE_SIZE - 1;
8728 u64 start;
8729 u64 end;
8730 int inode_evicting = inode->i_state & I_FREEING;
8733 * we have the page locked, so new writeback can't start,
8734 * and the dirty bit won't be cleared while we are here.
8736 * Wait for IO on this page so that we can safely clear
8737 * the PagePrivate2 bit and do ordered accounting
8739 wait_on_page_writeback(page);
8741 tree = &BTRFS_I(inode)->io_tree;
8742 if (offset) {
8743 btrfs_releasepage(page, GFP_NOFS);
8744 return;
8747 if (!inode_evicting)
8748 lock_extent_bits(tree, page_start, page_end, &cached_state);
8749 again:
8750 start = page_start;
8751 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), start,
8752 page_end - start + 1);
8753 if (ordered) {
8754 end = min(page_end, ordered->file_offset + ordered->len - 1);
8756 * IO on this page will never be started, so we need
8757 * to account for any ordered extents now
8759 if (!inode_evicting)
8760 clear_extent_bit(tree, start, end,
8761 EXTENT_DIRTY | EXTENT_DELALLOC |
8762 EXTENT_DELALLOC_NEW |
8763 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8764 EXTENT_DEFRAG, 1, 0, &cached_state);
8766 * whoever cleared the private bit is responsible
8767 * for the finish_ordered_io
8769 if (TestClearPagePrivate2(page)) {
8770 struct btrfs_ordered_inode_tree *tree;
8771 u64 new_len;
8773 tree = &BTRFS_I(inode)->ordered_tree;
8775 spin_lock_irq(&tree->lock);
8776 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8777 new_len = start - ordered->file_offset;
8778 if (new_len < ordered->truncated_len)
8779 ordered->truncated_len = new_len;
8780 spin_unlock_irq(&tree->lock);
8782 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8783 start,
8784 end - start + 1, 1))
8785 btrfs_finish_ordered_io(ordered);
8787 btrfs_put_ordered_extent(ordered);
8788 if (!inode_evicting) {
8789 cached_state = NULL;
8790 lock_extent_bits(tree, start, end,
8791 &cached_state);
8794 start = end + 1;
8795 if (start < page_end)
8796 goto again;
8800 * Qgroup reserved space handler
8801 * Page here will be either
8802 * 1) Already written to disk
8803 * In this case, its reserved space is released from data rsv map
8804 * and will be freed by delayed_ref handler finally.
8805 * So even we call qgroup_free_data(), it won't decrease reserved
8806 * space.
8807 * 2) Not written to disk
8808 * This means the reserved space should be freed here. However,
8809 * if a truncate invalidates the page (by clearing PageDirty)
8810 * and the page is accounted for while allocating extent
8811 * in btrfs_check_data_free_space() we let delayed_ref to
8812 * free the entire extent.
8814 if (PageDirty(page))
8815 btrfs_qgroup_free_data(inode, NULL, page_start, PAGE_SIZE);
8816 if (!inode_evicting) {
8817 clear_extent_bit(tree, page_start, page_end,
8818 EXTENT_LOCKED | EXTENT_DIRTY |
8819 EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
8820 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1,
8821 &cached_state);
8823 __btrfs_releasepage(page, GFP_NOFS);
8826 ClearPageChecked(page);
8827 if (PagePrivate(page)) {
8828 ClearPagePrivate(page);
8829 set_page_private(page, 0);
8830 put_page(page);
8835 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8836 * called from a page fault handler when a page is first dirtied. Hence we must
8837 * be careful to check for EOF conditions here. We set the page up correctly
8838 * for a written page which means we get ENOSPC checking when writing into
8839 * holes and correct delalloc and unwritten extent mapping on filesystems that
8840 * support these features.
8842 * We are not allowed to take the i_mutex here so we have to play games to
8843 * protect against truncate races as the page could now be beyond EOF. Because
8844 * truncate_setsize() writes the inode size before removing pages, once we have
8845 * the page lock we can determine safely if the page is beyond EOF. If it is not
8846 * beyond EOF, then the page is guaranteed safe against truncation until we
8847 * unlock the page.
8849 vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
8851 struct page *page = vmf->page;
8852 struct inode *inode = file_inode(vmf->vma->vm_file);
8853 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
8854 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8855 struct btrfs_ordered_extent *ordered;
8856 struct extent_state *cached_state = NULL;
8857 struct extent_changeset *data_reserved = NULL;
8858 char *kaddr;
8859 unsigned long zero_start;
8860 loff_t size;
8861 vm_fault_t ret;
8862 int ret2;
8863 int reserved = 0;
8864 u64 reserved_space;
8865 u64 page_start;
8866 u64 page_end;
8867 u64 end;
8869 reserved_space = PAGE_SIZE;
8871 sb_start_pagefault(inode->i_sb);
8872 page_start = page_offset(page);
8873 page_end = page_start + PAGE_SIZE - 1;
8874 end = page_end;
8877 * Reserving delalloc space after obtaining the page lock can lead to
8878 * deadlock. For example, if a dirty page is locked by this function
8879 * and the call to btrfs_delalloc_reserve_space() ends up triggering
8880 * dirty page write out, then the btrfs_writepage() function could
8881 * end up waiting indefinitely to get a lock on the page currently
8882 * being processed by btrfs_page_mkwrite() function.
8884 ret2 = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
8885 reserved_space);
8886 if (!ret2) {
8887 ret2 = file_update_time(vmf->vma->vm_file);
8888 reserved = 1;
8890 if (ret2) {
8891 ret = vmf_error(ret2);
8892 if (reserved)
8893 goto out;
8894 goto out_noreserve;
8897 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8898 again:
8899 lock_page(page);
8900 size = i_size_read(inode);
8902 if ((page->mapping != inode->i_mapping) ||
8903 (page_start >= size)) {
8904 /* page got truncated out from underneath us */
8905 goto out_unlock;
8907 wait_on_page_writeback(page);
8909 lock_extent_bits(io_tree, page_start, page_end, &cached_state);
8910 set_page_extent_mapped(page);
8913 * we can't set the delalloc bits if there are pending ordered
8914 * extents. Drop our locks and wait for them to finish
8916 ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
8917 PAGE_SIZE);
8918 if (ordered) {
8919 unlock_extent_cached(io_tree, page_start, page_end,
8920 &cached_state);
8921 unlock_page(page);
8922 btrfs_start_ordered_extent(inode, ordered, 1);
8923 btrfs_put_ordered_extent(ordered);
8924 goto again;
8927 if (page->index == ((size - 1) >> PAGE_SHIFT)) {
8928 reserved_space = round_up(size - page_start,
8929 fs_info->sectorsize);
8930 if (reserved_space < PAGE_SIZE) {
8931 end = page_start + reserved_space - 1;
8932 btrfs_delalloc_release_space(inode, data_reserved,
8933 page_start, PAGE_SIZE - reserved_space,
8934 true);
8939 * page_mkwrite gets called when the page is firstly dirtied after it's
8940 * faulted in, but write(2) could also dirty a page and set delalloc
8941 * bits, thus in this case for space account reason, we still need to
8942 * clear any delalloc bits within this page range since we have to
8943 * reserve data&meta space before lock_page() (see above comments).
8945 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
8946 EXTENT_DIRTY | EXTENT_DELALLOC |
8947 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8948 0, 0, &cached_state);
8950 ret2 = btrfs_set_extent_delalloc(inode, page_start, end, 0,
8951 &cached_state, 0);
8952 if (ret2) {
8953 unlock_extent_cached(io_tree, page_start, page_end,
8954 &cached_state);
8955 ret = VM_FAULT_SIGBUS;
8956 goto out_unlock;
8958 ret2 = 0;
8960 /* page is wholly or partially inside EOF */
8961 if (page_start + PAGE_SIZE > size)
8962 zero_start = size & ~PAGE_MASK;
8963 else
8964 zero_start = PAGE_SIZE;
8966 if (zero_start != PAGE_SIZE) {
8967 kaddr = kmap(page);
8968 memset(kaddr + zero_start, 0, PAGE_SIZE - zero_start);
8969 flush_dcache_page(page);
8970 kunmap(page);
8972 ClearPageChecked(page);
8973 set_page_dirty(page);
8974 SetPageUptodate(page);
8976 BTRFS_I(inode)->last_trans = fs_info->generation;
8977 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8978 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8980 unlock_extent_cached(io_tree, page_start, page_end, &cached_state);
8982 if (!ret2) {
8983 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, true);
8984 sb_end_pagefault(inode->i_sb);
8985 extent_changeset_free(data_reserved);
8986 return VM_FAULT_LOCKED;
8989 out_unlock:
8990 unlock_page(page);
8991 out:
8992 btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE, (ret != 0));
8993 btrfs_delalloc_release_space(inode, data_reserved, page_start,
8994 reserved_space, (ret != 0));
8995 out_noreserve:
8996 sb_end_pagefault(inode->i_sb);
8997 extent_changeset_free(data_reserved);
8998 return ret;
9001 static int btrfs_truncate(struct inode *inode, bool skip_writeback)
9003 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9004 struct btrfs_root *root = BTRFS_I(inode)->root;
9005 struct btrfs_block_rsv *rsv;
9006 int ret;
9007 struct btrfs_trans_handle *trans;
9008 u64 mask = fs_info->sectorsize - 1;
9009 u64 min_size = btrfs_calc_trunc_metadata_size(fs_info, 1);
9011 if (!skip_writeback) {
9012 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
9013 (u64)-1);
9014 if (ret)
9015 return ret;
9019 * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
9020 * things going on here:
9022 * 1) We need to reserve space to update our inode.
9024 * 2) We need to have something to cache all the space that is going to
9025 * be free'd up by the truncate operation, but also have some slack
9026 * space reserved in case it uses space during the truncate (thank you
9027 * very much snapshotting).
9029 * And we need these to be separate. The fact is we can use a lot of
9030 * space doing the truncate, and we have no earthly idea how much space
9031 * we will use, so we need the truncate reservation to be separate so it
9032 * doesn't end up using space reserved for updating the inode. We also
9033 * need to be able to stop the transaction and start a new one, which
9034 * means we need to be able to update the inode several times, and we
9035 * have no idea of knowing how many times that will be, so we can't just
9036 * reserve 1 item for the entirety of the operation, so that has to be
9037 * done separately as well.
9039 * So that leaves us with
9041 * 1) rsv - for the truncate reservation, which we will steal from the
9042 * transaction reservation.
9043 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
9044 * updating the inode.
9046 rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
9047 if (!rsv)
9048 return -ENOMEM;
9049 rsv->size = min_size;
9050 rsv->failfast = 1;
9053 * 1 for the truncate slack space
9054 * 1 for updating the inode.
9056 trans = btrfs_start_transaction(root, 2);
9057 if (IS_ERR(trans)) {
9058 ret = PTR_ERR(trans);
9059 goto out;
9062 /* Migrate the slack space for the truncate to our reserve */
9063 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
9064 min_size, 0);
9065 BUG_ON(ret);
9068 * So if we truncate and then write and fsync we normally would just
9069 * write the extents that changed, which is a problem if we need to
9070 * first truncate that entire inode. So set this flag so we write out
9071 * all of the extents in the inode to the sync log so we're completely
9072 * safe.
9074 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9075 trans->block_rsv = rsv;
9077 while (1) {
9078 ret = btrfs_truncate_inode_items(trans, root, inode,
9079 inode->i_size,
9080 BTRFS_EXTENT_DATA_KEY);
9081 trans->block_rsv = &fs_info->trans_block_rsv;
9082 if (ret != -ENOSPC && ret != -EAGAIN)
9083 break;
9085 ret = btrfs_update_inode(trans, root, inode);
9086 if (ret)
9087 break;
9089 btrfs_end_transaction(trans);
9090 btrfs_btree_balance_dirty(fs_info);
9092 trans = btrfs_start_transaction(root, 2);
9093 if (IS_ERR(trans)) {
9094 ret = PTR_ERR(trans);
9095 trans = NULL;
9096 break;
9099 btrfs_block_rsv_release(fs_info, rsv, -1);
9100 ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
9101 rsv, min_size, 0);
9102 BUG_ON(ret); /* shouldn't happen */
9103 trans->block_rsv = rsv;
9107 * We can't call btrfs_truncate_block inside a trans handle as we could
9108 * deadlock with freeze, if we got NEED_TRUNCATE_BLOCK then we know
9109 * we've truncated everything except the last little bit, and can do
9110 * btrfs_truncate_block and then update the disk_i_size.
9112 if (ret == NEED_TRUNCATE_BLOCK) {
9113 btrfs_end_transaction(trans);
9114 btrfs_btree_balance_dirty(fs_info);
9116 ret = btrfs_truncate_block(inode, inode->i_size, 0, 0);
9117 if (ret)
9118 goto out;
9119 trans = btrfs_start_transaction(root, 1);
9120 if (IS_ERR(trans)) {
9121 ret = PTR_ERR(trans);
9122 goto out;
9124 btrfs_ordered_update_i_size(inode, inode->i_size, NULL);
9127 if (trans) {
9128 int ret2;
9130 trans->block_rsv = &fs_info->trans_block_rsv;
9131 ret2 = btrfs_update_inode(trans, root, inode);
9132 if (ret2 && !ret)
9133 ret = ret2;
9135 ret2 = btrfs_end_transaction(trans);
9136 if (ret2 && !ret)
9137 ret = ret2;
9138 btrfs_btree_balance_dirty(fs_info);
9140 out:
9141 btrfs_free_block_rsv(fs_info, rsv);
9143 return ret;
9147 * create a new subvolume directory/inode (helper for the ioctl).
9149 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9150 struct btrfs_root *new_root,
9151 struct btrfs_root *parent_root,
9152 u64 new_dirid)
9154 struct inode *inode;
9155 int err;
9156 u64 index = 0;
9158 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9159 new_dirid, new_dirid,
9160 S_IFDIR | (~current_umask() & S_IRWXUGO),
9161 &index);
9162 if (IS_ERR(inode))
9163 return PTR_ERR(inode);
9164 inode->i_op = &btrfs_dir_inode_operations;
9165 inode->i_fop = &btrfs_dir_file_operations;
9167 set_nlink(inode, 1);
9168 btrfs_i_size_write(BTRFS_I(inode), 0);
9169 unlock_new_inode(inode);
9171 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9172 if (err)
9173 btrfs_err(new_root->fs_info,
9174 "error inheriting subvolume %llu properties: %d",
9175 new_root->root_key.objectid, err);
9177 err = btrfs_update_inode(trans, new_root, inode);
9179 iput(inode);
9180 return err;
9183 struct inode *btrfs_alloc_inode(struct super_block *sb)
9185 struct btrfs_fs_info *fs_info = btrfs_sb(sb);
9186 struct btrfs_inode *ei;
9187 struct inode *inode;
9189 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_KERNEL);
9190 if (!ei)
9191 return NULL;
9193 ei->root = NULL;
9194 ei->generation = 0;
9195 ei->last_trans = 0;
9196 ei->last_sub_trans = 0;
9197 ei->logged_trans = 0;
9198 ei->delalloc_bytes = 0;
9199 ei->new_delalloc_bytes = 0;
9200 ei->defrag_bytes = 0;
9201 ei->disk_i_size = 0;
9202 ei->flags = 0;
9203 ei->csum_bytes = 0;
9204 ei->index_cnt = (u64)-1;
9205 ei->dir_index = 0;
9206 ei->last_unlink_trans = 0;
9207 ei->last_log_commit = 0;
9209 spin_lock_init(&ei->lock);
9210 ei->outstanding_extents = 0;
9211 if (sb->s_magic != BTRFS_TEST_MAGIC)
9212 btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
9213 BTRFS_BLOCK_RSV_DELALLOC);
9214 ei->runtime_flags = 0;
9215 ei->prop_compress = BTRFS_COMPRESS_NONE;
9216 ei->defrag_compress = BTRFS_COMPRESS_NONE;
9218 ei->delayed_node = NULL;
9220 ei->i_otime.tv_sec = 0;
9221 ei->i_otime.tv_nsec = 0;
9223 inode = &ei->vfs_inode;
9224 extent_map_tree_init(&ei->extent_tree);
9225 extent_io_tree_init(&ei->io_tree, inode);
9226 extent_io_tree_init(&ei->io_failure_tree, inode);
9227 ei->io_tree.track_uptodate = 1;
9228 ei->io_failure_tree.track_uptodate = 1;
9229 atomic_set(&ei->sync_writers, 0);
9230 mutex_init(&ei->log_mutex);
9231 mutex_init(&ei->delalloc_mutex);
9232 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9233 INIT_LIST_HEAD(&ei->delalloc_inodes);
9234 INIT_LIST_HEAD(&ei->delayed_iput);
9235 RB_CLEAR_NODE(&ei->rb_node);
9236 init_rwsem(&ei->dio_sem);
9238 return inode;
9241 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9242 void btrfs_test_destroy_inode(struct inode *inode)
9244 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9245 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9247 #endif
9249 static void btrfs_i_callback(struct rcu_head *head)
9251 struct inode *inode = container_of(head, struct inode, i_rcu);
9252 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9255 void btrfs_destroy_inode(struct inode *inode)
9257 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
9258 struct btrfs_ordered_extent *ordered;
9259 struct btrfs_root *root = BTRFS_I(inode)->root;
9261 WARN_ON(!hlist_empty(&inode->i_dentry));
9262 WARN_ON(inode->i_data.nrpages);
9263 WARN_ON(BTRFS_I(inode)->block_rsv.reserved);
9264 WARN_ON(BTRFS_I(inode)->block_rsv.size);
9265 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9266 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9267 WARN_ON(BTRFS_I(inode)->new_delalloc_bytes);
9268 WARN_ON(BTRFS_I(inode)->csum_bytes);
9269 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9272 * This can happen where we create an inode, but somebody else also
9273 * created the same inode and we need to destroy the one we already
9274 * created.
9276 if (!root)
9277 goto free;
9279 while (1) {
9280 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9281 if (!ordered)
9282 break;
9283 else {
9284 btrfs_err(fs_info,
9285 "found ordered extent %llu %llu on inode cleanup",
9286 ordered->file_offset, ordered->len);
9287 btrfs_remove_ordered_extent(inode, ordered);
9288 btrfs_put_ordered_extent(ordered);
9289 btrfs_put_ordered_extent(ordered);
9292 btrfs_qgroup_check_reserved_leak(inode);
9293 inode_tree_del(inode);
9294 btrfs_drop_extent_cache(BTRFS_I(inode), 0, (u64)-1, 0);
9295 free:
9296 call_rcu(&inode->i_rcu, btrfs_i_callback);
9299 int btrfs_drop_inode(struct inode *inode)
9301 struct btrfs_root *root = BTRFS_I(inode)->root;
9303 if (root == NULL)
9304 return 1;
9306 /* the snap/subvol tree is on deleting */
9307 if (btrfs_root_refs(&root->root_item) == 0)
9308 return 1;
9309 else
9310 return generic_drop_inode(inode);
9313 static void init_once(void *foo)
9315 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9317 inode_init_once(&ei->vfs_inode);
9320 void __cold btrfs_destroy_cachep(void)
9323 * Make sure all delayed rcu free inodes are flushed before we
9324 * destroy cache.
9326 rcu_barrier();
9327 kmem_cache_destroy(btrfs_inode_cachep);
9328 kmem_cache_destroy(btrfs_trans_handle_cachep);
9329 kmem_cache_destroy(btrfs_path_cachep);
9330 kmem_cache_destroy(btrfs_free_space_cachep);
9333 int __init btrfs_init_cachep(void)
9335 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9336 sizeof(struct btrfs_inode), 0,
9337 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
9338 init_once);
9339 if (!btrfs_inode_cachep)
9340 goto fail;
9342 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9343 sizeof(struct btrfs_trans_handle), 0,
9344 SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
9345 if (!btrfs_trans_handle_cachep)
9346 goto fail;
9348 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9349 sizeof(struct btrfs_path), 0,
9350 SLAB_MEM_SPREAD, NULL);
9351 if (!btrfs_path_cachep)
9352 goto fail;
9354 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9355 sizeof(struct btrfs_free_space), 0,
9356 SLAB_MEM_SPREAD, NULL);
9357 if (!btrfs_free_space_cachep)
9358 goto fail;
9360 return 0;
9361 fail:
9362 btrfs_destroy_cachep();
9363 return -ENOMEM;
9366 static int btrfs_getattr(const struct path *path, struct kstat *stat,
9367 u32 request_mask, unsigned int flags)
9369 u64 delalloc_bytes;
9370 struct inode *inode = d_inode(path->dentry);
9371 u32 blocksize = inode->i_sb->s_blocksize;
9372 u32 bi_flags = BTRFS_I(inode)->flags;
9374 stat->result_mask |= STATX_BTIME;
9375 stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
9376 stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
9377 if (bi_flags & BTRFS_INODE_APPEND)
9378 stat->attributes |= STATX_ATTR_APPEND;
9379 if (bi_flags & BTRFS_INODE_COMPRESS)
9380 stat->attributes |= STATX_ATTR_COMPRESSED;
9381 if (bi_flags & BTRFS_INODE_IMMUTABLE)
9382 stat->attributes |= STATX_ATTR_IMMUTABLE;
9383 if (bi_flags & BTRFS_INODE_NODUMP)
9384 stat->attributes |= STATX_ATTR_NODUMP;
9386 stat->attributes_mask |= (STATX_ATTR_APPEND |
9387 STATX_ATTR_COMPRESSED |
9388 STATX_ATTR_IMMUTABLE |
9389 STATX_ATTR_NODUMP);
9391 generic_fillattr(inode, stat);
9392 stat->dev = BTRFS_I(inode)->root->anon_dev;
9394 spin_lock(&BTRFS_I(inode)->lock);
9395 delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
9396 spin_unlock(&BTRFS_I(inode)->lock);
9397 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9398 ALIGN(delalloc_bytes, blocksize)) >> 9;
9399 return 0;
9402 static int btrfs_rename_exchange(struct inode *old_dir,
9403 struct dentry *old_dentry,
9404 struct inode *new_dir,
9405 struct dentry *new_dentry)
9407 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9408 struct btrfs_trans_handle *trans;
9409 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9410 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9411 struct inode *new_inode = new_dentry->d_inode;
9412 struct inode *old_inode = old_dentry->d_inode;
9413 struct timespec64 ctime = current_time(old_inode);
9414 struct dentry *parent;
9415 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9416 u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
9417 u64 old_idx = 0;
9418 u64 new_idx = 0;
9419 u64 root_objectid;
9420 int ret;
9421 int ret2;
9422 bool root_log_pinned = false;
9423 bool dest_log_pinned = false;
9425 /* we only allow rename subvolume link between subvolumes */
9426 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9427 return -EXDEV;
9429 /* close the race window with snapshot create/destroy ioctl */
9430 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9431 down_read(&fs_info->subvol_sem);
9432 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9433 down_read(&fs_info->subvol_sem);
9436 * We want to reserve the absolute worst case amount of items. So if
9437 * both inodes are subvols and we need to unlink them then that would
9438 * require 4 item modifications, but if they are both normal inodes it
9439 * would require 5 item modifications, so we'll assume their normal
9440 * inodes. So 5 * 2 is 10, plus 2 for the new links, so 12 total items
9441 * should cover the worst case number of items we'll modify.
9443 trans = btrfs_start_transaction(root, 12);
9444 if (IS_ERR(trans)) {
9445 ret = PTR_ERR(trans);
9446 goto out_notrans;
9450 * We need to find a free sequence number both in the source and
9451 * in the destination directory for the exchange.
9453 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
9454 if (ret)
9455 goto out_fail;
9456 ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
9457 if (ret)
9458 goto out_fail;
9460 BTRFS_I(old_inode)->dir_index = 0ULL;
9461 BTRFS_I(new_inode)->dir_index = 0ULL;
9463 /* Reference for the source. */
9464 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9465 /* force full log commit if subvolume involved. */
9466 btrfs_set_log_full_commit(fs_info, trans);
9467 } else {
9468 btrfs_pin_log_trans(root);
9469 root_log_pinned = true;
9470 ret = btrfs_insert_inode_ref(trans, dest,
9471 new_dentry->d_name.name,
9472 new_dentry->d_name.len,
9473 old_ino,
9474 btrfs_ino(BTRFS_I(new_dir)),
9475 old_idx);
9476 if (ret)
9477 goto out_fail;
9480 /* And now for the dest. */
9481 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9482 /* force full log commit if subvolume involved. */
9483 btrfs_set_log_full_commit(fs_info, trans);
9484 } else {
9485 btrfs_pin_log_trans(dest);
9486 dest_log_pinned = true;
9487 ret = btrfs_insert_inode_ref(trans, root,
9488 old_dentry->d_name.name,
9489 old_dentry->d_name.len,
9490 new_ino,
9491 btrfs_ino(BTRFS_I(old_dir)),
9492 new_idx);
9493 if (ret)
9494 goto out_fail;
9497 /* Update inode version and ctime/mtime. */
9498 inode_inc_iversion(old_dir);
9499 inode_inc_iversion(new_dir);
9500 inode_inc_iversion(old_inode);
9501 inode_inc_iversion(new_inode);
9502 old_dir->i_ctime = old_dir->i_mtime = ctime;
9503 new_dir->i_ctime = new_dir->i_mtime = ctime;
9504 old_inode->i_ctime = ctime;
9505 new_inode->i_ctime = ctime;
9507 if (old_dentry->d_parent != new_dentry->d_parent) {
9508 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9509 BTRFS_I(old_inode), 1);
9510 btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
9511 BTRFS_I(new_inode), 1);
9514 /* src is a subvolume */
9515 if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
9516 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9517 ret = btrfs_unlink_subvol(trans, root, old_dir,
9518 root_objectid,
9519 old_dentry->d_name.name,
9520 old_dentry->d_name.len);
9521 } else { /* src is an inode */
9522 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9523 BTRFS_I(old_dentry->d_inode),
9524 old_dentry->d_name.name,
9525 old_dentry->d_name.len);
9526 if (!ret)
9527 ret = btrfs_update_inode(trans, root, old_inode);
9529 if (ret) {
9530 btrfs_abort_transaction(trans, ret);
9531 goto out_fail;
9534 /* dest is a subvolume */
9535 if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
9536 root_objectid = BTRFS_I(new_inode)->root->root_key.objectid;
9537 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9538 root_objectid,
9539 new_dentry->d_name.name,
9540 new_dentry->d_name.len);
9541 } else { /* dest is an inode */
9542 ret = __btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9543 BTRFS_I(new_dentry->d_inode),
9544 new_dentry->d_name.name,
9545 new_dentry->d_name.len);
9546 if (!ret)
9547 ret = btrfs_update_inode(trans, dest, new_inode);
9549 if (ret) {
9550 btrfs_abort_transaction(trans, ret);
9551 goto out_fail;
9554 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9555 new_dentry->d_name.name,
9556 new_dentry->d_name.len, 0, old_idx);
9557 if (ret) {
9558 btrfs_abort_transaction(trans, ret);
9559 goto out_fail;
9562 ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
9563 old_dentry->d_name.name,
9564 old_dentry->d_name.len, 0, new_idx);
9565 if (ret) {
9566 btrfs_abort_transaction(trans, ret);
9567 goto out_fail;
9570 if (old_inode->i_nlink == 1)
9571 BTRFS_I(old_inode)->dir_index = old_idx;
9572 if (new_inode->i_nlink == 1)
9573 BTRFS_I(new_inode)->dir_index = new_idx;
9575 if (root_log_pinned) {
9576 parent = new_dentry->d_parent;
9577 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9578 parent);
9579 btrfs_end_log_trans(root);
9580 root_log_pinned = false;
9582 if (dest_log_pinned) {
9583 parent = old_dentry->d_parent;
9584 btrfs_log_new_name(trans, BTRFS_I(new_inode), BTRFS_I(new_dir),
9585 parent);
9586 btrfs_end_log_trans(dest);
9587 dest_log_pinned = false;
9589 out_fail:
9591 * If we have pinned a log and an error happened, we unpin tasks
9592 * trying to sync the log and force them to fallback to a transaction
9593 * commit if the log currently contains any of the inodes involved in
9594 * this rename operation (to ensure we do not persist a log with an
9595 * inconsistent state for any of these inodes or leading to any
9596 * inconsistencies when replayed). If the transaction was aborted, the
9597 * abortion reason is propagated to userspace when attempting to commit
9598 * the transaction. If the log does not contain any of these inodes, we
9599 * allow the tasks to sync it.
9601 if (ret && (root_log_pinned || dest_log_pinned)) {
9602 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9603 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9604 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9605 (new_inode &&
9606 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9607 btrfs_set_log_full_commit(fs_info, trans);
9609 if (root_log_pinned) {
9610 btrfs_end_log_trans(root);
9611 root_log_pinned = false;
9613 if (dest_log_pinned) {
9614 btrfs_end_log_trans(dest);
9615 dest_log_pinned = false;
9618 ret2 = btrfs_end_transaction(trans);
9619 ret = ret ? ret : ret2;
9620 out_notrans:
9621 if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
9622 up_read(&fs_info->subvol_sem);
9623 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9624 up_read(&fs_info->subvol_sem);
9626 return ret;
9629 static int btrfs_whiteout_for_rename(struct btrfs_trans_handle *trans,
9630 struct btrfs_root *root,
9631 struct inode *dir,
9632 struct dentry *dentry)
9634 int ret;
9635 struct inode *inode;
9636 u64 objectid;
9637 u64 index;
9639 ret = btrfs_find_free_ino(root, &objectid);
9640 if (ret)
9641 return ret;
9643 inode = btrfs_new_inode(trans, root, dir,
9644 dentry->d_name.name,
9645 dentry->d_name.len,
9646 btrfs_ino(BTRFS_I(dir)),
9647 objectid,
9648 S_IFCHR | WHITEOUT_MODE,
9649 &index);
9651 if (IS_ERR(inode)) {
9652 ret = PTR_ERR(inode);
9653 return ret;
9656 inode->i_op = &btrfs_special_inode_operations;
9657 init_special_inode(inode, inode->i_mode,
9658 WHITEOUT_DEV);
9660 ret = btrfs_init_inode_security(trans, inode, dir,
9661 &dentry->d_name);
9662 if (ret)
9663 goto out;
9665 ret = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
9666 BTRFS_I(inode), 0, index);
9667 if (ret)
9668 goto out;
9670 ret = btrfs_update_inode(trans, root, inode);
9671 out:
9672 unlock_new_inode(inode);
9673 if (ret)
9674 inode_dec_link_count(inode);
9675 iput(inode);
9677 return ret;
9680 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9681 struct inode *new_dir, struct dentry *new_dentry,
9682 unsigned int flags)
9684 struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
9685 struct btrfs_trans_handle *trans;
9686 unsigned int trans_num_items;
9687 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9688 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9689 struct inode *new_inode = d_inode(new_dentry);
9690 struct inode *old_inode = d_inode(old_dentry);
9691 u64 index = 0;
9692 u64 root_objectid;
9693 int ret;
9694 u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
9695 bool log_pinned = false;
9697 if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9698 return -EPERM;
9700 /* we only allow rename subvolume link between subvolumes */
9701 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9702 return -EXDEV;
9704 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9705 (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
9706 return -ENOTEMPTY;
9708 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9709 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9710 return -ENOTEMPTY;
9713 /* check for collisions, even if the name isn't there */
9714 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9715 new_dentry->d_name.name,
9716 new_dentry->d_name.len);
9718 if (ret) {
9719 if (ret == -EEXIST) {
9720 /* we shouldn't get
9721 * eexist without a new_inode */
9722 if (WARN_ON(!new_inode)) {
9723 return ret;
9725 } else {
9726 /* maybe -EOVERFLOW */
9727 return ret;
9730 ret = 0;
9733 * we're using rename to replace one file with another. Start IO on it
9734 * now so we don't add too much work to the end of the transaction
9736 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9737 filemap_flush(old_inode->i_mapping);
9739 /* close the racy window with snapshot create/destroy ioctl */
9740 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9741 down_read(&fs_info->subvol_sem);
9743 * We want to reserve the absolute worst case amount of items. So if
9744 * both inodes are subvols and we need to unlink them then that would
9745 * require 4 item modifications, but if they are both normal inodes it
9746 * would require 5 item modifications, so we'll assume they are normal
9747 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9748 * should cover the worst case number of items we'll modify.
9749 * If our rename has the whiteout flag, we need more 5 units for the
9750 * new inode (1 inode item, 1 inode ref, 2 dir items and 1 xattr item
9751 * when selinux is enabled).
9753 trans_num_items = 11;
9754 if (flags & RENAME_WHITEOUT)
9755 trans_num_items += 5;
9756 trans = btrfs_start_transaction(root, trans_num_items);
9757 if (IS_ERR(trans)) {
9758 ret = PTR_ERR(trans);
9759 goto out_notrans;
9762 if (dest != root)
9763 btrfs_record_root_in_trans(trans, dest);
9765 ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
9766 if (ret)
9767 goto out_fail;
9769 BTRFS_I(old_inode)->dir_index = 0ULL;
9770 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9771 /* force full log commit if subvolume involved. */
9772 btrfs_set_log_full_commit(fs_info, trans);
9773 } else {
9774 btrfs_pin_log_trans(root);
9775 log_pinned = true;
9776 ret = btrfs_insert_inode_ref(trans, dest,
9777 new_dentry->d_name.name,
9778 new_dentry->d_name.len,
9779 old_ino,
9780 btrfs_ino(BTRFS_I(new_dir)), index);
9781 if (ret)
9782 goto out_fail;
9785 inode_inc_iversion(old_dir);
9786 inode_inc_iversion(new_dir);
9787 inode_inc_iversion(old_inode);
9788 old_dir->i_ctime = old_dir->i_mtime =
9789 new_dir->i_ctime = new_dir->i_mtime =
9790 old_inode->i_ctime = current_time(old_dir);
9792 if (old_dentry->d_parent != new_dentry->d_parent)
9793 btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
9794 BTRFS_I(old_inode), 1);
9796 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9797 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9798 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9799 old_dentry->d_name.name,
9800 old_dentry->d_name.len);
9801 } else {
9802 ret = __btrfs_unlink_inode(trans, root, BTRFS_I(old_dir),
9803 BTRFS_I(d_inode(old_dentry)),
9804 old_dentry->d_name.name,
9805 old_dentry->d_name.len);
9806 if (!ret)
9807 ret = btrfs_update_inode(trans, root, old_inode);
9809 if (ret) {
9810 btrfs_abort_transaction(trans, ret);
9811 goto out_fail;
9814 if (new_inode) {
9815 inode_inc_iversion(new_inode);
9816 new_inode->i_ctime = current_time(new_inode);
9817 if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
9818 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9819 root_objectid = BTRFS_I(new_inode)->location.objectid;
9820 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9821 root_objectid,
9822 new_dentry->d_name.name,
9823 new_dentry->d_name.len);
9824 BUG_ON(new_inode->i_nlink == 0);
9825 } else {
9826 ret = btrfs_unlink_inode(trans, dest, BTRFS_I(new_dir),
9827 BTRFS_I(d_inode(new_dentry)),
9828 new_dentry->d_name.name,
9829 new_dentry->d_name.len);
9831 if (!ret && new_inode->i_nlink == 0)
9832 ret = btrfs_orphan_add(trans,
9833 BTRFS_I(d_inode(new_dentry)));
9834 if (ret) {
9835 btrfs_abort_transaction(trans, ret);
9836 goto out_fail;
9840 ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
9841 new_dentry->d_name.name,
9842 new_dentry->d_name.len, 0, index);
9843 if (ret) {
9844 btrfs_abort_transaction(trans, ret);
9845 goto out_fail;
9848 if (old_inode->i_nlink == 1)
9849 BTRFS_I(old_inode)->dir_index = index;
9851 if (log_pinned) {
9852 struct dentry *parent = new_dentry->d_parent;
9854 btrfs_log_new_name(trans, BTRFS_I(old_inode), BTRFS_I(old_dir),
9855 parent);
9856 btrfs_end_log_trans(root);
9857 log_pinned = false;
9860 if (flags & RENAME_WHITEOUT) {
9861 ret = btrfs_whiteout_for_rename(trans, root, old_dir,
9862 old_dentry);
9864 if (ret) {
9865 btrfs_abort_transaction(trans, ret);
9866 goto out_fail;
9869 out_fail:
9871 * If we have pinned the log and an error happened, we unpin tasks
9872 * trying to sync the log and force them to fallback to a transaction
9873 * commit if the log currently contains any of the inodes involved in
9874 * this rename operation (to ensure we do not persist a log with an
9875 * inconsistent state for any of these inodes or leading to any
9876 * inconsistencies when replayed). If the transaction was aborted, the
9877 * abortion reason is propagated to userspace when attempting to commit
9878 * the transaction. If the log does not contain any of these inodes, we
9879 * allow the tasks to sync it.
9881 if (ret && log_pinned) {
9882 if (btrfs_inode_in_log(BTRFS_I(old_dir), fs_info->generation) ||
9883 btrfs_inode_in_log(BTRFS_I(new_dir), fs_info->generation) ||
9884 btrfs_inode_in_log(BTRFS_I(old_inode), fs_info->generation) ||
9885 (new_inode &&
9886 btrfs_inode_in_log(BTRFS_I(new_inode), fs_info->generation)))
9887 btrfs_set_log_full_commit(fs_info, trans);
9889 btrfs_end_log_trans(root);
9890 log_pinned = false;
9892 btrfs_end_transaction(trans);
9893 out_notrans:
9894 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9895 up_read(&fs_info->subvol_sem);
9897 return ret;
9900 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9901 struct inode *new_dir, struct dentry *new_dentry,
9902 unsigned int flags)
9904 if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
9905 return -EINVAL;
9907 if (flags & RENAME_EXCHANGE)
9908 return btrfs_rename_exchange(old_dir, old_dentry, new_dir,
9909 new_dentry);
9911 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry, flags);
9914 struct btrfs_delalloc_work {
9915 struct inode *inode;
9916 struct completion completion;
9917 struct list_head list;
9918 struct btrfs_work work;
9921 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9923 struct btrfs_delalloc_work *delalloc_work;
9924 struct inode *inode;
9926 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9927 work);
9928 inode = delalloc_work->inode;
9929 filemap_flush(inode->i_mapping);
9930 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9931 &BTRFS_I(inode)->runtime_flags))
9932 filemap_flush(inode->i_mapping);
9934 iput(inode);
9935 complete(&delalloc_work->completion);
9938 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
9940 struct btrfs_delalloc_work *work;
9942 work = kmalloc(sizeof(*work), GFP_NOFS);
9943 if (!work)
9944 return NULL;
9946 init_completion(&work->completion);
9947 INIT_LIST_HEAD(&work->list);
9948 work->inode = inode;
9949 WARN_ON_ONCE(!inode);
9950 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9951 btrfs_run_delalloc_work, NULL, NULL);
9953 return work;
9957 * some fairly slow code that needs optimization. This walks the list
9958 * of all the inodes with pending delalloc and forces them to disk.
9960 static int start_delalloc_inodes(struct btrfs_root *root, int nr)
9962 struct btrfs_inode *binode;
9963 struct inode *inode;
9964 struct btrfs_delalloc_work *work, *next;
9965 struct list_head works;
9966 struct list_head splice;
9967 int ret = 0;
9969 INIT_LIST_HEAD(&works);
9970 INIT_LIST_HEAD(&splice);
9972 mutex_lock(&root->delalloc_mutex);
9973 spin_lock(&root->delalloc_lock);
9974 list_splice_init(&root->delalloc_inodes, &splice);
9975 while (!list_empty(&splice)) {
9976 binode = list_entry(splice.next, struct btrfs_inode,
9977 delalloc_inodes);
9979 list_move_tail(&binode->delalloc_inodes,
9980 &root->delalloc_inodes);
9981 inode = igrab(&binode->vfs_inode);
9982 if (!inode) {
9983 cond_resched_lock(&root->delalloc_lock);
9984 continue;
9986 spin_unlock(&root->delalloc_lock);
9988 work = btrfs_alloc_delalloc_work(inode);
9989 if (!work) {
9990 iput(inode);
9991 ret = -ENOMEM;
9992 goto out;
9994 list_add_tail(&work->list, &works);
9995 btrfs_queue_work(root->fs_info->flush_workers,
9996 &work->work);
9997 ret++;
9998 if (nr != -1 && ret >= nr)
9999 goto out;
10000 cond_resched();
10001 spin_lock(&root->delalloc_lock);
10003 spin_unlock(&root->delalloc_lock);
10005 out:
10006 list_for_each_entry_safe(work, next, &works, list) {
10007 list_del_init(&work->list);
10008 wait_for_completion(&work->completion);
10009 kfree(work);
10012 if (!list_empty(&splice)) {
10013 spin_lock(&root->delalloc_lock);
10014 list_splice_tail(&splice, &root->delalloc_inodes);
10015 spin_unlock(&root->delalloc_lock);
10017 mutex_unlock(&root->delalloc_mutex);
10018 return ret;
10021 int btrfs_start_delalloc_inodes(struct btrfs_root *root)
10023 struct btrfs_fs_info *fs_info = root->fs_info;
10024 int ret;
10026 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10027 return -EROFS;
10029 ret = start_delalloc_inodes(root, -1);
10030 if (ret > 0)
10031 ret = 0;
10032 return ret;
10035 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int nr)
10037 struct btrfs_root *root;
10038 struct list_head splice;
10039 int ret;
10041 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
10042 return -EROFS;
10044 INIT_LIST_HEAD(&splice);
10046 mutex_lock(&fs_info->delalloc_root_mutex);
10047 spin_lock(&fs_info->delalloc_root_lock);
10048 list_splice_init(&fs_info->delalloc_roots, &splice);
10049 while (!list_empty(&splice) && nr) {
10050 root = list_first_entry(&splice, struct btrfs_root,
10051 delalloc_root);
10052 root = btrfs_grab_fs_root(root);
10053 BUG_ON(!root);
10054 list_move_tail(&root->delalloc_root,
10055 &fs_info->delalloc_roots);
10056 spin_unlock(&fs_info->delalloc_root_lock);
10058 ret = start_delalloc_inodes(root, nr);
10059 btrfs_put_fs_root(root);
10060 if (ret < 0)
10061 goto out;
10063 if (nr != -1) {
10064 nr -= ret;
10065 WARN_ON(nr < 0);
10067 spin_lock(&fs_info->delalloc_root_lock);
10069 spin_unlock(&fs_info->delalloc_root_lock);
10071 ret = 0;
10072 out:
10073 if (!list_empty(&splice)) {
10074 spin_lock(&fs_info->delalloc_root_lock);
10075 list_splice_tail(&splice, &fs_info->delalloc_roots);
10076 spin_unlock(&fs_info->delalloc_root_lock);
10078 mutex_unlock(&fs_info->delalloc_root_mutex);
10079 return ret;
10082 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
10083 const char *symname)
10085 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10086 struct btrfs_trans_handle *trans;
10087 struct btrfs_root *root = BTRFS_I(dir)->root;
10088 struct btrfs_path *path;
10089 struct btrfs_key key;
10090 struct inode *inode = NULL;
10091 int err;
10092 int drop_inode = 0;
10093 u64 objectid;
10094 u64 index = 0;
10095 int name_len;
10096 int datasize;
10097 unsigned long ptr;
10098 struct btrfs_file_extent_item *ei;
10099 struct extent_buffer *leaf;
10101 name_len = strlen(symname);
10102 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
10103 return -ENAMETOOLONG;
10106 * 2 items for inode item and ref
10107 * 2 items for dir items
10108 * 1 item for updating parent inode item
10109 * 1 item for the inline extent item
10110 * 1 item for xattr if selinux is on
10112 trans = btrfs_start_transaction(root, 7);
10113 if (IS_ERR(trans))
10114 return PTR_ERR(trans);
10116 err = btrfs_find_free_ino(root, &objectid);
10117 if (err)
10118 goto out_unlock;
10120 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
10121 dentry->d_name.len, btrfs_ino(BTRFS_I(dir)),
10122 objectid, S_IFLNK|S_IRWXUGO, &index);
10123 if (IS_ERR(inode)) {
10124 err = PTR_ERR(inode);
10125 goto out_unlock;
10129 * If the active LSM wants to access the inode during
10130 * d_instantiate it needs these. Smack checks to see
10131 * if the filesystem supports xattrs by looking at the
10132 * ops vector.
10134 inode->i_fop = &btrfs_file_operations;
10135 inode->i_op = &btrfs_file_inode_operations;
10136 inode->i_mapping->a_ops = &btrfs_aops;
10137 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10139 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
10140 if (err)
10141 goto out_unlock_inode;
10143 path = btrfs_alloc_path();
10144 if (!path) {
10145 err = -ENOMEM;
10146 goto out_unlock_inode;
10148 key.objectid = btrfs_ino(BTRFS_I(inode));
10149 key.offset = 0;
10150 key.type = BTRFS_EXTENT_DATA_KEY;
10151 datasize = btrfs_file_extent_calc_inline_size(name_len);
10152 err = btrfs_insert_empty_item(trans, root, path, &key,
10153 datasize);
10154 if (err) {
10155 btrfs_free_path(path);
10156 goto out_unlock_inode;
10158 leaf = path->nodes[0];
10159 ei = btrfs_item_ptr(leaf, path->slots[0],
10160 struct btrfs_file_extent_item);
10161 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
10162 btrfs_set_file_extent_type(leaf, ei,
10163 BTRFS_FILE_EXTENT_INLINE);
10164 btrfs_set_file_extent_encryption(leaf, ei, 0);
10165 btrfs_set_file_extent_compression(leaf, ei, 0);
10166 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
10167 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
10169 ptr = btrfs_file_extent_inline_start(ei);
10170 write_extent_buffer(leaf, symname, ptr, name_len);
10171 btrfs_mark_buffer_dirty(leaf);
10172 btrfs_free_path(path);
10174 inode->i_op = &btrfs_symlink_inode_operations;
10175 inode_nohighmem(inode);
10176 inode->i_mapping->a_ops = &btrfs_symlink_aops;
10177 inode_set_bytes(inode, name_len);
10178 btrfs_i_size_write(BTRFS_I(inode), name_len);
10179 err = btrfs_update_inode(trans, root, inode);
10181 * Last step, add directory indexes for our symlink inode. This is the
10182 * last step to avoid extra cleanup of these indexes if an error happens
10183 * elsewhere above.
10185 if (!err)
10186 err = btrfs_add_nondir(trans, BTRFS_I(dir), dentry,
10187 BTRFS_I(inode), 0, index);
10188 if (err) {
10189 drop_inode = 1;
10190 goto out_unlock_inode;
10193 d_instantiate_new(dentry, inode);
10195 out_unlock:
10196 btrfs_end_transaction(trans);
10197 if (drop_inode) {
10198 inode_dec_link_count(inode);
10199 iput(inode);
10201 btrfs_btree_balance_dirty(fs_info);
10202 return err;
10204 out_unlock_inode:
10205 drop_inode = 1;
10206 unlock_new_inode(inode);
10207 goto out_unlock;
10210 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
10211 u64 start, u64 num_bytes, u64 min_size,
10212 loff_t actual_len, u64 *alloc_hint,
10213 struct btrfs_trans_handle *trans)
10215 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
10216 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
10217 struct extent_map *em;
10218 struct btrfs_root *root = BTRFS_I(inode)->root;
10219 struct btrfs_key ins;
10220 u64 cur_offset = start;
10221 u64 i_size;
10222 u64 cur_bytes;
10223 u64 last_alloc = (u64)-1;
10224 int ret = 0;
10225 bool own_trans = true;
10226 u64 end = start + num_bytes - 1;
10228 if (trans)
10229 own_trans = false;
10230 while (num_bytes > 0) {
10231 if (own_trans) {
10232 trans = btrfs_start_transaction(root, 3);
10233 if (IS_ERR(trans)) {
10234 ret = PTR_ERR(trans);
10235 break;
10239 cur_bytes = min_t(u64, num_bytes, SZ_256M);
10240 cur_bytes = max(cur_bytes, min_size);
10242 * If we are severely fragmented we could end up with really
10243 * small allocations, so if the allocator is returning small
10244 * chunks lets make its job easier by only searching for those
10245 * sized chunks.
10247 cur_bytes = min(cur_bytes, last_alloc);
10248 ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
10249 min_size, 0, *alloc_hint, &ins, 1, 0);
10250 if (ret) {
10251 if (own_trans)
10252 btrfs_end_transaction(trans);
10253 break;
10255 btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10257 last_alloc = ins.offset;
10258 ret = insert_reserved_file_extent(trans, inode,
10259 cur_offset, ins.objectid,
10260 ins.offset, ins.offset,
10261 ins.offset, 0, 0, 0,
10262 BTRFS_FILE_EXTENT_PREALLOC);
10263 if (ret) {
10264 btrfs_free_reserved_extent(fs_info, ins.objectid,
10265 ins.offset, 0);
10266 btrfs_abort_transaction(trans, ret);
10267 if (own_trans)
10268 btrfs_end_transaction(trans);
10269 break;
10272 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10273 cur_offset + ins.offset -1, 0);
10275 em = alloc_extent_map();
10276 if (!em) {
10277 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
10278 &BTRFS_I(inode)->runtime_flags);
10279 goto next;
10282 em->start = cur_offset;
10283 em->orig_start = cur_offset;
10284 em->len = ins.offset;
10285 em->block_start = ins.objectid;
10286 em->block_len = ins.offset;
10287 em->orig_block_len = ins.offset;
10288 em->ram_bytes = ins.offset;
10289 em->bdev = fs_info->fs_devices->latest_bdev;
10290 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
10291 em->generation = trans->transid;
10293 while (1) {
10294 write_lock(&em_tree->lock);
10295 ret = add_extent_mapping(em_tree, em, 1);
10296 write_unlock(&em_tree->lock);
10297 if (ret != -EEXIST)
10298 break;
10299 btrfs_drop_extent_cache(BTRFS_I(inode), cur_offset,
10300 cur_offset + ins.offset - 1,
10303 free_extent_map(em);
10304 next:
10305 num_bytes -= ins.offset;
10306 cur_offset += ins.offset;
10307 *alloc_hint = ins.objectid + ins.offset;
10309 inode_inc_iversion(inode);
10310 inode->i_ctime = current_time(inode);
10311 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
10312 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
10313 (actual_len > inode->i_size) &&
10314 (cur_offset > inode->i_size)) {
10315 if (cur_offset > actual_len)
10316 i_size = actual_len;
10317 else
10318 i_size = cur_offset;
10319 i_size_write(inode, i_size);
10320 btrfs_ordered_update_i_size(inode, i_size, NULL);
10323 ret = btrfs_update_inode(trans, root, inode);
10325 if (ret) {
10326 btrfs_abort_transaction(trans, ret);
10327 if (own_trans)
10328 btrfs_end_transaction(trans);
10329 break;
10332 if (own_trans)
10333 btrfs_end_transaction(trans);
10335 if (cur_offset < end)
10336 btrfs_free_reserved_data_space(inode, NULL, cur_offset,
10337 end - cur_offset + 1);
10338 return ret;
10341 int btrfs_prealloc_file_range(struct inode *inode, int mode,
10342 u64 start, u64 num_bytes, u64 min_size,
10343 loff_t actual_len, u64 *alloc_hint)
10345 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10346 min_size, actual_len, alloc_hint,
10347 NULL);
10350 int btrfs_prealloc_file_range_trans(struct inode *inode,
10351 struct btrfs_trans_handle *trans, int mode,
10352 u64 start, u64 num_bytes, u64 min_size,
10353 loff_t actual_len, u64 *alloc_hint)
10355 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
10356 min_size, actual_len, alloc_hint, trans);
10359 static int btrfs_set_page_dirty(struct page *page)
10361 return __set_page_dirty_nobuffers(page);
10364 static int btrfs_permission(struct inode *inode, int mask)
10366 struct btrfs_root *root = BTRFS_I(inode)->root;
10367 umode_t mode = inode->i_mode;
10369 if (mask & MAY_WRITE &&
10370 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
10371 if (btrfs_root_readonly(root))
10372 return -EROFS;
10373 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
10374 return -EACCES;
10376 return generic_permission(inode, mask);
10379 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
10381 struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
10382 struct btrfs_trans_handle *trans;
10383 struct btrfs_root *root = BTRFS_I(dir)->root;
10384 struct inode *inode = NULL;
10385 u64 objectid;
10386 u64 index;
10387 int ret = 0;
10390 * 5 units required for adding orphan entry
10392 trans = btrfs_start_transaction(root, 5);
10393 if (IS_ERR(trans))
10394 return PTR_ERR(trans);
10396 ret = btrfs_find_free_ino(root, &objectid);
10397 if (ret)
10398 goto out;
10400 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10401 btrfs_ino(BTRFS_I(dir)), objectid, mode, &index);
10402 if (IS_ERR(inode)) {
10403 ret = PTR_ERR(inode);
10404 inode = NULL;
10405 goto out;
10408 inode->i_fop = &btrfs_file_operations;
10409 inode->i_op = &btrfs_file_inode_operations;
10411 inode->i_mapping->a_ops = &btrfs_aops;
10412 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10414 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10415 if (ret)
10416 goto out_inode;
10418 ret = btrfs_update_inode(trans, root, inode);
10419 if (ret)
10420 goto out_inode;
10421 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10422 if (ret)
10423 goto out_inode;
10426 * We set number of links to 0 in btrfs_new_inode(), and here we set
10427 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10428 * through:
10430 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10432 set_nlink(inode, 1);
10433 unlock_new_inode(inode);
10434 d_tmpfile(dentry, inode);
10435 mark_inode_dirty(inode);
10437 out:
10438 btrfs_end_transaction(trans);
10439 if (ret)
10440 iput(inode);
10441 btrfs_btree_balance_dirty(fs_info);
10442 return ret;
10444 out_inode:
10445 unlock_new_inode(inode);
10446 goto out;
10450 __attribute__((const))
10451 static int btrfs_readpage_io_failed_hook(struct page *page, int failed_mirror)
10453 return -EAGAIN;
10456 static struct btrfs_fs_info *iotree_fs_info(void *private_data)
10458 struct inode *inode = private_data;
10459 return btrfs_sb(inode->i_sb);
10462 static void btrfs_check_extent_io_range(void *private_data, const char *caller,
10463 u64 start, u64 end)
10465 struct inode *inode = private_data;
10466 u64 isize;
10468 isize = i_size_read(inode);
10469 if (end >= PAGE_SIZE && (end % 2) == 0 && end != isize - 1) {
10470 btrfs_debug_rl(BTRFS_I(inode)->root->fs_info,
10471 "%s: ino %llu isize %llu odd range [%llu,%llu]",
10472 caller, btrfs_ino(BTRFS_I(inode)), isize, start, end);
10476 void btrfs_set_range_writeback(void *private_data, u64 start, u64 end)
10478 struct inode *inode = private_data;
10479 unsigned long index = start >> PAGE_SHIFT;
10480 unsigned long end_index = end >> PAGE_SHIFT;
10481 struct page *page;
10483 while (index <= end_index) {
10484 page = find_get_page(inode->i_mapping, index);
10485 ASSERT(page); /* Pages should be in the extent_io_tree */
10486 set_page_writeback(page);
10487 put_page(page);
10488 index++;
10492 static const struct inode_operations btrfs_dir_inode_operations = {
10493 .getattr = btrfs_getattr,
10494 .lookup = btrfs_lookup,
10495 .create = btrfs_create,
10496 .unlink = btrfs_unlink,
10497 .link = btrfs_link,
10498 .mkdir = btrfs_mkdir,
10499 .rmdir = btrfs_rmdir,
10500 .rename = btrfs_rename2,
10501 .symlink = btrfs_symlink,
10502 .setattr = btrfs_setattr,
10503 .mknod = btrfs_mknod,
10504 .listxattr = btrfs_listxattr,
10505 .permission = btrfs_permission,
10506 .get_acl = btrfs_get_acl,
10507 .set_acl = btrfs_set_acl,
10508 .update_time = btrfs_update_time,
10509 .tmpfile = btrfs_tmpfile,
10511 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10512 .lookup = btrfs_lookup,
10513 .permission = btrfs_permission,
10514 .update_time = btrfs_update_time,
10517 static const struct file_operations btrfs_dir_file_operations = {
10518 .llseek = generic_file_llseek,
10519 .read = generic_read_dir,
10520 .iterate_shared = btrfs_real_readdir,
10521 .open = btrfs_opendir,
10522 .unlocked_ioctl = btrfs_ioctl,
10523 #ifdef CONFIG_COMPAT
10524 .compat_ioctl = btrfs_compat_ioctl,
10525 #endif
10526 .release = btrfs_release_file,
10527 .fsync = btrfs_sync_file,
10530 static const struct extent_io_ops btrfs_extent_io_ops = {
10531 /* mandatory callbacks */
10532 .submit_bio_hook = btrfs_submit_bio_hook,
10533 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10534 .merge_bio_hook = btrfs_merge_bio_hook,
10535 .readpage_io_failed_hook = btrfs_readpage_io_failed_hook,
10536 .tree_fs_info = iotree_fs_info,
10537 .set_range_writeback = btrfs_set_range_writeback,
10539 /* optional callbacks */
10540 .fill_delalloc = run_delalloc_range,
10541 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10542 .writepage_start_hook = btrfs_writepage_start_hook,
10543 .set_bit_hook = btrfs_set_bit_hook,
10544 .clear_bit_hook = btrfs_clear_bit_hook,
10545 .merge_extent_hook = btrfs_merge_extent_hook,
10546 .split_extent_hook = btrfs_split_extent_hook,
10547 .check_extent_io_range = btrfs_check_extent_io_range,
10551 * btrfs doesn't support the bmap operation because swapfiles
10552 * use bmap to make a mapping of extents in the file. They assume
10553 * these extents won't change over the life of the file and they
10554 * use the bmap result to do IO directly to the drive.
10556 * the btrfs bmap call would return logical addresses that aren't
10557 * suitable for IO and they also will change frequently as COW
10558 * operations happen. So, swapfile + btrfs == corruption.
10560 * For now we're avoiding this by dropping bmap.
10562 static const struct address_space_operations btrfs_aops = {
10563 .readpage = btrfs_readpage,
10564 .writepage = btrfs_writepage,
10565 .writepages = btrfs_writepages,
10566 .readpages = btrfs_readpages,
10567 .direct_IO = btrfs_direct_IO,
10568 .invalidatepage = btrfs_invalidatepage,
10569 .releasepage = btrfs_releasepage,
10570 .set_page_dirty = btrfs_set_page_dirty,
10571 .error_remove_page = generic_error_remove_page,
10574 static const struct address_space_operations btrfs_symlink_aops = {
10575 .readpage = btrfs_readpage,
10576 .writepage = btrfs_writepage,
10577 .invalidatepage = btrfs_invalidatepage,
10578 .releasepage = btrfs_releasepage,
10581 static const struct inode_operations btrfs_file_inode_operations = {
10582 .getattr = btrfs_getattr,
10583 .setattr = btrfs_setattr,
10584 .listxattr = btrfs_listxattr,
10585 .permission = btrfs_permission,
10586 .fiemap = btrfs_fiemap,
10587 .get_acl = btrfs_get_acl,
10588 .set_acl = btrfs_set_acl,
10589 .update_time = btrfs_update_time,
10591 static const struct inode_operations btrfs_special_inode_operations = {
10592 .getattr = btrfs_getattr,
10593 .setattr = btrfs_setattr,
10594 .permission = btrfs_permission,
10595 .listxattr = btrfs_listxattr,
10596 .get_acl = btrfs_get_acl,
10597 .set_acl = btrfs_set_acl,
10598 .update_time = btrfs_update_time,
10600 static const struct inode_operations btrfs_symlink_inode_operations = {
10601 .get_link = page_get_link,
10602 .getattr = btrfs_getattr,
10603 .setattr = btrfs_setattr,
10604 .permission = btrfs_permission,
10605 .listxattr = btrfs_listxattr,
10606 .update_time = btrfs_update_time,
10609 const struct dentry_operations btrfs_dentry_operations = {
10610 .d_delete = btrfs_dentry_delete,