ocfs2: fix locking for res->tracking and dlm->tracking_list
[linux/fpc-iii.git] / fs / btrfs / inode.c
blobb895be3d43112f9487d6661c0bf4f4a3433f01c9
1 /*
2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/kernel.h>
20 #include <linux/bio.h>
21 #include <linux/buffer_head.h>
22 #include <linux/file.h>
23 #include <linux/fs.h>
24 #include <linux/pagemap.h>
25 #include <linux/highmem.h>
26 #include <linux/time.h>
27 #include <linux/init.h>
28 #include <linux/string.h>
29 #include <linux/backing-dev.h>
30 #include <linux/mpage.h>
31 #include <linux/swap.h>
32 #include <linux/writeback.h>
33 #include <linux/statfs.h>
34 #include <linux/compat.h>
35 #include <linux/bit_spinlock.h>
36 #include <linux/xattr.h>
37 #include <linux/posix_acl.h>
38 #include <linux/falloc.h>
39 #include <linux/slab.h>
40 #include <linux/ratelimit.h>
41 #include <linux/mount.h>
42 #include <linux/btrfs.h>
43 #include <linux/blkdev.h>
44 #include <linux/posix_acl_xattr.h>
45 #include <linux/uio.h>
46 #include "ctree.h"
47 #include "disk-io.h"
48 #include "transaction.h"
49 #include "btrfs_inode.h"
50 #include "print-tree.h"
51 #include "ordered-data.h"
52 #include "xattr.h"
53 #include "tree-log.h"
54 #include "volumes.h"
55 #include "compression.h"
56 #include "locking.h"
57 #include "free-space-cache.h"
58 #include "inode-map.h"
59 #include "backref.h"
60 #include "hash.h"
61 #include "props.h"
62 #include "qgroup.h"
64 struct btrfs_iget_args {
65 struct btrfs_key *location;
66 struct btrfs_root *root;
69 static const struct inode_operations btrfs_dir_inode_operations;
70 static const struct inode_operations btrfs_symlink_inode_operations;
71 static const struct inode_operations btrfs_dir_ro_inode_operations;
72 static const struct inode_operations btrfs_special_inode_operations;
73 static const struct inode_operations btrfs_file_inode_operations;
74 static const struct address_space_operations btrfs_aops;
75 static const struct address_space_operations btrfs_symlink_aops;
76 static const struct file_operations btrfs_dir_file_operations;
77 static struct extent_io_ops btrfs_extent_io_ops;
79 static struct kmem_cache *btrfs_inode_cachep;
80 static struct kmem_cache *btrfs_delalloc_work_cachep;
81 struct kmem_cache *btrfs_trans_handle_cachep;
82 struct kmem_cache *btrfs_transaction_cachep;
83 struct kmem_cache *btrfs_path_cachep;
84 struct kmem_cache *btrfs_free_space_cachep;
86 #define S_SHIFT 12
87 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = {
88 [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE,
89 [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR,
90 [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV,
91 [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV,
92 [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO,
93 [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK,
94 [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK,
97 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
98 static int btrfs_truncate(struct inode *inode);
99 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent);
100 static noinline int cow_file_range(struct inode *inode,
101 struct page *locked_page,
102 u64 start, u64 end, int *page_started,
103 unsigned long *nr_written, int unlock);
104 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
105 u64 len, u64 orig_start,
106 u64 block_start, u64 block_len,
107 u64 orig_block_len, u64 ram_bytes,
108 int type);
110 static int btrfs_dirty_inode(struct inode *inode);
112 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
113 void btrfs_test_inode_set_ops(struct inode *inode)
115 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
117 #endif
119 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
120 struct inode *inode, struct inode *dir,
121 const struct qstr *qstr)
123 int err;
125 err = btrfs_init_acl(trans, inode, dir);
126 if (!err)
127 err = btrfs_xattr_security_init(trans, inode, dir, qstr);
128 return err;
132 * this does all the hard work for inserting an inline extent into
133 * the btree. The caller should have done a btrfs_drop_extents so that
134 * no overlapping inline items exist in the btree
136 static int insert_inline_extent(struct btrfs_trans_handle *trans,
137 struct btrfs_path *path, int extent_inserted,
138 struct btrfs_root *root, struct inode *inode,
139 u64 start, size_t size, size_t compressed_size,
140 int compress_type,
141 struct page **compressed_pages)
143 struct extent_buffer *leaf;
144 struct page *page = NULL;
145 char *kaddr;
146 unsigned long ptr;
147 struct btrfs_file_extent_item *ei;
148 int err = 0;
149 int ret;
150 size_t cur_size = size;
151 unsigned long offset;
153 if (compressed_size && compressed_pages)
154 cur_size = compressed_size;
156 inode_add_bytes(inode, size);
158 if (!extent_inserted) {
159 struct btrfs_key key;
160 size_t datasize;
162 key.objectid = btrfs_ino(inode);
163 key.offset = start;
164 key.type = BTRFS_EXTENT_DATA_KEY;
166 datasize = btrfs_file_extent_calc_inline_size(cur_size);
167 path->leave_spinning = 1;
168 ret = btrfs_insert_empty_item(trans, root, path, &key,
169 datasize);
170 if (ret) {
171 err = ret;
172 goto fail;
175 leaf = path->nodes[0];
176 ei = btrfs_item_ptr(leaf, path->slots[0],
177 struct btrfs_file_extent_item);
178 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
179 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
180 btrfs_set_file_extent_encryption(leaf, ei, 0);
181 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
182 btrfs_set_file_extent_ram_bytes(leaf, ei, size);
183 ptr = btrfs_file_extent_inline_start(ei);
185 if (compress_type != BTRFS_COMPRESS_NONE) {
186 struct page *cpage;
187 int i = 0;
188 while (compressed_size > 0) {
189 cpage = compressed_pages[i];
190 cur_size = min_t(unsigned long, compressed_size,
191 PAGE_CACHE_SIZE);
193 kaddr = kmap_atomic(cpage);
194 write_extent_buffer(leaf, kaddr, ptr, cur_size);
195 kunmap_atomic(kaddr);
197 i++;
198 ptr += cur_size;
199 compressed_size -= cur_size;
201 btrfs_set_file_extent_compression(leaf, ei,
202 compress_type);
203 } else {
204 page = find_get_page(inode->i_mapping,
205 start >> PAGE_CACHE_SHIFT);
206 btrfs_set_file_extent_compression(leaf, ei, 0);
207 kaddr = kmap_atomic(page);
208 offset = start & (PAGE_CACHE_SIZE - 1);
209 write_extent_buffer(leaf, kaddr + offset, ptr, size);
210 kunmap_atomic(kaddr);
211 page_cache_release(page);
213 btrfs_mark_buffer_dirty(leaf);
214 btrfs_release_path(path);
217 * we're an inline extent, so nobody can
218 * extend the file past i_size without locking
219 * a page we already have locked.
221 * We must do any isize and inode updates
222 * before we unlock the pages. Otherwise we
223 * could end up racing with unlink.
225 BTRFS_I(inode)->disk_i_size = inode->i_size;
226 ret = btrfs_update_inode(trans, root, inode);
228 return ret;
229 fail:
230 return err;
235 * conditionally insert an inline extent into the file. This
236 * does the checks required to make sure the data is small enough
237 * to fit as an inline extent.
239 static noinline int cow_file_range_inline(struct btrfs_root *root,
240 struct inode *inode, u64 start,
241 u64 end, size_t compressed_size,
242 int compress_type,
243 struct page **compressed_pages)
245 struct btrfs_trans_handle *trans;
246 u64 isize = i_size_read(inode);
247 u64 actual_end = min(end + 1, isize);
248 u64 inline_len = actual_end - start;
249 u64 aligned_end = ALIGN(end, root->sectorsize);
250 u64 data_len = inline_len;
251 int ret;
252 struct btrfs_path *path;
253 int extent_inserted = 0;
254 u32 extent_item_size;
256 if (compressed_size)
257 data_len = compressed_size;
259 if (start > 0 ||
260 actual_end > PAGE_CACHE_SIZE ||
261 data_len > BTRFS_MAX_INLINE_DATA_SIZE(root) ||
262 (!compressed_size &&
263 (actual_end & (root->sectorsize - 1)) == 0) ||
264 end + 1 < isize ||
265 data_len > root->fs_info->max_inline) {
266 return 1;
269 path = btrfs_alloc_path();
270 if (!path)
271 return -ENOMEM;
273 trans = btrfs_join_transaction(root);
274 if (IS_ERR(trans)) {
275 btrfs_free_path(path);
276 return PTR_ERR(trans);
278 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
280 if (compressed_size && compressed_pages)
281 extent_item_size = btrfs_file_extent_calc_inline_size(
282 compressed_size);
283 else
284 extent_item_size = btrfs_file_extent_calc_inline_size(
285 inline_len);
287 ret = __btrfs_drop_extents(trans, root, inode, path,
288 start, aligned_end, NULL,
289 1, 1, extent_item_size, &extent_inserted);
290 if (ret) {
291 btrfs_abort_transaction(trans, root, ret);
292 goto out;
295 if (isize > actual_end)
296 inline_len = min_t(u64, isize, actual_end);
297 ret = insert_inline_extent(trans, path, extent_inserted,
298 root, inode, start,
299 inline_len, compressed_size,
300 compress_type, compressed_pages);
301 if (ret && ret != -ENOSPC) {
302 btrfs_abort_transaction(trans, root, ret);
303 goto out;
304 } else if (ret == -ENOSPC) {
305 ret = 1;
306 goto out;
309 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
310 btrfs_delalloc_release_metadata(inode, end + 1 - start);
311 btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0);
312 out:
314 * Don't forget to free the reserved space, as for inlined extent
315 * it won't count as data extent, free them directly here.
316 * And at reserve time, it's always aligned to page size, so
317 * just free one page here.
319 btrfs_qgroup_free_data(inode, 0, PAGE_CACHE_SIZE);
320 btrfs_free_path(path);
321 btrfs_end_transaction(trans, root);
322 return ret;
325 struct async_extent {
326 u64 start;
327 u64 ram_size;
328 u64 compressed_size;
329 struct page **pages;
330 unsigned long nr_pages;
331 int compress_type;
332 struct list_head list;
335 struct async_cow {
336 struct inode *inode;
337 struct btrfs_root *root;
338 struct page *locked_page;
339 u64 start;
340 u64 end;
341 struct list_head extents;
342 struct btrfs_work work;
345 static noinline int add_async_extent(struct async_cow *cow,
346 u64 start, u64 ram_size,
347 u64 compressed_size,
348 struct page **pages,
349 unsigned long nr_pages,
350 int compress_type)
352 struct async_extent *async_extent;
354 async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
355 BUG_ON(!async_extent); /* -ENOMEM */
356 async_extent->start = start;
357 async_extent->ram_size = ram_size;
358 async_extent->compressed_size = compressed_size;
359 async_extent->pages = pages;
360 async_extent->nr_pages = nr_pages;
361 async_extent->compress_type = compress_type;
362 list_add_tail(&async_extent->list, &cow->extents);
363 return 0;
366 static inline int inode_need_compress(struct inode *inode)
368 struct btrfs_root *root = BTRFS_I(inode)->root;
370 /* force compress */
371 if (btrfs_test_opt(root, FORCE_COMPRESS))
372 return 1;
373 /* bad compression ratios */
374 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS)
375 return 0;
376 if (btrfs_test_opt(root, COMPRESS) ||
377 BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS ||
378 BTRFS_I(inode)->force_compress)
379 return 1;
380 return 0;
384 * we create compressed extents in two phases. The first
385 * phase compresses a range of pages that have already been
386 * locked (both pages and state bits are locked).
388 * This is done inside an ordered work queue, and the compression
389 * is spread across many cpus. The actual IO submission is step
390 * two, and the ordered work queue takes care of making sure that
391 * happens in the same order things were put onto the queue by
392 * writepages and friends.
394 * If this code finds it can't get good compression, it puts an
395 * entry onto the work queue to write the uncompressed bytes. This
396 * makes sure that both compressed inodes and uncompressed inodes
397 * are written in the same order that the flusher thread sent them
398 * down.
400 static noinline void compress_file_range(struct inode *inode,
401 struct page *locked_page,
402 u64 start, u64 end,
403 struct async_cow *async_cow,
404 int *num_added)
406 struct btrfs_root *root = BTRFS_I(inode)->root;
407 u64 num_bytes;
408 u64 blocksize = root->sectorsize;
409 u64 actual_end;
410 u64 isize = i_size_read(inode);
411 int ret = 0;
412 struct page **pages = NULL;
413 unsigned long nr_pages;
414 unsigned long nr_pages_ret = 0;
415 unsigned long total_compressed = 0;
416 unsigned long total_in = 0;
417 unsigned long max_compressed = 128 * 1024;
418 unsigned long max_uncompressed = 128 * 1024;
419 int i;
420 int will_compress;
421 int compress_type = root->fs_info->compress_type;
422 int redirty = 0;
424 /* if this is a small write inside eof, kick off a defrag */
425 if ((end - start + 1) < 16 * 1024 &&
426 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
427 btrfs_add_inode_defrag(NULL, inode);
429 actual_end = min_t(u64, isize, end + 1);
430 again:
431 will_compress = 0;
432 nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1;
433 nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE);
436 * we don't want to send crud past the end of i_size through
437 * compression, that's just a waste of CPU time. So, if the
438 * end of the file is before the start of our current
439 * requested range of bytes, we bail out to the uncompressed
440 * cleanup code that can deal with all of this.
442 * It isn't really the fastest way to fix things, but this is a
443 * very uncommon corner.
445 if (actual_end <= start)
446 goto cleanup_and_bail_uncompressed;
448 total_compressed = actual_end - start;
451 * skip compression for a small file range(<=blocksize) that
452 * isn't an inline extent, since it dosen't save disk space at all.
454 if (total_compressed <= blocksize &&
455 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
456 goto cleanup_and_bail_uncompressed;
458 /* we want to make sure that amount of ram required to uncompress
459 * an extent is reasonable, so we limit the total size in ram
460 * of a compressed extent to 128k. This is a crucial number
461 * because it also controls how easily we can spread reads across
462 * cpus for decompression.
464 * We also want to make sure the amount of IO required to do
465 * a random read is reasonably small, so we limit the size of
466 * a compressed extent to 128k.
468 total_compressed = min(total_compressed, max_uncompressed);
469 num_bytes = ALIGN(end - start + 1, blocksize);
470 num_bytes = max(blocksize, num_bytes);
471 total_in = 0;
472 ret = 0;
475 * we do compression for mount -o compress and when the
476 * inode has not been flagged as nocompress. This flag can
477 * change at any time if we discover bad compression ratios.
479 if (inode_need_compress(inode)) {
480 WARN_ON(pages);
481 pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
482 if (!pages) {
483 /* just bail out to the uncompressed code */
484 goto cont;
487 if (BTRFS_I(inode)->force_compress)
488 compress_type = BTRFS_I(inode)->force_compress;
491 * we need to call clear_page_dirty_for_io on each
492 * page in the range. Otherwise applications with the file
493 * mmap'd can wander in and change the page contents while
494 * we are compressing them.
496 * If the compression fails for any reason, we set the pages
497 * dirty again later on.
499 extent_range_clear_dirty_for_io(inode, start, end);
500 redirty = 1;
501 ret = btrfs_compress_pages(compress_type,
502 inode->i_mapping, start,
503 total_compressed, pages,
504 nr_pages, &nr_pages_ret,
505 &total_in,
506 &total_compressed,
507 max_compressed);
509 if (!ret) {
510 unsigned long offset = total_compressed &
511 (PAGE_CACHE_SIZE - 1);
512 struct page *page = pages[nr_pages_ret - 1];
513 char *kaddr;
515 /* zero the tail end of the last page, we might be
516 * sending it down to disk
518 if (offset) {
519 kaddr = kmap_atomic(page);
520 memset(kaddr + offset, 0,
521 PAGE_CACHE_SIZE - offset);
522 kunmap_atomic(kaddr);
524 will_compress = 1;
527 cont:
528 if (start == 0) {
529 /* lets try to make an inline extent */
530 if (ret || total_in < (actual_end - start)) {
531 /* we didn't compress the entire range, try
532 * to make an uncompressed inline extent.
534 ret = cow_file_range_inline(root, inode, start, end,
535 0, 0, NULL);
536 } else {
537 /* try making a compressed inline extent */
538 ret = cow_file_range_inline(root, inode, start, end,
539 total_compressed,
540 compress_type, pages);
542 if (ret <= 0) {
543 unsigned long clear_flags = EXTENT_DELALLOC |
544 EXTENT_DEFRAG;
545 unsigned long page_error_op;
547 clear_flags |= (ret < 0) ? EXTENT_DO_ACCOUNTING : 0;
548 page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
551 * inline extent creation worked or returned error,
552 * we don't need to create any more async work items.
553 * Unlock and free up our temp pages.
555 extent_clear_unlock_delalloc(inode, start, end, NULL,
556 clear_flags, PAGE_UNLOCK |
557 PAGE_CLEAR_DIRTY |
558 PAGE_SET_WRITEBACK |
559 page_error_op |
560 PAGE_END_WRITEBACK);
561 goto free_pages_out;
565 if (will_compress) {
567 * we aren't doing an inline extent round the compressed size
568 * up to a block size boundary so the allocator does sane
569 * things
571 total_compressed = ALIGN(total_compressed, blocksize);
574 * one last check to make sure the compression is really a
575 * win, compare the page count read with the blocks on disk
577 total_in = ALIGN(total_in, PAGE_CACHE_SIZE);
578 if (total_compressed >= total_in) {
579 will_compress = 0;
580 } else {
581 num_bytes = total_in;
584 if (!will_compress && pages) {
586 * the compression code ran but failed to make things smaller,
587 * free any pages it allocated and our page pointer array
589 for (i = 0; i < nr_pages_ret; i++) {
590 WARN_ON(pages[i]->mapping);
591 page_cache_release(pages[i]);
593 kfree(pages);
594 pages = NULL;
595 total_compressed = 0;
596 nr_pages_ret = 0;
598 /* flag the file so we don't compress in the future */
599 if (!btrfs_test_opt(root, FORCE_COMPRESS) &&
600 !(BTRFS_I(inode)->force_compress)) {
601 BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
604 if (will_compress) {
605 *num_added += 1;
607 /* the async work queues will take care of doing actual
608 * allocation on disk for these compressed pages,
609 * and will submit them to the elevator.
611 add_async_extent(async_cow, start, num_bytes,
612 total_compressed, pages, nr_pages_ret,
613 compress_type);
615 if (start + num_bytes < end) {
616 start += num_bytes;
617 pages = NULL;
618 cond_resched();
619 goto again;
621 } else {
622 cleanup_and_bail_uncompressed:
624 * No compression, but we still need to write the pages in
625 * the file we've been given so far. redirty the locked
626 * page if it corresponds to our extent and set things up
627 * for the async work queue to run cow_file_range to do
628 * the normal delalloc dance
630 if (page_offset(locked_page) >= start &&
631 page_offset(locked_page) <= end) {
632 __set_page_dirty_nobuffers(locked_page);
633 /* unlocked later on in the async handlers */
635 if (redirty)
636 extent_range_redirty_for_io(inode, start, end);
637 add_async_extent(async_cow, start, end - start + 1,
638 0, NULL, 0, BTRFS_COMPRESS_NONE);
639 *num_added += 1;
642 return;
644 free_pages_out:
645 for (i = 0; i < nr_pages_ret; i++) {
646 WARN_ON(pages[i]->mapping);
647 page_cache_release(pages[i]);
649 kfree(pages);
652 static void free_async_extent_pages(struct async_extent *async_extent)
654 int i;
656 if (!async_extent->pages)
657 return;
659 for (i = 0; i < async_extent->nr_pages; i++) {
660 WARN_ON(async_extent->pages[i]->mapping);
661 page_cache_release(async_extent->pages[i]);
663 kfree(async_extent->pages);
664 async_extent->nr_pages = 0;
665 async_extent->pages = NULL;
669 * phase two of compressed writeback. This is the ordered portion
670 * of the code, which only gets called in the order the work was
671 * queued. We walk all the async extents created by compress_file_range
672 * and send them down to the disk.
674 static noinline void submit_compressed_extents(struct inode *inode,
675 struct async_cow *async_cow)
677 struct async_extent *async_extent;
678 u64 alloc_hint = 0;
679 struct btrfs_key ins;
680 struct extent_map *em;
681 struct btrfs_root *root = BTRFS_I(inode)->root;
682 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
683 struct extent_io_tree *io_tree;
684 int ret = 0;
686 again:
687 while (!list_empty(&async_cow->extents)) {
688 async_extent = list_entry(async_cow->extents.next,
689 struct async_extent, list);
690 list_del(&async_extent->list);
692 io_tree = &BTRFS_I(inode)->io_tree;
694 retry:
695 /* did the compression code fall back to uncompressed IO? */
696 if (!async_extent->pages) {
697 int page_started = 0;
698 unsigned long nr_written = 0;
700 lock_extent(io_tree, async_extent->start,
701 async_extent->start +
702 async_extent->ram_size - 1);
704 /* allocate blocks */
705 ret = cow_file_range(inode, async_cow->locked_page,
706 async_extent->start,
707 async_extent->start +
708 async_extent->ram_size - 1,
709 &page_started, &nr_written, 0);
711 /* JDM XXX */
714 * if page_started, cow_file_range inserted an
715 * inline extent and took care of all the unlocking
716 * and IO for us. Otherwise, we need to submit
717 * all those pages down to the drive.
719 if (!page_started && !ret)
720 extent_write_locked_range(io_tree,
721 inode, async_extent->start,
722 async_extent->start +
723 async_extent->ram_size - 1,
724 btrfs_get_extent,
725 WB_SYNC_ALL);
726 else if (ret)
727 unlock_page(async_cow->locked_page);
728 kfree(async_extent);
729 cond_resched();
730 continue;
733 lock_extent(io_tree, async_extent->start,
734 async_extent->start + async_extent->ram_size - 1);
736 ret = btrfs_reserve_extent(root,
737 async_extent->compressed_size,
738 async_extent->compressed_size,
739 0, alloc_hint, &ins, 1, 1);
740 if (ret) {
741 free_async_extent_pages(async_extent);
743 if (ret == -ENOSPC) {
744 unlock_extent(io_tree, async_extent->start,
745 async_extent->start +
746 async_extent->ram_size - 1);
749 * we need to redirty the pages if we decide to
750 * fallback to uncompressed IO, otherwise we
751 * will not submit these pages down to lower
752 * layers.
754 extent_range_redirty_for_io(inode,
755 async_extent->start,
756 async_extent->start +
757 async_extent->ram_size - 1);
759 goto retry;
761 goto out_free;
764 * here we're doing allocation and writeback of the
765 * compressed pages
767 btrfs_drop_extent_cache(inode, async_extent->start,
768 async_extent->start +
769 async_extent->ram_size - 1, 0);
771 em = alloc_extent_map();
772 if (!em) {
773 ret = -ENOMEM;
774 goto out_free_reserve;
776 em->start = async_extent->start;
777 em->len = async_extent->ram_size;
778 em->orig_start = em->start;
779 em->mod_start = em->start;
780 em->mod_len = em->len;
782 em->block_start = ins.objectid;
783 em->block_len = ins.offset;
784 em->orig_block_len = ins.offset;
785 em->ram_bytes = async_extent->ram_size;
786 em->bdev = root->fs_info->fs_devices->latest_bdev;
787 em->compress_type = async_extent->compress_type;
788 set_bit(EXTENT_FLAG_PINNED, &em->flags);
789 set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
790 em->generation = -1;
792 while (1) {
793 write_lock(&em_tree->lock);
794 ret = add_extent_mapping(em_tree, em, 1);
795 write_unlock(&em_tree->lock);
796 if (ret != -EEXIST) {
797 free_extent_map(em);
798 break;
800 btrfs_drop_extent_cache(inode, async_extent->start,
801 async_extent->start +
802 async_extent->ram_size - 1, 0);
805 if (ret)
806 goto out_free_reserve;
808 ret = btrfs_add_ordered_extent_compress(inode,
809 async_extent->start,
810 ins.objectid,
811 async_extent->ram_size,
812 ins.offset,
813 BTRFS_ORDERED_COMPRESSED,
814 async_extent->compress_type);
815 if (ret) {
816 btrfs_drop_extent_cache(inode, async_extent->start,
817 async_extent->start +
818 async_extent->ram_size - 1, 0);
819 goto out_free_reserve;
823 * clear dirty, set writeback and unlock the pages.
825 extent_clear_unlock_delalloc(inode, async_extent->start,
826 async_extent->start +
827 async_extent->ram_size - 1,
828 NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
829 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
830 PAGE_SET_WRITEBACK);
831 ret = btrfs_submit_compressed_write(inode,
832 async_extent->start,
833 async_extent->ram_size,
834 ins.objectid,
835 ins.offset, async_extent->pages,
836 async_extent->nr_pages);
837 if (ret) {
838 struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
839 struct page *p = async_extent->pages[0];
840 const u64 start = async_extent->start;
841 const u64 end = start + async_extent->ram_size - 1;
843 p->mapping = inode->i_mapping;
844 tree->ops->writepage_end_io_hook(p, start, end,
845 NULL, 0);
846 p->mapping = NULL;
847 extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
848 PAGE_END_WRITEBACK |
849 PAGE_SET_ERROR);
850 free_async_extent_pages(async_extent);
852 alloc_hint = ins.objectid + ins.offset;
853 kfree(async_extent);
854 cond_resched();
856 return;
857 out_free_reserve:
858 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
859 out_free:
860 extent_clear_unlock_delalloc(inode, async_extent->start,
861 async_extent->start +
862 async_extent->ram_size - 1,
863 NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
864 EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
865 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
866 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK |
867 PAGE_SET_ERROR);
868 free_async_extent_pages(async_extent);
869 kfree(async_extent);
870 goto again;
873 static u64 get_extent_allocation_hint(struct inode *inode, u64 start,
874 u64 num_bytes)
876 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
877 struct extent_map *em;
878 u64 alloc_hint = 0;
880 read_lock(&em_tree->lock);
881 em = search_extent_mapping(em_tree, start, num_bytes);
882 if (em) {
884 * if block start isn't an actual block number then find the
885 * first block in this inode and use that as a hint. If that
886 * block is also bogus then just don't worry about it.
888 if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
889 free_extent_map(em);
890 em = search_extent_mapping(em_tree, 0, 0);
891 if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
892 alloc_hint = em->block_start;
893 if (em)
894 free_extent_map(em);
895 } else {
896 alloc_hint = em->block_start;
897 free_extent_map(em);
900 read_unlock(&em_tree->lock);
902 return alloc_hint;
906 * when extent_io.c finds a delayed allocation range in the file,
907 * the call backs end up in this code. The basic idea is to
908 * allocate extents on disk for the range, and create ordered data structs
909 * in ram to track those extents.
911 * locked_page is the page that writepage had locked already. We use
912 * it to make sure we don't do extra locks or unlocks.
914 * *page_started is set to one if we unlock locked_page and do everything
915 * required to start IO on it. It may be clean and already done with
916 * IO when we return.
918 static noinline int cow_file_range(struct inode *inode,
919 struct page *locked_page,
920 u64 start, u64 end, int *page_started,
921 unsigned long *nr_written,
922 int unlock)
924 struct btrfs_root *root = BTRFS_I(inode)->root;
925 u64 alloc_hint = 0;
926 u64 num_bytes;
927 unsigned long ram_size;
928 u64 disk_num_bytes;
929 u64 cur_alloc_size;
930 u64 blocksize = root->sectorsize;
931 struct btrfs_key ins;
932 struct extent_map *em;
933 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
934 int ret = 0;
936 if (btrfs_is_free_space_inode(inode)) {
937 WARN_ON_ONCE(1);
938 ret = -EINVAL;
939 goto out_unlock;
942 num_bytes = ALIGN(end - start + 1, blocksize);
943 num_bytes = max(blocksize, num_bytes);
944 disk_num_bytes = num_bytes;
946 /* if this is a small write inside eof, kick off defrag */
947 if (num_bytes < 64 * 1024 &&
948 (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
949 btrfs_add_inode_defrag(NULL, inode);
951 if (start == 0) {
952 /* lets try to make an inline extent */
953 ret = cow_file_range_inline(root, inode, start, end, 0, 0,
954 NULL);
955 if (ret == 0) {
956 extent_clear_unlock_delalloc(inode, start, end, NULL,
957 EXTENT_LOCKED | EXTENT_DELALLOC |
958 EXTENT_DEFRAG, PAGE_UNLOCK |
959 PAGE_CLEAR_DIRTY | PAGE_SET_WRITEBACK |
960 PAGE_END_WRITEBACK);
962 *nr_written = *nr_written +
963 (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE;
964 *page_started = 1;
965 goto out;
966 } else if (ret < 0) {
967 goto out_unlock;
971 BUG_ON(disk_num_bytes >
972 btrfs_super_total_bytes(root->fs_info->super_copy));
974 alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
975 btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0);
977 while (disk_num_bytes > 0) {
978 unsigned long op;
980 cur_alloc_size = disk_num_bytes;
981 ret = btrfs_reserve_extent(root, cur_alloc_size,
982 root->sectorsize, 0, alloc_hint,
983 &ins, 1, 1);
984 if (ret < 0)
985 goto out_unlock;
987 em = alloc_extent_map();
988 if (!em) {
989 ret = -ENOMEM;
990 goto out_reserve;
992 em->start = start;
993 em->orig_start = em->start;
994 ram_size = ins.offset;
995 em->len = ins.offset;
996 em->mod_start = em->start;
997 em->mod_len = em->len;
999 em->block_start = ins.objectid;
1000 em->block_len = ins.offset;
1001 em->orig_block_len = ins.offset;
1002 em->ram_bytes = ram_size;
1003 em->bdev = root->fs_info->fs_devices->latest_bdev;
1004 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1005 em->generation = -1;
1007 while (1) {
1008 write_lock(&em_tree->lock);
1009 ret = add_extent_mapping(em_tree, em, 1);
1010 write_unlock(&em_tree->lock);
1011 if (ret != -EEXIST) {
1012 free_extent_map(em);
1013 break;
1015 btrfs_drop_extent_cache(inode, start,
1016 start + ram_size - 1, 0);
1018 if (ret)
1019 goto out_reserve;
1021 cur_alloc_size = ins.offset;
1022 ret = btrfs_add_ordered_extent(inode, start, ins.objectid,
1023 ram_size, cur_alloc_size, 0);
1024 if (ret)
1025 goto out_drop_extent_cache;
1027 if (root->root_key.objectid ==
1028 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1029 ret = btrfs_reloc_clone_csums(inode, start,
1030 cur_alloc_size);
1031 if (ret)
1032 goto out_drop_extent_cache;
1035 if (disk_num_bytes < cur_alloc_size)
1036 break;
1038 /* we're not doing compressed IO, don't unlock the first
1039 * page (which the caller expects to stay locked), don't
1040 * clear any dirty bits and don't set any writeback bits
1042 * Do set the Private2 bit so we know this page was properly
1043 * setup for writepage
1045 op = unlock ? PAGE_UNLOCK : 0;
1046 op |= PAGE_SET_PRIVATE2;
1048 extent_clear_unlock_delalloc(inode, start,
1049 start + ram_size - 1, locked_page,
1050 EXTENT_LOCKED | EXTENT_DELALLOC,
1051 op);
1052 disk_num_bytes -= cur_alloc_size;
1053 num_bytes -= cur_alloc_size;
1054 alloc_hint = ins.objectid + ins.offset;
1055 start += cur_alloc_size;
1057 out:
1058 return ret;
1060 out_drop_extent_cache:
1061 btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0);
1062 out_reserve:
1063 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
1064 out_unlock:
1065 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1066 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
1067 EXTENT_DELALLOC | EXTENT_DEFRAG,
1068 PAGE_UNLOCK | PAGE_CLEAR_DIRTY |
1069 PAGE_SET_WRITEBACK | PAGE_END_WRITEBACK);
1070 goto out;
1074 * work queue call back to started compression on a file and pages
1076 static noinline void async_cow_start(struct btrfs_work *work)
1078 struct async_cow *async_cow;
1079 int num_added = 0;
1080 async_cow = container_of(work, struct async_cow, work);
1082 compress_file_range(async_cow->inode, async_cow->locked_page,
1083 async_cow->start, async_cow->end, async_cow,
1084 &num_added);
1085 if (num_added == 0) {
1086 btrfs_add_delayed_iput(async_cow->inode);
1087 async_cow->inode = NULL;
1092 * work queue call back to submit previously compressed pages
1094 static noinline void async_cow_submit(struct btrfs_work *work)
1096 struct async_cow *async_cow;
1097 struct btrfs_root *root;
1098 unsigned long nr_pages;
1100 async_cow = container_of(work, struct async_cow, work);
1102 root = async_cow->root;
1103 nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >>
1104 PAGE_CACHE_SHIFT;
1107 * atomic_sub_return implies a barrier for waitqueue_active
1109 if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) <
1110 5 * 1024 * 1024 &&
1111 waitqueue_active(&root->fs_info->async_submit_wait))
1112 wake_up(&root->fs_info->async_submit_wait);
1114 if (async_cow->inode)
1115 submit_compressed_extents(async_cow->inode, async_cow);
1118 static noinline void async_cow_free(struct btrfs_work *work)
1120 struct async_cow *async_cow;
1121 async_cow = container_of(work, struct async_cow, work);
1122 if (async_cow->inode)
1123 btrfs_add_delayed_iput(async_cow->inode);
1124 kfree(async_cow);
1127 static int cow_file_range_async(struct inode *inode, struct page *locked_page,
1128 u64 start, u64 end, int *page_started,
1129 unsigned long *nr_written)
1131 struct async_cow *async_cow;
1132 struct btrfs_root *root = BTRFS_I(inode)->root;
1133 unsigned long nr_pages;
1134 u64 cur_end;
1135 int limit = 10 * 1024 * 1024;
1137 clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED,
1138 1, 0, NULL, GFP_NOFS);
1139 while (start < end) {
1140 async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS);
1141 BUG_ON(!async_cow); /* -ENOMEM */
1142 async_cow->inode = igrab(inode);
1143 async_cow->root = root;
1144 async_cow->locked_page = locked_page;
1145 async_cow->start = start;
1147 if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS &&
1148 !btrfs_test_opt(root, FORCE_COMPRESS))
1149 cur_end = end;
1150 else
1151 cur_end = min(end, start + 512 * 1024 - 1);
1153 async_cow->end = cur_end;
1154 INIT_LIST_HEAD(&async_cow->extents);
1156 btrfs_init_work(&async_cow->work,
1157 btrfs_delalloc_helper,
1158 async_cow_start, async_cow_submit,
1159 async_cow_free);
1161 nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >>
1162 PAGE_CACHE_SHIFT;
1163 atomic_add(nr_pages, &root->fs_info->async_delalloc_pages);
1165 btrfs_queue_work(root->fs_info->delalloc_workers,
1166 &async_cow->work);
1168 if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) {
1169 wait_event(root->fs_info->async_submit_wait,
1170 (atomic_read(&root->fs_info->async_delalloc_pages) <
1171 limit));
1174 while (atomic_read(&root->fs_info->async_submit_draining) &&
1175 atomic_read(&root->fs_info->async_delalloc_pages)) {
1176 wait_event(root->fs_info->async_submit_wait,
1177 (atomic_read(&root->fs_info->async_delalloc_pages) ==
1178 0));
1181 *nr_written += nr_pages;
1182 start = cur_end + 1;
1184 *page_started = 1;
1185 return 0;
1188 static noinline int csum_exist_in_range(struct btrfs_root *root,
1189 u64 bytenr, u64 num_bytes)
1191 int ret;
1192 struct btrfs_ordered_sum *sums;
1193 LIST_HEAD(list);
1195 ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr,
1196 bytenr + num_bytes - 1, &list, 0);
1197 if (ret == 0 && list_empty(&list))
1198 return 0;
1200 while (!list_empty(&list)) {
1201 sums = list_entry(list.next, struct btrfs_ordered_sum, list);
1202 list_del(&sums->list);
1203 kfree(sums);
1205 if (ret < 0)
1206 return ret;
1207 return 1;
1211 * when nowcow writeback call back. This checks for snapshots or COW copies
1212 * of the extents that exist in the file, and COWs the file as required.
1214 * If no cow copies or snapshots exist, we write directly to the existing
1215 * blocks on disk
1217 static noinline int run_delalloc_nocow(struct inode *inode,
1218 struct page *locked_page,
1219 u64 start, u64 end, int *page_started, int force,
1220 unsigned long *nr_written)
1222 struct btrfs_root *root = BTRFS_I(inode)->root;
1223 struct btrfs_trans_handle *trans;
1224 struct extent_buffer *leaf;
1225 struct btrfs_path *path;
1226 struct btrfs_file_extent_item *fi;
1227 struct btrfs_key found_key;
1228 u64 cow_start;
1229 u64 cur_offset;
1230 u64 extent_end;
1231 u64 extent_offset;
1232 u64 disk_bytenr;
1233 u64 num_bytes;
1234 u64 disk_num_bytes;
1235 u64 ram_bytes;
1236 int extent_type;
1237 int ret, err;
1238 int type;
1239 int nocow;
1240 int check_prev = 1;
1241 bool nolock;
1242 u64 ino = btrfs_ino(inode);
1244 path = btrfs_alloc_path();
1245 if (!path) {
1246 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1247 EXTENT_LOCKED | EXTENT_DELALLOC |
1248 EXTENT_DO_ACCOUNTING |
1249 EXTENT_DEFRAG, PAGE_UNLOCK |
1250 PAGE_CLEAR_DIRTY |
1251 PAGE_SET_WRITEBACK |
1252 PAGE_END_WRITEBACK);
1253 return -ENOMEM;
1256 nolock = btrfs_is_free_space_inode(inode);
1258 if (nolock)
1259 trans = btrfs_join_transaction_nolock(root);
1260 else
1261 trans = btrfs_join_transaction(root);
1263 if (IS_ERR(trans)) {
1264 extent_clear_unlock_delalloc(inode, start, end, locked_page,
1265 EXTENT_LOCKED | EXTENT_DELALLOC |
1266 EXTENT_DO_ACCOUNTING |
1267 EXTENT_DEFRAG, PAGE_UNLOCK |
1268 PAGE_CLEAR_DIRTY |
1269 PAGE_SET_WRITEBACK |
1270 PAGE_END_WRITEBACK);
1271 btrfs_free_path(path);
1272 return PTR_ERR(trans);
1275 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
1277 cow_start = (u64)-1;
1278 cur_offset = start;
1279 while (1) {
1280 ret = btrfs_lookup_file_extent(trans, root, path, ino,
1281 cur_offset, 0);
1282 if (ret < 0)
1283 goto error;
1284 if (ret > 0 && path->slots[0] > 0 && check_prev) {
1285 leaf = path->nodes[0];
1286 btrfs_item_key_to_cpu(leaf, &found_key,
1287 path->slots[0] - 1);
1288 if (found_key.objectid == ino &&
1289 found_key.type == BTRFS_EXTENT_DATA_KEY)
1290 path->slots[0]--;
1292 check_prev = 0;
1293 next_slot:
1294 leaf = path->nodes[0];
1295 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1296 ret = btrfs_next_leaf(root, path);
1297 if (ret < 0) {
1298 if (cow_start != (u64)-1)
1299 cur_offset = cow_start;
1300 goto error;
1302 if (ret > 0)
1303 break;
1304 leaf = path->nodes[0];
1307 nocow = 0;
1308 disk_bytenr = 0;
1309 num_bytes = 0;
1310 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1312 if (found_key.objectid > ino)
1313 break;
1314 if (WARN_ON_ONCE(found_key.objectid < ino) ||
1315 found_key.type < BTRFS_EXTENT_DATA_KEY) {
1316 path->slots[0]++;
1317 goto next_slot;
1319 if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
1320 found_key.offset > end)
1321 break;
1323 if (found_key.offset > cur_offset) {
1324 extent_end = found_key.offset;
1325 extent_type = 0;
1326 goto out_check;
1329 fi = btrfs_item_ptr(leaf, path->slots[0],
1330 struct btrfs_file_extent_item);
1331 extent_type = btrfs_file_extent_type(leaf, fi);
1333 ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1334 if (extent_type == BTRFS_FILE_EXTENT_REG ||
1335 extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1336 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1337 extent_offset = btrfs_file_extent_offset(leaf, fi);
1338 extent_end = found_key.offset +
1339 btrfs_file_extent_num_bytes(leaf, fi);
1340 disk_num_bytes =
1341 btrfs_file_extent_disk_num_bytes(leaf, fi);
1342 if (extent_end <= start) {
1343 path->slots[0]++;
1344 goto next_slot;
1346 if (disk_bytenr == 0)
1347 goto out_check;
1348 if (btrfs_file_extent_compression(leaf, fi) ||
1349 btrfs_file_extent_encryption(leaf, fi) ||
1350 btrfs_file_extent_other_encoding(leaf, fi))
1351 goto out_check;
1352 if (extent_type == BTRFS_FILE_EXTENT_REG && !force)
1353 goto out_check;
1354 if (btrfs_extent_readonly(root, disk_bytenr))
1355 goto out_check;
1356 ret = btrfs_cross_ref_exist(trans, root, ino,
1357 found_key.offset -
1358 extent_offset, disk_bytenr);
1359 if (ret) {
1361 * ret could be -EIO if the above fails to read
1362 * metadata.
1364 if (ret < 0) {
1365 if (cow_start != (u64)-1)
1366 cur_offset = cow_start;
1367 goto error;
1370 WARN_ON_ONCE(nolock);
1371 goto out_check;
1373 disk_bytenr += extent_offset;
1374 disk_bytenr += cur_offset - found_key.offset;
1375 num_bytes = min(end + 1, extent_end) - cur_offset;
1377 * if there are pending snapshots for this root,
1378 * we fall into common COW way.
1380 if (!nolock) {
1381 err = btrfs_start_write_no_snapshoting(root);
1382 if (!err)
1383 goto out_check;
1386 * force cow if csum exists in the range.
1387 * this ensure that csum for a given extent are
1388 * either valid or do not exist.
1390 ret = csum_exist_in_range(root, disk_bytenr, num_bytes);
1391 if (ret) {
1393 * ret could be -EIO if the above fails to read
1394 * metadata.
1396 if (ret < 0) {
1397 if (cow_start != (u64)-1)
1398 cur_offset = cow_start;
1399 goto error;
1401 WARN_ON_ONCE(nolock);
1402 goto out_check;
1404 nocow = 1;
1405 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
1406 extent_end = found_key.offset +
1407 btrfs_file_extent_inline_len(leaf,
1408 path->slots[0], fi);
1409 extent_end = ALIGN(extent_end, root->sectorsize);
1410 } else {
1411 BUG_ON(1);
1413 out_check:
1414 if (extent_end <= start) {
1415 path->slots[0]++;
1416 if (!nolock && nocow)
1417 btrfs_end_write_no_snapshoting(root);
1418 goto next_slot;
1420 if (!nocow) {
1421 if (cow_start == (u64)-1)
1422 cow_start = cur_offset;
1423 cur_offset = extent_end;
1424 if (cur_offset > end)
1425 break;
1426 path->slots[0]++;
1427 goto next_slot;
1430 btrfs_release_path(path);
1431 if (cow_start != (u64)-1) {
1432 ret = cow_file_range(inode, locked_page,
1433 cow_start, found_key.offset - 1,
1434 page_started, nr_written, 1);
1435 if (ret) {
1436 if (!nolock && nocow)
1437 btrfs_end_write_no_snapshoting(root);
1438 goto error;
1440 cow_start = (u64)-1;
1443 if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
1444 struct extent_map *em;
1445 struct extent_map_tree *em_tree;
1446 em_tree = &BTRFS_I(inode)->extent_tree;
1447 em = alloc_extent_map();
1448 BUG_ON(!em); /* -ENOMEM */
1449 em->start = cur_offset;
1450 em->orig_start = found_key.offset - extent_offset;
1451 em->len = num_bytes;
1452 em->block_len = num_bytes;
1453 em->block_start = disk_bytenr;
1454 em->orig_block_len = disk_num_bytes;
1455 em->ram_bytes = ram_bytes;
1456 em->bdev = root->fs_info->fs_devices->latest_bdev;
1457 em->mod_start = em->start;
1458 em->mod_len = em->len;
1459 set_bit(EXTENT_FLAG_PINNED, &em->flags);
1460 set_bit(EXTENT_FLAG_FILLING, &em->flags);
1461 em->generation = -1;
1462 while (1) {
1463 write_lock(&em_tree->lock);
1464 ret = add_extent_mapping(em_tree, em, 1);
1465 write_unlock(&em_tree->lock);
1466 if (ret != -EEXIST) {
1467 free_extent_map(em);
1468 break;
1470 btrfs_drop_extent_cache(inode, em->start,
1471 em->start + em->len - 1, 0);
1473 type = BTRFS_ORDERED_PREALLOC;
1474 } else {
1475 type = BTRFS_ORDERED_NOCOW;
1478 ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr,
1479 num_bytes, num_bytes, type);
1480 BUG_ON(ret); /* -ENOMEM */
1482 if (root->root_key.objectid ==
1483 BTRFS_DATA_RELOC_TREE_OBJECTID) {
1484 ret = btrfs_reloc_clone_csums(inode, cur_offset,
1485 num_bytes);
1486 if (ret) {
1487 if (!nolock && nocow)
1488 btrfs_end_write_no_snapshoting(root);
1489 goto error;
1493 extent_clear_unlock_delalloc(inode, cur_offset,
1494 cur_offset + num_bytes - 1,
1495 locked_page, EXTENT_LOCKED |
1496 EXTENT_DELALLOC, PAGE_UNLOCK |
1497 PAGE_SET_PRIVATE2);
1498 if (!nolock && nocow)
1499 btrfs_end_write_no_snapshoting(root);
1500 cur_offset = extent_end;
1501 if (cur_offset > end)
1502 break;
1504 btrfs_release_path(path);
1506 if (cur_offset <= end && cow_start == (u64)-1) {
1507 cow_start = cur_offset;
1508 cur_offset = end;
1511 if (cow_start != (u64)-1) {
1512 ret = cow_file_range(inode, locked_page, cow_start, end,
1513 page_started, nr_written, 1);
1514 if (ret)
1515 goto error;
1518 error:
1519 err = btrfs_end_transaction(trans, root);
1520 if (!ret)
1521 ret = err;
1523 if (ret && cur_offset < end)
1524 extent_clear_unlock_delalloc(inode, cur_offset, end,
1525 locked_page, EXTENT_LOCKED |
1526 EXTENT_DELALLOC | EXTENT_DEFRAG |
1527 EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
1528 PAGE_CLEAR_DIRTY |
1529 PAGE_SET_WRITEBACK |
1530 PAGE_END_WRITEBACK);
1531 btrfs_free_path(path);
1532 return ret;
1535 static inline int need_force_cow(struct inode *inode, u64 start, u64 end)
1538 if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
1539 !(BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC))
1540 return 0;
1543 * @defrag_bytes is a hint value, no spinlock held here,
1544 * if is not zero, it means the file is defragging.
1545 * Force cow if given extent needs to be defragged.
1547 if (BTRFS_I(inode)->defrag_bytes &&
1548 test_range_bit(&BTRFS_I(inode)->io_tree, start, end,
1549 EXTENT_DEFRAG, 0, NULL))
1550 return 1;
1552 return 0;
1556 * extent_io.c call back to do delayed allocation processing
1558 static int run_delalloc_range(struct inode *inode, struct page *locked_page,
1559 u64 start, u64 end, int *page_started,
1560 unsigned long *nr_written)
1562 int ret;
1563 int force_cow = need_force_cow(inode, start, end);
1565 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW && !force_cow) {
1566 ret = run_delalloc_nocow(inode, locked_page, start, end,
1567 page_started, 1, nr_written);
1568 } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC && !force_cow) {
1569 ret = run_delalloc_nocow(inode, locked_page, start, end,
1570 page_started, 0, nr_written);
1571 } else if (!inode_need_compress(inode)) {
1572 ret = cow_file_range(inode, locked_page, start, end,
1573 page_started, nr_written, 1);
1574 } else {
1575 set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
1576 &BTRFS_I(inode)->runtime_flags);
1577 ret = cow_file_range_async(inode, locked_page, start, end,
1578 page_started, nr_written);
1580 return ret;
1583 static void btrfs_split_extent_hook(struct inode *inode,
1584 struct extent_state *orig, u64 split)
1586 u64 size;
1588 /* not delalloc, ignore it */
1589 if (!(orig->state & EXTENT_DELALLOC))
1590 return;
1592 size = orig->end - orig->start + 1;
1593 if (size > BTRFS_MAX_EXTENT_SIZE) {
1594 u64 num_extents;
1595 u64 new_size;
1598 * See the explanation in btrfs_merge_extent_hook, the same
1599 * applies here, just in reverse.
1601 new_size = orig->end - split + 1;
1602 num_extents = div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1603 BTRFS_MAX_EXTENT_SIZE);
1604 new_size = split - orig->start;
1605 num_extents += div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1606 BTRFS_MAX_EXTENT_SIZE);
1607 if (div64_u64(size + BTRFS_MAX_EXTENT_SIZE - 1,
1608 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1609 return;
1612 spin_lock(&BTRFS_I(inode)->lock);
1613 BTRFS_I(inode)->outstanding_extents++;
1614 spin_unlock(&BTRFS_I(inode)->lock);
1618 * extent_io.c merge_extent_hook, used to track merged delayed allocation
1619 * extents so we can keep track of new extents that are just merged onto old
1620 * extents, such as when we are doing sequential writes, so we can properly
1621 * account for the metadata space we'll need.
1623 static void btrfs_merge_extent_hook(struct inode *inode,
1624 struct extent_state *new,
1625 struct extent_state *other)
1627 u64 new_size, old_size;
1628 u64 num_extents;
1630 /* not delalloc, ignore it */
1631 if (!(other->state & EXTENT_DELALLOC))
1632 return;
1634 if (new->start > other->start)
1635 new_size = new->end - other->start + 1;
1636 else
1637 new_size = other->end - new->start + 1;
1639 /* we're not bigger than the max, unreserve the space and go */
1640 if (new_size <= BTRFS_MAX_EXTENT_SIZE) {
1641 spin_lock(&BTRFS_I(inode)->lock);
1642 BTRFS_I(inode)->outstanding_extents--;
1643 spin_unlock(&BTRFS_I(inode)->lock);
1644 return;
1648 * We have to add up either side to figure out how many extents were
1649 * accounted for before we merged into one big extent. If the number of
1650 * extents we accounted for is <= the amount we need for the new range
1651 * then we can return, otherwise drop. Think of it like this
1653 * [ 4k][MAX_SIZE]
1655 * So we've grown the extent by a MAX_SIZE extent, this would mean we
1656 * need 2 outstanding extents, on one side we have 1 and the other side
1657 * we have 1 so they are == and we can return. But in this case
1659 * [MAX_SIZE+4k][MAX_SIZE+4k]
1661 * Each range on their own accounts for 2 extents, but merged together
1662 * they are only 3 extents worth of accounting, so we need to drop in
1663 * this case.
1665 old_size = other->end - other->start + 1;
1666 num_extents = div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1667 BTRFS_MAX_EXTENT_SIZE);
1668 old_size = new->end - new->start + 1;
1669 num_extents += div64_u64(old_size + BTRFS_MAX_EXTENT_SIZE - 1,
1670 BTRFS_MAX_EXTENT_SIZE);
1672 if (div64_u64(new_size + BTRFS_MAX_EXTENT_SIZE - 1,
1673 BTRFS_MAX_EXTENT_SIZE) >= num_extents)
1674 return;
1676 spin_lock(&BTRFS_I(inode)->lock);
1677 BTRFS_I(inode)->outstanding_extents--;
1678 spin_unlock(&BTRFS_I(inode)->lock);
1681 static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
1682 struct inode *inode)
1684 spin_lock(&root->delalloc_lock);
1685 if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1686 list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
1687 &root->delalloc_inodes);
1688 set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1689 &BTRFS_I(inode)->runtime_flags);
1690 root->nr_delalloc_inodes++;
1691 if (root->nr_delalloc_inodes == 1) {
1692 spin_lock(&root->fs_info->delalloc_root_lock);
1693 BUG_ON(!list_empty(&root->delalloc_root));
1694 list_add_tail(&root->delalloc_root,
1695 &root->fs_info->delalloc_roots);
1696 spin_unlock(&root->fs_info->delalloc_root_lock);
1699 spin_unlock(&root->delalloc_lock);
1702 static void btrfs_del_delalloc_inode(struct btrfs_root *root,
1703 struct inode *inode)
1705 spin_lock(&root->delalloc_lock);
1706 if (!list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
1707 list_del_init(&BTRFS_I(inode)->delalloc_inodes);
1708 clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1709 &BTRFS_I(inode)->runtime_flags);
1710 root->nr_delalloc_inodes--;
1711 if (!root->nr_delalloc_inodes) {
1712 spin_lock(&root->fs_info->delalloc_root_lock);
1713 BUG_ON(list_empty(&root->delalloc_root));
1714 list_del_init(&root->delalloc_root);
1715 spin_unlock(&root->fs_info->delalloc_root_lock);
1718 spin_unlock(&root->delalloc_lock);
1722 * extent_io.c set_bit_hook, used to track delayed allocation
1723 * bytes in this file, and to maintain the list of inodes that
1724 * have pending delalloc work to be done.
1726 static void btrfs_set_bit_hook(struct inode *inode,
1727 struct extent_state *state, unsigned *bits)
1730 if ((*bits & EXTENT_DEFRAG) && !(*bits & EXTENT_DELALLOC))
1731 WARN_ON(1);
1733 * set_bit and clear bit hooks normally require _irqsave/restore
1734 * but in this case, we are only testing for the DELALLOC
1735 * bit, which is only set or cleared with irqs on
1737 if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1738 struct btrfs_root *root = BTRFS_I(inode)->root;
1739 u64 len = state->end + 1 - state->start;
1740 bool do_list = !btrfs_is_free_space_inode(inode);
1742 if (*bits & EXTENT_FIRST_DELALLOC) {
1743 *bits &= ~EXTENT_FIRST_DELALLOC;
1744 } else {
1745 spin_lock(&BTRFS_I(inode)->lock);
1746 BTRFS_I(inode)->outstanding_extents++;
1747 spin_unlock(&BTRFS_I(inode)->lock);
1750 /* For sanity tests */
1751 if (btrfs_test_is_dummy_root(root))
1752 return;
1754 __percpu_counter_add(&root->fs_info->delalloc_bytes, len,
1755 root->fs_info->delalloc_batch);
1756 spin_lock(&BTRFS_I(inode)->lock);
1757 BTRFS_I(inode)->delalloc_bytes += len;
1758 if (*bits & EXTENT_DEFRAG)
1759 BTRFS_I(inode)->defrag_bytes += len;
1760 if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1761 &BTRFS_I(inode)->runtime_flags))
1762 btrfs_add_delalloc_inodes(root, inode);
1763 spin_unlock(&BTRFS_I(inode)->lock);
1768 * extent_io.c clear_bit_hook, see set_bit_hook for why
1770 static void btrfs_clear_bit_hook(struct inode *inode,
1771 struct extent_state *state,
1772 unsigned *bits)
1774 u64 len = state->end + 1 - state->start;
1775 u64 num_extents = div64_u64(len + BTRFS_MAX_EXTENT_SIZE -1,
1776 BTRFS_MAX_EXTENT_SIZE);
1778 spin_lock(&BTRFS_I(inode)->lock);
1779 if ((state->state & EXTENT_DEFRAG) && (*bits & EXTENT_DEFRAG))
1780 BTRFS_I(inode)->defrag_bytes -= len;
1781 spin_unlock(&BTRFS_I(inode)->lock);
1784 * set_bit and clear bit hooks normally require _irqsave/restore
1785 * but in this case, we are only testing for the DELALLOC
1786 * bit, which is only set or cleared with irqs on
1788 if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) {
1789 struct btrfs_root *root = BTRFS_I(inode)->root;
1790 bool do_list = !btrfs_is_free_space_inode(inode);
1792 if (*bits & EXTENT_FIRST_DELALLOC) {
1793 *bits &= ~EXTENT_FIRST_DELALLOC;
1794 } else if (!(*bits & EXTENT_DO_ACCOUNTING)) {
1795 spin_lock(&BTRFS_I(inode)->lock);
1796 BTRFS_I(inode)->outstanding_extents -= num_extents;
1797 spin_unlock(&BTRFS_I(inode)->lock);
1801 * We don't reserve metadata space for space cache inodes so we
1802 * don't need to call dellalloc_release_metadata if there is an
1803 * error.
1805 if (*bits & EXTENT_DO_ACCOUNTING &&
1806 root != root->fs_info->tree_root)
1807 btrfs_delalloc_release_metadata(inode, len);
1809 /* For sanity tests. */
1810 if (btrfs_test_is_dummy_root(root))
1811 return;
1813 if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
1814 && do_list && !(state->state & EXTENT_NORESERVE))
1815 btrfs_free_reserved_data_space_noquota(inode,
1816 state->start, len);
1818 __percpu_counter_add(&root->fs_info->delalloc_bytes, -len,
1819 root->fs_info->delalloc_batch);
1820 spin_lock(&BTRFS_I(inode)->lock);
1821 BTRFS_I(inode)->delalloc_bytes -= len;
1822 if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 &&
1823 test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
1824 &BTRFS_I(inode)->runtime_flags))
1825 btrfs_del_delalloc_inode(root, inode);
1826 spin_unlock(&BTRFS_I(inode)->lock);
1831 * extent_io.c merge_bio_hook, this must check the chunk tree to make sure
1832 * we don't create bios that span stripes or chunks
1834 int btrfs_merge_bio_hook(int rw, struct page *page, unsigned long offset,
1835 size_t size, struct bio *bio,
1836 unsigned long bio_flags)
1838 struct btrfs_root *root = BTRFS_I(page->mapping->host)->root;
1839 u64 logical = (u64)bio->bi_iter.bi_sector << 9;
1840 u64 length = 0;
1841 u64 map_length;
1842 int ret;
1844 if (bio_flags & EXTENT_BIO_COMPRESSED)
1845 return 0;
1847 length = bio->bi_iter.bi_size;
1848 map_length = length;
1849 ret = btrfs_map_block(root->fs_info, rw, logical,
1850 &map_length, NULL, 0);
1851 /* Will always return 0 with map_multi == NULL */
1852 BUG_ON(ret < 0);
1853 if (map_length < length + size)
1854 return 1;
1855 return 0;
1859 * in order to insert checksums into the metadata in large chunks,
1860 * we wait until bio submission time. All the pages in the bio are
1861 * checksummed and sums are attached onto the ordered extent record.
1863 * At IO completion time the cums attached on the ordered extent record
1864 * are inserted into the btree
1866 static int __btrfs_submit_bio_start(struct inode *inode, int rw,
1867 struct bio *bio, int mirror_num,
1868 unsigned long bio_flags,
1869 u64 bio_offset)
1871 struct btrfs_root *root = BTRFS_I(inode)->root;
1872 int ret = 0;
1874 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1875 BUG_ON(ret); /* -ENOMEM */
1876 return 0;
1880 * in order to insert checksums into the metadata in large chunks,
1881 * we wait until bio submission time. All the pages in the bio are
1882 * checksummed and sums are attached onto the ordered extent record.
1884 * At IO completion time the cums attached on the ordered extent record
1885 * are inserted into the btree
1887 static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio,
1888 int mirror_num, unsigned long bio_flags,
1889 u64 bio_offset)
1891 struct btrfs_root *root = BTRFS_I(inode)->root;
1892 int ret;
1894 ret = btrfs_map_bio(root, rw, bio, mirror_num, 1);
1895 if (ret) {
1896 bio->bi_error = ret;
1897 bio_endio(bio);
1899 return ret;
1903 * extent_io.c submission hook. This does the right thing for csum calculation
1904 * on write, or reading the csums from the tree before a read
1906 static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio,
1907 int mirror_num, unsigned long bio_flags,
1908 u64 bio_offset)
1910 struct btrfs_root *root = BTRFS_I(inode)->root;
1911 enum btrfs_wq_endio_type metadata = BTRFS_WQ_ENDIO_DATA;
1912 int ret = 0;
1913 int skip_sum;
1914 int async = !atomic_read(&BTRFS_I(inode)->sync_writers);
1916 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
1918 if (btrfs_is_free_space_inode(inode))
1919 metadata = BTRFS_WQ_ENDIO_FREE_SPACE;
1921 if (!(rw & REQ_WRITE)) {
1922 ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata);
1923 if (ret)
1924 goto out;
1926 if (bio_flags & EXTENT_BIO_COMPRESSED) {
1927 ret = btrfs_submit_compressed_read(inode, bio,
1928 mirror_num,
1929 bio_flags);
1930 goto out;
1931 } else if (!skip_sum) {
1932 ret = btrfs_lookup_bio_sums(root, inode, bio, NULL);
1933 if (ret)
1934 goto out;
1936 goto mapit;
1937 } else if (async && !skip_sum) {
1938 /* csum items have already been cloned */
1939 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
1940 goto mapit;
1941 /* we're doing a write, do the async checksumming */
1942 ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info,
1943 inode, rw, bio, mirror_num,
1944 bio_flags, bio_offset,
1945 __btrfs_submit_bio_start,
1946 __btrfs_submit_bio_done);
1947 goto out;
1948 } else if (!skip_sum) {
1949 ret = btrfs_csum_one_bio(root, inode, bio, 0, 0);
1950 if (ret)
1951 goto out;
1954 mapit:
1955 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
1957 out:
1958 if (ret < 0) {
1959 bio->bi_error = ret;
1960 bio_endio(bio);
1962 return ret;
1966 * given a list of ordered sums record them in the inode. This happens
1967 * at IO completion time based on sums calculated at bio submission time.
1969 static noinline int add_pending_csums(struct btrfs_trans_handle *trans,
1970 struct inode *inode, u64 file_offset,
1971 struct list_head *list)
1973 struct btrfs_ordered_sum *sum;
1975 list_for_each_entry(sum, list, list) {
1976 trans->adding_csums = 1;
1977 btrfs_csum_file_blocks(trans,
1978 BTRFS_I(inode)->root->fs_info->csum_root, sum);
1979 trans->adding_csums = 0;
1981 return 0;
1984 int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end,
1985 struct extent_state **cached_state)
1987 WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0);
1988 return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end,
1989 cached_state, GFP_NOFS);
1992 /* see btrfs_writepage_start_hook for details on why this is required */
1993 struct btrfs_writepage_fixup {
1994 struct page *page;
1995 struct btrfs_work work;
1998 static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
2000 struct btrfs_writepage_fixup *fixup;
2001 struct btrfs_ordered_extent *ordered;
2002 struct extent_state *cached_state = NULL;
2003 struct page *page;
2004 struct inode *inode;
2005 u64 page_start;
2006 u64 page_end;
2007 int ret;
2009 fixup = container_of(work, struct btrfs_writepage_fixup, work);
2010 page = fixup->page;
2011 again:
2012 lock_page(page);
2013 if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
2014 ClearPageChecked(page);
2015 goto out_page;
2018 inode = page->mapping->host;
2019 page_start = page_offset(page);
2020 page_end = page_offset(page) + PAGE_CACHE_SIZE - 1;
2022 lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0,
2023 &cached_state);
2025 /* already ordered? We're done */
2026 if (PagePrivate2(page))
2027 goto out;
2029 ordered = btrfs_lookup_ordered_extent(inode, page_start);
2030 if (ordered) {
2031 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start,
2032 page_end, &cached_state, GFP_NOFS);
2033 unlock_page(page);
2034 btrfs_start_ordered_extent(inode, ordered, 1);
2035 btrfs_put_ordered_extent(ordered);
2036 goto again;
2039 ret = btrfs_delalloc_reserve_space(inode, page_start,
2040 PAGE_CACHE_SIZE);
2041 if (ret) {
2042 mapping_set_error(page->mapping, ret);
2043 end_extent_writepage(page, ret, page_start, page_end);
2044 ClearPageChecked(page);
2045 goto out;
2048 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
2049 &cached_state);
2050 if (ret) {
2051 mapping_set_error(page->mapping, ret);
2052 end_extent_writepage(page, ret, page_start, page_end);
2053 ClearPageChecked(page);
2054 goto out;
2057 ClearPageChecked(page);
2058 set_page_dirty(page);
2059 out:
2060 unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end,
2061 &cached_state, GFP_NOFS);
2062 out_page:
2063 unlock_page(page);
2064 page_cache_release(page);
2065 kfree(fixup);
2069 * There are a few paths in the higher layers of the kernel that directly
2070 * set the page dirty bit without asking the filesystem if it is a
2071 * good idea. This causes problems because we want to make sure COW
2072 * properly happens and the data=ordered rules are followed.
2074 * In our case any range that doesn't have the ORDERED bit set
2075 * hasn't been properly setup for IO. We kick off an async process
2076 * to fix it up. The async helper will wait for ordered extents, set
2077 * the delalloc bit and make it safe to write the page.
2079 static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end)
2081 struct inode *inode = page->mapping->host;
2082 struct btrfs_writepage_fixup *fixup;
2083 struct btrfs_root *root = BTRFS_I(inode)->root;
2085 /* this page is properly in the ordered list */
2086 if (TestClearPagePrivate2(page))
2087 return 0;
2089 if (PageChecked(page))
2090 return -EAGAIN;
2092 fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
2093 if (!fixup)
2094 return -EAGAIN;
2096 SetPageChecked(page);
2097 page_cache_get(page);
2098 btrfs_init_work(&fixup->work, btrfs_fixup_helper,
2099 btrfs_writepage_fixup_worker, NULL, NULL);
2100 fixup->page = page;
2101 btrfs_queue_work(root->fs_info->fixup_workers, &fixup->work);
2102 return -EBUSY;
2105 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2106 struct inode *inode, u64 file_pos,
2107 u64 disk_bytenr, u64 disk_num_bytes,
2108 u64 num_bytes, u64 ram_bytes,
2109 u8 compression, u8 encryption,
2110 u16 other_encoding, int extent_type)
2112 struct btrfs_root *root = BTRFS_I(inode)->root;
2113 struct btrfs_file_extent_item *fi;
2114 struct btrfs_path *path;
2115 struct extent_buffer *leaf;
2116 struct btrfs_key ins;
2117 int extent_inserted = 0;
2118 int ret;
2120 path = btrfs_alloc_path();
2121 if (!path)
2122 return -ENOMEM;
2125 * we may be replacing one extent in the tree with another.
2126 * The new extent is pinned in the extent map, and we don't want
2127 * to drop it from the cache until it is completely in the btree.
2129 * So, tell btrfs_drop_extents to leave this extent in the cache.
2130 * the caller is expected to unpin it and allow it to be merged
2131 * with the others.
2133 ret = __btrfs_drop_extents(trans, root, inode, path, file_pos,
2134 file_pos + num_bytes, NULL, 0,
2135 1, sizeof(*fi), &extent_inserted);
2136 if (ret)
2137 goto out;
2139 if (!extent_inserted) {
2140 ins.objectid = btrfs_ino(inode);
2141 ins.offset = file_pos;
2142 ins.type = BTRFS_EXTENT_DATA_KEY;
2144 path->leave_spinning = 1;
2145 ret = btrfs_insert_empty_item(trans, root, path, &ins,
2146 sizeof(*fi));
2147 if (ret)
2148 goto out;
2150 leaf = path->nodes[0];
2151 fi = btrfs_item_ptr(leaf, path->slots[0],
2152 struct btrfs_file_extent_item);
2153 btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2154 btrfs_set_file_extent_type(leaf, fi, extent_type);
2155 btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr);
2156 btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes);
2157 btrfs_set_file_extent_offset(leaf, fi, 0);
2158 btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2159 btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes);
2160 btrfs_set_file_extent_compression(leaf, fi, compression);
2161 btrfs_set_file_extent_encryption(leaf, fi, encryption);
2162 btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding);
2164 btrfs_mark_buffer_dirty(leaf);
2165 btrfs_release_path(path);
2167 inode_add_bytes(inode, num_bytes);
2169 ins.objectid = disk_bytenr;
2170 ins.offset = disk_num_bytes;
2171 ins.type = BTRFS_EXTENT_ITEM_KEY;
2172 ret = btrfs_alloc_reserved_file_extent(trans, root,
2173 root->root_key.objectid,
2174 btrfs_ino(inode), file_pos,
2175 ram_bytes, &ins);
2177 * Release the reserved range from inode dirty range map, as it is
2178 * already moved into delayed_ref_head
2180 btrfs_qgroup_release_data(inode, file_pos, ram_bytes);
2181 out:
2182 btrfs_free_path(path);
2184 return ret;
2187 /* snapshot-aware defrag */
2188 struct sa_defrag_extent_backref {
2189 struct rb_node node;
2190 struct old_sa_defrag_extent *old;
2191 u64 root_id;
2192 u64 inum;
2193 u64 file_pos;
2194 u64 extent_offset;
2195 u64 num_bytes;
2196 u64 generation;
2199 struct old_sa_defrag_extent {
2200 struct list_head list;
2201 struct new_sa_defrag_extent *new;
2203 u64 extent_offset;
2204 u64 bytenr;
2205 u64 offset;
2206 u64 len;
2207 int count;
2210 struct new_sa_defrag_extent {
2211 struct rb_root root;
2212 struct list_head head;
2213 struct btrfs_path *path;
2214 struct inode *inode;
2215 u64 file_pos;
2216 u64 len;
2217 u64 bytenr;
2218 u64 disk_len;
2219 u8 compress_type;
2222 static int backref_comp(struct sa_defrag_extent_backref *b1,
2223 struct sa_defrag_extent_backref *b2)
2225 if (b1->root_id < b2->root_id)
2226 return -1;
2227 else if (b1->root_id > b2->root_id)
2228 return 1;
2230 if (b1->inum < b2->inum)
2231 return -1;
2232 else if (b1->inum > b2->inum)
2233 return 1;
2235 if (b1->file_pos < b2->file_pos)
2236 return -1;
2237 else if (b1->file_pos > b2->file_pos)
2238 return 1;
2241 * [------------------------------] ===> (a range of space)
2242 * |<--->| |<---->| =============> (fs/file tree A)
2243 * |<---------------------------->| ===> (fs/file tree B)
2245 * A range of space can refer to two file extents in one tree while
2246 * refer to only one file extent in another tree.
2248 * So we may process a disk offset more than one time(two extents in A)
2249 * and locate at the same extent(one extent in B), then insert two same
2250 * backrefs(both refer to the extent in B).
2252 return 0;
2255 static void backref_insert(struct rb_root *root,
2256 struct sa_defrag_extent_backref *backref)
2258 struct rb_node **p = &root->rb_node;
2259 struct rb_node *parent = NULL;
2260 struct sa_defrag_extent_backref *entry;
2261 int ret;
2263 while (*p) {
2264 parent = *p;
2265 entry = rb_entry(parent, struct sa_defrag_extent_backref, node);
2267 ret = backref_comp(backref, entry);
2268 if (ret < 0)
2269 p = &(*p)->rb_left;
2270 else
2271 p = &(*p)->rb_right;
2274 rb_link_node(&backref->node, parent, p);
2275 rb_insert_color(&backref->node, root);
2279 * Note the backref might has changed, and in this case we just return 0.
2281 static noinline int record_one_backref(u64 inum, u64 offset, u64 root_id,
2282 void *ctx)
2284 struct btrfs_file_extent_item *extent;
2285 struct btrfs_fs_info *fs_info;
2286 struct old_sa_defrag_extent *old = ctx;
2287 struct new_sa_defrag_extent *new = old->new;
2288 struct btrfs_path *path = new->path;
2289 struct btrfs_key key;
2290 struct btrfs_root *root;
2291 struct sa_defrag_extent_backref *backref;
2292 struct extent_buffer *leaf;
2293 struct inode *inode = new->inode;
2294 int slot;
2295 int ret;
2296 u64 extent_offset;
2297 u64 num_bytes;
2299 if (BTRFS_I(inode)->root->root_key.objectid == root_id &&
2300 inum == btrfs_ino(inode))
2301 return 0;
2303 key.objectid = root_id;
2304 key.type = BTRFS_ROOT_ITEM_KEY;
2305 key.offset = (u64)-1;
2307 fs_info = BTRFS_I(inode)->root->fs_info;
2308 root = btrfs_read_fs_root_no_name(fs_info, &key);
2309 if (IS_ERR(root)) {
2310 if (PTR_ERR(root) == -ENOENT)
2311 return 0;
2312 WARN_ON(1);
2313 pr_debug("inum=%llu, offset=%llu, root_id=%llu\n",
2314 inum, offset, root_id);
2315 return PTR_ERR(root);
2318 key.objectid = inum;
2319 key.type = BTRFS_EXTENT_DATA_KEY;
2320 if (offset > (u64)-1 << 32)
2321 key.offset = 0;
2322 else
2323 key.offset = offset;
2325 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2326 if (WARN_ON(ret < 0))
2327 return ret;
2328 ret = 0;
2330 while (1) {
2331 cond_resched();
2333 leaf = path->nodes[0];
2334 slot = path->slots[0];
2336 if (slot >= btrfs_header_nritems(leaf)) {
2337 ret = btrfs_next_leaf(root, path);
2338 if (ret < 0) {
2339 goto out;
2340 } else if (ret > 0) {
2341 ret = 0;
2342 goto out;
2344 continue;
2347 path->slots[0]++;
2349 btrfs_item_key_to_cpu(leaf, &key, slot);
2351 if (key.objectid > inum)
2352 goto out;
2354 if (key.objectid < inum || key.type != BTRFS_EXTENT_DATA_KEY)
2355 continue;
2357 extent = btrfs_item_ptr(leaf, slot,
2358 struct btrfs_file_extent_item);
2360 if (btrfs_file_extent_disk_bytenr(leaf, extent) != old->bytenr)
2361 continue;
2364 * 'offset' refers to the exact key.offset,
2365 * NOT the 'offset' field in btrfs_extent_data_ref, ie.
2366 * (key.offset - extent_offset).
2368 if (key.offset != offset)
2369 continue;
2371 extent_offset = btrfs_file_extent_offset(leaf, extent);
2372 num_bytes = btrfs_file_extent_num_bytes(leaf, extent);
2374 if (extent_offset >= old->extent_offset + old->offset +
2375 old->len || extent_offset + num_bytes <=
2376 old->extent_offset + old->offset)
2377 continue;
2378 break;
2381 backref = kmalloc(sizeof(*backref), GFP_NOFS);
2382 if (!backref) {
2383 ret = -ENOENT;
2384 goto out;
2387 backref->root_id = root_id;
2388 backref->inum = inum;
2389 backref->file_pos = offset;
2390 backref->num_bytes = num_bytes;
2391 backref->extent_offset = extent_offset;
2392 backref->generation = btrfs_file_extent_generation(leaf, extent);
2393 backref->old = old;
2394 backref_insert(&new->root, backref);
2395 old->count++;
2396 out:
2397 btrfs_release_path(path);
2398 WARN_ON(ret);
2399 return ret;
2402 static noinline bool record_extent_backrefs(struct btrfs_path *path,
2403 struct new_sa_defrag_extent *new)
2405 struct btrfs_fs_info *fs_info = BTRFS_I(new->inode)->root->fs_info;
2406 struct old_sa_defrag_extent *old, *tmp;
2407 int ret;
2409 new->path = path;
2411 list_for_each_entry_safe(old, tmp, &new->head, list) {
2412 ret = iterate_inodes_from_logical(old->bytenr +
2413 old->extent_offset, fs_info,
2414 path, record_one_backref,
2415 old);
2416 if (ret < 0 && ret != -ENOENT)
2417 return false;
2419 /* no backref to be processed for this extent */
2420 if (!old->count) {
2421 list_del(&old->list);
2422 kfree(old);
2426 if (list_empty(&new->head))
2427 return false;
2429 return true;
2432 static int relink_is_mergable(struct extent_buffer *leaf,
2433 struct btrfs_file_extent_item *fi,
2434 struct new_sa_defrag_extent *new)
2436 if (btrfs_file_extent_disk_bytenr(leaf, fi) != new->bytenr)
2437 return 0;
2439 if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2440 return 0;
2442 if (btrfs_file_extent_compression(leaf, fi) != new->compress_type)
2443 return 0;
2445 if (btrfs_file_extent_encryption(leaf, fi) ||
2446 btrfs_file_extent_other_encoding(leaf, fi))
2447 return 0;
2449 return 1;
2453 * Note the backref might has changed, and in this case we just return 0.
2455 static noinline int relink_extent_backref(struct btrfs_path *path,
2456 struct sa_defrag_extent_backref *prev,
2457 struct sa_defrag_extent_backref *backref)
2459 struct btrfs_file_extent_item *extent;
2460 struct btrfs_file_extent_item *item;
2461 struct btrfs_ordered_extent *ordered;
2462 struct btrfs_trans_handle *trans;
2463 struct btrfs_fs_info *fs_info;
2464 struct btrfs_root *root;
2465 struct btrfs_key key;
2466 struct extent_buffer *leaf;
2467 struct old_sa_defrag_extent *old = backref->old;
2468 struct new_sa_defrag_extent *new = old->new;
2469 struct inode *src_inode = new->inode;
2470 struct inode *inode;
2471 struct extent_state *cached = NULL;
2472 int ret = 0;
2473 u64 start;
2474 u64 len;
2475 u64 lock_start;
2476 u64 lock_end;
2477 bool merge = false;
2478 int index;
2480 if (prev && prev->root_id == backref->root_id &&
2481 prev->inum == backref->inum &&
2482 prev->file_pos + prev->num_bytes == backref->file_pos)
2483 merge = true;
2485 /* step 1: get root */
2486 key.objectid = backref->root_id;
2487 key.type = BTRFS_ROOT_ITEM_KEY;
2488 key.offset = (u64)-1;
2490 fs_info = BTRFS_I(src_inode)->root->fs_info;
2491 index = srcu_read_lock(&fs_info->subvol_srcu);
2493 root = btrfs_read_fs_root_no_name(fs_info, &key);
2494 if (IS_ERR(root)) {
2495 srcu_read_unlock(&fs_info->subvol_srcu, index);
2496 if (PTR_ERR(root) == -ENOENT)
2497 return 0;
2498 return PTR_ERR(root);
2501 if (btrfs_root_readonly(root)) {
2502 srcu_read_unlock(&fs_info->subvol_srcu, index);
2503 return 0;
2506 /* step 2: get inode */
2507 key.objectid = backref->inum;
2508 key.type = BTRFS_INODE_ITEM_KEY;
2509 key.offset = 0;
2511 inode = btrfs_iget(fs_info->sb, &key, root, NULL);
2512 if (IS_ERR(inode)) {
2513 srcu_read_unlock(&fs_info->subvol_srcu, index);
2514 return 0;
2517 srcu_read_unlock(&fs_info->subvol_srcu, index);
2519 /* step 3: relink backref */
2520 lock_start = backref->file_pos;
2521 lock_end = backref->file_pos + backref->num_bytes - 1;
2522 lock_extent_bits(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2523 0, &cached);
2525 ordered = btrfs_lookup_first_ordered_extent(inode, lock_end);
2526 if (ordered) {
2527 btrfs_put_ordered_extent(ordered);
2528 goto out_unlock;
2531 trans = btrfs_join_transaction(root);
2532 if (IS_ERR(trans)) {
2533 ret = PTR_ERR(trans);
2534 goto out_unlock;
2537 key.objectid = backref->inum;
2538 key.type = BTRFS_EXTENT_DATA_KEY;
2539 key.offset = backref->file_pos;
2541 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2542 if (ret < 0) {
2543 goto out_free_path;
2544 } else if (ret > 0) {
2545 ret = 0;
2546 goto out_free_path;
2549 extent = btrfs_item_ptr(path->nodes[0], path->slots[0],
2550 struct btrfs_file_extent_item);
2552 if (btrfs_file_extent_generation(path->nodes[0], extent) !=
2553 backref->generation)
2554 goto out_free_path;
2556 btrfs_release_path(path);
2558 start = backref->file_pos;
2559 if (backref->extent_offset < old->extent_offset + old->offset)
2560 start += old->extent_offset + old->offset -
2561 backref->extent_offset;
2563 len = min(backref->extent_offset + backref->num_bytes,
2564 old->extent_offset + old->offset + old->len);
2565 len -= max(backref->extent_offset, old->extent_offset + old->offset);
2567 ret = btrfs_drop_extents(trans, root, inode, start,
2568 start + len, 1);
2569 if (ret)
2570 goto out_free_path;
2571 again:
2572 key.objectid = btrfs_ino(inode);
2573 key.type = BTRFS_EXTENT_DATA_KEY;
2574 key.offset = start;
2576 path->leave_spinning = 1;
2577 if (merge) {
2578 struct btrfs_file_extent_item *fi;
2579 u64 extent_len;
2580 struct btrfs_key found_key;
2582 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2583 if (ret < 0)
2584 goto out_free_path;
2586 path->slots[0]--;
2587 leaf = path->nodes[0];
2588 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2590 fi = btrfs_item_ptr(leaf, path->slots[0],
2591 struct btrfs_file_extent_item);
2592 extent_len = btrfs_file_extent_num_bytes(leaf, fi);
2594 if (extent_len + found_key.offset == start &&
2595 relink_is_mergable(leaf, fi, new)) {
2596 btrfs_set_file_extent_num_bytes(leaf, fi,
2597 extent_len + len);
2598 btrfs_mark_buffer_dirty(leaf);
2599 inode_add_bytes(inode, len);
2601 ret = 1;
2602 goto out_free_path;
2603 } else {
2604 merge = false;
2605 btrfs_release_path(path);
2606 goto again;
2610 ret = btrfs_insert_empty_item(trans, root, path, &key,
2611 sizeof(*extent));
2612 if (ret) {
2613 btrfs_abort_transaction(trans, root, ret);
2614 goto out_free_path;
2617 leaf = path->nodes[0];
2618 item = btrfs_item_ptr(leaf, path->slots[0],
2619 struct btrfs_file_extent_item);
2620 btrfs_set_file_extent_disk_bytenr(leaf, item, new->bytenr);
2621 btrfs_set_file_extent_disk_num_bytes(leaf, item, new->disk_len);
2622 btrfs_set_file_extent_offset(leaf, item, start - new->file_pos);
2623 btrfs_set_file_extent_num_bytes(leaf, item, len);
2624 btrfs_set_file_extent_ram_bytes(leaf, item, new->len);
2625 btrfs_set_file_extent_generation(leaf, item, trans->transid);
2626 btrfs_set_file_extent_type(leaf, item, BTRFS_FILE_EXTENT_REG);
2627 btrfs_set_file_extent_compression(leaf, item, new->compress_type);
2628 btrfs_set_file_extent_encryption(leaf, item, 0);
2629 btrfs_set_file_extent_other_encoding(leaf, item, 0);
2631 btrfs_mark_buffer_dirty(leaf);
2632 inode_add_bytes(inode, len);
2633 btrfs_release_path(path);
2635 ret = btrfs_inc_extent_ref(trans, root, new->bytenr,
2636 new->disk_len, 0,
2637 backref->root_id, backref->inum,
2638 new->file_pos); /* start - extent_offset */
2639 if (ret) {
2640 btrfs_abort_transaction(trans, root, ret);
2641 goto out_free_path;
2644 ret = 1;
2645 out_free_path:
2646 btrfs_release_path(path);
2647 path->leave_spinning = 0;
2648 btrfs_end_transaction(trans, root);
2649 out_unlock:
2650 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lock_start, lock_end,
2651 &cached, GFP_NOFS);
2652 iput(inode);
2653 return ret;
2656 static void free_sa_defrag_extent(struct new_sa_defrag_extent *new)
2658 struct old_sa_defrag_extent *old, *tmp;
2660 if (!new)
2661 return;
2663 list_for_each_entry_safe(old, tmp, &new->head, list) {
2664 kfree(old);
2666 kfree(new);
2669 static void relink_file_extents(struct new_sa_defrag_extent *new)
2671 struct btrfs_path *path;
2672 struct sa_defrag_extent_backref *backref;
2673 struct sa_defrag_extent_backref *prev = NULL;
2674 struct inode *inode;
2675 struct btrfs_root *root;
2676 struct rb_node *node;
2677 int ret;
2679 inode = new->inode;
2680 root = BTRFS_I(inode)->root;
2682 path = btrfs_alloc_path();
2683 if (!path)
2684 return;
2686 if (!record_extent_backrefs(path, new)) {
2687 btrfs_free_path(path);
2688 goto out;
2690 btrfs_release_path(path);
2692 while (1) {
2693 node = rb_first(&new->root);
2694 if (!node)
2695 break;
2696 rb_erase(node, &new->root);
2698 backref = rb_entry(node, struct sa_defrag_extent_backref, node);
2700 ret = relink_extent_backref(path, prev, backref);
2701 WARN_ON(ret < 0);
2703 kfree(prev);
2705 if (ret == 1)
2706 prev = backref;
2707 else
2708 prev = NULL;
2709 cond_resched();
2711 kfree(prev);
2713 btrfs_free_path(path);
2714 out:
2715 free_sa_defrag_extent(new);
2717 atomic_dec(&root->fs_info->defrag_running);
2718 wake_up(&root->fs_info->transaction_wait);
2721 static struct new_sa_defrag_extent *
2722 record_old_file_extents(struct inode *inode,
2723 struct btrfs_ordered_extent *ordered)
2725 struct btrfs_root *root = BTRFS_I(inode)->root;
2726 struct btrfs_path *path;
2727 struct btrfs_key key;
2728 struct old_sa_defrag_extent *old;
2729 struct new_sa_defrag_extent *new;
2730 int ret;
2732 new = kmalloc(sizeof(*new), GFP_NOFS);
2733 if (!new)
2734 return NULL;
2736 new->inode = inode;
2737 new->file_pos = ordered->file_offset;
2738 new->len = ordered->len;
2739 new->bytenr = ordered->start;
2740 new->disk_len = ordered->disk_len;
2741 new->compress_type = ordered->compress_type;
2742 new->root = RB_ROOT;
2743 INIT_LIST_HEAD(&new->head);
2745 path = btrfs_alloc_path();
2746 if (!path)
2747 goto out_kfree;
2749 key.objectid = btrfs_ino(inode);
2750 key.type = BTRFS_EXTENT_DATA_KEY;
2751 key.offset = new->file_pos;
2753 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
2754 if (ret < 0)
2755 goto out_free_path;
2756 if (ret > 0 && path->slots[0] > 0)
2757 path->slots[0]--;
2759 /* find out all the old extents for the file range */
2760 while (1) {
2761 struct btrfs_file_extent_item *extent;
2762 struct extent_buffer *l;
2763 int slot;
2764 u64 num_bytes;
2765 u64 offset;
2766 u64 end;
2767 u64 disk_bytenr;
2768 u64 extent_offset;
2770 l = path->nodes[0];
2771 slot = path->slots[0];
2773 if (slot >= btrfs_header_nritems(l)) {
2774 ret = btrfs_next_leaf(root, path);
2775 if (ret < 0)
2776 goto out_free_path;
2777 else if (ret > 0)
2778 break;
2779 continue;
2782 btrfs_item_key_to_cpu(l, &key, slot);
2784 if (key.objectid != btrfs_ino(inode))
2785 break;
2786 if (key.type != BTRFS_EXTENT_DATA_KEY)
2787 break;
2788 if (key.offset >= new->file_pos + new->len)
2789 break;
2791 extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item);
2793 num_bytes = btrfs_file_extent_num_bytes(l, extent);
2794 if (key.offset + num_bytes < new->file_pos)
2795 goto next;
2797 disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent);
2798 if (!disk_bytenr)
2799 goto next;
2801 extent_offset = btrfs_file_extent_offset(l, extent);
2803 old = kmalloc(sizeof(*old), GFP_NOFS);
2804 if (!old)
2805 goto out_free_path;
2807 offset = max(new->file_pos, key.offset);
2808 end = min(new->file_pos + new->len, key.offset + num_bytes);
2810 old->bytenr = disk_bytenr;
2811 old->extent_offset = extent_offset;
2812 old->offset = offset - key.offset;
2813 old->len = end - offset;
2814 old->new = new;
2815 old->count = 0;
2816 list_add_tail(&old->list, &new->head);
2817 next:
2818 path->slots[0]++;
2819 cond_resched();
2822 btrfs_free_path(path);
2823 atomic_inc(&root->fs_info->defrag_running);
2825 return new;
2827 out_free_path:
2828 btrfs_free_path(path);
2829 out_kfree:
2830 free_sa_defrag_extent(new);
2831 return NULL;
2834 static void btrfs_release_delalloc_bytes(struct btrfs_root *root,
2835 u64 start, u64 len)
2837 struct btrfs_block_group_cache *cache;
2839 cache = btrfs_lookup_block_group(root->fs_info, start);
2840 ASSERT(cache);
2842 spin_lock(&cache->lock);
2843 cache->delalloc_bytes -= len;
2844 spin_unlock(&cache->lock);
2846 btrfs_put_block_group(cache);
2849 /* as ordered data IO finishes, this gets called so we can finish
2850 * an ordered extent if the range of bytes in the file it covers are
2851 * fully written.
2853 static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
2855 struct inode *inode = ordered_extent->inode;
2856 struct btrfs_root *root = BTRFS_I(inode)->root;
2857 struct btrfs_trans_handle *trans = NULL;
2858 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
2859 struct extent_state *cached_state = NULL;
2860 struct new_sa_defrag_extent *new = NULL;
2861 int compress_type = 0;
2862 int ret = 0;
2863 u64 logical_len = ordered_extent->len;
2864 bool nolock;
2865 bool truncated = false;
2867 nolock = btrfs_is_free_space_inode(inode);
2869 if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
2870 ret = -EIO;
2871 goto out;
2874 btrfs_free_io_failure_record(inode, ordered_extent->file_offset,
2875 ordered_extent->file_offset +
2876 ordered_extent->len - 1);
2878 if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
2879 truncated = true;
2880 logical_len = ordered_extent->truncated_len;
2881 /* Truncated the entire extent, don't bother adding */
2882 if (!logical_len)
2883 goto out;
2886 if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
2887 BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
2890 * For mwrite(mmap + memset to write) case, we still reserve
2891 * space for NOCOW range.
2892 * As NOCOW won't cause a new delayed ref, just free the space
2894 btrfs_qgroup_free_data(inode, ordered_extent->file_offset,
2895 ordered_extent->len);
2896 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2897 if (nolock)
2898 trans = btrfs_join_transaction_nolock(root);
2899 else
2900 trans = btrfs_join_transaction(root);
2901 if (IS_ERR(trans)) {
2902 ret = PTR_ERR(trans);
2903 trans = NULL;
2904 goto out;
2906 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2907 ret = btrfs_update_inode_fallback(trans, root, inode);
2908 if (ret) /* -ENOMEM or corruption */
2909 btrfs_abort_transaction(trans, root, ret);
2910 goto out;
2913 lock_extent_bits(io_tree, ordered_extent->file_offset,
2914 ordered_extent->file_offset + ordered_extent->len - 1,
2915 0, &cached_state);
2917 ret = test_range_bit(io_tree, ordered_extent->file_offset,
2918 ordered_extent->file_offset + ordered_extent->len - 1,
2919 EXTENT_DEFRAG, 1, cached_state);
2920 if (ret) {
2921 u64 last_snapshot = btrfs_root_last_snapshot(&root->root_item);
2922 if (0 && last_snapshot >= BTRFS_I(inode)->generation)
2923 /* the inode is shared */
2924 new = record_old_file_extents(inode, ordered_extent);
2926 clear_extent_bit(io_tree, ordered_extent->file_offset,
2927 ordered_extent->file_offset + ordered_extent->len - 1,
2928 EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS);
2931 if (nolock)
2932 trans = btrfs_join_transaction_nolock(root);
2933 else
2934 trans = btrfs_join_transaction(root);
2935 if (IS_ERR(trans)) {
2936 ret = PTR_ERR(trans);
2937 trans = NULL;
2938 goto out_unlock;
2941 trans->block_rsv = &root->fs_info->delalloc_block_rsv;
2943 if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
2944 compress_type = ordered_extent->compress_type;
2945 if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
2946 BUG_ON(compress_type);
2947 ret = btrfs_mark_extent_written(trans, inode,
2948 ordered_extent->file_offset,
2949 ordered_extent->file_offset +
2950 logical_len);
2951 } else {
2952 BUG_ON(root == root->fs_info->tree_root);
2953 ret = insert_reserved_file_extent(trans, inode,
2954 ordered_extent->file_offset,
2955 ordered_extent->start,
2956 ordered_extent->disk_len,
2957 logical_len, logical_len,
2958 compress_type, 0, 0,
2959 BTRFS_FILE_EXTENT_REG);
2960 if (!ret)
2961 btrfs_release_delalloc_bytes(root,
2962 ordered_extent->start,
2963 ordered_extent->disk_len);
2965 unpin_extent_cache(&BTRFS_I(inode)->extent_tree,
2966 ordered_extent->file_offset, ordered_extent->len,
2967 trans->transid);
2968 if (ret < 0) {
2969 btrfs_abort_transaction(trans, root, ret);
2970 goto out_unlock;
2973 add_pending_csums(trans, inode, ordered_extent->file_offset,
2974 &ordered_extent->list);
2976 btrfs_ordered_update_i_size(inode, 0, ordered_extent);
2977 ret = btrfs_update_inode_fallback(trans, root, inode);
2978 if (ret) { /* -ENOMEM or corruption */
2979 btrfs_abort_transaction(trans, root, ret);
2980 goto out_unlock;
2982 ret = 0;
2983 out_unlock:
2984 unlock_extent_cached(io_tree, ordered_extent->file_offset,
2985 ordered_extent->file_offset +
2986 ordered_extent->len - 1, &cached_state, GFP_NOFS);
2987 out:
2988 if (root != root->fs_info->tree_root)
2989 btrfs_delalloc_release_metadata(inode, ordered_extent->len);
2990 if (trans)
2991 btrfs_end_transaction(trans, root);
2993 if (ret || truncated) {
2994 u64 start, end;
2996 if (truncated)
2997 start = ordered_extent->file_offset + logical_len;
2998 else
2999 start = ordered_extent->file_offset;
3000 end = ordered_extent->file_offset + ordered_extent->len - 1;
3001 clear_extent_uptodate(io_tree, start, end, NULL, GFP_NOFS);
3003 /* Drop the cache for the part of the extent we didn't write. */
3004 btrfs_drop_extent_cache(inode, start, end, 0);
3007 * If the ordered extent had an IOERR or something else went
3008 * wrong we need to return the space for this ordered extent
3009 * back to the allocator. We only free the extent in the
3010 * truncated case if we didn't write out the extent at all.
3012 if ((ret || !logical_len) &&
3013 !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3014 !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags))
3015 btrfs_free_reserved_extent(root, ordered_extent->start,
3016 ordered_extent->disk_len, 1);
3021 * This needs to be done to make sure anybody waiting knows we are done
3022 * updating everything for this ordered extent.
3024 btrfs_remove_ordered_extent(inode, ordered_extent);
3026 /* for snapshot-aware defrag */
3027 if (new) {
3028 if (ret) {
3029 free_sa_defrag_extent(new);
3030 atomic_dec(&root->fs_info->defrag_running);
3031 } else {
3032 relink_file_extents(new);
3036 /* once for us */
3037 btrfs_put_ordered_extent(ordered_extent);
3038 /* once for the tree */
3039 btrfs_put_ordered_extent(ordered_extent);
3041 return ret;
3044 static void finish_ordered_fn(struct btrfs_work *work)
3046 struct btrfs_ordered_extent *ordered_extent;
3047 ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
3048 btrfs_finish_ordered_io(ordered_extent);
3051 static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end,
3052 struct extent_state *state, int uptodate)
3054 struct inode *inode = page->mapping->host;
3055 struct btrfs_root *root = BTRFS_I(inode)->root;
3056 struct btrfs_ordered_extent *ordered_extent = NULL;
3057 struct btrfs_workqueue *wq;
3058 btrfs_work_func_t func;
3060 trace_btrfs_writepage_end_io_hook(page, start, end, uptodate);
3062 ClearPagePrivate2(page);
3063 if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start,
3064 end - start + 1, uptodate))
3065 return 0;
3067 if (btrfs_is_free_space_inode(inode)) {
3068 wq = root->fs_info->endio_freespace_worker;
3069 func = btrfs_freespace_write_helper;
3070 } else {
3071 wq = root->fs_info->endio_write_workers;
3072 func = btrfs_endio_write_helper;
3075 btrfs_init_work(&ordered_extent->work, func, finish_ordered_fn, NULL,
3076 NULL);
3077 btrfs_queue_work(wq, &ordered_extent->work);
3079 return 0;
3082 static int __readpage_endio_check(struct inode *inode,
3083 struct btrfs_io_bio *io_bio,
3084 int icsum, struct page *page,
3085 int pgoff, u64 start, size_t len)
3087 char *kaddr;
3088 u32 csum_expected;
3089 u32 csum = ~(u32)0;
3091 csum_expected = *(((u32 *)io_bio->csum) + icsum);
3093 kaddr = kmap_atomic(page);
3094 csum = btrfs_csum_data(kaddr + pgoff, csum, len);
3095 btrfs_csum_final(csum, (char *)&csum);
3096 if (csum != csum_expected)
3097 goto zeroit;
3099 kunmap_atomic(kaddr);
3100 return 0;
3101 zeroit:
3102 btrfs_warn_rl(BTRFS_I(inode)->root->fs_info,
3103 "csum failed ino %llu off %llu csum %u expected csum %u",
3104 btrfs_ino(inode), start, csum, csum_expected);
3105 memset(kaddr + pgoff, 1, len);
3106 flush_dcache_page(page);
3107 kunmap_atomic(kaddr);
3108 if (csum_expected == 0)
3109 return 0;
3110 return -EIO;
3114 * when reads are done, we need to check csums to verify the data is correct
3115 * if there's a match, we allow the bio to finish. If not, the code in
3116 * extent_io.c will try to find good copies for us.
3118 static int btrfs_readpage_end_io_hook(struct btrfs_io_bio *io_bio,
3119 u64 phy_offset, struct page *page,
3120 u64 start, u64 end, int mirror)
3122 size_t offset = start - page_offset(page);
3123 struct inode *inode = page->mapping->host;
3124 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
3125 struct btrfs_root *root = BTRFS_I(inode)->root;
3127 if (PageChecked(page)) {
3128 ClearPageChecked(page);
3129 return 0;
3132 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
3133 return 0;
3135 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID &&
3136 test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) {
3137 clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM,
3138 GFP_NOFS);
3139 return 0;
3142 phy_offset >>= inode->i_sb->s_blocksize_bits;
3143 return __readpage_endio_check(inode, io_bio, phy_offset, page, offset,
3144 start, (size_t)(end - start + 1));
3147 struct delayed_iput {
3148 struct list_head list;
3149 struct inode *inode;
3152 /* JDM: If this is fs-wide, why can't we add a pointer to
3153 * btrfs_inode instead and avoid the allocation? */
3154 void btrfs_add_delayed_iput(struct inode *inode)
3156 struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3157 struct delayed_iput *delayed;
3159 if (atomic_add_unless(&inode->i_count, -1, 1))
3160 return;
3162 delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL);
3163 delayed->inode = inode;
3165 spin_lock(&fs_info->delayed_iput_lock);
3166 list_add_tail(&delayed->list, &fs_info->delayed_iputs);
3167 spin_unlock(&fs_info->delayed_iput_lock);
3170 void btrfs_run_delayed_iputs(struct btrfs_root *root)
3172 LIST_HEAD(list);
3173 struct btrfs_fs_info *fs_info = root->fs_info;
3174 struct delayed_iput *delayed;
3175 int empty;
3177 spin_lock(&fs_info->delayed_iput_lock);
3178 empty = list_empty(&fs_info->delayed_iputs);
3179 spin_unlock(&fs_info->delayed_iput_lock);
3180 if (empty)
3181 return;
3183 spin_lock(&fs_info->delayed_iput_lock);
3184 list_splice_init(&fs_info->delayed_iputs, &list);
3185 spin_unlock(&fs_info->delayed_iput_lock);
3187 while (!list_empty(&list)) {
3188 delayed = list_entry(list.next, struct delayed_iput, list);
3189 list_del(&delayed->list);
3190 iput(delayed->inode);
3191 kfree(delayed);
3196 * This is called in transaction commit time. If there are no orphan
3197 * files in the subvolume, it removes orphan item and frees block_rsv
3198 * structure.
3200 void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans,
3201 struct btrfs_root *root)
3203 struct btrfs_block_rsv *block_rsv;
3204 int ret;
3206 if (atomic_read(&root->orphan_inodes) ||
3207 root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE)
3208 return;
3210 spin_lock(&root->orphan_lock);
3211 if (atomic_read(&root->orphan_inodes)) {
3212 spin_unlock(&root->orphan_lock);
3213 return;
3216 if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) {
3217 spin_unlock(&root->orphan_lock);
3218 return;
3221 block_rsv = root->orphan_block_rsv;
3222 root->orphan_block_rsv = NULL;
3223 spin_unlock(&root->orphan_lock);
3225 if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state) &&
3226 btrfs_root_refs(&root->root_item) > 0) {
3227 ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root,
3228 root->root_key.objectid);
3229 if (ret)
3230 btrfs_abort_transaction(trans, root, ret);
3231 else
3232 clear_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED,
3233 &root->state);
3236 if (block_rsv) {
3237 WARN_ON(block_rsv->size > 0);
3238 btrfs_free_block_rsv(root, block_rsv);
3243 * This creates an orphan entry for the given inode in case something goes
3244 * wrong in the middle of an unlink/truncate.
3246 * NOTE: caller of this function should reserve 5 units of metadata for
3247 * this function.
3249 int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode)
3251 struct btrfs_root *root = BTRFS_I(inode)->root;
3252 struct btrfs_block_rsv *block_rsv = NULL;
3253 int reserve = 0;
3254 int insert = 0;
3255 int ret;
3257 if (!root->orphan_block_rsv) {
3258 block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
3259 if (!block_rsv)
3260 return -ENOMEM;
3263 spin_lock(&root->orphan_lock);
3264 if (!root->orphan_block_rsv) {
3265 root->orphan_block_rsv = block_rsv;
3266 } else if (block_rsv) {
3267 btrfs_free_block_rsv(root, block_rsv);
3268 block_rsv = NULL;
3271 if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3272 &BTRFS_I(inode)->runtime_flags)) {
3273 #if 0
3275 * For proper ENOSPC handling, we should do orphan
3276 * cleanup when mounting. But this introduces backward
3277 * compatibility issue.
3279 if (!xchg(&root->orphan_item_inserted, 1))
3280 insert = 2;
3281 else
3282 insert = 1;
3283 #endif
3284 insert = 1;
3285 atomic_inc(&root->orphan_inodes);
3288 if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3289 &BTRFS_I(inode)->runtime_flags))
3290 reserve = 1;
3291 spin_unlock(&root->orphan_lock);
3293 /* grab metadata reservation from transaction handle */
3294 if (reserve) {
3295 ret = btrfs_orphan_reserve_metadata(trans, inode);
3296 BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */
3299 /* insert an orphan item to track this unlinked/truncated file */
3300 if (insert >= 1) {
3301 ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode));
3302 if (ret) {
3303 atomic_dec(&root->orphan_inodes);
3304 if (reserve) {
3305 clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3306 &BTRFS_I(inode)->runtime_flags);
3307 btrfs_orphan_release_metadata(inode);
3309 if (ret != -EEXIST) {
3310 clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3311 &BTRFS_I(inode)->runtime_flags);
3312 btrfs_abort_transaction(trans, root, ret);
3313 return ret;
3316 ret = 0;
3319 /* insert an orphan item to track subvolume contains orphan files */
3320 if (insert >= 2) {
3321 ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root,
3322 root->root_key.objectid);
3323 if (ret && ret != -EEXIST) {
3324 btrfs_abort_transaction(trans, root, ret);
3325 return ret;
3328 return 0;
3332 * We have done the truncate/delete so we can go ahead and remove the orphan
3333 * item for this particular inode.
3335 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3336 struct inode *inode)
3338 struct btrfs_root *root = BTRFS_I(inode)->root;
3339 int delete_item = 0;
3340 int release_rsv = 0;
3341 int ret = 0;
3343 spin_lock(&root->orphan_lock);
3344 if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3345 &BTRFS_I(inode)->runtime_flags))
3346 delete_item = 1;
3348 if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED,
3349 &BTRFS_I(inode)->runtime_flags))
3350 release_rsv = 1;
3351 spin_unlock(&root->orphan_lock);
3353 if (delete_item) {
3354 atomic_dec(&root->orphan_inodes);
3355 if (trans)
3356 ret = btrfs_del_orphan_item(trans, root,
3357 btrfs_ino(inode));
3360 if (release_rsv)
3361 btrfs_orphan_release_metadata(inode);
3363 return ret;
3367 * this cleans up any orphans that may be left on the list from the last use
3368 * of this root.
3370 int btrfs_orphan_cleanup(struct btrfs_root *root)
3372 struct btrfs_path *path;
3373 struct extent_buffer *leaf;
3374 struct btrfs_key key, found_key;
3375 struct btrfs_trans_handle *trans;
3376 struct inode *inode;
3377 u64 last_objectid = 0;
3378 int ret = 0, nr_unlink = 0, nr_truncate = 0;
3380 if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED))
3381 return 0;
3383 path = btrfs_alloc_path();
3384 if (!path) {
3385 ret = -ENOMEM;
3386 goto out;
3388 path->reada = -1;
3390 key.objectid = BTRFS_ORPHAN_OBJECTID;
3391 key.type = BTRFS_ORPHAN_ITEM_KEY;
3392 key.offset = (u64)-1;
3394 while (1) {
3395 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3396 if (ret < 0)
3397 goto out;
3400 * if ret == 0 means we found what we were searching for, which
3401 * is weird, but possible, so only screw with path if we didn't
3402 * find the key and see if we have stuff that matches
3404 if (ret > 0) {
3405 ret = 0;
3406 if (path->slots[0] == 0)
3407 break;
3408 path->slots[0]--;
3411 /* pull out the item */
3412 leaf = path->nodes[0];
3413 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3415 /* make sure the item matches what we want */
3416 if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3417 break;
3418 if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3419 break;
3421 /* release the path since we're done with it */
3422 btrfs_release_path(path);
3425 * this is where we are basically btrfs_lookup, without the
3426 * crossing root thing. we store the inode number in the
3427 * offset of the orphan item.
3430 if (found_key.offset == last_objectid) {
3431 btrfs_err(root->fs_info,
3432 "Error removing orphan entry, stopping orphan cleanup");
3433 ret = -EINVAL;
3434 goto out;
3437 last_objectid = found_key.offset;
3439 found_key.objectid = found_key.offset;
3440 found_key.type = BTRFS_INODE_ITEM_KEY;
3441 found_key.offset = 0;
3442 inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL);
3443 ret = PTR_ERR_OR_ZERO(inode);
3444 if (ret && ret != -ESTALE)
3445 goto out;
3447 if (ret == -ESTALE && root == root->fs_info->tree_root) {
3448 struct btrfs_root *dead_root;
3449 struct btrfs_fs_info *fs_info = root->fs_info;
3450 int is_dead_root = 0;
3453 * this is an orphan in the tree root. Currently these
3454 * could come from 2 sources:
3455 * a) a snapshot deletion in progress
3456 * b) a free space cache inode
3457 * We need to distinguish those two, as the snapshot
3458 * orphan must not get deleted.
3459 * find_dead_roots already ran before us, so if this
3460 * is a snapshot deletion, we should find the root
3461 * in the dead_roots list
3463 spin_lock(&fs_info->trans_lock);
3464 list_for_each_entry(dead_root, &fs_info->dead_roots,
3465 root_list) {
3466 if (dead_root->root_key.objectid ==
3467 found_key.objectid) {
3468 is_dead_root = 1;
3469 break;
3472 spin_unlock(&fs_info->trans_lock);
3473 if (is_dead_root) {
3474 /* prevent this orphan from being found again */
3475 key.offset = found_key.objectid - 1;
3476 continue;
3480 * Inode is already gone but the orphan item is still there,
3481 * kill the orphan item.
3483 if (ret == -ESTALE) {
3484 trans = btrfs_start_transaction(root, 1);
3485 if (IS_ERR(trans)) {
3486 ret = PTR_ERR(trans);
3487 goto out;
3489 btrfs_debug(root->fs_info, "auto deleting %Lu",
3490 found_key.objectid);
3491 ret = btrfs_del_orphan_item(trans, root,
3492 found_key.objectid);
3493 btrfs_end_transaction(trans, root);
3494 if (ret)
3495 goto out;
3496 continue;
3500 * add this inode to the orphan list so btrfs_orphan_del does
3501 * the proper thing when we hit it
3503 set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
3504 &BTRFS_I(inode)->runtime_flags);
3505 atomic_inc(&root->orphan_inodes);
3507 /* if we have links, this was a truncate, lets do that */
3508 if (inode->i_nlink) {
3509 if (WARN_ON(!S_ISREG(inode->i_mode))) {
3510 iput(inode);
3511 continue;
3513 nr_truncate++;
3515 /* 1 for the orphan item deletion. */
3516 trans = btrfs_start_transaction(root, 1);
3517 if (IS_ERR(trans)) {
3518 iput(inode);
3519 ret = PTR_ERR(trans);
3520 goto out;
3522 ret = btrfs_orphan_add(trans, inode);
3523 btrfs_end_transaction(trans, root);
3524 if (ret) {
3525 iput(inode);
3526 goto out;
3529 ret = btrfs_truncate(inode);
3530 if (ret)
3531 btrfs_orphan_del(NULL, inode);
3532 } else {
3533 nr_unlink++;
3536 /* this will do delete_inode and everything for us */
3537 iput(inode);
3538 if (ret)
3539 goto out;
3541 /* release the path since we're done with it */
3542 btrfs_release_path(path);
3544 root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE;
3546 if (root->orphan_block_rsv)
3547 btrfs_block_rsv_release(root, root->orphan_block_rsv,
3548 (u64)-1);
3550 if (root->orphan_block_rsv ||
3551 test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3552 trans = btrfs_join_transaction(root);
3553 if (!IS_ERR(trans))
3554 btrfs_end_transaction(trans, root);
3557 if (nr_unlink)
3558 btrfs_debug(root->fs_info, "unlinked %d orphans", nr_unlink);
3559 if (nr_truncate)
3560 btrfs_debug(root->fs_info, "truncated %d orphans", nr_truncate);
3562 out:
3563 if (ret)
3564 btrfs_err(root->fs_info,
3565 "could not do orphan cleanup %d", ret);
3566 btrfs_free_path(path);
3567 return ret;
3571 * very simple check to peek ahead in the leaf looking for xattrs. If we
3572 * don't find any xattrs, we know there can't be any acls.
3574 * slot is the slot the inode is in, objectid is the objectid of the inode
3576 static noinline int acls_after_inode_item(struct extent_buffer *leaf,
3577 int slot, u64 objectid,
3578 int *first_xattr_slot)
3580 u32 nritems = btrfs_header_nritems(leaf);
3581 struct btrfs_key found_key;
3582 static u64 xattr_access = 0;
3583 static u64 xattr_default = 0;
3584 int scanned = 0;
3586 if (!xattr_access) {
3587 xattr_access = btrfs_name_hash(POSIX_ACL_XATTR_ACCESS,
3588 strlen(POSIX_ACL_XATTR_ACCESS));
3589 xattr_default = btrfs_name_hash(POSIX_ACL_XATTR_DEFAULT,
3590 strlen(POSIX_ACL_XATTR_DEFAULT));
3593 slot++;
3594 *first_xattr_slot = -1;
3595 while (slot < nritems) {
3596 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3598 /* we found a different objectid, there must not be acls */
3599 if (found_key.objectid != objectid)
3600 return 0;
3602 /* we found an xattr, assume we've got an acl */
3603 if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3604 if (*first_xattr_slot == -1)
3605 *first_xattr_slot = slot;
3606 if (found_key.offset == xattr_access ||
3607 found_key.offset == xattr_default)
3608 return 1;
3612 * we found a key greater than an xattr key, there can't
3613 * be any acls later on
3615 if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3616 return 0;
3618 slot++;
3619 scanned++;
3622 * it goes inode, inode backrefs, xattrs, extents,
3623 * so if there are a ton of hard links to an inode there can
3624 * be a lot of backrefs. Don't waste time searching too hard,
3625 * this is just an optimization
3627 if (scanned >= 8)
3628 break;
3630 /* we hit the end of the leaf before we found an xattr or
3631 * something larger than an xattr. We have to assume the inode
3632 * has acls
3634 if (*first_xattr_slot == -1)
3635 *first_xattr_slot = slot;
3636 return 1;
3640 * read an inode from the btree into the in-memory inode
3642 static void btrfs_read_locked_inode(struct inode *inode)
3644 struct btrfs_path *path;
3645 struct extent_buffer *leaf;
3646 struct btrfs_inode_item *inode_item;
3647 struct btrfs_root *root = BTRFS_I(inode)->root;
3648 struct btrfs_key location;
3649 unsigned long ptr;
3650 int maybe_acls;
3651 u32 rdev;
3652 int ret;
3653 bool filled = false;
3654 int first_xattr_slot;
3656 ret = btrfs_fill_inode(inode, &rdev);
3657 if (!ret)
3658 filled = true;
3660 path = btrfs_alloc_path();
3661 if (!path)
3662 goto make_bad;
3664 memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
3666 ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3667 if (ret)
3668 goto make_bad;
3670 leaf = path->nodes[0];
3672 if (filled)
3673 goto cache_index;
3675 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3676 struct btrfs_inode_item);
3677 inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3678 set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
3679 i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
3680 i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
3681 btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3683 inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
3684 inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
3686 inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
3687 inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
3689 inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
3690 inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
3692 BTRFS_I(inode)->i_otime.tv_sec =
3693 btrfs_timespec_sec(leaf, &inode_item->otime);
3694 BTRFS_I(inode)->i_otime.tv_nsec =
3695 btrfs_timespec_nsec(leaf, &inode_item->otime);
3697 inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
3698 BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
3699 BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
3701 inode->i_version = btrfs_inode_sequence(leaf, inode_item);
3702 inode->i_generation = BTRFS_I(inode)->generation;
3703 inode->i_rdev = 0;
3704 rdev = btrfs_inode_rdev(leaf, inode_item);
3706 BTRFS_I(inode)->index_cnt = (u64)-1;
3707 BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item);
3709 cache_index:
3711 * If we were modified in the current generation and evicted from memory
3712 * and then re-read we need to do a full sync since we don't have any
3713 * idea about which extents were modified before we were evicted from
3714 * cache.
3716 * This is required for both inode re-read from disk and delayed inode
3717 * in delayed_nodes_tree.
3719 if (BTRFS_I(inode)->last_trans == root->fs_info->generation)
3720 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
3721 &BTRFS_I(inode)->runtime_flags);
3724 * We don't persist the id of the transaction where an unlink operation
3725 * against the inode was last made. So here we assume the inode might
3726 * have been evicted, and therefore the exact value of last_unlink_trans
3727 * lost, and set it to last_trans to avoid metadata inconsistencies
3728 * between the inode and its parent if the inode is fsync'ed and the log
3729 * replayed. For example, in the scenario:
3731 * touch mydir/foo
3732 * ln mydir/foo mydir/bar
3733 * sync
3734 * unlink mydir/bar
3735 * echo 2 > /proc/sys/vm/drop_caches # evicts inode
3736 * xfs_io -c fsync mydir/foo
3737 * <power failure>
3738 * mount fs, triggers fsync log replay
3740 * We must make sure that when we fsync our inode foo we also log its
3741 * parent inode, otherwise after log replay the parent still has the
3742 * dentry with the "bar" name but our inode foo has a link count of 1
3743 * and doesn't have an inode ref with the name "bar" anymore.
3745 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3746 * but it guarantees correctness at the expense of ocassional full
3747 * transaction commits on fsync if our inode is a directory, or if our
3748 * inode is not a directory, logging its parent unnecessarily.
3750 BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
3752 path->slots[0]++;
3753 if (inode->i_nlink != 1 ||
3754 path->slots[0] >= btrfs_header_nritems(leaf))
3755 goto cache_acl;
3757 btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
3758 if (location.objectid != btrfs_ino(inode))
3759 goto cache_acl;
3761 ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
3762 if (location.type == BTRFS_INODE_REF_KEY) {
3763 struct btrfs_inode_ref *ref;
3765 ref = (struct btrfs_inode_ref *)ptr;
3766 BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
3767 } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
3768 struct btrfs_inode_extref *extref;
3770 extref = (struct btrfs_inode_extref *)ptr;
3771 BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
3772 extref);
3774 cache_acl:
3776 * try to precache a NULL acl entry for files that don't have
3777 * any xattrs or acls
3779 maybe_acls = acls_after_inode_item(leaf, path->slots[0],
3780 btrfs_ino(inode), &first_xattr_slot);
3781 if (first_xattr_slot != -1) {
3782 path->slots[0] = first_xattr_slot;
3783 ret = btrfs_load_inode_props(inode, path);
3784 if (ret)
3785 btrfs_err(root->fs_info,
3786 "error loading props for ino %llu (root %llu): %d",
3787 btrfs_ino(inode),
3788 root->root_key.objectid, ret);
3790 btrfs_free_path(path);
3792 if (!maybe_acls)
3793 cache_no_acl(inode);
3795 switch (inode->i_mode & S_IFMT) {
3796 case S_IFREG:
3797 inode->i_mapping->a_ops = &btrfs_aops;
3798 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
3799 inode->i_fop = &btrfs_file_operations;
3800 inode->i_op = &btrfs_file_inode_operations;
3801 break;
3802 case S_IFDIR:
3803 inode->i_fop = &btrfs_dir_file_operations;
3804 if (root == root->fs_info->tree_root)
3805 inode->i_op = &btrfs_dir_ro_inode_operations;
3806 else
3807 inode->i_op = &btrfs_dir_inode_operations;
3808 break;
3809 case S_IFLNK:
3810 inode->i_op = &btrfs_symlink_inode_operations;
3811 inode->i_mapping->a_ops = &btrfs_symlink_aops;
3812 break;
3813 default:
3814 inode->i_op = &btrfs_special_inode_operations;
3815 init_special_inode(inode, inode->i_mode, rdev);
3816 break;
3819 btrfs_update_iflags(inode);
3820 return;
3822 make_bad:
3823 btrfs_free_path(path);
3824 make_bad_inode(inode);
3828 * given a leaf and an inode, copy the inode fields into the leaf
3830 static void fill_inode_item(struct btrfs_trans_handle *trans,
3831 struct extent_buffer *leaf,
3832 struct btrfs_inode_item *item,
3833 struct inode *inode)
3835 struct btrfs_map_token token;
3837 btrfs_init_map_token(&token);
3839 btrfs_set_token_inode_uid(leaf, item, i_uid_read(inode), &token);
3840 btrfs_set_token_inode_gid(leaf, item, i_gid_read(inode), &token);
3841 btrfs_set_token_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size,
3842 &token);
3843 btrfs_set_token_inode_mode(leaf, item, inode->i_mode, &token);
3844 btrfs_set_token_inode_nlink(leaf, item, inode->i_nlink, &token);
3846 btrfs_set_token_timespec_sec(leaf, &item->atime,
3847 inode->i_atime.tv_sec, &token);
3848 btrfs_set_token_timespec_nsec(leaf, &item->atime,
3849 inode->i_atime.tv_nsec, &token);
3851 btrfs_set_token_timespec_sec(leaf, &item->mtime,
3852 inode->i_mtime.tv_sec, &token);
3853 btrfs_set_token_timespec_nsec(leaf, &item->mtime,
3854 inode->i_mtime.tv_nsec, &token);
3856 btrfs_set_token_timespec_sec(leaf, &item->ctime,
3857 inode->i_ctime.tv_sec, &token);
3858 btrfs_set_token_timespec_nsec(leaf, &item->ctime,
3859 inode->i_ctime.tv_nsec, &token);
3861 btrfs_set_token_timespec_sec(leaf, &item->otime,
3862 BTRFS_I(inode)->i_otime.tv_sec, &token);
3863 btrfs_set_token_timespec_nsec(leaf, &item->otime,
3864 BTRFS_I(inode)->i_otime.tv_nsec, &token);
3866 btrfs_set_token_inode_nbytes(leaf, item, inode_get_bytes(inode),
3867 &token);
3868 btrfs_set_token_inode_generation(leaf, item, BTRFS_I(inode)->generation,
3869 &token);
3870 btrfs_set_token_inode_sequence(leaf, item, inode->i_version, &token);
3871 btrfs_set_token_inode_transid(leaf, item, trans->transid, &token);
3872 btrfs_set_token_inode_rdev(leaf, item, inode->i_rdev, &token);
3873 btrfs_set_token_inode_flags(leaf, item, BTRFS_I(inode)->flags, &token);
3874 btrfs_set_token_inode_block_group(leaf, item, 0, &token);
3878 * copy everything in the in-memory inode into the btree.
3880 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
3881 struct btrfs_root *root, struct inode *inode)
3883 struct btrfs_inode_item *inode_item;
3884 struct btrfs_path *path;
3885 struct extent_buffer *leaf;
3886 int ret;
3888 path = btrfs_alloc_path();
3889 if (!path)
3890 return -ENOMEM;
3892 path->leave_spinning = 1;
3893 ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location,
3895 if (ret) {
3896 if (ret > 0)
3897 ret = -ENOENT;
3898 goto failed;
3901 leaf = path->nodes[0];
3902 inode_item = btrfs_item_ptr(leaf, path->slots[0],
3903 struct btrfs_inode_item);
3905 fill_inode_item(trans, leaf, inode_item, inode);
3906 btrfs_mark_buffer_dirty(leaf);
3907 btrfs_set_inode_last_trans(trans, inode);
3908 ret = 0;
3909 failed:
3910 btrfs_free_path(path);
3911 return ret;
3915 * copy everything in the in-memory inode into the btree.
3917 noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
3918 struct btrfs_root *root, struct inode *inode)
3920 int ret;
3923 * If the inode is a free space inode, we can deadlock during commit
3924 * if we put it into the delayed code.
3926 * The data relocation inode should also be directly updated
3927 * without delay
3929 if (!btrfs_is_free_space_inode(inode)
3930 && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID
3931 && !root->fs_info->log_root_recovering) {
3932 btrfs_update_root_times(trans, root);
3934 ret = btrfs_delayed_update_inode(trans, root, inode);
3935 if (!ret)
3936 btrfs_set_inode_last_trans(trans, inode);
3937 return ret;
3940 return btrfs_update_inode_item(trans, root, inode);
3943 noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
3944 struct btrfs_root *root,
3945 struct inode *inode)
3947 int ret;
3949 ret = btrfs_update_inode(trans, root, inode);
3950 if (ret == -ENOSPC)
3951 return btrfs_update_inode_item(trans, root, inode);
3952 return ret;
3956 * unlink helper that gets used here in inode.c and in the tree logging
3957 * recovery code. It remove a link in a directory with a given name, and
3958 * also drops the back refs in the inode to the directory
3960 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
3961 struct btrfs_root *root,
3962 struct inode *dir, struct inode *inode,
3963 const char *name, int name_len)
3965 struct btrfs_path *path;
3966 int ret = 0;
3967 struct extent_buffer *leaf;
3968 struct btrfs_dir_item *di;
3969 struct btrfs_key key;
3970 u64 index;
3971 u64 ino = btrfs_ino(inode);
3972 u64 dir_ino = btrfs_ino(dir);
3974 path = btrfs_alloc_path();
3975 if (!path) {
3976 ret = -ENOMEM;
3977 goto out;
3980 path->leave_spinning = 1;
3981 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
3982 name, name_len, -1);
3983 if (IS_ERR(di)) {
3984 ret = PTR_ERR(di);
3985 goto err;
3987 if (!di) {
3988 ret = -ENOENT;
3989 goto err;
3991 leaf = path->nodes[0];
3992 btrfs_dir_item_key_to_cpu(leaf, di, &key);
3993 ret = btrfs_delete_one_dir_name(trans, root, path, di);
3994 if (ret)
3995 goto err;
3996 btrfs_release_path(path);
3999 * If we don't have dir index, we have to get it by looking up
4000 * the inode ref, since we get the inode ref, remove it directly,
4001 * it is unnecessary to do delayed deletion.
4003 * But if we have dir index, needn't search inode ref to get it.
4004 * Since the inode ref is close to the inode item, it is better
4005 * that we delay to delete it, and just do this deletion when
4006 * we update the inode item.
4008 if (BTRFS_I(inode)->dir_index) {
4009 ret = btrfs_delayed_delete_inode_ref(inode);
4010 if (!ret) {
4011 index = BTRFS_I(inode)->dir_index;
4012 goto skip_backref;
4016 ret = btrfs_del_inode_ref(trans, root, name, name_len, ino,
4017 dir_ino, &index);
4018 if (ret) {
4019 btrfs_info(root->fs_info,
4020 "failed to delete reference to %.*s, inode %llu parent %llu",
4021 name_len, name, ino, dir_ino);
4022 btrfs_abort_transaction(trans, root, ret);
4023 goto err;
4025 skip_backref:
4026 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4027 if (ret) {
4028 btrfs_abort_transaction(trans, root, ret);
4029 goto err;
4032 ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len,
4033 inode, dir_ino);
4034 if (ret != 0 && ret != -ENOENT) {
4035 btrfs_abort_transaction(trans, root, ret);
4036 goto err;
4039 ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len,
4040 dir, index);
4041 if (ret == -ENOENT)
4042 ret = 0;
4043 else if (ret)
4044 btrfs_abort_transaction(trans, root, ret);
4045 err:
4046 btrfs_free_path(path);
4047 if (ret)
4048 goto out;
4050 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4051 inode_inc_iversion(inode);
4052 inode_inc_iversion(dir);
4053 inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4054 ret = btrfs_update_inode(trans, root, dir);
4055 out:
4056 return ret;
4059 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4060 struct btrfs_root *root,
4061 struct inode *dir, struct inode *inode,
4062 const char *name, int name_len)
4064 int ret;
4065 ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len);
4066 if (!ret) {
4067 drop_nlink(inode);
4068 ret = btrfs_update_inode(trans, root, inode);
4070 return ret;
4074 * helper to start transaction for unlink and rmdir.
4076 * unlink and rmdir are special in btrfs, they do not always free space, so
4077 * if we cannot make our reservations the normal way try and see if there is
4078 * plenty of slack room in the global reserve to migrate, otherwise we cannot
4079 * allow the unlink to occur.
4081 static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
4083 struct btrfs_root *root = BTRFS_I(dir)->root;
4086 * 1 for the possible orphan item
4087 * 1 for the dir item
4088 * 1 for the dir index
4089 * 1 for the inode ref
4090 * 1 for the inode
4092 return btrfs_start_transaction_fallback_global_rsv(root, 5, 5);
4095 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4097 struct btrfs_root *root = BTRFS_I(dir)->root;
4098 struct btrfs_trans_handle *trans;
4099 struct inode *inode = d_inode(dentry);
4100 int ret;
4102 trans = __unlink_start_trans(dir);
4103 if (IS_ERR(trans))
4104 return PTR_ERR(trans);
4106 btrfs_record_unlink_dir(trans, dir, d_inode(dentry), 0);
4108 ret = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4109 dentry->d_name.name, dentry->d_name.len);
4110 if (ret)
4111 goto out;
4113 if (inode->i_nlink == 0) {
4114 ret = btrfs_orphan_add(trans, inode);
4115 if (ret)
4116 goto out;
4119 out:
4120 btrfs_end_transaction(trans, root);
4121 btrfs_btree_balance_dirty(root);
4122 return ret;
4125 int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4126 struct btrfs_root *root,
4127 struct inode *dir, u64 objectid,
4128 const char *name, int name_len)
4130 struct btrfs_path *path;
4131 struct extent_buffer *leaf;
4132 struct btrfs_dir_item *di;
4133 struct btrfs_key key;
4134 u64 index;
4135 int ret;
4136 u64 dir_ino = btrfs_ino(dir);
4138 path = btrfs_alloc_path();
4139 if (!path)
4140 return -ENOMEM;
4142 di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4143 name, name_len, -1);
4144 if (IS_ERR_OR_NULL(di)) {
4145 if (!di)
4146 ret = -ENOENT;
4147 else
4148 ret = PTR_ERR(di);
4149 goto out;
4152 leaf = path->nodes[0];
4153 btrfs_dir_item_key_to_cpu(leaf, di, &key);
4154 WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4155 ret = btrfs_delete_one_dir_name(trans, root, path, di);
4156 if (ret) {
4157 btrfs_abort_transaction(trans, root, ret);
4158 goto out;
4160 btrfs_release_path(path);
4162 ret = btrfs_del_root_ref(trans, root->fs_info->tree_root,
4163 objectid, root->root_key.objectid,
4164 dir_ino, &index, name, name_len);
4165 if (ret < 0) {
4166 if (ret != -ENOENT) {
4167 btrfs_abort_transaction(trans, root, ret);
4168 goto out;
4170 di = btrfs_search_dir_index_item(root, path, dir_ino,
4171 name, name_len);
4172 if (IS_ERR_OR_NULL(di)) {
4173 if (!di)
4174 ret = -ENOENT;
4175 else
4176 ret = PTR_ERR(di);
4177 btrfs_abort_transaction(trans, root, ret);
4178 goto out;
4181 leaf = path->nodes[0];
4182 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4183 btrfs_release_path(path);
4184 index = key.offset;
4186 btrfs_release_path(path);
4188 ret = btrfs_delete_delayed_dir_index(trans, root, dir, index);
4189 if (ret) {
4190 btrfs_abort_transaction(trans, root, ret);
4191 goto out;
4194 btrfs_i_size_write(dir, dir->i_size - name_len * 2);
4195 inode_inc_iversion(dir);
4196 dir->i_mtime = dir->i_ctime = CURRENT_TIME;
4197 ret = btrfs_update_inode_fallback(trans, root, dir);
4198 if (ret)
4199 btrfs_abort_transaction(trans, root, ret);
4200 out:
4201 btrfs_free_path(path);
4202 return ret;
4205 static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
4207 struct inode *inode = d_inode(dentry);
4208 int err = 0;
4209 struct btrfs_root *root = BTRFS_I(dir)->root;
4210 struct btrfs_trans_handle *trans;
4212 if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
4213 return -ENOTEMPTY;
4214 if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID)
4215 return -EPERM;
4217 trans = __unlink_start_trans(dir);
4218 if (IS_ERR(trans))
4219 return PTR_ERR(trans);
4221 if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4222 err = btrfs_unlink_subvol(trans, root, dir,
4223 BTRFS_I(inode)->location.objectid,
4224 dentry->d_name.name,
4225 dentry->d_name.len);
4226 goto out;
4229 err = btrfs_orphan_add(trans, inode);
4230 if (err)
4231 goto out;
4233 /* now the directory is empty */
4234 err = btrfs_unlink_inode(trans, root, dir, d_inode(dentry),
4235 dentry->d_name.name, dentry->d_name.len);
4236 if (!err)
4237 btrfs_i_size_write(inode, 0);
4238 out:
4239 btrfs_end_transaction(trans, root);
4240 btrfs_btree_balance_dirty(root);
4242 return err;
4245 static int truncate_space_check(struct btrfs_trans_handle *trans,
4246 struct btrfs_root *root,
4247 u64 bytes_deleted)
4249 int ret;
4251 bytes_deleted = btrfs_csum_bytes_to_leaves(root, bytes_deleted);
4252 ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv,
4253 bytes_deleted, BTRFS_RESERVE_NO_FLUSH);
4254 if (!ret)
4255 trans->bytes_reserved += bytes_deleted;
4256 return ret;
4260 static int truncate_inline_extent(struct inode *inode,
4261 struct btrfs_path *path,
4262 struct btrfs_key *found_key,
4263 const u64 item_end,
4264 const u64 new_size)
4266 struct extent_buffer *leaf = path->nodes[0];
4267 int slot = path->slots[0];
4268 struct btrfs_file_extent_item *fi;
4269 u32 size = (u32)(new_size - found_key->offset);
4270 struct btrfs_root *root = BTRFS_I(inode)->root;
4272 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
4274 if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) {
4275 loff_t offset = new_size;
4276 loff_t page_end = ALIGN(offset, PAGE_CACHE_SIZE);
4279 * Zero out the remaining of the last page of our inline extent,
4280 * instead of directly truncating our inline extent here - that
4281 * would be much more complex (decompressing all the data, then
4282 * compressing the truncated data, which might be bigger than
4283 * the size of the inline extent, resize the extent, etc).
4284 * We release the path because to get the page we might need to
4285 * read the extent item from disk (data not in the page cache).
4287 btrfs_release_path(path);
4288 return btrfs_truncate_page(inode, offset, page_end - offset, 0);
4291 btrfs_set_file_extent_ram_bytes(leaf, fi, size);
4292 size = btrfs_file_extent_calc_inline_size(size);
4293 btrfs_truncate_item(root, path, size, 1);
4295 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4296 inode_sub_bytes(inode, item_end + 1 - new_size);
4298 return 0;
4302 * this can truncate away extent items, csum items and directory items.
4303 * It starts at a high offset and removes keys until it can't find
4304 * any higher than new_size
4306 * csum items that cross the new i_size are truncated to the new size
4307 * as well.
4309 * min_type is the minimum key type to truncate down to. If set to 0, this
4310 * will kill all the items on this inode, including the INODE_ITEM_KEY.
4312 int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans,
4313 struct btrfs_root *root,
4314 struct inode *inode,
4315 u64 new_size, u32 min_type)
4317 struct btrfs_path *path;
4318 struct extent_buffer *leaf;
4319 struct btrfs_file_extent_item *fi;
4320 struct btrfs_key key;
4321 struct btrfs_key found_key;
4322 u64 extent_start = 0;
4323 u64 extent_num_bytes = 0;
4324 u64 extent_offset = 0;
4325 u64 item_end = 0;
4326 u64 last_size = new_size;
4327 u32 found_type = (u8)-1;
4328 int found_extent;
4329 int del_item;
4330 int pending_del_nr = 0;
4331 int pending_del_slot = 0;
4332 int extent_type = -1;
4333 int ret;
4334 int err = 0;
4335 u64 ino = btrfs_ino(inode);
4336 u64 bytes_deleted = 0;
4337 bool be_nice = 0;
4338 bool should_throttle = 0;
4339 bool should_end = 0;
4341 BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY);
4344 * for non-free space inodes and ref cows, we want to back off from
4345 * time to time
4347 if (!btrfs_is_free_space_inode(inode) &&
4348 test_bit(BTRFS_ROOT_REF_COWS, &root->state))
4349 be_nice = 1;
4351 path = btrfs_alloc_path();
4352 if (!path)
4353 return -ENOMEM;
4354 path->reada = -1;
4357 * We want to drop from the next block forward in case this new size is
4358 * not block aligned since we will be keeping the last block of the
4359 * extent just the way it is.
4361 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4362 root == root->fs_info->tree_root)
4363 btrfs_drop_extent_cache(inode, ALIGN(new_size,
4364 root->sectorsize), (u64)-1, 0);
4367 * This function is also used to drop the items in the log tree before
4368 * we relog the inode, so if root != BTRFS_I(inode)->root, it means
4369 * it is used to drop the loged items. So we shouldn't kill the delayed
4370 * items.
4372 if (min_type == 0 && root == BTRFS_I(inode)->root)
4373 btrfs_kill_delayed_inode_items(inode);
4375 key.objectid = ino;
4376 key.offset = (u64)-1;
4377 key.type = (u8)-1;
4379 search_again:
4381 * with a 16K leaf size and 128MB extents, you can actually queue
4382 * up a huge file in a single leaf. Most of the time that
4383 * bytes_deleted is > 0, it will be huge by the time we get here
4385 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4386 if (btrfs_should_end_transaction(trans, root)) {
4387 err = -EAGAIN;
4388 goto error;
4393 path->leave_spinning = 1;
4394 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
4395 if (ret < 0) {
4396 err = ret;
4397 goto out;
4400 if (ret > 0) {
4401 /* there are no items in the tree for us to truncate, we're
4402 * done
4404 if (path->slots[0] == 0)
4405 goto out;
4406 path->slots[0]--;
4409 while (1) {
4410 fi = NULL;
4411 leaf = path->nodes[0];
4412 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
4413 found_type = found_key.type;
4415 if (found_key.objectid != ino)
4416 break;
4418 if (found_type < min_type)
4419 break;
4421 item_end = found_key.offset;
4422 if (found_type == BTRFS_EXTENT_DATA_KEY) {
4423 fi = btrfs_item_ptr(leaf, path->slots[0],
4424 struct btrfs_file_extent_item);
4425 extent_type = btrfs_file_extent_type(leaf, fi);
4426 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4427 item_end +=
4428 btrfs_file_extent_num_bytes(leaf, fi);
4429 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4430 item_end += btrfs_file_extent_inline_len(leaf,
4431 path->slots[0], fi);
4433 item_end--;
4435 if (found_type > min_type) {
4436 del_item = 1;
4437 } else {
4438 if (item_end < new_size) {
4440 * With NO_HOLES mode, for the following mapping
4442 * [0-4k][hole][8k-12k]
4444 * if truncating isize down to 6k, it ends up
4445 * isize being 8k.
4447 if (btrfs_fs_incompat(root->fs_info, NO_HOLES))
4448 last_size = new_size;
4449 break;
4451 if (found_key.offset >= new_size)
4452 del_item = 1;
4453 else
4454 del_item = 0;
4456 found_extent = 0;
4457 /* FIXME, shrink the extent if the ref count is only 1 */
4458 if (found_type != BTRFS_EXTENT_DATA_KEY)
4459 goto delete;
4461 if (del_item)
4462 last_size = found_key.offset;
4463 else
4464 last_size = new_size;
4466 if (extent_type != BTRFS_FILE_EXTENT_INLINE) {
4467 u64 num_dec;
4468 extent_start = btrfs_file_extent_disk_bytenr(leaf, fi);
4469 if (!del_item) {
4470 u64 orig_num_bytes =
4471 btrfs_file_extent_num_bytes(leaf, fi);
4472 extent_num_bytes = ALIGN(new_size -
4473 found_key.offset,
4474 root->sectorsize);
4475 btrfs_set_file_extent_num_bytes(leaf, fi,
4476 extent_num_bytes);
4477 num_dec = (orig_num_bytes -
4478 extent_num_bytes);
4479 if (test_bit(BTRFS_ROOT_REF_COWS,
4480 &root->state) &&
4481 extent_start != 0)
4482 inode_sub_bytes(inode, num_dec);
4483 btrfs_mark_buffer_dirty(leaf);
4484 } else {
4485 extent_num_bytes =
4486 btrfs_file_extent_disk_num_bytes(leaf,
4487 fi);
4488 extent_offset = found_key.offset -
4489 btrfs_file_extent_offset(leaf, fi);
4491 /* FIXME blocksize != 4096 */
4492 num_dec = btrfs_file_extent_num_bytes(leaf, fi);
4493 if (extent_start != 0) {
4494 found_extent = 1;
4495 if (test_bit(BTRFS_ROOT_REF_COWS,
4496 &root->state))
4497 inode_sub_bytes(inode, num_dec);
4500 } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
4502 * we can't truncate inline items that have had
4503 * special encodings
4505 if (!del_item &&
4506 btrfs_file_extent_encryption(leaf, fi) == 0 &&
4507 btrfs_file_extent_other_encoding(leaf, fi) == 0) {
4510 * Need to release path in order to truncate a
4511 * compressed extent. So delete any accumulated
4512 * extent items so far.
4514 if (btrfs_file_extent_compression(leaf, fi) !=
4515 BTRFS_COMPRESS_NONE && pending_del_nr) {
4516 err = btrfs_del_items(trans, root, path,
4517 pending_del_slot,
4518 pending_del_nr);
4519 if (err) {
4520 btrfs_abort_transaction(trans,
4521 root,
4522 err);
4523 goto error;
4525 pending_del_nr = 0;
4528 err = truncate_inline_extent(inode, path,
4529 &found_key,
4530 item_end,
4531 new_size);
4532 if (err) {
4533 btrfs_abort_transaction(trans,
4534 root, err);
4535 goto error;
4537 } else if (test_bit(BTRFS_ROOT_REF_COWS,
4538 &root->state)) {
4539 inode_sub_bytes(inode, item_end + 1 - new_size);
4542 delete:
4543 if (del_item) {
4544 if (!pending_del_nr) {
4545 /* no pending yet, add ourselves */
4546 pending_del_slot = path->slots[0];
4547 pending_del_nr = 1;
4548 } else if (pending_del_nr &&
4549 path->slots[0] + 1 == pending_del_slot) {
4550 /* hop on the pending chunk */
4551 pending_del_nr++;
4552 pending_del_slot = path->slots[0];
4553 } else {
4554 BUG();
4556 } else {
4557 break;
4559 should_throttle = 0;
4561 if (found_extent &&
4562 (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4563 root == root->fs_info->tree_root)) {
4564 btrfs_set_path_blocking(path);
4565 bytes_deleted += extent_num_bytes;
4566 ret = btrfs_free_extent(trans, root, extent_start,
4567 extent_num_bytes, 0,
4568 btrfs_header_owner(leaf),
4569 ino, extent_offset);
4570 BUG_ON(ret);
4571 if (btrfs_should_throttle_delayed_refs(trans, root))
4572 btrfs_async_run_delayed_refs(root,
4573 trans->delayed_ref_updates * 2, 0);
4574 if (be_nice) {
4575 if (truncate_space_check(trans, root,
4576 extent_num_bytes)) {
4577 should_end = 1;
4579 if (btrfs_should_throttle_delayed_refs(trans,
4580 root)) {
4581 should_throttle = 1;
4586 if (found_type == BTRFS_INODE_ITEM_KEY)
4587 break;
4589 if (path->slots[0] == 0 ||
4590 path->slots[0] != pending_del_slot ||
4591 should_throttle || should_end) {
4592 if (pending_del_nr) {
4593 ret = btrfs_del_items(trans, root, path,
4594 pending_del_slot,
4595 pending_del_nr);
4596 if (ret) {
4597 btrfs_abort_transaction(trans,
4598 root, ret);
4599 goto error;
4601 pending_del_nr = 0;
4603 btrfs_release_path(path);
4604 if (should_throttle) {
4605 unsigned long updates = trans->delayed_ref_updates;
4606 if (updates) {
4607 trans->delayed_ref_updates = 0;
4608 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4609 if (ret && !err)
4610 err = ret;
4614 * if we failed to refill our space rsv, bail out
4615 * and let the transaction restart
4617 if (should_end) {
4618 err = -EAGAIN;
4619 goto error;
4621 goto search_again;
4622 } else {
4623 path->slots[0]--;
4626 out:
4627 if (pending_del_nr) {
4628 ret = btrfs_del_items(trans, root, path, pending_del_slot,
4629 pending_del_nr);
4630 if (ret)
4631 btrfs_abort_transaction(trans, root, ret);
4633 error:
4634 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID)
4635 btrfs_ordered_update_i_size(inode, last_size, NULL);
4637 btrfs_free_path(path);
4639 if (be_nice && bytes_deleted > 32 * 1024 * 1024) {
4640 unsigned long updates = trans->delayed_ref_updates;
4641 if (updates) {
4642 trans->delayed_ref_updates = 0;
4643 ret = btrfs_run_delayed_refs(trans, root, updates * 2);
4644 if (ret && !err)
4645 err = ret;
4648 return err;
4652 * btrfs_truncate_page - read, zero a chunk and write a page
4653 * @inode - inode that we're zeroing
4654 * @from - the offset to start zeroing
4655 * @len - the length to zero, 0 to zero the entire range respective to the
4656 * offset
4657 * @front - zero up to the offset instead of from the offset on
4659 * This will find the page for the "from" offset and cow the page and zero the
4660 * part we want to zero. This is used with truncate and hole punching.
4662 int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len,
4663 int front)
4665 struct address_space *mapping = inode->i_mapping;
4666 struct btrfs_root *root = BTRFS_I(inode)->root;
4667 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4668 struct btrfs_ordered_extent *ordered;
4669 struct extent_state *cached_state = NULL;
4670 char *kaddr;
4671 u32 blocksize = root->sectorsize;
4672 pgoff_t index = from >> PAGE_CACHE_SHIFT;
4673 unsigned offset = from & (PAGE_CACHE_SIZE-1);
4674 struct page *page;
4675 gfp_t mask = btrfs_alloc_write_mask(mapping);
4676 int ret = 0;
4677 u64 page_start;
4678 u64 page_end;
4680 if ((offset & (blocksize - 1)) == 0 &&
4681 (!len || ((len & (blocksize - 1)) == 0)))
4682 goto out;
4683 ret = btrfs_delalloc_reserve_space(inode,
4684 round_down(from, PAGE_CACHE_SIZE), PAGE_CACHE_SIZE);
4685 if (ret)
4686 goto out;
4688 again:
4689 page = find_or_create_page(mapping, index, mask);
4690 if (!page) {
4691 btrfs_delalloc_release_space(inode,
4692 round_down(from, PAGE_CACHE_SIZE),
4693 PAGE_CACHE_SIZE);
4694 ret = -ENOMEM;
4695 goto out;
4698 page_start = page_offset(page);
4699 page_end = page_start + PAGE_CACHE_SIZE - 1;
4701 if (!PageUptodate(page)) {
4702 ret = btrfs_readpage(NULL, page);
4703 lock_page(page);
4704 if (page->mapping != mapping) {
4705 unlock_page(page);
4706 page_cache_release(page);
4707 goto again;
4709 if (!PageUptodate(page)) {
4710 ret = -EIO;
4711 goto out_unlock;
4714 wait_on_page_writeback(page);
4716 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
4717 set_page_extent_mapped(page);
4719 ordered = btrfs_lookup_ordered_extent(inode, page_start);
4720 if (ordered) {
4721 unlock_extent_cached(io_tree, page_start, page_end,
4722 &cached_state, GFP_NOFS);
4723 unlock_page(page);
4724 page_cache_release(page);
4725 btrfs_start_ordered_extent(inode, ordered, 1);
4726 btrfs_put_ordered_extent(ordered);
4727 goto again;
4730 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
4731 EXTENT_DIRTY | EXTENT_DELALLOC |
4732 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
4733 0, 0, &cached_state, GFP_NOFS);
4735 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
4736 &cached_state);
4737 if (ret) {
4738 unlock_extent_cached(io_tree, page_start, page_end,
4739 &cached_state, GFP_NOFS);
4740 goto out_unlock;
4743 if (offset != PAGE_CACHE_SIZE) {
4744 if (!len)
4745 len = PAGE_CACHE_SIZE - offset;
4746 kaddr = kmap(page);
4747 if (front)
4748 memset(kaddr, 0, offset);
4749 else
4750 memset(kaddr + offset, 0, len);
4751 flush_dcache_page(page);
4752 kunmap(page);
4754 ClearPageChecked(page);
4755 set_page_dirty(page);
4756 unlock_extent_cached(io_tree, page_start, page_end, &cached_state,
4757 GFP_NOFS);
4759 out_unlock:
4760 if (ret)
4761 btrfs_delalloc_release_space(inode, page_start,
4762 PAGE_CACHE_SIZE);
4763 unlock_page(page);
4764 page_cache_release(page);
4765 out:
4766 return ret;
4769 static int maybe_insert_hole(struct btrfs_root *root, struct inode *inode,
4770 u64 offset, u64 len)
4772 struct btrfs_trans_handle *trans;
4773 int ret;
4776 * Still need to make sure the inode looks like it's been updated so
4777 * that any holes get logged if we fsync.
4779 if (btrfs_fs_incompat(root->fs_info, NO_HOLES)) {
4780 BTRFS_I(inode)->last_trans = root->fs_info->generation;
4781 BTRFS_I(inode)->last_sub_trans = root->log_transid;
4782 BTRFS_I(inode)->last_log_commit = root->last_log_commit;
4783 return 0;
4787 * 1 - for the one we're dropping
4788 * 1 - for the one we're adding
4789 * 1 - for updating the inode.
4791 trans = btrfs_start_transaction(root, 3);
4792 if (IS_ERR(trans))
4793 return PTR_ERR(trans);
4795 ret = btrfs_drop_extents(trans, root, inode, offset, offset + len, 1);
4796 if (ret) {
4797 btrfs_abort_transaction(trans, root, ret);
4798 btrfs_end_transaction(trans, root);
4799 return ret;
4802 ret = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), offset,
4803 0, 0, len, 0, len, 0, 0, 0);
4804 if (ret)
4805 btrfs_abort_transaction(trans, root, ret);
4806 else
4807 btrfs_update_inode(trans, root, inode);
4808 btrfs_end_transaction(trans, root);
4809 return ret;
4813 * This function puts in dummy file extents for the area we're creating a hole
4814 * for. So if we are truncating this file to a larger size we need to insert
4815 * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
4816 * the range between oldsize and size
4818 int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size)
4820 struct btrfs_root *root = BTRFS_I(inode)->root;
4821 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4822 struct extent_map *em = NULL;
4823 struct extent_state *cached_state = NULL;
4824 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
4825 u64 hole_start = ALIGN(oldsize, root->sectorsize);
4826 u64 block_end = ALIGN(size, root->sectorsize);
4827 u64 last_byte;
4828 u64 cur_offset;
4829 u64 hole_size;
4830 int err = 0;
4833 * If our size started in the middle of a page we need to zero out the
4834 * rest of the page before we expand the i_size, otherwise we could
4835 * expose stale data.
4837 err = btrfs_truncate_page(inode, oldsize, 0, 0);
4838 if (err)
4839 return err;
4841 if (size <= hole_start)
4842 return 0;
4844 while (1) {
4845 struct btrfs_ordered_extent *ordered;
4847 lock_extent_bits(io_tree, hole_start, block_end - 1, 0,
4848 &cached_state);
4849 ordered = btrfs_lookup_ordered_range(inode, hole_start,
4850 block_end - hole_start);
4851 if (!ordered)
4852 break;
4853 unlock_extent_cached(io_tree, hole_start, block_end - 1,
4854 &cached_state, GFP_NOFS);
4855 btrfs_start_ordered_extent(inode, ordered, 1);
4856 btrfs_put_ordered_extent(ordered);
4859 cur_offset = hole_start;
4860 while (1) {
4861 em = btrfs_get_extent(inode, NULL, 0, cur_offset,
4862 block_end - cur_offset, 0);
4863 if (IS_ERR(em)) {
4864 err = PTR_ERR(em);
4865 em = NULL;
4866 break;
4868 last_byte = min(extent_map_end(em), block_end);
4869 last_byte = ALIGN(last_byte , root->sectorsize);
4870 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
4871 struct extent_map *hole_em;
4872 hole_size = last_byte - cur_offset;
4874 err = maybe_insert_hole(root, inode, cur_offset,
4875 hole_size);
4876 if (err)
4877 break;
4878 btrfs_drop_extent_cache(inode, cur_offset,
4879 cur_offset + hole_size - 1, 0);
4880 hole_em = alloc_extent_map();
4881 if (!hole_em) {
4882 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
4883 &BTRFS_I(inode)->runtime_flags);
4884 goto next;
4886 hole_em->start = cur_offset;
4887 hole_em->len = hole_size;
4888 hole_em->orig_start = cur_offset;
4890 hole_em->block_start = EXTENT_MAP_HOLE;
4891 hole_em->block_len = 0;
4892 hole_em->orig_block_len = 0;
4893 hole_em->ram_bytes = hole_size;
4894 hole_em->bdev = root->fs_info->fs_devices->latest_bdev;
4895 hole_em->compress_type = BTRFS_COMPRESS_NONE;
4896 hole_em->generation = root->fs_info->generation;
4898 while (1) {
4899 write_lock(&em_tree->lock);
4900 err = add_extent_mapping(em_tree, hole_em, 1);
4901 write_unlock(&em_tree->lock);
4902 if (err != -EEXIST)
4903 break;
4904 btrfs_drop_extent_cache(inode, cur_offset,
4905 cur_offset +
4906 hole_size - 1, 0);
4908 free_extent_map(hole_em);
4910 next:
4911 free_extent_map(em);
4912 em = NULL;
4913 cur_offset = last_byte;
4914 if (cur_offset >= block_end)
4915 break;
4917 free_extent_map(em);
4918 unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state,
4919 GFP_NOFS);
4920 return err;
4923 static int wait_snapshoting_atomic_t(atomic_t *a)
4925 schedule();
4926 return 0;
4929 static void wait_for_snapshot_creation(struct btrfs_root *root)
4931 while (true) {
4932 int ret;
4934 ret = btrfs_start_write_no_snapshoting(root);
4935 if (ret)
4936 break;
4937 wait_on_atomic_t(&root->will_be_snapshoted,
4938 wait_snapshoting_atomic_t,
4939 TASK_UNINTERRUPTIBLE);
4943 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
4945 struct btrfs_root *root = BTRFS_I(inode)->root;
4946 struct btrfs_trans_handle *trans;
4947 loff_t oldsize = i_size_read(inode);
4948 loff_t newsize = attr->ia_size;
4949 int mask = attr->ia_valid;
4950 int ret;
4953 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
4954 * special case where we need to update the times despite not having
4955 * these flags set. For all other operations the VFS set these flags
4956 * explicitly if it wants a timestamp update.
4958 if (newsize != oldsize) {
4959 inode_inc_iversion(inode);
4960 if (!(mask & (ATTR_CTIME | ATTR_MTIME)))
4961 inode->i_ctime = inode->i_mtime =
4962 current_fs_time(inode->i_sb);
4965 if (newsize > oldsize) {
4966 truncate_pagecache(inode, newsize);
4968 * Don't do an expanding truncate while snapshoting is ongoing.
4969 * This is to ensure the snapshot captures a fully consistent
4970 * state of this file - if the snapshot captures this expanding
4971 * truncation, it must capture all writes that happened before
4972 * this truncation.
4974 wait_for_snapshot_creation(root);
4975 ret = btrfs_cont_expand(inode, oldsize, newsize);
4976 if (ret) {
4977 btrfs_end_write_no_snapshoting(root);
4978 return ret;
4981 trans = btrfs_start_transaction(root, 1);
4982 if (IS_ERR(trans)) {
4983 btrfs_end_write_no_snapshoting(root);
4984 return PTR_ERR(trans);
4987 i_size_write(inode, newsize);
4988 btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL);
4989 ret = btrfs_update_inode(trans, root, inode);
4990 btrfs_end_write_no_snapshoting(root);
4991 btrfs_end_transaction(trans, root);
4992 } else {
4995 * We're truncating a file that used to have good data down to
4996 * zero. Make sure it gets into the ordered flush list so that
4997 * any new writes get down to disk quickly.
4999 if (newsize == 0)
5000 set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE,
5001 &BTRFS_I(inode)->runtime_flags);
5004 * 1 for the orphan item we're going to add
5005 * 1 for the orphan item deletion.
5007 trans = btrfs_start_transaction(root, 2);
5008 if (IS_ERR(trans))
5009 return PTR_ERR(trans);
5012 * We need to do this in case we fail at _any_ point during the
5013 * actual truncate. Once we do the truncate_setsize we could
5014 * invalidate pages which forces any outstanding ordered io to
5015 * be instantly completed which will give us extents that need
5016 * to be truncated. If we fail to get an orphan inode down we
5017 * could have left over extents that were never meant to live,
5018 * so we need to garuntee from this point on that everything
5019 * will be consistent.
5021 ret = btrfs_orphan_add(trans, inode);
5022 btrfs_end_transaction(trans, root);
5023 if (ret)
5024 return ret;
5026 /* we don't support swapfiles, so vmtruncate shouldn't fail */
5027 truncate_setsize(inode, newsize);
5029 /* Disable nonlocked read DIO to avoid the end less truncate */
5030 btrfs_inode_block_unlocked_dio(inode);
5031 inode_dio_wait(inode);
5032 btrfs_inode_resume_unlocked_dio(inode);
5034 ret = btrfs_truncate(inode);
5035 if (ret && inode->i_nlink) {
5036 int err;
5039 * failed to truncate, disk_i_size is only adjusted down
5040 * as we remove extents, so it should represent the true
5041 * size of the inode, so reset the in memory size and
5042 * delete our orphan entry.
5044 trans = btrfs_join_transaction(root);
5045 if (IS_ERR(trans)) {
5046 btrfs_orphan_del(NULL, inode);
5047 return ret;
5049 i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5050 err = btrfs_orphan_del(trans, inode);
5051 if (err)
5052 btrfs_abort_transaction(trans, root, err);
5053 btrfs_end_transaction(trans, root);
5057 return ret;
5060 static int btrfs_setattr(struct dentry *dentry, struct iattr *attr)
5062 struct inode *inode = d_inode(dentry);
5063 struct btrfs_root *root = BTRFS_I(inode)->root;
5064 int err;
5066 if (btrfs_root_readonly(root))
5067 return -EROFS;
5069 err = inode_change_ok(inode, attr);
5070 if (err)
5071 return err;
5073 if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5074 err = btrfs_setsize(inode, attr);
5075 if (err)
5076 return err;
5079 if (attr->ia_valid) {
5080 setattr_copy(inode, attr);
5081 inode_inc_iversion(inode);
5082 err = btrfs_dirty_inode(inode);
5084 if (!err && attr->ia_valid & ATTR_MODE)
5085 err = posix_acl_chmod(inode, inode->i_mode);
5088 return err;
5092 * While truncating the inode pages during eviction, we get the VFS calling
5093 * btrfs_invalidatepage() against each page of the inode. This is slow because
5094 * the calls to btrfs_invalidatepage() result in a huge amount of calls to
5095 * lock_extent_bits() and clear_extent_bit(), which keep merging and splitting
5096 * extent_state structures over and over, wasting lots of time.
5098 * Therefore if the inode is being evicted, let btrfs_invalidatepage() skip all
5099 * those expensive operations on a per page basis and do only the ordered io
5100 * finishing, while we release here the extent_map and extent_state structures,
5101 * without the excessive merging and splitting.
5103 static void evict_inode_truncate_pages(struct inode *inode)
5105 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5106 struct extent_map_tree *map_tree = &BTRFS_I(inode)->extent_tree;
5107 struct rb_node *node;
5109 ASSERT(inode->i_state & I_FREEING);
5110 truncate_inode_pages_final(&inode->i_data);
5112 write_lock(&map_tree->lock);
5113 while (!RB_EMPTY_ROOT(&map_tree->map)) {
5114 struct extent_map *em;
5116 node = rb_first(&map_tree->map);
5117 em = rb_entry(node, struct extent_map, rb_node);
5118 clear_bit(EXTENT_FLAG_PINNED, &em->flags);
5119 clear_bit(EXTENT_FLAG_LOGGING, &em->flags);
5120 remove_extent_mapping(map_tree, em);
5121 free_extent_map(em);
5122 if (need_resched()) {
5123 write_unlock(&map_tree->lock);
5124 cond_resched();
5125 write_lock(&map_tree->lock);
5128 write_unlock(&map_tree->lock);
5131 * Keep looping until we have no more ranges in the io tree.
5132 * We can have ongoing bios started by readpages (called from readahead)
5133 * that have their endio callback (extent_io.c:end_bio_extent_readpage)
5134 * still in progress (unlocked the pages in the bio but did not yet
5135 * unlocked the ranges in the io tree). Therefore this means some
5136 * ranges can still be locked and eviction started because before
5137 * submitting those bios, which are executed by a separate task (work
5138 * queue kthread), inode references (inode->i_count) were not taken
5139 * (which would be dropped in the end io callback of each bio).
5140 * Therefore here we effectively end up waiting for those bios and
5141 * anyone else holding locked ranges without having bumped the inode's
5142 * reference count - if we don't do it, when they access the inode's
5143 * io_tree to unlock a range it may be too late, leading to an
5144 * use-after-free issue.
5146 spin_lock(&io_tree->lock);
5147 while (!RB_EMPTY_ROOT(&io_tree->state)) {
5148 struct extent_state *state;
5149 struct extent_state *cached_state = NULL;
5150 u64 start;
5151 u64 end;
5153 node = rb_first(&io_tree->state);
5154 state = rb_entry(node, struct extent_state, rb_node);
5155 start = state->start;
5156 end = state->end;
5157 spin_unlock(&io_tree->lock);
5159 lock_extent_bits(io_tree, start, end, 0, &cached_state);
5162 * If still has DELALLOC flag, the extent didn't reach disk,
5163 * and its reserved space won't be freed by delayed_ref.
5164 * So we need to free its reserved space here.
5165 * (Refer to comment in btrfs_invalidatepage, case 2)
5167 * Note, end is the bytenr of last byte, so we need + 1 here.
5169 if (state->state & EXTENT_DELALLOC)
5170 btrfs_qgroup_free_data(inode, start, end - start + 1);
5172 clear_extent_bit(io_tree, start, end,
5173 EXTENT_LOCKED | EXTENT_DIRTY |
5174 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
5175 EXTENT_DEFRAG, 1, 1,
5176 &cached_state, GFP_NOFS);
5178 cond_resched();
5179 spin_lock(&io_tree->lock);
5181 spin_unlock(&io_tree->lock);
5184 void btrfs_evict_inode(struct inode *inode)
5186 struct btrfs_trans_handle *trans;
5187 struct btrfs_root *root = BTRFS_I(inode)->root;
5188 struct btrfs_block_rsv *rsv, *global_rsv;
5189 int steal_from_global = 0;
5190 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
5191 int ret;
5193 trace_btrfs_inode_evict(inode);
5195 evict_inode_truncate_pages(inode);
5197 if (inode->i_nlink &&
5198 ((btrfs_root_refs(&root->root_item) != 0 &&
5199 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
5200 btrfs_is_free_space_inode(inode)))
5201 goto no_delete;
5203 if (is_bad_inode(inode)) {
5204 btrfs_orphan_del(NULL, inode);
5205 goto no_delete;
5207 /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */
5208 if (!special_file(inode->i_mode))
5209 btrfs_wait_ordered_range(inode, 0, (u64)-1);
5211 btrfs_free_io_failure_record(inode, 0, (u64)-1);
5213 if (root->fs_info->log_root_recovering) {
5214 BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
5215 &BTRFS_I(inode)->runtime_flags));
5216 goto no_delete;
5219 if (inode->i_nlink > 0) {
5220 BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5221 root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
5222 goto no_delete;
5225 ret = btrfs_commit_inode_delayed_inode(inode);
5226 if (ret) {
5227 btrfs_orphan_del(NULL, inode);
5228 goto no_delete;
5231 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
5232 if (!rsv) {
5233 btrfs_orphan_del(NULL, inode);
5234 goto no_delete;
5236 rsv->size = min_size;
5237 rsv->failfast = 1;
5238 global_rsv = &root->fs_info->global_block_rsv;
5240 btrfs_i_size_write(inode, 0);
5243 * This is a bit simpler than btrfs_truncate since we've already
5244 * reserved our space for our orphan item in the unlink, so we just
5245 * need to reserve some slack space in case we add bytes and update
5246 * inode item when doing the truncate.
5248 while (1) {
5249 ret = btrfs_block_rsv_refill(root, rsv, min_size,
5250 BTRFS_RESERVE_FLUSH_LIMIT);
5253 * Try and steal from the global reserve since we will
5254 * likely not use this space anyway, we want to try as
5255 * hard as possible to get this to work.
5257 if (ret)
5258 steal_from_global++;
5259 else
5260 steal_from_global = 0;
5261 ret = 0;
5264 * steal_from_global == 0: we reserved stuff, hooray!
5265 * steal_from_global == 1: we didn't reserve stuff, boo!
5266 * steal_from_global == 2: we've committed, still not a lot of
5267 * room but maybe we'll have room in the global reserve this
5268 * time.
5269 * steal_from_global == 3: abandon all hope!
5271 if (steal_from_global > 2) {
5272 btrfs_warn(root->fs_info,
5273 "Could not get space for a delete, will truncate on mount %d",
5274 ret);
5275 btrfs_orphan_del(NULL, inode);
5276 btrfs_free_block_rsv(root, rsv);
5277 goto no_delete;
5280 trans = btrfs_join_transaction(root);
5281 if (IS_ERR(trans)) {
5282 btrfs_orphan_del(NULL, inode);
5283 btrfs_free_block_rsv(root, rsv);
5284 goto no_delete;
5288 * We can't just steal from the global reserve, we need tomake
5289 * sure there is room to do it, if not we need to commit and try
5290 * again.
5292 if (steal_from_global) {
5293 if (!btrfs_check_space_for_delayed_refs(trans, root))
5294 ret = btrfs_block_rsv_migrate(global_rsv, rsv,
5295 min_size);
5296 else
5297 ret = -ENOSPC;
5301 * Couldn't steal from the global reserve, we have too much
5302 * pending stuff built up, commit the transaction and try it
5303 * again.
5305 if (ret) {
5306 ret = btrfs_commit_transaction(trans, root);
5307 if (ret) {
5308 btrfs_orphan_del(NULL, inode);
5309 btrfs_free_block_rsv(root, rsv);
5310 goto no_delete;
5312 continue;
5313 } else {
5314 steal_from_global = 0;
5317 trans->block_rsv = rsv;
5319 ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0);
5320 if (ret != -ENOSPC && ret != -EAGAIN)
5321 break;
5323 trans->block_rsv = &root->fs_info->trans_block_rsv;
5324 btrfs_end_transaction(trans, root);
5325 trans = NULL;
5326 btrfs_btree_balance_dirty(root);
5329 btrfs_free_block_rsv(root, rsv);
5332 * Errors here aren't a big deal, it just means we leave orphan items
5333 * in the tree. They will be cleaned up on the next mount.
5335 if (ret == 0) {
5336 trans->block_rsv = root->orphan_block_rsv;
5337 btrfs_orphan_del(trans, inode);
5338 } else {
5339 btrfs_orphan_del(NULL, inode);
5342 trans->block_rsv = &root->fs_info->trans_block_rsv;
5343 if (!(root == root->fs_info->tree_root ||
5344 root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID))
5345 btrfs_return_ino(root, btrfs_ino(inode));
5347 btrfs_end_transaction(trans, root);
5348 btrfs_btree_balance_dirty(root);
5349 no_delete:
5350 btrfs_remove_delayed_node(inode);
5351 clear_inode(inode);
5352 return;
5356 * this returns the key found in the dir entry in the location pointer.
5357 * If no dir entries were found, location->objectid is 0.
5359 static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
5360 struct btrfs_key *location)
5362 const char *name = dentry->d_name.name;
5363 int namelen = dentry->d_name.len;
5364 struct btrfs_dir_item *di;
5365 struct btrfs_path *path;
5366 struct btrfs_root *root = BTRFS_I(dir)->root;
5367 int ret = 0;
5369 path = btrfs_alloc_path();
5370 if (!path)
5371 return -ENOMEM;
5373 di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name,
5374 namelen, 0);
5375 if (IS_ERR(di))
5376 ret = PTR_ERR(di);
5378 if (IS_ERR_OR_NULL(di))
5379 goto out_err;
5381 btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5382 out:
5383 btrfs_free_path(path);
5384 return ret;
5385 out_err:
5386 location->objectid = 0;
5387 goto out;
5391 * when we hit a tree root in a directory, the btrfs part of the inode
5392 * needs to be changed to reflect the root directory of the tree root. This
5393 * is kind of like crossing a mount point.
5395 static int fixup_tree_root_location(struct btrfs_root *root,
5396 struct inode *dir,
5397 struct dentry *dentry,
5398 struct btrfs_key *location,
5399 struct btrfs_root **sub_root)
5401 struct btrfs_path *path;
5402 struct btrfs_root *new_root;
5403 struct btrfs_root_ref *ref;
5404 struct extent_buffer *leaf;
5405 struct btrfs_key key;
5406 int ret;
5407 int err = 0;
5409 path = btrfs_alloc_path();
5410 if (!path) {
5411 err = -ENOMEM;
5412 goto out;
5415 err = -ENOENT;
5416 key.objectid = BTRFS_I(dir)->root->root_key.objectid;
5417 key.type = BTRFS_ROOT_REF_KEY;
5418 key.offset = location->objectid;
5420 ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path,
5421 0, 0);
5422 if (ret) {
5423 if (ret < 0)
5424 err = ret;
5425 goto out;
5428 leaf = path->nodes[0];
5429 ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5430 if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5431 btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len)
5432 goto out;
5434 ret = memcmp_extent_buffer(leaf, dentry->d_name.name,
5435 (unsigned long)(ref + 1),
5436 dentry->d_name.len);
5437 if (ret)
5438 goto out;
5440 btrfs_release_path(path);
5442 new_root = btrfs_read_fs_root_no_name(root->fs_info, location);
5443 if (IS_ERR(new_root)) {
5444 err = PTR_ERR(new_root);
5445 goto out;
5448 *sub_root = new_root;
5449 location->objectid = btrfs_root_dirid(&new_root->root_item);
5450 location->type = BTRFS_INODE_ITEM_KEY;
5451 location->offset = 0;
5452 err = 0;
5453 out:
5454 btrfs_free_path(path);
5455 return err;
5458 static void inode_tree_add(struct inode *inode)
5460 struct btrfs_root *root = BTRFS_I(inode)->root;
5461 struct btrfs_inode *entry;
5462 struct rb_node **p;
5463 struct rb_node *parent;
5464 struct rb_node *new = &BTRFS_I(inode)->rb_node;
5465 u64 ino = btrfs_ino(inode);
5467 if (inode_unhashed(inode))
5468 return;
5469 parent = NULL;
5470 spin_lock(&root->inode_lock);
5471 p = &root->inode_tree.rb_node;
5472 while (*p) {
5473 parent = *p;
5474 entry = rb_entry(parent, struct btrfs_inode, rb_node);
5476 if (ino < btrfs_ino(&entry->vfs_inode))
5477 p = &parent->rb_left;
5478 else if (ino > btrfs_ino(&entry->vfs_inode))
5479 p = &parent->rb_right;
5480 else {
5481 WARN_ON(!(entry->vfs_inode.i_state &
5482 (I_WILL_FREE | I_FREEING)));
5483 rb_replace_node(parent, new, &root->inode_tree);
5484 RB_CLEAR_NODE(parent);
5485 spin_unlock(&root->inode_lock);
5486 return;
5489 rb_link_node(new, parent, p);
5490 rb_insert_color(new, &root->inode_tree);
5491 spin_unlock(&root->inode_lock);
5494 static void inode_tree_del(struct inode *inode)
5496 struct btrfs_root *root = BTRFS_I(inode)->root;
5497 int empty = 0;
5499 spin_lock(&root->inode_lock);
5500 if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) {
5501 rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree);
5502 RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
5503 empty = RB_EMPTY_ROOT(&root->inode_tree);
5505 spin_unlock(&root->inode_lock);
5507 if (empty && btrfs_root_refs(&root->root_item) == 0) {
5508 synchronize_srcu(&root->fs_info->subvol_srcu);
5509 spin_lock(&root->inode_lock);
5510 empty = RB_EMPTY_ROOT(&root->inode_tree);
5511 spin_unlock(&root->inode_lock);
5512 if (empty)
5513 btrfs_add_dead_root(root);
5517 void btrfs_invalidate_inodes(struct btrfs_root *root)
5519 struct rb_node *node;
5520 struct rb_node *prev;
5521 struct btrfs_inode *entry;
5522 struct inode *inode;
5523 u64 objectid = 0;
5525 if (!test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
5526 WARN_ON(btrfs_root_refs(&root->root_item) != 0);
5528 spin_lock(&root->inode_lock);
5529 again:
5530 node = root->inode_tree.rb_node;
5531 prev = NULL;
5532 while (node) {
5533 prev = node;
5534 entry = rb_entry(node, struct btrfs_inode, rb_node);
5536 if (objectid < btrfs_ino(&entry->vfs_inode))
5537 node = node->rb_left;
5538 else if (objectid > btrfs_ino(&entry->vfs_inode))
5539 node = node->rb_right;
5540 else
5541 break;
5543 if (!node) {
5544 while (prev) {
5545 entry = rb_entry(prev, struct btrfs_inode, rb_node);
5546 if (objectid <= btrfs_ino(&entry->vfs_inode)) {
5547 node = prev;
5548 break;
5550 prev = rb_next(prev);
5553 while (node) {
5554 entry = rb_entry(node, struct btrfs_inode, rb_node);
5555 objectid = btrfs_ino(&entry->vfs_inode) + 1;
5556 inode = igrab(&entry->vfs_inode);
5557 if (inode) {
5558 spin_unlock(&root->inode_lock);
5559 if (atomic_read(&inode->i_count) > 1)
5560 d_prune_aliases(inode);
5562 * btrfs_drop_inode will have it removed from
5563 * the inode cache when its usage count
5564 * hits zero.
5566 iput(inode);
5567 cond_resched();
5568 spin_lock(&root->inode_lock);
5569 goto again;
5572 if (cond_resched_lock(&root->inode_lock))
5573 goto again;
5575 node = rb_next(node);
5577 spin_unlock(&root->inode_lock);
5580 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5582 struct btrfs_iget_args *args = p;
5583 inode->i_ino = args->location->objectid;
5584 memcpy(&BTRFS_I(inode)->location, args->location,
5585 sizeof(*args->location));
5586 BTRFS_I(inode)->root = args->root;
5587 return 0;
5590 static int btrfs_find_actor(struct inode *inode, void *opaque)
5592 struct btrfs_iget_args *args = opaque;
5593 return args->location->objectid == BTRFS_I(inode)->location.objectid &&
5594 args->root == BTRFS_I(inode)->root;
5597 static struct inode *btrfs_iget_locked(struct super_block *s,
5598 struct btrfs_key *location,
5599 struct btrfs_root *root)
5601 struct inode *inode;
5602 struct btrfs_iget_args args;
5603 unsigned long hashval = btrfs_inode_hash(location->objectid, root);
5605 args.location = location;
5606 args.root = root;
5608 inode = iget5_locked(s, hashval, btrfs_find_actor,
5609 btrfs_init_locked_inode,
5610 (void *)&args);
5611 return inode;
5614 /* Get an inode object given its location and corresponding root.
5615 * Returns in *is_new if the inode was read from disk
5617 struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location,
5618 struct btrfs_root *root, int *new)
5620 struct inode *inode;
5622 inode = btrfs_iget_locked(s, location, root);
5623 if (!inode)
5624 return ERR_PTR(-ENOMEM);
5626 if (inode->i_state & I_NEW) {
5627 btrfs_read_locked_inode(inode);
5628 if (!is_bad_inode(inode)) {
5629 inode_tree_add(inode);
5630 unlock_new_inode(inode);
5631 if (new)
5632 *new = 1;
5633 } else {
5634 unlock_new_inode(inode);
5635 iput(inode);
5636 inode = ERR_PTR(-ESTALE);
5640 return inode;
5643 static struct inode *new_simple_dir(struct super_block *s,
5644 struct btrfs_key *key,
5645 struct btrfs_root *root)
5647 struct inode *inode = new_inode(s);
5649 if (!inode)
5650 return ERR_PTR(-ENOMEM);
5652 BTRFS_I(inode)->root = root;
5653 memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
5654 set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
5656 inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
5657 inode->i_op = &btrfs_dir_ro_inode_operations;
5658 inode->i_fop = &simple_dir_operations;
5659 inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5660 inode->i_mtime = CURRENT_TIME;
5661 inode->i_atime = inode->i_mtime;
5662 inode->i_ctime = inode->i_mtime;
5663 BTRFS_I(inode)->i_otime = inode->i_mtime;
5665 return inode;
5668 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5670 struct inode *inode;
5671 struct btrfs_root *root = BTRFS_I(dir)->root;
5672 struct btrfs_root *sub_root = root;
5673 struct btrfs_key location;
5674 int index;
5675 int ret = 0;
5677 if (dentry->d_name.len > BTRFS_NAME_LEN)
5678 return ERR_PTR(-ENAMETOOLONG);
5680 ret = btrfs_inode_by_name(dir, dentry, &location);
5681 if (ret < 0)
5682 return ERR_PTR(ret);
5684 if (location.objectid == 0)
5685 return ERR_PTR(-ENOENT);
5687 if (location.type == BTRFS_INODE_ITEM_KEY) {
5688 inode = btrfs_iget(dir->i_sb, &location, root, NULL);
5689 return inode;
5692 BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY);
5694 index = srcu_read_lock(&root->fs_info->subvol_srcu);
5695 ret = fixup_tree_root_location(root, dir, dentry,
5696 &location, &sub_root);
5697 if (ret < 0) {
5698 if (ret != -ENOENT)
5699 inode = ERR_PTR(ret);
5700 else
5701 inode = new_simple_dir(dir->i_sb, &location, sub_root);
5702 } else {
5703 inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL);
5705 srcu_read_unlock(&root->fs_info->subvol_srcu, index);
5707 if (!IS_ERR(inode) && root != sub_root) {
5708 down_read(&root->fs_info->cleanup_work_sem);
5709 if (!(inode->i_sb->s_flags & MS_RDONLY))
5710 ret = btrfs_orphan_cleanup(sub_root);
5711 up_read(&root->fs_info->cleanup_work_sem);
5712 if (ret) {
5713 iput(inode);
5714 inode = ERR_PTR(ret);
5718 return inode;
5721 static int btrfs_dentry_delete(const struct dentry *dentry)
5723 struct btrfs_root *root;
5724 struct inode *inode = d_inode(dentry);
5726 if (!inode && !IS_ROOT(dentry))
5727 inode = d_inode(dentry->d_parent);
5729 if (inode) {
5730 root = BTRFS_I(inode)->root;
5731 if (btrfs_root_refs(&root->root_item) == 0)
5732 return 1;
5734 if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5735 return 1;
5737 return 0;
5740 static void btrfs_dentry_release(struct dentry *dentry)
5742 kfree(dentry->d_fsdata);
5745 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5746 unsigned int flags)
5748 struct inode *inode;
5750 inode = btrfs_lookup_dentry(dir, dentry);
5751 if (IS_ERR(inode)) {
5752 if (PTR_ERR(inode) == -ENOENT)
5753 inode = NULL;
5754 else
5755 return ERR_CAST(inode);
5758 return d_splice_alias(inode, dentry);
5761 unsigned char btrfs_filetype_table[] = {
5762 DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
5765 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
5767 struct inode *inode = file_inode(file);
5768 struct btrfs_root *root = BTRFS_I(inode)->root;
5769 struct btrfs_item *item;
5770 struct btrfs_dir_item *di;
5771 struct btrfs_key key;
5772 struct btrfs_key found_key;
5773 struct btrfs_path *path;
5774 struct list_head ins_list;
5775 struct list_head del_list;
5776 int ret;
5777 struct extent_buffer *leaf;
5778 int slot;
5779 unsigned char d_type;
5780 int over = 0;
5781 u32 di_cur;
5782 u32 di_total;
5783 u32 di_len;
5784 int key_type = BTRFS_DIR_INDEX_KEY;
5785 char tmp_name[32];
5786 char *name_ptr;
5787 int name_len;
5788 int is_curr = 0; /* ctx->pos points to the current index? */
5789 bool emitted;
5791 /* FIXME, use a real flag for deciding about the key type */
5792 if (root->fs_info->tree_root == root)
5793 key_type = BTRFS_DIR_ITEM_KEY;
5795 if (!dir_emit_dots(file, ctx))
5796 return 0;
5798 path = btrfs_alloc_path();
5799 if (!path)
5800 return -ENOMEM;
5802 path->reada = 1;
5804 if (key_type == BTRFS_DIR_INDEX_KEY) {
5805 INIT_LIST_HEAD(&ins_list);
5806 INIT_LIST_HEAD(&del_list);
5807 btrfs_get_delayed_items(inode, &ins_list, &del_list);
5810 key.type = key_type;
5811 key.offset = ctx->pos;
5812 key.objectid = btrfs_ino(inode);
5814 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5815 if (ret < 0)
5816 goto err;
5818 emitted = false;
5819 while (1) {
5820 leaf = path->nodes[0];
5821 slot = path->slots[0];
5822 if (slot >= btrfs_header_nritems(leaf)) {
5823 ret = btrfs_next_leaf(root, path);
5824 if (ret < 0)
5825 goto err;
5826 else if (ret > 0)
5827 break;
5828 continue;
5831 item = btrfs_item_nr(slot);
5832 btrfs_item_key_to_cpu(leaf, &found_key, slot);
5834 if (found_key.objectid != key.objectid)
5835 break;
5836 if (found_key.type != key_type)
5837 break;
5838 if (found_key.offset < ctx->pos)
5839 goto next;
5840 if (key_type == BTRFS_DIR_INDEX_KEY &&
5841 btrfs_should_delete_dir_index(&del_list,
5842 found_key.offset))
5843 goto next;
5845 ctx->pos = found_key.offset;
5846 is_curr = 1;
5848 di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item);
5849 di_cur = 0;
5850 di_total = btrfs_item_size(leaf, item);
5852 while (di_cur < di_total) {
5853 struct btrfs_key location;
5855 if (verify_dir_item(root, leaf, di))
5856 break;
5858 name_len = btrfs_dir_name_len(leaf, di);
5859 if (name_len <= sizeof(tmp_name)) {
5860 name_ptr = tmp_name;
5861 } else {
5862 name_ptr = kmalloc(name_len, GFP_NOFS);
5863 if (!name_ptr) {
5864 ret = -ENOMEM;
5865 goto err;
5868 read_extent_buffer(leaf, name_ptr,
5869 (unsigned long)(di + 1), name_len);
5871 d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)];
5872 btrfs_dir_item_key_to_cpu(leaf, di, &location);
5875 /* is this a reference to our own snapshot? If so
5876 * skip it.
5878 * In contrast to old kernels, we insert the snapshot's
5879 * dir item and dir index after it has been created, so
5880 * we won't find a reference to our own snapshot. We
5881 * still keep the following code for backward
5882 * compatibility.
5884 if (location.type == BTRFS_ROOT_ITEM_KEY &&
5885 location.objectid == root->root_key.objectid) {
5886 over = 0;
5887 goto skip;
5889 over = !dir_emit(ctx, name_ptr, name_len,
5890 location.objectid, d_type);
5892 skip:
5893 if (name_ptr != tmp_name)
5894 kfree(name_ptr);
5896 if (over)
5897 goto nopos;
5898 emitted = true;
5899 di_len = btrfs_dir_name_len(leaf, di) +
5900 btrfs_dir_data_len(leaf, di) + sizeof(*di);
5901 di_cur += di_len;
5902 di = (struct btrfs_dir_item *)((char *)di + di_len);
5904 next:
5905 path->slots[0]++;
5908 if (key_type == BTRFS_DIR_INDEX_KEY) {
5909 if (is_curr)
5910 ctx->pos++;
5911 ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list, &emitted);
5912 if (ret)
5913 goto nopos;
5917 * If we haven't emitted any dir entry, we must not touch ctx->pos as
5918 * it was was set to the termination value in previous call. We assume
5919 * that "." and ".." were emitted if we reach this point and set the
5920 * termination value as well for an empty directory.
5922 if (ctx->pos > 2 && !emitted)
5923 goto nopos;
5925 /* Reached end of directory/root. Bump pos past the last item. */
5926 ctx->pos++;
5929 * Stop new entries from being returned after we return the last
5930 * entry.
5932 * New directory entries are assigned a strictly increasing
5933 * offset. This means that new entries created during readdir
5934 * are *guaranteed* to be seen in the future by that readdir.
5935 * This has broken buggy programs which operate on names as
5936 * they're returned by readdir. Until we re-use freed offsets
5937 * we have this hack to stop new entries from being returned
5938 * under the assumption that they'll never reach this huge
5939 * offset.
5941 * This is being careful not to overflow 32bit loff_t unless the
5942 * last entry requires it because doing so has broken 32bit apps
5943 * in the past.
5945 if (key_type == BTRFS_DIR_INDEX_KEY) {
5946 if (ctx->pos >= INT_MAX)
5947 ctx->pos = LLONG_MAX;
5948 else
5949 ctx->pos = INT_MAX;
5951 nopos:
5952 ret = 0;
5953 err:
5954 if (key_type == BTRFS_DIR_INDEX_KEY)
5955 btrfs_put_delayed_items(&ins_list, &del_list);
5956 btrfs_free_path(path);
5957 return ret;
5960 int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc)
5962 struct btrfs_root *root = BTRFS_I(inode)->root;
5963 struct btrfs_trans_handle *trans;
5964 int ret = 0;
5965 bool nolock = false;
5967 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5968 return 0;
5970 if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode))
5971 nolock = true;
5973 if (wbc->sync_mode == WB_SYNC_ALL) {
5974 if (nolock)
5975 trans = btrfs_join_transaction_nolock(root);
5976 else
5977 trans = btrfs_join_transaction(root);
5978 if (IS_ERR(trans))
5979 return PTR_ERR(trans);
5980 ret = btrfs_commit_transaction(trans, root);
5982 return ret;
5986 * This is somewhat expensive, updating the tree every time the
5987 * inode changes. But, it is most likely to find the inode in cache.
5988 * FIXME, needs more benchmarking...there are no reasons other than performance
5989 * to keep or drop this code.
5991 static int btrfs_dirty_inode(struct inode *inode)
5993 struct btrfs_root *root = BTRFS_I(inode)->root;
5994 struct btrfs_trans_handle *trans;
5995 int ret;
5997 if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
5998 return 0;
6000 trans = btrfs_join_transaction(root);
6001 if (IS_ERR(trans))
6002 return PTR_ERR(trans);
6004 ret = btrfs_update_inode(trans, root, inode);
6005 if (ret && ret == -ENOSPC) {
6006 /* whoops, lets try again with the full transaction */
6007 btrfs_end_transaction(trans, root);
6008 trans = btrfs_start_transaction(root, 1);
6009 if (IS_ERR(trans))
6010 return PTR_ERR(trans);
6012 ret = btrfs_update_inode(trans, root, inode);
6014 btrfs_end_transaction(trans, root);
6015 if (BTRFS_I(inode)->delayed_node)
6016 btrfs_balance_delayed_items(root);
6018 return ret;
6022 * This is a copy of file_update_time. We need this so we can return error on
6023 * ENOSPC for updating the inode in the case of file write and mmap writes.
6025 static int btrfs_update_time(struct inode *inode, struct timespec *now,
6026 int flags)
6028 struct btrfs_root *root = BTRFS_I(inode)->root;
6030 if (btrfs_root_readonly(root))
6031 return -EROFS;
6033 if (flags & S_VERSION)
6034 inode_inc_iversion(inode);
6035 if (flags & S_CTIME)
6036 inode->i_ctime = *now;
6037 if (flags & S_MTIME)
6038 inode->i_mtime = *now;
6039 if (flags & S_ATIME)
6040 inode->i_atime = *now;
6041 return btrfs_dirty_inode(inode);
6045 * find the highest existing sequence number in a directory
6046 * and then set the in-memory index_cnt variable to reflect
6047 * free sequence numbers
6049 static int btrfs_set_inode_index_count(struct inode *inode)
6051 struct btrfs_root *root = BTRFS_I(inode)->root;
6052 struct btrfs_key key, found_key;
6053 struct btrfs_path *path;
6054 struct extent_buffer *leaf;
6055 int ret;
6057 key.objectid = btrfs_ino(inode);
6058 key.type = BTRFS_DIR_INDEX_KEY;
6059 key.offset = (u64)-1;
6061 path = btrfs_alloc_path();
6062 if (!path)
6063 return -ENOMEM;
6065 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6066 if (ret < 0)
6067 goto out;
6068 /* FIXME: we should be able to handle this */
6069 if (ret == 0)
6070 goto out;
6071 ret = 0;
6074 * MAGIC NUMBER EXPLANATION:
6075 * since we search a directory based on f_pos we have to start at 2
6076 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody
6077 * else has to start at 2
6079 if (path->slots[0] == 0) {
6080 BTRFS_I(inode)->index_cnt = 2;
6081 goto out;
6084 path->slots[0]--;
6086 leaf = path->nodes[0];
6087 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6089 if (found_key.objectid != btrfs_ino(inode) ||
6090 found_key.type != BTRFS_DIR_INDEX_KEY) {
6091 BTRFS_I(inode)->index_cnt = 2;
6092 goto out;
6095 BTRFS_I(inode)->index_cnt = found_key.offset + 1;
6096 out:
6097 btrfs_free_path(path);
6098 return ret;
6102 * helper to find a free sequence number in a given directory. This current
6103 * code is very simple, later versions will do smarter things in the btree
6105 int btrfs_set_inode_index(struct inode *dir, u64 *index)
6107 int ret = 0;
6109 if (BTRFS_I(dir)->index_cnt == (u64)-1) {
6110 ret = btrfs_inode_delayed_dir_index_count(dir);
6111 if (ret) {
6112 ret = btrfs_set_inode_index_count(dir);
6113 if (ret)
6114 return ret;
6118 *index = BTRFS_I(dir)->index_cnt;
6119 BTRFS_I(dir)->index_cnt++;
6121 return ret;
6124 static int btrfs_insert_inode_locked(struct inode *inode)
6126 struct btrfs_iget_args args;
6127 args.location = &BTRFS_I(inode)->location;
6128 args.root = BTRFS_I(inode)->root;
6130 return insert_inode_locked4(inode,
6131 btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6132 btrfs_find_actor, &args);
6135 static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans,
6136 struct btrfs_root *root,
6137 struct inode *dir,
6138 const char *name, int name_len,
6139 u64 ref_objectid, u64 objectid,
6140 umode_t mode, u64 *index)
6142 struct inode *inode;
6143 struct btrfs_inode_item *inode_item;
6144 struct btrfs_key *location;
6145 struct btrfs_path *path;
6146 struct btrfs_inode_ref *ref;
6147 struct btrfs_key key[2];
6148 u32 sizes[2];
6149 int nitems = name ? 2 : 1;
6150 unsigned long ptr;
6151 int ret;
6153 path = btrfs_alloc_path();
6154 if (!path)
6155 return ERR_PTR(-ENOMEM);
6157 inode = new_inode(root->fs_info->sb);
6158 if (!inode) {
6159 btrfs_free_path(path);
6160 return ERR_PTR(-ENOMEM);
6164 * O_TMPFILE, set link count to 0, so that after this point,
6165 * we fill in an inode item with the correct link count.
6167 if (!name)
6168 set_nlink(inode, 0);
6171 * we have to initialize this early, so we can reclaim the inode
6172 * number if we fail afterwards in this function.
6174 inode->i_ino = objectid;
6176 if (dir && name) {
6177 trace_btrfs_inode_request(dir);
6179 ret = btrfs_set_inode_index(dir, index);
6180 if (ret) {
6181 btrfs_free_path(path);
6182 iput(inode);
6183 return ERR_PTR(ret);
6185 } else if (dir) {
6186 *index = 0;
6189 * index_cnt is ignored for everything but a dir,
6190 * btrfs_get_inode_index_count has an explanation for the magic
6191 * number
6193 BTRFS_I(inode)->index_cnt = 2;
6194 BTRFS_I(inode)->dir_index = *index;
6195 BTRFS_I(inode)->root = root;
6196 BTRFS_I(inode)->generation = trans->transid;
6197 inode->i_generation = BTRFS_I(inode)->generation;
6200 * We could have gotten an inode number from somebody who was fsynced
6201 * and then removed in this same transaction, so let's just set full
6202 * sync since it will be a full sync anyway and this will blow away the
6203 * old info in the log.
6205 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
6207 key[0].objectid = objectid;
6208 key[0].type = BTRFS_INODE_ITEM_KEY;
6209 key[0].offset = 0;
6211 sizes[0] = sizeof(struct btrfs_inode_item);
6213 if (name) {
6215 * Start new inodes with an inode_ref. This is slightly more
6216 * efficient for small numbers of hard links since they will
6217 * be packed into one item. Extended refs will kick in if we
6218 * add more hard links than can fit in the ref item.
6220 key[1].objectid = objectid;
6221 key[1].type = BTRFS_INODE_REF_KEY;
6222 key[1].offset = ref_objectid;
6224 sizes[1] = name_len + sizeof(*ref);
6227 location = &BTRFS_I(inode)->location;
6228 location->objectid = objectid;
6229 location->offset = 0;
6230 location->type = BTRFS_INODE_ITEM_KEY;
6232 ret = btrfs_insert_inode_locked(inode);
6233 if (ret < 0)
6234 goto fail;
6236 path->leave_spinning = 1;
6237 ret = btrfs_insert_empty_items(trans, root, path, key, sizes, nitems);
6238 if (ret != 0)
6239 goto fail_unlock;
6241 inode_init_owner(inode, dir, mode);
6242 inode_set_bytes(inode, 0);
6244 inode->i_mtime = CURRENT_TIME;
6245 inode->i_atime = inode->i_mtime;
6246 inode->i_ctime = inode->i_mtime;
6247 BTRFS_I(inode)->i_otime = inode->i_mtime;
6249 inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6250 struct btrfs_inode_item);
6251 memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item,
6252 sizeof(*inode_item));
6253 fill_inode_item(trans, path->nodes[0], inode_item, inode);
6255 if (name) {
6256 ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6257 struct btrfs_inode_ref);
6258 btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len);
6259 btrfs_set_inode_ref_index(path->nodes[0], ref, *index);
6260 ptr = (unsigned long)(ref + 1);
6261 write_extent_buffer(path->nodes[0], name, ptr, name_len);
6264 btrfs_mark_buffer_dirty(path->nodes[0]);
6265 btrfs_free_path(path);
6267 btrfs_inherit_iflags(inode, dir);
6269 if (S_ISREG(mode)) {
6270 if (btrfs_test_opt(root, NODATASUM))
6271 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6272 if (btrfs_test_opt(root, NODATACOW))
6273 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6274 BTRFS_INODE_NODATASUM;
6277 inode_tree_add(inode);
6279 trace_btrfs_inode_new(inode);
6280 btrfs_set_inode_last_trans(trans, inode);
6282 btrfs_update_root_times(trans, root);
6284 ret = btrfs_inode_inherit_props(trans, inode, dir);
6285 if (ret)
6286 btrfs_err(root->fs_info,
6287 "error inheriting props for ino %llu (root %llu): %d",
6288 btrfs_ino(inode), root->root_key.objectid, ret);
6290 return inode;
6292 fail_unlock:
6293 unlock_new_inode(inode);
6294 fail:
6295 if (dir && name)
6296 BTRFS_I(dir)->index_cnt--;
6297 btrfs_free_path(path);
6298 iput(inode);
6299 return ERR_PTR(ret);
6302 static inline u8 btrfs_inode_type(struct inode *inode)
6304 return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT];
6308 * utility function to add 'inode' into 'parent_inode' with
6309 * a give name and a given sequence number.
6310 * if 'add_backref' is true, also insert a backref from the
6311 * inode to the parent directory.
6313 int btrfs_add_link(struct btrfs_trans_handle *trans,
6314 struct inode *parent_inode, struct inode *inode,
6315 const char *name, int name_len, int add_backref, u64 index)
6317 int ret = 0;
6318 struct btrfs_key key;
6319 struct btrfs_root *root = BTRFS_I(parent_inode)->root;
6320 u64 ino = btrfs_ino(inode);
6321 u64 parent_ino = btrfs_ino(parent_inode);
6323 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6324 memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key));
6325 } else {
6326 key.objectid = ino;
6327 key.type = BTRFS_INODE_ITEM_KEY;
6328 key.offset = 0;
6331 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6332 ret = btrfs_add_root_ref(trans, root->fs_info->tree_root,
6333 key.objectid, root->root_key.objectid,
6334 parent_ino, index, name, name_len);
6335 } else if (add_backref) {
6336 ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino,
6337 parent_ino, index);
6340 /* Nothing to clean up yet */
6341 if (ret)
6342 return ret;
6344 ret = btrfs_insert_dir_item(trans, root, name, name_len,
6345 parent_inode, &key,
6346 btrfs_inode_type(inode), index);
6347 if (ret == -EEXIST || ret == -EOVERFLOW)
6348 goto fail_dir_item;
6349 else if (ret) {
6350 btrfs_abort_transaction(trans, root, ret);
6351 return ret;
6354 btrfs_i_size_write(parent_inode, parent_inode->i_size +
6355 name_len * 2);
6356 inode_inc_iversion(parent_inode);
6357 parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME;
6358 ret = btrfs_update_inode(trans, root, parent_inode);
6359 if (ret)
6360 btrfs_abort_transaction(trans, root, ret);
6361 return ret;
6363 fail_dir_item:
6364 if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6365 u64 local_index;
6366 int err;
6367 err = btrfs_del_root_ref(trans, root->fs_info->tree_root,
6368 key.objectid, root->root_key.objectid,
6369 parent_ino, &local_index, name, name_len);
6371 } else if (add_backref) {
6372 u64 local_index;
6373 int err;
6375 err = btrfs_del_inode_ref(trans, root, name, name_len,
6376 ino, parent_ino, &local_index);
6378 return ret;
6381 static int btrfs_add_nondir(struct btrfs_trans_handle *trans,
6382 struct inode *dir, struct dentry *dentry,
6383 struct inode *inode, int backref, u64 index)
6385 int err = btrfs_add_link(trans, dir, inode,
6386 dentry->d_name.name, dentry->d_name.len,
6387 backref, index);
6388 if (err > 0)
6389 err = -EEXIST;
6390 return err;
6393 static int btrfs_mknod(struct inode *dir, struct dentry *dentry,
6394 umode_t mode, dev_t rdev)
6396 struct btrfs_trans_handle *trans;
6397 struct btrfs_root *root = BTRFS_I(dir)->root;
6398 struct inode *inode = NULL;
6399 int err;
6400 int drop_inode = 0;
6401 u64 objectid;
6402 u64 index = 0;
6405 * 2 for inode item and ref
6406 * 2 for dir items
6407 * 1 for xattr if selinux is on
6409 trans = btrfs_start_transaction(root, 5);
6410 if (IS_ERR(trans))
6411 return PTR_ERR(trans);
6413 err = btrfs_find_free_ino(root, &objectid);
6414 if (err)
6415 goto out_unlock;
6417 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6418 dentry->d_name.len, btrfs_ino(dir), objectid,
6419 mode, &index);
6420 if (IS_ERR(inode)) {
6421 err = PTR_ERR(inode);
6422 goto out_unlock;
6426 * If the active LSM wants to access the inode during
6427 * d_instantiate it needs these. Smack checks to see
6428 * if the filesystem supports xattrs by looking at the
6429 * ops vector.
6431 inode->i_op = &btrfs_special_inode_operations;
6432 init_special_inode(inode, inode->i_mode, rdev);
6434 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6435 if (err)
6436 goto out_unlock_inode;
6438 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6439 if (err) {
6440 goto out_unlock_inode;
6441 } else {
6442 btrfs_update_inode(trans, root, inode);
6443 d_instantiate_new(dentry, inode);
6446 out_unlock:
6447 btrfs_end_transaction(trans, root);
6448 btrfs_balance_delayed_items(root);
6449 btrfs_btree_balance_dirty(root);
6450 if (drop_inode) {
6451 inode_dec_link_count(inode);
6452 iput(inode);
6454 return err;
6456 out_unlock_inode:
6457 drop_inode = 1;
6458 unlock_new_inode(inode);
6459 goto out_unlock;
6463 static int btrfs_create(struct inode *dir, struct dentry *dentry,
6464 umode_t mode, bool excl)
6466 struct btrfs_trans_handle *trans;
6467 struct btrfs_root *root = BTRFS_I(dir)->root;
6468 struct inode *inode = NULL;
6469 int drop_inode_on_err = 0;
6470 int err;
6471 u64 objectid;
6472 u64 index = 0;
6475 * 2 for inode item and ref
6476 * 2 for dir items
6477 * 1 for xattr if selinux is on
6479 trans = btrfs_start_transaction(root, 5);
6480 if (IS_ERR(trans))
6481 return PTR_ERR(trans);
6483 err = btrfs_find_free_ino(root, &objectid);
6484 if (err)
6485 goto out_unlock;
6487 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6488 dentry->d_name.len, btrfs_ino(dir), objectid,
6489 mode, &index);
6490 if (IS_ERR(inode)) {
6491 err = PTR_ERR(inode);
6492 goto out_unlock;
6494 drop_inode_on_err = 1;
6496 * If the active LSM wants to access the inode during
6497 * d_instantiate it needs these. Smack checks to see
6498 * if the filesystem supports xattrs by looking at the
6499 * ops vector.
6501 inode->i_fop = &btrfs_file_operations;
6502 inode->i_op = &btrfs_file_inode_operations;
6503 inode->i_mapping->a_ops = &btrfs_aops;
6505 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6506 if (err)
6507 goto out_unlock_inode;
6509 err = btrfs_update_inode(trans, root, inode);
6510 if (err)
6511 goto out_unlock_inode;
6513 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
6514 if (err)
6515 goto out_unlock_inode;
6517 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
6518 d_instantiate_new(dentry, inode);
6520 out_unlock:
6521 btrfs_end_transaction(trans, root);
6522 if (err && drop_inode_on_err) {
6523 inode_dec_link_count(inode);
6524 iput(inode);
6526 btrfs_balance_delayed_items(root);
6527 btrfs_btree_balance_dirty(root);
6528 return err;
6530 out_unlock_inode:
6531 unlock_new_inode(inode);
6532 goto out_unlock;
6536 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6537 struct dentry *dentry)
6539 struct btrfs_trans_handle *trans = NULL;
6540 struct btrfs_root *root = BTRFS_I(dir)->root;
6541 struct inode *inode = d_inode(old_dentry);
6542 u64 index;
6543 int err;
6544 int drop_inode = 0;
6546 /* do not allow sys_link's with other subvols of the same device */
6547 if (root->objectid != BTRFS_I(inode)->root->objectid)
6548 return -EXDEV;
6550 if (inode->i_nlink >= BTRFS_LINK_MAX)
6551 return -EMLINK;
6553 err = btrfs_set_inode_index(dir, &index);
6554 if (err)
6555 goto fail;
6558 * 2 items for inode and inode ref
6559 * 2 items for dir items
6560 * 1 item for parent inode
6562 trans = btrfs_start_transaction(root, 5);
6563 if (IS_ERR(trans)) {
6564 err = PTR_ERR(trans);
6565 trans = NULL;
6566 goto fail;
6569 /* There are several dir indexes for this inode, clear the cache. */
6570 BTRFS_I(inode)->dir_index = 0ULL;
6571 inc_nlink(inode);
6572 inode_inc_iversion(inode);
6573 inode->i_ctime = CURRENT_TIME;
6574 ihold(inode);
6575 set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
6577 err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index);
6579 if (err) {
6580 drop_inode = 1;
6581 } else {
6582 struct dentry *parent = dentry->d_parent;
6583 err = btrfs_update_inode(trans, root, inode);
6584 if (err)
6585 goto fail;
6586 if (inode->i_nlink == 1) {
6588 * If new hard link count is 1, it's a file created
6589 * with open(2) O_TMPFILE flag.
6591 err = btrfs_orphan_del(trans, inode);
6592 if (err)
6593 goto fail;
6595 d_instantiate(dentry, inode);
6596 btrfs_log_new_name(trans, inode, NULL, parent);
6599 btrfs_balance_delayed_items(root);
6600 fail:
6601 if (trans)
6602 btrfs_end_transaction(trans, root);
6603 if (drop_inode) {
6604 inode_dec_link_count(inode);
6605 iput(inode);
6607 btrfs_btree_balance_dirty(root);
6608 return err;
6611 static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
6613 struct inode *inode = NULL;
6614 struct btrfs_trans_handle *trans;
6615 struct btrfs_root *root = BTRFS_I(dir)->root;
6616 int err = 0;
6617 int drop_on_err = 0;
6618 u64 objectid = 0;
6619 u64 index = 0;
6622 * 2 items for inode and ref
6623 * 2 items for dir items
6624 * 1 for xattr if selinux is on
6626 trans = btrfs_start_transaction(root, 5);
6627 if (IS_ERR(trans))
6628 return PTR_ERR(trans);
6630 err = btrfs_find_free_ino(root, &objectid);
6631 if (err)
6632 goto out_fail;
6634 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
6635 dentry->d_name.len, btrfs_ino(dir), objectid,
6636 S_IFDIR | mode, &index);
6637 if (IS_ERR(inode)) {
6638 err = PTR_ERR(inode);
6639 goto out_fail;
6642 drop_on_err = 1;
6643 /* these must be set before we unlock the inode */
6644 inode->i_op = &btrfs_dir_inode_operations;
6645 inode->i_fop = &btrfs_dir_file_operations;
6647 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
6648 if (err)
6649 goto out_fail_inode;
6651 btrfs_i_size_write(inode, 0);
6652 err = btrfs_update_inode(trans, root, inode);
6653 if (err)
6654 goto out_fail_inode;
6656 err = btrfs_add_link(trans, dir, inode, dentry->d_name.name,
6657 dentry->d_name.len, 0, index);
6658 if (err)
6659 goto out_fail_inode;
6661 d_instantiate_new(dentry, inode);
6662 drop_on_err = 0;
6664 out_fail:
6665 btrfs_end_transaction(trans, root);
6666 if (drop_on_err) {
6667 inode_dec_link_count(inode);
6668 iput(inode);
6670 btrfs_balance_delayed_items(root);
6671 btrfs_btree_balance_dirty(root);
6672 return err;
6674 out_fail_inode:
6675 unlock_new_inode(inode);
6676 goto out_fail;
6679 /* Find next extent map of a given extent map, caller needs to ensure locks */
6680 static struct extent_map *next_extent_map(struct extent_map *em)
6682 struct rb_node *next;
6684 next = rb_next(&em->rb_node);
6685 if (!next)
6686 return NULL;
6687 return container_of(next, struct extent_map, rb_node);
6690 static struct extent_map *prev_extent_map(struct extent_map *em)
6692 struct rb_node *prev;
6694 prev = rb_prev(&em->rb_node);
6695 if (!prev)
6696 return NULL;
6697 return container_of(prev, struct extent_map, rb_node);
6700 /* helper for btfs_get_extent. Given an existing extent in the tree,
6701 * the existing extent is the nearest extent to map_start,
6702 * and an extent that you want to insert, deal with overlap and insert
6703 * the best fitted new extent into the tree.
6705 static int merge_extent_mapping(struct extent_map_tree *em_tree,
6706 struct extent_map *existing,
6707 struct extent_map *em,
6708 u64 map_start)
6710 struct extent_map *prev;
6711 struct extent_map *next;
6712 u64 start;
6713 u64 end;
6714 u64 start_diff;
6716 BUG_ON(map_start < em->start || map_start >= extent_map_end(em));
6718 if (existing->start > map_start) {
6719 next = existing;
6720 prev = prev_extent_map(next);
6721 } else {
6722 prev = existing;
6723 next = next_extent_map(prev);
6726 start = prev ? extent_map_end(prev) : em->start;
6727 start = max_t(u64, start, em->start);
6728 end = next ? next->start : extent_map_end(em);
6729 end = min_t(u64, end, extent_map_end(em));
6730 start_diff = start - em->start;
6731 em->start = start;
6732 em->len = end - start;
6733 if (em->block_start < EXTENT_MAP_LAST_BYTE &&
6734 !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
6735 em->block_start += start_diff;
6736 em->block_len -= start_diff;
6738 return add_extent_mapping(em_tree, em, 0);
6741 static noinline int uncompress_inline(struct btrfs_path *path,
6742 struct inode *inode, struct page *page,
6743 size_t pg_offset, u64 extent_offset,
6744 struct btrfs_file_extent_item *item)
6746 int ret;
6747 struct extent_buffer *leaf = path->nodes[0];
6748 char *tmp;
6749 size_t max_size;
6750 unsigned long inline_size;
6751 unsigned long ptr;
6752 int compress_type;
6754 WARN_ON(pg_offset != 0);
6755 compress_type = btrfs_file_extent_compression(leaf, item);
6756 max_size = btrfs_file_extent_ram_bytes(leaf, item);
6757 inline_size = btrfs_file_extent_inline_item_len(leaf,
6758 btrfs_item_nr(path->slots[0]));
6759 tmp = kmalloc(inline_size, GFP_NOFS);
6760 if (!tmp)
6761 return -ENOMEM;
6762 ptr = btrfs_file_extent_inline_start(item);
6764 read_extent_buffer(leaf, tmp, ptr, inline_size);
6766 max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size);
6767 ret = btrfs_decompress(compress_type, tmp, page,
6768 extent_offset, inline_size, max_size);
6771 * decompression code contains a memset to fill in any space between the end
6772 * of the uncompressed data and the end of max_size in case the decompressed
6773 * data ends up shorter than ram_bytes. That doesn't cover the hole between
6774 * the end of an inline extent and the beginning of the next block, so we
6775 * cover that region here.
6778 if (max_size + pg_offset < PAGE_SIZE) {
6779 char *map = kmap(page);
6780 memset(map + pg_offset + max_size, 0, PAGE_SIZE - max_size - pg_offset);
6781 kunmap(page);
6783 kfree(tmp);
6784 return ret;
6788 * a bit scary, this does extent mapping from logical file offset to the disk.
6789 * the ugly parts come from merging extents from the disk with the in-ram
6790 * representation. This gets more complex because of the data=ordered code,
6791 * where the in-ram extents might be locked pending data=ordered completion.
6793 * This also copies inline extents directly into the page.
6796 struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page,
6797 size_t pg_offset, u64 start, u64 len,
6798 int create)
6800 int ret;
6801 int err = 0;
6802 u64 extent_start = 0;
6803 u64 extent_end = 0;
6804 u64 objectid = btrfs_ino(inode);
6805 u32 found_type;
6806 struct btrfs_path *path = NULL;
6807 struct btrfs_root *root = BTRFS_I(inode)->root;
6808 struct btrfs_file_extent_item *item;
6809 struct extent_buffer *leaf;
6810 struct btrfs_key found_key;
6811 struct extent_map *em = NULL;
6812 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
6813 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6814 struct btrfs_trans_handle *trans = NULL;
6815 const bool new_inline = !page || create;
6817 again:
6818 read_lock(&em_tree->lock);
6819 em = lookup_extent_mapping(em_tree, start, len);
6820 if (em)
6821 em->bdev = root->fs_info->fs_devices->latest_bdev;
6822 read_unlock(&em_tree->lock);
6824 if (em) {
6825 if (em->start > start || em->start + em->len <= start)
6826 free_extent_map(em);
6827 else if (em->block_start == EXTENT_MAP_INLINE && page)
6828 free_extent_map(em);
6829 else
6830 goto out;
6832 em = alloc_extent_map();
6833 if (!em) {
6834 err = -ENOMEM;
6835 goto out;
6837 em->bdev = root->fs_info->fs_devices->latest_bdev;
6838 em->start = EXTENT_MAP_HOLE;
6839 em->orig_start = EXTENT_MAP_HOLE;
6840 em->len = (u64)-1;
6841 em->block_len = (u64)-1;
6843 if (!path) {
6844 path = btrfs_alloc_path();
6845 if (!path) {
6846 err = -ENOMEM;
6847 goto out;
6850 * Chances are we'll be called again, so go ahead and do
6851 * readahead
6853 path->reada = 1;
6856 ret = btrfs_lookup_file_extent(trans, root, path,
6857 objectid, start, trans != NULL);
6858 if (ret < 0) {
6859 err = ret;
6860 goto out;
6863 if (ret != 0) {
6864 if (path->slots[0] == 0)
6865 goto not_found;
6866 path->slots[0]--;
6869 leaf = path->nodes[0];
6870 item = btrfs_item_ptr(leaf, path->slots[0],
6871 struct btrfs_file_extent_item);
6872 /* are we inside the extent that was found? */
6873 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6874 found_type = found_key.type;
6875 if (found_key.objectid != objectid ||
6876 found_type != BTRFS_EXTENT_DATA_KEY) {
6878 * If we backup past the first extent we want to move forward
6879 * and see if there is an extent in front of us, otherwise we'll
6880 * say there is a hole for our whole search range which can
6881 * cause problems.
6883 extent_end = start;
6884 goto next;
6887 found_type = btrfs_file_extent_type(leaf, item);
6888 extent_start = found_key.offset;
6889 if (found_type == BTRFS_FILE_EXTENT_REG ||
6890 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6891 extent_end = extent_start +
6892 btrfs_file_extent_num_bytes(leaf, item);
6893 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6894 size_t size;
6895 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6896 extent_end = ALIGN(extent_start + size, root->sectorsize);
6898 next:
6899 if (start >= extent_end) {
6900 path->slots[0]++;
6901 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
6902 ret = btrfs_next_leaf(root, path);
6903 if (ret < 0) {
6904 err = ret;
6905 goto out;
6907 if (ret > 0)
6908 goto not_found;
6909 leaf = path->nodes[0];
6911 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6912 if (found_key.objectid != objectid ||
6913 found_key.type != BTRFS_EXTENT_DATA_KEY)
6914 goto not_found;
6915 if (start + len <= found_key.offset)
6916 goto not_found;
6917 if (start > found_key.offset)
6918 goto next;
6919 em->start = start;
6920 em->orig_start = start;
6921 em->len = found_key.offset - start;
6922 goto not_found_em;
6925 btrfs_extent_item_to_extent_map(inode, path, item, new_inline, em);
6927 if (found_type == BTRFS_FILE_EXTENT_REG ||
6928 found_type == BTRFS_FILE_EXTENT_PREALLOC) {
6929 goto insert;
6930 } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
6931 unsigned long ptr;
6932 char *map;
6933 size_t size;
6934 size_t extent_offset;
6935 size_t copy_size;
6937 if (new_inline)
6938 goto out;
6940 size = btrfs_file_extent_inline_len(leaf, path->slots[0], item);
6941 extent_offset = page_offset(page) + pg_offset - extent_start;
6942 copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset,
6943 size - extent_offset);
6944 em->start = extent_start + extent_offset;
6945 em->len = ALIGN(copy_size, root->sectorsize);
6946 em->orig_block_len = em->len;
6947 em->orig_start = em->start;
6948 ptr = btrfs_file_extent_inline_start(item) + extent_offset;
6949 if (create == 0 && !PageUptodate(page)) {
6950 if (btrfs_file_extent_compression(leaf, item) !=
6951 BTRFS_COMPRESS_NONE) {
6952 ret = uncompress_inline(path, inode, page,
6953 pg_offset,
6954 extent_offset, item);
6955 if (ret) {
6956 err = ret;
6957 goto out;
6959 } else {
6960 map = kmap(page);
6961 read_extent_buffer(leaf, map + pg_offset, ptr,
6962 copy_size);
6963 if (pg_offset + copy_size < PAGE_CACHE_SIZE) {
6964 memset(map + pg_offset + copy_size, 0,
6965 PAGE_CACHE_SIZE - pg_offset -
6966 copy_size);
6968 kunmap(page);
6970 flush_dcache_page(page);
6971 } else if (create && PageUptodate(page)) {
6972 BUG();
6973 if (!trans) {
6974 kunmap(page);
6975 free_extent_map(em);
6976 em = NULL;
6978 btrfs_release_path(path);
6979 trans = btrfs_join_transaction(root);
6981 if (IS_ERR(trans))
6982 return ERR_CAST(trans);
6983 goto again;
6985 map = kmap(page);
6986 write_extent_buffer(leaf, map + pg_offset, ptr,
6987 copy_size);
6988 kunmap(page);
6989 btrfs_mark_buffer_dirty(leaf);
6991 set_extent_uptodate(io_tree, em->start,
6992 extent_map_end(em) - 1, NULL, GFP_NOFS);
6993 goto insert;
6995 not_found:
6996 em->start = start;
6997 em->orig_start = start;
6998 em->len = len;
6999 not_found_em:
7000 em->block_start = EXTENT_MAP_HOLE;
7001 set_bit(EXTENT_FLAG_VACANCY, &em->flags);
7002 insert:
7003 btrfs_release_path(path);
7004 if (em->start > start || extent_map_end(em) <= start) {
7005 btrfs_err(root->fs_info, "bad extent! em: [%llu %llu] passed [%llu %llu]",
7006 em->start, em->len, start, len);
7007 err = -EIO;
7008 goto out;
7011 err = 0;
7012 write_lock(&em_tree->lock);
7013 ret = add_extent_mapping(em_tree, em, 0);
7014 /* it is possible that someone inserted the extent into the tree
7015 * while we had the lock dropped. It is also possible that
7016 * an overlapping map exists in the tree
7018 if (ret == -EEXIST) {
7019 struct extent_map *existing;
7021 ret = 0;
7023 existing = search_extent_mapping(em_tree, start, len);
7025 * existing will always be non-NULL, since there must be
7026 * extent causing the -EEXIST.
7028 if (start >= extent_map_end(existing) ||
7029 start <= existing->start) {
7031 * The existing extent map is the one nearest to
7032 * the [start, start + len) range which overlaps
7034 err = merge_extent_mapping(em_tree, existing,
7035 em, start);
7036 free_extent_map(existing);
7037 if (err) {
7038 free_extent_map(em);
7039 em = NULL;
7041 } else {
7042 free_extent_map(em);
7043 em = existing;
7044 err = 0;
7047 write_unlock(&em_tree->lock);
7048 out:
7050 trace_btrfs_get_extent(root, em);
7052 btrfs_free_path(path);
7053 if (trans) {
7054 ret = btrfs_end_transaction(trans, root);
7055 if (!err)
7056 err = ret;
7058 if (err) {
7059 free_extent_map(em);
7060 return ERR_PTR(err);
7062 BUG_ON(!em); /* Error is always set */
7063 return em;
7066 struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page,
7067 size_t pg_offset, u64 start, u64 len,
7068 int create)
7070 struct extent_map *em;
7071 struct extent_map *hole_em = NULL;
7072 u64 range_start = start;
7073 u64 end;
7074 u64 found;
7075 u64 found_end;
7076 int err = 0;
7078 em = btrfs_get_extent(inode, page, pg_offset, start, len, create);
7079 if (IS_ERR(em))
7080 return em;
7081 if (em) {
7083 * if our em maps to
7084 * - a hole or
7085 * - a pre-alloc extent,
7086 * there might actually be delalloc bytes behind it.
7088 if (em->block_start != EXTENT_MAP_HOLE &&
7089 !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7090 return em;
7091 else
7092 hole_em = em;
7095 /* check to see if we've wrapped (len == -1 or similar) */
7096 end = start + len;
7097 if (end < start)
7098 end = (u64)-1;
7099 else
7100 end -= 1;
7102 em = NULL;
7104 /* ok, we didn't find anything, lets look for delalloc */
7105 found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start,
7106 end, len, EXTENT_DELALLOC, 1);
7107 found_end = range_start + found;
7108 if (found_end < range_start)
7109 found_end = (u64)-1;
7112 * we didn't find anything useful, return
7113 * the original results from get_extent()
7115 if (range_start > end || found_end <= start) {
7116 em = hole_em;
7117 hole_em = NULL;
7118 goto out;
7121 /* adjust the range_start to make sure it doesn't
7122 * go backwards from the start they passed in
7124 range_start = max(start, range_start);
7125 found = found_end - range_start;
7127 if (found > 0) {
7128 u64 hole_start = start;
7129 u64 hole_len = len;
7131 em = alloc_extent_map();
7132 if (!em) {
7133 err = -ENOMEM;
7134 goto out;
7137 * when btrfs_get_extent can't find anything it
7138 * returns one huge hole
7140 * make sure what it found really fits our range, and
7141 * adjust to make sure it is based on the start from
7142 * the caller
7144 if (hole_em) {
7145 u64 calc_end = extent_map_end(hole_em);
7147 if (calc_end <= start || (hole_em->start > end)) {
7148 free_extent_map(hole_em);
7149 hole_em = NULL;
7150 } else {
7151 hole_start = max(hole_em->start, start);
7152 hole_len = calc_end - hole_start;
7155 em->bdev = NULL;
7156 if (hole_em && range_start > hole_start) {
7157 /* our hole starts before our delalloc, so we
7158 * have to return just the parts of the hole
7159 * that go until the delalloc starts
7161 em->len = min(hole_len,
7162 range_start - hole_start);
7163 em->start = hole_start;
7164 em->orig_start = hole_start;
7166 * don't adjust block start at all,
7167 * it is fixed at EXTENT_MAP_HOLE
7169 em->block_start = hole_em->block_start;
7170 em->block_len = hole_len;
7171 if (test_bit(EXTENT_FLAG_PREALLOC, &hole_em->flags))
7172 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
7173 } else {
7174 em->start = range_start;
7175 em->len = found;
7176 em->orig_start = range_start;
7177 em->block_start = EXTENT_MAP_DELALLOC;
7178 em->block_len = found;
7180 } else if (hole_em) {
7181 return hole_em;
7183 out:
7185 free_extent_map(hole_em);
7186 if (err) {
7187 free_extent_map(em);
7188 return ERR_PTR(err);
7190 return em;
7193 static struct extent_map *btrfs_new_extent_direct(struct inode *inode,
7194 u64 start, u64 len)
7196 struct btrfs_root *root = BTRFS_I(inode)->root;
7197 struct extent_map *em;
7198 struct btrfs_key ins;
7199 u64 alloc_hint;
7200 int ret;
7202 alloc_hint = get_extent_allocation_hint(inode, start, len);
7203 ret = btrfs_reserve_extent(root, len, root->sectorsize, 0,
7204 alloc_hint, &ins, 1, 1);
7205 if (ret)
7206 return ERR_PTR(ret);
7208 em = create_pinned_em(inode, start, ins.offset, start, ins.objectid,
7209 ins.offset, ins.offset, ins.offset, 0);
7210 if (IS_ERR(em)) {
7211 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7212 return em;
7215 ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid,
7216 ins.offset, ins.offset, 0);
7217 if (ret) {
7218 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 1);
7219 free_extent_map(em);
7220 return ERR_PTR(ret);
7223 return em;
7227 * returns 1 when the nocow is safe, < 1 on error, 0 if the
7228 * block must be cow'd
7230 noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
7231 u64 *orig_start, u64 *orig_block_len,
7232 u64 *ram_bytes)
7234 struct btrfs_trans_handle *trans;
7235 struct btrfs_path *path;
7236 int ret;
7237 struct extent_buffer *leaf;
7238 struct btrfs_root *root = BTRFS_I(inode)->root;
7239 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
7240 struct btrfs_file_extent_item *fi;
7241 struct btrfs_key key;
7242 u64 disk_bytenr;
7243 u64 backref_offset;
7244 u64 extent_end;
7245 u64 num_bytes;
7246 int slot;
7247 int found_type;
7248 bool nocow = (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW);
7250 path = btrfs_alloc_path();
7251 if (!path)
7252 return -ENOMEM;
7254 ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7255 offset, 0);
7256 if (ret < 0)
7257 goto out;
7259 slot = path->slots[0];
7260 if (ret == 1) {
7261 if (slot == 0) {
7262 /* can't find the item, must cow */
7263 ret = 0;
7264 goto out;
7266 slot--;
7268 ret = 0;
7269 leaf = path->nodes[0];
7270 btrfs_item_key_to_cpu(leaf, &key, slot);
7271 if (key.objectid != btrfs_ino(inode) ||
7272 key.type != BTRFS_EXTENT_DATA_KEY) {
7273 /* not our file or wrong item type, must cow */
7274 goto out;
7277 if (key.offset > offset) {
7278 /* Wrong offset, must cow */
7279 goto out;
7282 fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
7283 found_type = btrfs_file_extent_type(leaf, fi);
7284 if (found_type != BTRFS_FILE_EXTENT_REG &&
7285 found_type != BTRFS_FILE_EXTENT_PREALLOC) {
7286 /* not a regular extent, must cow */
7287 goto out;
7290 if (!nocow && found_type == BTRFS_FILE_EXTENT_REG)
7291 goto out;
7293 extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
7294 if (extent_end <= offset)
7295 goto out;
7297 disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7298 if (disk_bytenr == 0)
7299 goto out;
7301 if (btrfs_file_extent_compression(leaf, fi) ||
7302 btrfs_file_extent_encryption(leaf, fi) ||
7303 btrfs_file_extent_other_encoding(leaf, fi))
7304 goto out;
7306 backref_offset = btrfs_file_extent_offset(leaf, fi);
7308 if (orig_start) {
7309 *orig_start = key.offset - backref_offset;
7310 *orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, fi);
7311 *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
7314 if (btrfs_extent_readonly(root, disk_bytenr))
7315 goto out;
7317 num_bytes = min(offset + *len, extent_end) - offset;
7318 if (!nocow && found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7319 u64 range_end;
7321 range_end = round_up(offset + num_bytes, root->sectorsize) - 1;
7322 ret = test_range_bit(io_tree, offset, range_end,
7323 EXTENT_DELALLOC, 0, NULL);
7324 if (ret) {
7325 ret = -EAGAIN;
7326 goto out;
7330 btrfs_release_path(path);
7333 * look for other files referencing this extent, if we
7334 * find any we must cow
7336 trans = btrfs_join_transaction(root);
7337 if (IS_ERR(trans)) {
7338 ret = 0;
7339 goto out;
7342 ret = btrfs_cross_ref_exist(trans, root, btrfs_ino(inode),
7343 key.offset - backref_offset, disk_bytenr);
7344 btrfs_end_transaction(trans, root);
7345 if (ret) {
7346 ret = 0;
7347 goto out;
7351 * adjust disk_bytenr and num_bytes to cover just the bytes
7352 * in this extent we are about to write. If there
7353 * are any csums in that range we have to cow in order
7354 * to keep the csums correct
7356 disk_bytenr += backref_offset;
7357 disk_bytenr += offset - key.offset;
7358 if (csum_exist_in_range(root, disk_bytenr, num_bytes))
7359 goto out;
7361 * all of the above have passed, it is safe to overwrite this extent
7362 * without cow
7364 *len = num_bytes;
7365 ret = 1;
7366 out:
7367 btrfs_free_path(path);
7368 return ret;
7371 bool btrfs_page_exists_in_range(struct inode *inode, loff_t start, loff_t end)
7373 struct radix_tree_root *root = &inode->i_mapping->page_tree;
7374 int found = false;
7375 void **pagep = NULL;
7376 struct page *page = NULL;
7377 unsigned long start_idx;
7378 unsigned long end_idx;
7380 start_idx = start >> PAGE_CACHE_SHIFT;
7383 * end is the last byte in the last page. end == start is legal
7385 end_idx = end >> PAGE_CACHE_SHIFT;
7387 rcu_read_lock();
7389 /* Most of the code in this while loop is lifted from
7390 * find_get_page. It's been modified to begin searching from a
7391 * page and return just the first page found in that range. If the
7392 * found idx is less than or equal to the end idx then we know that
7393 * a page exists. If no pages are found or if those pages are
7394 * outside of the range then we're fine (yay!) */
7395 while (page == NULL &&
7396 radix_tree_gang_lookup_slot(root, &pagep, NULL, start_idx, 1)) {
7397 page = radix_tree_deref_slot(pagep);
7398 if (unlikely(!page))
7399 break;
7401 if (radix_tree_exception(page)) {
7402 if (radix_tree_deref_retry(page)) {
7403 page = NULL;
7404 continue;
7407 * Otherwise, shmem/tmpfs must be storing a swap entry
7408 * here as an exceptional entry: so return it without
7409 * attempting to raise page count.
7411 page = NULL;
7412 break; /* TODO: Is this relevant for this use case? */
7415 if (!page_cache_get_speculative(page)) {
7416 page = NULL;
7417 continue;
7421 * Has the page moved?
7422 * This is part of the lockless pagecache protocol. See
7423 * include/linux/pagemap.h for details.
7425 if (unlikely(page != *pagep)) {
7426 page_cache_release(page);
7427 page = NULL;
7431 if (page) {
7432 if (page->index <= end_idx)
7433 found = true;
7434 page_cache_release(page);
7437 rcu_read_unlock();
7438 return found;
7441 static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
7442 struct extent_state **cached_state, int writing)
7444 struct btrfs_ordered_extent *ordered;
7445 int ret = 0;
7447 while (1) {
7448 lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7449 0, cached_state);
7451 * We're concerned with the entire range that we're going to be
7452 * doing DIO to, so we need to make sure theres no ordered
7453 * extents in this range.
7455 ordered = btrfs_lookup_ordered_range(inode, lockstart,
7456 lockend - lockstart + 1);
7459 * We need to make sure there are no buffered pages in this
7460 * range either, we could have raced between the invalidate in
7461 * generic_file_direct_write and locking the extent. The
7462 * invalidate needs to happen so that reads after a write do not
7463 * get stale data.
7465 if (!ordered &&
7466 (!writing ||
7467 !btrfs_page_exists_in_range(inode, lockstart, lockend)))
7468 break;
7470 unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7471 cached_state, GFP_NOFS);
7473 if (ordered) {
7474 btrfs_start_ordered_extent(inode, ordered, 1);
7475 btrfs_put_ordered_extent(ordered);
7476 } else {
7477 /* Screw you mmap */
7478 ret = btrfs_fdatawrite_range(inode, lockstart, lockend);
7479 if (ret)
7480 break;
7481 ret = filemap_fdatawait_range(inode->i_mapping,
7482 lockstart,
7483 lockend);
7484 if (ret)
7485 break;
7488 * If we found a page that couldn't be invalidated just
7489 * fall back to buffered.
7491 ret = invalidate_inode_pages2_range(inode->i_mapping,
7492 lockstart >> PAGE_CACHE_SHIFT,
7493 lockend >> PAGE_CACHE_SHIFT);
7494 if (ret)
7495 break;
7498 cond_resched();
7501 return ret;
7504 static struct extent_map *create_pinned_em(struct inode *inode, u64 start,
7505 u64 len, u64 orig_start,
7506 u64 block_start, u64 block_len,
7507 u64 orig_block_len, u64 ram_bytes,
7508 int type)
7510 struct extent_map_tree *em_tree;
7511 struct extent_map *em;
7512 struct btrfs_root *root = BTRFS_I(inode)->root;
7513 int ret;
7515 em_tree = &BTRFS_I(inode)->extent_tree;
7516 em = alloc_extent_map();
7517 if (!em)
7518 return ERR_PTR(-ENOMEM);
7520 em->start = start;
7521 em->orig_start = orig_start;
7522 em->mod_start = start;
7523 em->mod_len = len;
7524 em->len = len;
7525 em->block_len = block_len;
7526 em->block_start = block_start;
7527 em->bdev = root->fs_info->fs_devices->latest_bdev;
7528 em->orig_block_len = orig_block_len;
7529 em->ram_bytes = ram_bytes;
7530 em->generation = -1;
7531 set_bit(EXTENT_FLAG_PINNED, &em->flags);
7532 if (type == BTRFS_ORDERED_PREALLOC)
7533 set_bit(EXTENT_FLAG_FILLING, &em->flags);
7535 do {
7536 btrfs_drop_extent_cache(inode, em->start,
7537 em->start + em->len - 1, 0);
7538 write_lock(&em_tree->lock);
7539 ret = add_extent_mapping(em_tree, em, 1);
7540 write_unlock(&em_tree->lock);
7541 } while (ret == -EEXIST);
7543 if (ret) {
7544 free_extent_map(em);
7545 return ERR_PTR(ret);
7548 return em;
7551 struct btrfs_dio_data {
7552 u64 outstanding_extents;
7553 u64 reserve;
7556 static void adjust_dio_outstanding_extents(struct inode *inode,
7557 struct btrfs_dio_data *dio_data,
7558 const u64 len)
7560 unsigned num_extents;
7562 num_extents = (unsigned) div64_u64(len + BTRFS_MAX_EXTENT_SIZE - 1,
7563 BTRFS_MAX_EXTENT_SIZE);
7565 * If we have an outstanding_extents count still set then we're
7566 * within our reservation, otherwise we need to adjust our inode
7567 * counter appropriately.
7569 if (dio_data->outstanding_extents >= num_extents) {
7570 dio_data->outstanding_extents -= num_extents;
7571 } else {
7573 * If dio write length has been split due to no large enough
7574 * contiguous space, we need to compensate our inode counter
7575 * appropriately.
7577 u64 num_needed = num_extents - dio_data->outstanding_extents;
7579 spin_lock(&BTRFS_I(inode)->lock);
7580 BTRFS_I(inode)->outstanding_extents += num_needed;
7581 spin_unlock(&BTRFS_I(inode)->lock);
7585 static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock,
7586 struct buffer_head *bh_result, int create)
7588 struct extent_map *em;
7589 struct btrfs_root *root = BTRFS_I(inode)->root;
7590 struct extent_state *cached_state = NULL;
7591 struct btrfs_dio_data *dio_data = NULL;
7592 u64 start = iblock << inode->i_blkbits;
7593 u64 lockstart, lockend;
7594 u64 len = bh_result->b_size;
7595 int unlock_bits = EXTENT_LOCKED;
7596 int ret = 0;
7598 if (create)
7599 unlock_bits |= EXTENT_DIRTY;
7600 else
7601 len = min_t(u64, len, root->sectorsize);
7603 lockstart = start;
7604 lockend = start + len - 1;
7606 if (current->journal_info) {
7608 * Need to pull our outstanding extents and set journal_info to NULL so
7609 * that anything that needs to check if there's a transction doesn't get
7610 * confused.
7612 dio_data = current->journal_info;
7613 current->journal_info = NULL;
7617 * If this errors out it's because we couldn't invalidate pagecache for
7618 * this range and we need to fallback to buffered.
7620 if (lock_extent_direct(inode, lockstart, lockend, &cached_state,
7621 create)) {
7622 ret = -ENOTBLK;
7623 goto err;
7626 em = btrfs_get_extent(inode, NULL, 0, start, len, 0);
7627 if (IS_ERR(em)) {
7628 ret = PTR_ERR(em);
7629 goto unlock_err;
7633 * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
7634 * io. INLINE is special, and we could probably kludge it in here, but
7635 * it's still buffered so for safety lets just fall back to the generic
7636 * buffered path.
7638 * For COMPRESSED we _have_ to read the entire extent in so we can
7639 * decompress it, so there will be buffering required no matter what we
7640 * do, so go ahead and fallback to buffered.
7642 * We return -ENOTBLK because thats what makes DIO go ahead and go back
7643 * to buffered IO. Don't blame me, this is the price we pay for using
7644 * the generic code.
7646 if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
7647 em->block_start == EXTENT_MAP_INLINE) {
7648 free_extent_map(em);
7649 ret = -ENOTBLK;
7650 goto unlock_err;
7653 /* Just a good old fashioned hole, return */
7654 if (!create && (em->block_start == EXTENT_MAP_HOLE ||
7655 test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
7656 free_extent_map(em);
7657 goto unlock_err;
7661 * We don't allocate a new extent in the following cases
7663 * 1) The inode is marked as NODATACOW. In this case we'll just use the
7664 * existing extent.
7665 * 2) The extent is marked as PREALLOC. We're good to go here and can
7666 * just use the extent.
7669 if (!create) {
7670 len = min(len, em->len - (start - em->start));
7671 lockstart = start + len;
7672 goto unlock;
7675 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
7676 ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
7677 em->block_start != EXTENT_MAP_HOLE)) {
7678 int type;
7679 u64 block_start, orig_start, orig_block_len, ram_bytes;
7681 if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7682 type = BTRFS_ORDERED_PREALLOC;
7683 else
7684 type = BTRFS_ORDERED_NOCOW;
7685 len = min(len, em->len - (start - em->start));
7686 block_start = em->block_start + (start - em->start);
7688 if (can_nocow_extent(inode, start, &len, &orig_start,
7689 &orig_block_len, &ram_bytes) == 1) {
7690 if (type == BTRFS_ORDERED_PREALLOC) {
7691 free_extent_map(em);
7692 em = create_pinned_em(inode, start, len,
7693 orig_start,
7694 block_start, len,
7695 orig_block_len,
7696 ram_bytes, type);
7697 if (IS_ERR(em)) {
7698 ret = PTR_ERR(em);
7699 goto unlock_err;
7703 ret = btrfs_add_ordered_extent_dio(inode, start,
7704 block_start, len, len, type);
7705 if (ret) {
7706 free_extent_map(em);
7707 goto unlock_err;
7709 goto unlock;
7714 * this will cow the extent, reset the len in case we changed
7715 * it above
7717 len = bh_result->b_size;
7718 free_extent_map(em);
7719 em = btrfs_new_extent_direct(inode, start, len);
7720 if (IS_ERR(em)) {
7721 ret = PTR_ERR(em);
7722 goto unlock_err;
7724 len = min(len, em->len - (start - em->start));
7725 unlock:
7726 bh_result->b_blocknr = (em->block_start + (start - em->start)) >>
7727 inode->i_blkbits;
7728 bh_result->b_size = len;
7729 bh_result->b_bdev = em->bdev;
7730 set_buffer_mapped(bh_result);
7731 if (create) {
7732 if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
7733 set_buffer_new(bh_result);
7736 * Need to update the i_size under the extent lock so buffered
7737 * readers will get the updated i_size when we unlock.
7739 if (start + len > i_size_read(inode))
7740 i_size_write(inode, start + len);
7742 adjust_dio_outstanding_extents(inode, dio_data, len);
7743 btrfs_free_reserved_data_space(inode, start, len);
7744 WARN_ON(dio_data->reserve < len);
7745 dio_data->reserve -= len;
7746 current->journal_info = dio_data;
7750 * In the case of write we need to clear and unlock the entire range,
7751 * in the case of read we need to unlock only the end area that we
7752 * aren't using if there is any left over space.
7754 if (lockstart < lockend) {
7755 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart,
7756 lockend, unlock_bits, 1, 0,
7757 &cached_state, GFP_NOFS);
7758 } else {
7759 free_extent_state(cached_state);
7762 free_extent_map(em);
7764 return 0;
7766 unlock_err:
7767 clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
7768 unlock_bits, 1, 0, &cached_state, GFP_NOFS);
7769 err:
7770 if (dio_data)
7771 current->journal_info = dio_data;
7773 * Compensate the delalloc release we do in btrfs_direct_IO() when we
7774 * write less data then expected, so that we don't underflow our inode's
7775 * outstanding extents counter.
7777 if (create && dio_data)
7778 adjust_dio_outstanding_extents(inode, dio_data, len);
7780 return ret;
7783 static inline int submit_dio_repair_bio(struct inode *inode, struct bio *bio,
7784 int rw, int mirror_num)
7786 struct btrfs_root *root = BTRFS_I(inode)->root;
7787 int ret;
7789 BUG_ON(rw & REQ_WRITE);
7791 bio_get(bio);
7793 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
7794 BTRFS_WQ_ENDIO_DIO_REPAIR);
7795 if (ret)
7796 goto err;
7798 ret = btrfs_map_bio(root, rw, bio, mirror_num, 0);
7799 err:
7800 bio_put(bio);
7801 return ret;
7804 static int btrfs_check_dio_repairable(struct inode *inode,
7805 struct bio *failed_bio,
7806 struct io_failure_record *failrec,
7807 int failed_mirror)
7809 int num_copies;
7811 num_copies = btrfs_num_copies(BTRFS_I(inode)->root->fs_info,
7812 failrec->logical, failrec->len);
7813 if (num_copies == 1) {
7815 * we only have a single copy of the data, so don't bother with
7816 * all the retry and error correction code that follows. no
7817 * matter what the error is, it is very likely to persist.
7819 pr_debug("Check DIO Repairable: cannot repair, num_copies=%d, next_mirror %d, failed_mirror %d\n",
7820 num_copies, failrec->this_mirror, failed_mirror);
7821 return 0;
7824 failrec->failed_mirror = failed_mirror;
7825 failrec->this_mirror++;
7826 if (failrec->this_mirror == failed_mirror)
7827 failrec->this_mirror++;
7829 if (failrec->this_mirror > num_copies) {
7830 pr_debug("Check DIO Repairable: (fail) num_copies=%d, next_mirror %d, failed_mirror %d\n",
7831 num_copies, failrec->this_mirror, failed_mirror);
7832 return 0;
7835 return 1;
7838 static int dio_read_error(struct inode *inode, struct bio *failed_bio,
7839 struct page *page, u64 start, u64 end,
7840 int failed_mirror, bio_end_io_t *repair_endio,
7841 void *repair_arg)
7843 struct io_failure_record *failrec;
7844 struct bio *bio;
7845 int isector;
7846 int read_mode;
7847 int ret;
7849 BUG_ON(failed_bio->bi_rw & REQ_WRITE);
7851 ret = btrfs_get_io_failure_record(inode, start, end, &failrec);
7852 if (ret)
7853 return ret;
7855 ret = btrfs_check_dio_repairable(inode, failed_bio, failrec,
7856 failed_mirror);
7857 if (!ret) {
7858 free_io_failure(inode, failrec);
7859 return -EIO;
7862 if (failed_bio->bi_vcnt > 1)
7863 read_mode = READ_SYNC | REQ_FAILFAST_DEV;
7864 else
7865 read_mode = READ_SYNC;
7867 isector = start - btrfs_io_bio(failed_bio)->logical;
7868 isector >>= inode->i_sb->s_blocksize_bits;
7869 bio = btrfs_create_repair_bio(inode, failed_bio, failrec, page,
7870 0, isector, repair_endio, repair_arg);
7871 if (!bio) {
7872 free_io_failure(inode, failrec);
7873 return -EIO;
7876 btrfs_debug(BTRFS_I(inode)->root->fs_info,
7877 "Repair DIO Read Error: submitting new dio read[%#x] to this_mirror=%d, in_validation=%d\n",
7878 read_mode, failrec->this_mirror, failrec->in_validation);
7880 ret = submit_dio_repair_bio(inode, bio, read_mode,
7881 failrec->this_mirror);
7882 if (ret) {
7883 free_io_failure(inode, failrec);
7884 bio_put(bio);
7887 return ret;
7890 struct btrfs_retry_complete {
7891 struct completion done;
7892 struct inode *inode;
7893 u64 start;
7894 int uptodate;
7897 static void btrfs_retry_endio_nocsum(struct bio *bio)
7899 struct btrfs_retry_complete *done = bio->bi_private;
7900 struct bio_vec *bvec;
7901 int i;
7903 if (bio->bi_error)
7904 goto end;
7906 done->uptodate = 1;
7907 bio_for_each_segment_all(bvec, bio, i)
7908 clean_io_failure(done->inode, done->start, bvec->bv_page, 0);
7909 end:
7910 complete(&done->done);
7911 bio_put(bio);
7914 static int __btrfs_correct_data_nocsum(struct inode *inode,
7915 struct btrfs_io_bio *io_bio)
7917 struct bio_vec *bvec;
7918 struct btrfs_retry_complete done;
7919 u64 start;
7920 int i;
7921 int ret;
7923 start = io_bio->logical;
7924 done.inode = inode;
7926 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7927 try_again:
7928 done.uptodate = 0;
7929 done.start = start;
7930 init_completion(&done.done);
7932 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
7933 start + bvec->bv_len - 1,
7934 io_bio->mirror_num,
7935 btrfs_retry_endio_nocsum, &done);
7936 if (ret)
7937 return ret;
7939 wait_for_completion(&done.done);
7941 if (!done.uptodate) {
7942 /* We might have another mirror, so try again */
7943 goto try_again;
7946 start += bvec->bv_len;
7949 return 0;
7952 static void btrfs_retry_endio(struct bio *bio)
7954 struct btrfs_retry_complete *done = bio->bi_private;
7955 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
7956 struct bio_vec *bvec;
7957 int uptodate;
7958 int ret;
7959 int i;
7961 if (bio->bi_error)
7962 goto end;
7964 uptodate = 1;
7965 bio_for_each_segment_all(bvec, bio, i) {
7966 ret = __readpage_endio_check(done->inode, io_bio, i,
7967 bvec->bv_page, 0,
7968 done->start, bvec->bv_len);
7969 if (!ret)
7970 clean_io_failure(done->inode, done->start,
7971 bvec->bv_page, 0);
7972 else
7973 uptodate = 0;
7976 done->uptodate = uptodate;
7977 end:
7978 complete(&done->done);
7979 bio_put(bio);
7982 static int __btrfs_subio_endio_read(struct inode *inode,
7983 struct btrfs_io_bio *io_bio, int err)
7985 struct bio_vec *bvec;
7986 struct btrfs_retry_complete done;
7987 u64 start;
7988 u64 offset = 0;
7989 int i;
7990 int ret;
7992 err = 0;
7993 start = io_bio->logical;
7994 done.inode = inode;
7996 bio_for_each_segment_all(bvec, &io_bio->bio, i) {
7997 ret = __readpage_endio_check(inode, io_bio, i, bvec->bv_page,
7998 0, start, bvec->bv_len);
7999 if (likely(!ret))
8000 goto next;
8001 try_again:
8002 done.uptodate = 0;
8003 done.start = start;
8004 init_completion(&done.done);
8006 ret = dio_read_error(inode, &io_bio->bio, bvec->bv_page, start,
8007 start + bvec->bv_len - 1,
8008 io_bio->mirror_num,
8009 btrfs_retry_endio, &done);
8010 if (ret) {
8011 err = ret;
8012 goto next;
8015 wait_for_completion(&done.done);
8017 if (!done.uptodate) {
8018 /* We might have another mirror, so try again */
8019 goto try_again;
8021 next:
8022 offset += bvec->bv_len;
8023 start += bvec->bv_len;
8026 return err;
8029 static int btrfs_subio_endio_read(struct inode *inode,
8030 struct btrfs_io_bio *io_bio, int err)
8032 bool skip_csum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8034 if (skip_csum) {
8035 if (unlikely(err))
8036 return __btrfs_correct_data_nocsum(inode, io_bio);
8037 else
8038 return 0;
8039 } else {
8040 return __btrfs_subio_endio_read(inode, io_bio, err);
8044 static void btrfs_endio_direct_read(struct bio *bio)
8046 struct btrfs_dio_private *dip = bio->bi_private;
8047 struct inode *inode = dip->inode;
8048 struct bio *dio_bio;
8049 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8050 int err = bio->bi_error;
8052 if (dip->flags & BTRFS_DIO_ORIG_BIO_SUBMITTED)
8053 err = btrfs_subio_endio_read(inode, io_bio, err);
8055 unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset,
8056 dip->logical_offset + dip->bytes - 1);
8057 dio_bio = dip->dio_bio;
8059 kfree(dip);
8061 dio_bio->bi_error = bio->bi_error;
8062 dio_end_io(dio_bio, bio->bi_error);
8064 if (io_bio->end_io)
8065 io_bio->end_io(io_bio, err);
8066 bio_put(bio);
8069 static void btrfs_endio_direct_write(struct bio *bio)
8071 struct btrfs_dio_private *dip = bio->bi_private;
8072 struct inode *inode = dip->inode;
8073 struct btrfs_root *root = BTRFS_I(inode)->root;
8074 struct btrfs_ordered_extent *ordered = NULL;
8075 u64 ordered_offset = dip->logical_offset;
8076 u64 ordered_bytes = dip->bytes;
8077 struct bio *dio_bio;
8078 int ret;
8080 again:
8081 ret = btrfs_dec_test_first_ordered_pending(inode, &ordered,
8082 &ordered_offset,
8083 ordered_bytes,
8084 !bio->bi_error);
8085 if (!ret)
8086 goto out_test;
8088 btrfs_init_work(&ordered->work, btrfs_endio_write_helper,
8089 finish_ordered_fn, NULL, NULL);
8090 btrfs_queue_work(root->fs_info->endio_write_workers,
8091 &ordered->work);
8092 out_test:
8094 * our bio might span multiple ordered extents. If we haven't
8095 * completed the accounting for the whole dio, go back and try again
8097 if (ordered_offset < dip->logical_offset + dip->bytes) {
8098 ordered_bytes = dip->logical_offset + dip->bytes -
8099 ordered_offset;
8100 ordered = NULL;
8101 goto again;
8103 dio_bio = dip->dio_bio;
8105 kfree(dip);
8107 dio_bio->bi_error = bio->bi_error;
8108 dio_end_io(dio_bio, bio->bi_error);
8109 bio_put(bio);
8112 static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw,
8113 struct bio *bio, int mirror_num,
8114 unsigned long bio_flags, u64 offset)
8116 int ret;
8117 struct btrfs_root *root = BTRFS_I(inode)->root;
8118 ret = btrfs_csum_one_bio(root, inode, bio, offset, 1);
8119 BUG_ON(ret); /* -ENOMEM */
8120 return 0;
8123 static void btrfs_end_dio_bio(struct bio *bio)
8125 struct btrfs_dio_private *dip = bio->bi_private;
8126 int err = bio->bi_error;
8128 if (err)
8129 btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
8130 "direct IO failed ino %llu rw %lu sector %#Lx len %u err no %d",
8131 btrfs_ino(dip->inode), bio->bi_rw,
8132 (unsigned long long)bio->bi_iter.bi_sector,
8133 bio->bi_iter.bi_size, err);
8135 if (dip->subio_endio)
8136 err = dip->subio_endio(dip->inode, btrfs_io_bio(bio), err);
8138 if (err) {
8139 dip->errors = 1;
8142 * before atomic variable goto zero, we must make sure
8143 * dip->errors is perceived to be set.
8145 smp_mb__before_atomic();
8148 /* if there are more bios still pending for this dio, just exit */
8149 if (!atomic_dec_and_test(&dip->pending_bios))
8150 goto out;
8152 if (dip->errors) {
8153 bio_io_error(dip->orig_bio);
8154 } else {
8155 dip->dio_bio->bi_error = 0;
8156 bio_endio(dip->orig_bio);
8158 out:
8159 bio_put(bio);
8162 static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev,
8163 u64 first_sector, gfp_t gfp_flags)
8165 struct bio *bio;
8166 bio = btrfs_bio_alloc(bdev, first_sector, BIO_MAX_PAGES, gfp_flags);
8167 if (bio)
8168 bio_associate_current(bio);
8169 return bio;
8172 static inline int btrfs_lookup_and_bind_dio_csum(struct btrfs_root *root,
8173 struct inode *inode,
8174 struct btrfs_dio_private *dip,
8175 struct bio *bio,
8176 u64 file_offset)
8178 struct btrfs_io_bio *io_bio = btrfs_io_bio(bio);
8179 struct btrfs_io_bio *orig_io_bio = btrfs_io_bio(dip->orig_bio);
8180 int ret;
8183 * We load all the csum data we need when we submit
8184 * the first bio to reduce the csum tree search and
8185 * contention.
8187 if (dip->logical_offset == file_offset) {
8188 ret = btrfs_lookup_bio_sums_dio(root, inode, dip->orig_bio,
8189 file_offset);
8190 if (ret)
8191 return ret;
8194 if (bio == dip->orig_bio)
8195 return 0;
8197 file_offset -= dip->logical_offset;
8198 file_offset >>= inode->i_sb->s_blocksize_bits;
8199 io_bio->csum = (u8 *)(((u32 *)orig_io_bio->csum) + file_offset);
8201 return 0;
8204 static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
8205 int rw, u64 file_offset, int skip_sum,
8206 int async_submit)
8208 struct btrfs_dio_private *dip = bio->bi_private;
8209 int write = rw & REQ_WRITE;
8210 struct btrfs_root *root = BTRFS_I(inode)->root;
8211 int ret;
8213 if (async_submit)
8214 async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers);
8216 bio_get(bio);
8218 if (!write) {
8219 ret = btrfs_bio_wq_end_io(root->fs_info, bio,
8220 BTRFS_WQ_ENDIO_DATA);
8221 if (ret)
8222 goto err;
8225 if (skip_sum)
8226 goto map;
8228 if (write && async_submit) {
8229 ret = btrfs_wq_submit_bio(root->fs_info,
8230 inode, rw, bio, 0, 0,
8231 file_offset,
8232 __btrfs_submit_bio_start_direct_io,
8233 __btrfs_submit_bio_done);
8234 goto err;
8235 } else if (write) {
8237 * If we aren't doing async submit, calculate the csum of the
8238 * bio now.
8240 ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1);
8241 if (ret)
8242 goto err;
8243 } else {
8244 ret = btrfs_lookup_and_bind_dio_csum(root, inode, dip, bio,
8245 file_offset);
8246 if (ret)
8247 goto err;
8249 map:
8250 ret = btrfs_map_bio(root, rw, bio, 0, async_submit);
8251 err:
8252 bio_put(bio);
8253 return ret;
8256 static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip,
8257 int skip_sum)
8259 struct inode *inode = dip->inode;
8260 struct btrfs_root *root = BTRFS_I(inode)->root;
8261 struct bio *bio;
8262 struct bio *orig_bio = dip->orig_bio;
8263 struct bio_vec *bvec = orig_bio->bi_io_vec;
8264 u64 start_sector = orig_bio->bi_iter.bi_sector;
8265 u64 file_offset = dip->logical_offset;
8266 u64 submit_len = 0;
8267 u64 map_length;
8268 int nr_pages = 0;
8269 int ret;
8270 int async_submit = 0;
8272 map_length = orig_bio->bi_iter.bi_size;
8273 ret = btrfs_map_block(root->fs_info, rw, start_sector << 9,
8274 &map_length, NULL, 0);
8275 if (ret)
8276 return -EIO;
8278 if (map_length >= orig_bio->bi_iter.bi_size) {
8279 bio = orig_bio;
8280 dip->flags |= BTRFS_DIO_ORIG_BIO_SUBMITTED;
8281 goto submit;
8284 /* async crcs make it difficult to collect full stripe writes. */
8285 if (btrfs_get_alloc_profile(root, 1) & BTRFS_BLOCK_GROUP_RAID56_MASK)
8286 async_submit = 0;
8287 else
8288 async_submit = 1;
8290 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS);
8291 if (!bio)
8292 return -ENOMEM;
8294 bio->bi_private = dip;
8295 bio->bi_end_io = btrfs_end_dio_bio;
8296 btrfs_io_bio(bio)->logical = file_offset;
8297 atomic_inc(&dip->pending_bios);
8299 while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) {
8300 if (map_length < submit_len + bvec->bv_len ||
8301 bio_add_page(bio, bvec->bv_page, bvec->bv_len,
8302 bvec->bv_offset) < bvec->bv_len) {
8304 * inc the count before we submit the bio so
8305 * we know the end IO handler won't happen before
8306 * we inc the count. Otherwise, the dip might get freed
8307 * before we're done setting it up
8309 atomic_inc(&dip->pending_bios);
8310 ret = __btrfs_submit_dio_bio(bio, inode, rw,
8311 file_offset, skip_sum,
8312 async_submit);
8313 if (ret) {
8314 bio_put(bio);
8315 atomic_dec(&dip->pending_bios);
8316 goto out_err;
8319 start_sector += submit_len >> 9;
8320 file_offset += submit_len;
8322 submit_len = 0;
8323 nr_pages = 0;
8325 bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev,
8326 start_sector, GFP_NOFS);
8327 if (!bio)
8328 goto out_err;
8329 bio->bi_private = dip;
8330 bio->bi_end_io = btrfs_end_dio_bio;
8331 btrfs_io_bio(bio)->logical = file_offset;
8333 map_length = orig_bio->bi_iter.bi_size;
8334 ret = btrfs_map_block(root->fs_info, rw,
8335 start_sector << 9,
8336 &map_length, NULL, 0);
8337 if (ret) {
8338 bio_put(bio);
8339 goto out_err;
8341 } else {
8342 submit_len += bvec->bv_len;
8343 nr_pages++;
8344 bvec++;
8348 submit:
8349 ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum,
8350 async_submit);
8351 if (!ret)
8352 return 0;
8354 bio_put(bio);
8355 out_err:
8356 dip->errors = 1;
8358 * before atomic variable goto zero, we must
8359 * make sure dip->errors is perceived to be set.
8361 smp_mb__before_atomic();
8362 if (atomic_dec_and_test(&dip->pending_bios))
8363 bio_io_error(dip->orig_bio);
8365 /* bio_end_io() will handle error, so we needn't return it */
8366 return 0;
8369 static void btrfs_submit_direct(int rw, struct bio *dio_bio,
8370 struct inode *inode, loff_t file_offset)
8372 struct btrfs_dio_private *dip = NULL;
8373 struct bio *io_bio = NULL;
8374 struct btrfs_io_bio *btrfs_bio;
8375 int skip_sum;
8376 int write = rw & REQ_WRITE;
8377 int ret = 0;
8379 skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM;
8381 io_bio = btrfs_bio_clone(dio_bio, GFP_NOFS);
8382 if (!io_bio) {
8383 ret = -ENOMEM;
8384 goto free_ordered;
8387 dip = kzalloc(sizeof(*dip), GFP_NOFS);
8388 if (!dip) {
8389 ret = -ENOMEM;
8390 goto free_ordered;
8393 dip->private = dio_bio->bi_private;
8394 dip->inode = inode;
8395 dip->logical_offset = file_offset;
8396 dip->bytes = dio_bio->bi_iter.bi_size;
8397 dip->disk_bytenr = (u64)dio_bio->bi_iter.bi_sector << 9;
8398 io_bio->bi_private = dip;
8399 dip->orig_bio = io_bio;
8400 dip->dio_bio = dio_bio;
8401 atomic_set(&dip->pending_bios, 0);
8402 btrfs_bio = btrfs_io_bio(io_bio);
8403 btrfs_bio->logical = file_offset;
8405 if (write) {
8406 io_bio->bi_end_io = btrfs_endio_direct_write;
8407 } else {
8408 io_bio->bi_end_io = btrfs_endio_direct_read;
8409 dip->subio_endio = btrfs_subio_endio_read;
8412 ret = btrfs_submit_direct_hook(rw, dip, skip_sum);
8413 if (!ret)
8414 return;
8416 if (btrfs_bio->end_io)
8417 btrfs_bio->end_io(btrfs_bio, ret);
8419 free_ordered:
8421 * If we arrived here it means either we failed to submit the dip
8422 * or we either failed to clone the dio_bio or failed to allocate the
8423 * dip. If we cloned the dio_bio and allocated the dip, we can just
8424 * call bio_endio against our io_bio so that we get proper resource
8425 * cleanup if we fail to submit the dip, otherwise, we must do the
8426 * same as btrfs_endio_direct_[write|read] because we can't call these
8427 * callbacks - they require an allocated dip and a clone of dio_bio.
8429 if (io_bio && dip) {
8430 io_bio->bi_error = -EIO;
8431 bio_endio(io_bio);
8433 * The end io callbacks free our dip, do the final put on io_bio
8434 * and all the cleanup and final put for dio_bio (through
8435 * dio_end_io()).
8437 dip = NULL;
8438 io_bio = NULL;
8439 } else {
8440 if (write) {
8441 struct btrfs_ordered_extent *ordered;
8443 ordered = btrfs_lookup_ordered_extent(inode,
8444 file_offset);
8445 set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
8447 * Decrements our ref on the ordered extent and removes
8448 * the ordered extent from the inode's ordered tree,
8449 * doing all the proper resource cleanup such as for the
8450 * reserved space and waking up any waiters for this
8451 * ordered extent (through btrfs_remove_ordered_extent).
8453 btrfs_finish_ordered_io(ordered);
8454 } else {
8455 unlock_extent(&BTRFS_I(inode)->io_tree, file_offset,
8456 file_offset + dio_bio->bi_iter.bi_size - 1);
8458 dio_bio->bi_error = -EIO;
8460 * Releases and cleans up our dio_bio, no need to bio_put()
8461 * nor bio_endio()/bio_io_error() against dio_bio.
8463 dio_end_io(dio_bio, ret);
8465 if (io_bio)
8466 bio_put(io_bio);
8467 kfree(dip);
8470 static ssize_t check_direct_IO(struct btrfs_root *root, struct kiocb *iocb,
8471 const struct iov_iter *iter, loff_t offset)
8473 int seg;
8474 int i;
8475 unsigned blocksize_mask = root->sectorsize - 1;
8476 ssize_t retval = -EINVAL;
8478 if (offset & blocksize_mask)
8479 goto out;
8481 if (iov_iter_alignment(iter) & blocksize_mask)
8482 goto out;
8484 /* If this is a write we don't need to check anymore */
8485 if (iov_iter_rw(iter) == WRITE)
8486 return 0;
8488 * Check to make sure we don't have duplicate iov_base's in this
8489 * iovec, if so return EINVAL, otherwise we'll get csum errors
8490 * when reading back.
8492 for (seg = 0; seg < iter->nr_segs; seg++) {
8493 for (i = seg + 1; i < iter->nr_segs; i++) {
8494 if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
8495 goto out;
8498 retval = 0;
8499 out:
8500 return retval;
8503 static ssize_t btrfs_direct_IO(struct kiocb *iocb, struct iov_iter *iter,
8504 loff_t offset)
8506 struct file *file = iocb->ki_filp;
8507 struct inode *inode = file->f_mapping->host;
8508 struct btrfs_root *root = BTRFS_I(inode)->root;
8509 struct btrfs_dio_data dio_data = { 0 };
8510 size_t count = 0;
8511 int flags = 0;
8512 bool wakeup = true;
8513 bool relock = false;
8514 ssize_t ret;
8516 if (check_direct_IO(BTRFS_I(inode)->root, iocb, iter, offset))
8517 return 0;
8519 inode_dio_begin(inode);
8520 smp_mb__after_atomic();
8523 * The generic stuff only does filemap_write_and_wait_range, which
8524 * isn't enough if we've written compressed pages to this area, so
8525 * we need to flush the dirty pages again to make absolutely sure
8526 * that any outstanding dirty pages are on disk.
8528 count = iov_iter_count(iter);
8529 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8530 &BTRFS_I(inode)->runtime_flags))
8531 filemap_fdatawrite_range(inode->i_mapping, offset,
8532 offset + count - 1);
8534 if (iov_iter_rw(iter) == WRITE) {
8536 * If the write DIO is beyond the EOF, we need update
8537 * the isize, but it is protected by i_mutex. So we can
8538 * not unlock the i_mutex at this case.
8540 if (offset + count <= inode->i_size) {
8541 mutex_unlock(&inode->i_mutex);
8542 relock = true;
8544 ret = btrfs_delalloc_reserve_space(inode, offset, count);
8545 if (ret)
8546 goto out;
8547 dio_data.outstanding_extents = div64_u64(count +
8548 BTRFS_MAX_EXTENT_SIZE - 1,
8549 BTRFS_MAX_EXTENT_SIZE);
8552 * We need to know how many extents we reserved so that we can
8553 * do the accounting properly if we go over the number we
8554 * originally calculated. Abuse current->journal_info for this.
8556 dio_data.reserve = round_up(count, root->sectorsize);
8557 current->journal_info = &dio_data;
8558 } else if (test_bit(BTRFS_INODE_READDIO_NEED_LOCK,
8559 &BTRFS_I(inode)->runtime_flags)) {
8560 inode_dio_end(inode);
8561 flags = DIO_LOCKING | DIO_SKIP_HOLES;
8562 wakeup = false;
8565 ret = __blockdev_direct_IO(iocb, inode,
8566 BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev,
8567 iter, offset, btrfs_get_blocks_direct, NULL,
8568 btrfs_submit_direct, flags);
8569 if (iov_iter_rw(iter) == WRITE) {
8570 current->journal_info = NULL;
8571 if (ret < 0 && ret != -EIOCBQUEUED) {
8572 if (dio_data.reserve)
8573 btrfs_delalloc_release_space(inode, offset,
8574 dio_data.reserve);
8575 } else if (ret >= 0 && (size_t)ret < count)
8576 btrfs_delalloc_release_space(inode, offset,
8577 count - (size_t)ret);
8579 out:
8580 if (wakeup)
8581 inode_dio_end(inode);
8582 if (relock)
8583 mutex_lock(&inode->i_mutex);
8585 return ret;
8588 #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC)
8590 static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
8591 __u64 start, __u64 len)
8593 int ret;
8595 ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS);
8596 if (ret)
8597 return ret;
8599 return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap);
8602 int btrfs_readpage(struct file *file, struct page *page)
8604 struct extent_io_tree *tree;
8605 tree = &BTRFS_I(page->mapping->host)->io_tree;
8606 return extent_read_full_page(tree, page, btrfs_get_extent, 0);
8609 static int btrfs_writepage(struct page *page, struct writeback_control *wbc)
8611 struct extent_io_tree *tree;
8612 struct inode *inode = page->mapping->host;
8613 int ret;
8615 if (current->flags & PF_MEMALLOC) {
8616 redirty_page_for_writepage(wbc, page);
8617 unlock_page(page);
8618 return 0;
8622 * If we are under memory pressure we will call this directly from the
8623 * VM, we need to make sure we have the inode referenced for the ordered
8624 * extent. If not just return like we didn't do anything.
8626 if (!igrab(inode)) {
8627 redirty_page_for_writepage(wbc, page);
8628 return AOP_WRITEPAGE_ACTIVATE;
8630 tree = &BTRFS_I(page->mapping->host)->io_tree;
8631 ret = extent_write_full_page(tree, page, btrfs_get_extent, wbc);
8632 btrfs_add_delayed_iput(inode);
8633 return ret;
8636 static int btrfs_writepages(struct address_space *mapping,
8637 struct writeback_control *wbc)
8639 struct extent_io_tree *tree;
8641 tree = &BTRFS_I(mapping->host)->io_tree;
8642 return extent_writepages(tree, mapping, btrfs_get_extent, wbc);
8645 static int
8646 btrfs_readpages(struct file *file, struct address_space *mapping,
8647 struct list_head *pages, unsigned nr_pages)
8649 struct extent_io_tree *tree;
8650 tree = &BTRFS_I(mapping->host)->io_tree;
8651 return extent_readpages(tree, mapping, pages, nr_pages,
8652 btrfs_get_extent);
8654 static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8656 struct extent_io_tree *tree;
8657 struct extent_map_tree *map;
8658 int ret;
8660 tree = &BTRFS_I(page->mapping->host)->io_tree;
8661 map = &BTRFS_I(page->mapping->host)->extent_tree;
8662 ret = try_release_extent_mapping(map, tree, page, gfp_flags);
8663 if (ret == 1) {
8664 ClearPagePrivate(page);
8665 set_page_private(page, 0);
8666 page_cache_release(page);
8668 return ret;
8671 static int btrfs_releasepage(struct page *page, gfp_t gfp_flags)
8673 if (PageWriteback(page) || PageDirty(page))
8674 return 0;
8675 return __btrfs_releasepage(page, gfp_flags & GFP_NOFS);
8678 static void btrfs_invalidatepage(struct page *page, unsigned int offset,
8679 unsigned int length)
8681 struct inode *inode = page->mapping->host;
8682 struct extent_io_tree *tree;
8683 struct btrfs_ordered_extent *ordered;
8684 struct extent_state *cached_state = NULL;
8685 u64 page_start = page_offset(page);
8686 u64 page_end = page_start + PAGE_CACHE_SIZE - 1;
8687 int inode_evicting = inode->i_state & I_FREEING;
8690 * we have the page locked, so new writeback can't start,
8691 * and the dirty bit won't be cleared while we are here.
8693 * Wait for IO on this page so that we can safely clear
8694 * the PagePrivate2 bit and do ordered accounting
8696 wait_on_page_writeback(page);
8698 tree = &BTRFS_I(inode)->io_tree;
8699 if (offset) {
8700 btrfs_releasepage(page, GFP_NOFS);
8701 return;
8704 if (!inode_evicting)
8705 lock_extent_bits(tree, page_start, page_end, 0, &cached_state);
8706 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8707 if (ordered) {
8709 * IO on this page will never be started, so we need
8710 * to account for any ordered extents now
8712 if (!inode_evicting)
8713 clear_extent_bit(tree, page_start, page_end,
8714 EXTENT_DIRTY | EXTENT_DELALLOC |
8715 EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
8716 EXTENT_DEFRAG, 1, 0, &cached_state,
8717 GFP_NOFS);
8719 * whoever cleared the private bit is responsible
8720 * for the finish_ordered_io
8722 if (TestClearPagePrivate2(page)) {
8723 struct btrfs_ordered_inode_tree *tree;
8724 u64 new_len;
8726 tree = &BTRFS_I(inode)->ordered_tree;
8728 spin_lock_irq(&tree->lock);
8729 set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
8730 new_len = page_start - ordered->file_offset;
8731 if (new_len < ordered->truncated_len)
8732 ordered->truncated_len = new_len;
8733 spin_unlock_irq(&tree->lock);
8735 if (btrfs_dec_test_ordered_pending(inode, &ordered,
8736 page_start,
8737 PAGE_CACHE_SIZE, 1))
8738 btrfs_finish_ordered_io(ordered);
8740 btrfs_put_ordered_extent(ordered);
8741 if (!inode_evicting) {
8742 cached_state = NULL;
8743 lock_extent_bits(tree, page_start, page_end, 0,
8744 &cached_state);
8749 * Qgroup reserved space handler
8750 * Page here will be either
8751 * 1) Already written to disk
8752 * In this case, its reserved space is released from data rsv map
8753 * and will be freed by delayed_ref handler finally.
8754 * So even we call qgroup_free_data(), it won't decrease reserved
8755 * space.
8756 * 2) Not written to disk
8757 * This means the reserved space should be freed here. However,
8758 * if a truncate invalidates the page (by clearing PageDirty)
8759 * and the page is accounted for while allocating extent
8760 * in btrfs_check_data_free_space() we let delayed_ref to
8761 * free the entire extent.
8763 if (PageDirty(page))
8764 btrfs_qgroup_free_data(inode, page_start, PAGE_SIZE);
8765 if (!inode_evicting) {
8766 clear_extent_bit(tree, page_start, page_end,
8767 EXTENT_LOCKED | EXTENT_DIRTY |
8768 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
8769 EXTENT_DEFRAG, 1, 1,
8770 &cached_state, GFP_NOFS);
8772 __btrfs_releasepage(page, GFP_NOFS);
8775 ClearPageChecked(page);
8776 if (PagePrivate(page)) {
8777 ClearPagePrivate(page);
8778 set_page_private(page, 0);
8779 page_cache_release(page);
8784 * btrfs_page_mkwrite() is not allowed to change the file size as it gets
8785 * called from a page fault handler when a page is first dirtied. Hence we must
8786 * be careful to check for EOF conditions here. We set the page up correctly
8787 * for a written page which means we get ENOSPC checking when writing into
8788 * holes and correct delalloc and unwritten extent mapping on filesystems that
8789 * support these features.
8791 * We are not allowed to take the i_mutex here so we have to play games to
8792 * protect against truncate races as the page could now be beyond EOF. Because
8793 * vmtruncate() writes the inode size before removing pages, once we have the
8794 * page lock we can determine safely if the page is beyond EOF. If it is not
8795 * beyond EOF, then the page is guaranteed safe against truncation until we
8796 * unlock the page.
8798 int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
8800 struct page *page = vmf->page;
8801 struct inode *inode = file_inode(vma->vm_file);
8802 struct btrfs_root *root = BTRFS_I(inode)->root;
8803 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
8804 struct btrfs_ordered_extent *ordered;
8805 struct extent_state *cached_state = NULL;
8806 char *kaddr;
8807 unsigned long zero_start;
8808 loff_t size;
8809 int ret;
8810 int reserved = 0;
8811 u64 page_start;
8812 u64 page_end;
8814 sb_start_pagefault(inode->i_sb);
8815 page_start = page_offset(page);
8816 page_end = page_start + PAGE_CACHE_SIZE - 1;
8818 ret = btrfs_delalloc_reserve_space(inode, page_start,
8819 PAGE_CACHE_SIZE);
8820 if (!ret) {
8821 ret = file_update_time(vma->vm_file);
8822 reserved = 1;
8824 if (ret) {
8825 if (ret == -ENOMEM)
8826 ret = VM_FAULT_OOM;
8827 else /* -ENOSPC, -EIO, etc */
8828 ret = VM_FAULT_SIGBUS;
8829 if (reserved)
8830 goto out;
8831 goto out_noreserve;
8834 ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
8835 again:
8836 lock_page(page);
8837 size = i_size_read(inode);
8839 if ((page->mapping != inode->i_mapping) ||
8840 (page_start >= size)) {
8841 /* page got truncated out from underneath us */
8842 goto out_unlock;
8844 wait_on_page_writeback(page);
8846 lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state);
8847 set_page_extent_mapped(page);
8850 * we can't set the delalloc bits if there are pending ordered
8851 * extents. Drop our locks and wait for them to finish
8853 ordered = btrfs_lookup_ordered_extent(inode, page_start);
8854 if (ordered) {
8855 unlock_extent_cached(io_tree, page_start, page_end,
8856 &cached_state, GFP_NOFS);
8857 unlock_page(page);
8858 btrfs_start_ordered_extent(inode, ordered, 1);
8859 btrfs_put_ordered_extent(ordered);
8860 goto again;
8864 * XXX - page_mkwrite gets called every time the page is dirtied, even
8865 * if it was already dirty, so for space accounting reasons we need to
8866 * clear any delalloc bits for the range we are fixing to save. There
8867 * is probably a better way to do this, but for now keep consistent with
8868 * prepare_pages in the normal write path.
8870 clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end,
8871 EXTENT_DIRTY | EXTENT_DELALLOC |
8872 EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
8873 0, 0, &cached_state, GFP_NOFS);
8875 ret = btrfs_set_extent_delalloc(inode, page_start, page_end,
8876 &cached_state);
8877 if (ret) {
8878 unlock_extent_cached(io_tree, page_start, page_end,
8879 &cached_state, GFP_NOFS);
8880 ret = VM_FAULT_SIGBUS;
8881 goto out_unlock;
8883 ret = 0;
8885 /* page is wholly or partially inside EOF */
8886 if (page_start + PAGE_CACHE_SIZE > size)
8887 zero_start = size & ~PAGE_CACHE_MASK;
8888 else
8889 zero_start = PAGE_CACHE_SIZE;
8891 if (zero_start != PAGE_CACHE_SIZE) {
8892 kaddr = kmap(page);
8893 memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start);
8894 flush_dcache_page(page);
8895 kunmap(page);
8897 ClearPageChecked(page);
8898 set_page_dirty(page);
8899 SetPageUptodate(page);
8901 BTRFS_I(inode)->last_trans = root->fs_info->generation;
8902 BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid;
8903 BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit;
8905 unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS);
8907 out_unlock:
8908 if (!ret) {
8909 sb_end_pagefault(inode->i_sb);
8910 return VM_FAULT_LOCKED;
8912 unlock_page(page);
8913 out:
8914 btrfs_delalloc_release_space(inode, page_start, PAGE_CACHE_SIZE);
8915 out_noreserve:
8916 sb_end_pagefault(inode->i_sb);
8917 return ret;
8920 static int btrfs_truncate(struct inode *inode)
8922 struct btrfs_root *root = BTRFS_I(inode)->root;
8923 struct btrfs_block_rsv *rsv;
8924 int ret = 0;
8925 int err = 0;
8926 struct btrfs_trans_handle *trans;
8927 u64 mask = root->sectorsize - 1;
8928 u64 min_size = btrfs_calc_trunc_metadata_size(root, 1);
8930 ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
8931 (u64)-1);
8932 if (ret)
8933 return ret;
8936 * Yes ladies and gentelment, this is indeed ugly. The fact is we have
8937 * 3 things going on here
8939 * 1) We need to reserve space for our orphan item and the space to
8940 * delete our orphan item. Lord knows we don't want to have a dangling
8941 * orphan item because we didn't reserve space to remove it.
8943 * 2) We need to reserve space to update our inode.
8945 * 3) We need to have something to cache all the space that is going to
8946 * be free'd up by the truncate operation, but also have some slack
8947 * space reserved in case it uses space during the truncate (thank you
8948 * very much snapshotting).
8950 * And we need these to all be seperate. The fact is we can use alot of
8951 * space doing the truncate, and we have no earthly idea how much space
8952 * we will use, so we need the truncate reservation to be seperate so it
8953 * doesn't end up using space reserved for updating the inode or
8954 * removing the orphan item. We also need to be able to stop the
8955 * transaction and start a new one, which means we need to be able to
8956 * update the inode several times, and we have no idea of knowing how
8957 * many times that will be, so we can't just reserve 1 item for the
8958 * entirety of the opration, so that has to be done seperately as well.
8959 * Then there is the orphan item, which does indeed need to be held on
8960 * to for the whole operation, and we need nobody to touch this reserved
8961 * space except the orphan code.
8963 * So that leaves us with
8965 * 1) root->orphan_block_rsv - for the orphan deletion.
8966 * 2) rsv - for the truncate reservation, which we will steal from the
8967 * transaction reservation.
8968 * 3) fs_info->trans_block_rsv - this will have 1 items worth left for
8969 * updating the inode.
8971 rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP);
8972 if (!rsv)
8973 return -ENOMEM;
8974 rsv->size = min_size;
8975 rsv->failfast = 1;
8978 * 1 for the truncate slack space
8979 * 1 for updating the inode.
8981 trans = btrfs_start_transaction(root, 2);
8982 if (IS_ERR(trans)) {
8983 err = PTR_ERR(trans);
8984 goto out;
8987 /* Migrate the slack space for the truncate to our reserve */
8988 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv,
8989 min_size);
8990 BUG_ON(ret);
8993 * So if we truncate and then write and fsync we normally would just
8994 * write the extents that changed, which is a problem if we need to
8995 * first truncate that entire inode. So set this flag so we write out
8996 * all of the extents in the inode to the sync log so we're completely
8997 * safe.
8999 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags);
9000 trans->block_rsv = rsv;
9002 while (1) {
9003 ret = btrfs_truncate_inode_items(trans, root, inode,
9004 inode->i_size,
9005 BTRFS_EXTENT_DATA_KEY);
9006 if (ret != -ENOSPC && ret != -EAGAIN) {
9007 err = ret;
9008 break;
9011 trans->block_rsv = &root->fs_info->trans_block_rsv;
9012 ret = btrfs_update_inode(trans, root, inode);
9013 if (ret) {
9014 err = ret;
9015 break;
9018 btrfs_end_transaction(trans, root);
9019 btrfs_btree_balance_dirty(root);
9021 trans = btrfs_start_transaction(root, 2);
9022 if (IS_ERR(trans)) {
9023 ret = err = PTR_ERR(trans);
9024 trans = NULL;
9025 break;
9028 ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv,
9029 rsv, min_size);
9030 BUG_ON(ret); /* shouldn't happen */
9031 trans->block_rsv = rsv;
9034 if (ret == 0 && inode->i_nlink > 0) {
9035 trans->block_rsv = root->orphan_block_rsv;
9036 ret = btrfs_orphan_del(trans, inode);
9037 if (ret)
9038 err = ret;
9041 if (trans) {
9042 trans->block_rsv = &root->fs_info->trans_block_rsv;
9043 ret = btrfs_update_inode(trans, root, inode);
9044 if (ret && !err)
9045 err = ret;
9047 ret = btrfs_end_transaction(trans, root);
9048 btrfs_btree_balance_dirty(root);
9051 out:
9052 btrfs_free_block_rsv(root, rsv);
9054 if (ret && !err)
9055 err = ret;
9057 return err;
9061 * create a new subvolume directory/inode (helper for the ioctl).
9063 int btrfs_create_subvol_root(struct btrfs_trans_handle *trans,
9064 struct btrfs_root *new_root,
9065 struct btrfs_root *parent_root,
9066 u64 new_dirid)
9068 struct inode *inode;
9069 int err;
9070 u64 index = 0;
9072 inode = btrfs_new_inode(trans, new_root, NULL, "..", 2,
9073 new_dirid, new_dirid,
9074 S_IFDIR | (~current_umask() & S_IRWXUGO),
9075 &index);
9076 if (IS_ERR(inode))
9077 return PTR_ERR(inode);
9078 inode->i_op = &btrfs_dir_inode_operations;
9079 inode->i_fop = &btrfs_dir_file_operations;
9081 set_nlink(inode, 1);
9082 btrfs_i_size_write(inode, 0);
9083 unlock_new_inode(inode);
9085 err = btrfs_subvol_inherit_props(trans, new_root, parent_root);
9086 if (err)
9087 btrfs_err(new_root->fs_info,
9088 "error inheriting subvolume %llu properties: %d",
9089 new_root->root_key.objectid, err);
9091 err = btrfs_update_inode(trans, new_root, inode);
9093 iput(inode);
9094 return err;
9097 struct inode *btrfs_alloc_inode(struct super_block *sb)
9099 struct btrfs_inode *ei;
9100 struct inode *inode;
9102 ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS);
9103 if (!ei)
9104 return NULL;
9106 ei->root = NULL;
9107 ei->generation = 0;
9108 ei->last_trans = 0;
9109 ei->last_sub_trans = 0;
9110 ei->logged_trans = 0;
9111 ei->delalloc_bytes = 0;
9112 ei->defrag_bytes = 0;
9113 ei->disk_i_size = 0;
9114 ei->flags = 0;
9115 ei->csum_bytes = 0;
9116 ei->index_cnt = (u64)-1;
9117 ei->dir_index = 0;
9118 ei->last_unlink_trans = 0;
9119 ei->last_log_commit = 0;
9121 spin_lock_init(&ei->lock);
9122 ei->outstanding_extents = 0;
9123 ei->reserved_extents = 0;
9125 ei->runtime_flags = 0;
9126 ei->force_compress = BTRFS_COMPRESS_NONE;
9128 ei->delayed_node = NULL;
9130 ei->i_otime.tv_sec = 0;
9131 ei->i_otime.tv_nsec = 0;
9133 inode = &ei->vfs_inode;
9134 extent_map_tree_init(&ei->extent_tree);
9135 extent_io_tree_init(&ei->io_tree, &inode->i_data);
9136 extent_io_tree_init(&ei->io_failure_tree, &inode->i_data);
9137 ei->io_tree.track_uptodate = 1;
9138 ei->io_failure_tree.track_uptodate = 1;
9139 atomic_set(&ei->sync_writers, 0);
9140 mutex_init(&ei->log_mutex);
9141 mutex_init(&ei->delalloc_mutex);
9142 btrfs_ordered_inode_tree_init(&ei->ordered_tree);
9143 INIT_LIST_HEAD(&ei->delalloc_inodes);
9144 RB_CLEAR_NODE(&ei->rb_node);
9146 return inode;
9149 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
9150 void btrfs_test_destroy_inode(struct inode *inode)
9152 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9153 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9155 #endif
9157 static void btrfs_i_callback(struct rcu_head *head)
9159 struct inode *inode = container_of(head, struct inode, i_rcu);
9160 kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
9163 void btrfs_destroy_inode(struct inode *inode)
9165 struct btrfs_ordered_extent *ordered;
9166 struct btrfs_root *root = BTRFS_I(inode)->root;
9168 WARN_ON(!hlist_empty(&inode->i_dentry));
9169 WARN_ON(inode->i_data.nrpages);
9170 WARN_ON(BTRFS_I(inode)->outstanding_extents);
9171 WARN_ON(BTRFS_I(inode)->reserved_extents);
9172 WARN_ON(BTRFS_I(inode)->delalloc_bytes);
9173 WARN_ON(BTRFS_I(inode)->csum_bytes);
9174 WARN_ON(BTRFS_I(inode)->defrag_bytes);
9177 * This can happen where we create an inode, but somebody else also
9178 * created the same inode and we need to destroy the one we already
9179 * created.
9181 if (!root)
9182 goto free;
9184 if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM,
9185 &BTRFS_I(inode)->runtime_flags)) {
9186 btrfs_info(root->fs_info, "inode %llu still on the orphan list",
9187 btrfs_ino(inode));
9188 atomic_dec(&root->orphan_inodes);
9191 while (1) {
9192 ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
9193 if (!ordered)
9194 break;
9195 else {
9196 btrfs_err(root->fs_info, "found ordered extent %llu %llu on inode cleanup",
9197 ordered->file_offset, ordered->len);
9198 btrfs_remove_ordered_extent(inode, ordered);
9199 btrfs_put_ordered_extent(ordered);
9200 btrfs_put_ordered_extent(ordered);
9203 btrfs_qgroup_check_reserved_leak(inode);
9204 inode_tree_del(inode);
9205 btrfs_drop_extent_cache(inode, 0, (u64)-1, 0);
9206 free:
9207 call_rcu(&inode->i_rcu, btrfs_i_callback);
9210 int btrfs_drop_inode(struct inode *inode)
9212 struct btrfs_root *root = BTRFS_I(inode)->root;
9214 if (root == NULL)
9215 return 1;
9217 /* the snap/subvol tree is on deleting */
9218 if (btrfs_root_refs(&root->root_item) == 0)
9219 return 1;
9220 else
9221 return generic_drop_inode(inode);
9224 static void init_once(void *foo)
9226 struct btrfs_inode *ei = (struct btrfs_inode *) foo;
9228 inode_init_once(&ei->vfs_inode);
9231 void btrfs_destroy_cachep(void)
9234 * Make sure all delayed rcu free inodes are flushed before we
9235 * destroy cache.
9237 rcu_barrier();
9238 if (btrfs_inode_cachep)
9239 kmem_cache_destroy(btrfs_inode_cachep);
9240 if (btrfs_trans_handle_cachep)
9241 kmem_cache_destroy(btrfs_trans_handle_cachep);
9242 if (btrfs_transaction_cachep)
9243 kmem_cache_destroy(btrfs_transaction_cachep);
9244 if (btrfs_path_cachep)
9245 kmem_cache_destroy(btrfs_path_cachep);
9246 if (btrfs_free_space_cachep)
9247 kmem_cache_destroy(btrfs_free_space_cachep);
9248 if (btrfs_delalloc_work_cachep)
9249 kmem_cache_destroy(btrfs_delalloc_work_cachep);
9252 int btrfs_init_cachep(void)
9254 btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
9255 sizeof(struct btrfs_inode), 0,
9256 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once);
9257 if (!btrfs_inode_cachep)
9258 goto fail;
9260 btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
9261 sizeof(struct btrfs_trans_handle), 0,
9262 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9263 if (!btrfs_trans_handle_cachep)
9264 goto fail;
9266 btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction",
9267 sizeof(struct btrfs_transaction), 0,
9268 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9269 if (!btrfs_transaction_cachep)
9270 goto fail;
9272 btrfs_path_cachep = kmem_cache_create("btrfs_path",
9273 sizeof(struct btrfs_path), 0,
9274 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9275 if (!btrfs_path_cachep)
9276 goto fail;
9278 btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
9279 sizeof(struct btrfs_free_space), 0,
9280 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL);
9281 if (!btrfs_free_space_cachep)
9282 goto fail;
9284 btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work",
9285 sizeof(struct btrfs_delalloc_work), 0,
9286 SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD,
9287 NULL);
9288 if (!btrfs_delalloc_work_cachep)
9289 goto fail;
9291 return 0;
9292 fail:
9293 btrfs_destroy_cachep();
9294 return -ENOMEM;
9297 static int btrfs_getattr(struct vfsmount *mnt,
9298 struct dentry *dentry, struct kstat *stat)
9300 u64 delalloc_bytes;
9301 struct inode *inode = d_inode(dentry);
9302 u32 blocksize = inode->i_sb->s_blocksize;
9304 generic_fillattr(inode, stat);
9305 stat->dev = BTRFS_I(inode)->root->anon_dev;
9306 stat->blksize = PAGE_CACHE_SIZE;
9308 spin_lock(&BTRFS_I(inode)->lock);
9309 delalloc_bytes = BTRFS_I(inode)->delalloc_bytes;
9310 spin_unlock(&BTRFS_I(inode)->lock);
9311 stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) +
9312 ALIGN(delalloc_bytes, blocksize)) >> 9;
9313 return 0;
9316 static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry,
9317 struct inode *new_dir, struct dentry *new_dentry)
9319 struct btrfs_trans_handle *trans;
9320 struct btrfs_root *root = BTRFS_I(old_dir)->root;
9321 struct btrfs_root *dest = BTRFS_I(new_dir)->root;
9322 struct inode *new_inode = d_inode(new_dentry);
9323 struct inode *old_inode = d_inode(old_dentry);
9324 struct timespec ctime = CURRENT_TIME;
9325 u64 index = 0;
9326 u64 root_objectid;
9327 int ret;
9328 u64 old_ino = btrfs_ino(old_inode);
9330 if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
9331 return -EPERM;
9333 /* we only allow rename subvolume link between subvolumes */
9334 if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
9335 return -EXDEV;
9337 if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
9338 (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID))
9339 return -ENOTEMPTY;
9341 if (S_ISDIR(old_inode->i_mode) && new_inode &&
9342 new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
9343 return -ENOTEMPTY;
9346 /* check for collisions, even if the name isn't there */
9347 ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino,
9348 new_dentry->d_name.name,
9349 new_dentry->d_name.len);
9351 if (ret) {
9352 if (ret == -EEXIST) {
9353 /* we shouldn't get
9354 * eexist without a new_inode */
9355 if (WARN_ON(!new_inode)) {
9356 return ret;
9358 } else {
9359 /* maybe -EOVERFLOW */
9360 return ret;
9363 ret = 0;
9366 * we're using rename to replace one file with another. Start IO on it
9367 * now so we don't add too much work to the end of the transaction
9369 if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
9370 filemap_flush(old_inode->i_mapping);
9372 /* close the racy window with snapshot create/destroy ioctl */
9373 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9374 down_read(&root->fs_info->subvol_sem);
9376 * We want to reserve the absolute worst case amount of items. So if
9377 * both inodes are subvols and we need to unlink them then that would
9378 * require 4 item modifications, but if they are both normal inodes it
9379 * would require 5 item modifications, so we'll assume their normal
9380 * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items
9381 * should cover the worst case number of items we'll modify.
9383 trans = btrfs_start_transaction(root, 11);
9384 if (IS_ERR(trans)) {
9385 ret = PTR_ERR(trans);
9386 goto out_notrans;
9389 if (dest != root)
9390 btrfs_record_root_in_trans(trans, dest);
9392 ret = btrfs_set_inode_index(new_dir, &index);
9393 if (ret)
9394 goto out_fail;
9396 BTRFS_I(old_inode)->dir_index = 0ULL;
9397 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9398 /* force full log commit if subvolume involved. */
9399 btrfs_set_log_full_commit(root->fs_info, trans);
9400 } else {
9401 ret = btrfs_insert_inode_ref(trans, dest,
9402 new_dentry->d_name.name,
9403 new_dentry->d_name.len,
9404 old_ino,
9405 btrfs_ino(new_dir), index);
9406 if (ret)
9407 goto out_fail;
9409 * this is an ugly little race, but the rename is required
9410 * to make sure that if we crash, the inode is either at the
9411 * old name or the new one. pinning the log transaction lets
9412 * us make sure we don't allow a log commit to come in after
9413 * we unlink the name but before we add the new name back in.
9415 btrfs_pin_log_trans(root);
9418 inode_inc_iversion(old_dir);
9419 inode_inc_iversion(new_dir);
9420 inode_inc_iversion(old_inode);
9421 old_dir->i_ctime = old_dir->i_mtime = ctime;
9422 new_dir->i_ctime = new_dir->i_mtime = ctime;
9423 old_inode->i_ctime = ctime;
9425 if (old_dentry->d_parent != new_dentry->d_parent)
9426 btrfs_record_unlink_dir(trans, old_dir, old_inode, 1);
9428 if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
9429 root_objectid = BTRFS_I(old_inode)->root->root_key.objectid;
9430 ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid,
9431 old_dentry->d_name.name,
9432 old_dentry->d_name.len);
9433 } else {
9434 ret = __btrfs_unlink_inode(trans, root, old_dir,
9435 d_inode(old_dentry),
9436 old_dentry->d_name.name,
9437 old_dentry->d_name.len);
9438 if (!ret)
9439 ret = btrfs_update_inode(trans, root, old_inode);
9441 if (ret) {
9442 btrfs_abort_transaction(trans, root, ret);
9443 goto out_fail;
9446 if (new_inode) {
9447 inode_inc_iversion(new_inode);
9448 new_inode->i_ctime = CURRENT_TIME;
9449 if (unlikely(btrfs_ino(new_inode) ==
9450 BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
9451 root_objectid = BTRFS_I(new_inode)->location.objectid;
9452 ret = btrfs_unlink_subvol(trans, dest, new_dir,
9453 root_objectid,
9454 new_dentry->d_name.name,
9455 new_dentry->d_name.len);
9456 BUG_ON(new_inode->i_nlink == 0);
9457 } else {
9458 ret = btrfs_unlink_inode(trans, dest, new_dir,
9459 d_inode(new_dentry),
9460 new_dentry->d_name.name,
9461 new_dentry->d_name.len);
9463 if (!ret && new_inode->i_nlink == 0)
9464 ret = btrfs_orphan_add(trans, d_inode(new_dentry));
9465 if (ret) {
9466 btrfs_abort_transaction(trans, root, ret);
9467 goto out_fail;
9471 ret = btrfs_add_link(trans, new_dir, old_inode,
9472 new_dentry->d_name.name,
9473 new_dentry->d_name.len, 0, index);
9474 if (ret) {
9475 btrfs_abort_transaction(trans, root, ret);
9476 goto out_fail;
9479 if (old_inode->i_nlink == 1)
9480 BTRFS_I(old_inode)->dir_index = index;
9482 if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
9483 struct dentry *parent = new_dentry->d_parent;
9484 btrfs_log_new_name(trans, old_inode, old_dir, parent);
9485 btrfs_end_log_trans(root);
9487 out_fail:
9488 btrfs_end_transaction(trans, root);
9489 out_notrans:
9490 if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
9491 up_read(&root->fs_info->subvol_sem);
9493 return ret;
9496 static int btrfs_rename2(struct inode *old_dir, struct dentry *old_dentry,
9497 struct inode *new_dir, struct dentry *new_dentry,
9498 unsigned int flags)
9500 if (flags & ~RENAME_NOREPLACE)
9501 return -EINVAL;
9503 return btrfs_rename(old_dir, old_dentry, new_dir, new_dentry);
9506 static void btrfs_run_delalloc_work(struct btrfs_work *work)
9508 struct btrfs_delalloc_work *delalloc_work;
9509 struct inode *inode;
9511 delalloc_work = container_of(work, struct btrfs_delalloc_work,
9512 work);
9513 inode = delalloc_work->inode;
9514 if (delalloc_work->wait) {
9515 btrfs_wait_ordered_range(inode, 0, (u64)-1);
9516 } else {
9517 filemap_flush(inode->i_mapping);
9518 if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
9519 &BTRFS_I(inode)->runtime_flags))
9520 filemap_flush(inode->i_mapping);
9523 if (delalloc_work->delay_iput)
9524 btrfs_add_delayed_iput(inode);
9525 else
9526 iput(inode);
9527 complete(&delalloc_work->completion);
9530 struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode,
9531 int wait, int delay_iput)
9533 struct btrfs_delalloc_work *work;
9535 work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS);
9536 if (!work)
9537 return NULL;
9539 init_completion(&work->completion);
9540 INIT_LIST_HEAD(&work->list);
9541 work->inode = inode;
9542 work->wait = wait;
9543 work->delay_iput = delay_iput;
9544 WARN_ON_ONCE(!inode);
9545 btrfs_init_work(&work->work, btrfs_flush_delalloc_helper,
9546 btrfs_run_delalloc_work, NULL, NULL);
9548 return work;
9551 void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work)
9553 wait_for_completion(&work->completion);
9554 kmem_cache_free(btrfs_delalloc_work_cachep, work);
9558 * some fairly slow code that needs optimization. This walks the list
9559 * of all the inodes with pending delalloc and forces them to disk.
9561 static int __start_delalloc_inodes(struct btrfs_root *root, int delay_iput,
9562 int nr)
9564 struct btrfs_inode *binode;
9565 struct inode *inode;
9566 struct btrfs_delalloc_work *work, *next;
9567 struct list_head works;
9568 struct list_head splice;
9569 int ret = 0;
9571 INIT_LIST_HEAD(&works);
9572 INIT_LIST_HEAD(&splice);
9574 mutex_lock(&root->delalloc_mutex);
9575 spin_lock(&root->delalloc_lock);
9576 list_splice_init(&root->delalloc_inodes, &splice);
9577 while (!list_empty(&splice)) {
9578 binode = list_entry(splice.next, struct btrfs_inode,
9579 delalloc_inodes);
9581 list_move_tail(&binode->delalloc_inodes,
9582 &root->delalloc_inodes);
9583 inode = igrab(&binode->vfs_inode);
9584 if (!inode) {
9585 cond_resched_lock(&root->delalloc_lock);
9586 continue;
9588 spin_unlock(&root->delalloc_lock);
9590 work = btrfs_alloc_delalloc_work(inode, 0, delay_iput);
9591 if (!work) {
9592 if (delay_iput)
9593 btrfs_add_delayed_iput(inode);
9594 else
9595 iput(inode);
9596 ret = -ENOMEM;
9597 goto out;
9599 list_add_tail(&work->list, &works);
9600 btrfs_queue_work(root->fs_info->flush_workers,
9601 &work->work);
9602 ret++;
9603 if (nr != -1 && ret >= nr)
9604 goto out;
9605 cond_resched();
9606 spin_lock(&root->delalloc_lock);
9608 spin_unlock(&root->delalloc_lock);
9610 out:
9611 list_for_each_entry_safe(work, next, &works, list) {
9612 list_del_init(&work->list);
9613 btrfs_wait_and_free_delalloc_work(work);
9616 if (!list_empty_careful(&splice)) {
9617 spin_lock(&root->delalloc_lock);
9618 list_splice_tail(&splice, &root->delalloc_inodes);
9619 spin_unlock(&root->delalloc_lock);
9621 mutex_unlock(&root->delalloc_mutex);
9622 return ret;
9625 int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput)
9627 int ret;
9629 if (test_bit(BTRFS_FS_STATE_ERROR, &root->fs_info->fs_state))
9630 return -EROFS;
9632 ret = __start_delalloc_inodes(root, delay_iput, -1);
9633 if (ret > 0)
9634 ret = 0;
9636 * the filemap_flush will queue IO into the worker threads, but
9637 * we have to make sure the IO is actually started and that
9638 * ordered extents get created before we return
9640 atomic_inc(&root->fs_info->async_submit_draining);
9641 while (atomic_read(&root->fs_info->nr_async_submits) ||
9642 atomic_read(&root->fs_info->async_delalloc_pages)) {
9643 wait_event(root->fs_info->async_submit_wait,
9644 (atomic_read(&root->fs_info->nr_async_submits) == 0 &&
9645 atomic_read(&root->fs_info->async_delalloc_pages) == 0));
9647 atomic_dec(&root->fs_info->async_submit_draining);
9648 return ret;
9651 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, int delay_iput,
9652 int nr)
9654 struct btrfs_root *root;
9655 struct list_head splice;
9656 int ret;
9658 if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state))
9659 return -EROFS;
9661 INIT_LIST_HEAD(&splice);
9663 mutex_lock(&fs_info->delalloc_root_mutex);
9664 spin_lock(&fs_info->delalloc_root_lock);
9665 list_splice_init(&fs_info->delalloc_roots, &splice);
9666 while (!list_empty(&splice) && nr) {
9667 root = list_first_entry(&splice, struct btrfs_root,
9668 delalloc_root);
9669 root = btrfs_grab_fs_root(root);
9670 BUG_ON(!root);
9671 list_move_tail(&root->delalloc_root,
9672 &fs_info->delalloc_roots);
9673 spin_unlock(&fs_info->delalloc_root_lock);
9675 ret = __start_delalloc_inodes(root, delay_iput, nr);
9676 btrfs_put_fs_root(root);
9677 if (ret < 0)
9678 goto out;
9680 if (nr != -1) {
9681 nr -= ret;
9682 WARN_ON(nr < 0);
9684 spin_lock(&fs_info->delalloc_root_lock);
9686 spin_unlock(&fs_info->delalloc_root_lock);
9688 ret = 0;
9689 atomic_inc(&fs_info->async_submit_draining);
9690 while (atomic_read(&fs_info->nr_async_submits) ||
9691 atomic_read(&fs_info->async_delalloc_pages)) {
9692 wait_event(fs_info->async_submit_wait,
9693 (atomic_read(&fs_info->nr_async_submits) == 0 &&
9694 atomic_read(&fs_info->async_delalloc_pages) == 0));
9696 atomic_dec(&fs_info->async_submit_draining);
9697 out:
9698 if (!list_empty_careful(&splice)) {
9699 spin_lock(&fs_info->delalloc_root_lock);
9700 list_splice_tail(&splice, &fs_info->delalloc_roots);
9701 spin_unlock(&fs_info->delalloc_root_lock);
9703 mutex_unlock(&fs_info->delalloc_root_mutex);
9704 return ret;
9707 static int btrfs_symlink(struct inode *dir, struct dentry *dentry,
9708 const char *symname)
9710 struct btrfs_trans_handle *trans;
9711 struct btrfs_root *root = BTRFS_I(dir)->root;
9712 struct btrfs_path *path;
9713 struct btrfs_key key;
9714 struct inode *inode = NULL;
9715 int err;
9716 int drop_inode = 0;
9717 u64 objectid;
9718 u64 index = 0;
9719 int name_len;
9720 int datasize;
9721 unsigned long ptr;
9722 struct btrfs_file_extent_item *ei;
9723 struct extent_buffer *leaf;
9725 name_len = strlen(symname);
9726 if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root))
9727 return -ENAMETOOLONG;
9730 * 2 items for inode item and ref
9731 * 2 items for dir items
9732 * 1 item for updating parent inode item
9733 * 1 item for the inline extent item
9734 * 1 item for xattr if selinux is on
9736 trans = btrfs_start_transaction(root, 7);
9737 if (IS_ERR(trans))
9738 return PTR_ERR(trans);
9740 err = btrfs_find_free_ino(root, &objectid);
9741 if (err)
9742 goto out_unlock;
9744 inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name,
9745 dentry->d_name.len, btrfs_ino(dir), objectid,
9746 S_IFLNK|S_IRWXUGO, &index);
9747 if (IS_ERR(inode)) {
9748 err = PTR_ERR(inode);
9749 goto out_unlock;
9753 * If the active LSM wants to access the inode during
9754 * d_instantiate it needs these. Smack checks to see
9755 * if the filesystem supports xattrs by looking at the
9756 * ops vector.
9758 inode->i_fop = &btrfs_file_operations;
9759 inode->i_op = &btrfs_file_inode_operations;
9760 inode->i_mapping->a_ops = &btrfs_aops;
9761 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
9763 err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name);
9764 if (err)
9765 goto out_unlock_inode;
9767 err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index);
9768 if (err)
9769 goto out_unlock_inode;
9771 path = btrfs_alloc_path();
9772 if (!path) {
9773 err = -ENOMEM;
9774 goto out_unlock_inode;
9776 key.objectid = btrfs_ino(inode);
9777 key.offset = 0;
9778 key.type = BTRFS_EXTENT_DATA_KEY;
9779 datasize = btrfs_file_extent_calc_inline_size(name_len);
9780 err = btrfs_insert_empty_item(trans, root, path, &key,
9781 datasize);
9782 if (err) {
9783 btrfs_free_path(path);
9784 goto out_unlock_inode;
9786 leaf = path->nodes[0];
9787 ei = btrfs_item_ptr(leaf, path->slots[0],
9788 struct btrfs_file_extent_item);
9789 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9790 btrfs_set_file_extent_type(leaf, ei,
9791 BTRFS_FILE_EXTENT_INLINE);
9792 btrfs_set_file_extent_encryption(leaf, ei, 0);
9793 btrfs_set_file_extent_compression(leaf, ei, 0);
9794 btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9795 btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9797 ptr = btrfs_file_extent_inline_start(ei);
9798 write_extent_buffer(leaf, symname, ptr, name_len);
9799 btrfs_mark_buffer_dirty(leaf);
9800 btrfs_free_path(path);
9802 inode->i_op = &btrfs_symlink_inode_operations;
9803 inode->i_mapping->a_ops = &btrfs_symlink_aops;
9804 inode_set_bytes(inode, name_len);
9805 btrfs_i_size_write(inode, name_len);
9806 err = btrfs_update_inode(trans, root, inode);
9807 if (err) {
9808 drop_inode = 1;
9809 goto out_unlock_inode;
9812 d_instantiate_new(dentry, inode);
9814 out_unlock:
9815 btrfs_end_transaction(trans, root);
9816 if (drop_inode) {
9817 inode_dec_link_count(inode);
9818 iput(inode);
9820 btrfs_btree_balance_dirty(root);
9821 return err;
9823 out_unlock_inode:
9824 drop_inode = 1;
9825 unlock_new_inode(inode);
9826 goto out_unlock;
9829 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9830 u64 start, u64 num_bytes, u64 min_size,
9831 loff_t actual_len, u64 *alloc_hint,
9832 struct btrfs_trans_handle *trans)
9834 struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
9835 struct extent_map *em;
9836 struct btrfs_root *root = BTRFS_I(inode)->root;
9837 struct btrfs_key ins;
9838 u64 cur_offset = start;
9839 u64 i_size;
9840 u64 cur_bytes;
9841 u64 last_alloc = (u64)-1;
9842 int ret = 0;
9843 bool own_trans = true;
9845 if (trans)
9846 own_trans = false;
9847 while (num_bytes > 0) {
9848 if (own_trans) {
9849 trans = btrfs_start_transaction(root, 3);
9850 if (IS_ERR(trans)) {
9851 ret = PTR_ERR(trans);
9852 break;
9856 cur_bytes = min(num_bytes, 256ULL * 1024 * 1024);
9857 cur_bytes = max(cur_bytes, min_size);
9859 * If we are severely fragmented we could end up with really
9860 * small allocations, so if the allocator is returning small
9861 * chunks lets make its job easier by only searching for those
9862 * sized chunks.
9864 cur_bytes = min(cur_bytes, last_alloc);
9865 ret = btrfs_reserve_extent(root, cur_bytes, min_size, 0,
9866 *alloc_hint, &ins, 1, 0);
9867 if (ret) {
9868 if (own_trans)
9869 btrfs_end_transaction(trans, root);
9870 break;
9873 last_alloc = ins.offset;
9874 ret = insert_reserved_file_extent(trans, inode,
9875 cur_offset, ins.objectid,
9876 ins.offset, ins.offset,
9877 ins.offset, 0, 0, 0,
9878 BTRFS_FILE_EXTENT_PREALLOC);
9879 if (ret) {
9880 btrfs_free_reserved_extent(root, ins.objectid,
9881 ins.offset, 0);
9882 btrfs_abort_transaction(trans, root, ret);
9883 if (own_trans)
9884 btrfs_end_transaction(trans, root);
9885 break;
9888 btrfs_drop_extent_cache(inode, cur_offset,
9889 cur_offset + ins.offset -1, 0);
9891 em = alloc_extent_map();
9892 if (!em) {
9893 set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
9894 &BTRFS_I(inode)->runtime_flags);
9895 goto next;
9898 em->start = cur_offset;
9899 em->orig_start = cur_offset;
9900 em->len = ins.offset;
9901 em->block_start = ins.objectid;
9902 em->block_len = ins.offset;
9903 em->orig_block_len = ins.offset;
9904 em->ram_bytes = ins.offset;
9905 em->bdev = root->fs_info->fs_devices->latest_bdev;
9906 set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
9907 em->generation = trans->transid;
9909 while (1) {
9910 write_lock(&em_tree->lock);
9911 ret = add_extent_mapping(em_tree, em, 1);
9912 write_unlock(&em_tree->lock);
9913 if (ret != -EEXIST)
9914 break;
9915 btrfs_drop_extent_cache(inode, cur_offset,
9916 cur_offset + ins.offset - 1,
9919 free_extent_map(em);
9920 next:
9921 num_bytes -= ins.offset;
9922 cur_offset += ins.offset;
9923 *alloc_hint = ins.objectid + ins.offset;
9925 inode_inc_iversion(inode);
9926 inode->i_ctime = CURRENT_TIME;
9927 BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9928 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9929 (actual_len > inode->i_size) &&
9930 (cur_offset > inode->i_size)) {
9931 if (cur_offset > actual_len)
9932 i_size = actual_len;
9933 else
9934 i_size = cur_offset;
9935 i_size_write(inode, i_size);
9936 btrfs_ordered_update_i_size(inode, i_size, NULL);
9939 ret = btrfs_update_inode(trans, root, inode);
9941 if (ret) {
9942 btrfs_abort_transaction(trans, root, ret);
9943 if (own_trans)
9944 btrfs_end_transaction(trans, root);
9945 break;
9948 if (own_trans)
9949 btrfs_end_transaction(trans, root);
9951 return ret;
9954 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9955 u64 start, u64 num_bytes, u64 min_size,
9956 loff_t actual_len, u64 *alloc_hint)
9958 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9959 min_size, actual_len, alloc_hint,
9960 NULL);
9963 int btrfs_prealloc_file_range_trans(struct inode *inode,
9964 struct btrfs_trans_handle *trans, int mode,
9965 u64 start, u64 num_bytes, u64 min_size,
9966 loff_t actual_len, u64 *alloc_hint)
9968 return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9969 min_size, actual_len, alloc_hint, trans);
9972 static int btrfs_set_page_dirty(struct page *page)
9974 return __set_page_dirty_nobuffers(page);
9977 static int btrfs_permission(struct inode *inode, int mask)
9979 struct btrfs_root *root = BTRFS_I(inode)->root;
9980 umode_t mode = inode->i_mode;
9982 if (mask & MAY_WRITE &&
9983 (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9984 if (btrfs_root_readonly(root))
9985 return -EROFS;
9986 if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9987 return -EACCES;
9989 return generic_permission(inode, mask);
9992 static int btrfs_tmpfile(struct inode *dir, struct dentry *dentry, umode_t mode)
9994 struct btrfs_trans_handle *trans;
9995 struct btrfs_root *root = BTRFS_I(dir)->root;
9996 struct inode *inode = NULL;
9997 u64 objectid;
9998 u64 index;
9999 int ret = 0;
10002 * 5 units required for adding orphan entry
10004 trans = btrfs_start_transaction(root, 5);
10005 if (IS_ERR(trans))
10006 return PTR_ERR(trans);
10008 ret = btrfs_find_free_ino(root, &objectid);
10009 if (ret)
10010 goto out;
10012 inode = btrfs_new_inode(trans, root, dir, NULL, 0,
10013 btrfs_ino(dir), objectid, mode, &index);
10014 if (IS_ERR(inode)) {
10015 ret = PTR_ERR(inode);
10016 inode = NULL;
10017 goto out;
10020 inode->i_fop = &btrfs_file_operations;
10021 inode->i_op = &btrfs_file_inode_operations;
10023 inode->i_mapping->a_ops = &btrfs_aops;
10024 BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops;
10026 ret = btrfs_init_inode_security(trans, inode, dir, NULL);
10027 if (ret)
10028 goto out_inode;
10030 ret = btrfs_update_inode(trans, root, inode);
10031 if (ret)
10032 goto out_inode;
10033 ret = btrfs_orphan_add(trans, inode);
10034 if (ret)
10035 goto out_inode;
10038 * We set number of links to 0 in btrfs_new_inode(), and here we set
10039 * it to 1 because d_tmpfile() will issue a warning if the count is 0,
10040 * through:
10042 * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
10044 set_nlink(inode, 1);
10045 unlock_new_inode(inode);
10046 d_tmpfile(dentry, inode);
10047 mark_inode_dirty(inode);
10049 out:
10050 btrfs_end_transaction(trans, root);
10051 if (ret)
10052 iput(inode);
10053 btrfs_balance_delayed_items(root);
10054 btrfs_btree_balance_dirty(root);
10055 return ret;
10057 out_inode:
10058 unlock_new_inode(inode);
10059 goto out;
10063 /* Inspired by filemap_check_errors() */
10064 int btrfs_inode_check_errors(struct inode *inode)
10066 int ret = 0;
10068 if (test_bit(AS_ENOSPC, &inode->i_mapping->flags) &&
10069 test_and_clear_bit(AS_ENOSPC, &inode->i_mapping->flags))
10070 ret = -ENOSPC;
10071 if (test_bit(AS_EIO, &inode->i_mapping->flags) &&
10072 test_and_clear_bit(AS_EIO, &inode->i_mapping->flags))
10073 ret = -EIO;
10075 return ret;
10078 static const struct inode_operations btrfs_dir_inode_operations = {
10079 .getattr = btrfs_getattr,
10080 .lookup = btrfs_lookup,
10081 .create = btrfs_create,
10082 .unlink = btrfs_unlink,
10083 .link = btrfs_link,
10084 .mkdir = btrfs_mkdir,
10085 .rmdir = btrfs_rmdir,
10086 .rename2 = btrfs_rename2,
10087 .symlink = btrfs_symlink,
10088 .setattr = btrfs_setattr,
10089 .mknod = btrfs_mknod,
10090 .setxattr = btrfs_setxattr,
10091 .getxattr = btrfs_getxattr,
10092 .listxattr = btrfs_listxattr,
10093 .removexattr = btrfs_removexattr,
10094 .permission = btrfs_permission,
10095 .get_acl = btrfs_get_acl,
10096 .set_acl = btrfs_set_acl,
10097 .update_time = btrfs_update_time,
10098 .tmpfile = btrfs_tmpfile,
10100 static const struct inode_operations btrfs_dir_ro_inode_operations = {
10101 .lookup = btrfs_lookup,
10102 .permission = btrfs_permission,
10103 .get_acl = btrfs_get_acl,
10104 .set_acl = btrfs_set_acl,
10105 .update_time = btrfs_update_time,
10108 static const struct file_operations btrfs_dir_file_operations = {
10109 .llseek = generic_file_llseek,
10110 .read = generic_read_dir,
10111 .iterate = btrfs_real_readdir,
10112 .unlocked_ioctl = btrfs_ioctl,
10113 #ifdef CONFIG_COMPAT
10114 .compat_ioctl = btrfs_ioctl,
10115 #endif
10116 .release = btrfs_release_file,
10117 .fsync = btrfs_sync_file,
10120 static struct extent_io_ops btrfs_extent_io_ops = {
10121 .fill_delalloc = run_delalloc_range,
10122 .submit_bio_hook = btrfs_submit_bio_hook,
10123 .merge_bio_hook = btrfs_merge_bio_hook,
10124 .readpage_end_io_hook = btrfs_readpage_end_io_hook,
10125 .writepage_end_io_hook = btrfs_writepage_end_io_hook,
10126 .writepage_start_hook = btrfs_writepage_start_hook,
10127 .set_bit_hook = btrfs_set_bit_hook,
10128 .clear_bit_hook = btrfs_clear_bit_hook,
10129 .merge_extent_hook = btrfs_merge_extent_hook,
10130 .split_extent_hook = btrfs_split_extent_hook,
10134 * btrfs doesn't support the bmap operation because swapfiles
10135 * use bmap to make a mapping of extents in the file. They assume
10136 * these extents won't change over the life of the file and they
10137 * use the bmap result to do IO directly to the drive.
10139 * the btrfs bmap call would return logical addresses that aren't
10140 * suitable for IO and they also will change frequently as COW
10141 * operations happen. So, swapfile + btrfs == corruption.
10143 * For now we're avoiding this by dropping bmap.
10145 static const struct address_space_operations btrfs_aops = {
10146 .readpage = btrfs_readpage,
10147 .writepage = btrfs_writepage,
10148 .writepages = btrfs_writepages,
10149 .readpages = btrfs_readpages,
10150 .direct_IO = btrfs_direct_IO,
10151 .invalidatepage = btrfs_invalidatepage,
10152 .releasepage = btrfs_releasepage,
10153 .set_page_dirty = btrfs_set_page_dirty,
10154 .error_remove_page = generic_error_remove_page,
10157 static const struct address_space_operations btrfs_symlink_aops = {
10158 .readpage = btrfs_readpage,
10159 .writepage = btrfs_writepage,
10160 .invalidatepage = btrfs_invalidatepage,
10161 .releasepage = btrfs_releasepage,
10164 static const struct inode_operations btrfs_file_inode_operations = {
10165 .getattr = btrfs_getattr,
10166 .setattr = btrfs_setattr,
10167 .setxattr = btrfs_setxattr,
10168 .getxattr = btrfs_getxattr,
10169 .listxattr = btrfs_listxattr,
10170 .removexattr = btrfs_removexattr,
10171 .permission = btrfs_permission,
10172 .fiemap = btrfs_fiemap,
10173 .get_acl = btrfs_get_acl,
10174 .set_acl = btrfs_set_acl,
10175 .update_time = btrfs_update_time,
10177 static const struct inode_operations btrfs_special_inode_operations = {
10178 .getattr = btrfs_getattr,
10179 .setattr = btrfs_setattr,
10180 .permission = btrfs_permission,
10181 .setxattr = btrfs_setxattr,
10182 .getxattr = btrfs_getxattr,
10183 .listxattr = btrfs_listxattr,
10184 .removexattr = btrfs_removexattr,
10185 .get_acl = btrfs_get_acl,
10186 .set_acl = btrfs_set_acl,
10187 .update_time = btrfs_update_time,
10189 static const struct inode_operations btrfs_symlink_inode_operations = {
10190 .readlink = generic_readlink,
10191 .follow_link = page_follow_link_light,
10192 .put_link = page_put_link,
10193 .getattr = btrfs_getattr,
10194 .setattr = btrfs_setattr,
10195 .permission = btrfs_permission,
10196 .setxattr = btrfs_setxattr,
10197 .getxattr = btrfs_getxattr,
10198 .listxattr = btrfs_listxattr,
10199 .removexattr = btrfs_removexattr,
10200 .update_time = btrfs_update_time,
10203 const struct dentry_operations btrfs_dentry_operations = {
10204 .d_delete = btrfs_dentry_delete,
10205 .d_release = btrfs_dentry_release,